text
stringlengths
8
267k
meta
dict
Q: Converting decision problems to optimization problems? (evolutionary algorithms) Decision problems are not suited for use in evolutionary algorithms since a simple right/wrong fitness measure cannot be optimized/evolved. So, what are some methods/techniques for converting decision problems to optimization problems? For instance, I'm currently working on a problem where the fitness of an individual depends very heavily on the output it produces. Depending on the ordering of genes, an individual either produces no output or perfect output - no "in between" (and therefore, no hills to climb). One small change in an individual's gene ordering can have a drastic effect on the fitness of an individual, so using an evolutionary algorithm essentially amounts to a random search. Some literature references would be nice if you know of any. A: Application to multiple inputs and examination of percentage of correct answers. True, a right/wrong fitness measure cannot evolve towards more rightness, but an algorithm can nonetheless apply a mutable function to whatever input it takes to produce a decision which will be right or wrong. So, you keep mutating the algorithm, and for each mutated version of the algorithm you apply it to, say, 100 different inputs, and you check how many of them it got right. Then, you select those algorithms that gave more correct answers than others. Who knows, eventually you might see one which gets them all right. There are no literature references, I just came up with it. A: Well i think you must work on your fitness function. When you say that some Individuals are more close to a perfect solution can you identify this solutions based on their genetic structure? If you can do that a program could do that too and so you shouldn't rate the individual based on the output but on its structure.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: JSF2 search box I develop a little app in javaee6 and jsf2. I want a search field with no button (just type and hit enter and give the result). I have a search method in a bean: public Book searchByTitle(String title) { this.book = bookFacade.searchByTitle(title); return book; } I want to call this method via jsf page (with parameter? Is it possible?), so I try to do this: <h:form> <h:inputText id="search" value="#{bookBean.searchString}"></h:inputText> <h:commandButton value="Search by title" action="#{bookBean.searchByTitle}"> <f:ajax execute="search" render="output"></f:ajax> </h:commandButton> <h2><h:outputText id="output" value="#{bookBean.book.title}"></h:outputText> </h2> </h:form> But it isn't work. What the proper way to do a search field in a jsf2 xhtml page? Edit: I tried to call the searchByTitle function with/without parameter. Thanks in advance! A: First step, If you are using a Java EE 6 compatible container (like GlassFish V3, Resin 4, JBoss AS 6 or 7, etc) and you have put something like commons-el.jar in your WEB-INF, remove it. This isn't needed and will only do harm. I want a search field with no button (just type and hit enter and give the result) In that case you also don't need the command button, but could go with something like this: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" > <h:head/> <h:body> <h:form> <h:inputText id="search" value="#{bookBean.searchString}" onkeypress="if (event.keyCode == 13) {onchange(event); return false;}" onchange="return event.keyCode !== undefined" > <f:ajax listener="#{bookBean.updateBook}" render="output" /> </h:inputText> <h2> <h:outputText id="output" value="#{bookBean.book}"/> </h2> </h:form> </h:body> </html> With the bookBean defined as: @ViewScoped @ManagedBean public class BookBean { private Map<String, String> exampleData = new HashMap<String, String>() {{ put("dune", "The Dune Book"); put("lotr", "The Lord of the Rings Book"); }}; private String searchString; private String book; public void updateBook(AjaxBehaviorEvent event) { book = exampleData.get(searchString); } public String getSearchString() { return searchString; } public void setSearchString(String searchString) { this.searchString = searchString; } public String getBook() { return book; } } In the Facelet, note the importance of the h:head element. Without it JSF does not know where to insert the required script for AJAX support in your response. In the example, the default onchange method that JSF generates when the f:ajax client behavior is added to so-called EditableValueHolders is called whenever the user presses enter. The listener attribute causes a method to be called on the AJAX event. Since searchString is already bound to a property of the backing bean, you don't have to provide it as argument to the listener method. A small disadvantage of this method is that the AJAX call will also be invoked when you change the value in the search field and simply click outside it. Update Adding an onchange handler to h:inputText fixed the above mentioned problem. This is automatically chained by JSF with the AJAX code from the client behavior. If it returns false, the chain is aborted and thus the AJAX call doesn't take place. The handler onchange="return event.keyCode !== undefined" will return false if the handler is triggered by the real change event; the event object will then not have the keyCode property. A: Use the following code to your jsf page: <h:form> <h:inputText id="search" value="#{bookBean.searchString}"></h:inputText> <h:commandButton value="Search by title" action="#{bookBean.searchByTitle(bookBean.searchString)}"> <f:ajax execute="search" render="output"></f:ajax> </h:commandButton> <h2><h:outputText id="output" value="#{bookBean.book.title}"></h:outputText> </h2> </h:form> And your java code: // note the return type is String. return type of methods which are to be called from actions of commandlinks or commandbuttons should be string public String searchByTitle(String title) { this.book = bookFacade.searchByTitle(title); return null; } EDIT: First, As far as parameter passing from jsf page is concerned, it should only be used if you want to pass a property of one bean to another bean. In your case, it is not required, since you are setting the property(searchString) of the same bean, and passing it to the very same bean. Your second question: you want that search works without search button: You can do this by adding a valueChangeListener to the h:inputText. And set the event attribute of f:ajax to blur <h:form> <h:inputText id="search" value="#{bookBean.searchString}" valueChangeListener="#{bookBean.searchStringChanged}"> <f:ajax execute="search" render="output" event="blur" /> </h:inputText> <h2><h:outputText id="output" value="#{bookBean.book.title}" /> </h2> </h:form> Also define the valueChangeListener method to bookBean java code: public void searchStringValueChanged(ValueChangeEvent vce) { searchByTitle((String) vce.getNewValue); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7544335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Benchmarking comet applications I'm currenctly working on my master's thesis. It's about real-time webapplications. Now I'd like to compare Node.js with for example long polling. I know some benchmarking tools such as ab, autobench etc., but these don't really test the application. Once they've made a request to the server, the request is handled and a new request is made. What I need is a benchmarking tool that will 'stay' on the webpage for a longer time so it'll simulate real people. For example: I've made a demo chat in both Node.js and long polling (PHP). Now I want to test this with 100 simultaneous that stay on the chat for about 30 seconds. Does anyone has some suggestions for me how I can reach this goal? I thank you in advance! A: Now I'd like to compare Node.js with for example long polling. Long polling itself is a platform agnostic web push technology, so you can compare long polling application made in node.js with similar application made in PHP for example. What I need is a benchmarking tool that will 'stay' on the webpage for a longer time so it'll simulate real people. You can create another server application which would simulate client connections, however this application shouldn't be hosted on the same machine as your long poll server application in order to have "near real" latency between clients and server. Even this approach may not give you exact environment as you would have with "real human" clients (since server application simulating client connection would be on the same origin and also because of famous quote "there is no test like production"), but it can give you rough environment to test your long polling server to gather some benchmark data. For example socket.io has this kind of application for simulation of a variety of browser transports.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery Cycle with Cufon Pager So, I am using jQuery with Cufon and jQuery Cycle. What I want, is the pager of Cycle to have Cufon fonts. Below is my JS var pagerclass; $(document).ready(function() { $("#slider").cycle({ fx: "scrollHorz", timeout: 7000, pager: "#pager ul", pagerAnchorBuilder: function(idx, slide) { if(idx==0) pagerclass = "first"; else if(idx==2) pagerclass="last"; else pagerclass=""; Cufon.replace("#pager ul"); return "<li class='"+pagerclass+"'><a href='#'>"+slide.title+"</a></li>"; } }); }); So the Cufon.replace("#pager ul");-line is not working, because it doesn't replace the last item. The last item gets returned after that. Is there any way to do something in jQuery Cycle after the Pager is built? That would solve the problem, I think. A: $(function() { function cufrep() { Cufon('#pager ul'); } $("#slider").cycle({ fx: "scrollHorz", timeout: 7000, pager: "#pager ul", after: cufrep, // after pagerAnchorBuilder: function(idx, slide) { if(idx==0) pagerclass = "first"; else if(idx==2) pagerclass="last"; else pagerclass=""; Cufon.replace("#pager ul"); return "<li class='"+pagerclass+"'><a href='#'>"+slide.title+"</a></li>"; } }); }); Cufon has an after function which fires after.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Embedding videos while hiding the source - is that possible at all? Here is the code that I use to embed video from "YouTube" to my blog: <object type="application/x-shockwave-flash" width="460" height="390" data="http://www.youtube.com/v/Hg8Fa_EUQqY&amp;feature&amp;rel=0"><param name="movie" value="http://www.youtube.com/v/Hg8Fa_EUQqY&amp;feature&amp;rel=0" /><param name="wmode" value="transparent" /><param name="quality" value="high" /></object></p> I wonder if it's possible to embed videos into your blog, but hide the source? I mean I don't want people to know that I have uploaded this video on "YouTube" or at least I don't want them to know where exactly on the "YouTube" I have uploaded my videos. Is it possible at all? Embedding videos while hiding the source - is that possible at all? A: If someone is sufficiently motivated, they will always be able to tell where their computer is loading the video from. But to answer your question, no, the HTML source will always be available to the user. After all, if their browser is allowed to see the source, it will happily provide this to the user. And if the browser isn't allowed to see the source, it can't show the user their video (because it doesn't know there is one, because it didn't see the HTML source).
{ "language": "en", "url": "https://stackoverflow.com/questions/7544346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C packing Integer into a buffer RFC 4506 I'm trying to implement this RFC 4.1. Integer An XDR signed integer is a 32-bit datum that encodes an integer in the range [-2147483648,2147483647]. The integer is represented in two's complement notation. The most and least significant bytes are 0 and 3, respectively. Integers are declared as follows: int identifier; (MSB) (LSB) +-------+-------+-------+-------+ |byte 0 |byte 1 |byte 2 |byte 3 | INTEGER +-------+-------+-------+-------+ <------------32 bits------------> and here's my code I need to know if there is a better way to do that ? void packInteger(char *buf,long int i) { if(i>=0) { *buf++ = i>>24; *buf++ = i>>16; *buf++ = i>>8; *buf++ = i; } if(i<0) { i = i*-1; i = 1 + (unsigned int)(0xffffffffu - i); buf[0] = (unsigned int)i>>24; buf[1] = (unsigned int)i>>16; buf[2] = (unsigned int)i>>8; buf[3] = (unsigned int)i; } } long int unpackInteger(char *buf) { unsigned long int i2 = ((unsigned long int)buf[0]<<24) | ((unsigned long int)buf[1]<<16) | ((unsigned long int)buf[2]<<8) | buf[3]; long int i; // change unsigned numbers to signed if (i2 <= 0x7fffffffu) { i = i2; } else { i = -1 - (long int)(0xffffffffu - i2); } return i; } int main(void) { char buf[4]; packInteger(buf,-31); printf("%u %u %u %u\n",buf[0],buf[1],buf[2],buf[3]); long int n = unpackInteger(buf); printf("%ld",n); return 0; } if someone on 64 bit system is it working or noT ? version 2 void packInteger(unsigned char *buf,long int i) { unsigned long int j = i; // this will convert to 2's complement *buf++ = i>>24; *buf++ = i>>16; *buf++ = i>>8; *buf++ = i; } A: You should be using unsigned char for your buffers. A cast to unsigned in C performs the mathematical equivalent of a conversion to 2s complement, so your pack function can be simplified: void packInteger(unsigned char *buf, long int i) { unsigned long u = i; buf[0] = (u >> 24) & 0xffUL; buf[1] = (u >> 16) & 0xffUL; buf[2] = (u >> 8) & 0xffUL; buf[3] = u & 0xffUL; } Your unpack function seems fine (with the change to unsigned char).
{ "language": "en", "url": "https://stackoverflow.com/questions/7544350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: monte carlo integration on a R^5 hypercube in MATLAB I need to write MATLAB code that will integrate over a R^5 hypercube using Monte Carlo. I have a basic algorithm that works when I have a generic function. But the function I need to integrate is: ∫dA A is an element of R^5. If I had ∫f(x)dA then I think my algorithm would work. Here is the algorithm: % Writen by Jerome W Lindsey III clear; n = 10000; % Make a matrix of the same dimension % as the problem. Each row is a dimension A = rand(5,n); % Vector to contain the solution B = zeros(1,n); for k = 1:n % insert the integrand here % I don't know how to enter a function {f(1,n), f(2,n), … f(5n)} that % will give me the proper solution % I threw in a function that will spit out 5! % because that is the correct solution. B(k) = 1 / (2 * 3 * 4 * 5); end mean(B) A: In any case, I think I understand what the intent here is, although it does seem like somewhat of a contrived exercise. Consider the problem of trying to find the area of a circle via MC, as discussed here. Here samples are being drawn from a unit square, and the function takes on the value 1 inside the circle and 0 outside. To find the volume of a cube in R^5, we could sample from something else that contains the cube and use an analogous procedure to compute the desired volume. Hopefully this is enough of a hint to make the rest of the implementation straightforward. A: I'm guessing here a bit since the numbers you give as "correct" answer don't match to how you state the exercise (volume of unit hypercube is 1). Given the result should be 1/120 - could it be that you are supposed to integrate the standard simplex in the hypercube? The your function would be clear. f(x) = 1 if sum(x) < 1; 0 otherwise A: %Question 2, problem set 1 % Writen by Jerome W Lindsey III clear; n = 10000; % Make a matrix of the same dimension % as the problem. Each row is a dimension A = rand(5,n); % Vector to contain the solution B = zeros(1,n); for k = 1:n % insert the integrand here % this bit of code works as the integrand if sum(A(:,k)) < 1 B(k) = 1; end end clear k; clear A; % Begin error estimation calculations std_mc = std(B); clear n; clear B; % using the error I calculate a new random % vector of corect length N_new = round(std_mc ^ 2 * 3.291 ^ 2 * 1000000); A_new = rand(5, N_new); B_new = zeros(1,N_new); clear std_mc; for k = 1:N_new if sum(A_new(:,k)) < 1 B_new(k) = 1; end end clear k; clear A_new; % collect descriptive statisitics M_new = mean(B_new); std_new = std(B_new); MC_new_error_999 = std_new * 3.921 / sqrt(N_new); clear N_new; clear B_new; clear std_new; % Display Results disp('Integral in question #2 is'); disp(M_new); disp(' '); disp('Monte Carlo Error'); disp(MC_new_error_999);
{ "language": "en", "url": "https://stackoverflow.com/questions/7544357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Confusion on Glassfish V3, Jboss, SOA supporting, WSO2(embeded Tomcat) I'm so confused for developing SOA applications in Java EE: * *Can "Glassfish V3 Open Source Edition" support ESB(SOA)? I must add external module on it? if yes, is it open source too or not? ---or--- if I want to use Glassfish I should buy the commercial Oracle Glassfish? *What is JBoss's behaviour? Is it possible to run ESB(SOA) on community JBoss open-source? What is Jboss SOA Platform? is it commercial? does have Jboss it's own commercial edition for enterprise SOA or with it's open-source editions we can do it? *What is WSO2? it works on which application-servers? I read somewhere it has it's own embedded tomcat server?! unless Tomcat be a Java EE container?!!!!! of course not. Please help me and bring me out of this confusion. A: Let me answer the WSO2 part- WSO2 has a set of products (all totally open source) which supports all aspects of SOA: * *Writing and hosting services (App Server, Data Services Server, Business Rules Server etc.) *Mediating them in various ways (ESB), composing services to make more services (Business Process Server and Mashup Server) *Managing/governing them (Governance Registry, Identity Server, Business Activity Monitor). WSO2 products use embedded Tomcat as its primary runtime for standalone execution but can also run within other app servers. See http://wso2.com/products for more info. As someone else said SOA is a design paradigm not a choice of technology. Yes it is possible to do SOA without EJBs or Web services even .. CORBA for example. A: Here's what I know on this: Glassfish v3 support EJB3.1 out of the box, you can use them per your pleassing JBoss Application Server version 6 also support EJB 3.1 out of the box. As always, JBoss offers some custom non-spec config options, some of which intervene just a little bit over the EJB3.1 specs, but in all it's ok. Yes, Tomcat by itself is not a full Java EE Application Server as it doesn't have (amongst others) an EJB Container. However one can be added to it via 3rd party modules
{ "language": "en", "url": "https://stackoverflow.com/questions/7544360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Replacement for DWR DWR is mainly used for handling AJAX responses from server.. So i wanted to know other similar technologies, which would make AJAX handling easy like calling a Java method from within Javascript and pasting the response in html code. I know jQuery has AJAX methods, but so not think it can call and handle specific Java methods. A: You can give Google Web Toolkit a try, at this point it's mature enough to have all the decent features and no annoying bugs: http://code.google.com/intl/fr-FR/webtoolkit/ Now GWT is not a straight out replacement for DWR. It's default usage is to have everything coded in Java (client UI and server side). This might be something prefferable to DWR's way of doing things. However if it's not, and you'd like to use GWT in a fashion more similar to DWR, you can have your javascript code / functions and your GWT Java classes, and you can call js functions from Java via GWT's JSNI API: http://code.google.com/intl/fr-FR/webtoolkit/doc/latest/DevGuideCodingBasicsJSNI.html A: I know jQuery has AJAX methods, but so not think it can call and handle specific Java methods I use spring with jquery, each request can be mapped to a specific method. I prefer it over dwr. Ajax and Spring. A: You can use JSON-RPC
{ "language": "en", "url": "https://stackoverflow.com/questions/7544362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What are these options in qgit? I have installed git in Ubuntu and downloaded the Hadoop repository using the below command. git pull git://git.apache.org/hadoop-common.git Then I installed qgit (GUI for GIT), when I open the above repository in qgit the following screen comes up. Can someone explain the meaning of the different fields? Also, using the 'Git tree' how can I view the code for different branches, tags etc? A: The top two options in that dialog are asking you for a range of commits to display from the commit graph. The default value for the most recent commit is HEAD, which represents the branch tip (or commit) that you are currently at. The "bottom", or the oldest value has defaulted to one of the tags in your repository. The other options in that dialog all have tooltips explaining what they do, but just to add a little more detail: * *working dir: If selected, this shows you the state of your working tree at the top of the displayed history in addition to all the committed versions. *all branches: If selected this won't just show you commits that are reachable working back from HEAD, but also those reachable from every branch. *whole history: If selected, the range options at the top are disabled, and you see the history right back to the root commit(s) in the repository. The tips of branches in the "rev list" pane, which shows you the commit graph, are labelled with a box with a green background, while remote-tracking branches have a beige background. The "Git tree" pane shows you the state of the tree at the commit that you've selected. If you navigate to a file in that tree and double click on it, you'll see the content of the file at that version and an indication of who most recently changed each line before that version.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Drupal 7, Creating widget with ImageField and a Textarea Can anyone help me figure out how can i create a widget(Field API) which will contain an image(i want to to be an ImageField) and a textarea in Drupal 7? Unfortunately i cannot find any tutorial how to do this on google. Thanks! A: There's no tutorial as such that I know of, but have a look at the Drupal Examples Module, there's a module within called field_example with all of the info you need. On a very basic level you want to do this: * *Implement hook_field_schema() in your module's .install file to define what columns are going to be held in your field table (probably file ID (fid), alternative text for the image, title text for the image and the contents of the text area in your case). *Implement hook_field_info() to define your field type. *Implement hook_field_is_empty() to provide a way for Drupal to know that a particular instance of a field is empty and can be removed when the entity is saved. *Implement hook_field_formatter_info() to tell Drupal the different ways the content of your field can be displayed. *Implement hook_field_formatter_view to define exactly how those field formatters defined in step 4 will be outputted. *Implement hook_field_widget_info to define the different input widgets for your field. *Implement hook_field_widget_form to define the elements that will make up the widget for your field. Once you've jumped through all of those hoops (it doesn't actually take that long to implement, most functions are just a few lines of code), enable the module and start adding your new field to entities! A: you should start from this 2 hook to create the widget. then you should start creating the compound field hook_field_widget_info() hook_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) here are some link to create custom field and widget http://www.phase2technology.com/node/1495/ http://drupal.org/project/dnd_character A: Sorry for not closing this. but the real answer to this is to use Field Collection module - drupal.org/project/field_collection. You add multiple field to this. When i asked this question i was new to D7 and in D6 we had to write this by hand. great module! A: Try taking a look at this tutorial. Most other ones the writer concentrates on sounding clever, this one has screenshots and is very clear and concise.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Debugging multiple forked processes in *nix Are there any easy ways to debug forked child processes in *nix, without having to sleep them and create new gdb instances, using ps to get the child's pid? Are there any debuggers that do this? A: You can already do this using gdb. Here is how: (gdb) set detach-on-fork off (gdb) set follow-fork-mode child (gdb) catch fork # use breakpoint if catch fork not available Then at some point you will reach your fork. Jump over it and gdb should inform you there is a new process. [New process 813] At this point you should view the "inferiors" (gdb) info inferiors Num Description Executable * 2 process 813 /home/cnicutar/fork 1 process 810 /home/cnicutar/fork To switch to a different inferior, use (gdb) inferior 1 [Switching to inferior 1 [process 810] (/home/cnicutar/fork)] [Switching to thread 1 (process 810)] (gdb) info inferiors Num Description Executable 2 process 813 /home/cnicutar/fork * 1 process 810 /home/cnicutar/fork Hope this helps :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7544376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Hive: dynamic partition adding to external table I am running hive 071, processing existing data which is has the following directory layout: -TableName - d= (e.g. 2011-08-01) - d=2011-08-02 - d=2011-08-03 ... etc under each date I have the date files. now to load the data I'm using CREATE EXTERNAL TABLE table_name (i int) PARTITIONED BY (date String) LOCATION '${hiveconf:basepath}/TableName';** I would like my hive script to be able to load the relevant partitions according to some input date, and number of days. so if I pass date='2011-08-03' and days='7' The script should load the following partitions - d=2011-08-03 - d=2011-08-04 - d=2011-08-05 - d=2011-08-06 - d=2011-08-07 - d=2011-08-08 - d=2011-08-09 I havn't found any discent way to do it except explicitlly running: ALTER TABLE table_name ADD PARTITION (d='2011-08-03'); ALTER TABLE table_name ADD PARTITION (d='2011-08-04'); ALTER TABLE table_name ADD PARTITION (d='2011-08-05'); ALTER TABLE table_name ADD PARTITION (d='2011-08-06'); ALTER TABLE table_name ADD PARTITION (d='2011-08-07'); ALTER TABLE table_name ADD PARTITION (d='2011-08-08'); ALTER TABLE table_name ADD PARTITION (d='2011-08-09'); and then running my query select count(1) from table_name; however this is offcourse not automated according to the date and days input Is there any way I can define to the external table to load partitions according to date range, or date arithmetics? A: I have a very similar issue where, after a migration, I have to recreate a table for which I have the data, but not the metadata. The solution seems to be, after recreating the table: MSCK REPAIR TABLE table_name; Explained here This also mentions the "alter table X recover partitions" that OP commented on his own post. MSCK REPAIR TABLE table_name; works on non-Amazon-EMR implementations (Cloudera in my case). A: The partitions are a physical segmenting of the data - where the partition is maintained by the directory system, and the queries use the metadata to determine where the partition is located. so if you can make the directory structure match the query, it should find the data you want. for example: select count(*) from table_name where (d >= '2011-08-03) and (d <= '2011-08-09'); but I do not know of any date-range operations otherwise, you'll have to do the math to create the query pattern first. you can also create external tables, and add partitions to them that define the location. This allows you to shred the data as you like, and still use the partition scheme to optimize the queries. A: I do not believe there is any built-in functionality for this in Hive. You may be able to write a plugin. Creating custom UDFs Probably do not need to mention this, but have you considered a simple bash script that would take your parameters and pipe the commands to hive? Oozie workflows would be another option, however that might be overkill. Oozie Hive Extension - After some thinking I dont think Oozie would work for this. A: I have explained the similar scenario in my blog post: 1) You need to set properties: SET hive.exec.dynamic.partition=true; SET hive.exec.dynamic.partition.mode=nonstrict; 2)Create a external staging table to load the input files data in to this table. 3) Create a main production external table "production_order" with date field as one of the partitioned columns. 4) Load the production table from the staging table so that data is distributed in partitions automatically. Explained the similar concept in the below blog post. If you want to see the code. http://exploredatascience.blogspot.in/2014/06/dynamic-partitioning-with-hive.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7544378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: eclipse 3.7.1 update error I'm currently using the Eclipse Indigo 3.7 IDE for Java Developers.So today I tried to update it to the latest 3.7.1 but during the update process a error downloading0 with Comparison method violates its general contract! pops out and the whole update process stucks at that process. Can someone help me with this problem? I'm using both JDK 7x64 and JRE 7x64 A: Due to lack of information, I can suggest it's related to eclipse bug 317785, if you are using Java 1.7. Possible workarounds: * use JRE6 OR * when using JRE7, theres a small rarely documented feature set system property java.util.Arrays.useLegacyMergeSort=true This should use old implementation and should not bring up the bug A: I was able to fix this problem by using this workaround taken from the link suggested by 4e6 and VonC (bugs.eclipse.org/bugs/show_bug.cgi?id=317785): To clarify comment #22 for those on JRE7 who can't upgrade to 3.7.1 because of this bug: Add the following line to your eclipse.ini: -Djava.util.Arrays.useLegacyMergeSort=true Then run the update to 3.7.1 from inside Eclipse again, it should succeed now. Afterwards, you should be able to drop that line from eclipse.ini again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: AppleScript cURL and parse URL I am working on a Automator workflow, I am passing list of URLs to the "Run Applescript" and I need to fetch the contents of on each page, concatenate and pass it to a BBedit (or any other text editor). on run {input, parameters} tell application "BBEdit" activate set astid to AppleScript's text item delimiters set startHere to "<tbody>" set stopHere to "</tbody>" repeat with anItem in input set blurb0 to (do shell script "curl " & anItem) set AppleScript's text item delimiters to startHere set blurb1 to text item 2 of blurb0 set AppleScript's text item delimiters to stopHere set blurb2 to text item 1 of blurb1 set AppleScript's text item delimiters to astid return blurb2 beep end repeat end tell end run The current code only properly gets only the contents from first URL. Can anybody fix this? A: This subroutine may be what you need (if you're using Safari)... on getSource(this_URL) tell application "Safari" activate set the URL of the current tab of document 1 to this_URL set the |source| to the source of the front document end tell tell application "TextEdit" activate set the text of the front document to the source end tell quit application "Safari" end getSource Call it using: repeat with anItem in input getSource(input) end repeat I hope this helps! A: Because you are inside the repeat with anItem in input loop it does all your work for the first item and the return exits the loop and in fact the whole Automator action. I think you have never heard the beep from your script ;-) On the other side I'm wondering why you want BBEdit to do the cUrl and sort work for you. All called handlers don't belong to BBEdit... I think your handler should look like this: on run {input, parameters} -- define a few parameters set astid to AppleScript's text item delimiters set startHere to "<tbody>" set stopHere to "</tbody>" -- define a list to store all found content set allFoundContent to {} repeat with anItem in input set blurb0 to (do shell script "curl " & anItem) set AppleScript's text item delimiters to startHere set blurb1 to text item 2 of blurb0 set AppleScript's text item delimiters to stopHere -- put the found content at the end of the list set end of allFoundContent to text item 1 of blurb1 set AppleScript's text item delimiters to astid end repeat -- from here you have three possibilities: -- 1. return the list to next Automator action (uncomment the next line): -- return allFoundContent -- 2. concatenate the list with a delimiter you like (here return & "------" & return) -- and give it to your preferred text editor from this point (uncomment the next lines): -- set AppleScript's text item delimiters to return & "------" & return -- tell application "TextEdit" -- make new document with properties {text: allFoundContent as text} -- end tell -- set AppleScript's text item delimiters to astid -- 3. concatenate the list with a delimiter you like (here return & "------" & return) -- and give it to the next workflow step, maybe a BBEdit action waiting for a string? (uncomment the next lines): -- set AppleScript's text item delimiters to return & "------" & return -- set returnString to allFoundContent as text -- set AppleScript's text item delimiters to astid -- return returnString -- Next decision (for choice 1 or 2): -- What do you want to give to next Automator action? -- you can pass your input (the given URLs) (uncomment next line): -- return input -- or your result list (uncomment next line): -- return allFoundContent end run Greetings, Michael / Hamburg
{ "language": "en", "url": "https://stackoverflow.com/questions/7544385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reversing a string in C using pointers? Language: C I am trying to program a C function which uses the header char *strrev2(const char *string) as part of interview preparation, the closest (working) solution is below, however I would like an implementation which does not include malloc... Is this possible? As it returns a character meaning if I use malloc, a free would have to be used within another function. char *strrev2(const char *string){ int l=strlen(string); char *r=malloc(l+1); for(int j=0;j<l;j++){ r[j] = string[l-j-1]; } r[l] = '\0'; return r; } [EDIT] I have already written implementations using a buffer and without the char. Thanks tho! A: No - you need a malloc. Other options are: * *Modify the string in-place, but since you have a const char * and you aren't allowed to change the function signature, this is not possible here. *Add a parameter so that the user provides a buffer into which the result is written, but again this is not possible without changing the signature (or using globals, which is a really bad idea). A: You may do it this way and let the caller responsible for freeing the memory. Or you can allow the caller to pass in an allocated char buffer, thus the allocation and the free are all done by caller: void strrev2(const char *string, char* output) { // place the reversed string onto 'output' here } For caller: char buffer[100]; char *input = "Hello World"; strrev2(input, buffer); // the reversed string now in buffer A: You could use a static char[1024]; (1024 is an example size), store all strings used in this buffer and return the memory address which contains each string. The following code snippet may contain bugs but will probably give you the idea. #include <stdio.h> #include <string.h> char* strrev2(const char* str) { static char buffer[1024]; static int last_access; //Points to leftmost available byte; //Check if buffer has enough place to store the new string if( strlen(str) <= (1024 - last_access) ) { char* return_address = &(buffer[last_access]); int i; //FixMe - Make me faster for( i = 0; i < strlen(str) ; ++i ) { buffer[last_access++] = str[strlen(str) - 1 - i]; } buffer[last_access] = 0; ++last_access; return return_address; }else { return 0; } } int main() { char* test1 = "This is a test String"; char* test2 = "George!"; puts(strrev2(test1)); puts(strrev2(test2)); return 0 ; } A: reverse string in place char *reverse (char *str) { register char c, *begin, *end; begin = end = str; while (*end != '\0') end ++; while (begin < --end) { c = *begin; *begin++ = *end; *end = c; } return str; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7544387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: "sys.getrefcount()" return value Why does sys.getrefcount() return 3 for every large number or simple string?Does that mean that 3 objects reside somewhere in the Program?Also,why doesn't setting x=(very large number) increase that object's ref count?Do those 3 ref counts result from my call to getrefcount? Thank you for clarifying this. for instance: >>> sys.getrefcount(4234234555) 3 >>> sys.getrefcount("testing") 3 >>> sys.getrefcount(11111111111111111) 3 >>> x=11111111111111111 >>> sys.getrefcount(11111111111111111) 3 A: * *Small strings and integers are cached by Python to save on object construction cost. *The interactive Python interpreter holds a temporary reference to each literal that you enter. Compare getrefcount('foobar') with getrefcount('foo' + 'bar'). (In the latter case, the interpreter has references to 'foo' and 'bar'.) *From the manual: The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount(). A: Large integer objects are not reused by the interpretor, so you get two distinct objects: >>> a = 11111 >>> b = 11111 >>> id(a) 40351656 >>> id(b) 40351704 sys.getrefcount(11111) always returns the same number because it measures the reference count of a fresh object. For small integers, Python always reuses the same object: >>> sys.getrefcount(1) 73 Usually you would get only one reference to a new object: >>> sys.getrefcount(object()) 1 But integers are allocated in a special pre-malloced area by Python for performance optimization, and I suspect the extra two references have something to do with this. It's implemented in longobject.c in CPython. (Update: link to Python3.) I do not claim to understand what's really going on. I think there are several things at work that cache temporary references: print sys.getrefcount('foo1111111111111' + 'bar1111111111111') #1 print sys.getrefcount(111111111111 + 2222222222222) #2 print sys.getrefcount('foobar333333333333333333') #3 A: It seems that when you pass a direct number as an argument to sys.getrefcount, you have 3 references: * *1 for the object itself (logical); *1 (temporary) for the object passed as argument to sys.getrefcount; *and I would suppose 1 (temporary) for the interpreter, which I suppose converts the raw number (or string, or anything else) into an interpretable object. For instance, let's consider this: >>> sys.getrefcount(123456) 3 >>> a = 123456 >>> sys.getrefcount(a) 2 I don't really know what happens in the mind of Python, but it is interesting nonetheless. I can only guess the raw integer (ref #1) is temporarily converted into an int object (ref #2), which is then passed as an argument to sys.getrefcount (ref #3).
{ "language": "en", "url": "https://stackoverflow.com/questions/7544395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Android Different Ways To Add LayoutParams I noticed there are two ways to add LayoutParams programmatically to any view and am curious to ask do they have different meanings as well. Example 1 In this example, setting LayoutParams directly to the button. LinearLayout parent = new LinearLayout(this); Button btnNew = new Button(this); LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); button.setLayoutParams(params); parent.addView(btnNew); Example 2 In this example adding layoutparams to button when it's being added to the parent view. LinearLayout parent = new LinearLayout(this); Button btnNew = new Button(this); LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); parent.addView(btnNew, params); What's different in both? A: There is no difference. If you check the android source code, it specifies that if no layout params are specified, the defualts params of the view group are set. When you use the method addView(child,params); It calls another method named addViewInner which just sets the params object to the child object. The source code from the ViewGroup.java can be seen here
{ "language": "en", "url": "https://stackoverflow.com/questions/7544403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What OO structure should I use to describe animal's behaviors? I have a Java assignment in which my professor requires me to use a LeJOS NXT to make a robot that simulates a certain animal's behaviors. I chose to develop a dragon. All the possible behaviors that I've come up so far is: * *Turning around if it's too close to an obstacle. *Going to sleep when battery is low. *Pushing an object if touches. *If it's too bright, find a dark spot. *etc. I'm now quite confused because I don't know whether to develop it sequentially in one class or to split all the dragon's behaviors into different classes. Please have a look at my explanation below. Instead of writing everything inside one class like this: Dragon.java public class Dragon { LightSensor ls = new LightSensor public static main(String args[]) { while (!BUTTON.Escape.IsPressed()) { if (this.closeToObject()) { this.turnAround(); } // more conditions } } private boolean closeToObject() { //TODO return false; } private void turnAround() { //TODO } //... more methods } However, I want to make it appears to be more object-oriented as the course is meant to help us gain more OOP skills. So what my second option is to create action classes that extends Dragon's Behavior abstract class like this (roughly): Dragon.java public class Dragon { Detect detect = new Detect(); // carry all the detection methods: distance, sound, etc. TurnAround turnAround = new TurnAround(); public static main(String args[]) { while (!BUTTON.Escape.IsPressed()) { if (detect.tooCloseToObject()) { turnAround.prepare(); // beep beep alert turnAround.setDerection(true); // e.g. turn right turnAround.turn(); } } } } DragonBehaviors.java abstract class DragonBehavior { abstract void prepare(); public void setDirection(boolean direction) { //... } } TurnAround.java public class TurnAround extends DragonBehaviors { String direction; public void TurnAround() {} public void prepare() { // sound alert } public void setDirection(boolean direction) { if (direction) this.direction = "Right"; else this.direction = "Left"; } public void turn() { // TODO } } The code above is roughly a draft, don't focus on it. Eventually, I want to ask if my idea about the OO structure above is reasonable, otherwise it's much easier to develop the whole thing in one class, but it has nothing to do with OOP. I also have several group members to make the code finished, so I think it could be better if we share the classes to develop in an OOP way. Which way should I go in this circumstance? I appreciate all the comments (: A: Your choice of extracting different actions into classes with common super class is IMHO reasonable. However I would make Dragon class only aware of the DragonBehavior abstract class, not the subclasses. This way you can add and remove behaviours to the dragon without actually changing it. How? Look at Chain-of-responsibility pattern - each behaviour has its place in the chain. If behaviour decides to activate itself (i.e. perform something) it may or may not allow further behaviours to be triggered. Moreover, you can and remove behaviours (even at runtime!) and rearrange them to change the precedence (is pushing the obstacle more or less important than going to sleep?).
{ "language": "en", "url": "https://stackoverflow.com/questions/7544404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: About NSException from "NSKeyedUnarchiver unarchiveObjectWithFile :" NSArray *t_annos; @try { NSLog(@" --- pointer before = %ld --- ", (long) t_annos); t_annos = [NSKeyedUnarchiver unarchiveObjectWithFile : d_path]; NSLog(@" --- pointer after = %ld --- ", (long) t_annos); } @catch (NSException *e) { NSLog(@" --- e caught ---"); t_annos = nil; } Please consider the above statements, the situation is : 1 According to documentation, an exception should be raised if d_path does not point to a valid archive. But no exception is caught even if d_path is deliberately set with an invalid path. 2 Have tested the code on both the xcode simulator and a test devise (iphone). Although both the simulator and the phone devise do not catch any exceptions, the phone unarchives the array as expected while on the simulator the program stops with an output : "Program received signal : "EXC_BAD_ACCESS"" at the Debugger Console. 3 The "bad access" error should have come at the "unarchiveObjectWithFile" statement since the program stops after the first NSLog output. 4 When try with a single NSString object archived and unarchive, both the simulator and the test device have no problem. But there is still no exception caught even when the path is wrong. There may be something missing on my part, hope that somebody knowledgable can help. A: According to the documentation, the exception is thrown only when there exists a file at the path and is not an archive created by NSKeyedArchiver. unarchiveObjectWithFile: Decodes and returns the object graph previously encoded by NSKeyedArchiver written to the file at a given path. + (id)unarchiveObjectWithFile:(NSString *)path Parameters: path A path to a file that contains an object graph previously encoded by NSKeyedArchiver. Return Value The object graph previously encoded by NSKeyedArchiver written to the file path. Returns nil if there is no file at path. Discussion This method raises an NSInvalidArgumentException if the file at path does not contain a valid archive. So, for - 1: Most likely the invalid path that you set is not pointing to any file, and hence the return value is nil without any exception. 2: Have you ensured the path on the simulator points to a valid file archived by NSKeyedArchiver earlier? Most likely, it points to some other file. 4: Same thing as #1.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Regular expression to select from X to Y I have the folowing HTML: <Some Html above....../> <!--Template Start --> <div> <p>Some text</p> ... <div> <!--Template End --> <Some Html below/> Now how can I write regular expression to match all text from Template Start to Template End here it says that notepad++ use Scintilla engine. Notepad++ non-greedy regular expressions A: <!--Template Start -->(.*?)<!--Template End --> s modifier should be switched on. A: Assuming that there are no nested templates: <!--Template Start -->(.*?)<!--Template End --> Note to switch on mode DOT_ALL to also cover newlines. A: It's a shame, but Notepad++ doesn't support matching newlines (\r\n) natively in regex mode. It does support matching newlines only in extended mode. However it DOES support INSERTING newlines in both modes. To achieve desired results, you can do a workaround: * *Delete all newlines in extended mode (replace \r\n with nothing) so you have one-liner. *Do regex manipulations in regex mode. *Add newlines back in extended mode (e.g. replace <div> with <div>\r\n and so on) or regex mode. I've read somewhere that PythonScript plugin for N++ adds better support for regexes but I haven't checked it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Selecting the most recent results, in ascending order I am currently using the mysql query: SELECT COUNT(*), time FROM visit GROUP BY time ORDER BY time DESC LIMIT 14 to get the 14 most recent "COUNT(*)"s from a mysql database. Unfortunately, they are in backwards order. If I replace DESC with ASC they are in the right order, but I get the 14 oldest rather than the 14 newest. How would I go about getting these in the right order? Any help appreciated. Thanks :) A: You have to add an alias select * from (select count(*), time from visit group by time order by time desc limit 14) as t order by time A: You could wrap it in another select: SELECT * FROM (SELECT COUNT(*), time FROM visit GROUP BY time ORDER BY time DESC LIMIT 14) as SUB ORDER BY time ASC
{ "language": "en", "url": "https://stackoverflow.com/questions/7544409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++: Are left/right bitshifts for negative and large values defined? My question is, within C++, is the following code defined? Some of it? And if it is, what's it supposed to do in these four scenarios? word << 100; word >> 100; word << -100; word >> -100; word is a uint32_t (This is for a bottleneck in a 3d lighting renderer. One of the more minor improvements in the inner most loop I wanna make is eliminating needless conditional forks. One of those forks is checking to see if a left shift should be done on several 32 bit words as part of a hamming weight count. If the left shift accepts absurd values, the checks don't need done at all) A: The C standard doesn't say what should happen when shift count is negative or greater than (or even equal) to the precision of the variable. The reason is that the C standard didn't want to impose a behavior that would require extra code to be emitted in case of parametric shift. Since different CPUs do different things the standard says that anything can happen. With x86 hardware the shift operator only uses last 5 bits of the shift counter to decide the shift amount (this can be seen by reading the CPU reference manual) so this is what most probably will happen with any C or C++ compiler on that platform. See also this answer for a similar question. A: In the C++0X draft N3290, §5.8: The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand. Note: the above paragraph is identical in the C++03 standard. So the last two are undefined. The others, I believe depend on whether word is signed or not, if word is at least 101bits long. If word is "smaller" than 101bits, the above applies and the behavior is undefined. Here are the next two sections of that paragraph in C++0X (these do differ in C++03): The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned type, the value of the result is E1 × 2E2 , reduced modulo one more than the maximum value representable in the result type. Otherwise, if E1 has a signed type and non-negative value, and E1 × 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined. The value of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a non-negative value, the value of the result is the integral part of the quotient of E1/2E2 . If E1 has a signed type and a negative value, the resulting value is implementation-defined.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: IFrames load Asyncronously? If not why does this error occur? EDIT: From tests it appears iframes do load asyncronously(though not fully sure). I fixed it by calling the function after a period of 700 milliseconds & that works. So it makes me think that they are asyncronous. I do this: insertHTMLIntoIFrame( HTML ); //$("#updaterIframe").contentWindow.location.reload(true); setTimeout("convertToUpdatable()", 700); End Edit I have something weird occuring with my iframe in my webpage. My function searches my iframe for all HTML elements with the class "updatable" & converts those elements to textareas. My problem: If I call the function right after I have inserted some HTML into an iframe then the function doesn't find any of the updatable elements(when they are there in the iframe) BUT If I delay the function execution by showing an alert(); prior to searching the iframe for updatable elements then I do find & convert all the elements in the iframe. This makes me think that iframes load asyncronously, is that correct? If not what is going wrong? Is there a way to refresh the iframe or ensure I dont call my function until the whole iframe has loaded? // I call the functions in the following order: insertHTMLIntoIFrame( "blah"); convertToUpdatable(); function convertToUpdatable() { // Post: Convert all HTML elements (with the class 'updatable') to textarea HTML elements // and store their HTML element type in the class attribute // EG: Before: <p class="updatable Paragraph1"/> Hello this is some text 1 </p> // After : <p class='updatableElementTitle'>Paragraph1</p><textarea class="updatable Paragraph1 p"/> Hello this is some text 1 </textarea> if (STATE != 1 ) { return; } // if I dont have this line then I cant find any updatable elements in the iframe alert("Displaying website with updatable regions"); $("#updaterIframe").contents().find(".updatable").each(function() { var className = this.className; var nodeName = this.nodeName; var title = getTitleName( this ); $(this).replaceWith("<p class='updatableElementTitle'>"+title+"</p><textarea class='"+ className + " " + nodeName +"'>"+$(this).html() +"</textarea>"); }); STATE = 0; } function insertHTMLIntoIFrame( htmlSrc ) { try { var ifrm = document.getElementById("updaterIframe"); ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument; ifrm.document.open(); ifrm.document.write( htmlSrc ); ifrm.document.close(); } catch (ex) { alert("In insertHTMLIntoIFrame(): "+ex); } } A: Yes iframe loading, and actually anything loading in your browser is asynchronous. Consider most anything that even smells like an event in js to be async and your life will become much easier. Forget about setTimeouts, bind to events instead, in this case the load event on the iframe object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: pySerial not working on Python3.2.2 I installed the 32 bit version of Python 3.2.2 and want to get the pySerial package to work. I most definitely have the pyWin32 package install but still when I try to import serial it gives me this error >>> import serial Traceback (most recent call last): File "<interactive input>", line 1, in <module> File "C:\Python32\lib\site-packages\serial\__init__.py", line 19, in <module> from serialwin32 import * ImportError: No module named serialwin32 >>> Any help? A: Search around in your C:/Python32/Lib/site-packages/serial/. See if you can find a file named serialwin32. If not, you should try uninstalling pywin32 and reinstalling it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Initialize a static const array member of class in main(...) and not globally? Suppose class Myclass { private: static const int myarray[2]; } If I wanted to initialize myarray I should put the following statement in global scope: const int Myclass::myarray[2] = {1,1}; What should I do If I want to initialize my array in main() (at some runtime calculated values eg at {n1, n2} where n1 and n2 are values calculated at runtime in main() based on the command line arguments) A: There's nothing much you can do. You could create a member function that would initialize the values, and call it. But, if it's static, private and const - then you can't even do that and out of options. You cannot initialize a static member at run-time, you cannot access a private member from outside of class (unless you make friends), and you cannot change a const member once initialized. If you give up const, then you can change it. You still have to initialize at global scope, but you can change values. Note that as long as its private, you won't be able to access it from main, but you can write a wrapper function member to do that for you (or make it public).
{ "language": "en", "url": "https://stackoverflow.com/questions/7544426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it good practice to end coldfusion self-closing tags with "/>"? In HTML, I was always taught to close self-closing with a "/>". For example "<br />", "<input type='button' value='myButton' />", etc. In Coldfusion, though, it seems to be standard to just never close these tags. I'm constantly seeing code like: <cfset myVariable = someValue> <cfset myOtherVariable = someOtherValue> etc. Is this bad code, or is it commonly accepted? I've seen it almost anywhere that I've seen coldfusion code. Is there any benefit to closing these tags, or is it fine to leave it as it is? A: Because there's no official coding standard for CFML, it's up to you whether to use these. Same as using uppercase/lowercase tags. Personally I love to have my code beautiful and readable, so I'm always using this syntax for single tags. But there is at least one techincal difference: custom tags. Let me show this by example. Consider following custom tag: <cfif thisTag.ExecutionMode EQ "start"> started<br/> </cfif> running<br/> <cfif thisTag.ExecutionMode EQ "end"> ended<br/> </cfif> Now these two types of invokation: <p>&lt;cf_demo&gt;</p> <cf_demo> <p>&lt;cf_demo /&gt;</p> <cf_demo /> And here's the output: <cf_demo> started running <cf_demo /> started running running ended Second syntax is equivalent of <cf_demo></cf_demo>. Possibly there are more differences, but I can't remember any at this moment... :) A: It doesnt matter, it is also not necessary in html unless it is xhtml. A: I agree with the last comment. I hate those single tag closes. It's pointless and not a coding standard for CFML. It started appearing when xml became popular due to it's strict tag syntax and people assuming it was correct for CFML. CFML isn't HTML. Treating it as such is really in itself lazy coding. I also think it looks more beauiful without the unnecessary closing /> :) but that's me for you. I also dislike {} spread on to new lines for each bracket. I guess it's just personal preference. A: I never used to use the /> until i started using Dreamweaver CC and the auto close only works if you close the tags somehow
{ "language": "en", "url": "https://stackoverflow.com/questions/7544429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Android VideoView will not play MKV files My VideoViewer will not play any MKV files. I've tested on .3gp video files and they work fine but MKV files won't work. The video never shows up, no buffering or anything. The screen will show up fine but as I said, the video player is either invisible or isn't there, I can't tell. In the output, it will say something along the lines of: connect to ........ new range: ........ and repeat them over and over depending on how big the MKV is. It'll then either make the application stop responding or give the following output. The output is: 09-25 07:54:40.767: INFO/ActivityManager(68): Starting: Intent { cmp=com.anime/.VideoPlayer } from pid 336 09-25 07:54:41.227: DEBUG/MediaPlayer(336): Couldn't open file on client side, trying server side 09-25 07:54:41.237: INFO/StagefrightPlayer(34): setDataSource('http://pbgl.net/Android/Naruto%20Shippuden/Hun_subtitle_sample1.mkv') 09-25 07:54:41.237: INFO/NuHTTPDataSource(34): connect to pbgl.net:80/Android/Naruto%20Shippuden/Hun_subtitle_sample1.mkv @0 09-25 07:54:41.767: INFO/ActivityManager(68): Displayed com.anime/.VideoPlayer: +968ms 09-25 07:54:43.017: INFO/NuCachedSource2(34): new range: offset= 821676 09-25 07:54:43.017: INFO/NuHTTPDataSource(34): connect to pbgl.net:80/Android/Naruto%20Shippuden/Hun_subtitle_sample1.mkv @821676 09-25 07:54:43.954: INFO/NuCachedSource2(34): new range: offset= 959025 09-25 07:54:43.954: INFO/NuHTTPDataSource(34): connect to pbgl.net:80/Android/Naruto%20Shippuden/Hun_subtitle_sample1.mkv @959025 09-25 07:54:45.564: INFO/NuCachedSource2(34): new range: offset= 1173410 09-25 07:54:45.564: INFO/NuHTTPDataSource(34): connect to pbgl.net:80/Android/Naruto%20Shippuden/Hun_subtitle_sample1.mkv @1173410 09-25 07:54:46.126: INFO/NuCachedSource2(34): ERROR_END_OF_STREAM 09-25 07:54:46.266: INFO/DEBUG(31): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** 09-25 07:54:46.266: INFO/DEBUG(31): Build fingerprint: 'generic/sdk/generic:2.3.3/GRI34/101070:eng/test-keys' 09-25 07:54:46.266: INFO/DEBUG(31): pid: 34, tid: 345 >>> /system/bin/mediaserver <<< 09-25 07:54:46.266: INFO/DEBUG(31): signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 00000024 09-25 07:54:46.266: INFO/DEBUG(31): r0 00000000 r1 00000008 r2 00000003 r3 000151c0 09-25 07:54:46.266: INFO/DEBUG(31): r4 0000fac0 r5 00014fb0 r6 00000000 r7 a30638bc 09-25 07:54:46.266: INFO/DEBUG(31): r8 a2f60ab1 r9 0000f444 10 00100000 fp 00000001 09-25 07:54:46.266: INFO/DEBUG(31): ip afc01100 sp 40606d58 lr a2ff0fd3 pc a2ff2b78 cpsr 40000030 09-25 07:54:46.426: INFO/DEBUG(31): #00 pc 000f2b78 /system/lib/libstagefright.so 09-25 07:54:46.426: INFO/DEBUG(31): #01 pc 000f0fce /system/lib/libstagefright.so 09-25 07:54:46.426: INFO/DEBUG(31): #02 pc 000f140e /system/lib/libstagefright.so 09-25 07:54:46.436: INFO/DEBUG(31): #03 pc 00054624 /system/lib/libstagefright.so 09-25 07:54:46.436: INFO/DEBUG(31): #04 pc 00046290 /system/lib/libstagefright.so 09-25 07:54:46.436: INFO/DEBUG(31): #05 pc 00047f08 /system/lib/libstagefright.so 09-25 07:54:46.436: INFO/DEBUG(31): #06 pc 00044ea8 /system/lib/libstagefright.so 09-25 07:54:46.436: INFO/DEBUG(31): #07 pc 00060a7e /system/lib/libstagefright.so 09-25 07:54:46.436: INFO/DEBUG(31): #08 pc 00060acc /system/lib/libstagefright.so 09-25 07:54:46.436: INFO/DEBUG(31): #09 pc 00011a7c /system/lib/libc.so 09-25 07:54:46.446: INFO/DEBUG(31): #10 pc 00011640 /system/lib/libc.so 09-25 07:54:46.446: INFO/DEBUG(31): code around pc: 09-25 07:54:46.446: INFO/DEBUG(31): a2ff2b58 685cd104 d101428c e0031c18 42933318 09-25 07:54:46.446: INFO/DEBUG(31): a2ff2b68 2000d1f4 46c0bd70 47706a00 47706b00 09-25 07:54:46.446: INFO/DEBUG(31): a2ff2b78 47706a40 600b6ac3 47706a80 47702001 09-25 07:54:46.446: INFO/DEBUG(31): a2ff2b88 47702000 47702000 47702000 47702000 09-25 07:54:46.446: INFO/DEBUG(31): a2ff2b98 6d591c03 47706d00 6dd91c03 47706d80 09-25 07:54:46.446: INFO/DEBUG(31): code around lr: 09-25 07:54:46.446: INFO/DEBUG(31): a2ff0fb0 fd4cf001 1c2b4f76 447f3308 90079306 09-25 07:54:46.446: INFO/DEBUG(31): a2ff0fc0 e0cb2300 98079904 fe26f001 f0011c06 09-25 07:54:46.446: INFO/DEBUG(31): a2ff0fd0 a909fdd3 1c309003 fdd0f001 201c9005 09-25 07:54:46.446: INFO/DEBUG(31): a2ff0fe0 ebb0f74d f7631c04 9408ff6f d0032c00 09-25 07:54:46.446: INFO/DEBUG(31): a2ff0ff0 a9081c20 eba0f74d f0011c30 2801fd97 09-25 07:54:46.446: INFO/DEBUG(31): stack: 09-25 07:54:46.446: INFO/DEBUG(31): 40606d18 000154c8 [heap] 09-25 07:54:46.446: INFO/DEBUG(31): 40606d1c afc009cf /system/lib/libstdc++.so 09-25 07:54:46.446: INFO/DEBUG(31): 40606d20 000154c8 [heap] 09-25 07:54:46.446: INFO/DEBUG(31): 40606d24 a8114ba7 /system/lib/libutils.so 09-25 07:54:46.446: INFO/DEBUG(31): 40606d28 0000fac0 [heap] 09-25 07:54:46.446: INFO/DEBUG(31): 40606d2c 000154c8 [heap] 09-25 07:54:46.446: INFO/DEBUG(31): 40606d30 a3060eb0 /system/lib/libstagefright.so 09-25 07:54:46.446: INFO/DEBUG(31): 40606d34 a8114ca9 /system/lib/libutils.so 09-25 07:54:46.446: INFO/DEBUG(31): 40606d38 00000002 09-25 07:54:46.446: INFO/DEBUG(31): 40606d3c 40606d78 09-25 07:54:46.446: INFO/DEBUG(31): 40606d40 00014fb0 [heap] 09-25 07:54:46.446: INFO/DEBUG(31): 40606d44 000154f0 [heap] 09-25 07:54:46.446: INFO/DEBUG(31): 40606d48 a30638bc /system/lib/libstagefright.so 09-25 07:54:46.446: INFO/DEBUG(31): 40606d4c a2f42a4d /system/lib/libstagefright.so 09-25 07:54:46.446: INFO/DEBUG(31): 40606d50 df002777 09-25 07:54:46.446: INFO/DEBUG(31): 40606d54 e3a070ad 09-25 07:54:46.446: INFO/DEBUG(31): #01 40606d58 00000004 09-25 07:54:46.446: INFO/DEBUG(31): 40606d5c 00000000 09-25 07:54:46.446: INFO/DEBUG(31): 40606d60 00000004 09-25 07:54:46.446: INFO/DEBUG(31): 40606d64 000152b0 [heap] 09-25 07:54:46.446: INFO/DEBUG(31): 40606d68 00000002 09-25 07:54:46.446: INFO/DEBUG(31): 40606d6c 00000000 09-25 07:54:46.446: INFO/DEBUG(31): 40606d70 00014fb8 [heap] 09-25 07:54:46.446: INFO/DEBUG(31): 40606d74 00015198 [heap] 09-25 07:54:46.446: INFO/DEBUG(31): 40606d78 0000fac0 [heap] 09-25 07:54:46.446: INFO/DEBUG(31): 40606d7c 00000000 09-25 07:54:46.457: INFO/DEBUG(31): 40606d80 000152f0 [heap] 09-25 07:54:46.457: INFO/DEBUG(31): 40606d84 40606da0 09-25 07:54:46.457: INFO/DEBUG(31): 40606d88 00014fb0 [heap] 09-25 07:54:46.457: INFO/DEBUG(31): 40606d8c 00000000 09-25 07:54:46.457: INFO/DEBUG(31): 40606d90 40606e74 09-25 07:54:46.457: INFO/DEBUG(31): 40606d94 a2ff1413 /system/lib/libstagefright.so 09-25 07:54:47.646: WARN/MediaMetadataRetriever(260): MediaMetadataRetriever server died! 09-25 07:54:47.646: WARN/AudioSystem(124): AudioFlinger server died! 09-25 07:54:47.646: WARN/AudioSystem(124): AudioPolicyService server died! 09-25 07:54:47.646: WARN/AudioSystem(336): AudioFlinger server died! 09-25 07:54:47.646: WARN/IMediaDeathNotifier(336): media server died 09-25 07:54:47.646: ERROR/MediaPlayer(336): error (100, 0) 09-25 07:54:47.646: ERROR/MediaPlayer(336): Error (100,0) 09-25 07:54:47.646: DEBUG/VideoView(336): Error: 100,0 09-25 07:54:47.666: WARN/AudioSystem(68): AudioFlinger server died! 09-25 07:54:47.666: WARN/AudioSystem(68): AudioPolicyService server died! 09-25 07:54:47.666: INFO/ServiceManager(28): service 'media.audio_flinger' died 09-25 07:54:47.666: INFO/ServiceManager(28): service 'media.audio_policy' died 09-25 07:54:47.666: INFO/ServiceManager(28): service 'media.player' died 09-25 07:54:47.666: INFO/ServiceManager(28): service 'media.camera' died 09-25 07:54:47.666: INFO/BootReceiver(68): Copying /data/tombstones/tombstone_04 to DropBox (SYSTEM_TOMBSTONE) 09-25 07:54:49.166: ERROR/AudioService(68): Media server died. 09-25 07:54:49.166: INFO/ServiceManager(68): Waiting for service media.audio_flinger... 09-25 07:54:49.977: INFO/(348): ServiceManager: 0xad50 09-25 07:54:49.977: DEBUG/AudioHardwareInterface(348): setMode(NORMAL) 09-25 07:54:49.977: INFO/CameraService(348): CameraService started (pid=348) 09-25 07:54:49.977: INFO/AudioFlinger(348): AudioFlinger's thread 0xc658 ready to run 09-25 07:54:50.198: ERROR/AudioService(68): Media server started. 09-25 07:54:50.207: DEBUG/AudioHardwareInterface(348): setMode(NORMAL) My code: (Not the main activity) package com.anime; import java.io.IOException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import android.app.*; import android.media.MediaPlayer; import android.net.Uri; import android.os.*; import android.text.*; import android.view.View; import android.view.View.OnClickListener; import android.widget.*; import android.widget.AdapterView.OnItemClickListener; public class VideoPlayer extends Activity implements OnClickListener { /** Called when the activity is first created. */ VideoView vv; Button close; public static String selectedVideo = ""; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.vidplayer); close = (Button) findViewById(R.id.button1); vv = (VideoView) findViewById(R.id.videoView1); playVideo(selectedVideo); View btn1 = findViewById(R.id.button1); btn1.setOnClickListener(this); } public void playVideo(String selected) { setContentView(R.layout.vidplayer); String url = RunApp.videoUrls.get(RunApp.currentShow).get(RunApp.videos.get(RunApp.currentShow).indexOf(selected)).toString(); // your URL here vv = (VideoView) findViewById(R.id.videoView1); try { vv.setVideoURI(Uri.parse(url)); vv.setMediaController(new MediaController(this)); vv.requestFocus(); vv.start(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } @Override public void onClick(View v) { System.out.println("ID: " + v.getId()); switch (v.getId()){ case R.id.button1: finish(); break; } } } A: MKV is not a supported media container under Android. The supported video file types (container formats) are: .3gp, .mp4 and .webm. There are also restrictions on supported video codecs. Also, video codec format (h263, h264, mpeg-4, vp8) and container format (3gp, mp4, webm) are two different things. Which means that even if you have a .mp4 file it does not mean Android will be able to play it. It's content would also need to be encoded with a supported codec. A: Since Android 4.0+, MKV videos are supported as described here. But as @Peter Knego said, video codec format and container format are two different things. The Android Media API seems to be poorly documented (or at least it was at question time), as other guys have already pointed here. However, using tips from this post and this answer I was able to retrieve both information from two sample videos: Uri videoUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.sample_video); // Codec Format extractor = new MediaExtractor(); extractor.setDataSource(this, videoUri, null); for (int i = 0; i < extractor.getTrackCount(); i++) { MediaFormat format = extractor.getTrackFormat(i); String mime = format.getString(MediaFormat.KEY_MIME); if (mime.startsWith("video/")) { Log.d(TAG, "CODEC: " + mime); break; } } // Container Format MediaMetadataRetriever mmr = new MediaMetadataRetriever(); mmr.setDataSource(this, videoUri); Log.d(TAG, "CONTAINER: " + mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE)); From two different MKV videos, I got the following outputs: D/VideoActivity: CODEC: video/mp4v-es D/VideoActivity: CONTAINER: video/x-matroska D/VideoActivity: CODEC: video/avc D/VideoActivity: CONTAINER: video/x-matroska Although I think the best approach to handle unsupported files might be using try/catch blocks and/or VideoView.setOnErrorListening (doc & example), someone could use above methods to extract more details of media before playing it or at least to log what happened if something went wrong.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Strange performance behavior I'm using Visual Studio 2010 SP1, Target framework is 2.0, Platform target: Any CPU, testing under Windows 7 x64 SP1. I'm experiencing strange performance behavior. Without an app.config, or with the following app.config, it makes my program run slowly (Stopwatch shows ~0.11 s) <?xml version="1.0"?> <configuration> <startup > <supportedRuntime version="v2.0.50727" /> </startup> </configuration> The following app.config makes my program run x5 times faster (Stopwatch shows ~0.02 s) <?xml version="1.0"?> <configuration> <startup > <supportedRuntime version="v4.0.30319" sku=".NETFramework,Version=v4.0" /> </startup> </configuration> This is the test program code: using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; class Program { static void Main(string[] args) { Stopwatch sw = new Stopwatch(); while (true) { sw.Reset(); sw.Start(); for (int i = 0; i < 1000000; i++ ) { "blablabla".IndexOf("ngrhotbegmhroes", StringComparison.OrdinalIgnoreCase); } Console.WriteLine(sw.Elapsed); } } } I'm sitting for hours and can't figure out what is happening here. Have you any idea? A: I just ran your benchmark with a few tweaks (which included more iterations and averaging), and can confirm that the .NET 4.0 targeted version is indeed 4-5 times faster. So presumably IndexOf() was optimised in .NET 4.0 A: OK, some benchmarks with the new VS11 n = 1000000; string haystack = "ngrhotbegmhroes"; string needle = "blablablablablablablablablangrhotbegmhrobla bla"; .NET 4.5 : 8 ms .NET 4.0 : 8 ms .NET 3.5 : 45 ms .NET 2.0 : 45 ms So these first results confirm your findings, the newer versions are faster. It is however much more common to look for s short string inside a larger string: n = 1000000; haystack = "blablablablablablablablablangrhotbegmhrobla bla"; needle = "ngrhotbegmhroes"; .NET 4.5 : 1020 ms .NET 4.0 : 1020 ms .NET 3.5 : 155 ms .NET 2.0 : 155 ms And with a much longer haystack (~400 chars) .NET 4.0 : 12100 ms .NET 2.0 : 1700 ms Which means things got worse for the most common use pattern... All measurements in Release config, and Client Profile where available. Running from VS 11 with Ctrl+F5 Win 7H, Core i7 2620M A: It sounds like you've just found a situation in which .NET 4 is a lot faster. By default, your app is running with the framework it was built to target. When you force it to use .NET 4, it's faster. That may be a JIT compiler improvement which happens to hit your situation, or it may be a framework improvement - but it shouldn't be too surprising that some things are faster in newer versions. (For what it's worth, I'd increase the number of iterations you're timing over if I were you... on my box under .NET 4, each iteration is only 10ms, which isn't really a great measurement. I prefer to benchmark for at least a few seconds.) (And like Mitch, I can confirm that I see the same effect.) EDIT: I've just investigated this a bit further, and seen an interesting effect... I'll assume we're calling haystack.IndexOf(needle, StringComparison.OrdinalIgnoreCase): * *On .NET 2, the results are roughly the same however big the "needle" is *On .NET 4: * *If needle is bigger than haystack (as per your example) .NET 4 is much faster than .NET 2 *If needle is the same size as haystack, .NET 4 is a little bit slower than .NET 2 *If needle is smaller than haystack, .NET 4 is a lot slower than .NET 2 (This is keeping a test where the first character of needle never appears in haystack, btw.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7544438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: non-ascii char as arguments printargv.js: console.log(Buffer.byteLength(process.argv[2])); In cmd.exe (with chcp=65001,font='Lucida Console'), I ran: node printargv.js Ā (Note: unicode code point of Ā is U+0100.) The script outputted: 1 I expected the script to print a number greater than 1 but it doesn't. Does anyone know why? edit: i think that node 'parses' initial arguments incorrectly for cmd.exe after i tried the below code: var i = require('readline').createInterface(process.stdin,process.stdout); i.question('char: ', function(c){ console.log( Buffer.byteLength(c) ); i.close(); process.stdin.destroy(); }); the output is 2 A: Your program is not receiving the Ā, it's receiving an A instead. I used this program to test: var n; for (n = 0; n < process.argv.length; ++n) { console.log(n + ": '" + process.argv[n] + "'"); } console.log("length: " + process.argv[2].length); console.log("code: " + process.argv[2].charCodeAt(0)); console.log("size: " + Buffer.byteLength(process.argv[2])); On Ubuntu using UTF-8 in the console, I got: $ node test.js Ā 0: 'node' 1: '/home/tjc/temp/test.js' 2: 'Ā' length: 1 code: 256 size: 2 ...which is correct. On Windows 7 using chcp 65001 and Lucida Console, I got: C:\tmp>node temp.js Ā 0: 'node' 1: 'C:\tmp\temp.js' 2: 'A' length: 1 code: 65 size: 1 Note that the Ā became an A at some point along the way. As I said in my comment on the question, I can only assume there's some issue with Lucida Console, or cmd.exe's handling of UTF-8, or perhaps node.exe's handling of Unicode from the console on Windows (I used the pre-built 0.5.7 version). Update: This might be something to take up with the NodeJS folks, since Windows appears to get it right on its own. If I put this code in a test.vbs file: WScript.Echo WScript.Arguments(0) WScript.Echo AscW(WScript.Arguments(0)) I get a correct result: C:\tmp>cscript /nologo test.vbs Ā Ā 256 ...suggesting that the terminal is passing the argument correctly to the program. So it could be an issue with the Windows node.exe build.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using jackson to map an unnamed array Hitting the twitter friends/ids API endpoint without a cursor specified will return this JSON response: ["243439460","13334762", "14654522"] however when specifying a cursor you get the documented format: {"next_cursor":0,"previous_cursor":0,"ids":["243439460","13334762","14654522"]} Using Jackson to deserialise the second response is easy using @JsonIgnoreProperties(ignoreUnknown = true) public class FriendIds { private List<String> ids; public List<String> getIds() { return ids; } public void setIds(List<String> ids) { this.ids = ids; } } and FriendIds friendIds = new ObjectMapper().readValue(jsonStr, FriendIds.class); However I haven't found a similar way to deserialise the first response to FriendIds using Jackson. Any ideas on how this can be done? A: How about just mapping them to id list first like: List<String> ids = mapper.readValue(json, List.class); // works because String happens to be 'natural' type for JSON Strings and then just construct wrapper object? There is no real way for Jackson to know that a JSON array was to be used to construct a POJO where one of the fields is to contain contents of the list, except by writing a custom deserializer. That is a possibility if you want to do it; and that could in fact support both cases. But needs some thinking, to use one method (default POJO deser) for JSON Objects, another for JSON arrays. So it might just be easiest to do it outside of Jackson. A: I hope this helps. You can do this using Spring RestTemplate.getForObject and Jackson annotations. This is the class for the Twitter Response: import java.util.List; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class TwitterResponse { private List<TwitterId> ids; @JsonCreator public TwitterResponse(List<TwitterId> ids) { this.ids = ids; } public List<TwitterId> getIds() { return ids; } @Override public String toString() { return "TwitterResponse [ids=" + ids + "]"; } } This is the TwitterId class: import com.fasterxml.jackson.annotation.JsonProperty; public class TwitterId { private String twitterId; public TwitterId(String twitterId) { this.twitterId = twitterId; } public String getTwitterId() { return twitterId; } @Override public String toString() { return "TwitterId [twitterId=" + twitterId + "]"; } } And a simple unit test showing it works. I just created a simple controller that returns your data above, and I'm testing it using RestTemplate import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.client.RestTemplate; public class ControllerTest { private static final Logger log = LoggerFactory.getLogger(ControllerTest.class); @Test public void testTwitter() { try { RestTemplate restTemplate = new RestTemplate(); TwitterResponse twitterResponse = restTemplate.getForObject("http://localhost:8080/twitter", TwitterResponse.class); log.debug("twitterResponse = {}", twitterResponse); } catch (Exception e) { e.printStackTrace(); } } } And the console showing test result: 19:57:42.506 [main] DEBUG org.springframework.web.client.RestTemplate - Created GET request for "http://localhost:8080/twitter" 19:57:42.545 [main] DEBUG org.springframework.web.client.RestTemplate - Setting request Accept header to [application/json, application/*+json] 19:57:42.558 [main] DEBUG org.springframework.web.client.RestTemplate - GET request for "http://localhost:8080/twitter" resulted in 200 (OK) 19:57:42.559 [main] DEBUG org.springframework.web.client.RestTemplate - Reading [class org.porthos.simple.TwitterResponse] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@4b5a5ed1] 19:57:42.572 [main] DEBUG org.porthos.simple.ControllerTest - twitterResponse = TwitterResponse [ids=[TwitterId [twitterId=243439460], TwitterId [twitterId=13334762], TwitterId [twitterId=14654522]]]
{ "language": "en", "url": "https://stackoverflow.com/questions/7544447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Index was outside the bounds of the array in c# I want to insert MySqlDataReader read value into an array.but I get the exception "Index was outside the bounds of the array". Here is my code, string[] a = new string[1000]; string myconstring = "SERVER=localhost;" + "DATABASE=alicosms;" + "UID=root;" + "PASSWORD=;"; MySqlConnection mycon = new MySqlConnection(myconstring); string sql = "SELECT flag FROM sms_data_bankasia group by flag"; MySqlCommand comd = mycon.CreateCommand(); comd.CommandText = sql; mycon.Open(); MySqlDataReader dtr = comd.ExecuteReader(); count = 0; int i = 0; while (dtr.Read()) { a[i] = dtr.GetValue(i).ToString(); i++; } What can I do.Any one can help me? A: This looks suspicious to me: a[i] = dtr.GetValue(i).ToString(); That means you're fetching column 0 of row 0, column 1 of row 1, column 2 of row 2 etc... but you've only got a single column ("flag"). I suspect you meant: a[i] = dtr.GetValue(0).ToString(); That will still fail if there are more than 1000 rows though - it would be better to use a List<string>: List<string> data = new List<string>(); while (dtr.Read()) { data.Add(dtr.GetValue(0).ToString()); // Or call GetString } A: Try cleaning your code a little and use a dynamically resizing List<T> to which you can add elements: var result = new List<string>(); var myconstring = "SERVER=localhost;DATABASE=alicosms;UID=root;PASSWORD=;"; using (var con = new MySqlConnection(myconstring)) using (var cmd = con.CreateCommand()) { con.Open(); cmd.CommandText = "SELECT flag FROM sms_data_bankasia group by flag"; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { result.Add(reader.GetString(reader.GetOrdinal("flag"))); } } } string[] a = result.ToArray();
{ "language": "en", "url": "https://stackoverflow.com/questions/7544453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can we use multiple forms in a web page? So far, all the web pages I met contain at most one <form> tag. Why not multiple ones? I can not think of reasons why multiple forms can't coexist within the same web page. Also, to be specific to ASP.NET - why are all the server controls are placed within the <form> tag? Why not place them somewhere else? Plus, I noticed that in an .aspx file, the <form> tag has the runat=server attribute, while a normal server control such as Button also has one. So it seems the <form> is also a server control. But strangely enough, I cannot find it in the Visual Studio Toolbox. A: As pointed out, this is one of the shortcomings of WebForms. I do want to point out, additionally, that with cross-page posting and validation groups, you can typically reach your desired behavior (for most "multi-form" solutions). A: There can be multiple forms, with hacks. It is indeed a shortcoming of WebForms. In ASP.NET MVC you can implement as many forms as you want (and it is valid & correct behavior of web pages). The reason all server controls are placed inside <form> tag is to allow the WebForms engine to recognize them, load their values & save their values from/to the ViewState. Almost all infrastructure of control management in WebForms is based on the idea that a tag contains everything you access from the code-behind. A: Regarding the additional question: the <form runat="server"> is parsed as HtmlForm class behind the scenes, which inherits from HtmlControl like any other HTML element with runat="server". Unlike any other HtmlControl though, there can exist only one instance per page and it does not appear in the toolbox as it's added automatically to every new Form you create, so it's quite pointless. A: Yes, it can be done - by creating a custom HtmlForm object and toggling the forms as needed. I've just answered a similar question here (with code): Paypal Form Ruins My ASP.NET webforms layout -> How to Solve? A: many non server forms - you can , but only one runAt Server form i also found this : A server-side form tag is the tag which has a runat="server" attribute. If this attribute is missing, then it's a typical HTML form tag. The conclusion is that you are allowed to use multiple form tags on a page, as long as only one has the runat="server" attribute. The disadvantage of the form that doesn't have this attribute, is that view state won't work (meaning form values will disappear when using the back/forward browser buttons). It's a small price to pay if you really need multiple forms on a page. A: * *Take master page & set design. *Take one form in master page. *Second form take in contain place holder. *In contain place holder in only for write form tag (not use) *Add aspx page & design second form but not write form tag only for control put *Take button click event fire code write This is proper way of two form
{ "language": "en", "url": "https://stackoverflow.com/questions/7544454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: using webcam & taking high res (2Mpix) pictures in a web application I need a web based application where the user needs to fill in 3 fields and taking a high resolution image (2mpix) with a webcam. Once these are ready I need to post them to the server so they are saved in a database. 1) What is the best way/tools available? 2) I saw thisjquery webcam plugin - is it possible to capture photos through your webcam up to 1920×1080? Thanks A: The quality of the pictures you take with ANY camera depends on the sophistication of the camera. Cameras have maximum resolutions and settings to configure them to a lower one as needed. If the webcam on the machine has a resolution as high as the one you need, you'll probably be able to do this. And its worth mentioning that the jquery webcam plugin requires flash to be available on the machine. Since you've tagged this question with the ".net" and "c#" tags i guess i should mention that you can access the webcam via a silverlight app as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: @Functions inheritance from parent Razor layout Is it possible to declare a function or helper in a Razor layout view and have a child Razor view use that function? My structure is : _layout.cshtml -> index.cshtml Where index.cshtml uses _layout.cshtml as its layout. This is the default structure. I want to be able to place common functions/helpers in _layout.cshtml and refer to them in index.cshtml and all other views that use _layout.cshtml. It doesn't work out of the box unless I've missed something. I know. I should be using compiled AppHelpers or HtmlHelpers for this, but I can foresee a great convenience in being able to tweak select functions/helpers directly in a _layout.cshtml file. Thanks A: No, that's not possible. @functions are visible only inside the current view. You could use @helper which could be placed inside the App_Code folder and be reused from all views. For example you define ~/App_Code/MyHelpers.cshtml: @helper Foo() { ... } and then in some view: @MyHelpers.Foo() But I would recommend compiled helpers. They are unit test friendly and view engine agnostic and when tomorrow Microsoft reveal their brand new Blade view engine you will have 0 work to do in order to use them, whereas if you code against Razor specific things like @functions and @helper you will have to port them. Probably not a concern for you but worth mentioning.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is inline code allowed in Jinja templates? I'm using Jinja on my site and I like it. I've come across a simple need. How to display today's date? Is there a way to inline some Python code in a Jinja template? import datetime now = datetime.datetime.utcnow() print now.strftime("%Y-%m-%d %H:%M") This article says no, but suggests using a macro or a filter? Really? Must we resort to all that? OK, what would that look like in this case? A: The current answers are correct for pretty much every situation. However there are some very rare cases where you would want to have python code inside the template. In my case I want to use it to preprocess some latex files and I would prefer to keep the python code generating table values, plots, etc, inside the latex file it self. So I made a Jinja2 extension that adds a new "py" block allowing python code to be written inside the template. Please keep in mind that I had to do some questionable work-arounds to get this to work, so I'm not 100% sure in which situations it fails or behaves unexpectedly. This is an example template. Foo was given to the template foo: {{ foo }} Bar was not, so it is missing bar is missing: {{ bar == missing }} {% py %} # Normal python code in here # Excess indentation will be removed. # All template variables are accessible and can be modified. import numpy as np a = np.array([1, 2]) m = np.array([[3, 4], [5, 6]]) bar = m @ a * foo # It's also possible to template the python code. {% if change_foo %} foo = 'new foo value' {% endif %} print("Stdio is redirected to the output.") {% endpy %} Foo will have the new value if you set change_foo to True foo: {{ foo }} Bar will now have a value. bar: {{ bar }} {% py %} # The locals from previous blocks are accessible. m = m**2 {% endpy %} m: {{ m }} The output if we set the template parameters to foo=10, change_foo=True is: Foo was given to the template foo: 10 Bar was not, so it is missing bar is missing: True Stdio is redirected to the output. Foo will have the new value if you set change_foo to True foo: new foo value Bar will now have a value. bar: [110 170] m: [[ 9 16] [25 36]] The extension with a main function to run the example. from jinja2 import Environment, PackageLoader, nodes from jinja2.ext import Extension from textwrap import dedent from io import StringIO import sys import re import ctypes def main(): env = Environment( loader=PackageLoader('python_spike', 'templates'), extensions=[PythonExtension] ) template = env.get_template('emb_py2.txt') print(template.render(foo=10, change_foo=True)) var_name_regex = re.compile(r"l_(\d+)_(.+)") class PythonExtension(Extension): # a set of names that trigger the extension. tags = {'py'} def __init__(self, environment: Environment): super().__init__(environment) def parse(self, parser): lineno = next(parser.stream).lineno body = parser.parse_statements(['name:endpy'], drop_needle=True) return nodes.CallBlock(self.call_method('_exec_python', [nodes.ContextReference(), nodes.Const(lineno), nodes.Const(parser.filename)]), [], [], body).set_lineno(lineno) def _exec_python(self, ctx, lineno, filename, caller): # Remove access indentation code = dedent(caller()) # Compile the code. compiled_code = compile("\n"*(lineno-1) + code, filename, "exec") # Create string io to capture stdio and replace it. sout = StringIO() stdout = sys.stdout sys.stdout = sout try: # Execute the code with the context parents as global and context vars and locals. exec(compiled_code, ctx.parent, ctx.vars) except Exception: raise finally: # Restore stdout whether the code crashed or not. sys.stdout = stdout # Get a set of all names in the code. code_names = set(compiled_code.co_names) # The the frame in the jinja generated python code. caller_frame = sys._getframe(2) # Loop through all the locals. for local_var_name in caller_frame.f_locals: # Look for variables matching the template variable regex. match = re.match(var_name_regex, local_var_name) if match: # Get the variable name. var_name = match.group(2) # If the variable's name appears in the code and is in the locals. if (var_name in code_names) and (var_name in ctx.vars): # Copy the value to the frame's locals. caller_frame.f_locals[local_var_name] = ctx.vars[var_name] # Do some ctypes vodo to make sure the frame locals are actually updated. ctx.exported_vars.add(var_name) ctypes.pythonapi.PyFrame_LocalsToFast( ctypes.py_object(caller_frame), ctypes.c_int(1)) # Return the captured text. return sout.getvalue() if __name__ == "__main__": main() A: You can add to global variables which can be accessed from Jinja templates. You can put your own function definitions in there, which do whatever you need. A: No, there is no way to inline Python into Jinja. However, you can add to the constructs that Jinja knows by extending the Environment of the template engine or the global namespace available to all templates. Alternately, you can add a filter that let's you format datetime objects. Flask stores the Jinja2 Environment on app.jinja_env. You can inject new context into the environment by either adding to this dictionary directly, or by using the @app.context_processor decorator. Whatever path you choose, this should be done while you are setting up the application, before you have served any requests. (See the snippets section of the website for some good examples of how to set up filters - the docs contain a good example of adding to the global variables).
{ "language": "en", "url": "https://stackoverflow.com/questions/7544461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Automation Error 80004005 I've been beating myself over the head with this for a few days now, searched up and down the internet. I know there is a lot I don't quite get about Com Interop but I've had success building and using simpler DLL's with Excel. Anyways to the point. I get the above mentioned Error -2147467259 80004005 Automation Error Unspecified Error in Excel VBA when running the following code wrapped in a DLL. [GuidAttribute("96BE21CD-887B-4770-9FAA-CF395375AEA9")] [ComVisibleAttribute(true)] interface QInterface { void ConnectionFill(string SQLQuery, string CONStr); string QueryValue(int QueryKey); string ConnectionValue(int ConnectionKey); string outputFile { get; set; } void ThreadTest(); } [ClassInterfaceAttribute(ClassInterfaceType.None)] [ProgIdAttribute("QueryThread")] class QueryThread : QInterface { DataSet QueryReturn = new DataSet(); private ArrayList SQLList = new ArrayList(); private ArrayList ConList = new ArrayList(); private string OutputFile; public void ConnectionFill(string SQLQuery, string CONStr) { SQLList.Add(SQLQuery); ConList.Add(CONStr); } public string QueryValue(int QueryKey) { return SQLList[QueryKey].ToString(); } public string ConnectionValue(int ConnectionKey) { return ConList[ConnectionKey].ToString(); } public string outputFile { set { OutputFile = value; } get { return OutputFile; } } public void ThreadTest() { int i = 0; i = SQLList.Count; Thread[] myThreads; myThreads = new Thread[i]; for (int t = 0; t != i; t++) { myThreads[t] = new Thread(() => ThreadRun(SQLList[t].ToString(), ConList[t].ToString())); myThreads[t].Name = "Thread " + t; myThreads[t].IsBackground = true; myThreads[t].Start(); Thread.Sleep(600); if (t > 9) { myThreads[t - 9].Join(); } } for (int t = 0; t != i; t++) { while (myThreads[t].IsAlive) { Thread.Sleep(20); } } TextWriter tw = new StreamWriter(OutputFile); for (int t = 0; t < QueryReturn.Tables.Count; t++) { DataTableReader DR = QueryReturn.Tables[t].CreateDataReader(); while (DR.Read()) { tw.WriteLine("{0} : {1}", DR.GetValue(0), DR.GetValue(1)); } } tw.Close(); QueryReturn.Dispose(); } private void ThreadRun(string SQLString, string ConString) { try { OleDbConnection DBCon = new OleDbConnection(ConString); DBCon.Open(); Thread.Sleep(200); OleDbCommand DBCmd = new OleDbCommand(SQLString, DBCon); OleDbDataAdapter DataAdapter = new OleDbDataAdapter(DBCmd); Thread.Sleep(200); DataAdapter.Fill(QueryReturn, Thread.CurrentThread.Name.ToString()); DBCon.Close(); DataAdapter.Dispose(); DBCon.Dispose(); DBCmd.Dispose(); } finally { } } } using this VBA code... Sub test() Dim QT As New QueryThreading.QueryThread Dim MyResults As String Dim outputfile As String Dim InputStuff(1, 1) As String InputStuff(0, 0) = "Select DISTINCT * From TrackingData;" InputStuff(0, 1) = "Provider =Microsoft.ACE.OLEDB.12.0;Data Source =C:\Users\Nick\Desktop\test.accdb; Persist Security Info =False;Connection Timeout=7;" InputStuff(1, 0) = "Select DISTINCT * From TrackingData;" InputStuff(1, 1) = "Provider =Microsoft.ACE.OLEDB.12.0;Data Source =C:\Users\Nick\Desktop\test2.accdb; Persist Security Info =False;Connection Timeout=7;" QT.ConnectionFill InputStuff(0, 0), InputStuff(0, 1) QT.ConnectionFill InputStuff(1, 0), InputStuff(1, 1) outputfile = "C:\Users\Nick\Desktop\testrun.txt" QT.outputfile = outputfile QT.ThreadTest End Sub It runs fine is a pure C# console application. Works perfect and quick with no problems. But via VBA I get the error. I'm assuming it's something to do with the calling of the access databases in multiple threads. I know there is a lot of junk code in there, it's not optimized of course I'm still in the "playing around" phase. I've used RegAsm and enabled com interop and all such stuff, I can read back from the returns just fine. So I know the DLL is working right, just when I fill the threads and run "ThreadTest()" I get the automation error. If I run it a second time Excel locks up. Any help would be greatly appreciated. A: You are calling QT.DictionaryFill though I can't seem to find a corresponding method in you C# code... what happens if you change the call to QT.ConnectionFill instead ? Another point: IIRC then VBA runs the object in STA - not sure whether MTA is supported though EDIT: According to this rather old post VBA does not support multi-threading...
{ "language": "en", "url": "https://stackoverflow.com/questions/7544465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: URL Encode problem with chine language I have such text in chines: "回家" - seems it is "house" in english. I go to google.com, post "回家" in search and get such url: http://www.google.ru/ ... q=%E5%9B%9E%E5%AE%B6 => q = %E5%9B%9E%E5%AE%B6 Then i go to taobao.com post "回家" to search and get url like this: http://search8.taobao.com/search?q=%BB%D8%BC%D2 => q = %BB%D8%BC%D2 Why url encoding is not the same? What encoding used on taobao? A: The byte sequence for "回家" in the UTF-8 encoding is E5 9B 9E E5 AE B6, the byte sequence in the GB 18030 encoding is BB D8 BC D2. Google uses UTF-8, Taobao uses GB 18030.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Data at the root level is invalid. Line 1, position 1 -why do I get this error while loading an xml file? Data at the root level is invalid. Line 1, position 1 -why I get this error while load xml file this my code: XmlDocument xmlDoc=new XmlDocument(); xmlDoc.LoadXml("file.xml"); A: The LoadXml method is for loading an XML string directly. You want to use the Load method instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Activity does not scroll when rotating screen when I turn the phone and the screen is rotating I cannot see the whole screen anymore. This is ok but I cannot scroll! Do I have to set some flag or property for scrolling? This is part of my xml... <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:focusable="true" android:focusableInTouchMode="true" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TableLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:stretchColumns="*"> ... </TableLayout> <TableLayout android:layout_width="fill_parent" android:layout_height="wrap_content" ... </TableLayout> </LinearLayout> Thanks! A: You have to put your complete layout inside a ScrollView in order for it to scroll. It scrolls if your layout height is more than the screen height, which happens generally in landscape mode. In your case put the LinearLayout inside a ScrollView, since ScrollView can only have 1 child. A: You must know that in order to use an scrollView , you must put only one component inside (maybe a linearLayout) .Maybe that's your problem if you are trying to put in more components at that level.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: query in a cursor I have a table 1 to many: name _id ## name ## 1 tony and points _marksid## date ## point 1 13 55 1 23 55 1 24 69 1 31 77 and i have cursor: Cursor cursorMarks = database.query(points, new String[] {"point"}, "_marksid=1", null,null,null,null); i want: select point from points where _marksid="1" why thats didnt work correctly? and i have cycle: TableRow row = (TableRow)findViewById(R.id.tableMarks); cursorMarks.moveToFirst(); do { TextView textView = new TextView(this); textView.setText(cursorMarks.getString(0)); row.addView(textView); } while (cursorMarks.moveToNext());
{ "language": "en", "url": "https://stackoverflow.com/questions/7544487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails, Paperclip, DelayedJob and cleaning temporary files In a Ruby on Rails application, I'm using Paperclip to handle attached files. The download (from a URL) and attachment is done in a background job (with DelayedJob). Each job might deal with many files to download, and it results to a dozens of temporary files left in the /tmp directory. Sometimes, some temp files are left in the filesystem until the DelayedJob worker is restarted. I wonder if there is a way to manually clean the temp files. Thanks for any help A: You could do this automatically with a regularly scheduled job, schedules with regular cron, or with something like the Clockwork gem or resque-scheduler if you want to avoid cron's syntax. Have it look for temp files in the given directory; it's easiest if it's a specific subdirectory under /tmp, and delete all files that are more than 10 minutes old, or whatever age makes sense for your application. Run that job once a day, or several times a day, and you shouldn't have to worry about it. A: You can use Tempfile. A utility class for managing temporary files. file = Tempfile.new('foo') begin # process here ensure file.close file.unlink # deletes the temp file end
{ "language": "en", "url": "https://stackoverflow.com/questions/7544490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Transport security in WCF I have 2 console applications in my solution. This is my WCF service: using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace TransportSecTaulty { [ServiceContract] public interface ITestService { [OperationContract] void CallMe(string message); } } using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace TransportSecTaulty { public class TestService : ITestService { public void CallMe(string message) { Console.BackgroundColor = ConsoleColor.Green; Console.Write(message); Console.BackgroundColor = ConsoleColor.Black; } } } This is my app.config of the application which is hosting my WCF service: <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name=""> <serviceMetadata httpsGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> <services> <service name="TransportSecTaulty.TestService"> <endpoint address="" binding="basicHttpBinding" bindingConfiguration="serviceConfig" contract="TransportSecTaulty.ITestService"> <identity> <dns value="localhost" /> </identity> </endpoint> <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" /> <host> <baseAddresses> <add baseAddress="https://localhost:8734/Design_Time_Addresses/TransportSecTaulty/TestService/" /> </baseAddresses> </host> </service> </services> <bindings> <basicHttpBinding> <binding name="serviceConfig"> <security mode="Transport"> </security> </binding> </basicHttpBinding> </bindings> </system.serviceModel> </configuration> My service correctly starts without any problem. However, when I try to add service reference in my client I get this error: There was an error downloading 'https://localhost:8734/Design_Time_Addresses/TransportSecTaulty/TestService/'. The underlying connection was closed: An unexpected error occurred on a send. Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. An existing connection was forcibly closed by the remote host Metadata contains a reference that cannot be resolved: 'https://localhost:8734/Design_Time_Addresses/TransportSecTaulty/TestService/'. An error occurred while making the HTTP request to https://localhost:8734/Design_Time_Addresses/TransportSecTaulty/TestService/. This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server. The underlying connection was closed: An unexpected error occurred on a send. Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. An existing connection was forcibly closed by the remote host If the service is defined in the current solution, try building the solution and adding the service reference again. I am unable to browse my servie in browser. However, the same thing works perfectly on http. Problem only comes in https. Any idea what can be wrong? A: You've got <endpoint address="" binding="basicHttpBinding" bindingConfiguration="serviceConfig" contract="TransportSecTaulty.ITestService"> but I expect you want binding="basicHttpsBinding" A: You are trying to protect the metadata with https, while the service itself is plain http. Is that really what you want? MSDN has an article on securing meta data. It also secures the service itself (which is reasonable - why secure metadata and not the service?) A: you should use WSHttpBinding ......
{ "language": "en", "url": "https://stackoverflow.com/questions/7544493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error: 'Unable to add mapping for keyPath news, one already exists...' I am using RestKit to get data from a Restful Web Service. With a flat file it works great. My problem starts if I want to get the response to a nested JSON. My JSON looks like: [{"homename":"Alien","created_at":"2011-09-15T12:46:37Z", "updated_at":"2011-09-15T12:46:37Z","gametype":"Final match", "id":1,"date":"2016-10-10","guestname":"Predator", "news":[{"minute":null,"created_at":"2011-09-15T13:19:51Z","player":null,"title":"Title", "updated_at":"2011-09-15T13:19:51Z","id":1,"bodytext":"News","game_id":1},{"minute":null,"created_at":"2011-09-15T13:22:06Z","player":null,"title":"New news","updated_at":"2011-09-15T13:22:06Z","id":2,"bodytext":"Old socks","game_id":1},{"minute":null,"created_at":"2011-09-15T13:26:32Z","player":null,"title":"another title","updated_at":"2011-09-15T13:26:32Z","id":3,"bodytext":"Bodytext 2","game_id":1},{"minute":null,"created_at":"2011-09-22T12:35:19Z","player":null,"title":"comment","updated_at":"2011-09-22T12:35:19Z","id":4,"bodytext":"body of the comment","game_id":1}]}] With the following code I would like to get the data mapped. RKLogConfigureByName("RestKit/Network*", RKLogLevelTrace); // Initialize RestKit RKObjectManager* objectManager = [RKObjectManager objectManagerWithBaseURL:@"http://X.X.X.X:3000"]; // Enable automatic network activity indicator management //objectManager.client.requestQueue.showsNetworkActivityIndicatorWhenBusy = YES; RKObjectMapping* newsMapping = [RKObjectMapping mappingForClass:[News class]]; [newsMapping mapKeyPath:@"id" toAttribute:@"id"]; [newsMapping mapKeyPath:@"minute" toAttribute:@"minute"]; [newsMapping mapKeyPath:@"title" toAttribute:@"title"]; [newsMapping mapKeyPath:@"bodytext" toAttribute:@"bodytext"]; // Setup our object mappings RKObjectMapping* gameMapping = [RKObjectMapping mappingForClass:[Game class]]; // [gameMapping mapKeyPath:@"id" toAttribute:@"id"]; [gameMapping mapKeyPath:@"guestname" toAttribute:@"guestname"]; [gameMapping mapKeyPath:@"homename" toAttribute:@"homename"]; [gameMapping mapKeyPath:@"date" toAttribute:@"date"]; [gameMapping mapKeyPath:@"gametype" toAttribute:@"gametype"]; [gameMapping mapKeyPath:@"news" toAttribute:@"news"]; [gameMapping mapKeyPath:@"news" toRelationship:@"news" withMapping:newsMapping]; [objectManager.mappingProvider setMapping:gameMapping forKeyPath:@"games"]; The statement [gameMapping mapKeyPath:@"news" toRelationship:@"news" withMapping:newsMapping]; raises an exception during runtime and I cannot figure out why: *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Unable to add mapping for keyPath news, one already exists...' Does someone see what I am doing wrong? Is the relation wrong for a 1:n relation? A: You have two mappings for news keyPath: [gameMapping mapKeyPath:@"news" toAttribute:@"news"]; and [gameMapping mapKeyPath:@"news" toRelationship:@"news" withMapping:newsMapping]; remove the first and see if it helps. Cheers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How would I go about expanding my PHP code library with Python code? I have a rather large API written in PHP that I've worked on for years. Some of the functionality needs to be upgraded to the extent where I should really just rewrite the classes. Since I need to scrap the old code anyway, I was thinking perhaps I could replace the old functionality with Python code. I came across PiP while searching for answers, and it seems like an exellent solution (Since I can actually create Python class instances in PHP and call their methods etc.) but it seems it was abandoned in the Alpha stages for reasons unknown to me. I suppose the simplest solution would be a CLI one, meaning I could run a python instance from PHP and collect the results. I don't particularly like this solution though, considering the amount of Python code I'd have to write just to handle input from PHP and respond accordingly. Plus it's not very reusable. I don't know if this is a normal problem, Google certainly don't seem to think so, but what would be the best way of complementing a PHP code library with Python code? A: I can think of two options, which should also make the overall solution somewhat more flexible: * *Write it as a web service: Write the python parts as a RESTful web service. Should be relatively straightforward to do. *Use something like ZeroMQ to create a message queue: There are zmq libraries for both PHP and Python, which should also make this option not very difficult to implement. As you may have noticed, all the options can be somewhat clunky in nature. You didn't mention what exactly did you mean by "API" (eg. is it a library or web service or what), so depending on what it is, it might just be easiest to rewrite it in PHP - it's not a bad language in the end if used properly. A: After some time researching this, I've concluded that there is no worthwhile way of building on a PHP library with Python code. The PiP project was the closest thing I could find but it has been abandoned. My solution has been to declare a 2.0. Every new function I add I write in Python. I translate some code from PHP to Python when necessary. It's working great so far!
{ "language": "en", "url": "https://stackoverflow.com/questions/7544498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Iterating through an Object array I have created an object array with the following code: $data = (object)array(); and populated it with data. it's results should look something like this when i'm done: Data-> accounts-> 54-> today-> sales checkout_fees trans_fees payable week-> sales checkout_fees trans_fees payable month-> sales checkout_fees trans_fees payable year-> sales checkout_fees trans_fees payable 55-> today-> sales checkout_fees trans_fees payable week-> sales checkout_fees trans_fees payable month-> sales checkout_fees trans_fees payable year-> sales checkout_fees trans_fees payable When i try to perform a foreach on an element in the tree it fails: foreach ($data->accounts as $account) { echo ("Working to calculate account for account ".$account."<br>\n"); } the error i get is this: Catchable fatal error: Object of class stdClass could not be converted to string I presume this is because I am trying to echo an array instead of the actual "account" name. Is there a way to grab this account name or it's sub (i.e. 55) and set it to a variable? I will need that same variable to iterate through and perform calculations on data in the array under it so this would help two-fold. Thanks, Silver Tiger UPDATE: *************************** Here is my object: object(stdClass)#11 (4) { ["56"]=> object(stdClass)#12 (3) { ["week"]=> object(stdClass)#13 (4) { ["sales"]=> float(6) ["checkout_fees"]=> float(0) ["trans_fees"]=> float(0.67) } ["month"]=> object(stdClass)#21 (4) { ["sales"]=> float(6) ["checkout_fees"]=> float(0) ["trans_fees"]=> float(0.67) } ["year"]=> object(stdClass)#27 (4) { ["sales"]=> float(6) ["checkout_fees"]=> float(0) ["trans_fees"]=> float(0.67) } } ["55"]=> object(stdClass)#15 (3) { ["week"]=> object(stdClass)#16 (4) { ["sales"]=> float(24) ["checkout_fees"]=> float(0) ["trans_fees"]=> float(0.67) } ["month"]=> object(stdClass)#23 (5) { ["sales"]=> float(24) ["checkout_fees"]=> float(0) ["trans_fees"]=> float(0.67) ["payable"]=> string(5) "14.00" } ["year"]=> object(stdClass)#29 (5) { ["sales"]=> float(24) ["checkout_fees"]=> float(0) ["trans_fees"]=> float(2.68) ["payable"]=> string(5) "14.00" } } ["54"]=> object(stdClass)#18 (3) { ["week"]=> object(stdClass)#19 (4) { ["sales"]=> float(4) ["checkout_fees"]=> float(0) ["trans_fees"]=> float(0.67) } ["month"]=> object(stdClass)#25 (4) { ["sales"]=> float(4) ["checkout_fees"]=> float(0) ["trans_fees"]=> float(0.67) } ["year"]=> object(stdClass)#31 (4) { ["sales"]=> float(4) ["checkout_fees"]=> float(0) ["trans_fees"]=> float(0.67) } } ["45"]=> object(stdClass)#33 (3) { ["week"]=> object(stdClass)#34 (1) { ["payable"]=> string(5) "15.00" } ["month"]=> object(stdClass)#35 (1) { ["payable"]=> string(5) "15.00" } ["year"]=> object(stdClass)#36 (1) { ["payable"]=> string(5) "15.00" } } } } I understand it has a heirarchy as it should like a multidimensional array might, but each item is an object. I would need to either be able to grab the name of an object and use that and reference data using the $data->accounts-$variable->week->sales. I will also look into converting an object into an array to work with it, I was just looking for the best solution. UPDATE: for ($counter=1; $counter < 9999; $counter++) { if (isset($data->{$counter})) { echo "Account number ".$counter." has data.<br>\n"; } } Effectively the loop above gives me all the "accounts" that need. I could shove these into an array to use for iteration through my objects and complete the calculations I need, though this is a terribly inefficient way to get a list I have found no way to reference an object's name other than to directly reference it specifically and unfortunately my list is created dynamically .. there's no way to tell in advance. does anyone know a better method to get the list of accounts ID's at the 2nd level of the object? Thanks, Silver Tiger UPDATE: I ended up just querying my database to see which accounts were active on both the "sales" side adn "payable" side and it returned the same list of accounts (45, 54, 55, 56) that was present when creating the object int he first place. I am now using this result to process the data as needed. Thank you though. A: Your $account variable is an object itself, for example: 54-> today-> sales checkout_fees trans_fees payable week-> sales checkout_fees trans_fees payable month-> sales checkout_fees trans_fees payable year-> sales checkout_fees trans_fees payable This cannot be converted to a string. Use this instead: foreach ($data->accounts as $account) { echo ("Working to calculate account for account:"); var_dump($account); } You might also be interested in converting your stdClass object into an array. I'd refer you to this: http://www.if-not-true-then-false.com/2009/php-tip-convert-stdclass-object-to-multidimensional-array-and-convert-multidimensional-array-to-stdclass-object/ A: You have got a composed object, so you need to iterate through each level of your composition to display the strings inside the composite (if that is what you try to achieve, it was not entirely clear to me what you question aims for): Data -> accounts -> account (numbered) -> period -> fees In PHP: foreach($data->accounts as $account) foreach($account as $period) foreach($period as $fee) echo $fee, "\n"; If I read your comment right you need to access the numbered properties, you can do so by putting them into curly brackets: $data->accounts->{54}->week->sales - $data->accounts->{55}->week->transaction_fees As you then wrote in your comment that you've got a problem to find about all numbers of accounts, which are just object variables of $data->accounts. You can get such a list by using the get_object_varsDocs function: $numbers = get_object_vars($data->accounts); I hope this helps you to continue further.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Saving a model in local storage I'm using Jerome's localStorage adapter with Backbone and it works great for collections. But, now I have a single model that I need to save. So in my model I set: localStorage: new Store("msg") I then do my saves and fetch. My problem is that everytime I do a refresh and initialize my app a new representation of my model is added to localStorage, see below. What am I doing wrong? window.localStorage.msg = { // Created after first run "1de5770c-1431-3b15-539b-695cedf3a415":{ "title":"First run", "id":"1de5770c-1431-3b15-539b-695cedf3a415" }, // Created after second run "26c1fdb7-5803-a61f-ca12-2701dba9a09e":{ "0":{ "title":"First run", "id":"1de5770c-1431-3b15-539b-695cedf3a415" }, "title":"Second run", "id":"26c1fdb7-5803-a61f-ca12-2701dba9a09e" } } A: I'm new to backbone.js too, but it looks like the persistence model is analogous to database tables. That is to say, it's designed to create/delete/read records from a table. The localStorage adapter does the same, so what you are doing there is creating a Msg "table" in localStorage, and creating a new Msg "record" each time, and the adapter gives each new Msg a unique id. If you just have one object, it's probably easier to just use localStorage directly. The API is really straight forward: localStorage.setItem("key","value"); Keep in mind that localStorage only deals with key/value pairs as strings, so you'd need to convert to/from string format. Take a look a this question for more on doing that: Storing Objects in HTML5 localStorage A: I ran into same issue. Maybe you have something similar to this var Settings = Backbone.Model.extend({ localStorage: new Store("Settings"), defaults: { a: 1 } }); var s = new Settings; s.fetch(); I changed to var s = new Settings({ id: 1 }); localStorage adapter check for id like case "read": resp = model.id ? store.find(model) : store.findAll(); break; so 0 or "" for id wont work and it will return all models in one
{ "language": "en", "url": "https://stackoverflow.com/questions/7544503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: problem with 3 button layout in android I have an activity with three buttons in the layout. All the buttons are at the bottom. I wanted the button to be extreme left,centre and extreme right. The extreme right and the extreme left buttons are fine. However, the centre button is taking up all the space in between the left and right button. However, I want the middle button to take necessary space and not all the space. Also, I am unable to move the imageButton to the middle of the screen. Any help with these things? Here's my XML layout file: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout android:id="@+id/rel" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/backgroundnr" xmlns:android="http://schemas.android.com/apk/res/android" > <ImageButton android:id="@+id/imageButtons" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/tempText2" android:layout_above="@+id/tempText" android:gravity="center" android:src="@drawable/start" android:background="@null" android:layout_gravity="center_horizontal" > </ImageButton> <TextView android:id="@+id/tempText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Touch to Start" android:layout_centerVertical="true" android:layout_gravity="center_vertical" > </TextView> <ImageView android:id="@+id/bottomlayout" android:layout_width="fill_parent" android:layout_height="100px" android:src="@drawable/bottombar" android:layout_alignParentBottom="true" > </ImageView> <Button android:id="@+id/profileButtons" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Profile" android:drawableTop="@drawable/profiledefault" android:gravity = "bottom" android:background="#0000" android:layout_alignParentBottom="true" android:layout_alignLeft="@+id/bottomlayout" android:textColor="#FFFFFF" android:paddingLeft="10dip" android:paddingBottom="5dip" > </Button> <Button android:id="@+id/savedButtons" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Saved" android:drawableTop="@drawable/favoritesdefault" android:gravity = "bottom" android:background="#0000" android:layout_alignParentBottom="true" android:textColor="#FFFFFF" android:paddingBottom="5dip" android:layout_toRightOf="@+id/profileButtons" android:layout_toLeftOf="@+id/recentButtons" android:layout_gravity="center_horizontal" > </Button> <Button android:id="@+id/recentButtons" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Recent" android:drawableTop="@drawable/recentdefault" android:gravity = "bottom" android:background="#0000" android:layout_alignParentBottom="true" android:textColor="#FFFFFF" android:layout_alignParentRight="true" android:paddingRight="10dip" android:paddingBottom="5dip" > </Button> </RelativeLayout> A: use android:layout_centerHorizontal="true" for your ImageButton instead of layout_gravity. and to rearrange your bottom buttons. don't use leftOf or rightOf for middle button which is "savedButtons" . just use android:layout_centerHorizontal="true" for it. And for the left button "profileButtons" use android:layout_toLeftOf = "@+id/savedButtons" for the right button "recentButtons" use android:layout_toRightOf = "@+id/savedButtons" In this layout middle button will occupy the center space necessary , and the remaining left and right areas are used for the remaining buttons. you will need alignParentBottom for each of 3 buttons. HTH.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use created connection string of Web.Config in my C# asp.net 4.0 project? Actually I am new in this topic so required some help. I have added connection string in Web.Config <connectionStrings> <add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/> </connectionStrings> and know that, to use it I have to put this statement in my C# code behind string connStr = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString; That's all I know. My Question is What should I do if I want to execute some query for my aspnetdb.mdf dataabase (Built in db of ASP.NET built in login contols in Visual Studio 2010) Earlier, I was doing this to accomplish my task 1) No connection string in Web.Config. and 2) Hard code in codebehind SqlConnection con = new SqlConnection("data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"); SqlCommand cmd = new SqlCommand(); protected void btnnameedit_Click(object sender, EventArgs e) { try { con.Open(); cmd.CommandText = "update tamhankarnikhil set fname = '" + fname.Text + "'"; cmd.Connection = con; cmd.ExecuteNonQuery(); con.Close(); fname.Text = ""; } catch (Exception a) { Response.Write(a.Message); } } A: Here's what you could do: protected void btnnameedit_Click(object sender, EventArgs e) { try { string connStr = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString; using (var conn = new SqlConnection(connStr)) using (var cmd = conn.CreateCommand()) { conn.Open(); cmd.CommandText = "UPDATE tamhankarnikhil SET fname = @fname"; cmd.Parameters.AddWithValue("@fname", fname.Text); cmd.ExecuteNonQuery(); fname.Text = ""; } } catch (Exception a) { Response.Write(a.Message); } } You will notice the usage of parametrized queries to avoid SQL injection to which your code was vulnerable to due to the string concatenations you were using when constructing the SQL query. You will also notice that the SqlConnection and SqlCommand are wrapped in using statements to ensure their proper disposal even in the event of an exception.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Thinking Sphinx Application Wide Search and Dealing with Results The use case is this: I'd like to let my user search from a single text box, then on the search results page organize the results by class, essentially. So for example, say I have the following models configured for Thinking Sphinx: Post, Comment and User. (In my situation i have about 10 models but for clarity on StackOverflow I'm pretending there are only 3) When i do a search similar to: ThinkingSphinx.search 'search term', :classes => [Post, Comment, User] I'm not sure the best way to iterate through the results and build out the sections of my page. My first inclination is to do something like: * *Execute the search *Iterate over the returned result set and do a result.is_a?(ClassType) *Based on the ClassType, add the item to 1 of 3 arrays -- @match_posts, @matching_comments, or @matching_users *Pass those 3 instance variables down to my view Is there a better or more efficient way to do this? Thank you! A: If you have only 3 models to search from then why don't you use only model.search instead of ThinkingSphinx.search . This would resolve your problem of performing result.is_a?. That means easier treatment to the way you want to display results for each model. A: I think it comes down to what's useful for people using your website. Does it make sense to have the same query run across all models? Then ThinkingSphinx.search is probably best, especially from a performance perspective. That said, do you want to group search results by their respective classes? Then some sorting is necessary. Or are you separating each class's results, like a GitHub search? Then having separate collections may be worthwhile, like what you've already thought of. At a most basic level, you could just return everything sorted by relevance instead of class, and then just render slightly different output depending on each result. A case statement may help with this - best to keep as much of the logic in helpers, and/or possibly partials?
{ "language": "en", "url": "https://stackoverflow.com/questions/7544515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass a variable from jQuery to a variable in View of MVC3? Possible Duplicate: How to pass variable from jquery to code in c# In my View I have a variable named as shown below x: @{ int x;} I want to set a value to x from within my jQuery code. How can I do it ? A: by this: @{var x = 5;} <script type="text/javascript"> var c= @(x); alert(c); </script> A: Just use @x to get the value. Ex. @{int x = 42;} <script type="text/javascript"> var x = @(x); alert('The answer to the Ultimate Question of Life, the Universe, and Everything is ' + x); </script> A: you can do something like this... @{ // declare this in your view int x = 100; } $(document).ready(function() { var postdata = @x + 100; // here is the updated code. if you want to change the value eg. this will alert 200 alert(postdata); $.ajax({ url: 'Home/Index', data: postdata, success: function (returnData) { alert(returnData); // this will alert 210 } }); }); Your Controller public ActionResult Index(int x) // x will get the value here which is 200 here now.. { var y = x + 10; // do some logic here with the posted data from your view return Json(y,JsonRequestBehaviour.AllowGet); // you will need to return Json here cos you using the AJAX call }
{ "language": "en", "url": "https://stackoverflow.com/questions/7544517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I would like to read an example of ArrayList with Objects.(Java) I have created two classes and I am trying to invoke a constructor(with argument) and a method. I find it easy if I just use an object. My Goal : * *To invoke the same method by using 3 objects. *Use ArrayList to invoke the method 3 times. My Homework: I did google a bit. I happen to end with explanation of ArrayList and certain examples of it. I did not find examples which I think I need i.e. using ArrayList with Objects(like my citation). public class DrawGraphics { BouncingBox box; /** Initializes this class for drawing. */ public DrawGraphics() { box = new BouncingBox(200, 50, Color.green); box.setMovementVector(1, 1); } //.................. //................ } Thank you for those who try to help. A: Continuing with your example this might give you an idea of what Lists can be used for: // Let's create an ArrayList that will contain the bouncingboxes List<BouncingBox> boxList = new ArrayList<BouncingBox>(); // Let's create 5 of them and add them to the end of the List for (int ii=0;ii<5;ii++) { boxList.add(new BouncingBox(200, 50, Color.green)); } // Iterate over the List we just created with the enhanced for - the method will // be called on all objects in the List. for (BouncingBox box : boxList) { box.setMovementVector(1, 1); } Is this what you were looking for? A: I'm sure this wont help the original poster unless they are taking the class over but: The details of this assignment are available on MIT "opencourseware" the goal of the assignment is to create 3 different objects by modifying provided code, an array list is not needed, an array is not needed for that matter, you simple create additional boxes by adding similar code ie: box = new BouncingBox(200, 50, Color.green); box.setMovementVector(1, 1); box2 = new BouncingBox(100, 100, Color.cyan); box2.setMovementVector(2,-1); etc... the second function in that same class needs to be modified as well, it will look something like this: public void draw(Graphics surface) { surface.drawLine(50, 50, 250, 250); box.draw(surface); box2.draw(surface); box3.draw(surface); } note that if you're actually interested in programming as a career or hobby, but don't understand what you're doing in class, it's a good idea to ask for help. Simply copying the answers online will not save you in the real world.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Images display in chrome but not in ie When browsing a url link to an image in ie it shows that the image doesnt exist(box with red cross in it). Its the same if I browse the image using safari on my iphone but displays a black box instead. However if you browse exactly the same url in chrome it does show the image. I've checked the server and the image file is in the correct location. There are 1000's of other images in that location too, most of which display ok in any browser.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create dynamic form? How to make this dynamic form? Hello How to make this dynamic form? "Possible answer" must have: name='1', name='2', name='3' to name='6'. A: You need a plugin like * *AWESOME FORMS *JQWIZARD *SMART WIZARD http://plugins.jquery.com/plugin-tags/wizard to convert a form into a multipage user experience with thumbnails for easy navigation
{ "language": "en", "url": "https://stackoverflow.com/questions/7544523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Like Box plugin for my URL (not for Facebook Page URL) I want to have a likebox plugin for my own URL (not a Facebook Page URL) E.g. http://www.example.com/product1.html http://www.example.com/product2.html I already have opengraph meta data, and user are able to like it, but I want to have likebox kind of plugin showing user faces...is it possible? A: Facebook says the Facebook Like Box is only for Facebook pages. You could generate a like button with a show faces option for your website though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Diagnostics.StopWatch time lag in XP but not Win7 ETA: Using Environment.TickCount does not present the same problem. ETA2: I should add that I don't actually use the Forms.Timer in my app - as this would negate the use of a high frequency timer. I've used it here to simplify the code. ETA3: I've published a workaround as an answer below. I'm having problems with the StopWatch class that I'm observing on a laptop with XP but not a different laptop with Win7. Here's the test code: Public Class FormTest Inherits Form Private WithEvents Timer1 As System.Windows.Forms.Timer = New System.Windows.Forms.Timer Private sw As Stopwatch = New Stopwatch Public Sub New() Me.Timer1.Interval = 1 End Sub Protected Overrides Sub OnClick(ByVal e As System.EventArgs) MyBase.OnClick(e) Me.sw.Start() Me.Timer1.Start() End Sub Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick Me.Text = sw.ElapsedMilliseconds.ToString Me.Update() End Sub End Class On windows 7, checking the ellapsed milliseconds every second, I get something like: 0, 1010, 2030, 3005 ... On XP, I get something like: 0, 200, 306, 390, 512, ... That is, it is way off. We're not talking about milliseconds. It's nothing to do with whether the timer is high resolution, as that reports as true. As far as I know it's nothing to do with processor affinity as I've tried setting that to each of the 2 processors. As I say, I think this is to do with XP, but it could be to do with the different cores - both laptops are, however, intel. A: Do you set the interval of the timer anywhere? To me it looks like they are running with different intervals. The Win7 is roughly fired every second. The XP one looks like it could be fired every 100ms (with a few sample points missed - it's hard to read things that fast). I can't find any documentation on the default timer interval. If it is undocumented, it could have been changed between OS and .NET framework versions between your machines. A: I've solved the problem by using the timeGetTime method instead. The following code is basically the Diagnostics.StopWatch class but with the QueryPerformanceCounter call replaced with timeGetTime. I haven't fully tested it yet* but, from what I've read, I should be able to make a call to TimeBeginPeriod(1) to achieve resolution in line with the framework stopwatch. (*If have fully tested it now and it does achieve millisecond accuracy). If anyone can tell me how to make QueryPerformanceCounter work for XP (if indeed XP is the problem), or detect if there is a problem, I'll un-mark this and mark yours as the answer. Imports System.Runtime.InteropServices Friend Class StopWatch Private Elapsed As Integer Private StartTimeStamp As Integer Public Sub Start() If Not Me._IsRunning Then Me.StartTimeStamp = StopWatch.timeGetTime Me._IsRunning = True End If End Sub Public Sub [Stop]() If Me.isRunning Then Me.Elapsed = (Me.Elapsed + (StopWatch.timeGetTime - Me.StartTimeStamp)) Me._IsRunning = False If (Me.Elapsed < 0) Then Me.Elapsed = 0 End If End If End Sub Public Sub Reset() Me.Elapsed = 0 Me._IsRunning = False Me.StartTimeStamp = 0 End Sub Private _IsRunning As Boolean Public ReadOnly Property IsRunning() As Boolean Get Return Me._IsRunning End Get End Property Public ReadOnly Property ElapsedMilliseconds() As Integer Get Dim elapsed = Me.Elapsed If Me._IsRunning Then elapsed = (elapsed + (StopWatch.timeGetTime - Me.StartTimeStamp)) End If Return elapsed End Get End Property <DllImport("winmm.dll", SetLastError:=True)> _ Private Shared Function timeGetTime() As Integer End Function End Class
{ "language": "en", "url": "https://stackoverflow.com/questions/7544534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring @ModelAttribute doesn't care about commandName JSP: <form:form commandName="editWeather" method="post" action="../edit"> <!-- Input fields --> <input type="submit" value="Submit"> </form:form> And this is how I get the model in Spring: @ModelAttribute("DONTGIVEADAMN") Weather weather And I can still use the weather to do my operations and it works great, for example: weatherService.editWeather(weather); My question is...Why does this work? A: Model attribute name doesn't matter when binding data received from a form (because names of form fields correspond to the names of fields of the model object), it matters only when rendering a form. I particular, when model attribute name in your POST handler method doesn't match the commandName in the form, you will be able to receive the data, but won't be able to redisplay a form with validation errors. A: its matching the class type (or interface), not the name of the variable/parameter; and the specified request mapping/method signature must be correct.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Arbitrary characters for forward-word/backward-word in Emacs How to add an arbitrary character (hyphen, for example) to forward/backward-word functionality, so Emacs would handle words like "k-vector" as a single word. The same question about double-click on the word. A: Syntax tables define which character is considered a word constituent. You can read about it here. A: Emacs's notion of "word" is rather fixed and doesn't quite match what you want. You can mess with the syntax-table, but it might break functionality of the major-mode. AFAICT what you want is to handle what Emacs calls "symbols" rather than "words". E.g. use forward-symbol and backward-symbol commands. The easiest way to use those other commands might be to enable superword-mode. A: Add following to your .emacs file to make hyphen included in words for every major mode: (add-hook 'after-change-major-mode-hook (lambda () (modify-syntax-entry ?- "w"))) A: You can use this code it use regular expression it use space or parents as word separator (defun backward-word-with-dash () (interactive) (search-backward-regexp "[ ()][A-Za-z\-]+ *") (forward-char)) (defun forward-word-with-dash () (interactive) (search-forward-regexp " *[A-Za-z\-]+[ ()]") (backward-char)) (global-set-key "\M-b" 'backward-word-with-dash) (global-set-key "\M-f" 'forward-word-with-dash) if you want other characters just add it to the regex
{ "language": "en", "url": "https://stackoverflow.com/questions/7544536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Removing duplicates from string array I'm new to C#, have looked at numerous posts but am still confused. I have a array list: List<Array> moves = new List<Array>(); I'm adding moves to it using the following: string[] newmove = { piece, axis.ToString(), direction.ToString() }; moves.Add(newmove); And now I wish to remove duplicates using the following: moves = moves.Distinct(); However it's not letting me do it. I get this error: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?) Help please? I'd be so grateful. Steve A: You need to call .ToList() after the .Distinct method as it returns IEnumerable<T>. I would also recommend you using a strongly typed List<string[]> instead of List<Array>: List<string[]> moves = new List<string[]>(); string[] newmove = { piece, axis.ToString(), direction.ToString() }; moves.Add(newmove); moves.Add(newmove); moves = moves.Distinct().ToList(); // At this stage moves.Count = 1 A: Your code has two errors. The first is the missing call to ToList, as already pointed out. The second is subtle. Unique compares objects by identity, but your duplicate list items have are different array instances. There are multiple solutions for that problem. * *Use a custom equality comparer in moves.Distinct().ToList(). No further changes necessary. Sample implementation: class ArrayEqualityComparer<T> : EqualityComparer<T> { public override bool Equals(T[] x, T[] y) { if ( x == null ) return y == null; else if ( y == null ) return false; return x.SequenceEquals(y); } public override int GetHashCode(T[] obj) { if ( obj == null) return 0; return obj.Aggregate(0, (hash, x) => hash ^ x.GetHashCode()); } } Filtering for unique items: moves = moves.Distinct(new ArrayEqualityComparer<string>()).ToList(); *Use Tuple<string,string,string> instead of string[]. Tuple offers built-in structural equality and comparison. This variant might make your code cluttered because of the long type name. Instantiation: List<Tuple<string, string, string>> moves = new List<Tuple<string, string, string>>(); Adding new moves: Tuple<string, string, string> newmove = Tuple.Create(piece, axis.ToString(), direction.ToString()); moves.Add(newmove); Filtering for unique items: moves = moves.Distinct().ToList(); *Use a custom class to hold your three values. I'd actually recommend this variant, because it makes all your code dealing with moves much more readable. Sample implementation: class Move { public Move(string piece, string axis, string direction) { Piece = piece; Axis = axis; Direction = direction; } string Piece { get; private set; } string Axis { get; private set; } string Direction { get; private set; } public override Equals(object obj) { Move other = obj as Move; if ( other != null ) return Piece == other.Piece && Axis == other.Axis && Direction == other.Direction; return false; } public override GetHashCode() { return Piece.GetHashCode() ^ Axis.GetHashCode() ^ Direction.GetHashCode(); } // TODO: override ToString() as well } Instantiation: List<Move> moves = new List<Move>(); Adding new moves: Move newmove = new Move(piece, axis.ToString(), direction.ToString()); moves.Add(newmove); Filtering for unique items: moves = moves.Distinct().ToList(); A: The compiler error is because you need to convert the result to a list: moves = moves.Distinct().ToList(); However it probably won't work as you want, because arrays don't have Equals defined in the way that you are hoping (it compares the references of the array objects, not the values inside the array). Instead of using an array, create a class to hold your data and define Equals and GetHashCode to compare the values. A: Old question, but this is an O(n) solution using O(1) additional space: public static void RemoveDuplicates(string[] array) { int c = 0; int i = -1; for (int n = 1; n < array.Length; n++) { if (array[c] == array[n]) { if (i == -1) { i = n; } } else { if (i == -1) { c++; } else { array[i] = array[n]; c++; i++; } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7544543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Database efficiency - table per user vs. table of users For a website having users. Each user having the ability to create any amount of, we'll call it "posts": Efficiency-wise - is it better to create one table for all of the posts, saving the user-id of the user which created the post, for each post - OR creating a different separate table for each user and putting there just the posts created by that user? A: Schemas with a varying number of tables are, generally, bad. Use one single table for your posts. A: If performance is a concern, you should learn about database indexes. While indexes is not part of the SQL standard, nearly all databases support them to help improve performance. I recommend that you create a single table for all users' posts and then add an indexes to this table to improve the performance of searching. For example you can add an index on the user column so that you can quickly find all posts for a given user. You may also want to consider adding other indexes, depending on your application's requirements. A: The database layout should not change when you add more data to it, so the user data should definitely be in one table. Also: * *Having multiple tables means that you have to create queries dynamically. *The cached query plan for one table won't be used for any other of the tables. *Having a lot of data in one table doesn't affect performance much, but having a lot of tables does. *If you want to add an index to the table to make queries faster, it's a lot easier to do on a single table. A: Your first proposal of having a single user and a single post table is the standard approach to take. At the moment posts may be the only user-specific feature on your site, but imagine that it might need to grow in the future to support users having messages, preferences, etc. Now your separate table-per-user approach leads to an explosion in the number of tables you'd need to create. A: Well to answer the specific question: In terms of efficiency of querying, it will always be better to have small tables, hence a table per user is likely to be the most efficient. However, unless you have a lot of posts and users, this is not likely to matter. Even with millions of rows, you will get good performance with a well-placed index. I would strongly advise against the table-per-user strategy, because it adds a lot of complexity to your solution. How would you query when you need to find, say, users that have posted on a subject within the year ? Optimize when you need to. Not because you think/are afraid something will be slow. (And even if you need to optimize, there will be easier options than table-per-user) A: I have a similar but different issue with your answer because both @guffa and @driis are assuming that the "posts" need to be shared among users. In my particular situation: not a single user datapoint can be shared for privacy reason with any other user not even for analytics. We plan on using mysql or postgres and here are the three options our team is warring about: N schema and 5 tables - some of our devs feel that this is the best direction to make to keep the data completely segregated. Pros - less complexity if you think of schema as a folder and tables as files. We'll have one schema per user Cons - most ORMs do connection pooling per schema 1 schema and nx5 tables - some devs like this because it allows for connection pooling but appears to make the issue more complex. Pros - connection pooling in the ORM is possible Cons - cannot find an ORM where Models are set up for this 1 schema and 5 tables - some devs like this because they think we benefit from caching. Pros: ORMs are happy because this is what they are designed to do Cons: every query requires the username table I, personally, land in camp 1: n schemas. My lead dev lands in camp 3: 1 schema 5 tables. Caching: If data is always 1:1, I cannot see how caching will ever help regardless of the solution we use because each user will be searching for different info. Any thoughts?
{ "language": "en", "url": "https://stackoverflow.com/questions/7544544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "38" }
Q: django imagefield save NoneType Object error How can I upload images with imagefield? The following is giving me a 'NoneType' object has no attribute 'chunks'. I believe I am doing this wrong, can someone show me the correct way of doing this? This is what I have so far for saving the uploaded image. def add_employee(request): if request.method == 'POST': form_input = AddEmployee(request.POST, request.FILES) if form_input.is_valid(): cd = form_input.cleaned_data new_emp = Employees( first_name = cd['first_name'] ..... ) new_emp.save() photo_file = cd['photo_file'] new_emp.photo.save('filename', photo_file) return HttpResponseRedirect('/thanks/') forms.py and models.py class AddEmployee(forms.Form): ... photo_file = forms.ImageField(required=False) class Employees(models.Model): ... photo = models.ImageField(upload_to='employee_photos', blank=True, null=True) A: Okay after some digging around I found out what the problem was. request.FILES is getting nothing, hence the NoneType i needed to add enctype=multipart/form-data in my form in order for the request to work. A: You should probably be using modelforms. With a modelform, your code would look something like this: in forms.py: from django import forms from .models import Employees class EmployeeForm(forms.ModelForm): class Meta: model = Employees in views.py: from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import EmployeeForm def add_employee(request): form = EmployeeForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() return HttpResponseRedirect('/thanks/') return render(request, 'your_template.html', {'form': form}) This is the standard/best practice way to deal with forms that are related to models. The request.POST or None is a trick to avoid having to check request.method == 'POST'. This is the simple case, you can easily add select fields to be included/excluded from your model, add extra fields for a specific form, add extra logic to be run before your model is saved, or add custom validation. See the documentation for ModelForms: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/
{ "language": "en", "url": "https://stackoverflow.com/questions/7544548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript: REGEX to change all relative Urls to Absolute I'm currently creating a Node.js webscraper/proxy, but I'm having trouble parsing relative Urls found in the scripting part of the source, I figured REGEX would do the trick. Although it is unknown how I would achieve this. Is there anyway I can go about this? Also I'm open to an easier way of doing this, as I'm quite baffle about how other proxies parse websites. I figured that most are just glorified site scrapers that can read a site's source a relay all links/forms back to the proxy. A: Advanced HTML string replacement functions Note for OP, because he requested such a function: Change base_url to your proxy's basE URL in order to achieve the desired results. Two functions will be shown below (the usage guide is contained within the code). Make sure that you don't skip any part of the explanation of this answer to fully understand the function's behaviour. * *rel_to_abs(urL) - This function returns absolute URLs. When an absolute URL with a commonly trusted protocol is passed, it will immediately return this URL. Otherwise, an absolute URL is generated from the base_url and the function argument. Relative URLs are correctly parsed (../ ; ./ ; . ; //). *replace_all_rel_by_abs - This function will parse all occurences of URLs which have a significant meaning in HTML, such as CSS url(), links and external resources. See the code for a full list of parsed instances. See this answer for an adjusted implementation to sanitise HTML strings from an external source (to embed in the document). *Test case (at the bottom of the answer): To test the effectiveness of the function, simply paste the bookmarklet at the location's bar. rel_to_abs - Parsing relative URLs function rel_to_abs(url){ /* Only accept commonly trusted protocols: * Only data-image URLs are accepted, Exotic flavours (escaped slash, * html-entitied characters) are not supported to keep the function fast */ if(/^(https?|file|ftps?|mailto|javascript|data:image\/[^;]{2,9};):/i.test(url)) return url; //Url is already absolute var base_url = location.href.match(/^(.+)\/?(?:#.+)?$/)[0]+"/"; if(url.substring(0,2) == "//") return location.protocol + url; else if(url.charAt(0) == "/") return location.protocol + "//" + location.host + url; else if(url.substring(0,2) == "./") url = "." + url; else if(/^\s*$/.test(url)) return ""; //Empty = Return nothing else url = "../" + url; url = base_url + url; var i=0 while(/\/\.\.\//.test(url = url.replace(/[^\/]+\/+\.\.\//g,""))); /* Escape certain characters to prevent XSS */ url = url.replace(/\.$/,"").replace(/\/\./g,"").replace(/"/g,"%22") .replace(/'/g,"%27").replace(/</g,"%3C").replace(/>/g,"%3E"); return url; } Cases / examples: * *http://foo.bar. Already an absolute URL, thus returned immediately. */doo Relative to the root: Returns the current root + provided relative URL. *./meh Relative to the current directory. *../booh Relative to the parent directory. The function converts relative paths to ../, and performs a search-and-replace (http://domain/sub/anything-but-a-slash/../me to http://domain/sub/me). replace_all_rel_by_abs - Convert all relevant occurences of URLs URLs inside script instances (<script>, event handlers are not replaced, because it's near-impossible to create a fast-and-secure filter to parse JavaScript. This script is served with some comments inside. Regular Expressions are dynamically created, because an individual RE can have a size of 3000 characters. <meta http-equiv=refresh content=.. > can be obfuscated in various ways, hence the size of the RE. function replace_all_rel_by_abs(html){ /*HTML/XML Attribute may not be prefixed by these characters (common attribute chars. This list is not complete, but will be sufficient for this function (see http://www.w3.org/TR/REC-xml/#NT-NameChar). */ var att = "[^-a-z0-9:._]"; var entityEnd = "(?:;|(?!\\d))"; var ents = {" ":"(?:\\s|&nbsp;?|&#0*32"+entityEnd+"|&#x0*20"+entityEnd+")", "(":"(?:\\(|&#0*40"+entityEnd+"|&#x0*28"+entityEnd+")", ")":"(?:\\)|&#0*41"+entityEnd+"|&#x0*29"+entityEnd+")", ".":"(?:\\.|&#0*46"+entityEnd+"|&#x0*2e"+entityEnd+")"}; /* Placeholders to filter obfuscations */ var charMap = {}; var s = ents[" "]+"*"; //Short-hand for common use var any = "(?:[^>\"']*(?:\"[^\"]*\"|'[^']*'))*?[^>]*"; /* ^ Important: Must be pre- and postfixed by < and >. * This RE should match anything within a tag! */ /* @name ae @description Converts a given string in a sequence of the original input and the HTML entity @param String string String to convert */ function ae(string){ var all_chars_lowercase = string.toLowerCase(); if(ents[string]) return ents[string]; var all_chars_uppercase = string.toUpperCase(); var RE_res = ""; for(var i=0; i<string.length; i++){ var char_lowercase = all_chars_lowercase.charAt(i); if(charMap[char_lowercase]){ RE_res += charMap[char_lowercase]; continue; } var char_uppercase = all_chars_uppercase.charAt(i); var RE_sub = [char_lowercase]; RE_sub.push("&#0*" + char_lowercase.charCodeAt(0) + entityEnd); RE_sub.push("&#x0*" + char_lowercase.charCodeAt(0).toString(16) + entityEnd); if(char_lowercase != char_uppercase){ /* Note: RE ignorecase flag has already been activated */ RE_sub.push("&#0*" + char_uppercase.charCodeAt(0) + entityEnd); RE_sub.push("&#x0*" + char_uppercase.charCodeAt(0).toString(16) + entityEnd); } RE_sub = "(?:" + RE_sub.join("|") + ")"; RE_res += (charMap[char_lowercase] = RE_sub); } return(ents[string] = RE_res); } /* @name by @description 2nd argument for replace(). */ function by(match, group1, group2, group3){ /* Note that this function can also be used to remove links: * return group1 + "javascript://" + group3; */ return group1 + rel_to_abs(group2) + group3; } /* @name by2 @description 2nd argument for replace(). Parses relevant HTML entities */ var slashRE = new RegExp(ae("/"), 'g'); var dotRE = new RegExp(ae("."), 'g'); function by2(match, group1, group2, group3){ /*Note that this function can also be used to remove links: * return group1 + "javascript://" + group3; */ group2 = group2.replace(slashRE, "/").replace(dotRE, "."); return group1 + rel_to_abs(group2) + group3; } /* @name cr @description Selects a HTML element and performs a search-and-replace on attributes @param String selector HTML substring to match @param String attribute RegExp-escaped; HTML element attribute to match @param String marker Optional RegExp-escaped; marks the prefix @param String delimiter Optional RegExp escaped; non-quote delimiters @param String end Optional RegExp-escaped; forces the match to end before an occurence of <end> */ function cr(selector, attribute, marker, delimiter, end){ if(typeof selector == "string") selector = new RegExp(selector, "gi"); attribute = att + attribute; marker = typeof marker == "string" ? marker : "\\s*=\\s*"; delimiter = typeof delimiter == "string" ? delimiter : ""; end = typeof end == "string" ? "?)("+end : ")("; var re1 = new RegExp('('+attribute+marker+'")([^"'+delimiter+']+'+end+')', 'gi'); var re2 = new RegExp("("+attribute+marker+"')([^'"+delimiter+"]+"+end+")", 'gi'); var re3 = new RegExp('('+attribute+marker+')([^"\'][^\\s>'+delimiter+']*'+end+')', 'gi'); html = html.replace(selector, function(match){ return match.replace(re1, by).replace(re2, by).replace(re3, by); }); } /* @name cri @description Selects an attribute of a HTML element, and performs a search-and-replace on certain values @param String selector HTML element to match @param String attribute RegExp-escaped; HTML element attribute to match @param String front RegExp-escaped; attribute value, prefix to match @param String flags Optional RegExp flags, default "gi" @param String delimiter Optional RegExp-escaped; non-quote delimiters @param String end Optional RegExp-escaped; forces the match to end before an occurence of <end> */ function cri(selector, attribute, front, flags, delimiter, end){ if(typeof selector == "string") selector = new RegExp(selector, "gi"); attribute = att + attribute; flags = typeof flags == "string" ? flags : "gi"; var re1 = new RegExp('('+attribute+'\\s*=\\s*")([^"]*)', 'gi'); var re2 = new RegExp("("+attribute+"\\s*=\\s*')([^']+)", 'gi'); var at1 = new RegExp('('+front+')([^"]+)(")', flags); var at2 = new RegExp("("+front+")([^']+)(')", flags); if(typeof delimiter == "string"){ end = typeof end == "string" ? end : ""; var at3 = new RegExp("("+front+")([^\"'][^"+delimiter+"]*" + (end?"?)("+end+")":")()"), flags); var handleAttr = function(match, g1, g2){return g1+g2.replace(at1, by2).replace(at2, by2).replace(at3, by2)}; } else { var handleAttr = function(match, g1, g2){return g1+g2.replace(at1, by2).replace(at2, by2)}; } html = html.replace(selector, function(match){ return match.replace(re1, handleAttr).replace(re2, handleAttr); }); } /* <meta http-equiv=refresh content=" ; url= " > */ cri("<meta"+any+att+"http-equiv\\s*=\\s*(?:\""+ae("refresh")+"\""+any+">|'"+ae("refresh")+"'"+any+">|"+ae("refresh")+"(?:"+ae(" ")+any+">|>))", "content", ae("url")+s+ae("=")+s, "i"); cr("<"+any+att+"href\\s*="+any+">", "href"); /* Linked elements */ cr("<"+any+att+"src\\s*="+any+">", "src"); /* Embedded elements */ cr("<object"+any+att+"data\\s*="+any+">", "data"); /* <object data= > */ cr("<applet"+any+att+"codebase\\s*="+any+">", "codebase"); /* <applet codebase= > */ /* <param name=movie value= >*/ cr("<param"+any+att+"name\\s*=\\s*(?:\""+ae("movie")+"\""+any+">|'"+ae("movie")+"'"+any+">|"+ae("movie")+"(?:"+ae(" ")+any+">|>))", "value"); cr(/<style[^>]*>(?:[^"']*(?:"[^"]*"|'[^']*'))*?[^'"]*(?:<\/style|$)/gi, "url", "\\s*\\(\\s*", "", "\\s*\\)"); /* <style> */ cri("<"+any+att+"style\\s*="+any+">", "style", ae("url")+s+ae("(")+s, 0, s+ae(")"), ae(")")); /*< style=" url(...) " > */ return html; } A short summary of the private functions: * *rel_to_abs(url) - Converts relative / unknown URLs to absolute URLs *replace_all_rel_by_abs(html) - Replaces all relevant occurences of URLs within a string of HTML by absolute URLs. * *ae - Any Entity - Returns a RE-pattern to deal with HTML entities. *by - replace by - This short function request the actual url replace (rel_to_abs). This function may be called hundreds, if not thousand times. Be careful to not add a slow algorithm to this function (customisation). *cr - Create Replace - Creates and executes a search-and-replace.Example: href="..." (within any HTML tag). *cri - Create Replace Inline - Creates and executes a search-and-replace.Example: url(..) within the all style attribute within HTML tags. Test case Open any page, and paste the following bookmarklet in the location bar: javascript:void(function(){var s=document.createElement("script");s.src="http://rob.lekensteyn.nl/rel_to_abs.js";document.body.appendChild(s)})(); The injected code contains the two functions, as defined above, plus the test case, shown below. Note: The test case does not modify the HTML of the page, but shows the parsed results in a textarea (optionally). var t=(new Date).getTime(); var result = replace_all_rel_by_abs(document.documentElement.innerHTML); if(confirm((new Date).getTime()-t+" milliseconds to execute\n\nPut results in new textarea?")){ var txt = document.createElement("textarea"); txt.style.cssText = "position:fixed;top:0;left:0;width:100%;height:99%" txt.ondblclick = function(){this.parentNode.removeChild(this)} txt.value = result; document.body.appendChild(txt); } See also: * *Answer: Parsing and sanitising HTML strings A: A reliable way to convert urls from relative to absolute is to use the built-in url module. Example: var url = require('url'); url.resolve("http://www.example.org/foo/bar/", "../baz/qux.html"); >> gives 'http://www.example.org/foo/baz/qux.html' A: This is Rob W answer "Advanced HTML string replacement functions" in current thread plus some code re-factoring from me to make JSLint happy. I should post it as answer's comment but I don't have enough reputation points. /*jslint browser: true */ /*jslint regexp: true */ /*jslint unparam: true*/ /*jshint strict: false */ /** * convertRelToAbsUrl * * https://stackoverflow.com/a/7544757/1983903 * * @param {String} url * @return {String} updated url */ function convertRelToAbsUrl(url) { var baseUrl = null; if (/^(https?|file|ftps?|mailto|javascript|data:image\/[^;]{2,9};):/i.test(url)) { return url; // url is already absolute } baseUrl = location.href.match(/^(.+)\/?(?:#.+)?$/)[0] + '/'; if (url.substring(0, 2) === '//') { return location.protocol + url; } if (url.charAt(0) === '/') { return location.protocol + '//' + location.host + url; } if (url.substring(0, 2) === './') { url = '.' + url; } else if (/^\s*$/.test(url)) { return ''; // empty = return nothing } url = baseUrl + '../' + url; while (/\/\.\.\//.test(url)) { url = url.replace(/[^\/]+\/+\.\.\//g, ''); } url = url.replace(/\.$/, '').replace(/\/\./g, '').replace(/"/g, '%22') .replace(/'/g, '%27').replace(/</g, '%3C').replace(/>/g, '%3E'); return url; } /** * convertAllRelativeToAbsoluteUrls * * https://stackoverflow.com/a/7544757/1983903 * * @param {String} html * @return {String} updated html */ function convertAllRelativeToAbsoluteUrls(html) { var me = this, att = '[^-a-z0-9:._]', entityEnd = '(?:;|(?!\\d))', ents = { ' ' : '(?:\\s|&nbsp;?|&#0*32' + entityEnd + '|&#x0*20' + entityEnd + ')', '(' : '(?:\\(|&#0*40' + entityEnd + '|&#x0*28' + entityEnd + ')', ')' : '(?:\\)|&#0*41' + entityEnd + '|&#x0*29' + entityEnd + ')', '.' : '(?:\\.|&#0*46' + entityEnd + '|&#x0*2e' + entityEnd + ')' }, charMap = {}, s = ents[' '] + '*', // short-hand for common use any = '(?:[^>\"\']*(?:\"[^\"]*\"|\'[^\']*\'))*?[^>]*', slashRE = null, dotRE = null; function ae(string) { var allCharsLowerCase = string.toLowerCase(), allCharsUpperCase = string.toUpperCase(), reRes = '', charLowerCase = null, charUpperCase = null, reSub = null, i = null; if (ents[string]) { return ents[string]; } for (i = 0; i < string.length; i++) { charLowerCase = allCharsLowerCase.charAt(i); if (charMap[charLowerCase]) { reRes += charMap[charLowerCase]; continue; } charUpperCase = allCharsUpperCase.charAt(i); reSub = [charLowerCase]; reSub.push('&#0*' + charLowerCase.charCodeAt(0) + entityEnd); reSub.push('&#x0*' + charLowerCase.charCodeAt(0).toString(16) + entityEnd); if (charLowerCase !== charUpperCase) { reSub.push('&#0*' + charUpperCase.charCodeAt(0) + entityEnd); reSub.push('&#x0*' + charUpperCase.charCodeAt(0).toString(16) + entityEnd); } reSub = '(?:' + reSub.join('|') + ')'; reRes += (charMap[charLowerCase] = reSub); } return (ents[string] = reRes); } function by(match, group1, group2, group3) { return group1 + me.convertRelToAbsUrl(group2) + group3; } slashRE = new RegExp(ae('/'), 'g'); dotRE = new RegExp(ae('.'), 'g'); function by2(match, group1, group2, group3) { group2 = group2.replace(slashRE, '/').replace(dotRE, '.'); return group1 + me.convertRelToAbsUrl(group2) + group3; } function cr(selector, attribute, marker, delimiter, end) { var re1 = null, re2 = null, re3 = null; if (typeof selector === 'string') { selector = new RegExp(selector, 'gi'); } attribute = att + attribute; marker = typeof marker === 'string' ? marker : '\\s*=\\s*'; delimiter = typeof delimiter === 'string' ? delimiter : ''; end = typeof end === 'string' ? '?)(' + end : ')('; re1 = new RegExp('(' + attribute + marker + '")([^"' + delimiter + ']+' + end + ')', 'gi'); re2 = new RegExp('(' + attribute + marker + '\')([^\'' + delimiter + ']+' + end + ')', 'gi'); re3 = new RegExp('(' + attribute + marker + ')([^"\'][^\\s>' + delimiter + ']*' + end + ')', 'gi'); html = html.replace(selector, function (match) { return match.replace(re1, by).replace(re2, by).replace(re3, by); }); } function cri(selector, attribute, front, flags, delimiter, end) { var re1 = null, re2 = null, at1 = null, at2 = null, at3 = null, handleAttr = null; if (typeof selector === 'string') { selector = new RegExp(selector, 'gi'); } attribute = att + attribute; flags = typeof flags === 'string' ? flags : 'gi'; re1 = new RegExp('(' + attribute + '\\s*=\\s*")([^"]*)', 'gi'); re2 = new RegExp("(" + attribute + "\\s*=\\s*')([^']+)", 'gi'); at1 = new RegExp('(' + front + ')([^"]+)(")', flags); at2 = new RegExp("(" + front + ")([^']+)(')", flags); if (typeof delimiter === 'string') { end = typeof end === 'string' ? end : ''; at3 = new RegExp('(' + front + ')([^\"\'][^' + delimiter + ']*' + (end ? '?)(' + end + ')' : ')()'), flags); handleAttr = function (match, g1, g2) { return g1 + g2.replace(at1, by2).replace(at2, by2).replace(at3, by2); }; } else { handleAttr = function (match, g1, g2) { return g1 + g2.replace(at1, by2).replace(at2, by2); }; } html = html.replace(selector, function (match) { return match.replace(re1, handleAttr).replace(re2, handleAttr); }); } cri('<meta' + any + att + 'http-equiv\\s*=\\s*(?:\"' + ae('refresh') + '\"' + any + '>|\'' + ae('refresh') + '\'' + any + '>|' + ae('refresh') + '(?:' + ae(' ') + any + '>|>))', 'content', ae('url') + s + ae('=') + s, 'i'); cr('<' + any + att + 'href\\s*=' + any + '>', 'href'); /* Linked elements */ cr('<' + any + att + 'src\\s*=' + any + '>', 'src'); /* Embedded elements */ cr('<object' + any + att + 'data\\s*=' + any + '>', 'data'); /* <object data= > */ cr('<applet' + any + att + 'codebase\\s*=' + any + '>', 'codebase'); /* <applet codebase= > */ /* <param name=movie value= >*/ cr('<param' + any + att + 'name\\s*=\\s*(?:\"' + ae('movie') + '\"' + any + '>|\'' + ae('movie') + '\'' + any + '>|' + ae('movie') + '(?:' + ae(' ') + any + '>|>))', 'value'); cr(/<style[^>]*>(?:[^"']*(?:"[^"]*"|'[^']*'))*?[^'"]*(?:<\/style|$)/gi, 'url', '\\s*\\(\\s*', '', '\\s*\\)'); /* <style> */ cri('<' + any + att + 'style\\s*=' + any + '>', 'style', ae('url') + s + ae('(') + s, 0, s + ae(')'), ae(')')); /*< style=" url(...) " > */ return html; } A: If you use a regex to find all non-absolute URLs, you can then just prefix them with the current URL and that should be it. The URLs you need to fix would be ones which don't start either with a / or http(s):// (or other protocol markers, if you care about them) As an example, let's say you're scraping http://www.example.com/. If you encounter a relative URL, let's say foo/bar, you would simply prefix the URL being scraped to it like so: http://www.example.com/foo/bar For a regex to scrape the URLs from the page, there are probably plenty of good ones available if you google a bit so I'm not going to start inventing a poor one here :) A: From a comment by Rob W above about the base tag I wrote an injection function: function injectBase(html, base) { // Remove any <base> elements inside <head> html = html.replace(/(<[^>/]*head[^>]*>)[\s\S]*?(<[^>/]*base[^>]*>)[\s\S]*?(<[^>]*head[^>]*>)/img, "$1 $3"); // Add <base> just before </head> html = html.replace(/(<[^>/]*head[^>]*>[\s\S]*?)(<[^>]*head[^>]*>)/img, "$1 " + base + " $2"); return(html); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7544550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: testing socket communication offline as a simulation Whenever having to test my app which basically is some kind of communication via sockets with external devices, the device itself has to be available and connected. I would like to ask,if there is a way to do the testing offline in some kind of simulation mode? For instance, redirecting the socket communication to some kind of stored file. And the file itself is a log of a previous session with the real device stored in an appropriate structure. Of course one could only simulate a recorded session, but that would help a lot already. thanks! A: You should have a look at netcat. If you have a record of your "session" in a file, you can use nc to "play it back" on a socket with something like: nc -l -p port_number < your_file You can then connect to that port number with telnet and you'll see the session data coming in. (You can do it the other way around too, i.e. have nc connect to your app and replay the session.) A: Don't know iphone, but having a local client, (or server), app. as a simulator is very common on other platforms. It's especially useful if the peer app is under development as well - having a simulator often surfaces protocol bugs at both ends, (as well as in the simulator:). Given an app spec that includes the protocol, but no peer yet, I usually start work on the simulator first - it gives me time to get experience with the protocol in an non-critical, non-deliverable way while the customer is still bolting on changes to the main app UI :) Rgds, Martin
{ "language": "en", "url": "https://stackoverflow.com/questions/7544553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Efficiently color cycling an image in Java I'm writing a Mandelbrot fractal viewer, and I would like to implement color cycling in a smart way. Given an image, I would like to modify its IndexColorModel. As far as I can tell, there's no way to modify an IndexColorModel, and there's no way to give an image a new IndexColorModel. In fact, I think there's no way to extract its color model or image data. It seems that the only solution is to hold on to the raw image data and color palette that were used to create the image, manually create a new palette with the rotated colors, create a new IndexColorModel, then create a whole new image from the data and new color model. This all seems like too much work. Is there an easier and faster way? Here's the best solution I can come up with. This code creates a 1000x1000 pixel image and shows an animation of the colors cycling at about 30 frames per second. (old) import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.swing.*; public class ColorCycler { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } private static void createAndShowGUI() { JFrame jFrame = new JFrame("Color Cycler"); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jFrame.add(new MyPanel()); jFrame.pack(); jFrame.setVisible(true); } } class MyPanel extends JPanel implements ActionListener { private byte[] reds = new byte[216]; private byte[] greens = new byte[216]; private byte[] blues = new byte[216]; private final byte[] imageData = new byte[1000 * 1000]; private Image image; public MyPanel() { generateColors(); generateImageData(); (new Timer(35, this)).start(); } // The window size is 1000x1000 pixels. public Dimension getPreferredSize() { return new Dimension(1000, 1000); } // Generate 216 unique colors for the color model. private void generateColors() { int index = 0; for (int i = 0; i < 6; i++) { for (int j = 0; j < 6; j++) { for (int k = 0; k < 6; k++, index++) { reds[index] = (byte) (i * 51); greens[index] = (byte) (j * 51); blues[index] = (byte) (k * 51); } } } } // Create the image data for the MemoryImageSource. // This data is created once and never changed. private void generateImageData() { for (int i = 0; i < 1000 * 1000; i++) { imageData[i] = (byte) (i % 216); } } // Draw the image. protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image, 0, 0, 1000, 1000, null); } // This method is called by the timer every 35 ms. // It creates the modified image to be drawn. @Override public void actionPerformed(ActionEvent e) { // Called by Timer. reds = cycleColors(reds); greens = cycleColors(greens); blues = cycleColors(blues); IndexColorModel colorModel = new IndexColorModel(8, 216, reds, greens, blues); image = createImage(new MemoryImageSource(1000, 1000, colorModel, imageData, 0, 1000)); repaint(); } // Cycle the colors to the right by 1. private byte[] cycleColors(byte[] colors) { byte[] newColors = new byte[216]; newColors[0] = colors[215]; System.arraycopy(colors, 0, newColors, 1, 215); return newColors; } } Edit 2: Now I precompute the IndexColorModels. This means that on each frame I only need to update the MemoryImageSource with a new IndexColorModel. This seems like the best solution. (I also just noticed that in my fractal explorer, I can reuse the single set of precomputed IndexColorModels on every image I generate. That means the one-time cost of 140K lets me color cycle everything in real-time. This is great.) Here's the code: import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.swing.*; public class ColorCycler { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } private static void createAndShowGUI() { JFrame jFrame = new JFrame("Color Cycler"); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jFrame.add(new MyPanel()); jFrame.pack(); jFrame.setVisible(true); } } class MyPanel extends JPanel implements ActionListener { private final IndexColorModel[] colorModels = new IndexColorModel[216]; private final byte[] imageData = new byte[1000 * 1000]; private final MemoryImageSource imageSource; private final Image image; private int currentFrame = 0; public MyPanel() { generateColorModels(); generateImageData(); imageSource = new MemoryImageSource(1000, 1000, colorModels[0], imageData, 0, 1000); imageSource.setAnimated(true); image = createImage(imageSource); (new Timer(35, this)).start(); } // The window size is 1000x1000 pixels. public Dimension getPreferredSize() { return new Dimension(1000, 1000); } // Generate 216 unique colors models, one for each frame. private void generateColorModels() { byte[] reds = new byte[216]; byte[] greens = new byte[216]; byte[] blues = new byte[216]; int index = 0; for (int i = 0; i < 6; i++) { for (int j = 0; j < 6; j++) { for (int k = 0; k < 6; k++, index++) { reds[index] = (byte) (i * 51); greens[index] = (byte) (j * 51); blues[index] = (byte) (k * 51); } } } for (int i = 0; i < 216; i++) { colorModels[i] = new IndexColorModel(8, 216, reds, greens, blues); reds = cycleColors(reds); greens = cycleColors(greens); blues = cycleColors(blues); } } // Create the image data for the MemoryImageSource. // This data is created once and never changed. private void generateImageData() { for (int i = 0; i < 1000 * 1000; i++) { imageData[i] = (byte) (i % 216); } } // Draw the image. protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image, 0, 0, 1000, 1000, null); } // This method is called by the timer every 35 ms. // It updates the ImageSource of the image to be drawn. @Override public void actionPerformed(ActionEvent e) { // Called by Timer. currentFrame++; if (currentFrame == 216) { currentFrame = 0; } imageSource.newPixels(imageData, colorModels[currentFrame], 0, 1000); repaint(); } // Cycle the colors to the right by 1. private byte[] cycleColors(byte[] colors) { byte[] newColors = new byte[216]; newColors[0] = colors[215]; System.arraycopy(colors, 0, newColors, 1, 215); return newColors; } } Edit: (old) Heisenbug suggested that I use the newPixels() method of MemoryImageSource. The answer has since been deleted, but it turned out to be a good idea. Now I only create one MemoryImageSource and one Image. On each frame I create a new IndexColorModel and update the MemoryImageSource. Here's the updated code: (old) import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.swing.*; public class ColorCycler { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } private static void createAndShowGUI() { JFrame jFrame = new JFrame("Color Cycler"); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jFrame.add(new MyPanel()); jFrame.pack(); jFrame.setVisible(true); } } class MyPanel extends JPanel implements ActionListener { private byte[] reds = new byte[216]; private byte[] greens = new byte[216]; private byte[] blues = new byte[216]; private final byte[] imageData = new byte[1000 * 1000]; private final MemoryImageSource imageSource; private final Image image; public MyPanel() { generateColors(); generateImageData(); IndexColorModel colorModel = new IndexColorModel(8, 216, reds, greens, blues); imageSource = new MemoryImageSource(1000, 1000, colorModel, imageData, 0, 1000); imageSource.setAnimated(true); image = createImage(imageSource); (new Timer(35, this)).start(); } // The window size is 1000x1000 pixels. public Dimension getPreferredSize() { return new Dimension(1000, 1000); } // Generate 216 unique colors for the color model. private void generateColors() { int index = 0; for (int i = 0; i < 6; i++) { for (int j = 0; j < 6; j++) { for (int k = 0; k < 6; k++, index++) { reds[index] = (byte) (i * 51); greens[index] = (byte) (j * 51); blues[index] = (byte) (k * 51); } } } } // Create the image data for the MemoryImageSource. // This data is created once and never changed. private void generateImageData() { for (int i = 0; i < 1000 * 1000; i++) { imageData[i] = (byte) (i % 216); } } // Draw the image. protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image, 0, 0, 1000, 1000, null); } // This method is called by the timer every 35 ms. // It updates the ImageSource of the image to be drawn. @Override public void actionPerformed(ActionEvent e) { // Called by Timer. reds = cycleColors(reds); greens = cycleColors(greens); blues = cycleColors(blues); IndexColorModel colorModel = new IndexColorModel(8, 216, reds, greens, blues); imageSource.newPixels(imageData, colorModel, 0, 1000); repaint(); } // Cycle the colors to the right by 1. private byte[] cycleColors(byte[] colors) { byte[] newColors = new byte[216]; newColors[0] = colors[215]; System.arraycopy(colors, 0, newColors, 1, 215); return newColors; } } A: In addition to pre-computing the cycles, as @Thomas comments, factor out the magic number 1000. Here's a related example of Changing the ColorModel of a BufferedImage and a project you may like. Addendum: Factoring out magic numbers will allow you to change them reliably while profiling, which is required to see if you're making progress. Addendum: While I suggested three color lookup tables per frame, your idea to pre-compute IndexColorModel instances is even better. As an alternative to an array, consider a Queue<IndexColorModel>, with LinkedList<IndexColorModel> as a concrete implementation. This simplifies your model rotation as shown below. @Override public void actionPerformed(ActionEvent e) { // Called by Timer. imageSource.newPixels(imageData, models.peek(), 0, N); models.add(models.remove()); repaint(); } Addendum: One more variation to dynamically change the color models and display timing. import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.IndexColorModel; import java.awt.image.MemoryImageSource; import java.util.LinkedList; import java.util.Queue; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; /** @see http://stackoverflow.com/questions/7546025 */ public class ColorCycler { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new ColorCycler().create(); } }); } private void create() { JFrame jFrame = new JFrame("Color Cycler"); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final ColorPanel cp = new ColorPanel(); JPanel control = new JPanel(); final JSpinner s = new JSpinner( new SpinnerNumberModel(cp.colorCount, 2, 256, 1)); s.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { cp.setColorCount(((Integer) s.getValue()).intValue()); } }); control.add(new JLabel("Shades:")); control.add(s); jFrame.add(cp, BorderLayout.CENTER); jFrame.add(control, BorderLayout.SOUTH); jFrame.pack(); jFrame.setLocationRelativeTo(null); jFrame.setVisible(true); } private static class ColorPanel extends JPanel implements ActionListener { private static final int WIDE = 256; private static final int PERIOD = 40; // ~25 Hz private final Queue<IndexColorModel> models = new LinkedList<IndexColorModel>(); private final MemoryImageSource imageSource; private final byte[] imageData = new byte[WIDE * WIDE]; private final Image image; private int colorCount = 128; public ColorPanel() { generateColorModels(); generateImageData(); imageSource = new MemoryImageSource( WIDE, WIDE, models.peek(), imageData, 0, WIDE); imageSource.setAnimated(true); image = createImage(imageSource); (new Timer(PERIOD, this)).start(); } // The preferred size is NxN pixels. @Override public Dimension getPreferredSize() { return new Dimension(WIDE, WIDE); } public void setColorCount(int colorCount) { this.colorCount = colorCount; generateColorModels(); generateImageData(); repaint(); } // Generate MODEL_SIZE unique color models. private void generateColorModels() { byte[] reds = new byte[colorCount]; byte[] greens = new byte[colorCount]; byte[] blues = new byte[colorCount]; for (int i = 0; i < colorCount; i++) { reds[i] = (byte) (i * 256 / colorCount); greens[i] = (byte) (i * 256 / colorCount); blues[i] = (byte) (i * 256 / colorCount); } models.clear(); for (int i = 0; i < colorCount; i++) { reds = rotateColors(reds); greens = rotateColors(greens); blues = rotateColors(blues); models.add(new IndexColorModel( 8, colorCount, reds, greens, blues)); } } // Rotate colors to the right by one. private byte[] rotateColors(byte[] colors) { byte[] newColors = new byte[colors.length]; newColors[0] = colors[colors.length - 1]; System.arraycopy(colors, 0, newColors, 1, colors.length - 1); return newColors; } // Create some data for the MemoryImageSource. private void generateImageData() { for (int i = 0; i < imageData.length; i++) { imageData[i] = (byte) (i % colorCount); } } // Draw the image. @Override protected void paintComponent(Graphics g) { super.paintComponent(g); long start = System.nanoTime(); imageSource.newPixels(imageData, models.peek(), 0, WIDE); models.add(models.remove()); double delta = (System.nanoTime() - start) / 1000000d; g.drawImage(image, 0, 0, getWidth(), getHeight(), null); g.drawString(String.format("%1$5.3f", delta), 5, 15); } // Called by the Timer every PERIOD ms. @Override public void actionPerformed(ActionEvent e) { // Called by Timer. repaint(); } } } A: I'd use LWJGL (OpenGL interface to Java) with a Mandelbrot pixel shader, and do the colour-cycling in the shader. Far more efficient than using Java2D. http://nuclear.mutantstargoat.com/articles/sdr_fract/
{ "language": "en", "url": "https://stackoverflow.com/questions/7544559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How to configure SQLite in Kohana 3? I'm struggling to find any information on how to configure SQLite in Kohana 3.2. I mainly need to know: * *What should I set hostname, database, username and password to (with default user and no password)? *Also, how can I set the path to the SQLite database file? *What should the "type" be? I tried "sqlite" but I get an error Class 'Database_Sqlite' not found. This is my current configuration options: 'exportedDatabase' => array ( 'type' => 'sqlite', 'connection' => array( /** * The following options are available for MySQL: * * string hostname server hostname, or socket * string database database name * string username database username * string password database password * boolean persistent use persistent connections? * * Ports and sockets may be appended to the hostname. */ 'hostname' => $hostname, 'database' => $database, 'username' => $username, 'password' => $password, 'persistent' => FALSE, ), 'table_prefix' => '', 'charset' => 'utf8', 'caching' => FALSE, 'profiling' => TRUE, ), A: You can use PDO through Database module. The proper way of configuring it looks like this: 'exportedDatabase' => array( 'type' => 'pdo', 'connection' => array( 'dsn' => 'sqlite:/path/to/file.sqlite', 'persistent' => FALSE, ), 'table_prefix' => '', 'charset' => NULL, /* IMPORTANT- charset 'utf8' breaks sqlite(?) */ 'caching' => FALSE, 'profiling' => TRUE, ), One disadvantage of using PDO in Kohana is that in ORM you have to specify all fields by hand in your model (you should do it anyway for performance reasons) because of how different database systems handle listing of table fields. There is also real database module created by banditron. You have to remember that's it is NOT a drop-in replacement for Database module and therefore Kohana's ORM will not work with it. Other than that it's pretty neat and has wide support for database systems other than SQLite. A: As I found out, Kohana 3.x doesn't actually support SQLite. There's an unsupported module for it and, as far as I can tell, it's not working. It's easy enough to use PDO though and the syntax is pretty much the same as Kohana's ORM: $db = new PDO('sqlite:' . $dbFilePath); $query = $db->prepare('CREATE TABLE example (id INTEGER PRIMARY KEY, something TEXT)'); $query->execute(); $query = $db->prepare("INSERT INTO example (id, something) VALUES (:id, :something)"); $query->bindParam(':id', $id); $query->bindParam(':something', $something); $query->execute(); A: I don't use Kohana, but this should work: 'hostname' => /path/to/your/sql/lite/file.sqlite 'database' => '' 'username' => '' 'password' => ''
{ "language": "en", "url": "https://stackoverflow.com/questions/7544568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why non-displaying HTML tags interfere with Displaying tags I often face a problem when I need to encapsulate some far apart fields in one form, and the fields in between them in other forms. Or encapsulating first two rows of a table in form and other two in other forms and so on. But of-course this is not allowed in standard practice. My question is why such tags like form (and other non displaying tags) have to be treated as "displaying" tags, and they also are restricted to be used at some places. Is there any genuine reason. PS: what I was thinking about form in particular, that I define as many forms as I want at a single place, and give their references (eg ids or names) to the corresponding fields. That way form tag does not have to interfere somehow with the location of fields? A: How is a <form> a non-displaying element? You can apply all kinds of CSS on it, and they will show up. It's just that they usually have no default browser styles. It's a rookie mistake to wrap elements in <div>s and styling those, when the only thing inside them is a single element. <div class="myform"><form>...</form></div> <form><div class="myform">...</div></form> Both equally superfluous. Just style the original element directly. <form class="myform">...</form> Now, before you jump on my back: I'm not saying you're doing that. Just a general advice. About restricted usage: that's probably to make it easier for implementors (browser creators) and for backwards compatibility. A: Asking "why" questions of HTML behaviour is not normally a useful activity. Very often the answer is "because one of the browsers originally did it that way and we're stuck with it for backward-compatibility reasons". Note also what @DanMan says about the displayability of <form>. However, your description of declaring forms in one place and then having the controls associate with the forms by id, is very similar to what has been done with the HTML5 form attribute. The only difference is that the controls reference the forms, rather than the forms referencing the controls. All we need to do now is wait for implementations in the browsers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Split variable-value in a regex I'm using Javascript regex functions to split expressions like: var1=32 var2<var4 var1!=var3 I'm using this regex: /^(.*)([=|!=|<|>])(.*)$/ig It works pretty well except with the != (different) operator. What's the problem? A: The problem is you are using a character class instead of an alternation. The expression [=|!=|<|>] is equivalent to [<>=!|]. Remove the [ and ] to get what you want. /^(.*?)(!=|=|<|>)(.*)$/ig I've also changed the first (.*) to be non-greedy so that it doesn't consume the ! in !=. If you know that the left and right expressions will always contain (for example) only alphanumeric characters only, it would be better to specify that instead of matching with the dot.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: overriding object parameters using UNITY I've started a project usinjg MS Unity as my IOC container and have two questions regarding overriding parameters. public interface ITab { bool AllowVisible {get;set;} } class Tab : ITab { IViewModel vm; public Tab(IViewModel vm) { this.vm = vm; } public bool allowVisible = false; public bool AllowVisible { get{ return allowVisible}; set{ allowVisible = vlaue}; } } public interface IViewModule { string Name; } public class ViewModel { public string Name; } 1) How do i set up the Tab type in unity so that i can pass in true or false to the AllowVisible property as a paramater? I dont want to have to add the additional line of tab.AllowVisible = true; as in the case below void Main() { ITab tab = unityContainer.RegisterType<ITab, Tab>(); tab.AllowVisible = true; } 2) If i already have an instance of the ViewModel, such as vm in the case below, how do i make the container resolve the Tab object while passing in the vm object into its constructor? Currently when i resolve for the tab object, the container creates another instance of the ViewModel. I want the vm instance to get used as the tab objects viewmodel? void Main() { unityContainer.RegisterType<IViewModel, ViewModel>(); unityContainer.RegisterType<ITab, Tab>(); ViewModel vm = unityContainer.Resolve<IViewModel>(); ITab tab = unityContainer.RegisterType<ITab, Tab>(); } A: If you automatically want to assign a value to the AllowVisible property of your ITab implementation then you can use the InjectionProperty type provided by Unity. You can do this in a fluent way, for example: IUnityContainer myContainer = new UnityContainer(); myContainer.Configure<InjectedMembers>() .ConfigureInjectionFor<MyObject>( new InjectionProperty("MyProperty"), new InjectionProperty("MyStringProperty", "SomeText")) ); A bit more concrete: container.RegisterType<ITab, Tab>(); container.RegisterType<ITab, Tab>( new InjectionProperty("AllowVisible", true) ); For more information on how to inject constructor parameters, property values...etc, check out: http://msdn.microsoft.com/en-us/library/ff650036.aspx As for the second part of you question, you must pass constructor parameters (IViewModel) to Unity's Resolve(...) method when you resolve an implementation for an ITab. This question has been asked before on SO, check out: Can I pass constructor parameters to Unity's Resolve() method? For completeness' sake: var viewModel = container.Resolve<IViewModel>(); container.Resolve<ITab>(new ParameterOverrides<Tab> { { "vm", viewModel} });"
{ "language": "en", "url": "https://stackoverflow.com/questions/7544581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is the information for pywintypes.com_error unreadable? Under Python 2.7.2 with pywin32-216.win32-py2.7 installed, when I use win32com module to process Excel on windows as follows: >>> import win32com.client >>> xlsApp = win32com.client.Dispatch('Excel.Application') >>> xlsApp.Workbooks.Open(r'D:/test.xls') I get an error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<COMObject <unknown>>", line 8, in Open pywintypes.com_error: (-2147352567, '\xb7\xa2\xc9\xfa\xd2\xe2\xcd\xe2\xa1\xa3', (0, u'Microsoft Office Excel', u'\u540d\u4e3a\u201ctest.xls\u201d\u7684\u6587\u6 863\u5df2\u7ecf\u6253\u5f00\u3002\u4e0d\u80fd\u540c\u65f6\u6253\u5f00\u540c\u540 d\u6587\u4ef6\uff0c\u65e0\u8bba\u5b83\u4eec\u662f\u5426\u5728\u540c\u4e00\u6587\ u4ef6\u5939\u4e2d\u3002\n\u8981\u6253\u5f00\u7b2c\u4e8c\u4efd\u6587\u6863\uff0c\ u8bf7\u5173\u95ed\u5df2\u7ecf\u6253\u5f00\u7684\u6587\u6863\uff0c\u6216\u8005\u9 1cd\u65b0\u547d\u540d\u5176\u4e2d\u7684\u4e00\u4e2a\u6587\u6863\u3002', None, 0, -2146827284), None) While the imformation is not readable, I don't konw what's going wrong! After searching on the Internet, I find something helpful at http://www.python-forum.org/pythonforum/viewtopic.php?f=15&t=17665: pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Office Excel', u"'test .xls' could not be found. Check the spelling of the file name, and verify that the file location is correct.\n\nIf you are trying to open the file from your list of most recently used files on the File menu, make sure that the file has not been renamed, moved, or deleted.", u'C:\Program Files\Microsoft Office\OFFICE11\1033\xlmain11.chm', 0, -2146827284), None) I guess it's the same problem, so I create an Excel file 'D:/test.xls' first, and then everything turns ok: >>> xlsApp.Workbooks.Open(r'D:/test.xls') <COMObject Open> If I got the readable error tip, I would solve the problem immediately without any difficult! I wonder why is the error I get from win32com.client like that? Is there anything I can do to make the information readable? I will appreciate your help! A: I imagine that it has come out like that because you are using internationalization settings for somewhere in Far East Asia (China, perhaps?) and you're using Python in the Command Prompt. I'm not sure whether the problem is with Python, the Command Prompt or the combination of the two, but either way the combination of these two doesn't work particularly well with non-Latin internationalization settings. I'd recommend using IDLE instead, since that appears to support Unicode characters properly. Here's what happens when I viewed that last string in IDLE. The text doesn't mean anything to me, but it might do to you: IDLE 2.6.4 >>> z = u'\u540d\u4e3a\u201ctest.xls\u201d\u7684\u6587\u6863\u5df2\u7ecf\u6253\u5f00\u3002\u4e0d\u80fd\u540c\u65f6\u6253\u5f00\u540c\u540d\u6587\u4ef6\uff0c\u65e0\u8bba\u5b83\u4eec\u662f\u5426\u5728\u540c\u4e00\u6587\u4ef6\u5939\u4e2d\u3002\n\u8981\u6253\u5f00\u7b2c\u4e8c\u4efd\u6587\u6863\uff0c\u8bf7\u5173\u95ed\u5df2\u7ecf\u6253\u5f00\u7684\u6587\u6863\uff0c\u6216\u8005\u91cd\u65b0\u547d\u540d\u5176\u4e2d\u7684\u4e00\u4e2a\u6587\u6863\u3002' >>> print z 名为“test.xls”的文档已经打开。不能同时打开同名文件,无论它们是否在同一文件夹中。 要打开第二份文档,请关闭已经打开的文档,或者重新命名其中的一个文档。 >>> However, even when using IDLE, chances are that when you get the exception, the text will still appear as it did above. If this happens, what you need to do is to get the data from the last exception raised and print the relevant string from within it. To get the last exception raised in the interpreter, you can use sys.last_value. Here's an example with a different exception message: >>> import sys >>> with open('nonexistent.txt') as f: pass ... Traceback (most recent call last): File "", line 1, in with open('nonexistent.txt') as f: pass IOError: [Errno 2] No such file or directory: 'nonexistent.txt' >>> sys.last_value IOError(2, 'No such file or directory') >>> print(sys.last_value[1]) No such file or directory >>> A: I experienced a similar error. In my particular case I was trying to use a temporary file created like this: fileprefix = 'Report' filesuffix = '.xlsx' filename = tempfile.gettempdir() + '\\' + fileprefix + filesuffix xfile = tempfile.NamedTemporaryFile(suffix = filesuffix, prefix = fileprefix) Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later). So, it seems that I cannot re-use that file in Windows OS. And that is the reason that I am getting the error. In your case, you may want to check how the file is being created in the first place.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to handle multiple jLists with one ListSelectionEvent I have three jLists in my class frmMain. I have created a class called ListActions. The code below is working for one jList. It returns the value clicked for one jList. How do I distinguish between the three other jList? Or do I need to create a seperate class for each listener? I need to perform an action based on which jList was clicked. I attempted to see if I could access the variable name of the jList that was clicked, but couldn't find a way to do this... class ListActions implements ListSelectionListener { public void valueChanged(ListSelectionEvent evt) { if (!evt.getValueIsAdjusting()) { JList list = (JList) evt.getSource(); int iSelectedDatabase = list.getSelectedIndex(); Object objSelectedDatabase = list.getModel().getElementAt(iSelectedDatabase); String sSelectedDatabase = objSelectedDatabase.toString(); JOptionPane.showConfirmDialog(null, sSelectedDatabase); } } } Thanks, - Jason A: JList inherits from Component. Therefore, you can use the getName() method to get the name of your Component and know which one has been called.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Extract directory from jar file I have searched for this for a while now, but cant seem to figure it out. I want to extract a directory from a jar/zip file, and save it recursively to a path on the filesystem in java. Anyone know how I might do this? A: An answer from this thread might give a good feeling how/where to start: * *How to extract Java resources from JAR and zip archive Simply put, it's java.util.jar you're looking for. A: I know that the original question was actualy doing this programmatically. But as it wasn't clear enough I guess many users (like me) ends up here when they just want to unzip a directory out of the jar using the jar command. jar -xvf <your>.jar <required-dir> E.g. extract META-INF directory out of some.jar jar -xvf some.jar META-INF to list the content of the jar use jar -tvf some.jar
{ "language": "en", "url": "https://stackoverflow.com/questions/7544600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to store photos in Cassandra? Can anybody tell me how to store photos (jpg, png etc) files in cassandra ? Any small example would give me quick start. A: "Manually split files into chunks of whatever size you are comfortable with". (from CassandraLimitations) Eg. use the file name as the row key and have the chunks as columns. A: Using Asytanax Client (Netflix) you can store large files. Take a look at the link below - https://github.com/Netflix/astyanax/wiki/Chunked-Object-Store You can specify the chunk size that the files would be split into.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to create events in Obj-c via code? I have one UIButton and i need to create event Touch up inside how i can to create this event no using IB in implementation file .m? A: Something like this would do the trick.... [myButton addTarget:self action:@selector(clickMethod:) forControlEvents:UIControlEventTouchUpInside];
{ "language": "en", "url": "https://stackoverflow.com/questions/7544605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Sending an object via sockets java How can I send objects of a class via sockets? As of now I'm only able to send the class members one by one via sockets and I want to send the object as a whole. Explaining with a simple example would be great. Thanks. A: You must use the java.io.Serializable interface for the objects you want to transer. Then ObjectInputStream or ObjectOutputStream to readObject or writeObject E.g. InputStream is = socket.getInputStream(); ObjectInputStream ois = new ObjectInputStream(is); MyObject obj = (MyObject)ois.readObject(); //Now use the object Where: class MyObject implements Serializable { //variables }
{ "language": "en", "url": "https://stackoverflow.com/questions/7544606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I get a textfield in Monotouch to appear as a lined notepad - the same appearance as the 'Notes' application I am experimenting with monotouch for the first time. I have essentially finished my first application, however, I am re-visiting the application to make it more appealing visually and was wondering if I could make a textfield look like the 'Notes' application? Thanks in advance to those who can help. A: I think an easy and simple way is to to do something like the Notes App. Is to use an UITextView and set an Backgroundimage/BackgroundColor, which looks like a paper.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: sharepoint 2010, customized sp ribbon javascript file is not loading properly in chrome....any inputs???? We have customized ribbon(js scripts) that loads properly in IE and firefox but in google chrome(which is a requirement to use it due to its high response time) it does not load the ribbon at the first instance. However, it loads after several page load refreshes(Ctrl + F5). If anyone come across this issue, provide your inputs. Appreciate your help. Thanks A: SharePoint and IIS are always trying to cache resource, to ensure application performace. When you're doing SharePoint Development you've always to ensure that cache is cleared. Especially when you're working with the SharePoint ribbon it's required to clear the cache before accessing the website after deployment. A: When you're using CKS tools for deployment from VS2010 you have to ensure that files are copied to the SharePoint Root. Sometimes I get an exception when they try to overwrite JS files in the SharePoint root, because sharepoint has a handle on them. When doing SharePoint development I always copy *.resx and *.js by hand. A: The issue appears to be with the rendering of the search box control in Google Chrome. Try adding 'Visible="false"' to the 'SharePoint:DelegateControl runat="server" ControlId="SmallSearchInputBox" Version="4"' control on the master page. This corrects the rendering issue for us. A: SharePoint is officially not built to work in Google Chrome A: I just fixed my webkit (chrome and safari) browser issues such as scrolling and the ribbon loading with this nice script http://goo.gl/1OUlI. Ended up being a timing issue. Hope it helps you out. I see this is a bit old but no best answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP echo category names in mysql table I have a table in my mysql database that looks like the following: id | category | title 1 | blue | title1 2 | green | title2 3 | red | title3 4 | purple | title4 5 | red | title5 1 | blue | title1 2 | green | title2 3 | blue | title3 4 | blue | title4 5 | red | title5 ..... I want to echo the category names on my page and then count how many items there are in each category. Goal is something like this: blue(4) green(2) red(3) purple(1) I have tried echoing the categories but I just receive a long list of duplicates. Can anybody point me in the right direction? A: No need to mess with associative arrays. You can easily do this in SQL using GROUP BY and COUNT. See the MySQL manual for an example. A: I'm not going to give you code, since you should be trying to write that yourself and since this sounds like homework. Here's a basic idea of what your PHP script can look like: * *Select all rows from your database. *Create an associative array where category name is the key and number of appearances is the value. *Iterate over the table data you got back from your query, and for each category, increment the respective count in your array. Good luck and feel free to ask another question once you've got some code written.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544611", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get a table automatically updated when another table is updated Using C# How to get a table automatically updated when another table is updated Using C# Hi all, I have 4 (four) tables using MySql database, ie: tb_item ( id_item, (varchar) --> PK item_name, (varchar) price, (double) ) tb_order ( id_order, (varchar) --> PK id_item, (varchar) -->FK date_order, (date) lead_time, (float) order_quantity, (double) ) tb_use ( id_use, (varchar) --> PK id_item, (varchar) -->FK date_use, (date) use_quantity, (double) ) tb_inventory ( id_inventory, (varchar) --> PK id_item, (varchar) --> FK id_order, (varchar) --> FK id_use, (varchar) --> FK item_stock, (double) ) My problem is I want to item_stock in tb_inventory automatically updated: when tb_order.order_quantity or tb_use.use_quantity are updated, then tb_inventory.item_stock will updated automatically by using a calculation “tb_order.order_quantity – tb_use.use_quantity = tb_inventory.item_stock” (Example: 10 - 7 = 3). and vice versa. How to create code for the problem in C#. Please help, thanks in advance. A: You can do it using triggers, but it would be better to normalize your database so that this information is stored only in one place. If you use triggers and somewhow the database is incorrectly updated, that error can persist for a long time unnoticed. An alternative is to create a view which calculates the amount of stock by querying the other tables. This will give a slight performance hit because the value will have to be recalculated every time it is requested. This performance hit can be partially solved by adding indexes to make the recalculation very fast. In the end it depends on whether you are more interested in raw speed, or consistency and correctness of the result.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: running C# web app with schedular in microsoft server I have a web application developed in C# that retrieves data from a database and writes the retrieved to a file. What i need to do is to be able to run this web app regularly on my server(Microsoft server), say once a day to update the data. I think using a schedular would be the way to do it but I don't know how to get it to run my web app i.e my .sln file. I looked at the post below for ideas: Running a web app automatically but need a little more guidance. A: You could write a console application which will send an HTTP request to the web application: class Program { static void Main() { using (var client = new WebClient()) { var result = client.DownloadString("http://example.com/test.aspx"); File.WriteAllText("foo.txt", result); } } } and then configure the Windows Scheduler to run this console application at given time. A: Use a Windows Scheduled Task. If you need to run in the web context, have the scheduled task retrieve a url, that will kick off the processing. A: Here is a sample VB script that can be called by the task scheduler to make an ASP.NET page be executed. Even if this kind of solution is quite common, it is not really a good one. If you have regular maintenance tasks that need to run daily, create a console app that does that and call that directly from scheduled tasks. If you need to run it more frequently, or respond to other events a Windows Service is better.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why don't I get a recursive infinite loop when throwing an error in the onError function? In my coldfusion Application.cfc file, I define an onError function. In certain situations, I explicitly throw an exception using a cfthrow tag - e.g. <cfthrow object="#myException#">. My question is, why doesn't this create an infinite loop? Or at least cause another call to the onError function? (Instead, it just dumps the error to the screen. Which is the functionality I want, actually :) - but I'm still confused about why this happens.) A: This is expected and documented behavior: If an exception occurs while processing the onError method, or if the onError method uses a cfthrow tag, the ColdFusion standard error handling mechanisms handle the exception.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTML- pass data to perl script I want to pass data from an html form to a Perl script, execute the script and display result on HTML page again. A: You can't pass data from HTML to a program directly, you would normally submit a form to a URI and configure the webserver to pass the submitted data to a program and the program's output back to the webbrowser. There are several common ways to do this
{ "language": "en", "url": "https://stackoverflow.com/questions/7544625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Deployement exception on jboss 5.0.1 . GA Hi I am getting following exception when I deploy my war in Jboss 5.0.1.GA Project uses maven. I think it is to do something with jar's Because earlier it was working in my old machine.But in new it is not I had to do changes in pom to successfully build the project. Please suggest. 2011-09-25 13:18:09,421 ERROR [org.jboss.kernel.plugins.dependency.AbstractKernelController] Error installing to Create: name=persistence.unit:unitName=#ldrive state=Configured java.lang.IllegalArgumentException: Wrong target. org.jboss.jpa.deployment.PersistenceUnitDeployment is not a org.jboss.jpa.deployment.PersistenceUnitDeployment at org.jboss.reflect.plugins.introspection.ReflectionUtils.invoke(ReflectionUtils.java:67) at org.jboss.reflect.plugins.introspection.ReflectMethodInfoImpl.invoke(ReflectMethodInfoImpl.java:150) at org.jboss.joinpoint.plugins.BasicMethodJoinPoint.dispatch(BasicMethodJoinPoint.java:66) at org.jboss.kernel.plugins.dependency.KernelControllerContextAction$JoinpointDispatchWrapper.execute(KernelControllerContextAction.java:241) at org.jboss.kernel.plugins.dependency.ExecutionWrapper.execute(ExecutionWrapper.java:47) at org.jboss.kernel.plugins.dependency.KernelControllerContextAction.dispatchExecutionWrapper(KernelControllerContextAction.java:109) at org.jboss.kernel.plugins.dependency.KernelControllerContextAction.dispatchJoinPoint(KernelControllerContextAction.java:70) at org.jboss.kernel.plugins.dependency.LifecycleAction.installActionInternal(LifecycleAction.java:221) at org.jboss.kernel.plugins.dependency.InstallsAwareAction.installAction(InstallsAwareAction.java:54) at org.jboss.kernel.plugins.dependency.InstallsAwareAction.installAction(InstallsAwareAction.java:42) at org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62) at org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71) at org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51) at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348) at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1598) at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934) at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1062) at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984) at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:774) at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:540) at org.jboss.deployers.vfs.deployer.kernel.BeanMetaDataDeployer.deploy(BeanMetaDataDeployer.java:121) at org.jboss.deployers.vfs.deployer.kernel.BeanMetaDataDeployer.deploy(BeanMetaDataDeployer.java:51) at org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer.internalDeploy(AbstractSimpleRealDeployer.java:62) at org.jboss.deployers.spi.deployer.helpers.AbstractRealDeployer.deploy(AbstractRealDeployer.java:50) at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:171) at org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1439) at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1157) at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1178) at org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1098) at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348) at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1598) at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934) at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1062) at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984) at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822) at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553) at org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:781) at org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:698) at org.jboss.system.server.profileservice.ProfileServiceBootstrap.loadProfile(ProfileServiceBootstrap.java:304) at org.jboss.system.server.profileservice.ProfileServiceBootstrap.start(ProfileServiceBootstrap.java:205) at org.jboss.bootstrap.AbstractServerImpl.start(AbstractServerImpl.java:405) at org.jboss.Main.boot(Main.java:209) at org.jboss.Main$1.run(Main.java:547) at java.lang.Thread.run(Thread.java:662) 2011-09-25 13:18:18,348 ERROR [org.jboss.kernel.plugins.dependency.AbstractKernelController] Error installing to Instantiated: name=jboss.jacc:id="vfszip:/D:/Jboss-5.0.Ldrive/server/default/deploy/Ldrive.war/",service=jacc state=Described mode=Manual requiredState=Configured java.lang.Error: Error in the server: mismatch between expected constructor arguments and supplied arguments. at org.jboss.mx.server.MBeanServerImpl.handleInstantiateExceptions(MBeanServerImpl.java:1310) at org.jboss.mx.server.MBeanServerImpl.instantiate(MBeanServerImpl.java:1246) at org.jboss.mx.server.MBeanServerImpl.instantiate(MBeanServerImpl.java:286) at org.jboss.mx.server.MBeanServerImpl.createMBean(MBeanServerImpl.java:344) at org.jboss.system.ServiceCreator.installPlainMBean(ServiceCreator.java:211) at org.jboss.system.ServiceCreator.install(ServiceCreator.java:130) at org.jboss.system.microcontainer.InstantiateAction.installAction(InstantiateAction.java:45) at org.jboss.system.microcontainer.InstantiateAction.installAction(InstantiateAction.java:37) at org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62) at org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71) at org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51) at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348) at org.jboss.system.microcontainer.ServiceControllerContext.install(ServiceControllerContext.java:286) at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1598) at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934) at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1062) at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984) at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822) at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553) at org.jboss.system.ServiceController.doChange(ServiceController.java:688) at org.jboss.system.ServiceController.install(ServiceController.java:274) at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:90) at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:46) at org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer.internalDeploy(AbstractSimpleRealDeployer.java:62) at org.jboss.deployers.spi.deployer.helpers.AbstractRealDeployer.deploy(AbstractRealDeployer.java:50) at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:171) at org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1439) at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1157) at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1178) at org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1098) at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348) at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1598) at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934) at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1062) at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984) at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822) at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553) at org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:781) at org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:698) at org.jboss.system.server.profileservice.ProfileServiceBootstrap.loadProfile(ProfileServiceBootstrap.java:304) at org.jboss.system.server.profileservice.ProfileServiceBootstrap.start(ProfileServiceBootstrap.java:205) at org.jboss.bootstrap.AbstractServerImpl.start(AbstractServerImpl.java:405) at org.jboss.Main.boot(Main.java:209) at org.jboss.Main$1.run(Main.java:547) at java.lang.Thread.run(Thread.java:662) 2011-09-25 13:18:18,370 ERROR [org.jboss.kernel.plugins.dependency.AbstractKernelController] Error installing to Real: name=vfszip:/D:/Jboss-5.0.Ldrive/server/default/deploy/Ldrive.war/ state=PreReal mode=Manual requiredState=Real org.jboss.deployers.spi.DeploymentException: Error deploying: jboss.jacc:service=jacc,id="vfszip:/D:/Jboss-5.0.Ldrive/server/default/deploy/Ldrive.war/" at org.jboss.deployers.spi.DeploymentException.rethrowAsDeploymentException(DeploymentException.java:49) at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:118) at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:46) at org.jboss.deployers.spi.deployer.helpers.AbstractSimpleRealDeployer.internalDeploy(AbstractSimpleRealDeployer.java:62) at org.jboss.deployers.spi.deployer.helpers.AbstractRealDeployer.deploy(AbstractRealDeployer.java:50) at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:171) at org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1439) at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1157) at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1178) at org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1098) at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348) at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1598) at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934) at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1062) at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984) at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822) at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553) at org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:781) at org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:698) at org.jboss.system.server.profileservice.ProfileServiceBootstrap.loadProfile(ProfileServiceBootstrap.java:304) at org.jboss.system.server.profileservice.ProfileServiceBootstrap.start(ProfileServiceBootstrap.java:205) at org.jboss.bootstrap.AbstractServerImpl.start(AbstractServerImpl.java:405) at org.jboss.Main.boot(Main.java:209) at org.jboss.Main$1.run(Main.java:547) at java.lang.Thread.run(Thread.java:662) Caused by: java.lang.Error: Error in the server: mismatch between expected constructor arguments and supplied arguments. at org.jboss.mx.server.MBeanServerImpl.handleInstantiateExceptions(MBeanServerImpl.java:1310) at org.jboss.mx.server.MBeanServerImpl.instantiate(MBeanServerImpl.java:1246) at org.jboss.mx.server.MBeanServerImpl.instantiate(MBeanServerImpl.java:286) at org.jboss.mx.server.MBeanServerImpl.createMBean(MBeanServerImpl.java:344) at org.jboss.system.ServiceCreator.installPlainMBean(ServiceCreator.java:211) at org.jboss.system.ServiceCreator.install(ServiceCreator.java:130) at org.jboss.system.microcontainer.InstantiateAction.installAction(InstantiateAction.java:45) at org.jboss.system.microcontainer.InstantiateAction.installAction(InstantiateAction.java:37) at org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62) at org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71) at org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51) at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:348) at org.jboss.system.microcontainer.ServiceControllerContext.install(ServiceControllerContext.java:286) at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:1598) at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:934) at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1062) at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:984) at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:822) at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:553) at org.jboss.system.ServiceController.doChange(ServiceController.java:688) at org.jboss.system.ServiceController.install(ServiceController.java:274) at org.jboss.system.deployers.ServiceDeployer.deploy(ServiceDeployer.java:90) ... 23 more A: I've been getting this stack-trace as well when I try to deploy my EAR file into JBoss AS 5.1. I've traced it to the jboss-as-client dependency, which was being included in the final EAR file: <dependency> <groupId>org.jboss.jbossas</groupId> <artifactId>jboss-as-client</artifactId> <version>5.1.0.CR1</version> </dependency> Try removing the dependency or changing the scope to provided. That has fixed the problem for me. <dependency> <groupId>org.jboss.jbossas</groupId> <artifactId>jboss-as-client</artifactId> <version>5.1.0.CR1</version> <scope>provided</scope> </dependency> After looking around, it seems that this dependency is only useful for applications sitting outside JBoss that need to communicate with your EJBs remotely. So chances are you will not need it in the artefact you are deploying.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: OpenGL: glTexEnvi, glBlendFunc and On Screen Text Messages I'm developing a movie player and I'm using OpenGL to draw frames and On Screen Messages. To draw the frame I use: glBegin(GL_QUADS); // Draw the quads glTexCoord2f(0.0f, 0.0f); glVertex2f (_movieRect.origin.x,_movieRect.origin.y + _movieRect.size.height); glTexCoord2f(0.0f, _imageRect.size.height); glVertex2f (_movieRect.origin.x, _movieRect.origin.y ); glTexCoord2f(_imageRect.size.width, _imageRect.size.height); glVertex2f (_movieRect.origin.x + _movieRect.size.width,_movieRect.origin.y); glTexCoord2f(_imageRect.size.width, 0.0f); glVertex2f (_movieRect.origin.x + _movieRect.size.width, _movieRect.origin.y + _movieRect.size.height); glEnd(); while to draw the On Screen Message I draw a rectangle which contains the representation of the text that I'm going to show. To handle transparency I do this before drawing text message: glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); I want now to give the option to modify brightness in real-time. To achieve this I'm using: double t = _brightnessValue; glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); if (t > 1.0f) { glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_ADD); glColor4f(t-1, t-1, t-1, t-1); } else { glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_SUBTRACT); glColor4f(1-t, 1-t, 1-t, 1-t); } glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_TEXTURE); glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_PRIMARY_COLOR); glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE); glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_TEXTURE); The brightness is modified correctly but now text messages are wrong. The rectangle around the text is transparent only when brightness has its default value and even text is affected by the brightness correction. (i.e. the text is white as default and it becomes more and more gray as I reduce brightness). Does the brightness regulation change the alpha spectrum outside 0-1? How can I solve this problem? I'm sorry if this sounds stupid but it's the first time that I'm using OpenGL A: Remember, OpenGL is a state machine. You can set your TexEnv state, draw the frame, then change the TexEnv state back to normal, and draw your OSD.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django-nonrel exception invoking a URL in a Appengine/Django-nonrel app I have been stumped by this problem for the last one day or so. I have a small personal project (called, say, 'myapp') which I have implemented in python/django-nonrel/appengine. I added some new features under the /Element1 sub-url, and made the relevant changes to app.yaml, the top-level urls.py (since I am using Django), and the urls.py & views.py for the module that implements these new features. I tested these features on my development setup and deployed 'myapp' to appengine. Now, on this deployed 'myapp', whenever I try to access features under the /Element1/ sub-url I get a 500 error, and the appengine logs show this exception: Internal Server Error: /Element1/element2 Traceback (most recent call last): File "/base/data/home/apps/s~myapp/1.353511512982932038/django/core/handlers/base.py", line 111, in get_response response = callback(request, *callback_args, **callback_kwargs) TypeError: 'str' object is not callable The exception I've shown above is thrown when the /Element1/ sub-url is accessed by a cron job using the request "GET /Element1/element2 HTTP/1.1", but I get the same error when I try to manually browse anything under the /Element1/ sub-url. Now the kicker is that all of this works perfectly under the dev_appserver environment on my development setup. It's only once I deploy my app to the cloud do I see this exception. I realize this information is sketchy. But I'd appreciate any guidance/pointers on what I may have done wrong here. My guess is some mis-configuration on my part is messing up Django's name resolution -- instead of receiving a callback method to the 'view' handlers under /Element1/, it's getting a string object. TIA!
{ "language": "en", "url": "https://stackoverflow.com/questions/7544640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UnknownHostException (webservice http-get) I have this simple code, that makes a get to a webservice. For some reason it cant connect and gives the error in the log unknownHostException This is the code: String URL = "http://services.sapo.pt/EPG/GetChannelList"; String result = ""; final String tag = "Data received: "; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final Button btnSearch = (Button)findViewById(R.id.btnSearch); btnSearch.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v) { callWebService(); } }); } // end onCreate() public void callWebService(){ HttpClient httpclient = new DefaultHttpClient(); HttpGet request = new HttpGet(URL); ResponseHandler<String> handler = new BasicResponseHandler(); try { result = httpclient.execute(request, handler); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } httpclient.getConnectionManager().shutdown(); Log.i(tag, result); } This is part of my manifest <permission android:name="android.permission.INTERNET"/> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".AndroidApp" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> A: I found the solution. I putted the internet permission using the GUI in manifest which added the tag < permission android:name"android.permission.INTERNET"/> Then by hand, i putted the correct tag that is: < uses-permission android:name="android.permission.INTERNET" /> which is a different tag and it worked. GUI fail. A: Not sure if you have already checked this, but please check if you are behind a proxy or firewall. Here is a way to configure the HttpClient for a proxy and official apache documentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using jlayer/javazoom, or vlcj to playback audio (MPEG4, RAW AMR, or THREE GPP) Can jlayer/javazoom, or vlcj playback MPEG4, RAW AMR, or THREE GPP? I have searched, and I cannot find how to correctly use the players, or whether they even support playback of these file formats. Are there any other players that can playback these audio formats? A: I've used Xuggler http://www.xuggle.com/xuggler/ for playing AMR from files. It uses ffmpeg with opencore-amr-nb. And I think it can play other formats. You can start from http://xuggle.googlecode.com/svn/trunk/java/xuggle-xuggler/src/com/xuggle/xuggler/demos/DecodeAndPlayAudio.java
{ "language": "en", "url": "https://stackoverflow.com/questions/7544657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Testing Mongoose Node.JS app I'm trying to write unit tests for parts of my Node app. I'm using Mongoose for my ORM. I've searched a bunch for how to do testing with Mongoose and Node but not come with anything. The solutions/frameworks all seem to be full-stack or make no mention of mocking stuff. Is there a way I can mock my Mongoose DB so I can return static data in my tests? I'd rather not have to set up a test DB and fill it with data for every unit test. Has anyone else encountered this? A: I too went looking for answers, and ended up here. This is what I did: I started off using mockery to mock out the module that my models were in. An then creating my own mock module with each model hanging off it as a property. These properties wrapped the real models (so that child properties exist for the code under test). And then I override the methods I want to manipulate for the test like save. This had the advantage of mockery being able to undo the mocking. but... I don't really care enough about undoing the mocking to write wrapper properties for every model. So now I just require my module and override the functions I want to manipulate. I will probably run tests in separate processes if it becomes an issue. In the arrange part of my tests: // mock out database saves var db = require("../../schema"); db.Model1.prototype.save = function(callback) { console.log("in the mock"); callback(); }; db.Model2.prototype.save = function(callback) { console.log("in the mock"); callback("mock staged an error for testing purposes"); }; A: I solved this by structuring my code a little. I'm keeping all my mongoose-related stuff in separate classes with APIs like "save", "find", "delete" and no other class does direct access to the database. Then I simply mock those in tests that rely on data. I did something similar with the actual objects that are returned. For every model I have in mongoose, I have a corresponding class that wraps it and provides access-methods to fields. Those are also easily mocked. A: Also worth mentioning: mockgoose - In-memory DB that mocks Mongoose, for testing purposes. monckoose - Similar, but takes a different approach (Implements a fake driver). Monckoose seems to be unpublished as of March 2015.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: How to Change page Title of Magento Module? I have successfully install magento, but site title remain magento, I try many times but did not change that title?and did not change thing under the widget? so what is the procedures? A: you can do it via layout files: <reference name="head"> <action method="setTitle" translate="title"><title>Your Title</title></action> </reference> or via code by accessing head block element and calling setTitle('your title') method on it $this->getLayout()->getBlock('head')->setTitle('your title'); grep for more references: grep '>setTitle(' app/code/ -rsn A: Put this function in Block page of that Module public function _prepareLayout() { $this->pageConfig->getTitle()->set(__('Your Page Title')); return parent::_prepareLayout(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7544660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: C# get caller class type (Not in Static) How do I get the caller class type in the base? this is the parent, here I want to print the child type without sending it public abstract class Parent: ISomeInterface { public void printChildType() { Type typeOfMyChild = ?????; MessageBox.Show(typeOfMyChild); //how do I get Child typeOfMyChild } } the child public class Child : parent { } pirnt the child type : Child child = new Child(); child.printChildType(); Thanks (I already saw this one: Get inherited caller type name in base static class but I am using none static methods) A: Type typeOfMyChild = this.GetType(); Thanks to polymorphism when you invoke: Child child = new Child(); child.printChildType(); it should print Child. A: Aren't you just looking for the current type ? public void printChildType() { Type typeOfMyChild = GetType(); MessageBox.Show(typeOfMyChild); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7544661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to export triggers from a database? I would like to generate a script/extract all of the triggers I have in database, so that I can use them in another one. How can I do this? A: You can get the list of triggers from sys.all_objects (sysobjects on 2000) and then the code from sp_helptext procedure. Example: http://databases.aspfaq.com/schema-tutorials/schema-how-do-i-show-all-the-triggers-in-a-database.html A: You can find trigger objects either on sys.objects view with an xtype = 'tr' or, starting in SQL 2008, on the sys.triggers view. You can get the definition for triggers (or any other object) by joining to sys.sql_modules.definition or by calling OBJECT_DEFINITION(object_id). Just don't use sys.syscomments.text because it caps out at nvarchar(4000) In any combination of the above (really doesn't matter) you could generate a single file to populate all of your scripts by terminating each definition with "Go" like this: SELECT m.definition, 'GO' FROM sys.triggers tr JOIN sys.sql_modules m ON tr.object_id = m.object_id Just take the resulting output and save it in a single file and execute to recreate every trigger. Generate Individual Scripts The problem is a little more complex if you want to generate individual files for each script. ...mostly in automating the file generation; the previous solution leans on just presenting data and letting you save it. You can use bcp utility, but I find SQL to be pretty clumsy at dealing with generating files. Alternatively, just grab the data in powershell and then generate files from there where you have a lot more fine tuned access and control. Here's a script that will grab all the triggers and create them into folders for each table. # config $server = "serverName" $database = "dbName" $dirPath = 'C:\triggers' # query $query = @" SELECT TOP 5 t.name AS TableName, tr.name AS TriggerName, m.definition As TriggerScript FROM sys.triggers tr JOIN sys.tables t ON tr.parent_id = t.object_id JOIN sys.sql_modules m ON tr.object_id = m.object_id "@ # connection $sqlConnection = New-Object System.Data.SqlClient.SqlConnection $sqlConnection.ConnectionString = "Server=$server;Database=$database;Integrated Security=True" $sqlConnection.Open() # command $sqlCmd = New-Object System.Data.SqlClient.SqlCommand($query, $sqlConnection) $sqlCmd.CommandTimeout = 10 * 60 # 10 minutes # execute $reader = $sqlCmd.ExecuteReader() while ($reader.Read()) { # get reader values $tableName = $reader.GetValue(0) $triggerName = $reader.GetValue(1) $triggerScript = $reader.GetValue(2) $filepath = "$dirPath\$tableName\$triggerName.sql" # ensure directory exists [System.IO.Directory]::CreateDirectory("$dirPath\$tableName\") # write file New-Item -Path $filepath -Value $triggerScript -ItemType File } $reader.Close() $sqlConnection.Close()
{ "language": "en", "url": "https://stackoverflow.com/questions/7544668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to call javascript from Android? How do we call javascript from Android? I have this javascript library which I would like to use, I want to call the javascript function and pass the result value to the android java code. Haven't found the answer from now. i managed to call android code from javascript, but I want the other way around. A: In order to match the method calls of the iOS WebviewJavascriptBridge ( https://github.com/marcuswestin/WebViewJavascriptBridge ), I made some proxy for the calls of register_handle and call_handle. Please note I am not a Javascript-guru therefore there is probably a better solution. javascriptBridge = (function() { var handlers = {}; return { init: function () { }, getHandlers : function() { return handlers; }, callHandler : function(name, param) { if(param !== null && param !== undefined) { JSInterface[name](param); } else { JSInterface[name](); } }, registerHandler : function(name, method) { if(handlers === undefined) { handlers = {}; } if(handlers[name] === undefined) { handlers[name] = method; } } }; }()); This way you can send from Javascript to Java calls that can have a String parameter javascriptBridge.callHandler("login", JSON.stringify(jsonObj)); calls down to @JavascriptInterface public void login(String credentialsJSON) { Log.d(getClass().getName(), "Login: " + credentialsJSON); new Thread(new Runnable() { public void run() { Gson gson = new Gson(); LoginObject credentials = gson.fromJson(credentialsJSON, LoginObject.class); SingletonBus.INSTANCE.getBus().post(new Events.Login.LoginEvent(credentials)); } }).start(); } and you can call back to Javascript with javascriptBridge.registerHandler('successfullAuthentication', function () { alert('hello'); }) and private Handler webViewHandler = new Handler(Looper.myLooper()); webViewHandler.post( new Runnable() { public void run() { webView.loadUrl("javascript: javascriptBridge.getHandlers().successfullAuthentication();" } } ); If you need to pass a parameter, serialize to JSON string then call StringEscapeUtils.escapeEcmaScript(json), otherwise you get unexpected identifier: source (1) error. A bit tacky and hacky, but it works. You just have to remove the following. connectWebViewJavascriptBridge(function(bridge) { } EDIT: in order to change the global variable to an actual property, I changed the above code to the following: (function(root) { root.bridge = (function() { var handlers = {}; return { init: function () { }, getHandlers : function() { return handlers; }, callHandler : function(name, param) { if(param !== null && param !== undefined) { Android[name](param); } else { Android[name](); } }, registerHandler : function(name, method) { if(handlers === undefined) { handlers = {}; } if(handlers[name] === undefined) { handlers[name] = method; } } }; }()); })(this); I got the idea from Javascript global module or global variable . A: You can use Rhino library to execute JavaScript without WebView. Download Rhino first, unzip it, put the js.jar file under libs folder. It is very small, so you don't need to worry your apk file will be ridiculously large because of this one external jar. Here is some simple code to execute JavaScript code. Object[] params = new Object[] { "javaScriptParam" }; // Every Rhino VM begins with the enter() // This Context is not Android's Context Context rhino = Context.enter(); // Turn off optimization to make Rhino Android compatible rhino.setOptimizationLevel(-1); try { Scriptable scope = rhino.initStandardObjects(); // Note the forth argument is 1, which means the JavaScript source has // been compressed to only one line using something like YUI rhino.evaluateString(scope, javaScriptCode, "JavaScript", 1, null); // Get the functionName defined in JavaScriptCode Object obj = scope.get(functionNameInJavaScriptCode, scope); if (obj instanceof Function) { Function jsFunction = (Function) obj; // Call the function with params Object jsResult = jsFunction.call(rhino, scope, scope, params); // Parse the jsResult object to a String String result = Context.toString(jsResult); } } finally { Context.exit(); } You can see more details at my post. A: There is a hack: * *Bind some Java object so that it can be called from Javascript with WebView: addJavascriptInterface(javaObjectCallback, "JavaCallback") *Force execute javascript within an existing page by WebView.loadUrl("javascript: var result = window.YourJSLibrary.callSomeFunction(); window.JavaCallback.returnResult(result)"); (in this case your java class JavaObjectCallback should have a method returnResult(..)) Note: this is a security risk - any JS code in this web page could access/call your binded Java object. Best to pass some one-time cookies to loadUrl() and pass them back your Java object to check that it's your code making the call. A: For a full implementation of JavaScript that doesn't require using a slow WebView, please see AndroidJSCore, which is a full port of Webkit's JavaScriptCore for Android. UPDATE 2018: AndroidJSCore is deprecated. However, its successor, LiquidCore has all of the same functionality and more. Calling functions from Android is very simple: JSContext context = new JSContext(); String script = "function factorial(x) { var f = 1; for(; x > 1; x--) f *= x; return f; }\n" + "var fact_a = factorial(a);\n"; context.evaluateScript("var a = 10;"); context.evaluateScript(script); JSValue fact_a = context.property("fact_a"); System.out.println(df.format(fact_a.toNumber())); // 3628800.0
{ "language": "en", "url": "https://stackoverflow.com/questions/7544671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: I'm not exactly sure what this x86 Add instruction is doing I'm not exactly sure what this add instruction is doing: add 0x0(%rbp,%rbx,4),%eax If it were: add %rbx,%eax I know it would add the contents of rbx and the contents in eax and store them back into eax. However, the 0x0(%rbp,%rbx,4) is throwing me off. A: That's because it's stupid&confusing AT&T syntax. In normal Intel syntax it's add eax,dword ptr[rbp+4*rbx+0] ie add the dword at rbp+4*rbx to eax.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Consume a wcf Service with a Java Client I try to consume a wcf service hosted on an iis with a simple java client. my service is a basicHttpService. now my Question. What do i need in java to access the service methods? i build a little example: using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using System.ServiceModel.Web; namespace android.Web { [ServiceContract] public interface ITestService { [OperationContract] void DoWork(); [WebGet(UriTemplate = "Login/")] String Login(); } } the login Method only returns a simple string that want to test in my java client. I tried some tutorials found in the internet, but nothing wokrs ;) thx alot. A: I do not think that your problem is due to a Java client. You are using basicHttpBinding, at the same time you are using a WebGet attribute which points to using REST and webhttpbinding. Try making sure that it works from a windows WCF client first.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Filter language in solr I indexed German and English docs with solr and i want to some ability to search just inside German docs or English docs,How to configure this? thanks A: Have a field indicating the language, and search on that. A: Some of the options as mentioned @ http://lucidworks.lucidimagination.com/display/LWEUG/Multilingual+Indexing+and+Search You may end up with having to implement multiple language fields and language detection.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best way to initialize a HashMap I usually do e.g. HashMap<String,String> dictionary = new HashMap<String,String>(); I started to think about it, and as far as I know a HashMap is implemented under the hood via a hash table. The objects are stored in the table using a hash to find where they should be stored in the table. Does the fact that I do not set a size on the construction of the dictionary makes the performace decrease? I.e. what would be the size of the hash table during construction? Would it need to allocate new memory for the table as elements increase? Or I am confused on the concept here? Are the default capacity and load adequate or should I be spending time for the actual numbers? A: Does the fact that I do not set a size on the construction of the dictionary makes the performace decrease? Depends on how much you're going to store in the HashMap and how your code will use it afterward. If you can give it a ballpark figure up front, it might be faster, but: "it's very important not to set the initial capacity too high [...] if iteration performance is important" 1 because iteration time is proportional to the capacity. Doing this in non-performance-critical pieces of code would be considered premature optimization. If you're going to outsmart the JDK authors, make sure you have measurements that show that your optimization matters. what would be the size of the hash table during construction? According to the API docs, 16. Would it need to allocate new memory for the table as elements increase? Yes. Every time it's fuller than the load factor (default = .75), it reallocates. Are the default capacity and load adequate Only you can tell. Profile your program to see whether it's spending too much time in HashMap.put. If it's not, don't bother. A: The nice thing about Java is that it is open-source, so you can pull up the source code, which answers a number of questions: * *No, there is no relationship between HashMap and HashTable. HashMap derives from AbstractMap, and does not internally use a HashTable for managing data. *Whether or not omitting an explicit size will decrease performance will depend upon your usage model (or more specifically, how many things you put into the map). The map will automatically double in size every time a certain threshold is hit (0.75 * <current map capacity>), and the doubling operation is expensive. So if you know approximately how many elements will be going into the map, you can specify a size and prevent it from ever needing to allocate additional space. *The default capacity of the map, if none is specified using the constructor, is 16. So it will double its capacity to 32 when the 12th element is added to the map. And then again on the 24th, and so on. *Yes, it needs to allocate new memory when the capacity increases. And it's a fairly costly operation (see the resize() and transfer() functions). Unrelated to your question but still worth noting, I would recommend declaring/instantiating your map like: Map<String,String> dictionary = new HashMap<String,String>(); ...and of course, if you happen to know how many elements will be placed in the map, you should specify that as well. A: Hashmap would automatically increase the size if it needs to. The best way to initialize is if you have some sort of anticipating how much elements you might needs and if the figure is large just set it to a number which would not require constant resizing. Furthermore if you read the JavaDoc for Hashmap you would see that the default size is 16 and load factor is 0.75 which means that once the hashmap is 75% full it will automatically resize. So if you expect to hold 1million elements it is natural you want a larger size than the default one A: I would declare it as interface Map first of all. Map<String,String> dictionary = new HashMap<String,String>(); Does the fact that I do not set a size on the construction of the dictionary makes the performace decrease? Yes, initial capacity should be set for better performance. Would it need to allocate new memory for the table as elements increase Yes, load factor also effects performance. More detail in docs A: As stated here, the default initial capacity is 16 and the default load factor is 0.75. You can change either one with different c'tors, and this depends on your usage (though these are generally good for general purposes).
{ "language": "en", "url": "https://stackoverflow.com/questions/7544691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: System for automating admin creation for any database For example I have a database, and want to have good automaticly generated admin for it. Is there software for this? A: Not sure what your question is. What kind of admin tasks are you trying to automate? The SQL Server Agent service can handle a lot of the scheduled aspect, as well as alerts for certain conditions. Policy Based Management can log and restrict certain database params across a single instance or multiple ones. What more are you looking for? SSMS is the gui that sits on top of SQL Server for an easy implementation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7544694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass image entry in atom rss feed. in rails 3.1 every time people give tutorials on how to make atom rss templates, but my question here is how can i pass in and image in the rss format. for instance i have this code sample in rss atom_feed :language => 'en-US' do |feed| feed.title @title feed.updated @updated @news_items.each do |item| next if item.updated_at.blank? feed.entry( item ) do |entry| entry.url news_item_url(item) entry.title item.title entry.content item.content, :type => 'html' # the strftime is needed to work with Google Reader. entry.updated(item.updated_at.strftime("%Y-%m-%dT%H:%M:%SZ")) entry.author do |author| author.name entry.author_name) end end end end where can i display the image of the article and how do i do it A: The Atom format (http://www.atomenabled.org/developers/syndication/) supports an icon (square) and a logo (rectangular)... so in your block entry.icon '/path/to/my/icon.png' entry.logo '/path/to/my/logo.png' EDIT: serves me right for not checking some code. Those elements are optional elements for the feed element, not the entry. Try: feed.icon '/path/to/my/icon.png'
{ "language": "en", "url": "https://stackoverflow.com/questions/7544702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error on eclipse start up I am desperate.... no idea whats wrong. Yesterday it worked today it doesn't. Here is the stacktrace from the logs, and it is generated before choosing the workspace: !SESSION 2011-09-25 11:31:39.687 ----------------------------------------------- eclipse.buildId=I20090611-1540 java.version=1.6.0_27 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=sk_SK Framework arguments: -product org.eclipse.epp.package.jee.product - clean Command-line arguments: -os win32 -ws win32 -arch x86 -product org.eclipse.epp.package.jee.product - clean !ENTRY org.eclipse.osgi 4 0 2011-09-25 11:31:42.718 !MESSAGE Startup error !STACK 1 java.lang.NumberFormatException: For input string: "" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at org.eclipse.osgi.storagemanager.StorageManager.updateTable(StorageManager.java:511) at org.eclipse.osgi.storagemanager.StorageManager.open(StorageManager.java:693) at org.eclipse.osgi.internal.baseadaptor.BaseStorage.initFileManager(BaseStorage.java:213) at org.eclipse.osgi.internal.baseadaptor.BaseStorage.initialize(BaseStorage.java:147) at org.eclipse.osgi.baseadaptor.BaseAdaptor.initializeStorage(BaseAdaptor.java:121) at org.eclipse.osgi.framework.internal.core.Framework.initialize(Framework.java:185) at org.eclipse.osgi.framework.internal.core.Framework.<init>(Framework.java:157) at org.eclipse.core.runtime.adaptor.EclipseStarter.startup(EclipseStarter.java:286) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:175) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:559) at org.eclipse.equinox.launcher.Main.basicRun(Main.java:514) at org.eclipse.equinox.launcher.Main.run(Main.java:1311) A: That is quite uncommon: bug 113596 suggests some kind of issue with Windows (but not a definitive cause). This thread suggests: Under the Eclipse installation directory is a folder named ...\configuration\.settings. If you move that folder to some temporary location, will Eclipse start? (it'll rebuild the folder and at least one of the prefs files if it starts). Considering the Eclipse used here seems quite old: eclipse.buildId=I20090611-1540 It is not surprising that the OP lyborko reports: Nevetherless, I downloaded latest eclipse, and it works well...
{ "language": "en", "url": "https://stackoverflow.com/questions/7544707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: php PUSH-server can't send multiply push-messages I have a php-script that fetches a couple of uuid's from a mysql database and then sends a message to all the users. But it doesn't work when there are a lot of users. The script can be found here: http://pastebin.com/VATM1eaC On line 19, I have a commented $sql query. When I use that one it works. The two UUID's there are my and my friends. But when it fetches all UUID's from the database, it doesn't work (a know a couple of people in the database that doesn't get the PUSH.). The database contains around 300 UUID's. I tested added sleep(1) after each fwrite, to see if that helped, but it didn't. (It helped on another script, when I only pushed the message to me and my friend, but several times). Any suggestions? A: We use this library http://code.google.com/p/apns-php/ for sending push notifications to our users. We currently have around 40.000+ users and we send out over 200.000 push notifications a day without any problems. I would check that library. It's easy to implement and works perfectly!
{ "language": "en", "url": "https://stackoverflow.com/questions/7544713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to use javascript to simulate click on link where href is php I am writing a Google Chrome Extension. I need to use javascript to simulate a click on this link: <a href="/logout.php /a> so I can log out. How can I get this done? No JQuery please, I haven't learned it yet. A: Main function will create any event: function ShowOperationMessage(obj, evt) { var fireOnThis = obj; if (document.createEvent) { var evObj = document.createEvent('MouseEvents'); evObj.initEvent(evt, true, false); fireOnThis.dispatchEvent(evObj); } else if (document.createEventObject) { fireOnThis.fireEvent('on' + evt); } } Now call the function: ShowOperationMessage(document.getElementById("linkID"), "click"); A: Since this is for an extension, you could submit an XHR request to the server /logout.php rather than simulate a click. But simulating a mouse click is rather simple, I use the following code in many of my extensions: function simulateClick(element) { if (!element) return; var dispatchEvent = function (elt, name) { var clickEvent = document.createEvent('MouseEvents'); clickEvent.initEvent(name, true, true); elt.dispatchEvent(clickEvent); }; dispatchEvent(element, 'mouseover'); dispatchEvent(element, 'mousedown'); dispatchEvent(element, 'click'); dispatchEvent(element, 'mouseup'); };
{ "language": "en", "url": "https://stackoverflow.com/questions/7544716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }