text
stringlengths
8
267k
meta
dict
Q: Jsoup div[class=] syntax works whereas div.class syntax doesn't - Why? For the following HTML snippet: <div class="class_one class_two class_three classfour classfive classsix"> some inner content </div> The following Jsoup selector works: div[class=class_one class_two class_three classfour classfive classsix] But the equivalent div.class syntax doesn't work: div.class_one.class_two.class_three.classfour.classfive.classsix Why? What am I missing? EDIT: Based on the feedback I received below, I realize that I failed to explain what "doesn't work" means. This was due to my confusion as to how multiclass selection syntax works. By "not working" I meant that the .classname syntax above selects way too many divs than the class=classname syntax (with the same exact number of classname and in the same order!) does, because the HTML in question contained additional divs with a 7th class name... It turns out that this is by design. That's what I was missing, and thanks to @Hovercraft Full Of Eels and @BalusC who helped me discover this. A: Again, as per my comment, you need to show us your code in context to show how it isn't working. For instance when I try to analyze this simple text: <html> <head></head> <body> <div class="class_one class_two class_three classfour classfive classsix"> some inner content </div> </body> </html> With this code: import java.io.IOException; import java.util.Scanner; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; public class Foo { public static void main(String[] args) throws IOException { Scanner scan = new Scanner(Foo.class.getResourceAsStream("Foo.txt")); String text = ""; while (scan.hasNextLine()) { text += scan.nextLine() + "\n"; } Document doc = Jsoup.parse(text); Elements eles = doc.select("div.class_one.class_two.class_three.classfour.classfive.classsix"); System.out.println(eles); } } I get this result: <div class="class_one class_two class_three classfour classfive classsix"> some inner content </div> Suggesting that your use of select should work, and if it's not working, something else may be going on. Your best bet may be to do what I've just done: post some data and some compilable runnable code (an SSCCE) and have it show just how your code is not working.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is there a C preprocessor macro to print out a struct? As far as I can tell, there's no way to print out a struct value in C. i.e., this doesn't fly: typedef struct { int a; double b; } stype stype a; a.a=3; a.b=3.4; printf("%z", a); instead you have to say: printf("a: %d\n", a.a); printf("b: %f\n", a.b); This seems like a perfect place where you could use a macro to save a vast amount of typing for arbitrary structs. Is the C preprocessor powerful enough to perform this transformation? A: I would make two macros, like this: #define STYPE_FMT "%d %f" #define STYPE_MEMS(s) (s).a, (s).b Then you can do something like: printf("hello %s, stype: " STYPE_FMT "\n", "world", STYPE_MEMS(my_s)); What makes this approach superior to a "print function" for the structure is that you can use the macros with any of the printf-family functions you like, and combine printing of other data. You could get even fancier and instead do: #define STYPE_FMT "%d %.*f" #define STYPE_MEMS(s) (s).a, 6, (s).b #define STYPE_MEMS_PREC(s, p) (s).a, (int)(p), (s).b and then you can use the default precision or choose a custom precision. A: I think that the simplest solution (and maybe the most beautiful) is to use a function to print your specific struct. void display_stype(stype *s) { printf("a: %d\n", s->a); printf("b: %f\n", s->b); } If your struct changed, you can adapt in one place your code easily. A: No, the C preprocessor is mostly a textual macro replacement tool. It doesn't know about types and structures of C. A: Is the C preprocessor powerful enough to perform this transformation? Yes, it is, but then you have to repeat the entire struct declaration within the macro which kind of defeats the purpose. You could have something like this: STRUCT_PRINTF( a , ( int, a ) ( double, b ) ); and then you would need a pretty complex implementation of such macro, with lots and lots of helper macros/functions. A: You cannot iterate on struct members in C, either dynamically or statically (nor in C++). There is no reflection in C. Thus, there is no way to make the preprocessor perform this transformation. A: You could make macro for this: #define PRINT_MEMBER(M) do {printf(#M": %d\n", (int) M;} while(0) and then print it like this: PRINT_MEMBER(a.a); PRINT_MEMBER(b->b); You might wanna define multiple of these to cover different types (e.g. floats, doubles, print as hex). Unfortunately there is no good workaround for this as C preprecossor has no notion of what types are, e.g. you can't use something like switch(typeof(M)) { case int: printf(.."%d"..; break; ...} .
{ "language": "en", "url": "https://stackoverflow.com/questions/7560086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Coffeescript class losing functions I have a CoffeeScript which I can't call functions from. But if I declare an instance of it and add functions to the instance it works. What am I missing? Function doesn't get called: class testClass username: 'Fred' this.testFunction = ()-> alert 'test' test = new testClass test.testFunction() Function works: class testClass username: 'Fred' test = new testClass test.testFunction = ()-> alert 'test' test.testFunction() A: Within the class body, this points to the class itself, not its prototype. What you want is class testClass username: 'Fred' testFunction: -> alert 'test' Writing this.testFunction =, on the other hand, creates testClass.testFunction. A: Try class testClass username: 'Fred' testFunction: ()-> alert 'test' test = new testClass test.testFunction() Coffeescript has classes as a first level concept; the this.testfunction = is wrong. You should just define it as a field of type function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Preserving the order of records from subquery while using "Union distinct" construct I want to make sure that the order of the result from subquery are preserved while using Union distinct. Please note that "union distinct" is required to filter on duplicates while doing the union. For example: select columnA1, columnA2 from tableA order by [columnA3] asc union distinct select columnB1, columnB2 from tableB When I run this, I am expecting that the records ordered from subquery ( select columnA1, columnA2 from tableA sort by [columnA3] asc) comes in first (as returned by order by columnA3 asc) followed by those from tableB. I am assuming that I cannot add another dummy column because that would make union distinct to not work. So, this won't work: select column1, column2 from ( select column1, column2, 1 as ORD from tableA order by [columnA3] asc union distinct select column1, column2, 2 as ORD from tableB ) order by ORD A: Essentially, MySQL isn’t preserving the order of records from sub-query while using “Union distinct” construct. After a bit of research, I found that it works if we put in a limit clause or have nested queries. So, below are the two approaches: Approach-1: Use Limit clause select columnA1, columnA2 from tableA order by [columnA3] asc Limit 100000000 union distinct select columnB1, columnB2 from tableB I have tested this behavior using few datasets and it seems to work consistently. Also, there is a reference to this behavior in MySQL‘s documentation ( http://dev.mysql.com/doc/refman/5.1/en/union.html ): “Use of ORDER BY for individual SELECT statements implies nothing about the order in which the rows appear in the final result because UNION by default produces an unordered set of rows. Therefore, the use of ORDER BY in this context is typically in conjunction with LIMIT, so that it is used to determine the subset of the selected rows to retrieve for the SELECT, even though it does not necessarily affect the order of those rows in the final UNION result. If ORDER BY appears without LIMIT in a SELECT, it is optimized away because it will have no effect anyway.” Please note that there is no particular reason in choosing LIMIT of 10000000000 other than having a sufficiently high number to make sure we cover all cases. Approach-2: A nested query like the one below also works. select column1, column2 from ( select column1, column2 order by [columnA3] asc ) alias1 union distinct ( select column1, column2 from tableB ) I couldn’t find a reason for nested query to work. There have being some references online (like the one from Phil McCarley at http://dev.mysql.com/doc/refman/5.0/en/union.html ) but no official documentation from MySQL. A: select column1, column2 from ( select column1, column2, 1 as ORD from tableA union distinct select tableB.column1, tableB.column2, 2 as ORD from tableB LEFT JOIN tableA ON tableA.column1 = tableB.column1 AND tableA.column2 = tableB.column2 WHERE tableA.column1 IS NULL ) order by ORD note that UNION not only de-dupes across the separate sets, but within sets Alternatively: select column1, column2 from ( select column1, column2, 1 as ORD from tableA union distinct select column1, column2, 2 as ORD from tableB WHERE (column1, column2) NOT IN (SELECT column1, column2 from tableA) ) order by ORD
{ "language": "en", "url": "https://stackoverflow.com/questions/7560091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Two key shortcut in emacs without repressing the first key? Suppose I define the following shortcut (global-set-key (kbd "C-d C-j") "Hello!") Is it possible to configure emacs so that if I type "C-d C-j C-j C-j" I will get "Hello! Hello! Hello!" rather than having to type "C-d C-j C-d C-j C-d C-j"? A: If you are looking for something generic that works on all commands I cant see how that would work - how would emacs know if you are starting a new command or want to repeat the previous. A better example would be "C-c h", if you type "h" after that, should emacs repeat the command or insert a h? That said, emacs already has a mechanism for this - the universal argument. Try this key sequence: C-u 3 C-d C-j It is even fewer keypresses than C-d C-j C-j C-j C-j A: Try something like this: (global-set-key (kbd "C-c C-j") (lambda() (interactive) (insert "Hello!") (message "Type j to print Hello!") (while (equal (read-event) ?j) (insert "Hello!")) (push last-input-event unread-command-events))) Idea taken from kmacro-call-macro A: I don’t think you can configure Emacs so that it does that for all commands. However, you can implement this functionality in the commands themselves. This is what is done for C-x e. Here is a macro I just wrote (guided by the standard definition of kmacro-call-macro in GNU Emacs 23.1.1) that makes it easy to add this functionality to your own commands: (defmacro with-easy-repeat (&rest body) "Execute BODY and repeat while the user presses the last key." (declare (indent 0)) `(let* ((repeat-key (and (> (length (this-single-command-keys)) 1) last-input-event)) (repeat-key-str (format-kbd-macro (vector repeat-key) nil))) ,@body (while repeat-key (message "(Type %s to repeat)" repeat-key-str) (let ((event (read-event))) (clear-this-command-keys t) (if (equal event repeat-key) (progn ,@body (setq last-input-event nil)) (setq repeat-key nil) (push last-input-event unread-command-events)))))) Here’s how you use it: (defun hello-world () (interactive) (with-easy-repeat (insert "Hello, World!\n"))) (global-set-key (kbd "C-c x y z") 'hello-world) Now you can type C-c x y z z z to insert Hello, World! three times. A: No. The sequence "ctrl-d ctrl-j" is what is bound to the string "Hello!" Emacs binds the sequence as a whole to the given string. Here's some good info on the topic: Link On the other hand, if you wanted just three instances of "Hello!", you could define that sequence C-d C-j C-d C-j C-d C-j as "Hello! Hello! Hello!", but it would be shorter to just define a simpler sequence for the string you want. A: I use this all the time. You'll need library repeat.el (part of GNU Emacs) to use it. (defun make-repeatable (command) "Repeat COMMAND." (let ((repeat-message-function 'ignore)) (setq last-repeatable-command command) (repeat nil))) (defun my-hello () "Single `hello'." (interactive) (insert "HELLO!")) (defun my-hello-repeat () (interactive) (require 'repeat) (make-repeatable 'my-hello)) Now bind my-hello-repeat: (global-set-key (kbd "") 'my-hello-repeat) Now just hold down the home key to repeat HELLO!. I use this same technique in multiple libraries, including Bookmark+, thing-cmds, and wide-n. A: smartrep is all you want (require 'smartrep) (defvar ctl-d-map (make-keymap)) ;; create C-d map (define-key global-map "\C-d" ctl-d-map) (smartrep-define-key global-map "C-d" '(("C-j" . (insert "hello"))))
{ "language": "en", "url": "https://stackoverflow.com/questions/7560094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: TTY and/or ARF Response from Experian's API I'm trying to use the PHP Curl library to connect to Experian's API. When I post a HTTPS request to Experian, I get an HTTP 200 OK response, but nothing more. I am expecting a TTY or ARF response. Do anyone have insight in what I'm doing wrong? Here's a snippet of my code below for reference $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,'http://stg1.experian.com/lookupServlet1?lookupServiceName=AccessPoint&lookupServiceVersion=1.0&serviceName=NetConnectDemo&serviceVersion=2.0&responseType=text/plain'); //not the actual site //For Debugging curl_setopt($ch, CURLOPT_VERBOSE, TRUE); curl_setopt($ch, CURLOPT_TIMEOUT,60); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_POST,1); //#2-Net Connect client receives ECALS response. This is the Net Connect URL. $ecals_url = curl_exec($ch); //#3-Net Connect client validates that the URL ends with “.experian.com”. If the URL is valid, the processing continues; otherwise, processing ends. $host_name = parse_url( $ecals_url ); $host_name = explode(".", $host_name['host'] ); $host_name = $host_name[1].'.'.$host_name[2]; if( $host_name == "experian.com" ) { //#4-Net Connect client connects to Experian using URL returned from ECALS. echo "step 4 - connect to secure connection<br>"; curl_setopt($ch, CURLOPT_VERBOSE, TRUE); curl_setopt($ch,CURLOPT_URL,$ecals_url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_USERPWD,"$username:$password"); curl_setopt($ch,CURLOPT_CERTINFO,1); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,1); curl_setopt($ch, CURLOPT_TIMEOUT, 10); //times out after 10s curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1); curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt"); curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $result = curl_exec ($ch); print_r ($result); A: It has been a while since I messed with our Experian Net Connect service but I believe you have to base64 encode the username:password value for their system to take it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What do the little icons next to the each variable denote, in the SSIS variables window There seems to be variations of the icon image, and i'm sure they mean something. The standard appears to be a blue box with an X in italics. And, some have a little 'circle' in the bottom left of the standard icon image. I have seen a blue circle with an plus in it, a red circle with a plus in it. what do these mean, and what are the other variations and their meanings. I have googled a bit and have found no answer. thanks in advance.. A: You have a Visual Studio snapin for ETL development that is causing the icons to get an overlay image. I know of two products that do that. I am not familiar with the glyphs you are referencing but they generally indicate an item configured using expressions or Below is BIXpress BIDSHelper (free) calls them SSIS Variable Window Extensions Finally, SQL Denali aka SQL Server v.Next will have "Icon marker (“Adorner”) to indicate Connection Managers and Variables with expressions" (Look really hard and you will see a little fx symbol in the corner of InputFile connection manager)
{ "language": "en", "url": "https://stackoverflow.com/questions/7560098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Logarithmic scale I am programming a small synthesizer application and I input musical notes by clicking along the length of a bar. Now, the musical scale is logarithmic and my question is, how do I convert the position of the mouse to a relevant pitch. At the moment I calculate a ratio. It works, sort of, but I get a wide range of closely packed low notes, and at the far end I takes of with just a few pixels translating into multiple octaves. Basically I want, if I click at the center of the bar (1/2), the frequency is doubled, and 1/4 is another double in freq. etc… I'm being stupid here! A: Frequencies of musical notes are indeed logarithmic. The frequency doubles when you go one octave higher, and halves when you go one octave lower. A standard A is exactly 440Hz. So, you need a power law to translate location into a frequency. Something like f*2.0^(x/w) where w is the width of an octave, f is a scale factor and ^ is the power operator.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use shared ItemGroup element in batching tasks I'm trying to automate the creation of Firefox addon for two different platforms by using MSbuild: I have shared files set which are the same for Mac and Windows and have platform specific files. I want to batch the task of making XPI(which is just a renamed Zip file) by platform, but I can't find the right way to add the platform agnostic(shared) files as input for Zip task. Currently, my solution is to duplicate shared files items with platform windows and with platform mac, and then batch Zip task by Platform parameter. I have a feeling that my solution is not optimal. Maybe community can propose a better solution. Below is the simplified solution I created with comments: <?xml version="1.0" encoding="utf-8"?> <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <ProjectMSBuildToolsPath Condition=" '$(ProjectMSBuildToolsPath)' == '' ">MSBuild</ProjectMSBuildToolsPath> </PropertyGroup> <!-- Required Import to use MSBuild Community Tasks --> <Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/> <!-- Default platform type is shared--> <ItemDefinitionGroup> <ZipFiles> <Platform>Shared</Platform> </ZipFiles> </ItemDefinitionGroup> <ItemGroup> <ZipFiles Include="chrome\overlay.js" /> <ZipFiles Include="chrome\Win\methodContainer.js"> <Platform>Win</Platform> </ZipFiles> <ZipFiles Include="chrome\Mac\dataContainer.js"> <Platform>Mac</Platform> </ZipFiles> </ItemGroup> <Target Name="_PrepareItemsForZip" Outputs="$(Platform)"> <ItemGroup> <!-- Merge Shared and Windows specific files --> <ZipFilesToWin Include="@(ZipFiles)" Condition="('%(ZipFiles.Platform)' == 'Shared') Or ('%(ZipFiles.Platform)' == 'Win')" > <Platform>Win</Platform> </ZipFilesToWin> <!-- Merge Shared and Mac specific files --> <ZipFilesToMac Include="@(ZipFiles)" Condition="('%(ZipFiles.Platform)' == 'Shared') Or ('%(ZipFiles.Platform)' == 'Mac')" > <Platform>Mac</Platform> </ZipFilesToMac> </ItemGroup> <!-- Merge Mac and Windows files set --> <ItemGroup> <_ZipFiles Include="@(ZipFilesToWin);@(ZipFilesToMac)" /> </ItemGroup> </Target> <!-- batch zipping files based on input platform --> <Target Name="MakeXPI" DependsOnTargets="_PrepareItemsForZip" Inputs="@(_ZipFiles)" Outputs="%(Platform)" > <Message Text="Zipped files: @(_ZipFiles) %(Platform)" Importance="high"/> <Zip Files="@(_ZipFiles)" WorkingDirectory="" ZipFileName="CoolAddon-%(Platform).xpi" ZipLevel="9" /> </Target> </Project> A: Extract them to file like SharedProperties.properties: <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <ZipFiles> <Platform>Shared</Platform> </ZipFiles> <PropertyGroup> </Project> And then simply import in targets/script you need them: <Project ... > <Import Project="SharedProperties.properties" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7560108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: visual studio weird behavior I am making a win32 application using visual studio 2008. When ever i compile my code which generates a simple dialog, all of the dialogs text show in Chinese language. I have not set Chinese anywhere. can some one elaborate what the issue is? My code is #include <windows.h> int WINAPI WinMain( HINSTANCE nowInstance, HINSTANCE prevInstance, LPSTR ipCmdLine, int nCmdShow ) { MessageBox(NULL,"My First Program","Our University",MB_OK); return 0; } A: It sounds like you're mixing Unicode and ANSI. Have you tried MessageBox(NULL, _T("My First Program"), _T("Our University"), MB_OK); And does that give you the expected results?
{ "language": "en", "url": "https://stackoverflow.com/questions/7560109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How to use jquery ajax and webmethod with sitecore I'm running Sitecore 6.4 and trying to get some data using ajax and webmethod in Sitecore. Everything is in a sublayout (user control) This is the code that calls the webmethod: $("#NextBanner").click(function () { $.ajax({ type: "POST", url: "/GetNext", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { alert('success'); }, error: function (err) { alert('error'); } }); This is the webmethod, returns a string: [WebMethod] public static string GetNext() { return "Hello"; } In a test project without using Sitecore I used "Default.aspx/GetNext" as the url for the ajax call but now obviously this doesn't work, I get 404 not found error because of the url. What should the url be? The sublayout path is: /layouts/sublayouts/test.ascx Any recommendation on a different approach of achieving this? Thanks, T Update Thanks everybody for the answers. I ended up creating a web service under website/sitecore/shell/webservices, not sure if that's the right place to put the web service, any suggestions? Thanks, T A: Put the code in a WebForm. You can't call a sublayout like a page. Reference the file by its file system path in your ajax call, e.g. /layouts/ajaxProcessor.aspx You should also check out the following blog post about sitecore and ajax goodness: http://blog.velir.com/index.php/2011/09/22/lazy-websites/ A: Instead of using web methods, we'll typically make use of ASP.NET MVC controllers to serve JSON data in Sitecore projects. Properly setup, you can access some Sitecore.Context values (just not Item) and all Sitecore data access APIs. http://www.sitecore.net/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2010/10/Sitecore-MVC-Crash-Course.aspx http://shashankshetty.wordpress.com/2009/03/04/using-jsonresult-with-jquery-in-aspnet-mvc/ The Json() ActionResult option in MVC controllers makes sending back serialized data really easy. A: I created a folder under 'Website' and placed my web services there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating a Interactive GUI for a java game Hey guys I'm creating a game similar to farmville in java and I'm just wondering how would I implement the interactive objects/buttons that the user would usually click to interact with the game client. I do not want to use the swing library (generic windows looky likey objects), I would like to import custom images for my buttons and assign button like properties to those images which would be used for the GUI. Any advice? Any pointers? I can't seem to find that information through youtube or some other java gaming sites as they're only showing simple example using swing. Any help would be deeply appreciated thanks! Regards Gareth A: Do you really not want to use Swing, or do you just not want the default look and feel of a JButton and other swing controls? What does " (generic windows looky likey objects), " mean? There are many sources out there that describe customizing buttons to include images on top of them: Creating a custom button in Java JButton and other controls have all the events and methods associated with adding click listeners, etc. You probably don't want to create your own control. We do not have enough information to go off of, for example what does "interactive objects" mean? If you simply want to add an icon to a JButton, use the constructor that takes an Icon. A: You can use JButton, just override the paint function. and draw what ever you want there. It takes a while until you get it at the first time how this works. I recommend you to read a little about the event-dispatching thread (here is java's explanation) And here is some code that I wrote so you have a simple reference. import java.awt.Graphics; import java.awt.GridLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; public class Test extends JButton implements ActionListener{ private static final long serialVersionUID = 1L; Image img; /** constuctor **/ public Test(String tImg, JFrame parent){ this.img = new ImageIcon(tImg).getImage(); this.addActionListener(this); } /*********** this is the function you want to learn ***********/ @Override public void paint(Graphics g){ g.drawImage(this.img, 0, 0, null); } @Override public void actionPerformed(ActionEvent arg0) { // TODO do some stuff when its clicked JOptionPane.showMessageDialog(null, "you clicked the button"); } public static void main(String[] args) { JFrame f = new JFrame(); Test t = new Test("pics.gif", f); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setLayout(new GridLayout(1, 1)); f.add(t); f.setSize(400,600); f.setVisible(true); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7560113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Random number c++ in some range Possible Duplicate: Generate Random numbers uniformly over entire range I want to generate the random number in c++ with in some range let say i want to have number between 25 and 63. How can I have that? A: You can use the random functionality included within the additions to the standard library (TR1). Or you can use the same old technique that works in plain C: 25 + ( std::rand() % ( 63 - 25 + 1 ) ) A: Since nobody posted the modern C++ approach yet, #include <iostream> #include <random> int main() { std::random_device rd; // obtain a random number from hardware std::mt19937 gen(rd()); // seed the generator std::uniform_int_distribution<> distr(25, 63); // define the range for(int n=0; n<40; ++n) std::cout << distr(gen) << ' '; // generate numbers } A: int range = max - min + 1; int num = rand() % range + min; A: int random(int min, int max) //range : [min, max] { static bool first = true; if (first) { srand( time(NULL) ); //seeding for the first time only! first = false; } return min + rand() % (( max + 1 ) - min); } A: float RandomFloat(float min, float max) { float r = (float)rand() / (float)RAND_MAX; return min + r * (max - min); } A: Use the rand function: http://www.cplusplus.com/reference/clibrary/cstdlib/rand/ Quote: A typical way to generate pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range: ( value % 100 ) is in the range 0 to 99 ( value % 100 + 1 ) is in the range 1 to 100 ( value % 30 + 1985 ) is in the range 1985 to 2014
{ "language": "en", "url": "https://stackoverflow.com/questions/7560114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "106" }
Q: devenv fails on build machine Our .vdproj setup project contains a few .dbproj projects. We are going to use devenv since MSBuild does not support the creation of MSIs from .vdproj setup install projects. When I run devenv.com from the command line on a build machine I receive the following error: The project 'UserManagement.dbproj' will close once model building has paused. Serializing the project state for project 'UserManagement.dbproj'... Project `UserManagement.dbproj' was successfully serialized to file 'C:\Builds\Test\Sources\UserManagement\UserManagement.dbmdl'. C:\Builds\Test\Sources\UserManagement\UserManagement.dbproj : error : Error HRESULT E_FAIL has been returned from a call to a COM component. It works great from my local machine. We have installed Visual Studio 2010 SP1 on our build box.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: And yet another javascript clearInterval not working I've seen a bunch of these threads and went through a few of them but nothing seemed to be of help so far. So I'm trying to call the timer continuously while the ajax call is taking place. Once the ajax call reaches the complete event, I'd like to clearInterval the timer, but that doesn't seem to be working because the call to CheckProgress() keeps going and going. Here's my code: var timer = ""; $("#ChartUpdateData").click(function () { $("#loadingimgfeatdiv").show(); //ajax loading gif if (timer == "") { console.log("Starting Progress Checks..."); timer = window.setInterval("CheckProgress()", 5000); } $.ajax({ type: "POST", async: true, url: '@(Url.Action("UpdateServerData","Charts"))', contentType: "application/json; charset=utf-8", success: function (data) { }, error: function (XMLHttpRequest, textStatus, errorThrown) { }, complete:function (jqXHR, textStatus) { $("#loadingimgfeatdiv").hide(); StopCheckingProgress(); LoadChart(); }, }); }); function StopCheckingProgress() { window.clearInterval(timer); timer = ""; console.log("Ending Progress Checks..."); } function CheckProgress() { console.log("Checking Progress..."); console.log(timer); } EDIT: A: I've never liked setInterval. I like managing timers directly. var timerStop = false $("#ChartUpdateData").click(function () { $("#loadingimgfeatdiv").show(); //ajax loading gif if (!timerStop) { console.log("Starting Progress Checks..."); CheckProgress() } $.ajax({ type: "POST", async: true, url: '@(Url.Action("UpdateServerData","Charts"))', contentType: "application/json; charset=utf-8", success: function (data) { }, error: function (XMLHttpRequest, textStatus, errorThrown) { }, complete:function (jqXHR, textStatus) { $("#loadingimgfeatdiv").hide(); timerStop = true; }, }); }); function CheckProgress() { if(timerStop) { console.log("Ending Progress Checks..."); return; } console.log("Checking Progress..."); console.log(timer); window.setTimeout(function(){CheckProgress()}, 5000); } A: Your code is fine. Here is a fiddle. It works on Google Chrome and Firefox just as you expected. Can you confirm this snippet is not working on your machine? I made few tiny changes: * *AJAX call to /echo/json *Smaller interval (50 ms) *function reference: setInterval(CheckProgress, 5000) instead of string with JavaScript Interval function is called few times and is cleared once echo service AJAX call returns. Exactly how you want it to be. Can you reproduce the problem there?
{ "language": "en", "url": "https://stackoverflow.com/questions/7560121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to configure mysql version '5.1.49-1ubuntu8' to show multibyte charecters? am using MySQL version 5.1.49 and I have not enabled UTF8 character encoding. The default character-set for MySQL is latin1. How can I change it show UTF8 characters? Even when I query a table using Workbench I get 'NULL' in name section which I want, should display mutibyte characters. A: ALTER DATABASE DEFAULT CHARACTER SET utf8 and for each table: ALTER TABLE SomeTableName DEFAULT CHARACTER SET utf8 also if you will be viewing them from a webpage the HTML need this: <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> and if you are using PHP, use htmlspecialchars() to display the values like this: echo htmlspecialchars($row['some_field'], ENT_COMPAT, 'UTF-8'); and (again only for PHP) do this after mysql_connect(): mysql_query("SET NAMES 'utf8'");
{ "language": "en", "url": "https://stackoverflow.com/questions/7560130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DOM Changed Event Firefox Extension So I have created a Firefox extension and it works great, however when I submitted it (although it was accepted) it came up with one security warning. It said setTimeout() was removed in an else clause. So, is there a way to listen for any DOM change? (or even a specific element changing, I have an ID for both). However, divs do not have an onChange event so any ideas? I don't mind if it's ANY change, doesn't have to be div-specific. A: DOMSubtreeModified event sound like something you want to use. Keep in mind, that it is deprecated and after some time its support will probably be removed from browsers. http://help.dottoro.com/ljrmcldi.php A: It turns out adding an "onChange" event to a div works fine, although it might not be W3C valid it doesn't really matter as it's only a Firefox extension (plus it works!).
{ "language": "en", "url": "https://stackoverflow.com/questions/7560131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What mechanism does Doctrine ORM use to create 'persistant' objects? I've recently begun exploring ORM tools such as Doctrine, and in my reading I'm learning that Doctrine creates 'persistant classes' -- which I might be understanding this incorrectly as objects that persist across multiple http requests. So I'm curious how Doctrine accomplishes this, do they store serialized classes on the filesystem, in a database, as data in a cookie? A: They store it in a database, using doctrine dbal. The choice of the database is up to you, and very many differents RDBMS are supported. This overview of the doctrine projects shows that there are also ODM projects (in beta or alpha release though) if you choose to use a NoSQL system like MongoDB, CouchDB, etc...
{ "language": "en", "url": "https://stackoverflow.com/questions/7560132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Best way to handle Unicode in Python Anyone has a link or best practices for handling Unicode characters across python applications? or we need to convert the strings all over the place? [EDIT] Currently we are converting everything we post in urlencode to utf-8 but im wondering if there is a better way to handle that instead of calling encode('UTF-8') A: The main thing you need to do is understand unicode. Realise that a str in Python stores bytes, while a unicode object stores characters; they are distinct things, and shouldn't be treated as interchangeable. All your text strings should always be unicode objects; everything else is binary data. For more, check out my article on getting Unicode right in Python. A: See Python documentation on unicode. In short: internally only work with unicode objects. If you need to talk to outside world, .decode() as early as you can on input and .encode() as late as you can on output.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: When selecting UIViewController in UITabBarController frame of view changes I'am having for my knowledge a strange problem. The thing is that frame of UIVIewController's view changes when is beeing displayed for the first time in UITabBarController. I'll try to describe my architecture. I have a class that is subclass of UITabController. Inside this class i create 3 UIViewController (A,B,C) and than put them to viewControllers array of UITabBarController. selectedIndex of UITabBarController is set to 0 so A is the first one dislayed. Everthing renders normaly in view A. But when i switch to second view B or third view C every subview frame is somehow broken. Sizes and positions are changed. i NSLog the frames of UIViewControllers (A, B, C) before adding them to the viewControllers array of UITabBarController and the result is (0,20,320,460). At the moment they are displayed, their frame changes to (0,0,320,411). But ViewControlles A still renders OK. Other two not:S A: Would have to see some code to know exactly what the problem is but in the meantime what you should do is setup the subviews int the viewWillAppear method of your viewController and use a BOOL to make sure they are only ever setup once (not every time the viewWillAppear method is called). This should make sure the subviews match the correct framing. -(void)viewWillAppear { if (!viewWasAlreadySetUpBOOL) { //setup all the views viewWasAlreadySetUpBOOL = YES; } } A: It does make sense that your frame height could change after adding the views to the tabBar array. The height of the standard tabBar is 49px, which is the difference in the height values you are seeing in your logs. This makes sense, since each view is adjusted to fit the available screen size, minus the size of the tabBar. How are you setting up your views, programmatically or IB? What sizes are you using? If you are setting up your frames, either programmatically or through IB, but not taking into consideration the offset from the tabBar, it could throw off where your views are being placed. It would help to see some code, but without any, I'd suggest checking how you adjusted your frames for the tab Bar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java - make a function to create a variable with the name = String we input? How can i make a function: When i input a string "abc" this function create a variable with the same name, like this: int abc = 10. void func("abc"){ .......... } //I will have: int abc =10; I can't do it, someone help me? A: You can't create variable in such dynamicly way in Java. But you can use a Map<String, Object>, which allow you support what you need. Try this: public class DynamicVariableUtil { private Map<String, Object> map = new HashMap<String, Object>(); public void setVariable(String name, Object value) { map.put(name, value); } public Object getValue(String name) { return map.get(name); } ... } dynamicVariableUtil.createVariable("abc", 10); ... dynamicVariableUtil.getValue("abc"); A: It is possible but very tricky. I do not think you really need what you are describing. What you really need is method (please, not function!) that returns int value, i.e. int func(String str) { return str.length(); } Now you can use this method: int i = func("abc"); this method will return 3. If you really want to create in variable into method so that this variable will be accessible outside the method you can use JDI (Java debugging interface). You can connect to the JVM where your application is running and do almost anything. But again, I think that this is not what you really need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Graph API Error 2500 We are in the middle of upgrading to Auth 2.0 and have noticed a lot of errors in the Diagnostic page under Insights. It shows "gr:" (which I know means the graph api) and error code 2500 with almost 1 million errors. Unfortunately FB hasn't got any errors documented so I'm hoping someone at FB can clarify the error. A: Apparently it is "An active access token must be used to query information about the current user." which means you're calling some API which requires access token without it. If you do upgrading please note that some API calls now require access token like pageID/feed which previously it didn't. hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7560141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Something wrong with linking I have 3 C++ files: genericStack.h: template <class T> class Stack{ public: Stack (int size){ top = -1; MAX_SIZE = size; v = new T (size); } ~Stack(){ delete v;} T pop(); void push (T); class Underflow{}; class Overflow{}; private: int top; int MAX_SIZE; T* v; }; genericStackImpl.c++: #include "genericStack.h" template <class T> void Stack <T> :: push (T c){ if (top == MAX_SIZE - 1) throw Overflow(); v[++top] = c; } template <class T> T Stack <T> :: pop(){ if (top < 0) throw Underflow(); return v[top--]; } driver.c++: #include <iostream> #include "genericStack.h" int main(){ Stack<char> sc(3); try{ while (true) sc.push ('p'); } catch (Stack<char>::Overflow){std::cout << "Overflow caught\n";} try{ while (true) std::cout << sc.pop() << '\n'; } catch (Stack<char>::Underflow){ std::cout << "Underflow caught\n";} return 0; } When i compile using g++ 4.5: g++ -o driver driver.c++ genericStackImpl.c++ I get these errors: /tmp/ccLXRXgF.o: In function `main': driver.c++:(.text+0x2e): undefined reference to `Stack<char>::push(char)' driver.c++:(.text+0x3c): undefined reference to `Stack<char>::pop()' collect2: ld returned 1 exit status I dont understand what the problem is. If i move the implementation in the driver file, then it compiles and runs. A: Generally speaking, template definitions need to also be in the header file. An exception to this is when you are explicitly instantiating, or using explicit specialisations, neither of which you are doing. One way to solve this would be to move the contents of genericStackImpl.c++ to the bottom of its header file. The reason for this is because template functions are not actual functions, they are just templates. A template is used (instantiated) to create actual functions, and those are what you link against. There are no functions in genericStackImpl.c++. The functions only get created once you use them, i.e. the first time the compiler sees sc.push and sc.pop. Unfortunately, when driver.c++ tries to create these functions, it can't find the template bodies -- they hidden in genericStackImpl.c++! Instead, it just compiles a reference to those functions, hoping that some other file will make them. Finally, when it comes to link time, the linker can't find the function anywhere, so it gives you an error. Another way to solve this would be to explicitly instantiate those functions yourself in genericStackImpl.c++, i.e. template class Stack<char>; This will create the functions, and the linker will find them. The problem with this approach is that it require you to know what types your going to be using in your stack beforehand, so most people just put template definitions in the header file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hot align text center in ListBox - asp.net 4.0 How can you text align center in asp.net 4.0 ListBox element. I tried cssclass but not working. Thank you. A: This works for me: <style type="text/css"> .listbox-centered { width:400px; text-align:center; } </style> ... <asp:ListBox ID="listBox1" runat="server" CssClass="listbox-centered"> <asp:ListItem Text="Item 1" Value="0"></asp:ListItem> <asp:ListItem Text="Item 2" Value="1"></asp:ListItem> </asp:ListBox>
{ "language": "en", "url": "https://stackoverflow.com/questions/7560149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Nesting CSS Styles or inheritance I'm pretty new to using CSS beyond applying directly to each element. I'd like to know how I should be doing this. (simplified from my actual implementation, but relatively the same). Is it possible to inherit styles somehow? I have 3 div classes defined, each positioning a div in my page. I've left out the css for these, but the style divide my page into 3 sections. div.left{} div.center{} div.right{} Now, when a user selects one of the divs, it's then highlighted, so I have css to highlight it. div.lefthighlighted{} div.centerhighlighted{} div.righthighlighted{} I have to now repeat all the styles from div.left{} to div.lefthighlighted{} and add the styles to highlight, and this has to be done for all three div styles I've defined. OK, I also have a tags within all three of these divs that I want styled different from all other a tags in my application, but they will be the same for the highlightd divs. This is were things get crazy. I end up with the following for left, center and right. The worst part of this is that all the a tag styling is the same for left, lefthighlighted, center, centerhighlighted, right and righthighlighted, but I can't figure out how to share all of this. div.left a:link {} div.left a:visited {} div.left a:active {} div.left a:hover {} div.lefthighlighted a:link{} div.lefthighlighted a:visited {} div.lefthighlighted a:active {} div.lefthighlighted a:hover {} Keep in mind, I'm simply putting empty braces here, but in my stylesheet, I've got a bunch of styles defined. Is there a way to say div.left a:link { inherit div.right a:link; or use div.right a:link; } I'm finding myself copying and pasting all the same styles and only changing the class name or the parent class name. A: Give the elements multiple classes. <div class="left highlighted"> And then just include the changed properties in the div.highlighted rule-set. A: You can group styles by using the , (commas) as a separator. Eg: div.left a:link, div.right a:link {} /*Newlines don't matter:*/ div.left a:link, div.right a:link {} Note that the following does not work as "expected": /*Expecting to select all links under div.left or div.right*/ div.left, div.right a:link {/*FAIL*/} Another note about inheritance. Elements inherit styles from their parents. When a new matching selector is encountered, the styles from the parent still apply, unless defined otherwise: a:link, a:visited, a:active { color: red; font-size: 16px; } a:hover{ font-size: 20px; /*font-size changed, while the color is still red.*/ }
{ "language": "en", "url": "https://stackoverflow.com/questions/7560150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating MySQL query for report I've been working a lot lately on making reports and there is a common problem I keep running into. I run into this when making reports or when creating charts. Say I have 2 tables: stages: id stage_name (Sample data: Open, Won, Lost) projects: id title, stage_id Projects and stages are related. The problem I have is when I join the table it's obviously only going to return results if there are any. So say I'm running a COUNT query and there aren't any results that are currently set to the "Open" stage. Well it won't show that stage. However I want it to show a 0 instead of just not showing anything. I have no idea how to do this and I've tried quite a bit. I'm not sure if this is something I should do with temp tables or not. I haven't done temp tables in years. This is the type of query I would run: SELECT COUNT(id), stage_name FROM projects LEFT JOIN stages ON stages.id = projects.stage_id GROUP BY stage_id Any help? A: You need to select from stages and join projects: SELECT stage_id , COUNT(projects.id) FROM stages LEFT JOIN projects ON stages.id = projects.stage_id GROUP BY stage_id
{ "language": "en", "url": "https://stackoverflow.com/questions/7560153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Time based GPS location in background (iphone) I want to create an (game based) iPhone application which sends your GPS location on a specific time (like 3-5 times a day) to a server. I found an apple page explaining some functionality to run in the background like location, music and VOIP. I need the GPS to be accurate on the meter. Can someone help me with a small example? A: It really depends on your usage of the location. If you monitor actively, kiss the battery of your user goodbye. Very detailed accuracy, even bigger hit to battery. The backgrounding of location is all or nothing as far as accuracy goes. Less hit, less accuracy is -startMonitoringForSignificantLocationChange. May not be accurate enough for you. Better depending on usage, region monitoring. Triggers event on entry or exit of defined region. You don't have the benefit of accuracy and timed location based events. You can do it, but is going to require a lot more effort on your end. A: While this is untested, I am planning an app with a similar need. My solution is that on a significant location change, the app will determine what interval exists between the update timestamp, and when I care to know the users location (5pm for instance). If that's below some threshold, it will go into startUpdatingLocation mode (full power, battery draining, which is why that threshold is important) and then, on each location update, check if that target time has passed. if SO, send the update to your server, and go back to monitoring for significant changes. The catch is that if it still requires some movement to trigger the significant change update...so it isn't a perfectly reliable solution, but it may work depending on how you're using the data A: You can't "schedule background work". iOS doesn't allow it. The solution is to set yourself up for notification on significant change (which is some hit to the battery, but it's not horrible), and then only DO anything with that at occasional intervals.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: guard gem run all triggers on start Hi this is driving me crazy. I couldn't find a solution after a long time. How do I trigger a "run_all" for all guards in the Guardfile. When i run "guard" in the shell, I want it to sort off pretend like all files have changed and trigger all guards. What's a clean way to do this from the Guardfile. A: Create a guardfile on the root of the app and set the guard config to something like rspec example: guard 'rspec', :version => 2, :all_on_start => false do A: This happens for me with no additional configuration. I've noticed that some guards have options to override this behavior. For instance, guard-rspec has the all_on_start option, which you can set to false if you don't want to run your specs when you fire up guard. As specified in the guard readme, if you are using guard >= 0.7.0, you can press enter to call each guards #run_all method in the order they are listed in the Guardfile. Try that?
{ "language": "en", "url": "https://stackoverflow.com/questions/7560165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: EREG expression for one or more first names separated by comma I somehow can't get this to work. I want at least one name but also the possibility to add more names separated by a comma and space. This is what i got: var exp_name2 = /^[A-Z]{1}[a-z-]*[,\s][A-Z]{1}[a-z-]$/; Any ideas how I can do this? A: Alright, so you're wanting it to be like this: Name, nAme lastname,NAME [a-zA-Z\s]*(?:,?[\s]?)? Selects either lowercase or uppercase letters until it hits a , or a space, then repeats. Otherwise: Name, Name, Name [A-Z][a-z\s]*(?:,\s)? A: This is something that should work. Check it out http://jsfiddle.net/bZy5Q/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/7560169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: logical operations on large files binary data in C/C++ I have two binary files (order of tens of MB) and I want to or every bit of these files. And of course, I want it to be as efficient as possible. So I have two ways in mind to do that, but I still think (I kinda feel) that should be a more efficient way that I do not know of. Given file a and b .. what I want to do is a = a|b * *Loading two files, parse them in to two huge std::bitsets and or them together *loading two files byte by byte and or them if a huge for loop... Is there any other way to do that? A: Don't go byte-by-byte. That'd be seriously slow. Instead, read the files in chunks. Find what the block size is for your system (4k? 8K? 64k?) and read the file using chunks of that size. Then you can loop through the byte streams in memory and do the OR operations there. In logical terms, even though you might only be reading a byte at a time, the OS will still read an entire block worth of data, then throw away all but the byte you wanted. Next time around that block'll be cached, but it's still going through the full read motions for every byte you want. So... just suck the entire block into memory and save yourself that wasted overhead. A: I would recommend loading the two files a chunk at a time, where a chunk is some appropiate portion of the data. The best size would depend on your operating system and filesystem, but its usually something like the cluster size, or 2 * the cluster size, or so on... You would have to run some test to determine the best buffer size. A: I don't think you would have any performance advantage either way (if in your "second option" you are going to load the file in big chunks), after all you'd be using a big stack-allocated buffer in both cases (which is what std::bitset boils down to), so go with the one you like best. The only advantage I see in the std::bitset::operator|=, besides clarity, is that it may be able to exploit some platform-specific trick to or big sequences of bytes, but I think that the compiler would be able to optimize your big "or loop" anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I use an object (an instance of a class) as a dictionary key in Python? I want to use a class instance as a dictionary key, like: classinstance = class() dictionary[classinstance] = 'hello world' Python seems to be not able to handle classes as dictionary key, or am I wrong? In addition, I could use a Tuple-list like [(classinstance, helloworld),...] instead of a dictionary, but that looks very unprofessional. Do you have any clue for fixing that issue? A: The following code works well because by default, your class object are hashable : Class Foo(object): def __init__(self): pass myinstance = Foo() mydict = {myinstance : 'Hello world'} print mydict[myinstance] Output : Hello world In addition and for more advanced usage, you should read this post : Object of custom type as dictionary key A: Try implementing the hash and eq methods in your class. For instance, here is a simple hashable dictionary class I made: class hashable_dict: def __init__(self, d): self.my_dict = d self.my_frozenset = frozenset(d.items()) def __getitem__(self, item): return self.my_dict[item] def __hash__(self): return hash(self.my_frozenset) def __eq__(self, rhs): return isinstance(rhs, hashable_dict) and self.my_frozenset == rhs.my_frozenset def __ne__(self, rhs): return not self == rhs def __str__(self): return 'hashable_dict(' + str(self.my_dict) + ')' def __repr__(self): return self.__str__() A: There is nothing wrong with using an instance as a dictionary key so long as it follows the rules: A dictionary key must be immutable. A: Your instances need to be hashable. The python glossary tells us: An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value. Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally. All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id(). A: You can create a folder like 'Strategy' then you can use pickle to save and load the objects of your class. import pickle import os # Load object as dictionary --------------------------------------------------- def load_object(): file_path = 'Strategy\\All_Pickles.hd5' if not os.path.isfile(file_path): return {} with open(file_path, 'rb') as file: unpickler = pickle.Unpickler(file) return dict(unpickler.load()) # Save object as dictionary --------------------------------------------------- def save_object(name, value): file_path = 'Strategy\\All_Pickles.hd5' object_dict = load_object() with open(file_path, 'wb') as file: object_dict[name] = value pickle.dump(object_dict, file) return True class MyClass: def __init__(self, name): self.name = name def show(self): print(self.name) save_object('1', MyClass('Test1')) save_object('2', MyClass('Test2')) objects = load_object() obj1 = objects['1'] obj2 = objects['2'] obj1.show() obj2.show() I created two objects of one class and called a method of the class. I hope, it can help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How do you make an add-in for Excel 2011 (Mac) I would like to add a button to the Ribbon and have it perform some basic tasks when clicked. Is this possible? If so, how? Thanks in advance. A: No, it is not possible. It looks like it is possible, but it is not. The only proper add in for Excel 2011 Mac is provided with Excel, and the ability to show it in Excel Mac's ribbon is apparently hard-coded into the Excel Mac application. None of the XML-based techniques for extending the Excel Mac ribbon work because the ribbon is hard-coded. It looks like the Windows version, but it is nothing like it. Obviously, it is hard to provide sources for a negative answer. I have researched this topic carefully including contacting Microsoft support, and found that there is no compiler or IDE from Microsoft for this purpose. You can certainly develop in VBA in Excel Mac, and you can make an XLA add-in, but you cannot access the ribbon. You can create little square Mac toolbar icons, just as in Excel 98. A: Here are some useful links that will answer your question: * *how to customize the ribbon *how to customize the ribbon with vba *how to create an add in (on MSDN) *a clearer tuto on how to create an addin Please ask a more precise question if you want more precise help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Highlighting and replacing non-printable unicode characters in Emacs I have an UTF-8 file containing some Unicode characters like LEFT-TO-RIGHT OVERRIDE (U+202D) which I want to remove from the file. In Emacs, they are hidden (which should be the correct behavior?) by default. How do I make such "exotic" unicode characters visible (while not changing display of "regular" unicode characters like german umlauts)? And how do I replace them afterwards (with replace-string for example. C-X 8 Ret does not work for isearch/replace-string). In Vim, its quite easy: These characters are displayed with their hex representation per default (is this a bug or missing feature?) and you can easily remove them with :%s/\%u202d//g for example. This should be possible with Emacs? A: How about this: Put the U+202d character you want to match at the top of the kill ring by typing M-:(kill-new "\u202d"). Then you can yank that string into the various searching commands, with either C-y (eg. query-replace) or M-y (eg. isearch-forward). (Edited to add:) You could also just call commands non-interactively, which doesn't present the same keyboard-input difficulties as the interactive calls. For example, type M-: and then: (replace-string "\u202d" "") This is somewhat similar to your Vim version. One difference is that it only performs replacements from the cursor position to the bottom of the file (or narrowed region), so you'd need to go to the top of the file (or narrowed region) prior to running the command to replace all matches. A: You can do M-x find-file-literally then you will see these characters. Then you can remove them using usual string-replace A: I also have this issue, and this is particularly annoying for commits as it may be too late to fix the log message when one notices the mistake. So I've modified the function I use when I type C-x C-c to check whether there is a non-printable character, i.e. matching "[^\n[:print:]]", and if there is one, put the cursor over it, output a message, and do not kill the buffer. Then it is possible to manually remove the character, replace it by a printable one, or whatever, depending on the context. The code to use for the detection (and positioning the cursor after the non-printable character) is: (progn (goto-char (point-min)) (re-search-forward "[^\n[:print:]]" nil t)) Notes: * *There is no need to save the current cursor position since here, either the buffer will be killed or the cursor will be put over the non-printable character on purpose. *You may want to slightly modify the regexp. For instance, the tab character is a non-printable character and I regard it as such, but you may also want to accept it. *About the [:print:] character class in the regexp, you are dependent on the C library. Some printable characters may be regarded as non-printable, like some recent emojis (but not everyone cares). *The re-search-forward return value will be regarded as true if and only if there is a non-printable character. This is exactly what we want. Here's a snippet of what I use for Subversion commits (this is between more complex code in my .emacs). (defvar my-svn-commit-frx "/svn-commit\\.\\([0-9]+\\.\\)?tmp\\'") and ((and (buffer-file-name) (string-match my-svn-commit-frx (buffer-file-name)) (progn (goto-char (point-min)) (re-search-forward "[^\n[:print:]]" nil t))) (backward-char) (message "The buffer contains a non-printable character.")) in a cond, i.e. I apply this rule only on filenames used for Subversion commits. The (backward-char) can be used or not, depending on whether you want the cursor to be over or just after the non-printable character.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Caching ASHX Image Response I have created an ashx file to generate image thumbnails on the fly. I would like to cache these images client side after they are called the first time. URL: ~/image.ashx?dir=user&w=25&h=25&force=yes&img=matt.jpg Code Behind: public void ProcessRequest (HttpContext context) { TimeSpan refresh = new TimeSpan(0, 15, 0); context.Response.Cache.SetExpires(DateTime.Now.Add(refresh)); context.Response.Cache.SetMaxAge(refresh); context.Response.Cache.SetCacheability(HttpCacheability.Server); context.Response.CacheControl = HttpCacheability.Public.ToString(); context.Response.Cache.SetValidUntilExpires(true); string dir = context.Request.QueryString["dir"]; string img = context.Request.QueryString["img"]; bool force = context.Request.QueryString["force"] == "yes"; double w = 0; double h = 0; ... context.Response.ContentType = "image/jpeg"; thumb.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); } Using the Dev Tools in Chrome I can see the following Response Header: HTTP/1.1 200 OK Server: ASP.NET Development Server/10.0.0.0 Date: Mon, 26 Sep 2011 19:17:31 GMT X-AspNet-Version: 4.0.30319 Set-Cookie: .ASPXAUTH=...; path=/; HttpOnly Cache-Control: no-cache Pragma: no-cache Expires: -1 Content-Type: image/jpeg Content-Length: 902 Connection: Close Can someone enlighten me as to why this isn't caching on multiple calls with the same exact URL? Any tips would be greatly appreciated. A: Surely this line: HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Server); Should be: HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public);
{ "language": "en", "url": "https://stackoverflow.com/questions/7560180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Creating WebApplication with Database Access in Java I have to create a simple WebApplication with Java which shows a Login Dialog and after it shows some textfields, gets some Data out of a Database (Sybase) do something with it and insert a new record to the database. Now I am looking for a good tutorial, which explains me, how to setup the needed environment and shows me the start for creating a WebApplication with Java. Can anyone give me some good links to such tutorials? - Many Thanks. A: If you want to look at using Spring (which seems very popular these days) maybe you should check out this question: Getting started with Spring 3 Web MVC - Setting everything up A: 1- BalusC blog - more JSF focused but has every thing . Does not use Spring. 2- Appfuse great starter application plus tutorials uses spring. 3- LULU - Interestingly does not have community presence or atleast not with same name.Uses Spring 4- Java Passion - But not free but very well worth it. I have been member since it was free and now pay annual subscription every year.Not based on spring but does have spring for those who are interested. 5- Spring Roo this is youtube link but you can google as well popular but not my personal choice. 6- Jboss - This is tips link which has further links.Does not use spring and wish they will all die (pun intended and hope not) 7- Netbeans No spring and probably best for any starter I can go on and on but this should be enough . Also I have a feeling that this question might be closed as soon as people in North-Western Hemisphere wake up :) A: Play framework is what you need. It provides the simplest way to create a web application. Starting with hello world application you'll find another manuals and samples that will help you to achieve your goals.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SSH problem using Netbeans and Git I have looked at the other posts from the other folks regarding this issue but I still have problems getting ssh to work with netbeans & git on windows 7. I am new to git so I am sure I am missing something somewhere. I have done init git on my Ubuntu server. I have also set a %HOME% under the "user variables for username" in system properties->advanced->environment variables and created a .ssh folder in the path that I defined for %HOME%. Now where so I get the key files? I copied them from the Ubuntu server to there but when I am trying to connect by netbean using ssh it still says ssh://user@200.200.200.111/git: reject HostKey: 200.200.200.111 What do I do wrong here? A: This is a known bug with NetBeans 7.0.1. Bug 199263 - Cannot connect to remote repositories with just ssh public/private keys Here is the link to their bug database: http://netbeans.org/bugzilla/show_bug.cgi?id=199263 Looks like it has been fixed for the next release (7.1). I tried it and it worked for me. Here is where I got the latest dev build: http://bits.netbeans.org/download/trunk/nightly/latest/ Remember, dev builds may have some stability problems. A: I've no Windows nor Netbeans at hand here, but that message looks like the 200.200.200.111 host is not in the known_hosts file. Try doing ssh 200.200.200.111 from the console, it should ask if you trust the hosts' fingerprint, answer yes and it will be stored in known_hosts file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Eclipse Servers view not showing added Tomcat runtime environment I am running Eclipse Helios SR2 (the EE version) on Ubuntu 11.04. I installed tomcat6.0.29 manually and can start/ stop it ok. I can add the Tomcat 6 Server Runtime environment successfully to eclipse - I've never had the "Cannot create the server" problem however the environment never show up in my Servers view. I've tried many avenues but no success (same issue with installing the aptitude tomcat6 and creating links etc) Any suggestions on how to progress this ? Other info:I have exactly the same issue with a brand new install of Eclipse Indigo (the EE version) I have java-6-sun installed: update-java-alternatives -l java-1.5.0-sun 53 /usr/lib/jvm/java-1.5.0-sun java-6-sun 63 /usr/lib/jvm/java-6-sun A: I had this problem a week ago (on Ubuntu 11.04). I failed to find why it doesn't show the servers in the view - they appear in the Servers project. But I fixed it by switching to a fresh workspace. (Of course, assuming you have right-clicked in the server view and chose "New -> server") A: Well I was inspecting what might be the issue. I was able to add a runtime but cannot add a new server. Changing permissions of Tomcat configuration files solved the issue for me (without creating a new workspace) chmod 664 /usr/share/tomcat6/conf/* It seems that if you add runtime that cannot read configuration, you are not able add such server under "Servers" window...
{ "language": "en", "url": "https://stackoverflow.com/questions/7560195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What happens to cron jobs when system in shutdown? From man page of crontab. string meaning ------ ------- @daily Run once a day, "0 0 * * *". @midnight (same as @daily) So a job @daily will never be executed if the system is always shutdown at midnight? What is the proper way to specify that I want to run this job once daily but I don't care when exactly it is executed in a day? A: The job may run, but probably won't complete. cron is implemented via a daemon, so it's always running. Depending on your system's shutdown order, cron may actually be sent the shutdown signal fairly late in the shutdown process, so jobs scheduled for the moment the shutdown started may still run. e.g. If the shutdown starts at 00:00:00 exactly, but doesn't get to sending cron a kill signal until 00:00:05 (5 seconds after midnight(, then a short running 2-second job may still have time to complete. However, if any services that job depends on have already been shutdown or are in the process of shutting down, then it's unlikely to be able to finish. e.g.... the script pings a mysql server for one little piece of data... but mysql shut down at 00:00:01 and your script didn't get to the mysql portion until 00:00:02. tl;dr: it's a race condition and your job MAY execute, but probably won't.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Syntax error in compiling .CSS file w/SASS 3.1.7 and previous versions sass .CSS compilation fails on one machine, but works on the other. Using Sass gem version 3.1.7 on both w/Bundler. If I do bundle show sass on both machines, they have identical output. Can't seem to track down what is at the root of this. I tried dumping my Gemfile.lock, and running bundle install from scratch - no go - same error message. Tried locking to some previous versions of the gem (3.1.6 and 3.1.5 specifically) - no change in symptoms. Not 100% sure what version of the gem I was using previously, but I've only been using Sass since mid-August, and it was never locked down to a version before, so I figured I'd try locking to the two previous versions, both of which were released before I began using Sass. $ bundle show sass /Users/[username]/.rvm/gems/ree-1.8.7-2011.03/gems/sass-3.1.7 And the error in the compiled .CSS file is: Syntax error: Invalid property: ":background-image= image_url("public-fade-bg.png")". on line 5 of [/path/to/application]/app/stylesheets/public_admin.sass 1: // Styles for public views - authentication controller 2: @import application.sass 3: 4: body 5: :background-image= image_url("public-fade-bg.png") 6: #environment 7: :position absolute 8: :background-color= !development_color 9: :font-size 18px 10: :padding 0 5px A: Solved this problem after discussing it with a fellow developer. The long and short of it is that the syntax this particular app is using was supported in a previous version of Sass, but is no longer. One of the gems I was using, somewhere along the lines, got its version changed. After fighting with it for a couple of days, I basically just rolled back my gems by checking out a known, working copy of the Gemfile and Gemfile.lock files from the application repository, and then did a bundle install --deployment After that, everything came back online, and worked as it did before this process started.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make this SQL query faster? I have the following query: SELECT DISTINCT `movies_manager_movie`.`id`, `movies_manager_movie`.`title`, `movies_manager_movie`.`original_title`, `movies_manager_movie`.`synopsis`, `movies_manager_movie`.`keywords`, `movies_manager_movie`.`release_date`, `movies_manager_movie`.`rating`, `movies_manager_movie`.`poster_web_url`, `movies_manager_movie`.`has_poster`, `movies_manager_movie`.`number`, `movies_manager_movie`.`has_sources`, `movies_manager_movie`.`season_id`, `movies_manager_movie`.`created`, `movies_manager_movie`.`updated`, `movies_manager_moviecache`.`activity_name` FROM `movies_manager_movie` LEFT OUTER JOIN `movies_manager_moviecache` ON (`movies_manager_movie`.`id` = `movies_manager_moviecache`.`movie_id`) WHERE (`movies_manager_movie`.`has_sources` = 1 AND (`movies_manager_moviecache`.`team_member_id` IN ( SELECT U0.`id` FROM `movies_manager_movieteammember` U0 INNER JOIN `movies_manager_movieteammemberactivity` U1 ON (U0.`id` = U1.`team_member_id`) WHERE U1.`movie_id` = 3588 ) AND `movies_manager_movie`.`number` IS NULL ) AND NOT (`movies_manager_movie`.`id` = 3588 )) ORDER BY `movies_manager_moviecache`.`activity_name` DESC LIMIT 3; This query can take up to 3 seconds and I'm very surprise since I got indexes everywhere and no more than 35 rows in each of my MyIsam tables, using the latest MySQL version. I cached everything I could but I have at least to run this one 20000 times every day, which is approximately 16 h of waiting for loading. And I'm pretty sure none of my user (nor Google Bot) appreciate a 4 secondes waiting time for each page loading. What could I do to make it faster ? I thought about duplicating field from movie to moviecache since the all purpose of movie cache is to denormalize to complex join already. I tried inlining the subquery to a list of ID but it surprisingly doubled the time of the query. Tables: +----------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | title | varchar(120) | NO | UNI | NULL | | | original_title | varchar(120) | YES | | NULL | | | synopsis | longtext | YES | | NULL | | | keywords | varchar(120) | YES | | NULL | | | release_date | date | YES | | NULL | | | rating | int(11) | NO | | NULL | | | poster_web_url | varchar(255) | YES | | NULL | | | has_poster | tinyint(1) | NO | | NULL | | | number | int(11) | YES | | NULL | | | season_id | int(11) | YES | MUL | NULL | | | created | datetime | NO | | NULL | | | updated | datetime | NO | | NULL | | | has_sources | tinyint(1) | NO | | NULL | | +----------------+--------------+------+-----+---------+----------------+ +---------------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(120) | NO | UNI | NULL | | | biography | longtext | YES | | NULL | | | birth_date | date | YES | | NULL | | | picture_web_url | varchar(255) | YES | | NULL | | | allocine_link | varchar(255) | YES | | NULL | | | created | datetime | NO | | NULL | | | updated | datetime | NO | | NULL | | | has_picture | tinyint(1) | NO | | NULL | | | biography_linkyfied | longtext | YES | | NULL | | +---------------------+--------------+------+-----+---------+----------------+ +----------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | movie_id | int(11) | NO | MUL | NULL | | | tag_slug | varchar(100) | YES | MUL | NULL | | | team_member_id | int(11) | YES | MUL | NULL | | | cast_rank | int(11) | YES | | NULL | | | activity_name | varchar(30) | YES | MUL | NULL | | +----------------+--------------+------+-----+---------+----------------+ Mysql tells me it's a slow query: # Query_time: 3 Lock_time: 0 Rows_sent: 9 Rows_examined: 454128 A: Move movies_manager_movieteammemberactivity and movies_manager_movieteammember to your main join statement (so that you're doing a left outer between movies_manager_movie and the inner join product of the other 3 tables). This should speed up your query considerably. A: Try this: SELECT `movies_manager_movie`.`id`, `movies_manager_movie`.`title`, `movies_manager_movie`.`original_title`, `movies_manager_movie`.`synopsis`, `movies_manager_movie`.`keywords`, `movies_manager_movie`.`release_date`, `movies_manager_movie`.`rating`, `movies_manager_movie`.`poster_web_url`, `movies_manager_movie`.`has_poster`, `movies_manager_movie`.`number`, `movies_manager_movie`.`has_sources`, `movies_manager_movie`.`season_id`, `movies_manager_movie`.`created`, `movies_manager_movie`.`updated`, ( SELECT `movies_manager_moviecache`.`activity_name` FROM `movies_manager_moviecache` WHERE (`movies_manager_movie`.`id` = `movies_manager_moviecache`.`movie_id` AND (`movies_manager_moviecache`.`team_member_id` IN ( SELECT U0.`id` FROM `movies_manager_movieteammember` U0 INNER JOIN `movies_manager_movieteammemberactivity` U1 ON (U0.`id` = U1.`team_member_id`) WHERE U1.`movie_id` = 3588 ) AND `movies_manager_movie`.`number` IS NULL ) ) LIMIT 1) AS `activity_name` FROM `movies_manager_movie` WHERE (`movies_manager_movie`.`has_sources` = 1 AND NOT (`movies_manager_movie`.`id` = 3588 )) ORDER BY `activity_name` DESC LIMIT 3; Let me know how that performs
{ "language": "en", "url": "https://stackoverflow.com/questions/7560207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Exclude anchor by title attribute. - Ajax I'm loading wordpress pages dynamically using ajax. It fires properly but I need to exclude a specific anchor. <a href="http://store.myurl.com" target="_blank" title="Store">Store</a> I thought using .not() would work like so $('a').not('a[title=Store]').live('click',function() { But that breaks the whole thing. If I use $('a').live('click',function() { it fires properly. p.s. I can't change the anchor output like ad an ID or a Class. A: you are missing the mandatory quotes on the attribute selector. try $('a:not(a[title="Store"])').live('click',function() edit: the live is not going to bind against elements returned by a filter (as .not()), you need a selector to match against when .live() resolves in body (where it is binded). so you need to use the :not selector, plus using the quotes for the attribute selector A: Does the attribute selector work without quotes? I would use $('a').not('a[title="Store"]').live('click',function() { A: You can try using the :not selector instead: $('a:not([title="Store"])').live('click', function(){ A: Try: $('a').not('[title=Store]').live('click',function() { (I removed the letter "a" before "[title=Store]")
{ "language": "en", "url": "https://stackoverflow.com/questions/7560211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why does macports list multiple installed ports of the same version, and how do I fix it? Specifically, the command: sudo port list installed Shows doubles of packages, like this: apache2 @2.2.21 www/apache2 apache2 @2.2.21 www/apache2 ... ncurses @5.9 devel/ncurses ncurses @5.9 devel/ncurses php5-iconv @5.3.8 php/php5-iconv php5-iconv @5.3.8 php/php5-iconv php5-intl @5.3.8 php/php5-intl php5-intl @5.3.8 php/php5-intl ... Why is this? How did it happen and how do I fix it? A: From macports bug list "port list installed" does not do what you think it does. "port list installed" gets the list of names of all the installed ports, and for each one, shows you the current version, regardless of what version is installed. To see the versions that are installed, you want to use "port installed". The inactive versions are older ports that have been replaced by newer ones that are active. port list inactive shows the ports that are not used any more and in your case should show one of each duplicate (or 2 or triplets etc) port uninstall inactive will remove the inactive ports and leave you with just one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: Current binding value I'm writing markup extension. I have XAML like this <TextBlock Text="{ui:Test SomeInfo}" /> and TestExtension with constructor taking one string argument. I'm getting "SomeInfo" string so everything is find. Now I want to nest extensions and write something like <TextBlock Text="{ui:Test {Binding PropName}}" /> and it does not work as is. I had to add constructor which takes one argument of System.Windows.Data.Binding type. Now I need to know * *How should I retrieve a current value from the Binding object? *When should I do this? Should I subscribe to changes some way or ask for that value every time in ProvideValue method? Update1 PropName should be resolved against DataContext of TextBlock. Update2 Just found related question: How do I resolve the value of a databinding? A: Bindings like this will not work because your MarkupExtension has no DataContext and it does not appear in the visual tree and i do not think you are supposed to interact with binding objects directly. Do you really need this extension? Maybe you could make do with the binding alone and a converter? If not you could create a dedicated class which has bindable properties (by inheriting from DependencyObject), this however would still not give you a DataContext or namescope needed for ElementName or a visual tree needed for RelativeSource, so the only way to make a binding work in that situation is by using a Source (e.g. set it to a StaticResource). This is hardly ideal. Also note that if you do not directly set a binding the ProvideValue method will only be called once, this means that even if you have a binding in your extension it may not prove very useful (with some exceptions, e.g. when returning complex content, like e.g. an ItemsControl which uses the binding, but you set the extension on TextBlock.Text which is just a string), so i really doubt that you want to use a MarkupExtension like this if the value should change dynamically based on the binding. As noted earlier: Consider converters or MultiBindings for various values instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Mock giving compile error when attempting to specify a return value I'm using Google Test and Google Mock for my C++/Qt application. I've been having great success with this setup until just now when I tried this: QList<AbstractSurface::VertexRow> rowList; for (unsigned i = 0; i < rows; ++i) { AbstractSurface::VertexRow curRow(new AbstractSurface::Vertex[cols]); for (unsigned j = 0; j < cols; ++j) { curRow[j] = AbstractSurface::Vertex(); } rowList.append(curRow); } ON_CALL(surface, numRows_impl()).WillByDefault(Return(rows)); ON_CALL(surface, numColumns_impl()).WillByDefault(Return(cols)); ON_CALL(surface, popAllRows_impl()).WillOnce(Return(rowList)); /* ... */ Attempting to compile this results in the following error message from gcc: ../../3DWaveSurface/test/TestWaterfallPresenter.cc: In member function ‘virtual void<unnamed>::WaterfallPresenterTest_CallingPaintGLCallsPaintRowForEachRowInSurface_Test::TestBody()’: ../../3DWaveSurface/test/TestWaterfallPresenter.cc:140:41: error: ‘class testing::internal::OnCallSpec<QList<boost::shared_array<AbstractSurface::Vertex> >()>’ has no member named ‘WillOnce’ If it helps, VertexRow is a typedef for a boost::shared_array<Vertex> and Vertex is a struct with a valid empty constructor. Is this an error in what I wrote for the test or some incompatibility with using QList or shared_array? SOLUTION After following VJo's recommendation, my tests compiled and ran but then crashed: Stack trace: : Failure Uninteresting mock function call - returning default value. Function call: popAllRows_impl() The mock function has no default action set, and its return type has no default value set. The process "/home/corey/development/3DWaveSurface-build-desktop-debug/test/test" crashed. Because there was no default return for popAllRows_impl(). I added a default: ON_CALL(surface, popAllRows_impl()).WillByDefault(Return(QList<AbstractSurface::VertexRow>())); To my SetUp() and all is well. As VJo pointed out, there is no WillOnce() for ON_CALL but there is for EXPECT_CALL and I missed this in the cook book.. A: The simplest solution is : EXPECT_CALL(surface, popAllRows_impl()).WillOnce(Return(rowList)); EDIT : ON_CALL has WillByDefault, but no WillOnce method. Check the gmock cookbook
{ "language": "en", "url": "https://stackoverflow.com/questions/7560215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: preload images with a specific class with jquery Is it possible to preload images that have a specific class applied to them? for example - preload only images with class '.grid' I've seen lots of examples of preload based on array, but my image names are dynamically generated (I'm using Drupal 6), and I don't want to preload the images globally unless I have to. Any ideas? Thanks Stephanie A: var imgs = new Array(); $('img.grid').each(function(idx){ var i = new Image(); i.src = $(this).attr('src'); imgs.push(i); }); A: If the problem you are trying to solve is to load images in your page that have the grid class faster, then there is no way to do that. To find the images in your page that have the grid class, you'd have to wait for the DOM to load and then search the DOM to find those images. At the point you are doing that, the browser is already working to load them. Nothing you can do in Javascript at that point can make the image load go any faster. The browser is already loading them. The only thing I know that you could do is to make an array of the URLs that you want to load and you can preload those in the very first part of your javascript (script in the head tag) and this "might" get the images loading a little faster. But, in order to do this, you'd have to manually list out the images you want to apply this to. You can't wait for the page to load and look for them in the page because, by then, they're already being loaded as fast as they can be. If you control the server-side code, you could generate this list of images server-side and put that array into the JS. If you did that, it would look something like this: <head> <script type="text/javascript"> var preloadURLs = [ "http://photos.smugmug.com/photos/344291068_HdnTo-Ti.jpg", "http://photos.smugmug.com/photos/344290837_ypsKL-Ti.jpg" ]; var preloadImgs = [], img; for (var i = 0; i < preloadURLs.length; i++) { img = new Image(); img.src = preloadURLs[i]; preloadImgs.push(img); } </script> </head> In most browsers, this should serve to somewhat give priority to the loading of these images since their requests would be launched first before the page starts to load.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Finding the line numbers of all occurences of a string in a text file I'm trying to write a function that does the following: Given a text file, I want to find all occurences of a certain string in this file; then, for each occurence, the line on which it was found should be added to a list. We assume that each line only contains at most one occurence. The text file can get very large, which means a simple for-loop to iterate over each line the file will be too slow. For example, say we have a file with the content: * *A B C D E F G *H J K L M N O *G F E D C B A *P Q R S T U V If I were to search for "A", the function would find it on lines 1 and 3 and thus add 1 and 3 to a list (and then return the list). I was considering binary search, but it seems to require that a list to be sorted and the elements to be distinct - I'm looking for identical values. So, is any other search algorithm i can base my function on, with roughly the same performance as binary search? Thanks! A: You can index your lines, if they change infrequently and you will be performing many searches on them. One way to index them would be to create a histogram of which characters are present in which lines (and how many times, perhaps). Then you can invert this and say that the letter A, for example, appears on lines 5, 10 and 20. If you are searching for "ABF", you can use the inverted histogram to determine which lines are candidates (i.e., contain the letters 'A', 'B' and 'F') and then only look at those lines. Whether or not this is an effective strategy will depend on the selectivity of your searches and the length of the search strings, among other things. Only testing will reveal whether or not the algorithm has merit for your particular usage patterns.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: where is the best place to save game progress? I'm developing a quiz game and I want to save the progress... Actually I use sharedsettings, is easy and fast, but the user can delete program files and lose the progress. Same happens with a database. I should use a file? I'm only interesting to save a boolean for each question: "correct answered or not?" Thank you!! A: SharedSettings. And you're already using it. It's very difficult to save a user from his/herself. If it's on the device then it can be destroyed either stupidly or maliciously. And don't forget that everything is a file and there's nothing you can put on the device that will be hack/idiot proof. The only way to get around this would be to store user settings off the device via something like a web service (and backing database.) But I would say that if you're using SharedSettings... you're OK. Leave it at that. I would only consider using an app-specific db if you expect the number of question you track to grow to a very large size and want more control over the data. A: Where in code logic? In general, it's best to save any UI preferences at onPause. Android design wants you to never have a "save" button, rather save constantly. As far as at each question, i guess you would save after answering each question?
{ "language": "en", "url": "https://stackoverflow.com/questions/7560227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: DispatcherHelper to thread I have an application which uses 1 Main Window and in turn this window has 5 UserControls which are created using a Ribbon Control. On one of the user controls I kick off a thread : if (AmtMembersWithEmail > 0) { DispatcherHelper.UIDispatcher.Invoke(new Action(() => { max = 100; Messenger.Default.Send<ShowProgressWindowMessage>( new ShowProgressWindowMessage(this)); Progress = 0; Thread.Sleep(1000); })); So this thread kicks off and reports progress back to the main window, during this time, as the thread executes the user cannot access the controls or do anything else within the application, from reading up on the dispatcher this is normal as it must use the single UIThread which allows the user to interact with controls on the UI. ( Using Galasoft MVVM light by the way! ) The window that displays reporting the progress has a command which binds to a relay command in my viewmodel: Extract from XAML progress window is below: <tk:LoadingAnimation Grid.Row="0" DataContext="{Binding}"/> <ContentControl Visibility="{Binding CanBeAborted, Converter={StaticResource VisibilityConverter}}" > <Hyperlink Command="{Binding AbortCommand}">cancel</Hyperlink> </ContentControl> Is there any way to use the dispatcher to allow the thread to run in the background? or will the user just have to wait until the operation completes? To add, the work the thread is actually doing is looping customer data, creating attachments ( invoices ) and creating an email object for each customer before finally looping that new email collection and sending each email individually to the customer... Any help would be greatly appreciated.... A: I am not completely clear whether you have your processing logic in the User Control (i.e. Code Behind), or in your ViewModel. If it's in your ViewModel, then I think you're on the right track. Instead of using the dispatcher, I suggest spinning a BackgroundWorker: public void DoWork() { BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += (sender, e) => { //Processing Logic here }; worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Work_Completed); worker.RunWorkerAsync(); } void Work_Completed(object sender, RunWorkerCompletedEventArgs e) { } This will not run on the UI thread, therefore your User Control should be responsive. Also, as Will as suggested, DO NOT TERMINATE THREADS. Your Abort logic should gracefully exit the loop inside of your processing logic, cleaning up the resources it used and performing any undo work you need done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to stop multiprocess python-program cleanly after exception? I have a Python program that has several processes (for now only 2) and threads (2 per process). I would like to catch every exception and especially shut down my program cleanly on Ctrl+c but I can't get it to work. Everytime an Exception occurs the program stops but does not shut down correctly, leaving me with an unusable commandline. What I have tried so far in pseudocode is: try: for process in processes: process.join() except: pass #Just to suppress error-messages, will be removed later finally: for process in processes: process.terminate() But as I already said with no luck. Also note, that I get the Exception error message for both Processes, so they are both halted I believe? Maybe I should also mention that most of the threads are blocked in listening on a pipe. EDIT So I nearly got it working. I needed to try: every thread and make sure the threads are joined correctly. There is just one flaw: Exception KeyboardInterrupt in <module 'threading' from '/usr/lib64/python2.7/threading.pyc'> ignored when shutting down. This is raised in the main-thread of the main-process. This thread is already finished, meaning it has passed the last line of code. A: The problem (I expect) is that the exceptions are raised inside the processes not in the join calls. I suggest you try wrapping each process's main method in try-except loop. Then have a flag (e.g. an instance of multiprocessing.Value) that the except statement sets to False. Each process could check the value of the flag and stop (cleaning up after itself) if it's set to False. Note, if you just terminate a process it won't clean up after itself, as this is the same as sending a SIG_TERM to it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: MVC3 and JQuery - Can JQuery ajax method display an image generated in the controller? Is it possible to use the JQuery ajax method to pass parameters into a controller, have the action in the controller return an image and display that image back to the user? $.ajax({ type: 'POST', url: '/Controller/Action', data: { 'parameter1': '\'' + parameter1Value + '\'', 'parameter2': '\'' + parameter1Value + '\'', 'parameter3': '\'' + parameter1Value }, dataType: 'image' /* Can ajax return an image? */, success: function (imageResults) { // Do something }, error: function (xhr, status, error) { // Do something else } } My goal is to generate a dynamic image based on parameters in the form and display that image back to the user. In addtion, ad added bonus would be to fire the ajaxstart and ajaxstop handling used by other ajax calls on the page. A: Don't AJAX controller actions that return images or files or something. A much easier solution is the following: $('body').append( $('<img/>', { src: '@Url.Action("Action", "Controller")?parameter1=' + encodeURIComponent(parameter1Value) + '&parameter2=' + encodeURIComponent(parameter2Value), alt: 'some image' }) ); This simply dynamically injects the following <img> tag to the end of the <body> (you could of course adapt the location if you don't like the body): <img src="/Controller/Action/?parameter1=foo&parameter2=bar" alt="some image" /> The browser will do the rest. Just ensure that the controller action returns a File result. Also if those images are dynamically generated each time, IE could cause certain PITAs as it might cache them. To bust the cache append a random timestamp to the url: $('body').append( $('<img/>', { src: '@Url.Action("Action", "Controller")?parameter1=' + encodeURIComponent(parameter1Value) + '&parameter2=' + encodeURIComponent(parameter2Value) + '&cacheBuster=' + encodeURIComponent((new Date()).getTime()), alt: 'some image' }) );
{ "language": "en", "url": "https://stackoverflow.com/questions/7560233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: php form submission-checking not being recognized I basically took in 3 pieces of data from a form, and before processing them, I just wanted to make sure that all fields were filled in. So the focus of this is the second to last IF statement, checking if the different variables are empty. It seems to only be working for the first variable and I can't figure out how to make it apply to all of them. <?php include ("account.php") ; include ("connect.php") ; $isdone = FALSE; $un = $_REQUEST [ "un"] ; $pw = $_REQUEST [ "pw"] ; $data = mysql_query("SELECT * FROM `auth` WHERE username = '$un'") or die(mysql_error()); $info = mysql_fetch_array($data); $info['username']; $password = $info['pw']; session_start(); if(trim($un) != '' && trim($pw) != '' && $password == $pw) { $_SESSION['uze']=$un; include "problem.html"; } elseif( !isset($_POST['submit1']) && $isdone == FALSE) { echo "wrong password"; } $selected = $_REQUEST [ "type"] ; if($selected == 'afs') { $typeinc = 'afs'; } else if($selected == 'db') { $typeinc = 'database'; } else if($selected == 'cs') { $typeinc = 'computer systems'; } else if($selected == 'pw') { $typeinc = 'password'; } else if($selected == 'hw') { $typeinc = 'hardware'; } else if($selected == 'other') { $typeinc = 'other'; } $text = $_REQUEST ["inc"]; $selected2 = $_REQUEST ["yesno"]; if($selected2 == 'yes') { $email = 'yes'; } else { $email = 'no'; } if(isset($_POST['submit1'])) { if(empty($typeinc) || empty($text) || empty($email)) { print( '<a href="http://web.njit.edu/~swp5/assignment/auth.html">You have not filled in all fields, click to sign in and re-enter</a>' ); } } else{ mysql_query("INSERT INTO `swp5_proj`. `inci` (`type`, `date`, `time`, `reporter`, `desc`) VALUES ('$typeinc', CURDATE(), CURTIME(), '".$_SESSION['uze']."', '$text');") or die(mysql_error()); mysql_query("DELETE FROM inci WHERE type = ' '"); $isdone = TRUE; } if(isset($_POST['submit1']) && $isdone == TRUE) { echo "session over"; } ?> A: if((trim($un) !== '') && (trim($pw) !== '') && ($password == $pw)) A: Make sure you clean your REQUEST variables before you put them in a MySQL query. A: You're setting $email to yes or no in the line just above. A: In your if statement you are using the shortcut OR operator.... As soon as a single statement evaluates to true, the entire statement evaluates to true and there is no need to continue processing further.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java: combine 2000-5000 PDFs into 1 using iText yield OutOfMemorryError I have eyeballing this code for a long time, trying to reducing the amount of memory the code use and still it generated java.lang.OutOfMemoryError: Java heap space. As my last resort, I want to ask the community on how can I improve this code to avoid OutOfMemoryError I have a driver/manifest file (.txt file) that contain information about the PDFs. I have about 2000-5000 pdf inside a zip file that I need to combine together. Before the combining, for each pdf, I need to add 2-3 more pdf pages to it. Manifest object holds information about a pdf. try{ blankPdf = new PdfReader(new FileInputStream(config.getBlankPdf())); mdxBacker = new PdfReader(new FileInputStream(config.getMdxBacker())); theaBacker = new PdfReader(new FileInputStream(config.getTheaBacker())); mdxAffidavit = new PdfReader(new FileInputStream(config.getMdxAffidavit())); theaAffidavit = new PdfReader(new FileInputStream(config.getTheaAffidavit())); ImmutableList<Manifest> manifestList = //Read manifest file and obtain List<Manifest> File zipFile = new File(config.getInputDir() + File.separator + zipName); //Extracting PDF into `process` folder ZipUtil.extractAll(config.getExtractPdfDir(), zipFile); outputPdfName = zipName.replace(".zip", ".pdf"); outputZipStream = new FileOutputStream(config.getOutputDir() + File.separator + outputPdfName); document = new Document(PageSize.LETTER, 0, 0, 0, 0); writer = new PdfCopy(document , outputZipStream); document.open(); //Open the document //Start combining PDF files together for(Manifest m : manifestList){ //Obtain full path to the current pdf String pdfFilePath = config.getExtractPdfDir() + File.separator + m.getPdfName(); //Before combining PDF, add backer and affidavit to individual PDF PdfReader pdfReader = PdfUtil.addBackerAndAffidavit(config, pdfType, m, pdfFilePath, blankPdf, mdxBacker, theaBacker, mdxAffidavit, theaAffidavit); for(int pageNumber=1; pageNumber<=pdfReader.getNumberOfPages(); pageNumber++){ document.newPage(); PdfImportedPage page = writer.getImportedPage(pdfReader, pageNumber); writer.addPage(page); } } } catch (DocumentException e) { } catch (IOException e) { } finally{ if(document != null) document.close(); try{ if(outputZipStream != null) outputZipStream.close(); if(writer != null) writer.close(); }catch(IOException e){ } } Please, rest assure that I have look at this code for a long time, and try rewrite it many times to reduce the amount of memory it using. After the OutOfMemoryError, there are still lots of pdf files that have not been added 2-3 extra pages, so I think it is inside addBackerAndAffidavit, however, I try to close every resources I opened, but it still exception out. Please help. A: You need to invoke PdfWriter#freeReader() by end of every loop to free the involved PdfReader. The PdfCopy#freeReader() has this method inherited from PdfWriter and does the same. See also the javadoc: freeReader public void freeReader(PdfReader reader) throws IOException Description copied from class: PdfWriter Use this method to writes the reader to the document and free the memory used by it. The main use is when concatenating multiple documents to keep the memory usage restricted to the current appending document. Overrides: freeReader in class PdfWriter Parameters: reader - the PdfReader to free Throws: IOException - on error
{ "language": "en", "url": "https://stackoverflow.com/questions/7560235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to include sharppcap library into Visual Studio? Sorry for the noob question. I don't really know how to make sharppcap library working in my project. I'm using Visual Studio 2010. A: Right click on your Project in Visual Studio-->Select Add reference --> Browse --> find the Sharppcap library and click done. You should now be able to use the Sharpcap library in your project. A: In your application find Reference option, right click on it and select Add Reference. Choose your sharppacp.dll and add it. At last write using sharppacp ; in your application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Problem with session in Django after login Hi am relatively new to Django, been making steady progress with most of the stuff but i have come to be stuck at the sessions part. After i login from my login view, it is successful and redirects to the next link which points to another view. This is where the problem happens, request.user simply returns an empty object and my user not detected as logged in. I tried googling everywhere and reading the official django tutorials but can't come up with anything, can anybody look at my code to see where i did wrong? I also looked at my database and it seems django is correctly storing sessions on my database, could this be something wrong with the cookies? Below is my 2 simple views. def mylogin(request): def errorHandle(error): form = LoginForm() return render_to_response('login/login.html', { 'error' : error, 'form' : form, }) if request.method == 'POST': # If the form has been submitted... form = LoginForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass username1 = request.POST['username'] password1 = request.POST['password'] u = User.objects.get(username=username1) user = authenticate(username=username1, password=password1) if user is not None: if user.is_active: # Redirect to a success page. login(request, user) username1 = user.last_name + " " + user.first_name return HttpResponseRedirect("../portal/") #return render_to_response('login/logged_in.html', { # 'username': username1, #},RequestContext(request)) else: # Return a 'disabled account' error message error = u'account disabled' return errorHandle(error) else: # Return an 'invalid login' error message. error = u'invalid login' return errorHandle(error) else: error = u'form is invalid' return errorHandle(error) else: form = LoginForm() # An unbound form return render_to_response('login/login.html', { 'form': form, }) def mytest(request): request.user.username return render_to_response('login/logged_in.html', { 'username': username1, }) A: I think you're reinventing the wheel unnecessarily - all this heavy lifting has already been done. I strongly recommend using django-registration for this, possibly in conjunction with django-profiles. The documentation is a bit abstract but it's extremely well written and very flexible. I never deploy a Django site without it, and never grapple with issues like this one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Xcode - Command /Developer/usr/bin/clang failed with exit code 1 I'm just starting programming, and trying to learn C. For my homework I had to design a program, and I'm pretty sure my code is right, but whenever I try to test it, or even try programs directly from the book, I get this error. Ld "/Users/BasirJamil/Library/Developer/Xcode/DerivedData/Lab_2-fuyrgmtkjwgafzctwttcpwxptwox/Build/Products/Debug/Lab 2.app/Contents/MacOS/Lab 2" normal x86_64 cd "/Users/BasirJamil/Desktop/Lab 2" setenv MACOSX_DEPLOYMENT_TARGET 10.7 /Developer/usr/bin/clang -arch x86_64 -isysroot /Developer/SDKs/MacOSX10.7.sdk -L/Users/BasirJamil/Library/Developer/Xcode/DerivedData/Lab_2-fuyrgmtkjwgafzctwttcpwxptwox/Build/Products/Debug -F/Users/BasirJamil/Library/Developer/Xcode/DerivedData/Lab_2-fuyrgmtkjwgafzctwttcpwxptwox/Build/Products/Debug -filelist "/Users/BasirJamil/Library/Developer/Xcode/DerivedData/Lab_2-fuyrgmtkjwgafzctwttcpwxptwox/Build/Intermediates/Lab 2.build/Debug/Lab 2.build/Objects-normal/x86_64/Lab 2.LinkFileList" -mmacosx-version-min=10.7 -framework Cocoa -o "/Users/BasirJamil/Library/Developer/Xcode/DerivedData/Lab_2-fuyrgmtkjwgafzctwttcpwxptwox/Build/Products/Debug/Lab 2.app/Contents/MacOS/Lab 2" ld: duplicate symbol _main in /Users/BasirJamil/Library/Developer/Xcode/DerivedData/Lab_2-fuyrgmtkjwgafzctwttcpwxptwox/Build/Intermediates/Lab 2.build/Debug/Lab 2.build/Objects-normal/x86_64/File.o and /Users/BasirJamil/Library/Developer/Xcode/DerivedData/Lab_2-fuyrgmtkjwgafzctwttcpwxptwox/Build/Intermediates/Lab 2.build/Debug/Lab 2.build/Objects-normal/x86_64/main.o for architecture x86_64 Command /Developer/usr/bin/clang failed with exit code 1 Can somebody please explain what the problem is, and how I can fix it, without getting overly technical (if possible)? Remember, I'm still new to programming Thanks In Advance A: You can also get this error of you include an implementation file rather than a header file accidentally. e.g. #import "MyClass.m" instead of #import "MyClass.h" A: As stated in the other answers, this happens because the linker is finding more than one symbol that is named the same thing... in this case "_main". There are a number of reasons why this can happen (global variables/methods of same name, global variables/methods defined--as opposed to declared--in .h files included more than once, etc.) However, this being Xcode related, the first thing you might want to check is your build phases. It is possible for your "Compile Sources" build phase is compiling the same file more than once. In your case, it is probably "main.m". Somehow this happened to me today after I added a lot of localized .xib files to my project and Xcode crashed. A: ld: duplicate symbol _main in /Users/BasirJamil/Library/Developer/Xcode/DerivedData/Lab_2 You have a variable (most likely) or a function defined more than once. In fact, it may be that you have defined _main twice. It helps to read the whole error message, not just the last line. :-) Check your code. A: I had this error, what i do is just look in my "Build Phases" -> "Compile Sources" and delete all duplicate files. A: This error is talking about 2 functions with same name - main have been defined. Per your description that you are new to C, so I guess you might make the same stupid mistake as me. At the very beginning, I just simply drag all the sources files I can download to study the C, 2 projects included LUA and http-parser then I started to build and run my Xcode project then I encountered the exactly same error message you posted at here. A: I got the same error, I used file-> open recent-> clear menu. after I have done it, the error disappear. There is nothing wrong with your code, just clean the history...
{ "language": "en", "url": "https://stackoverflow.com/questions/7560239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Iteratively Reference Controls by Name Pattern (VB.NET) Is there a way to iteratively reference an ASP.NET control based on it's name pattern? Perhaps by a "pointer" or something? What I have are a large set of comboboxes (each with an associated DropDownList and TextBox control). The DropDownList always has an item selected by default, but the use may wish to submit a NULL value. I come up with the following code to handle three cases: NULL, Existing Item, New Item. 'TextBoxControl & DropDownListControl should iteratively reference their ' respective TextBox & DropDownList controls by the actual control name If StrComp(TextBoxControl.Text, DropDownListControl.SelectedItem.ToString) = 0 Then 'When an Existing Item is selected, Do Something ElseIf Not TextBoxControl.Text = "" Then 'When a New Item is entered, Validate & Do Something Else 'When NULL, Do Something End If The problem is, with so many comboboxes, I could easily end up with hundreds of lines of code. I wish to handle this in a more dynamic way, but I do not know if it is possible to reference controls in this way. Say I wanted to reference all the TextBox Controls and DropDownList Controls, respectively. I can do string formatting with a given naming pattern to generate a name ID for any of the controls because they are all named with the same pattern. For example by attaching a specific suffix, say "_tb" for TextBox Controls and "_ddl" for DropDownList Controls: Left(item.SelectedItem.ToString, item.SelectedItem.ToString.Length - 3) + "_tb" Can this sort of thing be done in VB? Ultimately, my goal is to take the value entered/selected by the user, if any, and send it to a stored procedure on SQL Server for insertion into the database. A: Yes. Write your code inside of a function having parameters for the textbox and the dropdown, and then write the function in terms of those two parameters. Then you simply call that function for every set instead of copy/pasting code everywhere. Don't attempt choosing things by name. That's fragile and imposes machine requirements on a field that'd designed for human consumption. A: I am not sure if the samething that applies VBA will apply to your situation, but I had the same issue and was able to use: Me.MultiPage1.Pages(1).Controls("ref" & i + 1).Value where controls encompasses all controls on the userform ("Me"). So if the controls in your program conform to a consecutive naming structure it is easy handle if the above applies vb.net
{ "language": "en", "url": "https://stackoverflow.com/questions/7560240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert DOC to PDF from Command Line Anyone recommend a DOC to PDF converter that can be run from the command line? It seems like an easy requirement, but I have been coming up short on free solutions. A: I recommend the OfficeToPDF command line application. C:\>OfficeToPDF.exe /bookmarks /print /verbose test.docx test.pdf Converting test.docx to test.pdf Converting with Word converter Completed Conversion C:\> I used this solution to automate the PDF generating using ANT. A: I appreciate you are trying to do this from the command line but because you mentioned C#, the approach I use to is to first convert a doc to ps (PostScript) in C# which is relatively simple and well documented and then from the command line use Ghostscript to convert to PDF. Pls don't underestimate the tool from the basic looking website - it is amazing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: ASP.NET MVC 3 Razor Partial View - jQuery Included In Main Layout A partial view that I'm using requires certain jQuery libraries to be included, and I'm currently trying to think of the best way to nicely add them. My current setup is as follows: _Layout.cshtml: ... @if (ViewBag.jQuery) { <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script> } ... Index.cshtml: ... @{ Html.RenderPartial("PartialView", new MVCModel.Models.MyModel(), new ViewDataDictionary { { "ViewBag", ViewBag } }); } ... PartialView.cshtml: ... @{ if (ViewBag.ViewBag != null) { var vb = (dynamic)ViewBag.ViewBag; vb.jQuery = true; } } ... So what I'm trying to do is "turn on" the library in the partial view, and have that boolean propagate up to the master layout. This makes it so that I can enable the library as much as I want wherever I want (many partial views, or one view used multiple times), but it will only get included once. On top of that, I get control over the ordering of the includes, so I can make sure a files dependencies are included first. I'm just wondering if there is a nicer way of pulling this off. Right now my two biggest issues are: * *The ViewBag is not strongly typed, so intellisense won't tell me which libraries are available to me. *Passing the ViewBag to the partial view, just so I can re-use it. A: Here is a simple way to accomplish your objective. There is a function in MVC Razor views called RenderSection. It has a syntax like @RenderSection ("occasionalScripts", false) (occasionalScripts is the name of the section and false means the section is optional and may not appear in every page.) You would want to include this in your _Layout.cshtml which is Views\Shared. This will allow your main script template to display a section with your script definitions if you have it defined for a particular view. Generally, you want to put this at the bottom of your page just before the closing </body> tag. (This is a best practice for performance.) I would list all of my other scripts (the ones which load on every page) just above it. The reason is because the load order of jQuery scripts is very important. In each of your views where you have special scripts, add the following: @section occasionalScripts { ... put script references here } If you have a view which requires no special scripts, then you don't need to include this section there. The false on the @RenderSection tag will accommodate any view where the @section tag is missing. On each page where this functionality is implemented, you can select different scripts. Optionally, you could have multiple sections defined for different categories of files. A: I usually have a different approach, and consider that ALL libraries used on the web site should be referenced on every page. It does make the first load a bit slower, but then the loading of all the following pages is faster, as it uses the browser-cache. To improve it even better, you can make all your libraries available in only one file. I used SquishIt for that at some point. I integrates rather well in ASP.NET MVC.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can XML::LibXML add nodes to a document based on XPath alone? I'm looking for a method that allows me to spring to life a text node that something like: $doc->addNode( $xPath ); The fact that XPath queries can get quite funky at times is probably a good enough reason for not implementing such a method inside XML::LibXML. But the simpler, absolute XPaths do provide a convenient address representation for nodes. There are times when such a method makes life a whole lot easier, as well as a whole lot more sense. To address this need, I rolled my own overly-simplistic sub that performs a recursive walk up the XPath until an existing XPath is found, at which point the necessary nodes are created and added. While it works for the time being, it doesn't handle indexed XPaths (like /library/book[2]/title) and references to text() nodes need to be stripped out. I'm hoping there is an alternative solution that fulfills my requirement. Writing my own XPath-parser/node-generator is way too much work for what it's worth.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting a String to AppWidget via GetExtras (or) Shared prefrences I have an app widged which basically has a textview. I also have an activity which displays a textview from string created within. Now i have a button in Activity 1 which onClick will send data (string to appWidget class) I tried putExtra and getExtra methods and also Shared preferences method, im little confused to use which first! Here are some inputs from me for more clarity. Activity1: final String addwidget = ((TextView)findViewById(R.id.verse)).getText().toString(); Intent widgetIntent = new Intent(MyScheduledActivity.this, MainWidget.class); widgetIntent.putExtra("widgetVerse", addwidget); AppWidget: public class MainWidget extends AppWidgetProvider { RemoteViews views; public static String verseFromFav; private Bundle getVerseData; @Override public void onReceive(Context context, Intent intent) { getVerseData = intent.getExtras(); verseFromFav = getVerseData.getString("widgetVerse"); super.onReceive(context, intent); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { final int N = appWidgetIds.length; for (int i=0; i<N; i++) { views = new RemoteViews(context.getPackageName(),R.layout.widget_layout); if(verseFromFav == null){ verseFromFav = "no verse"; } views.setTextViewText(R.id.widgetVerse, verseFromFav); ComponentName thisWidget = new ComponentName( context, MainWidget.class ); AppWidgetManager.getInstance( context ).updateAppWidget( thisWidget, views ); appWidgetManager.updateAppWidget(appWidgetIds, views); } super.onUpdate(context, appWidgetManager, appWidgetIds); } } (THE APP WIDGET SHOWS "no verse" WHICH READS NULL) Can any one help me with a basic idea on how to display the string here. please. thanks in advance. A: onUpdate will ALWAYS be called (sometimes multiple times) so utilize that to fire a utility or controller class and do all the work in that class. Thus, in your app widget the only thing you might have, all I am demonstrating is updating a string in a TextView, is stuff in the onUpdate() method. @Override public void onUpdate( final Context context, final AppWidgetManager appWidgetManager, final int[] appWidgetIds ) { // Need this here to set the initial state of the app widget final AppWidgetController _actrlr = new AppWidgetController( context ); _actrlr.updateAppWidgetUI( this ); super.onUpdate( context, appWidgetManager, appWidgetIds ); } Then in AppWidgetController class you might have something like this... public final void updateAppWidgetUI( final Context context ) { final AppWidgetManager _manager = AppWidgetManager.getInstance( context ); final ComponentName _componentName = new ComponentName( context, com.your.namespace.theprovidername.class ); final int[] appWidgetIds = _manager.getAppWidgetIds( _componentName ); for ( final int i : appWidgetIds ) { final RemoteViews _rv = new RemoteViews( context.getPackageName(), R.layout.appwidget_xml_layout_file ); if( somethingIsTrue ) { _rv.setTextViewText( R.id.textViewThatYouWantToUpdate, "The text that you wish to display if something is TRUE" ); } else { _rv.setTextViewText( R.id.textViewThatYouWantToUpdate, "The text that you wish to display if something is FALSE" ); } _manager.updateAppWidget( i, _rv ); } } RemoteView setTextViewText() http://developer.android.com/reference/android/widget/RemoteViews.html#setTextViewText(int, java.lang.CharSequence) A: I would advise you to use sharedpreference for this. It would do you better. SharedPreferences settings = getSharedPreferences("MyWigdetPreferences", MODE_WORLD_READABLE); SharedPreferences.Editor prefEditor = Settings.edit(); prefEditor.putString("widgetVerse", addwidget); prefEditor.commit(); Then in the mainWidget activity pull it out by.. SharedPreferences settings = getSharedPreferences("MyWigdetPreferences", MODE_WORLD_READABLE); String verse = settings.getString("widgetVerse"); That should do it. EDIT: Instead of @Override public void onReceive(Context context, Intent intent) { getVerseData = intent.getExtras(); verseFromFav = getVerseData.getString("widgetVerse"); super.onReceive(context, intent); } Try @Override public void onReceive(Context context, Intent intent) { getVerseData = getIntent.getExtras(); verseFromFav = getVerseData.getString("widgetVerse"); super.onReceive(context, intent); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7560265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does -2 % 360 give -2 instead of 358 in c# Microsoft Mathematics and Google's calculator give me 358 for -2 % 360, but C# and windows calculator are outputting -2 ... which is the right answer ? A: Which is the right answer? Both answers are correct. It's merely a matter of convention which value is returned. A: Both, see Modulo operation on Wikipedia. A: I found this very easy to understand explanation at http://mathforum.org/library/drmath/view/52343.html There are different ways of thinking about remainders when you deal with negative numbers, and he is probably confusing two of them. The mod function is defined as the amount by which a number exceeds the largest integer multiple of the divisor that is not greater than that number. In this case, -340 lies between -360 and -300, so -360 is the greatest multiple LESS than -340; we subtract 60 * -6 = -360 from -340 and get 20: -420 -360 -300 -240 -180 -120 -60 0 60 120 180 240 300 360 --+----+----+----+----+----+----+----+----+----+----+----+----+----+-- | | | | -360| |-340 300| |340 |=| |==| 20 40 Working with a positive number like 340, the multiple we subtract is smaller in absolute value, giving us 40; but with negative numbers, we subtract a number with a LARGER absolute value, so that the mod function returns a positive value. This is not always what people expect, but it is consistent. If you want the remainder, ignoring the sign, you have to take the absolute value before using the mod function. Doctor Peterson, The Math Forum http://mathforum.org/dr.math/ A: The C# compiler is doing the right thing according to the C# specification, which states that for integers: The result of x % y is the value produced by x – (x / y) * y. Note that (x/y) always rounds towards zero. For the details of how remainder is computed for binary and decimal floating point numbers, see section 7.8.3 of the specification. Whether this is the "right answer" for you depends on how you view the remainder operation. The remainder must satisfy the identity that: dividend = quotient * divisor + remainder I say that clearly -2 % 360 is -2. Why? Well, first ask yourself what the quotient is. How many times does 360 go into -2? Clearly zero times! 360 doesn't go into -2 at all. If the quotient is zero then the remainder must be -2 in order to satisfy the identity. It would be strange to say that 360 goes into -2 a total of -1 times, with a remainder of 358, don't you think? A: IMO, -2 is much easier to understand and code with. If you divide -2 by 360, your answer is 0 remainder -2 ... just as dividing 2 by 360 is 0 remainder 2. It's not as natural to consider that 358 is also the remainder of -2 mod 360. A: From wikipedia: if the remainder is nonzero, there are two possible choices for the remainder, one negative and the other positive, and there are also two possible choices for the quotient. Usually, in number theory, the positive remainder is always chosen, but programming languages choose depending on the language and the signs of a and n.[2] However, Pascal and Algol68 do not satisfy these conditions for negative divisors, and some programming languages, such as C89, don't even define a result if either of n or a is negative.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: IE7-9 testing workflow on a Mac I'm at my wits end right now trying to get a website working in IE7-9, the issue I'm having is getting text-shadow to appear in a decent matter. I've been using the 960 grid system so changes are very minimum, I've been checking changes with IE Netrender. However lately IE Netrender has been having issues so I can't test the layout in a timely fashion. I did have VM Ware set up but I'm really tired of reactivating my Windows copy and installing a separate image for each version of the browser. I don't have Windows 7 for IE9 as well. I'm looking for a free option. I've tried searching but everything seems outdated. So my question is, how does everyone test their site for IE7-9? A: The IE Developer Tools let you set IE7 and IE8 modes on IE9, so you can get 98% testing with one version. There are some issues that don't crop up there though, so its a good idea to do a quick real browser check at the end. MS has free VMs you can download with the different versions of IE on them. I'm not sure if you can run them on a Mac though. http://www.microsoft.com/download/en/details.aspx?id=11575 A: By having a Windows license. Perhaps not the answer you're looking for, but there's no such thing as a free meal. The only truly guaranteed method of testing a site in Internet Explorer is to actually use it in Internet Explorer, be it in a virtual machine or on a real PC. Spoon used to have an Internet Explorer virtualization web app, but that has since been removed at Microsoft's behest.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: storing the accessor to innerHtml as a var I was trying to figure out a way to do the following var foo = document.body.innerHtml; then call foo = "testing" and the body's html would read "testing" but so far all that happens is innerHtml is returning the value of innerHtml ... which is expected is there any way to store innerHtml and maybe do something like var hold = "innerHtml" document.body[hold] = "foo" <--- this does not work by the way A: You will have to use innerHTML (uppercase) instead of innerHtml to get the desired results. These lines produce the same results: document.body.innerHTML; document.body["innerHTML"]; document["body"].innerHTML; document["body"]["innerHTML"];
{ "language": "en", "url": "https://stackoverflow.com/questions/7560270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails dynamic select menu for 3.1 How would this be updated for Rails 3.1? http://railscasts.com/episodes/88-dynamic-select-menus I just can't figure out how to call the js.erb file and have it run the code to generate the javascript dynamically. A: Might be something: in Rails 3.1, you're most likely using jQuery instead of Prototype. The example code on the Railscasts site is using good old Prototype instead of the new hotness that is jQuery (default javascript library in Rails 3.1). Once all your jquery pipes are connected, having rails respond to and render your js.erb is the same as always. In your controller: def country_selected // whatever you need to do respond_to do |format| format.js end end Then in your view directory, you have a country_selected.js.erb that you can put in whatever javascript you want to update the second select menu. (Remember you have to escape your shiz for it to work correctly) e.g. <%= escape_javascript(params[:country]) %> By the way, I think .rjs was moved out of Rails proper and into it's own Gem. Something else to keep in mind regarding Rails 3.1 vs. javascript.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL Server: pointing to the ID from other table I have two tables: (ID = int, Match = varchar, Status = char) TableA ID1 Match1 Status1 23 1200 PASS 24 1300 FAIL 25 1400 PASS 26 1500 PASS 27 1600 FAIL TableB ID2 Match2 Status2 456 1200 784 1300 457 1300 124 1400 741 1600 Now, I want to populate tableB (status2) with 'FAIL' where there is fail in tableA (match). so, I should get: TableB ID2 Match2 Status2 456 1200 NULL 784 1300 FAIL 457 1300 FAIL 124 1400 NULL 741 1600 FAIL now this is pretty simple. I want to put in status2, ID1 which caused the fail so the expected result would be: TableB ID2 Match2 Status2 456 1200 NULL 784 1300 FAIL of ID 24 457 1300 FAIL of ID 24 124 1400 NULL 741 1600 FAIL of ID 27 I am currently using simple update statement as follows: update B set status2 = 'Fail' from tableB B Inner join tableA A on a.match1 = b.match2 where a.status1 = 'FAIL' Please correct to point to the ID1. Thanks A: update B set status2 = 'Fail of ID ' + CAST(A.ID1 AS VARCHAR(4)) from tableB B Inner join tableA A on a.match1 = b.match2 where a.status1 = 'FAIL'
{ "language": "en", "url": "https://stackoverflow.com/questions/7560276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Match each variable passed in MYSQL IN() Basically I have the following query: SELECT DISTINCT users.ID, users.name FROM users INNER JOIN usersSkills ON users.ID = usersSkills.userID INNER JOIN usersLanguages ON users.ID = usersLanguages.userID WHERE activated = "1" AND type = "GRADUATE" AND usersSkills.skillID IN(2, 21) AND usersLanguages.languageID IN(2, 22) I need to match the skillID and languageID to each parameter passed in the IN() function at the moment on each of those it will serve up a result if either parameter is found. So essentially i want to only see results if the skill ID of 2 AND 21 are found on the skills table and the same idea for the languages... A: Use a GROUP BY (this will also eliminate the need for SELECT DISTINCT) to get an aggregate count and a HAVING clause to make sure the count of distinct elements returned matches the number of elements you're searching for. SELECT users.ID, users.name FROM users INNER JOIN usersSkills ON users.ID = usersSkills.userID INNER JOIN usersLanguages ON users.ID = usersLanguages.userID WHERE activated = "1" AND type = "GRADUATE" AND usersSkills.skillID IN(2, 21) AND usersLanguages.languageID IN(2, 22) GROUP BY users.ID, users.name HAVING COUNT(DISTINCT usersSkills.skillID) = 2 AND COUNT(DISTINCT usersLanguages.languageID) = 2
{ "language": "en", "url": "https://stackoverflow.com/questions/7560277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using math.factorial in a lambda function with reduce() I'm attempting to write a function that calculates the number of unique permutations of a string. For example aaa would return 1 and abc would return 6. I'm writing the method like this: (Pseudocode:) len(string)! / (A!*B!*C!*...) where A,B,C are the number of occurrences of each unique character. For example, the string 'aaa' would be 3! / 3! = 1, while 'abc' would be 3! / (1! * 1! * 1!) = 6. My code so far is like this: def permutations(n): ''' returns the number of UNIQUE permutations of n ''' from math import factorial lst = [] n = str(n) for l in set(n): lst.append(n.count(l)) return factorial(len(n)) / reduce(lambda x,y: factorial(x) * factorial(y), lst) Everything works fine, except when I try to pass a string that has only one unique character, i.e. aaa - I get the wrong answer: >>> perm('abc') 6 >>> perm('aaa') 2 >>> perm('aaaa') 6 Now, I can tell the problem is in running the lambda function with factorials on a list of length 1. I don't know why, though. Most other lambda functions works on a list of length 1 even if its expecting two elements: >>> reduce(lambda x,y: x * y, [3]) 3 >>> reduce(lambda x,y: x + y, [3]) 3 This one doesn't: >>> reduce(lambda x,y: ord(x) + ord(y), ['a']) 'a' >>> reduce(lambda x,y: ord(x) + ord(y), ['a','b']) 195 Is there something I should be doing differently? I know I can rewrite the function in many different ways that will circumvent this, (e.g. not using lambda), but I'm looking for why this specifically doesn't work. A: See the documentation for reduce(), there is an optional 'initializer' argument that is placed before all other elements in the list so that the behavior for one element lists is consistent, for example, for your ord() lambda you could set initializer to the the character with an ord() of 0: >>> reduce(lambda x, y: ord(x) + ord(y), ['a'], chr(0)) 97 A: Python's reduce function doesn't always know what the default (initial) value should be. There should be a version that takes an initial value. Supply a sensible initial value and your reduce should work beautifully. Also, from the comments, you should probably just use factorial on the second argument in your lambda: reduce(lambda x,y: x * factorial(y), lst, 1) A: If you want len(s)! / A!*B!*C! then the use of reduce() won't work, as it will calculate factorial(factorial(A)*factorial(B))*factorial(C). In other words, it really needs the operation to be commutative. Instead, you'll need to generate the list of factorials, then multiply them together: import operator reduce(operator.mul, [factorial(x) for x in lst]) A: Reduce works by first computing the result for the first two elements in the sequence and then pseudo-recursively follows from there. A list of size 1 is a special case. I would use a list comprehension here: prod( [ factorial(val) for val in lst ] ) Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7560284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Check if a field is final in java using reflection I'm writing a class, which at some point has to have all its Fields assigned from another item of this class. I did it through reflection: for (Field f:pg.getClass().getDeclaredFields()) { f.set(this, f.get(pg)); } The problem is, that this class contains a Field, which is final. I could skip it by name, but to me that seems not elegant at all. What's the best way to check if a Field is final in java using reflection? A: You can use getModifiers() method on the Field variable: if ((f.getModifiers() & Modifier.FINAL) == Modifier.FINAL) { //this is final field } A: The best and only one way is: Modifier.isFinal(f.getModifiers()) Reference: * *Field.getModifiers *Modifier.isFinal
{ "language": "en", "url": "https://stackoverflow.com/questions/7560285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "50" }
Q: Provide a folder out of source where all my external libraries are found I have the following folder structure * *lib *my_module I have moved all the libraries I need into the lib/ folder. In my module/__init__.py, I think I will do: import sys sys.path.append('../lib/') import my_dependency Then when I need to use this dependency, I will refer to it as my_module.my_dependency Is this a bad usage of Python import? NOTE: the dependencies consists of some third-party libraries not available via pip/easy_install and some C++ stuff that I wrote. A: sys.path.append('../lib/') assumes that the current working directory is the directory of your script, which may or may not be the case. A version that doesn't depend on the working directory is: import sys, os sys.path.append(os.path.join(os.path.split(os.path.split(os.path.abspath(sys.argv[0]))[0])[0], "lib")) import my_dependency The above in plain language takes the full path to the script, chops off the last two components (script directory and script filename) and appends lib. A: If the libraries you use are third-party modules—especially popular ones—namespacing them like that is going to get inconsistent pretty fast. You will end up with code that sometimes is referenced as bar and sometimes as foo.bar. Maintaining such a codebase will not be worth whatever gains you expect to get from prefixing them like that. If you keep third-party code in your own repository, consider replacing it with a requirements.txt file that can be fed to utilities like easy_install and pip. Both these tools support a --user switch that installs to your home directory (not touching system stuff). pip install -r requirements.txt --user
{ "language": "en", "url": "https://stackoverflow.com/questions/7560293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: best C# library for getting IP Camera stream? I found there's quite a lot of IP Camera libraries for C# on the net. In case you have worked with any of them, which seem to be the best? Thanks! A: Emgu CV is an open source C# wrapper for Open-CV which is a robust open source library for image processing and more. It has some out of the box webcam image capturing examples using only seven lines of code. The web cam part look like it was address in this question. Getting the camera stream through (httprequest)webrequest is not a huge deal. Most cameras will send the video back in an MJPEG stream. The stream is just a multi-part message that is broken up by a delimiter, specified in the head section of the response, and two carriage returns. The data inbetween the delimiters are JPEG images which you can feed into the wrapper for the CV library.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rewrite website content to load from subdomain I am figuring out how to rewrite website content (images/js/css) for faster loading times. This could also fix a "Access-Control-Allow-Origin" error for me. Is it possible to rewrite content/dir/file.ext to http://content.domain.com/dir/file.ext A: Yes it is possible. However, if your intention is faster load times, you'd be better off changing the URLs in your code than to have Apache rewrite/redirect every request. Given your current spec, that's the right way to do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I relay dynamic parameters passed into a functionA() to functionB() called within functionA() I'm trying to relay dynamic parameters from a web page into a function, which then passes them to a call inside the function. For example, take the simplified snippet below, as it is now, passing in the parameters directly is not problem. But how do I pass in a parameter which colorbox accepts without making a parameter for showColorbox() for every possible colorbox parameter? function showColorbox(title, url, width, height, modal, params) { $.colorbox({title:title, href:url, width:width, height:height, opacity:0.7}); } For instance, colorbox accepts passing in an event function, such as below if I called colorbox directly: $.colorbox({title:title, href:url, width:width, height:height, opacity:0.7, onComplete: function() { $.colorbox.resize(); } }); So, without adding some code or making another parameter and parsing it out somehow inside showColorbox(), is there a way for me to pass the onComplete param/code [via showColorbox(....{onComplete:yada yada}) or something] and have them relayed to the $.colorbox() function? UPDATE: Ended up using the following successfully, added an extra objParams parameter to the showColorbox() function. //m_title, m_url, m_width, m_height are from fixed parameters for showColorbox() var objBase = {title:m_title,href:m_url,width:m_width,height:m_height} ; var objFinal = {}; //add base parameters passed in directly, fixed params for(var item in objBase) { objFinal[item] = objBase[item]; } //add the parameters from objParams passed in (variable params/values) for(var item in objParams) { objFinal[item] = objParams[item] } //call function with combined parameters in object $.colorbox(objFinal) None of the callers needed to be updated, but now passing in a new object using parameters which $.colorbox understands works fine! Thanks again! A: It sounds like the solution you're looking for is wanting there to be a simple way to pass individual parameters of variable arguments as a named property value in an object literal. If so no there is no way to achieve this. Primarily because in this case there are no names for the arguments so there would be nothing for them to map to. The best way to approach this problem altogether is to require an object at every stage and omit the extra parameters altogether. function showColorbox(obj) { ... $.colorbox(obj); } showColorbox({title:title, href:url, width:width, height:height, opacity:0.7}); A: Why not just accept one parameter which is the object you pass to colorbox? function showColorbox(params) { $.colorbox(params); } Then you can call it like this: showColorbox({title:title, href:url, width:width, height:height, opacity:0.7});
{ "language": "en", "url": "https://stackoverflow.com/questions/7560315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SQL Selecting record with highest ID I have a issue with some SQL that I can't wrap my head around a solution. Right now the query I am running basically is: SELECT Q.ID, Q.STATUS, C.LASTNAME, C.FIRSTNAME, C.POSTAL, C.PHONE FROM QUEUE Q LEFT OUTER JOIN CUSTOMER C ON Q.ID = C.APPID WHERE C.LASTNAME LIKE 'SMITH%' I have about 200 records from this query. My issue is the same person has multiple occurances. Q.ID Q.STATUS C.LASTNAME C.FIRSTNAME ETC... 1 A SMITH JOHN 2 A SMITH RYAN 3 B SMITH BRIAN 100 A SMITH RYAN 200 A SMITH RYAN What I need returned instead is Q.ID Q.STATUS C.LASTNAME C.FIRSTNAME ETC... 1 A SMITH JOHN 3 B SMITH BRIAN 200 A SMITH RYAN Can anyone point me in the right direction please. I have tried SELECT WHATEVER FROM TABLE WHERE Q.ID IN (SELECT MAX(ID) FROM TABLE WHERE BLAH BLAH) which worked when searching for "RYAN SMITH" specifically. But I need to show all results for SMITH with the highest IDs. Any help is appreciated. Cheers A: I guess you could do something like below SELECT WHATEVER FROM TABLE WHERE Q.ID IN (SELECT MAX(ID) FROM TABLE WHERE BLAH...BLAH GROUP BY C.FIRSTNAME, C.LASTNAME) Hope this helps!! A: have you tried something like that? well it is not really a SQL statement, just showing the idea select * from Table where id in ( select max(q.id) from Table group by c.lastname, c,firstname ) A: Assuming there is a CUSTOMER.ID, and I think I'm right, here it goes: SELECT Q.ID, Q.STATUS, M.LASTNAME, M.FIRSTNAME, M.POSTAL, M.PHONE FROM QUEUE Q LEFT OUTER JOIN ( SELECT C2.ID CID, MAX(C2.FIRSTNAME) FIRSTNAME, MAX(C2.LASTNAME) LASTNAME, MAX(C2.POSTAL) POSTAL, MAX(C2.PHONE) PHONE, MAX(Q2.ID) QID FROM QUEUE Q2 LEFT OUTER JOIN CUSTOMER C2 ON Q2.ID = C.APPID WHERE C2.LASTNAME LIKE 'SMITH%' GROUP BY C2.ID ) M ON (M.QID = Q.ID) A: If I understand well, this should work: SELECT Q.ID , Q.STATUS , C.LASTNAME , C.FIRSTNAME, , C.POSTAL , C.PHONE FROM QUEUE Q join CUSTOMER C ON Q.ID = C.APPID WHERE C.LASTNAME like 'SMITH%' and not exists (SELECT * FROM CUSTOMER innerCustomer WHERE innerCustomer.LASTNAME like 'SMITH%' and innerCustomer.APPID > C.APPID ) Note: I have change "left join" by "inner join" because you are filtering per C.LASTNAME. So I think left join doesn't have many sense.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Error Microsoft.VJSharp.VJSharpCodeProvide I installed visual studio 2008 in our server and tried to run our proejct on the server but i got this error The CodeDom provider type "Microsoft.VJSharp.VJSharpCodeProvider, VJSharpCodeProvider, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" could not be located. Do you have any idea what is my problem? A: The J# support assemblies are not included in .NET, it is a separate download. A: In Visual Studio 2010, in addition to installing Microsoft Visual J# Version 2.0 Redistributable Package, adding the following to Web.config within the main <configuration> tag seemed to also be required: <system.codedom> <compilers> <compiler language="vj#;vjs;vjsharp" extension=".jsl;.java" type="Microsoft.VJSharp.VJSharpCodeProvider, VJSharpCodeProvider, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"></compiler> </compilers> </system.codedom> A: It may be your project may include some Java related files and due to it this error can come, Ref :- http://blogs.telerik.com/aspnet-ajax/posts/07-12-02/the-codedom-provider-type-microsoft-vjsharp-vjsharpcodeprovider-could-not-be-located.aspx can also manually find "JSON" or java files and can delete it if not need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ASP page - Lengthy code behind firing button click I have some asp.net page which is quite large, with a table of some 200 kBytes of data... And an asp:button that takes AGES to fire the code-behind. For instance the update progress displays for some 12 to 20 seconds before code executes! The same code-behind fires in less than a second from a shorter page. And Javascript onclick code fires instantly. Any idea why? A: Your view state may be too large, causing all this data to travel back and forth with every postback. I suggest evaluating your view state and mitigating the display of large data via JS/JQuery on demand - on a page by page basis via ScriptService or generic handler (+JSON).
{ "language": "en", "url": "https://stackoverflow.com/questions/7560326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: authorize my rails 3 applicationd I'm developing a rails 3 application using inherited_resources and devise. I tried to use cancan as my authorization plugin and it wasn't enough (i need more complex conditions for my authorization rules). I also tried using declarative_authorization but my rules didn't work for the "index" method of my controllers. Is there a RELIABLE rails plugin to handle authorization ?! Thanks ! A: You can see a list of authorization gems in here. My advice to you is you should give cancan a second chance. It handles almost everything about authorization.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WM_TOUCH is not immediately sent with touch down event I am working with a touch screen and using Windows 7 built in drivers (as it never prompted me to install any). it works fine, except for one small issue. When I touch the screen, it will not send the WM_LBUTTONDOWN until I move my finger off the screen. It appears to do this to determine if I intend to hold down to emulate WM_RBUTTONDOWN or not. (Also, I tried to disable the hold down emulate gesture, but it never disables in practice.) So I thought I would just receive the WM_TOUCH messages. And I found that WM_TOUCH (0x240) is also not sent to my window until I move my finger off the screen. I sort of thought that defeats the purpose of WM_TOUCH altogether. Both before and after registering to receive WM_TOUCH messages, I received three messages immediately upon touching the screen: 1. Send: 0x02CC (undocumented tablet messages) 2. Post: 0x011B (undocumented) 3. Send: 0x011A (WM_GESTURENOTIFY) 0x011A is WM_GESTURENOTIFY, which my code is to respond to (perhaps I am not responding correctly?). I reply with a standard response (using sample code from MS) to receive full notifications. Another thing, I began getting WM_TOUCH when I register for touch messages, but I continue to get the WM_GESTURENOTIFY message as well. According to the MS documentation, once I register to get WM_TOUCH, I no longer get gesture messages. If anyone can tell me how to get WM_TOUCH messages immediately (e.g. when I am getting the WM_GESTURENOTIFY messages), and not after I let my finger up off the touch scree, I would appreciate it much. A: I almost got the same issue and solved it by using : RegisterTouchWindow( hWnd, TWF_WANTPALM ); A: Check out this tutorial on touch events: http://msdn.microsoft.com/en-us/gg464991 What you want to use is the RegisterTouchWindow function, as such: RegisterTouchWindow(handle, 0); Windows will now send WM_TOUCH messages instead of WM_GESTURE messages to your window. Keep in mind that you will have to compile against Windows SDK version 7.0 or newer for this to work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to verify user email in Drupal 7 when registering user I want a user to enter email, password and password verification. After that they should receive an email notification with an activation URL. When they navigate to this URL, the account gets activated.Is there a Drupal 7 module for this? If not, how can I get started with coding it myself? A: Luckily enough someone's already written this functionality, it's available in the LoginToboggan module
{ "language": "en", "url": "https://stackoverflow.com/questions/7560335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to set the height of a Data Grid in Silverlight 4 I have a couple of DataGrids inside a page and each DataGrid is positioned via the following layout/markup: <border BorderBrush="Black"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="30"/> <RowDefinition Height="*"/> <RowDefinition Height="30"/> </Grid.RowDefinitions> <TextBlock x:Name="Title" Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" Margin="6,0,0,0" Content="Panel Title"/> <toolkit:BusyIndicator Grid.Row="1" Grid.Column="0" x:Name="GridLoadingIndicator"> <StackPanel Orientation="Vertical"> <sdk:DataGrid x:name="GVData" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" AutoGenerateColumns="False" HorizontalScrollBarVisibility="Visible" SelectionMode="Single"> <datagrid:DataGridTextColumn Header="Column 1" Binding="{Binding Col1}" /> <datagrid:DataGridTextColumn Header="Column 2" Binding="{Binding Col2}" /> <datagrid:DataGridTextColumn Header="Column 3" Binding="{Binding Col3}" /> <datagrid:DataGridTextColumn Header="Column 4" Binding="{Binding Col4}" /> <datagrid:DataGridTextColumn Header="Column 5" Binding="{Binding Col5}" /> </sdk:DataGrid> </StackPanel> </toolkit:BusyIndicator> <StackPanel x:Name="PagerControls" Grid.Row="2" Grid.Column="0" Orientation="Horizontal"> <!-- Pager --> </StackPanel> </Grid> </border> Well, the problem is that the grid itself doesn't want to stretch to fill the space allotted for it, and more over it doesn't respond to page size events either. Any ideas on how to fix the issue? A: Derek Beattie is correct in his comment. If your Grid is within a StackPanel and the StackPanel does not have HorizontalAlignment="Stretch" (i.e. in the direction that does not grow) then the stack panel will fit its children. This voids the HorizontalAlignment="Stretch" in your Grid as it can only stretch to its immediate parent (the StackPanel). The fact that it is a StackPanel means that VerticalAlignment="Stretch" does nothing on the inner Grid. If you actually require the inner StackPanel (no point with only one child), then add HorizontalAlignment="Stretch" to it as well. That will not do anything to the vertical stretch. Personally I would just dump the StackPanel that surrounds the inner Grid as it add no value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using number keys as meta keys in emacs I'm learning emacs and am trying to implement my standard keyboard shortcuts. Currently I use the number keys as meta keys, for instance I hold 4 and press N to highlight the previous word, but if I press and release 4 alone then the number 4 is entered into the text buffer. Is it possible to implement this behavior in emacs? It would be great if I could just do (global-set-key (kbd "4-N") 'highlight_left) A: Key-chord may be what you want. A: You can get something similar easily: Define 4 as a prefix key, with 4 4 to insert 4 and 4 N to highlight etc. (No, it's not the same thing -- here you don't hold 4 down while hitting N etc.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7560339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CSS scrollbar in div doesn't work in FF The below HTML used to show a vertical scrollbar in FF3.x and IE. I have installed FF6.0.2 and the scrollbar doesn't show up anymore!! <html> <body> There should be a scroll bar on the page <div style="background:red;position: relative; left: -1px; width: 19px; height: 300px; overflow: auto;"> <div style="background:green;width: 1px; height: 540px;"></div> </div> </body> </html> How can I get my scrollbars to appear with latest FF? This still works in IE9. I think this is an issue with the combination of Windows7(Home Premium) and FF6.0.2. I tested this on Windows XP and FF6.0.2 it works fine. A: Try setting your overflow to scroll: overflow:scroll; Is this what you're looking for?
{ "language": "en", "url": "https://stackoverflow.com/questions/7560345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery 'has no method' error when attempting to render a template This is probably a dumb question, but I've been beating my head at it long enough. I have a template built for use with jQuery .tmpl(). I can successfully select it with $("#templateId"), but calling $("#templateId").tmpl(data) results in a TypeError: Object [object Object] has no method 'tmpl'. It looks like an issue with jQuery's method definitions, but tmpl is in the core, right? Is there a conflict with UI? Running jQuery 1.6.4, UI 1.8.16 A: No it's an officially supported plugin, you can get the latest here A: It seems you're not using the tmpl plugin required: https://github.com/jquery/jquery-tmpl A: tmpl is a plugin, you need to download/install it before use it. http://api.jquery.com/jquery.tmpl/
{ "language": "en", "url": "https://stackoverflow.com/questions/7560356", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Generate possible combinations I have several hash maps I need to generate combinations of: A: [x->1, y->2,...] B: [x->1, a->4,...] C: [x->1, b->5,...] ... some possible combinations: A+B; A; A+C; A+B+C... For each combination I need to produce the joint hashmap and perform an operation of key-value pairs with the same key in both hash maps. All I could come up with was using a binary counter and mapping the digits to the respective hash map: 001 -> A 101 -> A,C ... Although this solution works, the modulo operations are time consuming when I have more than 100 hashmaps. I'm new to Scala but I believe that there must be a better way to achieve this? A: Scala sequences have a combinations function. This gives you combinations for choosing a certain number from the total. From you question it looks like you want to choose all different numbers, so your code in theory could be something like: val elements = List('a, 'b, 'c, 'd) (1 to elements.size).flatMap(elements.combinations).toList /* List[List[Symbol]] = List(List('a), List('b), List('c), List('d), List('a, 'b), List('a, 'c), List('a, 'd), List('b, 'c), List('b, 'd), List('c, 'd), List('a, 'b, 'c), List('a, 'b, 'd), List('a, 'c, 'd), List('b, 'c, 'd), List('a, 'b, 'c, 'd)) */ But as pointed out, all combinations will be too many. With 100 elements, choosing 2 from 100 will give you 4950 combinations, 3 will give you 161700, 4 will give you 3921225, and 5 will likely give you an overflow error. So if you just keep the argument for combinations to 2 or 3 you should be OK. A: Well, think of how many combinations there are of your maps: suppose you have N maps. (the maps individually) + (pairs of maps) + (triples of maps) + ... + (all the maps) Which is of course (N choose 1) + (N choose 2) + ... + (N choose N-1) Where N choose M is defined as: N! / (M! * (N-M)!) For N=100 and M=50, N choose M is over 100,000,000,000,000,000,000,000,000,000 so "time consuming" really doesn't do justice to the problem! Oh, and that assumes that ordering is irrelevant - that is that A + B is equal to B + A. If that assumption is wrong, you are faced with significantly more permutations than there are particles in the visible universe Why scala might help with this problem: its parallel collections framework! A: Following up on your idea to use integers to represent bitsets. Are you using the actual modulo operator? You can also use bitmasks to check whether some number is in a bitset. (Note that on the JVM they are both one instruction operations, so who knows what's happening there.) Another potential major improvement is that, since your operation on the range of the maps is associative, you can save computations by reusing the previous ones. For example, if you combine A,B,C but have already combined, say, A,C into AC, for instance, you can just combine B with AC. The following code implements both ideas: type MapT = Map[String,Int] // for conciseness later @scala.annotation.tailrec def pow2(i : Int, acc : Int = 1) : Int = { // for reasonably sized ints... if(i <= 0) acc else pow2(i - 1, 2 * acc) } // initial set of maps val maps = List( Map("x" -> 1, "y" -> 2), Map("x" -> 1, "a" -> 4), Map("x" -> 1, "b" -> 5) ) val num = maps.size // any 'op' that's commutative will do def combine(m1 : MapT, m2 : MapT)(op : (Int,Int)=>Int) : MapT = ((m1.keySet intersect m2.keySet).map(k => (k -> op(m1(k), m2(k))))).toMap val numCombs = pow2(num) // precomputes all required powers of two val masks : Array[Int] = (0 until num).map(pow2(_)).toArray // this array will be filled, à la Dynamic Algorithm val results : Array[MapT] = Array.fill(numCombs)(Map.empty) // fill in the results for "combinations" of one map for((m,i) <- maps.zipWithIndex) { results(masks(i)) = m } val zeroUntilNum = (0 until num).toList for(n <- 2 to num; (x :: xs) <- zeroUntilNum.combinations(n)) { // The trick here is that we already know the result of combining the maps // indexed by xs, we just need to compute the corresponding bitmask and get // the result from the array later. val known = xs.foldLeft(0)((a,i) => a | masks(i)) val xm = masks(x) results(known | xm) = combine(results(known), results(xm))(_ + _) } If you print the resulting array, you get: 0 -> Map() 1 -> Map(x -> 1, y -> 2) 2 -> Map(x -> 1, a -> 4) 3 -> Map(x -> 2) 4 -> Map(x -> 1, b -> 5) 5 -> Map(x -> 2) 6 -> Map(x -> 2) 7 -> Map(x -> 3) Of course, like everyone else pointed out, it will blow up eventually as the number of input maps increases.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Open Graph Beta: Aggregation's "Group By" Field The documentation for the Open Graph beta says: Group by - Option is only available if your Aggregation is displaying Objects. This option allows the aggregation to group by a property of the object. For example, you can group by Movie object's type, to show how many times you've watched a certain type of movie. How do you select this? I have Egg objects with that have a Collection property and want to aggregate based on that. For example, one aggregate story would include Egg objects with Collection set to "Easter" and another would include Egg objects with Collection set to "Christmas". Group By always seems to default select the object type I choose for Data to Display and I don't see an option to manually set this. Nor do I see a way to set the Aggregation Title to be the name of the group. A: You can't group by a String, only an Object. Try making an Object Type called Collection and make urls for each collection. Then Collection will show up in Data to Display and you can group by it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: setting onscreen keyboard type in Android I was wondering whether the soft keyboard that pops up when we want to type anything in android can be configured. For example, in iOS, we can set the type of the keyboard to be numeric or alphanumeric or email etc. Is there anything similar in Android ? A: Yes Use android:inputType="textShortMessage|textAutoCorrect|textCapSentences|textMultiLine" As a XML tag for EditText's and other writtable widgets
{ "language": "en", "url": "https://stackoverflow.com/questions/7560370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Have a div extend when an element from other div overlaps? I have a div (lets call it header), and another div (lets call is content). Now, the content div extends its height to its contents. Within header, i have an element that overlaps far into content, but content div doesnt extend with the elements overlapping from header. Heres the css i have so far: .content { height:auto; } Any suggestions? http://jsfiddle.net/pgvZr/ A: header and content are siblings, so there is no way to have content expand with content that is part of header using just css To solve your problem, you can: * *use javascript to calculate the height content should have and set it dynamically *put header inside content and remove the fixed height of content A: The reason your "content" div isn't being pushed down is because you have a height set on your "header" div. So, relative to your "header" div, your "content" div is starting 100px down. If you don't set the height, then the "header" div ends up being the height of whatever is contained within it. Take a look at this fiddle... simply removed your height: 100px; off the header and it accomplishes what you want. http://jsfiddle.net/pgvZr/4/ Edit: If you're adding content to the header and want it to be part of your content div (i.e have your content div grow with the header_inner text), then you should probably just move it into the content div. Otherwise, then you shouldn't specify the height on the header, and let it automatically push your content div down when you add the header_inner like my fiddle does. A: I'm not sure i understand the issue. You want to extend content height by adding text to header_inner? A: That's because the child div has a higher z index than anything else, meaning its stacked way on top of everything and it doesn't participate in the document "flow" due to its positioning. I suggest use JQuery to calculate and set its height based on the heights of the other two divs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the Renderer class for UIXIterator Summary What is the renderer class for UIXIterator(af:iterator)? Background I am writing a component and I am planning to extend UIXIterator just like UIXTable does. My component will basically accept the same kind of data binding as UIXIterator/UIXTable does. The only difference will be in the rendering and the client behavior. I am conducting some preliminary checks to see if this is feasible and how I will go about doing this. I have already determined that most likely I can just extend the component and tag classes(UIXIterator and UIXIteratorTag respectively). The only thing that I am not able to find is the renderer class for UIXIterator. A: There is no default Renderer. It renders himself, unless you did not set rendererType in UIXIterator class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Application Icon doesn't change correctly using c# I changed my Application's icon for a new one, by going to: "Project/MyProject Properties/Icon and Manifiest", and load the new icon. Now, in my debug folder the icon of my .exe file appear with the new icon, which is ok, but when I execute the .exe, the application icon in the taskbar still showing the old one. Please advice. A: You have two place to change your icon. First place The first place is in the project. * *Right click on the project *Select Property *Go in Application Tabs *Choose Icon and Manifest and select the icon you want Second place The second place is in the property of your Winform. * *Open the Form *Click on the Form *Press F4 or go in the property of the Form *Go down in the property to find "Icon" *Select the icon you want. The reason you have a different icon in the taskbar than your application (.exe) icon is that the taskbar use the current form icon to display in the taskbar. A: After encountering the same problem, I resolved it by doing the following: Just stop your explorer.exe from task manager and rerun the explorer.exe again. A: As a commenter mentioned, you should set in the properties of the *.ico file: Copy to Output Dir: Copy if newer. This property is not absolutely required. I developed a winform application and tested it without icon. Then I created and added the icon. The icon showed when running with the VS debugger. I copied the bin/debug directory to another pc and there it ran with showing the icon. But the icon did not show on the development machine when the app started by clicking the *.exe file. Logout/login windows did not cure this. Change the Copy To Output Dir property on the icon file to Copy If Newer, and rebuild the application, did help. Now I can start the app by clicking the *.exe and the icon shows nicely. Conclusion: It is not always required to build the app with the icon file copied to the output directory, but with this measure you will increase your chances. A: Make sure that your *.ico file contains an icon of the proper size (like 16x16 for small task bars). A: Check this out for icon information and sizes it supports. Assuming this is just a simple error that you are getting check if your ico's are as per what is specified here http://msdn.microsoft.com/en-us/library/ms997636.aspx A: * *Copy your new icon in Project Properties --> resources --> icons *In your Main_Load function add: this.Icon = Properties.Resources.newIcon; A: I had the same problem and none of the above solved it. In my case, I had defined the icon different for two different langages (default language english and german). You can see this if there appear two resources files: FormX.resx and FormX.de.resx With the accepted answer only default icon was changed. But when running the application on my pc the german icon was used. So I had to change the icon for both resources. In Visual Studio you can change the current resource language by switching the language item (in the forms properties) from default to another language. A: I had the same problem. The "first place" mentioned by Patrick is about the file icon, i.e. the .exe aspect. The "second place" is about the form (in the upper left corner). Restarting windows file explorer seemed to be a satisfactory solution too. But all this didn't work today. I didn't restart the computer, by the way. This is what really displayed the new icon in the task bar: I realized that there was an old shortcut of the .exe on the desktop. Deleting the shortcut did the job.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Android: how to sum real values from Sqlite? I've got the following code to get a sum of real values (debt amounts stored in an SQlite DB: public double getsumdebt() { Cursor mCursor = db.rawQuery("SELECT SUM(CurrentAmount) FROM tblDebts", null); if(mCursor.moveToFirst()) { return mCursor.getDouble(0); } return mCursor.getDouble(0); } I am trying to return the sum of all the values in the "CurrentAmount" column and display it in a textview: DbAdapter db2 = new DbAdapter(this); double sum= new Double(db2.getsumdebt()); //sum = db2.getsumdebt(); bar.setText("Progress: "+currencysymbol +current +" / " + currencysymbol + sum); however, when I run the app in the emulator, I get a Force close during launch, with the following in the DDMS log: 09-26 19:01:19.098: ERROR/AndroidRuntime(677): FATAL EXCEPTION: main 09-26 19:01:19.098: ERROR/AndroidRuntime(677): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.evanrich.android.debtdestroyer/com.evanrich.android.debtdestroyer.mainActivity}: java.lang.NullPointerException 09-26 19:01:19.098: ERROR/AndroidRuntime(677): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663) 09-26 19:01:19.098: ERROR/AndroidRuntime(677): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) 09-26 19:01:19.098: ERROR/AndroidRuntime(677): at android.app.ActivityThread.access$2300(ActivityThread.java:125) 09-26 19:01:19.098: ERROR/AndroidRuntime(677): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) 09-26 19:01:19.098: ERROR/AndroidRuntime(677): at android.os.Handler.dispatchMessage(Handler.java:99) 09-26 19:01:19.098: ERROR/AndroidRuntime(677): at android.os.Looper.loop(Looper.java:123) 09-26 19:01:19.098: ERROR/AndroidRuntime(677): at android.app.ActivityThread.main(ActivityThread.java:4627) 09-26 19:01:19.098: ERROR/AndroidRuntime(677): at java.lang.reflect.Method.invokeNative(Native Method) 09-26 19:01:19.098: ERROR/AndroidRuntime(677): at java.lang.reflect.Method.invoke(Method.java:521) 09-26 19:01:19.098: ERROR/AndroidRuntime(677): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 09-26 19:01:19.098: ERROR/AndroidRuntime(677): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 09-26 19:01:19.098: ERROR/AndroidRuntime(677): at dalvik.system.NativeStart.main(Native Method) 09-26 19:01:19.098: ERROR/AndroidRuntime(677): Caused by: java.lang.NullPointerException 09-26 19:01:19.098: ERROR/AndroidRuntime(677): at com.evanrich.android.debtdestroyer.database.DbAdapter.getsumdebt(DbAdapter.java:106) 09-26 19:01:19.098: ERROR/AndroidRuntime(677): at com.evanrich.android.debtdestroyer.mainActivity.onCreate(mainActivity.java:73) 09-26 19:01:19.098: ERROR/AndroidRuntime(677): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 09-26 19:01:19.098: ERROR/AndroidRuntime(677): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627) 09-26 19:01:19.098: ERROR/AndroidRuntime(677): ... 11 more It looks like it's not able to sum the real values stored in the DB. Can anyone help me? FYI, this is my table constructor: private static final String DATABASE_CREATE = "CREATE TABLE IF NOT EXISTS tblDebts (_id integer primary key autoincrement, " + "Debt text not null, StartingAmount real, CurrentAmount real, " + "InterestRate real, DueDate integer, MinimumPayment real );"; Thanks. A: You have an NPE 19:01:19.098: ERROR/AndroidRuntime(677): Caused by: java.lang.NullPointerException 09-26 19:01:19.098: ERROR/AndroidRuntime(677): at com.evanrich.android.debtdestroyer.database.DbAdapter.getsumdebt(DbAdapter.java:106) 09-26 Which is line 106?
{ "language": "en", "url": "https://stackoverflow.com/questions/7560385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check referral url and re-direct based on that? I need to check referral url and if it's generated from Facebook redirect the user to a different webpage. How do I do that? A: Take a look in $_SERVER['HTTP_REFERER']. You can then use parse_url() to get the hostname, and compare the domain to a list of known Facebook domains. Beware, the referer isn't required, and isn't always set. So, don't use it as any kind of security. A: if (stripos(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST), 'facebook') !== FALSE) { header('Location: differentwebpage.html'); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7560386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generics: Creating parameterized class argument How does one get a parameterized Class object to be used as a method argument? class A<T> { public A(Class<T> c) { } void main() { A<String> a1 = new A<String>(String.class); // OK A<List<String>> a2 = new A<List<String>>(List<String>.class); // error A<List<String>> a3 = new A<List<String>>(Class<List<String>>); // error } } Why do I want to do that, you may ask? I have a parameterized class whose type is another parameterized class, and whose constructor requires that other class type as an argument. I understand that runtime classes have no information on their type parameters, but that shouldn't prevent me from doing this at compile time. It seems that I should be able to specify a type such as List<String>.class. Is there another syntax to do this? Here is my real usage case: public class Bunch<B> { Class<B> type; public Bunch(Class<B> type) { this.type = type; } public static class MyBunch<M> extends Bunch<List<M>> { Class<M> individualType; // This constructor has redundant information. public MyBunch(Class<M> individualType, Class<List<M>> listType) { super(listType); this.individualType = individualType; } // I would prefer this constructor. public MyBunch(Class<M> individualType) { super( /* What do I put here? */ ); this.individualType = individualType; } } } Is this possible? A: How about just cast? super((Class<List<M>>)List.class); Class literals are not going to have the type parameters that you want. A: Remember you will NOT get a List as a class in runtime, and the right approach would probably be using TypeToken as BalusC told you. Without TypeToken, you can't cast to List, but you can create something like this: public static class MyBunch2<List_M extends List<M>, M> extends Bunch<List_M> { Class<M> individualType; @SuppressWarnings("unchecked") public MyBunch2(Class<M> individualType) { super((Class<List_M>) List.class); this.individualType = individualType; } } Since List_M extends List<M> this is not as typesafe as you may wish, but maybe is nice enough. Creating an instance will be as ugly as writing MyBunch2<List<String>, String> a = new MyBunch2<List<String>, String>(String.class); but you can improve it with a factory method public static <M2> MyBunch2<List<M2>, M2> of(Class<M2> individualType){ return new MyBunch2<List<M2>, M2>(individualType); } and then write MyBunch2<List<String>, String> b = MyBunch2.of(String.class); If you are using eclipse, code assist will help you writing the ugly class MyBunch2, String> Of course, in runtime, this.type will be java.util.List, not java.util.List To get it right, go for TypeToken. ---Continuation--- You can even make another class public static class MyBunch3<M> extends MyBunch2<List<M>, M> { public MyBunch3(Class<M> individualType) { super(individualType); } } And then create instances as MyBunch3<String> c = new MyBunch3<String>(String.class); There must be a way to do that in just one class...but I can't figure it out
{ "language": "en", "url": "https://stackoverflow.com/questions/7560387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Persisting model data on form post when redisplaying the view for an invalid ModelState Simplified example: [HttpGet] public ActionResult Report(DateTime? date) { if (!date.HasValue) { date = DateTime.Now; } // Clear the ModelState so that the date is displayed in the correct format as specified by the DisplayFormat attribute on the model ModelState.Clear(); // Expensive call to database to retrieve the report data ReportModel model = DataAdapter.Convert(this.reportService.GetReport((DateTime)date)); // Store in TempData in case validation fails on HttpPost TempData["ReportModel"] = model; return View(model); } [HttpPost] public ActionResult Report(ReportModel model) { if (ModelState.IsValid) { return RedirectToAction("Report", new { date = model.Date }); } else { // Load the report from TempData, and restore again in case of another validation failure model = TempData["ReportModel"] as ReportModel; TempData["ReportModel"] = model; // Redisplay the view, the user inputted value for date will be loaded from ModelState return View(model); } } My question is, am I going about this the right way by storing the report data in TempData? The code seems a little strange especially reading from and then writing back to TempData in the HttpPost action method to ensure it persists the next request. Other options I can think of are: (1) Make another call to the service layer from the HttpPost action (I'd rather not make another database call because of a validation failure just to redisplay the form as it seems inefficient). I guess I could implement caching at the service layer to avoid the database round trip... (2) Use hidden inputs in the form (yuk!). (3) Store the most recently viewed report in session permanently. How is everyone else doing this sort of thing? What's the recommended practice? A: My question is, am I going about this the right way by storing the report data in TempData? No, absolutely not. Store something into TempData if and only if you redirect immediately afterwards as TempData survivces only a single redirect. If you store something into TempData in your GET action and then render a view, an AJAX request for example from this view would kill the TempData and you won't get the values back on your POST request. The correct pattern is the following (no TempData whatsoever): public ActionResult Report(DateTime? date) { if (!date.HasValue) { date = DateTime.Now; } // Clear the ModelState so that the date is displayed in the correct format as specified by the DisplayFormat attribute on the model ModelState.Clear(); // Expensive call to database to retrieve the report data ReportModel model = DataAdapter.Convert(this.reportService.GetReport((DateTime)date)); return View(model); } [HttpPost] public ActionResult Report(ReportModel model) { if (ModelState.IsValid) { return RedirectToAction("Report", new { date = model.Date }); } else { // Redisplay the view, the user inputted value for date will be loaded from ModelState // TODO: query the database/cache to refetch any fields that weren't present // in the form and that you need when redisplaying the view return View(model); } } (1) Make another call to the service layer from the HttpPost action (I'd rather not make another database call because of a validation failure just to redisplay the form as it seems inefficient). I guess I could implement caching at the service layer to avoid the database round trip... That's exactly what you should do. And if you have problems with optimizing those queries or concerns of hitting your or something on each POST request cache those results. Databases are hyper optimized nowadays and are designed to do exactly this (don't abuse of course, define your indexes on proper columns and performance should be good). But of course caching is the best way to avoid hitting the database if you have a very demanding web site with lots of requests and users. (2) Use hidden inputs in the form (yuk!). Yuk, I agree but could work in situations where you don't have lots of them. (3) Store the most recently viewed report in session permanently. No, avoid Session. Session is the enemy of scalable and stateless applications.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Core-Plot: Plotting only one point in a Scatterplot? I have a graph with two plots. One plot shows 10 data points and is static. The second plot should only show one data point that is a function of a slider selection. However, whenever I move the slider to compute the coordinates of the single data point, the plot generates a whole series of points until I stop sliding. I would like to remove this trail of dots and only show the one represented by the stopping position of the slider. Hope this makes sense. Here is what the graph looks like (erroneously): Oops, I'm too new to post an image, but I'm sure you get the picture. Here is a portion of the code in the slider IBAction: CPTScatterPlot *dotPlot = [[[CPTScatterPlot alloc] init] autorelease]; dotPlot.identifier = @"Blue Plot"; dotPlot.dataSource = self; dotPlot.dataLineStyle = nil; [graph addPlot:dotPlot]; NSMutableArray *dotArray = [NSMutableArray arrayWithCapacity:1]; NSNumber *xx = [NSNumber numberWithFloat:[estMonthNumber.text floatValue]]; NSNumber *yy = [NSNumber numberWithFloat:[estMonthYield.text floatValue]]; [dotArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:xx,@"x",yy,@"y", nil]]; CPTMutableLineStyle *dotLineStyle = [CPTMutableLineStyle lineStyle]; dotLineStyle.lineColor = [CPTColor blueColor]; CPTPlotSymbol *yieldSymbol = [CPTPlotSymbol ellipsePlotSymbol]; yieldSymbol.fill = [CPTFill fillWithColor:[CPTColor blueColor]]; yieldSymbol.size = CGSizeMake(10.0, 10.0); dotPlot.plotSymbol = yieldSymbol; self.dataForPlot = dotArray; I've tried to reload the plot with [dotPlot reloadData] and even tried to remove and add back the dotPlot but neither seems to work or, perhaps, I am putting the instructions in the wrong place or wrong sequence. Any advice would be greatly appreciated. A: Why are you recreating the scatterplot in the slider action? The only thing you should need to do in that method is update the array that provides the data for the second plot, and call reloadData. In any case, the reason you're getting the trail is that you keep creating new plots and adding them to the graph. The only code that should be in the slider method is: NSMutableArray *dotArray = [NSMutableArray arrayWithCapacity:1]; NSNumber *xx = [NSNumber numberWithFloat:[estMonthNumber.text floatValue]]; NSNumber *yy = [NSNumber numberWithFloat:[estMonthYield.text floatValue]]; [dotArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:xx,@"x",yy,@"y", nil]]; self.dataForPlot = dotArray; [graph reloadData]; A: I figured I was about a line of code away from a solution. As typically happens, I dreamt the solution. First I removed all the NSMutableArray *dotArray, etc, etc code from the slider method. Second I retained the [graph reloadData] in the slider method as Flyingdiver advised. Third, I modified the datasource methods as follows: #pragma mark - Plot datasource methods -(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot { return [dataForPlot count]; } -(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex: (NSUInteger)index { NSNumber *num = [[dataForPlot objectAtIndex:index] valueForKey:(fieldEnum == CPTScatterPlotFieldX ? @"x" : @"y")]; // Blue dot gets placed above the red actual yields if ([(NSString *)plot.identifier isEqualToString:@"Blue Plot"]) { if (fieldEnum == CPTScatterPlotFieldX) { num = [NSNumber numberWithFloat:[estMonthNumber.text floatValue]]; } if (fieldEnum == CPTScatterPlotFieldY) { num = [NSNumber numberWithFloat:[estMonthYield.text floatValue]]; } } return num; } Once again, thanks a million to Flyingdiver for the clues that solved my mystery. I learned a lot.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I grab, sort and display top commenters (PHP/MySQL)? Its been two days and I still can't figure this out: how do I retrieve all the users who commented on a given article, sort them in descending order by the number of times they commented and then display their username and number of times they commented (i.e., michael (17), laurie (14), jenny (10), dennis (6), etc.)? A: Without seeing the database structure, it's hard to say. But assuming it's something like this: Article * *Id *Content Comments * *Id *ArticleId *UserId *Comment The query would look something like this: SELECT UserId, COUNT(*) as CommentCount FROM Comments WHERE ArticleId = 1 GROUP BY UserId ORDER BY CommentCount DESC; Then you'll just need to do a JOIN on the user table to get the user's name.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: compare character with single space java i'm trying to test a program that will print "space" if the user enters a single space. but nothings displayed when i hit space then enter. my aim was really to count the number of spaces but i guess i'll just start with this. help me guys, thanks for any help here's my code import java.util.Scanner; public class The { public static void main(String args[])throws Exception { Scanner scanner = new Scanner(System.in); String input; System.out.println("Enter string input: "); input = scanner.next(); char[] charArray; charArray = input.toCharArray(); for(char c : charArray) { if(c == ' ') { System.out.println("space"); } else { System.out.println(" not space"); } } } } A: Scanner ignores spaces by default. Use BufferedReader to read input. A: By default, Scanner will ignore all whitespace, which includes new lines, spaces, and tabs. However, you can easily change how it divides your input: scanner.useDelimiter("\\n"); This will make your Scanner only divide Strings at new line, so it will "read" all the space characters up until you press enter. Find more customization options for the delimiters here. A: public class CountSpace { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String word=null; System.out.println("Enter string input: "); word = br.readLine(); String data[] ; int k=0; data=word.split(""); for(int i=0;i<data.length;i++){ if(data[i].equals(" ")) k++; } if(k!=0) System.out.println(k); else System.out.println("not have space"); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7560425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: VS 2010 pre-compile web sites with build process? VS 2010; TFS 2010; ASP.Net 4.0; Web Deployment Projects 2010; I am using the build process templates in order to do one-click deploys (for dev and QA only). I want my sites to be pre-compiled. I can do it with the command line, using: C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_compiler -v /site_name -p "C:\...\site_name" -f "C:\...\site_name1" and this works fine if I copy the files over from site_name1 to site_name... but is there an option in the IDE for this?? It seems really silly to have to do this from the command line. I've read a lot about different options, but none seem applicable to building with the build definitions. A: You can do this by adding the following to your .csproj file <PropertyGroup> <PrecompileVirtualPath>/whatever</PrecompileVirtualPath> <PrecompilePhysicalPath>.</PrecompilePhysicalPath> <PrecompileTargetPath>..\precompiled</PrecompileTargetPath> <PrecompileForce>true</PrecompileForce> <PrecompileUpdateable>false</PrecompileUpdateable> </PropertyGroup> <Target Name="PrecompileWeb" DependsOnTargets="Build"> <Message Importance="high" Text="Precompiling to $(PrecompileTargetPath)" /> <GetFullPath path="$(PrecompileTargetPath)"> <Output TaskParameter="fullPath" PropertyName="PrecompileTargetFullPath" /> </GetFullPath> <Message Importance="high" Text="Precompiling to fullpath: $(PrecompileTargetFullPath)" /> <GetFullPath path="$(PrecompilePhysicalPath)"> <Output TaskParameter="fullPath" PropertyName="PrecompilePhysicalFullPath" /> </GetFullPath> <Message Importance="high" Text="Precompiling from fullpath: $(PrecompilePhysicalFullPath)" /> <AspNetCompiler PhysicalPath="$(PrecompilePhysicalPath)" VirtualPath="$(PrecompileVirtualPath)" TargetPath="$(PrecompileTargetPath)" Debug="true" Force="$(PrecompileForce)" Updateable="$(PrecompileUpdateable)" FixedNames="true" /> Then in TFS2010's default template * *your build definition *Process tab *Advanced parameters section *MSBuild Arguments *set /target="PrecompileWeb" A: As it currently stands, I can not find any IDE option to pre-compile websites using the build process templates. I would love to be proved wrong, as using the command line aspnet_compiler requires us (in our setup) to crack open the actual build process template, which we are trying to avoid. I would love to be proved wrong! :) A: We have a website that is stored in TFS2010 as a Web application. I use a MSBuild command to deploy from TFS2010. If you open your project in VS2010 Team Explorer you will see there is a "Builds" option. If you add a build and in the process tab use a build argument like ...:/p:DeployOnBuild=True /p:DeployTarget=MsDeployPublish /p:CreatePackageOnPublish=True /p:MSDeployPublishMethod=RemoteAgent /p:MSDeployServiceUrl=http://111.111.111.111/msdeployagentservice /p:DeployIisAppPath=MySiteNameInIIS /p:UserName=myDomain\BuildUser /p:Password=BuildUserPassword In the Process tab where it says "Items to Build" you just point it to your .sln file (might work with a .cspro but then the syntax changes slightly) We have a TFS2010 server and I deploy a few of our sites to a dev, qa, pre-production or production IIS server. I do unit testing on the dev build and if the test fail then I do not deploy. The MSBuild command does the pre-compile, would that work for you? A: A setting for precompiling has been added. The following works in Visual Studio 2015 * *Open a solution *Right click on the project *Select "Publish..." *Go to settings, expand "File *Check "Precompile during Publishing"
{ "language": "en", "url": "https://stackoverflow.com/questions/7560429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL storing images in an enum column A thought experiment: You have a CMS that allows users to upload an image, and each page is stored as a row in the database. When a user uploads an image, it is converted into a base64 encoded string. The upload script then alters an ENUM column in a table and adds the base64 encoded string as an allowed enumerable value. In the front-end of the CMS, a SELECT statement be run on the page and the value of the ENUM column would be used to render out the image using a data url. Would writing a select statement in which the WHERE clause was matching against an enum value have any performance advantage over a query in which the WHERE clause was matching against a varchar column? ...And for the record, I know this is an absolutely terrible design for a CMS. I'm more interested in learning how MySQL would suffer (or thrive) with this setup. A: enum storage is actually just the index of the value you're storing the field. so you wouldn't be storing the base64 data, just its associated index in whatever parallel table mysql stores the enum values in. however, consider that the actual SQL query strings will have to contain the full base64 data, so you're needlessly increasing the size of the query string. Consider that a single pixel jpeg is still (around) 119bytes, and in base64 form takes up 160 characters. That's probably 150+ characters of wasted space. For even moderately sized images, your query strings would be even larger and could quite easily exceed mysql's max_allowed_packet setting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript Scope problem with OAuth I was wondering how to call waitForPin in this line: setTimeout(this.waitForPin, 100); File: // namespace our code window.App = {}; // my class (no Class.create in JQuery so code in native JS) App.Something = function() { }; // add functions to the prototype App.Something.prototype = { // automatically called initialize: function(name, sound) { this.wnd; this.config = { // some vars }; this.oauth = new OAuth(this.config); // attach event handlers, binding to 'this' object $("#request_token").click($.proxy(this.request_token, this)); }, request_token: function() { this.oauth.fetchRequestToken(this.openAuthoriseWindow, this.failureHandler); }, openAuthoriseWindow: function (url) { this.wnd = window.open(url, 'authorise'); setTimeout(this.waitForPin, 100); // how to call waitForPin here? }, waitForPin : function (scope) { // do sth } }; A: setTimeout(window.App.Something.waitForPin(scope), 100); A: The waitForPin function is attached to the prototype of Something. In order to access it create an instance of Something and call the method on that instance. Example setTimeout((new App.Something()).waitForPin, 100); A: setTimeout(this.waitForPin, 100); That's the correct way to do it. var Q = new App.Something; Q.openAuthoriseWindow(); Demo: http://jsfiddle.net/bBRPv/ A: What about this: setTimeout($.proxy(this.waitForPin, this), 100);
{ "language": "en", "url": "https://stackoverflow.com/questions/7560438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Xcode Internal error and no project opens Im on 10.6 and using xcode 3.2.6. On xcode launch (however i launch) i get an xcode "internal error' popup telling me: File: /SourceCache/DevToolsBase/DevToolsBase-1809/XcodeFoundation/Specifications/XCSpecification.m Line: 448 Object: Method: registerSpecificationProxiesFromPropertyListsInDirectory:recursively:inDomain:inBundle: path should be a string, but it is nil I can 'quit' or 'continue'. Continue launches xcode. The problem is that once open if i double click an .xcodeproj - nothing happens within xcode. To open a project I have to manually go file->open and navigate to the file. Google gives a couple of similar issues - including this one http://lists.apple.com/archives/mac-games-dev/2011/Mar/threads.html#00001 And i've tried everything i can think of with no joy, (Including down grading to the xcode on the OS DVD). A: It looks like it can be an issue with whatever particular version of Xcode that you have running. It might be a good idea to get the latest and greatest to see if it's an issue with the Xcode software itself. A: I was just hitting this and fixed it by removing a dead symlink at: ~/Library/Application Support/Developer/Shared/Xcode/Plug-ins This thread tipped me off (although it wasn't Airplay in my case).
{ "language": "en", "url": "https://stackoverflow.com/questions/7560440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java: List insert of more than one object with same HASH I'm having a bit of trouble with this one: I need to override the hashCode() and equals(), resulting in some objects being "equal". That's the intended behavior, but i have collateral problems with collections (has expected...): I work with an ArrayList, and inserting a duplicate object at a predefined index is not honored by the insert method. Instead it is inserted at the PREVIOUS position of the FIRST duplicated existing element. Let's say i have A B C And i insert duplicate of A at index >0... it will be inserted at index 0. ->A A B C Is this normal behavior? Thanks. EDIT: Object is inserted at right position. The TableViewer i'm using (org.eclipse.jface.viewers.TableViewer) was confusing me, because it defaults the edit to the FIRST duplicated element (and that makes some sense...). A: I think in the list it does not matter whether it's duplicate or not. I think it depends whether we are doing (as to where they will end up in the list) - list.add(obj); //or list.add(index, obj); //or list.set(index, obj); Other than that for a List, it's the order in which we add the object to the list. Because if we have list like List list = ArrayList(); Than it doesn't matter what type of object we add into it, so it does not make any difference whether we have the hashCode and equals defined or not. A: no that isn't normal. as far as i know, no implementation of java.util.List uses the equals() or hasCode() method can you provide some code sniped please? Maby you were looking at the first A you have prevously inserted? A // prevously inserted B C A // the new duplicat
{ "language": "en", "url": "https://stackoverflow.com/questions/7560441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }