text
stringlengths
8
267k
meta
dict
Q: how can I disable output to log4j.rootLogger? I want to disable the output to the console when logging to file. See config-file below: log4j.rootLogger=info,stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L --- %m%n log4j.category.FileLog=info,R log4j.appender.R=org.apache.log4j.DailyRollingFileAppender log4j.appender.R.File=E:\\temp\\FileLog log4j.appender.R.Append = true log4j.appender.R.DatePattern='.'yyyy-MM-dd'.log' log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%m[%d{MM-dd HH:mm:ss}]%n when I using: Logger.getLogger("FileLog").info("LogText-FileLog"); this log print to stdout too,how can I disable it? A: remove stdout from here log4j.rootLogger=info,stdout To: log4j.rootLogger=info A: You can use `log4j.additivity.FileLog = false, that is the 'flag' you are looking for. From the official log4j documentation: The output of a log statement of logger C will go to all the appenders in C and its ancestors. This is the meaning of the term "appender additivity". However, if an ancestor of logger C, say P, has the additivity flag set to false, then C's output will be directed to all the appenders in C and its ancestors upto and including P but not the appenders in any of the ancestors of P. Loggers have their additivity flag set to true by default. Removing "stdout" from your root logger (as proposed in other answers) might not be a solution, because I suppose you are still interested in that console logs in some cases. A: I don't know the answer to the exact question the user provided, but facing a similar problem with the following log4j code: log4j.rootCategory=INFO, console log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.target=System.err log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{1}: %m%n I removed all logging lines from the console by changing log4j.rootCategory=INFO, console to log4j.rootCategory=OFF, console A: Remove "stdout" from root logger. It will stop writing on the console.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Hibernate wont write correctly floating point numbers to a MS SQL 2005 database Here is the case, I have a java double property mapped to a ms sql server decimal(18,3), it was float before I changed it to decimal but the outcome is the same. When I persist the java floating point number the floating point is lost. In other words ( java -> db )2.0345678D -> 20345678.00 . Does anyone have encountered anything like that. I cannot seem to find it as a known bug in hibernate. I did found that there is an issue with ms sql float and decimal points but not a real solution. Thanks, Peter A: You'll have to set precision and scale in Hibernate Note: decimal 18,3 allows 3 digits after the decimal place. So 2.0345678D would be 2.034 anyway,
{ "language": "en", "url": "https://stackoverflow.com/questions/7513466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: how to pass values to a html file in android I have a HTML formatted file saved in SD card. I want to retrieve it , pass values to it and save it again from an android activity. Please let me know how to do it. A: Use Html.fromHtml() Returns displayable styled text from the provided HTML string. Any tags in the HTML will display as a generic replacement image which your program can then go through and replace with real images. This uses TagSoup to handle real HTML, including all of the brokenness found in the wild. A: I don't understand what you mean by passing value to HTML formatted file either, but if you want to make operations on a file, you can do it this way
{ "language": "en", "url": "https://stackoverflow.com/questions/7513468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: STL thrust multiple vector transform? I was wondering if there was a more efficient way of writing a = a + b + c? thrust::transform(b.begin(), b.end(), c.begin(), b.begin(), thrust::plus<int>()); thrust::transform(a.begin(), a.end(), b.begin(), a.begin(), thrust::plus<int>()); This works but is there a way to get the same effect using just one line of code? I looked at the saxpy implementation in the examples, however this uses 2 vectors and a constant value; Is this more efficient? struct arbitrary_functor { template <typename Tuple> __host__ __device__ void operator()(Tuple t) { // D[i] = A[i] + B[i] + C[i]; thrust::get<3>(t) = thrust::get<0>(t) + thrust::get<1>(t) + thrust::get<2>(t); } }; int main(){ // allocate storage thrust::host_vector<int> A; thrust::host_vector<int> B; thrust::host_vector<int> C; // initialize input vectors A.push_back(10); B.push_back(10); C.push_back(10); // apply the transformation thrust::for_each(thrust::make_zip_iterator(thrust::make_tuple(A.begin(), B.begin(), C.begin(), A.begin())), thrust::make_zip_iterator(thrust::make_tuple(A.end(), B.end(), C.end(), A.end())), arbitrary_functor()); // print the output std::cout << A[0] << std::endl; return 0; } A: a = a + b + c has low arithmetic intensity (only two arithmetic operations for every 4 memory operations), so the computation is going to be memory bandwidth bound. To compare the efficiency of your proposed solutions, we need to measure their bandwidth demands. Each call to transform in the first solution requires two loads and one store for each call to plus. So we can model the cost of each transform call as 3N, where N is the size of the vectors a, b, and c. Since there are two invocations of transform, the cost of this solution is 6N. We can model the cost of the second solution in the same way. Each invocation of arbitrary_functor requires three loads and one store. So a cost model for this solution would be 4N, which implies that the for_each solution should be more efficient than calling transform twice. When N is large, the second solution should perform 6N/4N = 1.5x faster than the first. Of course, you could always combine zip_iterator with transform in a similar way to avoid two separate calls to transform.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: QtService does not pass the start parameters from Service Manager window How to get the Start parameters that are passed from the Windows Service Manager dialog. I was hoping I would get them as command line args passed to the main function. If I pass the arguments to binPath when creating the service then I get the arguments passed into main function. sc create "Myservice" binPath= "Path_to_exe\Myservice.exe -port 18082" But this way we need to uninstall and install the service everytime to change any arguments. Is there any way to get the start parameters in Qt? If I create the service using .NET, I can use the following function to get these Start parameters. System::Environment::GetCommandLineArgs(); A: I know that this question is old, but how it keeps unanswered and the problem persist until nowadays, I believe that is appropriate give a possible answer. You will be able to get the start parameters of a Qt Service by reimplementing void QtServiceBase::createApplication ( int & argc, char ** argv ) According to the docs: This function is only called when no service specific arguments were passed to the service constructor, and is called by exec() before it calls the executeApplication() and start() functions. So when your service call the start function the args will be available, because the createApplication is called before the start function. Here a example: #include <QtCore> #include "qtservice.h" class Service : public QtService<QCoreApplication> { public: explicit Service(int argc, char *argv[], const QString &name) : QtService<QCoreApplication>(argc, argv, name) { setServiceDescription("Service"); setServiceFlags(QtServiceBase::CanBeSuspended); setStartupType(QtServiceController::ManualStartup); } protected: void start() { // use args; } void stop() { } void pause() { } void resume() { } void processCommand(int code) { } void createApplication(int &argc, char **argv) { for (int i = 0; i < argc; i++) args.append(QString(argv[i])); QtService::createApplication(argc, argv); } private: QStringList args; }; int main(int argc, char *argv[]) { Service s(argc, argv, "Service"); return s.exec(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7513478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C++ compiling Issue I have been having an issue with an error that has been given to me when I try to compile. The error says, error: no matching function for call to 'Invoice::Invoice(const char [10], double, int)' It is giving me the error on //create an invoice using constructor with parameters Invoice ductTape("Duct Tape",2.99,10); Here is my code, first one you will need to save it as Invoice.h It has taken me a while to actually fix most of the errors. Only, this one is the only error I am having. #include <iostream> #include <string> using namespace std; class Invoice { public: void setDescription(string bagofhammers) { description = "bag of hammers"; } void setQuantity(int) { quantity = 1; } void setPrice (int) { price = 12.99; } void ductTape() { setDescription("Duct Tape"); setPrice(2.99); setQuantity(10); } string getDescription(string description) { return description; } int getQuantity(int quantity) { return quantity; } int getPrice(double price) { return price; } void print() { std::cout << "Invoiced item is: " << getDescription(description) << endl; std::cout << "Quantity ordered: "<< getQuantity(quantity) << endl; std::cout << "Each unit's price is: "<< getPrice(price) << endl; std::cout << "Total Amount: "<< (getPrice(price)*getQuantity(quantity)) << endl; } private: string description; double price; int quantity; }; And this one is the program that will use it. #include <iostream> #include "Invoice.h" using namespace std; int main() { string description; double price; int quantity; cout << "Enter the description: "; getline(cin, description); cout << "Enter the unit price: "; cin >> price; cout << "Enter the quantity: "; cin >> quantity; cout << endl;//a new line //create an invoice using default constructor Invoice hammers; hammers.setDescription(description); hammers.setPrice(price); hammers.setQuantity(quantity); //now print the invoice hammers.print(); cout << endl; //create an invoice using constructor with parameters Invoice ductTape("Duct Tape",2.99,10); cout << "[Invoice for object created using constructor]" <<endl; ductTape.print(); cin.ignore(255,'\n');//ignore any leftover new lines cin.get();//pause the output... return 0; } I would assume that I screwed something up on the ductTape part. You must keep in mind, this is the first time I'm taking C++. So if you don't mind explaining what is wrong with this, hopefully I can learn from it. A: You're missing constructors. Add to the public section in header Invoice() : description(0), price(0), quantity(0) {} Invoice(const char* _description, double _price, int _quantity) : description(_description), price(_price), quantity(_quantity) {} A: The error message is pretty clear. You need a constructor for your Invoice class. Invoice::Invoice(const char* description_, double price_, int quantity_) : description(description_), price(price_), quantity(quantity_) {} This constructor makes use of initialization list to initialize member variables with constructor arguments. EDIT: As @the.malkolm pointed you're also making use of Invoice's default constructor in your code by defining Invoice hammers; Since you implemented a constructor which takes arugments, you now need need to implement the default constructor as well. Invoice::Invoice() : description(0), price(0), quantity(0) {} A: You do not have the correct constructor in your Invoice class. A: You have not written the constructors ie. Invoice() { ....} and Invoice(const char * a, double b, int c) {....}
{ "language": "en", "url": "https://stackoverflow.com/questions/7513488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Strange sharepoint error at UserProfile Application this is a new sharepoint installation, and I have this problem when I navigate to the newly installed site. Any help please A: Your User Profile service application is corrupt. Delete and recreate UPSA. A: Check permissions of application pool account and UPA account. Note that UPA permissions may be configured in two places in Central Admin: one under "administrators" and other under "permissions" while configuring UPA. Also you should check timeout values in web.config located in same directory as UPA wcf service. Use IIS Manager to find it and try to increase timeout. I have had similar issue while SharePoint was hosted on slow machine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem related to spring/resources.xml while deploying Grails applicatoin war in tomcat I have developed an application (named CBR) in Grails 1.3.7. When i run it with "grails run-app" or "grails run-app prod" it works fine. However when i create a war using "grails war" command and then deploy this war in Tomcat 6.0.32 i see following exception: Sep 22, 2011 1:55:57 PM org.apache.catalina.startup.HostConfig deployWAR INFO: Deploying web application archive CBR.war context.ContextLoader Context initialization failed org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 1 in XML document from ServletContext resource [/WEB-INF/spring/resources.xml] is in valid; nested exception is org.xml.sax.SAXParseException: Premature end of file. at grails.spring.BeanBuilder.invokeBeanDefiningClosure(BeanBuilder.java:723) at grails.spring.BeanBuilder.beans(BeanBuilder.java:573) at grails.spring.BeanBuilder.invokeMethod(BeanBuilder.java:519) Caused by: org.xml.sax.SAXParseException: Premature end of file. at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195) at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:174) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:388) at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1414) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:1059) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737) at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119) at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:235) at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:284) ... 3 more Sep 22, 2011 1:57:48 PM org.apache.catalina.core.StandardContext start SEVERE: Error listenerStart Sep 22, 2011 1:57:48 PM org.apache.catalina.core.StandardContext start SEVERE: Context [/CBR] startup failed due to previous errors Although the project was fully unpacked. I have checked conf/spring/resources.xml ... its empty. I have ready all the threads similar to war deployment problem in Tomcat, but was unable to sort it out. Following is the code from my config.groovy file: environments { production { grails.serverURL = "http://localhost:8080/${appName}" } development { grails.serverURL = "http://localhost:8080/${appName}/auth" } test { grails.serverURL = "http://localhost:8080/${appName}" } } And, from Datasource.groovy file: environments { development { dataSource { dbCreate = "create-drop" // one of 'create', 'create-drop','update' url = "jdbc:mysql://localhost:3306/cbr?autoreconnect=true" } } test { dataSource { dbCreate = "update" url = "jdbc:mysql://localhost:3306/cbr?autoreconnect=true" } } production { dataSource { dbCreate = "update" url = "jdbc:mysql://localhost:3306/cbr_prod?autoreconnect=true" } } } And some more detail from application.properties file: app.grails.version=1.3.7 app.name=CBR app.servlet.version=2.4 app.version=0.1 plugins.autotranslate=0.3 plugins.hibernate=1.3.7 plugins.message-reports=0.1 plugins.navigation=1.2 plugins.richui=0.8 plugins.shiro=1.1.3 plugins.tomcat=1.3.7 plugins.xfire=0.8.3 I have spent last 2 days to sort out the issue. Please help me, it took me 1 month to develop this application. A: This may not be much of an answer, but something you should definitely try before you tie yourself in a knot... The first things I mistrust when I run into issues where something should obviously work, are the state of my build and the state of my machine's configuration. Since you haven't gone through the complete build-deploy cycle yet, you might make sure that it would work at all with your configuration. Build a simple Hello World grails app, generate the war file and deploy it. If that works, I'd start adding plugins and config changes to see if any of these break anything. Shouldn't take you more than 20 minutes. Good Luck
{ "language": "en", "url": "https://stackoverflow.com/questions/7513491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android game loop, how to control speed I have created my game loop through Surfaceview. Animations in the game run faster on powerful devices with high configuration and slower on low configuration devices. So I tried to count FPS and if FPS is high then there should be delay, otherwise no delay for myThreadSurfaceView.onDraw(c); Here is my code of game loop thread that I used for calculation: private long mLastTime; /** Variables for the counter */ private int frameSamplesCollected = 0; private int frameSampleTime = 0; private int fps = 0; @Override public void run() { while (myThreadRun) { Canvas c = null; try { c = myThreadSurfaceHolder.lockCanvas(null); synchronized (myThreadSurfaceHolder) { long now = System.currentTimeMillis(); if (mLastTime != 0) { //Time difference between now and last time we were here int time = (int) (now - mLastTime); frameSampleTime += time; frameSamplesCollected++; //After 10 frames if (frameSamplesCollected == 10) { //Update the fps variable fps = (int) (10000 / frameSampleTime); //Reset the sampletime + frames collected frameSampleTime = 0; frameSamplesCollected = 0; } } mLastTime = now; } if(fps>25) { try { myThreadSurfaceView.onDraw(c); TimeUnit.MILLISECONDS.sleep(35); //Thread.sleep(35); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { myThreadSurfaceView.onDraw(c); } } finally { // do this in a finally so that if an exception is thrown // during the above, we don't leave the Surface in an // inconsistent state if (c != null) { myThreadSurfaceHolder.unlockCanvasAndPost(c); } } } } Now this code is giving the desired output as I want sometimes FPS will be the same for high and low config. devices. What I want is that the game runs the same on both high and low config. devices. So how can I achieve my goal? Is there any better way to do this? A: First: (to answer your question) Use "clock time" to adjust frame rate rather than counting the number of frames. Frame counting is always going to be CPU power dependent - faster the hardware the more times it can call your update loop. So you want to adjust based on the actual time it takes to execute one pass through your loop and then adjust the sleep based on the result. The easiest way is to track how long it takes for your update code to execute (say, 10 milliseconds). private static final long ourTarget_millisPerFrame = 33; // ~30 FPS public void MyUpdate() { long startTime = SystemClock.uptimeMillis(); // ... Do your stuff here ... long stopTime = SystemClock.uptimeMillis(); // How much time do *we* require to do what we do (including drawing to surface, etc)? long howLongItTakesForUsToDoOurWork = stopTime - startTime; // So, say we took 10 millis // ... that leaves (33 - 10 =) 23 millis of "time to spare" // ... so that's how long we'll sleep long timeToWait = ourTarget_millisPerFrame - howLongItTakesForUsToDoOurWork; // But apply a minimum wait time so we don't starve the rest of the system if ( timeToWait < 2 ) timeToWait = 2; // Lullaby time sleep(timeToWait); } Part II: Also ... Perhaps consider using a Looper / Handler approach and posting delayed "Runnable" messages to execute your loop rather than sleep'ing the thread. It's a bit more flexible ... you don't need to deal with thread sleep at all ... and you will probably want to post other messages to your thread anyway (like pause/resume game). See the Android documentation for an code snippet example: * *Looper: http://developer.android.com/reference/android/os/Looper.html *Handler: http://developer.android.com/reference/android/os/Handler.html The Looper is simple - it just loops waiting for messages to array until you call myLooper.quit(). To process your timestep update loop call postDelayed(myRunnable, someDelay) where you create a class implementing runnable. Or, just put MyUpdate method in the class and call it when receive a message ID. (Runnable version is more efficient) class MyUpdateThread extends Thread { public static final int MSGID_RUN_UPDATE = 1; public static final int MSGID_QUIT_RUNNING = 2; public MyMessageHandler mHandler; private MyUpdateRunnable myRunnable = new MyUpdateRunnable(); private boolean mKeepRunning; // The *thread's* run method public run() { // Setup the Looper Looper.prepare(); // Create the message handler // .. handler is auto-magically attached to this thread mHandler = new MyMessageHandler(); // Prime the message queue with the first RUN_UPDATE message this.mKeepRunning = true; mHandler.post(myRunnable); // Start the Looper Looper.loop(); } // end run fun (of MyThread class) class MyMessageHandler extends Handler { @Override public void handleMessage(final Message msg) { try { // process incoming messages here switch (msg.what) { case MSGID_RUN_UPDATE: // (optional) // ... could call MyUpdate() from here instead of making it a runnable (do either/or but not both) break; case MSGID_QUIT_RUNNING: mKeepRunning = false; // flag so MyRunnable doesn't repost Looper.myLooper().quit(); break; } } catch ( Exception ex ) {} } class MyUpdateRunnable implements Runnable { public void run() { try { // ---- Your Update Processing ---- // -- (same as above ... without the sleep() call) -- // Instead of sleep() ... we post a message to "ourself" to run again in the future mHandler.postDelayed ( this, timeToWait ); } catch ( Exception ex ) {} } // end run fun (my runnable) } // end class (my runnable) } The following article is a more elaborate solution with attempts to compensate for the occasional "this one timestep ran long". It's for Flash actionscript but easily applied to your Android application. (It's a bit more advanced but it helps smooth frame rate hiccups) * *http://www.8bitrocket.com/2008/4/8/Tutorial-Creating-an-Optimized-AS3-Game-Timer-Loop/ A: I have seen this on tutorials, try to sleep() after every frame, or something like that, this will allow other processes on the phone to work and it should make ur game run the same speed whatever the hardware is, sorry that i cant give u a better answer, but try surface view tutorials
{ "language": "en", "url": "https://stackoverflow.com/questions/7513493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android Map Overlay Issues Is there any way i can implement a zoom listener that can trigger events as soon as the zoom level changes. So far, i have managed with the onUserinteraction method manually checking for changing zoom-level. Another thing is i to want add/remove overlays dynamically. what i,ve done so far is in the onUserinteraction method, i call a function which adds the overlays dynamically, using mapOverlays.add() function and the addition actually does happen dynamically. But somehow mapOverlays.remove() function is not removing the overlays //Function for adding first set of markers public void setOverlay() { worldLength = World.length; mapOverlays = mapView.getOverlays(); drawable0 = this.getResources().getDrawable(R.drawable.marker); itemizedOverlay0 = new MyItemizedOverlay(drawable0); for (int i = 0; i < worldLength; i++) { itemizedOverlay0.addOverlay(World[i]); } mapOverlays.add(itemizedOverlay0); mapView.postInvalidate(); } //Function for adding second set of markers public void setOverlay1() { mapView.setStreetView(true); usaLength = USA.length; mexicoLength = Mexico.length; mapOverlays = mapView.getOverlays(); drawable1 = this.getResources().getDrawable(R.drawable.marker); itemizedOverlay1 = new MyItemizedOverlay(drawable1); itemizedOverlay2 = new MyItemizedOverlay(drawable1); for (int i = 0; i < usaLength; i++) { itemizedOverlay1.addOverlay(USA[i]); } for (int i = 0; i < mexicoLength; i++) { itemizedOverlay2.addOverlay(Mexico[i]); } mapOverlays.add(itemizedOverlay1); mapOverlays.add(itemizedOverlay2); mapView.postInvalidate(); } public void onUserInteraction() { super.onUserInteraction(); if(mapView.getZoomLevel()>3) { mapOverlays.remove(itemizedOverlay0); setOverlay1(); //the above happens } else if(mapView.getZoomLevel()<=3 && mapOverlays.size()>5) { mapOverlays.remove(itemizedOverlay1); mapOverlays.remove(itemizedOverlay2); //the above doesn't setOverlay(); } else if(mapView.getZoomLevel()<=3) { } } A: In order to implement your custom zoom handler and add a listener, you need to be create your subclass of the MapView. First, let's create the interface for the OnZoomListener. Note that you could change the interface to suit your need, the following is just a skeleton code for you to start with public interface OnZoomListener { /*** * /** * Called when there is a zoom changes * @param mapView Reference to the current map view * @param currentZoom The current zoom, set to -1 initially * @param newZoom The new zoom level */ public void onZoomChanged(MapView mapView, int currentZoom, int newZoom); } Now, you need a subclass that will call this OnZoomListener whenever the zoom changes. Here is the skeleton code for that which is an extension of this SO Answer public class MyMapView extends MapView { int oldZoomLevel=-1; OnZoomListener onZoomListener; public MyMapView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public MyMapView(Context context, AttributeSet attrs) { super(context, attrs); } public MyMapView(Context context, String apiKey) { super(context, apiKey); } public void setOnZoomListener(OnZoomListener onZoomListener) { this.onZoomListener = onZoomListener; } @Override public void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); int newZoom = this.getZoomLevel(); if (newZoom != oldZoomLevel) { // dispatch the listeners if(oldZoomLevel != -1 && onZoomListener != null) { onZoomListener.onZoomChanged(this, oldZoomLevel, newZoom); } // update the new zoom level oldZoomLevel = getZoomLevel(); } } } Now you could use MyMapView in your layout instead of the standard MapView. Note: The code package com.so4729255 is what I use for testing only. <com.so4729255.MyMapView android:id="@+id/mapview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:enabled="true" android:apiKey="YOUR API KEY" android:clickable="true" /> And finally add the OnZoomListener in your code. The code below just show the Toast for illustration of usage, you could do whatever you need to do there MyMapView mapView = (MyMapView)this.findViewById(R.id.mapview); mapView.setOnZoomListener(new OnZoomListener() { public void onZoomChanged(MapView mapView, int currentZoom, int newZoom) { // implement your handler here Toast t = Toast.makeText(WebViewMain.this, "Zoom has changed from " + currentZoom + " to " + newZoom, 500); t.show(); } }); As for your second question, as everyone has answered, calling MapView.invalidate() should repaint the map with its new state as it will force the View to redraw per the API documentation A: well you have to refresh the map using mapview.invalidate() postInvalidate posts an invalidate request on the UI-thread, while a call to invalidate() invalidates the View immediately A: When the zoom level changes, the map is redrawn so I simply put this type of functionality in my overlay's draw method, like so: e@Override public void draw(Canvas canvas, MapView mapv, boolean shadow) { int zoom = mapv.getZoomLevel(); switch(zoom) { case 19: setMarkersForZoomLevel19(); break; case 18: setMarkersForZoomLevel18(); break; case 17: setMarkersForZoomLevel17(); break; case 16: setMarkersForZoomLevel16(); break; default: // Hide the markers or remove the overlay from the map view. mapv.getOverlays().clear(); } // Putting this call here rather than at the beginning, ensures that // the Overlay items are drawn over the top of canvas stuff e.g. route lines. super.draw(canvas, mapv, false); } and when you remove an overlay, remember to call mapView.invalidate().
{ "language": "en", "url": "https://stackoverflow.com/questions/7513494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WPF Commands Firing despite having Focus in WinForms TextBox Given: <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid.CommandBindings> <CommandBinding Command="Cut" Executed="CommandBinding_Executed"/> </Grid.CommandBindings> <TextBox x:Name="WpfTextBox" VerticalAlignment="Center" Text="Hello there" /> <WindowsFormsHost Grid.Column="1" VerticalAlignment="Center"> <wf:TextBox x:Name="WinFormsTextBox" Text="Hello there" /> </WindowsFormsHost> </Grid> Pressing Ctrl+X in WinFormsTextBox causes CommandBinding_Executed to fire, but not when you are in WpfTextBox. I wish to have the behaviour of WpfTextBox for WinFormsTextBox. I.e. The command should only fire when nothing has focus - it should work like a global view command or something. Note: Adding a handler to the command's CanExecute event only aids in either preventing anything from happening in the WinFormsTextBox (Ctrl+X is completely swallowed when e.CanExecute is set to true - meaning no text is cut), or performs as normal. Note 2: Cut is only an example, I would like a solution that would work for any command binding. Note 3: The command should be able to fire from another control, if it had focus - like a ListView or something. Unless it had a TextBox that had focus inside of it (think edit mode). I am not sure anything can really be done, I don't want to accept having to add specific handling in the CommandBinding_Executed method. But, C'est la vie. A: WPF commands are routed and you defined the CommandBinding for the Ctrl+X command in the parent control of WindowsFormsHost. So if you want it to be handled only in the WPF TextBox remove your CommandBinding from the Grid and put it there: <TextBox> <TextBox.CommandBindings> <CommandBinding Command="Cut" Executed="CommandBinding_Executed"/> </TextBox.CommandBindings> </TextBox> As commands are routed, the Ctrl+X command will be handled by the first parent having a binding for this command. As long as your focus is in the scope of the Grid and you execute Ctrl+X command, the Grid command bindings will handle it. Here is an excellent article about routed events and commands in WPF : Understanding Routed Events and Commands In WPF EDIT: If you don't want the command to be handled when in a TextBox then you have to define the CommandBindings only where Ctrl+X makes sense for you. I do not think you have another solution. Anyway, typically the ApplicationCommands like Cut are contextual to a specific scope, for example a RichTextBox or a ListBox. EDIT: You cannot block WindowsFormsHost firing underlying routed commands. But what you can do is just to remove the host from the CommandBindings scope: <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid Grid.Column="0"> <Grid.CommandBindings> <CommandBinding Command="Cut" Executed="CommandBinding_Executed"/> </Grid.CommandBindings> <TextBox x:Name="WpfTextBox" VerticalAlignment="Center" Text="Hello there" /> </Grid> <WindowsFormsHost Grid.Column="1" VerticalAlignment="Center"> <wf:TextBox x:Name="WinFormsTextBox" Text="Hello there" /> </WindowsFormsHost> </Grid> Of course if you have much more objects to layout it can be a bit tricky but it will work. Just remove the objects you do not want to handle commands from the scope of the CommandBindings. A: A slightly silly solution for a slightly silly problem. This is a simple version of my final solution: private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.ContinueRouting = IsFocusInWinFormsInputControl(); } private static bool IsFocusInWinFormsInputControl() { // Try get focus control WinForms.Control focusedWinFormsControl = GetFocusedWinFormsControl(); // Is there anything and is it a textbox etc? return focusedWinFormsControl != null && (focusedWinFormsControl is WinForms.TextBox || focusedWinFormsControl is WinForms.RichTextBox); } private static WinForms.Control GetFocusedWinFormsControl() { // Try get focused WinForms control IntPtr focusedControlHandle = GetFocus(); WinForms.Control focusedControl = null; if (focusedControlHandle != IntPtr.Zero) { // Note: If focused Control is not a WinForms control, this will return null focusedControl = WinForms.Control.FromHandle(focusedControlHandle); } return focusedControl; } [DllImport("user32.dll")] private static extern IntPtr GetFocus(); Basically, add in command validation logic to only execute the command if we are outside a WinForms TextBox.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Apache Camel - problem with error handling I have a problem with error handling. If an exception occurs in the jrnRoute, it is processed by the exceptionHandler processor. This is OK. But the message which caused the exception still stays in the jrnQueue, is processed again and causes the error over and over again. Also I have a warning (see below) in logs. How to stop the infinite redelivery? I want to throw a message away in case of an error. Camel configuration <camel:onException> <camel:exception>java.lang.Exception</camel:exception> <camel:redeliveryPolicy disableRedelivery="true" /> <camel:process ref="exceptionHandler" /> <camel:rollback markRollbackOnly="true" /> </camel:onException> <camel:route id="translatorRoute"> <camel:from ref="transactionsQueue" /> <camel:process ref="messageTranslator" /> <camel:inOnly ref="apfRequestQueue" /> </camel:route> <camel:route id="jrnRoute"> <camel:from ref="jrnQueue" /> <camel:process ref="jrnProcessor" /> <camel:stop /> </camel:route> </camel:camelContext> Warning 11:15:00,141 WARN [JmsMessageListenerContainer] Execution of JMS message listener failed, and no ErrorHandler has been set. org.apache.camel.RuntimeCamelException: org.apache.camel.RollbackExchangeException: Intended rollback. Exchange[JmsMessage: [ObjectMessageImpl com.swiftmq.jms.ObjectMessageImpl@c84d9d messageIndex = 5_2 messageId = [LazyUTF8String, s=ID:/172.26.214.11/5349789614428334512/10/0, buffer=[B@5f7fd8] userId = [LazyUTF8String, s=null, buffer=[B@1c254aa] clientId = null timeStamp = 1316682898526 correlationId = null replyTo = null destination = jrnQueue@z4smq_4001 deliveryMode = 2 redelivered = true deliveryCount = 8 type = null expiration = 0 priority = 4 props = {...} readOnly = true sourceRouter = null destRouter = null destQueue = null array=[B@1447e6b cnt=1295]] at org.apache.camel.util.ObjectHelper.wrapRuntimeCamelException(ObjectHelper.java:1145) at org.apache.camel.component.jms.EndpointMessageListener.onMessage(EndpointMessageListener.java:108) at org.springframework.jms.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:560) at org.springframework.jms.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:498) at org.springframework.jms.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:467) at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.doReceiveAndExecute(AbstractPollingMessageListenerContainer.java:325) at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveAndExecute(AbstractPollingMessageListenerContainer.java:243) at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.invokeListener(DefaultMessageListenerContainer.java:1058) at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.executeOngoingLoop(DefaultMessageListenerContainer.java:1050) at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:947) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:662) Caused by: org.apache.camel.RollbackExchangeException: Intended rollback. Exchange[JmsMessage: [ObjectMessageImpl com.swiftmq.jms.ObjectMessageImpl@c84d9d messageIndex = 5_2 messageId = [LazyUTF8String, s=ID:/172.26.214.11/5349789614428334512/10/0, buffer=[B@5f7fd8] userId = [LazyUTF8String, s=null, buffer=[B@1c254aa] clientId = null timeStamp = 1316682898526 correlationId = null replyTo = null destination = jrnQueue@z4smq_4001 deliveryMode = 2 redelivered = true deliveryCount = 8 type = null expiration = 0 priority = 4 props = {...} readOnly = true sourceRouter = null destRouter = null destQueue = null array=[B@1447e6b cnt=1295]] A: Yes the markRollbackOnly will cause the transaction manager to mark the TX as rollback, and therefore the JMS broker will keep the message in the queue, and redeliver it again. So remove that instead. And do as Ben posted above, with handled true: <camel:onException> <camel:exception>java.lang.Exception</camel:exception> <camel:redeliveryPolicy disableRedelivery="true" /> <camel:handled> <camel:constant>true</camel:constant> </camel:handled> <camel:process ref="exceptionHandler" /> </camel:onException> A: looks like markRollbackOnly="true" is the issue... I usually do something like this to simply handle (prevent propagating back to caller), prevent retries and log error messages... onException(Exception.class) .handled(true).maximumRedeliveries(0) .to("log:error processing message");
{ "language": "en", "url": "https://stackoverflow.com/questions/7513500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: A simple way to serialise a double? I am using ksoap and I want to send location information gathered by my android to ksoap. I want to try and avoid making a marshall class etc, is there a simple way to serialise and send the double to my soap xml? I've tried using String.valueof however it throws an error so i assume I cannot use that. Also is it an issue that I'm passing a double to the xml of type decimal? This is the xml file I am sending to: <s:element name="Customerlocation_AddNew"> <s:complexType> <s:sequence> <s:element minOccurs="0" maxOccurs="1" name="Token" type="s:string" /> <s:element minOccurs="0" maxOccurs="1" name="Username" type="s:string" /> <s:element minOccurs="1" maxOccurs="1" name="latitude" type="s:decimal" /> <s:element minOccurs="1" maxOccurs="1" name="longitude" type="s:decimal" /> <s:element minOccurs="1" maxOccurs="1" name="StatusId" type="s:int" /> </s:sequence> </s:complexType> </s:element> and my java code so far: SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); // set request.addProperty("Username", username); // variable name, value. I // got request.addProperty("latitude", String.valueOf(Latitude)); request.addProperty("longitude", String.valueOf(Longitude)); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); // put all required data into a soap envelope.dotNet = true; envelope.setOutputSoapObject(request); // prepare request AndroidHttpTransport httpTransport = new AndroidHttpTransport(URL); httpTransport.debug = true; httpTransport.call(SOAP_ACTION, envelope); // send request System.out.println("HERE IS THE ENVELOPE " + envelope.getInfo("User", "Password")); SoapObject result = (SoapObject) envelope.getResponse(); // get System.out.println(result); A: Why do you want to avoid using Marshal?! There is an implementation MarshalFloat especially for transporting floats. If you really want to go without Marshal - look at MarshalFloat implementation! In your case you should use something like this: request.addProperty("longitude", new BigDecimal(Longitude).toString()) EDIT: log your request\response to find out what is wrong: Log.d("test", "request: " + httpTransport .requestDump); Log.d("test", "response: " + httpTransport .responseDump); And try the following to obtain result object: SoapObject result = (SoapObject) envelope.bodyIn; Hope this helps. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7513506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Oracle SQL Query to to run a column value as sql query I have the following row in the table TEMP_ID HTML_LABEL HTML_NAME OPTIONS_TYPE OPTION_VALUES HTML_CODE ---------------------------------------------------------------------------------------------- 2 RULE_NO : RULE_NO_7_32 D SELECT DRV_COLUMN FROM FRD_DATA <reconTags:renderSelect></reconTags:renderSelect> I want an oracle sql query that gives the output like this TEMP_ID HTML_LABEL HTML_NAME OPTIONS_TYPE OPTION_VALUES HTML_CODE ---------------------------------------------------------------------------- 2 RULE_NO : RULE_NO_7_32 D 1,2,3,4 <reconTags:renderSelect></reconTags:renderSelect> I want the result of the query stored in the option_values field to be displayed as the value of the option_values field. (Possibly comma-separated concatenated values, where the query would return multiple rows.) A: Create a function that takes your sql column as a parameter, and loops through each record building up a string of values then return the result, the usage would be SELECT col1, your_function(col2) from your table Here's some pointers on dynamic SQL: http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28370/dynamic.htm I guess it will be something like this: CREATE OR REPLACE FUNCTION sql_to_csv (p_select IN VARCHAR2) RETURN VARCHAR AS v_out VARCHAR2 (4000); TYPE RefCurTyp IS REF CURSOR; v_cursor RefCurTyp; a_record DUAL%ROWTYPE; BEGIN OPEN v_cursor FOR p_select; -- Fetch rows from result set one at a time: LOOP FETCH v_cursor INTO a_record; EXIT WHEN v_cursor%NOTFOUND; v_out:=v_out || ',' || a_record.dummy; END LOOP; -- Close cursor: CLOSE v_cursor; RETURN (v_out); END;
{ "language": "en", "url": "https://stackoverflow.com/questions/7513510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: When increasing the size of VARCHAR column on a large table could there be any problems? I'm using SQL Server 2008 and I need to make a VARCHAR field bigger, from (200 to 1200) on a table with about 500k rows. What I need to know is if there are any issues I have not considered. I will be using this TSQL statement: ALTER TABLE MyTable ALTER COLUMN [MyColumn] VARCHAR(1200) I've already tried it on a copy of the data and this statement had no ill effects that I could see. So are there any possible problems from doing this that I may not have considered? By the way, the column is not indexed. A: This is a metadata change only: it is quick. An observation: specify NULL or NOT NULL explicitly to avoid "accidents" if one of the SET ANSI_xx settings are different eg run in osql not SSMS for some reason A: Changing to Varchar(1200) from Varchar(200) should cause you no issue as it is only a metadata change and as SQL server 2008 truncates excesive blank spaces you should see no performance differences either so in short there should be no issues with making the change. A: Just wanted to add my 2 cents, since I googled this question b/c I found myself in a similar situation... BE AWARE that while changing from varchar(xxx) to varchar(yyy) is a meta-data change indeed, but changing to varchar(max) is not. Because varchar(max) values (aka BLOB values - image/text etc) are stored differently on the disk, not within a table row, but "out of row". So the server will go nuts on a big table and become unresponsive for minutes (hours). --no downtime ALTER TABLE MyTable ALTER COLUMN [MyColumn] VARCHAR(1200) --huge downtime ALTER TABLE MyTable ALTER COLUMN [MyColumn] VARCHAR(max) PS. same applies to nvarchar or course. A: Another reason why you should avoid converting the column to varchar(max) is because you cannot create an index on a varchar(max) column. A: In my case alter column was not working so one can use 'Modify' command, like: alter table [table_name] MODIFY column [column_name] varchar(1200);
{ "language": "en", "url": "https://stackoverflow.com/questions/7513513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "90" }
Q: Designating columns based on element order in XML My XML is shown below: <?xml version="1.0" encoding="UTF-8"?> <JobListing> <ColumnOrder> <columnId>4</columnId> <columnId>2</columnId> <columnId>5</columnId> <columnId>1</columnId> <columnId>3</columnId> </ColumnOrder> <Jobs> <Job> <title>Java Developer</title> <code>JAVA</code> <openings>10</openings> <location>USA</location> <duration>6 months</duration> </Job> <Job> <title>.NET Developer</title> <code>DOTNET</code> <openings>10</openings> <location>USA</location> <duration>6 months</duration> </Job> </Jobs> </JobListing> I've a specific requirement that Jobs should be listed in a HTML page based on ColumnOrder specified in the XML. Internally, each columnId is mapped to a column as given below: * *1 -> Title *2 -> Code *3 -> Openings *4 -> Location *5 -> Duration In this case, for example, Job listing page should list columns in this order - Location, Code, Duration, Title, Openings. Am expecting something like as explained below: <tr> loop jobs for each columnorder if(columnId == 1) <td>get Title</td> else if (columnId == 2) <td>get Code</td> else if (columnId == 3) <td>get Openings</td> else if (columnId == 4) <td>get Location</td> else if (columnId == 5) <td>get Duration</td> end if end columnorder end jobs </tr> How do I achieve this using XSLT? Any help or different ideas/suggestions would be greatly appreciated. EDIT: The <Job> elements in the XML (title, openings, location, duration, code) are not necessarily in the same order. In fact, in our current framework, it gets generated in ascending order (like code, duration, location, openings, title). How to make it work without taking into account order of elements of <Job>? A: This transformation works even when the children of Job are mixed in any order: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:my="my:my" exclude-result-prefixes="my"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <my:Mapping> <id val="1">title</id> <id val="2">code</id> <id val="3">openings</id> <id val="4">location</id> <id val="5">duration</id> </my:Mapping> <xsl:variable name="vOrder" select="/*/ColumnOrder/*"/> <xsl:variable name="vMap" select= "document('')/*/my:Mapping/*"/> <xsl:template match="Jobs"> <table> <xsl:apply-templates/> </table> </xsl:template> <xsl:template match="Job"> <tr> <xsl:apply-templates select="*"> <xsl:sort data-type="number" select= "count($vOrder [. = $vMap [. = name(current())]/@val ] /preceding-sibling::* ) "/> </xsl:apply-templates> </tr> </xsl:template> <xsl:template match="Job/*"> <td><xsl:value-of select="."/></td> </xsl:template> <xsl:template match="ColumnOrder"/> </xsl:stylesheet> When applied on the provided XML document: <JobListing> <ColumnOrder> <columnId>4</columnId> <columnId>2</columnId> <columnId>5</columnId> <columnId>1</columnId> <columnId>3</columnId> </ColumnOrder> <Jobs> <Job> <title>Java Developer</title> <code>JAVA</code> <openings>10</openings> <location>USA</location> <duration>6 months</duration> </Job> <Job> <title>.NET Developer</title> <code>DOTNET</code> <openings>10</openings> <location>USA</location> <duration>6 months</duration> </Job> </Jobs> </JobListing> The wanted, correct result is produced: <table> <tr> <td>USA</td> <td>JAVA</td> <td>6 months</td> <td>Java Developer</td> <td>10</td> </tr> <tr> <td>USA</td> <td>DOTNET</td> <td>6 months</td> <td>.NET Developer</td> <td>10</td> </tr> </table> A: This stylesheet: <?xml version="1.0"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output indent="yes"/> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="JobListing"> <xsl:apply-templates /> </xsl:template> <xsl:template match="Jobs"> <table> <xsl:apply-templates /> </table> </xsl:template> <xsl:template match="Job"> <tr> <xsl:variable name="currentJob" select="."/> <xsl:for-each select="/JobListing/ColumnOrder/columnId"> <xsl:choose> <xsl:when test="current()=1"> <xsl:apply-templates select="$currentJob/title" /> </xsl:when> <xsl:when test="current()=2"> <xsl:apply-templates select="$currentJob/code" /> </xsl:when> <xsl:when test="current()=3"> <xsl:apply-templates select="$currentJob/openings" /> </xsl:when> <xsl:when test="current()=4"> <xsl:apply-templates select="$currentJob/location" /> </xsl:when> <xsl:when test="current()=5"> <xsl:apply-templates select="$currentJob/duration" /> </xsl:when> </xsl:choose> </xsl:for-each> </tr> </xsl:template> <xsl:template match="Job/*"> <td> <xsl:apply-templates /> </td> </xsl:template> <!--Don't render ColumnOrder--> <xsl:template match="ColumnOrder"/> </xsl:stylesheet> Applied to the sample input produces the following output: <?xml version="1.0" encoding="UTF-8"?> <table> <tr> <td>USA</td> <td>JAVA</td> <td>6 months</td> <td>Java Developer</td> <td>10</td> </tr> <tr> <td>USA</td> <td>DOTNET</td> <td>6 months</td> <td>.NET Developer</td> <td>10</td> </tr> </table> A: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/"> <xsl:apply-templates select="//Job"/> </xsl:template> <xsl:template match="Job"> <xsl:copy> <xsl:apply-templates select="../../ColumnOrder/columnId"> <xsl:with-param name="pos" select="position()"/> </xsl:apply-templates> </xsl:copy> </xsl:template> <xsl:template match="columnId"> <xsl:param name="pos"/> <xsl:copy-of select="../../Jobs/Job[position() = $pos]/*[position() = current()/.]"/> </xsl:template> </xsl:stylesheet> Output: <Job> <location>USA</location> <code>JAVA</code> <duration>6 months</duration> <title>Java Developer</title> <openings>10</openings> </Job> <Job> <location>USA</location> <code>DOTNET</code> <duration>6 months</duration> <title>.NET Developer</title> <openings>10</openings> </Job>
{ "language": "en", "url": "https://stackoverflow.com/questions/7513514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Iterate through JSON object I have a json object defined like this - "Content" : [ "Value1", "Value2", {"key": "value"}, {"key": "value"} ] I can get the length of contents since it is an array. How do I iterate through the object, so that I can display in this format- <div>Value1</div> <div>Value2</div> <div><a href=key>Value</a></div> <div><a href=key>Value</a></div> I am working on Javascript. Thanks a lot! A: If you had the variable var c = {"Content" :["Value1","Value2",{"href": "key","val":"value"},{"href":"key","val":"value"}]} you could then do what you wanted by using a for loop like this for(x in c.Content){ if(typeof(c.Content[x])== "object"){ var d = document.createElement("div"); d.innerHTML = "<a href='"+c.Content[x].href+"'>"+c.Content[x].val+"</a>"; document.body.appendChild(d); }else{ var d = document.createElement("div"); d.innerHTML = c.Content[x]; document.body.appendChild(d); } } As you can see I did have to change your JSON slightly to make it easier on you to extract the information you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: get will_paginate to define a custom offset on the first page i'm building a news section on my rails website and it uses will_paginate for pagination. now i was wondering how i can specify a custom offset for the first page with will_paginate. something like this: @featured_news = Post.first @news = Post.offset(1).paginate(:page => params[:page]) i need the latest news-entry to be special and not be included in the @news objects. how i can achieve this? thanks for your time! A: will_paginate redefines every offset and limit query conditions, to get the rows of a specific page. I can see two options for you : The ugly one : take advantage of the fact that will_paginate works on collections, and use this syntax (it will load all your table though) @news = Post.offset(1).all.paginate(:page => params[:page]) The longer one : fork the will_paginate gem so that it can handle custom offsets. I haven't tried it, but something like this should work (the changes to the gem are highlighted) # will_paginate / lib / will_paginate / active_record.rb module Pagination def paginate(options) options = options.dup pagenum = options.fetch(:page) { raise ArgumentError, ":page parameter required" } per_page = options.delete(:per_page) || self.per_page total = options.delete(:total_entries) ####################################### custom_offset = options.delete(:offset) ####################################### count_options = options.delete(:count) options.delete(:page) ####################################################### # rel = limit(per_page.to_i).page(pagenum) rel = limit(per_page.to_i).page(pagenum, custom_offset) ####################################################### rel = rel.apply_finder_options(options) if options.any? rel.wp_count_options = count_options if count_options rel.total_entries = total.to_i unless total.blank? rel end ################################ # def page(num) def page(num, custom_offset = 0) ################################ rel = scoped.extending(RelationMethods) pagenum = ::WillPaginate::PageNumber(num.nil? ? 1 : num) per_page = rel.limit_value || self.per_page ################################################################## # rel = rel.offset(pagenum.to_offset(per_page).to_i) rel = rel.offset(pagenum.to_offset(per_page).to_i + custom_offset) ################################################################## rel = rel.limit(per_page) unless rel.limit_value rel.current_page = pagenum rel end end This should allow you to use this syntax: @news = Post.paginate(:page => params[:page], :offset => 1)
{ "language": "en", "url": "https://stackoverflow.com/questions/7513519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: I'm forced to redirect to logo page in Facebook App IFRAME I want to login to facebook in IFRAME(Facebook Apps). Go http://apps.facebook.com/oauthtwosample/ with logoff and click "login" link. Response header have Location Header when redirect permissions request dialog page. Chrome screenshot below: http://gyazo.com/0f4988158cb0e0a9f52545374540de96 If you have any ideas, let me know. Source: require 'rubygems' require 'sinatra' require 'oauth2' require 'json' @@client = OAuth2::Client.new( 'xxxxxxxxxxxxx', 'xxxxxxxxxxxxxxxxxxxxxxxx', :site => 'https://graph.facebook.com' ) def redirect_uri uri = URI.parse(request.url) uri.path = '/auth/facebook/callback' uri.query = nil uri.to_s end get '/' do '<a href="/auth/facebook">login</a>' end post '/' do '<a href="/auth/facebook">login</a>' end get '/auth/facebook' do redirect @@client.web_server.authorize_url( :redirect_uri => redirect_uri, :scope => 'email,offline_access' ) end get '/auth/facebook/callback' do access_token = @@client.web_server.get_access_token( params[:code], :redirect_uri => redirect_uri ) user = JSON.parse(access_token.get('/me')) user.inspect end A: This is because of redirting user without permission you can easly solve it by adding target="_top" to link. <a href="url" target="_top">login</a>
{ "language": "en", "url": "https://stackoverflow.com/questions/7513540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Abstracting the accountcontroller MVC How would I go about abstracting the membership information in MVC3 c# Currently the membership data is kept on a localhost SQL server and is linked to MVC via the Entity Framework. As I want to perform some extensions, I need to abstract it, creating an interface and class for each entity in the SQL database? Where would I start? Are there any examples available? I can only find ones that are out of date or irrelevant A: I think you can rearrange your application, introducing a service layer separated from your presentation layer. The object model (domain model) that you define in the presentation layer for User and other entities should be distinct from the EF data model, so you need only that some sevices ( for example you can implement these as Web Services) read the data using EF and populate your domain model of the presentataion layer. This approach allows your application to be more flexible to future changes or extensions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery accordion and slider not working together We have the following code: http://jsfiddle.net/c5cpk/ Which should show an accordion with content in each pane along with a jquery slider. At the moment it doesn't it just show's the controls. If you edit the CSS line: #accordion .pane { display:none; height:705px; color:#fff; font-size:12px; } and take away the display:none you will see the panes expanded and the slideshows work correctly. Could anyone help me out as getting quite frustrated with the way it's (not) working. A: Solved by assigning the display none after the page had loaded using: jQuery('#accordion div.pane').css('display', 'none');
{ "language": "en", "url": "https://stackoverflow.com/questions/7513545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java annotation execute a method within the annotation declaration(usage for android) I'm fairly new to the annotation terms. I have read some sources and came to the conclusion that non answered my question. Perhaps I googled using the wrong search. Perhaps I overlook, or mayhbe im just clueless.. Anyway here is the deal. I am busy writing an application that requires "role validation". To do this I want to use an annotation. So something along the line of: @interface Validate (){ } What I aim to achieve is sometihng along the lines of: public @interface Validate() { public Validate() { //Do validation stuff return true/false } } So basically I want to define methods within the annotation. I want to be able to call @Validate public void methodThatRequiresAdminRole() { doStuff(); } Only admins should be able to enter this method. Otherwise an error should be generated. so if @validate returns true, the method should be executed Sorry if I am really unclear. I am not quite sure how to properly ask what I want. So I hope the examples tell the stories. Hope to read tips and perhaps even an answer soon. Thanks. ** EDIT ** I need to stress out the fact that the code must be used on an android application. So I prefer to not use strange frameworks not meant for android. I have no problem adding a custom library that gives the functionality without any kind of application framework. A: Annotations are meta data. What you need to write is an annotation processor. An annotation in itself cannot accomplish the validation logic. The annotation processor will look at the annotations and then do the validation and control the application flow. This SO answer has a good explanation Can Java Annotations help me with this? You also need to annotate the annotation with @Retention(RetentionPolicy.RUNTIME) so that the annotation information is preserved till the runtime. @Retention(RetentionPolicy.RUNTIME) public @interface Validate() { } A: Note, this might be quite off-topic. Using spring AOP with, processing the annotations is fairly straightforward: Create an aspect: @Aspect public class RoleCheckAspect { @Before("@annotation(your.package.Validate)") public void doAccessCheck() throws Exception { // Do validation stuff if (!valid) throw new IllegalAccessException("foo"); } } } Set-up your aspect: In META-INF/aop.xml <!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd"> <aspectj> <weaver> <!-- only weave classes in our application-specific packages --> <include within="your.package..*" /> </weaver> <aspects> <!-- weave in just this aspect --> <aspect name="com.bac.bsl.nonproc.TestAspect" /> </aspects> </aspectj> Set-up load time weaving In the spring context: <context:load-time-weaver/> Ensure that the spring-agent is started with your app: java -javaagent:/path/to/spring-agent.jar -classpath $CP your.package.MyApp A: I don't think you can achieve this with annotations alone. They are meant to provide meta information about code elements and not processing logic. To actually implement the restriction on the annotated methods invocation you will need to check the access by hand inside or outside the method or inject such a check using something like http://www.eclipse.org/aspectj/
{ "language": "en", "url": "https://stackoverflow.com/questions/7513549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Long running PHP scraper returns 500 Internal Error mostly I find the answers on my questions on google, but now i'm stuck. I'm working on a scraper script, which first scrapes some usernames of a website, then gets every single details of the user. there are two scrapers involved, the first goes through the main page, gets the first name, then gets the details of it's profile page, then it goes forward to the next page... the first site I'm scraping has a total of 64 names, displayed on one main page, while the second one, has 4 pages with over 365 names displayed. the first one works great, however the second one keeps getting me the 500 internal error. I've tried to limit the script, to scrape only a few names, which works like charm, so I'm more then sure that the script itself is ok! the max_execution_time in my php ini file is set to 1500, so I guess that's not the problem either, however there is something causing the error... not sure if adding a sleep command after every 10 names for example will solve my situation, but well, i'm trying that now! so if any of you have any idea what would help solve this situation, i would appreciate your help! thanks in advance, z A: This is definitely a memory issue. One of your variables is growing past the memory limit you have defined in php.ini. If you do need to store a huge amount of data, I'd recommend writing your results to a file and/or DB at regular intervals (and then free up your vars) instead of storing them all in memory at run time. * *get user details *dump to file *clear vars *repeat.. If you set your execution time to infinity and regularly dump the vars to file/db your php script should run fine for hours. A: support said i can higher the memory upto 4gigabytes Typical money gouging support answer. Save your cash & write better code because what you are doing could easily be run from the shared server of a free web hosting provider even with their draconian resource limits. Get/update the list of users first as one job then extract the details in smaller batches as another. Use the SQL BULK Insert command to reduce connections to the database. It also runs much faster than looping through individual INSERTS. Usernames and details is essentially a static list, so there is no rush to get all the data in realtime. Just nibble away with a cronjob fetching the details and eventually the script will catch up with new usernames being added to the incoming list and you end up with a faster,leaner more efficient system.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How does Enumerate work in MonoTouch? In MonoTouch I need to process each object in an NSSet. My attempt, using Enumerate, is as follows: public override void ReturnResults ( BarcodePickerController picker, NSSet results ) { var n = results.Count; // Debugging - value is 3 results.Enumerate( delegate( NSObject obj, ref bool stop ) { var foundCode = ( obj as BarcodeResult ); // Executed only once, not 3 times if ( foundCode != null ) { controller.BarcodeScannedResult (foundCode); } }); // Etc } Although the method is invoked with three objects in results, only one object is processed in the delegate. I would have expected the delegate to be executed three times, but I must have the wrong idea of how it works. Unable to find any documentation or examples. Any suggestion much appreciated. A: You have to set the ref parameter to false. This instructs the handler to continue enumerating: if ( foundCode != null ) { controller.BarcodeScannedResult (foundCode); stop = false; // inside the null check } Here is the ObjC equivalent from Apple documentation. A: Or you could try this extension method to make it easier.. public static class MyExtensions { public static IEnumerable<T> ItemsAs<T>(this NSSet set) where T : NSObject { List<T> res = new List<T>(); set.Enumerate( delegate( NSObject obj, ref bool stop ) { T item = (T)( obj ); // Executed only once, not 3 times if ( item != null ) { res.Add (item); stop = false; // inside the null check } }); return res; } } Then you can do something like: foreach(BarcodeResult foundCode in results.ItemsAs<BarcodeResult>()) { controller.BarcodeScannedResult (foundCode); } Note: Keep in mind this creates another list and copies everything to it, which is less efficient. I did this because "yield return" isn't allowed in anonymous methods, and the alternative ways I could think of to make it a real enumerator without the copy were much much more code. Most of the sets I deal with are tiny so this doesn't matter, but if you have a big set this isn't ideal.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to correctly refresh the ribbon's MFC default recent documents list? How to correctly refresh the ribbon's MFC default recent documents list? The list in not updating correclty. I enabled it using this: In the ribbon XML, inside the CATEGORY_MAIN tag i've created this <RECENT_FILE_LIST> <ENABLE>TRUE</ENABLE> <LABEL>Recent Documents</LABEL> </RECENT_FILE_LIST> and in the ::InitInstance() of my derived CWinApp class i used LoadStdProfileSettings(); the problem is: When i open or save a file, the list isn't updated. But when i close and open the program it passes trought the "LoadStdProfileSettings()" and the list is updated. thanks in advance A: Solution found. in my derived CWinApp class, in the overwritten method AddToRecentFileList, i needed to read the recent file list again adding this at the end of the method: m_pRecentFileList->ReadList();
{ "language": "en", "url": "https://stackoverflow.com/questions/7513556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HttpWebRequest.Timeout behaviour different in .Net / .Net CF? During some tests on multipart upload (using Ethernet) i have found something interesting: I set a short (17sec) HttpWebRequest.Timeout and simulate a long upload using Thread.Sleep in the loop, where the byte-blocks are written to the server. On a PC i get the timeout (RequestCanceled) but on .Net CF (Windows CE 5/6 Module) i dont get the timeout. Does anyone has made the same observation ? A: This is because the implementation of HttpWebRequest.Timeout in .Net CF does nothing: // from C:\Program Files (x86)\Microsoft.NET\SDK\CompactFramework\v3.5\WindowsCE\System.dll public override int Timeout { get { } set { } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7513557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get Current running page in WPF navigation NavigationWindow I m new in WPF, i am developing a navigation application of WPF, <NavigationWindow x:Class="KioskTraffic.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="768" Width="1024" Source="Home.xaml" WindowState="Maximized" ResizeMode="NoResize" ShowsNavigationUI="False" WindowStyle="None" Cursor="Arrow" Closing="NavigationWindow_Closing"></NavigationWindow> and i have some page which display in this navigarionwindow like <Page x:Class="KioskTraffic.Page1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" Height="768" Width="1024" Title="Page1"> How can i know which page is running currently under NavigationWindow.xaml.cs file? I have a timer in this navigation window that want to check if current page is home.xaml then i don't want to start that timer. A: You can get current running page in code behind using CurrentSource property of navigation window. As per your requirements, it's done using NavigationService.Navigate() method like below : NavWindow.xaml : <NavigationWindow x:Class="WPFTest.MyNavWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="768" Width="1024" Source="ShopList.xaml" Grid.Row="1" WindowState="Maximized" ResizeMode="NoResize" ShowsNavigationUI="True" WindowStyle="SingleBorderWindow" Cursor="Arrow" Navigated="NavigationWindow_Navigated"> </NavigationWindow> NavWindow.xaml.cs : namespace WPFTest { public partial class MyNavWindow : NavigationWindow { public MyNavWindow() { InitializeComponent(); } private void NavigationWindow_Navigated(object sender, NavigationEventArgs e) { MessageBox.Show(((NavigationWindow)this).CurrentSource.ToString()); } } } ShopList.xaml : <Page x:Class="WPFTest.ShopList" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="ShopList"> <Grid> <Label Height="28" Margin="81,12,99,0" Name="label1" VerticalAlignment="Top" FontSize="16" FontWeight="Bold">Shop List</Label> <Button Name="btnNext" Content="Go to Product list" Width="150" Height="30" Margin="0,50,0,0" Click="btnNext_Click"></Button> </Grid> ShopList.xaml.cs : namespace WPFTest { public partial class ShopList : Page { public ShopList() { InitializeComponent(); } private void btnNext_Click(object sender, RoutedEventArgs e) { NavigationService.Navigate(new System.Uri("ProductList.xaml", UriKind.Relative)); } } } ProductList.xaml : <Page x:Class="WPFTest.ProductList" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="ProductList"> <Grid> <Label Height="28" Margin="81,12,99,0" Name="label1" VerticalAlignment="Top" FontSize="16" FontWeight="Bold">Product List</Label> </Grid> </Page> It's working fine for me. Hope this solve your problem. Please feel free to ask if it not solve. UPDATE : If you want to navigate page using class name instead of Uri then you can get current source like : MessageBox.Show(((NavigationWindow)this).NavigationService.Content.GetType().Name.ToString() + ".xaml"); A: I had a similar problem. Upendra's accepted answer above lead me in the right direction. My problem was I was using different WPF Pages inside a FRAME. I needed to determine what page was being displayed inside the frame. Here's how I figured it out. Object CurrentPage; private void LSK_1L_Click(object sender, RoutedEventArgs e) { CurrentPage = MCDU_Page_Frame.Content.GetType(); } The CurrentPage object became the class name of the loaded page if used CurrentPage.ToString(); A: I found out my current page by looking at the Content property of the NavigationService of my container window. A: if we want to known current page with full path which display inside frame then we can use that: string currentpage = Myframe.CurrentSource.OriginalString.ToString().Replace("yoursolutionname;component/", ""); A: Use Page Load Event in Every Page to remove Back Entries and to show only Current Page Inside Page Load Use NavigationService function RemoveBackEntry() A: The NavigationWindow has a property called CurrentSource which is the URI of the last page navigated
{ "language": "en", "url": "https://stackoverflow.com/questions/7513558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Passing a const double[][] array as argument to a double** interface I have a 2-dim const double matrix which needs to be passed as argument to a function that takes a (non-const) double** parameter. [CEqParams.h] // < given as is - can't do a thing about it class CEqParams { public: void operator=(const CEqParams &right); ... double dm_params[4][8]; }; . [some_functions.h] // < dto. ... void setEqParams(double **m); ... . [CEqParams.cpp] void CEqParams::operator=(const CEqParams &right) { setEqParams( « magic here » ); } where « magic here » (in the final segment of code snippets) shall take right.dm_params (or an appropriate representation of its contents, respectively). What else than manually transferring right.dm_params to an auxiliary double** structure (by means of a nested loop running over all array fields and copying them one by one) and then passing the latter to setEqParams could I do here? PS: And given I'd be able to pass right.dm_params to a function that takes a double[][] (or double[4][8]?) as parameter - how would I get rid of the const? "Hint": A const_cast<double[4][8]>(right.dm_parameters) doesn't work. A: One fairly ugly way, which at least doesn't require duplicating all the data, is to create a temporary array of row pointers, e.g. void CEqParams::operator=(const CEqParams &right) { double * dm_params_ptrs[4] = { dm_params[0], dm_params[1], dm_params[2], dm_params[3] }; setEqParams(dm_params_ptrs); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7513565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Auto-login in python using mechanize I have an almost working code to connect to a server and do a search. But there is some issue here with the code. This is what I do now with the following python script. I login to the site. Construct a url for the search result and access the search page and open it in a browser. But issue I am facing here is that I am getting a session expired page. But if I have a logged in page open(manually) in the browser, this constructed url is giving me the desired output. So my question here is that How can I keep the 'logged in' session in the script active and open the constructed url in a browser which yield me the desired output. #!/usr/bin/env python import urllib, urllib2, cookielib, mechanize, webbrowser, subprocess from mechanize import ParseResponse, urlopen, urljoin def main(): usr = 'sg092350' pwd = 'gk530911' login_url = 'http://int15.sla.findhere.net/logininq.act?&site=superarms' search_url_1 = '&need_air=yes&need_rail=no&need_train=no&need_hotel=no&need_car=no&origin_request=regular+booking&monAbbrList[0]=9&monAbbrList[1]=9&dateList[0]=29&dateList[1]=30&pickUpCity=&pickUpTime=&dropOffCity=&dropOffTime=&dispAOptions=&dispADestinations=&checkSurroundingAirports=false&doEncodeDecodeForSurrArpt=false&checkPlusMinusDays=N&tripType=roundTrip&itinType=on&departList[0]=BLR&destinationList[0]=DEL&date0=9%2F29%2F11&travelMethodList[0]=departs&timeList[0]=8&date1=9%2F30%2F11&travelMethodList[1]=departs&timeList[1]=8&numPassengers=1&cabinClass=1&pricingType=1&preferredCarrier[0]=&preferredCarrier[1]=&preferredCarrier[2]=&userRequestedWebFares=true' br = mechanize.Browser() cj = cookielib.CookieJar() br.set_cookiejar(cj) br.set_handle_robots(False) br.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0.2) Gecko/20100101 Firefox/6.0.2')] br.open(login_url) br.select_form('loginForm') br.form['user'] = usr br.form['pwd'] = pwd br.submit() print br.geturl() response = urlopen(login_url) forms = ParseResponse(response, backwards_compat=False) form = forms[0] token = forms[0]['token'] site_id = forms[0]['siteID'] site = forms[0]['site'] water_mark = forms[0]['watermark'] trans_index = forms[0]['transIndex'] search_url_0 = 'http://int15.sla.findhere.net/pwairavail.act;' + '?site=' + site + '&sid=4' + '&siteID=' + site_id + '&watermark=' + water_mark + '&token=' + token + '&transIndex=' + trans_index + search_url_1 print search_url_0 print token print site_id print site print water_mark print trans_index print form response.read() #Inserting code to generate html and display the overlay htmlString = """ <html> <head> <title>DirectBook 1.0</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> <script type="text/javascript" src="./fx/jquery.fancybox-1.3.4.pack.js"></script> <link rel="stylesheet" type="text/css" href="./fx/jquery.fancybox-1.3.4.css" media="screen"/> <script type="text/javascript"> $(document).ready(function() { $("#urlLink").fancybox ({ 'width' : '100%', 'height' : '100%', 'autoScale' : false, 'transitionIn' : 'fade', 'transitionOut' : 'fade', 'type' : 'iframe' }); }); </script> </head> <body onload="document.getElementById('urlLink').click()"> <div id="content"> <script type="text/javascript"> var search_url = " """ + search_url_0 + """ "; document.write('<a id="urlLink"' + 'href="' + search_url + '"></a>'); </script> </div> </body> </html>""" # write the html file to the working folder fout = open("search.html", "w") fout.write(htmlString) fout.close() subprocess.Popen('"C:\\Program Files\\Mozilla Firefox\\firefox.exe" "C:\\Python27\\mechanize-0.2.5\\search.html"') if __name__ == '__main__': main() A: You need to share the session (or session identifier, which is probably stored in a cookie) between Mechanize and your browser. This is not easy, and definitely not portable between browsers (if you want that). However, there appears to be support in Mechanize for the SQLite database format that Firefox uses since version 3: https://github.com/jjlee/mechanize/blob/master/mechanize/_firefox3cookiejar.py You may want to check the documentation for that. A: This might be helpful for the login part: (Was able to get site to send data using wireshark. Also "user" might be something else e.g. "username" same with "password". Once again wireshark would help with this. Also could look at source of login page. Good luck!!!) from urllib import urlencode from urllib2 import Request, urlopen req = Request('www.site.com',urlencode({'user':'userhere', 'password':'passwordhere'})) open = urlopen(req)
{ "language": "en", "url": "https://stackoverflow.com/questions/7513569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: why PhantomReference does not work? Demo code: import java.lang.ref.PhantomReference; import java.lang.ref.ReferenceQueue; public class Main { public static void main(String[] args) throws InterruptedException { Object test = new Object(); ReferenceQueue<Object> q = new ReferenceQueue<Object>(); PhantomReference<Object> p = new PhantomReference<Object>(test, q); Object lock = new Object(); while (true) { synchronized (lock) { //q.poll() is null always,why? if (q.poll() != null) { break; } //System.gc(); lock.wait(); } } System.out.println(1111111); } } I tested the code,but it always is dead loop. The code (System.out.println(1111111);) can not execute,q.poll() reurn null. I think if test object is removed by GC,q.poll() will return p object,then break loop,but invoke this demo code,it is not like my thought Edited: I modify the demo code,it can work now. import java.lang.ref.PhantomReference; import java.lang.ref.ReferenceQueue; public class Main { public static void main(String[] args) throws InterruptedException { Object test = new Object(); ReferenceQueue<Object> q = new ReferenceQueue<Object>(); PhantomReference<Object> p = new PhantomReference<Object>(test, q); Object lock = new Object(); while (true) { synchronized (lock) { if (q.poll() != null) { break; } test = null; //it is important System.gc(); lock.wait(100);//should not lock.wait() } } System.out.println(1111111); } } AS sb says,the statement( test=null) is key.GC collect test object that assign null. A: The fact that the test variable is still present means the GC will never collect the object it refers to... I believe JVMs don't collect anything that a local variable refers to even if the local variable is never referred to in the rest of the method. (Also, it's not clear why you're using lock.wait() when nothing is calling lock.pulse().) Here's code which works for me: import java.lang.Thread; import java.lang.ref.PhantomReference; import java.lang.ref.ReferenceQueue; public class Test { public static void main(String[] args) throws InterruptedException { Object test = new Object(); ReferenceQueue<Object> q = new ReferenceQueue<Object>(); PhantomReference<Object> p = new PhantomReference<Object>(test, q); Object lock = new Object(); while (true) { System.out.println("Checking queue..."); if (q.poll() != null) { break; } System.out.println("Still polling..."); System.gc(); try { Thread.sleep(500); } catch (InterruptedException e) { System.out.println("Interrupted!"); break; } // Make the object garbage... test = null; } System.out.println("Finished."); } } A: Try test = null; before your while loop, so that the test object is eligible for garbage collection.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: why it show last pin's type of call out annotation in my mapview I am designing a map view in which i am dropping no. of pins. I have also add a custom view on every pin. Now problem is that when my map view add all pins then on map it don't show my last pin. Instead of last pin it will show only custom view which is not hidden when i tap on that. And on some pins it not add custom view. I am showing my code below... class.h @interface MappingBusinesses : UIViewController { MKMapView *_mapView; CalloutMapAnnotation *_calloutAnnotation; MKAnnotationView *_selectedAnnotationView; Places *Place_Object; DisplayMap *dm; NSMutableArray *routepoints; CSMapRouteLayerView *routeView; UICRouteOverlayMapView *routeOverlayView; UICGDirections *diretions; Yelp_OnTheWayAppDelegate *appDelegate; NSArray *wayPoints; UICGTravelModes travelMode; DetailView *DV_Object; UIActivityIndicatorView *aiv; UILabel *label; UIView *prosView; BusinessData *bd_object; } class.m - (void)viewDidLoad { [super viewDidLoad]; appDelegate = (Yelp_OnTheWayAppDelegate *)[[UIApplication sharedApplication] delegate]; self.title=@"Map"; //[NSThread detachNewThreadSelector:@selector(start) toTarget:self withObject:nil]; label.text=[NSString stringWithFormat:@"%d places along your route",[appDelegate.busines_Aray count]]; [self.mapView setMapType:MKMapTypeStandard]; [self.mapView setZoomEnabled:YES]; [self.mapView setScrollEnabled:YES]; [self.mapView setDelegate:self]; MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } }; region.center.latitude = appDelegate.start_lat; region.center.longitude = appDelegate.start_long; region.span.longitudeDelta = 0.01f; region.span.latitudeDelta = 0.01f; [self.mapView setRegion:region animated:YES]; dm=[[DisplayMap alloc]init]; for(int i=0;i<[appDelegate.mapPin_aray count];i++) { CLLocationCoordinate2D coord; coord.latitude=[[appDelegate.mapPin_lat objectAtIndex:i] floatValue]; coord.longitude=[[appDelegate.mapPin_long objectAtIndex:i] floatValue]; self.calloutAnnotation = [[CalloutMapAnnotation alloc] initWithLatitude:coord.latitude andLongitude:coord.longitude] ; [self.mapView addAnnotation:self.calloutAnnotation]; NSLog(@"coordinate of number%i is %f and %f",i,coord.latitude,coord.longitude); } } - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation { if ([annotation isKindOfClass:[MKUserLocation class]]) { return nil; } static NSString *identifier = @"RoutePinAnnotation"; if ([annotation isKindOfClass:[UICRouteAnnotation class]]) { MKPinAnnotationView *pinAnnotation = (MKPinAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:identifier]; if(!pinAnnotation) { pinAnnotation = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier] autorelease]; } if ([(UICRouteAnnotation *)annotation annotationType] == UICRouteAnnotationTypeStart) { pinAnnotation.pinColor = MKPinAnnotationColorGreen; } else if ([(UICRouteAnnotation *)annotation annotationType] == UICRouteAnnotationTypeEnd) { pinAnnotation.pinColor = MKPinAnnotationColorPurple; } else { pinAnnotation.pinColor = MKPinAnnotationColorPurple; } pinAnnotation.animatesDrop = YES; pinAnnotation.enabled = YES; pinAnnotation.canShowCallout = YES; return pinAnnotation; } static NSString * const kPinAnnotationIdentifier = @"PinIdentifier"; if (annotation == self.calloutAnnotation) { CalloutMapAnnotationView *calloutMapAnnotationView = (CalloutMapAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:kPinAnnotationIdentifier]; if (!calloutMapAnnotationView) { calloutMapAnnotationView = [[[CalloutMapAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"CalloutAnnotation"] autorelease]; calloutMapAnnotationView.contentHeight = 70.0f; bd_object=[appDelegate.busines_Aray objectAtIndex:self.calloutAnnotation.pinID]; UITextField *txtname=[[UITextField alloc] initWithFrame:CGRectMake(0, 5, 150, 30)]; txtname.text=[NSString stringWithFormat:@"%@",bd_object.name_business ]; txtname.userInteractionEnabled=NO; txtname.font = [UIFont boldSystemFontOfSize:18]; txtname.font=[UIFont fontWithName:@"Arial" size:18]; txtname.textColor = [UIColor whiteColor]; txtname.opaque = false; txtname.backgroundColor = [UIColor clearColor]; [calloutMapAnnotationView.contentView addSubview:txtname]; [txtname release]; UILabel *gpsCoordinatesLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, 70, 20)]; gpsCoordinatesLabel.text = @"Categories:"; gpsCoordinatesLabel.font = [UIFont boldSystemFontOfSize:14]; gpsCoordinatesLabel.font=[UIFont fontWithName:@"Arial" size:14]; gpsCoordinatesLabel.textColor = [UIColor whiteColor]; gpsCoordinatesLabel.opaque = false; gpsCoordinatesLabel.backgroundColor = [UIColor clearColor]; gpsCoordinatesLabel.textAlignment = UITextAlignmentRight; [calloutMapAnnotationView.contentView addSubview:gpsCoordinatesLabel]; [gpsCoordinatesLabel release]; UITextField *txtcate=[[UITextField alloc] initWithFrame:CGRectMake(70, 40, 100, 30)]; txtcate.text=[NSString stringWithFormat:@"%@", bd_object.cat_business]; txtcate.userInteractionEnabled=NO; txtcate.font = [UIFont boldSystemFontOfSize:18]; txtcate.font=[UIFont fontWithName:@"Arial" size:18]; txtcate.textColor = [UIColor whiteColor]; txtcate.opaque = false; txtcate.backgroundColor = [UIColor clearColor]; [calloutMapAnnotationView.contentView addSubview:txtcate]; [txtcate release]; UITextField *txtReview=[[UITextField alloc] initWithFrame:CGRectMake(190, 40, 40, 30)]; txtReview.text=[NSString stringWithFormat:@"%d", bd_object.noofreview]; txtReview.userInteractionEnabled=NO; txtReview.font = [UIFont boldSystemFontOfSize:18]; txtReview.textColor = [UIColor whiteColor]; txtReview.opaque = false; txtReview.backgroundColor = [UIColor clearColor]; [calloutMapAnnotationView.contentView addSubview:txtReview]; [txtReview release]; UIImageView *imgView=[[UIImageView alloc] initWithFrame:CGRectMake(210, 40, 31, 23)]; [imgView setImage:[UIImage imageNamed:@"reviewwhite.png"]]; [calloutMapAnnotationView.contentView addSubview:imgView]; [imgView release]; } calloutMapAnnotationView.parentAnnotationView = self.selectedAnnotationView; calloutMapAnnotationView.mapView = self.mapView; return calloutMapAnnotationView; } else { MKPinAnnotationView *annotationView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"CustomAnnotation"] autorelease]; annotationView.canShowCallout = NO; annotationView.pinColor = MKPinAnnotationColorRed; return annotationView; } MKAnnotationView *av; return av; } - (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view { if (self.calloutAnnotation != nil) { self.calloutAnnotation = [[CalloutMapAnnotation alloc] initWithLatitude:view.annotation.coordinate.latitude andLongitude:view.annotation.coordinate.longitude]; } else { self.calloutAnnotation.latitude = view.annotation.coordinate.latitude; self.calloutAnnotation.longitude = view.annotation.coordinate.longitude; } [self.mapView addAnnotation:self.calloutAnnotation]; self.selectedAnnotationView = view; } - (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view { if (self.calloutAnnotation != nil) { [self.mapView removeAnnotation: self.calloutAnnotation]; } } A: Not sure, but I think the issue might be that during your initial loop in viewDidLoad, you're remembering the annotations in self.calloutAnnotation and then checking for it in didSelect and didDeselect. The problem is that self.calloutAnnotation will be replaced every time round the init loop, so at the end, it will only be referencing the last annotation added. For example, when user selects a different annotation, you change self.calloutAnnotation's lat/long and add it again, but that will change the lat/long of the last annotation added in the array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to get sequence of user interaction with android device? After many sites searched and googling, I can't find anything for my problem. I want to capture the sequence of user interactions on android device. Starting from when the device is powered ON. And one more thing is that I'm not talking about the user event on UI of any application. It's for whole device UI interactions. And if any tools are available then please let me know about it. I didn't get anything about this. Any help or suggestion is well appreciate. A: I am not sure at what extent it will help you to achive your goal but the best way I know is that: * *You need to implement Broadcastreceiver for every action like action android:name="android.intent.action.BOOT_COMPLETED" when your device starts, similarly you need to use all the action which will notify you in your receiver. *You can run a service where you can check which app is running for your record. For this you need to fetch installed app list. A: This is not possible, except perhaps via modified firmware, for obvious security and privacy reasons.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the best way to identify logged user? I was looking for the efficient way to track the logged users when using asp.net login control if (!IsPostBack) { if (Membership.GetUser() != null) { var user = Membership.GetUser(); Session["user"] = user; } else { Session["user"] = ""; } } Any suggestions will be appreciated A: You can get the user identity (if you're using asp.net forms membership) through: HttpContext.Current.User.Identity.Name A: why all this pain and why do you try to save it in the Session (which is user specific and not application specific), when you can simply get it from this object: HttpContext.Current.User check this one for details: How to get current user who's accessing an ASP.NET application? A: On logging in, if the user is valid, use: FormsAuthentication.SetAuthCookie(login.UserName, false); rather than relying on Session to store user logged in state. You can then check if a user is logged in by: User.Identity.IsAuthenticated And get their username doing: User.Identity.Name A: You can just simply use User.Identity.Name A: You can use User.Identity.Name Please have a look at HttpContext.User Property
{ "language": "en", "url": "https://stackoverflow.com/questions/7513579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Appending inner contents of a container without losing binding in jQuery I'm trying to append the contents of a container from one to the other without losing any sort of binding and I'm scratching my head wondering why it's so difficult :D <div class="container"> <div class="field"> <label>Password</label> <input type="username" /> </div> </div> <div class="container"> <div class="field"> <label>Password</label> <input type="password" /> </div> </div> // This puts the actual container in, I need the inner contents of it $('.container').eq(0).append($('.container').eq(1)); // This loses any sort of binding that applies to what I'm moving $('.container').eq(0).append($('.container').eq(1).html()); // This screws up the HTML $('.container').eq(0).append($('*', $(container).eq(1))); Seems like such a simple and common task but I've got no idea how to get around this? My first answer would be to wrap the content in another container and move that instead. What d'ya think? Am I going mad or is this impossible? :D A: This should do what you want: $('.container').eq(0).append($('.container').eq(1).children()); JSBin Example - You'll notice the change function still works on the appended field.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Size in bytes of a structure containing unordered_map Need to find the exact size in bytes, occupied by a tree data structure that I have implemented. Node Structure is as follows struct Node { int word; int count; unordered_map<int, Node*> map; }node; What I have been doing is size(int)*2(for word and count) + map.bucket_count() * (sizeof(int) + sizeof(Node*)) and repeatedly do this for each node. Is this the correct way of doing this if i am neglecting the element overhead of storage in the unordered_map? Also, if I am correct map.bucket_count() gives the number of buckets that are currently allocated that is including the pre- allocated ones. Should I be using map.size() instead which will ignore the pre-allocated buckets? Or instead of all this, is it better to use tools like MemTrack to find the memory used? A: Or instead of all this, is it better to use tools like MemTrack to find the memory used? Yes. There's no telling from the outside how much memory an unordered_map or other complex, opaque object takes, and a good memory profiler might also show you how much overhead the memory allocator itself takes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to check whether a method is static in PHP? I need to know whether the method is declared as static given its name and the name of the class containing it. method_exists provides true for both static and non-static methods. A: use ReflectionMethod::isStatic A: Here's a little more clear way on how to use ReflectionMethod: $MethodChecker = new ReflectionMethod($ClassName,$MethodName); var_dump($MethodChecker->isStatic());
{ "language": "en", "url": "https://stackoverflow.com/questions/7513589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: flickering jquery animations Hey guys I'm in the process of making this website here: http://craigmarkdrums.com (bare in mind that it's still very early days, so no judging, yeh hehe) and take a look at the menu. In firefox it works fine, but in chrome and safari you can see a flickering in the right hand corner. i think what is happenning is it's the box changing size. they are all li's in a ul. here is my jquery: $(function() { $('#nav li').hover(function() { $(this).children().stop(true, true).fadeIn(); $(this).stop().animate({ width: '90px' }, 300, 'swing'); $(this).siblings().stop().animate({ width: '42px' }, 300, 'swing'); }, function() { $(this).children().stop(true, true).fadeOut(); $(this).stop().animate({ width: '50px' }, 200); $(this).siblings().stop().animate({ width: '50px' }, 200); }); }); any ideas what i'm doing wrong, or how i could improve this code? cheers Matt A: You're intuition is correct. To accomplish this effect using floats, you'd need to handle the animation yourself and resize all LIs in a single step, making sure the sum of their widths matched the containing element. Or try using absolute positioning and handling the offsets yourself. .. Or you could cheat and put the whole thing inside a container div whose background was the photo your using. That way any bleed through would be of the photo, not the white background. A: I'd suggest moving over to a flexible box layout for this (CSS3). You can just increase the size of the box you want and the others will shrink away by themselves. This page has a lot of examples of the flex-box layout (Take a look at the second example) Add this css to your menu panels: -moz-box-flex: 1; -webkit-box-flex: 1; box-flex: 1; And then set the width of the hovered element. For added fluidity, try adding some slight transition delays like this (I've separated the values for easy reading and understanding): -moz-transition-property: width; -moz-transition-duration: 0.2s; -moz-transition-easing: ease-in-out; -webkit-transition-property: width; -webkit-transition-duration: 0.2s; -webkit-transition-easing: ease-in-out; transition-property: width; transition-duration: 0.2s; transition-easing: ease-in-out;
{ "language": "en", "url": "https://stackoverflow.com/questions/7513594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++ vector push_back with class object I've been using this site for a while and so far never needed to ask a new question (found all answers I've needed until now). I need to push_back multiple objects into a vector but VS throws an error (This may be due to a corruption of the heap, which indicates a bug in PVSS00DataGate.exe or any of the DLLs it has loaded) that I cannot seem to work out for myself. Here is what I am trying to do, it works to push_back the first object into the vector but when I try to push_back a second object that is when the error occurs. class HWObject{} void DataLogger::WriteNewMessages() { unsigned int iBattery = 0; unsigned int iSignal = 0; TimeVar tTimeStamp; // I want to store all HWObjects in a temporary vector (loggerData) std::vector<HWObject> loggerData; CharString strElement; strElement.format( "batteryCondition.value" ); SendOneValuePVSS( (const char *)strElement, iBattery, tTimeStamp ); strElement.format( "signalStrength.value" ); SendOneValuePVSS( (const char *)strElement, iSignal, tTimeStamp ); } void DataLogger::SendOneValuePVSS(const char *szElementName, double dValue, TimeVar, &tValue) { HWObject obj; obj.setOrgTime(tValue); // Current time obj.setTimeOfPeriphFlag(); CharString address; address = strID; address += "."; address += szElementName; obj.setAddress(address); loggerData.reserve( loggerData.size() + 1 ); loggerData.push_back( obj ); obj.cutData(); } dataLogger is declared in class DataLogger { public: std::vector<HWObject> loggerData; ... } Here is the class HWObject, I didn't want to overwhelm you with code. public: /** Default constructor*/ HWObject(); /** Constructor, which sets the periphAddr and transformationType. * @param addressString address of the HW object * @param trans type of transformation */ HWObject(const char* addressString, TransformationType trans); /** Destructor. If the date pointer is not NULL, it is deleted. */ virtual ~HWObject(); /** Creates a new HWObject * This function returns an empty HWObject, no properties are duplicated or copied! * @classification public use, overload, call base */ virtual HWObject * clone() const; /** Reset all pvss2 relevant parts of the HWObject. when overloading this member * don't forget to call the basic function! * @classification public use, overload, call base */ virtual void clear(); /** Gets pointer to data * @return pointer to data */ const PVSSchar * getDataPtr() const { return dataPtr; } /** Gets the data buffer pointer * @return data buffer pointer */ PVSSchar * getData() { return dataPtr; } /** Cut the data buffer out of the HWObject. * This function is used to avoid the deletion * of the data buffer, when a new pointer is set using * setData() or the HWObject is deleted. * @return pointer to the data of the HWObject */ PVSSchar * cutData(); /** Get the data buffer lenght * @return length of the data buffer */ PVSSushort getDlen() const { return dataLen; } /** Set ptr to the data buffer, pointer is captured. * The actual data pointer in the HWObject is deleted, * if it is not NULL. To avoid the deletion use cutData() * in order to cut out the pointer. * @param ptr pointer to new data */ void setData(PVSSchar *ptr); /** Set the data length * @param len length to be set */ void setDlen(const PVSSushort len) { dataLen = len; } /** Get the periph address * @return periph address string */ const CharString & getAddress() const { return address; } /** Get the transformation type * @return type of transformation */ TransformationType getType() const { return transType; } /** Set the transformation type * @param typ type of transformation for setting */ void setType(const TransformationType typ) { transType = typ; } /** Get the subindex * @return subindex */ PVSSushort getSubindex() const { return subindex; } /** Set the subindex * @param sx subindex to be set */ void setSubindex( const PVSSushort sx) { subindex = sx; } /** Get the origin time * @return origin time */ const TimeVar& getOrgTime() const { return originTime; } /** Get the origin time * @return oriin time */ TimeVar& getOrgTime() { return originTime; } /** Set the origin time * @param tm origin time to be set */ void setOrgTime(const TimeVar& tm) { originTime = tm; } /** Get HWObject purpose * @return objSrcType */ ObjectSourceType getObjSrcType() const { return objSrcType; } /** Set HWObject purpose * @param tp objSrcType */ void setObjSrcType(const ObjectSourceType tp) { objSrcType = tp; } /** Get number of elements in data buffer * @return number of elements in data buffer */ PVSSushort getNumberOfElements() const { return number_of_elements; } /** Set number of elements in data buffer * @param var number of elements in data buffer */ void setNumberOfElements(const PVSSushort var) { number_of_elements = var; } /** Prints the basic HWObject information on stderr. * in case of overloading don't forget to call the base function! * @classification public use, overload, call base */ virtual void debugPrint() const; /** Prints th basic HWObject info in one CharString for internal debug DP. * in case of overloading call base function first, then append specific info * @classification public use, overload, call base */ virtual CharString getInfo() const; /** Set the periph address * @param adrStr pointer to address string */ virtual void setAddress(const char *adrStr); /** Set the additional data (flag, orig time, valid user byte,etc) * @param data aditional flags that be set * @param subix subindex, use subix 0 for setting values by default */ virtual void setAdditionalData(const RecVar &data, PVSSushort subix); /** Set the 'origin time comes from periph' flag */ void setTimeOfPeriphFlag() { setSbit(DRV_TIME_OF_PERIPH); } /** Check whether time comes from periph * @return PVSS_TRUE if the time is from perip */ PVSSboolean isTimeFromPeriph() const { // If isTimeOfPeriph is set, it must be valid return getSbit(DRV_TIME_OF_PERIPH); } /** Set the flag if you want to receive callback if event has answered the value change */ void setWantAnswerFlag() { setSbit(DRV_WANT_ANSWER); } /** Get the status of the 'want answer, flag */ PVSSboolean getWantAnswerFlag() const { // If isTimeOfPeriph is set, it must be valid return getSbit(DRV_WANT_ANSWER); } /** Set the user bit given by input parameter. * Status bits defined by the enum DriverBits * @param bitno bit number * @return PVSS_TRUE if bit was set */ PVSSboolean setSbit(PVSSushort bitno) { return (status.set(bitno) && status.set(bitno + (PVSSushort)DRV_VALID_INVALID - (PVSSushort)DRV_INVALID)); } /** Clear the user bit given by input parameter * @param bitno bit number * @return PVSS_TRUE if bit was cleared */ PVSSboolean clearSbit(PVSSushort bitno) { return (status.clear(bitno) && status.set(bitno + (PVSSushort)DRV_VALID_INVALID - (PVSSushort)DRV_INVALID)); } PVSSboolean isValidSbit(PVSSushort bitno) const { return status.get(bitno + (PVSSushort)DRV_VALID_INVALID - (PVSSushort)DRV_INVALID); } /** Check any bit * @param bitno bit number * @return status of the bit on bitno position */ PVSSboolean getSbit(PVSSushort bitno) const {return status.get(bitno);} /** Clear all status bits * return status of clear all */ PVSSboolean clearStatus() {return status.clearAll();} /** Get the status of this object * @return bit vector status */ const BitVec & getStatus() const {return status;} /** Set status of the bit vector * @param bv deference to bit vector to be set as status */ void setStatus(const BitVec &bv) {status = bv;} /** Set a user byte in the status. * @param userByteNo number of user byte range 0..3 * @param val value to set * @return PVSS_TRUE execution OK * PVSS_FALSE in case of error */ PVSSboolean setUserByte (PVSSushort userByteNo, PVSSuchar val); /** Reads a user byte from the status. * @param userByteNo number of user byte range 0..3 * @return the requested user byte */ PVSSuchar getUserByte (PVSSushort userByteNo) const; /** Check validity of user byte. * @param userByteNo number of user byte range 0..3 * @return PVSS_TRUE user byte is valid * PVSS_FALSE user byte is not valid */ PVSSboolean isValidUserByte(PVSSushort userByteNo) const; /** Format status bits into a string * @param str status bits converted to string */ void formatStatus (CharString & str) const ; // ------------------------------------------------------------------ // internal ones /** Read data from bin file * @param fp file handle */ virtual int inFromBinFile( FILE *fp ); /** Write data to bin file * @param fp file handle */ virtual int outToBinFile( FILE *fp ); /** Set data length * @param dlen data length */ void setDlenLlc (PVSSushort dlen) {dataLenLlc = dlen;} virtual void updateBufferLlc (HWObject * hwo, int offset1 = 0); virtual int compareLlc (HWObject * hwo, int offset1 = 0, int offset2 = 0, int len = -1); /** Get dataLenLlc * @return dataLenLlc */ PVSSushort getDlenLlc () const {return dataLenLlc;} /** Function to delete the data buffer; overload if special deletion must be done */ virtual void deleteData (); /** Set HW identifier * @param id hw identifier to be set */ void setHwoId(PVSSulong id) {hwoId = id;} /** Get HW identifier * @return hw identifier */ PVSSulong getHwoId() const {return hwoId;} protected: /// the dynamic data buffer PVSSchar* dataPtr; /// the data buffer len PVSSushort dataLen; /// the pvss2 periph address string CharString address; /// the start subix for the data buffer PVSSushort subindex; /// the datatype of the data in the buffer (i.e. transformationtype) TransformationType transType; /// the time of income, normally set by the constructor TimeVar originTime; /// the purpose of this HWObject ObjectSourceType objSrcType; /// the number of elements in the data buffer, used for arrays and records PVSSushort number_of_elements; // fuer array!!! /// the user bits of the original config BitVec status; private: PVSSushort dataLenLlc; PVSSulong hwoId; }; A: You're not showing the important parts. I'd guess that HWObject has dynamically allocated memory, and doesn't implement the rule of three (copy constructor, assignment operator and destructor). But it's only a guess. (Unless you're using special techniques like reference counting or smart pointers, copy must do a deep copy, and assignment should probably use the swap idiom.) Also, there's no point in reserving size() + 1 just before push_back.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to remove ¶ (pilcrow) sign from database records My aim is to remove ¶ (pilcrow) sign from the database records. There are thousands of records so I cannot do it manually. Is there any script available to remove ¶ (pilcrow) sign from MySQL database column? A: UPDATE table1 SET myfield = REPLACE(myfield,'¶','') WHERE myfield LIKE '%¶%' If you want to replace ¶ with an enter do: UPDATE table1 SET myfield = REPLACE(myfield,'¶','\n') WHERE myfield LIKE '%¶%' -- linefeed or UPDATE table1 SET myfield = REPLACE(myfield,'¶','\r\n') WHERE myfield LIKE '%¶%' -- cariage return+linefeed. http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace Make sure the collation and charset of the connection and the column in question are the same: DESCRIBE table1; -- copy the column charset and collation SET NAMES '<insert charset name>' COLLATE '<insert collation name>'; Now rerun the query. See: http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html A: Here's how I solved this (yes, major necro, but hey, I found this old thread, so someone else might also!): I edited the column directly using phpMyAdmin, and discovered that the database was displaying a pilcrow (¶), but it was storing some other representation in the background. No pilcrow displayed when editing the value, only a carriage return. I selected everything after the character that immediately preceded the pilcrow (the pilcrow was the last character in the column), used that invisible string in my query, and it worked. The working query looked like this: UPDATE myTable SET myCol=REPLACE(myCol,' ','') WHERE myKey>'myValue' Note that the query was one line of code, not two. The invisible carriage return only makes it look like two lines. I hope this helps someone! I investigated/tried lots of other suggestions, but none of them worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ASP.NET C# GridView - variable number of columns and image thumbnail Using GridView1.DataBind(); and AutoGenerateColumns="true" how can I find specific column and instead of URL display the thumbnail of image from that URL? GridView is generated as result of SQL Query that might return between 2 and 10 columns (one of which might be image URL.). For thumbnail I believe it's possible to use image.GetThumbnailImage(), but where to use it in such situation? Generating SQL query: if (CheckBoxUser.Checked) search_fields += "UserName"; if (CheckBoxDate.Checked) search_fields += ",EventDate"; ... if (CheckBoxImageUrl.Checked) search_fields += ",ImageUrl"; SqlConnection conn = new SqlConnection(connectionString); string select = "SELECT " + search_fields + " FROM TableName"; SqlDataAdapter DataCommand = new SqlDataAdapter(select, conn); DataCommand.Fill(ds); GridView1.DataSource = ds.Tables[0].DefaultView; GridView1.DataBind(); GridView1 is simply: <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True"> <HeaderStyle CssClass="header_grid" /> </asp:GridView> There are no columns declared manually since we don't know how many columns user wants to browse. But in case he marks "ImageUrl" column then instead of network file path (\somePc\path\file.jpg) he needs to see a thumbnail of this image inside GridView. A: If you know the type of your datasource and the name of the column which contains the image url, you could use the RowDataBound event like so: Note: This would only work if you are using no other templated columns. gridView1.RowDataBound += new GridViewRowEventHandler(gridView1_RowDataBound); ... void gridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { DataView dataSource = (DataView)gridView1.DataSource; DataColumn imageUrlColumn = dataSource.Table.Columns["ImageUrl"]; if (imageUrlColumn != null) { int index = imageUrlColumn.Ordinal; DataControlFieldCell cell = (DataControlFieldCell)e.Row.Controls[index]; string imageUrl = cell.Text; cell.Text = GenerateThumbnailUrl(imageUrl); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7513598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: DevExpress LookupEdit - setting the selected DataRow by code I am aware that there other questions like this, but their solutions do not work for me. I have the following code: lueSizes.Properties.DataSource = new BindingSource(PS.PaperSizes, null); lueSizes.Properties.Columns.Add(new LookUpColumnInfo("PaperName", "Größe")); lueSizes.Properties.DisplayMember = "PaperName"; lueSizes.Properties.ValueMember = "PaperName"; //PS is a regular System PrinterSettings object foreach (PaperSize size in PS.PaperSizes) //I confirmed with debugging that this actually happens correctly if (size.RawKind == binSettings.SizeRawKind) { lueSizes.EditValue = size; break; } Populating the LookupEdit with the DataSource works fine, the user can select the desired PaperSize from the dropdown, and lueSizes.GetSelectedDataRow() as PaperSize then returns a PaperSize object as expected. The problem I have is setting the EditValue, it simply does nothing. I have verified that at runtime, the DataSource contains all the PaperSize objects in PS.PaperSizes, including the one that is found in the foreach loop. But setting EditValue = size does not cause the selected data row to update accordingly. Other variations I have tried are: lueSizes.EditValue = size.PaperName; lueSizes.EditValue = lueSizes.Properties.GetKeyValueByDisplayText(size.PaperName); lueSizes.EditValue = lueSizes.Properties.GetKeyValueByDisplayValue(size.PaperName); lueSizes.EditValue = lueSizes.Properties.GetKeyValueByDisplayValue(size); lueSizes.EditValue = 0; None of these do anything, the selected datarow remains NULL and displays nothing to the user. What else can I try to set the selected DataRow by code? Edit: private void lueSizes_EditValueChanged(object sender, EventArgs e) { object o = lueSizes.EditValue; object p = lueSizes.GetSelectedDataRow(); PaperSize size = o as PaperSize; UpdateSize(size); } Object o is the item I have set earlier, the PaperSize size that Ive found in the loop, but object p is null. A: I think I have at least found a workaround: BindingSource bindingSource = new BindingSource(PS.PaperSizes, null); lueSizes.Properties.DataSource = bindingSource; lueSizes.Properties.Columns.Add(new LookUpColumnInfo("PaperName", "Größe")); lueSizes.Properties.DisplayMember = "PaperName"; foreach (PaperSize size in bindingSource) if (size.RawKind == BinSettings.SizeRawKind) { lueSizes.EditValue = size; break; } private void lueSizes_EditValueChanged(object sender, EventArgs e) { PaperSize size = lueSizes.EditValue as PaperSize; Update(size); } So first, I let the loop search in the BindingSource, which I have to define explicitely now, instead of the Printersettings object. Next, I may not set the DisplayValue property. Finally, I avoid looking up the DataRow and go for the edit value directly. Don't know what limitations I don't know what else that breaks, if anything, but for now it works. A: I know this is an old thread but I just got the same problem. The accepted answer is not the best practice since our goal is to get the selected object rather than the key value. The workaround is to call lookupEdit.Properties.ForceInitialize() right after EditValueChangedEvent got fired and GetSelectedDataRow() should work afterward. This solve the problem if the lookupEdit is not changed via mouse. A: You have to insure that the assigned value is exists in the lookupEdit's datasource, then try set the .Text property directly To pull the underlying assigned object PaperSize selectedPS = (PaperSize)lueSizes.Properties.GetDataSourceRowByDisplayValue(lueSizes.Text)
{ "language": "en", "url": "https://stackoverflow.com/questions/7513599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Read contents of structure via RFC in SAP Is it possible to read contents of SAP structures via RFCs from the outside? I know that RFC_READ_TABLE can be used to read table data, but is there something similar for structures? Or are structures only type definitions and don't contain any data? A: Yes, structures are only type definitions and don't contain any data. That's why you have a RFC to read from tables (transparent tables, cluster tables, etc) but not from structures or table types. Of course, a RFC can receive and return a structure as parameter, but again, that's only a structured type definition.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to get a unix timestamp in .NET C# Possible Duplicate: How to convert UNIX timestamp to DateTime and vice versa? I need simple one line piece of code how to do it. Can't find it on Internet. Thanks a lot
{ "language": "en", "url": "https://stackoverflow.com/questions/7513612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Auto generate random alphanumerical characters? Possible Duplicate: How to get random string with spaces and mixed case? How do I auto generate random alphanumercial characters Valid characters: Uppercase (A-Z), Lowercase (a-z), and digits (0-9) Size: 6 A: try this: string def = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; Random rnd = new Random(); StringBuilder ret = new StringBuilder(); for (int i = 0; i < 6; i++) ret.Append(def.Substring(rnd.Next(def.Length), 1)); return ret.ToString(); A: Something like this: var possibleChars = new List<char>(); for(var c='a';c<='z';c++) { possibleChars.Add(c); } for (var c = 'A'; c <= 'Z'; c++) { possibleChars.Add(c); } for (var c = '0'; c <= '9'; c++) { possibleChars.Add(c); } var r = new Random(); var randomChar = possibleChars[r.Next(possibleChars.Count)];
{ "language": "en", "url": "https://stackoverflow.com/questions/7513613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Have text in row overflow into right column I have a view with multiple columns that's showing documents with response documents underneath. I have a field on the parent document that is long that i'm putting in the first column. I've got another column that has a field specific to my response document. I want to have the first column be very small (width), so the responses aren't indented by much. The problem is that the parent document's field gets cut off. How can i allow the parent property column to overrun into the child property column? This would be similar to a categorised view, except that the 'category' is a parent document. I'd like a solution where i can get a child's property to overrun into a sub-child's property too, i.e. Document->Response->Response of response A: There are two ways to set up a parent/child relationship between the rows in a NotesView. First works with one or more types of documents where you take a flat view of documents, pick a column to group by, and set its type to Categorized. The Category row then shows up above the entries that have their field set to the category value. The second way is to have two types of documents using the built in document / response (and optionally response to response) relationship. In your form selection criteria, you make sure you select all the documents you want, and then tack on the descendants. In the view settings you need to select "Show response documents in a hierarchy". Then the parent documents will show above all their child documents. I think you're trying to use the second method, but it seems like something is missing. When it is set up, the parent row can show any number of columns, and usually the child row shows only one (see the design of the built-in discussion databases). To designate a column to be for responses, select the Show Responses Only option in the column properties. Otherwise the column will appear for just the parent document. To get what you want to do you should just need a couple of columns. The first one would be for the response documents and can be very narrow, but will automatically stretch across the whole window. The second would be for the parent document. Lastly you can select the "Extend last column to window width" option so the parent column fills the screen, or just stretch the parent's column wide enough to fit everything. You can even set the view properties to allow that column to show on multiple lines (up to 9) if it doesn't fit on one. Hopefully this fills in any gaps. If I missed something please let me know in the comments.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can i make press event with Javascript (jquery, dojo)? In the touch screen. * *if i keep press in the center of a screen for 20 seconds, i want to show alert("This is a secret window"); *If i pressed for 5 seconds each corners in the touch screen as: top/left top/right bottom/right bottom/left it will show alert("This is more secret window"); How do i do this in jQuery/Dojo or Mootools or in plain Javascript? Any one ever did this? I do not find any "pressed" event with time set. Note: there will be also many normal press inputs, so i want to do it in optimized way, for real-time actions except those two. A: You need two event handlers and a timer. // Put this lot in a closure so you don't pollute the global namespace. (function () { var timer; function onTouchStart() { timer = setTimeout(doTheThing, 20*1000); } function onTouchEnd() { clearTimeout(timer); } function doTheThing() { alert('foo') } })(); Bind onTouchStart/End to the appropriate events on the appropriate elements. See a working example altered to operate with a mouse button and for 5 seconds (because 20 is too much time to hang around for this test).
{ "language": "en", "url": "https://stackoverflow.com/questions/7513617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get all the pages validated, not just the current one, when submitting a form? First I created a form in Orbeon Forms with Form Builder. Next I made it a multi-page form as described in Create a wizard or multi-page form with Form Builder. The problem I'm facing is that when submitting the form, validation only occurs on the currently visible sections. When submitting, I would like all sections to be validated even though only one section may be visible. What would be the best way to achieve this? A: I would recommend you change the code of your "Next" button so it doesn't switch to the following page if there are errors on the current page. You can do so by adding an if "guard" on the <xforms:setvalue> inside the "Next" button, that reads: if="xxforms:instance('fr-error-summary-instance')/valid = 'true'" This will also make things easier for users: if you let them navigate to page 2 while there are errors on page 1, when they try to save while on page 2, you will somehow have to tell them that the error is on a previous page, and provide a way for them to navigate to that page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Twisted under windows Twisted located at C:\Python26\Lib\site-packages\Twisted-11.0.0-py2.6-win32.egg\twisted but C:\projects\webmorda>twistd -n morda_server Traceback (most recent call last): File "C:\Python26\Scripts\twistd.py", line 4, in <module> import pkg_resources File "C:\Python27\lib\site-packages\pkg_resources.py", line 2671, in <module> working_set.require(__requires__) File "C:\Python27\lib\site-packages\pkg_resources.py", line 654, in require needed = self.resolve(parse_requirements(requirements)) File "C:\Python27\lib\site-packages\pkg_resources.py", line 552, in resolve raise DistributionNotFound(req) pkg_resources.DistributionNotFound: twisted==11.0.0 what's wrong? A: It looks like you have installed Twisted in a Python 2.6 environment but are using Python 2.7 to run it. I think the following command should work: C:\Python26\python.exe C:\Python26\Scripts\twistd.py -n morda_server (It looks like the twistd.py script is being run by the python.exe binary associated with the .py file extension - which in your case appears to be Python 2.7. Alternatively you have a PYTHONPATH environment variable set up to point to the Python 2.7 site-packages directory.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7513626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Chrome Issue Google Map Api Jquery Is not Loading I have implemented Simple Google Map Direction Api Javascript in my webpage. When my Destinaion loaded from database, it will draw a map directly from this google api. But here in google chrome map cant be loaded, it is showing me some error kind of Resource interpreted as image but transferred with MIME type text/HTMl. Can someone please bring me out from this issue. Thanks in advance. A: It was another jQuery disturbing. now i got solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mathematica: Thread::tdlen: Objects of unequal length in {Null} {} cannot be combined. >> I have aproblem: Thread::tdlen: Objects of unequal length in {Null} {} cannot be combined. >> It seems to occur in the while test which makes no sense at all since I am onlu comparing numbers...? The program is a program to solve the 0-1 knapsack dynamic programming problem though I use loops, not recursion. I have put some printouts and i can only think that the problem is in the while loop and it doesnt make sense. (* 0-1 Knapsack problem item = {value, weight} Constraint is maxweight. Objective is to max value. Input on the form: Matrix[{value,weight}, {value,weight}, ... ] *) lookup[x_, y_, m_] := m[[x, y]]; generateTable[items_, maxweight_] := { nbrofitems = Dimensions[items][[1]]; keep = values = Table[0, {j, 0, nbrofitems}, {i, 1, maxweight}]; For[j = 2, j <= nbrofitems + 1, j++, itemweight = items[[j - 1, 2]]; itemvalue = items[[j - 1, 1]]; For[i = 1, i <= maxweight, i++, { x = lookup[j - 1, i, values]; diff = i - itemweight; If[diff > 0, y = lookup[j - 1, diff, values], y = 0]; If[itemweight <= i , {If[x < itemvalue + y, {values[[j, i]] = itemvalue + y; keep[[j, i]] = 1;}, {values[[j, i]] = x; keep[[j, i]] = 0;}] }, y(*y eller x?*)] } ] ]; {values, keep} } pickItems[keep_, items_, maxweight_] := { (*w=remaining weight in knapsack*) (*i=current item*) w = maxweight; knapsack = {}; nbrofitems = Dimensions[items][[1]]; i = nbrofitems + 1; x = 0; While[i > 0 && x < 10, { Print["lopp round starting"]; x++; Print["i"]; Print[i]; Print["w"]; Print[w]; Print["keep[i,w]"]; Print[keep[[i, w]]]; If[keep[[i, w]] == 1, {Append[knapsack, i]; Print["tjolahej"]; w -= items[[i - 1, 2]]; i -= 1; Print["tjolahopp"]; }, i -= 1; ]; Print[i]; Print["loop round done"]; } knapsack; ] } Clear[keep, v, a, b, c] maxweight = 5; nbrofitems = 3; a = {5, 3}; b = {3, 2}; c = {4, 1}; items = {a, b, c}; MatrixForm[items] results = generateTable[items, 5]; keep = results[[1]][[2]]; Print["keep:"]; MatrixForm[keep] Print["------"]; results2 = pickItems[keep, items, 5]; MatrixForm[results2] A: This is not really an answer to the specific question being asked, but some hints on general situations when this error occurs. The short answer is that this is a sign of passing lists of unequal lengths to some Listable function, user-defined or built-in. Many of Mathematica's built-in functions are Listable(have Listable attribute). This basically means that, given lists in place of some or all arguments, Mathematica automatically threads the function over them. What really happens is that Thread is called internally (or, at least, so it appears). This can be illustrated by In[15]:= ClearAll[f]; SetAttributes[f,Listable]; f[{1,2},{3,4,5}] During evaluation of In[15]:= Thread::tdlen: Objects of unequal length in f[{1,2},{3,4,5}] cannot be combined. >> Out[17]= f[{1,2},{3,4,5}] You can get the same behavior by using Thread explicitly: In[19]:= ClearAll[ff]; Thread[ff[{1,2},{3,4,5}]] During evaluation of In[19]:= Thread::tdlen: Objects of unequal length in ff[{1,2},{3,4,5}] cannot be combined. >> Out[20]= ff[{1,2},{3,4,5}] In case of Listable functions, this is a bit more hidden though. Some typical examples would include things like {1, 2} + {3, 4, 5} or {1, 2}^{3, 4, 5} etc. I discussed this issue in a bit more detail here. A: Try this version: pickItems[keep_, items_, maxweight_] := Module[{}, {(*w=remaining weight in knapsack*)(*i=current item*)w = maxweight; knapsack = {}; nbrofitems = Dimensions[items][[1]]; i = nbrofitems + 1; x = 0; While[i > 0 && x < 10, { Print["lopp round starting"]; x++; Print["i"]; Print[i]; Print["w"]; Print[w]; Print["keep[i,w]"]; Print[keep[[i, w]]]; If[keep[[i, w]] == 1, { Append[knapsack, i]; Print["tjolahej"]; w -= items[[i - 1, 2]]; i -= 1; Print["tjolahopp"]; }, i -= 1; ]; Print[i]; Print["loop round done"] }; knapsack ] } ] no errors now, but I do not know what it does really :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7513628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Linq to SQL atomic set of operations I would like to ensure that var a has not changed between retrieving it and performing the update on var b. var a = from item in.... if (a > 100) { var b = from item in... b.something = 100; db.SubmitChanges() } How would I go about doing this? Do I just wrap the thing in a TransactionScope? A: Linq 2 sql is designed for optimistic concurrency out of the box (what you want is pessimistic) http://msdn.microsoft.com/en-us/library/bb399373.aspx Due to possible deadlocks etc. with locking, I think you better stick to optimistic and handle the conflict resolution. Otherwise, have a look here: LINQ to SQL and Concurrency Issues
{ "language": "en", "url": "https://stackoverflow.com/questions/7513630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Custom Authentication with WCF and NHibernate I'm attaching an NHibernate session to the operation context in my WCF webservice which allows me to access the session object during the processing of each operation (the service instance context is per call). The service implements custom authentication using UserNamePasswordValidator but unfortunately prior to the request being authenticated the OperationContext.Current is always null (presumably by design). My question is how should I set up the NHibernate session on the Validate(string userName, string password) method if I can't get the session via the OperationContext.Current? How are other peeps doing this? Thanks in advance. A: Use separate session in validator = create new one through session factory. There is no shared storage between security processing and operation processing by design. They should even run in different threads. You should follow this design and don't share session and loaded objects between security processing and operation processing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: form expand/reduce handling with jquery I have a comment form with a textarea, input text and input radio. first, you'll see the textarea. if you click in it, the whole form expand. When you click outside the form and the fields have no values, the form should reduce to the textarea again. This works as well. The problem is, when you switch from field to field inside the form, the form reduces and expand, and again and again. The if ($this.not(":focus")) will not help out. Any ideas? HTML <div id="commentBox"> <form action="..."> <label for="comment">Write a comment...</label> <textarea id="comment"></textarea> <div class="expandBox" style="display: none"> <label for="title">Title</label> <input type="text" id="title" /> <br /> <label for="email">E-Mail *</label> <input type="text" id="email" /> <br /> <label for="name">Newsletter</label> <input type="radio" id="yes" name="newsletter" /><label for="yes">ja</label> <input type="radio" id="no" name="newsletter" /><label for="no">nein</label> <br /> <label for="name">Name *</label> <input type="text" id="name" /> <br /> <input type="submit" value="senden" /> </div> </form> </div> jQuery snippet (in domready off course) $("#commentBox").find("input,textarea").each(function() { var $this = $(this); var $expandBox = $this.parents("#commentBox").find(".expandBox"); $this.focus(function() { $expandBox.slideDown(250); }); $this.blur(function() { if ($this.val() === "" && $this.not(":focus")) { $expandBox.slideUp(250); } }); }); A: The problem is that when you switch between inputs/textareas, focus() is triggered on the new focused element, and blur() on the last one. $expandBox is thus asked to slideUp() AND slideDown(). To fix this problem, you have to tell these animations to stop previous animations when they're called. That way, slideUp() will be called, and immediately stopped by slideDown(). Use stop() for that. $("#commentBox").find("input,textarea").each(function() { var $this = $(this); var $expandBox = $this.parents("#commentBox").find(".expandBox"); $this.focus(function() { $expandBox.stop().slideDown(250); }); $this.blur(function() { if ($this.val() === "" && $this.not(":focus")) { $expandBox.stop().slideUp(250); } }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7513632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why i can not use Sensor.TYPE_ORIENTATION_VECTOR. Type is not recognised The problem is, that this sensors should be available: * *int TYPE_ACCELEROMETER *int TYPE_ALL *int TYPE_GRAVITY *int TYPE_GYROSCOPE *int TYPE_LIGHT *int *TYPE_LINEAR_ACCELERATION* *int TYPE_MAGNETIC_FIELD *int TYPE_ORIENTATION *int TYPE_PRESSURE *int TYPE_PROXIMITY *int TYPE_ROTATION_VECTOR *int TYPE_TEMPERATURE Why are these three disabled? They are not recognised..."TYPE_ROTATION_VECTOR cannot be resolved or is not a field" Only these are recognised: * *int TYPE_ACCELEROMETER *int TYPE_ALL *int TYPE_GYROSCOPE *int TYPE_LIGHT *int TYPE_MAGNETIC_FIELD *int TYPE_ORIENTATION *int TYPE_PRESSURE *int TYPE_PROXIMITY *int TYPE_TEMPERATURE code is: mRotationVectorSensor = mSensorManager.getDefaultSensor( Sensor.TYPE_ROTATION_VECTOR); Project build target is 2.2, API 8. Why i can not use TYPE_ROTATION_VECTOR and other types? Tnx for andswer! A: You are trying to access a sensor that is available only from API version 9 (you are using API version 8). http://developer.android.com/reference/android/hardware/Sensor.html#TYPE_ROTATION_VECTOR Check the "Since API level ..." at the right of each method/field A: in Android 2.2, Gravity and linear Acceleration Vectors are not available... Only for versions 2.3 (GingerBread) and newer... Greetings Ralf
{ "language": "en", "url": "https://stackoverflow.com/questions/7513638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TFS API - Why is the AllowedFieldValues for 'Reasons' empty? I'm trying to retrieve the list of valid Reasons for a WorkItem (MS Agile 5 template), which works correctly for a new work item. However for editing existing work items, the AllowedValues is always empty, whatever the state. WorkItem item = GetItem(...) item.Fields["Reason"].AllowedValues.ToList() // always empty (ToList is my own extension method). The problem is, the Visual Studio UI correctly updates the Reasons list when you change the state in the drop down list. The Reason field also has IsLimitedToAllowedValues=false but when you enter an arbitary value it complains that it's not a valid list item. A: We also use MS Agile 5 & the following worked fine on an existing work items named myWorkItem (I tried with User Story & Task): FieldDefinitionCollection fdc = myWorkItem.Type.FieldDefinitions; Console.WriteLine(myWorkItem.Type.Name); foreach (FieldDefinition fd in fdc) { if(fd.Name == "Reason") { AllowedValuesCollection avc = fd.AllowedValues; foreach (string allowedValue in avc) { Console.WriteLine(allowedValue.ToString()); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7513643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how do i expose function from anonymous self invoking function? (function(){ var a = function () { alert("hey now!! "); }; return {"hi":function(){return a;}}; })(); hi(); This code doesn' t work. How do i expose a function?? A: The self invoking function returns an object with the property hi, this object is not added to the global scope so that you can use the property directly. Put the result of the function in a variable: var o = (function(){ var a = function (){ alert("hey now!! "); }; return {"hi":function(){return a;}}; })(); Using the property to call the function will only return the function contained in the variable a, so you have to call the return value from the function to call the function that contains the alert: o.hi()(); Demo: http://jsfiddle.net/Guffa/9twaH/ A: There are two basic ways: var MyNameSpace = (function(){ function a (){ alert("hey now!! "); }; return {a: a}; })(); MyNameSpace.a(); or (function(){ function a (){ alert("hey now!! "); }; MyNameSpace = {a: a}; })(); MyNameSpace.a(); I prefer the 2nd way since it seems cleaner It is called the "revealing module pattern" btw, which you can read up on to understand it better :) https://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript A: var obj = (function(){ var a= function (){ alert("hey now!! "); }; return {"hi":function(){return a;}}; })(); obj.hi() A: You have to assign the return value of the anonymous function to a variable in the current scope: var f = (function() { var a = function() { alert("hey now!! "); }; return { "hi": function() { return a; } }; })(); f.hi()(); A: It? (function(){ var a = function () { alert("hey now!! "); }; return {"hi":function(){return a;}}; })().hi()(); A: I suppose in order to expose the function, instead of its code, the syntax should be var obj2 = (function(){ var a= function (){ alert("hey now!! "); }; return {"hi":a}; })(); alert(obj2.hi()); A: Or you could wrap your 'hi' function in an IIFE like so... var myFunction = (function(){ var a = function () { alert("hey now!! "); }; return { "hi": (function(){ return a; }()) }; })(); myFunction.hi();
{ "language": "en", "url": "https://stackoverflow.com/questions/7513645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: iOS Searching an array for a string and adding it if missing I'm trying to go through a mutable array searching for a given string. If the string does not exist in the array, I want to add it ONCE. The issue I'm having right now is that the string gets added a number of times. Here's the code I'm using NSMutableArray *array; array=[self.storedData getNames]; if([array count]!=0){ for (int i=0; i<[array count]; i++) { MyUser *user=[array objectAtIndex:i]; if(![user.firstName isEqualToString:self.nameField.text]){ [array addObject: object constructor method goes here]; [self.storedData setNames:array]; } } } else{ [array addObject:object constructor method]; [self.storedData setNames:array]; } Any help would be greatly appreciated. A: You're adding new string on each loop iteration when enumerating array which is clearly wrong. When enumerating array just set a flag indicating whether string was found and after the loop ad your string to array if it was not: NSMutableArray *array = [self.storedData getNames]; BOOL found = NO; for (MyUser *user in array){ if(![user.firstName isEqualToString:self.nameField.text]){ found = YES; break; } } if (!found){ [array addObject: object constructor method goes here]; [self.storedData setNames:array]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7513646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: lighttpd: 404 page does not return 404 status I'm using a lighttpd 404 error handler, with a static 404 page. The entire conf file looks like this: server.document-root = "/home/www/local/www/mysite/html" url.rewrite = ( "^(.*)/($|\?.*)" => "$1/index.html", "^(.*)/([^.?]+)($|\?.*)$" => "$1/$2.html" ) server.error-handler-404 = "/404.html" $HTTP["scheme"] == "http" { url.redirect = ( "^/blog.html$" => "/blog/", // various individual redirects ) } $HTTP["scheme"] == "https" { $HTTP["url"] !~ "^/blog/admin/" { url.redirect = ( "^/(.*)" => "http://www.mysite.com/$1" ) } } However, when I go to an address that should 404, I do correctly see our 404 page, but the status code is 200. The lighttpd docs say that you should get a 404 status code if using a static page. I think we're using a static page, but could something about the way we're redirecting mean that we're actually not? Sorry for the newbie question. A: Fixed this by using server.errorfile-prefix instead - think it is simply a bug in server.error-handler-404. Seems to be a known bug in some versions of lighttpd. I was actually using a later version than 1.4.17, but still seeing the same problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: subclass of a serializable class needs to be serializable? If I have 3 classes say A and It Implements java.io.Serializable . And I have B ,which is subclass of A. If I want to serialize B , B also implements java.io.Serializable. If not Why HttpServlet implements java.io.Serializable as GenericServlet already implements it. Please clarify me . Thanks in Advance Raj A: From the Java docs: All subtypes of a serializable class are themselves serializable. A: Technically, not necessary. Note that Serializable is just a marker interface. So, by explicitly implementing it, you're basically saying (marking) that you are aware of the Serializable restrictions/contract and designed accordingly. A: As far as I can see, it doesn't need to implement java.io.Serializable. Maybe it's simply being done for the sake of clarity. A: As pointed out by other folks, it does not have any technical implications (HttpServlet implementing java.io.Serializable). Its more from the clarity point of view which allows a developer to quickly view if this class is serializable or not. Its there all around JDK. Checkout the java.lang.Number and its subclasses. Its similar to best practices of importing packages wherein we should avoid wildcards (java.io.*). Technically, there is nothing wrong is using wildcard (unless there are conflicting classnames) but importing classes with fully qualified classnames is cleaner,
{ "language": "en", "url": "https://stackoverflow.com/questions/7513651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Div not auto expanding due to dynamically loaded content I have a bit of an issue... Ive made a div, and normally, it expands to suit the height of its contents fine, however... Now i have a problem. My content is being returned from a Sql statment, and its not expanding to suit its height, a working non dynamic version is #commentblock { min-height:50px; width:90%; margin:20px auto; padding:10px; border:1px solid #999; } My code is as follows (its in a for loop making a new div for each instance) // Now lets query to grab the responses to this fault $querytwo = "SELECT * FROM comments WHERE faultid=".$fid; // execute query $resulttwo = mysql_query($querytwo) or die ("Error in query: $querytwo. ".mysql_error()); // see if any rows were returned if (mysql_num_rows($resulttwo) > 0) { // print them one after another while($row = mysql_fetch_row($resulttwo)) { // lets make this render then echo "<div id='commentblock'>"; echo "<div class='loggedby'>Logged By : <span>".$row[4]."</span><p class='contactno'>Entered : <span>".$row[3]."</span></p></div>"; echo "<div class='info'><span>".$row[2]."</span></div>"; echo "</div>"; } } // free result set memory mysql_free_result($resulttwo); // close connection mysql_close($connection); Thanks in advance :) A: Got it, the content was in a span which was inheriting a floating attribute. Removed the float - now its all fine :) A: It might not be to do with dynamic code, but invalid HTML. You are using: id='commentblock' ... in a loop, which create multiple, identical IDs on the same page, which is not valid. You should change to: class='commentblock' and reference you CSS as: .commentblock ... instead of: #commentblock
{ "language": "en", "url": "https://stackoverflow.com/questions/7513657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Programmatically Suppressing Graphs in Crystal Reports I'm using Crystal Reports to create some graphs. I'm linking students in a report showing a graph of results for each subject Student Ian Smoth UREL5 U TU Course UREL5 5 9 23 33 23 6 1 LREL5 10 13 23 27 20 7 Dependent on whether the the course is an Upper or Lower course I want to give them a different graph, as the axis change. You can see that LREL5 doesn't have the same number of fields. Is there a way in Crystal Reports to suppress the display of a graph if certain criteria is met? I'm looking to do the following in the 'Formula Workshop': if {All_Students_txt.Qual Level} = "U" then suppress LowerGraph else suppress UpperGraph Alternatively I could mess about with dynamically updating the graph on each record A: You might want to create a separate section for each graph (right click the section and choose Insert Section Below), then suppress the appropriate section. This approach gives you more flexibility. The suppression formula for the 'upper' section would be: {All_Students_txt.Qual Level} <> "U" The suppression formula for the 'lower' section would be: {All_Students_txt.Qual Level} = "U"
{ "language": "en", "url": "https://stackoverflow.com/questions/7513659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problems with UDP Received and Sent UDP Packages? I am trying to write a simple program about UDP Connections to learn about them. I have implemented some basic things but when I try to send and get back what I sent but I face some problems like, When I do this ; send a string "asd" to server I get back asdxxxxxxxxxx and when I try to print What I get in the server I get [B@5f186fab How can I solve this problem ? To be more clear I am sending you a few lines of code , In client; Scanner in = new Scanner(System.in); String result = in.nextLine(); // send request byte[] buf = new byte[1000]; String read = result; InetAddress address = InetAddress.getByName("localhost"); DatagramPacket packet = new DatagramPacket(result.getBytes(), result.getBytes().length, address, 4445); socket.send(packet); // get response packet = new DatagramPacket(buf, buf.length); socket.receive(packet); // display response String received = new String(packet.getData(), 0, packet.getLength()); System.out.println("Quote of the Moment: " + received); In server ; byte[] buf = new byte[1000]; DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); byte[] received = packet.getData(); System.out.println(received.toString()); // figure out response // send the response to the client at "address" and "port" InetAddress address = packet.getAddress(); int port = packet.getPort(); packet = new DatagramPacket(received, received.length, address, port); socket.send(packet); Thank you all EDIT 1 I think I have problems with my buffer but I dont know how to solve . A: You can use System.out.println(Arrays.toString(received)); but what you probably want is System.out.println(new String(received, o, lengthRead, "UTF-8")); A: Have you fixed this? Otherwise, what I've found is that if you declare a receiving byte[] buf with a capacity that's greater than the length string you're actually receiving, you'll end up with the rest of the buffer full of unwanted bytes. Eg. if you declare byte[] received = new byte[1000]; but only receive a string of 4 bytes, you'll end up with 996 unwanted bytes. One quick way around this is to do something like byte[] received = packet.getData(); System.out.println(received.toString().trim()); trim() did the trick for me. Hope that helps you!
{ "language": "en", "url": "https://stackoverflow.com/questions/7513661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL Server Alert using WMI Event ERROR I want to execute a job when ever a file is dropped into a particular folder. I found some articles that showed me how I can do it on SQL Server. I created a alert type: WMI Event Alert For the name space its the SQL instance which comes automatically as \\.\root\Microsoft\SqlServer\ServerEvents\MSSQLSERVER On the Query section - I wrote the below query , SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance ISA 'CIM_DataFile' AND TargetInstance.Name = ‘c:\\TestFolder\’ ` The error message returned is: Cannot create new alert. ADDITIONAL INFORMATION: Create failed for Alert 'AlertTest'. (Microsoft.SqlServer.Smo) For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.50.2425.0+((KJ_PCU_Main).110406-2044+)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Create+Alert&LinkId=20476 An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo) SQLServerAgent Error: WMI error: 0x80041058 The @wmi_query could not be executed in the @wmi_namespace provided. Verify that an event class selected in the query exists in the namespace and that the query has the correct syntax. (Microsoft SQL Server, Error: 22022) For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.50.2425&EvtSrc=MSSQLServer&EvtID=22022&LinkId=20476 Please may you advise if my Query is correct and if there is anything else I need to check? Thanks a lot in advance. A: You are using the wrong namespace, the CIM_DataFile WMI class is part of the \root\CIMV2 namespace and not of \root\Microsoft\SqlServer\ServerEvents\MSSQLSERVER A: In this case, the answer from RRUZ is correct. However there are other possible causes of this error message: The @wmi_query could not be executed in the @wmi_namespace provided. One possible reason is the account that runs the Windows service "Windows Management Instrumentation" is disabled as a SQL login. (If you are running SQL 2012+, look for the login 'NT SERVICE\winmgmt'). (Source: Blog by 'rahmanagoro' ) Edit 2020-05-29: I've made a more comprehensive answer to this question on the DBA forum. Another possible fix is to restart the "Windows Management Instrumentation" service. No idea what leads to the problem, but restarting the service fixes it. I've seen this twice, both times on Windows Server 2008 R2 Standard Edition x64. Edit 2020-05-29: I've made a more comprehensive answer to this question on the DBA forum.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to get values for same column name from two different tables in SQL How to get values for same column name from two different tables in SQL? column name is emp_id loacated in these two tables: company,employee. A: If you want data in seperate columns from two tables then try : SELECT c.emp_id, emp.emp_id FROM company c INNER JOIN employee emp on c.company_id = emp.company_id If you want to merge both columns data then use this : SELECT emp_id FROM company UNION SELECT emp_id FROM employee A: Use this to get the results: company.emp_id, employee.emp_id A: Just put the name of the table before the name of the colomn with a "." between, like: SELECT company.emp_id, employe.emp_id A: You can do what you are asking, something like the example below, but if you provide a sample query, it would help... select emp.emp_id,company.emp_id from company join employee emp on emp.company_id=company_company_id
{ "language": "en", "url": "https://stackoverflow.com/questions/7513669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Eclipse-Marketplace Error Message in Linux machine Eclipse Indigo : once i go into eclipse market place option i got this message : Unexpected exception java.lang.reflect.InvocationTargetException this is in mu linux machine can i know why am i getting this message. A: I had the same issue happen to me... I couldn't get the Indigo Marketplace Client to install, so I had to switch to the Helios repository and install that one. It installed, but running it gave me the same error message you got. I had to switch back to Indigo and install (upgrade) to that one, and then everything worked. Click Help->Install New Software->Add, and add the location: http://download.eclipse.org/mpc/indigo/ A: I have got the same problem with window 7 64 bit. I fixed it by changing the Proxy of windows which eclipse uses by through control panel.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Any ideas why my blueimp jQuery file upload script is not working? I'm using blueimp JQuery file upload script to fancy the uploading of files. You can download it here: https://github.com/blueimp/jQuery-File-Upload/zipball/master (ZIP). Here is a snippet of the JavaScript code: $(function () { 'use strict'; // Initialize the jQuery File Upload widget: $('#fileupload').fileupload({ // Dirs url: 'accesspoint/upload.php', uploadDir: 'accesspoint/files/', thumbnailsDir: '', // Options autoUpload: 1, maxNumberOfFiles: 1, limitConcurrentUploads: 1, maxFileSize: 1000000, }); // Load existing files: $.getJSON($('#fileupload form').prop('action'), function (files) { var fu = $('#fileupload').data('fileupload'); fu._adjustMaxNumberOfFiles(-files.length); fu._renderDownload(files) .appendTo($('#fileupload .files')) .fadeIn(function () { // Fix for IE7 and lower: $(this).show(); }); }); // Open download dialogs via iframes, // to prevent aborting current uploads: $('#fileupload .files a:not([target^=_blank])').live('click', function (e) { e.preventDefault(); $('<iframe style="display:none;"></iframe>') .prop('src', this.href) .appendTo('body'); }); }); Now take a look at http://www.mcemperor.nl/test/appstest/blueimpjqueryfileupload/example/. We can upload a file, and it works. Now if I upload a file which is larger than the maximum file size defined in the JavaScript snippet above, then you'll see something like this. Perfect, works as expected. (Note that I have set the maximum upload size to 1000000 bytes, so if you upload a file of 1 MB, it states the file is too big.) But... Now when I paste the same script (with some small modifications) as a module into a framework of some kind, the script won't work properly; I get this: As you can see, The 'delete entry' icon is smaller (it's supposed to be square) and nothing happens when I click on it. I do not have any clue what can be the problem. Does anyone have ideas? * *Can using this script inside another <form> be the problem? *Can multiple elements with the same id be the problem? *Can collisions between javascripts (e.g. redefining functions or objects) be the problem? A: I am not sure how to fix the scripts, but maybe a workaround would be to locate the element using FireBug and patch it with a css entry or a jquery function. Also, you might take a look at jquery.fileupload-ui.css which is the css file responsible for overriding jqueryUI elements for the control. I do know that the buttons are styleable independently. Again, I am not for certain, but there may be a class added via script to change the icon on the delete button.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mocking out nHibernate QueryOver with Moq The following line fails with a null reference, when testing: var awards = _session.QueryOver<Body>().Where(x => x.BusinessId == (int)business).List(); My test is like so: var mockQueryOver = new Mock<IQueryOver<Body, Body>>(); mockQueryOver.Setup(q => q.List()).Returns(new List<Body> {_awardingBody}); _mockSession.Setup(c => c.QueryOver<Body>()).Returns((mockQueryOver.Object)); _mockCommandRunner = new Mock<ICommandRunner>(); _generator = new CertificateGeneratorForOpenSSLCommandLine(_mockSession.Object, _mockCommandRunner.Object, _mockDirectory.Object, _mockFile.Object, _mockConfig.Object); To be honest I'm flailing around in the dark here - I'm relatively new to nHibernate and Moq, so I'm not very sure what to google to get the right information. A: This is not a good idea. You should not mock the types you don't own. Instead you should introduce a Repository, base its interface on domain/business language and implement it using NHibernate. Implementation can use ICriteria, HQL, QueryOver, Linq etc. The point is that this decision will be encapsulated and hidden from the code that consumes repository. You can write an integration test that will test combination of your interface + Real ORM + Real or Fake database. Please take a look at this and this answers about testing repositories and data access. Testing the code that uses Repository is also super easy because you can mock Repository interface. What are the advantages of this approach other than testability? They are somewhat related to each other: * *Separation of Concerns. Data access issues solved in the data access layer (repository implementation). *Loose Coupling. The rest of the system is not coupled to the data-access-tool-of-the-day. You have potential for switching repository implementation from NHibernate to raw sql, azure, web service. Even if you never need to switch, the layering is enforced better if you design 'as if' you need to switch. *Readability. Domain objects, including repository interface definition are based on business/domain language. A: I've used several approaches in the past. One way is, as others have suggested, to create a Repository class that you can mock/stub that encapsulates your queries. One problem with this is that it's not very flexible and you wind up having a stored procedure like solution, except this one is in code rather than the database. A recent solution I have tried is creating a QueryOver stub that I provide when I stub the QueryOver method. I can then provide a list of items that should be returned. Keep in mind if you using this approach you should not only write unit tests, but an integration test, which will test whether or not the query actually works. public class QueryOverStub<TRoot, TSub> : IQueryOver<TRoot, TSub> { private readonly TRoot _singleOrDefault; private readonly IList<TRoot> _list; private readonly ICriteria _root = MockRepository.GenerateStub<ICriteria>(); public QueryOverStub(IList<TRoot> list) { _list = list; } public QueryOverStub(TRoot singleOrDefault) { _singleOrDefault = singleOrDefault; } public ICriteria UnderlyingCriteria { get { return _root; } } public ICriteria RootCriteria { get { return _root; } } public IList<TRoot> List() { return _list; } public IList<U> List<U>() { throw new NotImplementedException(); } public IQueryOver<TRoot, TRoot> ToRowCountQuery() { throw new NotImplementedException(); } public IQueryOver<TRoot, TRoot> ToRowCountInt64Query() { throw new NotImplementedException(); } public int RowCount() { return _list.Count; } public long RowCountInt64() { throw new NotImplementedException(); } public TRoot SingleOrDefault() { return _singleOrDefault; } public U SingleOrDefault<U>() { throw new NotImplementedException(); } public IEnumerable<TRoot> Future() { return _list; } public IEnumerable<U> Future<U>() { throw new NotImplementedException(); } public IFutureValue<TRoot> FutureValue() { throw new NotImplementedException(); } public IFutureValue<U> FutureValue<U>() { throw new NotImplementedException(); } public IQueryOver<TRoot, TRoot> Clone() { throw new NotImplementedException(); } public IQueryOver<TRoot> ClearOrders() { return this; } public IQueryOver<TRoot> Skip(int firstResult) { return this; } public IQueryOver<TRoot> Take(int maxResults) { return this; } public IQueryOver<TRoot> Cacheable() { return this; } public IQueryOver<TRoot> CacheMode(CacheMode cacheMode) { return this; } public IQueryOver<TRoot> CacheRegion(string cacheRegion) { return this; } public IQueryOver<TRoot, TSub> And(Expression<Func<TSub, bool>> expression) { return this; } public IQueryOver<TRoot, TSub> And(Expression<Func<bool>> expression) { return this; } public IQueryOver<TRoot, TSub> And(ICriterion expression) { return this; } public IQueryOver<TRoot, TSub> AndNot(Expression<Func<TSub, bool>> expression) { return this; } public IQueryOver<TRoot, TSub> AndNot(Expression<Func<bool>> expression) { return this; } public IQueryOverRestrictionBuilder<TRoot, TSub> AndRestrictionOn(Expression<Func<TSub, object>> expression) { throw new NotImplementedException(); } public IQueryOverRestrictionBuilder<TRoot, TSub> AndRestrictionOn(Expression<Func<object>> expression) { throw new NotImplementedException(); } public IQueryOver<TRoot, TSub> Where(Expression<Func<TSub, bool>> expression) { return this; } public IQueryOver<TRoot, TSub> Where(Expression<Func<bool>> expression) { return this; } public IQueryOver<TRoot, TSub> Where(ICriterion expression) { return this; } public IQueryOver<TRoot, TSub> WhereNot(Expression<Func<TSub, bool>> expression) { return this; } public IQueryOver<TRoot, TSub> WhereNot(Expression<Func<bool>> expression) { return this; } public IQueryOverRestrictionBuilder<TRoot, TSub> WhereRestrictionOn(Expression<Func<TSub, object>> expression) { return new IQueryOverRestrictionBuilder<TRoot, TSub>(this, "prop"); } public IQueryOverRestrictionBuilder<TRoot, TSub> WhereRestrictionOn(Expression<Func<object>> expression) { return new IQueryOverRestrictionBuilder<TRoot, TSub>(this, "prop"); } public IQueryOver<TRoot, TSub> Select(params Expression<Func<TRoot, object>>[] projections) { return this; } public IQueryOver<TRoot, TSub> Select(params IProjection[] projections) { return this; } public IQueryOver<TRoot, TSub> SelectList(Func<QueryOverProjectionBuilder<TRoot>, QueryOverProjectionBuilder<TRoot>> list) { return this; } public IQueryOverOrderBuilder<TRoot, TSub> OrderBy(Expression<Func<TSub, object>> path) { return new IQueryOverOrderBuilder<TRoot, TSub>(this, path); } public IQueryOverOrderBuilder<TRoot, TSub> OrderBy(Expression<Func<object>> path) { return new IQueryOverOrderBuilder<TRoot, TSub>(this, path, false); } public IQueryOverOrderBuilder<TRoot, TSub> OrderBy(IProjection projection) { return new IQueryOverOrderBuilder<TRoot, TSub>(this, projection); } public IQueryOverOrderBuilder<TRoot, TSub> OrderByAlias(Expression<Func<object>> path) { return new IQueryOverOrderBuilder<TRoot, TSub>(this, path, true); } public IQueryOverOrderBuilder<TRoot, TSub> ThenBy(Expression<Func<TSub, object>> path) { return new IQueryOverOrderBuilder<TRoot, TSub>(this, path); } public IQueryOverOrderBuilder<TRoot, TSub> ThenBy(Expression<Func<object>> path) { return new IQueryOverOrderBuilder<TRoot, TSub>(this, path, false); } public IQueryOverOrderBuilder<TRoot, TSub> ThenBy(IProjection projection) { return new IQueryOverOrderBuilder<TRoot, TSub>(this, projection); } public IQueryOverOrderBuilder<TRoot, TSub> ThenByAlias(Expression<Func<object>> path) { return new IQueryOverOrderBuilder<TRoot, TSub>(this, path, true); } public IQueryOver<TRoot, TSub> TransformUsing(IResultTransformer resultTransformer) { return this; } public IQueryOverFetchBuilder<TRoot, TSub> Fetch(Expression<Func<TRoot, object>> path) { return new IQueryOverFetchBuilder<TRoot, TSub>(this, path); } public IQueryOverLockBuilder<TRoot, TSub> Lock() { throw new NotImplementedException(); } public IQueryOverLockBuilder<TRoot, TSub> Lock(Expression<Func<object>> alias) { throw new NotImplementedException(); } public IQueryOver<TRoot, U> JoinQueryOver<U>(Expression<Func<TSub, U>> path) { return new QueryOverStub<TRoot, U>(new List<TRoot>()); } public IQueryOver<TRoot, U> JoinQueryOver<U>(Expression<Func<U>> path) { return new QueryOverStub<TRoot, U>(new List<TRoot>()); } public IQueryOver<TRoot, U> JoinQueryOver<U>(Expression<Func<TSub, U>> path, Expression<Func<U>> alias) { return new QueryOverStub<TRoot, U>(_list); } public IQueryOver<TRoot, U> JoinQueryOver<U>(Expression<Func<U>> path, Expression<Func<U>> alias) { return new QueryOverStub<TRoot, U>(new List<TRoot>()); } public IQueryOver<TRoot, U> JoinQueryOver<U>(Expression<Func<TSub, U>> path, JoinType joinType) { return new QueryOverStub<TRoot, U>(new List<TRoot>()); } public IQueryOver<TRoot, U> JoinQueryOver<U>(Expression<Func<U>> path, JoinType joinType) { return new QueryOverStub<TRoot, U>(new List<TRoot>()); } public IQueryOver<TRoot, U> JoinQueryOver<U>(Expression<Func<TSub, U>> path, Expression<Func<U>> alias, JoinType joinType) { return new QueryOverStub<TRoot, U>(new List<TRoot>()); } public IQueryOver<TRoot, U> JoinQueryOver<U>(Expression<Func<U>> path, Expression<Func<U>> alias, JoinType joinType) { return new QueryOverStub<TRoot, U>(new List<TRoot>()); } public IQueryOver<TRoot, U> JoinQueryOver<U>(Expression<Func<TSub, IEnumerable<U>>> path) { return new QueryOverStub<TRoot, U>(new List<TRoot>()); } public IQueryOver<TRoot, U> JoinQueryOver<U>(Expression<Func<IEnumerable<U>>> path) { return new QueryOverStub<TRoot, U>(new List<TRoot>()); } public IQueryOver<TRoot, U> JoinQueryOver<U>(Expression<Func<TSub, IEnumerable<U>>> path, Expression<Func<U>> alias) { return new QueryOverStub<TRoot, U>(new List<TRoot>()); } public IQueryOver<TRoot, U> JoinQueryOver<U>(Expression<Func<IEnumerable<U>>> path, Expression<Func<U>> alias) { return new QueryOverStub<TRoot, U>(new List<TRoot>()); } public IQueryOver<TRoot, U> JoinQueryOver<U>(Expression<Func<TSub, IEnumerable<U>>> path, JoinType joinType) { return new QueryOverStub<TRoot, U>(new List<TRoot>()); } public IQueryOver<TRoot, U> JoinQueryOver<U>(Expression<Func<IEnumerable<U>>> path, JoinType joinType) { return new QueryOverStub<TRoot, U>(new List<TRoot>()); } public IQueryOver<TRoot, U> JoinQueryOver<U>(Expression<Func<TSub, IEnumerable<U>>> path, Expression<Func<U>> alias, JoinType joinType) { return new QueryOverStub<TRoot, U>(new List<TRoot>()); } public IQueryOver<TRoot, U> JoinQueryOver<U>(Expression<Func<IEnumerable<U>>> path, Expression<Func<U>> alias, JoinType joinType) { return new QueryOverStub<TRoot, U>(new List<TRoot>()); } public IQueryOver<TRoot, TSub> JoinAlias(Expression<Func<TSub, object>> path, Expression<Func<object>> alias) { return this; } public IQueryOver<TRoot, TSub> JoinAlias(Expression<Func<object>> path, Expression<Func<object>> alias) { return this; } public IQueryOver<TRoot, TSub> JoinAlias(Expression<Func<TSub, object>> path, Expression<Func<object>> alias, JoinType joinType) { return this; } public IQueryOver<TRoot, TSub> JoinAlias(Expression<Func<object>> path, Expression<Func<object>> alias, JoinType joinType) { return this; } public IQueryOverSubqueryBuilder<TRoot, TSub> WithSubquery { get { return new IQueryOverSubqueryBuilder<TRoot, TSub>(this); } } public IQueryOverJoinBuilder<TRoot, TSub> Inner { get { return new IQueryOverJoinBuilder<TRoot, TSub>(this, JoinType.InnerJoin); } } public IQueryOverJoinBuilder<TRoot, TSub> Left { get { return new IQueryOverJoinBuilder<TRoot, TSub>(this, JoinType.LeftOuterJoin); } } public IQueryOverJoinBuilder<TRoot, TSub> Right { get { return new IQueryOverJoinBuilder<TRoot, TSub>(this, JoinType.RightOuterJoin); } } public IQueryOverJoinBuilder<TRoot, TSub> Full { get { return new IQueryOverJoinBuilder<TRoot, TSub>(this, JoinType.FullJoin); } } } A: Don't try to mock QueryOver. Instead, define a repository interface (which uses QueryOver internally) and mock that interface. A: I don't think the above code is right. AFAIK QueryOver is an extension method on ISession interface and you can not Mock extensions method like that (at least not with conventional Mocking tools like Moq or RhinoMocks). A: Lately I've been moving the code that calls .QueryOver() to a protected virtual method instead and building my own TestableXYZ that inherits from XYZ and overrides the method and returns a empty list or whatever. This way I dont need a repository just for testing. A: NHibernate QueryOver async code can be mocked using c# moq var session = new Mock<NHibernate.ISession>(); session.Setup(x => x.QueryOver<Etype>().ListAsync(CancellationToken.None)).ReturnsAsync(data); _dbContext.Setup(m => m.Session).Returns(session.Object);
{ "language": "en", "url": "https://stackoverflow.com/questions/7513681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How to generate mysql query to insert the 2000 records at a time? Here is my scenario, I have table ID(PK) TYPE(PK) 01 3 02 3 03 3 04 3 now i have to insert ID upto 1000 with type 3... is there any option to do that automatically??? A: Use a stored procedure DELIMITER $$ CREATE PROCEDURE insertMany(Pstart_id INT, Pend_id INT, Ptype INT) BEGIN DECLARE i INT; IF (pstart_id > pend_id) THEN BEGIN SET i = PEnd_id; SET Pend_id = Pstart_id; SET Pstart_id = Pend_id; END; END IF; SET i = Pstart_id; WHILE I <= Pend_id DO BEGIN INSERT INTO table1 (id, `type`) VALUES (i, Ptype); SET i = i + 1; END; END WHILE; END $$ DELIMITER ; SELECT @first_id:= max(id)+1, @last_id:= max(id)+2001 FROM table1; CALL InsertMany(@first_id, @last_id, 3); This is faster than use a php loop because you are not sending a 1000 insert queries across the network. Or you can have a look at this question: How to select a single row a 100 million x A: If ID is a number: INSERT INTO TableX ( ID, TYPE ) VALUES (1, 3) , (2, 3) , (3, 3) , (4, 3) , (5, 3) , (6, 3) ; INSERT INTO TableX ( ID, TYPE ) SELECT ID, 3 FROM ( SELECT 7+ d0.ID - 1 + (d1.ID * 6) - 6 + (d2.ID * 36) - 36 + (d3.ID * 216) - 216 AS ID FROM TableX AS d0 CROSS JOIN TableX AS d1 CROSS JOIN TableX AS d2 CROSS JOIN TableX AS d3 WHERE d0.TYPE = 3 AND d0.ID <= 6 AND d1.TYPE = 3 AND d1.ID <= 6 AND d2.TYPE = 3 AND d2.ID <= 6 AND d3.TYPE = 3 AND d3.ID <= 6 ) AS tmp WHERE ID <= 1000 ; A: Not sure about a MySQL query but since you are familiar with PHP why not write a very simple php script that loops 1000 times and does the insert..? A: Maybe you can try http://www.generatedata.com/#generator to insert automatically.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MFC Serial Port WriteFile() Crash I am trying to write to a serial port using the WriteFile() function and when I put some breakpoints to check whether it is writing or not, it doesn't. I am trying to pass a string of data through my COMM port. BOOL bWriteRC = false; DWORD iBytesWritten = 0; //String data: "$ABCEFG,00000020,010000003F800000*##\r\n" ==> stored in a CString CString sStore = "$ABCEFG,00000020,010000003F800000*##\r\n"; bWriteRC = WriteFile(hdl,sStore.GetBuffer(),sStore.GetLength(),&iBytesWritten,NULL); // doesn't go past this... Somehow whenever I execute it, the program doesn't go past this function and it stops. Any suggestions on what am I doing wrong? I tried reducing the GetLength(), made it 14 and it works flawlessly but as soon as the number of bytes to write increases beyond 14, WriteFile() stops to go further. Thanks in advance. A: Considering your question, WriteFile() should always succeed as Alex mentioned earlier. Better check the string which you are trying to write is correct or not and is acceptable on the serial port or not. Sometimes, such small things might be overseen and result in big errors. Other than that, in my opinion it should work if it is a simple write operation. A: If it hangs in WriteFile it means that COM port driver does not accept your data, it cannot send it to COM port. It depends on such COM port setting as DTR signal state. You need to check flow control settings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C# managed code reference type question I have a class that contains some properties, consisting of lists. These lists can be populated with some Sharepoint objects that can be fairly memory intensive. I pass this class with its list properties through to my function like this: public void InsertFixedLineItems(CacheBundle cb) { //work here } As you can see the type in question is called a CacheBundle, and at runtime its heavily populated. For ease of use I want to localize the exact list properties further like this: public void InsertFixedLineItems(CacheBundle cb) { List<XYZCacheItem> XYZCacheItems = cb.xyzCacheItems; List<YYYCacheItem> YYYCacheItems = cb.YYYCacheItems; List<ZZZCacheItem> ZZZCacheItems = cb.ZZZCacheItems; } My question is, during this assignment above is the code creating a copy of each property, essentially each collection. By doing so waste memory? Or is the XYZCacheItems merely some kind of pointer to the cb.xyzCacheItems. If it is not, is it possible to create a "pointer variable" so that if I update XYZCacheItems -> cb.xyzCacheItems gets updated too? At the same time use no extra (or very little) memory and have both assignments. A: Lists are reference types, therefore are NEVER copied during assignment or while passing them into a function. XYZCacheItems points to the same object as cb.xyzCacheItems after the assignment, any changes to XYZCacheItems will appear in cb.xyzCacheItems as well. Variables of reference types, referred to as objects, store references to the actual data. From MSDN. You may also want to read some articles about differences between value and reference types (like this one). Understanding this is crucial to work with .Net languages efficiently. EDIT: Don't mess up the terminilogy. Pointer is pointer (integer describing specific location in memory), reference is reference (identifier referring to specific managed object, which can be moved around in memory by the runtime, among other things). You CAN use classic C-like pointers in C#, but they have their drawbacks. A: The pointer is copied when you pass it as a parameter ... but the object is not. So the only memory overhead is the allocation of a pointer. Changes the properties of the object pulled from the list will be reflected in the original ... unless you reassign it. If you reassign the pointer in the list the original pointer will still point to the old object. Parameter passing in c# --> http://msdn.microsoft.com/en-us/library/0f66670z(v=vs.71).aspx A: The other answers are good, but I just want to clear up a major assumption we're making, and that is that the property wwwCacheItems does not return a copy of the list. If it isn't, then all is fine. A: If any of object references point to the same object, any of these will be modifying the same object. That's, while you don't create another object, you're creating many references to the same object, which isn't a waste of memory. Be careful about having heavy objects being referenced in a lot of places, because if some of these are in persistent contexts - like singletons -, these will be never recycled by GAC. A: List<T> (really class, interface, and delegate) are reference types and when you pass them to a method, in fact a pointer of them passed to method. For more information follow this page's sections.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Application wait for Windows profile to be created I have a WPF VB.NET 3.5 application which we have set to run at login via GPO (Windows 7, AD 2003/2008), when this application runs on user login I finding that it is failing when the user has not logged into the PC before and the profile needs to be created. In our environment we use redirected folders to point folders such as Favorites and AppData (Global) to a network share. My application copies files and folders to these redirected folders. When my application is processing the folder and file copy code, I am seeing exceptions appear in my log file that the folder doesn't exist. I have added the following bits of code to the top of my Window_Loaded method, which checks that the drives exist, and thinking that explorer runs when the profile has been created, I have also put in a check that this process exists. Do Until checkProcessRunning("Explorer") = True AND _ Directory.Exists("U:\") AND Direcotry.Exists("S:\") Thread.Sleep(100) Loop However, even with this in place I am still experiencing the issue of folders not being present. One such folder I need is %AppData%\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar. The Exception I am getting is Could not find part of the path. What I am hoping for is some guidance or suggestions on how people have overcome this type of problem in the past, or what I am I missing, am I heading in the right direction or completely missing the mark? Greatly appreciate any assistance given. Matt
{ "language": "en", "url": "https://stackoverflow.com/questions/7513692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to isolate unit tests We have a batch processing project that utilizes a cache (that relies on static data). The unit tests for this project unfortunately mess up other unit tests within the same solution (because of the static data), so I need to isolate the batch processing unit tests from all other unit tests. The framework/organization that we work in is really strict and all unit tests have to be in the same project. Still all unit tests have to be run in the build. What I need is to ensure that the batch processing unit tests are not run within the same process as other unit tests. Is there any way to do this? Edit: Specifically, I'm looking for a way to control which process each test is run under. I couldn't find documentation about this, but it seems that all unit test are run under the same instance of the QTAgent32.exe process. There's a setting that determines whether tests are run in the same process (Tools > Options > Test Tools > Test Execution > Keep test ion engine running between tests). However, this is a global setting. What I need is to say is "run these tests in this process, and these tests in this process". Is there any way to do this? A: That's the problem with global state, as you have mentioned: modifying it in one test, will affect other tests. This tells me you are using automated tests more as an Integration tests. You can still create another project for all you "integration" style tests and place them together (knowing that they may affect each other and be brittle) and you can plug both test projects into your build / CI system. The other way to fix this is to use mock objects and make write tests in "unit test" style, having no other dependencies than the Class Under Test. Depending on what you are writing this may range from being hard to do so, not possible or applicable by minor refactorings. A: One key requirement for a good unit test is that it is isolated. In practice, this means no unit test uses state from other tests or can be affected by state in other tests. A unit test must set up the required state before execution and tear it down afterwards. This can for instance be done through the use of test fixtures. Related to this is Arrange-Act-Assert (AAA), which is a pattern for writing unit tests. In your case the static data is bad and that makes it difficult to test! What about refactoring your code so that the static data is available through some kind of interface or through a factory? Not knowing your problem area it's impossible to give a precise answer what would be the best. However, the approach you should go for is to take out the shared static data, so each test can set up it's own data set. Now each test can be isolated and will only deal with "own" data. This gives further benefits such as 1) unit tests would just have a data set enough to test one thing 2) less dependencies in your system, and 3) probably faster/smaller tests. Lastly, I agree with Hadi that you should keep unit test and integration/functional test separate. This is very important, because they test things differently. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7513700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Most efficient way to find 1s in a binary word? I am unsure what something like this would be called, (hence the clumsy title) but I need something like this for something I'm working on. I can't describe it well in words, but I hope this drawing explains for me: What would be the fastest way of getting the number of "on-bits", "3" in this example, when everything after the arbitrary "index" (5 for example) is to be ignored? A: In addition to what has already been said, I would like to bring it to your attention that many compilers offer a build-in popcnt that may be faster than doing it manually (then again, maybe not, be sure to test it). They have the advantage of probably compiling to a single popcnt opcode if it's available in your target architecture (but I heard they do stupid slow things when falling back to a library function), whereas you'd be very lucky if the compiler detected one of the algorithms from Sean's bithacks collection (but it may). For msvc, it's __popcnt (and variants), for gcc it's __builtin_popcount (and variants), for OpenCL (ok you didn't ask for that, but why not throw it in) it's popcnt but you must enable cl_amd_popcnt. A: First do input &= 0xfffffff8 (or the equivalent for your input type) to clear the three rightmost bits. Then take your pick from here. A: Something like the following: int countOnes( unsigned value, int top ) { assert( top >= 0 && opt < CHAR_BIT * sizeof( unsigned ) ); value &= ~(~0 << top); int results = 0; while ( value != 0 ) { ++ results; value &= value - 1; } return results; } This depends on the somewhat obscure fact that i & (i - 1) resets the low order bit. A: A lookup table will give you this information in constant time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to Show data in GridView TextBox, and/or DropDownListBoxs in asp.net My client has given one requirement like below: He wants to Insert, Update, Delete record inside the GridView only. He wants all the data to be present in TextBoxes and DropDownList controls (i.e. not in the label controls). If he wants to update any record, then he wants to straight-away update the record there and clicks on Update button. He doesn't want to click on the Edit link to get the record in Edit mode. How can I achieve this functionality? I should also consider references columns while designing GridView. i.e. some templates will contain DropDownList items also. Can anybody please suggest me how to do this. Some suggestions or some links to learn are appreciatable. Please help me on this. A: Checkout this link: http://geekswithblogs.net/dotNETvinz/archive/2009/08/09/adding-dynamic-rows-in-asp.net-gridview-control-with-textboxes-and.aspx. In this example author used only TextBoxes but DropDownList can be used in similar fashion, from the link you will at least get the idea about using control inside GridView cell and then retrieving the data they contains. A: GvYou can add the requied field to the grid view in a template field <asp:TemplateField HeaderText="fieldname" > <ItemTemplate> <asp:TextBox ID="txbType" Text='<%# Eval("field") %>' runat="server"></asp:TextBox> </ItemTemplate> </asp:TemplateField> and then in the backend code protected void Gv_RowUpdating(object sender, GridViewUpdateEventArgs e) { int index = Convert.ToInt32(e.RowIndex.ToString()); GridViewRow row = GV.Rows[index]; var txbName = row.FindControl("txbType") as TextBox; string name = ""; if (txbName != null) { name = txbName.Text.Trim(); } if (true) // your update function } same for the deleting protected void Gv_RowDeleting(object sender, GridViewDeleteEventArgs e) { }
{ "language": "en", "url": "https://stackoverflow.com/questions/7513711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Assignments in C Can you write something like this in C with multiple assignment operations? int a = 0, b = 0, c = 0, d = 0; (((a = b) = c) = d); I've read somewhere that C standard states that the result of this won't be lvalue? is this undefined? A: You can do a = b = c = d; which is the same as a = (b = (c = d)); As you say, the (sub-)expression (a = b) is not an lvalue and can't be assigned a value. A: a=b returns value of b which won't be lvalue, and that's the reason why the value of c can't be assigned to that expression. With parentheses you are changing usual order of assignments. a = b = c = d; in this case value of d is assigned to c, then value of c to b, then value of b to a. A: a=b=c=d; is same as (a = (b = (c = d))); because '=' operator assign right to left..
{ "language": "en", "url": "https://stackoverflow.com/questions/7513712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Regex for special ucwords I want to do an ucwords() in JavaScript on a string of the form: test1_test2_test3 and it should return Test1_Test2_Test3. I already found an ucwords function on SO, but it only takes space as new word delimiters. Here is the function: function ucwords(str) { return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) { return $1.toUpperCase(); }); Could anyone help? A: Just add an underscore to the list of acceptable word breaks: function ucwords(str) { return (str + '').replace(/^([a-z])|[\s_]+([a-z])/g, function ($1) { return $1.toUpperCase(); }) }; As you can see ive replace the bit which was \s+ to [\s_]+ Live example: http://jsfiddle.net/Bs8ZG/ A: Try the regular expression /(?:\b|_)([a-z])/ For an example see here A: Two other solutions that seems pretty complete: String.prototype.ucwords = function() { str = this.toLowerCase(); return str.replace(/(^([a-zA-Z\p{M}]))|([ -][a-zA-Z\p{M}])/g, function($1){ return $1.toUpperCase(); }); } $('#someDIV').ucwords(); Source: http://blog.justin.kelly.org.au/ucwords-javascript/ function ucwords (str) { return (str + '').replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function ($1) { return $1.toUpperCase(); }); } ucwords('kevin van zonneveld'); Source: http://phpjs.org/functions/ucwords/ Worked fine to me!
{ "language": "en", "url": "https://stackoverflow.com/questions/7513718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android keyboard does not open when using media queries I have a mobile site that includes a search box at the bottom. I also use media queries to hide content in portrait mode and display it in landscape mode. However in Android devices when I click on the search field the keyboard opens then immediately closes, making it impossible to type in the box. This is not a problem in iOS. The page can be viewed here - http://so.ajcw.com/android-keyboard.htm and here is the full page code: <!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-type" content="text/html; charset=UTF-8"> <title>Erroring search field</title> <style> .address { display: none; } @media only screen and (orientation: landscape) { .address { display: block; } } </style> </head><body> <h3>Venue 1</h3> <p>Cuisine</p> <p>Price</p> <p>Rating</p> <p class="address">Address</p> <h3>Venue 2</h3> <p>Cuisine</p> <p>Price</p> <p>Rating</p> <p class="address">Address</p> <form><input type="text"></form> </body></html> Thing's I've tried * *If I have only one venue or if I move the search up the page the problem goes away (this isn't a solution, just an observation). *I have tried changing the DOCTYPE - an HTML5 doctype slightly changes the functionality in that the keyboard remains after the second click, but again it doesn't fix the issue. *edit* * *This does seem to be browser specific. An old Android phone does not have the problem, nor it seems does my Android's (HTC Desire) default browser, but it does happen in Dolphin HD. A: This is not a solution, but a little telling I think. When I added float:left and position:relative I get the behavior you describe when changing the doc-type. On the second click when the keyboard does show up the landscape items show up too. Seems like a hiccup in the orientation: landscape for android. .address {display:none} @media only screen and (orientation: landscape) { .address {color:red;display:block;float:left;position:relative} } Given the vast difference in screen sizes these days. I'd suggest moving away from using orientation and instead use max and min widths. UPDATE: Ok I think I confirmed that at least on my Motorola Triumph in the android browser, orientation:landscape is not fully supported. I used the following and clicking the text box in portrait view triggered the landscape styles to display... @media only screen and (orientation: landscape) { BODY {background:pink} } A: Using Adam's research the issue is solved by avoiding using orientation. The solution that works for me is taken from this CSS3 'boilerplate', and uses min and max widths like so: @media only screen and (max-width: 320px) { .address { display: none; } } @media only screen and (min-width: 321px) { .address { display: block; } } This can be seen in action here - http://so.ajcw.com/android-keyboard-solved.htm (http://goo.gl/nNIm9) However this solution is not ideal as using fixed dimensions will eventually break as devices resolutions change.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: SOAP client application exception I wrote a client application that consumes a SOAP web service. I developed the code using Eclips and it works fine there. Now, I'm trying to run the same application from the terminal by using wsrunclient.sh so it gets the input but after that it crashes and gives this exception: Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/axis/client/Service at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632) at java.lang.ClassLoader.defineClass(ClassLoader.java:616) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141) at java.net.URLClassLoader.defineClass(URLClassLoader.java:283) at java.net.URLClassLoader.access$000(URLClassLoader.java:58) at java.net.URLClassLoader$1.run(URLClassLoader.java:197) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:248) at Weather.main(Unknown Source) Caused by: java.lang.ClassNotFoundException: org.apache.axis.client.Service at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:248) But the axis.jar which is version 1.4 is already in the classpath! So, please any thoughts why this error come up? A: Solved!!! Actually I was trying to run using this command: wsrunclient.sh -classpath output myService So, I thought since the jar files are already within the output folder they will be included with the classpath but that was wrong! I have to name all the jar files separately with the class path, so the correct way to do it is: wsrunclient.sh -classpath output:output/net/webservicex/axis.jar:output/net/webservicex/log4j-1.2.8.jar:output/net/webservicex/commons-discovery-0.2.jar myService
{ "language": "en", "url": "https://stackoverflow.com/questions/7513720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery Chosen breaks in firefox What's wrong with firefox's calculations while using the Chosen plugin? Other browsers work well. Example. Be patient, it takes some time to load the less stylesheets (not precompiled while testing). A: What's wrong with firefox's calculations while using the Chosen plugin? Calculation of the border/padding of the search field is wrong. In particular, this line: sf_width = dd_width - get_side_border_padding(this.search_container) - get_side_border_padding(this.search_field) In Chrome dd_width is 98 and the resulting sf_width value is 63. In Firefox dd_width is 100 and the resulting sf_width is 94. Given that after the page loads I get 8 for get_side_border_padding(this.search_container) and 27 for get_side_border_padding(this.search_field) I would guess that the calculation of the padding is done too early, most likely before the CSS file loaded. Probably making some assumptions about the load order that are true in Chrome but not in Firefox.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What means "No such channel"-Exception in Apache ODE? I have multiple BPEL-processes which runs fine on WSO2 (version 2.0.1). But after some time, there appears following exception in the log. I have no clue, what they means nor how to get rid of them. Here is a snippet of the stacktrace: [2011-10-05 11:28:26,541] ERROR - Method "run" in class "org.apache.ode.bpel.rtrep.v2.RuntimeInstanceImpl$3" threw an unexpected exception. {org.apache.ode.jacob.vpu.JacobVPU} java.lang.IllegalArgumentException: No such channel; id=71 at org.apache.ode.jacob.vpu.ExecutionQueueImpl.findChannelFrame(ExecutionQueueImpl.java:205) at org.apache.ode.jacob.vpu.ExecutionQueueImpl.consumeExport(ExecutionQueueImpl.java:232) at org.apache.ode.jacob.vpu.JacobVPU$JacobThreadImpl.importChannel(JacobVPU.java:369) at org.apache.ode.jacob.JacobObject.importChannel(JacobObject.java:47) at org.apache.ode.bpel.rtrep.v2.RuntimeInstanceImpl$3.run(RuntimeInstanceImpl.java:627) at sun.reflect.GeneratedMethodAccessor41.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.ode.jacob.vpu.JacobVPU$JacobThreadImpl.run(JacobVPU.java:451) at org.apache.ode.jacob.vpu.JacobVPU.execute(JacobVPU.java:139) at org.apache.ode.bpel.rtrep.v2.RuntimeInstanceImpl.execute(RuntimeInstanceImpl.java:639) at org.apache.ode.bpel.engine.BpelRuntimeContextImpl.execute(BpelRuntimeContextImpl.java:618) at org.apache.ode.bpel.engine.ODEProcess.executeContinueInstanceTimerReceived(ODEProcess.java:476) at org.apache.ode.bpel.engine.ODEProcess.execInstanceEvent(ODEProcess.java:684) at org.apache.ode.bpel.engine.ODEProcess.access$000(ODEProcess.java:105) at org.apache.ode.bpel.engine.ODEProcess$4.run(ODEProcess.java:619) at org.apache.ode.bpel.engine.Contexts$1.call(Contexts.java:86) at org.apache.ode.bpel.engine.Contexts$1.call(Contexts.java:85) at org.apache.ode.bpel.engine.Contexts.execTransaction(Contexts.java:106) at org.apache.ode.bpel.engine.Contexts.execTransaction(Contexts.java:83) at org.apache.ode.bpel.engine.BpelServerImpl$TransactedRunnable.run(BpelServerImpl.java:893) at org.apache.ode.bpel.engine.BpelInstanceWorker$2.call(BpelInstanceWorker.java:143) at org.apache.ode.bpel.engine.BpelInstanceWorker$2.call(BpelInstanceWorker.java:142) at org.apache.ode.bpel.engine.BpelInstanceWorker.doInstanceWork(BpelInstanceWorker.java:174) at org.apache.ode.bpel.engine.BpelInstanceWorker.run(BpelInstanceWorker.java:141) at org.apache.ode.bpel.engine.ODEProcess$ProcessRunnable.run(ODEProcess.java:1290) at org.apache.ode.bpel.engine.BpelServerImpl$ServerRunnable.run(BpelServerImpl.java:839) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619) This the complete stacktrace from one of these exceptions. The errors seems to have no influence on the actual running processes, because the all do what the should. Can this be a configuration problem of my WSO2/ODE-Instance? Maybe it is a thread-pool-problem?! Any help or hint would be great, thanks! A: From the logs, this is not a configuration issue but rather an internal bug. For some reason, the navigator receives a timer event (did you use <pick>s with onAlarm and/or event handlers?) but the callback channel for this timer does not exist (anymore). I could imagine such timers are scheduled but not removed when when the process instance is completed. Later when the timer is triggered the path to target activity is not available. This is just guess work but fits to your description. I only know the ODE and ODE 2.0-experimental code base and not much about WSO2's customizations so I'd suggest to file a bug in their JIRA. A: We were able to identify one issue that was causing the java.lang.IllegalArgumentException: No such channel; You can find the from following jira. https://wso2.org/jira/browse/BPS-218 These will be incorporated into the new releases. A: we ran into the same problem. We could nail it down and explore it with a small process example. See thread 17451 on the forum of wso2.org (http://wso2.org/forum/thread/17451). A workaround might be to use a Timer instead of onAlarm. Remove the onAlarm and put a Timer activity in parallel to the pick activity. Wrap the pick and timer activity into a Scope and attach an exception handler to it. There's nothing to do in the exception handler, it just causes the engine to cancel all activities within the scope, including the timer (unfortunatley, an onAlarm is not cancelled). Throw an exception whenever you want to cancel the timer and also in the activity-path of the timer to make the bpel engine get out of the (parallel) pick activity. A problem that might happen: The timer (i.e. the former onAlarm) could fire while the engine is not waiting in the pick-activity, but executing a regular onMessage before the exception fired...
{ "language": "en", "url": "https://stackoverflow.com/questions/7513726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ruby - remove_const :File What is this piece of code doing? class Object remove_const :File end Is it completely deleting[1] the class? When I call File.instance_methods after that piece of code, it's just showing the methods that are inherited from Object/Kernel. Is it possible to revert this to original state? I mean, after using remove_const, is there a way to bring the class back to it's original state? (without saving the class definition previously.) [1] sorry for using the word "delete" A: according to documentation: http://apidock.com/ruby/Module/remove_const "Predefined classes and singleton objects (such as true) cannot be removed." So this method will do nothing with File class. That is why you can use instance_methods on File. Class File still exists. When you remove some class then you have to load it one more time (or run code of this class) if you want to use it again. Important Edit: That was theory but practice shows (what undur_gongor and Andrew Grimm pointed out in the comments) that with both Ruby 1.8.7 and Ruby 1.9.2, we will get "uninitialized constant File". So documentation is misleading in this case...
{ "language": "en", "url": "https://stackoverflow.com/questions/7513727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Hash invert in Ruby? I've got a hash of the format: {key1 => [a, b, c], key2 => [d, e, f]} and I want to end up with: { a => key1, b => key1, c => key1, d => key2 ... } What's the easiest way of achieving this? I'm using Ruby on Rails. UPDATE OK I managed to extract the real object from the server log, it is being pushed via AJAX. Parameters: {"status"=>{"1"=>["1", "14"], "2"=>["7", "12", "8", "13"]}} A: hash = {:key1 => ["a", "b", "c"], :key2 => ["d", "e", "f"]} first variant hash.map{|k, v| v.map{|f| {f => k}}}.flatten #=> [{"a"=>:key1}, {"b"=>:key1}, {"c"=>:key1}, {"d"=>:key2}, {"e"=>:key2}, {"f"=>:key2}] or hash.inject({}){|h, (k,v)| v.map{|f| h[f] = k}; h} #=> {"a"=>:key1, "b"=>:key1, "c"=>:key1, "d"=>:key2, "e"=>:key2, "f"=>:key2} UPD ok, your hash is: hash = {"status"=>{"1"=>["1", "14"], "2"=>["7", "12", "8", "13"]}} hash["status"].inject({}){|h, (k,v)| v.map{|f| h[f] = k}; h} #=> {"12"=>"2", "7"=>"2", "13"=>"2", "8"=>"2", "14"=>"1", "1"=>"1"} A: Lots of other good answers. Just wanted to toss this one in too for Ruby 2.0 and 1.9.3: hash = {apple: [1, 14], orange: [7, 12, 8, 13]} Hash[hash.flat_map{ |k, v| v.map{ |i| [i, k] } }] # => {1=>:apple, 14=>:apple, 7=>:orange, 12=>:orange, 8=>:orange, 13=>:orange} This is leveraging: Hash::[] and Enumerable#flat_map Also in these new versions there is Enumerable::each_with_object which is very similar to Enumerable::inject/Enumerable::reduce: hash.each_with_object(Hash.new){ |(k, v), inverse| v.each{ |e| inverse[e] = k } } Performing a quick benchmark (Ruby 2.0.0p0; 2012 Macbook Air) using an original hash with 100 keys, each with 100 distinct values: Hash::[] w/ Enumerable#flat_map 155.7 (±9.0%) i/s - 780 in 5.066286s Enumerable#each_with_object w/ Enumerable#each 199.7 (±21.0%) i/s - 940 in 5.068926s Shows that the each_with_object variant is faster for that data set. A: Ok, let's guess. You say you have an array but I agree with Benoit that what you probably have is a hash. A functional approach: h = {:key1 => ["a", "b", "c"], :key2 => ["d", "e", "f"]} h.map { |k, vs| Hash[vs.map { |v| [v, k] }] }.inject(:merge) #=> {"a"=>:key1, "b"=>:key1, "c"=>:key1, "d"=>:key2, "e"=>:key2, "f"=>:key2} Also: h.map { |k, vs| Hash[vs.product([k])] }.inject(:merge) #=> {"a"=>:key1, "b"=>:key1, "c"=>:key1, "d"=>:key2, "e"=>:key2, "f"=>:key2} A: In the case where a value corresponds to more than one key, like "c" in this example... { :key1 => ["a", "b", "c"], :key2 => ["c", "d", "e"]} ...some of the other answers will not give the expected result. We will need the reversed hash to store the keys in arrays, like so: { "a" => [:key1], "b" => [:key1], "c" => [:key1, :key2], "d" => [:key2], "e" => [:key2] } This should do the trick: reverse = {} hash.each{ |k,vs| vs.each{ |v| reverse[v] ||= [] reverse[v] << k } } This was my use case, and I would have defined my problem much the same way as the OP (in fact, a search for a similar phrase got me here), so I suspect this answer may help other searchers. A: If you're looking to reverse a hash formatted like this, the following may help you: a = {:key1 => ["a", "b", "c"], :key2 => ["d", "e", "f"]} a.inject({}) do |memo, (key, values)| values.each {|value| memo[value] = key } memo end this returns: {"a"=>:key1, "b"=>:key1, "c"=>:key1, "d"=>:key2, "e"=>:key2, "f"=>:key2} A: new_hash={} hash = {"key1" => ['a', 'b', 'c'], "key2" => ['d','e','f']} hash.each_pair{|key, val|val.each{|v| new_hash[v] = key }} This gives new_hash # {"a"=>"key1", "b"=>"key1", "c"=>"key1", "d"=>"key2", "e"=>"key2", "f"=>"key2"} A: If you want to correctly deal with duplicate values, then you should use the Hash#inverse from Facets of Ruby Hash#inverse preserves duplicate values, e.g. it ensures that hash.inverse.inverse == hash either: * *use Hash#inverse from here: http://www.unixgods.org/Ruby/invert_hash.html *use Hash#inverse from FacetsOfRuby library 'facets' usage like this: require 'facets' h = {:key1 => [:a, :b, :c], :key2 => [:d, :e, :f]} => {:key1=>[:a, :b, :c], :key2=>[:d, :e, :f]} h.inverse => {:a=>:key1, :b=>:key1, :c=>:key1, :d=>:key2, :e=>:key2, :f=>:key2} The code looks like this: # this doesn't looks quite as elegant as the other solutions here, # but if you call inverse twice, it will preserve the elements of the original hash # true inversion of Ruby Hash / preserves all elements in original hash # e.g. hash.inverse.inverse ~ h class Hash def inverse i = Hash.new self.each_pair{ |k,v| if (v.class == Array) v.each{ |x| i[x] = i.has_key?(x) ? [k,i[x]].flatten : k } else i[v] = i.has_key?(v) ? [k,i[v]].flatten : k end } return i end end h = {:key1 => [:a, :b, :c], :key2 => [:d, :e, :f]} => {:key1=>[:a, :b, :c], :key2=>[:d, :e, :f]} h.inverse => {:a=>:key1, :b=>:key1, :c=>:key1, :d=>:key2, :e=>:key2, :f=>:key2} A: One way to achieve what you're looking for: arr = [{["k1"] => ["a", "b", "c"]}, {["k2"] => ["d", "e", "f"]}] results_arr = [] arr.each do |hsh| hsh.values.flatten.each do |val| results_arr << { [val] => hsh.keys.first }··· end end Result: [{["a"]=>["k1"]}, {["b"]=>["k1"]}, {["c"]=>["k1"]}, {["d"]=>["k2"]}, {["e"]=>["k2"]}, {["f"]=>["k2"]}]
{ "language": "en", "url": "https://stackoverflow.com/questions/7513730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to calculate number of views in my viewcontroller Currently i am generating "n" number of custom views in my DeatilViewController screen.So i want to calculate the number of views present in my DeatilViewController.xib and they belongs to which class. How can i do this? A: Try NSArray *subViews = [DeatilViewController.view subviews]; or for their count NSInteger count = [[DeatilViewController.view subviews] count]; A: UIViewController has a property called view that returns the controller's view. This UIView in turns has a property subviews that returns the subviews of the view. Get the length of this array and you got your subviews. http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIViewController_Class/Reference/Reference.html http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/doc/c_ref/UIView
{ "language": "en", "url": "https://stackoverflow.com/questions/7513733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Progress getting incorrect value from backgroundworker I'm new in c# and i'm still working way through and learning it all. I have made this code for a progress bar when downloading a file from ftp, and it actually working just fine. But progress value is all wrong. It looks like it is byte value somehow. But the weird thing is when I print the value to the screen, then it prints the correct value. private void frm_movie_db_Load(object sender, EventArgs e) { if (!File.Exists("movies.list.gz")) { bg_worker.RunWorkerAsync(); } } private void bg_worker_DoWork(object sender, DoWorkEventArgs e) { string strDownloadFrom = "ftp://ftp.sunet.se/pub/tv+movies/imdb/movies.list.gz"; string strDownloadTo = "movies.list.gz"; try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(strDownloadFrom); request.Method = WebRequestMethods.Ftp.GetFileSize; request.Credentials = new NetworkCredential("anonymous", ""); request.UsePassive = true; request.UseBinary = true; request.KeepAlive = true; Int64 intFileSize = request.GetResponse().ContentLength; Int64 intRunningByteTotal = 0; request = (FtpWebRequest)FtpWebRequest.Create(strDownloadFrom); request.Method = WebRequestMethods.Ftp.DownloadFile; request.Credentials = new NetworkCredential("anonymous", ""); request.UsePassive = true; request.UseBinary = true; request.KeepAlive = false; FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream reader = response.GetResponseStream(); Stream writer = new FileStream(strDownloadTo, FileMode.Create, FileAccess.Write, FileShare.None); byte[] byteBuffer = new byte[1024]; int intByteSize = 0; int intProgressPct = 0; while ((intByteSize = reader.Read(byteBuffer, 0, byteBuffer.Length)) > 0) { if (intByteSize == 0) { intProgressPct = 100; bg_worker.ReportProgress(intProgressPct); } else { writer.Write(byteBuffer, 0, intByteSize); if (intByteSize + intRunningByteTotal <= intFileSize) { intRunningByteTotal += intByteSize; double dIndex = intRunningByteTotal; double dTotal = byteBuffer.Length; double dProgressPct = (double)(dIndex / dTotal); intProgressPct = (int)dProgressPct; bg_worker.ReportProgress(intProgressPct); } } } //reader.Close(); //mem_stream.Close(); //response.Close(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } private void bg_worker_ProgressChanged(object sender, ProgressChangedEventArgs e) { //pb_download_files.Value = e.ProgressPercentage; lbl_progress_pct.Text = e.ProgressPercentage.ToString() + "%"; } private void bg_worker_RunWorkerComplete(object sender, RunWorkerCompletedEventArgs e) { pnlProgress.Visible = false; } I hope someone can help me with this, as i've done everything so far to fix the problem myself. Best regards Jesper A: You're completely mistaken on percentage progress calculation: perc must be 100 x current / total, so you're using wrong values. Try with this: double dProgressPct = 100.0 * intRunningByteTotal / intFileSize; bg_worker.ReportProgress((int)ProgressPct); Read Microsoft documentation: public void ReportProgress(int percentProgress) where percentageProgress is the percentage, from 0 to 100, of the background operation that is complete. A: double dTotal = byteBuffer.Length; Does not assign the total bytes to dTotal. byteBuffer is a buffer with a constant size of 1024 bytes. Try something like double dTotal = reader.Length; to retrieve the length in bytes of the stream. A: you have: double dTotal = byteBuffer.Length; double dProgressPct = (double)(dIndex / dTotal); I think you want: double dProgressPct = (double)(dIndex / intFileSize );
{ "language": "en", "url": "https://stackoverflow.com/questions/7513741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CakePHP/Croogo: A veeery complex association When I was working on my current project, I ran into a rather complex issue. I'll point out my problem much more detailed right now: There are three Models: User, UsersExtendedField and UsersExtended. UsersExtendedField contains custom fields that can be managed manually. All custom fields can be shown in the Users view as well, and be filled out of course. The values are then stored in UsersExtended, which has got two foreignKeys: user_id and field_id. The relations look like this: User hasMany UsersExtendedField, UsersExtendedField hasMany UsersExtended, UsersExtended belongsTo User, UsersExtendedField. The problem: When accessing the Users view, a form with user information input is shown. Any UsersExtendedFields are available as well, and since these hasMany UsersExtended, they've got plenty of UsersExtended values. But I want to reduce those to only the value(s) that belong to the User, whose view is shown at the moment. Here are my (desired) relations: Croogo::hookBehavior('User', 'Crooboard.ExtendedUser', array( 'relationship' => array( 'hasMany' => array( 'UsersExtendedField' => array( 'className' => 'Crooboard.UsersExtendedField', 'foreignKey' => '', 'conditions' => array('status' => 1) ), ), ), )); class UsersExtendedField extends AppModel { var $name = 'UsersExtendedField'; var $displayField = 'fieldname'; var $hasMany = array( 'UsersExtended' => array( 'className' => 'Crooboard.UsersExtended', 'foreignKey' => 'field_id', 'conditions' => array( 'UsersExtended.user_id = User.id' ) ), ); } This is not the full code, these are the important parts. The problem starts right where I wrote 'UsersExtended.user_id = User.id'. Obviously, this won't work. But I do not have any idea how to access the User.id here. I also could not imagine a HABTM structure to solve this task. Do you have any idea how to get the semantics of this 'UsersExtended.user_id = User.id' to work? Thank your very much for taking the time to read through this and helping me! A: It sounds like you need to set up your HABTM relationship properly. You already have the join table, UsersExtended, which contains your foreign keys. Remove all previous relationships and set up HABTM in each of your User and UserExtendedField models. The relationship code in your User model would look like this: var $hasAndBelongsToMany = array( 'UsersExtended' => array( 'className' => 'UsersExtended', 'joinTable' => 'UsersExtended', //assuming this is the //name of that model's table 'foreignKey' => 'user_id', 'associationForeignKey' => 'field_id' ) ); For more information check out the page in the cakephp book In addition, this blog post helped me grasp the relationship concepts when I was learning cakephp.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MediaPlayer.Volume control I have a slider where I get a value from 0 to 100 to adjust the volume. The MediaPlayer.Volume expects a value between 0.0 and 1.0 while 0=-96db and 1=-0db. Currently I use the following code to adjust the linear values from my slider: float newVolume = (float)(Math.Sqrt(sliderValue) / 10); newVolume = MathHelper.Clamp(newVolume, 0.0001f, 1.0f); MediaPlayer.Volume = newVolume; This works better then directly mapping the 0 to 100 values but in the higher half the adjustment is still rather low compared to the lower half. Are there any better solutions? A: This works for me, where 'value' is from 0 to 100 value = MathHelper.Clamp(value, 0f, 100f); var logged = Math.Log(value + 1) / Math.Log(101); MediaPlayer.Volume = MathHelper.Clamp((float)logged, 0.001f, 1.0f);
{ "language": "en", "url": "https://stackoverflow.com/questions/7513746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Plugins in dropins-catalog are not found What could cause Eclipse to ignore plugins in the dropins catalog? I've created a dummyplugin based on the Eclipse wizard, exported it to a jar. When dropping it into the drop-ins catalog of a fresh Eclipse installation, it works fine. When I do the same thing but on a custom Eclipse installation, it doesn't work. The plugin doesn't even show up in the plugin registry view. No error messages or anything like that. I've tried: * *Running with -clean *Running with -clean -consoleLog but no errors were printed *Starting up with -console, and checking if the plugin is seen with the command ss, no luck. *Running with -Dorg.eclipse.equinox.p2.reconciler.dropins.directory=C:\Program\Eclipse\eclipse3.6\dropins\ *Changing name of the eclipse catalog from eclipse3.6 to eclipse, in case I had run into a variation of an Eclipse bug *It's not due to dependency issues (like this question), since the plugin isn't even found *Update Copied the eclipse.ini from the working eclipse installation to the custom one, with the same result; The plugin wasn't found. So the issue isn't in the ini file *Update Thought the issue might be some rights issue, since I my user wasn't the owner of the custom installation. So I made a copy of the entire dir of the custom installation to make sure I was the owner with full rights. No change *Update Starting with a new workspace doesn't make any difference Is it possible to define that Eclipse should ignore the dropins catalog? How? The custom version of Eclipse defines a lot of variables, but nothing that seems related to p2 or the behaviour of dropins. A: The dropins/ folder is a best effort, totally optional, silently failing legacy leftover. Not big on the diagnostics, as you've found. If you use the director to install your bundle into your custom eclipse, at least you'll be able to get an error message that will tell you what the problem is. I'd suggest exporting your jar with some minimal p2 metadata. Then you use something like: eclipse/eclipse \ -application org.eclipse.equinox.p2.director \ -noSplash \ -repository \ file://$HOME/eclipseUpdate \ -installIUs \ org.dojotoolkit/1.6.1.v201105210659 If p2 can't find some dependency, it should spew out the confusing error messages it can generate. A: Hi @Fredrick I've made my own plugin and I've added to my eclipse in this way: * *Export the plugin as Deployable plug-ins and fragements. (Right click on the plugin project - Export - Plugin Development - Deployable plug-ins and fragements) *That will generate a .jar file that file you have to copied into \eclipse\plugins *Restart eclipse. I'd say that will be all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: DevExpress RowUpdating old values returning text value I have a DevExpress ASPXGridView which has been bound with a dataset. I'm using the edit row command to edit the data in the row and return it to the database. When the edit button is clicked, the row opens up and there is an ASPXComboBox that is bound to another dataset. The TextField and the ValueField have both been properly set in the ASPXComboBox and are displaying data correctly. The data is as shown * *List item *List item When e.NewValues("") is called the integer value field i.e 1 is returned. However, when e.OldValues("") the TextField is returned i.e. "List Item" Is there a way of returning the the integer value when calling e.Oldvalues without having to make another call to the database? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7513753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: adding new pair in dictionary why the last added 'mynewkey': 'mynewvalue' came first in dictionary >>> d = {'key':'value'} >>> print d {'key': 'value'} >>> d['mynewkey'] = 'mynewvalue' >>> print d {'mynewkey': 'mynewvalue', 'key': 'value'} why the last added 'mynewkey': 'mynewvalue' came first in dictionary A: Python dictionaries are not ordered. If you iterate over the items of a dict object you will not get them in the order you inserted them. The reason is the internal data structure behind it. If you use Python 2.7 or Python 3.3 you can resort to http://docs.python.org/dev/library/collections.html#collections.OrderedDict A: Dictionaries and sets are unordered in Python. The items end up in an order that varies from Python version to Python version, implementation to implementation, and shouldn't be relied upon. If you need to keep the items in order, you can use a collections.OrderedDict. For versions of Python older than 2.7, you can download it from PyPI.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to make list blob request (windows azure)? Unable to make list blob request using following URI with replacing myaccount with my storage account http://myaccount.blob.core.windows.net/mycontainer?restype=container&comp=list A: Are you sure that your blob is public? You can check is using CloudBerry Explorer a great free tool to manage Blobs. You can download it here: http://www.cloudberrylab.com/free-microsoft-azure-explorer.aspx Once the application is install go on the container and right-click. Go check in Properties is the security is public.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to display only right page using booklet plugin? Is it possible to display only the right page using booklet ? I like the effect with flipping page, but I can only have displayed in page. Thanks in advance A: Yes. I got this working simply by modifying the css. I think it was a combination of position: absolute; right:100%; with css clip or css crop, or something likeclip: rect(10px,10px,10px,10px);. It basically still uses the same two page book, but hides your left page out of visible sight. I found it quite neat to just show 10-15 px of the left page to make it look more book like.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Hide the iframes whose content get blocked by proxy I have a webpage with iframes. These iframes are for showing some external website data. But problem arise when those external servers get blocked in a network it gives a error that "The proxy server is refusing connections". It does not look good to me. I want to hide all these blocked iframes or want to show some alternate data there. A: It's not possible to check whether a page has not loaded. However, it's possible to use onload event handlers. It's important to not rely on JQuery, because JQuery is also an external source which has to be loaded. Add this code within <script> tags after the last IFRAME element (often, at the end of the body). Code: //Cannot rely on JQuery, as it has to be loaded (function(){//Anonymous wrapper. var iframes = document.getElementsByTagName("iframe"); var num_frames = iframes.length; //Function to add Event handlers var addLoad = window.addEventListener ? function(elem, func){ elem.addEventListener("load", func, true); } : window.attachEvent ? function(elem, func){ elem.attachEvent("onload", func); } : function(elem, func){ elem.onload = func; }; var success_load = 0; for(var i=0; i<num_frames; i++){ addLoad(iframes[i], function(){ this.dataSuccessfullyLoaded = true; success_load++; }); } addLoad(window, function(){ if(success_load < num_frames){ for(var i=num_frames-1; i>=0; i--){ if(!iframes[i].dataSuccessfullyLoaded){ iframes[i].parentNode.removeChild(iframes[i]); //Or: iframes[i].style.display = "none"; } } } }); })(); Fiddle: http://jsfiddle.net/3vnrg/ EDIT Your proxy seems to send HTTP pages with status code 200. Another option is to include the CSS file, and check whether a CSS variable exists or not: /*From http://static.ak.fbcdn.net/rsrc.php/v1/yb/r/CeiiYqUQjle.css*/ #facebook .hidden_elem{display:none !important} #facebook .invisible_elem{visibility:hidden} HTML: <link rel="Stylesheet" href="http://static.ak.fbcdn.net/rsrc.php/v1/yb/r/CeiiYqUQjle.css" /> <div id="facebook"><div class="hidden_elem invisible_elem"></div></div> JavaScript (execute this code after all resources have been loaded): if($("#facebook div").css("display") != "none" || $("#facebook div").css("visibility") != "hidden") disableFBFrame(); // Where disableFBFrame(); is a function which hides the frame.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How we can Find cause of CTS Error? I found some CTS errors which are given below: Compatibility Test Case: CtsAppTestCases Package Name: android.app.cts.DialogTest Error: -- testContextMenu fail junit.framework.AssertionFailedError at android.app.cts.DialogTest.testContextMenu(DialogTest.java:971)` -- testTabScreen fail java.lang.RuntimeException: Intent { act=Activity lifecycle incorrect: received onResume but expected onStop at 5 } at android.app.cts.ActivityTestsBase.waitForResultOrThrow(ActivityTestsBase.java:149) -- testTabScreen fail java.lang.RuntimeException: Intent { act=Activity lifecycle incorrect: received onResume but expected onStop at 5 } at android.app.cts.ActivityTestsBase.waitForResultOrThrow(ActivityTestsBase.java:149) -- testScreen fail java.lang.RuntimeException: Intent { act=Activity lifecycle incorrect: received onResume but expected onStop at 5 } at android.app.cts.ActivityTestsBase.waitForResultOrThrow(ActivityTestsBase.java:149)` A: This Test is expecting the lifecycle as onPause() then onStop(), but onResme() was called rather than onStop(). According to Android Activity Docs – “After receiving this call you will usually receive a following call to onStop() (after the next activity has been resumed and displayed), however in some cases there will be a direct call back to onResume() without going through the stopped state.” So, it is not mandatory to get desired sequence.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Asp.net flash muti-file uploaders - Is MultiPowUpload ok, or which is the best and easiest? I am considering using the MultiPowUpload control from element-it on a project, as well as perhaps on a second. Does anyone have any feedback on that particular control? Does it actually work as advertised, handle errors well, etc? I've played with quite a few others, but that seems the best so far. The easiest for the junior members to get off and going with, nearly all features out of the box, etc. Some of what I need to do: * *Multi-select of files (from a single 'browse' click, not multi-textbox) *Progress bar (client requirement) *Queue for upload (it's ok if it can only upload immediately) *Feedback from server - custom error messages (permissions,etc) *Pass the session ID automatically, but I can use a URL hack for the upload page too *Be able to remove files from the queue *Support large files (~50MB, really up to 300mb would be perfect) *Accessible/usable JS api *Can change the view style a little bit at least! *Localizable - we need english, chinese, italian, and possible a few others *Resume incomplete transfers (eg, connection dropped, so on, not required, but ++) I've been working with all of these below, and gotten most of them working in demo pages, finding issues as I go along. * *Fancy Upload - quite nice, but no feedback from server, uses mootools not jq *MultiPowUpload - looks good, resumes, no flash cookie bug, $149 *Uploadify - looks reasonable, real world though? *YUI - mostly custom code, will work but tedious *SWFUpload - no progress bar, otherwise pretty basic & good *JQuery Multifile (fyneworks.com) - inconsistent browser support *devex / telerek - missing to many required features, sadly *PL UPload - nice, but missing 'retry' and error reporting. may be able to add So, does anyone have any real-world experience with MultiPowUpload, or have suggestions for a free or commercial option? PL UPLOAD WON - for now! If we get complaints, or find it doesn't work in our real life scenarios, then we'll consider switching to MultiPowUpload. But it is good enough, and we can write some JS to do a few of the missing things. With chunking I had no problems with 300mb uploads. Yay. A: Did U try this one. Plupload Allows you to upload files using HTML5 Gears, Silverlight, Flash, BrowserPlus or normal forms, providing some unique features such as upload progress, image resizing and chunked uploads.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C#: BindingSource CancelEdit for all objects and there child objects from EF Let's say i have two objects from EF with INotifyPropertyChanged. Object1 has many Object2 and the BindingSource1 has many Object1. If I change some Properties of BindingSource1.Current (Object1) I'm able to restore them by calling BindigSource1.CancelEdit, before the BindingSource1.Current (Object1) has changed. But if I create a BindingSource2 for the Objects2 in the BindingSource1.Current (Object1) and change Properties in BindingSource2(Object2), I can't restore them by calling BindigSource1.CancelEdit. In my case I have BindingSource1 bind to DataGridView1 and BindingSource2 to DataGridView2. Now I want so Retore Object1 and all its Object2 if the user selects an other Object1 in DataGridView1 without clicking Save. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7513773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Mimicking WP7 Unlock Page Animation In my app, i need to create wp7 page unloak animation(ie sliding up the picture and unloak the device) how i can implement that in my app either with the help of xaml or with the help of C# code. A: These are the steps to achieve wp7 page unlock animation 1.Create the following storyboards <Storyboard x:Name="LockScreenSlideAnimation"> <DoubleAnimation Duration="0:0:1" To="-768" Storyboard.TargetProperty=" (UIElement.RenderTransform). (CompositeTransform.TranslateY)" Storyboard.TargetName="LockScreenGrid" d:IsOptimized="True"/> </Storyboard> <Storyboard x:Name="CoastGrid" > <DoubleAnimationUsingKeyFrames Storyboard.TargetName="LockScreenGrid" Storyboard.TargetProperty="(UIElement.RenderTransform) .(CompositeTransform.TranslateY)"> <EasingDoubleKeyFrame x:Name="coastY" KeyTime="00:00:01" Value="0"> </EasingDoubleKeyFrame> </DoubleAnimationUsingKeyFrames> </Storyboard> 2.Assume that the grid name is LockScreenGrid [Image Grid which will fly up on tap] <Grid Grid.Row="1" x:Name="LockScreenGrid" Visibility="{Binding LockScreenGridVisibility}" ManipulationDelta="lock_ManipulationDelta" ManipulationCompleted="lock_ManipulationCompleted" > 3.Implement lock_manipulationCompleted, lock_ManipulationDelta private void lock_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e) { if (this.gridTranslate.TranslateY< 0.0) { IEasingFunction function; this.CoastGrid.Stop(); this.gridTranslate.TranslateY = e.TotalManipulation.Translation.Y; if((e.IsInertial)&& (e.FinalVelocities.LinearVelocity.Y<-1500) || (this.gridTranslate.TranslateY<(base.ActualHeight/-2.0))) { this.coastY.Value = (-1.0 * this.LockScreenGrid.ActualHeight); function = new CircleEase(); ((CircleEase)function).Ease(1.0); } else { this.coastY.Value = 0.0; function = new BounceEase(); ((BounceEase)function).Ease(0); ((BounceEase)function).Ease(2); ((BounceEase)function).Ease(5.0); } this.coastY.EasingFunction=function; this.CoastGrid.Begin(); } } private void lock_ManipulationDelta(object sender, ManipulationDeltaEventArgs e) { e.Handled = true; this.gridTranslate.TranslateY = (this.gridTranslate.TranslateY + e.DeltaManipulation.Translation.Y); if(this.gridTranslate.TranslateY>0.0) { this.gridTranslate.TranslateY = 0.0; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7513776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Django Forms - Processing GET Requests We have an existing Django form that accepts GET requests to allow users to bookmark their resulting query parameters. The form contains many fields, most of which are required. The form uses semi-standard boilerplate for handling the request, substituting GET for POST: if request.method == 'GET': form = myForm(request.GET) if form.isValid() # Gather fields together into query. else form = myForm() The problem is that the first time the form is loaded, there's nothing in the GET request to populate the required fields with, so most of the form lights up with 'missing field' errors. Setting initial values doesn't work; apparently, the non-existent values in the GET request override them. How can we avoid this? I'm pretty certain we're simply not processing things correctly, but I can't find an example of a form that handles GET requests. We want errors to show up if the user hits the "Submit" button while fields are blank or otherwise invalid, but don't want these errors showing up when the form is initially displayed. A: The positional argument to the forms.Form subclass informs Django that you intend to process a form rather than just display a blank/default form. Your if request.method == 'GET' isn't making the distinction that you want because regular old web requests by typing a URL in a web browser or clicking a link are also GET requests, so request.method is equal to GET either way. You need some differentiating mechanism such that you can tell the difference between a form display and a form process. Ideas: If your processing is done via. AJAX, you could use if request.is_ajax() as your conditional. Alternatively, you could include a GET token that signifies that the request is processing. Under this example, first you'd need something in your form: <input type="hidden" name="action" value="process_form" /> And then you can look for that value in your view: if 'action' in request.GET and request.GET['action'] == 'process_form': form = myForm(request.GET) if form.is_valid(): # form processing code else: form = myForm() I'll also give you the standard, boilerplate point that it's generally preferable not to use GET for form processing if you can help it (precisely because you run into difficulties like this since you're using an anomalous pattern), but if you have a use case where you really need it, then you really need it. You know your needs better than I do. :-) A: If your clean page load doesn't have any non form GET params, you can differentiate between a clean page load and a form submit in your view. Instead of the usual form = YourForm() if request.POST: you can do if request.GET.items(): form = YourForm(request.GET) if form.is_valid(): ... else: form = YourForm() If your clean page load could have other params (eg email link tracking params) you'll need to use the QueryDict methods to test if any of your form params are in the request. A: request.GET is and empty dictionary when you first load a clean form. Once you have submitted the form, request.GET will be populated with your fields data, even if the fields contain only empty data. A: My first question is this, which I posted as comment: Why not just use request.POST and the standard way of processing form data? After considering everything here, perhaps what you are looking for is a way of processing data in your query string to populate a form. You can do that without using request.GET as your form.data. In my own views, I take advantage of a utility function I created to add initial data to the form from request.GET, but I am not going to share that function here. Here's the signature, though. initial_dict is typically request.GET. model_forms is either a single ModelForm or a list of ModelForm. def process_initial_data(model_forms, initial_dict): Nevertheless, I am able to process the form through the standard practice of using request.POST when the form is POSTed. And I don't have to pass around all kinds of information in the URL query string or modify it with JavaScript as the user enters information.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Android query to extract first word from a field So I've been dragging with this one for some time now and simply can't find the solutions Let's say I have a table called NAME with values like John Doe Jane Doe etc. I just want to pull the first word.... so everything after the first space ' ' will not show I'm pulling the data into a Cursor as it's over 2000 records Any thoughts on a raw query that will do such a thing? Thanks in advance Yeshai A: You just get the string from db as a string and use something like String[] strs = dbString.split(" "); str[0] should be what you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to force the screen orientation to portrait before starting an App? I am using the following line of code for each of my activities in order to force the screen orientation to portrait mode: setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); It works ok unless I put the device in landscape mode before launching the app. In this case, the activity closes suddenly. Any idea on how to manage this case? A: you need to use android:screenOrientation = "portrait" in your activity tag.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to remove style one click event? How can i remove the style class applied to a textbox on the click event? I'm calling the textbox element using getElementsByName(). Here's my code: <input id="userNameExists" name="popUpText" class="pop-upText" onclick="clearText(this);" /> function clearText(element) { id = element.getAttribute("id"); var textElement = document.getElementById(id); textElement.value = ""; var element = document.getElementsByName("popUpText"); var count = 0; for (count = 0; count < 2; count++) { var id = element.item(count); id.classname = ""; } } In the above script, im not getting the id in the variable id. Right now the values are like "#inputTextBoxName". Please help. A: you can use removeClass(); you can manege your styling using attr(); exp: $("#yourid").attr("style","float: right"); or remove class using $("#yourid").removeClass("yourClass"); A: It is case sensitive so id.className = ''; A: If you're trying to remove the class from the textbox when you click on the textbox itself, that code is far, far longer than it needs to be. HTML: <input type="text" id="userNameExists" name="popUpText" class="pop-upText" onclick="clearText(this);" /> Javascript: <script> function clearText(element) { element.className = ''; element.value = ''; } </script> That said, inline event handlers (ie. declaring an onclick attribute on your HTML element) are a bad practice to get into. Also, if you pass in a reference to an element, get its id, then call document.getElementById() with said id, you end up with two references to the same element. Yes, it should work, but totally pointless.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }