text
stringlengths
8
267k
meta
dict
Q: NameError occurs after switching from vendored gems to Bundler in Rails 2.3.8 /Users/me/.rvm/gems/ree-1.8.7-2011.03@evokat25/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:105:in `const_missing':NameError: uninitialized constant Rails::Initializer::Paperclip There is no mention of Rails::Initializer::Paperclip anywhere in my code base. Anybody have a clue as to what it is trying to do? A: I figured this out. I had some configuration lines in config/initializers/.rb and config/environments/.rb. After I put the "require" lines in each for the appropriate gems, the problem disappeared.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: nested RadAjaxPanel Telerik do not update I create a RadAjaxPanel with some of inside controls.one of inside control is a nested radajax with a TextBox and a button.both of radajaxpanel update mode are always(in code behind). when i click on button in nested radajax parent radajax will be update an nested radajax will be hide!!Why? I test this scenario with updatepanel and worked correct... Markup: <telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" onajaxsettingcreated="RadAjaxPanel1_AjaxSettingCreated1"> <asp:TextBox runat="server" ID="txt2" /> <asp:Button Text="but1" ID="but" runat="server" onclick="but_Click" /> <telerik:RadAjaxPanel ID="RadAjaxPanel2" runat="server" Height="200px" Width="300px" onajaxsettingcreated="RadAjaxPanel2_AjaxSettingCreated"> <asp:TextBox runat="server" ID="txt" /> <asp:Button Text="but2" ID="but2" runat="server" onclick="but2_Click" /> </telerik:RadAjaxPanel> </telerik:RadAjaxPanel> Code Behind: protected void but_Click(object sender, EventArgs e) { txt.Text = "ok"; txt2.Text = "ok"; } protected void but2_Click(object sender, EventArgs e) { txt.Text = "ok"; txt2.Text = "ok"; } protected void RadAjaxPanel1_AjaxSettingCreated1(object sender, Telerik.Web.UI.AjaxSettingCreatedEventArgs e) { e.UpdatePanel.UpdateMode = UpdatePanelUpdateMode.Always; } protected void RadAjaxPanel2_AjaxSettingCreated(object sender, Telerik.Web.UI.AjaxSettingCreatedEventArgs e) { e.UpdatePanel.UpdateMode = UpdatePanelUpdateMode.Always; } A: You don't need to have a RadAjaxPanel nested inside of another RadAjaxPanel. I can't see anything in your code that warrants it either, so the easiest solution would be to remove it. If you want to have more control over which controls are AJAX driven, I would suggest using the RadAjaxManager instead: <telerik:RadAjaxManager ID="AjaxManager" runat="server" UpdatePanelsRenderMode="Inline"> <AjaxSettings> <telerik:AjaxSetting AjaxControlID="MyControl"> <UpdatedControls> <telerik:AjaxUpdatedControl ControlID="MyOtherControl" /> </UpdatedControls> </telerik:AjaxSetting> </AjaxSettings> </telerik:RadAjaxManager> It looks like the second RadAjaxPanel is just setting a fixed width. Just use a regular Panel or a DIV for this and you should be all set.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: pattern recognition and string matching I have two files taken from two different server. In these two files are presents the matches of some football teams. As you know football teams can be called with differents names. I would like implement a code that can recognise the same football match in the two files in order to take same variables from a file and some other from the other file. for example in one file i have a match called Derry City - Bray Wanderers and in the other file i have the same match that is called Derry City - Bray how can i do this? i have no ideas. A: In c++: Have a look at Boost.Regex and Boost.Tokenizer as they will do what you need. All you need is a pattern to match. boost::regex("Bray[\s]*(Wanderers)?", boost::regex::icase); Or something like that -- easy to set up as a set of unit tests. A: Very simple script to replace aliases for teams. You'll need to fill it with aliases yourself, I made some up. If you have multiple games, the hash will overwrite the existing ones, as long as all the aliases are exchanged for full names. #!/usr/bin/perl use strict; use warnings; my %games; while (<DATA>) { chomp; my ($home, $guest) = split /\s*-\s*/, $_, 2; $home = get_name($home); $guest = get_name($guest); $games{"$home - $guest"} = 1; } sub get_name { # Return the full name for the team, if it exists, otherwise return the original my %alias = ( 'Derry' => 'Derry City', 'Brawlers' => 'Beijing', 'Dolphins' => 'Miami', 'Bray' => 'Bray Wanderers', ); return $alias{$_[0]} // $_[0]; } use Data::Dumper; print Dumper \%games; __DATA__ Derry City - Bray Wanderers Derry City - Bray Brawlers - Dolphins Beijing - Miami Miami - Beijing
{ "language": "en", "url": "https://stackoverflow.com/questions/7613295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the best practice for maintain users? aspnet_Users or create new user table I installed the database asp.net Membership but I want to ask what is best practice here should I use the aspnet_Users table as a main table for Website user or should create new user table to store the website users login information and password ?? A: According to my understanding aspnet_Users tables are the easiest and best option if you already not having tables for user management A: The generated aspnet_Users table gives you a quick out-of-the-box option, and you can also use it across multiple applications. I have used this before and it has served me well. A: I have never used the aspnet_Users table even once in my entire career as a software developer, senior software developer and now present software architect. I think that pretty much sums this up. A: To me using asp.net membership provider is a easier and safer way. And it contains in build method that can use. If we need to Implement a Custom Membership User it also possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Profiling synchronization operations in Linux I want to profile synchronization operations, such as locking and unlocking of mutexes, semaphores etc. in Linux. I know that deep down they are implemented using futexes, so maybe it is enough to profile locking and unlocking of futexes (please correct me if I'm wrong here). So my question is how to profile it, since futex operations normally occur in user space. Is their any tool which allow me to profile this? I am basically interested in knowing the functions which lock the futexes and the frequency. A: You could be interested by valgrind and it's tool callgrind. valgrind --trace-children=yes --tool=callgrind -v ./program It will generates a detailled callgraph into a file, with among others, the amount of time passed in each function. Then you can see all of that with kcachegrind, which is a nice UI to visualize the data. kcachegrind It will allow you to see all functions which called pthread_mutex_lock() (or others), and among them, the top ones, by percent of time, ... The most relevant part of callgrind is that you can easily find bottleneck in single-threaded program, because you just have to look the function which took the most cpu time. On multithreaded program, a function waiting a long time for something (a mutex) is a normal condition, so it's more difficult. You can also use the tool Helgrind from valgrind, which help find errors in your usage of mutexes (potential deadlocks or potential data races). I guess that it analyses your calls to synchronization functions, and the data you read/write, to detect potential problem (problem that could occur 1 time over 1000000), by analyzing the Serializability conformance of your synchronization and data access. (I repeat : I guess). valgrind --tool=helgrind --suppressions=$PWD/supp --gen-suppressions=yes --db-attach=yes --track-lockorders=no ./program And the core feature of valgrind: Checking memory leak: valgrind --leak-check=yes -v --db-attach=yes ./program
{ "language": "en", "url": "https://stackoverflow.com/questions/7613304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Unidentified Errors.Please notify... error instead of my simple forms.ValidationError OK, trying to add a clean method to a ModelForm in Django. I'm adding a simple raise statement just to see if it works, and instead of my message, I get "Unidentified Errors. Please notify..." Here's my (simple) test: class ConfigurationForm(forms.ModelForm): ... def clean(self): cleaned_data = self.cleaned_data typeid = cleaned_data.get("typeid") value = cleaned_data.get("value") if value and typeid: raise forms.ValidationError("this is the error") I couldn't even find a reference to "Unidentified Errors" anywhere in the django code base. Thanks in advance for your help. A: Is your clean method returning the cleaned_data? If you look at the docs here: https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other you'll notice you have to make sure to return self.cleaned_data. Furthermore, don't raise validation errors; instead delete the invalid field from the data (again, as you have to return it) So: def clean(self): typeid = cleaned_data.get("typeid", False) value = cleaned_data.get("value", False) if value and typeid: self._errors["typeid"] = self.error_class(["Some error has happened"]) del(self.cleaned_data['typeid']) return self.cleaned_data A: I use clean model methond intensively. You should search for your errors on NON_FIELD_ERRORS: On template: {% if form.non_field_errors %} <ul> {% for error in form.non_field_errors %} <li> {{error}} </li> {% endfor %} </ul> {% endif %} On code: form._errors.[NON_FIELD_ERRORS] Here you can learn about how to move business rules from forms to model.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WebGL and rectangular (power of two) textures WebGL is known to have poor support for NPOT (non-power-of-two) textures. But what about rectangular textures where both width and height are powers of two? Specifically, I'm trying to draw to a rectangular framebuffer as part of a render-to-texture scheme to generate some UI elements. The framebuffer would need to be 512x64 or thereabouts. How much less efficient would this be in terms of drawing? If framerate is a concern, would I do better to allocate a 512x512 power-of-two-sized buffer and only render to the top 64 pixels, sacrificing memory for speed? A: There has never been the constraint for that width must equal height. A: More specifically: 2D textures are not at all required to be square; a 512x64 texture is not only allowed but should also be efficiently implemented by the driver; on the other hand cube maps need to be square. For 2D textures, you can use NPOT textures if both wrap modes are CLAMP_TO_EDGE and your minification filter does not require a mipmap. Efficiency of NPOT texture may vary depending on your driver.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Plotting fluctuation in R I will try to be as less vague as possible. The below data set consists of a device's power measurement and I have to plot a graph which would show the average fluctuation of the power (watt) during the Time column. I have to accomplish this in R but i really don't know which function or how should I do it as i'm a newbie to R. Any help will be highly appreciated! Store No.,Date,Time,Watt 33,2011/09/26,09:11:01,0.0599E+03 34,2011/09/26,09:11:02,0.0597E+03 35,2011/09/26,09:11:03,0.0598E+03 36,2011/09/26,09:11:04,0.0596E+03 37,2011/09/26,09:11:05,0.0593E+03 38,2011/09/26,09:11:06,0.0595E+03 39,2011/09/26,09:11:07,0.0595E+03 40,2011/09/26,09:11:08,0.0595E+03 41,2011/09/26,09:11:09,0.0591E+03 A: rollapply in package:zoo will return a moving average (or a moving any-function). You can plot using points and then add a moving average line: dat$D.time <- as.POSIXct(paste(dat$Date, dat$Time)) require(zoo) ?rollapply length(rollapply(dat$Watt,3, mean)) plot(dat$D.time, dat$Watt) lines(dat$D.time[3:9], rollapply(dat$Watt,3, mean))
{ "language": "en", "url": "https://stackoverflow.com/questions/7613312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get Hudson to correctly build multiple modules changed by a single commit Consider a Maven project with multiple interdependent modules: let's say, three jar modules A, B, and C, which are dependencies for a war module Z. I have a separate Hudson build for each of these modules, so that only modules that have changed are re-built. My issue is that if I commit a changeset that changes both module A and module Z, Z may be built before A and fail, before A completes and triggers a rebuild of Z which now passes. Allowing builds to regularly fail for reasons to do with build ordering rather than "real" failures desensitizes us to real failures; we end up ignoring builds which have legitimately broken because we are used to assuming it will eventually flip back. I have been managing this through the use of quiet periods, blocking when upstream builds are running, etc. But in practice, my build has more modules than the example I've given, many of which take a while to build and test. I also have a small horde of diligent developers making frequent commits. This means my jar modules are constantly building, only rarely leaving a gap for my war module(s) to build. So the war doesn't build very frequently, meaning it takes a long time to find out when we've broken it, and also takes longer to identify which change broke it. Also, the constant running of builds means that if I commit a change that touches jars A and B, the war file Z may be built once for jar A (which builds quickly), and then again for jar B (which takes longer). This makes it hard to understand the results of a given commit. I've considered using the join plugin, but this appears to require all of the modules to build every time. Since I actually have quite a few jar modules, I really don't want to have to build them all every time, I only want to build the ones that have changed for a given commit. Are there any better ways to handle this? Thanks A: This is always a difficult problem (and I've re-written this answer more than once!) In terms of a technical solution, you want something that will wait for the build of several different jobs to be not running before it starts to run. If it's difficult to quantify, it's going to be difficult to put in place. I'll be very interested to see what technical solutions are suggested in this thread. I guess you have to look at why your jobs are being run, and how often. If there's any code that requires unit testing in your WAR, could you move it out into it's own module? That way you can run only integration tests every hour/30 mins using the war and not worry about where and when the individual modules are at. You may want to also look at what your modules contain. Do they ALL have to be modules? Can you perhaps reduce the fragmentation - it might help reduce the complexity of what you are attempting to schedule :) I understand and applaud your efforts to get as much tested as soon as possible - but sometimes a smoke test is all you can do if there's a constant churn of code. A: The approach we're now looking at is combining some Maven modules into single Hudson jobs, rather than having a one to one mapping of modules to jobs. Specifically, if a war module's dependencies are fairly small and quick to build on their own, building them in the same job with the war ensures that all of the code from a single commit is built together, at least for that given war file. This does result in duplication - we have multiple war files using the same jars, so the jars are essentially rebuilt for every war, rather than once only. But in practice, the jars are quick to build, and this makes the war files conceptually cleaner. This would be less attractive if the jars took a while to build and test, since the combined jars + war job would then be quite long, giving us long feedback loops for problems within the jars. Getting the balance right is important. So my takeaway: don't assume that one Hudson/Jenkins job per module is the best way to go, and don't be afraid to rebuild the same code in multiple jobs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to configure PHP engine with Apache 2.2.x? i have installed Apache 2.2.x but when i turned to instal PHP V5.2.17 i didn't find the apache 2.2.x radio button in the web server setup step !! only the fast CGI,other CGI and don't install a web server radio buttons is appearing, what i can do ?? A: I suspect you're talking about windows. Lining up a proper build of apache, php module, etc is a bit of a pain, so unless it's for production, I suggest using WampServer or XAMPP. Otherwise, the PHP modules are here if you really want to roll your own. Remember to match the PHP and Apache runtimes and word-size (32 or 64 bit).
{ "language": "en", "url": "https://stackoverflow.com/questions/7613317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What are my options for building an desktop app with web technologies that needs to invoke a process on the client? I have a local desktop app that needs a UI overhaul, the data in this app is largely driven by a back end DB and the best tools available to make a user friendly UI for this kind of system seems to be to build it as a web app. However, the primary function of this tool is to have the user make a choice from a list and then use that to kick off a perforce sync on their local machine. This app needs to run on both Windows and OSX so, my first thought was to use a cross platform GUI framework like wxWidgets and embed a web view for all of the functionality apart from the sync step. However all the wx based web views I have found seem to be very limiting. So, what are my other options? Is there anyway to invoke a p4 sync from a browser, or is a local app with an embedded web view my only viable choice? A: You might be able to use the P4 Javascript API and build your app as a tool accessible from P4V. Not sure if the P4V part of that would be a deal breaker for you. I'm not sure if the Javascript API is available outside of the context of P4V. If it is, then you should be able to use that to build whatever kind of web app that you want. A: I ended up writing a browser plugin that invokes a p4 sync operation to solve this problem. I used the firebreath framework to provide a javascript api that allows me to invoke a p4 sync on the users' local machine. To do this I needed to be able to have a p4.ini already present on the local machine and know it's location, or I needed to pass the user/pass and client workspace to the plugin. This works fairly well, but it's not as clean as I would like, piping the output of the sync process to the browser seems to be slow, and the output seems to scroll for a lot longer than the process runs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a custom page with Codeigniter, not as controller I have a website which is built on Codeigniter and I want to create some pages with information like terms or privacy, their address should be: http://domain.com/terms http://domain.com/privacy My question is: should I create for each page a controller? In CMS for example, if I add a page it has to create a 'pysical' page on the server (CMS which is built on Codeigniter)? A: For static pages like a Privacy Policy or Terms of Service page where they don't really fit under any other controller I usually create a "content" controller that looks something like this: class Content extends CI_Controller { public function privacy_policy() { $this->load->view('privacy_policy'); } public function terms_of_service() { $this->load->view('terms_of_service'); } } Then I add some routes to remove "content" from the URL: $route['privacy-policy'] = 'content/privacy_policy'; $route['terms-of-service'] = 'content/terms_of_service'; That way you don't need to create a new controller for each page and you can keep your static pages organized in a single spot. A: Something I do is make your policy statements as a DL, DT, DD. hide the DD with jquery, show the DD then on a click to the DT. Then have the DD popup as a modal The entire thing is contained in the footer. No need for anything to do with the controller
{ "language": "en", "url": "https://stackoverflow.com/questions/7613319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to exit a chroot inside a perl script? While writing a perl script intended to fully automate the setup of virtual machines (Xen pv) I hit a small maybe very simple problem. Using perl's chroot function I do my things on the guest file system and then I need to get back to my initial real root. How the hell I do that? Script example: `mount $disk_image $mount_point`; chdir($mount_point); chroot($mount_point); #[Do my things...] #<Exit chroot wanted here> `umount $mount_point`; #[Post install things...] I've tried exit; but obviously that exit the whole script. Searching for a way to exit the chroot I've found a number of scripts who aim to exit an already setup chroot (privilege escalation). Since I do the chroot here theses methods do not aplies. Tried some crazy things like: opendir REAL_ROOT, "/"; chdir($mount_point); chroot($mount_point); chdir(*REAL_ROOT); But no go. UPDATE Some points to consider: * *I can't split the script in multiple files. (Silly reasons, but really, I can't) *The chrooted part involve using a lot of data gathered earlier by the script (before the chroot), enforcing the need of not lunching another script inside the chroot. *Using open, system or backticks is not good, I need to run commands and based on the output (not the exit code, the actual output) do other things. *Steps after the chroot depends on what was done inside the chroot, hence I need to have all the variables I defined or changed while inside, outside. *Fork is possible, but I don't know a good way to handle correctly the passing of informations from and to the child. A: You can't undo a chroot() on a process - that's the whole point of the system call. You need a second process (a child process) to do the work in the chrooted environment. Fork, and have the child undergo the chroot and do its stuff and exit, leaving the parent to do the cleanup. A: Try spawning a child process that does the chroot, e.g. with system or fork depending on your needs, and waiting for the child to return the main program continues. A: This looks like it might be promising: Breaking Out of a Chroot Jail Using PERL A: The chrooted process() cannot "unchroot" itself by exiting (which would just exit). You have to spawn a children process, which will chroot. Something along the lines of the following should do the trick: if (fork()) { # parent wait; } else { # children chroot("/path/to/somewhere/"); # do some Perl stuff inside the chroot... exit; } # The parent can continue it's stuff after his chrooted children did some others stuff... It stills lacks of some error checking thought. A: Save the original root as the current working directory or as a file descriptor: chdir "/"; chroot "/mnt"; # Do something chroot "."; OR open DIR, "<", "/"; chroot "/mnt"; # Do something chdir DIR; chroot "."; close DIR;
{ "language": "en", "url": "https://stackoverflow.com/questions/7613325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I add/remove an element to/from the first td of the table before text? I have a div with id (titlediv_1265601). How can I add/remove a * to the first td of the table before "Adjuster Name:" based on the following condition using jquery? if(a == 'addSpan') {} else if(a == 'RemoveSpan') {} <div id="titlediv_1265601" style="width: 100%; position: relative; visibility: visible; display: block;"> <table> <tbody> <tr> <td id="AdjusterOrAdjusterAssistantCell" class="MyTableHeadingCell">Adjuster Name:</td> <td class="MyTableTagsCell"><input type="text" id="AdjusterOrAdjusterAssistant"></td> <td class="MyTableHeadingCell"></td> <td class="MyTableTagsCell"></td> </tr> </tbody> </table> </div> A: $("#AdjusterOrAdjusterAssistantCell") .prepend('<span class="Required" title="Required">* </span>'); will probably work correctly. A: If I understood you correctly: You can use the :first-child pseudo selector to access the first <td> in the table, and then jQuery's prepend()` to prepend your desired content. $('#titlediv_1265601 table td:first-child').prepend('<span class=“Required” title=“Required”>* </span>'); A: To add: $("#AdjusterOrAdjusterAssistantCell").prepend('<span class="Required" title="Required">*</span>'); To remove: $("#AdjusterOrAdjusterAssistantCell span").remove();
{ "language": "en", "url": "https://stackoverflow.com/questions/7613329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Structure of C language Why does this work printf("Hello" "World"); Whereas printf("Hello ""World"); does not? ANSI C concatenates adjacent Strings, that's ok... but it's a different thing. Does this have something to do with the C language parser or something? Thanks A: The string must be terminated before the end of the line. This is a good thing. Otherwise, a forgotten close-quote could prevent subsequent lines of code from executing. This could cost significant time to debug. These days syntax coloring would provide a clue, but in the early years there were monochrome displays. A: You can't make a new line in a string literal. This was a choice made my the designers of C. IMO it's a good feature though. You can however do this: printf("Hello\ ""World"); Which gives the same results. A: The C language is defined in terms of tokens and one of the tokens is a string literal (in standardese: an s-char-sequence). s-char-sequences start and end with unescaped double quotes and must not contain an unescaped newline. Relevant standard (C99) quote: > Syntax > string-literal: > " s-char-sequence(opt) " > L" s-char-sequence(opt) " > s-char-sequence: > s-char > s-char-sequence s-char > s-char: > any member of the source character set > except the double-quote ", backslash \, > or new-line character > escape-sequence Escaped newlines, however, are removed in an early translation phase called line splicing, so the compiler never gets to interpret them. Here's the relevant standard (C99) quote: The precedence among the syntax rules of translation is specified by the following phases. * *Physical source file multibyte characters are mapped, in an implementationdefined manner, to the source character set (introducing new-line characters for end-of-line indicators) if necessary. Trigraph sequences are replaced by corresponding single-character internal representations. *Each instance of a backslash character (\) immediately followed by a new-line character is deleted, splicing physical source lines to form logical source lines. Only the last backslash on any physical source line shall be eligible for being part of such a splice. A source file that is not empty shall end in a new-line character, which shall not be immediately preceded by a backslash character before any such splicing takes place. *The source file is decomposed into preprocessing tokens6) and sequences of white-space characters (including comments). A source file shall not end in a partial preprocessing token or in a partial comment. Each comment is replaced by one space character. New-line characters are retained. Whether each nonempty sequence of white-space characters other than new-line is retained or replaced by one space character is implementation-defined. *Preprocessing directives are executed, macro invocations are expanded, and _Pragma unary operator expressions are executed. If a character sequence that matches the syntax of a universal character name is produced by token concatenation (6.10.3.3), the behavior is undefined. A #include preprocessing directive causes the named header or source file to be processed from phase 1 through phase 4, recursively. All preprocessing directives are then deleted. *Each source character set member and escape sequence in character constants and string literals is converted to the corresponding member of the execution character set; if there is no corresponding member, it is converted to an implementationdefined member other than the null (wide) character.7) *Adjacent string literal tokens are concatenated. *White-space characters separating tokens are no longer significant. Each preprocessing token is converted into a token. The resulting tokens are syntactically and semantically analyzed and translated as a translation unit. *All external object and function references are resolved. Library components are linked to satisfy external references to functions and objects not defined in the current translation. All such translator output is collected into a program image which contains information needed for execution in its execution environment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Set Base URL in Yii Framework When I do print_r(Yii::app()->request->baseUrl) I get an empty string. A post on the Yii forum says this is blank by default. How can I change its default value so that I can use absolute URLs? A: You can edit /path/to/application/protected/config/main.php to change the default value. Add a request component, and configure baseUrl porperty. return array( ... 'components' => array( ... 'request' => array( 'baseUrl' => 'http://www.example.com', ), ), ); A: It's most likely blank because your bootstrap file (index.php) is at your web root. If it wasn't, you should see some value. Changing it would defeat it's purpose. You would use like: href="<?php echo 'http://www.myhost.com' . Yii::app()->request->baseUrl; ?>/css/screen.css" which for most cases wouldn't change the path, but if you did, say, decide to put your Yii app inside a subdirectory, then it would be portable. (Simply remove the http method and hostname above to make it work on the same host the user is on.) A: As the post in that forum says, it might be different for different platforms, or if the web app isnt located in the default folder. All these things work for me: echo Yii::app()->request->baseUrl."<br/>" ; print_r(Yii::app()->request->baseUrl); echo "<br/>"; var_dump(Yii::app()->getBaseUrl(true)); echo "<br/>"; echo Yii::app()->request->getBaseUrl(true); I used yiic to create the web app, with default settings using the following command in a terminal, yiic webapp /path/to/webapp So that generates the necessary directory structure for the web app, and also the default skeleton files. Try it and then see how it works. I'm new to yii myself. Edit: This solution might have worked for the op, but the correct way baseUrl can be set is shown by ecco's answer to this question. A: Yii::app()->baseUrl returns just a relative Path from the url to index.php for example: 127.0.0.1/index.php returns '' 127.0.0.1/yii/index.php returns '/yii' A: If you are using Url helper to generate urls, you will need to set baseUrl key to UrlManager component 'urlManager' => [ 'baseUrl' => 'http://example.com', Then you can create absolute url by using Url helper as, echo Url::to(['site/index', 'src' => 'ref1', '#' => 'name'], true); // output ===> http://example.com/index.php?r=site%2Findex&src=ref1#name A: try echo Yii::$app->baseUrl(true) Note that the true parameter is what does the needful. A: Using Yii 2.0.13.1 the below code is working fine <?php echo Yii::$app->request->baseUrl; ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7613335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: c++ inheritance: error C2614 calling base class' constructor I have a base class 'A' which has a subclass 'B' which has a subclass 'C' which has a subclass 'D'. I want D to call 'A's constructor, D(int x,int y):A(x,y){}; but I am getting the error message: error C2614: 'D' : illegal member initialization: 'A' is not a base or member. D can call any of 'C's constructors fine but that is not what I want. Any help would be super appreciated. A: You're stuck, that's the way C++ works - you only get to call the constructor of your immediate parent. You can daisy chain them so that D calls C's constructor which calls B's constructor which calls A's constructor. D(int x,int y):C(x,y){}; C(int x,int y):B(x,y){}; B(int x,int y):A(x,y){}; A: As Mark Ransom's answer states, a derived class is only allowed to call its base class' constructor. In your case, you can solve the problem by passing along the constructor arguments to D down the inheritance hierarchy until A's constructor is called by B with those arguments. Another option is to create a protected function, say A::init( args ) that can be called by D directly. A: In addition to the option of passing arguments down the inheritance hierarchy or having a protected member function in the base class, you could also solve this by using virtual inheritance. With virtual inheritance all base class constructors are called directly from the derived class so you don't have to go through the inheritance chain. class A { public: A(){} public: A(int x, int y){} }; class B : public virtual A { public: B(){} }; class C : public virtual B { public: C(){} }; class D : public virtual C { public: D(int x,int y):A(x,y){}; };
{ "language": "en", "url": "https://stackoverflow.com/questions/7613336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Trigger a function inside a JQuery file jquery.js from a html Lets say This is my html form definition: <form id="feedback" action="" enctype="multipart/form-data" method="post"> The jQuery file is defined in the head tag: <script type="text/javascript" src="js/ajaxarchive.js"></script> I've also created a html div within an input field as a button: <div id ="button" class="button"> <input type="submit" name="submit" id="submit" value="Enviar" /> </div> I have JavaScript code inside my index.html and I prefer keep the code to validate my form outside the index.htm. I could add my functions in a sentence like this (but I rather want to call my functions from an external file): if ($li_e.attr('class')==='cc_content_13'){ /*here I try to recieve code from the ajaxarchive.js inside functions*/ } How I define the functions also inside the ajaxarchive.js in order to to something like var formData = $('form').serialize(); submitForm(formData); <-- This is the name of the function A: It sounds like you want to hook up some validation logic to the clicking of the "Submit" button without modifying the actual HTML to include a reference. If that's the case then just bind to the click event in an external js file $(document).ready(function() { $('#submit').click(function() { // Call your function here. }); }); A: You can bind a function to your form's "submit" event. You can define your function anywhere you wish, as long as you include its source file before calling $.ready. // somewhere in $(document).ready: $("#feedback").submit(yourExternalFunctionNameHere); Where parameter e in the function is the event object. Make sure to call e.preventDefault() or return false inside the function so the form won't submit by default - you can submit it manually by using: $("#feedback").submit();
{ "language": "en", "url": "https://stackoverflow.com/questions/7613337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Slerp with more than two points The correct way to interpolate between two points on a sphere is using slerp. How would one interpolate between more than two points on a sphere? So summing a set of points with different weights on the surface of a sphere? Simply summing the points multiplied by their weights and then normalising the result is not accurate enough when the angles are large. We need 'true' spherical interpolation. A: I asked this question on math.stackexchange.com, and someone found a paper that describes exactly this. Here it is: Spherical Averages and Applications to Spherical Splines and Interpolation A: The problem I see is: Slerp gives constant velocity. That is, a given increment in your interpolation parameter gives you the same distance on the sphere, regardless of where you are on the [0,1] range. Unfortunately, because the sphere is curved, you can't do this for more than one interpolation parameter. Either you need to give up constant velocity, or give up interpolating with more than one parameter. You may be able to find an interpolation function that isn't constant velocity that nonetheless satisfies your requirements. But because of the above problem, I don't think it will correspond directly and symmetrically to the 1-D slerp.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: The operation has timed out--Exception in a WCF Service RSS Hello I have created a WCF Service which has a method as public List<AppharborDbModel.MMTS_Stations> GetStations() { db = new AppharborDbModel.AppHarborDBEntities(); var x = from n in db.MMTS_Stations select n; return x.ToList<AppharborDbModel.MMTS_Stations>(); } When I'm consuming it from client application I'm getting the following exception... TimeOutException The request channel timed out while waiting for a reply after 00:00:58.8880000. Increase the timeout value passed to the call to Request or increase the SendTimeout value on the Binding. The time allotted to this operation may have been a portion of a longer timeout. The operation has timed out Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Net.WebException: The operation has timed out Source Error: Line 601: Line 602: public System.Collections.Generic.List<ServiceWebReference.MMTS_Stations> GetStations() { Line 603: return base.Channel.GetStations(); Line 604: } Line 605: } And I'm using "WCF Service" web template in .Net 4.0 which has implicit endpoints and bindings.. So there is no end points r bundings in web.config. Where should I change TimeOut value? A: Change your timeouts on the server that is hosting your WCF endpoint: Explaination of different timeout types
{ "language": "en", "url": "https://stackoverflow.com/questions/7613342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Programmatically apply an XSL transform outside the browser I have XML data which I want to be able to display in a browser through an XSL Transform, and also compile with XeLaTeX. Inside the XML file, I have set the stylesheet to be the one for the browser, and currently, to get LaTeX output I have to go into the XML file, change that, open it in a browser, copy it into a file, save the file and run XeLaTeX against it. Instead, I would like to leave the XML file associated with the XSLT stylesheet that transforms it to XHTML, and just have a build script that would: * *Apply the LaTeX XSL transform file to the XML file, writing the result to a .tex file. *Run XeLaTeX against it. *Run XeLaTex against it again (the document requires second-pass). *Clean up log files, etc., unless instructed not to do so. I know how to do #2-#4. What is the best way to accomplish #1? For example, is there a Python3 recipe for applying an XSL transform to an XML document? A: If your stylesheet written in the XSLT 1.0 you can use libxslt through lxml (libxml2 & libxslt python bindings). Look for lxml examples (link to google web cache, because actual page aren't available on the http://lxml.de) A: Following the lead given by @Phillip Kovalev, I have come up with this Python3 code: from lxml import etree def transform(xsltpath:str, xmlpath:str): return etree.XSLT(etree.parse(xsltpath))(etree.parse(xmlpath)) def main(): import sys print(transform(sys.argv[1], sys.argv[2])) if __name__ == '__main__': main() Kudos to the developer of lxml--works like a charm!
{ "language": "en", "url": "https://stackoverflow.com/questions/7613345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: lose data in the form when clicking the back button on any browser (Django) My current application has a form which the user fills and hits the submit button to get the output data. But, I loose all the data which was entered into the form when I click the back button on the browser. All the drop down select list get reset to initial setting. Is there a way where I can store these inputted values and populate it back when the user hits the back button. I want to avoid the user from entering the values into the from again and again.. Thanks A: One way of doing it is to use the Javascript beforeunload event, which occurs when you navigate away from a page, then to store the data in a cookie. When the user comes back, you could check for the cookie's existance and content, and repopulate the fields with that data. This is my first reply on StackOverflow, so I hope it was helpful! :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7613346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Delete rows in table view associated with core data My table view is populated from an array containing data in the core data, I want to delete rows while updating the core data correspondingly, here is my code of deletion. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the row from the data source. NSManagedObject *selectedObject = [arrayList objectAtIndex:[indexPath row]]; [managedObjectContext deleteObject:selectedObject]; [arrayList removeObjectAtIndex:[indexPath row]]; [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; } } However, I am getting the following error when I hit delete button: *** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-1448.89/UITableView.m:995 *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (4) must be equal to the number of rows contained in that section before the update (4), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted).' My data source is arrayList containing NSManagedObjects fetched from core data. Ideas? Thanks in advance! Update: Now the deletion can work after I remove the data in the arrayList, but data in core data didn't get deleted correspondingly, when app relaunches, the list is still the same. A: It means that even after you deleted the row, the datasource is still returning 4 as the number of rows in section 0. So now the table view only has 3 rows displayed for a section that should have 4. From your description, you probably need to delete the object from arrayList in addition to deleting it from CoreData. Alternatively reload arrayList after deleting the object from CoreData and then delete the row.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why Can't I access src/test/resources in Junit test run with Maven? I am having a problems running the following code: configService.setMainConfig("src/test/resources/MainConfig.xml"); From within a Junit @Before method. Is this the way Maven builds out its target folder? A: Access MainConfig.xml directly. The src/test/resources directory contents are placed in the root of your CLASSPATH. More precisely: contents of src/test/resources are copied into target/test-classes, so if you have the following project structure: . └── src └── test ├── java │   └── foo │   └── C.java └── resources ├── a.xml └── foo └── b.xml It will result with the following test CLASSPATH contents: * */foo/C.class */a.xml */foo/b.xml To actually access the files from Java source, use getClass().getResource("/MainConfig.xml").getFile(). A: I ran into the same problem today and I have found some solutions. First, here is my file structure: . └── src │ └── test │ ├── java │ │ └── mypackage │ │ └── MyClassTest.java │ └── resources │ └── image.jpg └── target └── test-classes ├── image.jpg └── mypackage └── MyClassTest.class What is not working: (Java 11 synthax) var imgFile = new File("image.jpg"); // I was expecting that Junit could find the file. var absPath = file.getAbsolutePath(); // /home/<user>/../<project-root>/image.jpg var anyFileUnderThisPath = file.exists(); // false What we can notice is that the absolute path does not point at all on my image! But if I had an image under at the project-root, then it would have worked. Solution 1: Paths (introduced in Java 7) var relPath = Paths.get("src", "test", "resources", "image.jpg"); // src/test/resources/image.jgp var absPath = relPath.toFile().getAbsolutePath(); // /home/<user>/../<project-root>/src/test/resources/image.jpg var anyFileUnderThisPath = new File(absPath).exists(); // true As we can see, it points on the right file. Solution 2: ClassLoader var classLoader = getClass().getClassLoader(); var url = classLoader.getResource("image.jpg"); // file:/home/<user>/../<project-root>/target/test-classes/image.jpg var file = new File(url.getFile()); // /home/<user>/../<project-root>/target/test-classes/image.jpg var anyFileUnderThisPath = file.exists(); // true Note that now the file is searched under the target directory! and it works. Solution 3: File (Adaptation of the non-working example) var absPath = new File("src/test/resources/image.jpg").getAbsolutePath(); var var anyFileUnderThisPath = new File(absPath).exists(); // true Which works also after taking the absolute path and putting src/test/resources/ as prefix. Summary All three solutions works but having to put src/test/resources/ is, in my own opinion not elegant, and this is why I would prefer the 2nd solution (ClassLoader). Sources: * *Read file and resource in junit test *Java read a file from resources folder A: I guess setMainConfig expects the path of a resource, that it will load using the ClassLoader, and not a relative file path. It would help if you linked to the javadoc of this mysterious configService.setMainConfig method. If my guess is correct, then the path should just be MainConfig.xml. Mave copies the contents of src/test/resources to the target/test-classes (IIRC) folder. And this test-classes folder is in the classpath of the unit tests.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "48" }
Q: Ruby: day selection program (select next available day from a list) I'm tryind to build a helper to select the next available day from a list. I have a list of days as a reference (those are the day where I want something to happen) class_list = ["Monday","Saturday","Sunday"] I need to check the current day and match it in the list. If it's part of the list I select it, if it isn't I select the next one from the list. this is what i have so far: #select current day, get its name value and weekday number value today = Time.now today_name = today.strftime("%A") #not sure which of the 2 following line is better #today_index = DateTime.parse(today_name).wday today_index = today.strftime("%u").to_i Then I do the matching if class_list.include? today_name #victory!!! puts today_name else puts "find next day" class_list.each do |x| if DateTime.parse(x).wday > today_index puts "result #{x}" break end end end When I run it seems to work fine, but as i'm just learning Ruby i'm always wondering if i'm not overcomplicating things. Does this code looks alright to you Ruby masters? A: I would better have a map linking a given day to the following one and a default value if the day is not found: days = {:Monday => :Tuesday, :Tuesday => :Wednesday ...} days.default = :Monday When you do days[:Monday] you get :Tuesday when you try to get a non existing entry, you get the default. A: For the part: if class_list.include? today_name #victory!!! puts today_name else puts "find next day" class_list.each do |x| if DateTime.parse(x).wday > today_index puts "result #{x}" break end end end You could write it like this: if class_list.include? today_name #victory!!! puts today_name else puts "find next day" result = class_list.find {|e| DateTime.parse(e).wday > today_index } puts "result = #{result}" end A: require 'date' def next_date_from(ar) cur_day = Date.today cur_day += 1 until ar.include?(cur_day.strftime('%A')) cur_day end puts next_date_from(%w(Monday Saturday Sunday)) #=>2011-10-01
{ "language": "en", "url": "https://stackoverflow.com/questions/7613360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Simply getting fields from django query set class Question(models.Model): question_text = ... class Answer(models.Model): question = models.ForeignKey ... user = models... Basically, what I'm trying to do is return the set of questions that have been unanswered by the user. So basically, lets say answers = Answer.objects.exclude(user=my_user), i need to somehow do Question.objects.filter(id__in=answers.question.id). This last statement is obviously not going to work, but I hope you can get the idea. Appreciate any help on this. Thanks. A: Question.objects.exclude(id__in=[answer.question.id for answer in Answer.objects.filter(user='Joe')])
{ "language": "en", "url": "https://stackoverflow.com/questions/7613362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: using frameset in Spring 3 I am a newbie to Spring 3 , and am learning on my own. I have run into a issue regarding framesets. In my page , I have included 3 framesets , something like this <frameset rows="10"> <frame src="/WEB-INF/views/frame1.jsp" name="frame1"scrolling="no"> <frameset cols="20%,*"> <frame src="/WEB-INF/views/frame2.jsp" name="frame2"> <frame src="/WEB-INF/views/frame3.jsp" name="frame3"> </frameset> </frameset> Now when I run the frameset page it throws a resource not found exception , I do not get why. Is it that I have to define the mapping for each of the frame*.jsp pages in the Controller. Any examples would be appreciated Thanks in advance : Vivek A: All pages inside WEB-INF directory not accessed to user, so if this is a simple JSP pages, move it to public folder (and check that it accessable via browser). A: Normally the browser itself should not be able to access files located under WEB-INF (this is an app-container thing). You'd need to map them to something publicly-accessible; a view, a JSP not under WEB-INF, etc. A: A frame source would require an actual mapping or a publicly available file. You will notice that you will get a 404 if you try to hit that resource in a browser. A: Instead of framesets directly having link to jsp as src, point it to a server side action. Let the action handler (for ex. servlet or spring controller) do a forward to your jsp present inside web-inf. A: I had the same problem of not being linked to the jsp page in one frames in the frameset. Note that each frame is a new http request. the flow is web.xml ---> servletname-servlet.xml --> controller --> view resolver. put some thing like this in your frameset frame frame src="frame_b" link it with controller @RequestMapping(value = "/frame_b", method = RequestMethod.GET) public ModelAndView goFrameb(ModelMap model) { return new ModelAndView("frame_b"); } view resolver can map to your jsp page like frame_b.jsp **** jsp is present in web-inf/jsp/*.jsp A: I had the same problem of not being linked to the jsp page in one frames in the frameset. Note that each frame is a new http request. the flow is web.xml ---> servletname-servlet.xml --> controller --> view resolver. put some thing like this in your frameset frame src of frame has src="frame_b" link it with controller @RequestMapping(value = "/frame_b", method = RequestMethod.GET) public ModelAndView goFrameb(ModelMap model) { return new ModelAndView("frame_b"); } view resolver can map to your jsp page like frame_b.jsp **** jsp is present in web-inf/jsp/*.jsp
{ "language": "en", "url": "https://stackoverflow.com/questions/7613363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Assigning relevant splash screens in config.xml for PhoneGap I am currently developing an application using PhoneGap for multiple devices. How do we configure it in config.xml so that we can specify the size of splash screen (and matter of fact for icons) for the different devices (e.g. iPhone, iPad, Android)? A: For Android: design relevant Splash and icon images and drop them in respective drawables (drawable-mdpi, drawable-hdpi etc ..) folders For iPhone: Just select Default.png images in your XCode for both iPhone and iPad
{ "language": "en", "url": "https://stackoverflow.com/questions/7613368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cygwin - Running msbuild with switches I'm trying to improve our build automation using bash. My shell scripting leaves a lot to be desired but essentially I want to be able to use a bash shell script to run MSBuild.exe passing in certain build switches. So in myscript.sh there's a line : C:/Windows/Microsoft.NET/Framework/v4.0.30319/MSBuild.exe /maxcpucount:8 /verbosity:q /p:Configuration=Debug C:/Myfolder/Main.sln This fails due to the /p:Configuration=Debug. I can say that with certainty as without it the execution of MSBuild.exe works. Can anyone help on this? A: As it turns out it was due to /p: When using /property:Configuration=Debug it works. Thanks for the help. Tim
{ "language": "en", "url": "https://stackoverflow.com/questions/7613371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: using .asmx using lighttpd and mono fastcgi I have deployed a web service to a ubuntu server running lighttpd and fastcgi-mono-server2. The .asmx page loads correctly but when I test the method I get a 404. My web service is called Import.asmx and my method is called download and the 404 comes back saying import.asmx/download does not exist Using xsp2 the same service works perfectly I assume it is something to do with how the /download gets served by lighttpd/fastcgi but cannot work out how to fix it. A: Solved the 404 error... but now I have a 500. Actually I was getting this error on every MyService.asmx/SomeMethod post calls. The solution [NOT REALLY] I've figured it out: location ~ \.(aspx|asmx|ashx|asmx\/(.*)|asax|ascx|soap|rem|axd|cs|config|dll)$ { fastcgi_pass 127.0.0.1:9001; index index.html index.htm default.aspx Default.aspx; fastcgi_index Default.aspx; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include /etc/nginx/fastcgi_params; } I've change it from only asmx to asmx/()*. Ok no 404 but now a 500: System.Web.HttpException: Method 'POST' is not allowed when accessing file '/Services/MyService.asmx/MyMethod'. This findings give me some clues that nginx don't handle properly this kind of requests. After googling for almost 2 hours I've found a solution: location ~ \.asmx(.*) { fastcgi_split_path_info ^(.+\.asmx)(.*)$; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info; include /etc/nginx/fastcgi_params; fastcgi_index Default.aspx; fastcgi_pass 127.0.0.1:9001; } I wasn't to far from it. Just add this location rule before the current you have and works fine. A: I had the very same issue. Turned out to be default directive for serving 404 when not finding assets. Removed the following line: try_files $uri $uri/ =404; And add PATH_INFO as fastcgi param in /etc/nginx/fastcgi_params: fastcgi_param PATH_INFO $fastcgi_path_info; That fixed it for me. Hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AJAX Horizontal Scrolling with scrollbar I need to create something like this site, I found many jQuery infinite scrolling scripts that allow you to load contents using AJAX while you're scrolling. What I need is very similar, except I want it to be horizontal and I want to set the size of the scroll bar according to the amount of contents I have. If you check out this website you'll see that you can jump from page one to page lets say 3 without loading the second page. Any idea how they do that ? their scroll bar is draggable too ! This is exactly what I need but don't know how. Any help is appreciated. A: jQuery lazyload works with horizontal scrolling too. Look at this example that I created here. The site you are linking to is not a "horizontal scrolling" page. That's actually pagination not scrolling. If you want to do pagination then you don't need any plug in at all. Just call your AJAX when page or tab link clicked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++ Type Traits Overview Has anybody put together a list of all the type traits available in standard <type_traits> (GCC-4.6.1) and Boost's own <boost/type_traits.hpp>? A: The full lists of traits are available online: * *The Boost documentation lists the traits in <boost/type_traits.hpp>; *The C++0x draft lists the traits in <type_traits>. However, the GCC implementation is not yet complete. GCC 4.6 is missing: * *The std::underlying_type trait. This one will be on GCC 4.7. *The std::is_trivially_X series of traits. Instead it has std::has_trivial_default_constructor and similar that seem to have the name from an earlier draft. The one about the move constructor is missing. *The std::is_nothrow_X series of traits. These also use an older name like std::has_nothrow_default_constructor. The one about the move constructor is missing too. *The std::aligned_union trait. This one can be easily implemented in terms of std::aligned_storage, which is currently supported.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any quick way to determine first k digits on n^n I am writing a program where I need to know only the first k (k can be anywhere between 1-5) numbers of another big number which can be represented as n^n where n is a very large number. Currently I am actually calculating n^n and then parsing it as a string. I wonder if there is a better more fast method exists. A: if you mean the least significant or rightmost digits, this can be done with modular multiplication. It's O(N) complexity and doesn't require any special bignum data types. #include <cmath> #include <cstdio> //returns ((base ^ exponent) % mod) int modularExponentiation(int base, int exponent, int mod){ int result = 1; for(int i = 0; i < exponent; i++){ result = (result * base) % mod; } return result; } int firstKDigitsOfNToThePowerOfN(int k, int n){ return modularExponentiation(n, n, pow(10, k)); } int main(){ int n = 11; int result = firstKDigitsOfNToThePowerOfN(3, n); printf("%d", result); } This will print 611, the first three digits of 11^11 = 285311670611. This implementation is suitable for values of N less than sqrt(INT_MAX), which will vary but on my machine and language it's over 46,000. Furthermore, if it so happens that your INT_MAX is less than (10^k)^2, you can change modularExponentiation to handle any N that can fit in an int: int modularExponentiation(int base, int exponent, int mod){ int result = 1; for(int i = 0; i < exponent; i++){ result = (result * (base % mod)) % mod; //doesn't overflow as long as mod * mod < INT_MAX } return result; } if O(n) time is insufficient for you, we can take advantage of the property of exponentiation that A^(2*C) = (A^C)^2, and get logarithmic efficiency. //returns ((base ^ exponent) % mod) int modularExponentiation(int base, int exponent, int mod){ if (exponent == 0){return 1;} if (exponent == 1){return base % mod;} if (exponent % 2 == 1){ return ((base % mod) * modularExponentiation(base, exponent-1, mod)) % mod; } else{ int newBase = modularExponentiation(base, exponent / 2, mod); return (newBase * newBase) % mod; } } A: There are two possibilities. If you want the first k leading digits (as in: the leading digit of 12345 is 1), then you can use the fact that n^n = 10^(n*Log10(n)) so you compute the fractional part f of n*Log10(n), and then the first k digits of 10^f will be your result. This works for numbers up to about 10^10 before round-off errors start kicking in if you use double precision. For example, for n = 2^20, f = 0.57466709..., 10^f = 3.755494... so your first 5 digits are 37554. For n = 4, f = 0.4082..., 10^f = 2.56 so your first digit is 2. If you want the first k trailing digits (as in: the trailing digit of 12345 is 5), then you can use modular arithmetic. I would use the squaring trick: factor = n mod 10^k result = 1 while (n != 0) if (n is odd) then result = (result * factor) mod 10^k factor = (factor * factor) mod 10^k n >>= 1 Taking n=2^20 as an example again, we find that result = 88576. For n=4, we have factor = 1, 4, 6 and result = 1, 1, 6 so the answer is 6.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Autorelease CFMutableDictionary How do I autorelease a CFMutableDictionary? I'm creating it like this: self.mappingByMediatedObject = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); And in dealloc: self.mappingByMediatedObject = nil; A: CoreFoundation doesn't have a notion of autorelease-- that's a Cocoa-level construct. However, for the objects that are "toll-free" bridged across worlds like strings and the collection classes, you can get the same result by casting the CF reference to its corresponding Cocoa reference, and sending it the -autorelease message, like this: [(NSDictionary *)aDictionaryRef autorelease]; In your case, though, you might not really want to use autorelease here, because you're not handing back the reference for a Cocoa caller. Why not be a little more explicit around your allocation instead and just releasing it after setting it, like this: CFDictionaryRef mapping = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); self.mappingByMediatedObject = mapping; CFRelease(mapping); A: CFDictionary and NSDictionary are toll-free bridged. This means the CoreFoundation object and its Cocoa counterpart are interchangable. So to autorelease a CFDictionary you can write the following: CFDictionary dict = CFDictionaryCreateMutable(...); self.mappingByMediatedObject = dict; [(NSDictionary*)dict autorelease]; Of course autorelease the dictionary only if your mappingByMediatedObject property retains its value (@property(retain)) A: As of iOS7 and Mac OS X 10.9 you can use the Core-Foundation auto release function CFAutorelease().
{ "language": "en", "url": "https://stackoverflow.com/questions/7613399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Caliburn Micro - is it possible to intercept calls to execute a command? I want to add error handling to my view-models so that when a command is executed and an exception thrown, the error is handled gracefully and a modal dialog displayed. I've got this working but my approach is a too wordy. Errors are trapped within a command and then published via an IObservable. A behavior subscribes to the errors - creating an appropriate view model and passing to the WindowManager. While it works, I'd prefer something more declarative. Instead I want to decorate or intercept calls to commannds (bound to a button) and provide generic error handling. The try-catch might call out to a method on the view model or command that is decorated with a Rescue attribute. I understand this is possible within Caliburn but can it be done with Micro? Perhaps there's an alternative approach? A: Have a look at this question I asked on SO and subsequently answered with help via the CM codeplex forum. I slightly modified the RescueAttribute of this CM filters implementation to allow the error handling routine to be executed as a coroutine. This in combination with the ShowModal IResult available in some of the samples should get you what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to use the required property in IE? I have code like this: <input required> In good browsers I can use jquery like this to add a class of error to the input: $('input[required]').addClass('error'); It doesn't work in IE though. I will resort to this otherwise, but it's not as neat... HTML: <input data-required=true> Javascript: if( $('input').data('required') ) $('input').addClass('error'); Any ideas? Thanks,Will EDIT: Yea, I am using HTML5. IE actually interprets this: <input required> as: <input required=""> So it is possible to check that like this: if( $('input').prop() == undefined ) But again, it's a bit of a messy way of doing things, especially considering that it is only IE that has the issue. This code works perfectly in all other browsers. I am basically asking if there is a method of checking that is cross browser and tidy. I'm a bit of a perfectionist perhaps! ;) A: using data- attribute is safe and your page will be valid if you use them. But you need qoutation for your value. I'm using data attributes all the time. We support IE7. <input data-required="true"> Or even you can leave the value in cases like this: <input data-required> If you are using data attributes often then it's good to know that you can use dataset property in Chrome developer tools (and Firebug) to access your element's data attributes via console. It's not safe yet to use dataset API in your code. it's not supported in IE8 in your console write: $$('input')[0].dataset and get the data attribute values and properties! A: Try using required="required", it might make older browsers like it better. IMPORTANT NOTE: It's still very much valid to write <input required>
{ "language": "en", "url": "https://stackoverflow.com/questions/7613404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Java Annotations removing string literals from them? Not sure if this is a decent question or not but here it goes. We are trying to implement a UI testing framework (selenium web-driver) and want to use a Page driven design for example class HomePage { @FindBy(how = How.Id, id="myPageHeaderID") private String pageHeader In the simple example above I need to hard-code the "myPageHeaderID" string literal. One of the requirements proposed is that we be able to pull in the "myPageHeaderID" from a property for both maintenance reasons (no code deploy if something changes) and for internationalization reasons. I have been searching around and probably not doing a proper search but is there any way of doing what I am asking above? A: I briefly went down this route, but due to our application it wasn't quite achievable (pages aren't always displayed in the same order once you've visited a page). public class PageElement implements WebElementAdapter, Locatable { private How how; private String using; private boolean required; @FindBy(how = How.ID_OR_NAME, using = DEFAULT_LOCATION_STRATEGY) private WebElement backingElement; public PageElement(How how, String using using) { this.how = how; this.using = using; this.required = true; } /** * This is how the overriding of the element location is done. I then injected * these values in a spring configured bean file. * * This is needed on your config file: * default-lazy-init="true" default-init-method="initialize"> */ public final void initElement() { if (backingElement == null || isStale() { backingElement = getDriver().findElement(getLocationStrategy()); } } public By getLocationStrategy() { By by = new ByIdOrName(using.replace(DEFAULT_LOCATION_STRATEGY, using)); switch(how) { case CLASS_NAME: by = By.className(using.replace(DEFAULT_LOCATION_STRATEGY, using)); break; //Do for others } return by; } public WebElement getBackingElement() { return backingElement; } } public interface WebElementAdapter { WebElement getBackingElement(); } public interface Locatable { By getLocationStrategy(); } I then created common widgets in POJOs, and injected these into page objects which were a collection of these widgets. From there I had a simple test harness which was responsible for taking in strings (which were then executed. Basically it allowed for test cases to be written in SpEL and act on the beans which were injected. It was what I thought a pretty neat project, but I had to shelf it to get some other things done. A: Annotations are essentially metadata. Taking database metadata for example, it would be weird if Oracle database would turn into MySQL, right? Here is the article about Annotation Transformers in TestNG. Didn't try it myself, but I think it could be implemented in some way or another. A: AFAIK, you can call a method from the Annotation. @FindBy(how = How.Id, id=getProp()) private String pageHeader; private String getProp() { String prop = //whatever way you want to get the value return prop; } Doesn't that work?
{ "language": "en", "url": "https://stackoverflow.com/questions/7613408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to access C# MessageHeader Concrete types I receive a System.ServiceModel.Channels.Message from a WCF service, it has a message header that at runtime is of type System.ServiceModel.Channels.ToHeader but I can't find this type anywhere to upcast it to use the ToHeaders properties. Is this a dynamic type that can only be accessed by reflection? A: You shouldn't need to access the members of the ToHeader class (which is internal). The only property which cannot be accessed from the base (public) class is the To (of type Uri), which you can access via the message directly (message.Headers.To).
{ "language": "en", "url": "https://stackoverflow.com/questions/7613410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Implement geocoding in android 2.2 Friends... i'm woking on a project on geocoding.I tried to implement it several times.But i'm not able to retrieve the latitude and longitude values corresponding to a location.Please help me out to complete my project.. A: try this code hope this will help you: package com.example.map; import java.util.List; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import android.app.AlertDialog; import android.app.Dialog; import android.location.Address; import android.location.Geocoder; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class mapView extends MapActivity{ MapView myMap; Button btnSearch; EditText adress; Geocoder gc; double lat; double lon; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); myMap = (MapView) findViewById(R.id.simpleGM_map); // Get map from XML btnSearch = (Button) findViewById(R.id.simpleGM_btn_search); // Get button from xml adress = (EditText) findViewById(R.id.simpleGM_adress); // Get address from XML gc = new Geocoder(this); // create new geocoder instance btnSearch.setOnClickListener(new OnClickListener() { public void onClick(View v) { String addressInput = adress.getText().toString(); // Get input text try { List<Address> foundAdresses = gc.getFromLocationName( addressInput, 5); // Search addresses if (foundAdresses.size() == 0) { // if no address found, // display an error Dialog locationError = new AlertDialog.Builder( mapView.this).setIcon(0).setTitle( "Error").setPositiveButton(R.string.ok, null) .setMessage( "Sorry, your address doesn't exist.") .create(); locationError.show(); } else { // else display address on map for (int i = 0; i < foundAdresses.size(); ++i) { // Save results as Longitude and Latitude // @todo: if more than one result, then show a // select-list Address x = foundAdresses.get(i); lat = x.getLatitude(); lon = x.getLongitude(); } navigateToLocation((lat * 1000000), (lon * 1000000), myMap); // display the found address } } catch (Exception e) { // @todo: Show error message } } }); } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } / * Navigates a given MapView to the specified Longitude and Latitude * @param latitude * @param longitude * @param mv */ public static void navigateToLocation(double latitude, double longitude, MapView mv) { GeoPoint p = new GeoPoint((int) latitude, (int) longitude); // new // GeoPoint mv.displayZoomControls(true); // display Zoom (seems that it doesn't // work yet) MapController mc = mv.getController(); mc.animateTo(p); // move map to the given point int zoomlevel = mv.getMaxZoomLevel(); // detect maximum zoom level mc.setZoom(zoomlevel - 1); // zoom mv.setSatellite(false); // display only "normal" mapview } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7613414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android, rotate 18x18 pixel circle icon, result: icons of different sizes? I'm drawing a bunch of icons on a map. Actually the icons come from the same image rotated. But on the map the images take on two different sizes, I don't know why. This is what the result looks like: http://orangesoftware.net/iconmap.png The image file looks like this: http://orangesoftware.net/arrow18.png The code to rotate the icon: Matrix mtx = new Matrix(); mtx.postRotate(unit.heading); Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.arrow18); Bitmap rotatedBMP = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), mtx, true); BitmapDrawable bmd = new BitmapDrawable(rotatedBMP); Any magically insights appreciated, thanks A: The cause of the variation in sizes is when a rotation is not a multiple of 90 degrees. The bmp becomes a diamond who's corners stick out beyond the ImageView holding it, thus it gets resized to fit the ImageView. The easiest way to take care of this discrepancy is to set the ImageView's scaleType to CENTER. This will simply center the image inside without scaling it to fit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c++ win32 prevent application from running on windows xp I've developed a application which uses Vista (or higher) API's and i would like to add a popup message if the application detects a unsupported OS. I would like to add a popup message when a user runs my application on windows XP. Currently the application just throws a popup(messageBox) saying that some DLL's can't be loaded. I've defined the windows version like this: #define _WIN32_WINNT 0x0600 What do i have to do to prevent from running on versions lower than Vista? Do i have to check the OS version when the application starts (and show a message to the user)? A: If you are using APIs that are not available on XP, you will need to separate your application into a loader and the real app (or a loader and a DLL containing the actual app). Compile the loader with #define _WIN32WINNT 0x0501 to ensure that it can run on XP and display your popup. Check the version with VerifyVersionInfo or GetVersionEx A: In order to show a popup message, you need to run the executable. That means that you have to reduce your windows version to the lowest one you intend to 'support' (support here meaning be able to run at, and show a popup saying that it won't run). That would require you to delay the point were you link to your relevant DLLs, otherwise they won't be found and you would still get the same message box you do know. All in all, there are numerous drawbacks with this approach since you have to build a valid executable both at XP as well as Vista. If you really need this check, then you could have one executable do it and decide whether to show a popup message or start your actual application (in a different executable). A: You could write a very small wrapper app that defines _WIN32_WINNT as 0x0501. Then that program can do an OS check and either display some nice UI for your user (if it is the wrong version of Windows) or just quietly launch your other executable (if it is a supported version of Windows). Ideally your distribution channel (website, etc) would check that the user has a supported version of windows before allowing them to download it. If you use WiX (or MSI directly) to install your app, you can let the installer handle the unsupported OS check. A: You cannot expect dynamic runtime behavior if you enforce static compile time behavior. You need to define the XP windows version so that your exe linkg against the XP DLLs, and then at runtime you need to dynamically change the behavior and load the Vista DLLs and find the entry points 'by hand'. This is, as you'd expect, painful and error prone. Good luck. A: You can define _WIN32_WINNT to a lower value, suitable for 2000 or XP. But then you will need to use explicit linking for Vista only APIs. Changing _WIN32_WINNT will also result in missing type declarations for the Vista only APIs. So, if you know which APIs you need you could leave _WIN32_WINNT at 0x0600 and use explicit linking for those APIs. Obviously you would need a version check too to give a helpful message to the user. Personally I'd take a different route to solving this. I'd check the version at install time and block it there. That allows you to carry on with _WIN32_WINNT 0x0600 and all the conveniences that affords. A: What's happening is the DLLs are being loaded by the application loader and you are seeing the error messages before your application even starts. You need to prevent this from happening. You could put your application into a DLL and create a stub program that performs the OS check like Mystical describes in his answer. Edit: It seems Mystical deleted his answer... Do something like this: OSVERSIONINFO OSversion; OSversion.dwOSVersionInfoSize=sizeof(OSVERSIONINFO); ::GetVersionEx(&OSversion); switch(OSversion.dwPlatformId) { case VER_PLATFORM_WIN32_NT: if(OSversion.dwMajorVersion >= 6) { // Yay, load the DLL and call entry point } default: // Show unsupported OS message } You can call LoadLibrary() to load your application DLL then call whatever entry point in it you defined. Note this answer has a cool list of OS version numbers. A: I don't know how to do this in Visual Studio or other compilers, but in Borland/CodeGear/Embarcadero IDEs, there is an option to set the minimum supported OS version in the compiled executable's PE header. If the OS loader tries to run an executable with an incompatible version, it will not run the executable and will display an error message to the user about the version mismatch. Check if your compiler/IDE has a similar option available. Otherwise, you have to dynamically load the desired APIs at runtime via LoadLibrary()/GetModuleHandle() and GetProcAddress() instead of statically linking to them at compile time. Then you can perform your own OS version checks in your code before using newer API functions that may not be available.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: In excel how to set a cost of 29.00 to a 11 digit no decimal point format How do I tell excel I want the first two digits to be assummed to be decimal places using NNNNNNNNNNN format? thx I'm trying to use excel format to convert 29.00 to following: 00000002900 but it keeps look like the following: 00000000029 // how do I get the 29 to move up by two digits like the first one???? I'm using custom format in excel of "00000000000" but that is not working. thx A: First off, your custom format should be "00000000000" instead of "NNNNNNNNNNN" if I'm not mistaken. If you don't want to see a decimal place you can store all your values in cents instead of dollars (multiply by 100) and use "00000000000". If you want to still use dollars and don't mind a decimal point use "000000000.00" A: I don't think you can do that with a Format mask as the only way would be to actually modify the underlying value. you could use; =TEXT(A1*100,"00000000000")
{ "language": "en", "url": "https://stackoverflow.com/questions/7613425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I go about finding memory leaks in Java applications? I wrote an app for the production team to measure their scores, it runs fine for 2-3 weeks and then the machine that the copies are running on slows down and a restart fixes it. What are the best practice steps for fixing this? A: You need to analyse the Heap and find out what objects are being retained in there that shouldn't be. One option: Try reducing the -Xmx max heap size to expedite an out of memory exception, add this option to the jvm at startup -XX:+HeapDumpOnOutOfMemoryError and then load the heap dump that is generated into something like Eclipse Memory Analyzer. Another option: Dump the heap from your running process using jmap (probably needs sudo privileges) jmap -heap:format=b <pid> and again, load the heap dump binary into jhat or Eclipse Memory Analyzer. If your app is slowing down but not throwing an OutOfMemoryError it is likely that you don't have a leak but you do need to do some JVM tuning because it's spending too much time doing GC. You should be monitoring GC collection times (you can log them using -Xloggc:/tmp/gc.out) or you can use jstat to see how often GC takes place and how long it takes. If you have an application with lots of medium lived objects is the Young Generation big enough (-XX:NewRatio=N) ? If not your app will spend to long promoting objects to the old gen only to have to GC them shortly after (GC in old gen is expensive relative to New Gen, especially when you have fragmented memory). Also - have you enabled the CMS collector? If you have a multi-core machine I suggest you do (-XX:+UseConcMarkSweepGC). A: There are no memory leaks in Java in the traditional sense unless you are using JNI. Memory leak in Java usually refers to creating referenced objects that you are no longer using. The symptom typically is that the memory usage of the application keeps growing. Do you see the memory usage growing? You would do well to search for the exact same question in Google and follow the links. The best practice to address is it usually to use a Profiler to check your allocations. It may also point at performance bottlenecks not caused by the "memory leaks" A: You can check the memory the JVM requires by using an OS utility such as a task manager or top. You can use a profiler to check the memory of your java code, e.g. Java VisualVM. Keep in mind that Java uses garbage collection, so the only way of "memory leakage" is by holding references to (a lot of) unused objects. Josh Bloch's Effective Java item 6 (Eliminate obsolete object references) explains these situations and how to prevent them very well. You can also use further methods to check for this kind of "memory leakage", e.g. static analysis and pluggable type systems or jvm memory options. A: One good thing to track down memory issues is to enable garbage collection logging by adding the following commands to java at startup -verbose:gc -XX:+PrintGCDetails and -XX:+PrintGCTimeStamps. Then you can analyze how the garbage collector behaves, i.e. how often the GC is running, how long time it takes for the garbage collector to reclaim memory, how much memory is being reclaimed and if the used memory of your application is increasing. Here's a document explaining the gc logging output: GC tuning guide for Java 6
{ "language": "en", "url": "https://stackoverflow.com/questions/7613429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: see who entered profile with facebook api I have recently see facebook api, I am interested in that. Does Facebook have any API that help me to visit who entered my profile. I want to know is there any way to track who entered my Facebook page. A: To build an app that tracks profiles is against the Facebook platform policies. You can read about it in the "Prohibited Functionality" section of their policy guide. A: No, Facebook does not give that information out. That would be a huge violation of privacy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Attach keyboard events to html5 canvas It looks like mouse events will add listeners to canvas elements fine, but keyboard events don't seem to be working for canvas elements. Example: http://jsfiddle.net/H8Ese/1/ Browsers: Chrome 14.0 FF 5.0.1 I know I can use the document level listeners, but I'm trying to get the Canvas element first (so that your keyboard works everywhere else on the page). Any ideas on how to get key event listening working on canvas elements? A: I don't think you can add keyboard event listener directly to the canvas. If you don't want to register event handler on window level then I think you can wrap the canvas inside a div and register keyboard events on the div. <div id="canvasWrapper" style="border:1px solid; width:600px; height:400px;"> <canvas id="canvas" width="600" height="400" > Could not create Canvas! </canvas> </div> jQuery("#canvasWrapper").keypress(function(e){ keys[e.keyCode] = true; alert("key pressed!"); }); Another interesting way is to use tabIndex on the canvas tag and bind keypress on the canvas. I have updated the code at jsfiddle, pasting here too for future references. <canvas id="my-canvas" tabindex="1"></canvas> $("#my-canvas").bind({ keydown: function(e) { var key = e.keyCode; var elem=document.getElementById("my-canvas"); var context=elem.getContext("2d"); context.font = "bold 20px sans-serif"; context.clearRect(0,0,300,200); context.fillText("key pressed " + key, 10,29); }, focusin: function(e) { $(e.currentTarget).addClass("selected"); }, focusout: function(e) { $(e.currentTarget).removeClass("selected"); } }); $("#my-canvas").focus();
{ "language": "en", "url": "https://stackoverflow.com/questions/7613433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Facing XML Parsing Error while creating XULRunner application I tried creating an XULRunner app as given in the tutorial - http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xulrunner_about.html But when I tried running the app it gave me the following error - XML Parsing Error: Location: chrome://pyxpcom_gui_app/content/pyxpcom_gui_app.xul Line Number 19, Column 48: persist="screenX screenY width height"> -----------------------------------------------^ I am not getting what went wrong. Content of pyxpcom_gui_app.xul - <window id="pyxpcom_gui_app" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" title="&pyxpcom_gui_app.title;" style="width: 700px; height: 500px;" script-type="application/x-python" persist="screenX screenY width height"> <!-- This is Line Number 19 --> I am on Windows. A: Given that your code doesn't seem to have any syntax errors, the most likely issue is the &pyxpcom_gui_app.title; entity reference (note that the XML parser used by Firefox always points to the end of a tag regardless of the line where it finds an unknown entity). Either you forgot to include the DTD file defining this entity or the address of that DTD file is wrong or it doesn't define an entity named pyxpcom_gui_app.title. A: Same problem here, yet unsolved. If the pyxpcom_gui_app.title entity is correctly specified in your DTD, and your DTD is located as specified in your chrome.manifest, then the problem is in the line script-type="application/x-python" (if you delete this line you'll get the XUL part of the application running). According to the Pyxpcomext list, the problem is related to the 1.9.1 pythonext Windows builds, as documented in: http://www.mozdev.org/pipermail/pyxpcomext/2009-March/000052.html I've tried out the newest builds but they still won't work. I'll keep trying. A: Assuming that is the entire file, you need to close the window tag.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FPGA TCP implementation Does anybody know of an implementation of TCP on a FPGA WITHOUT using any sort of microblaze? Preferably open source, because it is for an university/research project. A: I know Easics has a TCP core. You can find a presentation on it here A: Depending on what you want you maybe can get away with a relative small own implentation (e.g. for packet inspection). The statefulness of TCP makes an full hardware implementation vary big and cumbersome. If possible I would recommend to switch to UDP, that makes it much easier. As project dealing with all the IP stuff I know NetFPGA, but I never checked their design, so it could be, that they utilize internal a microblaze for some stuff, but my guess would be not. EDIT: I also remember, that I met one someone from the University of Copenhagen (not sure about this point) at a conference, who also implemented TCP stack on Xilinx FPGAs. A: As far as I know both Intelop and Velocytech have commercial TCP/IP cores available A: A full and low latency TCP/IP Hardware Stack is also available at PLDA
{ "language": "en", "url": "https://stackoverflow.com/questions/7613444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: In SQL, are there non-aggregate min / max operators Is there something like select max(val,0) from table I'm NOT looking to find the maximum value of the entire table There has to be an easier way than this right? select case when val > 0 then val else 0 end from table EDIT: I'm using Microsoft SQL Server A: Not in SQL per se. But many database engines define a set of functions you can use in SQL statements. Unfortunately, they generally use different names and arguments list. In MySQL, the function is GREATEST. In SQLite, it's MAX (it works differently with one parameter or more). A: Functions GREATEST and LEAST are not SQL standard but are in many RDBMSs (e.g., Postgresql). So SELECT GREATEST(val, 0) FROM mytable; A: Make it a set based JOIN? SELECT max(val) FROM ( select val from table UNION ALL select 0 ) foo This avoids a scalar udf suggested in the other question which may suit better A: What you have in SQL is not even valid SQL. That's not how MAX works in SQL. In T-SQL the MAX aggregates over a range returning the maximum value. What you want is a simply the greater value of two. Read this for more info: Is there a Max function in SQL Server that takes two values like Math.Max in .NET?
{ "language": "en", "url": "https://stackoverflow.com/questions/7613448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Data structure for storing chord progression rules? What would be the most appropriate (naturally suited) way to represent the various chord progression (musical) rules in a data-structure such that each chord had a weighted set of options that it could progress to? This data structure would be implemented in a procedural music generation program in a way that you could code: (language-agnostic pseudo-code) Chord[7] songArray; Chord first = new Chord(I); //set the first chord's value songArray[0] = first; for (i=0; i<7; i++){ Chord temp = songArray[i].next(); //select the following chord songArray[i+1] = temp; } Note: In classical-type music, each chord in a given key can naturally progress to another chord following these rules: ---------------------- | Chord | Leads to | |======================= | I | any | | ii | V, vii | | iii | IV, vi | | IV | ii, V, vii | | V | vi | | vi | ii, ii, IV, V| | vii | I | ---------------------- The data structure would store the various progressions as weighted options. As an example, consider the IV chord in any given major key: IV can naturally progress to ii, V, or vii, but could also break the rules in progressing to any other chord. Breaking the rules would happen infrequently. I have considered some sort of linked list/tree data structure, but it would hardly resemble any type of tree or list I've ever used -- additionally, I can't work out how to implement the weighting: Another thought was to use JSON or something similar, but it seems to get redundant very quickly: { "I":{ "100%":{ "I", "ii", "iii", "IV", "V", "vi", "vii" } }, "ii":{ "80%":{ "V", "vii" }, "20%":{ "i", "ii", "iii", "IV", "vi" } }, // ... } Note: I am comfortable implementing this in a handful of languages, and at this point am NOT concerned with a specific language implementation, but a language-agnostic data-structure architecture. A: A Markov Chain might be a good fit for this problem. A Markov chain is a stochastic process where the progression to the next state is determined by the current state. So for a given interval from your table you would apply weights to the "Leads to" values and then determine randomly to which state to progress. A: I'd expect you to have less than 100 chords, therefore if you use 32 bits to represent probability series (likely extreme overkill) you'd end up with a 100x100x4 (40000) byte array for a flat Markov matrix representation. Depending on the sparsity of the matrix (e.g. if you have 50 chords, but each one typically maps to 2 or 3 chords) for speed and less importantly space reasons you may want an array of arrays where each final array element is (chord ID, probability). In either case, one of the key points here is that you should use a probability series, not a probability sequence. That is, instead of saying "this chord has a 10% chance, and this one has a 10% chance, and this one has a 80% chance) say "the first chord has a 10% chance, the first two chords have a 20% chance, and the first three chords have a 100% chance." Here's why: When you go to select a random but weighted value, you can generate a number in a fixed range (for unsigned integers, 0 to 0xFFFFFFFF) and then perform a binary search through the chords rather than linear search. (Search for the element with least probability series value that is still greater than or equal to the number you generated.) On the other hand, if you've only got a few following chords for each chord, a linear search would likely be faster than a binary search due to a tighter loop, and then all the probability series saves you calculating a simple running sum of the probability values. If you don't require the most staggeringly amazing performance (and I suspect you don't -- for a computer there's just not that many chords in a piece of music) for this portion of your code, I'd honestly just stick to a flat representation of a Markov matrix -- easy to understand, easy to implement, reasonable execution speed. Just as a fun aside, this sort of thing lends itself well to thinking about predictive coding -- a common methodology in data compression. You might consider an n-gram based algorithm (e.g. PPM) to achieve higher-order structure in your music generation without too much example material required. It's been working in data compression for years. A: It sounds like you want some form of directed, weighted graph where the nodes are the chords and the edges are the progression options with edge weights being the progression's likelihood.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Rollapply & xts. Can I output the time of max value in the window? I'm studying some yahoo finance data via quantmod. How would I determine not only the Max and Min price over a rolling window of data, but also the exact Timestamp of those highs and lows? I have tried which.max() with rollapply but this only reports the seq of the value in the rolling window itself, and not the .index() of the row that holds the timestamp. Can anyone suggest a solution? a reproducible example is below, and some sample output I'd like to have... > library(quantmod) > getSymbols("BET.L") xmin <- rollapply(BET.L$BET.L.Close,10,min, ascending = TRUE) names(xmin) <- "MinClose" xmax <- rollapply(BET.L$BET.L.Close,10,max, ascending = TRUE) names(xmax) <- "MaxClose" head(cbind(BET.L$BET.L.Close, as.xts(xmax), as.xts(xmin)),15) BET.L.Close MaxClose MinClose 2010-10-22 1550.00 NA NA 2010-10-25 1546.57 NA NA 2010-10-26 1545.00 NA NA 2010-10-27 1511.26 NA NA 2010-10-28 1490.00 1550.00 1395 2010-10-29 1435.00 1546.57 1381 2010-11-01 1447.00 1545.00 1347 2010-11-02 1420.00 1511.26 1347 2010-11-03 1407.00 1490.00 1347 2010-11-04 1395.00 1447.00 1347 2010-11-05 1381.00 1447.00 1347 2010-11-08 1347.00 1490.00 1347 2010-11-09 1415.00 1490.00 1347 2010-11-10 1426.00 1490.00 1347 2010-11-11 1430.00 1490.00 1347 and the type of output I would like to generate would look something like: BET.L.Close MaxClose MinClose MaxDate MinDate 2010-10-22 1550.00 NA NA NA NA 2010-10-25 1546.57 NA NA NA NA 2010-10-26 1545.00 NA NA NA NA 2010-10-27 1511.26 NA NA NA NA 2010-10-28 1490.00 1550.00 1395 2010-10-22 2010-11-04 2010-10-29 1435.00 1546.57 1381 2010-10-25 2010-11-05 Ideally any approach I take must cater for the fact of duplicate prices which is common, and in this case I would order my window to take the first of the max values, and the last of the min values. A: There is a big problem with this plan. The coredata element is a matrix, hence all elements must be classless and of the same mode. You cannot have objects of Date class in an xts object, and if you insist on a character class then it will force all of the other elements to also be character. So with that understood it's still possible to do something by calculating the which.max result, then creating a row-number from which that which.max-value is an offset, and finally using that result as an index into the index of the object. (Sorry for the double uses of "which" and "index". Hope the meaning is clear from the code.) xmin <- rollapply(BET.L$BET.L.Close,10,min) names(xmin) <- "MinClose" xmax <- rollapply(BET.L$BET.L.Close,10,max, ascending = TRUE) names(xmax) <- "MaxClose" head(dat <- cbind(BET.L$BET.L.Close, as.xts(xmax), as.xts(xmin)),15)) w.MaxDate <- rollapply(BET.L$BET.L.Close,10, which.max) names(w.MaxDate) <- "w.maxdt" dat <- cbind(dat, as.xts(w.MaxDate) ) dat<-cbind(dat,as.xts(seq.int(236), order.by=index(dat))) > head(dat) BET.L.Close MaxClose MinClose w.maxdt ..2 2010-10-22 1550.00 NA NA NA 1 2010-10-25 1546.57 NA NA NA 2 2010-10-26 1545.00 NA NA NA 3 2010-10-27 1511.26 NA NA NA 4 2010-10-28 1490.00 1550.00 1395 1 5 2010-10-29 1435.00 1546.57 1381 1 6 dat$maxdate <- xts( index(dat)[dat$..2-5+dat$BET.L.Close.1], order.by=index(dat)) > head(dat) BET.L.Close MaxClose MinClose w.maxdt ..2 maxdate 2010-10-22 1550.00 NA NA NA 1 NA 2010-10-25 1546.57 NA NA NA 2 NA 2010-10-26 1545.00 NA NA NA 3 NA 2010-10-27 1511.26 NA NA NA 4 NA 2010-10-28 1490.00 1550.00 1395 1 5 14904 2010-10-29 1435.00 1546.57 1381 1 6 14907 So I got you the integer representation of the date. You can see that they are the correct values by just looking at the head of the input vector: > head(index(dat)[dat$..2-5+dat$w.maxdt]) [1] NA NA NA NA "2010-10-22" "2010-10-25" A: I think you can add one more numeric column representing date to your original xts object and then use rollapply. Look at xminmax from example below: require(quantmod) getSymbols("BET.L") ## add Date as numeric BET.L$dt <- as.numeric(format(index(BET.L), "%Y%m%d")) xmin <- rollapply(BET.L, 10, align='r', by.column = FALSE, FUN = function(dw) return(dw[which.min(dw[,'BET.L.Close']), c('BET.L.Close', 'dt')]) ) xmax <- rollapply(BET.L, 10, align='r', by.column = FALSE, FUN = function(dw) return(dw[which.max(dw[,'BET.L.Close']), c('BET.L.Close', 'dt')]) ) xminmax <- cbind(xmin, xmax) ## to get back to dates use: ## as.Date(as.character(as.integer(xminmax$dt.xmin)), format = "%Y%m%d") ## left edge of data window x_ldt <- rollapply(BET.L$dt, 10, align='r', function(dw) return(dw[1])) Results: head(xminmax) BET.L.Close.xmin dt.xmin BET.L.Close.xmax dt.xmax 2010-11-04 1395 20101104 1550.00 20101022 2010-11-05 1381 20101105 1546.57 20101025 2010-11-08 1347 20101108 1545.00 20101026 2010-11-09 1347 20101108 1511.26 20101027 2010-11-10 1347 20101108 1490.00 20101028 2010-11-11 1347 20101108 1447.00 20101101
{ "language": "en", "url": "https://stackoverflow.com/questions/7613460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Refreshing webpage after browser back button? Let me begin by saying I do not want to "disable" or otherwise prevent the proper usage of the browser history buttons. What I need is a javascript-based procedure (cross-browser compatible, hopefully) to refresh a webpage (staying on the same URL) after navigating to it using the back/forward buttons. This is necessary because during this process the server keeps track of the user's position/page, and if the user wants to jump back 3 pages I need to "inform" the server of the new location by reloading the page (or is there a better way to do it?) I already disabled caching through HTTP headers but this doesn't work for back/forward history, at least in Firefox 7. Using jQuery is of course acceptable and desirable. I looked around a bit and found out about $(document).ready(). Now, please keep in mind I'm a complete javascript noob. I have zero experience, and the same goes for jQuery (I know what it does, I've looked at the docs, but that's about it). So I'm trying to understand how this works, but pages that mention this method seem to assume that the webdeveloper wants to modify the DOM from it, and there are a few quirks when you want to do that (load order and stuff). Since in my case I only need to refresh, it should hopefully be easier. So: * *I understand this doesn't only run when you browse back, it also runs every time you load the page. How can I make sure I don't end up with an infinite loop? I want it to run once when I browse back, but not on load, after the automated refresh or otherwise. On a normal load I'd rather not have it running because the user would have to download each page twice, which is stupid! *Or is there a better way to do this? Any other ideas? Care to explain or point me in the right direction? EDIT: I only need compatibility with: Internet Explorer 8 or higher Firefox 4 or higher Recent-ish Chrome/Safari (I don't keep track of version numbers but why would someone not use up to date Chrome anyway?) A: The best workaround I ever found for this problem is to use location.replace(), like so. It does not directly address the problem from my original question; however, since that seems not to have a solution (for now), I recommend that everyone uses this client side function to protect the server side pages they do not wish to have executed again by a client using the back button. I'm sure this is better explained elsewhere on stackoverflow, but for the few people using my convoluted way of thinking to look the problem up, there you have it. A: Its a bit of an abuse, but one of the ways of doing this would be to have your "proceed to next step" button as a form which POSTs. For example; instead of <a href = "#foo">Proceed to next Page</a> you have <form action = "foo" method = "POST"><input type = "submit" value = "Proceed to next page" /></form> If the user hits back, they'll be forced to re-send their data to the server and your page would be refreshed. This would probably be really annoying to the user though! But as i mentioned, major abuse of forms! EDIT: This abuse will only work for certain scenarios though, you'll be the best judge of whether it's appropriate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rake aborted - uninitialized constant Rake::DSL Possible Duplicate: Ruby on Rails and Rake problems: uninitialized constant Rake::DSL I'm in the early stages of learning Rails. I'm following the tutorial in the Agile WebDev book. When I tried to apply my first migration, I got the following error: rake aborted! uninitialized constant Rake::DSL D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/1.9.1/rake.rb:2482:in `const_missing' D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/tasklib.rb:8:in `<class:TaskLib>' D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/tasklib.rb:6:in `<module:Rake>' D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/tasklib.rb:3:in `<top (required)>' D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/rdoc-3.9.4/lib/rdoc/task.rb:37:in `require' D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/rdoc-3.9.4/lib/rdoc/task.rb:37:in `<top (required)>' D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.10/lib/rails/tasks/documentation.rake:2:in `require' D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.10/lib/rails/tasks/documentation.rake:2:in `<top (required)>' D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.10/lib/rails/tasks.rb:15:in `load' D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.10/lib/rails/tasks.rb:15:in `block in <top (required)>' D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.10/lib/rails/tasks.rb:6:in `each' D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.10/lib/rails/tasks.rb:6:in `<top (required)>' D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.10/lib/rails/application.rb:215:in `require' D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.10/lib/rails/application.rb:215:in `initialize_tasks' D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.10/lib/rails/application.rb:139:in `load_tasks' D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.10/lib/rails/application.rb:77:in `method_missing' C:/Documents and Settings/Wael Khobalatte/Bureau/sellit/Rakefile:7:in `<top (required)>' D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/1.9.1/rake.rb:2373:in `load' D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/1.9.1/rake.rb:2373:in `raw_load_rakefile' D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/1.9.1/rake.rb:2007:in `block in load_rakefile' D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/1.9.1/rake.rb:2058:in `standard_exception_handling' D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/1.9.1/rake.rb:2006:in `load_rakefile' D:/Learning/Ruby On Rails/Ruby/Ruby192/lib/ruby/1.9.1/rake.rb:1991:in `run' D:/Learning/Ruby On Rails/Ruby/Ruby192/bin/rake:31:in `<main>' I have tried different solutions available here and elsewhere and none worked. I updated rake, evoked the bundle, and even added a require 'rake/dsl_definition' to the Rakefile. I even created an app elsewhere to see if the location was the problem (I was developing inside my Dropbox), but it persisted. Here is the Gemfile: source 'http://rubygems.org' gem 'rails', '3.0.10' # Bundle edge Rails instead: # gem 'rails', :git => 'git://github.com/rails/rails.git' gem 'sqlite3' # Use unicorn as the web server # gem 'unicorn' # Deploy with Capistrano # gem 'capistrano' # To use debugger (ruby-debug for Ruby 1.8.7+, ruby-debug19 for Ruby 1.9.2+) # gem 'ruby-debug' # gem 'ruby-debug19', :require => 'ruby-debug' # Bundle the extra gems: # gem 'bj' # gem 'nokogiri' # gem 'sqlite3-ruby', :require => 'sqlite3' # gem 'aws-s3', :require => 'aws/s3' # Bundle gems for the local environment. Make sure to # put test-only gems in this group so their generators # and rake tasks are available in development mode: # group :development, :test do # gem 'webrat' # end And here is the output when I run rake test: D:/Learning/Ruby On Rails/Ruby/Ruby192/bin/ruby.exe: invalid option -O (-h will show valid options) (RuntimeError) D:/Learning/Ruby On Rails/Ruby/Ruby192/bin/ruby.exe: invalid option -O (-h will show valid options) (RuntimeError) D:/Learning/Ruby On Rails/Ruby/Ruby192/bin/ruby.exe: invalid option -O (-h will show valid options) (RuntimeError) Errors running test:units, test:functionals, test:integration!
{ "language": "en", "url": "https://stackoverflow.com/questions/7613465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting the Current username when impersonated I am using something like the following method to impersonate a user in my code: How do you do Impersonation in .NET? In another class, I need to find out the current user (like "mydomain\moose"), but I won't have any idea if I'm currently impersonating another user or not. How do I get the username, if I'm impersonating someone? System.Environment.UserName and System.Security.Principal.WindowsIdentity.GetCurrent().Name both return the original user, not the currently impersonated user. More Details: I am doing this impersonation so that I can access some files in a netowrk share the user usually does not have access to. If I use a logon type of LOGON32_LOGON_INTERACTIVE, I do see the new user, but I cannot access the network share. If I use a logon type of LOGON32_LOGON_NEW_CREDENTIALS (a value of 9), i can access the network share but I don't see the new user in Environment.UserName. A: According to example at http://msdn.microsoft.com/en-us/library/chf6fbt4.aspx the current identity changes during impersonation. Are you sure your code is inside the impersonated code block? A: I wrote a helper class that does it: public static class ImpersonationUtils { private const int SW_SHOW = 5; private const int TOKEN_QUERY = 0x0008; private const int TOKEN_DUPLICATE = 0x0002; private const int TOKEN_ASSIGN_PRIMARY = 0x0001; private const int STARTF_USESHOWWINDOW = 0x00000001; private const int STARTF_FORCEONFEEDBACK = 0x00000040; private const int CREATE_UNICODE_ENVIRONMENT = 0x00000400; private const int TOKEN_IMPERSONATE = 0x0004; private const int TOKEN_QUERY_SOURCE = 0x0010; private const int TOKEN_ADJUST_PRIVILEGES = 0x0020; private const int TOKEN_ADJUST_GROUPS = 0x0040; private const int TOKEN_ADJUST_DEFAULT = 0x0080; private const int TOKEN_ADJUST_SESSIONID = 0x0100; private const int STANDARD_RIGHTS_REQUIRED = 0x000F0000; private const int TOKEN_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID; [StructLayout(LayoutKind.Sequential)] private struct PROCESS_INFORMATION { public IntPtr hProcess; public IntPtr hThread; public int dwProcessId; public int dwThreadId; } [StructLayout(LayoutKind.Sequential)] private struct SECURITY_ATTRIBUTES { public int nLength; public IntPtr lpSecurityDescriptor; public bool bInheritHandle; } [StructLayout(LayoutKind.Sequential)] private struct STARTUPINFO { public int cb; public string lpReserved; public string lpDesktop; public string lpTitle; public int dwX; public int dwY; public int dwXSize; public int dwYSize; public int dwXCountChars; public int dwYCountChars; public int dwFillAttribute; public int dwFlags; public short wShowWindow; public short cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; } private enum SECURITY_IMPERSONATION_LEVEL { SecurityAnonymous, SecurityIdentification, SecurityImpersonation, SecurityDelegation } private enum TOKEN_TYPE { TokenPrimary = 1, TokenImpersonation } [DllImport("advapi32.dll", SetLastError = true)] private static extern bool CreateProcessAsUser( IntPtr hToken, string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, int dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation); [DllImport("advapi32.dll", SetLastError = true)] private static extern bool DuplicateTokenEx( IntPtr hExistingToken, int dwDesiredAccess, ref SECURITY_ATTRIBUTES lpThreadAttributes, int ImpersonationLevel, int dwTokenType, ref IntPtr phNewToken); [DllImport("advapi32.dll", SetLastError = true)] private static extern bool OpenProcessToken( IntPtr ProcessHandle, int DesiredAccess, ref IntPtr TokenHandle); [DllImport("userenv.dll", SetLastError = true)] private static extern bool CreateEnvironmentBlock( ref IntPtr lpEnvironment, IntPtr hToken, bool bInherit); [DllImport("userenv.dll", SetLastError = true)] private static extern bool DestroyEnvironmentBlock( IntPtr lpEnvironment); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool CloseHandle( IntPtr hObject); private static void LaunchProcessAsUser(string cmdLine, IntPtr token, IntPtr envBlock, int sessionId) { var pi = new PROCESS_INFORMATION(); var saProcess = new SECURITY_ATTRIBUTES(); var saThread = new SECURITY_ATTRIBUTES(); saProcess.nLength = Marshal.SizeOf(saProcess); saThread.nLength = Marshal.SizeOf(saThread); var si = new STARTUPINFO(); si.cb = Marshal.SizeOf(si); si.lpDesktop = @"WinSta0\Default"; si.dwFlags = STARTF_USESHOWWINDOW | STARTF_FORCEONFEEDBACK; si.wShowWindow = SW_SHOW; if (!CreateProcessAsUser( token, null, cmdLine, ref saProcess, ref saThread, false, CREATE_UNICODE_ENVIRONMENT, envBlock, null, ref si, out pi)) { throw new Win32Exception(Marshal.GetLastWin32Error(), "CreateProcessAsUser failed"); } } private static IDisposable Impersonate(IntPtr token) { var identity = new WindowsIdentity(token); return identity.Impersonate(); } private static IntPtr GetPrimaryToken(Process process) { var token = IntPtr.Zero; var primaryToken = IntPtr.Zero; if (OpenProcessToken(process.Handle, TOKEN_DUPLICATE, ref token)) { var sa = new SECURITY_ATTRIBUTES(); sa.nLength = Marshal.SizeOf(sa); if (!DuplicateTokenEx( token, TOKEN_ALL_ACCESS, ref sa, (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, (int)TOKEN_TYPE.TokenPrimary, ref primaryToken)) { throw new Win32Exception(Marshal.GetLastWin32Error(), "DuplicateTokenEx failed"); } CloseHandle(token); } else { throw new Win32Exception(Marshal.GetLastWin32Error(), "OpenProcessToken failed"); } return primaryToken; } private static IntPtr GetEnvironmentBlock(IntPtr token) { var envBlock = IntPtr.Zero; if (!CreateEnvironmentBlock(ref envBlock, token, false)) { throw new Win32Exception(Marshal.GetLastWin32Error(), "CreateEnvironmentBlock failed"); } return envBlock; } public static void LaunchAsCurrentUser(string cmdLine) { var process = Process.GetProcessesByName("explorer").FirstOrDefault(); if (process != null) { var token = GetPrimaryToken(process); if (token != IntPtr.Zero) { var envBlock = GetEnvironmentBlock(token); if (envBlock != IntPtr.Zero) { LaunchProcessAsUser(cmdLine, token, envBlock, process.SessionId); if (!DestroyEnvironmentBlock(envBlock)) { throw new Win32Exception(Marshal.GetLastWin32Error(), "DestroyEnvironmentBlock failed"); } } CloseHandle(token); } } } public static IDisposable ImpersonateCurrentUser() { var process = Process.GetProcessesByName("explorer").FirstOrDefault(); if (process != null) { var token = GetPrimaryToken(process); if (token != IntPtr.Zero) { return Impersonate(token); } } throw new Exception("Could not find explorer.exe"); } } You can use it like that: ImpersonationUtils.LaunchAsCurrentUser("notepad"); using (ImpersonationUtils.ImpersonateCurrentUser()) { } More explanations and examples you can find here : Impersonating CurrentUser from SYSTEM A: First, I'd like to point out what the property WindowsIdentity.GetCurrent().Name will return if you use LOGON32_LOGON_NEW_CREDENTIALS or LOGON32_LOGON_INTERACTIVE as logon type for the LogonUser (inside the impersonation class) function: * *Using LOGON32_LOGON_INTERACTIVE // Assuming this code runs under USER_B using (var imp = new Impersonation("treyresearch", "USER_A", "SecurePwd", LOGON32_LOGON_INTERACTIVE )) { // Now, we run under USER_A Console.Out.WriteLine(WindowsIdentity.GetCurrent().Name); // Will return USER_A } *Using LOGON32_LOGON_NEW_CREDENTIALS // Assuming this codes runs under USER_B using (var imp = new Impersonation("treyresearch", "USER_A", "SecurePwd", LOGON32_LOGON_NEW_CREDENTIALS )) { Console.Out.WriteLine(WindowsIdentity.GetCurrent().Name); // Will return USER_B } This is the behaviour as you have described in your question and is consistent with the description on MSDN for the LogonUser function. For LOGON32_LOGON_NEW_CREDENTIALS the created user token is just a clone of the current user token. This means that the created user session has the same identifier as the calling thread. The passed credentials to the LogonUser function are only used for outbound network connections. Second, let me point out two situation where the described difference between LOGON32_LOGON_INTERACTIVE and LOGON32_LOGON_NEW_CREDENTIALS becomes clear: * *Two domain joined computers: computer_A, computer_B *Two users: user_A (local admin on computer_A), user_B (only standard user rights on B) *One networkshare on computer_B (mynetworkshare, user_B does have permission to access share). *One local folder on computer_A (only user_A has permission to write to this folder). You run your program on computer_A (under the account of user_A). You impersonate user_B (using LOGON32_LOGON_INTERACTIVE). Then you connect to the network share on computer_B and try to copy a file to the local folder (only user_A has the permission to write to this folder). Then, you get an access denied error message, because the file operation is done with the permissions of user_B who does not have permission on the local folder. Same situation as above. But now, we use LOGON32_LOGON_NEW_CREDENTIALS to impersonate user_B. We connect to the network drive and copy a file from the network drive to the local folder. In this case the operation succeeds because the file operation is done with the permissions of user_A. A: Take a look at QueryCredentialsAttributes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: how to open many text files with python I have 800 text files about protein. Actually I should make a matrix 800 in 800 to compare interaction between proteins. I entered their names in a list. Because writing all names in program is difficult. Now I want to open them in the python programming to use. But I don’t know what the program is to do it. import csv from os import listdir from os.path import isfile,join Protein_List = [f for f in listdir("/home/rezvane/GENE6") if isfile(join("/home/rezvane/GENE6",f))] Matrix_Interaction = [[]*7] Number_of_Interaction = 0 for i in range(7): CC_Interaction = [] fh = open("/home/rezvane/GENE6/O15209:ZBTB22.txt") test = False for line in fh.readline(): if "CC -!- INTERACTION" in line: test = True if "CC -!- SUBCELLULAR LOCATION" in line: break if test: data = line.split(";")[0][9:] CC_Interaction.append(data) for j in range(7): if Protein_List[j] in CC_Interaction: Matrix_Interaction[i][j] = 1 Number_of_Interaction +=1 else: Matrix_Interaction[i][j] = 0 print Matrix_Interaction print Number_of_Interaction A: Do not write your filenames in code. Instead, do one of the following: * *Store your file names in a data store of some sort, like an XML file or database, and use that data store to open your files, or *Write a function that generates the file names based on existing information about the proteins. Also, consider the possibility that, instead of using separate text files, you should be storing or importing the data into a database, and using that database to analyze and manipulate your protein data instead of text files.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: Divs in normal flow overlapping I'm attempting to position a series of div's (which are dynamic in height) one after another so that they are the same width as their parent. My understanding is that this is what the normal flow should do, but instead they end up overlapping. See http://www.euro-endo.nl/technologies.php My html: <div id="col"> <div id="thing"> <div id="rimage"> <div id="pic1"></div> </div> <div id="ltext"> text1 </div> </div> <div id="thing"> <div id="limage"> <div id="pic2"></div> </div> <div id="rtext"> text2 </div> </div> and the corresponding css is: #col { position: absolute; left: 20px; right: 50px; top:0; bottom:0px; width: auto; padding: 10px 20px 0px 0px; overflow: hidden; } #thing { position: static; width: 100%; height: auto; Margin: 20px; } #ltext { position: absolute; left: 0px; right: 210px; top:0px; bottom:0px; width: auto; height: auto; } #rtext { position: absolute; right: 0px; left: 210px; top:0px; bottom:0px; width: auto; height: auto; } #rimage { position: absolute; right: 0px; top:0px; bottom:0px; width: 210; height: auto; } #limage { position: absolute; left: 0px; top:0px; bottom:0px; width: 210; height: auto; } (There are a couple more of the id="thing" div's but I think this gives the gist of it.) A: One big problem for sure... You cannot have multiple <div>'s sharing the same id. id must be unique for each <div>. As noted in comments, you would use classes to apply styles to multiple elements at once. You also have them all set to position:absolute; with top:0px; which puts them all in the same place simultaneously. Running your page through the W3C Validator would catch many issues such as the multiple id's... http://validator.w3.org A: Your divs are NOT in the normal flow when they are positioned absolutely. This is why the elements overlap. Absolute positioning will places them 'absolutely' with reference to the nearest positioned parent. Note the other comments about unique id names.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: View Hierarchy with UIToolBar and UITabBarController I have a rootViewController that is a UITabBarController. A UIToolBar is present in that controller since it has a SearchBar that is global to the app. In certain tabs, there should be specific UIBarButtonItems, or UISegmentedControl, along with the searchBar. In other tabs, there should be nothing in the toolBar, just a title. What is a good way to lay out the view? Currently based on what tab is selected, the main toolBar from the rootViewController is either used as it is, have a UISegmentedControl added to it, hidden completely and replaced with another viewController that has its own toolbar, etc. To me, I'm thinking that each viewController that is present in its own tab can have its own ToolBar, and reference the global functionality, vs hiding/showing different toolbars. sorry if this is a convoluted question. Just wondering if people had experience with this. Thanks. A: The short answer is that there isn't really a good way to do this. If you're using a tab bar controller, the tab bar will always be visible along the bottom of your screen. Presumably each tab is a UINavigationController with a navigation bar at the top. There's not an appropriate place to put toolbar buttons in this layout. A better design could be to abandon the UITabBarController and use a UINavigationController as your root view controller. Instead of tabs, you can have a table view with an item for each view of your application. Then you'll have room for a toolbar at the bottom of the screen. In fact, UINavigationController supports having a toolbar at the bottom. You just override the toolbarItems property to return the items that should appear in each of the child view controllers. You'll just need to set toolbarHidden to NO on the UINavigationController, and you're good to go.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Insert tracks into a big mp3 file I need to insert audio tracks to a big mp3 file. The mp3 file is about 40 minutes long and I would like to add tracks so that I can skip a track or go back to a track. Instead of doing this manually by using tools like audacity, I would like to automate this by using a script (any script). Like passing the file name and location and the script add tracks in 10 minute intervals. Is there a sample source code in java that I can learn from? Java happens to be my preferred choice but doesn't have to be. Any suggestions? I had a similar question posted yesterday and a moderator closed it out saying it was vague or incomplete. I hope this post more clear to understand and gets some suggestions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Coded UI - how to identify the grid row and columns inserted dynamically In the control properties, new row has name equals to Volume Row 62 and Row Index equals to 61 - as recorded and add values in few columns. When I insert a new row with external data and fill the respective columns, it tries to override the column data in the row which was used in the recording and not the one that is being inserted. If i remove the 62 and 61 from the Row Properties and make that general, it goes to the first row in the grid and tries to edit. What properties should be changed or searched for so that columns is populated correctly in the the new row (whose name and row index is not known). any help is appreciated. Thanks. A: To solve this in our application we exported the UI map method and created a temp list using VAR I don't know if this will work for you or not but solved several of our issues around dynamic grid rows and columns: public void DoubleClickLaunch_UOW() { var temp = this.UIWindow.UIUnitGridTable.GetChildren().ToList(); temp.RemoveAt(0); var rows = temp.Select(t => t.GetChildren().Select(s => s.GetValue()).ToList()).ToList(); var tractLetters = rows.Select(s => s[1]).ToList(); var index = tractLetters.IndexOf(DoubleClickLaunch_UOWParams.UITESTUNIT_TPText); if (index >= 0) { var textbox = temp[index].GetChildren()[1].GetChildren()[0]; Mouse.DoubleClick(textbox); } else { Mouse.DoubleClick(this.UIWindow.UIUnitGridTable.UIItemRow.UIUnitNameCell.UITESTUNIT_TPText); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7613488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to generate a client ssh key at each connection? For now, I think that the public key that is used on a client-side is reused several times (maybe as long as the config dosn't change I think). I assume we are using the password method. This worries me. I would prefer my ssh client to automatically generate a RSA key on each connection (but the Client-side key MUST remain the same to ensure authenticity and Is this possible ? Thanks. EDIT : Please see comment #3. A: The public key in SSH is used for identifying the client. The private key is used for proving that the user is not an imposter. The server only knows the public key. If you change it for each connection, it's like changing your username for each connection. So the server knows the user "john", but then you say "I'm Joe". It doesn't matter whether you can prove that you're Joe, the server doesn't know you, so it won't let you in. It's not like SSL where you use a signed certificate to prove who you are, so you can change the key whenever you want. Here the public key is part of your identity, so you have to use the same one for every connection. A: What you are missing is that the public and private keys are cryptographically bound to one another. When the private key is generated, the corresponding public key is as well. Encrypt something with one key and it can only be decrypted with the other. Anyone with the public key can validate that a message can only have come from someone with the private key because of this cryptographic relationship. When an SSH session starts up, each side uses this property to authenticate the other. During the handshake a secret (technically, it's called a 'nonce' and it's basically a random number) is encrypted with the recipient's public key and then signed with the sender's private key. When this is received, the recipient a) can validate the signature with the sender's public key; and b) is the only one who can possibly decrypt the message. This authenticates the exchange. If this handshake occurs in both directions, it is possible for both sides to validate each other. This is called mutual authentication. So, it is not the value of the key that is important but rather the cryptographic principle binding the public and private keys. This process provides the ability to create a random session key and exchange it securely using the public/private key pairs and is the heart of how SSH (or SSL or TLS for that matter) fires up a session. This means the answer to your question is that if SSH is set up for mutual authentication (i.e. you do not need to enter a password), your client's public key must be in the keystore of the server. Since you cannot change the public key without changing the private key it is necessary to reload the public key at the server each time a key change is made. A: If you use password authentication, no client side RSA key is used. If you use public key authentication, the client side key obviously can't change every time as the server needs to know it already in order to authenticate you. You seem to have deep misconceptions about the SSH protocol. I can only suggest to read RFC 4252 to clarify things.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hudson build scripts location - recommendation? I'm already finishing my project build automation :) with Hudson and Nant. My project structure is something like $/Project build.scripts script1.build script2.build build.properties.xml Code Project1 Project2 So Hudson downloads from the root $/Project to the workspace folder. And everything is ok since the build.scripts are in the workspace, I run them very easily, however what is bugging me is the fact that since the build scripts are inside the workspace, then I can't program Hudson to run automatically either based on time or changes because it will always detect changes to the files (note build.properties.xml which I check out and check in at build time to store some stats). Where do you recommend these files to go in and still get the advantage of having them source-controlled? A: What I ended up doing is to NOT check-in changes to those files. I changed my CI workflow to create another file (local to the workspace only) where the changes are written to. This way, I still get the last build info written somewhere to pick it up, and avoid the issue of Jenkins detecting the change. PS: I changed from Hudson to Jenkins since I saw that most plugins ran away from the former. The transition was too smooth to be true.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ArrayAdapter and ListView display only specific items I am trying to impement a school planner app. There is a timetable overview implemented as a ListView for each day wrapped into a Tab Layout. So the user can switch between days Monday to Friday and gets his timetable for the specific day. public class TimetableAdapter extends ArrayAdapter<Lesson> { private List<Lesson> lessonList; // The model ... public View getView(int position, View convertView, ViewGroup parent) { View view = null; ... view = inflater.inflate(R.layout.timetable_row, null); Lesson currentLesson = lessonList.get(position); // Checks if selected Tab (context.getDay()) correspondends to // currentLesson's day. If so the lesson will be rendered into // the appropriated ListView. So if the user selects the Monday Tab // he only wants to see the lessons for Monday. if (context.getDay() == currentLesson.getWeekDay().getWeekDay()) { fillView(currentLesson, holder); // render Lesson } ... return view; } private void fillView(Lesson currentLesson, ViewHolder holder) { holder.subject.setText(currentLesson.getSubject().getName()); } public class TimetableActivity extends Activity implements OnTabChangeListener { public void onCreate(Bundle savedInstanceState) { .... timetableAdapter = new TimetableAdapter(this, getModel()); } private List<Lesson> getModel() { return timetable.getLessons(); } public void onTabChanged(String tabId) { currentTabName = tabId; if (tabId.equals("tabMonday")) { setCurrentListView(mondayListView); } else if (tabId.equals("tabTuesday")) { // Checks tabTuesday and so on.... ... } } private void addLesson() { timetable.addLesson(new Lesson(blabla(name, weekday etc.))); // blabla = user specified values timetableAdapter.notifyDataSetChanged(); } So basically if the user adds a lesson he specifies some parameters like corresponding weekday, name etc. This is represented by blabla. The problem is that, because I am using only one ArrayList for my data, wether it's a subject on Monday or on Tuesday the lesson e.g. for Monday is rendered on my Tuesday's ListView as an empty row, because getView(...) is called for each item in lessonList and it just returns a new View(), if the weekday isn't the desired one, I think. One solution might be creating 5 ArrayLists and 5 ArrayAdapters for the appropriated weekdays. So the lessons on Monday will be in ArrayList mondayList, and the adapter will be bound to this list. But this is somewhat unflexible. Is there a better solution? Thanks in advance. A: Instead of using ArrayAdapter, use SimpleAdapter. It is far more flexible for what you want to display. Second keep your ArrayList of all the appointments out of the Adapter, create some sort of filtering method to copy applicable objects and pass this new list to the SimpleAdapter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook-style API access scenario with Azure ACS and OAuth 2.0: how to implement app authorization? I am building a social website that will expose REST API (WCF WebAPI) to the world so any developer would be able to create a client application for the website, integrate it with other services, etc. I would like to implement Facebook/Twitter-style access control mechanism for the API. So that developers will register their apps on the developer section on the site, create a key and use that app key in OAuth workflow to get access to the API. Since I use Azure in this project, I consider leveraging Azure ACS to facilitate OAuth processes. However, I am unable to find any code sample or manual for app authorization with ACS. Can someone share such example or at least give me a direction for my own research? If I can achieve Facebook/Twitter behavior with another OAuth library (e.g. DotNetOpenAuth), that would be cool, too. Thank you in advance. A: ACS is a good choice for this sort of thing. Your scenario is pretty much OAuth Delegation, which ACS supports. You should look into ACS with OAuth 2 Delegation sample in: https://connect.microsoft.com/site1168/Downloads (It is called Wif Oauth CTP version) Note that in this sample custom authentication is used for autheticating the user. Since ACS provides Single Sign On with Idps, you can instead use ACS here (e.g with Facebook). If you go this path, you can find more information on how to use a custom home realm discovery page in the following sample: http://msdn.microsoft.com/en-us/library/hh127794.aspx Finally, you will neeed to have a web page where your client apps will manage their settings. For this you will be required to use ACS management service. You can find detailed information on using ACS management service in: http://msdn.microsoft.com/en-us/library/gg185970.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7613502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating a new Hibernate table So I'm still pretty new to Hibernate, and I'm working on a large-ish application that already has a database with several Hibernate tables. I'm working on a new feature, which includes a new @Entity class, and I need these objects to be stored in a new table. The class is declared like this: @Entity @Table(name="DATA_REQUEST") public class DataRequest { //Some fields, nothing fancy } The DATA_REQUEST table does not exist, nor do I have any data to store in it yet. I started the application up, expecting that it would either create the table or crash because it doesn't exist yet. Neither of these actually happened. So: do I need to create the table manually (easily done)? Or do I need to go somewhere else to tell Hibernate that I need this table? I've seen the hibernate.cfg.xml file, which looks like a good place to start. A: You need to specify "create" for the "hibernate.hbm2ddl.auto" property. Read more details here. This is not recommended in production but only for testing purposes. A: As for adding a new column to the table * *As long as it is not a not null column you don't need drop the table or restart your hibernate app *If you do want to use the column then you need to map the column in the code/hbm file, so you will have to restart the hibernate app *If there is no mapping present as far as hibernate is concerned the column does not exisist, If it is a not null column then underlying data base would reject inserts/updates as hibernate will not include the column in generated sql A: from hibernate documentation hibernate.hbm2ddl.auto Automatically validates or exports schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly. e.g. validate | update | create | create-drop hibernate Configuration
{ "language": "en", "url": "https://stackoverflow.com/questions/7613513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: algorithms for modular inverses i have read section about The Extended Euclidean Algorithm & Modular Inverses,which states that it not only computes GCD(n,m) but also a and b such that a*n+b*b=1; algorithm is described by by this way: * *Write down n, m, and the two-vectors (1,0) and (0,1) *Divide the larger of the two numbers by the smaller - call this quotient q *Subtract q times the smaller from the larger (ie reduce the larger modulo the smaller) (i have question here if we denote by q n/m,then n-q*m is not equal to 0?because q=n/m;(assume that n>m),so why it is necessary such kind of operation? then 4 step 4.Subtract q times the vector corresponding to the smaller from the vector corresponding to the larger 5.Repeat steps 2 through 4 until the result is zero 6.Publish the preceding result as gcd(n,m) so my question for this problem also is how can i implement this steps in code?please help me,i dont know how start and from which point could i start to solve such problem,for clarify result ,it should look like this An example of this algorithm is the following computation of 30^(-1)(mod 53); 53 30 (1,0) (0,1) 53-1*30=23 30 (1,0)-1*(0,1)=(1,-1) (0,1) 23 30-1*23=7 (1,-1) (0,1)-1*(1,-1)=(-1,2) 23-3*7=2 7 (1,-1)-3*(-1,2)=(4,-7) (-1,2) 2 7-3*2=1 (4,-7) (-1,2)-3*(4,7)=(-13,23) 2-2*1=0 1 (4,-7)-2*(-13,23)=(30,-53) (-13,23) From this we see that gcd(30,53)=1 and, rearranging terms, we see that 1=-13*53+23*30, so we conclude that 30^(-1)=23(mod 53). A: The division is supposed to be integer division with truncation. The standard EA for gcd(a, b) with a <= b goes like this: b = a * q0 + r0 a = r0 * q1 + r1 r0 = r1 * q2 + r2 ... r[N+1] = 0 Now rN is the desired GCD. Then you back-substitute: r[N-1] = r[N] * q[N+1] r[N-2] = r[N-1] * q[N] + r[N] = (r[N] * q[N+1]) * q[N] + r[N] = r[N] * (q[N+1] * q[N] + 1) r[N-3] = r[N-2] * q[N-1] + r[N-1] = ... <substitute> ... Until you finally reach rN = m * a + n * b. The algorithm you describe keeps track of the backtracking data right away, so it's a bit more efficient. If rN == gcd(a, b) == 1, then you have indeed found the multiplicative inverse of a modulo b, namely m: (a * m) % b == 1.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XSL - Escaping an apostrophe during xsl:when test I have the following code which appears to be failing. <xsl:when test="$trialSiteName = 'Physician&apos;s Office'"> Also, visual studio is complaining saying "Expected end of expression, found 's" How am I supposed to escape the character? XSLT v1.0. Apache XSL-FO processor. A: Much more simple -- use: <xsl:when test="$trialSiteName = &quot;Physician&apos;s Office&quot;"> A: * *Declare a variable: <xsl:variable name="apos" select='"&apos;"'/> *Use the variable like this in the <xsl:when> clause: <xsl:when test="$trialSiteName = concat('Physician', $apos, 's Office')"> A: &apos; works for XPath 1.0. If you are using XSLT 2.0 with XPath 2.0 try double apostrophe: <xsl:when test="$trialSiteName = 'Physician''s Office'"> Look for a full explanation by Dimitre Novatchev in his answer Escape single quote in xslt concat function A: in between &quot; you can add what ever special characters you want. <xsl:when test="$trialSiteName = &quot;Physician's what ever special charactors plainly add Office&quot;">
{ "language": "en", "url": "https://stackoverflow.com/questions/7613521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: jqgrid load from multiple urls I have a page, that has jqgrid, it is fetching json from a url. I want to load data from multiple urls instead on one url, on the same grid. How can I achieve that. The reason is, I have to display data from different sources, the ids will be unique no-matter if its from which source. Thanks A: You can load the data which you want to place in the grid as array of items. From every source you will get an array. then you can concatinate the arrays for example with respect of jQuery.merge. You will receive the full array of items. At the end you create jqGrid with datatype: 'local' and with the array of concatenated items as the value of the data parameter. A: Did you try just calling addJSONData multiple times? var grid = $('#'+grid_id)[0]; grid.addJSONData(jsondata1); grid.addJSONData(jsondata2); grid.addJSONData(jsondata3);
{ "language": "en", "url": "https://stackoverflow.com/questions/7613523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I run a program in msys through Python? I've got a short python script that will eventually edit an input file, run an executable on that input file and read the output from the executable. The problem is, I've compiled the executable through msys, and can only seem to run it from the msys window. I'm wondering if the easiest way to do this is to somehow use os.command in Python to run msys and pipe a command in, or run a script through msys, but I haven't found a way to do this. Has anyone tried this before? How would you pipe a command into msys? Or is there a smarter way to do this that I haven't thought of? Thanks in advance! EDIT: Just realized that this information might help, haha . . . . I'm running Windows, msys 1.0 and Python 2.7 A: * *Find where in the msys path libgcc_s_dw2-1.dll is. *Find the environmental variable in MSYS that has that path in it. *Add that environmental variable to Windows.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613525", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I get Java's hasNextInt() to stop waiting for ints without inputting a character? I was given the following code and asked to write the Solution class extending from TestList. I wrote a constructor for it (which just called super) and the printSecond2() method invoked in the last line of the code below. All other methods are inherited. Here's the code: public class Test3A { public static void main(String[] args) { TestList tl = new Solution(); tl.loadList(); ((Solution) (tl)).printSecond2();//prints every second element } } However, the damn thing was never printing anything out, so I went into the TestList class (which was provided) and put println statements after every single line of the loadList () method: public void loadList () { if (input.hasNextInt ())//input is a Scanner object { int number = input.nextInt (); loadList (); add (number); } } I discovered that I can continue to add whitespace, newlines and integers indefinitely, and that the add(number) method is only finally called when I input a character. So if I don't do that, it just sort of hangs around waiting for more input instead of moving on. I'm confused by this as the provided sample input/output is: sample input 1 2 3 4 5 sample output 2 4 So there's no character being inputted by the automatic marker. I have tried overriding the method in Solution (we can't touch the other classes) and: * *) changing if to while *) adding an else block *) adding an else if (!input.hasNextInt ()) None of these changed anything. I have no idea how the program is supposed to move on and get as far as calling printSecond2(). Any thoughts? I'd really like to pass my next prac test :D A: When user is supposed to enter a sequence of numbers either the number of items should be provided or the input should be terminated in some manner. 1 2 3 and 1 2 3 4 are both valid inputs so scanner can't decide where to end on its own. It can be assumed that the number sequence is terminated by EOF character Ctrl-Z on windows and Ctrl-D on unix as no other information is given. A: There is a way to stop the Scanner at the end of the line. You need to define a delimiter that contains whitespace, the empty expression, but not the next line character: public static void main(final String[] args) { Scanner scan = new Scanner(System.in).useDelimiter(" *"); while (scan.hasNextInt() && scan.hasNext()) { int x = scan.nextInt(); System.out.println(x); } } This way the Scanner sees the \n followed by a delimiter (nothing) and the input stops after pressing return.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jqGrid treegrid, Expand Node Programmatically I am experimenting with the jqGrid treegrid feature. Can anyone explain why the 'expandNode' method doesn't work in this example? (Testing under Chrome and JQ 1.4.2). Note 1: I can't get any of the expand or collapse methods to do anything. They change the appearance of the icon, but the child rows don't disappear. If I click the icon manually, the appearance changes AND the child rows get hidden as expected. Note 2: What's the difference between expand/collapse ROW and expand/collapse NODE? Note 3: I found some entries on the jqGrid wiki about using setTimeOut, but I think that is relating to wanting to expand everything on initial load. I want to do it based on a click, as indicated here. $(document).ready(function() { var table = $("<table id=treegrid></table>"); $("body").append(table); grid = $("#treegrid"); /* DIRECT COPY FROM SO http://stackoverflow.com/questions/6788727/jqgrid-tree-grid-with-local-data */ var mydata = [ { id:"1", name:"Cash", num:"100", debit:"400.00",credit:"250.00", balance:"150.00", enbl:"1", level:"0", parent:"", isLeaf:false, expanded:false, loaded:true }, { id:"2", name:"Cash 1", num:"1", debit:"300.00",credit:"200.00", balance:"100.00", enbl:"0", level:"1", parent:"1", isLeaf:false, expanded:false, loaded:true }, { id:"3", name:"Sub Cash 1", num:"1",debit:"300.00",credit:"200.00", balance:"100.00", enbl:"1", level:"2", parent:"2", isLeaf:true, expanded:false, loaded:true }, { id:"4", name:"Cash 2", num:"2",debit:"100.00",credit:"50.00", balance:"50.00", enbl:"0", level:"1", parent:"1", isLeaf:true, expanded:false, loaded:true }, { id:"5", name:"Bank\'s", num:"200",debit:"1500.00",credit:"1000.00", balance:"500.00", enbl:"1", level:"0", parent:"", isLeaf:false, expanded:true, loaded:true }, { id:"6", name:"Bank 1", num:"1",debit:"500.00",credit:"0.00", balance:"500.00", enbl:"0", level:"1", parent:"5", isLeaf:true, expanded:false, loaded:true }, { id:"7", name:"Bank 2", num:"2",debit:"1000.00",credit:"1000.00", balance:"0.00", enbl:"1", level:"1", parent:"5", isLeaf:true, expanded:false, loaded:true }, { id:"8", name:"Fixed asset", num:"300",debit:"0.00",credit:"1000.00", balance:"-1000.00", enbl:"0", level:"0", parent:"", isLeaf:true, expanded:false, loaded:true } ], grid = $("#treegrid"); grid.jqGrid({ datatype: "jsonstring", datastr: mydata, colNames:["Id","Account","Acc Num","Debit","Credit","Balance","Enabled"], colModel:[ {name:'id', index:'id', width:1, hidden:true, key:true}, {name:'name', index:'name', width:180}, {name:'num', index:'acc_num', width:80, align:"center"}, {name:'debit', index:'debit', width:80, align:"right"}, {name:'credit', index:'credit', width:80,align:"right"}, {name:'balance', index:'balance', width:80,align:"right"}, {name:'enbl', index:'enbl', width: 60, align:'center', formatter:'checkbox', editoptions:{value:'1:0'}, formatoptions:{disabled:false}} ], height: 'auto', gridview: true, rowNum: 10000, sortname: 'id', treeGrid: true, treeGridModel: 'adjacency', treedatatype: "local", ExpandColumn: 'name', caption: "Demonstrate how to use Tree Grid for the Adjacency Set Model", jsonReader: { repeatitems: false, root: function (obj) { return obj; }, page: function (obj) { return 1; }, total: function (obj) { return 1; }, records: function (obj) { return obj.length; } } }); /* END DIRECT COPY */ var f = $("<button>ExpandCash</button>"); $("body").append(f); // Test reloading and summarization changes f.bind("click",function() { var rec = $("#treegrid").getRowData("1"); //console.log(JSON.stringify(rec)); $("#treegrid").expandNode(rec); $("#treegrid").expandRow(rec); }); }); A: I was able to get it to expand by aiming for the root nodes (and then second headers; my grid was 3 levels deep) using this code: function Expand() { var rows = $("#treeGrid").jqGrid('getRootNodes'); for (var i = 0; i < rows.length; i++){ var childRows = $("#treeGrid").jqGrid('getNodeChildren', rows[i]); $("#treeGrid").jqGrid('expandNode', rows[i]); $("#treeGrid").jqGrid('expandRow', rows[i]); for (var j = 0; j < childRows.length; j++) { $("#treeGrid").jqGrid('expandNode', childRows[j]); $("#treeGrid").jqGrid('expandRow', childRows[j]); } } } Placed inside a simple click function, this would expand all nodes. Data format shouldn't matter, but I used json data. Nested 'for' loops isn't always the best way to go, but I didn't see another solution that worked for me; it shouldn't be bad though unless you have a large number of nested nodes. NOTE: this code is sensitive to the number of levels your treegrid has; you will need additional loops (or another method) for more than 3 levels (level 0 = root, level 1 = first header, level 2 = leaf), and won't need the inner loop for a 2 level tree
{ "language": "en", "url": "https://stackoverflow.com/questions/7613527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Restrict passed parameter to a string literal I have a class to wrap string literals and calculate the size at compile time. The constructor looks like this: template< std::size_t N > Literal( const char (&literal)[N] ); // used like this Literal greet( "Hello World!" ); printf( "%s, length: %d", greet.c_str(), greet.size() ); There is problem with the code however. The following code compiles and I would like to make it an error. char broke[] = { 'a', 'b', 'c' }; Literal l( broke ); Is there a way to restrict the constructor so that it only accepts c string literals? Compile time detection is preferred, but runtime is acceptable if there is no better way. A: Yes. You can generate compile time error with following preprocessor: #define IS_STRING_LITERAL(X) "" X "" If you try to pass anything other than a string literal, the compilation will fail. Usage: Literal greet(IS_STRING_LITERAL("Hello World!")); // ok Literal greet(IS_STRING_LITERAL(broke)); // error A: With a C++11 compiler with full support for constexpr we can use a constexpr constructor using a constexpr function, which compiles to a non-const expression body in case the trailing zero character precondition is not fulfilled, causing the compilation to fail with an error. The following code expands the code of UncleBens and is inspired by an article of Andrzej's C++ blog: #include <cstdlib> class Literal { public: template <std::size_t N> constexpr Literal(const char (&str)[N]) : mStr(str), mLength(checkForTrailingZeroAndGetLength(str[N - 1], N)) { } template <std::size_t N> Literal(char (&str)[N]) = delete; private: const char* mStr; std::size_t mLength; struct Not_a_CString_Exception{}; constexpr static std::size_t checkForTrailingZeroAndGetLength(char ch, std::size_t sz) { return (ch) ? throw Not_a_CString_Exception() : (sz - 1); } }; constexpr char broke[] = { 'a', 'b', 'c' }; //constexpr Literal lit = (broke); // causes compile time error constexpr Literal bla = "bla"; // constructed at compile time I tested this code with gcc 4.8.2. Compilation with MS Visual C++ 2013 CTP failed, as it still does not fully support constexpr (constexpr member functions still not supported). Probably I should mention, that my first (and preferred) approach was to simply insert static_assert(str[N - 1] == '\0', "Not a C string.") in the constructor body. It failed with a compilation error and it seems, that constexpr constructors must have an empty body. I don't know, if this is a C++11 restriction and if it might be relaxed by future standards. A: No there is no way to do this. String literals have a particular type and all method overload resolution is done on that type, not that it's a string literal. Any method which accepts a string literal will end up accepting any value which has the same type. If your function absolutely depends on an item being a string literal to function then you probably need to revisit the function. It's depending on data it can't guarantee. A: There is a way to force a string literal argument: make a user defined literal operator. You can make the operator constexpr to get the size at compile time: constexpr Literal operator "" _suffix(char const* str, size_t len) { return Literal(chars, len); } I don't know of any compiler that implements this feature at this time. A: A string literal does not have a separate type to distinguish it from a const char array. This, however, will make it slightly harder to accidentally pass (non-const) char arrays. #include <cstdlib> struct Literal { template< std::size_t N > Literal( const char (&literal)[N] ){} template< std::size_t N > Literal( char (&literal)[N] ) = delete; }; int main() { Literal greet( "Hello World!" ); char a[] = "Hello world"; Literal broke(a); //fails } As to runtime checking, the only problem with a non-literal is that it may not be null-terminated? As you know the size of the array, you can loop over it (preferable backwards) to see if there's a \0 in it. A: I once came up with a C++98 version that uses an approach similar to the one proposed by @k.st. I'll add this for the sake of completeness to address some of the critique wrt the C++98 macro. This version tries to enforce good behavior by preventing direct construction via a private ctor and moving the only accessible factory function into a detail namespace which in turn is used by the "offical" creation macro. Not exactly pretty, but a bit more fool proof. This way, users have to at least explicitly use functionality that is obviously marked as internal if they want to misbehave. As always, there is no way to protect against intentional malignity. class StringLiteral { private: // Direct usage is forbidden. Use STRING_LITERAL() macro instead. friend StringLiteral detail::CreateStringLiteral(const char* str); explicit StringLiteral(const char* str) : m_string(str) {} public: operator const char*() const { return m_string; } private: const char* m_string; }; namespace detail { StringLiteral CreateStringLiteral(const char* str) { return StringLiteral(str); } } // namespace detail #define STRING_LITERAL_INTERNAL(a, b) detail::CreateStringLiteral(a##b) /** * \brief The only way to create a \ref StringLiteral "StringLiteral" object. * This will not compile if used with anything that is not a string literal. */ #define STRING_LITERAL(str) STRING_LITERAL_INTERNAL(str, "")
{ "language": "en", "url": "https://stackoverflow.com/questions/7613528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How to load a XML into a DataSet via XSL with C# I'm trying to load a xml which contains metadata, for example: <DataSet> <DataTable id="Estrutura"> <Columns> <Column FieldName="ORDEM" DisplayLabel="ORDEM" DataType="Integer" Required="0" Size="0"/> <Column FieldName="NOME" DisplayLabel="NOME" DataType="String" Required="0" Size="100"/> <Column FieldName="NIVEL" DisplayLabel="NIVEL" DataType="Integer" Required="0" Size="0"/> <Column FieldName="INDICE_IMAGEM" DisplayLabel="INDICE_IMAGEM" DataType="Integer" Required="0" Size="0"/> <Column FieldName="TIPO" DisplayLabel="TIPO" DataType="String" Required="0" Size="100"/> </Columns> <Rows> <Row ORDEM="4" NOME="DUnit Pré-Libor6M" NIVEL="3" INDICE_IMAGEM="12" TIPO="Carteira"/> <Row ORDEM="3" NOME="DUnit CDI-Libor6M" NIVEL="3" INDICE_IMAGEM="12" TIPO="Carteira"/> <Row ORDEM="2" NOME="DUnit RF_Swaps" NIVEL="2" INDICE_IMAGEM="10" TIPO="Pasta"/> <Row ORDEM="1" NOME="DUnit RF_Swaps" NIVEL="1" INDICE_IMAGEM="2" TIPO="Tesouraria"/> <Row ORDEM="0" NOME="DUnit" NIVEL="0" INDICE_IMAGEM="0" TIPO="Instituição"/> </Rows> </DataTable> <DataTable id="Parametro;RME"> <Columns> <Column FieldName="Definição" DisplayLabel="Definição" DataType="String" Required="0" Size="50"/> <Column FieldName="Valor" DisplayLabel="Valor" DataType="String" Required="0" Size="150"/> </Columns> <Rows> <Row Definição="Padrão da Cota" Valor="Fechamento"/> <Row Definição="Data Inicial" Valor="11/1/2011"/> <Row Definição="Data Final" Valor="12/1/2011"/> <Row Definição="Formas Apuração" Valor="Customizado"/> <Row Definição="Tipo Preço Stock" Valor="Fechamento"/> <Row Definição="Data Atual/Hora" Valor="18/8/2011 17:42:00"/> <Row Definição="Usuário" Valor="DUNIT"/> <Row Definição="Definições de Cálculo" Valor="Usuário"/> <Row Definição="Moeda Visual" Valor="REAL"/> <Row Definição="Tipo Financeiro" Valor="Líquida"/> <Row Definição="Tipo Rentabilidade" Valor="Líquida"/> <Row Definição="Método Rentabilidade" Valor="TIR"/> <Row Definição="Quantidade de Barras no Gráfico" Valor="10"/> <Row Definição="Usa Todas as Barras no Gráfico" Valor="Não"/> </Rows> </DataTable> </DataSet> Well, how it's possible to see, it's look like a dataset structure, but I'm not getting this do work. I think the way is try xls, but, how can I make a xls which turn this xml code in a xml recognizable by a DataSet. In other words, how can I make this XSL and load it together with XML to be recognizable by the DataSet? Thank you. A: You'll probably want to have a look at how DataSet infers table structure from XML. Looks to me like you'll just need to: * *delete the column definitions (those are what are inferred), *rename your DataTable element to the actual name of the table, and *make Row a child element of the new table element. For example, something like this ought to work: <DataSet> <Estrutura> <Row ORDEM="4" NOME="DUnit Pré-Libor6M" NIVEL="3" .../> <Row ORDEM="3" NOME="DUnit CDI-Libor6M" NIVEL="3" .../> ... Using an XSL transform to reach this state is a pretty basic use of XSL and shouldn't be too hard with the intros to XSL around the web. I suggest you give it a try and post a new question here on SO when you run into specific XSL problems.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Method improvement on data access via ADO.NET Which of the two code segments below would you prefer? Why? Are there any circumstances where the other would be preferable? Could you make any further improvements? i. private int GetSize(string deptName) { QueryHelper dqh = new QueryHelper(); return dqh.GetDataSet("sp_GetDeptSize",deptName).Tables[0].Rows[0]["Size"]; } ii. private int GetSize(string deptName) { QueryHelper dqh = new QueryHelper(); DataSet ds = dqh.GetDataSet("sp_GetDeptSize", deptName); DataTable dt = ds.Tables[0]; DataRow dr = dt.Rows[0]; int size = dr["Size"]; return size; } Please note that QueryHelper is custom type. My answer to this: I prefer to method i, which is more concise. It seems that method ii is not preferable under any circumstances. I need advice on further improvement on method i, and idea would be very much appreciated. A: The two methods you listed are 99% identical. The notational difference is a matter of taste. Both still need a cast to int. I would prefer skipping the DataSet and use Command.ExecuteScalar() A: Given the code, i will say Method 2 is better as you must NULL check everything before trying to access. what if dataset it NULL?. Method 1 will error out. What if there is no table in the dataset? Again method 1 will error out. What if there is a table but no row? Again method 1 will error out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: validation of viewstate mac failed Exception I have a question and i searched on stack-over flow and found some answer but none of it works for me ,i have a web application it works on the local host but when i host it online it gives me and error that : <customErrors mode="Off" > must be off i made that then i gone to use my application it gives me the following one : Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster. any help will be great ,thanks A: You lose security benefits by doing this, but the quickest solution would be to set enableViewStateMac="false" in the web.config. <pages enableViewStateMac="false" ...> This can sometimes happen if your ViewState is very large, and you postback before the page has finished loading. If you're using ViewState as a data repository, that's probably why this happens. I would also inspect your markup and make sure that you don't have any unclosed <script> tags.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: YAML - substituting values for variables? consider the following yaml hadoop: storage: '/x/y/z/a/b' streaming_jar_path: '/x/c/d/f/r/*.jar' commands: mkdir: 'hadoop dfs -mkdir dir' copyFromLocal: 'hadoop dfs -copyFromLocal from_path to_path' run: 'hadoop jar $streaming_jar_path -mapper mapper_path -reducer reducer_path -input hdfs_input -output hdfs_output' I want to substitute the value of streaming_jar_path to $streaming_jar_path, how can I do that? I know we can merge the hashes using &(anchors) but here i just want to change one value I am sorry if this is trivial thing, I am very new to YAML Thank you A: You can restructure your YAML file and execute with Ansible. commands.yml: - hosts: localhost vars: streaming_jar_path: '/x/c/d/f/r/*.jar' tasks: - name: mkdir shell: "hadoop dfs -mkdir dir" - name: copyFromLocal shell: "hadoop dfs -copyFromLocal from_path to_path" - name: run shell: "hadoop jar {{ streaming_jar_path }} -mapper mapper_path -reducer reducer_path -input hdfs_input -output hdfs_output" Then simply run ansible-playbook to execute shell commands: ansible-playbook commands.yml A: This should be a simple process of reading your file, editing the data and writing back to file. import yaml infile = 'input.yaml' outfile = 'output.yaml' #read raw yaml data from file into dict with open(infile, 'r') as f: data = yaml.load(f.read()) #make changes to dict data['hadoop']['streaming_jar_path'] = '$streaming_jar_path' #write dict back to yaml file with open(outfile, 'w') as f: f.write(yaml.dump(data))
{ "language": "en", "url": "https://stackoverflow.com/questions/7613536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Adjusting table cell width Let's take 4 table columns - ID, Text, Date, Action. In my case table have always constant width - in example 960px. How can I create such table as : *-*------------------------------------*----------*----* |1| Some text... |May 2011 |Edit| *-*------------------------------------*----------*----* |2| Another text... |April 2011|Edit| *-*------------------------------------*----------*----* As we can see, ID, Date and Action adjust their width to content, Text is as long as possible.... Is that possible to do without setting specific width of columns ? When ID = 123 or Date = November 2011, columns should automatically be wider... A: basically, it's just like this: http://jsfiddle.net/49W5A/ - you have to set the cell-width to something small (like 1px) to make them stay as small as possible. but as you'll see, theres one problem with the date-fields doing a line-wrap. to prevent this, just add white-space: nowrap; for your text-field: http://jsfiddle.net/ZXu7U/ working example: <style type="text/css"> .table{ width:500px; border: 1px solid #ccc; } .table td{ border: 1px solid #ccc; } .id, .date, .action{ width:1px; } .date{ white-space: nowrap; } </style> <table class="table"> <tr> <td class="id">1</td> <td class="text">Some Text...</td> <td class="date">May 2011</td> <td class="action">Edit</td> </tr> <tr> <td class="id">2</td> <td class="text">Another Text...</td> <td class="date">April 2011</td> <td class="action">Edit</td> </tr> </table> A: My best advice to you is to not touch the widths of the table, the table automatically layouts in a way that does all cells best. However, if you'd like to push through, I'd use width: 1px; on the cells that needs adjusting (one of each column is enough). Also use white-space: nowrap on all cells. that will make sure the lines don't break. A: Try this: .id, .date, .action is the table cells (td). CSS: .id, .date, .action { width: 1em; } It worked for me. The width:1em will not cut the text but force the width size to the minimum. A: Using a 100% width on the wide td and a fixed width for the table along with white-space:nowrap, this can be done: Demo HTML <table> <tr> <td>1</td> <td width="100%">Some text... </td> <td>May 2011</td> <td>Edit</td> </tr> <tr> <td>2</td> <td width="100%">Another text... </td> <td>April 2011</td> <td>Edit</td> </tr> </table> CSS table { ... width:960px; } td { ... white-space:nowrap; } A: The best way that I've found for setting table column widths is to use a table head (which can be empty) and apply relative widths for each table head cell. The widths of all cells in the table body will conform to the width of their column head. Example: HTML <table> <thead> <tr> <th width="5%"></th> <th width="70%"></th> <th width="15%"></th> <th width="10%"></th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Some text...</td> <td>May 2018</td> <td>Edit</td> </tr> <tr> <td>2</td> <td>Another text...</td> <td>April 2018</td> <td>Edit</td> </tr> </tbody> </table> CSS table { width: 600px; border-collapse: collapse; } td { border: 1px solid #999999; } View Result Alternatively, you can use colgroup as suggested here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Increase font size chrome console How can i increase the font-size in the chrome console? It seems Paul Irish did it: http://www.youtube.com/watch?v=4mf_yNLlgic UPDATE Here are some tips on how customize the theme: https://plus.google.com/115133653231679625609/posts/UZF34wPJXsL A: Windows 7, Google Chrome 19.0.1084.46 m Method with modifying "User StyleSheets/Custom.css" not worked on me, but Ctrl+"+" worked :-) A: THIS IS OBSOLETE - See @TinyJaguar's answer. You can now just use Command-+ if you've selected something in the developer console. If you want to increase the font size in the Javascript console, you need some specific font sizes. It's a bit trickier than just setting the font size for source: .source-code { font-size: 16px !important; font-family: monospace; } .console-prompt { font-size: 16px !important; font-family: monospace; } .console-message-text { font-size: 16px !important; font-family: monospace; } .monospace { font-size: 16px !important; font-family: monospace; } #elements-content { font-size: 16px !important; } A: On MacOs, if your key 0 or + or - are on the second level, typing ⌘ ⇧ + won't work. In such a case, you need to use capslock ⇪, and then you can type ⌘ + and ⌘ 0 A: Of Note: From within DevTools, you must have the Elements Tab open in order to adjust font size by using "Ctrl +/-." For some reason it cannot be done in other tabs. In the newer version of Chrome, you can easily change the font size of font in Developer Tools. * *Open Developer Tools *Click on any line in source code *Press Ctrl + + to increase font size or Ctrl + - to decrease font size A: I've created a small plugin which provides a collection editor settings for Chrome Developer Tools, including the ability to incrementally control font size. * *Install DevTools Author Chrome extension from Chrome Web Store *Enable Developer Tools experiments in chrome://flags/#enable-devtools-experiments. Restart Chrome for flags to take effect. *Open DevTools (cmd + opt + I); Settings > Experiments > check Allow custom UI themes. This will add an 'Author Settings' panel to Chrome Developer Tools, where you can incrementally control font size, from 10px - 22px A: If you're like me, CMD++ is not working for you because it switches you to the first tab instead (even though you have Enable ⌘ + 1-9 shortcut to switch panels turned off). Well, in that case, open Dev Tools, Undock into separate window and then go for View --> Zoom in in Chrome Menu Bar. Voilà! Once you dock Dev Tools back into the browser window, View --> Zoom in will actually increase font size in a browser window, but as long as Dev Tools are undocked, it targets the undocked Dev Tools. A: Press * *CTRL++ to zoom in *CTRL+- to zoom out *CTRL+0 to reset to default For Mac, replace CTRL with CMD key (a.k.a., ⌘). A: I know this is way old, but the simple solution I found is to increase the min. font size in the settings and that will take care of the font size in chrome debugger. A: Another quick way to change the font size in Chrome Dev tools permanently: Settings--> Show Advanced Settings --> Web Content : change the Page Zoom percentage. Here is the result: http://i.imgur.com/Puzduo9.png A: If you just need a quick, temporary size bump you can press Ctrl + / - to zoom and Ctrl 0 to reset. A: Here's a pretty recent blog post on the subject. Basically, override Default/User StyleSheets/Custom.css in your user directory with something like: /* Keep .platform-mac to make the rule more specific than the general one above. */ body.platform-mac.platform-mac-snowleopard .monospace, body.platform-mac.platform-mac-snowleopard .source-code { font-size: 11px !important; font-family: Menlo, monospace; } body.platform-windows .monospace, body.platform-windows .source-code { font-size: 12px !important; font-family: Consolas, Lucida Console, monospace; } body.platform-linux .monospace, body.platform-linux .source-code { font-size: 11px !important; font-family: dejavu sans mono, monospace; } A: * *Open Browser *Open Console. *Press Ctrl+. I hope it will help you A: If you are on a Mac, are using a japanese keyboard, and want to zoom the console temporarily, the short-cuts are: Zoom In: ⌘ ^ Zoom Out: ⌘ - Reset Zoom: ⌘ 0 Other Applications are using + for zooming in, but because on japanese keyboards the plus-sign is on the second level, it is only accessible with shift. So: ⌘ ⇧ + That where it gets weird, because to Chrome ⌘ ⇧ + apparently means "Zoom Content". If you are in the Javascript console, and do ⌘ ⇧ +, the window's content area in zoomed in. But doing a Zoom-out ⌘ - moves the focus back to the console and zooms it out. Result: The content is getting larger, the console smaller. Aaarggghhh. A: If you're using a newer MacBook pro 2017, you can simply use command => shift => + or - all pressed at once. A: If you are using a laptop, you can do that with only your laptop trackpad. Tap on your trackpad with one finger(don't release yet) then scroll up or down with another finger to increase or decrease font size. Just make sure the dev tools panel is on focus. Tested and working on my HP Pavilion, Windows 8. A: press ctrl and hover your mouse wheel
{ "language": "en", "url": "https://stackoverflow.com/questions/7613546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "127" }
Q: Generate PDF in ASP.NET from Fully Rendered Page Does anyone know of a component (open source or 3rd party) that would allow you to export a fully rendered HTML page to PDF in c#? We have a page that has its DOM modified with jquery but the methods we have tried (ABCpdf.NET, WebClient, etc) don't register any DOM changes from javascript in the PDF. We need to programmatically export that rendered HTML (post-jquery) to PDF on the fly. A: ExpertPDF HtmlToPdf Converter v7.0 A: I was looking for something similar many months ago and as far as I can remember, it's not possible with any free third-party controls. There are paid ones available. The closest you can get is iTextSharp. It will allow you to export the contents of specific html tads and user controls but it's a bit of a pain to deal with A: I'm never tried is but there's an open source solution called wkhtmltopdf that renders a PDF from HTML/JavaScript/CSS using the WebKit engine. This post talks a little bit about using it. If it works I'd like to know because I've heard this request a couple of times here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can I view resolved files after a merge in hg? I'm using mercurial and one problem I found while merging was the fact that it's hard for a single developer to merge with the default trunk after a lot of changes. So even if the developer resolves the conflicts by hand there is always a change to miss some of the intersecting changes. I would like to take a look at the history of a merge and see the resolved files, so other developers can review it. Can I view resolved files after a merge in hg? A: What I like to do is this workflow: hg pull ;; assuming I'm on development branch hg merge -r default hg diff ;;do incoming changes look good ;; run tests hg commit -m "merged from others, lookin' good" hg up default -C hg merge -r development hg diff ;;everything look good still? ;; run tests hg commit -m "And back to default, all tests pass" hg push
{ "language": "en", "url": "https://stackoverflow.com/questions/7613550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hierarchical data - Parent id or Nested set model I'm working on a project that required categories, I used a nested set model and it worked out well. I have another portion of the same project, however it requires a different type of hierarchy, there will only ever be a parent. So, an item can only EVER relate to one other item. Would you say for this, using simply parent_id would be more appropriate then a full nested set model? Thank you! A: I would say it doesn't matter. I think of nested set and adjacent tree model as different data structure but the same type of hierarchical tree. I think of a ternary trie and a patricia trie. Both have a different data structure but the type trie is the same.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a common UIToolbar helper file and methods for Objective C I have build a view with a UIToolbar which is working great. This toolbar will be appearing right across the app, and right now I am copy/pasting the code into lots of different files. I do not want to repeat myself, and am looking to create a helper file that will include the toolbar setup and the methods linked to the toolbar in every file I need. I've tried putting the following code into a .h .m file and inheriting from UIView, but there is a problem because there is a reference to self.navigiationItem Is there a way that I can create a common Objective C file that will have all the code and methods I want to use? Thanks. - (void)viewDidLoad // ... // appears in viewDidLoad // ---- TOOLBAR -----------// UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 100.0, 44.01f)]; //[toolbar setBackgroundColor:[UIColor blackColor]]; //[toolbar setTintColor:[UIColor redColor]]; //[toolbar.layer setBorderColor:[[UIColor redColor] CGColor]]; // Bar buttons UIBarButtonItem *barReloadBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(btnReload:)]; [barReloadBtn setStyle:UIBarButtonItemStyleBordered]; // Profile bar button UIImage *image = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"111-user" ofType:@"png"]]; UIBarButtonItem *barProfileBtn = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStyleBordered target:self action:@selector(btnProfile:)]; // Button array NSMutableArray *buttons = [[NSMutableArray alloc] init]; [buttons addObject:barProfileBtn]; [buttons addObject:barReloadBtn]; [toolbar setItems:buttons]; // Set nav items self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:toolbar]; // memory cleanup [image release]; [buttons release]; [barReloadBtn release]; [barProfileBtn release]; [toolbar release]; // ---- /TOOLBAR -----------// } #pragma mark - IBActions -(IBAction) btnProfile:(id)sender { UserProfileVC *userProfileVC = [[UserProfileVC alloc] initWithNibName:@"UserProfileVC" bundle:[NSBundle mainBundle]]; UINavigationController *tmpNavCon = [[UINavigationController alloc] initWithRootViewController:userProfileVC]; [self.navigationController presentModalViewController:tmpNavCon animated:YES]; [tmpNavCon release]; [userProfileVC release]; } -(IBAction) btnReload:(id)sender { NSLog(@"Not done yet"); } A: navigationItem is a property of UIViewController, not UIView. If you've got common functionality like this, I would inherit from UIViewController, add your custom logic to viewDidLoad (or wherever is appropriate) and then inherit your view controllers from that class. Just make sure you call [super viewDidLoad] from your subclasses' implementations of viewDidLoad.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: finding duplicate rows on more than one field I am using this query to find duplicates based on two fields: SELECT last_name, first_name, middle_initial, COUNT(last_name) AS Duplicates, IF(rec_id = '', 1, 0) AS has_REC_ID FROM files GROUP BY last_name, first_name HAVING COUNT(last_name) > 1 AND COUNT(first_name) > 1; Okay, what this returns is a set of rows with first, last, and middle names, a column called 'Duplicates' with a lot of 2s, and a column called has_REC_ID with mixed 1s and 0s. Ultimately, what I'm trying to do is find which rows have matching first and last names--and then for each of those pairs, find the one that has ('') as a value for rec_id, assign the rec_id value from the one that DOES have a rec_id, and then delete the record that had a rec_id in the first place. So for starters I though I would create a new column and do something like this: UPDATE files a SET a.has_dup --new column = if(a.last_name IN ( SELECT b.last_name FROM files b GROUP BY b.last_name HAVING COUNT(b.last_name) > 1 ) , 1, null); But MySQL returns: "You can't specify target table 'a' for update in from clause" I'll bet there's something much less ridiculous than the method I'm trying here. Can someone please help me figure out what that is? UPDATE: I also tried: UPDATE files a SET a.has_dup = 1 WHERE a.last_name IN ( SELECT b.last_name FROM files b GROUP BY b.last_name HAVING COUNT(b.last_name) > 1 ); ...and got the same error message. A: From the documentation: Currently, you cannot update a table and select from the same table in a subquery. I can't think of a quick workaround to that. Update Apparently, there is a "quick" workaround, but whether or not it's performant is another issue. It's all about adding a new layer of indirection by introducing a temporary table: UPDATE files a SET a.has_dup --new column = if(a.last_name IN ( SELECT b.last_name FROM (SELECT * FROM files) -- new table target b GROUP BY b.last_name HAVING COUNT(b.last_name) > 1 ), 1, null); A: You could: 1) Create a holding table 2) Populate the holding table with those rows that have a matching first and last name and have rec_id != "" 3) Delete the rows from the original table (files) that have a matching first and last name and have rec_id != "" 4) Update the rows in the original table that have a matching first and last name and have rec_id = "". 5) Drop the holding table So something like: create table temp ( firstname varchar(100) not null, lastname varchar(100) not null, rec_id int not null ); insert into temp (select firstname,lastname,rec_id from files where firstname = lastname and rec_id != ''); delete from files where firstname = lastname and rec_id != ''; update files f set f.rec_id = (select t.rec_id from temp t where f.firstname = t.firstname and f.lastname = t.lastname) where f.firstname = f.lastname and f.rec_id != ''; drop table temp; A: I don't have any MySQL to test, but this I think this should be work: (EDITED->FAIL) UPDATE files SET has_dup = if(last_name IN ( SELECT b.last_name FROM files b GROUP BY b.last_name HAVING COUNT(b.last_name) > 1 ) , 1, null); EDITED: Another try: UPDATE files f, (SELECT b.last_name FROM files b GROUP BY b.last_name HAVING COUNT(b.last_name) > 1 ) as duplicates SET f.has_dup = 1 WHERE f.last_name = duplicates.last_name
{ "language": "en", "url": "https://stackoverflow.com/questions/7613555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OCaml: Declaring a function before defining it Is there a way to declare a function before defining it in OCaml? I'm using an OCaml interpreter. I have two functions: let myFunctionA = (* some stuff here..... *) myFunctionB (*some stuff *) let myFunctionB = (* some stuff here .... *) myFunctionA (* some stuff *) This doesn't work though, since myFunctionA can't call myFunctionB before it's made. I've done a few google searches but can't seem to find anything. How can I accomplish this? A: What you want is to make these two functions mutually recursive. Instead of using "let ... let ...", you have to use "let rec ... and ..." as follows: let rec myFunctionA = (* some stuff here..... *) myFunctionB (*some stuff *) and myFunctionB = (* some stuff here .... *) myFunctionA (* some stuff *) A: Actually "let rec .." has a very serious limitation: it only works within a single module. This forces the programmer to write big modules where it is not desired .. a problem which does not occur in lowly C! There are several workarounds, all unsatisfactory. The first is to make a variable of the function type and initially store a function raising an exception in it, then later store the desired value. The second is to use class types and classes (and one indirection). If you have a lot of mutually recursive functions this is the best way (because you only need to pass a single object to each of them). The easiest and most ugly is to pass the functions to each other as arguments, a solution which rapidly gets out of control. In a module following all the definitions you can simplify the calling code by introducing a set of "let rec" wrappers. Unfortunately, this does not help defining the functions, and it is common that most of the calls will occur in such definitions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Adding Views to an Android Viewgroup Programmatically This seems to be a common question yet documentation is very hard to find. I'm looking for examples that show me how to create my own view group (preferably by extending an already existing one) and then add views programmaticly. Thanks. A: ViewGroup ViewGroup is abstract, and its onLayout is abstract too. So you need to provide an implementation for onLayout where you do assign a position at every child (View) of the viewgroup.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: ActiveModel fields not mapped to accessors Using Rails 3 and ActiveModel, I am unable to use the self. syntax to get the value of an attribute inside an ActiveModel based object. In the following code, in save method, self.first_name evaluates to nil where @attributes[:first_name] evaluates to 'Firstname' (the value passed in from the controller when initializing the object). In ActiveRecord this seems to work, but when building the same class in ActiveModel, it does not. How do you refer to a field using accessors in an ActiveModel based class? class Card include ActiveModel::Validations extend ActiveModel::Naming include ActiveModel::Conversion include ActiveModel::Serialization include ActiveModel::Serializers::Xml validates_presence_of :first_name def initialize(attributes = {}) @attributes = attributes end #DWT TODO we need to make sure that the attributes initialize the accessors properyl, and in the same way they would if this was ActiveRecord attr_accessor :attributes, :first_name def read_attribute_for_validation(key) @attributes[key] end #save to the web service def save Rails.logger.info "self vs attribute:\n\t#{self.first_name}\t#{@attributes["first_name"]}" end ... end A: I figured it out. The "hack" that I mentioned as a comment to Marian's answer actually turns out to be exactly how the accessors for ActiveRecord classes are generated. Here's what I did: class MyModel include ActiveModel::AttributeMethods attribute_method_suffix "=" # attr_writers attribute_method_suffix "" # attr_readers define_attribute_methods [:foo, :bar] # ActiveModel expects attributes to be stored in @attributes as a hash attr_reader :attributes private # simulate attribute writers from method_missing def attribute=(attr, value) @attributes[attr] = value end # simulate attribute readers from method_missing def attribute(attr) @attributes[attr] end end You can see the same thing if you look in ActiveRecord's source code (lib/active_record/attribute_methods/{read,write}.rb). A: You need ActiveModel::AttributeMethods for that
{ "language": "en", "url": "https://stackoverflow.com/questions/7613574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to open text in Notepad from .NET? When I click a button on a Windows Forms form, I would like to open a Notepad window containing the text from a TextBox control on the form. How can I do that? A: You don't need to create file with this string. You can use P/Invoke to solve your problem. Usage of NotepadHelper class: NotepadHelper.ShowMessage("My message...", "My Title"); NotepadHelper class code: using System; using System.Runtime.InteropServices; using System.Diagnostics; namespace Notepad { public static class NotepadHelper { [DllImport("user32.dll", EntryPoint = "SetWindowText")] private static extern int SetWindowText(IntPtr hWnd, string text); [DllImport("user32.dll", EntryPoint = "FindWindowEx")] private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); [DllImport("User32.dll", EntryPoint = "SendMessage")] private static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam); public static void ShowMessage(string message = null, string title = null) { Process notepad = Process.Start(new ProcessStartInfo("notepad.exe")); if (notepad != null) { notepad.WaitForInputIdle(); if (!string.IsNullOrEmpty(title)) SetWindowText(notepad.MainWindowHandle, title); if (!string.IsNullOrEmpty(message)) { IntPtr child = FindWindowEx(notepad.MainWindowHandle, new IntPtr(0), "Edit", null); SendMessage(child, 0x000C, 0, message); } } } } } References (pinvoke.net and msdn.microsoft.com): SetWindowText: pinvoke | msdn FindWindowEx: pinvoke | msdn SendMessage: pinvoke | msdn A: Save the file to disk using File.WriteAllText: File.WriteAllText("path to text file", myTextBox.Text); Then use Process.Start to open it in notepad: Process.Start("path to notepad.exe", "path to text file"); A: Try this out: System.IO.File.WriteAllText(@"C:\test.txt", textBox.Text); System.Diagnostics.Process.Start(@"C:\test.txt"); A: For non ASCII user. [DllImport("User32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Unicode)] private static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam); Based on @Peter Mortensen answer Add CharSet = CharSet.Unicode to the attribute for supporting Unicode characters A: I was using the NotepadHelper solution until I discovered it doesn't work on Windows 11. Writing the file to disk and starting with the default text editor seems to be the best solution. This has already been posted, but I discovered you need to pass UseShellExecute=true. System.IO.File.WriteAllText(path, value); System.Diagnostics.ProcessStartInfo psi = new() { FileName = path, UseShellExecute = true }; System.Diagnostics.Process.Start(psi); I write to the System.IO.Path.GetTempPath() folder and run a cleanup when the application exits - searching for a unique prefix pattern for file names used by my app. Something like this: string pattern = TempFilePrefix + "*.txt"; foreach (string f in Directory.EnumerateFiles(Path.GetTempPath(), pattern)) { File.Delete(f); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7613576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Java - how do I prevent WindowClosing from actually closing the window I seem to have the reverse problem to most people. I have the following pretty standard code to see if the user wants to do some saves before closing the window: frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent ev) { boolean close = true; // check some files, asking if the user wants to save // YES and NO handle OK, but if the user hits Cancel on any file, // I want to abort the close process // So if any of them hit Cancel, I set "close" to false if (close) { frame.dispose(); System.exit(0); } } }); No matter what I try, the window always closes when I come out of windowClosing. Changing WindowAdapter to WindowListener doesn't make any difference. What is weird is that the documentation explicitly says "If the program does not explicitly hide or dispose the window while processing this event, the window close operation will be cancelled," but it doesn't work that way for me. Is there some other way of handling the x on the frame? TIA A: I've just tried this minimal test case: import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.WindowConstants; public class Test { public static void main(String[] args) { final JFrame frame = new JFrame("Test"); frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent ev) { //frame.dispose(); } }); frame.setVisible(true); } } If I keep the dispose call commented, and hit the close button, the window doesn't exit. Uncomment that and hit the close button, window closes. I'd have to guess that something is wrong in your logic to set your "close" variable. Try double checking that. A: not sure where is your problem, import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ClosingFrame extends JFrame { private JMenuBar MenuBar = new JMenuBar(); private JFrame frame = new JFrame(); private static final long serialVersionUID = 1L; private JMenu File = new JMenu("File"); private JMenuItem Exit = new JMenuItem("Exit"); public ClosingFrame() { File.add(Exit); MenuBar.add(File); Exit.addActionListener(new ExitListener()); WindowListener exitListener = new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { int confirm = JOptionPane.showOptionDialog(frame, "Are You Sure to Close this Application?", "Exit Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); if (confirm == JOptionPane.YES_OPTION) { System.exit(1); } } }; frame.addWindowListener(exitListener); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.setJMenuBar(MenuBar); frame.setPreferredSize(new Dimension(400, 300)); frame.setLocation(100, 100); frame.pack(); frame.setVisible(true); } private class ExitListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { int confirm = JOptionPane.showOptionDialog(frame, "Are You Sure to Close this Application?", "Exit Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); if (confirm == JOptionPane.YES_OPTION) { System.exit(1); } } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { ClosingFrame cf = new ClosingFrame(); } }); } } A: For the handling of this thing do: if the user selects yes then use setDefaultCloseOperation(DISPOSE_ON_CLOSE); within the curly braces of that if else if a cancel is selected then use setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); Consider example: int safe = JOptionPane.showConfirmDialog(null, "titleDetails!", "title!!", JOptionPane.YES_NO_CANCEL_OPTION); if(safe == JOptionPane.YES_OPTION){ setDefaultCloseOperation(DISPOSE_ON_CLOSE);//yes } else if (safe == JOptionPane.CANCEL_OPTION) { setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);//cancel } else { setDefaultCloseOperation(DISPOSE_ON_CLOSE);//no } A: This is the key, methinks: frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); Makes the difference in the test case I cooked up. A: Not sure where your problem is, but this works for me! frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { int res=JOptionPane.showConfirmDialog(null, "Do you want to exit.?"); if(res==JOptionPane.YES_OPTION){ Cal.this.dispose(); } } }); A: To solve the same problem I tried the very first answer of this article. As separate application it works, but not in my case. Maybe difference is in JFrame(in answer) and FrameView (my case). public class MyApp extends SingleFrameApplication { // application class of my project ... protected static MyView mainForm; // main form of application ... } public class MyView extends FrameView { ... //Adding this listener solves the problem. MyApp.getInstance().addExitListener(new ExitListener() { @Override public boolean canExit(EventObject event) { boolean res = false; int reply = JOptionPane.showConfirmDialog(null, "Are You sure?", "", JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.YES_OPTION) { res = true; } return res; } @Override public void willExit(EventObject event) { } }); ... } A: setDefaultCloseOperation() method helps in the problem .https://chortle.ccsu.edu/java5/Notes/chap56/ch56_9.html view this link
{ "language": "en", "url": "https://stackoverflow.com/questions/7613577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "55" }
Q: Call a controller's method in other controllers (staying DRY) I'm slightly new to Rails (i.e. stupid and need some teachin'). I have a controller (call it ControllerFoo) that performs a particular task (theMethod) which could be useful in other controllers (say, from within ControllerBar). So, of course, the method is defined as self.theMethod in ControllerFoo (which means it's a class method, right?), and access in ControllerBar as ControllerFoo.theMethod. Confused yet? Here's the problem: the ControllerFoo.theMethod uses session data, and when called from ControllerBar, session is nil. In fact, it seems that session is also nil when being called from itself. I guess what I'm saying is class methods can't access session data? <rant>I hate how session data can't simply be accessed anywhere like in PHP</rant> So for now, since I'm not smart enough to know how to do this correctly, I've just duplicated the logic in several places throughout my app. But this is not DRY at all, and I hate it. So how can I create a method in a controller that's accessible to other controllers and can also access session data? class ControllerFoo < ApplicationController def self.theMethod (greeting) p "#{greeting} #{session[:user]}!" end end class ControllerBar < ApplicationController def show ControllerFoo.theMethod("Hello,") end end A: Couple of options... * *Put the shared method in the shared parent ApplicationController *Create a module that both ControllerFoo and ControllerBar will include e.g. module SharedModule def theMethod (greeting) p "#{greeting} #{session[:user]}!" end end class ControllerFoo < ApplicationController include SharedModule end class ControllerBar < ApplicationController include SharedModule def show theMethod("Hello,") end end A: The way you would do this is Ruby would be to create a module containing the class (or instance) methods you wish to share and include it in the classes you need to have those methods defined in.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Order of listeners in Java I wrote my own table cell editor that extends an AbstractCellEditor and implements a TableCellEditor, an ItemListener, and a MouseListener. Is there a way I can have the mouseClicked method be executed first before the itemStateChanged method? I'm trying to do the following: private int rowClicked; private JTable table; public void itemStateChanged(ItemEvent e) { if (rowClicked == 5) { // Do something to row 5. } } public void mouseClicked(MouseEvent e) { Point p = e.getPoint(); rowClicked = table.rowAtPoint(p); } A: Here is a nice article explaining the absence of listener notification order in swing: Swing in a better world A: I encountered a similar problem and just wrote this class. It is a composite action listener where action listeners have priorities. Higher priorities get called first. It is not generic and only applies to action listeners. import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import java.util.TreeSet; public class CompositeActionListenerWithPriorities implements ActionListener { private Map<Integer, ArrayList<ActionListener>> listeners = new TreeMap<Integer,ArrayList<ActionListener>>(); @Override public void actionPerformed(ActionEvent e) { TreeSet<Integer> t = new TreeSet<Integer>(); t.addAll(listeners.keySet()); Iterator<Integer> it = t.descendingIterator(); while(it.hasNext()){ int x = it.next(); ArrayList<ActionListener> l = listeners.get(x); for(ActionListener a : l){ a.actionPerformed(e); } } } public boolean deleteActionListener(ActionListener a){ for(Integer x : listeners.keySet()){ for(int i=0;i<listeners.get(x).size();i++){ if(listeners.get(x).get(i) == a){ listeners.get(x).remove(i); return true; } } } return false; } public void addActionListener(ActionListener a, int priority){ deleteActionListener(a); if(!listeners.containsKey(priority)){ listeners.put(priority,new ArrayList<ActionListener>()); } listeners.get(priority).add(a); } } A: Ideally you should not try to get the row number being edited inside the editor. Once user is done editing in the editor and moves to another cell, JTable will get the current value in the editor using the getCellEditorValue() method and then call setValueAt(Object aValue, int rowIndex, int columnIndex) on the table model. So it may be better to handle anything specific to the row in the setValueAt() method. A: You cannot depend on event firing order, but you can forward events as needed. In this case, don't try to determine the row in the ItemListener. Instead, let the CellEditor conclude, and use the new value to update the model, as suggested here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Pointing at array There is such code: int tab[14][2]; int (*wskk)[2] = tab; // &tab makes error int tab2[2]; wskk = &tab2; // tab2 makes error Why is it possible to use one pointer to point at two arrays of different dimensions? A: To understand what's going on you must be familiar with a few key-concepts: * *a multidimensional array is an array of arrays; *the name of an array decays to a pointer to its first element; *the type of wskk is "pointer to an array of 2 ints". Thus, if you write tab you're getting a pointer to the first element of tab, which is its first row; the row has type int[2], so a pointer to it has type int (*)[2], which is exactly the type of your pointer. Because of this you can assign tab to wskk, which will now point to the first row of tab. You can't assign &tab to it, because that yields you a pointer to the whole multidimensional array, which is of type int (*)[14][2]. As for the second piece, it's even simpler: tab2 is an array of two ints, so its type is int[2]. If you get a pointer to it via the & operator, you get a int (*)[2], which is the type of your pointer. Actually, it makes sense: tab2 and a row of tab are effectively the same stuff (an array of 2 ints). You can't assign tab2 to it because tab2 decays to a pointer to its first element, i.e. an int *. A: Make the array-to-pointer conversion explicit, it may become more clear: int tab[14][2]; int (*wskk)[2] = &tab[0]; // point at tab[0], which has type array of 2 int int tab2[2]; wskk = &tab2; // point at tab2, which has type array of 2 int See also: How do I use arrays in C++?
{ "language": "en", "url": "https://stackoverflow.com/questions/7613584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Php recursive function optimization My recursive php function looks like that. It generates menu from db table based on parent-child structure function generateMenu($parent, $level, $menu, $db){ $q = $db->query("select id, name FROM menu WHERE parent = '$parent' AND showinmenu='$menu'"); if($level > 0 && $q->num_rows > 0){ echo "\n<ul>\n"; } while($row=$q->fetch_object()){ echo "<li>"; echo '<a href="?page=' . $row->id . '">' . $row->name . '</a>'; //display this level's children generateMenu($row->id, $level++, $menu, $db); echo "</li>\n\n"; } if($level > 0 && $q->num_rows > 0){ echo "</ul>\n"; } } It works but i feel that it does bunch of work for nothing. Is there anything that needs to be optimized? A: I would get rid of some of that code like this: function generateMenu($parent, $level, $menu, $db){ $q = $db->query("select id, name FROM menu WHERE parent = '$parent' AND showinmenu='$menu'"); if($level > 0 && $q->num_rows > 0){ echo "\n<ul>\n"; while($row=$q->fetch_object()){ echo "<li>"; echo '<a href="?page=' . $row->id . '">' . $row->name . '</a>'; //display this level's children generateMenu($row->id, $level++, $menu, $db); echo "</li>\n\n"; } echo "</ul>\n"; } } A: I would save on the many database queries and instead do it in one like this. This will definitely result in better performance: function generateMenu($parent, $level, $menu, $db){ $q = $db->query("select parent, id, name FROM menu WHERE showinmenu='$menu'"); $elements = array(); while($row=$q->fetch_object()){ $elements[$row->parent][] = $row; } _generateMenu($parent, $level, $elements); } function _generateMenu($parent, $level, $elements){ if (!array_key_exists($parent, $elements)){ return; } if($level > 0){ echo "\n<ul>\n"; } foreach($elements[$parent] as $row){ echo "<li>"; echo '<a href="?page=' . $row->id . '">' . $row->name . '</a>'; //display this level's children _generateMenu($row->id, $level+1, $elements); echo "</li>\n\n"; } if($level > 0){ echo "</ul>\n"; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7613585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I build my own personal android app store? How does one create a personal app store for Android built from either custom or open source software. A: * *Build a website using custom or open source software that presents applications so people can download them *Devise a means for developers to register & upload applications *??? *Profit A: I would imagine you start with a server and place your apk's in the server then write a front side handler to interface between the server and the rest of the world. Then write an app to connect to the server.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: HQL / Nested Eager Loading I am wondering what the best way is to load nested values for lazy loaded objects. I'm providing an example to help explain this better. public class A{ private B b; //Lazy loaded private C c; //Lazy loaded private D d; //Lazy loaded } public class B{ private E e; //Lazy loaded private F f; //Lazy loaded } public class C{ } public class D{ } As an example I want to do: System.out.println(a.getB().getE()); If I ran the above statement I'd get a lazy load exception. I can always do the following: for (A a : somePossiblyLargeList) { org.hibernate.Hibernate.initialize(a.getB().getE()); } but obviously performance would suck. Is there a way I can write a custom HQL query which returns A objects that are pre-populated with those specific nested fields? Thanks! A: Of course. Use join fetch in your HQL query, as explained in the Hibernate reference documentation (that you should read): select a from A a left join fetch a.b b left join fetch b.e e where ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7613590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Error While posting Data to a web application from a windows service."The remote server returned an error: (500) Internal Server Error." I'm getting this error while trying to post data to a hosted web application from a windows service. PostSubmitter post = new PostSubmitter(); post.Url = "http://192.168.0.1/Invoice/Invoice1.aspx"; post.PostItems.Add("subscriberid", subscriberid.ToString()); post.PostItems.Add("StartDate", StartDate); post.PostItems.Add("EndDate", EndDate); post.PostItems.Add("AdvanceBillDate", AdvanceBillDate); post.Type = PostSubmitter.PostTypeEnum.Post; try { string res = post.Post(); } catch (Exception exp) { } This is code snippet of my windows service which posts data to web application. Does any one know the reason.I'm using asp .Net C# A: Compare your request from C# with one done in a browser. Use fiddler to do this. You should be able to compare everything from header values, to complete post data, etc. and be able to figure out what you have missing. I would suspect you are leaving out required a value and the server application is throwing a (likely unexpected) exception. A: Finally i got wat was missing.Actually i was posting data to the web application and reading it using Request.QueryString......Which is actually how Get Method is read.So modified my code as PostSubmitter post = new PostSubmitter(); post.Url = "http://192.168.0.1/Invoice/Invoice1.aspx"; post.PostItems.Add("subscriberid", subscriberid.ToString()); post.PostItems.Add("StartDate", StartDate); post.PostItems.Add("EndDate", EndDate); post.PostItems.Add("AdvanceBillDate", AdvanceBillDate); post.Type = PostSubmitter.PostTypeEnum.Get; try { string res = post.Post(); } catch (Exception exp) { }
{ "language": "en", "url": "https://stackoverflow.com/questions/7613597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Drupal displaying "region" instead of content everywhere? My completely finished website started displaying "region" in all the regions instead of the content. This was shortly after I enabled "Calendar Multiday" so perhaps it was related (although I have now disabled that module). Calendar and Date were previously enabled and working perfectly. I am not actually sure if the problem has anything to do with the module. Anyone seen anything like this? Could it have to do with access control? I disabled the module but that didn't do anything.. To be clear, even admins cannot see the content and simply see "region" in every region. A: please clear the cache and tell me if its solved the problem... you can clear the cache by flushing the database tables that start with cache_... , or by implementing cache_clear_all(), drupal_flush_all_caches() functions ... A: Check the region.tpl.php file if you have this problem as it was overriding all my content!
{ "language": "en", "url": "https://stackoverflow.com/questions/7613599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What doesn't get inherited in .Net? I guess I was surprised to learn that Implements or <Serializable()> do not get inherited from class to class which means that it must be redefined each I want to recreated those behaviors. I was wondering what else isn't inhertible in .Net? Thanks A: These are 2 different items: interface and attribute inheritance. The Inherits portion refers to how interfaces behave across class hierarchies. Interfaces are indeed inherited. If a given base class implements IFactory then all of it's derived types will. There are certain language oddities on how a derived class can re-implement the interface or specific methods. However at a .Net level once a base class implements an interface all derived classes will as well. Whether or not an attribute is inherited depends on the value of AttributeUsage.Inherited on the AttributeUsage for the given attribute. In the case of Serializable it's marked as Inherits=false and won't be inherited. Every attribute must pick their own behavior here. A: The long answer would take too long, but the short answer is any class using the sealed (c#) or NotInheritable (VB.NET) modifier. http://msdn.microsoft.com/en-us/library/88c54tsw%28v=vs.71%29.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7613602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: random username generator i am trying to create a random username generator. i have looked at several random string generators, but none of them look like actual usernames. i am wondering how i would go about creating a script like the one featured on this page: http://generator.my-addr.com/generate_usernames-free_username_generator_online_tool.php basically takes a word from the dictionary, adds a certain number of random characters, and then adds a certain number of numbers. my biggest problem is having it create realistic usernames. A: Even though I don't see why you'd want to generate username, if your only concern is that they be pronounceable I would look into Markov chains, which will allow you to randomly generate pronounceable words. You could look at the following projects for examples: * *http://passkool.sourceforge.net/ *http://shorl.com/koremutake A: If you're looking for quick PHP solution to drop in, then I'd recommend: Mudnames It generates fantasy style names from a set of dictionaries that you can find in the install readme. (I'd also throw a short salt in after the name, just to be sure it's unique.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7613604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Change Page Title on Canvas App This is a shot in the dark, but is it possible to update the page title of a canvas app using Javascript? While the page title does seem to reflect the app, is it possible to update it once the page has rendered? I'd like to be able to add an active counter to the title (e.g. "(0) Title", "(1) Title", "(2) Title") based on what's happening in the app, which doesn't seem possible from within an iframe. [edit] Document.title obviously doesn't work since it's applied to my page. But I've also tried parent.document.title and that doesn't work either. A: To access the parent window you need something like: parent.document.title But this is NOT allowed for obvious reasons: * *Facebook won't allow you to access their page (document) *Read about Cross Domain Communications & Same origin policy (there are suggested workarounds but I don't think Facebook will allow them either) Anyway, if you try the code above you'll get (as expected): Permission denied to access property 'document'
{ "language": "en", "url": "https://stackoverflow.com/questions/7613608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where should infrastructure services contracts live? I have UI, Application, Domain and Infrastructure Layers. In my Infrastructure Layer take reference of Domain and Application Layer to register services interfaces of both using Ninject. But I need in my Application Layer a service in Infrastructure Layer, then i need to reference the Infrastructure Layer in my Application Layer. The problem is Infrastructure Layer take reference to Application Layer and when I'll reference Infrastructure Layer in Application Layer the following error is show: A reference to 'Infrastructure' could not be added. Addind this project as a reference would cause a circular dependency. How I solve this? Put the Ninject Configuration of Application Layer in the Application Layer? I think this is not correct, because I'll have Infrastructure implementation in my Application Layer. A: Infrastructure services contracts should be defined in the layers that consume them (Domain and Application), but implemented in Infrastructure. Take a look at Dependency Inversion Principle and Onion Architecture. Infrastructure layer should depend on App and Domain. Your Domain and App should not depend on Infrastructure. They should depend on abstraction defined in their own terms. You may find this answer interesting. The actual implementation of this abstraction should be injected at the application startup in a so called Composition Root. For example in your Application you can define and interface like: ICanNotifyUserOfSuccessfullRegistration The Infrastructure layer will reference Application and will implement this interface using SMTP or SMS classes: class SmsNotificator : ICanNotifyUserOfSuccessfullRegistration { ... } Later on this implementation will be injected into Application by DI container. Application will not have a dependency on Infrastructure but will still use it, hence Dependecny Inversion. I recommend reading Dependency Injection in .NET, even if you use Java or other stacks. A: Sounds like your layers are either too tightly coupled or have the wrong boundaries. You can decouple the layers by introducing interfaces that live in their own project and can be referenced by the others.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What are your best practices for working with test data in Django? I currently use a single fixtures file per application, but as projects grow, the tests are taking far too long and I believe that the (now large) fixtures being loaded for each test class are at fault. I've avoided having lots of smaller fixtures because of concerns about duplication and maintenance, but I know think that's unavoidable. Before I go down that path though, I thought I would ask what others do with fixtures for testing their applications/projects. A: Yes you have hit on a problem with a large set of fixtures. The constant deserialization/loading does add up as your test suite grows. I would suggest writing utility functions to create data as you need it rather than relying on fixtures. For instance you might have a function to create a new auth.User like: def create_user(data=None): data = data or {} defaults = { 'username': get_random_string(), 'email': get_random_email(), 'password': get_random_string() } defaults.update(data) return User.objects.create_user(**defaults) Writing a function to generate a random string/email is left as an exercise for the reader :) A: Make sure you use sqlite for testing purposes. There's a considerable difference in speed compared to other db engines.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JUNG: which libraries are required dependencies? I'm looking at JUNG for visualizing directed graphs. The JUNG 2.0.1 download comes with 17 different jar files, and some of them appear to be samples and demos. Does anyone know which are the real libraries that are required if you want to use JUNG? A: never mind, they're documented in this wiki page: Following is a list of the primary projects of jung2, along with their dependencies: * *jung-api: the core interfaces that define graphs and their behaviors, plus some utility classes for handling graphs. * *compile/runtime dependencies: none *jung-graph-impl: our implementations of the jung-api interfaces, plus some facilities for generating (random) graphs. * *compile/runtime dependencies: jung-api, collections-generic *additional unit test dependencies: junit *jung-algorithms: classes for analyzing graphs, e.g., clustering, ranking, shortest path calculations, and layout algorithms. * *compile/runtime dependencies: jung-api, collections-generic, colt *additional unit test dependencies: junit, jung-graph-impl *jung-io: classes for saving and storing graphs. * *compile/runtime dependencies: jung-api, jung-algorithms, collections-generic, colt *additional unit test dependencies: junit, jung-graph-impl *jung-visualization: interfaces and classes for rendering graphs as diagrams. * *compile/runtime dependencies: jung-api, jung-algorithms, colt *jung-samples: examples of how to use JUNG. * *compile/runtimedependencies: jung-api, jung-graph-impl, jung-algorithms, jung-io, jung-visualization A: Based upon the dependency list mentioned in its pom for 2.0.1 version, there shouldn't be any 3rd party dependencies.
{ "language": "en", "url": "https://stackoverflow.com/questions/7613619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }