text
stringlengths
8
267k
meta
dict
Q: Comparing DateTime values in SelectCommand I am working on ASP.net application with a MS Access database.I want to only display those list of entries whose DateTime value is greater than the present date and time. I am having difficulty in comparing in SelectCommand, as to how to pass the datetime parameter. My code is as follows: ` SelectCommand="SELECT `ID`, `eventname`, `description`, `venue`, `coordinator`, `time` FROM `upcoming` ORDER BY `time` WHERE (`time`&gt;=?)" UpdateCommand="UPDATE `upcoming` SET `eventname` = ?, `description` = ?, `venue` = ?, `coordinator` = ?, `time` = ? WHERE `ID` = ?"> <UpdateParameters> <asp:Parameter Name="eventname" Type="String" /> <asp:Parameter Name="description" Type="String" /> <asp:Parameter Name="venue" Type="String" /> <asp:Parameter Name="coordinator" Type="String" /> <asp:Parameter Name="time" Type="DateTime" /> <asp:Parameter Name="ID" Type="Int32" /> </UpdateParameters> <SelectParameters> <asp:Parameter Name="time" Type="DateTime" PropertyName="Text" /> </SelectParameters> </asp:AccessDataSource>` Please tell me how can i pass the datetime value to the SelectParameters through this code. Thank You for looking in it. A: you should use SELECT ID, eventname, description, venue, coordinator, [time] FROM upcoming WHERE time > NOW() ORDER BY time NOW() is a builtin function in Access, so you don't need to pass it to the query
{ "language": "en", "url": "https://stackoverflow.com/questions/7529436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python - Access protected network resource I need to open a file on my local network from a Python script. In the basic case is very simple: fh = open('\\servername\path\resource.txt', 'r') ... The problem is that the access to this network resource is protected. I tried something like: fh = open('\\servername\path\resource.txt@username:pass', 'r') but it doesn't work. Any idea? A: First of all, backslashes in Python need to be escaped, so your path string is '\\\\servername\\path\\resource.txt' # or .. r'\\servername\path\resource.txt' Python's open function has no support for passwords. You'll need to use windows functions to specify passwords. Here's an example program doing exactly that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: install php fork on ubuntu I'm trying to use fork in php for first time. when I use $pid = pcntl_fork(); if ($pid == -1) { die('could not fork'); } else if ($pid) { // we are the parent pcntl_wait($status); //Protect against Zombie children } else { // we are the child }(fork example in php.net) I will received following error.Server error The website encountered an error while retrieving http://localhost/fork.php. It may be down for maintenance or configured incorrectly. I think fork is not enable,so I donwload php5 source code and do ./configure --enable-pcntl make make install but I will get same error too. where is problem? A: execute phpinfo(); and see if pcntl is enabled.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What values need to be least selected to optimize indexes with database engine tuning advisor For MSSQL 2008 R2 database what values need to be selected minimum to find required indexes when profiler trace given to the database engine tuning advisor ? These are the values that can be selected at profiler http://img40.imageshack.us/img40/5274/minimumy.png I need to select lowest possible variable to record because profiler will run on product environment. I want database engine tuning advisor to find necessary indexes from this profiler recorded trace. So minimum which checkboxes need to be checked. A: If you want to feed your trace data into the Database Tuning Advisor, your best bet is to select the "Tuning" template in the trace properties dialog. This will set all of those selections for you and provide a trace that the DTA can use.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# ToCharArray does not work with char* I have the following struct: [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)] unsafe public struct Attributes { public OrderCommand Command { get; set; } public int RefID { get; set; } public fixed char MarketSymbol[30]; } Now, I want to write characters to the field MarketSymbol: string symbol = "test"; Attributes.MarketSymbol = symbol.ToCharArray(); The compiler throws an error, saying its unable to convert from char[] to char*. How do I have to write this? Thanks A: Like this: [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)] public struct Attributes { public OrderCommand Command { get; set; } public int RefID { get; set; } [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 30)] public string MarketSymbol; } Watch out for pack = 1, it is quite unusual. And good odds for CharSet.Ansi if this interops with C code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: iOS change accessibility focus Is there a way to set the accessibility focus programatically (App Store safe)? Any help will be greatly appreciated. A: To focus on element you can call. Swift: UIAccessibility.post(notification: .screenChanged, argument: self.myFirstView) ObjC: UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, self.myFirstView); Otherwise for iOS 8+ use the accessibilityElements to set element order and it will focus automatically on first element in the list self.accessibilityElements = @[myFirstView, mySecondButton, myThirdLabel] A: This is the Swift code: UIAccessibility.post(notification: .screenChanged, argument: <theView>) Example usage let titleLabel = UILabel() override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) UIAccessibility.post(notification: .screenChanged, argument: titleLabel) } A: extension UIAccessibility { static func setFocusTo(_ object: Any?) { if UIAccessibility.isVoiceOverRunning { DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { UIAccessibility.post(notification: .layoutChanged, argument: object) } } } } Add this extension and call it by passing in the view you would like to be focused. If you would like to change focus when navigating using a tabbar, you can call this from viewWillAppear. This code wont work in any init method without a the delay of 0.7 or more. A: UIAccessibility.post(notification: .layoutChanged, argument: toast) toast.becomeFirstResponder() toast.isAccessibilityElement = true toast.accessibilityTraits = .staticText //Traits option ie .header, .button etc toast.accessibilityLabel = "Accessibility label to be read by VoiceOver goes here" WHERE: * *toast is my UIView (a pop up which gets triggered upon particular scenario) *above code needs to be added to the toast View *this code will automatically change focus to pop up view (toast) and VoiceOver will read accessibilityLabel
{ "language": "en", "url": "https://stackoverflow.com/questions/7529464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "47" }
Q: Custom Grouping with Telerik Grid for MVC I wish to create a Telerik grid which can be grouped by different fields in the table, but I'm running into quite a problem - Telerik only allows me to designate a property to group by, and then that's it. What I want to do is to partly be able to designate the title of the group. Instead of "Current Index: 9" I might want to remove the property name (Current Index) and replace the number by getting the value for it in a dictionary. Also, say I want to sort by a date - Then I'll be wanting to sort only by year, month and day, and not by the full extent of the datetime down to the very last millisecond (results in separate groups for every object). Is there any way to achieve something like this at all? Thanks. A: I solved my conumdrum by using ClientTemplates (Ajax binding) and custom properties in my viewmodel.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Importing a class in Groovy I'm trying to import another class in groovy, but to no sucess so far. I've tried to run this example: http://www.chatsiri.com/?q=node/163 didn't work. Caught: groovy.lang.MissingPropertyException: No such property: readData A: There is a lot of typos in the Code, and it does not follow the Convention for the java classes like (and the article is from 2007): * *Class instead of class *Class name starting with lowercase *printIn? instead of println *System.In.readString()??? Not in the actual Groovy JDK Anyways, just creating new classes Foo and Bar to corraborate what the blog is saying..... File Bar.groovy class Bar{ def print(){ println "Bar" } def add(a, b){ return a+b; } } File Foo.groovy def b = new Bar() b.print() println b.add(1,2) Runing >groovy Foo.groovy Bar 3
{ "language": "en", "url": "https://stackoverflow.com/questions/7529476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Capistrano destroys ssh public key authorisation I am quite out of my depths with a problem that I have faced with two different ssh-users on two different servers where I deploy to with Capistrano. I am sure I am not the only one to have come across this: * *I set up an ssh-connection from the command line with passwordless authentication, using my public key, that is known to the remote server. This works: I can log into the remote system. *I execute »cap deploy:setup«. Surprisingly, I have to enter the password of the ssh-user, and from then I have to enter the password again each time I log into the server via ssh on the command line. The public key is not accepted any more, as shown by the output produced by ssh's -v option: _ shell$ ssh -vp 5222 my_ssh_user@my-remote-host.de OpenSSH_5.6p1, OpenSSL 0.9.8r 8 Feb 2011 debug1: Reading configuration data /etc/ssh_config debug1: Applying options for * debug1: Connecting to my-remote-host.de [1.2.3.4] port 5222. debug1: Connection established. debug1: identity file /Users/martin/.ssh/id_rsa type 1 debug1: identity file /Users/martin/.ssh/id_rsa-cert type -1 debug1: identity file /Users/martin/.ssh/id_dsa type -1 debug1: identity file /Users/martin/.ssh/id_dsa-cert type -1 debug1: Remote protocol version 2.0, remote software version OpenSSH_5.1p1 Debian-5ubuntu1 debug1: match: OpenSSH_5.1p1 Debian-5ubuntu1 pat OpenSSH* debug1: Enabling compatibility mode for protocol 2.0 debug1: Local version string SSH-2.0-OpenSSH_5.6 debug1: SSH2_MSG_KEXINIT sent debug1: SSH2_MSG_KEXINIT received debug1: kex: server->client aes128-ctr hmac-md5 none debug1: kex: client->server aes128-ctr hmac-md5 none debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP debug1: SSH2_MSG_KEX_DH_GEX_INIT sent debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY debug1: Host '[my-remote-host.de]:5222' is known and matches the RSA host key. debug1: Found key in /Users/martin/.ssh/known_hosts:9 debug1: ssh_rsa_verify: signature correct debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug1: SSH2_MSG_NEWKEYS received debug1: Roaming not allowed by server debug1: SSH2_MSG_SERVICE_REQUEST sent debug1: SSH2_MSG_SERVICE_ACCEPT received debug1: Authentications that can continue: publickey,password debug1: Next authentication method: publickey debug1: Offering RSA public key: /Users/martin/.ssh/id_rsa debug1: Authentications that can continue: publickey,password debug1: Trying private key: /Users/martin/.ssh/id_dsa debug1: Next authentication method: password my_ssh_user@my-remote-host.de's password: <here I enter my password> debug1: Authentication succeeded (password). Authenticated to my-remote-host.de ([1.2.3.4]:5222). debug1: channel 0: new [client-session] debug1: Requesting no-more-sessions@openssh.com debug1: Entering interactive session. debug1: Sending environment. debug1: Sending env LANG = de_DE.UTF-8 Linux ve2003 2.6.18-238.5.1.el5.028stab085.5 #1 SMP Thu Apr 14 15:42:34 MSD 2011 x86_64 The programs included with the Ubuntu system are free software; the exact distribution terms for each program are described in the individual files in /usr/share/doc/*/copyright. Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. To access official Ubuntu documentation, please visit: http://help.ubuntu.com/ Last login: Fri Sep 23 13:05:55 2011 from I am using Mac OS Lion locally and Ubuntu on the remote side. My Capistrano is extended by the multistage-extension. I have set set :ssh_options, {:forward_agent => true} and it works for the passwordless pulling of the git repository on the remote side. How can I prevent Capistrano to scrumble up my SSH settings and make it use public key auth again? Greatly appreciate any help! EDIT: The problem is Server-side: I just found out that I cannot use other systems to passwordless log into my remote system. How can I know what is wrong with the server?
{ "language": "en", "url": "https://stackoverflow.com/questions/7529486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: No session share and avoid navigation buttons in browser while opening application window We are using VBScript code to open the application window to avoid users having forward/back navigation while opening the IE8 window. This is the code used. Set WshShell = CreateObject("shell.application") Set IE=CreateObject("InternetExplorer.Application") IE.menubar = 1 IE.toolbar = 0 IE.statusbar = 0 'here we open the application url IE.navigate "http://www.google.com" IE.visible = 1 WshShell.AppActivate(IE) This is working fine, however the problem is that if the user opens multiple windows the session cookies are shared accross the windows. For this also there is a solution that we can use the nomerge option while opening the IE WshShell.ShellExecute "iexplore.exe", " -nomerge http://www.google.com", null, null, 1 Now we want both these options to be available. i.e user should not be able to navigate forward/backward and also if two windows are opened data should not be shared. We were not able to get both these things working together. Also we do not want any full screen mode(i.e after pressing F11) Can any one provide the solution? Thanks in advance. A: See the answers for this very closely related question: Launch Internet Explorer 7 in a new process without toolbars. There are a couple of workable options, one using Powershell, and one using some cludgy VBScript. A: From what I understand, cookies are set by instance. Multiple browser windows are still going to be the same instance. You might be able to pass in a sort of ID parameter that the program tracks, but the browser doesn't. That way regardless of how the program runs, it will have its own 'session' ID. I think you can do this with javascript, and reading it using a asp.net hidden field. This might give you the uniqueness you're looking for. <asp:HiddenField ID="HiddenFieldSessionID" runat="server" /> protected void Page_Load(object sender, EventArgs e) { HiddenFieldSessionID.Value = Session.SessionID; } <script type="text/javascript"> function ShowSessionID() { var Hidden; Hidden = document.getElementById("HiddenFieldSessionID"); document.write(Hidden.value); } </script> A: The solution mentioned in the link answered by patmortech is not perfect, as the cookies were still shared. So used the -nomerge option in the AppToRun variable which creates two processes when user opens the application twice in the single machine. In IE8 if two internet explorers are opened then they are merged into single process so the -nomerge option which opens the IE8 instances in difference processes. On Error Resume Next AppURL = "http://www.stackoverflow.com" AppToRun = "iexplore -nomerge" AboutBlankTitle = "Blank Page" LoadingMessage = "Loading stackoverflow..." ErrorMessage = "An error occurred while loading stackoverflow. Please close the Internet Explorer with Blank Page and try again. If the problem continues please contact IT." EmptyTitle = "" 'Launch Internet Explorer in a separate process as a minimized window so we don't see the toolbars disappearing dim WshShell set WshShell = WScript.CreateObject("WScript.Shell") WshShell.Run AppToRun, 6 dim objShell dim objShellWindows set objShell = CreateObject("Shell.Application") set objShellWindows = objShell.Windows dim ieStarted ieStarted = false dim ieError ieError = false dim seconds seconds = 0 while (not ieStarted) and (not ieError) and (seconds < 30) if (not objShellWindows is nothing) then dim objIE dim IE 'For each IE object for each objIE in objShellWindows if (not objIE is nothing) then if isObject(objIE.Document) then set IE = objIE.Document 'For each IE object that isn't an activex control if VarType(IE) = 8 then if IE.title = EmptyTitle then if Err.Number = 0 then IE.Write LoadingMessage objIE.ToolBar = 0 objIE.StatusBar = 1 objIE.Navigate2 AppURL ieStarted = true else 'To see the full error comment out On Error Resume Next on line 1 MsgBox ErrorMessage Err.Clear ieError = true Exit For end if end if end if end if end if set IE = nothing set objIE = nothing Next end if WScript.sleep 1000 seconds = seconds + 1 wend set objShellWindows = nothing set objShell = nothing 'Activate the IE window and restore it success = WshShell.AppActivate(AboutBlankTitle) if success then WshShell.sendkeys "% r" 'restore end if
{ "language": "en", "url": "https://stackoverflow.com/questions/7529492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Quotation real usages I faced with the 'quotation' term and I'm trying to figure out some real-life examples of usage of it. Ability of having AST for each code expression sounds awesome, but how to use it in real life? Does anyone know such example? A: F# and Nemerle quotations are both used for metaprogramming, but the approaches are different: Nemerle uses metaprogramming at compilation time to extend the language, while F# uses them at run time. Nemerle In Nemerle, quotations are used within macros for taking apart pieces of code and generating new ones. Much of the language itself is implemented this way. For example, here is an example from the official library — the macro implementing the when conditional construct. Nemerle does not have statements, so an if has to have an else part: when and unless macros provide shorthand for an if with an empty then and else parts, respectively. The when macro also has extended pattern-matching functionality. macro whenmacro (cond, body) syntax ("when", "(", cond, ")", body) { match (cond) { | <[ $subCond is $pattern ]> with guard = null | <[ $subCond is $pattern when $guard ]> => match (pattern) { | PT.PExpr.Call when guard != null => // generate expression to replace 'when (expr is call when guard) body' <[ match ($subCond) { | $pattern when $guard => $body : void | _ => () } ]> | PT.PExpr.Call => // generate expression to replace 'when (expr is call) body' <[ match ($subCond) { | $pattern => $body : void | _ => () } ]> | _ => // generate expression to replace 'when (expr is pattern) body' <[ match ($cond) { | true => $body : void | _ => () } ]> } | _ => // generate expression to replace 'when (cond) body' <[ match ($cond : bool) { | true => $body : void | _ => () } ]> } } The code uses quotation to handle patterns that look like some predefined templates and replace them with corresponding match expressions. For example, matching the cond expression given to the macro with: <[ $subCond is $pattern when $guard ]> checks whether it follows the x is y when z pattern and gives us the expressions composing it. If the match succeeds, we can generate a new expression from the parts we got using: <[ match ($subCond) { | $pattern when $guard => $body : void | _ => () } ]> This converts when (x is y when z) body to a basic pattern-matching expression. All of this is automatically type-safe and produces reasonable compilation errors when used incorrectly. So, as you see quotation provides a very convenient and type-safe way of manipulating code. A: Well, anytime you want to manipulate code programmatically, or do some metaprogramming, quotations make it more declarative, which is a good thing. I've written two posts about how this makes life easier in Nemerle: here and here. For real life examples, it's interesting to note that Nemerle itself defines many common statements as macros (where quotations are used). Some examples include: if, for, foreach, while, break, continue and using. A: I think quotations have quite different uses in F# and Nemerle. In F#, you don't use quotations to extend the F# language itself, but you use them to take an AST (data representation of code) of some program written in standard F#. In F#, this is done either by wrapping a piece of code in <@ ..F# code.. @>, or by adding a special attribtue to a function: [<ReflectedDefinition>] let foo () = // body of a function (standard F# code) Robert already mentioned some uses of this mechanism - you can take the code and translate F# to SQL to query database, but there are several other uses. You can for example: * *translate F# code to run on GPU *translate F# code to JavaScript using WebSharper A: As Jordão has mentioned already quotations enable meta programming. One real world example of this is the ability to use quotations to translated F# into another language, like for example SQL. In this way Quotations server much the same purpose as expression trees do in C#: they enable linq queries to be translated into SQL (or other data-acess language) and executed against a data store. A: Unquote is a real-life example of quotation usage.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I order groups alphabetically? It may be a bit more complicated then that, but here goes. This report lists overtime on a weekly basis. Each driver has worksheets that outline details of a given shift. The user selects a period of a week, and I have some formulas that fill variables with their hours worked for each day of the week. The lines look something like this: CKL09844 - LATTA   Scott    9.5   8.6    10.5    11     0 hourlysum, etc. The records are grouped by the 'Driver ID' - the first field - but I'd like to have them listed in alphabetical order. Only the group footers are being displayed currently. Anyone have any advice? Edit: List them alphabetically by last name, that is. A: You can either * *Change the group to the 'LastName, FirstName' field or fields instead of driverID or *Use a summary to sort the group. You can do this by inserting a summary like maximum({table.name},{table.driverID}) and placing it in the footer and then suppressing it (It's stupid but Crystal needs this field actually in the report before it will allow you to access the next step). Then, go to "Report -> Group Sort Expert -> For this group sort: All" and select the summary you just made.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Implement DataTemplate DependencyProperty in UserControl I'm trying to make an intertia touch scrolling list in a UserControl in Silverlight 4 using Expression Blend 4. I've already made the dependency properties in my UserControl which i want to work like the ListBox does. ItemSource is the list of objects i want to show in my list and datatemplate is the way it should be shown. How do i deal with these properties inside my UserControl? I have a StackPanel where all the datatemplates should be added showing the data ofc. How do i apply the data in my IEnumerable to the DataTemplate when looping through the ItemSource to add them to the list (StackPanel). public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(InertiaScrollBox), null); public IEnumerable ItemsSource { get{ return (IEnumerable)GetValue(ItemsSourceProperty); } set{ SetValue(ItemsSourceProperty, value); } } public static readonly DependencyProperty ItemTemplateProperty = DependencyProperty.Register("ItemTemplate", typeof(DataTemplate), typeof(InertiaScrollBox), null); public DataTemplate ItemTemplate { get { return (DataTemplate)GetValue(ItemTemplateProperty); } set { SetValue(ItemTemplateProperty, value); } } This was kinda hard to explain but hope you understand otherwise please ask. Thanks in advance A: Dependency properties are rather useless if to not handle their changes. At first you should add PropertyChanged callbacks. In my example I add them inline and call the UpdateItems private method. public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(InertiaScrollBox), new PropertyMetadata((s, e) => ((InertiaScrollBox)s).UpdateItems())); public static readonly DependencyProperty ItemTemplateProperty = DependencyProperty.Register("ItemTemplate", typeof(DataTemplate), typeof(InertiaScrollBox), new PropertyMetadata((s, e) => ((InertiaScrollBox)s).UpdateItems())); Then you can call the LoadContent method of the DataTemplate class and set an item from the ItemsSource as the DataContext to the returned visual element: private void UpdateItems() { //Actually it is possible to use only the ItemsSource property, //but I would rather wait until both properties are set if(this.ItemsSource == null || this.ItemTemplate == null) return; foreach (var item in this.ItemsSource) { var visualItem = this.ItemTemplate.LoadContent() as FrameworkElement; if(visualItem != null) { visualItem.DataContext = item; //Add the visualItem object to a list or StackPanel //... } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7529501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Task Pattern for Java Web Applications It's pretty common to see some flavor of the Task Pattern implemented on enterprise Swing applications. It just makes sense: you'll have a lot of complex user commands that may take (differing) long periods of time to complete, and you can't expect your users to just sit there and wait. But what about its practicality in a dynamic web application? Say I've got some web app that is heavily-based in AJAX so that users can issue all sorts of commands all over the page , and each of those commands get sent as standalone requests back to the server. Is the task pattern an appropriate "request handling mechanism" for such an application, or are todays web containers so advanced & multi-threaded that doing so would be overkill? Thanks in advance for any input! A: I'm using @Sanjay T. Sharma's response as an answer. I'm doing this because I like to have an acceptance rate of 100% and it's pretty obvious that for some reason he/she does not want to answer this question. (Sanjay's) Answer: "...things which don't demand instant feedback to the user are better off being handled on independent servers/services while the "web container" can focus on serving web clients. Carrying on with your example, when the answer is accepted, the updation of "accept rate" isn't exactly "sent back" to the client after it finishes but is reflected in the underlying data store asynchronously which is showed to the user the next time a response is created for the user."
{ "language": "en", "url": "https://stackoverflow.com/questions/7529504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Drupal 7 example module, page not found, why? I wrote a simple test module example, 2 files, test.module, test.info, and enabled them in drupal 7 modules. I cleared all the cache, and still when i'm trying to go to localhost/drupal/hello , i get drupal 404 page not found, why is that? Here is my code: <?php function test_world_help($section) { switch ($section) { case 'admin/help#hello_world': $output = '<p>Hello world help...</p>'; return $output; case 'admin/modules#description': return 'Hello world module description...'; } } function test_world_menu($may_cache) { $items = array(); if ($may_cache) { } else { $items['hello'] = array( 'title' => 'Hello world page...', 'callback' => 'test_world_page', 'access' => TRUE, 'type' => MENU_CALLBACK ); } return $items; } function test_world_page() { return '<p>Hello world!</p>'; } A: You have posted almost the same question once and twice before. Why don't you update the original one instead of posting new ones? * *The hook_menu() does not have the $may_cache argument in Drupal 7. You should remove it. However, it should not solve your problem as it is unset and false. Thus, the $items should still be populated. *It is correct, as jprofitt says, that you should change 'callback' to 'page callback'. *There is no such thing as 'access', but there is 'access callback' and 'access arguments'. You are most likely looking for 'access callback'. However, you can't just set it to 'true'. It expects a function name which returns either 'true' or 'false'. It defaults to 'user_access', so you should just leave it that way. However, you might want to set 'access arguments' to something like 'access content'. Does the following piece of code work better? function test_world_menu() { $items = array(); $items['hello'] = array( 'title' => 'Hello World!', 'page callback' => 'test_world_page', 'access arguments' => array('access content'), 'type' => MENU_CALLBACK ); return $items; } It seems that you haven't really had a look at the documentation. I might be wrong. However, the documentation at api.drupal.org is always a good start to look when you want to learn the basics of how something work. A: You should probably change 'callback' to 'page callback', as I don't believe hook_menu() has just a plain "callback" option. And since you're working with Drupal 7, its hook_menu() actually doesn't have parameters. A: Uninstall and reinstall your custom module. I hope this will help you. Because it's necessary for drupal core to know the newly created path created using hook_menu.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: aix java core zero size in my AIX 6.1 ,java 1.5.0 bash-3.2$ java -fullversion java full version "J2RE 1.5.0 IBM AIX build pap32devifx-20080811c (SR8a)" bash-3.2$ i am getting core by running java . but i see the size of core file is zero. i set ulimit -c unlimited and here below are deatils -rw-r--r-- 1 vyellepe rdl 54763 Sep 23 08:43 management_demo_client.log -rwx------ 1 root system 0 Sep 23 08:43 core.20110923.084309.1339644.dmp bash-3.2$ bash-3.2$ bash-3.2$ ulimit -a core file size (blocks, -c) unlimited data seg size (kbytes, -d) unlimited file size (blocks, -f) 1048575 max memory size (kbytes, -m) 32768 open files (-n) 2000 pipe size (512 bytes, -p) 64 stack size (kbytes, -s) 32768 cpu time (seconds, -t) unlimited max user processes (-u) 1024 virtual memory (kbytes, -v) unlimited bash-3.2$ can you help what needed to be set to get the core file A: Not too much versed about ulimit on AIX, but seems memory limit: max memory size (kbytes, -m) 32768 Seems not sufficient for Java JVM, so try increasing it. Typical JVM memory for a production server could stert at 512MB. Post about problem with memory limit in AIX 6.1 after rebooting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Run script when someone inserts or updates a row in certain Table I am using MYSQL under ubuntu. I want to run a certain program automatically when inserting or updating row in a certain table. The program is actually sending request to a php on the same server. The php script is implemented and it notifies all clients that "data is updated, please get it". How can I do it? Thank You A: best solution is create cron job and use system command in cron file. A: If you have control of the script, the easiest way would be to create your own query() method that wraps around whatever SQL query call you need to make. You can put something in there to see if there's an UPDATE/DELETE/INSERT and if so fire off your "data updated" notice. A: Probably cannot be done without major security issues on mysql server. you could to this from php. either execute the program when you send the query to mysql or create a cronjob
{ "language": "en", "url": "https://stackoverflow.com/questions/7529519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using MessagePack with Android Has someone tried to use MessagePack with an Android app? Is it possible? I have tried to use the Jar from msgpack-java and received the following Exception: Caused by: java.lang.ExceptionInInitializerError at org.msgpack.Packer.pack(Packer.java:532) at org.msgpack.MessagePack.pack(MessagePack.java:31) ... 15 more Caused by: java.lang.ExceptionInInitializerError at org.msgpack.template.TemplateRegistry.<clinit>(TemplateRegistry.java:38) ... 17 more Caused by: java.lang.VerifyError: org.msgpack.template.BeansFieldEntryReader at org.msgpack.template.builder.BeansTemplateBuilder.<init (BeansTemplateBuilder.java:42) at org.msgpack.template.builder.BuilderSelectorRegistry.initForJava(BuilderSelectorRegistry.java:73) at org.msgpack.template.builder.BuilderSelectorRegistry.<clinit>(BuilderSelectorRegistry.java:38) ... 18 more The code that I use is very simple PrintWriter out = new PrintWriter(socket.getOutputStream()); Message msg = new Message(); msg.body = "asdasdasd"; msg.from = "qwe"; msg.to = "ttt"; byte[] bytes = MessagePack.pack(msg); out.print(bytes); out.flush(); I have javassist.jar, msgpack-0.5.2.jar, slf4j-api-1.6.2.jar and slf4j-jdk14-1.6.2.jar in my lib directory. In my server application this code works fine with the same libraries. A: (Hopefully) FINAL UPDATE msgpack : 0.6.8 works on Android without any problems msgpack-rpc : 0.7.0 works on Android with one caveat. Specifically, you need to add the following to onCreate for API Level 8 (Android 2.2.1), and possibly lower: java.lang.System.setProperty("java.net.preferIPv4Stack", "true"); java.lang.System.setProperty("java.net.preferIPv6Addresses", "false"); due to this bug. If you want to see a simple example, here's a pair of projects set up for this purpose: * *https://github.com/mikkoz/msgpack-android-test-server/tree/master/msgpack-android-test-server *https://github.com/mikkoz/msgpack-android-test-client/tree/master/msgpack-android-test-client Previous Versions UPDATE: as of 0.6.7 msgpack should be compatible with Android (there is a small dependency exclusion issue). Check the text below for msgpack-rpc (which also might be adapted in the future). NOTE: If you're also using msgpack-rpc, you need to do the following steps: * *Download the msgpack-rpc source from git://github.com/msgpack/msgpack-rpc.git (specifically, the "java" folder). *Change the main msgpack artifact version to the one you've built. *In org.msgpack.rpc.loop.netty.NettyEventLoop, change the NioClientSocketChannelFactory to OioClientSocketChannelFactory(getWorkerExecutor()). *Build the MessagePack-RPC in the same way as in the case of the main MessagePack JAR (see Step 11 above). The NettyEventLoop replacement is due to this issue: http://markmail.org/message/ypa3nrr64kzsyfsa . Important: I've only tested synchronous communication. Asynchronous might not work. And here's the reason for msgpack not working with Android prior to 0.6.7: The reason for the error is that MessagePack uses several java.beans classes that are not included in the Android SDK. You're probably using the MessagePackBeans annotation. This is a similar problem to the one described here, for which the general solution is outlined here. Unfortunately, in our case it requires a rebuild of msgpack. Here's what I did (you can almost certainly skip Steps 5 and 8, but I haven't tried it that way) : * *Download the MessagePack source from https://github.com/msgpack/msgpack-java.git. *Import the MessagePack source as a project in your IDE. *Download the Apache Harmony source for the relevant packages from http://svn.apache.org/repos/asf/harmony/enhanced/java/trunk/classlib/modules/beans/src/main/java . *Copy these packages into your MessagePack project's src/main/java folder: * *java.beans *java.beans.beancontext *org.apache.harmony.beans *org.apache.harmony.beans.internal.nls *In your MessagePack project, remove the following classes: * *PropertyChangeListener *IndexedPropertyChangeEvent *PropertyChangeEvent *PropertyChangeListenerProxy *PropertyChangeSupport *Rename the java.beans packages to something different, e.g. custom.beans . *Change all java.beans references to the renamed ID, so again e.g. custom.beans. This applies especially to BeansFieldEntryReader (this class is the reason for the original error). *Change the custom.beans references for the five classes you removed in Step 5 back to java.beans. *In the org.apache.harmony.beans.internal.nls.Messages class, comment out the method setLocale, and remove the imports associated with it. *Remove all classes that still have errors, except Encoder. In that class, comment out all references to the classes you've removed. You should now have an error-free project. *Build the MessagePack JAR: * *If you're using Maven, change the version in the pom.xml to something unique, run Maven build with the install goal, then add the dependency in your Android project with that version. *If you're not using Maven, you have to run the jar goal for Ant with the included build.xml. Replace the msgpack JAR in your Android project with this one. *If you're publishing your app, remember to include the relevant legal notice for Apache Harmony. It's an Apache License, just like MessagePack. That should do it. Using your example code, and my own data class, I was successfully able to pack and unpack data. The entire renaming ritual is due to the fact that the DEX compiler complains about java.* package naming. A: There is a critical msgpack bug saying data packed with msgpack will get corrupted on the Dalvik VM. http://jira.msgpack.org/browse/MSGPACK-51 A: There is an ongoing effort by @TheTerribleSwiftTomato and the MessagePack core team to get MessagePack working on Android, please see the related GitHub issue. The fix mentioned in @TheTerribleSwiftTomato's answer is to be found here. Update I've managed to get it at least running on Android by (painstakingly) adding all the necessary javassist Classes which are currently required for the build to succeed. An extra 600KB gain in size, yet at least it seems to work. All in all, it appears to be working to some extent on Android, eventually check out the lesser-known resources about Message Pack such as its User Group and its Wiki for more information. On a side-note, be sure to use a HTTP Request Library (such as LoopJ's Android Async HTTP or Apache's HttpClient) which can handle binary data. Last but not least you can ping me if there is interest in this jar which makes MessagePack seemingly work on Android – credits go out of course to @TheTerribleSwiftTomato who supplied the fix above! A: I suggest you write this in the main proguard-rules file- -dontwarn org.msgpack.** -keep class org.msgpack.** { *; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7529522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Keep the scrollbars hidden in a Delphi dbgrid (even on resize) For our dbgrid we want the scrollbars to be constantly hidden. Since TDBGrid doesn't have a 'scrollbars' property, we use: ShowScrollBar(DBGrid1.Handle, SB_VERT, False); ShowScrollBar(DBGrid1.Handle, SB_HORZ, False); However when we resize the window (and the panel containing the dbgrid), for a second the scrollbars appear and becom hidden again only after recalling the two above methods. A solution is to call these methods in DrawColumnCell, but this causes flickering of the dbgrid, even with DoubleBuffered set to true. Is there any way to hide the scrollbars permanently? Thanks in advance! A: Hiding the scrollbar of the TDBGrid in CreateParams has a very short time effect. There's the procedure UpdateScrollBar which causes the scrollbar to be visible. It happens because the scroll bar visibility is controlled depending on the data displayed, thus this procedure is called whenever the data is changed. And since this procedure is called whenever the scrollbar needs to be updated and because it's virtual, it's time to override it. The following code sample uses the interposed class, so all TDBGrid components on the form which belongs to this unit will behave the same: unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs; type TDBGrid = class(DBGrids.TDBGrid) private procedure UpdateScrollBar; override; end; type TForm1 = class(TForm) DBGrid1: TDBGrid; private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TDBGrid.UpdateScrollBar; begin // in this procedure the scroll bar is being shown or hidden // depending on data fetched; and since we never want to see // it, do just nothing at all here end; end. A: The scroll bar is updated in TDBGrid.UpdateScrollBar. Unfortunately this routine is not virtual (in D7 at least). Within that routine, SetScrollInfo is called, a Windows function that doesn't send any message that could be intercept. No luck there. The only possibility left is to override the message handler for the message that is send whenever the control changed size: type TDBGrid = class(DBGrids.TDBGrid) private procedure WMWindowPosChanged(var Message: TWMWindowPosChanged); message WM_WINDOWPOSCHANGED; end; procedure TDBGrid.WMWindowPosChanged(var Message: TWMWindowPosChanged); begin inherited; Windows.ShowScrollBar(Handle, SB_VERT, False); end; Although UpdateScrollBar is also called when the data is changed or when the dataset's Active property changes, this seems to work here without flickering. A: Perhaps overriding CreateParams() method and removing WS_HSCROLL and WS_VSCROLL bits form Params.Style makes difference. You could try to do it with class helper if you don't want to write custom descendant. You could also use SetWindowLongPtr API with GWL_STYLE to change window's style but then the changes are lost when grid's window is recreated for some reason (so it's not as reliable than overriding CreateParams).
{ "language": "en", "url": "https://stackoverflow.com/questions/7529524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Existing Pages as Apps I have several existing Pages that when I login to https://developers.facebook.com/apps All show up in my Apps list. However the one page (not created my be but I am an admin) does not. How do I access this Page as an App (with out creating an new App that will create a second page) A: Facebook apps also have their own facebook pages on facebook itsself. eg: https://www.facebook.com/nameofapp This might be your way to get to the app page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to inner join a derived table with Hibernate/NHibernate? (First i'd like to apologize if this is a duplicate, I can't find any good solution for it even though it must be simple) I'm creating reports from sales-data and need to output some aggregated values along with some non-aggregated/non-grouped ones, like Name. This is what I'd like to output: Total profit per employee with User.Name and SUM(Order.Profit) like this: Name Profit [+ more aggregated columns] ------------------- John Doe | $250 James Smith | $130 This is fairly simple with plain SQL like: SELECT u.Name, x.TotalProfit FROM dbo.Users u INNER JOIN ( SELECT o.UserID as UserID, SUM(o.Profit) AS TotalProfit, --[..] more aggregated columns FROM Orders o GROUP BY o.UserID ) x ON u.ID = x.ProfitToID I don't want to group by u.Name since it will affect performance (Read more about why at sqlteam.com) How do I do this with NHibernate? A: If you're using fancy SQL like that, just use a native query: entityManager.createNativeQuery("your query here", SomeDTOClass.class); A: In Hibernate you define the join paths in the mappings. So classes not related in Java with another classes cannot join themselves. Hibernate is an ORM it make sense. Try creating a SQLquery. Works pretty much in the same way that ordinary HQL queries. Then you would retrieve an array with the data. Parse it or create a DTO with a constructor that fit. select a.b.MyDTO(u.Name, x.TotalProfit) from... class MyDTO{ String name; int totalProfit; public MyDTO(String name, int totalProfit) { // ... } } Udo.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Order by performance problems I have an index problem with my order by statement. I have this query witch is runing fast: SELECT name from members where kat = 2 order by date DESC; I have a composite index on members table: kat_index(kat,date); Now my aplication has changed and i have added a query like this: SELECT name from members where kat = 2 order by logged_in DESC, status DESC, date DESC; Now the query i slow because it's using filesort. So the question is... What type of index should i add to satisfy both queries? A: You should have two indexes: (kat, date) (kat, logged_in, status, date) Each query will use the index that is best for that query. A: You cannot cover both queries with one index. You must form a leftmost prefix on the composite index along with the ORDER BY clause as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Create kml from csv in Python I am new to Python. I am working on gps files. I need to convert a CSV file having all the gps data to kml file. Below is the code in python I am using : import csv #Input the file name. fname = raw_input("Enter file name WITHOUT extension: ") data = csv.reader(open(fname + '.csv'), delimiter = ',') #Skip the 1st header row. data.next() #Open the file to be written. f = open('csv2kml.kml', 'w') #Writing the kml file. f.write("<?xml version='1.0' encoding='UTF-8'?>\n") f.write("<kml xmlns='http://earth.google.com/kml/2.1'>\n") f.write("<Document>\n") f.write(" <name>" + fname + '.kml' +"</name>\n") for row in data: f.write(" <Placemark>\n") f.write(" <name>" + str(row[1]) + "</name>\n") f.write(" <description>" + str(row[0]) + "</description>\n") f.write(" <Point>\n") f.write(" <coordinates>" + str(row[3]) + "," + str(row[2]) + "," + str(row[4]) + "</coordinates>\n") f.write(" </Point>\n") f.write(" </Placemark>\n") f.write("</Document>\n") f.write("</kml>\n") print "File Created. " print "Press ENTER to exit. " raw_input() The csv file I am using is available here : dip12Sep11newEdited.csv The kml file generated is available here : csv2kml.kml But the kml file is not getting created correctly. Apparently after some rows in the csv the code is not able to generate more Placemarks. Its not able to iterate. You can see that by scrolling to the last part of the kml file generated. Can anyone help me finding out the error in the code, because for some smaller csv files it worked correctly and created kml files fully. Thanks. A: You didn't answer the query above, but my guess is that the error is that you're not closing your output file (which would flush your output). f.close() A: use etree to create your file http://docs.python.org/library/xml.etree.elementtree.html It's included with Python and protects you from generating broken XML. (eg. because fname contained &, which has special meaning in XML.) A: This code is well written thank you for the post. I got it to work by putting my CSV in the same directory as the .py code. I made a few edits to bring it to py 3.3 import csv #Input the file name."JoeDupes3_forearth" fname = input("Enter file name WITHOUT extension: ") data = csv.reader(open(fname + '.csv'), delimiter = ',') #Skip the 1st header row. #data.next() #Open the file to be written. f = open('csv2kml.kml', 'w') #Writing the kml file. f.write("<?xml version='1.0' encoding='UTF-8'?>\n") f.write("<kml xmlns='http://earth.google.com/kml/2.1'>\n") f.write("<Document>\n") f.write(" <name>" + fname + '.kml' +"</name>\n") for row in data: f.write(" <Placemark>\n") f.write(" <name>" + str(row[1]) + "</name>\n") f.write(" <description>" + str(row[3]) + "</description>\n") f.write(" <Point>\n") f.write(" <coordinates>" + str(row[10]) + "," + str(row[11]) + "," + str() + "</coordinates>\n") f.write(" </Point>\n") f.write(" </Placemark>\n") f.write("</Document>\n") f.write("</kml>\n") print ("File Created. ") print ("Press ENTER to exit. ") input() f.close() Hope it helps if you are trying to convert your data. A: The simplekml package works very well, and makes easy work of such things. To install on Ubuntu, download the latest version and run the following from the directory containing the archive contents. sudo python setup.py install There are also some tutorials to get you started. A: One answer mentions the "etree", one advantage that you do not have to hardcode the xml format: Below one of my examples, of course you have to adjust it to your case, but you may get the principle idea of how etree works: to get something like this <OGRVRTDataSource> <OGRVRTLayer name="GW1AM2_201301010834_032D_L1SGRTBR_1110110_channel89H"> <SrcDataSource>G:\AMSR\GW1AM2_201301010834_032D_L1SGRTBR_1110110_channel89H.csv</SrcDataSource> <GeometryType>wkbPoint</GeometryType> <GeometryField encoding="PointFromColumns" x="lon" y="lat" z="brightness" /> </OGRVRTLayer> </OGRVRTDataSource> you can use this code: import xml.etree.cElementTree as ET [....] root = ET.Element("OGRVRTDataSource") OGRVRTLayer  = ET.SubElement(root, "OGRVRTLayer") OGRVRTLayer.set("name", AMSRcsv_shortname) SrcDataSource = ET.SubElement(OGRVRTLayer, "SrcDataSource") SrcDataSource.text = AMSRcsv GeometryType = ET.SubElement(OGRVRTLayer, "GeometryType") GeometryType.text = "wkbPoint" GeometryField = ET.SubElement(OGRVRTLayer,"GeometryField") GeometryField.set("encoding", "PointFromColumns") GeometryField.set("x", "lon") GeometryField.set("y", "lat") GeometryField.set("z", "brightness") tree = ET.ElementTree(root) tree.write(AMSRcsv_vrt) also some more info here A: Just use simplekml library to create kml easily.. instead of writing the kml data.. I achieved it directly by using simplekml. import simplekml Read the documentation of simplekml with open(arguments+'.csv', 'r') as f: datam = [(str(line['GPSPosLongitude']), str(line['GPSPosLatitude'])) for line in csv.DictReader(f)] kml = simplekml.Kml() linestring = kml.newlinestring(name='linename') linestring.coords = datam linestring.altitudemode = simplekml.AltitudeMode.relativetoground linestring.style.linestyle.color = simplekml.Color.lime linestring.style.linestyle.width = 2 linestring.extrude = 1 kml.save('file.kml') kml.savekmz('file.kmz', format=False) kml2geojson.main.convert('file.kml', '')
{ "language": "en", "url": "https://stackoverflow.com/questions/7529538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Auto close Youtube Video when it's ended on an iPod Touch/iPhone I'm currently doing a mobile website. I have embedded Youtube videos in it. Thing is, when you open a youtube video in an iPod, it does its thing where it goes full screen, and at the end you must manually close the video to continue browsing. I was wondering if there is a command to auto-close the fullscreen on the end of the youtube video. A: I don't know what code are you using but I saw this a while ago: <object width="425" height="344" type="application/x-shockwave-flash" data="http://www.youtube.com/watch?v=hoA1MBRJ_BA&amp;hl=de&amp;fs=1&amp;rel=0"><param name="movie" value="http://www.youtube.com/watch?v=hoA1MBRJ_BA&amp;hl=de&amp;fs=1&amp;rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param></object> That is supposed to work flawlessly, source: Embedding youtube video in webpage for both desktop and iphone/ipad
{ "language": "en", "url": "https://stackoverflow.com/questions/7529539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP birth checker error I currently have a registration form which checks a persons date of birth via three inputs day(dd) - month(mm) - year(yyyy) The code I am using to check: function dateDiff($dformat, $endDate, $beginDate) { $date_parts1=explode($dformat, $beginDate); $date_parts2=explode($dformat, $endDate); $start_date=gregoriantojd($date_parts1[1], $date_parts1[0], $date_parts1[2]); $end_date=gregoriantojd($date_parts2[1], $date_parts2[0], $date_parts2[2]); return $end_date - $start_date; } //Enter date of birth below in MM/DD/YYYY $dob="$day/$month/$year"; $dob2 = "$dob"; $one = round(dateDiff("/", date("d/m/Y", time()), $dob2)/365, 0) . " years."; if($one <13){ ?> You must be 13 years of age or older to join! <? }else{ ?> YAY you're 13 or above! <? } ?> I am receiving an error saying: error: Warning: gregoriantojd() expects paramater 1 to be long string Can anyone help me with this? Thank you in advance! A: Why complicate when you can do it in really simple way: function dateDiff($dateFormat, $beginDate, $endDate) { $begin = DateTime::createFromFormat($dateFormat, $beginDate); $end = DateTime::createFromFormat($dateFormat, $endDate); $interval = $begin->diff($end); if($interval->y >= 13) { echo 'Over 13'; } else { echo 'Not 13'; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7529543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Access violation reading location 0x00000000. 'new' keyword? I have two classes, A and Bar, both share a header file that has essentially Foo* foo in it. Class A instantiates an object Bar* bar. This works fine. However, if I make the instantiation of the object Bar* bar = new Bar(); I get an access violation when bar attempts to do something with foo. Why does this make a difference? If I don't use 'new' it works fine. This is the error: Unhandled exception at 0x003c17ea in Direct3DTutorial7.exe: 0xC0000005: Access violation reading location 0x00000000. Thanks. A: 0xC0000005: Access violation reading location 0x00000000. This means you're dereferencing a null pointer, likely in the constructor of Bar, or in some other code called by this constructor. Use a debugger to determine exactly where. A: I would guess that you are not allocating your Foo object. As it is a global variable it is initialised to zero on program start-up, which for pointers corresponds to a null value. A: Did you remember to construct a Foo object and assign it to the foo pointer? It sounds like your Bar constructor tries to do something with foo, but you haven't created the Foo object yet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How do I make table headers repeat when printed? Possible Duplicate: CSS: Repeat table headers in print mode I can repeat the headers in Firefox but not IE or Chrome. I am using the thead and tbody tags (which work in Firefox) Also I have added <thead style="display:table-header-group;"> but it still wont work in Chrome. However, it now works in IE.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to draw rectangular in J2ME by canvas through drawline method This is first time I at a question in here. Im new in J2ME, and now im developing a small application, but i get problem when i wanna show data into table. But in J2me not support table there for that i know another way can represent for table such as create table by Canvas or CustomItem. In Canvas i can draw 2 lines something like: ----------------------- | | | | but i dont know how can get coordinate of 2 lines remain such as like: | | | | | -------------------------- two draw a rectangular in whole screen, i know drawline method has 4 factors x1,y1,x2,y2. but i can not calculate x point and y point to draw two lines above I need you help me explain or give me example My Code: package test; import javax.microedition.lcdui.Canvas; import javax.microedition.lcdui.Graphics; /** * * @author J2MENewBie */ public class TableCanvasExample extends Canvas { private int cols=3; private int rows =50; protected void paint(Graphics g) { g.setColor(0x94b2ff); g.fillRect(0, 0, this.getWidth(), this.getHeight()); //draw two lines g.setColor(0xf8011e); g.drawLine(0, 0, 0, this.getWidth()); g.drawLine(0, 0, this.getHeight(), 0); } } package test; import javax.microedition.lcdui.Display; import javax.microedition.midlet.*; /** * @author J2ME NewBie */ public class TableCanvasMidlet extends MIDlet { private TableCanvasExample tbcve; public TableCanvasMidlet(){ tbcve = new TableCanvasExample(); } public void startApp() { Display.getDisplay(this).setCurrent(tbcve); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } } P/s: the vertical line doesn't full size i dont know why ??? Thank you! A: too much same-looking zeroes in your code - try using descriptive names instead: int w = getWidth(), h = getHeight(); // I think this way it's easier to read int xLeft = 0, yTop = 0; // descriptive names for zeroes // below, replace w - 1 -> w and h - 1 -> h if lines drawn are off-by-one int xRight = w - 1, yBottom = h - 1; // names for top - right coordinates g.drawLine(xLeft, yTop, xLeft, yBottom); // your left vertical g.drawLine(xLeft, yTop, xRight, yTop); // your top horizontal g.drawLine(xRight, yTop, xRight, yBottom); // add right vertical g.drawLine(xLeft, yBottom, xRight, yBottom); // add bottom horizontal if rectangle drawn doesn't look like you expect find where there is wrong semantic in code above
{ "language": "en", "url": "https://stackoverflow.com/questions/7529561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to fix TextView on Java, Android I have the layout: <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:weightSum="1"> <LinearLayout android:layout_weight="0.2" android:orientation="horizontal" android:layout_height="fill_parent" android:layout_width="wrap_content" android:id="@+id/linearLayout1"> <TextView android:text="TextView" android:gravity="center" android:layout_gravity="center" android:id="@+id/textView2" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> <LinearLayout android:layout_weight="0.8" android:background="@android:color/white" android:orientation="horizontal" android:layout_height="fill_parent" android:layout_width="wrap_content" android:id="@+id/linearLayout2"> <TextView android:layout_gravity="center" android:gravity="center" android:text="123" android:id="@+id/textView1" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> </LinearLayout> But I have a problem: If I put in TextView2 long text than TextView2 will be more longer default size and TextView1 will be more shortly default size. But I need than textview2 and textview1 have fixed size on width and will increase on height only. How can I do that? Thank you A: Try this: <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:text="TextView" android:gravity="center" android:layout_gravity="center" android:id="@+id/textView2" android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1"/> <TextView android:layout_gravity="center" android:gravity="center" android:text="123" android:id="@+id/textView1" android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1"/> </LinearLayout> A: use these in both TextView..size depend on you what you want..i have give 50dp android:maxWidth="50dp" android:minWidth="50dp" A: You saying TextView width as fixed size: then you can use android:layout_width="150dp" or something.., it makes your TextView width fixed and use android:ellipsize="end" to fix it. and android:layout_height="wrap_content" Hope it helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7529565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to reference from drawable to style My app with tabs has two themes. In each theme tabs have different images in selected and unselected state. How I can properly reference to image by theme? For example. I have in themes.xml <?xml version="1.0" encoding="utf-8"?> <style name="LightTheme" parent="@android:style/Theme.Light"> <item name="tabShows">@drawable/ic_tab_shows_unselected_light</item> <item name="tabShowsSelected">@drawable/ic_tab_shows_selected_light</item> <item name="tabNews">@drawable/ic_tab_news_selected_light</item> <item name="tabNewsSelected">@drawable/ic_tab_news_unselected_light</item> </style> <style name="DarkTheme" parent="@android:style/Theme.Black"> <item name="tabShows">@drawable/ic_tab_shows_unselected_dark</item> <item name="tabShowsSelected">@drawable/ic_tab_shows_selected_dark</item> <item name="tabNews">@drawable/ic_tab_news_selected_dark</item> <item name="tabNewsSelected">@drawable/ic_tab_news_unselected_dark</item> </style> Also I have a tab_shows.xml and tab_news.xml <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_selected="true" android:drawable="@drawable/ic_tab_shows_selected_light"/> <item android:state_selected="false" android:drawable="@drawable/ic_tab_shows_unselected_light" /> How I can reference to needed image in selector according to current theme? This not work for me <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_selected="true" android:drawable="?tabShowsSelected"/> <item android:state_selected="false" android:drawable="?tabShows" /> In layout files this works, I mean reference to style via ?styleName A: Build your style A and style B in your case you put android:drawable="@drawable/ic_tab_shows_selected_light" instead of background (I just copied snipets from my code) #000 <style name="styleB"> <item name="android:background">#000</item> </style> your theme A <style name="Theme.A"> <item name="pageBackground">@style/styleA</item> </style> theme B <style name="Theme.Blue"> <item name="pageBackground">@style/styleB</item> </style> in your attr.xml <?xml version="1.0" encoding="utf-8"?> <resources> <attr name="pageBackground" format="reference" /> </resources> finally in your widget you do style="?pageBackground" A: You can find your answer here http://www.androidengineer.com/2010/06/using-themes-in-android-applications.html Edit (Additional information by Lukap in comments) * *Define one or more themes in themes.xml and set the definitions of your styles there. *Define custom attributes, a.k.a. custom styles, in attrs.xml. *Describe what the values of your custom styles are in styles.xml. But you will need read more about the attrs.xml <item name="android:background">? android:attr/activatedBackgroundIndicator</item> </style> Instead, we are referring to the value of some other attribute – activatedBackgroundIndicator – from our inherited theme. Whatever the theme defines as being the activatedBackgroundIndicator is what our background should be.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Bash: how to add subdirs to the PATH In .bashrc I have added a dir where I put some scripts. Is that possible - to add all its subdir automatically - so that I would not have to add them one-by-one manually? (and wouldn't have to visit .bashrc every time I'll make a dir there) Edit: Using Laurent Legrand's solution, that's what I'm using now: PATH=$PATH:/usr/local/share/NAMD_2.7_Linux-x86_64:/usr/local/share/jmol-12.0.31:/usr/local/share/NAMD_2.7_Linux-x86_64_orig:/usr/local/share/sage-4.6.2:/opt/mongoDB/bin PATH=$PATH:$(find ~/Study/geek/scripts -type d -printf "%p:") this adds the dir and its sub dirs. A: Something like that should work PATH=$PATH:$(find your_dir -type d -printf "%p:") A: in your .bashrc suppose that all your scripts are under ~/bin maindir=~/bin for subdir in `tree -dfi $maindir` do PATH=$PATH:$subdir done export $PATH can do the trick ... A: This is the best practice to add executables from /opt directory to the path: for subdir in $(find /opt -maxdepth 1 -mindepth 1 -type d); do PATH="$subdir/bin:$PATH" done export $PATH As all needed executables should be in /opt/*/bin, we are avoiding subdirs that are beyond /opt/* using -maxdepth 1 and the /opt dir itself with -mindepth 1. Also note that we added /bin to the end of each dir. Same can be applied in your case with scripts. If you need more depth, just modify value of -maxdepth or remove it completely for infinite levels (same applies for -mindepth if main script path shoud be included). Just beware of ambiguity if same script name can be found in multiple subdirectory levels. So, in your case you may just use: for subdir in $(find $HOME/path/to/scripts -type d); do PATH="$subdir:$PATH" done export $PATH
{ "language": "en", "url": "https://stackoverflow.com/questions/7529575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTML/CSS tiled border (left, bottom, right) How do I create borders from images in CSS/HTML without using CSS3? I have three border tiles: left, right, bottom. The should show up (repeat-x/y) to the left, to the right and to the bottom of my content container. I tried to build div containers around my content container, but I could'nt figure out how to set the properties... Is this even the best way? A: Use the following HTML structure: ( explanation below ) <div class="container"> <div class="left"></div> <div class="right"></div> <div class="bot"></div> </div> And the following CSS: .container { position: relative; padding: 5px; // size of your border images } .container .left { position: absolute; left: 0; top: 0; background: url(border_left.jpg) repeat-y; width: 5px; height: 100%; } .container .right { position: absolute; right: 0; top: 0; background: url(border_right.jpg) repeat-y; width: 5px; height: 100%; } .container .bot { position: absolute; left: 0; bottom: 0; background: url(border_bot.jpg) repeat-x; width: 100%; height: 5px; } Basically what you do here is the following: * *You create a container which is relatively positioned so absolutely positioned elements inside it will be positioned within its boundaries. It also has a padding equal to (could also be higher than) the width / height of the border images to make up for the room they take up. *You add three divs inside of the container that get pushed to the left, right and bottom of the container and stretch along the entire width / height. This jsFiddle illustrates what I'm explaining here, using background colors instead of images. You can see the borders overlap at the corners, you could fix this by also creating extra images that are positioned in the corners. A: I would suggest to container add bg repeating at the bottom, bottom padding, make it relative, and using :after and :before place aside borders :) Sorry don't have time to write code now :(
{ "language": "en", "url": "https://stackoverflow.com/questions/7529576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to give a string as input to cut command in perl I have a string say my $str = "Hello Hi Bye", and I want supply this string to cut command get the fields. Can anyone please help me how to do this? And what about this? I was actually trying to do like this...I have an array: my @str = ("hello hi bye","hello hi you","abc def ghi","abc def jkl"); I want to provide this array to cut the first two fields and get the unique one among them. Like output should be "hello hi" and "abc def" and get the count of such unique combination of those 2 fields, here it is 2.. A: split use warnings; use strict; my $str = "Hello Hi Bye"; my @fields = split /\s+/, $str; Whenever you want "unique", think "hash": use warnings; use strict; use Data::Dumper; $Data::Dumper::Sortkeys = 1; my %count; my @str = ("hello hi bye","hello hi you","abc def ghi","abc def jkl"); for (@str) { my @flds = (split)[0..1]; $count{"@flds"}++; } print Dumper(\%count); __END__ $VAR1 = { 'abc def' => 2, 'hello hi' => 2 }; A: Try using the split function: my $str = "Hello Hi Bye"; my @fields = split(/\s+/, $str); # => ('Hello', 'Hi', 'Bye')
{ "language": "en", "url": "https://stackoverflow.com/questions/7529580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to store private encrypted user data in the database, but make them available to other chosen users? firstly, I apologize if my question sounds little confusing, I will try my best to describe my scenario as detailed as possible: I have website where user can input their personal data about themselves. They are mainly health data, so it's very private and sensitive information. So I need to encrypt this data on the server even then the server is compromised these data are secured because they will be encrypted with each user's password. Of course, user passwords will not be stored as clear-type text on the server, only password hashes. But my problem is that the website will offer "social function" when user can choose to share some of his/her information with another user. But this would be problem, because I will not have any way of decrypting user private data and so I can't show it to another user. Can you please give me some options, or at least ideas, how could this be solved ? Preferrably using LAMP environment. A: This can be solved using public-key cryptography: * *Generate a public/private key pair for each user; and only ever decrypt the private key temporarily with the user's password. *For each data item, randomly choose a (symmetric) key S and encrypt the data d with it. Store S(d). *Encrypt S with the the public key P+u of the user you want to grant access. Initially, that's the user u whose data you're storing. *Store P+u(S) permanently. Forget all other keys. Now, when a user u wants to share the data with the user x, do the following: * *Decrypt the user's private key P-u with the user's password. *Using that private key, decrypt the stored data: P-u(P+u(S)) = S. *Encrypt S with the public key of the user you want to share the information with. *Store the resulting P+x(S) permanently. Forget all other keys. Now, when any user x wants to access the data, perform the following process: * *Decrypt the user's private key P-x with the user's password. *Find P+x(S). (If it's not stored, that means nobody shared the data with the poor user x). *Using the private key, decrypt the stored data: P-x(P+x(S)) = S. *Using S, decrypt the stored encrypted S(d): S(S(d)) = d.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Open Graph Publishing I'll try my best not to make this too long winded. Basically, with Open Graph, if a user 'likes' a web page (in my example, a blog), you can set it up so that when a new post is added, an entry is shown in their news feed linking to it. For how this is allegedly done, see here: https://developers.facebook.com/blog/post/465/ Basically, you add OG meta tags to your site, create an app, link to the app_id in the OG tags, like the page and it will then create a kind of invisable facebook page that only the admins can see - users get taken to the site instead. The crutial thing is, because people 'like' this page, you can write posts from that page and the users will see it. The weird thing is, this worked for me yesterday but it's suddenly stopped working. Nothing's changed, it just stopped working. So I've created a blog, added the correct meta OG tags, created an app, added the fb:app_id tag to the blog containing the app ID. The code in the example can be split into two parts. Firstly, getting the access token: $access_token_url = "https://graph.facebook.com/oauth/access_token"; $parameters = "grant_type=client_credentials&client_id=" . $app_id . "&client_secret=" . $app_secret; $access_token = file_get_contents($access_token_url . "?" . $parameters); That works fine, it returns an access token. However, the second part of the example, posting from the facebook page doesn't work. $apprequest_url = "https://graph.facebook.com/feed"; $parameters = "?" . $access_token . "&message=" . $mymessage . "&id=" . urlencode($ogurl) . "&method=post"; $myurl = $apprequest_url . $parameters; $result = file_get_contents($myurl); The error I get is: (#200) The user hasn't authorized the application to perform this action Has Facebook changed their API in the last 24 hours or something? Any help would be much appreciated as this is driving me completely nuts! Cheers Pete A: Does the user authorize your app? You need to authenticate the user the first time so the app can post on his behalf: http://developers.facebook.com/docs/authentication/ You will need to request the publish_stream permission. Here is a reference: http://developers.facebook.com/docs/reference/api/permissions/ After that you can follow the examples to post or use what you currently had. (remember to keep the access_token) Here is an example with JS https://developers.facebook.com/docs/reference/dialogs/feed/
{ "language": "en", "url": "https://stackoverflow.com/questions/7529585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Query contacts across multiple mailboxes in 1 service call Is there a way, using Exchange Web Services Managed API, to query for a contact across multiple mailboxes using a single service call? I have a grid that loads contacts for the current user but as one of the grid columns I want to show a list of all other users who have that same contact (matching by contact email address for example). I've found this post and this post on how to do it using an older version of EWS but I haven't been able to implement it with the current version A: EWS supports this as told in the post. Is it possible that you are using the EWS Managed API? This API unfortunately does not have a FindItems method which takes multiple foler ids. You'll need to use EWS directly for this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PC Lint error 714 In my CRC8.c I have this function: BOOL isCRCValid(const UINT8 *ptr, UINT8 Len, UINT8 CRCChar){ return CRCChar == generateCRC(ptr, Len); //generareCRC returns a UINT8 } It's is declared in CRC8.h, but PC Lint returns me the following. Info 714: Symbol 'isCRCValid(const unsigned char *, unsigned char, unsigned char)' not referenced Info 830: Location cited in prior message Help says 714 is: 714: Symbol 'Symbol' (Location) not referenced -- The named external variable or external function was defined but not referenced. This message is suppressed for unit checkout (-u option). and 830 is: 830 Location cited in prior message -- Message 830 is a vehicle to convey in 'canonical form' the location information embedded within some other message. For example, consider the (somewhat simplified) message: file x.c line 37: Declaration for 'x' conflicts with line 22 This contains the location ("line 22") embedded in the text of the message. Embedded location information is not normally understood by editors and IDE's (Interactive Development Environments) which can only position to the nominal location (line 37 in this example). By adding this additional message with the nominal location of line 22 the user can, by stepping to the next message and, in this case, see what the 'conflict' is all about. This message and message 831 below do not follow the ordinary rules for message suppression. If they did then when the option -w2 was employed to turn the warning level down to 2 these messages (at level 3) would also vanish. Instead they continue to function as expected. To inhibit them you need to explicitly turn them off using one of: -e830 -e831 They may be restored via +e830 and +e831; they state of suppression can be saved and restored via the -save -restore options. Options such as -e8* and -e{831} will have no effect. As I'm newbie with PC Lint, and relative newbie with C, I'm not achieving resolving this problem. Can anyone help me with this problem? A: The message simply means that PCLint didn't find anything that actually uses this function, so it could be dead code/candidate for removal. A: It could also mean that you did not use the input arguments in your function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Restrict the use of a Clojure fn I have an application where Clojure code is evaluated either from the application classpath or as a remote file store resource. Only the administrator has access to the classpath location, but all users can provide their code on the remote store. In order to facilitate some operations, the application API includes a auth/as-admin macro that executes the input forms if they were executed as a logged in administrator, but obviously I don't want it to be successfully used in user provided code. How can I reliably restrict the use of auth/as-admin to classpath-only code, preventing any "malicious" binding in user code trying to circumvent the constraint? A: After reading the code and before evaluating it, you can iterate it and remove dangerous calls, (ns tmp (:require [clojure.zip :as zip]) (:use clojure.contrib.pprint)) ;;stolen from http://nakkaya.com/2011/06/29/ferret-an-experimental-clojure-compiler/ (defn remove-form [tree pred] (loop [loc (zip/seq-zip tree)] (if (zip/end? loc) (zip/root loc) (recur (zip/next (if (pred (zip/node loc)) (zip/remove loc) loc)))))) (remove-form (read-string (str \( "(+ 1 1) (println \"No print\")" \))) #(and (seq? %) (= 'println (first %)))) this will remove all println calls, tmp=> ((+ 1 1)) or you can use a library such as clj-sandbox that is designed for this. A: hiredman maintains the clojurebot on the clojure IRC channel. this bot is a great example of how to sandbox clojure code from untrusted sources. https://github.com/hiredman/clojurebot Thanks Hiredman! Clojurebot it awesome :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7529611", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SVN not working after updating to xcode 4.1 for snow leopard I have recently updated my xcode to version 4.1 for snow leopard, but after that my life became miserable and all the repositories in Organizer are unable to connect and show red icons. Anybody has any idea how to fix that??? A: have you tried this: 1.open a terminal 2.type 'svn list svn://~~~paths' ie. "NJW-Mac:~ bluepin$ svn list svn://192.168.0.184/BMA" 3.You will need to enter PCUserPassword,svnUserID,svnUserPassword 4.U should see output from the svn list command which means you were able to connect to the SVN server 5.return to xcode4 6.try again your job(connect Repositories) from Xcode 4 + SVN = working? A: Is it the IP addr in the settings of svn? I had the same problem on lion at the begin. so pls try to input your svn server name to replace the ip addr, it's will be work. If you did not get the name of your server, you could set a new name in the /etc/hosts file by yourself. Such as "192.168.1.10 iOS_SVN_Server".
{ "language": "en", "url": "https://stackoverflow.com/questions/7529624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Show only 2 rows preview of div content How to show only two rows preview of div content? If I use like substring in C# would cause HTML tag error issue. so, I wonder if I could do this? A: you could do this from css to the parent element overflow: hidden; height: necessary_height_to_show_only_2_rows; width: 100%; display: block; A: If i understood you correctly, you have this: <div> line-one line-two line-three </div> you can use the following css to hide the last line: div { line-height: 14px; #for example. height: 28px; #double the line-height. overflow: hidden; } if you want to add padding/extra space - create a wrapper div.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: IE conditional comments working but tags visible? I have the magnificent HTML5 javascript shim linked to in my <head>. It works fine apart from it displays the tags at the top of the page ie: <!--[if lt IE9]> <![endif]--> When I view source, it looks absolutely fine and dandy. I have absolutely no idea what is going on!!! A: Add a space between IE and 9.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Using PHP to remove a html element from a string I am having trouble working out how to do this, I have a string looks something like this... $text = "<p>This is some example text This is some example text This is some example text</p> <p><em>This is some example text This is some example text This is some example text</em></p> <p>This is some example text This is some example text This is some example text</p>"; I basically want to use something like preg_repalce and regex to remove <em>This is some example text This is some example text This is some example text</em> So I need to write some PHP code that will search for the opening <em> and closing </em> and delete all text in-between hope someone can help, Thanks. A: $text = preg_replace('/([\s\S]*)(<em>)([\s\S]*)(</em>)([\s\S]*)/', '$1$5', $text); A: $text = '<p>This is some example text This is some example text This is some example text</p> <p><em>This is the em text</em></p> <p>This is some example text This is some example text This is some example text</p>'; preg_match("#<em>(.+?)</em>#", $text, $output); echo $output[0]; // This will output it with em style echo '<br /><br />'; echo $output[1]; // This will output only the text between the em [ View output ] For this example to work, I changed the <em></em> contents a little, otherwise all your text is the same and you cannot really understand if the script works. However, if you want to get rid of the <em> and not to get the contents: $text = '<p>This is some example text This is some example text This is some example text</p> <p><em>This is the em text</em></p> <p>This is some example text This is some example text This is some example text</p>'; echo preg_replace("/<em>(.+)<\/em>/", "", $text); [ View output ] A: In case if you are interested in a non-regex solution following would aswell: <?php $text = "<p>This is some example text This is some example text This is some example text</p> <p><em>This is some example text This is some example text This is some example text</em></p> <p>This is some example text This is some example text This is some example text</p>"; $emStartPos = strpos($text,"<em>"); $emEndPos = strpos($text,"</em>"); if ($emStartPos && $emEndPos) { $emEndPos += 5; //remove <em> tag aswell $len = $emEndPos - $emStartPos; $text = substr_replace($text, '', $emStartPos, $len); } ?> This will remove all the content in between tags. A: Use strrpos to find the first element and then the last element. Use substr to get the part of string. And then replace the substring with empty string from original string. A: format: $text = str_replace('<em>','',$text); $text = str_replace('</em>','',$text);
{ "language": "en", "url": "https://stackoverflow.com/questions/7529636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Rails + Google Analytics I want to ask some question about using Rails (2.1.0) and Ruby (1.8.7). I have development mode and production. Production mode has a domain (for example blabla.online.com), development mode has an ip adress (for example 199.199.199.199). QUESTION: Do I need to create two different accounts in analytics (one for development and one for production)? A: You don't want multiple "Accounts", but you do want multiple "Website Profiles". * *Login to Google Analytics, you should be on a page with title "Overview: all accounts" *Click on the link for the correct account (in your example it's probably called "online"). *You should now be on a page with title "Overview >> online" that shows a list of all website profiles associated with this account. *At the bottom of the table click "Add website profile" Note that your new website profile will have a different tracking ID (e.g. the thing that looks like UA-255235386-2) so you'll need to have an environment specific configuration in your Rails app to use the appropriate tracking ID for the appropriate environment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Taking Data From Multiple Table using TestNG Data Provider I am Using Selenium RC with TestNG to do some kind of keyword driven testing.For the same purpose i want to read some data from an excel sheet and use it.Here I have used Data Provider annotation of TestNG.but My problem is that i want to read data from multiple tables and use them in a single test method using only one data provider.But I am Getting Problem in it.Can somebody Help me in Doing so. Thanks Here Is my Code: @DataProvider(name = "DP1") public Object[][] createData1() throws Exception { return new Object[][] { {getTableData.getTableArray(" Xls File Path", "Sheet name", "Table1")}, {getTableData.getTableArray(" Xls File Path", "Sheet name", "Table2")} }; } This Is My Test Method: @Test (dataProvider = ("DP1")) public void testallpivot(String Command, String Target, String Value) throws Exception { //Test Code here } But This Code is Showing Array Index Out of Bound Exception.. Somebody Please Help me..... Well this is how getTableArray looks.. public static Object[][] getTableArray(String xlFilePath, String sheetName, String tableName) throws Exception{ Object[][] tabArray; Workbook workbook = Workbook.getWorkbook(new File(xlFilePath)); Sheet sheet = workbook.getSheet(sheetName); int startRow,startCol, endRow, endCol,ci,cj; Cell tableStart=sheet.findCell(tableName); //System.out.println(tableName); startRow=tableStart.getRow(); startCol=tableStart.getColumn(); Cell tableEnd= sheet.findCell(tableName, startCol+1,startRow+1, 100, 64000, false); endRow=tableEnd.getRow(); endCol=tableEnd.getColumn(); System.out.println("startRow="+startRow+", endRow="+endRow+", " + "startCol="+startCol+", endCol="+endCol); tabArray=new String[endRow-startRow-1][endCol-startCol-1]; ci=0; for (int i=startRow+1;i<endRow;i++,ci++){ cj=0; for (int j=startCol+1;j<endCol;j++,cj++){ tabArray[ci][cj]=sheet.getCell(j,i).getContents(); } } return(tabArray); } And this is the Stack Trace..... java.lang.ArrayIndexOutOfBoundsException: 1 at org.testng.internal.Invoker.injectParameters(Invoker.java:1144) at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1020) atorg.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:137) at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:121) at org.testng.TestRunner.runWorkers(TestRunner.java:953) at org.testng.TestRunner.privateRun(TestRunner.java:633) at org.testng.TestRunner.run(TestRunner.java:505) at org.testng.SuiteRunner.runTest(SuiteRunner.java:359) at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354) at org.testng.SuiteRunner.privateRun(SuiteRunner.java:316) at org.testng.SuiteRunner.run(SuiteRunner.java:195) at org.testng.TestNG.createAndRunSuiteRunners(TestNG.java:903) at org.testng.TestNG.runSuitesLocally(TestNG.java:872) at org.testng.TestNG.run(TestNG.java:780) at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:75) at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:127) A: We can't help you much if you don't include the stack trace and also what getTableArray() returns (it should be Object[]). A: you can return only one array by copying the second in to first. Try something like: List<Object[]> retVal = Arrays.asList (getTableData.getTableArray(" Xls File Path", "Sheet name", "Table1")); retVal.addAll( Arrays.asList(getTableData.getTableArray(" Xls File Path", "Sheet name", "Table2"))); return retVal.toArray(); A: If you open the Excel sheet while executing code then this error is found. Please make sure you save and close excel doc before executing test cases.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: image pop up problem When you hover or click on an image within the webpage a pop up appears. However, this new pop up image is hidden behind the div to the right. Is there any way of bringing it forward so it is visible instead? Thanks in advance. Paul A: The div with more z-index will appear above the the one with lower z-index. Add z-index to your style class or quote as inline style to the div; .in_style { background-color: #E0EAF1; white-space: nowrap; z-index: 300; } or <div id='upperDiv' style='z-index:300;'> Your contents </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7529640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JavaScript/ jQuery for Closing Browser FireFox / Chrome / IE As I need JavaScript / jQuery code for closing browser's ( FireFox / Chrome and IE..) As I have try with window.close(). But it only work for IE. Is any other way..? A: This worked for IE and Chrome. (window.close() worked for IE, then win.close for chrome) <script type="text/javascript"> function CloseThis() { var win = window.open('', '_self'); window.close(); win.close(); return false; } </script> A: Can check Browser and write respective script for IE / FireFox IE----> window.close() FireFox ---> var answer = confirm("Do you want to close this window ?"); if (answer){ netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserWrite'); window.close(); } else{ stop; } A: I don't think that is possible as javascript can only interact with the pages rendered by the browser, not the actual browser. A: Windows can only be closed by scripts (window.close()) that were opened by scripts in the first place. So generally, this isn't possible (https://developer.mozilla.org/en/DOM/window.close) A: Try this snippet window.close()
{ "language": "en", "url": "https://stackoverflow.com/questions/7529641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to write the stream to memory stream? public void doprocess(TcpClient client) { MemoryStream ms = new MemoryStream(); Stream clStream = client.GetStream(); byte[] buffer_1 = new byte[8192]; int count = clStream.Read(buffer_1, 0, buffer_1.Length); while (count > 0) { ms.Write(buffer_1, 0, count); //the below line doesn't gives response and code hangs here count = clStream.Read(buffer_1, 0, buffer_1.Length); } } Is there any other way to write one stream to another? I want to use this Stream twice, which is why I need to write it to the MemoryStream. A: In .NET 4 the copying part is really easy: MemoryStream ms = new MemoryStream(); client.GetStream().CopyTo(ms); If you're not using .NET 4, then code similar to what you've already got is basically the same thing. However, note that this (and any other attempt) will only work if the network stream has been closed - otherwise the Read call will block waiting for more data. I suspect that's what's going wrong for you - and it's a fundamental problem. If your network stream isn't closed, then it's unclear how you'd really want it to behave - should the two readers of the "split" stream basically read any buffered data, but then block until there's new data otherwise? The buffered data could be removed when it's been read from both streams, of course. If that is what you're after, I don't think there's anything in .NET to help you particularly - and it's probably pretty tricky. If you could give us more context of what you're trying to do (and what the TcpClient is connecting to) that would really help. A: The reason why your code hangs on clStream.Read is because you are tying to read 8192 bytes from the socket but on the other side no-one is writing that many bytes. So the client just sits there and waits for the other side to send the required number of bytes. Depending on the protocol you are trying to implement over TCP there must be some indincation from the server how much data it intends to send so that the client knows in advance and only tries to read that many bytes. For example in the HTTP protocol the server sends in the headers the Content-Length header to indicate to the clients how much data is going to be sent in the body.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: WriteFile() crashes when trying to carry on multithreading I am working on an mfc dll that is accessed via a script and all this works fine. I have added a multi-threading component to it and am trying to use the WriteFile() function to write to my serial port, but somehow the WriteFile() function exits the application after the 2nd write command gets executed. Without the multithreading bit, everything works normally and I can apply as many writefile commands as I want. Multi-threading: I am using CreateThread(NULL,0,WorkerThread,this,0,0); to create my thread. Using "WorkerThread" to carry out the writefile operations described earlier in the background. Additionally, I need to use the Sleep() function while writing it at intervals defined by me. At the moment, the program just quits when trying to use Sleep(). So, I just removed it for the time being but would need it at a later stage. Is this a known problem or something with a but-obvious solution? Update: I have sort of tried to reach somewhere close to the problem but still not been able to resolve it. Apparently it looks like there is some problem with my WriteFile() parameters. WriteFile(theApp.m_hCom,tBuffer,sizeof(tBuffer),&iBytesWritten,NULL); It is not taking the sizeof(tBuffer) properly and because of which it is crashing. I checked out the string to be passed, which is exactly equal to what I need to pass but its crashing out the program if I write the code as done above (for WriteFile()). When I keep the stringlength i.e. manually set the sizeof(tBuffer) parameter to 14, then the program runs but the command does not get executed as the total string size of buffer is 38. CString sStore = "$ABCDEF,00000020,01000000C1200000*##\r\n"; char tBuffer[256]; memset(tBuffer,0,sizeof(tBuffer)); int Length = sizeof(TCHAR)* sStore.GetLength(); memcpy(&tBuffer,sStore.GetBuffer(),Length); and then sending it with the WriteFile command. WriteFile(theApp.m_hCom,tBuffer,sizeof(tBuffer),&iBytesWritten,NULL); A: This is wrong: sizeof(TCHAR). Since you are using char you should use sizeof(char) instead. TCHAR could be either 1 or 2 bytes... In the call to WriteFile you should use Length instead of sizeof(tBuffer). Otherwise you'd probably end up with garbage data in your file (which I assume is later read from somewhere else). A: I'm guessing its crashing because you are trying to run that directly from your DLL. Write Function looks fine to me and I think if you try to run your program from the Python script ONLY, it should work. I have faced something similar earlier and came to the conclusion of not running my DLL through the debugger but just the script. Please read this and this for more information. Hope this helps. Good Luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7529645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create content types available in multiple site collections I want to create a content type, lets call it MyDocument with some properties we need. However we have 10 departments each one with its own site collection. I want all documents to be created using MyDocument,across all site collections. Thanks A: In SharePoint 2010, you can use a Content Type Hub. From Plan to share terminology and content types: To share content types among site collections, you make one content type gallery the “hub” of a managed metadata service, create connections to the service from each Web application that contains a site collection, and specify that site collections should use the content types in the service. The same effect can also be achieved using a custom Feature.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Encapsulating Logic in SQL - Best Practice Greetings and thanks for reading! I was wondering what the best practice for encapsulating stored procedure logic using a set-based SQL technique. For example, I have a product entry application that I am developing. While attempting to limit code duplication, I created a stored procedure called AddItem which creates a new product in the product tables. The downside is that in order to utilize this procedure in a situation that requires adding a group of products, I am forced to use a cursor or WHILE loop to execute the procedure in a "FOR EACH" type of way. This is resulting in very poor performance on large sets of items. Of course I could hard-code the INSERT statements into the calling procedure but that makes me feel icky because the whole point is to be able to change (in one place) the "add item" logic. So if a column changed I would have to remember to change all of the INSERT statements in all of the places that use it. I just figured there has to be a better way of doing this and any advice would be appreciated. EDIT: Quite right, I should provide a code example. Here is the contents of the AddItem procedure which is being executed on a MS SQL2005 database: ALTER PROCEDURE [dbo].[AddItem] @ProjectNumber int, @ItemName varchar(255), @SupplierID int, @SKUType int, @Store varchar(3), @Category varchar(4), @AddedBy varchar(255), @ParentSKU varchar(255) = NULL, @SetNumber int = NULL, @NewItemNumber int OUTPUT AS SET NOCOUNT ON DECLARE @DiscontinuedStatus bit BEGIN TRY BEGIN TRAN SET @NewItemNumber = 0 INSERT INTO ProductEntry.dbo.Items (ProjectNumber, SetNumber, SKUType, Store, Category, AddedBy, ParentSKU, EntryTime) VALUES(@ProjectNumber, @SetNumber, @SKUType, @Store, @Category, @AddedBy, @ParentSKU, CURRENT_TIMESTAMP) SET @NewItemNumber = SCOPE_IDENTITY() IF @SKUType = 1 BEGIN SET @DiscontinuedStatus = 1 END ELSE BEGIN SET @DiscontinuedStatus = 0 END INSERT INTO ProductEntry.dbo.ItemInfo (ItemNumber, ItemName, Discontinued) VALUES (@NewItemNumber, @ItemName, @DiscontinuedStatus) INSERT INTO ProductEntry.dbo.ItemSupplierInfo (ItemNumber, SupplierID) VALUES(@NewItemNumber, @SupplierID) INSERT INTO ProductEntry.dbo.ItemWebInfo (ItemNumber) VALUES(@NewItemNumber) INSERT INTO ProductEntry.dbo.ItemTags (ItemNumber) VALUES (@NewItemNumber) COMMIT TRAN END TRY BEGIN CATCH ROLLBACK TRAN END CATCH I have a need for a procedure that adds multiple items at a time (with numbers greater than 1000) and when using a cursor the performance is very bad. It takes over a minute to add a group of 800 products and it only gets worse from there. EDIT: To further clarify the solution, the application allows items that have a parent-child relationship. When adding a new parent item, the user selects from a list of options and a set of child items is generated based on the option set. For example, a user could create a product called "Awesome Boot" with an option set of Colors="Brown, Black", Size="10M, 11M, 12M", ToeStyle="SteelToe, SoftToe" - this would generate a set of 12 items. Obviously you can see how this could increase exponentially, considering that most boots have around 36 sizes, multiple colors and toe styles, as well as other options. This can result in a parent item with a large number of child items. I guess one solution would be to combine all of the different item information into one "Items" table, eliminating the need for storing the same IDENTITY in multiple tables. I kind of like the convenience of splitting up the related data logically into different tables though. Maybe I'm trying to have my cake and eat it too! Thanks! :) A: This is just a stray comment - the two tables ItemWebInfo and ItemTags - unless those tables will eventually have multiple rows per entity, I think it would make a lot more sense (at least in most cases - there are always exceptions) if those columns were in the primary table. I also might suggest the same for the supplierInfo, unless an item can have more than one supplier the supplierID should just be a column in the primary table as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to memory map a compressed file? We have large files with zlib-compressed binary data that we would like to memory map. Is it even possible to memory map such a compressed binary file and access those bytes in an effective manner? Are we better off just decompressing the data, memory mapping it, then after we're done with our operations compress it again? EDIT I think I should probably mention that these files can be appended to at regular intervals. Currently, this data on disk gets loaded via NSMutableData and decompressed. We then have some arbitrary read/write operations on this data. Finally, at some point we compress and write the data back to disk. A: Memory mapping is all about the 1:1 mapping of memory to disk. That's not compatible with automatic decompression, since it breaks the 1:1 mapping. I assume these files are read-only, since random-access writing to a compressed file is generally impractical. I would therefore assume that the files are somewhat static. I believe this is a solvable problem, but it's not trivial, and you will need to understand the compression format. I don't know of any easily reusable software to solve it (though I'm sure many people have solved something like it in the past). You could memory map the file and then provide a front-end adapter interface to fetch bytes at a given offset and length. You would scan the file once, decompressing as you went, and create a "table of contents" file that mapped periodic nominal offsets to real offset (this is just an optimization, you could "discover" this table of contents as you fetched data). Then the algorithm would look something like: * *Given nominal offset n, look up greatest real offset m that maps to less than n. *Read m-32k into buffer (32k is the largest allowed distance in DEFLATE). *Begin DEFLATE algorithm at m. Count decompressed bytes until you get to n. Obviously you'd want to cache your solutions. NSCache and NSPurgeableData are ideal for this. Doing this really well and maintaining good performance would be challenging, but if it's a key part of your application it could be very valuable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: how to block a user in facebook via api(coding) I am developing a windows app using c#.net. I want to block a user in facebook using api. Any one suggest me is there any methods to block a user in facebook via api A: There is a function to ban users from your app in the Facebook REST api here: https://developers.facebook.com/docs/reference/rest/admin.banUsers/ The REST API is deprecated but you can call many of the same functions through the Open Graph API.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Use a file as a buffer for a producer consumer system of two programs I have two programs one of which writes some entries into a file and the other one reads all the entries from the file an processes them. Currently, the files are executed sequentially. That means, the first programs produces the file completely and exits before the second program is run. Now I want, without much modifications that the second program can be run simultaneously in a producer-consumer fashion. I know I should use interprocess communication, but at this point I want to make minimal changes the programs to get the running. Specifically, I want that the second program processes the entries from the second file in real time as they are generated by the first file. I am using gcc on ubuntu 11.04 A: If you are using a Unix-like operating system, may I suggest pipes? Modify your first program to write to standard output (instead of opening a file and passing references that ofstream around, pass std::cout). Modify your 2nd program to read from standard input (ditto, but replace your ifstream references with std::cin). Then, instead of prog1 -o some-tmp-file.txt prog2 -i some-tmp-file.txt do this: prog1 | prog2 EDIT: If your existing programs are based on <cstdio> instead of <iostream>, the same principle applies. Use stdout instead of your existing FILE* in the first program. Uses stdin instead of your FILE* in the second program. EDIT #2: If you want to make absolutely no change to the second program, and perhaps only minimal changes to the first program, try using named pipes. mkfifo /tmp/some-tmp-file.txt prog2 -i /tmp/some-temp-file.txt & prog1 -o /tmp/some-temp-file.txt
{ "language": "en", "url": "https://stackoverflow.com/questions/7529656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How would it be possible to add a caption to the bottom of a table? I have a table which has a caption which appears on top of the table. I'd need another caption to appear at the bottom of the table. how would it be possible? <table> <caption>My Table - Start</caption> <tbody></tbody> <tfooter></tfooter> <caption>My Table - End</caption> </table> A: You should put the <caption> at the top of the table, right below the <table> tag. Then you can use the CSS: caption { caption-side: bottom; } to get it below the table. And only one caption per table as a previous person wrote. If you need a table title, then either use <th> or put a heading outside the table and use CSS to position it correctly. A: You could mock one by doing the following, and applying some CSS <table> <caption class="cap">some caption text</caption> <tr> <td>cell 1</td><td>cell 2</td><td>cell3</td> </tr> <tr> <td>cell 1</td><td>cell 2</td><td>cell3</td> </tr> <tr> <td>cell 1</td><td>cell 2</td><td>cell3</td> </tr> <tr> <td colspan="3" class="cap foot"> This is pretty much a footer caption. </td> </tr> </table> Here's an example A: I believe you can only have 1 caption per table and it must appear after the table tag. You could add a div right after the table and put your caption there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Gitolite not updating authorized_keys file I have recently installed Gitolite in a Cygwin environment using SSH keys and everything else. I successfully installed Gitolite and had access to the gitolite-admin repository, configured and put the new keys. When I committed and pushed, everything was fine until I noticed that I can't access the new repositories or gitolite-admin repository again ... I then entered my server via ssh and noticed that gitolite deleted all of the public keys in authorized_keys except for my default SSH key I configured with SSH. I checked if the hooks are propagating and everything looks fine - Gitolite created the new repositories and compiled the new gitolite.conf I don't know what i missed - something is wrong but I don't have an idea what it is. The last I saw is that the file ~/.gitolite/src/sshkeys-lint manage the authorized_keys files but i dont understand the shell script language very well. A: When you commit, are you getting the following error in the console(of the machine where from you are commiting)?? remote: FIND: Parameter format not correct remote: FIND: Parameter format not correct If yes then the problem is the find.exe. Windows has a find.exe in its \windows\system32 folder and cygwin has its own find.exe. Usually \windows\system32 comes first in the environment variable 'path'. Gitolite uses 'find' in its scripts, but unfortunately the find.exe from windows rather than from cywin gets executed. Now to fix the problem, go to the environment variables tab and add bin directory of cygwin before system32. After this you wont face the issue of "authorized_keys file getting cleared on a commit" again. I have gitolite working on windows server 2008 machine with mirroring working fine. (I have configured this as a slave and the master is a centOs machine.) More info, As you have installed sshd as a windows service, the cygwin path would be given lesser proirity over windows path will kick in.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Timing of gridComplete event with Trirand's jqGrid I'm not convinced that the gridComplete event runs "after all the data is loaded into the grid and all other processes are complete," as specified in the documentation. I've got a grid that is loading correctly. In the gidComplete event, I'm triggering some filtering methods (.extend and .setGridParam) to apply a filter as soon as the grid is loaded. However, although my custom function is firing (seen through console), the filter is not being applied. If I use the setTimeout to delay the execution by a second (or so), then the filter is, in fact, applied. So it seems to me that the gridComplete is firing too early. Incidentally, the filter function (called setGridFilter()) also fires in an onchange event bound to a select menu (where the user can choose from pre-set filter options). This works perfectly. It's just the gridComplete invocation of this function that is failing. $("#list3").jqGrid({ url: 'blah.php', colNames: ['blah1','blah2','etc.','PresentationTemplateID'], colModel: [name: 'blah1', index: 'blah1'], [name: 'blah2', index: 'blah2'], [name: 'etc.', index: 'etc.'], [name: 'PresentationTemplateID', index: 'PresentationTemplateID', hidden:true] viewRecords:true, loadonce: true, pager: '#pager3', search:true, gridComplete: function(){ //var t = setTimeout('setGridFilter()',1000); //this works, for some reason setGridFilter(); //this does not } }); function setGridFilter() { var postdata = $("#list3").jqGrid('getGridParam','postData'); var text = $("#ddlGridFilterMenu").val(), f; $.extend(postdata,{filters:'',searchField: 'PresentationTemplateID', searchOper: 'eq', searchString: text}); $("#list3").jqGrid('setGridParam', { search: text.length>0, postData: postdata }); $("#list3").trigger("reloadGrid",[{page:1}]); } A: Try using loadComplete instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django test runner ignoring the --settings option I'm trying to use a different set of configs for testing my django app (like, using in-memory sqlite3 instead of mysql) and for this purpose I'm trying to use another settings module. I run my tests this way: python manage.py test --settings=test_settings But Django seems to ignore my test_settings module. Am I doing something wrong? A: Is test_settings a file or a directory? Here's how I load different settings for tests. In settings.py, at the bottom: # if manage.py test was called, use test settings if 'test' in sys.argv: try: from test_settings import * except ImportError: pass Super bonus! If you want to use sqlite3 for tests, you should activate integrity constraints, so you get the same foreign key exceptions as with mysql (lost of lot of time with this one). In some file of your project: from django.db.backends.signals import connection_created def activate_foreign_keys(sender, connection, **kwargs): """Enable integrity constraint with sqlite.""" if connection.vendor == 'sqlite': cursor = connection.cursor() cursor.execute('PRAGMA foreign_keys = ON;') connection_created.connect(activate_foreign_keys) A: I just bumped into this and confirm that on Django 1.6.1 --settings option is ignored. I filed a ticket on the Django bug tracker: https://code.djangoproject.com/ticket/21635#ticket
{ "language": "en", "url": "https://stackoverflow.com/questions/7529666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Scala: Can you use "foo match { bar }" in an expression without parentheses? Why are the parentheses needed here? Are there some precedence rules I should know? scala> 'x' match { case _ => 1 } + 1 <console>:1: error: ';' expected but identifier found. 'x' match { case _ => 1 } + 1 ^ scala> ('x' match { case _ => 1 }) + 1 res2: Int = 2 Thanks! A: As Agilesteel says, a match is not considered as a simple expression, nor is an if statement, so you need to surround the expression with parentheses. From The Scala Language Specification, 6 Expressions, p73, the match is an Expr, as is an if. Only SimpleExpr are accepted either side of the + operator. To convert an Expr into a SimpleExpr, you have to surround it with (). Copied for completeness: Expr ::= (Bindings | id | ‘_’) ‘=>’ Expr | Expr1 Expr1 ::= ‘if’ ‘(’ Expr ‘)’ {nl} Expr [[semi] else Expr] | ‘while’ ‘(’ Expr ‘)’ {nl} Expr | ‘try’ ‘{’ Block ‘}’ [‘catch’ ‘{’ CaseClauses ‘}’] [‘finally’ Expr] | ‘do’ Expr [semi] ‘while’ ‘(’ Expr ’)’ | ‘for’ (‘(’ Enumerators ‘)’ | ‘{’ Enumerators ‘}’) {nl} [‘yield’] Expr | ‘throw’ Expr | ‘return’ [Expr] | [SimpleExpr ‘.’] id ‘=’ Expr | SimpleExpr1 ArgumentExprs ‘=’ Expr | PostfixExpr | PostfixExpr Ascription | PostfixExpr ‘match’ ‘{’ CaseClauses ‘}’ PostfixExpr ::= InfixExpr [id [nl]] InfixExpr ::= PrefixExpr | InfixExpr id [nl] InfixExpr PrefixExpr ::= [‘-’ | ‘+’ | ‘~’ | ‘!’] SimpleExpr SimpleExpr ::= ‘new’ (ClassTemplate | TemplateBody) | BlockExpr | SimpleExpr1 [‘_’] SimpleExpr1 ::= Literal | Path | ‘_’ | ‘(’ [Exprs] ‘)’ | SimpleExpr ‘.’ id s | SimpleExpr TypeArgs | SimpleExpr1 ArgumentExprs | XmlExpr Exprs ::= Expr {‘,’ Expr} BlockExpr ::= ‘{’ CaseClauses ‘}’ | ‘{’ Block ‘}’ Block ::= {BlockStat semi} [ResultExpr] ResultExpr ::= Expr1 | (Bindings | ([‘implicit’] id | ‘_’) ‘:’ CompoundType) ‘=>’ Block Ascription ::= ‘:’ InfixType | ‘:’ Annotation {Annotation} | ‘:’ ‘_’ ‘*’ A: After some inspection in the Scala specification, I think I can give it a shot. If I am wrong please correct me. first, an if or match are defined as Expr - expressions. You are trying to create an infix expression (defined by the use of the operator between two expressions) However the especification (section 3.2.8) states that : All type infix operators have the same precedence; parentheses have to be used for grouping It also also states that: In a sequence of consecutive type infix operations t0 op1 t1 op2 . . .opn tn, all operators op1, . . . , opn must have the same associativity. If they are all left-associative, the sequence is interpreted as (. . . (t0 op1 t1) op2 . . .) opn tn. So my take is that Scala does not know what to reduce first: the match or the method '+' invocation. Take a look at this answer Please correct me if I am wrong. A: A match expression is not considered as simple expression. Here is a similar example: scala> val foo = "bar" + if(3 < 5) 3 else 5 // does not compile scala> val foo = "bar" + (if(3 < 5) 3 else 5) // does compile Apparently you can't write complex expressions wherever you want. I don't know why and hope that someone with more knowledge of the topic will give you a better answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to access a file that is being used by another process in Windows? I see that this question has been asked many times in stackoverflow, as well as in other places. The questioners solved their problem by different methods. Most of these solutions are around how they designed their applications and locking level on the files. I understand that Windows provides Read/Write protection in different ways. But, still, if the file is on my disk, and being an administrator, can't I read the contents of the locked file forcefully? Any pointers on how I can achieve that would be greatly helpful. The file in question is totally inaccessible to other processes through C# .NET APIs. Looks like its readlocked. Thanks. A: If file is locked from your app, you have to close all buffers/streams or whatever you have opened before. If file is locked from something else the only solution I know is to use Unlocker, which can be run even without GUI using some console param (so using Process class in C#). But be careful to walk this way, because you could corrupt file and create some memory leak closing with brute force opened handles and probably application that was using them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Multiple core usage on Adobe Flash 10 I'm developing a p2p mutliplayer game using adobe rtmfp server on facebook using flex 4. I have box2d for physics engine and the hardware acceleration is on. In 60fps, Average cpu cost for 6 players room is %40 for 1.86mhz intel core 2 duo. But in 8 and more players rooms, the cpu usage increases to %50 and fps drops to 50. I'm guessing that flash player uses only 1 core in full performance and resting the other. However I need all cores for 8+ rooms to simulate 60 fps smooth game. Is there a way to make flash use multiple cores at once? A: Nope, other than to use pixel bender to do whatever number crunching is possible. Pixel bender runs on it's own thread independent of the flash VM (if you use shader jobs properly). See my answer here: Flash parallel programming
{ "language": "en", "url": "https://stackoverflow.com/questions/7529670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: If the where condition is on a joined table, will I get duplicated results? I have three tables, one is tasks which are tasks that factory workers complete by putting them into batches, which is another table, each task has a batch_id, multiple tasks can have the same batch_id. The third table is the batch_log where all time that someone has worked on a batch is recorded in the form of a unique id, a batch_id, the person's userid, the start_time and the end_time. Each task has an estimated_recurring time in seconds and an estimated_nonrecurring time in seconds. I'm looking to get the sum of both of those fields grouped by the operation_id which is a field in the tasks table to represent whether it is a laser cutting, deburr, painting, etc task. The issue is that I only want the tasks that have batches that were in the batch_log during a time_period. Batches have multiple entries in the batch_log table. Here is what I'm trying: SELECT operation_id, SUM(t.estimated_nonrecurring + t.estimated_recurring) / 3600 as work_completed FROM tasks t INNER JOIN batch_log l on t.batch_id = l.batch_id WHERE l.start_time BETWEEN DATE("10:00:00") AND DATE(NOW()) AND l.time_elapsed < "10:00:00" GROUP BY t.operation_id I'm concerned that I will get a higher estimate than is real because multiple entries in the task table can have the same batch. A: Because you only want the times based on tasks that were in your batch log file what you posted will definately not work. Assuming you have 3 tables: Tasks, Batches, and BatchLog. You'll want this: SELECT SUM(t.estimated_nonrecurring + t.estimated_recurring) / 3600 as work_completed, t.OperationID FROM Tasks t INNER JOIN Batches b ON b.BatchID = t.BatchID INNER JOIN BatchLog bl ON bl.BatchID = b.BatchID WHERE bl.start_time BETWEEN DATE("2011-08-01") AND DATE(NOW()) GROUP BY t.OperationID
{ "language": "en", "url": "https://stackoverflow.com/questions/7529683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add an image to Django admin header How do I display an image in the header of Django's admin (I refer to the place on the top of the page with the yellow title "Django administration" with blue background)? I've tried to so with the HTML tag of <img> with some absolute path (under the assumption that the server and the client are running on the same machine): <img width="225" height="151" src="C:\Python27\Lib\site-packages\django\contrib\admin\media\img\admin\sunrise.png" alt="Sunrise here"> But the image isn't displayed (just the string "Sunrise here").
{ "language": "en", "url": "https://stackoverflow.com/questions/7529685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP error message I am getting the following error when attempting to buy something in the shop at www.1dt.biz/shop. I wondered if you could point me in the right direction on how I could fix it? Deprecated: Function eregi() is deprecated in /home/1dt/web/shop/includes/functions/general.php on line 1090 Deprecated: Function eregi() is deprecated in /home/1dt/web/shop/includes/functions/general.php on line 1090 Deprecated: Function eregi() is deprecated in /home/1dt/web/shop/includes/functions/general.php on line 1090 Deprecated: Function eregi() is deprecated in /home/1dt/web/shop/includes/functions/general.php on line 1090 Deprecated: Function eregi() is deprecated in /home/1dt/web/shop/includes/functions/general.php on line 1090 Warning: Cannot modify header information - headers already sent by (output started at /home/1dt/web/shop/includes/functions/general.php:1090) in /home/1dt/web/shop/includes/functions/general.php on line 33 A: Assuming the site is yours, you should stop using eregi as it's deprecated. A: You are using eregi, and that is deprecated (as the warning says) The last warning is because the warnings allready send a header you can't send another one best option: replace eregi with a preg variant: http://php.net/manual/en/function.preg-match.php second best option: set error_reporting to something that doesn't show the deprecated errors. (error_reporting(E_ALL ^ E_DEPRECATED); or something like that.) A: Use preg_match http://www.php.net/manual/en/function.preg-match.php A: you can use @eregi() to suppress warnings from that call. or use preg_match instead, because eregi is deprecated A: eregi() was deprecated in PHP 5.3 you either need to replace that call with preg_match() or change your warnings to ignore deprecated functions (not recommended). A: You should use preg_match, because eregi is deprecated and will be removed A: The following warning is caused by a header change attempt after it is too late (i.e. you have already echo'd, etc): Warning: Cannot modify header information - headers already sent by (output started at /home/1dt/web/shop/includes/functions/general.php:1090) in /home/1dt/web/shop/includes/functions/general.php on line 33 The depreciation warning is obvious and answered a bunch already here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Appending a Counter() list to a pygtk treestore (Python) I'm currently attempting to append a sorted list of items to a pygtk treestore. The list is a count of the times the number occurs in the original list, eg. 2 lots of 24 Generating the list from collections import Counter c = Counter(aSeries) l = c.items() l.sort(key = lambda item: item[0]) print l Example of list printed [(u'1', 23), (u'2', 24), (u'3', 23), (u'4', 17), (u'5', 25), (u'6', 23), (u'7', 22)] Attempting to append self.treestore.append(path, [l]) Image of list appended: http://i.stack.imgur.com/f3BGU.png I would like the list to be appended like so * 1: 23 * 2: 24 * 3: 23 * 4: 17 * 5: 25 How can i modify the way the list is counted or printed so that it will play nicely with the syntax that treestore.append requires ? A: This might depend a bit on your model, but how about something like this (i.e. append every single element of the list seperately to the treestore, which I assume to have only one column based on your picture): l = c.items() … for (char, count) in l: treestore.append(parent, ("%d: %s" % (count, char),))
{ "language": "en", "url": "https://stackoverflow.com/questions/7529691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: API Keys used to not be the APP ID? I'm upgrading our FB app to use the new SDK. Noticed that API Keys are now the same as the App ID. We're still sending over our old API Key for tokens. Are the old API Keys Obsolete/Deprecated... Should I change all of our to api keys to app id's? What's the logic behind this? Or at the least- any sort of migration, cut off dates for this. Where would/could I search for docs on this? Keywords? A: Yes, if you haven't migrated by now, your old app will not work. You will need to change over to the new oauth2 ASAP! :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7529702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the best way to handle SOAP type Exceptions in python In case the user enters data that is NOT on the web server being accessed by a WSDL, i get an error: <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:ns3="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns0="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="http://soap.rpc.jira.atlassian.com" xmlns:ns2="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <SOAP-ENV:Header/> <ns2:Body> <ns1:getFieldsForEdit> <in0 xsi:type="ns3:string">FmofSimScl</in0> <in1 xsi:type="ns3:string">QA-65000</in1> </ns1:getFieldsForEdit> </ns2:Body> </SOAP-ENV:Envelope> <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:ns3="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns0="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="http://soap.rpc.jira.atlassian.com" xmlns:ns2="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <SOAP-ENV:Header/> <ns2:Body> <ns1:getIssue> <in0 xsi:type="ns3:string">FmofSimScl</in0> <in1 xsi:type="ns3:string">QA-65000</in1> </ns1:getIssue> </ns2:Body> </SOAP-ENV:Envelope> Traceback (most recent call last): File "/home/qa/jira-test/.hg/check_jira.py", line 64, in <module> main() File "/home/qa/jira-test/.hg/check_jira.py", line 12, in main commit_text_verified = verify_commit_text(os.popen('hg tip --template "{desc}"')) File "/home/qa/jira-test/.hg/check_jira.py", line 35, in verify_commit_text if CheckForJiraIssueRecord(m_args) == 0: File "/home/qa/jira-test/.hg/check_jira.py", line 58, in CheckForJiraIssueRecord issue = com.run(command_name, logger, jira_env, my_args) File "/home/qa/jira-test/.hg/jira.py", line 1367, in run return self.commands[command].dispatch(logger, jira_env, args) File "/home/qa/jira-test/.hg/jira.py", line 75, in dispatch results = self.run(logger, jira_env, args) File "/home/qa/jira-test/.hg/jira.py", line 174, in run logger.error(decode(e)) File "/home/qa/jira-test/.hg/jira.py", line 1434, in decode str = e.faultstring AttributeError: 'WebFault' object has no attribute 'faultstring' transaction abort! rollback completed abort: pretxncommit.jira hook exited with status 1 Is there a way to handle this so i can write my own error string , or a warning message instead of all this. If i turn OFF stdout i dont get the xml data, but i still get: transaction abort! rollback completed abort: pretxncommit.jira hook exited with status 1 which is from mercurial, but would be nice to have a an error string appended to it like warnings.warn("%s does not exist"%issue_id) ok, i looked in jira.py and changed on line 1434 : str = e.faultstring to str = e.fault and got: faultcode = "soapenv:Server.userException" faultstring = "com.atlassian.jira.rpc.exception.RemotePermissionException: This issue does not exist or you don't have permission to view it." detail = (detail){ com.atlassian.jira.rpc.exception.RemotePermissionException = "" hostname = "JIRA" } } A: it was fixed in jira.py : change he decode function to: def decode(e): """Process an exception for useful feedback""" # TODO how to log the fact it is an error, but allow info to be unchanged? # TODO now fault not faultstring? # The faultType class has faultcode, faultstring and detail str = e.fault if str == 'com.atlassian.jira.rpc.exception.RemotePermissionException': return "This issue does not exist or you don't have permission to view it" return e.fault instead of : def decode(e): """Process an exception for useful feedback""" # TODO how to log the fact it is an error, but allow info to be unchanged? # TODO now fault not faultstring? # The faultType class has faultcode, faultstring and detail str = e.faultstring if str == 'java.lang.NullPointerException': return "Invalid issue key?" return e.faultstring
{ "language": "en", "url": "https://stackoverflow.com/questions/7529703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: can we store the value printed by printf() into a unsigned long variable? I have a following array and a printf() stament, char array[1024] = "My Message: 0x7ffff6be9600"; printf("%.14s", strstr(array, " 0x") + 1); The output of above printf() is 0x7ffff6be9600, can we store it into a unsigned long variable? A: Look at sscanf A: Try this: const char* numBuf = strstr(array, " 0x"); unsigned long number = 0; /* Set default value here. */ if(numBuf) number = strtoul(numBuf + 1, 0, 0); A: Since you tagged this as C++, see istringstream. using std::istringstream; const char source_text[] = "0x7ffff6be9600"; unsigned long value; istringstream input(source_text); input >> hex >> value;
{ "language": "en", "url": "https://stackoverflow.com/questions/7529704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Pear is not recognized as internal or external? issue I have installed pear but when run from my command prompt i get "pear is not recognized as internal or external command" . can anyone tell me how to fix this issue? Thanks A: You need to add the pear bin directory to your $PATH variable. For windows: http://pear.php.net/manual/en/installation.getting.php A: One after I am having the same issue. But this is what I did: * *Create a folder called PEAR in C:\wamp\bin\php\php5.3.8 *Downloaded latest go-pear.phar from http://pear.php.net/go-pear.phar to the above folder *cd to the PEAR then Ran command php go-pear.phar
{ "language": "en", "url": "https://stackoverflow.com/questions/7529715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sencha Touch Carousel randomisation I currently have a static carousel set up as below: varPanelTop = new Ext.Carousel({ defaults: { cls: 'homeTop' }, items: [{ html: '<img src="IMAGE ONE" />' }, { html: '<img src="IMAGE TWO" />' }, { html: '<img src="IMAGE THREE" />' }, { html: '<img src="IMAGE FOUR" />' }] }); Not a problem all works fine, but now i have been thrown a big one, in which 'can i do this so that each time this page is refreshed the order of the html/imgs are different each time? So would this be possible to do and how if so? Many Thanks A: It's possible. Have an array with objects like this: var images = [{html:'<img src="i1.jpg" />'},{html:'<img src="i2.jpg" />'},{html:'<img src="i3.jpg" />'},{html:'<img src="i4.jpg" />'}]; Then depending when you show the carousel you will have: Ext.getCmp('carouselId').items.add(images[Math.floor(Math.random()*images.length)]); etc. you can check if the images were added already i.e. all you need is a list of random numbers and you add the images to the carousel like that. Afterwards you call Ext.getCmp('carouselId').doLayout(); to display the images. Note that carouselId is the "id" property of the carousel object, but there are better ways to get to the carousel object. It all depends where you have it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unable to create class instance I have a singleton class that implements two other abstract classes. My monkey::getMonkey fails because of thisMonkey = new monkey() returns "object of abstract class type "monkey" is not allowed". I know you cannot instantiate abstract classes, but my monkey implements two abstract classes (meaning it is not abstract.. right?) What is a solution to this? class monkey : public animal, public npc { public: ~monkey(); static monkey* getMonkey(); private: monkey(); static monkey* thisMonkey; } monkey::monkey() {}; monkey::~monkey() {}; /* .. implements the virtual methods of animal and npc ... */ monkey::getMonkey() { if (!thisMonkey) thisMonkey = new monkey(); return thisMonkey; } A: You don't show enough to say exactly, but a priori, your class monkey doesn't implement all of the pure virtual functions in the base class. A class which has pure virtual functions which haven't been overridden is abstract. A: Find all the the methods declared pure-virtual in the classes anmial and npc and provide implementations for them within the monkey class. They are base classes of the monkey class, and it appears that you haven't fulfilled their abstract interface. Pure virtual classes look like: return_type methodName(params)=0; You must provide a function in the derived class (monkey) with that exact prototype, with an implementation. This will be called when you have a pointer to one of the derived classes and call that "pure-virutal" function. I.e. animal* aptr = new monkey; aptr->methodName(params); will map to: monkey::methodName
{ "language": "en", "url": "https://stackoverflow.com/questions/7529725", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C++ Derived polymorphic class - does it contain an entire instance of Base, including a vptr? Say we have Class A { public: int _i; virtual int getI(); }; class B : public A { public: int _j; virtual int getI(); }; So assuming that the size of a class in memory is the sum of its members (i.e. ignoring padding or whatever might actually happen), what is the size of a B instance? Is it sizeof(A) + sizeof(int) + sizeof(vptr)? Or does a B instance not hold an A vptr in it's personal A instance, so that sizeof(b) would be sizeof(int) + sizeof(int) + sizeof(vptr)? A: It's whatever the implementation needs to make the code work. All you can say is that it is at least 2 * sizeof(int), because objects of type B contain two ints (and possibly other things). In a typical implementation, A and B will share a vptr, and the total size will be just one pointer more than the two ints (modulo padding for alignment, but on most implementations, I don't think that there will be any). But that's just a typical implementation; you can't count on it. A: Any talk of a vtable is going to be specific to a certain implementation, since even the existance of a vtable isn't specified by the C++ standard - it's an implementation detail. Generally an object will only have one pointer to a vtable, and that vtable will be shared among all objects of that type. The derived class will contain pointers in the table for each virtual function of the base classes plus each new virtual function that it didn't inherit, but again this is a static table and it is not part of the object. To actually answer the question, the most likely outcome is sizeof(B) == sizeof(A::_i) + sizeof(B::_j) + sizeof(vptr). A: In addition to what James Kanze said, it is perhaps worth mentioning that (on a typical implementation) the B's virtual table will contain A's virtual table at its beginning. For example: class A { virtual void x(); virtual void y(); }; class B : A { virtual void y(); virtual void z(); }; A's virtual table: * *A:x() *A:y() B's virtual table: * *A:x() *B:y() *B:z() That's why an instance of B can get away with just one virtual table pointer. BTW, multiple inheritance can complicate things quite a bit and introduce multiple virtual table pointers per object. Always keep in mind that all this is an implementation detail and you should never write code that depends on it. A: Why would you want to know? If you are going to use that in your program, I'd try to look for a more portable way than calculate it and either add a virtual function that returns the size, or perhaps use the runtime type infomration to get the correct type and then return the size. (if you vote up or add comments I'll start decorating the answer)
{ "language": "en", "url": "https://stackoverflow.com/questions/7529728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CakePHP 1.3 or 2.0.0-RC2? I want to start developing in an MVC framework, specifically CakePHP. I see they have released 2.0.0-RC2 and was wondering if it is a waste of time to start an app in 1.3 when 2.0 is right around the corner. Should I start learning and developing in 2.0-RC2 rather as I'm guessing most of what I will learn in 1.3 now might become redundant soon? Thank you. A: I would advise against starting on a Release Candidate when you are new to the platform or programming pattern - mostly because you won't know the difference between broken/missing functionality and your lack of knowledge. Start with the stable build, then move to the new hotness once it has an official release. A: For now, you can start learning CakePHP 1.3. There is official documentation from where you can start and also you have a lot of examples on internet. When CakePHP 2.0 come stable you will be ready to work with it. A: Well .. first of all , i would recommend against use of php frameworks before you have learned enough to understand how they work. But especially large distance should be kept from Cake and other Ruby on Rails clones in PHP. They all are filled with bad practices, and it is not MVC pattern which they are implementing. A: I would start with CakePHP 2.0.0-RC2 as CakePHP 2.0 is the future of CakePHP. CakePHP 1.3.x is outdated in my opinion as it is still PHP4-based... For documentation, see the cookbook for CakePHP 2.0: http://book.cakephp.org/2.0/en/ . And if there are questions, ask in the IRC channel, or post in the Google group (or here), and/or read the source code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to discover if the screen is ON or OFF while developing in Android? How can I know if the screen is ON/OFF? A: If you simply wish to poll the current state you can do so this way. pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE); boolean screen = pm.isScreenOn(); If you are looking to be notified when the state changes you'll have to register a Broadcast Reciver to listen for ACTION_SCREEN_OFF and ACTION_SCREEN_ON. For this particular intent you must set your Intent Filter from java code. Doing so in the Manifest does not seem to work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Wrong background images in EditText.setError(..) popup I'm using EditText.setError(..) to show up an error message if the user did not correctly fill in the formular. The app will be for Honeycomb. I tried with both android:style/Theme.Holo and android:style/Theme.Holo.Light. The Problem is that the background images of the error popup seem to be wrong. There are to images for that background - one, for when the error popup is shown above the EditText and one for when it's shown beneath it. In Theme.Holo the above-image has a black background and the beneath-image has a white background. The text color always is black, so the text is not readable in the above-popup. Before updating to the latest sdk I was able to "hack" this problem with the following lines of code: <item name="android:textColorPrimaryInverse">#ffffffff</item> <item name="android:errorMessageBackground">@drawable/popup_inline_error</item> <item name="android:errorMessageAboveBackground">@drawable/popup_inline_error_above</item> But now with sdk tools 12 I get a compilation error using these lines with the information that e.g. the resource android:errorMessageBackground could not be found... Any ideas? Thank you! Chris A: The linked thread has a solution for this. The problem also seems to be fixed since Android 4.0.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Running unit tests before building stage in multi-module maven project I have a multi-module maven project. In every module there are unit tests. When I make clean install tests run before every module and if all tests in one module are success it build successfully. If one test failure all other tests in that module run successfully (or some run successfully, other failed). The build of module in what the first failure unit test is placed failed. Other modules are skipped. I want such thing: first to run all unit tests in all modules, and after that if there is no failed tests build all modules, or if there is one or more failed tests in one or mode modules skip building of all modules. Can you help me with it? A: AFAIK its impossible in maven. You are trying to change a maven build lifecycle which is not allowed in maven. However there are a couple of configuration parameters you can pass to maven and this will affect the testing. mvn install -Dmaven.test.skip This won't run unit tests at all mvn install -Dmaven.test.failure.ignore=true This will cause maven to not stop and proceed the module building process even if there were failures during the test phase. Hope, this helps A: run: mvn clean test mvn install -Dmaven.test.skip=true note, if you have inter-module dependencies (which i assume you do), you probably can't really do this, as you will need to build the dependent jars before you can run the tests in the other module. A: The problem is: the modules probably have dependencies upon each other, and to resolve those dependencies, you have to build the modules in order, or they won't compile. So there's no sane solution to your problem. Insane solutions would somehow aggregate the sources (and external dependencies) from all child projects and run compile and test on that conglomerate, but it would be such a monstrous hack that I'm glad they didn't do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails 3 - routing for admin section the structure of my admin section looks like this: controlers -> admin -> admin_controllers... views -> admin -> users -> data views -> admin -> settings -> data My routes looks like: resources :users, :user_sessions match 'login' => 'user_sessions#new', :as => :login match 'logout' => 'user_sessions#destroy', :as => :logout EDIT namespace :admin do ... resources :users, :user_sessions match 'login' => 'user_sessions#new', :as => :login match 'logout' => 'user_sessions#destroy', :as => :logout end But if I set up to the browser url address admin/login, so I will receive an error about missing template (especially Missing template user_sessions/new). How is it possible? What I forgot? Thanks A: to use namespaces, you have to use such shema: namespace :admin do resources :users, :user_sessions end all that views should be in app/views/admin/, like this app/views/admin/users/new.html.erb the API details is here: http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing
{ "language": "en", "url": "https://stackoverflow.com/questions/7529741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Starting InstalledAppDetails for certain application is causes force close I am working on an application whose job it is to clear the browser history. As part of this process I send the user to the APPLICATIONS_DETAILS_SETTINGS screen for the browser so they can press the "Force Stop" button, which will close any windows which are currently open in the browser. This is the code that I am using to open up to the app details activity for the browser package. killBrowserIntent = new Intent(); killBrowserIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS"); // I have tried "android.intentaction.VIEW" here as well. killBrowserIntent.setData(Uri.parse("package:com.android.browser")); ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.applications.InstalledAppDetails"); killBrowserIntent.setComponent(cn); This works great on many devices. However one of the devices I am testing on this causes a force close with the following log: 09-23 08:21:26.231: INFO/ActivityManager(231): Starting: Intent { act=android.settings.APPLICATION_DETAILS_SETTINGS dat=package:com.android.browser cmp=com.android.settings/.applications.InstalledAppDetails } from pid 3497 09-23 08:04:23.833: INFO/ActivityManager(231): Start proc com.android.settings for activity com.android.settings/.applications.InstalledAppDetails: pid=3434 uid=1000 gids={1015, 3002, 3001, 3003, 2001, 1007, 3005} 09-23 08:04:23.843: WARN/InputManagerService(231): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@407e4ec0 09-23 08:04:23.873: INFO/ActivityManager(231): No longer want com.motorola.android.deviceinformationprovider (pid 3124): hidden #21 09-23 08:04:23.893: WARN/dalvikvm(3434): Refusing to reopen boot DEX '/system/framework/com.motorola.android.frameworks.jar' 09-23 08:04:23.903: WARN/dalvikvm(3434): Refusing to reopen boot DEX '/system/framework/com.motorola.android.ptt.common.jar' 09-23 08:04:24.083: WARN/dalvikvm(3434): threadid=1: thread exiting with uncaught exception (group=0x4001e560) 09-23 08:04:24.083: ERROR/AndroidRuntime(3434): FATAL EXCEPTION: main 09-23 08:04:24.083: ERROR/AndroidRuntime(3434): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.settings/com.android.settings.applications.InstalledAppDetails}: java.lang.NullPointerException 09-23 08:04:24.083: ERROR/AndroidRuntime(3434): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1702) 09-23 08:04:24.083: ERROR/AndroidRuntime(3434): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1727) 09-23 08:04:24.083: ERROR/AndroidRuntime(3434): at android.app.ActivityThread.access$1500(ActivityThread.java:124) 09-23 08:04:24.083: ERROR/AndroidRuntime(3434): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:974) 09-23 08:04:24.083: ERROR/AndroidRuntime(3434): at android.os.Handler.dispatchMessage(Handler.java:99) 09-23 08:04:24.083: ERROR/AndroidRuntime(3434): at android.os.Looper.loop(Looper.java:130) 09-23 08:04:24.083: ERROR/AndroidRuntime(3434): at android.app.ActivityThread.main(ActivityThread.java:3859) 09-23 08:04:24.083: ERROR/AndroidRuntime(3434): at java.lang.reflect.Method.invokeNative(Native Method) 09-23 08:04:24.083: ERROR/AndroidRuntime(3434): at java.lang.reflect.Method.invoke(Method.java:507) 09-23 08:04:24.083: ERROR/AndroidRuntime(3434): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889) 09-23 08:04:24.083: ERROR/AndroidRuntime(3434): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:647) 09-23 08:04:24.083: ERROR/AndroidRuntime(3434): at dalvik.system.NativeStart.main(Native Method) 09-23 08:04:24.083: ERROR/AndroidRuntime(3434): Caused by: java.lang.NullPointerException 09-23 08:04:24.083: ERROR/AndroidRuntime(3434): at com.android.settings.applications.InstalledAppDetails.onCreate(InstalledAppDetails.java:369) 09-23 08:04:24.083: ERROR/AndroidRuntime(3434): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 09-23 08:04:24.083: ERROR/AndroidRuntime(3434): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1666) 09-23 08:04:24.083: ERROR/AndroidRuntime(3434): ... 11 more 09-23 08:04:24.083: WARN/ActivityManager(231): Force finishing activity com.android.settings/.applications.InstalledAppDetails To dig in to it a bit further I went into settings->Manage Applications->Browser on the device manually and noticed that the Intent that is fired when I do it this way has Extras bundled into it. This is the Intent line from the Log when this activity is launched manually: 09-23 08:23:59.470: INFO/ActivityManager(231): Starting: Intent { act=android.settings.APPLICATION_DETAILS_SETTINGS dat=package:com.android.browser cmp=com.android.settings/.applications.InstalledAppDetails (has extras) } from pid 3540 This is the Intent Line from when it is launched from my application: 09-23 08:21:26.231: INFO/ActivityManager(231): Starting: Intent { act=android.settings.APPLICATION_DETAILS_SETTINGS dat=package:com.android.browser cmp=com.android.settings/.applications.InstalledAppDetails } from pid 3497 Has anyone come across something like this before? What is the best way for me to figure out what it is that I need to Bundle up and add to the Intent in order for it to properly start on this device? I've located the source code for the InstalledAppDetails activity, it can be found here But the line referred to in my exception is 1: outside of onCreate and 2: blank. Is there a way that I can listen for the Intent that is fired when this activity is opened manually and unpack the extras from it so that I know what they are, and thus what I need to add to my Intent? A: I'd remove the setComponent() call. It should not be needed (assuming the docs are correct), and calling setComponent() for a component that is not yours is rarely a good idea. The action string alone should route it to the appropriate activity.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: sqlite and python... fast and furious I implemented in python a program that builds some db from protein fasta file. A fasta file is a text file that contains some macromolecular sequences. You can read more about here. From each protein my program generate a list of peptides, they are pieces of proteins. For my goals the program builds and interrogates a DB in SQLite. Do you know if there are many tricks to populate or interrogate a sqlite db faster in python? If I use layers or ORMs like SQLAlchemy, can I improve the performance? A: You won't improve performance, the ORM layer will add a bit of overhead, but you'll probably be able to experiment easier. Given the size of your data you might be able to create the database in memory which would be faster. Or you might want to look at a different type of database, like redis for example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: simulate different PC with different IP addresses in linux environment im new to linux environment and any help/feedback would be appreciated. Im actually trying to develop a client-server (MULTICAST) program, so, i would like to test one client sending information to different servers (one-to-many relationship). thus, i would like to simulate different server side in linux with different IP addresses in one computer. A: Did you try using different ports instead? I didn't try it myself, but perhaps that can help you in the mid-time. A: If you're really multicasting, you don't need to worry about physical host-specific IP:s, all you should need to do is make sure all the programs (clients and servers) are using the same multicast group addresses. Then they should all see each other's traffic automatically. There's nothing stopping you from running multiple clients on the same machine that also runs the server, in this case. A: I sounds like you want to test your code with different IP's. You can create IP aliases on your interface and simulate multiple IP's on one computer. for e.g. if eth0 is you're active interface with IP, say 192.168.5.11 you can assign another IP to eth0:0 (an alias to eth0) as below. ifconfig eth0:0 192.168.5.12 netmask255.255.255.0 up ifconfig eth0:1 192.168.5.13 netmask255.255.255.0 up run your server on one of the IP's and distribute clients to all your aliases A: Use either of the following when you do not have sufficient hardware: * *Multicast loop which has the IP stack redirect outbound packets to local receivers. *Virtual machines. Be aware that semantics of the socket option for #1 change depending on the operating system; for #2 only some virtual machines support multicast, refer to the vendor for details. http://msdn.microsoft.com/en-us/library/windows/desktop/ms739161(v=vs.85).aspx Ultimately though you must test with different machines due to specific artifacts of how hosts manage multicast groups. You can for instance create send-only membership which will block every other application on the host. Also consider that an internet, lower case 'I', will introduce further artifacts regarding group joining and propagation delays and drops that your application may need to be aware of. A: You can create multiple IP for same machine with help of IP alias. As mentioned above. But to create multiple Server at one PC you must need different port for each server if you want to simulate the all server behavior with network as well. I mean for one port multicast traffic always goes to that and some process in the PC will be receiving the packet and has to serve for all server in the PC, Means you have one packet only and all server is receiving with locally manipulation. But really simulation would be you have multiple server at 1 PC and all are receiving multicast traffic from network rather then from local process. my Solution: You keep number for server == number of port at the PC. Client send the multicast traffic over all port simultaneously and all server at the PC end will be receiving multicast packet from corresponding port from the Network. Please correct me if my understanding is wrong.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What javascript/php template libraries will parse the same template files? I originally was using Mustache.js but found that it does not work well for rendering large nested trees (it has no way of disambiguating variables of the same name in nested structures). I was happy to find a PHP version of Underscore.js, but when I looked at the code of Underscore.php I realized that its template method does not render Underscore.js-style templates. Instead it replicates similar functionality but with PHP variables. Jquery-tmpl/jquery-tmpl-php is another template language with JS and PHP libraries, but my concerns are that the jquery-tmpl-php library seems not to be used much (very few people are following it on github) and that jQuery decided to remove jQuery-tmpl as an official plugin: http://blog.jquery.com/2011/04/16/official-plugins-a-change-in-the-roadmap/ Also it seems that the author of jquery-tmpl has not touched it in months. What are other people doing to render Javascript and PHP using the same templates? A: Jade does it: https://github.com/everzet/jade.php https://github.com/visionmedia/jade A: You should try mustache. It's has implementations in many different languages. Have to get used to a different way to do control structures but its not too difficult to figure out. http://mustache.github.io/
{ "language": "en", "url": "https://stackoverflow.com/questions/7529754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Regex for dd/mm/yyyy and d/m/yyyy Possible Duplicate: Regex to validate dates in this format d/m/yyyy I can find regex for dd/mm/yyyy but does anyone know what it would be to also allow single digit dates and months (e.g. d/m/yyyy)? A: I think below is work for you ^((((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00))))$ A: if you've got a working regex for dd/mm/yyyy, then just add a question mark after the first d and m characters to make them optional. However, I would caution that date valiation using regex does have issues -- you might find it more flexable to use a dedicated date validation library (you don't specify what language you're working with, but most languages do have good date handling tools available) A: I think you could use this (\d{1,2})/(\d{1,2})/(\d{4}) Working example: http://regexr.com?2up1s A: ^(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1?[012])/(19|20)\d\d$ A: (?x) (0?[1-9]|[12][0-9]|3[01]) / (0?[12]|1[0-2]) / [0-9]{4}
{ "language": "en", "url": "https://stackoverflow.com/questions/7529755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET Routing, make i possible to route to a .zip file for download I'm using ASP.NET Routing in my webapp. On my site I have a .zip file that I want to users to be able to download. But I get error saying: "There is no build provider registered for the extension '.zip'. " What I'm I doing wrong? A: For ASP.NET MVC try using FileContentResult Class msdn link
{ "language": "en", "url": "https://stackoverflow.com/questions/7529757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to add a GEF editor to my multiplePage Editor? (eclipse RCP) I would like to add a GraphicalEditor to a multipage editor. However, when I simply call addPage(new MyEditor()); inside addPages(), I have an error since. Since my GEF editor extends GraphicalEditor, it cannot extend also FormPage. So, I made it implement IFormPage. But, I still get errors, actually it says that the editor that I'm using for the multipage editor cannot be cast to the one that corresponds to the my graphical editor. So, finally How can we add a GEF editor to the multipage editor? Any hint please to solve that? A: These are steps that I have done to add gef editor to multipage editor successfully: * *Extend org.eclipse.ui.part.EditorPart that have org.eclipse.gef.ui.parts.ScrollingGraphicalViewer as a member. public class GraphEditorPage extends EditorPart { private SPEEditor editor; private ScrollingGraphicalViewer viewer; ... } *In method createPartControl you need to layout the editor part, in my case, I did it with a SashForm as parent component, after that, create controls for you graphical viewer on parent component. *In method createPages(), create an GraphEditorPage and add it private void initGraphPage() { graphPage = new GraphEditorPage(this); addPage(0, graphPage, "Diagram"); } Hope this help!
{ "language": "en", "url": "https://stackoverflow.com/questions/7529761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change the color of JQgrid I have a jqGrid and it has a default color: blue. However I want to change it's color. What can I do? EDIT: I have that includes for jqgrid CSS: <link rel="stylesheet" href="/css/ui.jqgrid.css"/> <link rel="stylesheet" href="/css/ui.multiselect.css"/> <link rel="stylesheet" href="/css/jquery-ui-1.8.1.custom.css"/> A: At present you are using custom classes jQueryUI. The file in question is jquery-ui-1.8.1.custom.css. I will recommend or use a template already defined that your choice here: http://jqueryui.com/themeroller/ in the Gallery section. Once you've chosen a theme, for example, "Cupertino" change this line of code: <link rel="stylesheet" href="/css/jquery-ui-1.8.1.custom.css"/> with: <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/cupertino/jquery-ui.css" type="text/css"/> however, if you want a custom version from a theme already defined; click on edit and you are shown a screen where you yourself can change the colors of all elements of jQueryUI and once finished editing, you download the custom theme and I include it in your project. I hope I was clear!
{ "language": "en", "url": "https://stackoverflow.com/questions/7529762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to 'self-destruct' an application from within itself? I want the ability to uninstall an application from within itself. Example: UIAlertView pops up and says "This Application has Expired." The user hits 'Ok' and then the application proceeds to shut down and remove itself from the device. Is there any way to do this? A: I don't think there is a way to remove the app from phone itself. But, you can terminate the execution of an app from code using, exit(0); And this is also not encouraged as you should not quit the app abruptly without the user's knowledge. But its alright if you show an alert and quit the app, and is really necessary to quit the app. A: No. And even if was technically possible, Apple would reject it. They don't like apps that are time limited -- note that even "lite" apps have to be useful in their own right. A: I agree that you can terminate the app but I would also say that you should consider that the HIG says the following: Don’t Quit Programmatically Never quit an iOS application programmatically because people tend to interpret this as a crash. However, if external circumstances prevent your application from functioning as intended, you need to tell your users about the situation and explain what they can do about it. Depending on how severe the application malfunction is, you have two choices. Display an attractive screen that describes the problem and suggests a correction. A screen provides feedback that reassures users that there’s nothing wrong with your application. It puts users in control, letting them decide whether they want to take corrective action and continue using your application or press the Home button and open a different application If only some of your application's features are not working, display either a screen or an alert when people activate the feature. Display the alert only when people try to access the feature that isn’t functioning. If you want to programatically quit the application, you MUST have something in place to inform the user what is going on and possibly offer a way for the user to recover (subscribe to a service or something) so that the user can continue to enjoy the app that they presumably love. A: As Stephen said, no, it's not possible. The traditional means is to provide LITE and FULL versions of the application. The LITE version is functional and allows a user to see some of the functionality of your application while also offering the ability to upgrade to the full version.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CSS lines are repeating using stylesheet_link_tag I'm trying to order my stylesheets in a rails3 app, but I've got an issue with the lines repeating themselves using the *stylesheet_link_tag* helper. In app/views/layouts/application.html.erb <%= stylesheet_link_tag :reset, :application, :event_calendar, :cache => false %> In produced source code: <link href="/assets/reset.css?body=1" media="screen" rel="stylesheet" type="text/css" /> <link href="/assets/application.css?body=1" media="screen" rel="stylesheet" type="text/css" /> <link href="/assets/event_calendar.css?body=1" media="screen" rel="stylesheet" type="text/css" /> <link href="/assets/reset.css?body=1" media="screen" rel="stylesheet" type="text/css" /> <link href="/assets/event_calendar.css?body=1" media="screen" rel="stylesheet" type="text/css" /> Content of app/assets/stylesheets/ folder: calendar (master *)$ ls app/assets/stylesheets/ application.css event_calendar.css reset.css The same kind of problem appears using *javascript_include_tag* helper, I think both can be related. A: If you're using the asset pipeline you only need include application.css as inside that there should be lines like... /* * This is a manifest file that'll automatically include all the stylesheets available in this directory * and any sub-directories. You're free to add application-wide styles to this file and they'll appear at * the top of the compiled file, but it's generally better to create a new file per style scope. *= require_self *= require_tree . */ Don't be fooled by the fact its commented out, this will be processed and will automatically include all the files in the same directory because of the require_tree . command. Just put... <%= stylesheet_link_tag :application, :cache => false %> You can specify the order within application.css if you need your reset.css to come first *= require reset *= require_self *= require_tree .
{ "language": "en", "url": "https://stackoverflow.com/questions/7529771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the elegant way to create HTML horizontal tabs? I am going to make a HTML web page. I am wondering what is the most elegant way to create HTML horizontal tabs (as a navigation bar) ? I would like to have selected tab and unselected tab have different colors. I guess I should use CSS for styling and maybe jQuery to show and hide different content under different tab? A: Use the jQuery UI Tabs module. http://jqueryui.com/demos/tabs/ A: Refer this URL's, it may help you:- 2 level tabs and css horizontal tabs A: There's a wonderful article on http://alistapart.com regarding the CSS »sliding doors« technique how to add tabbed navigation to a site. It's plain HTML, but I'm sure you can combine it with javascript. A: Typical best practice is to use <li> elements for tabs and menus (with a <ul> as a container for a tab group), and style them accordingly. The key bits of styling are: float:left; --or-- display:inline-block; list-style:none; float:left; and display:inline-block; both acheive similar effects in that they cause the list items to be displayed in a horizontal row. They achieve it in quite different ways, which may have an impact on other aspects of your styling, but either can be used, depending on which you're more comfortable with. (the only caveat is if you need to support IE6, in which case inline-block doesn't work, but there are work-arounds for this) list-style:none; tells the list items not to display the bullet point that they would normally be given. Beyond those two styles, you can use virtually any CSS you like to get them to look exactly how you want. Typically tabs have borders around three sides, rounded corners, highlight the active tab and if you hover over them... all these effects can be achieved with CSS. This article gives a good walk through of how to achieve all these effects and more. There are a number of other good tutorials on the web as well. Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Altering numpy function output array in place I'm trying to write a function that performs a mathematical operation on an array and returns the result. A simplified example could be: def original_func(A): return A[1:] + A[:-1] For speed-up and to avoid allocating a new output array for each function call, I would like to have the output array as an argument, and alter it in place: def inplace_func(A, out): out[:] = A[1:] + A[:-1] However, when calling these two functions in the following manner, A = numpy.random.rand(1000,1000) out = numpy.empty((999,1000)) C = original_func(A) inplace_func(A, out) the original function seems to be twice as fast as the in-place function. How can this be explained? Shouldn't the in-place function be quicker since it doesn't have to allocate memory? A: I think that the answer is the following: In both cases, you compute A[1:] + A[:-1], and in both cases, you actually create an intermediate matrix. What happens in the second case, though, is that you explicitly copy the whole big newly allocated array into a reserved memory. Copying such an array takes about the same time as the original operation, so you in fact double the time. To sum-up, in the first case, you do: compute A[1:] + A[:-1] (~10ms) In the second case, you do compute A[1:] + A[:-1] (~10ms) copy the result into out (~10ms) A: If you want to perform the operation in-place, do def inplace_func(A, out): np.add(A[1:], A[:-1], out) This does not create any temporaries (which A[1:] + A[:-1]) does. All Numpy binary operations have corresponding functions, check the list here: http://docs.scipy.org/doc/numpy/reference/ufuncs.html#available-ufuncs A: I agree with Olivers explanation. If you want to perform the operation inplace, you have to loop over your array manually. This will be much slower, but if you need speed you can resort to Cython which gives you the speed of a pure C implementation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Handling TLB Misses I want to see which pages are being accessed by my program. Now one way is to use mprotect with SIGSEGV handler to note down pages which are being accessed. However, this involves the overhead of setting protection bits for all the memory pages I'm interested in. The second way that comes in mind is to invalidate the Translation Lookaside Buffer (TLB) in the beginning and then note down the misses. At each miss I will note down the addressed memory page and therefore note it down. Now the question is how to handle TLB misses in user space for a linux program. And if you know even a faster method than either TLB misses or mprotect to note down dirtied memory pages, kindly let me know. Also, I want a solution for x86 only. A: I want to see which pages are being accessed by my program. You can simulate a CPU and get this data. Variants: * *1) valgrind - dynamic translator of user-space binaries with good support of instrumentation. Try cachegrind tool - it will emulate even L1/L2 caches; also you can try to build new tool to log all memory accesses (e.g. with page granularity) *2) qemu - dynamic translator, both system-wide and process-wide modes. No instrumentation in the original qemu as I know *3) bochs - system-wide CPU emulator (very slow). You can easily hack "memory access" code to get memory log. *4) PTLsim - www.ptlsim.org/papers/PTLsim-ISPASS-2007.pdf However, this involves the overhead of setting protection bits for all the memory pages Is this overhead too big? Now the question is how to handle TLB misses in user space for a linux program. You cant handle a miss nor in user-space neither in kernel-space (on x86 and many other popular platforms). This is because most platforms manages TLB misses in hardware:. MMU (part of CPU/chipset) will do a walk on page tables and will get physical address transparently. Only if some bits are set or when the address region is not mapped, page fault interrupt is generated and delivered to kernel. Also, seems there is no way to dump TLB in modern CPUs (but 386DX was able to to this) You can try to detect TLB miss by the delay introduced. But this delay can be hided by Out-of-order start of TLB lookup. Also, most hardware events (memory access, tlb access, tlb hits, tlb misses) are counted by hardware performance monitoring (this part of CPU is used by Vtune, CodeAnalyst and oprofile). Unfortunately, this is only a global counters for events and you can't activate more than 2-4 events at same time. The good news is that you can set the perfmon counter to interrupt when some count is reached. Then you will get (via interrupt) address of instruction ($eip), where the count was reached. So, you can find TLB-miss-heavy hot-spot with this hardware (it is in every modern x86 cpu; both intel and amd). A: TLB is transparent to userspace program, at most you can count TLB misses by some performance counter (without addresses). A: Take a look at /proc/PID/maps file for your process. According to the documentation in http://www.kernel.org/doc/Documentation/filesystems/proc.txt, /proc/PID/maps specifies the memory map for each process. This map will tell you "which pages are being accessed by my program". However, it looks like you want to know which of these are dirty pages. While I am not sure how to find the exact list of pages that are dirty, it's possible to find how many pages are dirty by looking at private dirty and shared dirty fields in /proc/PID/smaps and dividing it by the pagesize. Note that this method is pretty fast. I believe an approximate idea of which pages are dirty can be obtained by polling /proc/PID/maps periodically.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Twitter-like Textbox Character Count with inline alert I would like to have a textbox character "count up" that will increase the count as a user types and display a text alert when the user crosses the required character but still allows user to continue typing. A: If you want to roll your own HTML <div> Type text here: <input type="text" id="txt" /> </div> <div id="warning" style="color: red; display: none"> Sorry, too much text. </div> <br> <input type="text" id="counter" disabled="disabled" value="0"/> Script $("#txt").keyup(function () { var i = $("#txt").val().length; $("#counter").val(i); if (i > 10) { $("#warning").show() } else { $("#warning").hide() } }); JSFiddle here A: You can check this plugins http://plugins.jquery.com/plugin-tags/character-counter
{ "language": "en", "url": "https://stackoverflow.com/questions/7529792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to send emails connecting to the SMTP server directly? I do not want to use mail() to send e-mail. I would like to connect to the SMTP server directly. Is there a class to do this job? A: SwiftMailer does this. http://swiftmailer.org/ A: Zend_Mail can do this for you: $tr = new Zend_Mail_Transport_Smtp('mail.example.com'); Zend_Mail::setDefaultTransport($tr); $mail = new Zend_Mail(); $mail->addTo('studio@example.com', 'Test'); $mail->setFrom('studio@example.com', 'Test'); $mail->setSubject('Subject'); $mail->setBodyText('...Your message here...'); $mail->send(); A: You have a list of existing smtp classes here
{ "language": "en", "url": "https://stackoverflow.com/questions/7529793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Target "debug" does not exist in the project I am trying to do custom build, hence I am editing build.xml file. I have added 2 new targets, but now NetBeans are giving me error, when trying to debug - Target "debug" does not exist in the project.But I have added target of different names, no debug at all! Does it mean I have to put in my build.xml all the content from android-sdk\tools\ant\main_rules.xml ? A: In build.xml, you'll neet to add the target. Add these lines inside <project>: <target name="debug" description="generate the distribution"> <mkdir dir="dist"/> <jar jarfile="dist/MyProject.jar" /> </target>
{ "language": "en", "url": "https://stackoverflow.com/questions/7529801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Compiler gives error when struct is not initialized and if we try to access the property but not with variable I have one observation about struct. When I declare a property in Struct and if I don't initialize the Struct then it gives me the below error - "Use of unassigned local variable empStruct" PSeduo Code- struct EmpStruct { private int firstNumber; public int FirstNumber { get { return firstNumber; } set { firstNumber = value; } } public int SecondNumber; } Program.cs- EmpStruct empStruct; empStruct.FirstNumber = 5; But when I declare public variable then the above code works. EmpStruct empStruct; empStruct.SecondNumber; So my question is why compiler not gives error when i try to access variable.(In case of Class it will give the error). A: Regarding fields C# language Specification says: 10.5.4 Field initialization The initial value of a field, whether it be a static field or an instance field, is the default value (§5.2) of the field’s type. It is not possible to observe the value of a field before this default initialization has occurred, and a field is thus never “uninitialized 11.3.4 Default values However, since structs are value types that cannot be null, the default value of a struct is the value produced by setting all value type fields to their default value and all reference type fields to null. The default value of a struct corresponds to the value returned by the default constructor of the struct (§4.1.2). PS: in case of class it gives error because reference type value by default is null A: There's a tremendous amount of confusion in this thread. The principle is this: until all of the fields of an instance of a struct are definitely assigned, you can not invoke any properties or methods on the instance. This is why your first block of code will not compile. You are accessing a property without definitely assigning all of the fields. The second block of code compiles because it's okay to access a field without all of the fields being definitely assigned. One way to definitely assign a struct is to say EmpStruct empStruct = new EmpStruct(); This invokes the default parameterless constructor for EmpStruct which will definitely assign all of the fields. The relevant section of the specification is §5.3 on Definite Assignment. And from the example in §11.3.8 No instance member function (including the set accessors for the properties X and Y) can be called until all fields of the struct being constructed have been definitely assigned. It would be more helpful (ahem, Eric Lippert!) if the compiler error message were along the lines of Use of not definitely assigned local variable empStruct. Then it becomes clear what to search for the in the specification or on Google. Now, note that you've defined a mutable struct. This is dangerous, and evil. You shouldn't do it. Instead, add a public constructor that lets you definitely assign firstNumber and secondNumber, and remove the public setter from EmpStruct.FirstNumber. A: In your first example, the code doesn't work because local variables have to be initialized before you can use them. There is no "default" value; they must be initialized first. You always have to initialize every local variable before you can use it. For example: EmpStruct empStruct = new EmpStruct(); empStruct.FirstNumber = 5; Fields in a class don't have this same restriction. If you don't explicitly initialize them, they will be automatically initialized with default values. In effect, the runtime is automatically calling "new EmpStruct()" on the field in your class. That's why your second example works. A: A few code samples might help clarify this better: // This works because you assign both fields before accessing anything EmpStruct empStruct; empStruct.SecondNumber = 2; empStruct.firstNumber = 1; // I made this public empStruct.FirstNumber = 3; Console.WriteLine(empStruct.FirstNumber); Console.WriteLine(empStruct.SecondNumber); // This fails because you can't use properties before assigning all the variables EmpStruct empStruct; empStruct.SecondNumber = 2; empStruct.FirstNumber = 3; // This works because you are only accessing a field that the compiler knows you've assigned EmpStruct empStruct; empStruct.SecondNumber = 2; Console.WriteLine(empStruct.SecondNumber); // This fails because you haven't assigned the field before it gets accessed. EmpStruct empStruct; Console.WriteLine(empStruct.SecondNumber); The point is, the compiler knows exactly what will happen when you assign a field. But when you assign a property, that might access any number of other fields on the struct. The compiler doesn't know for sure. So it requires you to have all the fields assigned before you can access a property.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: What is the default path of debug.keystore on Mac? I am a new Mac user. I searched everywhere for debug.keystore file, but no luck. Is it possible that eclipse can't create the file? A: Using the Command+shift+G I found the files in .android directory, but for mac I found no "debug.keystore" file rather I found "debug.keyset". Being not so sure, but I deleted this one and clean and build my app, now its working for me. A: should be here: ~/.android/debug.keystore A: The default location is /Users/<username>/.android/debug.keystore. Go into Finder, navigate to your home directory, then press Command+Shift+G and in the pop-up type .android - you'll see all files there. A: Open Terminal found in Finder > Applications > Utilities In Terminal, paste the following: defaults write com.apple.finder AppleShowAllFiles YES Press return Hold ‘alt’ on your keyboard, then right click on the Finder icon in the dock and click Relaunch.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "45" }
Q: Is there any way to access Java library from flash? Flash is great tool for animations. I was wondering if I could send events to Java and receive results back. In other words call some functions in flash and get their results. A: Apache Thrift would probably be the best way. Unforutanetly its unclear if it supports Action Script (Wikipedia says it does). Your next best bet is to make a REST interface in Java for your Action Script to call in which case you should look at JAX-RS (Jersey implementation being my first choice). If you need a true event based system (the messages are bidirectional and asynchronous) you should look into RabbitMQ or MOM in general. In which case you would use JSON to send messages back in forth to Java and flash. A: We use PureMVC for this. It allows you to map objects on both sides and deals with type conversions, and cleanly separates concerns using MVC.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get a list from all opened forms of my software? I want to ask the user to close all opened forms before terminate my application. How can I automatically get a list from opened forms? I'm using Delphi 2006, and don't using form's Auto-Create, but I'm using the auto created form's referenced var with Application.CreateForm. My regards. A: A possible solution (I use in C#) is to store every opened form instance in a list var. For example you could have a global list named openedForms; when every form is created, form itself can add its reference to openedForms and remove it when closing. When user tries to close your app, you could check that list count is greater than zero and, if user wants really close, you close gracefully every form instance contained in openedForms before shutting the app down. A: Have a look at Screen.FormCount and Screen.Forms. A: procedure ShowAllForms; VAR i: Integer; begin for i:= 0 to Screen.FormCount-1 DO ShowMessage(Screen.Forms[i].Name); end; or if you want to show also the MDI forms: procedure ShowAllForms; var i:integer; begin with Application do for i:=0 to componentcount-1 do if components[i] is TMyCustomForm //your form class here, or simply TForm then ShowMessage(components[i].Name); end; A: I use Main.MDIChildCount >0 for Child forms.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Internal Error in Drupal 7 after posting from Windows / apache to Linux I recently upoaded my drupal 7 site from local windows system, running on apache 2, to a linux server. the local system was having php 5.3 and server has 5.2. ONce uploaded I am not able to go to any sub pages - it shows me an Internal server error. I was able to login to admin and sube pages using ?q=user/admin, ?q=node/1 etc but the present url is already seo friendly - like sitename.com/aboutme, etc. How can I overcome this issue? Thank you. A: Drupal 7: PHP 5.2.5* or higher (5.3 recommended) there is some things you have to do with IIS to make your url clean http://drupal.org/node/3854 this topic will help you... A: Try this in your .htaccess file # For example if your site is at http://example.com/drupal uncomment and # modify the following line: # RewriteBase /drupal # If your site is running in a VirtualDocumentRoot at http://example.com/, # uncomment the following line: # RewriteBase /
{ "language": "en", "url": "https://stackoverflow.com/questions/7529816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to stream movies to Apple TV from iPad/iPhone while a UI is still on the iPad/iPhone Is it possible to stream a movie to Apple TV (either wirelessly or via WiFi) from an iOS device, while having a separate UI on the iPhone/iPad? The UI could for instance, act to control what is playing on the Apple TV. A: Simplest answer to your question is YES you can play content from ios on Apple TV with airplay, UI does not interfere and has nothing to do with that. A: Apparently you can do it with AirPlay: http://www.apple.com/iphone/features/airplay.html If this is something Apple is already providing than it can be a waste of time to develop it on your own, as they can reject it saying that it provides a duplicate functionality. A: Sure, you can use Airplay to stream from an iOS device to an Apple TV, and while the streaming is going on, the UI on the device will be available for other purposes. Here's one avenue you can try and put together a sample for pretty quickly: * *Create an app where you are displaying UIWebView on your primary display. *Implement support for a second display using Airplay - here's documentation for doing that: http://developer.apple.com/library/IOs/#documentation/AudioVideo/Conceptual/AirPlayGuide/EnrichYourAppforAirPlay/EnrichYourAppforAirPlay.html http://developer.apple.com/library/IOs/documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/CreatingWindows/CreatingWindows.html#//apple_ref/doc/uid/TP40009503-CH4-SW9 *Load Vimeo page to the UIWebView. If the app is running on an iPad that is setup to stream to an Apple TV over Airplay, then the video will play on the Apple TV, and take over the interface from whatever you're currently displaying on the Apple TV. As the video is playing on the Apple TV, you'll have full access to the UI on the device. You can get similar results using the Media Player Framework.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding rows and columns to HTML with jQuery/JavaScript this is my html code: <h3>Ilm selles linnas</h3> <table> <tr> <th>id</th> <th>city_id</th> <th>temp</th> <th>date</th> </tr> <div id="info"></div> </table> this is my script: function(data) { $('#info').empty(); var html = ""; for(var i = 0; i < data.length; i++) { html += "<tr>"+ "<td>"+data[i].id+"</td>"+ "<td>"+data[i].city_id+"</td>"+ "<td>"+data[i].temperature+"</td>"+ "<td>"+data[i].date+"</td>"+ "</tr>"; } $('#info').append(html); } After this is done, in the real ouput this happens: So: 1) All the info is higher than table headers (<th> tag) 2) All the info isn't in the column, but just smashed together 3) None of the info is showed in HTML source. What must I change to make it look as it should? Feel free to ask any questions. A: Just remove your <div id="info"></div> and append directly to the table. $('table tr:gt(0)').remove(); var html = ""; $(data).each(function() { html += "<tr>"+ "<td>"+this.id+"</td>"+ "<td>"+this.city_id+"</td>"+ "<td>"+this.temperature+"</td>"+ "<td>"+this.date+"</td>"+ "</tr>"; }); $('table').append(html); Code: http://jsfiddle.net/Xdbqs/5/ A: You can't put a div in a table. Try this: <table id="datatable"> <tr> <th>id</th> <th>city_id</th> <th>temp</th> <th>date</th> </tr> </table> function(data) { var html = ""; for(var i = 0; i < data.length; i++) { html += "<tr>"+ "<td>"+data[i].id+"</td>"+ "<td>"+data[i].city_id+"</td>"+ "<td>"+data[i].temperature+"</td>"+ "<td>"+data[i].date+"</td>"+ "</tr>"; } $('#datatable').append(html); } A: <table id="info"> <tr> <th>id</th> <th>city_id</th> <th>temp</th> <th>date</th> </tr> </table> As stated it's your markup. Change it to the above. A: Don't use a div. You could just use a and your code would work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7529819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Enable/Disable Asp.net Image button during postback I am trying to check if user is available or not in the database for that I have kept a button named "Check availability".Once when user clicks that he can checks whether the name exists in the database or not and changes the textbox background color to red if "exists" and "green" if not Now I have a registration page where the user fills the form if the user exists I need to disable the SignUp button which I am using the "Image button" for it. So What happens is I am unable to disable it while the user is available. When I am disabling the Image button(ie..the SignUp button) during page load and after the user fills the form though the user is available the page is refreshing and submitting the information to the database as a duplicate field. And these are the many ways I have worked out but none worked out for me. .enabled = true; .disabled = false; document.getElementById('<%= button.ClientID %>').disabled = true; document.getElementById('<%= button.ClientID %>').disabled = false; $('#ButtonId').prop("disabled", true); ->> disabled $('#ButtonId').prop("disabled", false); ->> Enabled Here is my code: <script type="text/javascript"> $(function () { $("#<% =btnavailable.ClientID %>").click(function () { if ($("#<% =txtUserName.ClientID %>").val() == "") { $("#<% =txtUserName.ClientID %>").removeClass().addClass('notavailablecss').text('Required field cannot be blank').fadeIn("slow"); } else { $("#<% =txtUserName.ClientID %>").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow"); $.post("LoginHandler.ashx", { uname: $("#<% =txtUserName.ClientID %>").val() }, function (result) { if (result == "1") { $("#<% =txtUserName.ClientID %>").addClass('notavailablecss').fadeTo(900, 1); document.getElementById('<%= btnSignUp.ClientID %>').enabled = false; } else if (result == "0") { $("#<% =txtUserName.ClientID %>").addClass('availablecss').fadeTo(900, 1); document.getElementById('<%= btnSignUp.ClientID %>').enabled = true; } else { $("#<% =txtUserName.ClientID %>").addClass('notavailablecss').fadeTo(900, 1); } }); } }); $("#<% =btnavailable.ClientID %>").ajaxError(function (event, request, settings, error) { alert("Error requesting page " + settings.url + " Error:" + error); }); }); </script> This is my handler code: Public Class LoginHandler : Implements IHttpHandler Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest Dim uname As String = context.Request("uname") Dim result As String = "0" If uname IsNot Nothing Then result = CheckUnAvailable(uname) End If context.Response.Write(result) context.Response.[End]() End Sub Public Function CheckUnAvailable(ByVal name As String) As String Dim result As String = "0" Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("HDIConnectionString").ConnectionString) Try con.Open() Dim com As New SqlCommand("Select Username from Registration where Username=@UserName", con) com.Parameters.AddWithValue("@UserName", name) Dim uname As Object = com.ExecuteScalar() If uname IsNot Nothing Then result = "1" End If Catch result = "error" Finally con.Close() End Try Return result End Function Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable Get Return False End Get End Property Updated Code for Check Availability Click: If txtUserName.BackColor = Drawing.Color.Red Then btnSignUp.Enabled = False ElseIf txtUserName.BackColor = Drawing.Color.Green Then btnSignUp.Enabled = True End If A: Try using: disabled=disabled EDIT Try: $('#ButtonId').removeProp("disabled"); A: If the button is an Asp.Net button: $('#<%= button.ClientID %>').prop("disabled", true); Or... $("[id$=ButtonId]").prop("disabled", true);
{ "language": "en", "url": "https://stackoverflow.com/questions/7529825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }