text
stringlengths
8
267k
meta
dict
Q: How to get rid of top fading edge in android full screen mode? By putting the following two lines of code in activity.OnCreate, I can get a full screen view: requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ); However, if you look carefully, there is still a slight fading edge on the top edge of the screen which looks like a residue of the removed title bar. How can I get rid of that completely? See this screen capture, which is a fullscreen view obtained using the above two lines of code, but the top fading edge is visible and annoying, I already tried android:fadingEdge="none" and android:fadingEdgeLength="0sp" on the root view of this activity, doesn't work: A: This will do what you asking for: requestWindowFeature(Window.FEATURE_NO_TITLE); setTheme(android.R.style.Theme_NoTitleBar_Fullscreen); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
{ "language": "en", "url": "https://stackoverflow.com/questions/7524607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Simulating a click on a menu item in Robolectric It's fairly simple to simulate a button click in Robolectric: Button someButton = (Button) findViewById(R.id.some_button); someButton.performClick(); However, I can't seem to figure out how to do the same thing with a menu item. I create a menu in Activity.onCreateOptionsMenu, how can I simulate a click on one of its items? A: MenuItem item = new TestMenuItem() { public int getItemId() { return R.id.hello; } }; activity.onOptionsItemSelected(item); ShadowActivity shadowActivity = Robolectric.shadowOf(activity); Intent startedIntent = shadowActivity.getNextStartedActivity(); ShadowIntent shadowIntent = Robolectric.shadowOf(startedIntent); assertThat(shadowIntent.getComponent().getClassName(), equalTo(HelloActivity_.class.getName())); Enjoy! A: You are already using Robolectric then why don't use RoboMenuItem ? private MenuItem menuItemName = new RoboMenuItem(R.id.action_names); private MenuItem menuItemStar = new RoboMenuItem(R.id.action_stars); add as many items as required. @Test public void onOptionItemSelectedTest() { activity.onOptionsItemSelected(menuItemStar); activity.onOptionsItemSelected(menuItemName); } Make sure your activity is not null @Before public void setUp() { activity = Robolectric.buildActivity(MainActivity.class) .create(new Bundle()) .saveInstanceState(new Bundle()) .restoreInstanceState(new Bundle()) .resume() .get(); } Robolectric version 4.3 A: In Robolectric 3.0+, you can use ShadowActivity.clickMenuItem(menuItemResId): // Get shadow ShadowActivity shadowActivity = Shadows.shadowOf(activity); // Click menu shadowActivity.clickMenuItem(R.id.settings_option_item); // Get intent Intent startedIntent = shadowActivity.getNextStartedActivity(); ShadowIntent shadowIntent = Shadows.shadowOf(startedIntent); // Make your assertion assertThat(shadowIntent.getComponent().getClassName(), equalTo(HelloActivity_.class.getName())); A: In robolectric 3.0+ the class is called RoboMenuItem A: Using robolectric 2.4: Activity activity = Robolectric.buildActivity(MainActivity.class).create().get(); MenuItem item = new TestMenuItem(R.id.settings_option_item); activity.onOptionsItemSelected(item); A: You can also use Mockito if you'd like to cut down on the amount of overriding/abstract coding required. Like this (in Kotlin): val menuItem = mock(MenuItem::class.java) `when`(menuItem.itemId).thenReturn(R.id.itemId) activity.onOptionsItemSelected(menuItem)
{ "language": "en", "url": "https://stackoverflow.com/questions/7524611", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: how to count rows from multiple tables in sqlite i am using following code - (int)GetTextCount { NSMutableArray *audioArray=[[NSMutableArray alloc]init]; int count = 0; //This method is defined to retrieve data from Database NSString *dbPath=filePath; sqlite3 *database; if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) { // Setup the SQL Statement and compile it for faster access /* SELECT ( SELECT COUNT(*) FROM tab1 ) AS count1, ( SELECT COUNT(*) FROM tab2 ) AS count2 FROM dual */ const char *sqlStatement = "select count(*) from photo where mid=? "; //const char *sqlStatement = "select * from textt where mid=?"; sqlite3_stmt *compiledStatement; if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) { sqlite3_bind_int(compiledStatement, 1, memoryData.memoryId); //(compiledStatement, 1, [header UTF8String], -1, SQLITE_TRANSIENT); while(sqlite3_step(compiledStatement) == SQLITE_ROW) { AudioData *data=[[AudioData alloc]init]; //create the MemoryData object to store the data of one record // Read the data from the result row int pId=sqlite3_column_int(compiledStatement, 0); NSLog(@"total audiosssss are %i",pId); //NSString *filePath=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)]; //filePath=[self retrievePath:filePath]; //[data setAudioId:pId]; //[data setFilePath:filePath]; //Store every object of MemoryData in t [audioArray addObject:data]; } // end of the while } sqlite3_finalize(compiledStatement); } sqlite3_close(database); return [audioArray count]; } To count from one table , but I need to count the rows from four tables , so now what i am doing that running separate queries which reduces the performance so I want to run one query to select from four tables , please help how can I do that? A: Try this: SELECT COUNT(*) AS MyCount, 'MyTable1Count' AS Description FROM Table1 UNION ALL SELECT COUNT(*) AS MyCount, 'MyTable2Count' AS Description FROM Table2 UNION ALL SELECT COUNT(*) AS MyCount, 'MyTable3Count' AS Description FROM Table3 UNION ALL SELECT COUNT(*) AS MyCount, 'MyTable4Count' AS Description FROM Table4 This will produce a resultset like: MyCount Description ---------------------- 534 MyTable1Count 33 MyTable2Count 92843 MyTable3Count 931 MyTable4Count A: I think you want this query. (Sorry If I am wrong). SELECT (SELECT count(*) from table_1 where mid = ?) + (SELECT count(*) from table_2 where mid = ?) + (SELECT count(*) from table_3 where mid = ?) + (SELECT count(*) from table_4 where mid = ?) A: There are several ways to do this task, SELECT (SELECT COUNT(DISTINCT id) FROM member) AS members, (SELECT COUNT(DISTINCT id) FROM thread) AS threads, (SELECT COUNT(DISTINCT id) FROM post) AS posts or you can use, SELECT COUNT(DISTINCT member.id), COUNT(DISTINCT thread.id), COUNT(DISTINCT post.id) FROM member, thread, post;
{ "language": "en", "url": "https://stackoverflow.com/questions/7524612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I run a loop for a period of time in C#? Possible Duplicate: How to execute the loop for specific time So, I have an infinite loop in C#, but the thing is, I want the loop to end at some point. Not based on a count or a loop interval, but based on a period of time, so once that period of time has passed, the loop ends. How do I do such a thing? A: Make use of Timer or Thread to do that. you can achieve the task easily. System.Threading.Timer Timer; System.DateTime StopTime; public void Run() { StopTime = System.DateTime.Now.AddMinutes(10); Timer = new System.Threading.Timer(TimerCallback, null, 0, 5000); } private void TimerCallback(object state) { if(System.DateTime.Now >= StopTime) { Timer.Dispose(); return; } // do your work..... } check other solution : .NET, event every minute (on the minute). Is a timer the best option? or Edit try DateTime dt = DateTime.Now.AddMinutes(10); for (; ; ) { if (dt < DateTime.Now) break; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7524613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MKMapView current location showing as custom pins I have set so that my MKMapView shows the current location. I also have a custom pin implemented for other pins. However, it turns out the current location shows as a custom pin, whereas I just wanted it to be a regular blue circle (like what google map has). I have defined the following in my code: - (MKAnnotationView *) mapView: (MKMapView *) mapView viewForAnnotation: (id<MKAnnotation>) annotation MKAnnotationView *pin = (MKAnnotationView *) [self.mapView dequeueReusableAnnotationViewWithIdentifier: @"VoteSpotPin"]; if (pin == nil) { pin = [[[MKAnnotationView alloc] initWithAnnotation: annotation reuseIdentifier: @"TestPin"] autorelease]; } else { pin.annotation = annotation; } [pin setImage:[UIImage imageNamed:@"TestPin.png"]]; pin.canShowCallout = YES; pin.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; return pin; } How can I prevent the current location to show up as a pin? A: you need to implement this:- - (MKAnnotationView *) mapView: (MKMapView *) mapView viewForAnnotation:(id<MKAnnotation>) annotation { if (annotation == mapView.userLocation) { return nil; } else { MKAnnotationView *pin = (MKAnnotationView *) [self.mapView dequeueReusableAnnotationViewWithIdentifier: @"VoteSpotPin"]; if (pin == nil) { pin = [[[MKAnnotationView alloc] initWithAnnotation: annotation reuseIdentifier: @"TestPin"] autorelease]; } else { pin.annotation = annotation; } [pin setImage:[UIImage imageNamed:@"TestPin.png"]]; pin.canShowCallout = YES; pin.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; return pin; } } A: For Swift: if annotation is MKUserLocation { return nil } A: - (MKAnnotationView *)mapView:(MKMapView *)mapViewTmp viewForAnnotation:(id<MKAnnotation>)annotation { if(annotation == mapView.userLocation) return nil; else { MKAnnotationView *pin = (MKAnnotationView *) [self.mapView dequeueReusableAnnotationViewWithIdentifier: @"VoteSpotPin"]; if (pin == nil) { pin = [[[MKAnnotationView alloc] initWithAnnotation: annotation reuseIdentifier: @"TestPin"] autorelease]; } else { pin.annotation = annotation; } [pin setImage:[UIImage imageNamed:@"TestPin.png"]]; pin.canShowCallout = YES; pin.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; return pin; } } A: Want simplest solution? Just change your object pin from MKAnnotationView to MKPinAnnotationView it will show you what you want. A: mapView.delegate=self; MKCoordinateRegion myRegion; CLLocationCoordinate2D center; center.latitude=40.4000;//spean center.longitude=-3.6833;//firstLagi;//-5.345373; MKCoordinateSpan span; span.latitudeDelta=My_Span; span.longitudeDelta=My_Span; myRegion.center=center; myRegion.span=span; [mapView setRegion:myRegion animated:YES]; NSMutableArray *locations=[[NSMutableArray alloc]init]; CLLocationCoordinate2D location; Annotation *myAnn; allList=[[AllList alloc]init]; for (int j = 0; j<[appDelegate.allListArray count]; j++) { cat=@"cat"; myAnn=[[Annotation alloc]init]; allList=[appDelegate.allListArray objectAtIndex:j]; location.latitude=[allList.lati doubleValue]; location.longitude=[allList.lagi doubleValue]; myAnn.coordinate=location; myAnn.title=allList.name; //myAnn.subtitle=allList.type; [locations addObject:myAnn]; } [self.mapView addAnnotations:locations];
{ "language": "en", "url": "https://stackoverflow.com/questions/7524615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: RegEx replace content within curly brakets I'm working on a small system with a WYSIWYG-editor that spits out HTML. In the generated code the HTML-links looks like this. <a href="{link:3645}">One line</a><br/> <p>yada yaya</p> <a href="{link:2780}" target="_blank">Another link</a> I would like to "scan" all the HTML and replace all the Href Values with a URL found in my database. Something like this: - for each match of {link:x} - look in the database for id x - replace {link:x} with URL from database I'm looking at RegEX, of course, but cant really figure out how to do this in the smartest way. Any good ideas about links? Cheers A: Well, here's the extraction part: using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { string text = @"<a href=""{link:3645}"">One line</a><br/> <p>yada yaya</p> <a href=""{link:2780}"" target=""_blank"">Another link</a>"; Regex regex = new Regex(@"\{([^}]*)\}"); foreach (Match match in regex.Matches(text)) { Console.WriteLine(match.Groups[1].Value); } } } Version replacing links: using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { string text = @"<a href=""{link:3645}"">One line</a><br/> <p>yada yaya</p> <a href=""{link:2780}"" target=""_blank"">Another link</a>"; Regex regex = new Regex(@"\{link:([^}]*)\}"); text = regex.Replace(text, ConvertLink); Console.WriteLine(text); } private static string ConvertLink(Match match) { // Put real logic in here :) string link = match.Groups[1].Value; return "http://converted/" + link + ".html"; } } Note that the regex here is slightly more specific - it forces the link: part. You may or may not want that. I would say that using regular expressions in HTML isn't often a good idea - you should consider things like what would happen if the rest of the HTML itself contained curly braces. That's slightly less of a problem in the second form where we look for "link" but it's still not great... A: I think is better to use Html Agility Pack it is allow you to parse html like LINQ to XML and you can find all href attributes and replace with value what you need and look at the example HtmlDocument doc = new HtmlDocument(); doc.Load("file.htm"); foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href"]) { HtmlAttribute att = link["href"]; att.Value = FixLink(att); } doc.Save("file.htm"); where FixLink it is you function that set the correct value of href or HtmlWeb hw = new HtmlWeb(); HtmlDocument doc = hw.Load(txtLink.Text); foreach(HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]")) { HtmlAttribute att = link["href"]; att.Value = FixLink(att); } A: One way to do this is the to use the following regex in a loop till no further matches are found: /href="\{link:(\d+)\}"/ When a match is found then $1 should contain the link ID. Fetch the link from DB and replace it with the href.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why is class a reserved word in JavaScript? I am planning to implement class inherit interface using JavaScript. class is the perfect word as the name of the constructor. class = function (classname) {}; // create a class with classname classA = new class("classA"); // create a class named classA Unfortunately, class is a reserved word in JavaScript. Why does JavaScript reserve the word class (since it never uses it)? A: Languages evolve. It is prudent to reserve a few keywords that might come in use later. According to the ECMA standard, class is a Future Reserved Word. If you did not reserve them, introducing new keywords could conflict with existing code (which already might be using the word for other things). Happened with Java and assert. A: Now it's used in ECMAScript® 2015 Language Specification: class Foo { constructor(bar) { this.bar = bar; } } new Foo(10).bar; // 10 A: class is reserved as a future keyword by the ECMAScript specification Reserved Words - MDN A: It's reserved to future-proof ECMAScript The following words are used as keywords in proposed extensions and are therefore reserved to allow for the possibility of future adoption of those extensions. Don't fret though, if you're using best-practices in your JavaScripts, you're placing all accessible functions/variables/constructors in a namespace, which will allow you to use whatever name you'd like: foo = {}; foo['class'] = function(){...code...}; var myClass = new foo['class'](); A: It is there so that support can be added in future without breaking existing programs. Please take a look at the following post. You can also look at https://developer.mozilla.org/en/JavaScript/Reference/Reserved_Words
{ "language": "en", "url": "https://stackoverflow.com/questions/7524618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: web2py: how to copy a python array into a javascript one I'm currently having an issue with getting javascript and python to communicate in web2py. controller: def testDB(): a=[] a.append('a') a.append('b') a.append('c') return dict(m=a) (Eventually this will be replaced with an array of DB rows) Currently I'm trying to assign the values in m to an array in javascript. I've tried this a few ways: var t="{{=m}}"; Returns about 43 meaningless characters. Then I tried: var t= new Array(); var i=0;"{{q=0}}" "{{i=len(message)}}" i="{{=i}}"; for(q=0;q<i;q++,"{{q=q+1}}"){ t[q]="{{m[q]}}"; } Which failed because the python q variable would reset every time the loop did, which is the heart of my problem. I also tried using pop: for(q=0;q<i;q++,"{{q=q+1}}"){ alert("{{m.pop()}}"); } But the array keeps resetting again at the start of the loop, so it keeps showing the same variable. Is there a simpler way to copy the arrays, or to stop the python variables resetting, or even simply to plug the javascript q variable into "{{m[q]}}" instead? From what I've found, the problem comes from python being server side so you can't assign javascript values to it's variables, but I'm not sure what that has to do with the loop part of it (If I do the same outside a loop, the values do not reset). The common solution seems to be to use ajax or json, but I'd like to avoid that if possible. Thanks A: In web2py (or any server-side template language), you cannot mix server-side Python code with client-side Javascript code the way you have. When the page is requested, the Python in the web2py view is evaluated, and a pure HTML page (with Javascript code included) is generated and returned to the browser. The browser doesn't get any of the Python code and cannot execute a mix of Javascript and Python. The web2py view only inserts text/code into the page when you have {{=some_value}} (note the equals sign). So, things like {{m[q]}} have no effect. If you want to see what the browser is receiving from web2py, look at the page source in the browser -- it will show you the end result of the HTML/Javascript generated by your view. As for your particular question, you can use response.json() to convert your Python list to a JSON object. However, if you include that as is in the view, it will escape all the quotes, so you have to pass it to the XML() helper to avoid the escaping. Something like this: var t = {{=XML(response.json(m))}} A: Use the json module: >>> import json >>> s = json.dumps(range(5)) >>> print repr(s) '[0, 1, 2, 3, 4]' >>> print json.loads(s) [0, 1, 2, 3, 4] >>> A: Anthony's answer doesn't work on web2py 2.9.12 or above. To assign python variable value to javascript varible, first convert it to json in controller and then pass to view And in view, use XML() to assign it to javascript varible so that it is not escaped Controller from gluon.serializers import json def index(): array = [1, 2, 3, 4, 5] dictionary = dict(id=1, name='foo') return dict(array=json(array), dictionary=json(dictionary)) View <script> var js_array = {{=XML(array)}}; var js_dictionary = {{=XML(dictionary)}}; </script> Other solution is use ASSIGNJS helper Controller def index(): array = [1, 2, 3, 4, 5] dictionary = dict(id=1, name='foo') return dict(array=array, dictionary=dictionary) View <script> {{=ASSIGNJS(js_array = array)}} {{=ASSIGNJS(js_dictionary = dictionary)}} </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7524623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to create UI components dynamically using Sencha touch? I am a beginner to Sencha touch API. I am real struggling to make the UI components using Sencha touch lib. I have created some sample UI. But it is static in nature for now. How can i make it dynamic. Dynamic means i want my JSON response to decide the components to be added on the screen. How can i do this. Please help me. Ext.setup({ icon: 'icon.png', tabletStartupScreen: 'tablet_startup.png', phoneStartupScreen: 'phone_startup.png', glossOnIcon: false, onReady: function() { var form; var formBase = { scroll : 'vertical', standardSubmit : false, items: [ { xtype: 'fieldset', title: 'Login Screen', instructions: 'Enter agent number and password to login.', defaults: { required: true, labelAlign: 'left', labelWidth: '45%' }, items: [ { xtype: 'textfield', name : 'username', label: 'Agent Number', useClearIcon: true }, { xtype: 'passwordfield', name : 'password', label: 'Password', useClearIcon: false }] }], listeners : { submit : function(form, result){ console.log('success', Ext.toArray(arguments)); }, exception : function(form, result){ console.log('failure', result); } }, dockedItems: [ { xtype: 'toolbar', dock: 'bottom', items: [ { text: 'Exit', ui: 'exit', handler: function() { alert('Are you sure ?'); } }, { text: 'Login', ui: 'confirm', handler: function() { alert('Login please wait..'); } } ] } ] }; if (Ext.is.Phone) { formBase.fullscreen = true; } else { Ext.apply(formBase, { autoRender: true, floating: true, modal: true, centered: true, hideOnMaskTap: false, height: 385, width: 480 }); } form = new Ext.form.FormPanel(formBase); form.show(); } }); A: To add items to a panel use panel.items.add(list); and afterwards don't forget to call panel.doLayout();. See this question for example Calling the items.add method twice causes the two items to overlap on the card A: Dyanmic forms from json file in sencha touch check this link I have posted the solution for this .You just need to send xtype for the views through JSON .And whatever you want . I have also posted the json file and code to create dynamic view .hOpe it will help you
{ "language": "en", "url": "https://stackoverflow.com/questions/7524625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to get a form value in a controller I am using Spring MVC. How can I get text box value of the following snippet in my controller method? <form name="forgotpassord" action="forgotpassword" method="POST" > <ul> <li><label>User:</label> <input type='text' name='j_username' /></li> <li><label>&nbsp;</label> <input type="submit" value="OK" class="btn"></li> </ul> </form> A: You can use @RequestParam like this: @RequestMapping(value="/forgotpassword", method=RequestMethod.POST) public String recoverPass(@RequestParam("j_username") String username) { //do smthin } A: You can get single value by @RequestParam and total form values by @ModelAttribute. Here is code for single field- @RequestMapping(value="/forgotpassword", method=RequestMethod.POST) public String getPassword(@RequestParam("j_username") String username) { //your code... } And if you have more values in form and want to get all as a single object- Use @ModelAttribute with spring form tag. A: 1. Use Form tag library Just add <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <form:form name="forgotpassord" action="forgotpassword" method="POST"> <ul> <li><label>User:</label> <input type='text' name='j_username' /></li> <li><label>&nbsp;</label> <input type="submit" value="OK" class="btn"></li> </ul> </form:form> 2. Now in controller @RequestMapping(value="/forgotpassword", method = RequestMethod.POST) public ModelAndView forgotpassword(@ModelAttribute("FormJSP_Name") User user,BindingResult result) { String user = user.getjUsername(); //use it further ModelAndView model1 = new ModelAndView("NextJSP_Name"); return model1; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7524629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Is it possible in c++ to forbid calling a certain function at compile time? I have 2 classes: class Entity { void addChild(Entity* e); }; class Control : public Entity { }; What I want to do is to not allow adding a Control as a child of something that's not a Control. So, for example: Control c; Entity e; e.addChild(c); // This line would throw an error (at compile time if possible); The first thing I thought of is adding this to Entity: void addChild(Control* c){ assert(false); }; NOTE: both Entity and Control are abstract classes but both has many subclasses. But is there any way to get an error at compile time? A: You can declare the function, but don't implement it. That will give a linker error if you try to use it. A: void addChild(Control c){ assert(false); }; But is there any way to get an error at compile time? You could use static_assert if your implementation has some C++11 support, or BOOST_STATIC_ASSERT that will work in any implementation. However, I would suggest you redesign your hierarchy appropiately. Also note that you are mixing pointers and objects in the definitions of addChild suggested. A: In C++0x, the mechanism you seek is indeed possible. class Entity { public: void addEntity(Entity*); void addEntity(Control*) = delete; }; But it does not work as you would expect it! int main() { Entity e; Control c; e.addEntity(&c); // ERROR Entity& ec = c; e.addEntity(&ec); // OK } As others have suggested, your use case is fishy. If you do not want Control classes to be passed as Entity, then remove the inheritance relationship. If you keep the inheritance relationship, then whenever an Entity is expected, a Control can be passed. A: With a little bit of template specialization, it can be somewhat be done. But the only way I could make this work is by having the "addChild" method on the child element itself (renamed to "AttachToParent"). And passed by reference instead of by pointer. Template specialization is hard! class Entity { public: void AddChild(Entity* pChild); }; class Control : public Entity { public: template <typename T> void AttachToParent(T& parent) { parent.You_are_trying_to_attach_Control_to_something_not_a_Control(); } template <> void AttachToParent<Control>(Control& parent) { parent.AddChild(this); } }; int main(int argc, char** argv) { Entity eParent; Entity eChild; Control cChild1; Control cChild2; eParent.AddChild(&eChild); // legal cChild2.AttachToParent(cChild1); // allowed //cChild1.AttachToParent(eParent); // uncomment this line and a compile error will occur return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7524634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Refreshing Data in BO I am getting an error while refreshing the report in BO. What I have to do is to refresh a report in BO and find the refreshing time it taken for that. Once I find all these I have to insert those data in MySQL table. While I am doing this I get the following error. Exception in thread "main" com.businessobjects.rebean.wi.ServerException: A database error occured. The database error text is: (CS) "DBDriver failed to load : C:\Program Files\Business Objects\BusinessObjects Enterprise 12.0\win32_x86\dataAccess\connectionServer\dbd_oci.dll (The specified module could not be found. )" . (WIS 10901) How is this caused and how can I solve it? Here is the BO code: import java.util.Iterator; import java.sql.*; import com.businessobjects.rebean.wi.DocumentInstance; import com.businessobjects.rebean.wi.ReportEngine; import com.businessobjects.rebean.wi.ReportEngines; import com.crystaldecisions.sdk.exception.SDKException; import com.crystaldecisions.sdk.framework.CrystalEnterprise; import com.crystaldecisions.sdk.framework.IEnterpriseSession; import com.crystaldecisions.sdk.framework.ISessionMgr; import com.crystaldecisions.sdk.occa.infostore.IInfoObject; import com.crystaldecisions.sdk.occa.infostore.IInfoObjects; import com.crystaldecisions.sdk.occa.infostore.IInfoStore; public class RefreshWebi { /** * @param args * @throws ClassNotFoundException * @throws SQLException */ public static void main(String[] args) throws ClassNotFoundException, SQLException { // TODO Auto-generated method stub String cms="172.16.56.114"; String username="administrator"; String password=""; String auth="secEnterprise"; String driver="com.mysql.jdbc.Driver"; Connection conn; IEnterpriseSession enterpriseSession; System.out.println("success"); Long currentTime; try { ISessionMgr sessionMgr=CrystalEnterprise.getSessionMgr(); enterpriseSession=sessionMgr.logon(username, password,cms, auth); IInfoStore iStore=(IInfoStore)enterpriseSession.getService("InfoStore"); //bologger.entering("BOUtilities", "refreshWebIReport"); IInfoObjects reportObjects = iStore.query("select top 1 * from ci_infoobjects where si_kind='webi'"); ReportEngines reportEngines = (ReportEngines) enterpriseSession.getService("ReportEngines"); ReportEngine reportEngine = reportEngines.getService(ReportEngines.ReportEngineType.WI_REPORT_ENGINE); Iterator it = reportObjects.iterator(); while (it.hasNext()) { IInfoObject reportObject = (IInfoObject) it.next(); DocumentInstance documentInstance = reportEngine .openDocument(reportObject.getID()); currentTime = System.currentTimeMillis(); documentInstance.refresh(); System.out.println("Time taken to refresh " + (System.currentTimeMillis() - currentTime) / 1000); documentInstance.closeDocument(); int documentID = reportObject.getID(); String documentName=reportObject.getTitle(); long refreshtime=currentTime.intValue(); long refreshDuration=(System.currentTimeMillis() - currentTime) / 1000; int refreshtimes=(int)refreshtime; int refdur=(int)refreshDuration; System.out.println("Document id :"+documentID); System.out.println("Document name :"+documentName); System.out.println("Refreshtime :"+refreshtimes); System.out.println("Refresh duration :"+refdur); Class.forName(driver); conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password"); Statement st=conn.createStatement(); st.executeUpdate("insert into refreshtimings (documentid,documentname,refreshtime,refreshduration)values('"+documentID+"','"+documentName+"','"+refreshtimes+"','"+refdur+"')"); conn.close(); } reportEngine.close(); reportEngines.close(); } catch (SDKException e) { e.printStackTrace(); } } A: The error is referring to the database driver for that report is not available on the Business Objects server. I would check to see if you get the same error inside Info View, I'm guessing that you will. To resolve, you'll want to verify that the database type the report's connection is using is correct and that you have installed the relevant Data Source type for Business Objects.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does every Object in java have its own Constructor? This question is because of this line i read A new instance of an object is created by calling a constructor method. i agrre but constructor method of what..? an OObject or a Class itself..?.. Sorry if its an amateur question but i'm still learning java and i'm finding it hard to understand. and this reminded me of which is first chicken or egg..? EDIT: May be my question was not clear, i know how objects are created and every class has a constructor but what i want to know is, every Objects in the heap have their own copy of instance variable. in the same way will they also have a Constructor with them or its just something that only classes have. A: In Object-oriented design, a constructor is what creates an object out of your class definition... 2 key concepts here * *Class - a class is the blueprint for what an instantiated object should contain, both behaviour (methods) and information (properties). Usually contains a Constructor. *Object - The thing that is Created by the constructor, a instatiated version of the Class in practical use. Example of a Constructor in use public class MyClass { public int intProperty; // This is the Constructor, Notice it shares a name with the Class public MyClass(int value) { intProperty = value; } } Now to Use the class // |----------This is calling the constructor // | and placing a new MyClass object // v in myClassObejct MyClass myClassObject = new MyClass(3); myClassObject.intProperty; // 3 This creates a new MyClass Object Java does not work without Classes and Constructors, it is core to the design pattern of the language... Only Classes have constructors, Objects are the product of Constructors, an Object itself does not contain a constructor. A: Yes, you call the constructor of the class: MyClass instance = new MyClass(); but note that some objects have special constructors allowed by the language, for example String: String x = "foobar"; Is very similar to (but not exactly the same as): String x = new String("foobar"); Note that if no constructors are defined for the class, a default (no-args) constructor is implied . A: Yes every class has a constructor. If you do not explicitly define one, Java will create a default empty one for you. A: In Java every class has one or more constructors, and when you create an object using the new keyword, a constructor of that class is called. example: Integer i = new Integer("1"); //i is the object, and the Integer class constructor gets called A: Every class must have its own constructor. Either you provide one or more ctor's or the compiler generates a default no-argument ctor for you. If you have your own ctor, than the compiler doesn't generate anything. A: Every object in Java must be created through some Class's constructor, with the exception of a few primitive classes like String, which has special allocation rules. Even at the most basic level, you can always call Object o = new Object(); and since all objects in Java inherit from the Object superclass, most objects will inherit the default constructor. The exception to this is when a class only has a private constructor--one that cannot be called by any outside classes. In that case, because the default constructor is no longer necessary, it will not be accessible either. class MyClass { private MyClass() { //cannot be called by outside classes } } In general, this is used either for purely static classes (which don't need instances) or Singleton objects (that want to restrict instantiation). Therefore all objects are created from some constructor, but not all classes necessarily have a usable constructor. A: The statement "A new instance of an object is created by calling a constructor method" is an incorrect statement and is what's causing the confusion. There's no such thing as an instance of an object. An object is an instance of a class. The following 2 statements are valid: An object is created by calling a constructor method. An instance of a class (i.e. an object) is created by calling a constructor method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem implementing virtual method in derived class Hey I was trying to multiple inherit a pure virtual function using MVS2010 Compiler. So I can run a draw for all renderable objects. So here is the diagram in ASCII |Renderable | |Entity | |virtual bool draw()=0;| | functions in here | is - a is - a Shape So it seems it wont let me inherit the pure virtual function? and implement the virtual function. Here is my code. // Renderable.h #ifndef H_RENDERABLE_ #define H_RENDERABLE_ class Renderable { public: virtual bool Draw() = 0; }; #endif //Shapes.h #ifndef H_SHAPES_ #define H_SHAPES_ #include "Renderable.h" #include "Entity.h" class Shapes : public Entity, public Renderable { public: Shapes(); ~Shapes(); }; #endif //shapes.cpp #include "Shapes.h" Shapes::Shapes() { } Shapes::~Shapes() { } virtual void Shapes::Draw() { } I have tried multiple things and it doesn't work also google searched. A: First, you need to declare the draw function again in your Shapes class. Then make sure it has the same signature as the one declared in the Renderable class. //Shapes.h #ifndef H_SHAPES_ #define H_SHAPES_ #include "Renderable.h" #include "Entity.h" class Shapes : public Entity, public Renderable { public: Shapes(); ~Shapes(); virtual bool Draw(); }; #endif //shapes.cpp bool Shapes::Draw() { } A: Your return types are not matching. The Renderable::Draw returns bool, and you Shapes::Draw returns void. The entire function signature (including the return types) must match, otherwise the function in the derived class simply hides the function in the base class. A: You need to declare Draw in Shapes: class Shapes : public Entity, public Renderable { public: Shapes(); ~Shapes(); virtual void Draw(); }; Just defining it later is not enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hibernate child tables are not updated I have 3 mysql database tables called "Invoice","Selling","Invoice".ER diagram is as following. This is a simple database for billing application. Invoice table keeps data about the invoice and Selling table keeps the items which are bought for the particular invoice. Item table keeps details about the each item.when the purchasing is done, the invoice is issued. This is how I save to database using Hibernate.Hsession is which my Sessionfactory is in and returns a session.Date invoiceD = invoice.invoiceDate.getDate(); returns the invoice date successfully. public boolean saveInvoice() { try { Session session = HSession.getSession(); Transaction transaction = session.beginTransaction(); Date invoiceD = invoice.invoiceDate.getDate(); Entity.Invoice inv = new Entity.Invoice(); final int invcNo = this.invoiceNo; inv.setInvNo(invcNo); inv.setDateInv(invoiceD); inv.setValue(totalValue); inv.setInvDisc(discountAmount); inv.setInvNetvalue(netValue); inv.setInvPaid(paid); Set<Selling> sellings = new HashSet<Selling>(); Iterator iterator = purchasingList.iterator(); while (iterator.hasNext()) { Item item = (Item) iterator.next(); Selling sel = new Selling(); SellingId sId = new SellingId(); sId.setInvoiceInvNo(invcNo); sId.setItemItemid(item.getItemid()); System.out.println("Selling .." + item.getItemid()); sel.setId(sId); sel.setSellQty(item.getQty()); sel.setSoldPrice(item.getSellingPrice()); sel.setInvoice(inv); sel.setItem(item); sellings.add(sel); } inv.setSellings(sellings); session.save(inv); transaction.commit(); session.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } My problem is only the invoice data saved but not selling details which are set to invoice inv.setSellings(sellings); (Invoice table has one to may relationship and all purchasing items objects are added to Set and then that set is added to invoice object.) But when I save the Invoice and sellings seperately both are saved successfully.(saving invoice details in one session, comit its transaction, then again items are saved in another seperate session).(Hibernate mapping and creating entities were done with Netbeans IDE) Please any one tell my where & what the problem is and where should I check. Also let me know how to see the hibernate sql execution in netbeans IDE. Parent Invoice mapping; <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated Sep 18, 2011 5:03:10 PM by Hibernate Tools 3.2.1.GA --> <hibernate-mapping> <class name="Entity.Invoice" table="invoice" catalog="ssm"> <id name="invNo" type="java.lang.Integer"> <column name="inv_no" /> <generator class="identity" /> </id> <many-to-one name="customer" class="Entity.Customer" fetch="select"> <column name="Customer_cust_id" /> </many-to-one> <property name="dateInv" type="date"> <column name="date_inv" length="0" not-null="true" /> </property> <property name="value" type="double"> <column name="value" precision="22" scale="0" not-null="true" /> </property> <property name="invDisc" type="java.lang.Double"> <column name="inv_disc" precision="22" scale="0" /> </property> <property name="invNetvalue" type="double"> <column name="inv_netvalue" precision="22" scale="0" not-null="true" /> </property> <property name="invPaid" type="double"> <column name="inv_paid" precision="22" scale="0" not-null="true" /> </property> <set name="cheqIncomes" inverse="true"> <key> <column name="Invoice_inv_no" not-null="true" /> </key> <one-to-many class="Entity.CheqIncome" /> </set> <set name="sellings" inverse="true"> <key> <column name="Invoice_inv_no" not-null="true" /> </key> <one-to-many class="Entity.Selling" /> </set> <set name="receipts" inverse="true"> <key> <column name="Invoice_inv_no" not-null="true" /> </key> <one-to-many class="Entity.Receipt" /> </set> </class> </hibernate-mapping> child entity; Selling <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated Sep 18, 2011 5:03:10 PM by Hibernate Tools 3.2.1.GA --> <hibernate-mapping> <class name="Entity.Selling" table="selling" catalog="ssm"> <composite-id name="id" class="Entity.SellingId"> <key-property name="invoiceInvNo" type="int"> <column name="Invoice_inv_no" /> </key-property> <key-property name="itemItemid" type="string"> <column name="Item_itemid" length="12" /> </key-property> </composite-id> <many-to-one name="invoice" class="Entity.Invoice" update="false" insert="false" fetch="select"> <column name="Invoice_inv_no" not-null="true" /> </many-to-one> <many-to-one name="item" class="Entity.Item" update="false" insert="false" fetch="select"> <column name="Item_itemid" length="12" not-null="true" /> </many-to-one> <property name="sellQty" type="int"> <column name="sell_qty" not-null="true" /> </property> <property name="soldPrice" type="double"> <column name="sold_price" precision="22" scale="0" not-null="true" /> </property> </class> </hibernate-mapping> A: In your Hibernate mapping for the Invoice entity you need to set the cascade type to "persist" or possibly to "all", depending on what you need. Refer to the Hibernate documentation at http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html A: Check your mapping for Entity as pointed out by RichW above. Add cascade="all" to Set definition. <set name="sellings" inverse="true" cascade="all"> <key> <column name="Invoice_inv_no" not-null="true" /> </key> <one-to-many class="Entity.Selling" /> </set>
{ "language": "en", "url": "https://stackoverflow.com/questions/7524649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP: Populated drop down menu and get posted item I want to populate text file to drop down menu. Then, post the selected item to another text file. The script does not work. It only writes a blankline to "userinput.ini". My code for index.php: <html> <META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE"> <META HTTP-EQUIV="Pragma" CONTENT="no-cache"> <body> </body> </html> <form action="foo.php" method="post"> <input type="submit" value="Confirm"> </form> <?php $clientcode = "clientcode.csv"; $read_clientcode = @fopen($clientcode, "r") or die ("Couldn't Access $clientcode"); $clientcode_contents = fread($read_clientcode, filesize($clientcode)); $clientcode_array = explode("\n",$clientcode_contents); fclose($read_clientcode); echo '<select name="SITE">'; foreach($clientcode_array as $key => $value) { echo '<option value="'.$key.'">'.$value.'</option>'; } echo '</select>'; ?> My code for foo.php: <? $fp = "userinput.ini"; $fh = fopen($fp,"w") or die ("Error opening file in write mode!"); fputs($fh,$_POST['SITE']. "\n"); fclose($fh); ?> Thank you for your advice! A: you must have to end end of file. your code should be as follow <html> <META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE"> <META HTTP-EQUIV="Pragma" CONTENT="no-cache"> <body> </body> </html> <form action="foo.php" method="post"> <input type="submit" value="Confirm"> <?php $clientcode = "clientcode.csv"; $read_clientcode = @fopen($clientcode, "r") or die ("Couldn't Access $clientcode"); $clientcode_contents = fread($read_clientcode, filesize($clientcode)); $clientcode_array = explode("\n",$clientcode_contents); fclose($read_clientcode); echo '<select name="SITE">'; foreach($clientcode_array as $key => $value) { echo '<option value="'.$key.'">'.$value.'</option>'; } echo '</select>'; ?> </form> A: Take a look at the PHP function fgetcsv() Have that read the csv file to generate your pick list, then on foo.php have it also take that csv file again and this time use it as a white-list to check that the value has not been tampered with as Pål Brattberg has rightly commented. Picking the csv file up twice might make you think about creating a shared function, or if this csv file only changes say, once a week, you might just bite the bullet and re-write the csv as a straightforward PHP array in a file - which you update when a new csv is uploaded. A: Problem fixed: index.php <html> <META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE"> <META HTTP-EQUIV="Pragma" CONTENT="no-cache"> <body> </body> </html> <form action="foo.php" method="post"> <?php $clientcode = "clientcode.csv"; $read_clientcode = @fopen($clientcode, "r") or die ("Couldn't Access $clientcode"); $clientcode_contents = fread($read_clientcode, filesize($clientcode)); $clientcode_array = explode("\n",$clientcode_contents); fclose($read_clientcode); echo '<select name="SITE">'; foreach($clientcode_array as $SITE) { echo ("<option"); if ($HTTP_POST_VARS["SITE"] == $SITE) echo (" selected"); echo (">$SITE"); } ?></select><br> <input type="submit" value="Confirm"> </form> foo.php <?php echo $HTTP_POST_VARS['SITE']; ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7524650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rich Text Editor suggestions for CMS build onZend Framework I developed a simple CMS, for managing my website in Zend Framework. Now for the contents I require a rich text editor. Is there any specialized editor, which I can use directly on Zend Framework. Found digit editor, but as I am a novice I found it pretty hard to implement. Moreover to rich text editing, I require to upload images and attach files too. A: As @Frederik Eychenié told you, this looks like a "client side" issue. You can see a similar question for the rich text editor here: RichTextEditor for PHP CMS Personally, I'm using CKEditor together with Zend Framework. Zend Framework doesn't need to know anything about the editor in the client side, it retrieves the HTML data as just another form element (and validates it, of course). Hope that helps, A: Rich text editors are mainly browser side, that's why it's hard for you to find one for Zend Framework, php being server side. Implementing a rich text editor generally means doing some javascript to make it work, the php side is normally the same thing as handling data coming from a usual form, although validating/filtering it's data will require more work in security terms. Have a look at HTMLPurifier, and this ZendCast about it's integration in ZF. For image uploading and file attachment it's quite the same problem. The editor provides an interface for navigating your uploaded files and to send new ones, but you have to code at least usual file uploading and retrieving on server side and then adapt it to comunicate well with the editor. Generally you'll find in the editor's docs information about what kind of request it sends and where, and what kind of data it need have access to. However, there are some collaboration's between Zend and Dojo which resulted in the Zend_Dojo component, and Dojo has a Rich text editor and a file uploader. But as i never used them i can't give you any advice about them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Preparing for and backing up my first non-school project So I've decided to start a personal programming project just to try and to improve my programming skills and improve my abilities to organize myself better. The problem is I've only worked on small assignments so far, at most a few classes (the files of course) per project in Java. We covered inheritance and basic data structures (linked list & stack) in my previous winter semester and am currently taking Data Structures & Algorithms and Advanced Program Design with C++. I intend to do the project in C++ since it'll help me out with the course. This means I don't have experience organizing a larger project and all it entails. I would love some general advice related to what I've already discussed. I don't have a project idea yet, which I know would help this out a lot. One thing in particular I'm concerned about is backup, since it would keep my project safe as well as the ability to access from other machines. I've been using Dropbox for my homework for all my courses for a while, but after hearing about their privacy issues I don't really want to put anything important on it. What's a good service for backing up code privately and securely, but so that I can still work on it without constantly redownloading just to unencrypt. Or should I even bother with that and just make it open source? Either way it would be good if the solution were preferably free or very cheap. In either case I was thinking about trying some sort of version management, but once again I know very little to nothing about it. I was thinking of using NetBeans since it works with everything I need for school so I may as well use it for this as well, so the version management should work with it. Also my preferred operating system is Windows 7 64-bit. I've heard good things about Git but apparently NetBeans only works with a local Git repository so I'm not sure how well that would work with an online repository. Also, a quick question on versioning: should the program be in some sort of working state before even uploading it to the version management system, be it on an open source site or not? I know I'm asking a lot and I bet there are even more things I could ask. I'm looking for as much advice as I can get because I really feel like I have no idea what I'm doing or getting myself into. Edit: Of course the code should be able to be worked on while offline, when I take the train home for example. A: You can take a look at Bitbucket (https://bitbucket.org/) on which you can host public and private repositories (with Mercurial). For your concerns about getting something to a working state before uploading, this is not important. If it's a new project, it's totally normal to have nothing working for some times. A: Since NetBeans7.0.1 (according to the Plan for Git support), NetBeans supports pull/push operation to/from a remote Git repo. So you can use it with: * *a remote repo on an USB disk for backup (either with git bundle or a bare repo) *GitHub for publishing a public version. You don't need to have a stable project when you check-in with a DVCS (Git or Mercurial) because you are committing only in your local repo. And if you are publishing on a backup repo (like your USB key), it doesn't matter. Those intermediate commits are called "checkpoint commits": see "git newbie question - Commit style: Commit all changed files at once or one at a time?" But if you are publishing on a public repo (than other can clone), then it is best to clean your history of commits first.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to pause video recording in gstreamer I created a pipeline as this: v4l2src -> tee -> queue -> encoder -> avimux -> filesink tee -> queue -> v4l2sink Now I want to pause the recording(keep loopback, but pause encoder), and when I resume, I expect the recoding file continues from where I resume. I tried to use gst_element_set_state: If I pause the pipeline, the loopback stops. If I pause the encoder, the return value of gst_element_set_state is ok, but the encoder not really pauses. I paused the avimux, same with encoder. Can anyone help? Thank a lot. A: Please take a look at camerabin / camerabin2 in gst-plugins-bad. What you want to do is unfortunately a bit complicated. I'll explain. For starters you will need to get the src-pad on the queue, set it to be leaky=downstream and block the src-pad. This pauses the video. You can also use the valve element after the queue for the same effect. If you are lucky everything is fine (should be the case for avimux). For other formats (mp4mux) you will need to remember the the time-stamp of the last buffer when pausing (via pad-data-probe) and when you get the first new buffer after unpausing, subtract the pausing time from the timestamps. Otherwise you will have a pause in the resulting video. This is due to the fact that video streams in mp4 containers can be sparse. This also affects other formats. In theory you should also be able to handle this, by sending a new-segment event downstream after unpausing (before the first buffer), but I have not tried that. Again check how it is done especially in camerabin2. Also consider just using camerabin2 :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7524658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Cross domain uploading Are there ways to upload files using a form in url A that points to url B in its "action" attribute without redirecting the page to url B? A: I know it's 3 years later, but since I had this same question myself today, I figured I'd post my solution here. It's not the prettiest, but it uses an iframe, which should help it be more supported by legacy browsers. The biggest challenge of the iframe is that you can't read the contents of an iframe if it's on another domain for security reasons (the browser restricts said functionality). In essence, my solution is this: * *The user selects a file to upload. *The form that encases the file field sends a POST request targeting a hidden iframe. *A PHP script executes in the handler script, uploading the file. *When the script is done (or errored out), it sends a Location redirect, sending the iframe back to HTTP_REFERER, which will be the on the same domain as the form page, which means that the script will be able to read the contents. *In order to send useful information along the redirect, I simply add onto the GET parameters of the referrer page. These can be extracted and read via JavaScript. The HTML: <form method="post" action="http://other/website/upload.php" enctype="multipart/form-data"> <input type="file" name="file" /> </form> <br /><br /> <img id="avatar" /> The JavaScript: $('form').submit(function () { $('<iframe></iframe>').attr({name: 'iframe', id: 'iframe'}).prependTo($('body')).load(function () { var response = JSON.parse(decodeURIComponent(/[\\?&]_response=([^&#]*)/.exec(this.contentWindow.location.href)[1]).replace(/\+/g, ' ')); if (response.error) { alert(response.error); } else { $('#avatar').attr('src', response.url); } $(this).remove(); }); $(this).attr('target', 'iframe'); }); $('input[name="avatar"]').change(function () { $('form').submit(); }); The PHP: <?php define('MAX_SIZE', 28 * 1024); // 28 KB define('UPLOAD_PATH', 'uploads/'); define('UPLOAD_URI', 'http://other/website/uploads/'); header('Content-Type: application/json'); header('Access-Control-Allow-Origin: *'); function format_size ($bytes) { for ($labels = array ('B', 'KB', 'MB', 'GB', 'TB'), $x = 0; $bytes >= 1024 && $x < count($labels)-1; $bytes /= 1024, ++$x); return round($bytes, 2) . ' ' . $labels[$x]; } function respond ($message) { parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY), $params); $params = array_merge($params, array ('_response' => json_encode($message))); header('Location: ' . $_SERVER['HTTP_REFERER'] . '?' . http_build_query($params)); exit; } if (isset($_FILES['file'])) { $file = $_FILES['file']; switch ($file['error']) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: respond(array ('error' => 'You may not upload a file larger than ' . format_size(MAX_SIZE) . '.')); break; case UPLOAD_ERR_PARTIAL: case UPLOAD_ERR_NO_TMP_DIR: case UPLOAD_ERR_CANT_WRITE: case UPLOAD_ERR_EXTENSION: respond(array ('error' => 'The server could not upload the file.')); break; } if ($file['size'] > MAX_SIZE) { respond(array ('error' => 'You may not upload a file larger than ' . format_size(MAX_SIZE) . '.')); } else if (!in_array($file['type'], array ('image/png', 'image/gif', 'image/jpeg'))) { respond(array ('error' => 'The uploaded file must be a PNG, GIF, or JPEG image.')); } $split = explode('.', basename($file['name'])); $ext = array_pop($split); $name = implode('.', array_merge($split, array (uniqid(), $ext))); if (!move_uploaded_file($file['tmp_name'], UPLOAD_PATH . $name)) { respond(array ('error' => 'The server could not upload the file.')); } else { respond(array ('url' => UPLOAD_URI . $name)); } } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7524659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: how to get rid of the fraud transction made through a interface developed with ubercart-paypal in drupal i had developed a site in drupal using ubercart and paypal as default gateway, everything is working fine only one problem - some people making the fraud transaction through my site, i got log messages from paypal like "Noting Matched Transaction Declined" even after getting error messages the credit card is processed. Is their any method/settings in paypal or in the ubercart module to halt the transaction after getting this kind of error messages. A: Noting to do with the ubercart module. At the paypal, settings are available in profile under section Security and risk setting where we can set the different filters to accept and deny the payment based on specific conditions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: django - use filter in the argument to a simple_tag I had a custom simple-tag. And it seems I can't use a filter as its argument. Here is an example. mysum is the tag. myincrease is the filter. foobar is a variable and I want to pass foobar|myincrease to mysum. The template: {% mysum foobar|myincrease 1 2 %} gives the error: TemplateSyntaxError at / Caught VariableDoesNotExist while rendering: Failed lookup for key [foobar|myincrease] in ... The tag: @register.simple_tag def mysum(a, b, c): return a + b + c The filter: @register.filter def myincrease(num): return num + 1 I have worked around my original problem using other approaches. But I'm still wondering if this is by design, or a mistake of mine, or a bug of django, or something that has been overlooked. I think calling something like compile_filter in the simple_tag decorator implementation would do it. A: Though it doesn't appear to be mentioned in the ticket, it looks like the fixing of https://code.djangoproject.com/ticket/13956 added filter support to positional arguments to a tag. You can see the commit at https://github.com/django/django/commit/8137027f - the new parse_bits function called compile_filter() on positional arguments. Another workaround would be to use the {% with %} tag.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Why my ordering by linq does not work Trying to order logs by logtype or by logType and thenBy DateTime but does not work.What am I missing? public enum LogType { Fatal, Error, Warn, Info, Debug, None, } public class Log { public DateTime LoggedDateTime { get; set; } public string Message { get; set; } public LogType LoggedType { get; set; } public override string ToString() { return string.Format("LogType: {0} Datetime: {1} Message: {2}", LoggedType, LoggedDateTime, Message); } } class Program { static void Main() { var logFatal = new Log { LoggedDateTime = new DateTime(2011, 2, 22), Message = "Hi am a Fatal message", LoggedType = LogType.Fatal }; var logInfo = new Log { LoggedDateTime = new DateTime(2013, 2, 22), Message = "Hi I am a Info message", LoggedType = LogType.Info }; var logError = new Log { LoggedDateTime = new DateTime(2010, 2, 22), Message = "Hi I am a Error message", LoggedType = LogType.Error }; var logWarning = new Log { LoggedDateTime = new DateTime(2014, 2, 22), Message = "Hi I am a Warning message", LoggedType = LogType.Warn }; List<Log> logs = new List<Log> { logWarning, logError, logInfo, logFatal }; Console.WriteLine("Not Ordered"); Console.WriteLine(""); logs.ForEach(x=>Console.WriteLine(x.LoggedType)); var orderedLogs = logs.OrderBy(x => x.LoggedType == LogType.Fatal) .ThenBy(x => x.LoggedType == LogType.Error) .ThenBy(x => x.LoggedType == LogType.Warn) .ThenBy(x => x.LoggedDateTime).ToList(); Console.WriteLine("Ordered by logType fatal first and NOT WORKING"); Console.WriteLine(""); orderedLogs.ForEach(x=>Console.WriteLine(x.LoggedType)); Console.WriteLine(""); Console.WriteLine("Ordered by logType fatal first and NOT WORKING");//NOT WORKING List<Log> orderedFatal = logs.OrderBy(x => x.LoggedType == LogType.Fatal).ToList(); orderedFatal.ForEach(x => Console.WriteLine(x.LoggedType)); Console.WriteLine(""); Console.WriteLine("Sorted by datetime AND WORKS"); //THIS IS THE ONLY ONE THAT WORKS logs.Sort((x,y)=>x.LoggedDateTime.CompareTo(y.LoggedDateTime)); logs.ForEach(x => Console.WriteLine(x.LoggedDateTime)); Console.Read(); } } Thanks for any suggestions A: The problem is that false is ordered before true. Thus first in your order come those that are not Fatal. Out of those first come those that are not Error etc. You can use inequalities to make it work: x => x.LoggedType != LogType.Fatal etc. or use OrderByDescending and ThenByDescending. But I'd prefer to give an order of the enum: public enum LogType : int { Fatal = 5, Error = 4, Warn = 3, Info = 2, Debug = 1, None = 0, } and then just use this value: var orderedLogs = logs.OrderByDescending(x => x.LoggedType); A: Both your logWarning and logError have LoggedType = LogType.Error ! Another point: you should implement/use an IComparer for LogType... see MSDN at http://msdn.microsoft.com/en-us/library/8ehhxeaf.aspx Bascially something like: public class LogComparer : IComparer<Log> { public int Compare(Log x, Log y) { if ( x == y ) return 0; if ( x.LoggedType == y.LoggedType ) return 0; if ( x.LoggedType == LogType.Fatal ) return 1; if ( y.LoggedType == LogType.Fatal ) return -1; // etc. } } // Usage similar to this logs.OrderBy(x => x, new LogComparer()); A: You need to do something like: var orderedLogs = logs.GroupBy(l => l.LoggedType) .OrderBy(g => g.Key) .SelectMany(g => g.OrderByDescending(l => l.LoggedDateTime)).ToList(); A: You can sort the collection by the field LoggedType, then by the field LoggedDateTime in the following code: var orderedLogs = logs.OrderBy(x => x.LoggedType) // not x => x.LoggedType == LogType.Fatal .ThenBy(x => x.LoggedDateTime).ToList(); I think there will be sorting by integer representation of enum. So with your enum there will be Fatal, Error, Warn etc. Or you can use IComparer (from Yahia answer) for your own definition rules of comparison.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hudson / Sonar report about compiler warnings Is there a plugin to show compiler warnings in Hudson and / or Sonar? A: Hudson/Jenkins has the Warnings plugin. There's no similar plugin for Sonar, but I'm wondering if the compiler checks are redundant with the many checks embedded in Sonar (Checkstyle, Sonar Squid, PMD, Findbugs, ...).
{ "language": "en", "url": "https://stackoverflow.com/questions/7524671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Javascript Beginner: Why isn't my form submitting Trying to teach myself javascript here so do bear with me. Why isn't the following snippet working? <script type="text/javascript"> function form() { var role_id = document.contextform.role.value; document.contextform.action="profile/" + role_id; document.contextform.submit(); } </script> <form name="contextform" method="post" action="" /> <div class="input_group"> <select name="role" style="opacity: 0;" onchange="form();"> <option value="none">Select Context</option> <option value="4">Profile 4</option> </select> </div> </form> I'm basically trying to redirect the user based on the value of the option on the drop down list. Thanks. A: you closed the form tag when you declare it <form name="contextform" method="post" action="" /> . . </form> changed it to this and try again <form name="contextform" method="post" action=""> . . </form> A: Your HTML is invalid <form name="contextform" method="post" action="" /> should be <form name="contextform" method="post" action=""> Also, your function name form() is a reserved word. Try something else for the name of that function. A: Please change the function name form() to something else such as myForm(). A: Frist of all, <select name="role" style="opacity: 0;" onchange="form();"> the opacity there makes it disappeared. So, you can just remove the style. Secondly, the name form seemsed to be a reserved keyword. So, you can't use that name. Try to put some other name like form_handler() <script type="text/javascript"> function form_handler() { var role_id = document.contextform.role.value; document.contextform.action="profile/" + role_id; document.contextform.submit(); } </script> and change your html as well (with the style removed) <select name="role" onchange="form_handler();"> A: If you change the name of your function to postForm in both the function declaration and in the onchange handler, it seems to work for me. There must be a conflict with a global identifier or reserved word named "form". A: That script really isn't needed, try: <form name="contextform" method="post" action="/profile"> <div class="input_group"> <select name="role" style="opacity: 0;" onchange="document.contextform.submit();"> <option value="none">Select Context</option> <option value="4">Profile 4</option> </select> </div> </form> A: Try to replace all document.contextform on document.getElementsByName('contextform') A: Nai, The function name that you have is the same as the key word. That means the form() is the same as the tag "form" and therefore you will get an error and the submit will not work. If you change the function name to form1() it will do the trick. Another thing, role_id value is 4 so the path in action event would be "profile/4" but the file extension is not present so i do not think you will sent to the correct. Below is you code with the changes that i have suggested, hope they work for you. <script type="text/javascript"> function form1() { var role_id = document.contextform.role.value; document.contextform.action="profile/" + role_id + ".html"; document.contextform.submit(); } </script> <form name="contextform" method="post" action=""> <div class="input_group"> <select name="role" style="opacity: 0;" onchange="form1()"> <option value="none">Select Context</option> <option value="4">Profile 4</option> </select> </div> </form>
{ "language": "en", "url": "https://stackoverflow.com/questions/7524676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cacheing pictures for a listview so i have a listview with images from some urls, i tryed to save the pictures after loading in a arrayList of bitmaps but in the end only 2-3 pictuers showed in the list on my device (the emulator shows all pictures), so i tried to cache the pictures after downloading and i use: ` for (int i = 0; i < url.length; i++){ URL urlAdress = new URL(url[i]); HttpURLConnection conn = (HttpURLConnection) urlAdress .openConnection(); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); Bitmap bmImg = BitmapFactory.decodeStream(is); // picList.add(bmImg); File cacheDir = context.getCacheDir(); File f = new File(cacheDir, "000" + (i + 1)); FileOutputStream out = null; try { out = new FileOutputStream(f); bmImg.compress(Bitmap.CompressFormat.JPEG, 80, out); } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) out.close(); } catch (Exception ex) { } } } ` to save the pics in cache, and then i use this to load the pictures from cache in the adapter : File cacheDir = context.getCacheDir(); File f = new File(cacheDir, "000" + position); Drawable d = Drawable.createFromPath(f.getAbsolutePath()); holder.icon.setImageDrawable(d); but i still get 3-4 pictures from 9, is this a memory issue ? (all the pics together have 300 kb) A: found the problem Bitmap bmImg = BitmapFactory.decodeStream(is); has bugs and skips data on slow internet conections like on a real device, so i added Bitmap bmImg = BitmapFactory.decodeStream(new FlushedInputStream(is)); and static class FlushedInputStream extends FilterInputStream { public FlushedInputStream(InputStream inputStream) { super(inputStream); } @Override public long skip(long n) throws IOException { long totalBytesSkipped = 0L; while (totalBytesSkipped < n) { long bytesSkipped = in.skip(n - totalBytesSkipped); if (bytesSkipped == 0L) { int b = read(); if (b < 0) { break; // reached EOF } else { bytesSkipped = 1; // read one byte } } totalBytesSkipped += bytesSkipped; } return totalBytesSkipped; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7524690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to authenticate on an ASP.NET 4.0 application and Redirect to ASP.NET 3.5 app On a Windows Server 2003 machine running IIS 6 I have an ASP.NET 4.0 web application on its own website (http://authorize.com) that has the Login.aspx page. When the login button is pressed it authenticates the user with: FormsAuthentication.SetAuthCookie("spud", False) Response.Redirect("http://legacy.com/Default.aspx") In the web.config of authorize.com I have the authentication configured like so: <authentication mode="Forms"> <forms loginUrl="Login.aspx" timeout="5000000" ticketCompatibilityMode="Framework20" protection="Validation"> </authentication> <authorization> <deny users="?"/> </authorization> <machineKey decryptionKey="AF96F355CEC57EFD2F996515BF465166075E596F19EB9B47" validationKey="5C9D7A8F3E336278F771C7FE45B65BF6E9B41BA9575F04672CCC4242B225DD399FAF7B806B2CD5545200CD0E63A8991CA6BFB2D77FE9C5B0D69889359574C5F3" validation="SHA1" decryption="3DES"/> I also have an ASP.NET 3.5 web application on a different website (http://legacy.com). It has a web.config of: What is currently happening is when you go to http://legacy.com/Default.aspx it redirects you to http://authorize.com/Login.aspx and then when you click the login button it takes you back to the Login.aspx page as if you were not authenticated. How do I configure my sites so that the ASP.NET 3.5 site can share the authentication token of the ASP.NET 4.0 site? EDIT: I had to explicitly add protection="Validation" in the forms tag of all web.config's to make the ASPXAUTH cookie the same length. A: Browser does not pass cookies of one domain to another domain - so in your case, cookies for authroize.com and legacy.com have different scopes and browser will not share them. So your scheme will not work. However, if you can make both sites as a part of same domain (e.g. authroize.myite.com and legacy.mysite.com) then cookie created as parent domain (mysite.com) will be shared across both sites. Note that ASP.NET allows you to set the domain for the cookie using domain attribute of forms configuration element. Of course, you still need to have same set of machine keys for both the servers. For cross-domain authentication to work, you have to basically implement single sign-on feature. In your case, a implementation outline will be would be * *Legacy site will redirect to authentication site for authentication passing the return url *authentication site will authenticate the user, set the cookie for itself and then redirect to legacy site return url passing the token for the authenticated user. *A simplistic implementation for a token can be user identity encrypted by shared private key. However to avoid replay attacks etc, you need to add time-stamp into the token. Also legacy site also needs to pass some random salt value while requesting authentication that will be used for hashing etc. *Once legacy site receives the user token, it validates the token (by decrypting it, checking hash & time-stamp etc) and set its own authentication cookie. See this link (for subdomain) & this link (for cross domain) that describes above approaches in more detail.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get the desired output using awk in unix I'm new to using awk, and I'm stuck on a problem. I have a file: startpoint--A endpoint--B startpoint--C endpoint--D I want the output as desired in a column so that under startpoint, I have all the start variables(A,C) and under endpoint all the end varibles(B,D). For example: startpoint endpoint A B C D How can I accomplish this with awk? A: Presumably your data file alternates startpoint and endpoint lines. In that case you can just save the most recent startpoint and print them both out when you encounter an endpoint. $ cat data.txt startpoint--A endpoint--B startpoint--C endpoint--D $ cat points.awk BEGIN { print "startpoint endpoint" } $1 == "startpoint" { sp = $3 } $1 == "endpoint" { printf "%-12s%s\n", sp, $3 } $ awk -F- -f points.awk data.txt startpoint endpoint A B C D A: Don't need awk, cut and paste will do: { printf "startpoint\tendpoint\n" cut -d '-' -f 3 data.txt | paste - - } | column -t I assume that all you data is "well-formed", with an endpoint immediately following a startpoint.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: using structures in GCC and getting errors The same code ran in TURBO C. struct details { char name[20]; int year; float price; }my_str; details book1[10]; This error is produced. How can this be fixed? ram.c: In function ‘main’: ram.c:11:1: error: ‘details’ undeclared (first use in this function) ram.c:11:1: note: each undeclared identifier is reported only once for each function it appears in A: There are two ways to fix this: Change second line to this: struct details book1[10]; Or you can change the declaration to: typedef struct{ char name[20]; int year; float price; } details; C is slightly different from C++, so you can't declare structs quite the same way. A: details book1[10]; needs to be ... struct details book1[10]; A: You need to make the structure variable declaration like this: struct details book1[10]; This is because the details is not typedefed, and therefore you cannt use it like a user defined type, and therefore you need to use the struct keyword. Note that, in your above definition my_str is a variable (allocated object) of type struct details You can also do: typedef struct details { char name[20]; int year; float price; } my_str; And then do: my_str book1[10]; This is same as above. Here note that, the my_str is not a variable (object) but the typename which you have defined with the typedef keyword. After this point the compiler would know that you are using the my_str as a new user defined type name for the composite structure data type you have created, and therefore you can use my_str directly instead of using struct details A: This is a a bit more correct in terms of C: typedef struct _detailstype { char name[20]; int year; float price; } details; details book1[10];
{ "language": "en", "url": "https://stackoverflow.com/questions/7524715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: InputStream.read method getting called too fast I'm trying to read InputStream data from Bluetooth socket and the method does what it suppose to do at the beginning. But for some reason later on it doesn't read everything. Here's the method that I'm using right now: public int read(byte[] b, int off, int len) When I check the byte array its end part is the beginning of the next part of data. Which means the read method got called again even before it finished reading. Does anyone know how to handle this problem? A: You are going to have to deal with this yourself in your application protocol design. Assuming that you are using Android BluetoothSocket with RFCOMM, the javadoc says this: RFCOMM is a connection-oriented, streaming transport over Bluetooth. and The interface for Bluetooth Sockets is similar to that of TCP sockets: While it is not crystal clear from these quotes, the implication is that the streams will behave like TCP streams, and that means that there are no reliably discernible message / packet / records boundaries in the bytes deliver by the read methods. If the sender decides to send two messages back-to-back, then the receiver is liable to get the end of one message and the beginning of the next one in the read buffer. So ... if you have a message / packet oriented application protocol running over the socket, you have to design your application protocol so that the message boundaries are discernible by the receiver irrespective of how few / many bytes come through at a time. In other words, you need to use packet byte counts, end-of-packet markers or some-such in your protocol to allow the receiver to figure out where each packet ends and the next one begins.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: powershell : using get-content as body of an smtp mail I am using powershell to send an SMTP mail. The body of the email is from a file. The problem is, when I receive this email, it removes all spaces and linefeeds so it looks ugly. Outlook client is no removing linebreaks. My code is as follows: $smtpserver = "smtpserver" $from="email1@domain.com" $to="email2@domain.com" $subject="something" $body= (Get-Content $OutputFile ) $mailer = new-object Net.Mail.SMTPclient($smtpserver) $msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body) $msg.IsBodyHTML = $true $mailer.send($msg) I have even tried to use get-content with -encoding ASCII and couple of others but no help. Can anyone please help? - thanks A: Add HTML line break tag at each end of a line: $body= (Get-Content $OutputFile) -join '<BR>' A: Found the answer: use out-string in when reading the file. i.e. $body= (Get-Content $OutputFile | out-string ) A: What worked for me was converting the content to HTML as the following: $html = $result | ConvertTo-Html | Out-String Send-MailMessage -Credential $mycreds -From "" -To "" -BodyAsHtml $html -Encoding ASCII -Subject "Test" -SmtpServer '' -Port 25 A: If you are using PowerShell v2.0 try Send-MailMessage: http://technet.microsoft.com/en-us/library/dd347693.aspx The default encoding here will be ASCII. So, to be able to retain the encoding, you may want to try and find the encoding of the file and then set the relevant encoding. To find encoding of a file, use the script here. http://poshcode.org/2059 Now, combine the above function with Send-MailMessage. For example, send-mailmessage -from "User01 <user01@example.com>" -to "User02 <user02@example.com>", "User03 <user03@example.com>" -subject "Sending the Attachment" -body (Get-Content C:\somefile.txt) -dno onSuccess, onFailure -smtpServer smtp.fabrikam.com -encoding (Get-FileEncoding C:\somefile.txt) Remember, Get-FileCoding is not a builtin cmdlet. You need to copy it from the poshcode link.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: android - passing variable from intent extra to ImageView Android newcomer here. I'm trying to setup an activity to display a selected image. The foundation of this code is from the Hello, Android 3rd edition (Pragmatic Programmer) that I have attempted to modify. Basically, I want to be able to click a button in one activity, and have that start another activity that changes the layout to display the image associated with that button. I have several buttons, and would like each button to cause a different image to be displayed. files (simplified code by removing pic3-...): main.xml : layout for two buttons (pic1 and pic2) Main.java : contains onclicklisteners for buttons - intents w/ extras (filename for image) Viewer.java : default created by eclipse, purpose is to set new layout setContentView(R.layout.viewer); viewer.xml : layout for ImageView I have gotten strings stored in strings.xml to work (I create a string in eclipse with a value of @drawable/pic1 and give it a name of imagename so I can call @string/imagename for the src of ImageView in viewer.xml). However, I have learned from searching and reading on this forum that I cannot change strings.xml values from within an activity (my original idea was to have a couple lines of code in Viewer.java that would change the imagename string to whatever was passed by the Intent extras. I found this post (http://stackoverflow.com/questions/3523384/android-pass-string-from-activity-to-layout) where someone was trying to do a similar thing with a TextView, but I've tried that route and I keep getting syntax errors on those lines. I'm really stuck. Any ideas? Thanks! main.java public class Main extends Activity implements OnClickListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // click listeners View pic1Button = findViewById(R.id.pic1_button); pic1Button.setOnClickListener(this); View pic2Button = findViewById(R.id.pic2_button); pic2Button.setOnClickListener(this); } // ... public void onClick(View v) { switch (v.getId()) { case R.id.pic1_button: Intent l = new Intent(this, Viewer.class); l.putExtra("imagefilename", "pic1filename"); startActivity(l); break; case R.id.pic2_button: Intent i = new Intent(this, Viewer.class); i.putExtra("imagefilename", "pic2filename"); startActivity(i); break; } } } viewer.xml <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/imageView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src='@string/imagename' android:scaleType="matrix"> </ImageView> </FrameLayout> A: Your question is not very clear but from my understanding you could achieve that using the following code. AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.stackoverflow.biowi" android:versionCode="1" android:versionName="1.0"> <application android:label="@string/app_name" android:icon="@drawable/icon"> <activity android:name="Main" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="Viewer" /> </application> </manifest> Main.java: package com.stackoverflow.biowi; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class Main extends Activity implements OnClickListener { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // click listeners View pic1Button = findViewById(R.id.pic1_button); pic1Button.setOnClickListener(this); View pic2Button = findViewById(R.id.pic2_button); pic2Button.setOnClickListener(this); } public void onClick(View v) { Intent i = new Intent(this, Viewer.class); switch (v.getId()) { case R.id.pic1_button: i.putExtra("imagefilename", "pic1filename"); break; case R.id.pic2_button: i.putExtra("imagefilename", "pic2filename"); break; } startActivity(i); } } Viewer.java: package com.stackoverflow.biowi; import android.app.Activity; import android.os.Bundle; import android.widget.ImageView; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.View; import android.widget.ImageView; public class Viewer extends Activity { /** To be documented. */ private Bitmap mImage1; /** To be documented. */ private Bitmap mImage2; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.viewer); Bundle bundle = getIntent().getExtras(); String imageName = bundle.getString("imagefilename"); // click listeners ImageView imageView = (ImageView)findViewById(R.id.imageView); mImage1 = BitmapFactory.decodeResource(getResources(), R.drawable.pic1); mImage2 = BitmapFactory.decodeResource(getResources(), R.drawable.pic2); if(imageName.matches("pic1filename")) { imageView.setImageBitmap(mImage1); } else if (imageName.matches("pic2filename")) { imageView.setImageBitmap(mImage2); } } } main.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Hello World, Main" /> <Button android:id="@+id/pic1_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button" /> <Button android:id="@+id/pic2_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button" /> </LinearLayout> viewer.xml: <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/imageView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src='@drawable/pingouin' android:scaleType="matrix"> </ImageView> </FrameLayout> With pic1.png, pic2.png and pingouin.png in res/drawable…
{ "language": "en", "url": "https://stackoverflow.com/questions/7524725", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Outdated book description of Try-Except-Finally statement I am following Apress, Beginning Python from Novice to Professional book. It is mentioned that: finally. You can use try/finally if you need to make sure that some code (for example, cleanup code) is executed regardless of whether an exception is raised or not. This code is then put in the finally clause. Note that you cannot have both except clauses and a finally clause in the same try statement—but you can put one inside the other. I tried this code: def someFunction(): a = None try: a = 1 / 0 except ZeroDivisionError, e: print 'Yesss' print e finally: print 'Cleanup' del a if __name__ == '__main__': someFunction() ...and the output is Yesss integer division or modulo by zero Cleanup Here, I have used except and finally in the same try segment, haven't I? And the code works fine as expected. I can't quite get what the book says! Someone please clarify. Thanks. A: I believe the book actually gives the example itself, hence I don't know what he meant by it exactly. As the previous answer noted, this was changed in python 2.5 so that try: try: print 'something' except: print 'some weird error' finally: print 'finally something Is equivalent to try: print 'something' except: print 'some weird error' finally: print 'finally' A: This has been fixed since python 2.5, and is clearly noted in the documentation In other words, your book is incorrect / out of date A: That book might be wrong, I'm afraid, as the Python documentation uses all three. Maybe it's time to get a new book? A: Until python 2.4 it was not allowed to combine finally with except or else statement. But since python 2.5, like other object oriented programming language it support the combining except blocks and a finally block. Refer the latest python documentation
{ "language": "en", "url": "https://stackoverflow.com/questions/7524728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to use the Amazon Webservices in my iphone application? iam developing one applciation.In that i want to use the Amazon webservices for storing the data.I dont know anything about how to use the amazon webservices in iphone application.SO please tell me how to integrate both of these. A: You would have to read the APIs yourself. You may use AWS SDK for iOS The AWS SDK for iOS provides a library, code samples, and documentation for developers to build connected applications for iPad, iPhone, or iPod touch devices using Amazon Web Services.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: "The result set is closed" error on nested execute query I want to write a query that should print values for xml tags from database in java. <employee emp:empid=" " emp:empname="" /><location loc:locname=" "/> The code below gives the error "The result set is closed". How can this be fixed? connection = dataSource.getConnection(); ResultSet rs; connection.setAutoCommit(false); System.out.println("Connected to server OELDBSQL!!!"); Statement stmt = connection.createStatement(); String querystring = "select empid,empname from empt"; rs = stmt.executeQuery(querystring); Element child1 = doc.createElement("employee"); try { while (rs.next()) { child1.setAttributeNS(emp, "emp:empid", rs.getString(1)); child1.setAttributeNS(emp, "emp:empname", rs.getString(2)); } String querystring1 = "select locname from Locate"; ResultSet rs1; rs1 = stmt.executeQuery(querystring1); while (rs1.next()) { Element element = doc.createElement("location"); child1.appendChild(element); element.setAttributeNS(loc, "loc:locaname", rs.getString(1)); } } catch (Exception e) { System.out.println("Exception in connecting to DB" + e.getMessage()); System.err.println(e.getMessage()); } } catch (Exception e) { System.out .println("Exception in connecting to DB" + e.getMessage()); System.err.println(e.getMessage()); } A: After you have opened rs1 using the same statement, IMHO this line of code element.setAttributeNS(loc,"loc:locaname",rs.getString(1));} will throw you the exception, since it is working on the older result set (rs) Javadocs of Statement class states : /** * <P>The object used for executing a static SQL statement * and returning the results it produces. * <P> * By default, only one <code>ResultSet</code> object per <code>Statement</code> * object can be open at the same time. Therefore, if the reading of one * <code>ResultSet</code> object is interleaved * with the reading of another, each must have been generated by * different <code>Statement</code> objects. All execution methods in the * <code>Statement</code> interface implicitly close a statment's current * <code>ResultSet</code> object if an open one exists. * * @see Connection#createStatement * @see ResultSet */ A: In other words, I believe what Scorpion is saying is that you need a new statement for rs1. Try adding a new statement like this: connection = dataSource.getConnection(); ResultSet rs; connection.setAutoCommit(false); System.out.println("Connected to server OELDBSQL!!!"); Statement stmt = connection.createStatement(); String querystring = "select empid,empname from empt"; rs = stmt.executeQuery(querystring); Element child1 = doc.createElement("employee"); try { while (rs.next()) { child1.setAttributeNS(emp, "emp:empid", rs.getString(1)); child1.setAttributeNS(emp, "emp:empname", rs.getString(2)); } String querystring1 = "select locname from Locate"; Statement stmt1 = connection.createStatement(); ResultSet rs1; rs1 = stmt1.executeQuery(querystring1); while (rs1.next()) { Element element = doc.createElement("location"); child1.appendChild(element); element.setAttributeNS(loc, "loc:locaname", rs.getString(1)); } } catch (Exception e) { System.out.println("Exception in connecting to DB" + e.getMessage()); System.err.println(e.getMessage()); } } catch (Exception e) { System.out .println("Exception in connecting to DB" + e.getMessage()); System.err.println(e.getMessage()); } Also I noticed you aren't closing your resultsets/statements/connection. I would strongly recommend that you close them (in reverse order of creation).
{ "language": "en", "url": "https://stackoverflow.com/questions/7524735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: popViewController when textFieldShouldReturn is called? I've got a simple UIViewController with a UINavigationController. All that the view controller contains is a single UITextField. This view has two purposes: * *Create a new item. In this case, there are "Cancel" and "Save" buttons in the UINavigationController. *Edit the name of an existing item. In this case, there's just the "Back" button in the top-left corner. What I'd like is for the Return key on the iPhone keyboard to dismiss the UITextField. Here's my textFieldShouldReturn code: -(BOOL)textFieldShouldReturn:(UITextField *)textField { if(self.navigationItem.rightBarButtonItem) { //If we're creating a new item (there'd be a Save button in the top right) [self saveItem]; //This method just saves the Core Data for this item. [self.delegate addItemViewController:self didAddItem:item]; //This works fine; this method just tells the delegate to dismiss this view controller. }else { //If there's no button in the top-right corner, then we're editing an existing fridge. [self saveItem]; //This method just saves the Core Data for this item. [self.navigationController popViewControllerAnimated:YES]; //This is what doesn't work. } [textField resignFirstResponder]; return YES; } A: Well, I suggest you to go with UIButtons as the operation is being depended and you want to manage it at your end. btnSave = [UIButton buttonWithType:UIButtonTypeCustom]; btnSave.frame = CGRectMake(250, 6, 61, 30); [btnSave setImage:[UIImage imageNamed:@"btn-save.png"] forState:UIControlStateNormal]; btnSave.backgroundColor = [UIColor clearColor]; [btnSave addTarget:self action:@selector(btnSave_clicked:) forControlEvents:UIControlEventTouchUpInside]; [self.navigationController.navigationBar addSubview:btnSave]; - (IBAction)btnSave_clicked:(id)sender { //If we're creating a new item (there'd be a Save button in the top right) [self saveItem]; //This method just saves the Core Data for this item. [self.delegate addItemViewController:self didAddItem:item]; //This works fine; this method just tells the delegate to dismiss this view controller. }
{ "language": "en", "url": "https://stackoverflow.com/questions/7524739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I execute commands on a remote computer? I have a machine that I am able to connect using the Remote Desktop Connection application and it is on a different domain. This machine has a SQL Server that can ONLY be accessed when I attempt to access it after logging into this machine. Is it possible (either via C# or Powershell or some other mechanism) to initiate something like an ssh connection to this machine, execute the sqlcmd command and copy back the data? A: Try psexec It allows you to run a command prompt on a remote machine A: Your question is quite open - PowerShell V2 does allow you to connect remotely (some config is required and Ravi's written a great guide here -http://www.ravichaganti.com/blog/?cat=240) This will give you an overview on the command to configure PS Remoting. help Enable-PSRemoting Depending on your setup you may just need to run this. However your question sound like something is not quite right (or right if it's by design but why?) with your SQL set up. This machine has a SQL Server that can ONLY be accessed when I attempt to access it after logging into this machine. Is there a reason you can't initiate a SQL connection directly to the server?
{ "language": "en", "url": "https://stackoverflow.com/questions/7524740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to split the time i need to split the time from datetime format using the json parsing . A: String[] startDateAndTime = e.getString("startTime").split(" "); String startDate = startDateAndTime[0]; String startTime = startDateAndTime[1]; try this to get your start date and time. A: In the current scnario, the date and time are seperated by a seperated by a space. You can split this string using space delimater. A: String response= " {"events":{"event":[{"title":"Audi urban future","startTime":"2011-09-16 00:30:00","endTime":"2011-09-22 00:35:00","description":"test","image":"http://audi.smart-media.no/wp-content/uploads/2011/09/20110919130749-medium.jpg","latitude":45.73154,"longitude":4.8592365}]}} "; String startTime=response.substring(response.indexOf("startTime"); String finalTime=startTime.substring(startTime.indexOf(" "),startTime.indexOf(",")-1);
{ "language": "en", "url": "https://stackoverflow.com/questions/7524745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Placing image which is in WebContent folder in H2 tag in HTML I am creating tabbed sections with tab heading as H2 as below: <div class="mainTab"> <div class="myTab"> <h2>Tab1</h2> Tab1 content here </div> <div class="mtTab"> <h2>Tab2</h2> Tab2 content here </div> <div> I want to place a image before the tab heading. Like email image before Email tab heading. This could be achieved by something like: .h2one { font-size: 36px; font-weight: bold; background: url ('http://images.findicons.com/files/icons/1676/primo/128/email_open.png') center left no-repeat; padding-left: 120px; } .h2two { font-size: 36px; font-weight: bold; background: url('http://images.findicons.com/files/icons/1676/primo/128/email_close.png') center left no-repeat; padding-left: 120px; } What if the images are in webcontent folder of my server. In that case how would the url look like. Will <=%request.getContextPath> work here ???? A: @nikunj; you can use background-image in your h2 tag like this h2{ backgrond:url(image.jpg) no-repeat 0 3px; padding-left:10px; } in above example i define image background position left:0 & top:3px but you can adjust your image according to your requirements & i also give padding-left so, text shift 10px and you can see the image. you can also use text-indent instead of padding. if you want separate image for different tabs then give different class for your background images like this: http://jsfiddle.net/sandeep/NqXhB/4/ A: you need to use the background image property of css.. here is a link that gets you started: http://w3.org/TR/CSS2/colors.html#background and specifically to your question: <h2 class="image">My photo album</h2> and your style sheet is as follows: .image{ width: 300px; height: 75px; background-image: url(header.gif); background-repeat: no-repeat; } By W3 standards: Partial URLs are interpreted relative to the source of the style sheet, not relative to the document thus if your css is in content folder and you need to go to images folder.. you go something like this: url("../images/header.png") A: you put image like this <h2><img src='image/email.jpg' />Email</h2>
{ "language": "en", "url": "https://stackoverflow.com/questions/7524748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In need to display different colors in BAR - chat by using silverlight? In silverlight generally we can create a chat but i need create a BAR-chat based on the below requirement. Example: students marks 50,70,60,90.....like that having .for me based on marks i need to create different colors in the bar chat.below >50 means red color ,>70 means amber color ,>90 means green color... I need different colors to display in the bar chat based on the marks... A: Using IValueConverter is an option for you. <Grid x:Name="LayoutRoot" Background="Gray"> <Grid.Resources> <local:NumberToBrushConverter x:Key="NumberToBrushConverter" /> </Grid.Resources> <ListBox x:Name="List1"> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="Padding" Value="0" /> </Style> </ListBox.ItemContainerStyle> <ListBox.ItemTemplate> <DataTemplate> <Grid Background="{Binding Converter={StaticResource NumberToBrushConverter}}"> <TextBlock Text="{Binding}" /> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> And code behind: int[] numbers = new int[] { 10, 20, 30 }; List1.ItemsSource = numbers; And the ValueConverter class: public class NumberToBrushConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value is int) { switch ((int)value) { case 10: return new SolidColorBrush(Colors.Red); case 20: return new SolidColorBrush(Colors.Green); case 30: return new SolidColorBrush(Colors.Blue); } } return Colors.Transparent; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return null; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7524757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Photoshop like Grid/Guidelines with JQuery, Html 5 I'm looking for Photoshop like grid & Guidelines with JQuery. Is there any plugin for this ? Or is there any way to create such dragable/movable guides over Html 5 page. UPDATE / ANSWER Here is working Fiddle [ Thanks to Xenethyl ] A: As far as I'm aware, there aren't any plugins available for something like this. Creating said functionality should be pretty straight-forward, though. jQuery UI has a draggable property that you can assign, so I would approach this by just creating divs that have dimensions equal to either 100% width, 1px height or 1px width, 100% height. You can have your ruler (or some other tray to pull the guides out of) on the edges of your work area, and when the user clicks in the hot spot area they end up grabbing a hidden guideline. If they drag the guideline back to the tray area, the guide is hidden and/or destroyed. Since you can only create one guideline at a time (following the Photoshop approach), I'd suggest pre-creating both a vertical and a horizontal guideline and hiding them under your ruler or whatever hot spot you're using for guideline creation. That way you can propagate the mousedown event to the hidden guide relatively easily and you don't have to worry about transferring the event to a DOM element that has not yet been created (ie. I would avoid creating guides as needed; always have one ready to go). I would probably handle the hiding of the guidelines using z-indexing, but you could also play around with opacity and background color options if either would be easier to implement given your application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Figure out if hours spanned is greater than 24 I don't know if am am loosing my mind or if this is even possible. By the way, I am not using any standard libraries so this is not language dependent, hence why it's here and not on stackoverflow. I have 2 time periods that are being passed to me in a int format. 1st period- Start Time: End Time: 2nd period- Start Time: End Time: The Int's are minutes since midnight, so 7am would be 420 minutes. So an example of a function I am trying to write is: bool SpanMoreThan24Hours(int firstStartTime, int firstEndTime, int secondStartTime, int secondEndTime) { .... } I am not even sure this can be done. P.S. Spanning midnight is fine, but it doesn't have to. Periods can't overlap. So it could look like this: 420, 1140, 1260, 419 7am, 7pm, 9pm, 6:59am - Valid This would be valid since it doesn't span over 24 hours. 420, 1140, 1260, 421 7am, 7pm, 9pm, 7:01am - Not valid 420, 60, 120, 419 7am, 1am,2am, 6:59am - Valid I have to make sure from 1st period start time till 2nd period end time is not over 24 hours. A: If a period can start on monday and end on wednesday, there is no solution to the problem; otherwise, here is some C# to you: int MinutesBetweenTwoTimes(int time1, int time2) { return time1 < time2 ? time2 - time1 : (1440-time1) + time2; } bool SpanMoreThan24Hours(int firstStartTime, int firstEndTime, int secondStartTime, int secondEndTime) { int totalSpannedTime = MinutesBetweenTwoTimes(firstStartTime, firstEndTime) + MinutesBetweenTwoTimes(firstEndTime, secondStartTime) + MinutesBetweenTwoTimes(secondStartTime, secondEndTime); return totalSpannedTime > 1440; } A: I may be misunderstanding, but couldn't you just check whether firstStartTime <= secondEndTime? A: If I read it right, I think this works, no? bool SpanMoreThan24Hours(int firstStartTime, int firstEndTime, int secondStartTime, int secondEndTime) { // Logically, you'll only have a span > 24 hours if one of them spans midnight if ( firstStartTime > firstEndTime || secondStartTime > secondEndTime ) { // Check for period overlap: // If the second period doesn't span midnight, this means the first does. // So check for overlap: if ( secondStartTime <= secondEndTime && firstEndTime > secondStartTime ) throw new Exception ("Periods cannot overlap"); // If *both* periods span midnight, this means they logically overlap. else if ( firstStartTime > firstEndTime && secondStartTime > secondEndTime ) throw new Exception ("Periods cannot overlap"); // If we get to here, we know that the periods don't overlap, yet they span midnight // The answer now is simply if the end of the second span is after the first begins return secondEndTime > firstStartTime; } // Neither period span midnight, so overlap check is a snap: if ( firstEndTime > secondStartTime ) throw new Exception ("Periods cannot overlap"); // No errors (no overlaps) and no midnight span means // the only logical result is that this is not > 24 hours return false; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7524763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to resolve Haskell type errors I'm trying to learn Haskell, and I'm writing the unzip function (yes I know it's built in, this is practice) but I'm having issues with my recursion line. I have: -- unzip turns a list of two element tuples into two lists unzip' [] = ([],[]) unzip' [(x,y):ls] = let (a, b) = unzip' ls in ([x] ++ a, [y] ++ b) But I get the error: Couldn't match expected type `(t, t1)' against inferred type `[(t, t1)]' Expected type: [(t, t1)] -> (t2, t3) Inferred type: [[(t, t1)]] -> ([a], [a1]) In the expression: unzip' ls In a pattern binding: (a, b) = unzip' ls I don't understand how to unpack the results of the recursive call. Can anyone explain how to unpack the two lists from the returned tuple? A: i don't know if this solves it but it looks to me that unzip' [(x,y):ls] = should just be: unzip' ((x,y):ls) =
{ "language": "en", "url": "https://stackoverflow.com/questions/7524767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery - option buttons reset cancelled I have a single checkbox that indicates that a user would like dinner. Under this checkbox are several radio buttons from which the user can select his/her dinner option. I am looking for two things to happen... 1) Whenever the user "checks" that they would like dinner I have a default dinner choice option selected. When the user "un-checks" the dinner option I want all the dinner choices deselected. All this is working fine until I try and add an additional jQuery option. 2) If the user selects a dinner option I would like the checkbox that indicates that the user wants dinner to be checked. This last option seems to negate the first. I have created a jsfiddle.net example located here ... http://jsfiddle.net/ScEw2/1/ I have also pasted the code here for example ... HTML <p><input type="checkbox" id="IsHavingDinner" name="Dinner" /> Do you want dinner?</p> <hr /> <input type="radio" id="DinnerChoiceChicken" name="DinnerChoice" value="Chicken"> Chicken<br/> <input type="radio" id="DinnerChoiceFish" name="DinnerChoice" value="Fish"> Fish<br/> <input type="radio" id="DinnerChoiceSteak" name="DinnerChoice" value="Steak"> Steak<br/> <input type="radio" id="DinnerChoiceVegan" name="DinnerChoice" value="Vegan"> Vegan<br/> jQuery code // Select default dinner option otherwise deselect all options $('#IsHavingDinner').click(function(event) { if ($('#IsHavingDinner').attr('checked')) { // Select Dinner Choice Chicken by default $('#DinnerChoiceChicken').attr('checked', 'checked'); } else { // Deselect all Dinner Choices $('input[name="DinnerChoice"]').attr('checked', false); } }) // If a dinner choice is selected, make sure the checkbox // indicating they want dinner is selected $('[name="DinnerChoice"]').click(function(event) { $('#IsHavingDinner').attr('checked', 'checked'); }) I cannot determine why the dinner options are not deselected if the user deselect dinner. Is one event cancelling the other? Any thoughts? A: Use JQuery's .change() event instead of click(). click() is executed before the checkbox changes. $('#IsHavingDinner').change(function(event) { .. Also use prop() instead of attr() in JQuery 1.6+. A: // Select default dinner option otherwise deselect all options // Listen for a change event on the having dinner checkbox $('#IsHavingDinner').change(function(){ if($(this).is(':checked')){ // if checked $('#DinnerChoiceChicken').prop('checked', true); // check a default dinner choice } else { $('input[name="DinnerChoice"]').prop('checked', false); // otherwise, uncheck all } }); // If a dinner choice is selected, make sure the checkbox // indicating they want dinner is selected $('input[name="DinnerChoice"]').change(function(){ if($(this).is(':checked')){ // if checked $('#IsHavingDinner').prop('checked', true); // check having dinner } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7524770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Show Date in a Textbox in android I have a problem that, I have two Textboxes which contains dates, from calendar Dialog, the Calendar dialog shows default current Date for both TExtboxes, But I want, If a user selects a date from first TextBox(startdate) then the next Calendar Dialog for second TextBox(End Date) should not be lesser means it will always show one value greater as a default value in second Caledar Dialog. I mean to say that the End Date will always be equal or greater than start Date but never be smaller. I don't know how to achieve this? I wish a kind favour of you regarding this subject. Thanks in advance. A: you can compare the date by using public int compareTo (Date date) check http://developer.android.com/reference/java/util/Date.html#compareTo%28java.util.Date%29
{ "language": "en", "url": "https://stackoverflow.com/questions/7524772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL: INSERT INTO table SHOW CREATE VIEW I need to write the column 'Create View' of SHOW CREATE VIEW in to a temporary table. Note that i cannot use the INFORMATION_SCHEMA because the create view statement there is a little bit different to the statement i get from 'Create View'. Specifically the statement in INFORMATION_SCHEMA has the database schema name in the Create View statement and i want to dump this without the schema name. (I cannot use RegEx to remove the statement names because i cannot know if the schema name is set automatically or by the user how creates the statement) Thanks for your ideas! A: If the database specified in your connection by default differs from the database containing the view, SHOW CREATE VIEW will return the same result as INFORMATION_SCHEMA. So you should not count on it. Try to unparse the text in your application, but it can be difficult to do.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unexpected Delay in Controller I have a method that gets the IBOutlet of another class by initializing an instance to the other class and then runs code that uses the references to the IBOutlets to set a memory address in another app. The code runs fine but is periodically updated by a timer that I set up to refresh every 5 seconds. The problem is that every 5 seconds the memory address is periodically changed to the wrong value and then back to the right value. Here is my essential code: #define OFF 0 #define ON 1 - (void)onOff:(id)sender { if ([[appDelegate buttonOutletName] state] == ON) { [helper setIntForAddress:0xFFFFFF value:1]; } if ([[appDelegate buttonOutletName] state] == OFF) { [helper setIntForAddress:0xFFFFFF value:0]; } } The problem is that whenever I call this code from anything other than a button press (ex. [self onOff:self]; ) It briefly sets the value to 0 and then back to 1. My code worked fine when implemented inside the application controller; however, now it works but with this error. If anyone could help me that would be greatly appreciated. Thanks. A: I imagine the method is somehow being called twice. Are you sure you're only calling it once? Check with the Instruments app to see if it is indeed being called twice. A: I feel that setIntForAddress:value: method changes the value of [appDelegate buttonOutletName] state]. If so, just convert the two if statements into a single if-else block. if ([[appDelegate buttonOutletName] state] == ON) { [helper setIntForAddress:0xFFFFFF value:1]; } else if ([[appDelegate buttonOutletName] state] == OFF) { [helper setIntForAddress:0xFFFFFF value:0]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7524776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: selenium: checkbox not getting enabled? I have a webpage where I have a text field/box and two checkboxes. The checkboxes are enabled only after something is typed inside the textbox. When i do this manually everything is fine. But when i try it with selenium, the checkbox does not get enabled, even after writing some text in the textbox. Could someone please help me with this problem? Apache License, Version 2.0 I am trying on firefox code to type test: I am using python: class FieldElement(Text): def __init__(self): self.locator = "css=input#fieldname" class main_class(mainpage): username = FieldElement() self.username = "respective_text" A: if I had to guess you are probably using the wrong API to set the test and that is why your javascript event is not being fired.. Dont use method like SetText or its equivalent.. use the method TypeKeys or something similar. take a look at this: http://release.seleniumhq.org/selenium-remote-control/0.9.2/doc/dotnet/Selenium.DefaultSelenium.TypeKeys.html A: I had a similar situation where send_keys was not working correctly, but I found a work-around by using javascript to fix the html by-hand. Something like: self.driver.execute("document.getElementById('myElement').checked = true;")
{ "language": "en", "url": "https://stackoverflow.com/questions/7524777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IExtractImage:Extract Method "Object reference not set to an instance of an object." error I want to develope image library for office document which will create thumbnail image of office documents. I got code for http://msdn.microsoft.com/en-us/library/aa289172.aspx The code i got that is in vb.net i converted in to c#. private bool _getThumbNail(string file, IntPtr pidl, IShellFolder item) { IntPtr hBmp = IntPtr.Zero; IExtractImage extractImage = null; try { string pidlPath = PathFromPidl(pidl); if (Path.GetFileName(pidlPath).ToUpper().Equals(Path.GetFileName(file).ToUpper())) { IUnknown iunk = null; int prgf = 0; Guid iidExtractImage = new Guid("BB2E617C-0920-11d1-9A0B-00C04FC2D6C1"); item.GetUIObjectOf(IntPtr.Zero, 1, ref pidl, ref iidExtractImage, ref prgf, ref iunk); extractImage = (IExtractImage)iunk; if (extractImage != null) { Console.WriteLine("Got an IExtractImage object!"); SIZE sz = new SIZE(); sz.cx = DesiredSize.Width + 1; sz.cy = DesiredSize.Height + 1; StringBuilder location = new StringBuilder(260, 260); int priority = 0; int requestedColourDepth = 32; EIEIFLAG flags = EIEIFLAG.IEIFLAG_ASPECT | EIEIFLAG.IEIFLAG_SCREEN | EIEIFLAG.IEIFLAG_ASYNC; int uFlags = (int)flags; try { extractImage.GetLocation(location, location.Capacity, ref priority, ref sz, requestedColourDepth, ref uFlags); //if(hBmp != IntPtr.Zero) extractImage.Extract(ref hBmp); } catch (System.Runtime.InteropServices.COMException ex) { Console.Write(ex.Message); } if (hBmp != IntPtr.Zero) { _thumbNail = Bitmap.FromHbitmap(hBmp); } Marshal.ReleaseComObject(extractImage); extractImage = null; } return true; } else { return false; } } catch (Exception ex) { if (hBmp != IntPtr.Zero) { UnmanagedMethods.DeleteObject(hBmp); } if (extractImage != null) { Marshal.ReleaseComObject(extractImage); } throw ex; } } Here is the function in which i am facing problem at extractImage.Extract(ref hBmp); Can any one please help me i am using VS2010 and OS Vista 32 bit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to check a textbox value inside a table is null or not? I have a page where i have a table it consists of a 3 textboxes inside each row, also i have a add row button at the bottom of the page, by clicking this should add a new row to the table, but it should trigger this action only if all the inputs in the table are not null. Anyway i have done a little bit but its not working fine for me. Can anybody take a look on my code and help me to sort out what is wrong with that? What i have done in JQuery is given below // Add functionality Scripts $('#teacherAdd').live('click', function(event) { if(IsValidTableContent()){ // my code to add new row return false; }else{ event.preventDefault(); } }); function IsValidTableContent(){ var isvalid = false; $('#adminList tbody tr td input:text').each(function(){ if($(this).val() == ''){ return isvalid; }else{ isvalid = true; return isvalid; } }); return isvalid; } also similarly Can you say how to iterate through a select box inside the table to check whether the first option is selected or not? A: Something like this should work (provided your selector is correct): function IsValidTableContent(){ var isvalid = true; $('#adminList tbody tr td input:text').each(function(){ if ($(this).val() === '') { isvalid = false; return false; // breaks out of each loop } }); return isvalid; } Alternatively: function IsValidTableContent(){ return $('#adminList tbody tr td input:text').filter(function() { return $(this).val() === '';}).length === 0; } A: first thing I noticed is that you are setting isvalid to true if one is and then returning true for all the rest because you are not resetting it, just return true; or return false; and skip the variable setting. EDIT Ok, I see what you are trying to do, variable is backwards. you want to start out with true and if any are false set it to false and then it will return false. Currently if any are true it returns true even if the others are false. A: Try removing the last return statement of your function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to join three tables from a database using just one common field amongst them all.(Mysql) These are three tables 1. table `p_transactions` has following fields (`txn_id`, `txn_uid`, `txn_bid_no`, `txn_date`, `txn_desc`, `txn_amt`, `txn_fee`, `txn_mode`, `txn_status`, `txn_mdate`) 2 . table `p_game_results` has following fields. (`id`, `game_id`, `game_combo`, `game_combo_hr`, `cdate`, `mdate`) 3. Table `p_game_room_results` has following fields (`id`, `game_id`, `room_id`, `txn`, `round`, `result`, `score`, `cdate`, `mdate`) I would like to join them using their txn id as a common field. here's something I tried. but not sure, I'm sure its wrong . $sql = "SELECT * FROM " . $prefix . "_user_game_results".$prefix."_game_room_results".$prefix."_transactions WHERE". $prefix . "_user_game_result.uid"='$prefix."_game_room_results.id"'. and .$prefix."_transactions.txn_uid"='$prefix."_game_room_results.uid"'""; $result = $this->sql_fetchrowset($this->sql_query($sql)); Thanks. A: This should do it: select * from p_transactions pt inner join p_game_room_results pgrr on pgrr.txn=pt.txn_id inner join p_game_results pgr on pgr.game_id=pgrr.game_id Joined all tables by their common fields. p_game_room_results and p_game_results were joined by game id since that seems to be the common field. A: select * from p_transactions as p_t INNER JOIN p_game_results as p_g_r ON p_t.txn_id = p_g_r.id INNER JOIN p_game_room_results as p_g_r_r ON p_g_r_r.game_id = p_g_r.game_id; The following alias are used in INNER JOIN p_transactions as p_t p_game_results as p_g_r p_game_room_results as p_g_r_r I suggest you to go through these useful SQL Joins Tutorial http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html http://en.wikipedia.org/wiki/Join_%28SQL%29
{ "language": "en", "url": "https://stackoverflow.com/questions/7524785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Patterns for accessing subject hierarchy in RSpec When using RSpec to test deeply nested data structures, I find the need to define subjects in nested contexts in terms of the subjects in the containing contexts. I have looked extensively but not found any examples on how to do with without defining many variables. It complicates the specs and limits the possibility of spec reuse. I am curious whether there is a way to do this in RSpec as it stands and, if not, what would be a good way to approach the problem. Right now, my code looks something like: context 'with a result which is a Hash' do before do @result = get_result() end subject { @result } it { should be_a Hash } context 'with an Array' do before do @array_elem = @result[special_key] end subject { @array_elem } it { should be_an Array } context 'that contains a Hash' do before do @nested_hash = ... end subject { @nested_hash } ... end end end Instead, I'd rather write something along the lines of: context 'with a result which is a Hash' do subject { get_result } it { should be_a Hash } context 'with an Array' do subject { parent_subject[special_key] } it { should be_an Array } context 'that contains a Hash' do subject { do_something_with(parent_subject) } ... end end end What's a way to extend RSpec with this type of automatic subject hierarchy management? A: I found this question while trying to do something similar. My solution can be found at https://gist.github.com/asmand/d1ccbcd01789353c01c3 What it does is to test the flex work time calculation of a week over Christmas, i.e. of the given week, only Monday and Friday are working days, the rest are holidays. The solution is based around named subjects. I.e. describe WeeklyFlexCalculator, "during Christmas week" do subject(:calculation) { WeeklyFlexCalculator.new(params).calculate } context "with no work performed" do it { should have(1).item } context "the week calculated" do subject(:workweek) {calculation[0]} its([:weekTarget]) { should eq 15.0 } its([:weekEffort]) { should eq 0.0 } context "the work efforts" do subject(:efforts) {workweek[:efforts]} it { should have(2).items } context "the first work effort" do subject(:effort) {efforts[0]} its([:target]) {should eq 7.5} its([:diff]) {should eq -7.5} its([:effort]) {should eq 0.0} end end end end end A lot of code is left out for brevity, but the complete example can be found in the linked gist. A: I'm guessing that this functionality isn't built into Rspec because it would encourage more complicated specs and code. According to OOP best practices, classes should have a single responsibility. As a result, your specs should be concise and easy to understand. For the sake of conciseness and readability, a spec should only have one type of subject. There can be variations on this subject, but ultimately, they should all be based on the class/object you are describing. If I were you, I would take a step back and really ask myself what I'm really trying to do. It seems like a code smell if you are finding yourself having multiple subjects of different class in the same spec. It's either a problem with how you're using Rspec, or your class is doing too much. Another thing to note is that you should be testing the behavior of your objects, and not details of what they are doing internally. Who cares if something is an array or a hash if it behaves how it should? Take aways... Should your child subject really be a separate class with its own spec? Are you over testing implementation and not behavior? A: In this type of hierarchic structure, I would actually drop the use of subject and make the subject explicit. While this could result in a bit more typing (if you have a lot of tests), it is also clearer. The nested subject-statements could also be confusing what is actually being tested if you are three levels down. context 'with a result which is a Hash' do before do @result = get_result() end it { @result.should be_a Hash } context 'special_key' do before do @array_elem = @result[special_key] end it { @array_elem.should be_an Array } context 'that contains a Hash' do before do @nested_hash = ... end it { @nested_hash.should be_a Hash } ... end end end But this could be a matter of taste. Hope this helps. A: I was looking for the same kind of thing, and wanted to use subject so that I could use its, so I implemented it like this: describe "#results" do let(:results) { Class.results } context "at the top level" do subject { results } it { should be_a Hash } its(['featuredDate']) { should == expected_date } its(['childItems']) { should be_a Array } end context "the first child item" do subject { results['childItems'][0] } it { should be_a Hash } its(['title']) { should == 'Title' } its(['body']) { should == 'Body' } end context "the programme info for the first child item" do subject { results['childItems'][0]['programme'] } it { should be_a Hash } its(['title']) { should == 'title' } its(['description']) { should == 'description' } end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7524786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Is it possible to smooth button corners in Delphi I need smooth corners for my button. Is it possible to get that for TSpeedButton? A: I used the TJvXPButton (built into Jedi JVCL) for that purpose. It has rounded corners, it's free, it looks great, and it's the same on all versions of windows, with themes on and with themes off. In apps where I don't need the whole JVCL, I have isolated it into only 5 files, which is easy to add to any project. If you wanted to add this to TSpeedButton you will run into the problem that TSpeedButton has been specifically designed to make your owner-draw job difficult. It is designed to draw Win 3.1 style "edges" when themes are off, and to use the XP/Vista/Win7 themes, when themes are turned on on the PC. You can owner-draw a Speed button, but a nice smooth round cornered button is more difficult than you might think, thus the suggestion of the Jedi JVCL XP Button control (TJvXPButton). A: well, since the TSpeedButton has its own focused border. it is really impossible. I suggest to use the rzBMPButton on RaizeComponent pack. There you can do whatever you do to the button. you just have to draw Bitmap Button with soft edge.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Refreshing a window from another thread while other operations are performed? I have been trying to keep the splash screen for my application from hanging while the application loads its initial data, however I have not yet been sucessful in finding a way to do this. Here is the code I have tried: SplashView splashScreen = new SplashView(); new Thread((ThreadStart)delegate { splashScreen.Dispatcher.Invoke((Action)delegate { while ((bool)splashScreen.Dispatcher.Invoke((Func<SplashView, bool>)delegate(SplashView sView) { return sView.IsEnabled; }, DispatcherPriority.Render, new object[] { splashScreen })) { splashScreen.Dispatcher.Invoke((Action<SplashView>)delegate(SplashView sView) { sView.UpdateLayout(); }, DispatcherPriority.Render, new object[] { splashScreen }); Thread.Sleep(10); } }, DispatcherPriority.Render, new object[] { }); }).Start(); Can someone please tell me how to accomplish this? Thanks, Alex. A: * *Load all your data (model / view models) on background thread (like BackgroundWorker). *Dispatcher.Invoke() will hang your UI thread as multiple invokes would block due to synchronous execution of code. Use Dispatcher.BeginInvoke() instead. It uses the dispatcher queue more effectively. *Use DispatcherPriority to your advantage. Any Splash UI notifications which are of lower importance could be displayed following higher priority ones. *Use Dispatcher.PushFrames() if you want to notify Splash for something on priority. *Split your data loading in multltiple background threads and use Wait / Pulse to notify others when the slower ones finish. Unrelated data can be loaded in different threads e.g. Finance related data and employee related data can be loaded using different threads.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Detect Shift key down using jna I have implemented keyBoardHook, but however cannot detect the character pressed while shift key is down. I have tried using the GetAsyncKeyState function of windows to detect when shift key is pressed. But this does not process shift+2 = @. it overrides the shift key and prints the keycode for 2. i can obtain every key but however Shift + 2 are detected both as separate keys (Even though [SHIFT+2] gives @ on my keyboard). IE: The program outputs both SHIFT, and 2, but not what they produce: @. Question: How can i detect the characters produced when shift key is down. Code i have written so far. public class Keyhook { private static volatile boolean quit; private static HHOOK hhk; private static LowLevelKeyboardProc keyboardHook; public static void main(String[] args) { final User32 lib = User32.INSTANCE; HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null); keyboardHook = new LowLevelKeyboardProc() { public LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT info) { if (nCode >= 0) { switch (wParam.intValue()) { case User32.WM_KEYUP: break; case User32.WM_KEYDOWN: if(lib.GetAsyncKeyState(160) == 1){ System.out.println(info.vkCode); } break; case User32.WM_SYSKEYUP: break; case User32.WM_SYSKEYDOWN: System.err.println("in callback, key=" + info.vkCode); if (info.vkCode == 81) { quit = true; } } } return lib.CallNextHookEx(hhk, nCode, wParam, info.getPointer()); } }; hhk = lib.SetWindowsHookEx(User32.WH_KEYBOARD_LL, keyboardHook, hMod, 0); System.out.println("Keyboard hook installed, type anywhere, 'q' to quit"); //noinspection ConstantConditions new Thread() { public void run() { while (!quit) { try { Thread.sleep(10); } catch (Exception e) { e.printStackTrace(); } } System.err.println("unhook and exit"); lib.UnhookWindowsHookEx(hhk); System.exit(0); } }.start(); // This bit never returns from GetMessage int result; MSG msg = new MSG(); while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) { if (result == -1) { System.err.println("error in get message"); break; } else { System.err.println("got message"); lib.TranslateMessage(msg); lib.DispatchMessage(msg); } } lib.UnhookWindowsHookEx(hhk); } } A: There's no easy way to predict the generated output (some key combinations don't produce any output). If Java generates a KeyTyped event, the generated string will be provided in the event, but I don't think there's any API (Java or native) that provides you with a keystroke to key string mapping. A: According to the LowLevelKeyboardProc documentation, the reason you cannot detect the shift key: Note When this callback function is called in response to a change in the state of a key, the callback function is called before the asynchronous state of the key is updated. Consequently, the asynchronous state of the key cannot be determined by calling GetAsyncKeyState from within the callback function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Swing components freezing until one component completes its job I have created a simple JAVA Swing program that has a JTextArea, three JTextFields and one JButton. What this application does is when the user clicks the button it updates the JTextArea with a text line, the text line inserted into the JTextArea is prepared in a for loop and number of repeat times is given in a JTextField. My problem is when I click the start JButton all the components of the application are freeze, I can't even close the window until the for loop completes it's job. How can I separate this JTextField updating work from other tasks in the form? A: You are probably doing the work on the Event Dispatch Thread (the same thread as the GUI rendering is done). Use SwingWorker it will do the work in another thread instead. Example Code below produces this screenshot: Example worker: static class MyWorker extends SwingWorker<String, String> { private final JTextArea area; MyWorker(JTextArea area) { this.area = area; } @Override public String doInBackground() { for (int i = 0; i < 100; i++) { try { Thread.sleep(10); } catch (InterruptedException e) {} publish("Processing... " + i); } return "Done"; } @Override protected void process(List<String> chunks) { for (String c : chunks) area.insert(c + "\n", 0); } @Override protected void done() { try { area.insert(get() + "\n", 0); } catch (Exception e) { e.printStackTrace(); } } } Example main: public static void main(String[] args) throws Exception { final JTextArea area = new JTextArea(); JFrame frame = new JFrame("Test"); frame.add(new JButton(new AbstractAction("Execute") { @Override public void actionPerformed(ActionEvent e) { new MyWorker(area).execute(); } }), BorderLayout.NORTH); frame.add(area, BorderLayout.CENTER); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 300); frame.setVisible(true); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7524800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to know the coverage for the django application ? I am having a simple django project that contains some applications.Everything works well.Now how do i check code coverage for my project.I have installed coverge-3.5 tool and just tried to know coverage by typing "coverage report" from terminal..It shows some result like NAME -----> (some file in my project) STMS -----> (some number) MISS -----> (some number) COVER -----> (some %) In my case,it will display some result that shows only some of the file names from my project.It didnt shows coverage for all files from my project.How do i make it to show all my file name ???? please suggest any better working coverage tool if you know ! A: I just got it working like this: coverage run --source=app1,app2 ./manage.py test --settings=path.to.test_settings app1,app2 I don't think that this is the intended way to do it since we don't use the ./manage.py test_coverage command at all, but I couldn't find any other way. A: first make sure you are using the latest coverage version. than you can do: assuming your django project lives under project_parent/project, from project_parent run: coverage html --include=project/*.* this will give you a coverage report of your project only (i.e. doesn't output 3rd party lib coverage) A: I manage to solve this issue with django_coverage and django_nose I added to INSTALLED_APPS 'django_coverage' and 'django_nose' with this on settings.py TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' # Tell nose to measure coverage on the 'foo' and 'bar' apps NOSE_ARGS = [ '--with-coverage', '--cover-package=schedule', ] to install it pip install django_coverage How do I use it? Install as a Django app Place the entire: django_coverage app in your third-party apps directory. Update your settings.INSTALLED_APPS to include django_coverage. Include test coverage specific settings in your own settings file. See settings.py for more detail. Once you've completed all the steps, you'll have a new custom command available to you via manage.py test_coverage. It works just like manage.py test. Use it as a test runner You don't have to install django_coverage as an app if you don't want to. You can simply use the test runner if you like. Update settings.TEST_RUNNER = 'django_coverage.coverage_runner.CoverageRunner' Include test coverage specific settings in your own settings file. See settings.py for more detail. Run manage.py test like you normally do.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Apple Script - to choose color displays a buttonless headless color wheel Color Picker I used the information on this post to create a Color Picker on my mac to replace the digital color meter app. http://www.macosxtips.co.uk/index_files/replace-digitalcolor-meter-in-lion.php But after I did that, I get a color picker alright, but the buttons on the top that lets me shift between color wheel, color slider, color palletes, image, hex etc dont appear. They appear only when I run the apple script from the apple script editor. When I save the apple script as an app and run it by double clicking it, I just a get simple color wheel with none of the buttons on the top. I use Mac OS Lion.. Thanks! EDIT: Adding a screenshot : A: I wanted colors as a hex value so I also looked to applescript for a solution. Check out this blog post for a complete example, and also a downloadable applescript application (with a nice icon) that you can customize to your needs. I have tested it with OS X Lion and it seems to work fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: TabStrip issue on postback I have a page and in the page I have a RadTabStrip, it has a MultiView with two indexes and two TabStrip indexes. The problem I am having is that when i update something in the second index, it returns back to the first index on postback. So I added a parameter in the url called &mode=Updated so on load if it cones wuth that string I make it stay in that page.. that works.. The problem now is that when I go to the first tab, anything that posts back there causes to read the same parameter and it comes back on the second tab now.. lol ... So I am not sure how to do this... Please help **THIS CODE IS OUTSIDE THE if(!Page.IsPostBack) if (Request.UrlReferrer != null) { if (Request.UrlReferrer.AbsoluteUri.Contains("myPage.aspx")) { MyMultiView.SelectedIndex = 1; MyTabStrip.SelectedIndex = 1; } else if (!String.IsNullOrEmpty(pageKey)) { switch (pageKey) { case "updated": LabelT.Text ="Updated Successful"; break; case "error": LabelT.Text ="There was an error"; break; default: LabelT.Text = string.Empty; break; } MyMultiView.SelectedIndex = 1; MyTabStrip.SelectedIndex = 1; pageKey = string.Empty; } else { MyMultiView.SelectedIndex = 0; MyTabStrip.SelectedIndex = 0; } } A: Be sure to only adjust you RadTabStrip if the page isn't posting back. If (!Page.IsPostBack){ //Adjust here }
{ "language": "en", "url": "https://stackoverflow.com/questions/7524808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redirect to new page on session expire, in Zend_Auth I'm using zend 1.11 framework with doctrine . I'm sending below ajax request to populate dropdown list & etc... But once session expired i'm redirecting to login page in every actions of controllers. So i'm getting whole html page as response if session got expired. How to do that in javascript (how can i find out whole html response or not) . I'm using Zend_Auth for session management. function loadzone(value) { var xmlhttp; if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("district_span").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","/main/zonechange?zc="+value,true); xmlhttp.send(); } A: Well to my understanding: A user is logged in and opens some form. You do AJAX-Checkups to see if user is still logged in. If user was idle for too long the session will expire. In that case you want to redirect the user? If is is like i think you can just give the user a bad callback. This can be done like this: $this->_response->setHttpResponseCode(401); //401 = unauthorized If you do so, you can just extend your JS Functionality to catch that code if (xmlhttp.readyState==4 && xmlhttp.status==401) { //do the redirect } Is this what you're asking for or did i misinterpret your question? :) Additional Information regarding response codes can be found here: http://de.wikipedia.org/wiki/HTTP-Statuscode
{ "language": "en", "url": "https://stackoverflow.com/questions/7524815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Properties button disabled when accessing network properties through IContextMenu So, I have a c++ plugin dll for an app that supports plugins. The dll enumerates the Shell Folder for networks and displays your networks. It then allows you to invoke action on default Context Menu actions for those networks. Now, if you invoke the action for say "Local Area Connection", it is the same as right-clicking on it and going to properties. However, the difference when I do it manually vs launching it through the app, is that the properties button for IPv4 and IPv6 properties is disabled. Which makes me wonder if it has something to do with permissions, but I have UAC set to lowest and I start the app with Admin privileges. I also added a manifest to the dll with admin permissions. Neither of these changes made any difference. The action on the context menu is being called using InvokeCommand() of IContextMenu. Any ideas?
{ "language": "en", "url": "https://stackoverflow.com/questions/7524816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android NDK make file i am trying to execute a sample in ndk,but getting the following error. Android NDK: There is no Android.mk under mp3solutions/jni Android NDK: If this is intentional please define APP_BUILD_SCRIPT to point Android NDK: to a valid NDK build script. android-ndk-r5b/build/core/add-application.mk:1 26: *** Android NDK: Aborting... . Stop. so please guide me how to resolve this one A: are you having Android.mk in your JNI folder?, see NDK-build the files which are all listed in Android.mk, so just be sure to have Android.mk file A: Do you have a file application.mk.If you do have than please delete that file.Sometimes the path specified in the application.mk file causes this error. A: I got the same issue and this is because mistaken I named file Andorid.mk instead Android.mk. This work for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Selenium IDE - Not capturing button link In Selenium IDE, the application has got image as button. The click event for that is not capturing. Is there any alternative Selenium Commands available for that or otherwise, is there any JavaScript user extensions can be added? Please help. Thanks A: Yes.. the image will act as a button.. Found a solution for that!! Simply added a JavaScript code which supports clickAt() commands. A: To detect button as image you can use one of the below solution xpath=//img[@src='/images/logo_home.png'] xpath=//img[@alt='Home'] //img[@src='/images/logo_home.png']
{ "language": "en", "url": "https://stackoverflow.com/questions/7524829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sharepoint LookUp field on Choice field? How to create a lookup field for the Choice field..For eg: In a list i have Choice field and i have to create an lookup column in other list pointing to this choice field ..When i select this list this column is not appearing in the dropdown...Please let me know if there is any Limitation for that A: the programmatical Solution is at risk to run into an endless recursion: The ItemAdded Event and UpdatedEvents are asynchrone. This means, that the command: this.EventFireingEnabled = false is not threadsafe. After systemUpdate you set EventFireingEnabled to true. But because the ItemUpdated is asynchronus, you cannot guarantee, that the ItemUpdated for your system.update has already been called at this time!. A: You can use calculated column is source list, that will display value of Choice column. Then you can add lookup column for this calculated field. It will work only for Choice column with single selection. For multiple selection you can use 3rd party components like that: http://www.sparqube.com/SharePoint-Lookup-Column A: It is not possible to create a lookup field for a choice (dropdown) field. There are two ways to resolve your problem: The programmatic approach and the workaround. The programmatic approach involves an creating event receiver to do the magic - pretty work intensive. But there is an explanation here: * *Sharepoint 2010 - How to use List Events to Set a Column's Value using Visual Studio 2010 (C#) You can also just create another list, containing your choice field values and use a calculated field as a source for your lookup column. Check out the following explanation: * *Using a lookup field on a choice field workaround A: It works out of the box for me... but the lookup option is is only available if you go to "List Settings" and click on "Create Column" here is how I configured my column on sharepoint online (in 2019) and it works perfectly... this is copy and pasted from the list settings screen under this column... Column name: Equipment List The type of information in this column is: Lookup Get information from: Equipment Master List In this column: "Equipment Name" (dropdown selector of all the column names on the other list) Allow multiple values (to be selected) [TICKED] there are some notes lower down too.. Relationship A lookup column establishes a relationship between list items in this list and related items in the target list. Specify the relationship behavior enforced by this lookup column when a list item in the target list is deleted. When an item in the target list is deleted, cascade delete will delete all related items in this list. Restrict delete will prevent the deletion of an item in the target list if it has one or more related items in this list. Enforce relationship behavior [CHECKBOX] radio buttions: Restrict delete Cascade delete
{ "language": "en", "url": "https://stackoverflow.com/questions/7524833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Not able to write the testcases for inner class using EasyMock I am new to the EasyMock. I need to test my class using the EasyMock. but here the problem is my class has inner class and this inner class is instatiated in the outer class's method and calling the method of inner class by passing some parameters. I am not sure how to write the test case for this scenario. Please help me write the test case for this. Any help or suggetions are highly appreciated. public class ServiceClass implements ServiceInterface { public void updateUSer(USer) { //some logic over here. sendEmailNotice(subject, vTemplate); } private sendEmailNotice(subject, vTemplate) { MimeMessagePrepator eNotice = new PrepareEmailNotice(subject, vTemplate); MailSender.send( eNotice ); } public class PrepareEmailNotice implements MimeMessagePrepator { // some local variables. public PrepareEmailNotice(subject, vTemplate) { subject = subject; vTemplate = vTemplate; } public void prepare( MimeMessage message) { MimeMessageHealper helper = new MimeMessageHealper(message, true); // setting the mail properties like subject, to address, etc.. } } Thanks. A: First of all you need to think about what is the class responsibility. At should it be doing with who should it be speaking? Once you've clearly identified the dependencies you need to see how you can handle them in your code. You might need do to perform some refactoring in order to conform to the dependency inversion principle. For example here you have a dependency to the MailSender class but you won't be able to mock it as this dependency is "hard coded". There is a good video about that: http://www.youtube.com/watch?v=XcT4yYu_TTs
{ "language": "en", "url": "https://stackoverflow.com/questions/7524836", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Fixed point vs Floating point number I just can't understand fixed point and floating point numbers due to hard to read definitions about them all over Google. But none that I have read provide a simple enough explanation of what they really are. Can I get a plain definition with example? A: From my understanding, fixed-point arithmetic is done using integers. where the decimal part is stored in a fixed amount of bits, or the number is multiplied by how many digits of decimal precision is needed. For example, If the number 12.34 needs to be stored and we only need two digits of precision after the decimal point, the number is multiplied by 100 to get 1234. When performing math on this number, we'd use this rule set. Adding 5620 or 56.20 to this number would yield 6854 in data or 68.54. If we want to calculate the decimal part of a fixed-point number, we use the modulo (%) operand. 12.34 (pseudocode): v1 = 1234 / 100 // get the whole number v2 = 1234 % 100 // get the decimal number (100ths of a whole). print v1 + "." + v2 // "12.34" Floating point numbers are a completely different story in programming. The current standard for floating point numbers use something like 23 bits for the data of the number, 8 bits for the exponent, and 1 but for sign. See this Wikipedia link for more information on this. A: A fixed point number just means that there are a fixed number of digits after the decimal point. A floating point number allows for a varying number of digits after the decimal point. For example, if you have a way of storing numbers that requires exactly four digits after the decimal point, then it is fixed point. Without that restriction it is floating point. Often, when fixed point is used, the programmer actually uses an integer and then makes the assumption that some of the digits are beyond the decimal point. For example, I might want to keep two digits of precision, so a value of 100 means actually means 1.00, 101 means 1.01, 12345 means 123.45, etc. Floating point numbers are more general purpose because they can represent very small or very large numbers in the same way, but there is a small penalty in having to have extra storage for where the decimal place goes. A: The term ‘fixed point’ refers to the corresponding manner in which numbers are represented, with a fixed number of digits after, and sometimes before, the decimal point. With floating-point representation, the placement of the decimal point can ‘float’ relative to the significant digits of the number. For example, a fixed-point representation with a uniform decimal point placement convention can represent the numbers 123.45, 1234.56, 12345.67, etc, whereas a floating-point representation could in addition represent 1.234567, 123456.7, 0.00001234567, 1234567000000000, etc. A: A fixed point number has a specific number of bits (or digits) reserved for the integer part (the part to the left of the decimal point) and a specific number of bits reserved for the fractional part (the part to the right of the decimal point). No matter how large or small your number is, it will always use the same number of bits for each portion. For example, if your fixed point format was in decimal IIIII.FFFFF then the largest number you could represent would be 99999.99999 and the smallest non-zero number would be 00000.00001. Every bit of code that processes such numbers has to have built-in knowledge of where the decimal point is. A floating point number does not reserve a specific number of bits for the integer part or the fractional part. Instead it reserves a certain number of bits for the number (called the mantissa or significand) and a certain number of bits to say where within that number the decimal place sits (called the exponent). So a floating point number that took up 10 digits with 2 digits reserved for the exponent might represent a largest value of 9.9999999e+50 and a smallest non-zero value of 0.0000001e-49. A: There's of what a fixed-point number is and , but very little mention of what I consider the defining feature. The key difference is that floating-point numbers have a constant relative (percent) error caused by rounding or truncating. Fixed-point numbers have constant absolute error. With 64-bit floats, you can be sure that the answer to x+y will never be off by more than 1 bit, but how big is a bit? Well, it depends on x and y -- if the exponent is equal to 10, then rounding off the last bit represents an error of 2^10=1024, but if the exponent is 0, then rounding off a bit is an error of 2^0=1. With fixed point numbers, a bit always represents the same amount. For example, if we have 32 bits before the decimal point and 32 after, that means truncation errors will always change the answer by 2^-32 at most. This is great if you're working with numbers that are all about equal to 1, which gain a lot of precision, but bad if you're working with numbers that have different units--who cares if you calculate a distance of a googol meters, then end up with an error of 2^-32 meters? In general, floating-point lets you represent much larger numbers, but the cost is higher (absolute) error for medium-sized numbers. Fixed points get better accuracy if you know how big of a number you'll have to represent ahead of time, so that you can put the decimal exactly where you want it for maximum accuracy. But if you don't know what units you're working with, floats are a better choice, because they represent a wide range with an accuracy that's good enough. A: Take the number 123.456789 * *As an integer, this number would be 123 *As a fixed point (2), this number would be 123.46 (Assuming you rounded it up) *As a floating point, this number would be 123.456789 Floating point lets you represent most every number with a great deal of precision. Fixed is less precise, but simpler for the computer.. A: It is CREATED, that fixed-point numbers don't only have some Fixed number of decimals after point (digits) but are mathematically represented in negative powers. Very good for mechanical calculators: e.g, the price of smth is USD 23.37 (Q=2 digits after the point. ) The machine knows where the point is supposed to be!
{ "language": "en", "url": "https://stackoverflow.com/questions/7524838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "155" }
Q: C# - trim text file contents to specified line number I have a very annoying bug, code generation tool has generated like 20,000 lines of rubbish in file. Removing it all by hand, is, well, rather hard, so I want to write a program that does so. Good news is that source code file contains needful info on lines 1 - 300, and then rubbish all the way down to line 20,000. I'm not very experienced in handling files in C#, and couldn't google up method I need. Are there any ways to do so? A: File.WriteAllLines("test.txt", File.ReadAllLines("test.txt").Take(300)); A: Below is an example code to do this file trimming: public static void TrimFile(string fileName,int start, int end) { File.WriteAllLines(fileName, File.ReadAllLines(fileName) .Skip(start - 1).Take(end - start)); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7524839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java2D negative position can not be displayed, move origin to bottom left I am trying to draw lines on coordinates system in Graphics2D. However, I find out that the part on line in negative area can not be shown. Is there anyway I can make the lines in negative area be seen? Also, is there anyway I can convert direct of y-axis from downward to upward? Graphics2D g2 = (Graphics2D) g; g2.scale(1, -1); g2.translate(0, -HEIGHT); Can't work. Object disappears. Thanks! A: Ah, you are using the HEIGHT attribute. You should be using getHeight(). The code below produces this screenshot (g2.drawLine(0, 0, 100, 100)): Code: public static void main(String[] args) throws Exception { JFrame frame = new JFrame("Test"); frame.add(new JComponent() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g.create(); { g2.translate(0, getHeight() - 1); g2.scale(1, -1); g2.drawLine(0, 0, 100, 100); } g2.dispose(); } }); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 300); frame.setVisible(true); } A: As far as I understand Java2D you can't use negative coordinates. You always operate in the so-called "User Space" in Java2D. The translates coordinates of your position in "Device Space" might be negative, but this is invisible to you in Java. See also Java2D Tutorial - Coordinates and Graphics2D API. You might be able to achieve what you want by subclassing Graphics2D and doing the those translation yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Get Canvas coordinates after scaling up/down or dragging in android I'm developing an application in which I'm pasting images, doing drawing and painting on canvas. This app can also Scale up/down the canvas or drag it to different location. My problem is: I can't get the correct canvas coordinates after scaling or dragging the canvas. I want to draw finger paint after the canvas is scaled or dragged but unable to retrieve the right place where i've touched..:( Also I'm new bee. Here is the code. @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.save(); //canvas.translate(mPosX, mPosY); canvas.scale(mScaleFactor, mScaleFactor, super.getWidth() * 0.5f, super.getHeight() * 0.5f); mIcon.draw(canvas); for (Path path : listPath) { canvas.drawPath(path, paint); } canvas.restore(); } public TouchExampleView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean onTouchEvent(MotionEvent ev) { // Let the ScaleGestureDetector inspect all events. mScaleDetector.onTouchEvent(ev); final int action = ev.getAction(); switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: { final float x = ev.getX(); final float y = ev.getY(); mLastTouchX = x; mLastTouchY = y; mActivePointerId = ev.getPointerId(0); break; } case MotionEvent.ACTION_MOVE: { final int pointerIndex = ev.findPointerIndex(mActivePointerId); final float x = ev.getX(pointerIndex); final float y = ev.getY(pointerIndex); // Only move if the ScaleGestureDetector isn't processing a gesture. if (!mScaleDetector.isInProgress()) { final float dx = x - mLastTouchX; final float dy = y - mLastTouchY; mPosX += dx; mPosY += dy; invalidate(); } mLastTouchX = x; mLastTouchY = y; break; } case MotionEvent.ACTION_UP: { mActivePointerId = INVALID_POINTER_ID; break; } case MotionEvent.ACTION_CANCEL: { mActivePointerId = INVALID_POINTER_ID; break; } case MotionEvent.ACTION_POINTER_UP: { final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; final int pointerId = ev.getPointerId(pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mLastTouchX = ev.getX(newPointerIndex); mLastTouchY = ev.getY(newPointerIndex); mActivePointerId = ev.getPointerId(newPointerIndex); } break; } } float objectNewX,objectNewY; if (mScaleFactor >= 1) { objectNewX = ev.getX() + (ev.getX() - super.getWidth() * 0.5f) * (mScaleFactor - 1); objectNewY = ev.getY() + (ev.getY() - super.getHeight() * 0.5f) * (mScaleFactor - 1); } else { objectNewX = ev.getX() - (ev.getX() - super.getWidth() * 0.5f) * (1 - mScaleFactor); objectNewY = ev.getY() - (ev.getY() - super.getHeight() * 0.5f) * (1 - mScaleFactor); } if (ev.getAction() == MotionEvent.ACTION_DOWN) { path = new Path(); path.moveTo(objectNewX,objectNewY); path.lineTo(objectNewX,objectNewY); } else if (ev.getAction() == MotionEvent.ACTION_MOVE) { path.lineTo(objectNewX,objectNewY); listPath.add(path); } else if (ev.getAction() == MotionEvent.ACTION_UP) { path.lineTo(objectNewX,objectNewY); listPath.add(path); } return true; } private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { @Override public boolean onScale(ScaleGestureDetector detector) { mScaleFactor *= detector.getScaleFactor(); // Don't let the object get too small or too large. mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f)); invalidate(); return true; } } A: Done it finally by myself. Draw everything by applying this formula to (px,py) coordinates: float px = ev.getX() / mScaleFactor + rect.left; float py = ev.getY() / mScaleFactor + rect.top; rect = canvas.getClipBounds(); //Get them in on Draw function and apply above formula before drawing A: @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); clipBounds_canvas = canvas.getClipBounds(); /////Do whatever you want to do..!!! }; @Override public boolean onTouchEvent(MotionEvent ev) { int x = ev.getX() / zoomFactor + clipBounds_canvas.left; int y = ev.getY() / zoomFactor + clipBounds_canvas.top; //Use the above two values insted of ev.getX() and ev.getY(); } Hope this will help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: In Ruby, how can I reflect on classes contained within a module? I'm using a library that lays its library out like this: module Lib class A; end class B; end ... end I know that I can use send on an object to "call" a method known only at runtime (e.g., foo.send(:bar, :baz_param=>42). How can I do this at the class level? In other words, I suspect there's a way to write something like this: label = :Klass MyModule.some_method(label).new that executes, in effect, as: MyModule::Klass.new Am I right? A: As soon as I posted the question, I had a brainwave: const_get Class names are treated as constants, and the method is defined for all modules, too, so the lookup scope can be restricted to that module only. Just remember to get the capitalization right: MyModule.const_get(:Klass).new # => #<Klass:> #CORRECT MyModule.const_get(:klass).new # => NameError: wrong constant name
{ "language": "en", "url": "https://stackoverflow.com/questions/7524846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Logging into a server using JSON object I've a bit of code that will be used to login to a clients server with his user name and password. Here is the code that I am using. My problem is that it isn't authenticating properly. I've checked the URL, user name & password but still there seems to be some sorta error public class HttpClient { private static final String TAG = "&&----HTTPClient-----**"; public static void SendHttpPost (String URL, JSONObject jsonObjSend){ try{ DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpPostRequest = new HttpPost(URL); Log.v("The url is","The url is "+URL); StringEntity se; se = new StringEntity(jsonObjSend.toString()); httpPostRequest.setEntity(se); httpPostRequest.setHeader("Accept", "application/json"); httpPostRequest.setHeader("Content-type", "application/json"); long t = System.currentTimeMillis(); HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest); Log.i(TAG, "HTTPRESPONSE RECIEVED" +(System.currentTimeMillis()-t) + "ms"); HttpEntity entity = response.getEntity(); if(entity != null){ InputStream instream = entity.getContent(); String resultString = convertStreamToString(instream); Log.v(TAG , "The response is " +resultString); instream.close(); JSONObject jsonObj = new JSONObject(resultString); JSONObject sessionJson = jsonObj.getJSONObject("session"); String sessionId = sessionJson.getString("sessionid"); String name = sessionJson.getString("name"); Log.v("The name is"+name,""+sessionId); } } catch (Exception e){ e.printStackTrace(); } } private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try{ while((line = reader.readLine()) !=null ){ sb.append(line + "\n"); } } catch (IOException e){ e.printStackTrace(); } finally{ try { is.close(); } catch (IOException e){ e.printStackTrace(); } } return sb.toString(); } } This is the HOMEACTIVITY public class HomeActivity extends Activity { private static final String tag = "##-----HomeActivity-----&&"; private static final String URL = "**************************"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); JSONObject jsonObjSend = new JSONObject(); try { JSONObject header = new JSONObject(); header.put("username","125"); header.put("password","1"); header.put("company", "1000"); jsonObjSend.put("user", header); // Output the JSON object we're sending to Logcat: Log.i(tag,"Output the JSON object we're sending to Logcat: " +jsonObjSend.toString(2)); } catch (JSONException e) { e.printStackTrace(); } } } At the URL of home activity I am passing the actual server URL (which cannot be shared). A: you are not calling the httppost in homeactivity try this HttpClient.SendHttpPost(URL, jsonObjSend);
{ "language": "en", "url": "https://stackoverflow.com/questions/7524847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: A tricky XSLT transformation I have a loosely structured XHTML data and I need to convert it to better structured XML. Here's the example: <tbody> <tr> <td class="header"><img src="http://www.abc.com/images/icon_apples.gif"/><img src="http://www.abc.com/images/flag/portugal.gif" alt="Portugal"/> First Grade</td> </tr> <tr> <td>Green</td> <td>Round shaped</td> <td>Tasty</td> </tr> <tr> <td>Red</td> <td>Round shaped</td> <td>Bitter</td> </tr> <tr> <td>Pink</td> <td>Round shaped</td> <td>Tasty</td> </tr> <tr> <td class="header"><img src="http://www.abc.com/images/icon_strawberries.gif"/><img src="http://www.abc.com/images/flag/usa.gif" alt="USA"/> Fifth Grade</td> </tr> <tr> <td>Red</td> <td>Heart shaped</td> <td>Super tasty</td> </tr> <tr> <td class="header"><img src="http://www.abc.com/images/icon_bananas.gif"/><img src="http://www.abc.com/images/flag/congo.gif" alt="Congo"/> Third Grade</td> </tr> <tr> <td>Yellow</td> <td>Smile shaped</td> <td>Fairly tasty</td> </tr> <tr> <td>Brown</td> <td>Smile shaped</td> <td>Too sweet</td> </tr> I am trying to achieve following structure: <data> <entry> <type>Apples</type> <country>Portugal</country> <rank>First Grade</rank> <color>Green</color> <shape>Round shaped</shape> <taste>Tasty</taste> </entry> <entry> <type>Apples</type> <country>Portugal</country> <rank>First Grade</rank> <color>Red</color> <shape>Round shaped</shape> <taste>Bitter</taste> </entry> <entry> <type>Apples</type> <country>Portugal</country> <rank>First Grade</rank> <color>Pink</color> <shape>Round shaped</shape> <taste>Tasty</taste> </entry> <entry> <type>Strawberries</type> <country>USA</country> <rank>Fifth Grade</rank> <color>Red</color> <shape>Heart shaped</shape> <taste>Super</taste> </entry> <entry> <type>Bananas</type> <country>Congo</country> <rank>Third Grade</rank> <color>Yellow</color> <shape>Smile shaped</shape> <taste>Fairly tasty</taste> </entry> <entry> <type>Bananas</type> <country>Congo</country> <rank>Third Grade</rank> <color>Brown</color> <shape>Smile shaped</shape> <taste>Too sweet</taste> </entry> </data> Firstly I need to extract the fruit type from the tbody/tr/td/img[1]/@src, secondly the country from tbody/tr/td/img[2]/@alt attribute and finally the grade from tbody/tr/td itself. Next I need to populate all the entries under each category while including those values (like shown above). But... As you can see, the the data I was given is very loosely structured. A category is simply a td and after that come all the items in that category. To make the things worse, in my datasets, the number of items under each category varies between 1 and 100... I've tried a few approaches but just can't seem to get it. Any help is greatly appreciated. I know that XSLT 2.0 introduces xsl:for-each-group, but I am limited to XSLT 1.0. A: In this case, you are not actually grouping elements. It is more like ungrouping them. One way to do this is to use an xsl:key to look up the "header" row for each of detail rows. <xsl:key name="fruity" match="tr[not(td[@class='header'])]" use="generate-id(preceding-sibling::tr[td[@class='header']][1])"/> i.e For each detail row, get the most previous header row. Next, you can then match all your header rows like so: <xsl:apply-templates select="tr/td[@class='header']"/> Within the matching template, you could then extract the type, country and rank. Then to get the associated detail rows, it is a simple case of looking at the key for the parent row: <xsl:apply-templates select="key('fruity', generate-id(..))"> Here is the overall XSLT <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:key name="fruity" match="tr[not(td[@class='header'])]" use="generate-id(preceding-sibling::tr[td[@class='header']][1])"/> <xsl:template match="/tbody"> <data> <!-- Match header rows --> <xsl:apply-templates select="tr/td[@class='header']"/> </data> </xsl:template> <xsl:template match="td"> <!-- Match associated detail rows --> <xsl:apply-templates select="key('fruity', generate-id(..))"> <!-- Extract relevant parameters from the td cell --> <xsl:with-param name="type" select="substring-before(substring-after(img[1]/@src, 'images/icon_'), '.gif')"/> <xsl:with-param name="country" select="img[2]/@alt"/> <xsl:with-param name="rank" select="normalize-space(text())"/> </xsl:apply-templates> </xsl:template> <xsl:template match="tr"> <xsl:param name="type"/> <xsl:param name="country"/> <xsl:param name="rank"/> <entry> <type> <xsl:value-of select="$type"/> </type> <country> <xsl:value-of select="$country"/> </country> <rank> <xsl:value-of select="$rank"/> </rank> <color> <xsl:value-of select="td[1]"/> </color> <shape> <xsl:value-of select="td[2]"/> </shape> <taste> <xsl:value-of select="td[3]"/> </taste> </entry> </xsl:template> </xsl:stylesheet> When applied to your input document, the following output is generated: <data> <entry> <type>apples</type> <country>Portugal</country> <rank>First Grade</rank> <color>Green</color> <shape>Round shaped</shape> <taste>Tasty</taste> </entry> <entry> <type>apples</type> <country>Portugal</country> <rank>First Grade</rank> <color>Red</color> <shape>Round shaped</shape> <taste>Bitter</taste> </entry> <entry> <type>apples</type> <country>Portugal</country> <rank>First Grade</rank> <color>Pink</color> <shape>Round shaped</shape> <taste>Tasty</taste> </entry> <entry> <type>strawberries</type> <country>USA</country> <rank>Fifth Grade</rank> <color>Red</color> <shape>Heart shaped</shape> <taste>Super tasty</taste> </entry> <entry> <type>bananas</type> <country>Congo</country> <rank>Third Grade</rank> <color>Yellow</color> <shape>Smile shaped</shape> <taste>Fairly tasty</taste> </entry> <entry> <type>bananas</type> <country>Congo</country> <rank>Third Grade</rank> <color>Brown</color> <shape>Smile shaped</shape> <taste>Too sweet</taste> </entry> </data>
{ "language": "en", "url": "https://stackoverflow.com/questions/7524854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Right to left Text HTML input For my website, i need to provide arabic support. Part of it is to provide input textboxes where when user types in, the new characters have to be appended to the left and the text has to be right aligned. setting the css property to text-align:right didn't work, as i could not get the cursor to come to the left and add letters there. So I removed that property and added direction:RTL Here, the cursor came to the left and text was right aligned. but the newly added characters were not getting appended to the left. Instead they were getting appended to the right end only. How do I fix this? please help.. For example, see the google arabic page search box. I need the exact behavior, although not with those fancy keyboard icon etc., http://www.google.com/webhp?hl=ar A: function rtl(element) { if(element.setSelectionRange){ element.setSelectionRange(0,0); } } <input type="text" name="textbox" style="direction:RTL;" onkeyup="rtl(this);"/> This code will do. A: Simply use this CSS, this will change your text field and cursor position from right to left. input, textarea { unicode-bidi:bidi-override; direction: RTL; } A: You can use the dir="rtl" on the input. It is supported. <input dir="rtl" id="foo"/> A: Use only direction:RTL and when switched to a proper keyboard (e.g. Arabic) in the system settings, the newly added characters will correctly be appended to the left. A: A feature specific to Angular Material, in addition to direction: rtl, is : .mat-form-field { text-align: start!important; } This will work for both RLT & LTR A: A better, more user-friendly way to do this is to set the dir attribute to auto. <input dir="auto" id="foo"/> This way if a user enters English text it will be left-aligned and if he enters Arabic text it will be right-aligned automatically See here for more information on the dir attribute A: Here's what I can think of: * *Use direction:RTL for the RIGHT alignment *Write a JavaScript handler attached to the event: "onkeyup", which performs the shifting of the entered character to the LEFT (doing some text processing). A: Use on the input in css. input { unicode-bidi:bidi-override; direction: RTL; } A: It works for Chrome browser. Use a div element and make it editable. <div contenteditable="true"> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7524855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "45" }
Q: Visual Studio 2010: How to generate component diagram from code I got into a project that is under development for quite sometime and lacks models and documentation on the design. We are using Visual Studio 2010 Ultimate. There is one old preliminary VS architecture model and I am trying to grow it up to show how the system looks like from different perspectives. While, I can generate the class diagrams fairly well and generate the sequence diagrams on the fly, I am stuck in generating the component diagram. I wanted to avoid the pain of generating it of my own and wished if there could be some easy process to reflect the code/implementation to a good extent. Fine-tuning is not an issue. I expected, I could put the assemblies in the solution as components in the Model explorer. But could not. I also tried drag-and-dropping the projects to the component diagram or the namespaces/classes from the architecture explorer on to the component diagram. Is there any easy way out? A: You will need to download and install the Visual Studio SDK and the Visual Studio Visualization and Modeling SDK then create a Domain-Specific Language Solution. * *MSDN for VS 2008 DSL *MSDN for VS 2010 DSL (differs quite a bit, therefore both links) *Visual Studio Development Center - DSL Unfortunately that is pretty much all Information I could gather, as I cannot install the VS 2010 SDK even though I do have VS 2010 Professional installed. If you happen to not be able to install it yourself here is a link to a post in the Microsoft forum of someone having the same problem atm. It is still unresolved, but was just asked a little while ago. Edit: For creating UML component diagrams with VS2010 one will need VS2010 Ultimate. I am not quite sure weather you need it to actually install the Modeling SDK also. I dont feel a need to test it on my Professional installation though and you do have Ultimate anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WatiN : Textfields are not getting automated while running the code as WatiN.Core.IE window = new WatiN.Core.IE(); // Frames // Model TextField txt_txtName = window.TextField(Find.ByName("txtName")); TextField txt_txtPassword = window.TextField(Find.ByName("txtPassword")); Button btn_btnLogin = window.Button(Find.ByName("btnLogin")); // Code window.GoTo("http://134.554.444.55/asdfgfghh/"); txt_txtName.TypeText("fghfjghm"); txt_txtPassword.TypeText("gfhgjfgh"); btn_btnLogin.Click(); } only the window.GoTo("http://134.554.444.55/asdfgfghh/"); code works and the rest are doing nothing, When I am using a catch block it throws exception as Could not find INPUT (hidden) or INPUT (password) or INPUT (text) or INPUT (textarea) or TEXTAREA element tag matching criteria: Attribute 'name' equals 'txtName' at "http://134.554.444.55/asdfgfghh/ (inner exception: Unable to cast COM object of type 'System.__ComObject' to interface type 'mshtml.IHTMLElement'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{3050F1FF-98B5-11CF-BB82-00AA00BDCE0B}' failed due to the following error: Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY)).) A: My answer is very similar with Pavlo's one, but I must advice to use Page which is a built-in suport for Model as described by Pavlo. Create a class MyPage public class MyPage : WatiN.Core.Page { public TextField NameField { get { return Document.TextField(Find.ByName("txtName")); } } public TextField PasswordField { get { return Document.TextField(Find.ByName("txtPassword")); } } public TextField LoginButton { get { return Document.Button(Find.ByName("btnLogin")); } } } Then you can just call .Page<MyClass> method. using(var browser = new IE("http://134.554.444.55/asdfgfghh/")) { var page = browser.Page<MyClass>(); page.NameField.TypeText("name field"); page.PasswordField.TypeText("password field"); page.LoginButton.Click(); } A: When you call Button, TextField or whatever it does not create mapping it actually searches for control on page. And if the page is not opened yet than control does not exist. You can create properties that will find control when you request it. So you define a particular model as class with appropriate properties. public TextField txt_txtName { get { return window.TextField(Find.ByName("txtName")); } } Added: If creating properties does not work for you, then use this: var model = new { txt_txtName = new Func<TextField>(() => window.TextField(Find.ByName("txtName"))), txt_txtPassword = new Func<TextField>(() => window.TextField(Find.ByName("txtPassword"))), btn_btnLogin = new Func<Button>(() => window.Button(Find.ByName("btnLogin"))) }; window.GoTo("http://134.554.444.55/asdfgfghh/"); model.txt_txtName().TypeText("fghfjghm"); model.txt_txtPassword().TypeText("gfhgjfgh"); model.btn_btnLogin().Click();
{ "language": "en", "url": "https://stackoverflow.com/questions/7524862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Node.js: How do Proxy sites deal with relative Urls? I've created a relatively simple proxy in Node, which allows me to download pages and display them. This is fine, although some scripts, links, forms and images seem to be broken since they are pointing to relative files. As a project I'm trying to create a fully functional web proxy. How do sites like Proxify solve this problem? Program for reference: var app = require('express').createServer(); var request = require('request'), sys = require('sys'), fs=require('fs'); app.get('/url', function(req, res){ console.log(req.query.link); request({ uri: req.query.link, headers: {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; rv:6.0) Gecko/20110814 Firefox/6.0"} }, function (error, response, body) { if (error && response.statusCode !== 200) { console.log('Error when contacting google.com') } res.send(body, {"Content-type": "text/html"}); res.end(); }); }); A: Right now your code is only proxying the html file, and the client is grabbing the rest directly from the real site. You'll want to use something like node jQuery to replace all src/href in the document to make them go through your proxy, and at the same time you can check if they're relative or not and if they are prepend the current url and then create your proxy url.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Caching with Cedar/Memcache/Rails 3.1 So I have been trying to get caching to work on my private website, which basically just serves static stuff with little dynamic stuff in it. Since I am going to deply to Heroku Cedar, I have to go with Memcache instead of Varnish. However, I do not seem to be able to make it cache. I always get cache: stale, invalid, store. The way I cache is to set the appropriate config params, and use the built-in cache_pages method of ActionController. Can someone help me debugging this? A: I see the same. But it looks like page caching works. A: So i decided to use Cloudflare for caching, after a couple days of running, i received significant boost in performance/caching.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: screen rotation in android I want to use screen rotation in android device. But I don't want to rotate whole activity. How is this possible to rotate only some of views in a activity Like there are two button and one ImageView. I want to rotate only ImageView on screen orientation change. Plz suggest the way. Thanks. A: Create another xml file with same name and put it in new folder inside res/ folder. Name that new folder layout-land. and change in your xml file according to your requirements. It will automatically change the layout file when the orientation will be changed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom building of APK is there any way how to change, via changes in build.xml file, package name in time of build? Is it even possible?
{ "language": "en", "url": "https://stackoverflow.com/questions/7524879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: A basic question on multihreading For example I have a resource lock. So a multithreaded function checks if it's set before accessing a resource, then if it's not sets it Is there a tiny possibility that between checking and setting, another thread would have set the same lock? A: Yes, there is such possibility. You may checkout double-checked locking. A: Depends how you want it to work. Read the man page for mutex_lock. The checking whether a lock is set is superfluous in this case, since the very act of setting the mutex pauses the thread until the mutex is available (and so any sort of if(resource_unavailable) { wait for availability } code becomes unnecessary). A: You don't check the state of a lock first to then acquire it. What you do is to just acquire it, specifying that you do not want to block or wait for it. The call will fail immediately if the lock is held by another thread. The "lock acquire" call is implemented as an atomic operation. Many implementations provide a specific tryLock() function that achieves what I described above.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: QTextStream and std out I have the code: QTextStream out(mFileHandle); out << (QTime::currentTime().toString(Qt::LocalDate) + " - ").toAscii(); out << "Something another"; std::cout << "Data: \n"; std::cout << out.string(); out.flush(); It writes to file but after 'Data:' I get '0', why? How to send data to both streams? A: It looks to me like you constructed your QTextStream out from a file handle. This means that it is going to write to that file. The .string() method in QTextStream is only to access the QString used to construct it. In this case, it is zero, since you didn't use a string to construct it. If you want to access the all the text that has been written to the QTextstream, you probably want to pass it a QByteArray as the constructor argument. This will make it write output to that QByteArray, rather than out to a file. Then, you can access the contents written to the stream through the QByteArray. A: You would do somthing like that: QByteArray outBytes; QTextStream outStream(&outBytes); //write something to outBytes via stream outStream << (QTime::currentTime().toString(Qt::LocalDate) + " - "); outStream << "Something another"; //construct QString from written bytes std::cout << QString(outBytes).toStdString();
{ "language": "en", "url": "https://stackoverflow.com/questions/7524887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Framework/Library like Sitemesh I am looking at a UI framework similar to Sitemesh http://www.sitemesh.org/ Just to add, I am planning to have a Java based web app, which would be based on fluid design and would have "slightly" different layouts for desktop/mobile/tablet. (e.g. some areas just rearranging on different screen sizes or even hidden on smaller screens, etc) Please suggest whatever ideas you may have.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Onitemclick listener on getview method I'm trying to implement to open a custom dialog box having related info from the adapter list. here I'm using onclicklistener, it is working fine i'm getting custom dialog box, my problem is i'm not getting the correct info. If i click on any item on the list in dialog box it is showing the last item details. At the time of generating the list it is showing the positions in logcat. But when i'm trying to click on details textview it is taking the last item position. public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View v = convertView; if(v == null){ LayoutInflater vl = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vl.inflate(R.layout.listItem, null); } Fields o = results.get(position); if (o != null) { TextView iv = (TextView)v.findViewById(R.id.toptext); TextView tv_link = (TextView)v.findViewById(R.id.toptext1); ImageView tv_Image = (ImageView)v.findViewById(R.id.Locimage); tv_link.setText("Details >>"); tv_link.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Dialog dialog = new Dialog(mContext); dialog.setContentView(R.layout.locationdetails); dialog.setTitle("Title"); System.out.println("Position "+pos); TextView LocName = (TextView) dialog.findViewById(R.id.LocDescName); LocName.setText(o.getLocationName()); ImageView LocDescImage = (ImageView) dialog.findViewById(R.id.LocDescImage); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream((InputStream) new URL(o.getLocationImage()).getContent()); LocDescImage .setImageBitmap(bitmap); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } dialog.show(); } }); } DbLoc.close(); return v; } } A: Try to use the setTag(Object o) and getTag() methods on TextView,it may help you I mean tv_link.setTag(o); inside the onClickListener,get that object using v.getTag(); Fields o=(Fields)v.getTag(); LocName.setText(o.getLocationName()); it may solve your problem. A: This is because int:pos inside tv_link.setOnClickListener is not managed properly . why you did not add code related to it here . anyway now if passing single object by tv_link.setTag(your_pbject) will be enough as per your requirment , go through it , else create inner class which will implement View.onClickListener and pass related data through constructor at the time of setting this onclickListenet for each view .
{ "language": "en", "url": "https://stackoverflow.com/questions/7524892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I add a rich text box to a Custom Post Type in Dashboard? I'm trying to add a custom post type for 'surgeons' unfortunately theres like 6 sections i need to add which need to be rich text and not plain text for images, etc. this is what i currently have. I have all the plain text fields working fine but now i need to add all rich text ones. Set up various structures on backend function personal_meta() { global $post; $custom = get_post_custom($post->ID); $email = $custom["email"][0]; $phone = $custom["phone"][0]; $address = $custom["address"][0]; $website = $custom["website"][0]; ?> <p><label>Email:</label><br /> <input type="text" name="email" value="<?php echo $email; ?>" /></p> <p><label>Phone - with extension. i.e. (805) 555-2323 Ext 234</label><br /> <input type="text" name="phone" value="<?php echo $phone; ?>" /></p> <p><label>Address:</label><br /> <textarea cols="50" rows="4" name="address"><?php echo $address; ?></textarea></p> <p><label>Website - BEGINNING WITH http://</label><br /> <input type="text" name="website" value="<?php echo $website; ?>" /></p> <?php } heres the code to save it add_action('save_post', 'save_details'); function save_details(){ global $post; update_post_meta($post->ID, "email", $_POST["email"]); update_post_meta($post->ID, "phone", $_POST["phone"]); update_post_meta($post->ID, "address", $_POST["address"]); update_post_meta($post->ID, "website", $_POST["website"]); } A: You need to add the class "theEditor" which will then add the tinyMCE editor to the textarea: <textarea class="theEditor" cols="50" rows="4" name="address"> <?php echo $address; ?> </textarea> However, that will strip out <p> and <br> tags (not any others) when saved. To prevent stripping those tags, you will need to try something like this: <textarea class="theEditor" cols="50" rows="4" name="address"> <?php echo wpautop(get_post_meta($post->ID, 'your text area', true)); ?> </textarea> A: i think you have to do deep works, as on update_metadata , wordpress uses sanitize_meta function, which sanitizes the meta value, and thus, you may get plain value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Installing PDCurses for Cygwin I've been searching for a solution to do this for a while now, but still unsure. How do u install the PDCurses library in cygwin. I have the zip, I just don't know where to place the files. Is there a way to do this? Thanks in advance EDIT: If ncurses itself would be better how would I go about installing that with cygwin. Whichever one works. Basically how would I get ncurses like functionality in windows. A: I hate doing this but I solved it and wanted to get the answer out there. Download the files http://pdcurses.sourceforge.net/ at this location. A more direct link is http://sourceforge.net/projects/pdcurses/files/pdcurses/3.4/. I downloaded this one "pdc34dllw.zip". Place all files in the same location as the file you are compiling. you must link the lib to your file like this gcc ./your_file_name ./pdcurses.lib and your done. I think the *.dll needs to stay with the file though so include that when you distribute. Make sure you include the file curses.h in your file. #include "curses.h" It seems to work with all the classic ncurses commands :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7524902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Should I call Close() or Dispose() for stream objects? Classes such as Stream, StreamReader, StreamWriter etc implements IDisposable interface. That means, we can call Dispose() method on objects of these classes. They've also defined a public method called Close(). Now that confuses me, as to what should I call once I'm done with objects? What if I call both? My current code is this: using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { using (StreamWriter writer = new StreamWriter(filename)) { int chunkSize = 1024; while (!reader.EndOfStream) { char[] buffer = new char[chunkSize]; int count = reader.Read(buffer, 0, chunkSize); if (count != 0) { writer.Write(buffer, 0, count); } } writer.Close(); } reader.Close(); } } As you see, I've written using() constructs, which automatically call Dispose() method on each object. But I also call Close() methods. Is it right? Please suggest me the best practices when using stream objects. :-) MSDN example doesn't use using() constructs, and call Close() method: * *How to: Download Files with FTP Is it good? A: On many classes which support both Close() and Dispose() methods, the two calls would be equivalent. On some classes, however, it is possible to re-open an object which has been closed. Some such classes may keep some resources alive after a Close, in order to permit reopening; others may not keep any resources alive on Close(), but might set a flag on Dispose() to explicitly forbid re-opening. The contract for IDisposable.Dispose explicitly requires that calling it on an object which will never be used again will be at worst harmless, so I would recommend calling either IDisposable.Dispose or a method called Dispose() on every IDisposable object, whether or not one also calls Close(). A: No, you shouldn't call those methods manually. At the end of the using block the Dispose() method is automatically called which will take care to free unmanaged resources (at least for standard .NET BCL classes such as streams, readers/writers, ...). So you could also write your code like this: using (Stream responseStream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(responseStream)) using (StreamWriter writer = new StreamWriter(filename)) { int chunkSize = 1024; while (!reader.EndOfStream) { char[] buffer = new char[chunkSize]; int count = reader.Read(buffer, 0, chunkSize); if (count != 0) { writer.Write(buffer, 0, count); } } } The Close() method calls Dispose(). A: The documentation says that these two methods are equivalent: StreamReader.Close: This implementation of Close calls the Dispose method passing a true value. StreamWriter.Close: This implementation of Close calls the Dispose method passing a true value. Stream.Close: This method calls Dispose, specifying true to release all resources. So, both of these are equally valid: /* Option 1, implicitly calling Dispose */ using (StreamWriter writer = new StreamWriter(filename)) { // do something } /* Option 2, explicitly calling Close */ StreamWriter writer = new StreamWriter(filename) try { // do something } finally { writer.Close(); } Personally, I would stick with the first option, since it contains less "noise". A: A quick jump into Reflector.NET shows that the Close() method on StreamWriter is: public override void Close() { this.Dispose(true); GC.SuppressFinalize(this); } And StreamReader is: public override void Close() { this.Dispose(true); } The Dispose(bool disposing) override in StreamReader is: protected override void Dispose(bool disposing) { try { if ((this.Closable && disposing) && (this.stream != null)) { this.stream.Close(); } } finally { if (this.Closable && (this.stream != null)) { this.stream = null; /* deleted for brevity */ base.Dispose(disposing); } } } The StreamWriter method is similar. So, reading the code it is clear that that you can call Close() & Dispose() on streams as often as you like and in any order. It won't change the behaviour in any way. So it comes down to whether or not it is more readable to use Dispose(), Close() and/or using ( ... ) { ... }. My personal preference is that using ( ... ) { ... } should always be used when possible as it helps you to "not run with scissors". But, while this helps correctness, it does reduce readability. In C# we already have plethora of closing curly braces so how do we know which one actually performs the close on the stream? So I think it is best to do this: using (var stream = ...) { /* code */ stream.Close(); } It doesn't affect the behaviour of the code, but it does aid readability. A: This is an old question, but you can now(C# 8.0) write using statements without needing to block each one. They will be disposed of in reverse order when the containing block is finished. using var responseStream = response.GetResponseStream(); using var reader = new StreamReader(responseStream); using var writer = new StreamWriter(filename); int chunkSize = 1024; while (!reader.EndOfStream) { char[] buffer = new char[chunkSize]; int count = reader.Read(buffer, 0, chunkSize); if (count != 0) { writer.Write(buffer, 0, count); } } https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/using A: For what it's worth, the source code for Stream.Close explains why there are two methods: // Stream used to require that all cleanup logic went into Close(), // which was thought up before we invented IDisposable. However, we // need to follow the IDisposable pattern so that users can write // sensible subclasses without needing to inspect all their base // classes, and without worrying about version brittleness, from a // base class switching to the Dispose pattern. We're moving // Stream to the Dispose(bool) pattern - that's where all subclasses // should put their cleanup now. In short, Close is only there because it predates Dispose, and it can't be deleted for compatibility reasons. A: Just to complement other answers, as of C# 8.0, you don't need to open a block of code just to use an using statement if (...) { using FileStream f = new FileStream(@"C:\users\jaredpar\using.md"); // statements } // Equivalent to if (...) { using (FileStream f = new FileStream(@"C:\users\jaredpar\using.md")) { // statements } } docs: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/using
{ "language": "en", "url": "https://stackoverflow.com/questions/7524903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "190" }
Q: Logout functionality in android I am making a kind of social networking app. I am implementing log-out functionality in it. On Logout button click it should navigate to login screen but instead it is now navigating to the home page screen.I am using the following code for logout.. IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("com.package.ACTION_LOGOUT"); registerReceiver(new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { System.out.println("onReceive Log out in progress"); Intent intent1 = new Intent(getApplicationContext(), Login.class); startActivity(intent1); finish(); } }, intentFilter); A: use following for Logout. yourintent.setflag(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK); It may help you A: Simply give the intent to your login activity and put the flag in intent inten1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); it will clear all the activities and navigate to ur login page. A: This is a stack problem. You need to handle it. The best solution I found is that keep single activity in stack when your app runs and on log out only login screen will be in stack and if user presses back button, he will see Home screen. A: What worked for me is keeping track of your login state internally, using some sort of global: public boolean loggedin = false; and then in all your activities, override onResume() and finish() if you're logged out: @Override public void onResume() { super.onResume(); if (!loggedin) finish(); } A: Try this: Intent intent = new Intent(getApplicationContext(), Login.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); Toast.makeText(this, "Signed out", Toast.LENGTH_SHORT).show(); startActivity(intent); finish(); A: First make these changes to your code Intent intent = new Intent(getApplicationContext(),Login.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); Then remove finish(); written inside your broadcast receiver. Best of luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: jQuery plugin default options prefix, string combine I'm wring a jQuery plugin, and I want the divs created inside of the plugin can be customized the ids, which i mean: this is what i've done: (function($) { $.fn.plugin = function (options) { var defaults = { box_id = "nos-box_id", shoes_id = "nos-shoes_id" } ... ... ... return this; })(jQuery); and i want this: (function($) { $.fn.plugin = function (options) { var defaults = { plugin_prefix = "nos-", box_id = _somethinghere_ + "box_id", shoes_id = _somethinghere_ + "shoes_id" } ... ... ... return this; })(jQuery); to make "somethinghere" equals to defaults.plugin_prefix(in this case, "nos"). can anybody help me figure this out? Thx ! A: Don't build the id attributes until you have the prefix in hand. Leave plugin_prefix in your defaults but move box_id and shoes_id to somewhere else. $.fn.plugin = function (options) { var defaults = { plugin_prefix: "nos-", // other options ... }; options = $.extend({ }, options, defaults); var ids = { box_id: options.plugin_prefix + "box_id", shoes_id: options.plugin_prefix + "shoes_id", pancakes_id: options.plugin_prefix + "pancakes_id", // other ids you may need... }; //...
{ "language": "en", "url": "https://stackoverflow.com/questions/7524908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Shortcut key to close Immediate window in visual studio 2010 What is the shortcut key to close Immediate window in Visual Studio 2010. I open it using Ctr+Alt+I I want to close it using shortcut key with dock mode. A: Shift + Esc This is the correct answer. It's already in several comments. A: Press CTRL+F4 to close the immediate window (close any document window or e.g. a tab). A: Pressing Escape one or more times will take you back to the active code-window. A: There is way to do it via window menu: Alt + -, H
{ "language": "en", "url": "https://stackoverflow.com/questions/7524912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Copy File from UNC Path Server - Using Delphi 7 Services I created one service which is running in one server and I need to copy directory from another server to directory in this server through this service. The service is failed when finding directory specified in another server. Like If DirectoryExists("\\ServerName\DirectoryName"). It is not working even, I set up the service with Network Authority. Please give solution for this. It will be helpful. Mallik. A: A possible explanation is that the service runs as a user that does not have read rights to the other server's volumes. Authenticating with NETWORKSERVICE does not help you. That's just a user that has access to TCP etc. What you need to do is to run your service as a user which has read access to the other server's volumes. As a test try your personal login, but in the longer run you may wish to use a dedicated user just for this task.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: issue in excel exporting with chrome12 I have a asp.net web application which exports the data into an excel sheet. This function is perfectly working in firefox, IE and chrome5.XX But not in chrome 12.XXX.. it generated the file as report.aspx insted of report.xls. any idea..? Thanks in advance. A: Even I had the same problem and it is working fine with the below code: Response.AddHeader("Content-Disposition", "attachment;filename=FileName.xls");
{ "language": "en", "url": "https://stackoverflow.com/questions/7524919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I zip files programmatically in iOS? Possible Duplicate: Zip and UnZip a file programmatically in iphone? I want to zip images and audio programmatically in my app. How can I do that? A: Try ZipKit. Put this as part of your build and then #import <ZipKit/ZipKit.h> After this you are good to go.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is my WCF client timing out after calling a method in the WCF server that raises an event? I have a WCF service hosted within a Windows service. There is s method in the WCF service that will raise an event that the Windows service subscribes to. When the event is raised and the Windows service catches it, the Windows service calls another WCF method to send a message to all connected clients. For some reason when I have all these these happen in this sequence an error is thrown: This request operation sent to http://localhost:8731/Design_Time_Addresses/WCF/WCFService/ did not receive a reply within the configured timeout (00:00:29.9939996).... Here is the relevant code from teh WCF service: public event EventHandler<CustomEventArgs> CustomEvent; private static readonly List<IMessageCallback> subscribers = new List<IMessageCallback>(); public void SendMessageToClients(string msgType, string message) { subscribers.ForEach(delegate(IMessageCallback callback) { if (((ICommunicationObject)callback).State == CommunicationState.Opened) { callback.OnMessageReceived(msgType, message, DateTime.Now); } else { subscribers.Remove(callback); } }); } public bool messageHost() { try { if (CustomEvent != null) CustomEvent(null, new CustomEventArgs()); return true; } catch { return false; } } And the Code from the Windows service: wcfService = new WCF.WCFService(); sHost = new ServiceHost(wcfService); wcfService.CustomEvent += new EventHandler<WCF.CustomEventArgs>(wcfService_CustomEvent); sHost.Open(); private void wcfService_CustomEvent(object source, WCF.CustomEventArgs e) { wcfService.SendMessageToClients("log", "CLient connected!!"); osae.AddToLog("client message"); //just writes to a log file } And the client just calls this: wcfObj.messageHost(); Here is the client config: <system.serviceModel> <bindings> <wsDualHttpBinding> <binding name="WSDualHttpBinding_IWCFService" closeTimeout="00:00:10" openTimeout="00:00:10" receiveTimeout="00:10:00" sendTimeout="00:00:30" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <reliableSession ordered="true" inactivityTimeout="00:10:00" /> <security mode="Message"> <message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" /> </security> </binding> </wsDualHttpBinding> </bindings> <client> <endpoint address="http://localhost:8731/Design_Time_Addresses/WCF/WCFService/" binding="wsDualHttpBinding" bindingConfiguration="WSDualHttpBinding_IWCFService" contract="WCFService.IWCFService" name="WSDualHttpBinding_IWCFService"> <identity> <dns value="localhost" /> </identity> </endpoint> </client> And the service config: <system.serviceModel> <services> <service name="WCF.WCFService" behaviorConfiguration="WCFBehavior"> <endpoint address="" binding="wsDualHttpBinding" contract="WCF.IWCFService"> <identity> <dns value="localhost" /> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration="" contract="IMetadataExchange"/> <host> <baseAddresses> <add baseAddress="http://localhost:8731/Design_Time_Addresses/WCF/WCFService/" /> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior name="WCFBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> If I remove the SendMessageToClients call from the event in the Windows service it works and just logs the 'client message' as expected. Also, when the error is thrown about the timeout I can click continue and the the client continues to run and it received the message from the host. Why is the strange behavior happening? EDIT: Marc led me to search in the right place: http://www.codeproject.com/KB/WCF/WCF_Duplex_UI_Threads.aspx A: The symptoms here suggest to me like there is a deadlock happening, perhaps due to a sync-context (WCF respects sync-context by default). Meaning: the outward message is waiting on access to the context, but it is itself the thing that the existing context is waiting on. The easiest way to investigate that would be to perform the outward message on a worker thread: ThreadPool.QueueUserWorkItem(delegate { wcfObj.messageHost(); }); I believe you can also configure WCF to change how it approaches sync-context, but I can't remember how...
{ "language": "en", "url": "https://stackoverflow.com/questions/7524927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Annotation based ApplicationContext I understand that the ApplicationContext can be annotation based in Spring 3. Can anybody please share an example , so that I could refer the same. Thanks in advance, Vivek EDIT - This is the XML configuration: <context:annotation-config /> <context:component-scan base-package="com.test" /> <mvc:annotation-driven /> <bean id="dataSource" destroy-method="close" class=org.apache.commons.dbcp.BasicDataSource "> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test" /> <property name="username" value="test" /> <property name="password" value="test" /> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="mapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.test.Mapper" /> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="dao" class="com.test.MapperDao"> <property name="mapper" ref="mapper" /> </bean> <bean id="Controller" class="com.test.Controller" /> A: I have been through the Spring 3 Documentation and understood the @Configuration annotation. So issue resolved :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7524936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change application type with Mono.Cecil? How can I modify an application from Console Application Type to Windows Application Type and vice versa with Mono.Cecil? A: To convert a console .exe to windows .exe, you can use: var file = "foo.exe"; var module = ModuleDefinition.ReadModule (file); // module.Kind was previously ModuleKind.Console module.Kind = ModuleKind.Windows; module.Write (file); The other way around is as simple as choosing the appropriate ModuleKind value. From Cecil's source: public enum ModuleKind { Dll, Console, Windows, NetModule, } A: For people who needed more help on this like me :) you may need the apt pacakge libmono-cecil-cil-dev //mono-cecil-set-modulekind-windows.cs using System; using Mono.Cecil; namespace CecilUtilsApp { class CecilUtils { static void Main(string[] args) { var file = args[0]; var module = ModuleDefinition.ReadModule (file); module.Kind = ModuleKind.Windows; module.Write (file); } } } // ----- //Makefile //mono-cecil-set-modulekind-eq-windows.exe: // mcs $(shell pkg-config --libs mono-cecil) ./mono-cecil-set-modulekind-windows.cs ./mono-cecil-set-modulekind-windows.exe myprog.exe
{ "language": "en", "url": "https://stackoverflow.com/questions/7524938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Set cookies before subsequent requests in IE I'm trying to set some cookies (via javascript) before the browser makes a request for various resources lower on the page. The following works in Chrome/Firefox, but, not IE: [some_page.html] <!doctype html> <head> <script> var hash=new Date(); document.cookie='hash=' + hash + ';'; console.log("From page: " + hash); </script> <script src="/test_cookie.php"></script> </head> <body></body> </html> [test_cookie.php] console.log('From script: <?=$_COOKIE['hash']?>'); When viewing some_page.html, I see the following in the console (in Chrome/Firefox): "From page: 1316757967982" "From script: 1316757967982" Are there any tricks to get this to work in IE? Like setting defer on the test_cookie.php script tag, or, something else along those lines...? Thanks! A: You could dynamically generate the second script tag and inject it into the page so there's no way it could start before you had set the cookie. Then, if you're going to dynamically generate the script tag, it might actually be even better to add "?hash=1316757967982" onto the end of the test_cookie.php src URL so you could be guaranteed that your server gets the hash value (from the URL rather than the cookie). Then, you don't have to rely on cookie vs. script timing. Here's how you dynamically add a script tag: function addScriptTag(url) { var s = document.createElement(’script’); s.type=’text/javascript’; s.src= url; document.getElementsByTagName(’head’)[0].appendChild(s); } addScriptTag("/test_cookie.php?hash=" + new Date()); There is no contract with the browser that it won't start loading multiple scripts at the same time, there's only a contract that it will execute statically defined scripts in sequential order so I don't think your current approach is ever guaranteed to work. Loading multiple scripts in parallel could easily be a desired browser speedup option.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: what's the overhead of passing python callback functions to Fortran subroutines? I just wrapped a Fortran 90 subroutine to python using F2PY. The subtlety here is that the Fortran subroutine aslo takes a python call-back function as one of its arguments: SUBROUTINE f90foo(pyfunc, a) real(kind=8),intent(in) :: a !f2py intent(callback) pyfunc external pyfunc !f2py real*8 y,x !f2py y = pyfunc(x) !*** debug begins*** print *, 'Start Loop' do i=1,1000 p = pyfunc(a) end do total = etime(elapsed) print *, 'End: total=', total, ' user=', elapsed(1), ' system=', elapsed(2) stop !*** debug ends *** The pyfunc is a python function defined elsewhere in my python code. The wrapper works fine, but running the wrapped version above, I got an elapsed time about factor of 5 times longer than what I can get using pure python as follows, def pythonfoo(k): """ k: scalar returns: scalar """ print('Pure Python: Start Loop') start = time.time() for i in xrange(1000): p = pyfunc(k) elapsed = (time.time() - start) print('End: total=%20f'% elapsed) So, the question is, what is the overhead coming from? I really want to leave pyfunc as is because it is extremely time-consuming to re-code it into pure fortran function, so is there any way to improve the speed of the wrapper module? A: In the code you posted, a is double precision float. Passing it from Fortran to Python means wrapping the Fortran double to a PyFloat object, which does have a cost. In the pure Python version, k is a PyFloat and you don't pay the price for wrapping it 1000 times. Another issue is the function call itself. Calling Python functions from C is already bad performance-wise, but calling them from Fortran is worse, because there is an additional layer of code to transform the Fortran function call conventions (regarding the stack etc.) to C function call conventions. When calling a Python function from C, you need to prepare the arguments as Python objects, generally create a PyTuple object to serve as the *args argument of the Python function, make a lookup in the table of the module to get the function pointer... Last but not least: you need to take care of the array orders when passing 2D arrays between Fortran and Numpy. F2py and numpy can be smart in that regard, but you'll get performance hits if your Python code is not written to manipulate the arrays in Fortran order. I don't know what pyfunc is meant to do, but if it is close to what you posted, writing the loop in Python, and calling the function only once will save you time. And if you need the intermediate values (p), let your Python function return a Numpy array with all the intermediate values.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: SQL + ASP.Net Efficient paging My method of paging is inefficient as it calls the same query twice therefore doubling the query time. I currently call the 1 query that joins about 5 tables together with XML search querys to allow for passing List from ASP.net.. then I need to call exactly the same query except with a Count(row) to get the amount of records For Example (I have removed bits to make it easier to read) Main Query: WITH Entries AS ( select row_number() over (order by DateReady desc) as rownumber, Columns..., from quote join geolookup as Pickup on pickup.geoid = quote.pickupAddress where quote.Active=1 and //More ) select * from entries where Rownumber between (@pageindex - 1) * @pagesize + 1 and @pageIndex * @pageSize end Count Query: select count(rowID) from quote join geolookup as Pickup on pickup.geoid = quote.pickupAddress where quote.Active=1 and //More ) A: You can set an output parameter which will hold the number of rows from the first query. You could do something like WITH Entries AS ( select row_number() over (order by DateReady desc) as rownumber, Columns..., from quote join geolookup as Pickup on pickup.geoid = quote.pickupAddress where quote.Active=1 and //More ) select @rowcount = max(rownumber) from entries select * from entries where Rownumber between (@pageindex - 1) * @pagesize + 1 and @pageIndex * @pageSize Hope this helps A: You could select the results of your big query into a temp table, then you could query this table for the row number and pull out the rows you need. To do this, add (after your select statement and before the from) INTO #tmpTable Then reference your table as #tmpTable select row_number() over (order by DateReady desc) as rownumber, Columns..., into #tmpTable from quote join geolookup as Pickup on pickup.geoid = quote.pickupAddress where quote.Active=1 and //More ) SELECT @Count = COUNT(*) FROM #tmpTable select * from #tmpTable where Rownumber between (@pageindex - 1) * @pagesize + 1 and @pageIndex * @pageSize
{ "language": "en", "url": "https://stackoverflow.com/questions/7524942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: entity framework navigation property to table in different db I have 2 tables in different db db1..Towns id Nazv db2..MathchedTown id t_id d_name They are joined by по Towns.id = MathchedTown.t_id This EF classes: [Table("Towns")] public class Town { [Key] public int id { get; set; } public string Nazv { get; set; } } [Table("MathchedTown")] public class mTown { [Key] public int id { get; set; } [Required] public string t_id{ get; set; } [Required] public string d_name{ get; set; } [ForeignKey("t_id")] public virtual Town town { get; set; } } when i try to get item.town.nazv i get error: Invalid object name 'dbo.Towns'. If i change [Table("Towns")] to [Table("db1.dbo.Towns")], then appear almost the same error: Invalid object name 'dbo.db1.dbo.Towns'. That all errors are SqlExceptions How i can talk EF4 don't substite the "dbo." prefix? A: Entity framework does not support multiple databases in a single context. But it supports multiple schemas in a single database. If you do not specify the schema it will assume dbo. [Table("Towns", "MySchema")] public class Town You can specify the schema as above. If you want to use a table in a different database you can create a view to that table in your database. But it will be read only. A: Unfortunately EF4 does not support navigation property that is in other db. You have two choices. One, create a stored procedure and import it as a function in edm. And genetate complex type for the return result. Two, create two entity models for each database. And run a query for a database then run the other query to the other database with where clause from the first query result.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524946", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: starting text in uitextview from center both horizontally and vertically I want to begin text entered into UItextview from center both horizontally and vertically, please some one help me. A: set Alignment as center.for that select the textfield from .xib class and go to the library and in that set Alognment as center.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }