text
stringlengths
8
267k
meta
dict
Q: Overload operator= to exchange data between to classes I'd like to use two classes A and B for some different types of task. But i want to exchange some data, which should be similar in both, so i'd like to use a A = B for ex. So, how to use this, with avoiding two-way including in header files? Example: in class_a.h: #include class_b.h class A { private: int i; public: A& operator=(B& const b); } class_b.h: #include class_a.h // won't work here ... class B { private: unsigned long n; public: B& operator=(A& const a); } A: You must forward-declare the other class: class B; class A { private: int i; public: A& operator=(B& const b); } Also note that you should probably declare friend class B; inside the definition of A if you don't have getters and need to access B::n. A: You need to use a forward declaration: class A; class B { private: unsigned long n; public: B& operator=(A& const a); } A: Not necessarily better but consider also the idea not to override the assignment, but provide conversions. You can do like #include "b.h" class A { public: A(const B&); operator B() const; }; If you do a=b; it will become implicitly a=A(b) and if you do b=a; will become implicitly b=a.operator B(); This is like saying that B can be "promoted" to A and A "demoted" to B. But you can do all around A, not modifying B.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What's the most efficient way of incrementing weekly totals in mongo? In a scenario where I have weekly total points as an array of integers per user, I was reading in tip #7 in the "50 tips and tricks for MongoDB developers" that for best performance in Mongo that I should pre-populate the array. Thus for each user I should say insert 20 weeks ahead of time. e.g. Profile:{name:bob, totals:[{week:1,pts:0}, {week:2,pts:0}, {week:2,pts:0}, {week:2,pts:0}...etc..]} If that's the case, whats the best way to update the points field? I can do a $inc command if the entry for the week exists, but should I do an addToSet command first to make sure that the entry for the week exists and then do the $inc command? That seems inefficient... will the $inc command be combined with an upsert of some kind? The book's example suggests that instead of embedding totals in the profile, I can say create an annual totals document for each user and have an array of weekly points total in that document, pre-populating 52 weeks worth. I could then run a batch job to create a new annual totals document for each user if they are on their last week. Is it better to store my totals in a seperate collection rather than embed it in the profile with my use case?
{ "language": "en", "url": "https://stackoverflow.com/questions/7582604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: rendering query x times instead of required once because instance... help? I am trying to return a custom query, which renders each row once, however sometimes the table it queries is the same... For example. My output code currently is this... //Query one returns each instance of an object. There are two of the first, one of the second. 13775 13775 66777 //Query two returns each bit of information against the first object. // As you can see its loading the first too twice because of the query above being the same... SID=13775 TOKEN=b8r5x6w53d6cahw SID=13775 TOKEN=p5ugbeg68b4qixy SID=13775 TOKEN=b8r5x6w53d6cahw SID=13775 TOKEN=p5ugbeg68b4qixy SID=66777 TOKEN=4c85zznh955gjsc My code is as follows for the above display... //Query table where firstname, lastname and email all match $query = "SELECT * FROM lime_all_tokens WHERE fname='".$fname."' AND lname ='".$lname."'"; //execute query $result = mysql_query($query) or die ("Error in query: $query. ".mysql_error()); $sid = array(); // see if any rows were returned if (mysql_num_rows($result) > 0) { // yes // print them one after another $i = 0; while($row = mysql_fetch_row($result)) { //Shows the SID's echo $row[5]."<br />"; //Add into the DB in order... $sid[] = $row[5]; $i++; } } // free result set memory mysql_free_result($result); for ($j = 0; $j < $i; $j++) { $querytokens = "SELECT * FROM lime_tokens_".$sid[$j]." WHERE firstname='".$fname."' AND lastname ='".$lname."'"; echo $tokens[$j]."<br />"; //execute query $resulttokens = mysql_query($querytokens) or die ("Error in query: $querytokens. ".mysql_error()); // see if any rows were returned //print_r(mysql_fetch_row($resulttokens)); while($rowtokens = mysql_fetch_row($resulttokens)) { //Display our token echo "SID=".$sid[$j]." TOKEN=".$rowtokens[5]."<br />"; $displayonce = false; } } echo "<br /><br /><h2>There are a total of ".$i." calls availible!</h2>"; // free result set memory mysql_free_result($resulttokens); // close connection mysql_close($connection); How can i get it to return the data properly? i.e 13775 13775 66777 SID=13775 TOKEN=b8r5x6w53d6cahw SID=13775 TOKEN=p5ugbeg68b4qixy SID=66777 TOKEN=4c85zznh955gjsc A: IMHO you could change first query to: SELECT DISTINCT id FROM lime_all_tokens WHERE fname='".$fname."' AND lname ='".$lname."'"
{ "language": "en", "url": "https://stackoverflow.com/questions/7582606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use Nuget on an intranet I think NuGet is a great idea for dependency management. I would like to try using it for my team to manage dependencies. The problem is that we are on an intranet and not connected to the internet. Ideally, I would like to be able to mirror the official NuGet feed locally and supplement that with a local feed of packages that we provide internally. Can anyone provide guidance on how to do this? A: We have setup a local intranet feed for our own packages using: http://haacked.com/archive/2011/03/31/hosting-simple-nuget-package-feed.aspx Our teamcity is building the packages in special builds and pushing those to our internal feed. That blogpost says internal but it is in its current version also writeable. Make sure to check David Ebbo posts: http://blog.davidebbo.com/search/label/NuGet Especially: the dated: http://blog.davidebbo.com/2011/08/easy-way-to-set-up-nuget-to-restore.html Those will for example have you setup a build event which will make your projects on build download the referenced packages if they are missing (so you don't have to commit the packages to your sourcecontrol!). You will have to change a line in: .nuget\NuGet.targets to get package first from your local source and use the default nuget as secondary: <PackageSources>"http://[localserver]/nuget/nuget/;https://go.microsoft.com/fwlink/?LinkID=206669"</PackageSources> A: Jon Galloway has a powershell script that achieves this http://weblogs.asp.net/jgalloway/archive/2011/02/02/downloading-a-local-nuget-repository-with-powershell.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7582610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Inject new SMS event on Android I’m working on an app for Android. Is it possible to inject an event, so the phone thinks It just revived a new SMS. So it gives you a notification and everything. Not just put the new sms in the inbox. Still cant get this to work, im thinking something like: Intent a = new Intent("android.provider.Telephony.SMS_RECEIVED"); a.putExtra("tlf", "123"); startActivity(a); And then some :) Any one? A: I think you should call an SMS_RECEIVED intent.... here's some more info how sms_received intent works http://davanum.wordpress.com/2007/12/15/android-listen-for-incoming-sms-messages/ A: To get SMS notification, use this link. "Check Receiving SMS Messages" To abort messages in Android in Receiver class, set abortBroadcast() and in Manifest.xml, set below code in SMSReceiver: <intent-filter android:priority="1000"> <action android:name="android.provider.Telephony.SMS_RECEIVED"/> </intent-filter>
{ "language": "en", "url": "https://stackoverflow.com/questions/7582613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to find the latitude and longitude of a point from a given point, given the distance between the two? I want to find the point which is some X kms from the current point say A, if I know the latitude and longitude of center point How can I get the latitude, longitude of four points at circumference.... I am searching SO for quite long but not able to get the solution in JavaScript or in Java... distance In my case will be in few kms so cant consider earth as flat surface so plz dont suggest such solution... Thanks A: Take a look at this page which explains in great detail the spherical model for distance calculation with JavaScript examples: Given a start point, initial bearing, and distance, this will calculate the destination point and final bearing travelling along a (shortest distance) great circle arc. JavaScript: var lat2 = Math.asin( Math.sin(lat1)*Math.cos(d/R) + Math.cos(lat1)*Math.sin(d/R)*Math.cos(brng) ); var lon2 = lon1 + Math.atan2(Math.sin(brng)*Math.sin(d/R)*Math.cos(lat1), Math.cos(d/R)-Math.sin(lat1)*Math.sin(lat2)); A: I was crushing the code above Until I did not realized that both lat and lon are the radian Value! You have to convert them back to the degrees, and you will see real values. Here is the code public class cal { public static void main(String []args){ double R = 6371.0; double d = 0.100; double lat1 = 42.873, lon1 = 74.568; double Radlat1 = Math.toRadians(42.873); double Radlon1 = Math.toRadians(74.568); double brng = Math.toRadians(225); double lat2,lon2; System.out.println("Hello World"); //lat2 = Math.sin(); lat2 = Math.asin(Math.sin(Radlat1)*Math.cos(d/R) + Math.cos(Radlat1)*Math.sin(d/R)*Math.cos(brng)); System.out.println("Lat2degree"+"="+Math.toDegrees(lat2)+"\n"+"Lat2="+lat2); double NewRadLat2 = Math.toRadians(Math.toDegrees(lat2)); lon2 = Radlon1+Math.atan2(Math.sin(brng)*Math.sin(d/R)*Math.cos(Radlat1), Math.cos(d/R)-Math.sin(Radlat1)*Math.sin(lat2)); System.out.println("Lon2"+"="+Math.toDegrees(lon2)); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7582614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JSF 2 - Unique ids across multiple pages I'm looking to create a JSF application in which there are multiple xhtml pages displayed in different regions of the browser. I could do this with iframes but they add extra memory and accessing objects across iframes is not that trivial. I am considering an approach in which I load different xhtml pages within the main page using ajax. The problem is that there will be many elements within the main page that will have the same ids, since the ids are unique only within their respective view roots. I know 1 solution would be to implement some custom client side logic that handles these duplicate ids, but it would be better to just not have duplicate ids at all. What can i do to solve the problem? A side question: Is there a framework that handles such a requirement better, i.e. having multiple pages displayed within the same browser window? A: You could replace the view root with one that implements NamingContainer: <?xml version='1.0' encoding='UTF-8'?> <faces-config version="2.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <component> <component-type>javax.faces.ViewRoot</component-type> <component-class>components.ReplacementRoot</component-class> </component> </faces-config> This sample implementation creates a clientId based on the viewId: public class ReplacementRoot extends UIViewRoot implements NamingContainer { @Override public String getClientId(FacesContext context) { return "jsf" + getViewId().replaceAll("[^\\p{Alnum}]", "_"); } } This will generate client identifiers of the form jsf_index_xhtml:foo. A: Have a look on the Portlet technology since probably this is what you want. The problem is that I haven't seen yet really good portlet implementations, and also that you need a JSF portlet bridge in order to handle the JSF lifecycle - don't know the state of that either. Another option would be to create your own facelets provider, that adds dynamically whatever components you need, so when you rebuild the component tree, they will suddenly appear. I couldn't tell you more about that either, but I've seen it done and working for some wiki-like software that was editing the pages as facelets xhtml.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jquery error Object doesn't support this property or method error I have a ruby application. I am getting the error "object doesn't support this property or method" which corresponds to the following line in my application.js file. $('textarea.autoresize').autoResize({ onResize : function() {$(this).css({opacity:0.8});}, animateCallback : function() {$(this).css({opacity:1});}, limit: 300 }).change(); Please let me know what changes are required.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why does fopen fail when given value from main( argv[]) this is my program #include <ncurses.h> int main( int argc, char *argv[] ) { initscr(); FILE *fd; char *ProgFile; ProgFile = argv[1]; printw(ProgFile); refresh(); fd = fopen(ProgFile,"rb"); if( fd==NULL ) { printw("error"); perror ("The following error occurred"); refresh(); } else { printw("bin file loaded: '%s'",ProgFile); refresh(); } getch(); endwin(); return 0; } when run it given this error message: No such file or directory. but if i hardcode ProgFile = "filemname.bin"; then the program works perfectly. when the program is run both versions print filemname.bin when asked the value of ProgFile. I have been trying to solve this for 2 days and have no idea what is happening. can anyone tell me what is wrong ? this is c++ on linux centos A: First, this is C and not C++. I don't see any C++ in your code. This #include <stdio.h> #include <stdlib.h> int main( int argc, char *argv[] ) { FILE *fd; char *ProgFile; ProgFile = argv[1]; printf(ProgFile); fd=fopen(ProgFile,"rb"); if( fd==NULL ) { printf("error"); } else { printf("bin file loaded: '%s'",ProgFile); } return 0; } Works perfectly fine for me. Make sure you're passing the right argument and the correct path. I suggest you passing the whole path, and not just filemname.bin. A: A program looks for relative filenames (those not starting with /) in its present working directory; this is inherited from the parent, which is the shell if you execute the program from the command line, and can be set explicitly when you run it from a starter. So, you need to make sure the program is started in the same directory that the file is in. (You could also use an absolute path or do an explicit chdir system call the directory where the file is, but both are ugly and make it pretty much impossible to move the program around.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7582619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I return multiple arrays from a method? Say that I wanted to return 6 arrays from one method to another (in another class). What is the best way of doing this and why? This is what I have so far. public Object getData()throws FileNotFoundException{ counter = 0; Scanner f = new Scanner(new File("Contacts.txt")).useDelimiter(","); while (f.hasNext()){ firstNames[counter] = f.next(); lastNames[counter] = f.next(); emailList[counter] = f.next(); ageList[counter] = f.next(); imgLoc[counter] = f.nextLine(); counter++; } f.close(); firstNames = Arrays.copyOf(firstNames, counter); lastNames = Arrays.copyOf(lastNames,counter); emailList = Arrays.copyOf(emailList, counter); ageList = Arrays.copyOf(ageList, counter); imgLoc = Arrays.copyOf(imgLoc, counter); data = Arrays.copyOf(data, counter); for (int i = 0; i <= counter - 1; i++){ data[i] = firstNames[i] + " " + lastNames[i] + ", " + ageList[i]; } ArrayList<Object> arrays = new ArrayList<Object>(); arrays.add(firstNames); arrays.add(lastNames); arrays.add(emailList); arrays.add(ageList); arrays.add(imgLoc); arrays.add(data); return arrays; } Using an ArrayList was a guess. I'm not sure if I'm headed in the right direction there. A: I think this is a terrible idea. I'd prefer one object that encapsulates first, last, email, age, and image into a Person class and return a List of those. Java's an object-oriented language. You'll do better if you stop thinking in terms of primitives like Strings, ints, and arrays and start thinking in terms of objects. Encapsulate things that are meant to be together into a single object whenever you can. Here's how I'd write that method: public List<Person> readPersons(File file) throws FileNotFoundException { List<Person> persons = new LinkedList<Person>(); Scanner f = new Scanner(file).useDelimiter(","); while (f.hasNext()){ String first = f.next(); String last = f.next(); String email = f.next(); String age = f.next(); // age ought to be a positive integer String imageLocation = f.nextLine(); persons.add(new Person(first, last, email, age, imageLocation)); } return persons; } Less code, and easier to understand. A: Cleaner implementation (though lacking in error checking...) public class Person { private final String fName; private final String lName; private final String email; private final String age; private final String imgLoc; public Person(String fName, String lName, String email, String age, String imgLoc) { super(); this.fName = fName; this.lName = lName; this.email = email; this.age = age; this.imgLoc = imgLoc; } /* ...Getters here... */ } public Object getData()throws FileNotFoundException{ ArrayList<Person> out = new ArrayList<Person>(); Scanner f = new Scanner(new File("Contacts.txt")).useDelimiter(","); while (f.hasNext()){ out.add(new Person( f.next(), f.next(), f.next(), f.next(), f.next() )); } f.close(); return out; } A: Here's what I would do: public static class Person { public final String firstName, lastName, email, age, imgLoc; Person(String firstName, String lastName, String email, String age, String imgLoc) { this.firstName = firstName; this.lastName = lastName; this.email = email; this.age = age; this.imgLoc = imgLoc; } } public List<Person> getData() throws FileNotFoundException { ArrayList<Person> list = new ArrayList<Person>(); Scanner f = new Scanner(new File("Contacts.txt")).useDelimiter(","); while (f.hasNext()) { list.add(new Person(f.next(), f.next(), f.next(), f.next(), f.nextLine())); } f.close(); return list; } Update: An almost identical answer was posted by claymore1977 as I was writing this. The only notable difference is that I declared the type of the method to be List, which is what it actually is, while he retained your declared type of Object. Update 2: Oh, one more difference. He declared members of the return class private, with getters, while I used public fields. Since they are final, I would not bother with getters, but it's a matter of taste.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ASPxColorEdit custom colors I'm using the latest ASPxEditor controls of devexpress.As you know this control has pre-defined colors.In my case I need to change these colors and put my custom palette into this control. Is it possible to do so ? What are the alternatives ? Best Regards A: It seems that, at present, the ASPxColorEdit control does not offer such a functionality. There is a corresponding request regarding this feature: http://www.devexpress.com/issue=S33198
{ "language": "en", "url": "https://stackoverflow.com/questions/7582629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SimpleModal - Callback function not working -- On click of Yes I wanted to send custom confirm message to SimpleModal . But on click of Yes , its not triggering callback function. on click of close button , I want to fire Simple modal confirm box . I have many places were i want this functionality . That's why dint wanted to hard-code message inside div tag. Please see below code and let me know how can i make this work . thanks in advance . jQuery(function($) { $('#btn').click(function(e) { e.preventDefault(); // example of calling the confirm function // you must use a callback function to perform the "yes" action confirm("", function() { window.location.href = 'http://www.google.com/'; }); }); }); function confirm(message, callback) { // alert("1"); $('body').append('<div id="container"><div id="confirm" style="display:none"><div class="header"><span>Confirm</span></div><div class="message">' + message + '</div><div class="buttons"><div class="no simplemodal-close">No</div><div class="yes">Yes</div></div></div><div style="display: none"><img src="skin/img/header.gif" alt="" /><img src="skin/img/button.gif" alt=""/></div></div>'); $('#confirm').modal({ closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>", resizable: false, position: ["20%", ], overlayId: 'confirm-overlay', containerId: 'confirm-container', onButtonClick: function(dialog) { var modal = this; // if the user clicks "yes" $('.yes', dialog.data[0]).click(function() { // call the callback if ($.isFunction(callback)) { callback.apply(); } // close the dialog modal.close(); // or $.modal.close(); }); } }); } HTML code below : <!DOCTYPE html> <html> <head> <title> Confirm Modal Dialog </title> <!-- Confirm CSS files --> <link type='text/css' href='skin/confirm.css' rel='stylesheet' media='screen' /> <!-- JS files are loaded at the bottom of the page --> </head> <body> <input id="btn" type='button' name='confirm' value='Close' onclick="return confirm('Are you sure?');" /> <script type='text/javascript' src='jquery/jquery.js'></script> <script type='text/javascript' src='jquery/jquery.simplemodal.js'></script> <script type='text/javascript' src='jquery/confirm.js'></script> </body> </html> A: You shouldn't be appending the confirm dialog code to the page with jQuery. By appending it after the DOM is loaded, the plugin can't find the ".yes" button. Your dialog should already be on the page and set to "display:none". The following code will make any button on your page with the class "confirm" produce a confirm dialog (assuming you have correctly included all the plugin JS files). CSS: #confirm {display:none;} HTML: <input type='button' class='confirm' value='Click to Confirm'/> <!-- modal content --> <div id='confirm'> <div class='header'><span>Confirm</span></div> <div class='message'></div> <div class='buttons'> <div class='no simplemodal-close'>No</div><div class='yes'>Yes</div> </div> </div> JS: $('.confirm').click(function (e) { e.preventDefault(); confirm("Confirm yes or no", function () { alert('yes clicked'); }); }); Working example here: http://jsfiddle.net/YzRpP/2/
{ "language": "en", "url": "https://stackoverflow.com/questions/7582632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best Practice using reusable Actions on GUI Components I tried differend things on how to make Actions resuable in my Swing applications. I am not a friend on heavy-weight, 1000+ line classes (with lots of inner/anon classes) and try to split my code up into multiple classes. Thus make them resuseable and exchangeable easily. For reusing same Actions in an application I made for every Action its own class to use it in JMenuBar and JToolBar. Please have a look at the minimal example below. Is this a good choosen practice (esp. using static inner classes)? public class SomeGUI extends JFrame { public static void main(String[] args) { new SomeGUI(); } public SomeGUI() { setJMenuBar(new MyMenuBar()); add(new MyToolBar()); setSize(400, 400); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } } class MyMenuBar extends JMenuBar { JMenu menu = new JMenu("File"); public MyMenuBar() { add(menu); menu.add(new JMenuItem(new Actions.NewAction("New", null, "New File", KeyEvent.VK_N))); } } class MyToolBar extends JToolBar { public MyToolBar() { add(new Actions.NewAction("New", null, "New File", KeyEvent.VK_N)); } } class Actions { static class NewAction extends AbstractAction { public NewAction(String name, ImageIcon icon, String desc, Integer mnemonic) { super(name, icon); putValue(SHORT_DESCRIPTION, desc); putValue(MNEMONIC_KEY, mnemonic); } @Override public void actionPerformed(ActionEvent paramActionEvent) { System.out.println("do the new action..."); } } } Looking forward for your advises. Thanks in advance. A: One suggestion would be not to use an aggregate class which holds all actions. Just use a separate file for each class and make it public. This way for using the class in another project you would just need to copy the file assuming it has no specific dependencies in current project. A: Is this a good choosen practice (esp. using static inner classes)? This is the way much of the base Swing code is implemented. For example take a look at the source code of DefaultEditorKit where all the Actions are defined. A: What I often do (and it's even easier when using GutsAction from guts-gui project) is that I group related actions in one class. I store each action as a final public field (but if you hate public fields you can still make them private and dfine a getter method on each). Each action is defined as a tiny anonymous class where the final field is declared. The criteria for grouping are essentially functional but they can also include some context, e.g. you can have a class that include various actions that perform on the currently selected order (from an order JTable), thus I can put the context (current selected order) in only one class, and I can also put there the necessary methods to enable/disable all actions when selection changes. Having grouped actions in one class helps avoid proliferation of action classes all over the place and having to manage instantiation of each individual action. It also enables easier Dependency Injection of dependencies common to several actions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: WebKitErrorDomain error 101 (in mapview) here is my code i get this error NSString *url = [NSString stringWithFormat:@"%@?lat=%@&long=%@", [[NSBundle mainBundle] pathForResource:@"map" ofType:@"html"], @"17.734503", @"83.2999716"]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]]; DirctionWeb.delegate = self; [DirctionWeb loadRequest:request]; so here i connect webpage into google map html page why this error message please guide me A: Make sure the url isproperly encoded and has the +- on the lat and long, like so: NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://maps.google.com/?q=+17.734503,+83.2999716"]]; DirctionWeb.delegate = self; [DirctionWeb loadRequest:request]; So, replace this: NSString *htmlFile = [NSString stringWithFormat:@"%@?lat=%@&long=%@",                  [[NSBundle mainBundle] pathForResource:@"map" ofType:@"html"],                  @"17.734503",                  @"-83.2999716"]; With: NSString *htmlFile = [NSString stringWithFormat:@"%@?lat=+.000000f&long=%+.000000f",                  [[NSBundle mainBundle] pathForResource:@"map" ofType:@"html"],                  @"17.734503",                  @"-83.2999716"];
{ "language": "en", "url": "https://stackoverflow.com/questions/7582635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Servlet 3.0: where is @WebServletContextListener? I am trying to follow a Servlet 3.0 tutorial which refers to @WebServletContextListener. However, I cannot find such an annotation in my javaee-web-api-6.0.jar dependency (I am using maven). So, where is @WebServletContextListener? A: The annotation is called @WebListener. And you still have to implement ServletContextListener.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: How to get a drop down menu in asp.net master page? In my master page I have a table and inside that table I have these, This is for displaying the username after user login to the website. I want to have a icon when clicked it should display signout, changepassword. How can I do that. Something similar like facebook where there is a inverted triangle whenclicked displays privacy setting. <td class="style1"> <asp:Label ID="Label_Welcome" runat="server" Text="Welcome:"></asp:Label> </td> <td> <asp:Label ID="Label_UsereName" runat="server" Text="Label"></asp:Label> </td> A: You will need to look into some javascript code which will show/hide your options. jQuery Toggle or jQuery Show would be a good place to start. A: this type menu can be made using jquery refer to this link Facebook Style CSS JQuery drop down menus
{ "language": "en", "url": "https://stackoverflow.com/questions/7582639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding UIActivityController on the splash screen I took a default.png file and made it as my splash screen and i made it sleep for a few seconds to make it visible. But i also want to add an UIActivityController to it. As i didn't take any ViewController. How should i add it? - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { _homeViewController = [[XTHomeViewController alloc]initWithNibName:kHOME_VIEW bundle:nil]; _navigate = [[UINavigationController alloc]initWithRootViewController:_homeViewController]; [self.window addSubview:_navigate.view]; [self.window makeKeyAndVisible]; [NSThread sleepForTimeInterval:0.75]; return YES; This is All i Have. A: There is no way using UIActivityController but you can do it following way First of all, you take in .h file IBOutlet UIProgressView * threadProgressView; in .m file // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { threadProgressView.progress = 0.0; [self performSelectorOnMainThread:@selector(makeMyProgressBarMoving) withObject:nil waitUntilDone:NO]; [super viewDidLoad]; } //For progress bar - (void)makeMyProgressBarMoving { float actual = [threadProgressView progress]; if (actual < 1) { threadProgressView.progress = actual + 0.02; [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(makeMyProgressBarMoving) userInfo:nil repeats:NO]; } A: You can add Activityindicater like this in DemoappeDelegate.h file IBOutlet UiView *splashView; in DemoappDelegate.m - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { UIActivityIndicatorView *spinningWheel = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(145.0, 290.0, 25.0, 25.0)]; [spinningWheel startAnimating]; spinningWheel.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray; [splashView addSubview:spinningWheel]; [spinningWheel release]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7582641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: java.awt.Desktop.browse returns "The requested lookup key was not found in any active activation context" only on Win XP I use the following code to access the default browser from java when a button is clicked: if( !java.awt.Desktop.isDesktopSupported() ) { System.err.println( "Desktop is not supported (fatal)" ); } java.awt.Desktop desktop = java.awt.Desktop.getDesktop(); if( !desktop.isSupported( java.awt.Desktop.Action.BROWSE ) ) { System.err.println( "Desktop doesn't support the browse action (fatal)" ); } String number = txtInCall.getText(); String uriString = "http://localwebserver/new?number="+number; //number only contains numbers similar to 023456789 try { java.net.URI uri = new java.net.URI( uriString ); desktop.browse( uri ); } catch ( Exception ex ) { System.err.println( ex.getMessage() ); } The programm works well on Windows 7 Home Premium x64. If I test it on Windows XP Professional x32 SP3 the console returns: "The requested lookup key was not found in any active activation context". I googled about it and found out, that the error occurs in connection with Internet Explore. The default browser on the tested machines howerer is Mozilla Firefox 6.0.2. I also checked the registry and the http-protocol is registered for firefox.exe and I updated IE. The other question about this error did not help me either. On the XP machine a click always returns the mentioned error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use photoshop graphic files (*.psd?) in xcode? I heard that I can directly import photoshop psd file into a XCode project to use the images provided by the psd file. However, i could not find a way to import the psd file into the interface builder. Can some expert help me out here? How do i make use of a psd file? Or what is the another file format i need to use? thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7582645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP Regex and enter problem Code (preg_match_all("#\[level-(.+)-\](.+?)\[/level\]#", $string, $matches) Problem if I assign any value to $string with enter, my regex doesn't work. Example: //This doesn't work $string = '[level-0-]This is a test[/level]'; //This works $string = '[level-0-]This is a test[/level]'; What I Want I would like my regex to work no matter what characters between (enter, etc..). I will be glad if anyone could help me out with this one. I still didn't dig into regex yet so I'm not that good with it :( A: You just need the DOTALL flag /s in your regex. This allows the dot . to match any character, including linebreaks (which it doesn't do per default). preg_match_all("#\[level-(.+)-\](.+?)\[/level\]#s", .... See also the PCRE flags list http://php.net/manual/en/reference.pcre.pattern.modifiers.php A: You probably need to get regex to treat its input as a single line by adding the /s flag to your pattern. A: Use s Pattern Modifier: If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. (Ref: Possible modifiers in regex patterns) A: this should work : (preg_match_all("#\[level-(.+)-\](.+?)(\b)*(.+?)*\[/level\]#", $string, $matches) A: "Test[.|\n]is[.|\n]a[.|\n]test" this might work
{ "language": "en", "url": "https://stackoverflow.com/questions/7582652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: which causes the custom button text update UI Thread (or) onDraw in Android I subclassed a class to Button and overriden the onDraw() method. And have written a handler in the constuctor of the class where I am updating a variable whose value has to be updated to that button text. Below is the code snippet, public class CustomButton extends Button{ CustomButton(){ handler = new Handler(); Runnable runObj = new Runnable(){ public void run(){ counter++; handler.postDelayed(this,1000); } }; handler.post(runObj); } @Override protected void onDraw(Canvas canvas){ super.onDraw(canvas); setBackgroundResource(R.drawable.button9patch); setTextColor(COMPONENTTEXTCOLOR); setText(counter); } } Well the button text gets updated. I know that the onDraw() method gets called when the button gets rendered initially and when we do some amendments to the button view like setting the label or image etc.,. Here in my code I am updating the counter outside of the onDraw() method, but calling the setText(counter) explicitly from onDraw() method. As I am not calling setText(counter) from the Hanlder code How it is updating the button text periodically? Is it that the UI thread that causes the counter variable changes updated to the button periodically? I am confused. Thanks A: You are never starting the Handler for the first time. handler.postDelayed(runObj,1000); Update: Every time you update the counter you must force the button to redraw itself: counter++; CustomButton.this.postInvalidate();
{ "language": "en", "url": "https://stackoverflow.com/questions/7582655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Password Encoding and Decoding on iOS Is there any API for encoding or decoding a password to text in iPhone? A: There is the Common Crypto API. #import <CommonCrypto/CommonCryptor.h> + (NSData *)doCipher:(NSData *)dataIn iv:(NSData *)iv key:(NSData *)symmetricKey context:(CCOperation)encryptOrDecrypt { CCCryptorStatus ccStatus = kCCSuccess; size_t cryptBytes = 0; // Number of bytes moved to buffer. NSMutableData *dataOut = [NSMutableData dataWithLength:dataIn.length + kCCBlockSizeAES128]; ccStatus = CCCrypt( encryptOrDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding, symmetricKey.bytes, kCCKeySizeAES128, iv.bytes, dataIn.bytes, dataIn.length, dataOut.mutableBytes, dataOut.length, &cryptBytes); if (ccStatus != kCCSuccess) { NSLog(@"CCCrypt status: %d", ccStatus); } dataOut.length = cryptBytes; return dataOut; } Also add Security.framework to your project. If the security is important consider having someone with security experience create the code and protocol. If the security is not important, just send the password in the clear. A few bugs in an app is not that bad, the app still basically works, one bug in security and all security is lost. Good security is not as easy as one might think. A: If you are only interested in passwords you might as well use hash functions (md5, sha) and compare the input hash with the hash of the password. That way the password is never saved in plaintext and if your server gets hacked some day they only get the hashes and have to do a pre-image attack in order to get the password. A: What you want to do is use the Security Framework. This web site provides you with examples: Symmetric encryption: http://greghaygood.com/2009/01/17/symmetric-encryption-with-the-iphone-sdk-and-securityframework Asymmetric encryption: http://greghaygood.com/2009/01/17/asymmetric-encryption-with-the-iphone-sdk-and-securityframework I hope this helps... Emmanuel
{ "language": "en", "url": "https://stackoverflow.com/questions/7582657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is there a way in C++ to create 'super private' variables? I had an idea for a feature for C++, and I was wondering if it was possible to create. Let's say I want a private variable in 'MyClass' to be accessible only by two functions, the public getter and setter. That is, if another public or private function of MyClass tries to get or change the value of my super-private variable, I will get a compile error. However, the getter and setter behave normally. Any ideas? Edit 1: A use case is having the getter/setter perform error checking or other form of logic. I wouldn't want even the class itself touching the variable directly. Edit 2: Something like this then: template <class T> class State{ private: T state; public: State() { state = 0; } T getState() { return state; } void setState(T state) { this->state = state; } }; And then any class can inherit it and access 'state' only through the getter/setter. Of course, the class is useless without modifying the getter and setter according to your desired logic. A: The granularity of accessibility in C++ is the class. So if you need to make a variable accessible to only two methods you need to move the variable and the two methods into a separate class, dedicated to maintaining privacy.. A: I would put a very ugly name to the variable, and a nice one to the getter/setter: class Foo { private: int _hey_do_not_use_me_im_super_private_whatever; public: int get_whatever() const { //extra logic return _hey_do_not_use_me_im_super_private_whatever; } void set_whatever(int we) { //extra logic _hey_do_not_use_me_im_super_private_whatever = we; } }; A comment expaining what super-private means will be most welcome by the people that inherits your code. A: You could wrap the variable in a class and make it private there and a const T& getter. Than you declare the get and set member functions of the containing class as friends to that wrapper. Now you keep the wrapper class as a member in your original class. That should achieve what you want albeit it looks hard to maintain and not very useful. So here is some dummy implementation that shows how this would work (Note that the whole new VeryPrivateWrapper business is just a wacky way around declarations, a unique_ptr would be more helpful): class VeryPrivateWrapper; class Original { VeryPrivateWrapper* m_wrapper; public: Original(); // imagine that I remembered the rule of three here void set(int); void other(); }; // make this a template for more fun class VeryPrivateWrapper { int m; public: const int& get() const { return m; } // !!! // the important bit // !!! friend void Original::set(int); }; Original::Original() : m_wrapper(new VeryPrivateWrapper) {} void Original::set(int i) { m_wrapper->m = i; } void Original::other() { // this borks as we would like // m_wrapper->m = 23; } int main() { Original o; o.set(3); return 0; } A: I believe this is what you asked for. Is it desirable? Some people will think this is an abomination. If you decided to use it, you'll probably want to pull out the public Get and Set from the macro and write those manually. #define SUPER_PRIVATE(c,t,m) \ template <typename C, typename T> \ class SuperPrivate##m { \ friend T& C::Get##m(); \ friend void C::Set##m(const T&); \ T value; \ }; \ public: \ t& Get##m() { return m.value; } \ void Set##m(const t& value) { m.value = value; } \ private: \ SuperPrivate##m<c,t> m; class SomeClass { public: SomeClass() { SetX(42); SetY(58); } int DosomethingWithX() { return GetX() * 2; } // int DosomethingWithX2() { return X.value * 2; } // error // int DosomethingWithX3() { return X; } // error SUPER_PRIVATE(SomeClass, int, X); SUPER_PRIVATE(SomeClass, int, Y); }; int main() { SomeClass someObject; int x1 = someObject.GetX(); int y1 = someObject.GetY(); someObject.SetY(89); int y2 = someObject.GetY(); int x2 = someObject.DosomethingWithX(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7582664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: How can I identify that the GridViewRow is in edit mode before leaving or Navigating to other page? Possible Duplicate: How can I identify the edited row in GridView? My client wanted the GridView to display fields inside TextBoxes, and DropDownListBoxes only. He wanted the flexibility to update the Record just by clicking on the Update button after altering the values in the cell. If user forgets to click on "Update" button for the current editing record before he navigates to some other page, then the program should prompt the user with the message "Do you want to save changes made to Emp.No 1003?" with "Yes", "No" options. If user selects "Yes" then the Emp record should be updated in the database. If users selects "No" then those changes should be discarded. Can anybody please tell how can I achieve this requirement? A: You can achieve this using some javascript and calling the window.onbeforeunload method. Probably best have a global variable in your javascript code var changesMade = false;, Then when the user clicks on the Edit button, or makes changes, set the global variable to true. Then in your window.onbeforeunload method use this code: $(function(){ window.onbeforeunload = function () { if (changesMade) { return "You have unsaved changes. Please Save all changes."; // customize this msg accordingly. } } }); Please note I am using jQuery here to set up the method once the DOM has loaded.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: WP: shortcodes when using if(have_posts()) followed by while(have_posts()) I'm trying to minimize my code and have put together this little snippet, it doesn't seem to work however. What am I missing? query_posts( 'year=2011' ); if ( have_posts() ); while ( have_posts() ); echo 'test'; endwhile; wp_reset_query(); endif; A: I think that your problem is the question mark at the end of the if and at the end of while. IMy opinion is that you need a colon ":" query_posts( 'year=2011' ); if(have_posts()): while(have_posts()): echo 'test'; endwhile; wp_reset_query(); endif;
{ "language": "en", "url": "https://stackoverflow.com/questions/7582674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Special Characters NSString I have a NSString I am trying to declare so I can use it as an applescript. here is the code: NSString *script1 = @"do shell script /usr/bin/php -r ($mac = \"g1:ag:g3:cg:gg:eg\"; $porttemp = \"9\"; $ip = \"255.255.255.255\"; $mac_bytes = explode(\":\", $mac); $mac_addr = \"\"; for ($i=0; $i<6; $i++) $mac_addr .= chr(hexdec($mac_bytes[$i])); $packet = \"\"; for ($i=0; $i<6; $i++) /*6x 0xFF*/ $packet .= chr(255); for ($i=0; $i<16; $i++) /*16x MAC address*/ $packet .= $mac_addr; $port = $porttemp; $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, TRUE); socket_sendto($sock, $packet, strlen($packet), 0, $ip, $port); socket_close($sock); );" The Problem I am facing it that xcode says I am not terminating it and gives a whole bunch of errors. Any idea how I can solve it or have I got anything wrong? A: You must surrond every row with "". Like: NSString *HelloWorld = @"Hello" " World"; What you are doing is: NSString *HelloWorld = @"Hello World"; which is not valid. [Edited to correct code display, so example makes sense as line breaks were being removed.]
{ "language": "en", "url": "https://stackoverflow.com/questions/7582675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTML website & jquery webpage for mobile My expertise is somewhat limited, but I have a HTML5 website which works well on screen and tablets, but not so good on mobile devices. My thoughts are for creating a jquery Mobile website just for mobile devices; as it's mainly all text. So my question is how can I link the two sites, so the main website will be available for all devices bar mobile, in which case the jquery Mobile website will be displayed? Can this be achieved and how? A: An alternative to using jQuery would be styling your website based on the screen resolution of the device the user is using. You can use CSS Media Queries (would post link, but my reputation isn't high enough to do more than two; check the css-tricks.com website for "CSS Media Queries & Using Available Space") to create styles based on screen resolution. Alternatively, there are some other options that can specify how the website is viewed by using meta viewport tags and javascript. See here for some information of how this can be accomplished. If you still wanted to use jQuery Mobile, you could detect the device by using a user agent match in javascript. Here some information on that: Loading JS script for only iOS devices? Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7582677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP batch print Ι'm working on a project where a user creates a number of contracts (stored in a MySQL database) and then needs to print them all at once on his printer. I can't think of a way to perform this using PHP. I would like to simulate the browser printing process programatically for the number of contracts (ie, print contracts 1-50) in other words, how to print a large number of contracts at once without having to open each one on the browser and printing it from there. Let me know if you need any further explanation. Thanks. A: PHP is server-side, it has nothing to do with client-side printing. Rather use javascript's window.print . However you cannot set print properties, that's left for the user to decide.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ViewPager problem As give in this document . I did the same.While running i am using a emulator which has android 2.3.3(means API 10 ) support. It is showing no compatible device found.Any idea from any body plz share. A: You need to use the android compatibility package and you can set the min sdk to 4 (1.6). I have created a demo app in a post of my blog. Feel free to grab the code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Apple like search box I need exactly the same search box of apple.com for my website. I tried to grab it but no success. Can anyone help me to create something like that or grab it from apple.com? http://jsfiddle.net/gHSp2/1/ A: That's what you're looking for http://www.bloggermint.com/2011/06/css3-search-box-inspired-by-apple-com/ A: This is probably what you want: <style> #search{ width : 100px; background-color:gray; -webkit-transition: all 0.3s linear; -moz-transition: all 0.3s linear; border-radius : 15px; outline:none; } </style> <input id='search' onfocus='this.style.width="120px";this.style.backgroundColor="white"' onblur='this.style.width="100px";this.style.backgroundColor="gray"'> Demo A: Try this their's part of code: <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <link id="globalheader-stylesheet" rel="stylesheet" href="http://images.apple.com/global/nav/styles/navigation.css" type="text/css" /> <title>Apple</title> </head> <body> <script type="text/javascript"> var searchSection = 'global'; var searchCountry = 'us'; </script> <script src="http://images.apple.com/global/nav/scripts/globalnav.js" type="text/javascript" charset="utf-8"></script> <nav id="globalheader" class="apple"> <div id="globalsearch"> <form action="/search/" method="post" class="search" id="g-search"><div class="sp-label"> <label for="sp-searchtext">Search</label> <input type="text" name="q" id="sp-searchtext" accesskey="s" /> </div></form> <div id="sp-magnify"><div class="magnify-searchmode"></div><div class="magnify"></div></div> <div id="sp-results"></div> </div> </nav> <script type="text/javascript"> AC.GlobalNav.Instance = new AC.GlobalNav(); </script> <!-- SiteCatalyst code version: H.8. Copyright 1997-2006 Omniture, Inc. --> </body> </html> Use js beautifier for theirs globalnav.js and inspect it for just want to know how it works
{ "language": "en", "url": "https://stackoverflow.com/questions/7582688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: two's complement finding algorithm I am trying to see how compiler writes in binary negative numbers, so here is code which should do it #include <cstdlib> #include <iostream> using namespace std; void complement(int n) { int l = n; int s = 0; int k = 0; int m = 0; while (n != 0) { s = n % 2; n /= 2; cout << s << " "; } cout << endl; m = ~l + 1; cout << m << endl; cout << endl; while (m != 0) { int k = m % 2; m /= 2; cout << k << " "; } } int main(int argc, char *argv[]) { int n; cin >> n; cout << endl; complement(n); system("PAUSE"); return EXIT_SUCCESS; } but strange is that, when I enter 5, for instance, which clearly in binary form is 101 in 3 bit, its complement -5 is represented -10-1? This is what my code's output shows me, but I know that is it not correct, because 2's complement of any number is given by reversing its bits, 0 by 1 and vice-versa, and then +1, in case of 5(101), -5 will be (010+1)=(011). Please help me, how to correct my code so that, it could make complement correctly. A: If you want to see the bits of number you better use such constructs: int main(int argc, _TCHAR* argv[]) { int i = -10; //my value std::string result; for (int bit = 0; bit < sizeof(int)*8; ++bit) { int bit_val = 1 & i; result = (bit_val ? "1" : "0") + result; i = i >> 1; } std::cout << result << std::endl; } A: The simplest way to see the bits in C++ is to use std::bitset. It supports iostream output and conversion to/from string. Like this: #include <stdio.h> // printf #include <limits.h> // CHAR_BIT #include <bitset> int main() { int const bitsPerByte = CHAR_BIT; int const bitsPerInt = sizeof( int )*bitsPerByte; int const m = -10; std::bitset<bitsPerInt> bits( m ); printf( "%d in decimal is %s in %d-bits binary.\n", m, bits.to_string().c_str(), bitsPerInt ); } Output: -10 in decimal is 11111111111111111111111111110110 in 32-bits binary.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Php security question about post validation Is the following a valid way to validate some info coming from a post? function validate($age, $name, $sex) { $pdo = new PDO(...); $age = (int)$age; $name = $pdo -> quote($name); $sex = (strtolower($sex) == "m" ? "m" : "f"); // and then process data with pdo's query method. } Do you see any security flaw in this function? If yes, can you help me to fix them? A: Not quite. That's pretty common mistake among PHP users. Here is a rule you are breaking in your code: Do not mix data validation with sql security. Data validation is one matter and sql security is another. Data validation rules may change. Sql security rules shouldn't. Although your current code is safe, the very idea of asking such a question is wrong. You have to use sql protection techniques unconditionally, despite of the data source and contents. That's the only way to be sure. Besides that, there is just no point in creating different rules for the different fields. Just run your validation and after that you have to call just the code like this $db->insert($table,$data); and let the internals do care of the data (knowing nothing of it's safety, validness or whatever else nonsense). Got the point? A: That's totally valid and secure as you won't receive any SQL Injections. Btw, if you will repeat the query, rather than pdo->query go for prepared statements.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I use railties to install files other than migrations (for e.g. config files) I'm using Rails 3.1 and I am able to use railties to install migrations (by doing rake railties:install:migrations FROM=plugin_name). However, I have a couple of config files (.yml, etc.) that I need to copy over as well. How do I do this ? A: For example see the code in a gem i created: https://github.com/nathanvda/on_the_spot/blob/master/lib/generators/on_the_spot/install/install_generator.rb Simply put: use thor commands, like copy_file. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: OpenSource .net SMS library, I can't seem to find one at all for C# I've been using GSM modems in my projects to send/recieve SMS-s. I have been using built-in serial port communication features of .net to do this by using standard AT commands. Now I have to extend its functionality (like SMSs in PDU mode, more efficient delivery report handling etc). I don't wanna reinvent the wheel, so first I'd like to know if there is a good open source project or a free library on this topic. It should send/recieve sms in text and pdu mode, handle delivery reports. I've googled it, but I have not found an efficient one so far. Platform: Windows/.net4/vs2010/c# A: Since, you are not looking for just a client library, you need to deploy your own SMS gateway. This is what you need A: I accually wrote my own SMS library in C#, back in 2005. My aim was to create a commercial library out of it, but it just never happened; besides this is probably my 1000 th project that has never been released... Anyway I decided to change that - because of this question - and will now start to release much of my superfine code under MIT license (free, free, free). https://github.com/johanssonrobotics/FJR.SmsSolution (click the link, then the "Zip" button on GitHub to download) Anyway, as I said, I wrote most of the code in 2005, but did some heavy refactoring to it about a year ago, so it should be solid. Anyway, feel free to test it. Comes with a demo Windows-forms application. For instance, this could be used to connect a phone via COM-cable and send/receive SMS-messages. Easily. Have fun & hope this helps! A: If you are planning to use a local phone/gsm modem via serial you can use the following. http://www.codeproject.com/KB/cs/SMS.aspx?msg=2961173 http://www.codeproject.com/KB/windows/smspdulib.aspx Local serial sending will be quite slow and not good for high volume sending of messages. If you need to send high volume of sms you will need to use some sort of sms gateway. A: Have you looked into the APIs provided by Tropo? I haven't used it but I gathered that if you use your own gateway, it's free, and if use theirs, it's reasonably priced. A: I have found this just now: Does anybody has experiences wit it? A: Tom, You should be able to use the .NET CE Framework (from within Windows) to accomplish this. Sending SMSs from your Microsoft .NET Compact Framework-based Applications .NET Compact Framework has built-in handling for sending SMS-s and PDU over a GSM operator and it's fairly well documented. Also, while not straight .NET, you have options available in the base mobile/broadband api's, it's straight Windows, and can be wrapped/imported using standard .NET technologies. http://msdn.microsoft.com/en-us/library/windows/desktop/dd323268%28v=VS.85%29.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7582696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Hello World Library using autotools Creating bin program is really easy using autotools I need to just define two files. `Makefile.am' bin_PROGRAMS = hello hello_SOURCES = hello.c `configure.in' AC_INIT(hello.c) AM_INIT_AUTOMAKE(hello,1.0) AC_PROG_CC AC_PROG_INSTALL AC_OUTPUT(Makefile) can any body give a smallest example for creating static library using autotools ? A: Makefile.am: lib_LIBRARIES = libhello.a libhello_a_SOURCES = hello.c configure.ac: AC_INIT([libhello], [1.0], [bug@libhello.org]) AM_INIT_AUTOMAKE([-Wall -Werror foreign]) AC_PROG_CC AC_PROG_RANLIB AC_CONFIG_FILES([Makefile]) AC_OUTPUT The documentation for building libraries with Automake is here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Adding an Event Handler with Mootools' .addEvent() fails mysteriously in a certain place I'm having a rather mind-boggling problem with some JS I'm working on for a web app. Unfortunately, I can't post the full code for this, as it's part of a not-yet-released project. This issue has both me and some colleagues I asked stumped - from what I can tell, it should work. Now, to the actual problem: a user enters some info into some form fields and clicks a "confirm" image, whereupon an AJAX request is sent back to the server. The server does some processing, then sends back a response with a status and some attached data. A status message is displayed in the modal dialogue window the user was using, and an icon with a link is displayed. Here's the "onComplete" Handler for the Mootools Request.JSON object, with some error condition handling removed: onComplete: function(response) { if (response) { if (response.status == 0) { // this means the request was successful licenses = response.licenses; updateControls(); licenseList(); // here I add the status message... $("createform_result").innerHTML = "<img src=\'/media/com_supportarea/images/db_success.png\' /> License created. Download:<br /><br />"; // ...and the download "link" if (response.tlsid) { $("createform_result").innerHTML += "<a href=\"#\" id=\"newtlslic-"+response.tlsid+"\"><img src=\'/media/com_supportarea/images/download_small.png\' /></a> <em>TLS</em>"; // this line is here for debugging only, to make sure this // block of code is run (it is) and the element is found (it is) $("newtlslic-"+response.tlsid).style.border = "1px solid red"; $("newtlslic-"+response.tlsid).addEvent("click", function(e) { // I've stripped out all other code, also for debugging e.stop(); }); } } } } The message and icon with link appears, the style is applied (red border appears) and no error message appears in either Firefox or Chrome. However, clicking the icon results in a # being appended to the URL (the e.stop()) does nothing). According to the EventBug plugin, no click event is attached to the link. It seems like .addEvent() simply does nothing here. Now, and here's they prize question: why is this and how can I fix it? Help! A: strings in javascript are immutable. when you do stuff like: $("createform_result").innerHTML += "<a href=\"#\" id=\"newtlslic-"+response.tlsid+"\"><img src=\'/media/com_supportarea/images/download_small.png\' /></a> <em>TLS</em>"; you are referencing the innerHTML as a string. what this does is, it fetches the property into a string, concatenates it to the other strings you pass on and then returns a new string in the end, which gets set as the innerHTML. in doing so, you are OVERWRITING the contents of the element every time, for every iteration. events attached to elements are not done by a generic ID handler - they rely on the element being in the DOM, then the element UID (an internal property mootools assigns to all passed elements) is being read and the event callback is added into the element storage behind that UID. you can see this work by doing console.log(element.retrieve("events")); if you rewrite the innerHTML, the inner element is re-created and gets a NEW UID, which means the callback now points to an empty pointer as the UID is the key in element storage. I may be wrong about what you are doing here as I don't actually see the bit where you rewrite it again, but there probably is one in the code you stripped, especially if you are running a loop. the best way to deal with this is something else - use Event Delegation. it can allow you to add the click event to the parent element instead via some selector. this will work for ANY element added in any way at any time that matches. eg. // add this once, outside the loop $("createform_result").addEvent("click:relay(a.editLink)", function(event, element) { console.log(this === element); console.log(this === event.target); console.log(this.get("data-id")); }); // then as you loop the results, just inject the els or use innerHTML or whatever... new Element("a.editLink", { html: '<img src=\'/media/com_supportarea/images/download_small.png\' /></a> <em>TLS</em>', "data-id": response.tlsid }).inject($("createform_result")); Event delegation is now a part of mootools core in 1.4.0 or is in mootools-more in previous versions. have fun!
{ "language": "en", "url": "https://stackoverflow.com/questions/7582701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Testing SMTP errors in my Java app My Java application encountered an issue in production where the SMTP server is rejecting mails sent to more than x destinations at once. I would like to test the behavior of the application in that situation. I found Dumbster Fake SMTP Server that is very nice but does not seem to offer a way to reject messages in some tests. Do you have any suggestions on how I could test this specific scenario ? A: I do not know Dumbster, but SubEthaSMTP does have this capability. Maybe the simplest solution is to extend the Wiser class (which implements a simple SMTP server specifically for testing) by overriding its accept method, returning false after the x. recipient. A: An alternative I can suggest is through writing a Junit test with EasyMock/ Mockito and simulating the exception that you see on production. You can focus on the part of code that you suspect and issue with and drill down on and fix the root cause. Obviously, if the above suggested SMTP services give you the capability to simulate the error, they may give you better confidence.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Adding bound combobox to datagridview The scenario is almost the same as http://arsalantamiz.blogspot.com/2008/09/binding-datagridview-combobox-column.html. but I can't get it working on c#... I have mySql db with two tables: 1. protocols 2. pcapdata In protocols tables I have a two fields: idprotocols and protocolName Int the pcaps table I have wizardProtocol (which is "linked" to the idprotocols field) What I'm trying to get is to have a combobox containing names which will replace the wizardprotocol field. Next, If the user updates the "names" combobox the wizardProtocol will be changed accordingly (so I will be able to update the changes in the database accordingly). Now, after reading some information on the net: I've written the following code: public void Bind(ref DataGridView dataGridView) { try { mySqlDataAdapter = new MySqlDataAdapter(SELECT_ALL_PCAP, _con); mySqlCommandBuilder = new MySqlCommandBuilder(mySqlDataAdapter); mySqlDataAdapter.UpdateCommand = mySqlCommandBuilder.GetUpdateCommand(); mySqlDataAdapter.DeleteCommand = mySqlCommandBuilder.GetDeleteCommand(); mySqlDataAdapter.InsertCommand = mySqlCommandBuilder.GetInsertCommand(); dataSet = new DataSet(); mySqlDataAdapter.Fill(dataSet, "pcap"); MySqlDataAdapter adp2 = new MySqlDataAdapter(SELECT_ALL_PROTOCOL, _con); MySqlCommandBuilder builder = new MySqlCommandBuilder(adp2); adp2.UpdateCommand = builder.GetUpdateCommand(); adp2.DeleteCommand = builder.GetDeleteCommand(); adp2.InsertCommand = builder.GetInsertCommand(); adp2.Fill(dataSet, "protocol"); bindingSource = new BindingSource(); bindingSource.DataSource = dataSet; bindingSource.DataMember = "pcap"; dataGridView.DataSource = bindingSource; dataGridView.Columns["length"].ReadOnly = true; dataGridView.Columns["length"].DefaultCellStyle.ForeColor = System.Drawing.Color.SandyBrown; dataGridView.AllowUserToAddRows = false; dataGridView.AllowUserToDeleteRows = false; DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn(); colType.HeaderText = "Type"; colType.DropDownWidth = 90; colType.Width = 90; colType.DataPropertyName = "wizardProtocol"; colType.DataSource = bindingSource; colType.DisplayMember = "protocolName"; colType.ValueMember = "idprotocols"; dataGridView.Columns.Insert(dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) - 1, colType); } catch (System.Exception e) { MessageBox.Show(e.ToString()); } } I'm trying to manipulable the DisplayMember property, but I fail (I know that the problem is with probably with my data-binding, but I can't figure it out...) UPDATE: Thanks to the answer, I'm re-attaching the fixed code mySqlDataAdapter = new MySqlDataAdapter(SELECT_ALL_PCAP, _con); mySqlCommandBuilder = new MySqlCommandBuilder(mySqlDataAdapter); mySqlDataAdapter.UpdateCommand = mySqlCommandBuilder.GetUpdateCommand(); mySqlDataAdapter.DeleteCommand = mySqlCommandBuilder.GetDeleteCommand(); mySqlDataAdapter.InsertCommand = mySqlCommandBuilder.GetInsertCommand(); dataSet = new DataSet(); mySqlDataAdapter.Fill(dataSet, "pcap"); MySqlDataAdapter adp2 = new MySqlDataAdapter(SELECT_ALL_PROTOCOL, _con); MySqlCommandBuilder builder = new MySqlCommandBuilder(adp2); adp2.UpdateCommand = builder.GetUpdateCommand(); adp2.DeleteCommand = builder.GetDeleteCommand(); adp2.InsertCommand = builder.GetInsertCommand(); adp2.Fill(dataSet, "protocol"); bindingSource = new BindingSource(); bindingSource.DataSource = dataSet; bindingSource.DataMember = "pcap"; dataGridView.DataSource = bindingSource; dataGridView.AllowUserToAddRows = false; dataGridView.AllowUserToDeleteRows = false; DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn(); BindingSource wizardBindingSource = new BindingSource(); wizardBindingSource.DataSource = dataSet; wizardBindingSource.DataMember = "protocol"; colType.HeaderText = "Type"; colType.DropDownWidth = 90; colType.Width = 90; colType.DataPropertyName = "wizardProtocol"; colType.DataSource = wizardBindingSource; colType.DisplayMember = "protocolName"; colType.ValueMember = "idprotocols"; dataGridView.Columns.Insert(dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) - 1, colType); A: The most obvious thing that you are doing wrong is that you use the same binding source for both your datagridview and for your comboboxcolumn. If you look at the example you provided you'll notice that they create a second bindingsource productBindingSource. So what you need to do is create a bindingsource (let's call it wizardProtocolBindingSource) which you then fill with the data from your protocols table. This becomes the datasource for your combobox column. The key code looks something like this: // You bind the datagridview just as before // this dataset should have the idprotocols field which is your foreign key // to the protocols table - you will probably want this to be hidden. bindingSource = new BindingSource(); bindingSource.DataSource = dataSet; bindingSource.DataMember = "pcap"; dataGridView.DataSource = bindingSource; // hide the foreign key column dataGridView.Columns["idProtocols"].Visible = false; // here we populate your comboboxcolumn binding source wizardProtocolBindingSource= new BindingSource(); // this dataset is from the protocols table wizardProtocolBindingSource.DataSource = dataSet; // Add the combobox column DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn(); colType.HeaderText = "Type"; colType.DropDownWidth = 90; colType.Width = 90; colType.DataSource = wizardProtocolBindingSource; // The DataPropertyName refers to the foreign key column on the datagridview datasource colType.DataPropertyName = "wizardProtocol"; // The display member is the name column in the column datasource colType.DisplayMember = "protocolName"; // The value member is the primary key of the protols table colType.ValueMember = "idprotocols"; // I usually just add the column but you can insert if you need a particular position dataGridView.Columns.Add(colType); The above should work for you, though not knowing the names of your dataset columns I had to guess a little.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SQL Server - Stored Procedure issue to get Matrix type of data Need help, struggling to do this please Got the following fields in table Package_Name Package_StartTime Package_Endtime What I require is: Based on data range give me how much time each package took time to execute like Package Name - 21 Sept 22 Sept 23 Sept ABC 3 mins 4 mins 2 mins This way I want to see the execution time pattern of the packages. A: Try this to get the data select package_Name as Package,Package_StartTime as Start, DateDiff(s,Package_StartTime,Package_EndTime) as Time from table where Package_StartTime >= @StartOfRange and Package_EndTime <= @EndOfRange You could format the seconds to time inside SQL if you want using cast((DateDiff(s,Package_StartTime,Package_EndTime) / 60) as varchar(2)) + ':' + cast((DateDiff(s,Package_StartTime,Package_EndTime) % 60) as varchar(2)) This will return a result set looking like this... Package Start Time ABC 9/21/2011 360 ABC 9/22/2011 570 etc. or Package Start Time ABC 9/21/2011 6:00 ABC 9/22/2011 9:30 etc. Depending on how you get the Time column If you are using SQL 2005 and above, you can use PIVOT to spread this across columns... Here is a good link with an example of how to use PIVOT Quick PIVOT example, not tested, but hopefully gets you started. select * from PackageTableAbove pivot (max (Time) for Start in ([9/21/2011],[9/22/2011], [9/23/2011],[9/24/20111])) as PackageTimePerDay If you don't want to hard-code the dates, you can look at using dynamic SQL to build the above statement. I am using Max(Time) under the assumption each package runs once per day. A: For every package, this query will calculate execution time in minutes for every day between StartTime and EndTime. Solution: CREATE TABLE dbo.Package ( Name NVARCHAR(10) PRIMARY KEY ,StartTime DATETIME NOT NULL ,EndTime DATETIME NOT NULL ); INSERT dbo.Package SELECT 'A', '2011-01-01T00:02:00', '2011-01-01T00:05:00' UNION ALL SELECT 'B', '2011-01-01T23:50:00', '2011-01-02T00:04:00' UNION ALL SELECT 'C', '2011-01-01T23:50:00', '2011-01-01T23:59:00' UNION ALL SELECT 'D', '2011-01-02T22:10:00', '2011-01-05T01:00:00'; WITH PivotSource AS ( SELECT a.Name ,CONVERT(VARCHAR(25),b.DayStartTime,112) [Day] ,DATEDIFF(MINUTE,b.DayStartTime,b.DayEndTime) DayMinutes FROM dbo.Package a CROSS APPLY ( SELECT v.number ,CONVERT(VARCHAR(25),DATEADD(DAY,v.number,a.StartTime),112) IntermediateTime ,CASE WHEN v.number=0 THEN a.StartTime ELSE CONVERT(VARCHAR(25),DATEADD(DAY,v.number,a.StartTime),112) END DayStartTime ,CASE WHEN CONVERT(VARCHAR(25),a.EndTime,112)=CONVERT(VARCHAR(25),DATEADD(DAY,v.number,a.StartTime),112) THEN a.EndTime ELSE CONVERT(VARCHAR(25),DATEADD(DAY,v.number,a.StartTime),112)+' 23:59:59.999' END DayEndTime FROM master.dbo.spt_values v WHERE v.type = 'P' AND v.number <= DATEDIFF(DAY,a.StartTime,a.EndTime) ) b ) SELECT pvt.* FROM PivotSource cte PIVOT( SUM(cte.DayMinutes) FOR cte.[Day] IN ([20110101],[20110102],[20110103],[20110104],[20110105]) ) pvt DROP TABLE dbo.Package; Results: Name 20110101 20110102 20110103 20110104 20110105 ---------- ----------- ----------- ----------- ----------- ----------- A 3 NULL NULL NULL NULL B 10 4 NULL NULL NULL C 9 NULL NULL NULL NULL D NULL 110 1440 1440 60
{ "language": "en", "url": "https://stackoverflow.com/questions/7582709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Localize output of strtotime string I read through manuals concerning strtotime and strftime as well as related functions, but I cannot seem to make any progress in trying to solve my problem. Basically, I'm interested in ways to print output of $deldate5 in local language (Dutch in this case). $deldate5 = date("d.m.Y., l", strtotime("today + 5 day", time())); I would most likely need to ditch strtotime string and replace it with something else in order to facilitate "today + 5 day" parameter. Can anyone help? Thank you in advance. A: Let's pick this apart: $deldate5 = date("d.m.Y., l", strtotime("today + 5 day", time())); This is doing two things: * *strtotime: Create a UNIX timestamp (number of seconds since the epoch). *date: Format the output. Your problem is related to the output (2.), not creating the timestamp (1.). So let's put this apart: $timestamp = strtotime("today + 5 day", time()); $formatted = date("d.m.Y., l", $timestamp); The only thing required now is to deal with the following line of code: $formatted = date("d.m.Y., l", $timestamp); The formatting parameters for the dateDocs function are: d - Day of the month, 2 digits with leading zeros m - Numeric representation of a month, with leading zeros Y - A full numeric representation of a year, 4 digits l - A full textual representation of the day of the week As l (lower case L) requires a locale in your output, let's see which formatting parameter strftimeDocs has to offer that is similar: %A - A full textual representation of the day. So it's just a small step to change from date to strftime: $formatted = strftime("%d.%m.%Y., %A", $timestamp); Hope this helps. A: Try setting the date default timezone to your local timezone: http://www.php.net/manual/en/function.date-default-timezone-set.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7582712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I get: Bad request I have got two similar FB apps i am working on. The one works, the copy gives 'Bad request.' Environment: Request Method: GET Request URL: http://doctorme.herokuapp.com/?code=AQAAWe0A6wnm24YuT066ILJMInzeJ0YPANpzb_bnS5jJRCg62KAxmTmD1m56QFVxW5DRRWRgMN8lWFNTucZpQXPHPJstRiFVPE7IfIntei-qMkNlz30SICWvfPDlfvw1g0NPBrqvkPqjZtjAF4xtR8j-WpK89ZAiMARzr3i9_GwsK6Ruhk6Zg2hqYy-qgP4CWY0 Django Version: 1.3.1 Python Version: 2.7.1 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.admindocs'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Traceback: File "/app/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 111. response = callback(request, *callback_args, **callback_kwargs) File "/app/doctorme/views.py" in home 14. access_token = fbapi_auth(request)[0] File "/app/doctorme/fbapi.py" in fbapi_auth 60. encode_func=simple_dict_serialisation) File "/app/doctorme/fbapi.py" in fbapi_get_string 48. result = urllib2.urlopen(url).read() File "/usr/local/lib/python2.7/urllib2.py" in urlopen 126. return _opener.open(url, data, timeout) File "/usr/local/lib/python2.7/urllib2.py" in open 398. response = meth(req, response) File "/usr/local/lib/python2.7/urllib2.py" in http_response 511. 'http', request, response, code, msg, hdrs) File "/usr/local/lib/python2.7/urllib2.py" in error 436. return self._call_chain(*args) File "/usr/local/lib/python2.7/urllib2.py" in _call_chain 370. result = func(*args) File "/usr/local/lib/python2.7/urllib2.py" in http_error_default 519. raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) Exception Type: HTTPError at / Exception Value: HTTP Error 400: Bad Request A: Check you're using the right configs among FB app and your app. Give HTTPs a shot (even if it seems not the HTTPs case...) with Heroku it's just a matter of 10secs to have it enabled :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7582717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to sort mysql search result by relevance? I have a similar query as asked on this question MySQL - How to ORDER BY RELEVANCE? INNODB Table Difference is, here I want to search from 5 fields as add1, add2, add3, post_town, post_code And only records in post_code field will be NOT EMPTY, other fields records may be empty at some places. If I search for keyword kingston, it returns Acre Road, Kingston upon Thames, KT2 6EA Kingston Road, Epsom, KT19 0DG Kingston Road, Epsom, KT20 0DH and these results are combination of all fields add1, add2, add3, post_town, post_code I need this result in following order Kingston Road, Epsom, KT19 0DG Kingston Road, Epsom, KT20 0DH Acre Road, Kingston upon Thames, KT2 6EA My Current SQL query is like this SELECT add1, add2, add3, post_town, post_code FROM address_mst WHERE add1 LIKE '%".$keyword."%' OR add2 LIKE '%".$keyword."%' OR add3 LIKE '%".$keyword."%' OR post_town LIKE '%".$keyword."%' OR post_code LIKE '%".$keyword."%' So I need records with search Keyword coming in the beginning would come first. How can I do that ? A: Not the prettiest but should work! select a.* from ( SELECT add1, add2, add3, post_town, post_code, 1 as rank FROM address_mst WHERE add1 LIKE '%".$keyword."%' UNION SELECT add1, add2, add3, post_town, post_code, 2 as rank FROM address_mst WHERE add2 LIKE '%".$keyword."%' UNION SELECT add1, add2, add3, post_town, post_code, 3 as rank FROM address_mst WHERE add3 LIKE '%".$keyword."%' UNION SELECT add1, add2, add3, post_town, post_code, 4 as rank FROM address_mst WHERE post_town LIKE '%".$keyword."%' UNION SELECT add1, add2, add3, post_town, post_code, 5 as rank FROM address_mst WHERE post_code LIKE '%".$keyword."%' ) a order by a.rank asc; A: Why not select the minimal qualifying results with query, and use own logic in the script to give advance ranking weightage to your result and sort them accordingly ? That would help you to : * *Have more complex ranking criteria which may or may not be possible in the query. *Not editing the sql query if your ranking criteria changes. A: For relevancy based sorting, FULL TEXT SEARCH is the more reliable option. FULL TEXT SEARCH used relevancy based on the number of occurrences of the searched term which could be later on used to ORDER results returned.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to assign a property in php? I have given an <a> element a data-filter property, as shown: <ul> <li> <a href="#" data-filter="*" class="all current"><?php _e('All', 'framework'); ?></a> <span>/</span> </li> <?php wp_list_categories(array( 'title_li' => '', 'taxonomy' => 'skill-type', 'walker' => new Portfolio_Walker(), 'show_option_none' => '' ) ); ?> </ul> How can I pass this data-filter property to PHP? A: How can I pass this data-filter property to PHP? You can't. It's not possible using pure HTML and PHP to transfer a certain (made-up) HTML attribute to PHP. A decent alternative is to use a form instead, where you could select a radio button and submit the form. EDIT: Another alternative is to simply pass the filter through the request's query string: <li> <a href="?data-filter=*" class="all current"><?php _e('All', 'framework'); ?></a> <span>/</span> </li> // in PHP: $data_filter = $_GET['data-filter']; echo $data_filter;
{ "language": "en", "url": "https://stackoverflow.com/questions/7582731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Oracle Update success but not getting updated in table I have updated a row in a table using this SQL query: UPDATE fruits SET f_name='Mangosteen' WHERE f_ID='1' and the query returns, 1 rows updated but in the table the change is not getting reflected. The table is accepting manual changes but not through the query, what can be the reason. I tried rebuilding the table, but it still fails. A: Have you committed the transaction? A: Make sure you COMMIT the changes. A: Had a similar problem on column ISTLIEFERTERMIN in table T_AUFTRAG and then remembered the trigger: create trigger tU1_T_AUFTRAG before UPDATE on T_AUFTRAG for each row begin if :NEW.ABGESCHLOSSEN <> 1 and :NEW.KOMMNR not like '%ANFRAG%' then :NEW.ISTLIEFERTERMIN := NULL; end if; end; :-D A: I had the same problem. In my case it was another process I wasn't aware of that was setting my column to the old value very frequently giving the impression of an update not taking any effect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to make a multi boot dvd for linux Is it possible to make a single bootable dvd with multiple linux distros in it? we should be able to select which os to boot by a menu. A: There are several tutorials for this: http://www.justlinux.com/forum/showthread.php?t=150078 http://pcquest.ciol.com/content/enterprise/2005/105070101.asp
{ "language": "en", "url": "https://stackoverflow.com/questions/7582734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: GWT 2.4 DataGrid automatic scrolling when selecting an item I am using GWT 2.4's new DataGrid in a project. I configured the DataGrid with a pagesize of 50. The available screen is not big enough to display all items and thus a vertical scrollbar is shown (this is actually the main purpose for using a DataGrid in the first place). I attached a SingleSelectionModel to the DataGrid in order to be able to select items. This works fine so far. However I also have another widget with which the user can interact. Based on that user action a item from the DataGrid should be selected. Sometimes the selected item is not in the visible screen region and the user has to scroll down in the DataGrid to see it. Is there any way to automatically or manually scroll down, so that the selected item is visible? I checked the JavaDocs of the DataGrid and found no appropriate method or function for doing that. A: Don't know if this works, but you could try to get the row element for the selection and use the scrollIntoView Method. Example Code: dataGrid.getRowElement(INDEX_OF_SELECTED_ITEM).scrollIntoView(); A: The answer above works pretty well, though if the grid is wider than your window and has a horizontal scroll bar, it also scrolls all the way to the right which is pretty annoying. I was able to get it to scroll down and stay scrolled left by getting the first cell in the selected row and then having it scroll that into view. dataGrid.getRowElement(dataGrid.getVisibleItems().indexOf(object)).getCells().getItem(0).scrollIntoView(); A: Don't have time to try it out, but DataGrid implements the interface HasRows, and HasRows has, among other things, a method called setVisibleRange. You just need to figure out the row number of the item that you want to focus on, and then set the visible range from that number n to n+50. That way the DataGrid will reset to put that item at the top (or near the top if it is in the last 50 elements of the list backing the DataGrid). Don't forget to redraw your DataGrid. Have you already looked at this? If so, I'd be surprised that it didn't work. Oh, and since this is one widget talking to another, you probably have some messaging set up and some message handlers so that when the user interacts with that second widget and "selects" the item, the message fires on the EventBus and a handler for that message fixes up the DataGrid along the lines I've described. I think you'll have to do this wiring yourself. A: My solution, a little better: dataGrid.getRow(model).scrollIntoView(); A: I got a Out of bounds exception doing the above. I solved it getting the ScrollPanel in the DataGrid and used .scrollToTop() and so on on the ScrollPanel. However, to access the ScrollPanel in the DataGrid I had to use this comment: http://code.google.com/p/google-web-toolkit/issues/detail?id=6865 A: As Kem pointed out, it's annoying the "scrollToRight" effect after the scrollIntoView. After me, Kem's solution gives a better behaviour than the base one as usually the first columns in a table are the more meaningful. I improved a bit his approach, which scrolls horizontally to the first column of the row we want to be visible, by calculating the first visible column on the left before applying the scroll and then scrolling to it. A final note: Columns absolute left is tested against "51". This is a value I found "experimentally" by looking the JS values in the browser's developer tool, I think it depends on the table's style, you may need to change/calculate it. Below the code: public void scrollIntoView(T next) { int index = datagrid.getVisibleItems().indexOf(next); NodeList<TableCellElement> cells = datagrid.getRowElement(index).getCells(); int firstVisibleIndex = -1; for(int i=0; i<cells.getLength() && firstVisibleIndex<0;i++) if(UIObject.isVisible(cells.getItem(i)) && (cells.getItem(i).getAbsoluteLeft() > 51) && (cells.getItem(i).getAbsoluteTop() > 0)) firstVisibleIndex = i; cells.getItem(firstVisibleIndex>=0? firstVisibleIndex : 0).scrollIntoView(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7582742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Discrete Fourier transform I am currently trying to write some fourier transform algorithm. I started with a simple DFT algorithm as described in the mathematical definition: public class DFT { public static Complex[] Transform(Complex[] input) { int N = input.Length; Complex[] output = new Complex[N]; double arg = -2.0 * Math.PI / (double)N; for (int n = 0; n < N; n++) { output[n] = new Complex(); for (int k = 0; k < N; k++) output[n] += input[k] * Complex.Polar(1, arg * (double)n * (double)k); } return output; } } So I tested this algorithm with the following code: private int samplingFrequency = 120; private int numberValues = 240; private void doCalc(object sender, EventArgs e) { Complex[] input = new Complex[numberValues]; Complex[] output = new Complex[numberValues]; double t = 0; double y = 0; for (int i = 0; i < numberValues; i++) { t = (double)i / (double)samplingFrequency; y = Math.Sin(2 * Math.PI * t); input[i] = new Complex(y, 0); } output = DFT.Transform(input); printFunc(input); printAbs(output); } The transformation works fine, but only if numberValues is a multiple number of the samplingFrequency (in this case: 120, 240, 360,...). Thats my result for 240 values: The transformation just worked fine. If i am trying to calculate 280 values I get this result: Why I am getting a incorrect result if I change the number of my calculated values? I am not sure if my problem here is a problem with my code or a misunderstanding of the mathematical definition of the DFT. In either way, can anybody help me with my problem? Thanks. A: You are NOT getting the incorrect result for a non-periodic sinusoid. And they are not just "artifacts". Your result is actually the more complete DFT result which you don't see with a periodic sinusoid. Those other non-zero values contain useful information which can be used to, for example, interpolate the frequency of a single non-periodic-in-aperture sinusoid. A DFT can be thought of as convolving a rectangular window with your sine wave. This produces (something very close to) a Sinc function, which has infinite extent, BUT just happens to be zero at every DFT bin frequency other than its central DFT bin for any sinusoid centered exactly on a DFT bin. This happens only when the frequency is exactly periodic in the FFT aperture, not for any other. The Sinc function has lots of "humps" which are all hidden in your first plot. A: What you are experiencing is called Spectral Leakage. This is caused because the underlying mathematics of the Fourier transform assumes a continuous function from -infinity to + infinity. So the range of samples you provide is effectively repeated an infinite number of times. If you don't have a complete number of cycles of the waveform in the window the ends won't line up and you will get a discontinuity which manifests its self as the frequency smearing out to either side. The normal way to handle this is called Windowing. However, this does come with a downside as it causes the amplitudes to be slightly off. This is the process of multiply the whole window of samples you are going to process by some function which tends towards 0 at both ends of the window causing the ends to line up but with some amplitude distortion because this process lowers the total signal power. So to summarise there is no error in your code, and the result is as expected. The artefacts can be reduced using a window function, however this will effect the accuracy of the amplitudes. You will need to investigate and determine what solution best fits the requirements of your project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Android User Interface - Are tabs at the bottom the best approach? I am creating an app that provides users information about a building that the app is being designed for. For example it will tell the user the location of the building, hotels/restaurants/cafes nearby and some other useful information. I will be creating seperate activities to carry this out, so an activity to tell user the location and maybe contain a map, an activity listing hotels and an activity listing nearby cafes etc. My problem is that I am not sure how to design the interface for this. I was thinking of having tabs at the botton of the screen where each tab opens the corresponding activity. Is this a good way to do it or is there a better way? Thanks A: This is really a UX (user experience) decision, not a coder decision. You are probably asking this question on a wrong site. I recommend you look around how other apps have solved a similar problem, to get ideas what is possible. Then pick a solution that you like best. A: You might want to ask that at UX Personally I think Tabs are a quite intuitive way to let the user choose between dedicated views/activities - especially if they are labelled with distinct icons A: Tabs is always a clean solution. Maybe something like a dashboard would also be nice. (Pattern 3 in my link) This link covers some things that may be useful in further development. Android Dev UI Development A: Right now i can think of some other solutions * *Use a gesture to swap to another activity *Use a pair of arrow buttons at the bottom But your solution seems nicer
{ "language": "en", "url": "https://stackoverflow.com/questions/7582747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Check if file exists in resourses/project navigator I need to check if an image exists in the project navigator. If it doesn't it needs to download it from the internet. The goal is to be able to use images like [UIImage imageNamed:@"23451.jpg"]; So I need to check if the image exists, if not download it. I tried to do this as followed: NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; //Set image NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:@"12345.jpg"]; //Check if the image exists at a given path BOOL imageExists = [[NSFileManager defaultManager] fileExistsAtPath:imagePath]; //If the image doesn't exists download it. if (!imageExists) { NSData* data = UIImageJPEGRepresentation([UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"www.mywebsite.com/12345.jpg"]]]); [data writeToFile:imagePath atomically:YES]; } If everything goes the right way the image is saved at the above path. But I still am not able to use this image with [UIImage imageNamed:@"12345.jpg"]; I have got the feeling that i'm saving the images in a different directory than I should be saving them to. Do you have any idea on how I should do this? A: imageNamed will only work form image in the app bundle, not those stored in the Document directory. And you can't add the image to the app bundle, it readonly. if (!imageExists) { NSData* data = UIImageJPEGRepresentation([UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"www.mywebsite.com/12345.jpg"]]]); [data writeToFile:imagePath atomically:YES]; } There is no need to do this, you are now JPG a JPG: if (!imageExists) { NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.mywebsite.com/12345.jpg"]]; [data writeToFile:imagePath atomically:YES]; } A: NSData* data = [NSData dataWithData:UIImageJPEGRepresentation([UIImage imageWithContentsOfFile:imagePath], 0.8)]; [data writeToFile:imagePath atomically:YES]; A: I did something similar .. here are some excerpts of the code .. not the complete code ... - (void)loadAndStoreImage{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSURL *theurlPortrait = [[NSURL alloc] initWithString:[[DataController sharedDataController].imageResponse objectForKey:@"portraitImageUrl"] ]; NSLog(@"Image url %@ ",theurlPortrait); imageDataPortrait = [NSData dataWithContentsOfURL:theurlPortrait]; [theurlPortrait release]; imagePortrait= [[UIImage alloc]initWithData:imageDataPortrait]; oldPathPortrait = [documentsDirectory stringByAppendingPathComponent:@"pt_wallpaper_1.png"]; NSURL *theurlLandscape = [[NSURL alloc] initWithString:[[DataController sharedDataController].imageResponse objectForKey:@"landscapeImageUrl"]]; imageDataLandscape = [NSData dataWithContentsOfURL:theurlLandscape]; [theurlLandscape release]; imageLandscape= [[UIImage alloc]initWithData:imageDataLandscape]; oldPathLandscape = [documentsDirectory stringByAppendingPathComponent:@"ls_wallpaper_1.png"]; [self replaceImages]; } -(void)replaceImages{ //check if images were fully downloaded or corrupted. if (isUserSignedIn) { if (imageDataPortrait && imageDataLandscape) { [UIImagePNGRepresentation(imagePortrait) writeToFile:oldPathPortrait atomically:YES]; [UIImagePNGRepresentation(imageLandscape) writeToFile:oldPathLandscape atomically:YES]; NSLog(@"IMAGES REPLACED"); NSDate *currentDate=[NSDate date]; [[ NSUserDefaults standardUserDefaults] setObject:currentDate forKey:@"previousDate"]; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7582750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: threading.Timer time precision What does the time accuracy of Python's threading.Timer depend on? Does it depend on the OS used? Does it depend on the Python implementation used? Does it depend on the interval? How can it be benchmarked? Are there already benchmarks out there? A: In CPython, the threading.Timer accuracy (waiting part) is based on a Condition.wait() call. The Condition.wait() (implemented here) is done by successive sleep with a delay of min(delay * 2, remaining, .05) where delay is originally set at 0.0005 # 500 us -> initial delay of 1 ms. According to this implementation (that is OS independant) we can argue that the accuracy is at least the time.sleep accuracy. But, the time.sleep() accuracy is based on the OS used (here is the implementation : floatsleep()), on Windows, it uses the WaitForSingleObject() with a internal windows timer, on Linux it uses the select() method. At least, because apart the sleep delay, the charge of the OS could interfer with the reactivity of the python process, the scheduling algorithm can also have an influence on the accuracy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Monodroid WebRequest bombs application I have tried this code in a normal C# app and it works fine. In monodroid, it completely bugs out (in other words, not even the try-catch works) when I try to READ from the stream (or the base stream) in ANY way. Please help: try { WebRequest request = WebRequest.Create(string.Format("http://maps.google.com/maps/geo?q={0},{1}&output=xml&sensor=false", "35.245619","-98.276369")); WebResponse wresponse = request.GetResponse(); using (StreamReader sr = new StreamReader(wresponse.GetResponseStream())) { RunOnUiThread(() => _debug.Text = (sr.ReadToEnd()).ToString()); } wresponse.Close(); } catch (Exception ex) { RunOnUiThread(() => _debug.Text = string.Format("Exception: ", ex.Message)); } _debug is a TextView object on my UI. A: How about this way? try { WebRequest request = WebRequest.Create(string.Format("http://maps.google.com/maps/geo?q={0},{1}&output=xml&sensor=false", "35.245619","-98.276369")); WebResponse wresponse = request.GetResponse(); var resp=string.Empty; using (StreamReader sr = new StreamReader(wresponse.GetResponseStream())) { resp=sr.ReadToEnd().ToString(); } wresponse.Close(); RunOnUiThread(() => _debug.Text = resp); } catch (Exception ex) { RunOnUiThread(() => _debug.Text = string.Format("Exception: ", ex.Message)); } A: Sound has provided the answer. That should work. I'll just explain the reason a bit. From your code, it seems like you are doing the HTTP request on a background thread. That's why you need to do the RunOnUiThread. This is a very good approach. However, RunOnUiThread does not guarantee that the code will be executed immediately on the UI thread. It merely posts a message to the UI thread run loop. And when the UI thread gets a chance, it will execute it. What this essentially means is that "wresponse.close()" will probably run before "resp=sr.ReadToEnd().ToString()". Since the response is closed, any attempt to read from it will cause an error. But the error happens on the UI thread since the read attempt will be on UI thread. Thats why your try/catch block doesn't function. In Sound's code, this problem is eliminated. As a side note, this code is also much better performing since the actual reading of bytes is offloaded to the worker thread, so your UI thread will be much more responsive.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: RegExp to get any number + `;#`? I have several numbers in a string, such as: 8;# 10;# 34;# etc... I wanted to erase all of these from the string, so was thinking RegExp would be my best option. What regexp expression do I use that will identify any series of numbers followed by ;# ? A: Try something like this this: \d+;# I don't know AS3 but I think your code should look something like this: var r:RegExp = /\d+;#/; var s:String = "foo 8;# bar 10;#baz 34;# bah"; var x:String = s.replace(r, "")
{ "language": "en", "url": "https://stackoverflow.com/questions/7582761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: TinyMCE with ajax tabs I'm using tabs component of JQuery UI 1.8, and I'm loading content of tabs via ajax (html content). In one of this tabs I'm using tinyMCE component, and when I load this tab the first time, the tiny initializates correctly but if I navegate to other tab and I recall the tab again the tiny breaks down. This occurs when the import of tiny_mce.js is outside the contents of tabs. When I move the import into tab call, the tiny didn't load because it seems to be not initialized. The question is: how can initialize tiny in an ajax tab? Thanks in advance. A: When I was having similar problems with TinyMCE and switching between ajax loaded tabs I found this wonderful piece of code at Ready4State so I thought I would share as I hope it helps others. This will remove all instances of TinyMCE on the page. var i, t = tinyMCE.editors; for (i in t){ if (t.hasOwnProperty(i)){ t[i].remove(); } } Then you can safely reinitialize TinyMCE. Personally I carry out the above code before using a switch statement to handle each ui.index, and I have a function that performs the initialisation for TinyMCE. So I just call that function in each of the relevant case statements. Hope this helps someone else. A: It might be worth re-initialising tiny MCE every time you switch back to the tab with the editor in. You can use the "select" event on the tab object. $( ".selector" ).tabs({ select: function(event, ui) { // initialise Tiny MCE here } }); You may have to destroy any previous instances of / references to the editor before re-initialising. A: You need to shut down your tinymce instances before you switch to another tab else the editor element with that id will be blocked. Remove the control before you switch the tab using // the_editor_id equals the id of the underliing textarea tinyMCE.execCommand('mceRemoveControl', false, the_editor_id); A: I found the solution to my problem. The initialization of tinymce must be in load event of jquery tabs, like this: $("div#tabs").tabs ({collapsible: false ,selected: -1 ,fx: {opacity: 'toggle'} ,load: function (event, ui) { // Tab with tinyMCE if (ui.index == 0) { tinyMCE.init({mode: "none", theme: "advanced", theme_advanced_toolbar_location: "top", theme_advanced_toolbar_align: "left" }); tinyMCE.execCommand ('mceAddControl', false, 'text_area_id'); } else { tinyMCE.triggerSave(); tinyMCE.execCommand('mceFocus', false, 'text_area_id'); tinyMCE.execCommand('mceRemoveControl', false, 'text_area_id'); } } }); I hope this helps others. Besides, if the content of the textarea is load via ajax, the command: tinyMCE.triggerSave(); is not necesary. A: Well, spent 3 hours on the same problem today... with Jquery UI 1.10 and TinyMCE 4. The problem is, when unselected, the content of the ajax panel isnt removed from the DOM but just hidden. That means the textarea could be more than 1 time in the DOM (navigating the panels). => Death of tiny MCE... There is no event in Jquery 1.10 to catch an "unselected panel". You have to deal with the before load event. So the idea is to empty each "ajax loaded" panel before to load a panel. The code : $( "#list_onglet_lecteur" ).tabs({ beforeLoad: function( event, ui ) { $("#list_onglet_lecteur div[role=tabpanel]").each(function(){ if($(this).attr("id") != "list_onglet_lecteur-accueil")$(this).empty(); }); $(ui.panel).html('<div style="width:100%;text-align:center"><img src="/images/ajax_loader_big.gif" alt=""></img><br />Chargement de l\'onglet</div>'); ui.jqXHR.error(function() { ui.panel.html("Echec du chargement de l'onglet. Merci d'actualiser la page."); }); } }) Note i havn't find the way to make the difference between "ajax loaded panels" and "pre-loaded panels"... That's a shame because you have to add each "pre-loaded panel" ids into the code... Anyway, that resolve the tiny MCE problem. No need to init into the load event, and use the mceRemoveControl/mceAddControl commands. Just init the tinyMCE edit in the "ajax loaded tab panel" view : $(function() { tinyMCE.init({ height : 300, mode : "specific_textareas", editor_selector : "mceEditor", theme : "modern", language : 'fr_FR', plugins: [ "advlist autolink lists link image charmap print preview anchor", "searchreplace visualblocks code fullscreen", "insertdatetime media contextmenu paste moxiemanager" ], toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image" }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7582764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Do something when screen resolution changes with jQuery I want to set height of a div as height of window when page loads... So I used the below code : $(document).ready(function () { var x = screen.availWidth; var y1 = screen.availHeight; var y2 = screen.Height; var w = $(window).height(); var d = $(document).height(); alert('availHeight : ' + y1); alert('Height : ' + y2); alert('window : ' + w); alert('document : ' + d); $('#OuterDiv').css({ 'height': w }); //alert($('#OuterDiv').css('height')); }); //End Of $(document).reedy Problem #1: When screen resolution changes that div still have previous height. How can I fix that ? Problem #2: I want height=100% for that div and because of some css problems I used jQuery. But when page is loading (during page load) that div's height is the height of it's content and after that jQuery worked, that div gets window's height. I think this is not nice during page load. How can I fix this issue? height:100% does not work for that div: Here is the reason -> LINK Thanks in advance A: You can capture the resize event like so: $(window).resize(function() { alert($(window).width()); alert($(window).height()); }); If you want to resize straight away, take the script out of the ready event, and put it inline, directly below your div (and maybe call it again on ready as well) E.g. <div class="myDiv">Content</div> <script>$('#myDiv').height($(window).height());</script> A: Is there any reason you can't just use CSS? If you set the width and height of your body to 100% and position your div absolutely, you should achieve the same effect. Here's the jQuery event you're looking for, which sets #box to the width and height of the window $(document).ready(function() { var resizeBox = function() { $('#jq').css({width: $(window).width(), height: $(window).height()}); }; resizeBox(); $(window).resize(resizeBox); }); Here's an example at http://jsfiddle.net/JxWm9/4/ which includes a CSS box for comparison. Note the JS version lags because it's based on the resize event, while the CSS resize is native to the browser itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass and get Parameters between two Pages in Jquery Mobile? I am working on a some demo App to learn things in Jquery Mobile. I have tried a lot of options but not able to get solution on a few things :- * *http://jsfiddle.net/sahil20grover1988/zZMXQ/48/ In this case when i add param with Url in Index page it is not directing to Search Page *In case if I dont add Params to Index page then how do I pass params from Index page to Search page. *Also I need help how to retrieve the Params in search page ?? A: Does this help? * *http://jsfiddle.net/phillpafford/VXV3R/ JS $('#page2').live('pageshow', function(event, ui) { alert('Page 2 - CID: ' + getParameterByName('cid')); }); function getParameterByName(name) { var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search); return match && decodeURIComponent(match[1].replace(/\+/g, ' ')); } HTML <div data-role="page" id="home"> <div data-role="content"> <ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="f"> <li data-role="list-divider"> Home Page </li> <li> <a href="?cid=1234#page2" rel="external">Page 2</a> </li> </ul> </div> </div> <!-- page 2 --> <div data-role="page" id="page2"> <div data-role="content"> <ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="f"> <li data-role="list-divider"> Page 2 </li> <li> <a href="?cid=4321#home">Home Page</a> </li> </ul> </div> </div> A: I came up with this simple approach... First add custom HTML5 attributes to the elements on page 1 to hold the data to be passed. My attribute is named data-parm <div data-role="page" id="one"> <div data-role="content"> <ul data-role="listview" data-theme="c"> <li><a data-parm="john" href="#two">one</a></li> <li><a data-parm="mary" href="#two">two</a></li> <li><a data-parm="sue" href="#two">three</a></li> </ul> </div> </div> <div data-role="page" id="two"> <div data-role="content"> <div id="showParmHere"></div> </div> </div> In your javascript, create a click handler (or other type of handler) that selects the attribute and assigns the value to a variable which will be available for you on page 2. For this example, I have added it to the html of a div that is on page 2. $("a").on("click", function (event) { var parm = $(this).attr("data-parm"); //do something here with parameter on page 2 (or any page in the dom) $("#showParmHere").html(parm); }); A: To pass valor with url in jQuery mobile you can use rel="external"... Example: <a id="l" href="index.html?id='1234'#dateA" rel="external"> You can see: http://demos.jquerymobile.com/1.2.0/docs/pages/page-links.html A: I stumbled on this question because the same issue, but think I found an easier way. At least if you use the "pagebeforechange" event. That's where I tried the solution so far. You can get the search string from the second parameter of the pageonchange event function by this object path: ".options.link.context.search". I hope the example code is enough to explain it. $(document).live("pagebeforechange", function(e, secondparameter) { alert(secondparameter.options.link.context.search); }); A: I created a solution for jQM 1.4+ which allows parameters to be passed through the URL. This works quite nicely if you want the user to be able to go directly to a page with parameters (say from an e-mail), or if the user refreshes the page. It's under the MIT license and you can find it here on GitHub.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: which is the best way to externalize a database configuration on a desktop app? I'm working in a desktop app, and we're using Eclipse RCP with EclipseLink. All my database configuration is inside a class, but I'll need these thing (database URL, password, username) configurable. Which is the best way to do that? A: The standard way is to have a properties (either java.util.Properties or XML) file in which is stored the database details. This can be writeable by the user of course, and passwords stored in such a file need to be encrypted. It's a nice idea to give the user a means of setting these from the application rather than having to edit the file manually though. A: In addition to the answers already given I would suggest externalizing the reference to the properties file by specifying it as a command-line option, e.g: java my.app.MainClass -Ddb.config=/path/to/db.properties You can then grab the path like so: final String dbConfigPath = System.getProperty("db.config"); A: Easiest way would be to use some simple property file and java.util.Properties to read it. You can read the file from classpath, e.g: Class.getResourceAsStream ("resource.properties");
{ "language": "en", "url": "https://stackoverflow.com/questions/7582784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Switching branch for a subdirectory only in Git I'm working on a Git repository with two main branches and two main folders. One of these folders is very similar between the two branches, the other is very different. This means that, even if I'm just working on the common folder, switching between the two branches is slow due to all the updates required to the other folder. Is it possible to switch the branch of a subfolder in a Git repository without switching the branch of the rest of the repository? In Subversion, I could just use svn switch on any subfolder, and everything would Just Work™, but I haven't found an equivalent in Git. Ideally, when I'm working in the folder that's common to the two branches, I'd like to be able to switch branches in that folder, make commits to either branch, and do all the other useful Git goodness, without having to wait for the other folder to be more-or-less completely rewritten. Just to complicate matters, I'm using git svn; the two main branches I mention are the trunk and a branch in the underlying Subversion repository. A: You can do this in git with something called "sparse checkout". First, you have to enable this on your project: git config core.sparsecheckout true Then, you have to set up the directories you want to check out. Open .git/info/sparse-checkout in an editor, and list the directories you want to limit the checkout to (each on a separate line). Then run this command: git read-tree -m -u HEAD You can disable sparecheckout at some later point to return the behavior to normal. A: I've found a new solution to this: git-new-workdir. It doesn't let me switch a subfolder, but it does let me have separate working directories which I can switch between instead of using a "switch" operation. It solves the underlying problem: I can have one working directory for each of the main branches, swap between them whenever I want with no cost, and the two working directories share the same Git repository, so I don't need two separate clones as Ben Lee suggested in the comments to his answer. To get at the script on my (Cygwin) system, I needed to download and install the Git source code; it's in the contrib directory there. A: If you really wanted to be able to do that, the only way in Git would be to set up the subfolder as a submodule http://book.git-scm.com/5_submodules.html I guess the reason SVN allows this is because it places separate .svn files in each subfolder which keep track of the current state. A: I don't think it's possible. Git is a content tracker and tracks content changes, not files or folders. As a workaround you could use git-svn to fetch your SVN trunk in one Git repository and the SVN branch in another.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a way to take screenshots of current running Java desktop application and stream it as video? So I have a java desktop application running on a server. I would like to take series of screenshot which can be streamed to the client. It should be almost as if watching a VNC video output. Basically need a way to stream the graphic output from java desktop application runing on the server to the client. It would best if there was a tool to capture the region of the running application and stream that region as video to the client. A: Using Cisco Webex you can make that server a host of the presentation and then only share the window you need with other 'participants' of the presentation. Buy Webex costs money. I am sure that there is some VNC tool that can share only part of the desktop. Maybe UltraVNC?
{ "language": "en", "url": "https://stackoverflow.com/questions/7582799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Send app to background and show the app(s) in the below window I dont want my app to run in background, I only want to give the user the option to close his/her other app(s) when my app gets a memory warning. That is, my app shows an alert view with Cancel and OK buttons. If s/he touches OK, then the twice push on the home button is simulated. Is it possible? I have this as an option in their settings, i.e. if they want to see the memory warning or not. I mentioned that I don't want my app running in background, because I see many questions asked here about running their own app in background. It is not relevant to my question, I just wanted to make it clear. A: Not with public APIs. Beside that, when you receive a memory warning you should only take care of the resources you allocate and use, and not ask someone else to free memory instead of you. A: This is not possible. When your app receives a memory warning it should act responsibly and free memory where it can. From the Apple docs When a view controller receives a memory warning (didReceiveMemoryWarning), it should relinquish ownership of resources that are currently not needed and that can be recreated later if required. I'm not quite sure what this has to do with not running your app in the background.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Clusters over time in R I have a series of data that I'm going to use clustering on, and I want to see how this data clusters over time. So essentially everyone starts in a single group, as they have done nothing, but over time as they do different things they will be put into different groups based on their behavior, and I want to track this. I've been looking for a way to do this in R (with some preprocessing of data in Python), and represent it graphically. The only way I can currently think of doing this is breaking the time period into say, 3 weeks, and then clustering each of the 3 weeks. The only problem with this is I don't really know how to track movements of people between clusters over those 3 weeks (e.g. to see if someones actions moves them from group A to group B). I could put it in a table, but it would be nice to somehow show it graphically (like red lines between cluster over time or something). Any ideas on how to do this would be much appreciated, or if there is a good way to track clusters over time that I've been missing please point me towards it. A: I've used the Mfuzz in R for clustering time-course microarray data sets. Mfuzz uses "soft-clustering". Basically, individuals can appear in more than one group. Here is an example with some simulated data: library(Mfuzz) tps = 6;cases = 90 d = rnorm(tps*cases, 1) ##Poisson distribution with mean 1 m = matrix(d, ncol=tps, nrow=cases) ##First 30 individuals have increasing trends m[1:30,] = t(apply(m[1:30,], 1, cumsum)) ##Next 30 have decreasing trends ##A bit hacky, sorry m[31:60,] = t(apply(t(apply(m[31:60,], 1, cumsum)), 1, rev)) ##Last 30 individuals have random numbers from a Po(1) ##Create an expressionSet object tmp_expr = new('ExpressionSet', exprs=m) ##Specify c=3 clusters cl = mfuzz(tmp_expr, c=3, m=1.25) mfuzz.plot(tmp_expr,cl=cl, mfrow=c(2, 2)) This gives:
{ "language": "en", "url": "https://stackoverflow.com/questions/7582806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you tie UIMA to SOLR Dataimporthandler? We've been doing some tests with Apache UIMA. The results are amazing! Our ideal set up would be a tight integration of UIMA with SOLR. Ideally, we like to pass all the content we index past UIMA, for additional metadata. There are examples and documentation available how to do the the UIMA integration with the SOLR Update handler, but ideally we'd like to use the existing DataImportHandler (DIH). All our data is imported though a JDBC connection, and should be passed to UIMA before indexing. Can anybody shed some light on how to accomplish this? Thanks, René A: Data Import handler do supports the update.processor. So you can probably tie the dataimport handler with the uima update processor - <requestHandler name="/dataimport" class="org.apache.solr.handler.dataimport.DataImportHandler"> <lst name="defaults"> <str name="config">data-config.xml</str> <str name="update.processor">uima</str> </lst> </requestHandler> Just an option, haven't tried it myself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: parsing SNMP MIB files (OID translation) I am making a network device monitor. Part of it is a PHP front-end where user can enter the SNMP values he is interested in (SNMP OIDs). I want to make the process simpler for the user so I want to create a simple MIB browser, allowing user to select the value(s) from the tree. The problem is reading MIB files to database (or at least XML-like format) from where I could present them to the user. Parsing MIB files on-the-fly seems wasteful to me so that rules out PHP's snmp_read_mib() - unless I can read MIB once and save the OID translations to DB? Also, I would like to avoid writing my own parser if possible. :) I have found libsmi but I'm not sure how to use it for this case... I tried using smidump but could only create some short XML with no useful content. I didn't try xmldump yet though, because it is not available on Debian (as package) and would have to build it from sources. Also, I think it is from 2005. Would it help? So the question is: how can I read OID names and/or other data (SNMP Trap info) from MIB files and convert them to some ready-to-use format? A: I ended up using Mibble - I wrote a small program which uses this library to parse the MIBs and outputs the data. Very simple and seems to work nicely. Still, thank you both for trying to help me - I appreciate it! A: smidump -f identifiers <MIB_filename> If the MIB isn't up to par with it's syntax, use smilint -ms <MIB_filename> That should get you started
{ "language": "en", "url": "https://stackoverflow.com/questions/7582810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to initialise a C string with a 16-bit integer? I want to create a global 22 character (+ NULL) string in C. I am initialising it like this: #define SVN_REVISION "1143" #define SERIAL_NUMBER "PST3201109270001" char general_info[23] = SVN_REVISION SERIAL_NUMBER SAMPLING_FREQUENCY; So far, this works fine. general_info is initialised with the concatenation of the two strings. Now, for the last two characters, I want them to be a 16-bit integer. But I can't simply do this: #define SVN_REVISION "1143" #define SERIAL_NUMBER "PST3201109270001" #define SAMPLING_FREQUENCY (UINT16)500 char general_info[23] = SVN_REVISION SERIAL_NUMBER SAMPLING_FREQUENCY SAMPLING_FREQUENCY; What can I do? A: You have to use the usual "stringify operator" trick. #define STRINGIFY_HELPER(str) #str #define STRINGIFY(str) STRINGIFY_HELPER(str) #define SVN_REVISION "1143" #define SERIAL_NUMBER "PST3201109270001" #define SAMPLING_FREQUENCY (UINT16)500 char general_info[23] = SVN_REVISION SERIAL_NUMBER SAMPLING_FREQUENCY STRINGIFY(SAMPLING_FREQUENCY); You need the double macro to exploit the preprocessor # operator because the macro arguments are not expanded when the # operator is used. Thus, an extra macro step is needed to first expand the arguments, and then use the # operator. A good explanation can be found here. edit Actually, that won't work because of the (UINT16) cast, that will be stringified as well. You can still get away with macros only if you can afford creating an extra macro: #define STRINGIFY_HELPER(str) #str #define STRINGIFY(str) STRINGIFY_HELPER(str) #define SVN_REVISION "1143" #define SERIAL_NUMBER "PST3201109270001" #define SAMPLING_FREQUENCY_NOCAST 500 #define SAMPLING_FREQUENCY (UINT16)(SAMPLING_FREQUENCY_NOCAST) char general_info[23] = SVN_REVISION SERIAL_NUMBER SAMPLING_FREQUENCY STRINGIFY(SAMPLING_FREQUENCY_NOCAST); It isn't very elegant, but you still avoid the problem of duplicating the 500 value (you just have to update it in a single place and everything will work fine). A: If you mean you want to embed 16-bit integer 500 as binary data in the end of the string, you can use raw hex bytes: /* Little-endian unsigned 16-bit integer with the value 500 */ #define SAMPLING_FREQUENCY "\xf4\x01" Beware, though, endianness is architecture dependent, so you might want to add an extra macro to correctly order the bytes depending on the architecture: #ifdef ... /* little endian */ #define BYTES2(a,b) b a #else ... /* big endian */ #define BYTES2(a,b) a b #endif #define SAMPLING_FREQUENCY BYTES16("x01", "\xf4") EDIT: If you want to have a human-readable number, you can't have it at compile-time (at least not in C), but you can initialize it at runtime: #define SVN_REVISION "1143" #define SERIAL_NUMBER "PST3201109270001" #pragma pack(push, 1) union { struct { char svn_rev_serial[20]; uint16_t freq; char nul; }; char general_info[23]; } u = {{ SVN_REVISION SERIAL_NUMBER, 500, '\0' }}; #pragma pack(pop) This uses more non-standard (but well-supported) constructs, like #pragma pack and writing to one union member and reading from another. A: Well, you can try this: char general_info[23] = SVN_REVISION SERIAL_NUMBER SAMPLING_FREQUENCY; strcat(genral_info, itoa(SAMPLING_FREQUENCY)); A: Youy can try something like : #define SVN_REVISION "1143" #define SERIAL_NUMBER "PST3201109270001" #define SAMPLING_FREQUENCY "\xF4\x1\00\00" char general_info[29] = SVN_REVISION SERIAL_NUMBER SAMPLING_FREQUENCY SAMPLING_FREQUENCY; \xF4\x1\00\00 is the memory representation for decimal 500 (at least on Windows platforms)
{ "language": "en", "url": "https://stackoverflow.com/questions/7582811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WPF FlowDocument Symmetric Layout How can a symmetric layout be generated using one FlowDocument? My code is: <Grid Name="grid1"> <FlowDocumentScrollViewer Name="name1" Margin="6,0,17,0"> <FlowDocument> <Paragraph> <Figure HorizontalAnchor="PageLeft" VerticalAnchor="PageTop" Width="0.5content"> <BlockUIContainer> <Button >HelloTwo</Button> </BlockUIContainer> </Figure> <Figure HorizontalAnchor="PageRight" VerticalAnchor="PageTop" Width="0.5content"> <BlockUIContainer> <Button >HelloTwo</Button> </BlockUIContainer> </Figure> </Paragraph> </FlowDocument> </FlowDocumentScrollViewer> </Grid> I want them to be aligned side-by-side with each one's content in the same position. How can I achieve this layout? A: You should use FlowDocumentReader or FlowDocumentPageViewer. Using FlowDocumentScrollViewer, Figure is treated as different anchored block, and can't be paired side by side.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Multiple domain linking to one existing domain I have an existing site almost 85% of its contents are database driven, Now I want 50 more such sites. I have an Idea of using this site as base site and access this site from different domains. I can keep database different for each domain. All of these websites behave and work as independent sites , except the fact, that these all is actually using a single site with their own database . Now Is this a feasible idea ? what are the Pros and cons of this approach ? Is there an issue of Google blocking these sites arise ? I have given one more option of keeping centralized database for sites and keep there code in respective domains. I am confused as am also a newbie in PHP and web development. I found some breakthrough here .htaccess RewriteRule: two domains using same server and directory now I have to see about Google issue Thanks A: A big con is the duplication of comments (as mentioned in the comments). If domain1.com has contains the same, or all most the same content as domain2.com Google gives both sites a penalty which will result in in lower rating. Keep in mind that the same happens if you duplicate content over multiple pages in a website. (domain1.com/page1 having the same content as domain1.com/page2). If the 50 site have unique contents this won't be a problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DjangoUnicodeDecodeError codec can't decode byte 0xdd in position I have a Django Web Application running in Apache with mod_wsgi in my dedicated server with Centos 5.5. However, sometimes (six or seven times in a day) it starts to give 500 Error for some random pages. But if I refresh the page two or three times, the page turns to normal. But once it starts to give 500 error, every other page in my web site gives that error. After I restarted the apache, it turns to normal for 5 or 6 hours but it never ends to give that error. I paste the full error log below but indeed it says that DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0xdd in position 330: invalid continuation byte. What may cause this kind of error and how can I detect it ? I may provide any additional information asap. PS: I have same setup on my local PC(Apache-mod_wsgi) with Win7 and I have never got this error. [Wed Sep 28 12:03:53 2011] [error] [client 46.104.250.30] mod_wsgi (pid=30331): Exception occurred processing WSGI script '/var/www/html/MY_SITE/django.wsgi'., referer: http://www.MY_SITE.com/ [Wed Sep 28 12:03:53 2011] [error] [client 46.104.250.30] Traceback (most recent call last):, referer: http://www.MY_SITE.com/ [Wed Sep 28 12:03:53 2011] [error] [client 46.104.250.30] File "/opt/python2.7.1/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 273, in __call__, referer: http://www.MY_SITE.com/ [Wed Sep 28 12:03:53 2011] [error] [client 46.104.250.30] response = self.get_response(request), referer: http://www.MY_SITE.com/ [Wed Sep 28 12:03:53 2011] [error] [client 46.104.250.30] File "/opt/python2.7.1/lib/python2.7/site-packages/django/core/handlers/base.py", line 169, in get_response, referer: http://www.MY_SITE.com/ [Wed Sep 28 12:03:53 2011] [error] [client 46.104.250.30] response = self.handle_uncaught_exception(request, resolver, sys.exc_info()), referer: http://www.MY_SITE.com/ [Wed Sep 28 12:03:53 2011] [error] [client 46.104.250.30] File "/opt/python2.7.1/lib/python2.7/site-packages/django/core/handlers/base.py", line 203, in handle_uncaught_exception, referer: http://www.MY_SITE.com/ [Wed Sep 28 12:03:53 2011] [error] [client 46.104.250.30] return debug.technical_500_response(request, *exc_info), referer: http://www.MY_SITE.com/ [Wed Sep 28 12:03:53 2011] [error] [client 46.104.250.30] File "/opt/python2.7.1/lib/python2.7/site-packages/django/views/debug.py", line 59, in technical_500_response, referer: http://www.MY_SITE.com/ [Wed Sep 28 12:03:53 2011] [error] [client 46.104.250.30] html = reporter.get_traceback_html(), referer: http://www.MY_SITE.com/ [Wed Sep 28 12:03:53 2011] [error] [client 46.104.250.30] File "/opt/python2.7.1/lib/python2.7/site-packages/django/views/debug.py", line 117, in get_traceback_html, referer: http://www.MY_SITE.com/ [Wed Sep 28 12:03:53 2011] [error] [client 46.104.250.30] frame['vars'] = [(k, force_escape(pprint(v))) for k, v in frame['vars']], referer: http://www.MY_SITE.com/ [Wed Sep 28 12:03:53 2011] [error] [client 46.104.250.30] File "/opt/python2.7.1/lib/python2.7/site-packages/django/template/defaultfilters.py", line 34, in _dec, referer: http://www.MY_SITE.com/ [Wed Sep 28 12:03:53 2011] [error] [client 46.104.250.30] args[0] = force_unicode(args[0]), referer: http://www.MY_SITE.com/ [Wed Sep 28 12:03:53 2011] [error] [client 46.104.250.30] File "/opt/python2.7.1/lib/python2.7/site-packages/django/utils/encoding.py", line 93, in force_unicode, referer: http://www.MY_SITE.com/ [Wed Sep 28 12:03:53 2011] [error] [client 46.104.250.30] raise DjangoUnicodeDecodeError(s, *e.args), referer: http://www.MY_SITE.com/ [Wed Sep 28 12:03:53 2011] [error] [client 46.104.250.30] DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0xdd in position 330: invalid continuation byte. You passed in "<WSGIRequest\\nGET:<QueryDict: {}>,\\nPOST:<QueryDict: {}>,\\nCOOKIES:{},\\nMETA:{'CSRF_COOKIE': '041ed0a93c4b355d4861a0662d49fcb4',\\n 'DOCUMENT_ROOT': '/var/www/html/MY_SITE',\\n 'GATEWAY_INTERFACE': 'CGI/1.1',\\n 'HTTP_ACCEPT': 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',\\n 'HTTP_ACCEPT_ENCOD\\xddNG': 'gzip, deflate',\\n 'HTTP_ACCEPT_LANGUAGE': 'en-us',\\n 'HTTP_CACHE_CONTROL': 'max-age=0',\\n 'HTTP_CONNECT\\xddON': 'keep-alive',\\n 'HTTP_COOK\\xddE': 'csrftoken=10bc570d4ef77b17ce580106dafa9fb6; sessionid=60fb98634573194f7f5e18ef6014f59b',\\n 'HTTP_HOST': 'www.MY_SITE.com',\\n 'HTTP_REFERER': 'http://www.MY_SITE.com/',\\n 'HTTP_USER_AGENT': 'Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B367 Safari/531.21.10',\\n 'PATH_INFO': u'/main/faq/',\\n 'PATH_TRANSLATED': '/var/www/html/MY_SITE/django.wsgi/main/faq/',\\n 'QUERY_STRING': '',\\n 'REMOTE_ADDR': '46.104.250.30',\\n 'REMOTE_PORT': '49643',\\n 'REQUEST_METHOD': 'GET',\\n 'REQUEST_URI': '/main/faq/',\\n 'SCRIPT_FILENAME': '/var/www/html/MY_SITE/django.wsgi',\\n 'SCRIPT_NAME': u'',\\n 'SERVER_ADDR': '93.94.251.82',\\n 'SERVER_ADMIN': 'bilgi@MY_SITE.com',\\n 'SERVER_NAME': 'www.MY_SITE.com',\\n 'SERVER_PORT': '80',\\n 'SERVER_PROTOCOL': 'HTTP/1.1',\\n 'SERVER_SIGNATURE': '<address>Apache/2.2.3 (CentOS) Server at www.MY_SITE.com Port 80</address>\\\\n',\\n 'SERVER_SOFTWARE': 'Apache/2.2.3 (CentOS)',\\n 'mod_wsgi.application_group': 'MY_SITE.com|',\\n 'mod_wsgi.callable_object': 'application',\\n 'mod_wsgi.handler_script': '',\\n 'mod_wsgi.input_chunked': '0',\\n 'mod_wsgi.listener_host': '',\\n 'mod_wsgi.listener_port': '80',\\n 'mod_wsgi.process_group': '',\\n 'mod_wsgi.request_handler': 'wsgi-script',\\n 'mod_wsgi.script_reloading': '1',\\n 'mod_wsgi.version': (3, 3),\\n 'wsgi.errors': <mod_wsgi.Log object at 0x2b7d75ddbfb0>,\\n 'wsgi.file_wrapper': <built-in method file_wrapper of mod_wsgi.Adapter object at 0x2b7d75f12a80>,\\n 'wsgi.input': <mod_wsgi.Input object at 0x2b7d75fa0a30>,\\n 'wsgi.multiprocess': True,\\n 'wsgi.multithread': False,\\n 'wsgi.run_once': False,\\n 'wsgi.url_scheme': 'http',\\n 'wsgi.version': (1, 1)}>" (<type 'str'>), referer: http://www.MY_SITE.com/ The web site works seamlessly both in Apache and Django's built-in developer server at my local computer(Win7,Apache,mod_wsgi) A: In this request the client is sending a <WSGIRequest> with the client header 'HTTP_ACCEPT_ENCOD\\xddNG': 'gzip, deflate' in it. If the actual encoding of the <WSGIRequest> is supposed to be UTF-8, then the server error is legitimate (unless this is not really what the client sent). In UTF-8 byte value 0xdd can only be used as the first of a two-byte character coding, in which case the next byte must have leading bits 10. But here the byte following 0xdd has a leading 0 bit, so that's a decode error using UTF-8. If the actual encoding of the <WSGIRequest> is something else, then the server error may not be legitimate because the client header could be interpreted as 'HTTP_ACCEPT_ENCODÝNG': 'gzip, deflate' (in the case of ISO-8859-1) and ignored. Try to identify the specific client that is sending in these requests. A: You have two problems. (1) Something between your server and this user is mangling the header the user's sending you, turning HTTP_CONNECTION into HTTP_CONNECTÝON. This kind of thing is usually done by the more ancient and brain-dead kinds of web proxy sometimes used by misguided mobile internet providers. In this case they're even screwing with your HTTP_COOKIE, which is sure to make your app non-functional anyway, even if you fix the other problem: (2) It's a bug in Django that it gets an exception trying to read a header name with a non-ASCII/non-UTF-8 byte sequence inside. HTTP explicitly defines header names as being represented in ISO-8859-1 so Django should be using this encoding to convert the header names to Unicode and not UTF-8. All byte sequences are valid in ISO-8859-1 so there should never be a UnicodeDecodeError. In practice there are no headers that ever use non-ASCII names, and browser handling of non-ASCII header values is a bumpy and inconsistent ride. But still, Django should allow, and ignore, the bogus headers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Additional criteria to symfony filter i'm working on a symfony project to manage a database. First i explain how it works: In the database, all elements are associated to an unique element 'scene'. When a user accesses the application, chooses what scene he wants to see (it saves that in a user parameter). So when listing elements, the application should only list elements associated with the scene selected by the user. *Note: all elements have an scene attribute in the table definition. So my problem comes here: I developed a listing of an element entities using the help of a sfPropelPager class to paginate. Also added some filters to search in the list, and for that i used the filter system provided by symfony (<element>FormFilter.class.php and stuff). Now i want the list to not show elements from other scenes than the selected by the user. How can i do to add additional criteria to the criteria given by the filter class? or How would you solve the problem? here is my action code: public function executeUnidadfilter(sfWebRequest $request){ $this->filter = new BaUnidadorganizativaTblFormFilter(); $c = $this->filter->getCriteria(); $this->filter->bind($request->getParameter($this->filter->getName())); if($this->filter->isValid()){ $this->pager = new sfPropelPager('BaUnidadorganizativaTbl',$this->sfPropelPagerLines); echo $this->getUser()->getEscenario(); $this->pager->setCriteria($c); $this->pager->init(); }else{ $this->pager = new sfPropelPager('BaUnidadorganizativaTbl',$this->sfPropelPagerLines); $this->pager->init(); } $this->setTemplate('Unidadlist'); } *Note: 'scene' mentioned below is Escenario in the code thank you very much for your time A: I solved the problem. The trouble was that i assigned the formfilter generated criteria to my criteria var Before the filter was filled. That's why of the error. The resulting code is that: public function executeUnidadfilter(sfWebRequest $request){ $this->filter = new BaUnidadorganizativaTblFormFilter(); $this->filter->bind($request->getParameter($this->filter->getName())); if($this->filter->isValid()){ $this->pager = new sfPropelPager('BaUnidadorganizativaTbl',$this->sfPropelPagerLines); $esc = $this->getUser()->getEscenario(); $c = new Criteria(); $c = $this->filter->getCriteria(); $c->addAnd('codigo_escenario',$esc); $this->pager->setCriteria($c); $this->pager->init(); }else{ $this->pager = new sfPropelPager('BaUnidadorganizativaTbl',$this->sfPropelPagerLines); $this->pager->setCriteria($this->filter->getCriteria()); $this->pager->init(); } $this->message=null; $this->messageType=null; $this->setTemplate('Unidadlist'); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7582827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check if a string is a legal "dd/mm/yyyy" date? Given a string str, how could I check if it is in the dd/mm/yyyy format and contains a legal date ? Some examples: bla bla // false 14/09/2011 // true 09/14/2011 // false 14/9/2011 // false 1/09/2011 // false 14/09/11 // false 14.09.2011 // false 14/00/2011 // false 29/02/2011 // false 14/09/9999 // true A: Try - var strDate = '12/03/2011'; var dateParts = strDate.split("/"); var date = new Date(dateParts[2], (dateParts[1] - 1) ,dateParts[0]); There's more info in this question - Parse DateTime string in JavaScript (the code in my answer is heavily influenced by linked question) Demo - http://jsfiddle.net/xW2p8/ EDIT Updated answer, try - function isValidDate(strDate) { if (strDate.length != 10) return false; var dateParts = strDate.split("/"); var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]); if (date.getDate() == dateParts[0] && date.getMonth() == (dateParts[1] - 1) && date.getFullYear() == dateParts[2]) { return true; } else return false; } This function passes all the test cases. As far as I'm aware, Adam Jurczyk had posted an accurate answer well before I corrected my original wrong answer. He deserves credit for this. Demo - http://jsfiddle.net/2r6eX/1/ A: Edit: exact solution below You could do something like this, but with a more accurate algorithm for day validation: function testDate(str) { var t = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/); if(t === null) return false; var d = +t[1], m = +t[2], y = +t[3]; // Below should be a more acurate algorithm if(m >= 1 && m <= 12 && d >= 1 && d <= 31) { return true; } return false; } http://jsfiddle.net/aMWtj/ Date validation alg.: http://www.eee.hiflyers.co.uk/ProgPrac/DateValidation-algorithm.pdf Exact solution: function that returns a parsed date or null, depending exactly on your requirements. function parseDate(str) { var t = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/); if(t !== null){ var d = +t[1], m = +t[2], y = +t[3]; var date = new Date(y, m - 1, d); if(date.getFullYear() === y && date.getMonth() === m - 1) { return date; } } return null; } http://jsfiddle.net/aMWtj/2/ In case you need the function to return true/false and for a yyyy/mm/dd format function IsValidDate(pText) { var isValid = false ; var t = pText.match(/^(\d{4})\/(\d{2})\/(\d{2})$/); if (t !== null) { var y = +t[1], m = +t[2], d = +t[3]; var date = new Date(y, m - 1, d); isValid = (date.getFullYear() === y && date.getMonth() === m - 1) ; } return isValid ; } A: you can use regular exp to validate date . try like this : re = /^\d{1,2}\/\d{1,2}\/\d{4}$/; if(form.mydate.value != '' && !form.mydate.value.match(re)) //do something here note: this will only work for dd/mm/yyyy for exact match of your requirement use re = /^\d{2}\/\d{2}\/\d{4}$/; A: I'm going to answer a different question, as Misha Moroshko's has already been well-answered: use HTML5. That is, on the assumption that the strings in question arise as user inputs through a Web browser, I propose that the entries be received as <input type = "date" ... I recognize that not all browsers likely to be in use will interpret "date" in a way that rigorously enforces validity. It's the right thing to do, though, will certainly improve as time goes on, and might well be good enough in a particular context even now simply to eliminate the need to validate the date-string after the fact. A: Personally, I think the best solution would be to modify the UI to use dropdowns for the month and possibly day selections. Trying to figure out if 1/2/2001 is January 2nd or February 1st based solely on that input string is impossible. A: Recent discovery: You can use date.js lib, it adds function Date.parseExact so you can just do Date.parseExact(dateString,"dd/MM/yyyy"). It fails when month is 00, but its still usefull. A: for dd/mm/yyyy format only ^(0?[1-9]|[12][0-9]|3[01])[\/](0?[1-9]|1[012])[\/]\d{4}$
{ "language": "en", "url": "https://stackoverflow.com/questions/7582828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How to handle disk full errors in java I am working on a Java application. We read lot of data, manipulate it and then write to files in local m/c. If, in any case, the disk is full then how to handle this exception in Java application. A: Can you specify more exactly what do you mean when you say how to handle this exception? The way I see it there are two ways: * *either you will present that information to user and then the user will be required to clean up some disk space *or you will delete some of the unneeded data that you manipulate on your own, from the application, for example the data that has been for the longest time in the system or by some other criteria. A: This is a good blog post on the topic: http://weblog.janek.org/Archive/2004/12/20/ExceptionWhenWritingToAFu.html Also, this bug ticket for Java, explains various strategies: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4338871 A: You can take a look here. This workaround solves the problem that no exception is thrown when your disk is full. Basically, it is done by this: FileOutputStream fos = ...; fos.write("hello".getBytes()); fos.getFD().sync(); fos.close(); The call to the sync() method will throw a SyncFailedException, when the disk is full.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to enable the (two finger) zoom in/out feature for an image in android Possible Duplicate: android imageView: setting drag and pinch zoom parameters I am very new to android .. I have an image view in my layout .. I want to enable the zoom in and zoom out for the image coming from this image view .. zoom should be done on two finger touch .. can anyone tell me how to accomplish this, Thanks , Raj A: see this private static final String TAG = "Touch"; //These matrices will be used to move and zoom image Matrix matrix = new Matrix(); Matrix savedMatrix = new Matrix(); // We can be in one of these 3 states static final int NONE = 0; static final int DRAG = 1; static final int ZOOM = 2; static final int DRAW =3; int mode = NONE; // Remember some things for zooming PointF start = new PointF(); PointF mid = new PointF(); float oldDist = 1f; // Limit zoomable/pannable image private float[] matrixValues = new float[9]; private float maxZoom; private float minZoom; private float height; private float width; private RectF viewRect; /////////************ touch events functions **************//////////////////// @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if(hasFocus){ init(); } } private void init() { maxZoom = 4; minZoom = 0.25f; height = myimage.getDrawable().getIntrinsicHeight()+20; width = myimage.getDrawable().getIntrinsicWidth()+20; viewRect = new RectF(0, 0, myimage.getWidth()+20, myimage.getHeight()+20); } /////////************touch events for image Moving, panning and zooming ***********/// public boolean onTouch(View v, MotionEvent event) { // Dump touch event to log dumpEvent(event); // Handle touch events here... switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: savedMatrix.set(matrix); start.set(event.getX(), event.getY()); Log.d(TAG, "mode=DRAG"); mode = DRAG; break; case MotionEvent.ACTION_POINTER_DOWN: oldDist = spacing(event); Log.d(TAG, "oldDist=" + oldDist); if (oldDist > 10f) { savedMatrix.set(matrix); midPoint(mid, event); mode = ZOOM; Log.d(TAG, "mode=ZOOM"); } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: mode = NONE; Log.d(TAG, "mode=NONE"); break; case MotionEvent.ACTION_MOVE: if (mode == DRAW){ onTouchEvent(event);} if (mode == DRAG) { ///code for draging.. } else if (mode == ZOOM) { float newDist = spacing(event); Log.d(TAG, "newDist=" + newDist); if (newDist > 10f) { matrix.set(savedMatrix); float scale = newDist / oldDist; matrix.getValues(matrixValues); float currentScale = matrixValues[Matrix.MSCALE_X]; // limit zoom if (scale * currentScale > maxZoom) { scale = maxZoom / currentScale; }else if(scale * currentScale < minZoom){ scale = minZoom / currentScale; } matrix.postScale(scale, scale, mid.x, mid.y); } } break; } myimage.setImageMatrix(matrix); return true; // indicate event was handled } //*******************Determine the space between the first two fingers private float spacing(MotionEvent event) { float x = event.getX(0) - event.getX(1); float y = event.getY(0) - event.getY(1); return FloatMath.sqrt(x * x + y * y); } //************* Calculate the mid point of the first two fingers private void midPoint(PointF point, MotionEvent event) { float x = event.getX(0) + event.getX(1); float y = event.getY(0) + event.getY(1); point.set(x / 2, y / 2); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7582833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Streaming between two NSURLConnections, blocking NSInputStream read blocks all connections? I'm trying to stream data between two iOS NSURLConenctions (one downloading, the other uploading), but can't seem to make it work. * *I have two NSURLConnections running simultaneously. *One is downloading content from a url using a GET request. *The other is uploading the same content just received, to another url, in the request body of a PUT request. *In the upload connection I'm using setHTTPBodyStream to specify a custom NSInputStream whose read method returns data previously received from the other connection. *Both NSURLConnections are scheduled in the run loops of separate background threads, so that any (possibly blocking) delegate callbacks don't mess with each other (and neither with the main thread). So I thought it would work like this: * *The upload connection calls [read:maxLength] (which I have overridden) on the input stream. *Since there's no data available yet, the read call blocks. *On another thread, [connection:didReceiveData:] is called on the delegate of the download connection. *It puts the received data in a shared buffer, thus making it available for the input stream of the upload connection. *The upload stream's read call now isn't blocked anymore, it can return a chunk of data. Unfortunately in practice, this does not work. After the upload stream's read method blocks, the download connection's delegate methods (eg. didReceiveData) don't get called anymore. (Note that if I disable the blocking on the upload side, then didReceiveData on the download side does get called all right.) I suspect that this has to do something with the fact that the upload input stream's read method is called not on the thread where the connection and the stream objects were created, but on some other thread (apparently created by Cocoa). As if this was some shared thread used by both NSURLConnections, so once it's blocked, all other connections stop working as well. Or something like that. Does anyone have an idea about what's really happening? Also, is there a way to control on which thread the request body input stream's read method gets called?
{ "language": "en", "url": "https://stackoverflow.com/questions/7582834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Variable comparison problems I'm still relatively new to C# and the answer to this is probably pretty obvious, but I'm struggling to solve it I have an enum defined as follows: enum Request { None = 0, GetData, SendData, some other values... }; I then have two variables both defined as type Request as follows Request currentRequest; // This is a class member variable Request request; // This is a local variable within a method. The first variable is assigned using currentRequest = Request.GetData; The second local variable request is assigned using request = (Request)data, where data is byte of value 1 (as the value is being decoded from a buffer of USB data being received). I don't know if this is relevant but mention it just in case. I want to compare them within the method in which the second variable is declared, I originally did it like this: if(request != currentRequest) { // Throw an exception } This works most of the time, but occaisionally the exception is thrown because the two values don't equate, however when I check them in the debugger they are both equal to Request.GetData. This got me thinking that the variables may be pointers to objects rather than values so I tried also using... !request.Equals(currentRequest) and request.CompareTo(currentRequest)!=0 and similarly both of these work most of the time but occaisionally fail even though when the values are checked in the debugger they are both Request.GetData. What's really confused me is that it works most of the time, just fails occaisionally - I'd expect it to either work or not work consistently. Any ideas? A: No, if the variables are genuinely of type Request then that's a value type, and using == should be absolutely fine. I suspect that the debugger is showing you something slightly odd. I suggest you make the exception include both request and currentRequest to show you what's going on.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: changing the images Could anyone helps me in the following. I need to show the 3 images in a image box control of asp.net. The images should shown for 30 seconds and those should be one after the other. A: Your question is more about Javascript than C# / ASP.NET. There are several ways to create an Image Slideshow: * *Using pure JavaScript: Create a function to load next image and use SetInterval() function to activate that function after a specific time *Using JQuery plugins like Cycle. Pure JavaScript Example: function changeImage() { // ... var img = new Image(); img.src = "fileNameForTheNextImage"; document["YourIMGTagID"].src = img.src; } // Then in your document load, after DOM Ready: setInterval("changeImage()", 30000); A: I think its better for you to create some javascript for easy reading and call it from code behind using RegisterStartupScript. <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <script type="text/javascript"> // called every n milisecond function changeImage(imgID, imageList) { if (typeof (this.currentImageCounter) == "undefined") { // init counter when necessary this.currentImageCounter = 0; } else { // increment counter between 0 to image array length this.currentImageCounter = (++this.currentImageCounter) % imageList.length; } // display image based on current image counter document.getElementById(imgID).src = imageList[this.currentImageCounter]; } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:Image ID="imgSlideShow" runat="server" ClientIDMode="Static" /> </div> </form> </body> </html> note: make sure you put ClientIDMode="static", otherwise javascript won't recognized your image control. and then call it from code behind: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load imgSlideShow.ImageUrl = "../chimg/1-P.png" ClientScript.RegisterStartupScript(GetType(String), "scChangeImage", _ "setInterval(""changeImage('imgSlideShow', " & _ "new Array('../chimg/1-i.png','../chimg/2-i.png','../chimg/3-i.PNG'))"",2000);", True) End Sub You can also call RegisterStartupScript using C# if you want to. A: You can best do this with jQuery and CSS. See for example Easy Jquery Auto Image Rotator and Create an Image Rotator with Description (CSS/jQuery) or Google JQuery Image Rotator.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: General Question about Android Gallery Control So, I've been doing xml layout for a project that involves getting a horizontal scrollable row of images on a screen, and did so using just a horizontalscrollview. and a bunch of imagebuttons. I used an include to put this on another xml layout page and another programmer will then populate the images dynamically. My question is, how would the gallery control benefit us? I haven't done much Java programming and I've seen some instruction online of how to implement this control, but not a lot on WHY you would use this. It looks like this control works mainly via Java insertion via array, but other than that I can't tell what the benefits are from reading over my way of just creating the layout and having this other programmer insert his own images manually. Another related question - do these images for a gallery need to me imageviews, or can they be imagemaps? Currently they are imagemaps because we want them to be clicable to go to a user's profile, etc. Thanks! A: Gallery is nearly perfect. In one of my projects I do have a LinearLayout with a Gallery in it: <Gallery android:id="@+id/gallery" android:layout_height="0dip" android:layout_weight="1" android:layout_width="fill_parent" android:spacing="2dip" /> An activity implements OnItemClickListener: public class MyActivity extends Activity implements OnItemClickListener { A data structure contains all items and is send to an adapter: private void processGallery() { adapter = new MyAdapter(this, containers, appName); if (adapter != null) { gallery.setAdapter(adapter); } } @Override public void onItemClick(final AdapterView<?> adapterView, final View view, final int position, final long id) { if (containers != null) { container = containers.get(position); if (container != null) { // Handle selected image } } } The adapter is a usual BaseAdapter - nothing magic: public class MyAdapter extends BaseAdapter { private ArrayList<Container> containers; private Context context; public int getCount() { return containers.size(); } public Object getItem(final int position) { return containers.get(position); } public long getItemId(final int position) { return position; } public View getView(final int position, final View contentView, final ViewGroup viewGroup) { ImageView imageView = new ImageView(context); Container container = containers.get(position); if (container != null) { // Do your image thing here } return imageView; } public MyAdapter(final Context context, final ArrayList<Container> containers, final String appName) { this.context = context; this.containers = containers; } } This simple code gives a horizontal scrolling image gallery with clickable items. The click is send to the activity - no need to do something fancy in the adapter. I removed from the code shown here a DrawableCache that I use because my items do come from the web.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fill gradient color in area under line chart in Protovis 3.2 In my project, I use Protovis 3.2 to render line chart. I want to fill gradient color in the area under line chart. Although I have tried available color functions in Protovis but they did not work. Is there any simple solution for this problem? Below is my code to add area into line chart addArea: -> self = this @vis.add(pv.Area) .data(self.data[0].values) .bottom(1) .left((d) -> self.xAxisUnits(d.index)) .height((d) -> self.yAxisUnits(d.value)) .fillStyle(pv.ramp('black', 'red')) .anchor("top") .add(pv.Line) .lineWidth(2) .strokeStyle("#78B9E2") this A: Sorry, but I'm pretty sure Protovis has no support for gradient fills. You might try D3.js, which doesn't support gradients out of the box but offers lower-level access to the SVG element, which you can use to define an svg:linearGradient fill.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get DependencyProperties using reflection (Type.GetProperties)? I got a custom Type that as a couple of fields, and I'd like to only get Dependency Properties. Here is the code that returns all properties : propertyInfos = myType.GetProperties(); foreach (PropertyInfo propertyInfo in propertyInfos) { Console.WriteLine(propertyInfo.Name); } I know I have to add something in parameter for GetProperties, somethg with BindingFlags.XXX but I check everything that is possible as XX and didn't find something that sounds good to me... A: Dependency properties are static fields of type DependencyProperty static IEnumerable<FieldInfo> GetDependencyProperties(Type type) { var dependencyProperties = type.GetFields(BindingFlags.Static | BindingFlags.Public) .Where(p => p.FieldType.Equals(typeof(DependencyProperty))); return dependencyProperties; } If you want to get dependency properties of parents of that control too then you can use the following method: static IEnumerable<FieldInfo> GetDependencyProperties(Type type) { var properties = type.GetFields(BindingFlags.Static | BindingFlags.Public) .Where(f=>f.FieldType == typeof(DependencyProperty)); if (type.BaseType != null) properties = properties.Union(GetDependencyProperties(type.BaseType)); return properties; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7582848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Get Child Content Types of a Content Type How can I get the child content types of a content type? From here I've learned that, all the child content types have the contentTypeId begins with the parent's ID. So, I tried to use the suggested way that is in the link. Let me show you what I've tried first: using (var site = new SPSite(SPContext.Current.Site.ID)) { using (var web = site.RootWeb) { SPContentTypeId ctId = new SPContentTypeId(MasterContentTypeId); SPContentType masterCt = web.ContentTypes[ctId]; var queryString = string.Empty; queryString += "<Where>"; queryString += "<BeginsWith>"; queryString += "<FieldRef Name='ContentTypeId'/>"; queryString += "<Value Type='Text'>"; queryString += MasterContentTypeId; queryString += "</Value>"; queryString += "</BeginsWith>"; queryString += "</Where>"; SPSiteDataQuery query = new SPSiteDataQuery { Query = queryString }; DataTable dt = web.GetSiteData(query); DataView dv = new DataView(dt); foreach (DataRow row in dt.Rows) { //Do Something Necessary } } } But the DataTable returns with no rows. Is this the right way to do this but there's something missing or wrong; or am I doing this all wrong? A: I guess I've found a solution. Here is the reference: link IEnumerable<SPContentType> descendantContentTypes = from SPContentType childCt in web.AvailableContentTypes where childCt.Id.IsChildOf(parentContentTypeId) select childCt;
{ "language": "en", "url": "https://stackoverflow.com/questions/7582851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Programmatically copy indexes from one table to another in SQL Server Basically the exact same question as in this question: How to copy indexes from one table to another in SQL Server, BUT, how do I do it programmatically in T-SQL, given a source table name and destination table name? I.e. without knowing what table up front. I can copy the basic structure SELECT TOP (0) * INTO [BackupTable] FROM [OriginalTable] But that doesn't copy indexes, constraints, triggers etc I ideally would like a stored proc that looks something like: spCloneTableStructure @ExistingTableName, @NewTableName That copies the columns, primary keys and indexes Anything like that exist? (note that I'm on SQL Server 2008 R2) A: This is what I came up with. It works for me and copies all the stuff I care about. CREATE PROCEDURE [dbo].[spCloneTableStructure] @SourceSchema nvarchar(255), @SourceTable nvarchar(255), @DestinationSchema nvarchar(255), @DestinationTable nvarchar(255), @RecreateIfExists bit = 0 AS BEGIN /* Clones an existing table to another table (without data) Optionally drops and re-creates target table Copies: * Structure * Primary key * Indexes (including ASC/DESC, included columns, filters) * Constraints (and unique constraints) DOES NOT copy: * Triggers * File groups * Probably a lot of other things Note: Assumes that you name (unique) constraints with the table name in it (in order to not duplicate constraint names) */ SET NOCOUNT ON; BEGIN TRANSACTION --drop the table if EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = @DestinationSchema AND TABLE_NAME = @DestinationTable) BEGIN if @RecreateIfExists = 1 BEGIN exec('DROP TABLE [' + @DestinationSchema + '].[' + @DestinationTable + ']') END ELSE RETURN END --create the table exec('SELECT TOP (0) * INTO [' + @DestinationSchema + '].[' + @DestinationTable + '] FROM [' + @SourceSchema + '].[' + @SourceTable + ']') DECLARE @PKSchema nvarchar(255), @PKName nvarchar(255) SELECT TOP 1 @PKSchema = CONSTRAINT_SCHEMA, @PKName = CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA = @SourceSchema AND TABLE_NAME = @SourceTable AND CONSTRAINT_TYPE = 'PRIMARY KEY' --create primary key IF NOT @PKSchema IS NULL AND NOT @PKName IS NULL BEGIN DECLARE @PKColumns nvarchar(MAX) SET @PKColumns = '' SELECT @PKColumns = @PKColumns + '[' + COLUMN_NAME + '],' FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME = @SourceTable and TABLE_SCHEMA = @SourceSchema AND CONSTRAINT_SCHEMA = @PKSchema AND CONSTRAINT_NAME= @PKName ORDER BY ORDINAL_POSITION SET @PKColumns = LEFT(@PKColumns, LEN(@PKColumns) - 1) exec('ALTER TABLE [' + @DestinationSchema + '].[' + @DestinationTable + '] ADD CONSTRAINT [PK_' + @DestinationTable + '] PRIMARY KEY CLUSTERED (' + @PKColumns + ')'); END --create other indexes DECLARE @IndexId int, @IndexName nvarchar(255), @IsUnique bit, @IsUniqueConstraint bit, @FilterDefinition nvarchar(max) DECLARE indexcursor CURSOR FOR SELECT index_id, name, is_unique, is_unique_constraint, filter_definition FROM sys.indexes WHERE type = 2 and object_id = object_id('[' + @SourceSchema + '].[' + @SourceTable + ']') OPEN indexcursor; FETCH NEXT FROM indexcursor INTO @IndexId, @IndexName, @IsUnique, @IsUniqueConstraint, @FilterDefinition; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @Unique nvarchar(255) SET @Unique = CASE WHEN @IsUnique = 1 THEN ' UNIQUE ' ELSE '' END DECLARE @KeyColumns nvarchar(max), @IncludedColumns nvarchar(max) SET @KeyColumns = '' SET @IncludedColumns = '' select @KeyColumns = @KeyColumns + '[' + c.name + '] ' + CASE WHEN is_descending_key = 1 THEN 'DESC' ELSE 'ASC' END + ',' from sys.index_columns ic inner join sys.columns c ON c.object_id = ic.object_id and c.column_id = ic.column_id where index_id = @IndexId and ic.object_id = object_id('[' + @SourceSchema + '].[' + @SourceTable + ']') and key_ordinal > 0 order by index_column_id select @IncludedColumns = @IncludedColumns + '[' + c.name + '],' from sys.index_columns ic inner join sys.columns c ON c.object_id = ic.object_id and c.column_id = ic.column_id where index_id = @IndexId and ic.object_id = object_id('[' + @SourceSchema + '].[' + @SourceTable + ']') and key_ordinal = 0 order by index_column_id IF LEN(@KeyColumns) > 0 SET @KeyColumns = LEFT(@KeyColumns, LEN(@KeyColumns) - 1) IF LEN(@IncludedColumns) > 0 BEGIN SET @IncludedColumns = ' INCLUDE (' + LEFT(@IncludedColumns, LEN(@IncludedColumns) - 1) + ')' END IF @FilterDefinition IS NULL SET @FilterDefinition = '' ELSE SET @FilterDefinition = 'WHERE ' + @FilterDefinition + ' ' if @IsUniqueConstraint = 0 exec('CREATE ' + @Unique + ' NONCLUSTERED INDEX [' + @IndexName + '] ON [' + @DestinationSchema + '].[' + @DestinationTable + '] (' + @KeyColumns + ')' + @IncludedColumns + @FilterDefinition) ELSE BEGIN SET @IndexName = REPLACE(@IndexName, @SourceTable, @DestinationTable) exec('ALTER TABLE [' + @DestinationSchema + '].[' + @DestinationTable + '] ADD CONSTRAINT [' + @IndexName + '] UNIQUE NONCLUSTERED (' + @KeyColumns + ')'); END FETCH NEXT FROM indexcursor INTO @IndexId, @IndexName, @IsUnique, @IsUniqueConstraint, @FilterDefinition; END; CLOSE indexcursor; DEALLOCATE indexcursor; --create constraints DECLARE @ConstraintName nvarchar(max), @CheckClause nvarchar(max) DECLARE constraintcursor CURSOR FOR SELECT REPLACE(c.CONSTRAINT_NAME, @SourceTable, @DestinationTable), CHECK_CLAUSE from INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE t INNER JOIN INFORMATION_SCHEMA.CHECK_CONSTRAINTS c ON c.CONSTRAINT_SCHEMA = TABLE_SCHEMA AND c.CONSTRAINT_NAME = t.CONSTRAINT_NAME WHERE TABLE_SCHEMA = @SourceSchema AND TABLE_NAME = @SourceTable OPEN constraintcursor; FETCH NEXT FROM constraintcursor INTO @ConstraintName, @CheckClause; WHILE @@FETCH_STATUS = 0 BEGIN exec('ALTER TABLE [' + @DestinationSchema + '].[' + @DestinationTable + '] WITH CHECK ADD CONSTRAINT [' + @ConstraintName + '] CHECK ' + @CheckClause) exec('ALTER TABLE [' + @DestinationSchema + '].[' + @DestinationTable + '] CHECK CONSTRAINT [' + @ConstraintName + ']') FETCH NEXT FROM constraintcursor INTO @ConstraintName, @CheckClause; END; CLOSE constraintcursor; DEALLOCATE constraintcursor; COMMIT TRANSACTION END A: I have made some alterations to Gareth's work, which BTW works and I think is great. I wanted to include cloning the Triggers and copy the tables content as well. In essence "copy" as much of the table as best I can in one shot. I have included the whole piece of code. Remember this is not completely original, and I do not claim credit for any of Gareth's hard work. I hope this is useful for anyone interested. CREATE PROCEDURE [dbo].[spCloneTableStructure] @SourceSchema nvarchar(255) , @SourceTable nvarchar(255) , @DestinationSchema nvarchar(255) , @DestinationTable nvarchar(255) , @RecreateIfExists bit = 0 AS BEGIN /* Clones an existing table to another table (without data) Optionally drops and re-creates target table Copies: * Structure * Primary key * Indexes (including ASC/DESC, included columns, filters) * Constraints (and unique constraints) DOES NOT copy: * Triggers (It seems to do this now) * File groups * Probably a lot of other things Note: Assumes that you name (unique) constraints with the table name in it (in order to not duplicate constraint names) */ SET NOCOUNT ON; BEGIN TRANSACTION --drop the table IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = @DestinationSchema AND TABLE_NAME = @DestinationTable) BEGIN IF @RecreateIfExists = 1 BEGIN EXEC('DROP TABLE [' + @DestinationSchema + '].[' + @DestinationTable + ']') END ELSE BEGIN RETURN END END --create the table EXEC('SELECT TOP (0) * INTO [' + @DestinationSchema + '].[' + @DestinationTable + '] FROM [' + @SourceSchema + '].[' + @SourceTable + ']') DECLARE @PKSchema nvarchar(255), @PKName nvarchar(255) SELECT TOP 1 @PKSchema = CONSTRAINT_SCHEMA, @PKName = CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA = @SourceSchema AND TABLE_NAME = @SourceTable AND CONSTRAINT_TYPE = 'PRIMARY KEY' ----------------------------------------------------------------------------------- DECLARE @SourceColumns int DECLARE @DestinationColumns int DECLARE @MyColumn int SELECT @SourceColumns = count(*) FROM information_schema.columns WHERE TABLE_NAME = @SourceTable AND TABLE_SCHEMA = @SourceSchema SELECT @DestinationColumns = count(*) FROM information_schema.columns WHERE TABLE_NAME = @DestinationTable AND TABLE_SCHEMA = @DestinationSchema IF @SourceColumns = @DestinationColumns BEGIN DECLARE @FullSourceTable varchar(128) DECLARE @FullDestinationTable varchar(128) SET @FullSourceTable = @SourceSchema+'.'+@SourceTable SET @FullDestinationTable = @DestinationSchema+'.'+@DestinationTable DECLARE @MySQL varchar(MAX) DECLARE @MyValues varchar(MAX) SET @MyColumn = 2 SET @MySQL = 'INSERT INTO '+@FullDestinationTable+' (' SET @MyValues = COL_NAME(OBJECT_ID(@FullSourceTable), 1) + ', ' WHILE @MyColumn <= @DestinationColumns --Change this back BEGIN SET @MyValues = @MyValues+ COL_NAME(OBJECT_ID(@FullSourceTable), @MyColumn) + ', ' SET @MyColumn = @MyColumn + 1 END SELECT @MyValues = SUBSTRING(LTRIM(RTRIM(@MyValues)),1,DATALENGTH(LTRIM(RTRIM(@MyValues)))-1) SET @MySQL = @MySQL+@MyValues+') ' SET @MySQL = @MySQL+' SELECT '+@MyValues+' FROM '+@FullSourceTable --SELECT @MySQL EXEC(@MySQL) END ELSE BEGIN RAISERROR('Number of Source and Destination Columns do not match. Cannot continue with copying content.',16,1) END ----------------------------------------------------------------------------------- --create primary key IF NOT @PKSchema IS NULL AND NOT @PKName IS NULL BEGIN DECLARE @PKColumns nvarchar(MAX) SET @PKColumns = '' SELECT @PKColumns = @PKColumns + '[' + COLUMN_NAME + '],' FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME = @SourceTable AND TABLE_SCHEMA = @SourceSchema AND CONSTRAINT_SCHEMA = @PKSchema AND CONSTRAINT_NAME= @PKName ORDER BY ORDINAL_POSITION SET @PKColumns = LEFT(@PKColumns, LEN(@PKColumns) - 1) EXEC('ALTER TABLE [' + @DestinationSchema + '].[' + @DestinationTable + '] ADD CONSTRAINT [PK_' + @DestinationTable + '] PRIMARY KEY CLUSTERED (' + @PKColumns + ')'); END --create other indexes DECLARE @IndexId int, @IndexName nvarchar(255), @IsUnique bit, @IsUniqueConstraint bit, @FilterDefinition nvarchar(max) ------------------------------------------------------------------------------- -- Cursor Start ------------------------------------------------------------------------------- DECLARE indexcursor CURSOR FOR SELECT index_id, name, is_unique, is_unique_constraint, filter_definition FROM sys.indexes WHERE type = 2 AND object_id = object_id('[' + @SourceSchema + '].[' + @SourceTable + ']') OPEN indexcursor; FETCH NEXT FROM indexcursor INTO @IndexId, @IndexName, @IsUnique, @IsUniqueConstraint, @FilterDefinition; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @Unique nvarchar(255) DECLARE @KeyColumns nvarchar(max), @IncludedColumns nvarchar(max) SET @Unique = CASE WHEN @IsUnique = 1 THEN ' UNIQUE ' ELSE '' END SET @KeyColumns = '' SET @IncludedColumns = '' SELECT @KeyColumns = @KeyColumns + '[' + c.name + '] ' + CASE WHEN is_descending_key = 1 THEN 'DESC' ELSE 'ASC' END + ',' FROM sys.index_columns ic INNER JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id WHERE index_id = @IndexId AND ic.object_id = object_id('[' + @SourceSchema + '].[' + @SourceTable + ']') AND key_ordinal > 0 ORDER BY index_column_id SELECT @IncludedColumns = @IncludedColumns + '[' + c.name + '],' FROM sys.index_columns ic INNER JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id WHERE index_id = @IndexId AND ic.object_id = object_id('[' + @SourceSchema + '].[' + @SourceTable + ']') AND key_ordinal = 0 ORDER BY index_column_id IF LEN(@KeyColumns) > 0 BEGIN SET @KeyColumns = LEFT(@KeyColumns, LEN(@KeyColumns) - 1) END IF LEN(@IncludedColumns) > 0 BEGIN SET @IncludedColumns = ' INCLUDE (' + LEFT(@IncludedColumns, LEN(@IncludedColumns) - 1) + ')' END IF @FilterDefinition IS NULL BEGIN SET @FilterDefinition = '' END ELSE BEGIN SET @FilterDefinition = 'WHERE ' + @FilterDefinition + ' ' END IF @IsUniqueConstraint = 0 BEGIN EXEC('CREATE ' + @Unique + ' NONCLUSTERED INDEX [' + @IndexName + '] ON [' + @DestinationSchema + '].[' + @DestinationTable + '] (' + @KeyColumns + ')' + @IncludedColumns + @FilterDefinition) END ELSE BEGIN SET @IndexName = REPLACE(@IndexName, @SourceTable, @DestinationTable) EXEC('ALTER TABLE [' + @DestinationSchema + '].[' + @DestinationTable + '] ADD CONSTRAINT [' + @IndexName + '] UNIQUE NONCLUSTERED (' + @KeyColumns + ')'); END FETCH NEXT FROM indexcursor INTO @IndexId, @IndexName, @IsUnique, @IsUniqueConstraint, @FilterDefinition; END; CLOSE indexcursor; DEALLOCATE indexcursor; ------------------------------------------------------------------------------- -- Cursor END ------------------------------------------------------------------------------- --create constraints DECLARE @ConstraintName nvarchar(max), @CheckClause nvarchar(max) ------------------------------------------------------------------------------- -- Cursor START ------------------------------------------------------------------------------- DECLARE constraintcursor CURSOR FOR SELECT REPLACE(c.CONSTRAINT_NAME, @SourceTable, @DestinationTable), CHECK_CLAUSE FROM INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE t INNER JOIN INFORMATION_SCHEMA.CHECK_CONSTRAINTS c ON c.CONSTRAINT_SCHEMA = TABLE_SCHEMA AND c.CONSTRAINT_NAME = t.CONSTRAINT_NAME WHERE TABLE_SCHEMA = @SourceSchema AND TABLE_NAME = @SourceTable OPEN constraintcursor; FETCH NEXT FROM constraintcursor INTO @ConstraintName, @CheckClause; WHILE @@FETCH_STATUS = 0 BEGIN EXEC('ALTER TABLE [' + @DestinationSchema + '].[' + @DestinationTable + '] WITH CHECK ADD CONSTRAINT [' + @ConstraintName + '] CHECK ' + @CheckClause) EXEC('ALTER TABLE [' + @DestinationSchema + '].[' + @DestinationTable + '] CHECK CONSTRAINT [' + @ConstraintName + ']') FETCH NEXT FROM constraintcursor INTO @ConstraintName, @CheckClause; END; CLOSE constraintcursor; DEALLOCATE constraintcursor; ------------------------------------------------------------------------------- -- Cursor END ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- Build Triggers on new table START ------------------------------------------------------------------------------- DECLARE @TriggerType varchar(32) DECLARE @CHeader varchar(255) DECLARE @trigger_name varchar(128) DECLARE @table_schema varchar(128) DECLARE @table_name varchar(128) DECLARE @isupdate tinyint DECLARE @isdelete tinyint DECLARE @isinsert tinyint DECLARE @isafter tinyint DECLARE @isinsteadof tinyint DECLARE @disabled tinyint DECLARE @TriggerCode varchar(MAX) DECLARE db_cursor CURSOR FOR SELECT so.name ,( SELECT TOP 1 SCHEMA_NAME(T1.schema_id) FROM sys.tables AS T1 WHERE T1.name = OBJECT_NAME(parent_obj)) ,OBJECT_NAME(parent_obj) ,OBJECTPROPERTY(so.id, 'ExecIsUpdateTrigger') ,OBJECTPROPERTY(so.id, 'ExecIsDeleteTrigger') ,OBJECTPROPERTY(so.id, 'ExecIsInsertTrigger') ,OBJECTPROPERTY(so.id, 'ExecIsAfterTrigger') ,OBJECTPROPERTY(so.id, 'ExecIsInsteadOfTrigger') ,OBJECTPROPERTY(so.id, 'ExecIsTriggerDisabled') ,LTRIM(RTRIM(c.[text])) FROM sys.sysobjects AS so INNER JOIN sys.objects o ON so.id = o.object_id INNER JOIN sys.syscomments AS c ON o.object_id = c.id WHERE so.type = 'TR' AND OBJECT_NAME(parent_object_id) = @SourceTable OPEN db_cursor FETCH NEXT FROM db_cursor INTO @trigger_name, @table_schema, @table_name, @isupdate, @isdelete, @isinsert, @isafter, @isinsteadof, @disabled, @TriggerCode WHILE @@FETCH_STATUS = 0 BEGIN --SELECT @trigger_name, @table_schema, @table_name, @isupdate, @isdelete, @isinsert, @isafter, @isinsteadof, @disabled, @TriggerCode SET @TriggerCode = LTRIM(RTRIM(REPLACE(@TriggerCode, CHAR(13)+CHAR(13)+CHAR(13), CHAR(13)))) SET @TriggerCode = LTRIM(RTRIM(REPLACE(@TriggerCode, CHAR(13)+CHAR(13), CHAR(13)))) ------------------------------------------------------------------------------- --Which one is first? ------------------------------------------------------------------------------- DECLARE @MyStart tinyint DECLARE @MyForStart tinyint DECLARE @MyAfterStart tinyint DECLARE @MyInsteadStart tinyint SELECT @MyForStart = CHARINDEX('for',@TriggerCode) SELECT @TriggerType = LTRIM(RTRIM(SUBSTRING(@TriggerCode,CHARINDEX('for',@TriggerCode)-1, 4 ))) SELECT @MyAfterStart = CHARINDEX('after',@TriggerCode) SELECT @TriggerType = LTRIM(RTRIM(SUBSTRING(@TriggerCode,CHARINDEX('after',@TriggerCode)-1, 6 ))) SELECT @MyInsteadStart = CHARINDEX('instead',@TriggerCode) SELECT @TriggerType = LTRIM(RTRIM(SUBSTRING(@TriggerCode,CHARINDEX('Instead',@TriggerCode)-1, 8 ))) IF @MyAfterStart <> 0 AND @MyAfterStart < @MyForStart BEGIN SET @MyStart = @MyAfterStart SELECT @TriggerType = LTRIM(RTRIM(SUBSTRING(@TriggerCode,@MyStart-1, 6 ))) END ELSE IF @MyInsteadStart <> 0 AND @MyInsteadStart < @MyForStart BEGIN SET @MyStart = @MyInsteadStart SELECT @TriggerType = LTRIM(RTRIM(SUBSTRING(@TriggerCode,@MyStart-1, 8 ))) END ELSE IF @MyForStart <> 0 AND @MyForStart < @MyAfterStart AND @MyForStart < @MyInsteadStart BEGIN SET @MyStart = @MyForStart SELECT @TriggerType = LTRIM(RTRIM(SUBSTRING(@TriggerCode,@MyStart-1, 4 ))) END ------------------------------------------------------------------------------- --Build the correct header and append it to the create trigger code then run it ------------------------------------------------------------------------------- IF @TriggerType LIKE '%FOR%' BEGIN SET @CHeader = 'CREATE TRIGGER ['+@DestinationSchema+'].['+@trigger_name+'] ON ['+@DestinationSchema+'].['+@DestinationTable+']' --print @CHeader+char(13)+SUBSTRING(@TriggerCode,CHARINDEX('FOR',@TriggerCode)-1,DATALENGTH(@TriggerCode)) SET @TriggerCode = @CHeader+char(13)+SUBSTRING(@TriggerCode,CHARINDEX('for',@TriggerCode)-1,DATALENGTH(@TriggerCode)) EXEC(@TriggerCode) END ELSE IF @TriggerType LIKE '%AFTER%' BEGIN SET @CHeader = 'CREATE TRIGGER ['+@DestinationSchema+'].['+@trigger_name+'] ON ['+@DestinationSchema+'].['+@DestinationTable+']' --print @CHeader+char(13)+SUBSTRING(@TriggerCode,CHARINDEX('AFTER',@TriggerCode)-1,DATALENGTH(@TriggerCode)) SET @TriggerCode = @CHeader+char(13)+SUBSTRING(@TriggerCode,CHARINDEX('after',@TriggerCode)-1,DATALENGTH(@TriggerCode)) EXEC(@TriggerCode) END ELSE IF @TriggerType LIKE '%INSTEAD%' BEGIN SET @CHeader = 'CREATE TRIGGER ['+@DestinationSchema+'].['+@trigger_name+'] ON ['+@DestinationSchema+'].['+@DestinationTable+']' --print @CHeader+char(13)+SUBSTRING(@TriggerCode,CHARINDEX('INSTEAD',@TriggerCode)-1,DATALENGTH(@TriggerCode)) SET @TriggerCode = @CHeader+char(13)+SUBSTRING(@TriggerCode,CHARINDEX('instead',@TriggerCode)-1,DATALENGTH(@TriggerCode)) EXEC(@TriggerCode) END FETCH NEXT FROM db_cursor INTO @trigger_name, @table_schema, @table_name, @isupdate, @isdelete, @isinsert, @isafter, @isinsteadof, @disabled, @TriggerCode END CLOSE db_cursor DEALLOCATE db_cursor COMMIT TRANSACTION END A: Thanks Gareth. That works. I have altered to work across databases: CREATE PROCEDURE [dbo].[spCloneDatabaseTableStructurev3] @SourceDatabase nvarchar(max), @SourceSchema nvarchar(max), @SourceTable nvarchar(max), @DestinationDatabase nvarchar(max), @DestinationSchema nvarchar(max), @DestinationTable nvarchar(max), @RecreateIfExists bit = 0 AS BEGIN /* Clones an existing table to another table (without data) Optionally drops and re-creates target table Copies: * Structure * Primary key * Indexes (including ASC/DESC, included columns, filters) * Constraints (and unique constraints) DOES NOT copy: * Triggers * File groups * Probably a lot of other things Note: Assumes that you name (unique) constraints with the table name in it (in order to not duplicate constraint names) */ declare @sql nvarchar(max) SET NOCOUNT ON; BEGIN TRANSACTION set @sql = ' declare @RecreateIfExists bit = ' + convert(varchar(max),@RecreateIfExists) + ' --drop the table if EXISTS (SELECT * FROM [' + @DestinationDatabase + '].INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ''' + @DestinationSchema + ''' AND TABLE_NAME = ''' + @DestinationTable + ''') BEGIN if @RecreateIfExists = 1 BEGIN DROP TABLE [' + @DestinationDatabase + '].[' + @DestinationSchema + '].[' + @DestinationTable + '] END ELSE RETURN END --create the table SELECT TOP (0) * INTO [' + @DestinationDatabase + '].[' + @DestinationSchema + '].[' + @DestinationTable + '] FROM [' + @SourceDatabase + '].[' + @SourceSchema + '].[' + @SourceTable + '] DECLARE @PKSchema nvarchar(255), @PKName nvarchar(255) SELECT TOP 1 @PKSchema = CONSTRAINT_SCHEMA, @PKName = CONSTRAINT_NAME FROM [' + @SourceDatabase + '].INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA = ''' + @SourceSchema + ''' AND TABLE_NAME = ''' + @SourceTable + ''' AND CONSTRAINT_TYPE = ''PRIMARY KEY'' --create primary key IF NOT @PKSchema IS NULL AND NOT @PKName IS NULL BEGIN DECLARE @PKColumns nvarchar(MAX) SET @PKColumns = '''' SELECT @PKColumns = @PKColumns + ''['' + COLUMN_NAME + ''],'' FROM [' + @SourceDatabase + '].INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME = ''' + @SourceTable + ''' and TABLE_SCHEMA = ''' + @SourceSchema + ''' AND CONSTRAINT_SCHEMA = @PKSchema AND CONSTRAINT_NAME= @PKName ORDER BY ORDINAL_POSITION SET @PKColumns = LEFT(@PKColumns, LEN(@PKColumns) - 1) exec(''ALTER TABLE [' + @DestinationDatabase + '].[' + @DestinationSchema + '].[' + @DestinationTable + '] ADD CONSTRAINT [PK_' + @DestinationTable + '] PRIMARY KEY CLUSTERED ('' + @PKColumns + '')'') END --create other indexes DECLARE @IndexId int, @IndexName nvarchar(255), @IsUnique bit, @IsUniqueConstraint bit, @FilterDefinition nvarchar(max) DECLARE indexcursor CURSOR FOR SELECT index_id, name, is_unique, is_unique_constraint, filter_definition FROM sys.indexes WHERE type = 2 and object_id = object_id(''[' + @SourceSchema + '].[' + @SourceTable + ']'') OPEN indexcursor; FETCH NEXT FROM indexcursor INTO @IndexId, @IndexName, @IsUnique, @IsUniqueConstraint, @FilterDefinition; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @Unique nvarchar(255) SET @Unique = CASE WHEN @IsUnique = 1 THEN '' UNIQUE '' ELSE '''' END DECLARE @KeyColumns nvarchar(max), @IncludedColumns nvarchar(max) SET @KeyColumns = '''' SET @IncludedColumns = '''' select @KeyColumns = @KeyColumns + ''['' + c.name + ''] '' + CASE WHEN is_descending_key = 1 THEN ''DESC'' ELSE ''ASC'' END + '','' from sys.index_columns ic inner join sys.columns c ON c.object_id = ic.object_id and c.column_id = ic.column_id where index_id = @IndexId and ic.object_id = object_id(''[' + @SourceSchema + '].[' + @SourceTable + ']'') and key_ordinal > 0 order by index_column_id select @IncludedColumns = @IncludedColumns + ''['' + c.name + ''],'' from sys.index_columns ic inner join sys.columns c ON c.object_id = ic.object_id and c.column_id = ic.column_id where index_id = @IndexId and ic.object_id = object_id(''[' + @SourceSchema + '].[' + @SourceTable + ']'') and key_ordinal = 0 order by index_column_id IF LEN(@KeyColumns) > 0 SET @KeyColumns = LEFT(@KeyColumns, LEN(@KeyColumns) - 1) IF LEN(@IncludedColumns) > 0 BEGIN SET @IncludedColumns = '' INCLUDE ('' + LEFT(@IncludedColumns, LEN(@IncludedColumns) - 1) + '')'' END IF @FilterDefinition IS NULL SET @FilterDefinition = '''' ELSE SET @FilterDefinition = ''WHERE '' + @FilterDefinition + '' '' if @IsUniqueConstraint = 0 exec(''CREATE '' + @Unique + '' NONCLUSTERED INDEX ['' + @IndexName + ''] ON [' + @DestinationDatabase + '].[' + @DestinationSchema + '].[' + @DestinationTable + '] ('' + @KeyColumns + '')'' + @IncludedColumns + @FilterDefinition) ELSE BEGIN SET @IndexName = REPLACE(@IndexName, ''' + @SourceTable + ''', ''' + @DestinationTable + ''') exec(''ALTER TABLE [' + @DestinationDatabase + '].[' + @DestinationSchema + '].[' + @DestinationTable + '] ADD CONSTRAINT ['' + @IndexName + ''] UNIQUE NONCLUSTERED ('' + @KeyColumns + '')'') END FETCH NEXT FROM indexcursor INTO @IndexId, @IndexName, @IsUnique, @IsUniqueConstraint, @FilterDefinition; END; CLOSE indexcursor; DEALLOCATE indexcursor; --create constraints DECLARE @ConstraintName nvarchar(max), @CheckClause nvarchar(max) DECLARE constraintcursor CURSOR FOR SELECT REPLACE(c.CONSTRAINT_NAME, ''' + @SourceTable + ''', ''' + @DestinationTable + '''), CHECK_CLAUSE from [' + @SourceDatabase + '].INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE t INNER JOIN [' + @SourceDatabase + '].INFORMATION_SCHEMA.CHECK_CONSTRAINTS c ON c.CONSTRAINT_SCHEMA = TABLE_SCHEMA AND c.CONSTRAINT_NAME = t.CONSTRAINT_NAME WHERE TABLE_SCHEMA = ''' + @SourceSchema + ''' AND TABLE_NAME = ''' + @SourceTable + ''' OPEN constraintcursor; FETCH NEXT FROM constraintcursor INTO @ConstraintName, @CheckClause; WHILE @@FETCH_STATUS = 0 BEGIN exec(''ALTER TABLE [' + @DestinationDatabase + '].[' + @DestinationSchema + '].[' + @DestinationTable + '] WITH CHECK ADD CONSTRAINT ['' + @ConstraintName + ''] CHECK '' + @CheckClause) exec(''ALTER TABLE [' + @DestinationDatabase + '].[' + @DestinationSchema + '].[' + @DestinationTable + '] CHECK CONSTRAINT ['' + @ConstraintName + '']'') FETCH NEXT FROM constraintcursor INTO @ConstraintName, @CheckClause; END; CLOSE constraintcursor; DEALLOCATE constraintcursor;' exec(@sql) COMMIT TRANSACTION END A: To give you an idea of what's involved (and why you should use SMO for this as mentioned in comments): * *Get list of indexes from sys.indexes based on the object_ID of the source table * *This includes other info like UNIQUE, PK, IGNORE_DUP_KEY, FILL_FACTOR, PADDED, DISABLED, ROW LOCKS, PAGE LOCKS which will all need to be coded separately in your dynamic SQL *Get list of all key fields (and their order, and if they are ASC or DESC) for each index from sys.index_columns. This will involve JOINing sys.columns for the names since they are all column IDs *Get list of included fields from sys.index_columns *Get a list of filters for each index from sys.indexes Now translate all the above data into valid SQL scripts to execute on the target table. For efficiency you should also script out the clustered index first and run it, since it will take longer to build a cluster if there are already non-clustered indexes in place. A: Thanks Gareth. Good work! I needed a TSQL script which works across databases. Basicly what F_Face did. I've adjusted F_Face modification because there is still a hard coded database name and some statements are relying on that. Anyway, I agree to all the comments that this isn't the way a deep structure copy of a table should be done. Use SMO via PowerShell via xp_cmdshell via TSQL to do it in a propper way would be my suggestion. In that way SMO is taking care that everything is copied and that next SQL Server generation works as well with it. This mentioned, here the code: --If the SP exists, we do nothing. If we would drop it, we would loose security settings. --If the SP doesn't exist, create a dummy SP to be able to use ALTER PROCEDURE in both cases. DECLARE @spName varchar(255) SET @spName='spCloneTableStructure' IF object_id(@spName) IS NULL --does the SP exist? EXEC ('CREATE PROCEDURE dbo.'+@spName+' AS SELECT 1') --create dummy sp GO ALTER PROCEDURE [dbo].[spCloneTableStructure] @SourceDatabase nvarchar(max), @SourceSchema nvarchar(max), @SourceTable nvarchar(max), @DestinationDatabase nvarchar(max), @DestinationSchema nvarchar(max), @DestinationTable nvarchar(max), @RecreateIfExists bit = 0 AS BEGIN /* Clones an existing table to another table (without data) Optionally drops and re-creates target table Copies: * Structure * Primary key * Indexes (including ASC/DESC, included columns, filters) * Constraints (and unique constraints) DOES NOT copy: * Triggers * File groups * Probably a lot of other things Note: Assumes that you name (unique) constraints with the table name in it (in order to not duplicate constraint names) */ DECLARE @sql NVARCHAR(MAX) SET NOCOUNT ON; BEGIN TRANSACTION set @sql = 'DECLARE @RecreateIfExists bit = ' + convert(varchar(max),@RecreateIfExists) + ' --drop the table if EXISTS (SELECT * FROM [' + @DestinationDatabase + '].INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ''' + @DestinationSchema + ''' AND TABLE_NAME = ''' + @DestinationTable + ''') BEGIN IF @RecreateIfExists = 1 BEGIN DROP TABLE [' + @DestinationDatabase + '].[' + @DestinationSchema + '].[' + @DestinationTable + '] END ELSE RETURN END --create the table SELECT TOP (0) * INTO [' + @DestinationDatabase + '].[' + @DestinationSchema + '].[' + @DestinationTable + '] FROM [' + @SourceDatabase + '].[' + @SourceSchema + '].[' + @SourceTable + '] DECLARE @PKSchema nvarchar(255), @PKName nvarchar(255) SELECT TOP 1 @PKSchema = CONSTRAINT_SCHEMA, @PKName = CONSTRAINT_NAME FROM [' + @SourceDatabase + '].INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA = ''' + @SourceSchema + ''' AND TABLE_NAME = ''' + @SourceTable + ''' AND CONSTRAINT_TYPE = ''PRIMARY KEY'' --create primary key IF NOT @PKSchema IS NULL AND NOT @PKName IS NULL BEGIN DECLARE @PKColumns nvarchar(MAX) SET @PKColumns = '''' SELECT @PKColumns = @PKColumns + ''['' + COLUMN_NAME + ''],'' FROM [' + @SourceDatabase + '].INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME = ''' + @SourceTable + ''' AND TABLE_SCHEMA = ''' + @SourceSchema + ''' AND CONSTRAINT_SCHEMA = @PKSchema AND CONSTRAINT_NAME= @PKName ORDER BY ORDINAL_POSITION SET @PKColumns = LEFT(@PKColumns, LEN(@PKColumns) - 1) EXEC(''ALTER TABLE [' + @DestinationDatabase + '].[' + @DestinationSchema + '].[' + @DestinationTable + '] ADD CONSTRAINT [PK_' + @DestinationTable + '] PRIMARY KEY CLUSTERED ('' + @PKColumns + '')'') END --create other indexes DECLARE @IndexId int, @IndexName nvarchar(255), @IsUnique bit, @IsUniqueConstraint bit, @FilterDefinition nvarchar(max) DECLARE indexcursor CURSOR FOR SELECT index_id, name, is_unique, is_unique_constraint, filter_definition FROM ['+@SourceDatabase+'].sys.indexes WHERE type = 2 AND object_id = object_id(''['+@SourceDatabase+'].[' + @SourceSchema + '].[' + @SourceTable + ']'') OPEN indexcursor; FETCH NEXT FROM indexcursor INTO @IndexId, @IndexName, @IsUnique, @IsUniqueConstraint, @FilterDefinition; WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @Unique nvarchar(255) SET @Unique = CASE WHEN @IsUnique = 1 THEN '' UNIQUE '' ELSE '''' END DECLARE @KeyColumns nvarchar(max), @IncludedColumns nvarchar(max) SET @KeyColumns = '''' SET @IncludedColumns = '''' SELECT @KeyColumns = @KeyColumns + ''['' + c.name + ''] '' + CASE WHEN is_descending_key = 1 THEN ''DESC'' ELSE ''ASC'' END + '','' FROM ['+@SourceDatabase+'].sys.index_columns ic INNER JOIN ['+@SourceDatabase+'].sys.columns c ON c.object_id = ic.object_id and c.column_id = ic.column_id WHERE index_id = @IndexId AND ic.object_id = object_id(''['+@SourceDatabase+'].[' + @SourceSchema + '].[' + @SourceTable + ']'') AND key_ordinal > 0 ORDER BY index_column_id SELECT @IncludedColumns = @IncludedColumns + ''['' + c.name + ''],'' from ['+@SourceDatabase+'].sys.index_columns ic INNER JOIN ['+@SourceDatabase+'].sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id WHERE index_id = @IndexId AND ic.object_id = object_id(''['+@SourceDatabase+'].[' + @SourceSchema + '].[' + @SourceTable + ']'') AND key_ordinal = 0 ORDER BY index_column_id IF LEN(@KeyColumns) > 0 SET @KeyColumns = LEFT(@KeyColumns, LEN(@KeyColumns) - 1) IF LEN(@IncludedColumns) > 0 BEGIN SET @IncludedColumns = '' INCLUDE ('' + LEFT(@IncludedColumns, LEN(@IncludedColumns) - 1) + '')'' END IF @FilterDefinition IS NULL SET @FilterDefinition = '''' ELSE SET @FilterDefinition = ''WHERE '' + @FilterDefinition + '' '' if @IsUniqueConstraint = 0 exec(''CREATE '' + @Unique + '' NONCLUSTERED INDEX ['' + @IndexName + ''] ON [' + @DestinationDatabase + '].[' + @DestinationSchema + '].[' + @DestinationTable + '] ('' + @KeyColumns + '')'' + @IncludedColumns + @FilterDefinition) ELSE BEGIN SET @IndexName = REPLACE(@IndexName, ''' + @SourceTable + ''', ''' + @DestinationTable + ''') exec(''ALTER TABLE [' + @DestinationDatabase + '].[' + @DestinationSchema + '].[' + @DestinationTable + '] ADD CONSTRAINT ['' + @IndexName + ''] UNIQUE NONCLUSTERED ('' + @KeyColumns + '')'') END FETCH NEXT FROM indexcursor INTO @IndexId, @IndexName, @IsUnique, @IsUniqueConstraint, @FilterDefinition; END; CLOSE indexcursor; DEALLOCATE indexcursor; --create constraints DECLARE @ConstraintName nvarchar(max), @CheckClause nvarchar(max) DECLARE constraintcursor CURSOR FOR SELECT REPLACE(c.CONSTRAINT_NAME, ''' + @SourceTable + ''', ''' + @DestinationTable + '''), CHECK_CLAUSE FROM [' + @SourceDatabase + '].INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE t INNER JOIN [' + @SourceDatabase + '].INFORMATION_SCHEMA.CHECK_CONSTRAINTS c ON c.CONSTRAINT_SCHEMA = TABLE_SCHEMA AND c.CONSTRAINT_NAME = t.CONSTRAINT_NAME WHERE TABLE_SCHEMA = ''' + @SourceSchema + ''' AND TABLE_NAME = ''' + @SourceTable + ''' OPEN constraintcursor; FETCH NEXT FROM constraintcursor INTO @ConstraintName, @CheckClause; WHILE @@FETCH_STATUS = 0 BEGIN exec(''ALTER TABLE [' + @DestinationDatabase + '].[' + @DestinationSchema + '].[' + @DestinationTable + '] WITH CHECK ADD CONSTRAINT ['' + @ConstraintName + ''] CHECK '' + @CheckClause) exec(''ALTER TABLE [' + @DestinationDatabase + '].[' + @DestinationSchema + '].[' + @DestinationTable + '] CHECK CONSTRAINT ['' + @ConstraintName + '']'') FETCH NEXT FROM constraintcursor INTO @ConstraintName, @CheckClause; END; CLOSE constraintcursor; DEALLOCATE constraintcursor;' --PRINT SUBSTRING(@sql, 0, 4000) --PRINT SUBSTRING(@sql, 4000, 8000) EXEC(@sql) COMMIT TRANSACTION END A: This is quick and dirty mod, based on this question: Generate CREATE scripts for a list of indexes but should get you most of the way there. You could do what you are already doing to clone the structure, and you a version of this proc to do they indexes and then modify as necessary: CREATE sp_CloneIndex @OldTableName varchar(50), @NewTableName varchar(50) AS WITH indexCTE AS ( SELECT DISTINCT i.index_id, i.name, i.object_id FROM sys.indexes i INNER JOIN sys.index_columns ic ON i.index_id = ic.index_id AND i.object_id = ic.object_id WHERE EXISTS (SELECT * FROM sys.columns c WHERE c.column_id = ic.column_id AND c.object_id = ic.object_id) ), indexCTE2 AS ( SELECT indexCTE.name 'IndexName', OBJECT_NAME(indexCTE.object_ID) 'TableName', CASE indexCTE.index_id WHEN 1 THEN 'CLUSTERED' ELSE 'NONCLUSTERED' END AS 'IndexType', (SELECT DISTINCT c.name + ',' FROM sys.columns c INNER JOIN sys.index_columns ic ON c.object_id = ic.object_id AND ic.column_id = c.column_id AND ic.Is_Included_Column = 0 WHERE indexCTE.OBJECT_ID = ic.object_id AND indexCTE.index_id = ic.index_id FOR XML PATH('') ) ixcols, ISNULL( (SELECT DISTINCT c.name + ',' FROM sys.columns c INNER JOIN sys.index_columns ic ON c.object_id = ic.object_id AND ic.column_id = c.column_id AND ic.Is_Included_Column = 1 WHERE indexCTE.OBJECT_ID = ic.object_id AND indexCTE.index_id = ic.index_id FOR XML PATH('') ), '') includedcols FROM indexCTE ) SELECT 'CREATE ' + IndexType + ' INDEX ' + IndexName + ' ON ' + @NewTableName + '(' + SUBSTRING(ixcols, 1, LEN(ixcols)-1) + CASE LEN(includedcols) WHEN 0 THEN ')' ELSE ') INCLUDE (' + SUBSTRING(includedcols, 1, LEN(includedcols)-1) + ')' END FROM indexCTE2 where tablename = @OldTableName ORDER BY TableName, IndexName A: Here is my version. The destination table and schema are the same like the source with something added at the end in my case _STG. You can add something at the end using @NameAdd NVARCHAR(128) variable. I did it this way to avoid sql injection. In my version no outside provided text is executed. IF EXISTS(SELECT * FROM sys.objects WHERE type = 'P' AND name='uspCloneTableStructure') BEGIN DROP PROCEDURE [dbo].[uspCloneTableStructure] END GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE [dbo].[uspCloneTableStructure] @inSourceSchema nvarchar(128), @inSourceTable nvarchar(128), @RecreateTable bit = 0, @RecreateIndexes bit = 0 AS BEGIN SET NOCOUNT ON; DECLARE @RecID INT ,@RecCount INT ,@ExecuteCMD NVARCHAR(MAX) = '' ,@DateTime VARCHAR(100) ,@SourceSchema NVARCHAR(128) ,@SourceTable NVARCHAR(128) ,@DestinationSchema NVARCHAR(128) ,@DestinationTable NVARCHAR(128) ,@NameAdd NVARCHAR(128) = N'_STG'; BEGIN TRANSACTION; BEGIN TRY; SET XACT_ABORT ON; SELECT @SourceSchema = s.name ,@SourceTable = t.name ,@DestinationSchema = s.name ,@DestinationTable = t.name + @NameAdd FROM sys.tables AS t INNER JOIN sys.schemas AS s ON s.schema_id = t.schema_id WHERE s.name = @inSourceSchema AND t.name = @inSourceTable; --drop the table if @RecreateTable = 1 AND @DestinationSchema IS NOT NULL AND @DestinationTable IS NOT NULL BEGIN SET @ExecuteCMD ='IF EXISTS (SELECT * FROM sys.tables AS t INNER JOIN sys.schemas AS s ON s.schema_id = t.schema_id WHERE s.name = ''' + @DestinationSchema + ''' AND t.name = ''' + @DestinationTable + ''') DROP TABLE [' + @DestinationSchema + '].[' + @DestinationTable + '] SELECT TOP (0) * INTO [' + @DestinationSchema + '].[' + @DestinationTable + '] FROM [' + @SourceSchema + '].[' + @SourceTable + ']'; SELECT @DateTime = CONVERT(VARCHAR(100),GETDATE(),(121)); RAISERROR('--Creating table: %s at: %s ',0,1,@DestinationTable,@DateTime) WITH NOWAIT; PRINT @ExecuteCMD; EXECUTE sp_executesql @ExecuteCMD; END; IF @RecreateIndexes = 1 BEGIN --create other indexes DECLARE @IndexId INT ,@IndexName NVARCHAR(128) ,@FilterDefinition NVARCHAR(MAX) ,@IsPrimaryKey BIT ,@Unique NVARCHAR(128) ,@Clustered NVARCHAR(128) ,@DataCompression NVARCHAR(60) ,@KeyColumns NVARCHAR(MAX) ,@IncludedColumns NVARCHAR(MAX); IF OBJECT_ID('tempdb.dbo.#Indexes') IS NOT NULL BEGIN DROP TABLE dbo.#Indexes; END; CREATE TABLE dbo.#Indexes ( [RecID] INT IDENTITY(1, 1) PRIMARY KEY ,IndexId INT ,IndexName NVARCHAR(128) ,IsUnique BIT ,FilterDefinition NVARCHAR(MAX) ,IsClustered INT ,IsPrimaryKey BIT ,DataCompression NVARCHAR(60) ); INSERT INTO dbo.#Indexes ( IndexId ,IndexName ,IsUnique ,FilterDefinition ,IsClustered ,IsPrimaryKey ,DataCompression ) SELECT i.index_id ,i.name ,i.is_unique ,i.filter_definition ,i.index_id ,i.is_primary_key ,sp.data_compression_desc FROM sys.indexes AS i INNER JOIN sys.tables AS t ON t.[object_id] = i.[object_id] INNER JOIN sys.schemas AS s ON s.[schema_id] = t.[schema_id] INNER JOIN sys.partitions AS sp ON i.[object_id] = sp.[object_id] AND i.[index_id] = sp.[index_id] AND sp.partition_number = 1 WHERE i.type <>0 AND s.name = @SourceSchema AND t.name = @SourceTable; SELECT @RecCount = COUNT(*) FROM dbo.#Indexes; SET @RecID = 1; WHILE (@RecID <= @RecCount) BEGIN SELECT @IndexId = IndexId ,@IndexName = IndexName ,@Unique = CASE WHEN IsUnique = 1 THEN ' UNIQUE ' ELSE '' END ,@FilterDefinition = FilterDefinition ,@Clustered = CASE WHEN IsClustered = 1 THEN ' CLUSTERED ' ELSE ' NONCLUSTERED ' END ,@IsPrimaryKey = IsPrimaryKey ,@DataCompression = DataCompression ,@KeyColumns = '' ,@IncludedColumns = '' FROM dbo.#Indexes WHERE [RecID] = @RecID; SELECT @KeyColumns = @KeyColumns + '[' + c.name + '] ' + CASE WHEN is_descending_key = 1 THEN 'DESC' ELSE 'ASC' END + ',' FROM sys.index_columns ic INNER JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id INNER JOIN sys.tables AS t ON t.object_id = c.object_id INNER JOIN sys.schemas AS s ON s.schema_id = t.schema_id WHERE ic.index_id = @IndexId AND s.name = @SourceSchema AND t.name = @SourceTable AND key_ordinal > 0 ORDER BY index_column_id; SELECT @IncludedColumns = @IncludedColumns + '[' + c.name + '],' FROM sys.index_columns ic INNER JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id INNER JOIN sys.tables AS t ON t.object_id = c.object_id INNER JOIN sys.schemas AS s ON s.schema_id = t.schema_id WHERE ic.index_id = @IndexId AND s.name = @SourceSchema AND t.name = @SourceTable AND key_ordinal = 0 ORDER BY index_column_id; IF LEN(@KeyColumns) > 0 SET @KeyColumns = LEFT(@KeyColumns, LEN(@KeyColumns) - 1); IF LEN(@IncludedColumns) > 0 BEGIN SET @IncludedColumns = ' INCLUDE (' + LEFT(@IncludedColumns, LEN(@IncludedColumns) - 1) + ')'; END IF @FilterDefinition IS NULL SET @FilterDefinition = ''; ELSE SET @FilterDefinition = 'WHERE ' + @FilterDefinition + ' '; --create the index or PK IF @IsPrimaryKey = 1 SET @ExecuteCMD = 'ALTER TABLE [' + @DestinationSchema + '].[' + @DestinationTable + '] ADD CONSTRAINT [' + @IndexName + @NameAdd + '] PRIMARY KEY CLUSTERED (' + @KeyColumns + ') WITH (SORT_IN_TEMPDB=ON,DATA_COMPRESSION='+@DataCompression+');'; ELSE SET @ExecuteCMD = 'CREATE ' + @Unique + @Clustered + ' INDEX [' + @IndexName + '] ON [' + @DestinationSchema + '].[' + @DestinationTable + '] (' + @KeyColumns + ')' + @IncludedColumns + @FilterDefinition + ' WITH (SORT_IN_TEMPDB=ON,DATA_COMPRESSION='+@DataCompression+');'; SELECT @DateTime = CONVERT(VARCHAR(100),GETDATE(),(121)); RAISERROR('--Creating index: %s%s at: %s ',0,1,@IndexName,@NameAdd,@DateTime) WITH NOWAIT; PRINT @ExecuteCMD; EXECUTE sp_executesql @ExecuteCMD; SET @RecID = @RecID + 1; END;/*While loop*/ END; COMMIT TRAN; SET XACT_ABORT OFF; END TRY BEGIN CATCH; SET XACT_ABORT OFF; IF (XACT_STATE() != 0) BEGIN; ROLLBACK TRANSACTION; END; THROW; -- RETURN; END CATCH; END GO A: Another procedure to clone ONLY foreign keys (Note that referenced table must already exists, obviously). CREATE PROCEDURE [dbo].[spCloneFKStructure] @SourceDatabase nvarchar(max), @SourceSchema nvarchar(max), @SourceTable nvarchar(max), @DestinationDatabase nvarchar(max), @DestinationSchema nvarchar(max), @DestinationTable nvarchar(max) AS BEGIN declare @sql nvarchar(max) SET NOCOUNT ON; BEGIN TRANSACTION set @sql = ' --create foreign keys DECLARE @ConstraintName nvarchar(max),@ColName nvarchar(max),@RefTable nvarchar(max),@RefColName nvarchar(max) DECLARE fkcursor CURSOR FOR select a.name,c.name,object_name(b.referenced_object_id,db_id(''' + @SourceDatabase + ''')),d.name from [' + @SourceDatabase + '].sys.foreign_keys a join [' + @SourceDatabase + '].sys.foreign_key_columns b on a.object_id=b.constraint_object_id join [' + @SourceDatabase + '].sys.columns c on b.parent_column_id = c.column_id and a.parent_object_id=c.object_id join [' + @SourceDatabase + '].sys.columns d on b.referenced_column_id = d.column_id and a.referenced_object_id = d.object_id where object_name(a.parent_object_id,db_id(''' + @SourceDatabase + ''')) = ''' + @SourceTable + ''' order by c.name OPEN fkcursor; FETCH NEXT FROM fkcursor INTO @ConstraintName, @ColName, @RefTable, @RefColName; WHILE @@FETCH_STATUS = 0 BEGIN exec(''ALTER TABLE [' + @DestinationDatabase + '].[' + @DestinationSchema + '].[' + @DestinationTable + '] ADD CONSTRAINT ['' + @ConstraintName + ''] FOREIGN KEY ('' + @ColName + '') REFERENCES '' + @RefTable + ''('' + @RefColName + '')'') FETCH NEXT FROM fkcursor INTO @ConstraintName, @ColName, @RefTable, @RefColName; END; CLOSE fkcursor; DEALLOCATE fkcursor;' exec(@sql) COMMIT TRANSACTION END
{ "language": "en", "url": "https://stackoverflow.com/questions/7582852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: What WPF threading approach should I go with? I'm writing a WPF application (new technique, mostly I've been writing in WinForms). My goal is to make UI responsive whole time, and I've read that it can be achived using Threading/BackgroundWorker. I think that I should use background worker to put there time consuming methods. But I plan to use method *m_AddLog(string logText)* which should append text to textbox. This method I want to call from main UI thread aswell as from background worker, so messages would be sent immediatelly while processing in backround instead of waiting for background task to end. Could you please kindly advise how to write properly write these methods for UI being fully responsive as I don't know much about delegates, invoking, background workers, etc? A: If you want to run some background process then update the UI on completion the following pattern works well (if ran from the UI thread). Task.Factory.StartNew(() => { // Background work }).ContinueWith((t) => { // Update UI thread }, TaskScheduler.FromCurrentSynchronizationContext()); Put the background work in the first task and the UI work in the following his is task. The TaskScheduler option ensures the second task runs on the UI thread. A: Most of the items in wpf application using task and dispatcher will give better results. have a Look at the following code hope this may helps you.. In the below code i have considered a scenario like fetching images from remote server and i created a task for doing that... in the task in side for loop i am using dispatched thread to update UI to notify the progress... and after fetching all the images execution will be moved to continue block.... You can have a look at the following link that may helps you to understand it better ObservableCollection items= new ObservableCollection(); TaskFactory tFactory = new TaskFactory(); tFactory.StartNew(() => { for (int i = 0; i < 50; i++) { //Request to server System.Windows.Application.Current.Dispatcher.BeginInvoke((Action)delegate() { // UPDATE PROGRESS BAR IN UI }); items.Add((""); } }).ContinueWith(t => { if (t.IsFaulted) { // EXCEPTION IF THREAD IS FAULT throw t.Exception; } System.Windows.Application.Current.Dispatcher.BeginInvoke((Action)delegate() { //PROCESS DATA AND DISPLAY }); }); A: As People Said there are tons of question that will show you how to do that But if you want to compare it you can find it here with detailed comparison
{ "language": "en", "url": "https://stackoverflow.com/questions/7582853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Error in creator function when trying to adapt sqlalchemy's polymorphic association example I am looking at http://www.sqlalchemy.org/trac/browser/examples/generic_associations/discriminator_on_association.py and trying to adapt the example to one that is generic and can be reused. So I attempted to abstract all the classes. However there seems to be an error in the new function of the creator object. Can anyone please help me how to repair this? Otherwise, if I know what is wrong, I guess it will be a good candidate to include in the SQLalchemy recipes. ERROR: Traceback (most recent call last): File "sqlalchemyex.py", line 136, in <module> zip="95732") File "<string>", line 4, in __init__ File "/home/ahmed/dev/pyrenv/lib/python2.6/site-packages/SQLAlchemy-0.6.6-py2.6.egg/sqlalchemy/orm/state.py", line 111, in initialize_instance return manager.events.original_init(*mixed[1:], **kwargs) File "/home/ahmed/dev/pyrenv/lib/python2.6/site-packages/SQLAlchemy-0.6.6-py2.6.egg/sqlalchemy/ext/declarative.py", line 1378, in _declarative_constructor setattr(self, k, kwargs[k]) File "/home/ahmed/dev/pyrenv/lib/python2.6/site-packages/SQLAlchemy-0.6.6-py2.6.egg/sqlalchemy/ext/associationproxy.py", line 195, in __set__ setattr(obj, self.target_collection, creator(values)) File "sqlalchemyex.py", line 28, in <lambda> discriminator=discriminator) TypeError: object.__new__() takes no parameters from sqlalchemy.schema import Column, ForeignKey from sqlalchemy.types import String, Integer from sqlalchemy.ext.declarative import declared_attr, declarative_base from sqlalchemy.orm import relationship, backref from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.engine import create_engine from sqlalchemy.orm.session import sessionmaker import os class AssociationBase(object): discriminator = Column(String) """Refers to the type of parent.""" @classmethod def creator(cls, discriminator): """Provide a 'creator' function to use with the association proxy.""" return lambda associateds:AssociationBase( associateds=associateds, discriminator=discriminator) @property def parent(self): """Return the parent object.""" return getattr(self, "%s_parent" % self.discriminator) ''' @property def associateds(self): return getattr(self, "backref_%s" % self.discriminator) ''' class HasPolymorphicParents(object): @declared_attr def association_id(self): cls = self foreignkey_assoc_id = "{0}_association.id".format(cls.__name__) return Column(Integer, ForeignKey(foreignkey_assoc_id)) @declared_attr def association(self): cls = self association_class = "{0}Association".format(cls.__name__) return relationship(association_class, backref="associateds".format(cls.__name__)) parent = association_proxy("association", "parent") class HasAssociatedsMixin(object): @declared_attr def association_id(self): cls = self associated_classname = cls.__associated__ foreignkey_assoc_id = "{0}_association.id".format(associated_classname) return Column(Integer, ForeignKey(foreignkey_assoc_id)) @declared_attr def association(self): cls = self discriminator = cls.__name__.lower() associated_classname = cls.__associated__ ########## assoc_rel = 'associateds' assoc_proxy = association_proxy('association', assoc_rel, creator=self.__assoc_cls__.creator(discriminator) ) setattr(cls, assoc_rel, assoc_proxy) ########## association_classname = "{0}Association".format(associated_classname) return relationship(association_classname, backref=backref("%s_parent" % discriminator, uselist=False)) DecBase = declarative_base() class AddressAssociation(DecBase, AssociationBase, ): __tablename__ = "Address_association" id = Column(Integer, primary_key=True) class Address(HasPolymorphicParents, DecBase): __tablename__ = 'Addresses' id = Column(Integer, primary_key=True) street = Column(String) city = Column(String) zip = Column(String) class Customer(HasAssociatedsMixin, DecBase): __tablename__ = 'Customers' __associated__ = 'Address' __assoc_rel__ = 'addresses' __assoc_cls__ = AddressAssociation id = Column(Integer, primary_key=True) name = Column(String) class Supplier(HasAssociatedsMixin, DecBase): __tablename__ = 'Suppliers' __associated__ = 'Address' __assoc_rel__ = 'addresses' __assoc_cls__ = AddressAssociation id = Column(Integer, primary_key=True) name = Column(String) company_name = Column(String) os.environ['PYTHONINSPECT'] = 'True' eng = create_engine('sqlite://') DecBase.metadata.create_all(eng) session = sessionmaker(bind=eng)() session.add_all([ Customer( name='customer 1', associateds=[ Address( street='123 anywhere street', city="New York", zip="10110"), Address( street='40 main street', city="San Francisco", zip="95732") ] ), Supplier( company_name="Ace Hammers", associateds=[ Address( street='2569 west elm', city="Detroit", zip="56785") ] ), ]) session.commit() for customer in session.query(Customer): for address in customer.addresses: print address print address.parent A: This is the error what you get? Traceback (most recent call last): File "/tmp/test4.py", line 134, in <module> associateds=[ File "<string>", line 4, in __init__ File "/usr/lib/python2.7/site-packages/sqlalchemy/orm/state.py", line 98, in initialize_instance return manager.original_init(*mixed[1:], **kwargs) File "/usr/lib/python2.7/site-packages/sqlalchemy/ext/declarative.py", line 1388, in _declarative_constructor setattr(self, k, kwargs[k]) File "/usr/lib/python2.7/site-packages/sqlalchemy/ext/associationproxy.py", line 201, in __set__ setattr(obj, self.target_collection, creator(values)) File "/tmp/test4.py", line 23, in <lambda> discriminator=discriminator) TypeError: object.__new__() takes no parameters
{ "language": "en", "url": "https://stackoverflow.com/questions/7582861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Storing Viewstate in Database disables my asp:ImageButtons events I followed the guide here to save my ViewState into the database. I did some changes to it to fit my projects code design, but the essential parts are there. But when I implant this solution all my asp:ImageButtons events stops working, but regular asp:Buttons seems to work. Why doesn't the events from asp:ImageButtons work? Code: public class DatabasePageStatePersister : PageStatePersister { //This object handles the saving and loading from database CiroLightLibrary.BLL.ViewState myViewState; public DatabasePageStatePersister(Page p, string GUID): base(p) { myViewState = new CiroLightLibrary.BLL.ViewState(); myViewState.GUID = GUID; } public override void Load() { myViewState.Load(); this.ViewState = this.StateFormatter.Deserialize(myViewState.Value); } public override void Save() { myViewState.Value = this.StateFormatter.Serialize(this.ViewState); myViewState.Save(); } } public class PageViewStateDatabaseStored : Page { private PageStatePersister _PageStatePersister; protected override System.Web.UI.PageStatePersister PageStatePersister { get { if (_PageStatePersister == null) { CiroLightLibrary.BLL.ViewState myViewState = new ViewState(); if (Request["__DATABASE_VIEWSTATE"] != null) myViewState.GUID = Request["__DATABASE_VIEWSTATE"].ToString(); else myViewState.GUID = Guid.NewGuid().ToString(); _PageStatePersister = new DatabasePageStatePersister(this, myViewState.GUID); Literal l = new Literal(); l.Text = "<div><input type=\"hidden\" name=\"__DATABASE_VIEWSTATE\" value=\"" + myViewState.GUID + "\" /></div>"; this.Form.Controls.Add(l); } return _PageStatePersister; } } } And heres a Test page: public partial class test : PageViewStateDatabaseStored { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { imgButton1.CommandArgument = "1"; btnButton1.CommandArgument = "1"; } } protected void imgButton_OnCommand(object sender, CommandEventArgs e) { Response.Write(e.CommandArgument.ToString()); } protected void imgButton_OnClick(object sender, EventArgs e) { Response.Write("Click"); } } Asp.net Page <form runat="server"> <asp:ImageButton ID="imgButton1" runat="server" OnCommand="imgButton_OnCommand" /> <asp:ImageButton ID="imgButton2" runat="server" OnClick="imgButton_OnClick" /> <asp:Button ID="btnButton1" runat="server" OnCommand="imgButton_OnCommand" /> <asp:Button ID="btnButton2" runat="server" OnClick="imgButton_OnClick" /> </form> A: I tried to override LoadPageStateFromPersistenceMedium() and SavePageStateToPersistenceMedium() instead, and now my asp:ImageButtons also fires the events. public class PageViewStateDatabaseStored : Page { protected override object LoadPageStateFromPersistenceMedium() { CiroLightLibrary.BLL.ViewState myViewState = new ViewState(); if (Request["__DATABASE_VIEWSTATE"] != null) { myViewState.GUID = Request["__DATABASE_VIEWSTATE"].ToString(); myViewState.Load(); } LosFormatter myFormatter = new LosFormatter(); return myFormatter.Deserialize(myViewState.Value); } protected override void SavePageStateToPersistenceMedium(object viewState) { CiroLightLibrary.BLL.ViewState myViewState = new ViewState(); if (Request["__DATABASE_VIEWSTATE"] != null) myViewState.GUID = Request["__DATABASE_VIEWSTATE"].ToString(); else myViewState.GUID = Guid.NewGuid().ToString(); LosFormatter myFormatter = new LosFormatter(); StringWriter myStringWriter = new StringWriter(); myFormatter.Serialize(myStringWriter, viewState); myViewState.Value = myStringWriter.ToString(); myViewState.Save(); ScriptManager.RegisterHiddenField(this, "__DATABASE_VIEWSTATE", myViewState.GUID); } } A: I know this is an old post.... But the answer is simply that you're saving the viewstate not the controlstate. public override void Load() { myViewState.Load(); var pair = (Pair)this.StateFormatter.Deserialize(myViewState.Value); this.ViewState = pair.First; this.ControlState = pair.Second; } public override void Save() { myViewState.Value = this.StateFormatter.Serialize(new Pair(this.ViewState, this.ControlState)); myViewState.Save(); } Personally I'd inherit my PageStatePersister from HiddenFieldPageStatePersister then in my save method write the guid into the viewstate property and set the controlstate to null, then call the base Save method. In the Load, call the load the base.load then get the GUID from the viewstate property before pushing the db aquired values into the viewstate, controlstate properties. That way we're not modifying the control tree.... Like so: public class MyPageStatePersister : System.Web.UI.HiddenFieldPageStatePersister { public MyPageStatePersister(Page page) : base(page) { } public override void Load() { base.Load(); this.CurrentKey = (Guid)this.ViewState; var s = this.CurrentKey; var state = SomeDAOManager.GetState(s); if (state != null) { this.ViewState = state.First; this.ControlState = state.Second; } else { this.ControlState = null; this.ViewState = null; } } public Guid CurrentKey {get;set;} public override void Save() { if (CurrentKey == Guid.Empty) { this.CurrentKey = Guid.NewGuid(); } Guid guid = CurrentKey; SomeDAOManager.SaveState(guid, new Pair(this.ViewState, this.ControlState)); this.ViewState = guid; this.ControlState = null; base.Save(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7582863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cast XML layout as view in android before setContentView I want to cast multiple XML layouts as views. Because of a change request I need to use a ViewSwitcher. So I have to cast the XML layout to Views before setContentView. I always get a NullPointerException. I tried: view = (View) findViewById(R.id.viewgroup_id); view = (RelativeLayout) findViewById(R.id.viewgroup_id); view = (View) findViewById(R.layout.xml_layout); view = (View) getResources().getLayout(R.layout.xml_layout); A: Try using LayoutInflater. Use this code inside your activity code- LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.your_layout, null); A: You need to inflate layouts for that Check this link
{ "language": "en", "url": "https://stackoverflow.com/questions/7582864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check if rootViewController is of a specific class? I would like to know if the rootViewController in a navigation controller stack is of specific class. How to do such a thing ? Thx for helping, Stephane A: The navigation controllers root view controller is, id rootVC = [[navigationController viewControllers] objectAtIndex:0]; And check the class of rootVC like this, if ([rootVC isKindOfClass:[YourClass class]]) { A: Here you go buddy id rootController = [self.navigationController rootViewController]; if([rootController isKindOfClass:[YourDesiredController class]]){ //do something } A: You can check the class with: if ([rootViewController isKindOfClass:[YourClass class]]){ }else if ([rootViewController isKindOfClass:[AnotherClass class]]){ }else{ } A: Perhaps you can use the method isKindOfClass [rootViewController isKindOfClass: [RootViewController class]]; A: How to check your current rootViewController and use it in an if statement : // Get your current rootViewController NSLog(@"My current rootViewController is: %@", [[[UIApplication sharedApplication].delegate.window.rootViewController class]); // Use in an if statement UIViewController *rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController; if ([rootViewController isKindOfClass:[MyViewController class]]) { NSLog(@"Your rootViewController is MyViewController!!"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7582865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Size of images for iPhone app store what size should I export my graphics, for use in the example/screenshot section of the app on the app store. Thanks A: You should read the dedicated Apple documentation about the subject that gives every info about the icon sizes Read this Technical Note too where every icon and artwork sizes are described in detail. For the screenshots published on the AppStore, simply do a screenshot of your app for this (which will be 640x960px if you make your screenshot from an iPhone with Retina display (iPhone4), and 320x480px for iPhone 3GS or older, etc. Namely the size of the screen in pixels, obviously). To do those screenshots: * *either directly on the device hold the Power+Home buttons together and it will display a small/quick "flash" effect on the screen to tell you the screenshot has been saved in your iPhone library *Or from the Xcode Organizer, after you have plugged the iPhone to your Mac obviously, select the iPhone in the list and in the appropriate section of the organizer, click on the button to generate a screenshot directly from Xcode. A: Questions like this are answered in the Developer Guide for iTunes Connect: https://itunesconnect.apple.com/docs/iTunesConnect_DeveloperGuide.pdf See pages 13 and 14 for size information. A: The best place to look for this currently is on the iTunes Connect Developer Guide under "Adding New Apps": http://developer.apple.com/library/ios/#documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/8_AddingNewApps/AddingNewApps.html#//apple_ref/doc/uid/TP40011225-CH13-SW42 A: https://help.apple.com/app-store-connect/#/devd274dd925 6.5 inch (iPhone 12 Pro Max, iPhone 11 Pro Max, iPhone 11, iPhone XS Max, iPhone XR) 1284 x 2778 pixels (portrait) 2778 x 1284 pixels (landscape) 5.8 inch (iPhone 12 Pro, iPhone 12, iPhone 12 mini, iPhone 11 Pro, iPhone XS, iPhone X) 1170 x 2532 pixels (portrait) 2532 x 1170 pixels (landscape) 5.5 inch (iPhone 8 Plus, iPhone 7 Plus, iPhone 6s Plus) 1242 x 2208 pixels (portrait) 2208 x 1242 pixels (landscape) 4.7 inch (iPhone SE (2nd generation), iPhone 8, iPhone 7, iPhone 6s, iPhone 6) 750 x 1334 pixels (portrait) 1334 x 750 pixels (landscape) 4 inch (iPhone SE (1st generation)) 640 x 1096 pixels (portrait without status bar) 640 x 1136 pixels (portrait with status bar) 1136 x 600 pixels (landscape without status bar) 1136 x 640 pixels (landscape with status bar) 3.5 inch (iPhone 4s) 640 x 920 pixels (portrait without status bar) 640 x 960 pixels (portrait with status bar) 960 x 600 pixels (landscape (without status bar) 960 x 640 pixels (landscape with status bar) 12.9 inch (iPad Pro (4th generation, 3rd generation)) 2048 x 2732 pixels (portrait) 2732 x 2048 pixels (landscape) 12.9 inch (2nd generation iPad Pro) 2048 x 2732 pixels (portrait) 2732 x 2048 pixels (landscape) 11 inch (iPad Pro, 4th generation iPad Air) 1668 x 2388 pixels (portrait) 2388 x 1668 pixels (landscape) 10.5 inch (iPad (8th generation, 7th generation), iPad Pro, iPad Air) 1668 x 2224 pixels (portrait) 2224 x 1668 pixels (landscape) 9.7 inch (iPad, iPad mini) 1536 x 2008 pixels (portrait (without status bar) 1536 x 2048 pixels (portrait with status bar) 2048 x 1496 pixels (landscape without status bar) 2048 x 1536 pixels (landscape with status bar) Mac One of the following, with a 16:10 aspect ratio. 1280 x 800 pixels 1440 x 900 pixels 2560 x 1600 pixels 2880 x 1800 pixels Apple TV 1920 x 1080 pixels 3840 x 2160 pixels Apple Watch (Series 6, Series 5, Series 4, Series 3, SE) 368 x 448 pixels
{ "language": "en", "url": "https://stackoverflow.com/questions/7582868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to change Google task status from completed to Pending? I am working on Google task api When i update task status from needAction to complete it change perfectly. But when change from completed to anything(Pending/needAction) It gives error means status not change when once it set to completed. any solution? A: You can create an new Task, exactly same as current, and put into queue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: issue with iphone NSString I have an iphone application in which I want to draw the route between two locations on the map. The locations are refered by their coordinates(latitude, longitude). For loading the waypoints between those two locations I use a script that acces google maps, with this method: function loadDirections(from, to, options) { gdir.load("from: " + from + " to: " + to, options); } from should be of this form: 46.777248,23.59989 and to also like this: 44.437711,26.097367. In other words if I write this method like this: function loadDirections(from, to, options) { gdir.load("from:46.777248,23.59989 to:44.437711,26.097367 ", options); } everything goes great. Now, going into my iphone app....this is how I call this method: [directions loadWithStartPoint:startPoint endPoint:endPoint options:options]; - (void)loadWithStartPoint:(NSString *)startPoint endPoint:(NSString *)endPoint options:(UICGDirectionsOptions *)options { [googleMapsAPI stringByEvaluatingJavaScriptFromString: [NSString stringWithFormat:@"loadDirections('%@', '%@', %@)", startPoint, endPoint, [options JSONRepresentation]]]; } In other words, startPoint should contain the coordinates of the first location like this: 46.777248,23.59989 and endPoint should have the same form. So in my iphone app I receive the latitude and longitude for the startPoint and also for the endPoint and in order to have them under the requested form I have this: NSString *startPoint; NSString *endPoint; startPoint = [NSString stringWithFormat:@"%@,%@", latitudeString, longitudeString]; endPoint = [NSString stringWithFormat:@"%@,%@", partenaire_lat, partenaire_lng]; But when I call the javascript through this options.travelMode = UICGTravelModeDriving; [directions loadWithStartPoint:startPoint endPoint:endPoint options:options]; the app blocks.I assume it doesn't like the way startPoint and endPoint are formatted. IMPORTANT: When I call the above method with null values for startPoint and endPoint the app works. Anyone has any idea? I did my best to explain it very clearly!!!!!I'm here in case something is unclear! A: I think this may solve your problem, NSString *startPoint; NSString *endPoint; startPoint = [NSString stringWithFormat:@"%@,%@", latitudeString, longitudeString]; endPoint = [NSString stringWithFormat:@"%@,%@", partenaire_lat, partenaire_lng]; [startPoint retain]; [endPoint retain]; A: I think it is because you are adding single quotes around the coordinates. These get preserved when you concatenate the strings in your function loadDirections (assuming that is a javascript function). Also, you have a space after from: and to: in your loadDirections, don't know if that is important. Try - (void)loadWithStartPoint:(NSString *)startPoint endPoint:(NSString *)endPoint options:(UICGDirectionsOptions *)options { [googleMapsAPI stringByEvaluatingJavaScriptFromString: [NSString stringWithFormat:@"loadDirections(%@, %@, %@)", startPoint, endPoint, [options JSONRepresentation]]]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7582870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I find radius from center in MKMapView in iphone programming? I have to send radius to web-service and it will return the data of stores back to iPhone. It is pretty good when I am sending radius as digit such as 45, 60, or whatsoever, but what if I am on map and want longitude and latitude from map and want to know radius of visible area? I am visible MKMapView, and I want radius from center of visible area, what can I do to achieve it?
{ "language": "en", "url": "https://stackoverflow.com/questions/7582873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is a Join Faster than two queries I know this question has been asked before, example, and I do agree that one query with a join is faster than performing another query for each record returned by the firs query. However, since with a join you tend to generate redundant field will this slow the network ? Let's say I have a table hotel and HOTEL has a number of images in a table HOTEL_IMAGE. HOTEL has 20 fields. performing a join on HOTEL_IMAGE will produce 20 fields for each hotel image. will this query still be faster over the network ? A: Don't use select * but only the columns that you need. IF you do this, a join will be faster (not sure why you would ever want to do this with 2 queries, you have to make 2 connections to your database ect.) A: That depends a lot on your actual data, but from what I have seen, if you have a well-parameterized DB with fresh statistics, it is much better to put the join in SQL and let the DB figure out what to do. Anyway, DB queries are in my opinion the first things you want to profile. It is not a coincidence that any good DBMS has a lot of performance measuring tools. And you need to profile with data as close to actual data as possible (recent copies of your production environment are best). A: As a solution to avoid duplication in joined data, you can return multiple recordsets from single query, if your database supports it. One recordset will return the master records, and second - the detail records plus the key fields from master query. select ID, Name, ... from HOTEL where <.... your criteria>; select h.ID as HotelID, i.ID, i.Description, i.ImageFile, .... from HOTEL_IMAGE i join HOTEL h on h.ID = i.HotelID and ( <.... same criteria for HOTEL> ) Not sure if the query on the master table would be cached, so the second select will reuse it, but it will save traffic for sure. We are using this approach for queries, which tend to return multi-level joined results.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Simplifying fractions in C# I have made a console app that adds and subtracts fractions, I have added a function to simplify: public static Numbers Add(Numbers n1, Numbers n2) { int den1; int num1; int num2; int dsimp; int nsimp; int numtop; num1 = n1.Numerator * n2.Denominator; num2 = n2.Numerator * n1.Denominator; den1 = n1.Denominator * n2.Denominator; numtop = num2 + num1; if (numtop == 0) { return new Numbers(0); } if (numtop % n1.Denominator == 0) { nsimp = numtop / n1.Denominator; dsimp = den1 / n1.Denominator; return new Numbers(nsimp, dsimp); } else { return new Numbers(numtop, den1); } } When I put in 1/2 + 4/8 it simplifies it all perfectly the way I tell it to, but, it gives me 8/8. This needs to be simplified to 1/1. How do I get it to simplify what has already been simplified to the lowest possible fraction? A: Divide the numerator and denominator by the GCD (greatest common divisor) of the numerator and denominator. Eg: Start with say 12/8. The GCD is 4. Thus 3/2.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Deletion in binary heap I am just trying to learn binary heap and have a doubt regarding doing delete operation in binary heap. I have read that we can delete an element from binary heap and we need to reheapify it. But at the following link, it says unavailable: http://en.wikibooks.org/wiki/Data_Structures/Tradeoffs Binary Search AVL Tree Binary Heap (min) Binomial Queue (min) Find O(log n) O(log n) unavailable unavailable Delete element O(log n O(log n) unavailable unavailable I am little confused about it. Thanks in advance for all of the clarifications. A: Binary heaps and other priority queue structures don't usually support a general "delete element" operation; you need an additional data structure that keeps track of each element's index in the heap, e.g. a hash table. If you have that, you can implement a general delete operation as * *find-element, O(1) expected time with a hash table *decrease key to less than the minimum, O(lg n) time *delete-min and update the hash table, O(lg n) combined expected time. A: A regular delete is possible, just like a DeleteMin/Max. The "problem" is that you have to check for both up- and downshifts (i.e.: when the "last" node takes up the vacant spot, it can be over- or underevaluated. Since it still can't be both, for obvious reasons, it's easy to check for correctness. The only problem that remains is the Find. The answer above states that you can Find Element in O(lg n), but I wouldn't know how. In my implementations, I generally build a Heap of pointers-to-elements rather than elements (cheaper copying during up/downshifts). I add a "position" variable to the Element type, which keeps track of the index of the Element's pointer in the Heap. This way, given an element E, I can find it's position in the Heap in constant time. Obviously, this isn't cut out for every implementation. A: I am confused why delete operation of binary heap is mentioned as unavailable in the link of your question. Deletion in binary heap quite possible and it's composition of 2 other operations of binary heap. https://en.wikipedia.org/wiki/Binary_heap I am considering you know all other operations of Binary Heap Deleting a key from binary heap requires 2 lines of code/operation. Suppose you want to delete item at index x. Decrease it's value to lowest integer possible. That's Integer.MIN_VALUE. Since it's lowest value of all integer it will go to root position when decreaseItem(int index, int newVal) execution done. Afterwards extract the root invoking extractMin() method. // Complexity: O(lg n) public void deleteItem(int index) { // Assign lowest value possible so that it will reach to root decreaseItem(index, Integer.MIN_VALUE); // Then extract min will remove that item from heap tree. correct ? extractMin(); } Full Code: BinaryHeap_Demo.java
{ "language": "en", "url": "https://stackoverflow.com/questions/7582887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Alert dialog gets dismissed by itself? @Override protected Dialog onCreateDialog(int id) { LayoutInflater factory = LayoutInflater.from(GmailFetchActivity.this); final View textEntryView = factory.inflate(R.layout.alertdialog_gmail, null); final EditText username = (EditText) textEntryView.findViewById(R.id.edit_username); editxt_pass = (EditText) textEntryView.findViewById(R.id.edit_password); final CheckBox remember = (CheckBox) textEntryView.findViewById(R.id.checkBox_remember); username.setText(myPrefs.getString("username", "")); editxt_pass.setText(myPrefs.getString("password", "")); AlertDialog.Builder alert=new AlertDialog.Builder(this); alert.setTitle("Gmail login"); alert.setView(textEntryView); alert.setPositiveButton("Login", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if(username.getText().toString().trim().equalsIgnoreCase("")) { } else{ if(isNetworkAvailable()){ String user=username.getText().toString(); String pass=editxt_pass.getText().toString(); if(remember.isChecked()){ prefsEditor.putString("username",user); prefsEditor.putString("password",pass); prefsEditor.commit(); } else{ prefsEditor.putString("username",""); prefsEditor.putString("password",""); prefsEditor.commit(); } progressHrz.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressHrz.setMessage("Fetching attachment's list"); progressHrz.setCancelable(true); progressHrz.show(); new FetchGmail().execute(user+"@gmail.com",pass); } else Toast.makeText(getApplicationContext(), "No internet access", Toast.LENGTH_LONG).show(); } } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { finish(); } }) ; return alert.create(); } if the username is empty i just want to show a toast,but the dialog gets dismissedafter show the toast y?i want it to stay as it is A: There is a work around you can implement. You just would need to re-show the dialog if whatever checks you're performing don't pass. Take a look at this previous answer: Is there a way prevent AlertDialog from closing with invalid inputs? Note: You may not even need to implement your own alert dialog to do this. You should be able to do this right in your onClick() listener by calling dialog.show(). Give it a shot and let us know if it works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Add Custom ComboBox Filters to Admin User List in Wordpress I want to add 2 combo box in Admin User List Panel. For example the first one will be a combo box with countries and the other combo will be User Age. So I want to add these combos in order to filter the user list. Could you please shed some light here?. Thank you. A: This is what i'm looking for: add_action('restrict_manage_posts', 'my_restrict_manage_posts'); function my_restrict_manage_posts() { global $typenow; if ($typenow == 'your_custom_post_type') { $args = array( 'show_option_all' => "Show All Categories", 'taxonomy' => 'your_custom_taxonomy', 'name' => 'your_custom_taxonomy' ); wp_dropdown_categories($args); } } add_action('request', 'my_request'); function my_request($request) { if (is_admin() && $GLOBALS['PHP_SELF'] == '/wp-admin/edit.php' && isset($request['post_type']) && $request['post_type'] == 'your_custom_post_type') { $request['term'] = get_term($request['your_custom_taxonomy'], 'your_custom_taxonomy')->name; } return $request; } A: You can add your own fields to a user add/edit field. this example shows how to add a address input field, if you get this working try switching it with the dropdown's that you need. If that's what you mean by 'combobox' function fb_add_custom_user_profile_fields( $user ) { ?> <h3><?php _e('Extra Profile Information', 'your_textdomain'); ?></h3> <table class="form-table"> <tr> <th> <label for="address"><?php _e('Address', 'your_textdomain'); ?> </label></th> <td> <input type="text" name="address" id="address" value="<?php echo esc_attr( get_the_author_meta( 'address', $user->ID ) ); ?>" class="regular-text" /><br /> <span class="description"><?php _e('Please enter your address.', 'your_textdomain'); ?></span> </td> </tr> </table> <?php } function fb_save_custom_user_profile_fields( $user_id ) { if ( !current_user_can( 'edit_user', $user_id ) ) return FALSE; update_usermeta( $user_id, 'address', $_POST['address'] ); } add_action( 'show_user_profile', 'fb_add_custom_user_profile_fields' ); add_action( 'edit_user_profile', 'fb_add_custom_user_profile_fields' ); add_action( 'personal_options_update', 'fb_save_custom_user_profile_fields' ); add_action( 'edit_user_profile_update', 'fb_save_custom_user_profile_fields' );
{ "language": "en", "url": "https://stackoverflow.com/questions/7582892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How come when I run a .php script in Ubunutu it just echos the script itself? I have to decode the binary content data of one of my Chrome cache files which I name cache.log. The way I am trying to decode it is by using a php script I found here http://www.frozax.com/blog/2011/05/recover-file-google-chrome-cache-gzipped/ I have installed php with the following command already sudo apt-get install php5 libapache2-mod-php5 sudo apt-get install php5-cgi When I try to run the index1.php script I get the following in Terminal s3z@s3z-laptop:~/Desktop$ php index1.php PHP Deprecated: Comments starting with '#' are deprecated in /etc/php5/cli/conf.d/mcrypt.ini on line 1 in Unknown on line 0 // cache.log is a copy of chrome cache page with only the file content section $cacheString = file_get_contents("cache.log"); $matches = array(); preg_match_all('/\s[0-9a-f]{2}\s/', $cacheString, $matches); $f = fopen("t.bin","wb"); foreach ($matches[0] as $match) { fwrite($f,chr(hexdec($match))); } fclose($f); ob_start(); readgzfile("t.bin"); $decoded_data=ob_get_clean(); echo $decoded_data; As you can see, all it is doing is echoing the script. How do I actually run the script? A: It doesn't look like the code is wrapped in: <?php ?> If it doesn't have that, it will just echo instead of executing. The reason for this is that PHP lets you mix server scripting and HTML in the same file. <html> <head><title></title></head> <body> <?php //Inside the php block so it gets executed and prints 'Hello World' echo "Hello, World!"; ?> <!--Outside the php block so it just gets echoed and prints 'echo "Hello, World!";' --> echo "Hello, World!"; </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7582894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: How to integrate my own structural annotations engine in the Entity Framework designer? In the accepted answer to this SO question there is an explanation about structural annotations, a way to customize the data on the EDMX files generated by the Entity Framework designer. This feature is used by the Portable Extensible Metadata framework in order to add validation information to the entities defined in an EF model, by adding extra entries to the "Properties" window of the created entities and its properties. My question is: what should I do if I want to create my own custom structural annotations engine? That is, I want Visual Studio to show some extra entries in the properties window for the EF entities; and I want to integrate my own code with the EDMX code generator in order to generate structural annotations. I guess that I need to create a Visual Studio extension but apart from this, I could not find any further information anywhere else. Where should I look for information on this subject? A: Entity framework has very low extensibility on ORM layer but it has surprisingly good extensibility on designer layer. The core of extensibility is based on few interfaces which can be implemented to add custom features to EDMX designer as VS extension. The step by step process of adding custom property to designer is described in Entity Framework 4 in Action book. You can also use Designer Extension Starter Kit to get some prepared templates and kick start for creating your own extensions. These features targets EFv4. Extension starter kit doesn't work with June 2011 CTP and its new designer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Grouping table view sections by day and country I have an Core Data entity called Event and the two relevant attributes are called startDateTime and countryCode. My problem is that the sections in my table view need to be grouped by day AND country code. I've seen a lot of examples on how the achieve grouping by day only (DateSectionTitles by Apple for example), but it gets a lot more complicated when I add the country code. I use a transient sectionIdentifier as recommended in the DateSectionTitles example and the sections look something like this: "20110928 SE", "20110929 SE", "20110928 GB" etc. I first tried this: NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"startDateTime" ascending:NO]; NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"countryCode" ascending:NO]; sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor1, nil]; [sortDescriptor1 release]; [sortDescriptor2 release]; But this doesn't work since startDateTime has a time component which leads to index mismatch. What I need is to sort the startDateTime without the time component. The obvious solution would be to separate the date and time into two different entity attributes. But when I think about it that wouldn't work since a date is relative to a timezone. When the phone changes timezone the date and times attributes would be invalid. I've also tried to subclass a NSSortDescriptor and create a custom compareObject function, but it never seems to be called and I can't find any working examples. How would you solve this? Is the subclassed NSSortDescriptor the way to go, or is there perhaps a much smarter way? A: Create a category on NSDate with a method that strips the time from the date returning just the day e.g. converts this: 2011-09-29 09:53:28 -0500 … to this: 2011-09-29 Then set your sort key to dateAttribute.methodName.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Declare @MyVar SameAs [Table].[Column] In the latest version of T-SQL, which I presume is SQL 2008 R2, can one declare a variable and specify that its type is to be the same as a specified table.column rather than hard coding a specific data type/length? I'm guessing that T-SQL still doesn't have it but I wanted to be sure. A: No. You can't. It has been requested though on MS Connect. Vote it up. And asked for twice too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Casting string to bytes while parsing XML to Objects ('str' does not support the buffer interface) I encountered a problem while using function parseString xml.sax.parseString(src, builder) TypeError: 'str' does not support the buffer interface I trying change this calling to: xml.sax.parseString(bytes(src,'utf-8'), builder) but still not working Python 3.2
{ "language": "en", "url": "https://stackoverflow.com/questions/7582909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Erroneous Results calculating the gradient of an image with ITK In the header file, I declare all of this types, The “Gradient ImageFilter” is for calculate the gradient of a 2D image, and the “VectorIndexSelectionCastImageFilter” is for selecting the ’x’ and ‘y’ component of the gradient calculating, due to the fact that the result of computing th gradient is a vector image. typedef double operatorValueType; typedef double outputValueType; typedef double InputPixelType; typedef itk::Image<InputPixelType, 2> InputImageType; typedef itk::GradientImageFilter< InputImageType, operatorValueType, outputValueType> GradientFilterType; //for extracting a scalar from the vector image typedef double OutputPixelTypeImage; typedef double ComponentType; typedef itk::CovariantVector<ComponentType,2> OutputPixelType; typedef itk::Image <OutputPixelType, 2> OutputImageType; typedef itk::VectorIndexSelectionCastImageFilter<OutputImageType,InputImageType> SelectionFilterType; // < intputType , outputType> After the declarations, the main part of interest of the code is below: GradientFilterType::Pointer gradientFilter = GradientFilterType::New(); gradientFilter->SetInput(T_g->GetOutput()); // From T_g (is a reader) comes the image gradientFilter->Update(); SelectionFilterType::Pointer componentExtractor_x = SelectionFilterType::New(); SelectionFilterType::Pointer componentExtractor_y = SelectionFilterType::New(); componentExtractor_x->SetIndex(0);// x component of the gradient componentExtractor_y->SetIndex(1);// y component of the gradient componentExtractor_x->SetInput(gradientFilter->GetOutput()); componentExtractor_y->SetInput(gradientFilter->GetOutput()); componentExtractor_x->Update(); componentExtractor_y->Update(); It seems that everything works fine, but the problem is that when I read the image and I compare it with the calculation of the gradient in Matlab (which I assume to be correct) the results are completely different…Anyone has used before the “VectorIndexSelectionCastImageFilter” and see something strange? Or in the process of calculating the gradient? Thanks so much! Antonio A: ITK should respect voxel spacing in the computations. Do you images have isotropic unit spacing? This could account for the differences with matlab. A: The problem was in the spacing of the image, just by adding this line: gradientFilter->SetUseImageSpacingOff(); // for derivation in isotropic pixel space the problem was solved, and the derivation was done in an isotropic space
{ "language": "en", "url": "https://stackoverflow.com/questions/7582923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event doesn't get called i am making a cocos2d game and i can't get the touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event to be called. Is there something i should do besides including this function? A: When using cocos2d with touches you should use the following methods instead - (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
{ "language": "en", "url": "https://stackoverflow.com/questions/7582926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Delete Contents Of A table How Can I delete Contents of A table.. If I have 100 rows in a table and i want to delete all of them without droping a table how would I? A: Use DELETE without a WHERE clause: DELETE FROM tablename This may fail if you have other tables that refer to it via foreign key references. A: You can also use TRUNCATE http://dev.mysql.com/doc/refman/5.0/en/truncate-table.html http://www.postgresql.org/docs/current/static/sql-truncate.html (Thanks for PostgreSQL link to rfusca) TRUNCATE TABLE tablename A: Both given answers are correct. The main difference between TRUNCATE TABLE tablename and DELETE FROM tablename is that TRUNCATE will reset the auto_increment value back to 1. It may make a difference if things have to be unique. A: You can use Truncate also,it's faster than DELETE but TRUNCATE will not work under a table lock or transaction. have a look at http://dev.mysql.com/doc/refman/5.0/en/truncate-table.html http://dev.mysql.com/doc/refman/5.0/en/delete.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7582927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }