source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0000077558.txt" ]
Q: How can I use the PHP File api to write raw bytes? I want to write a raw byte/byte stream to a position in a file. This is what I have currently: $fpr = fopen($out, 'r+'); fseek($fpr, 1); //seek to second byte fwrite($fpr, 0x63); fclose($fpr); This currently writes the actually string value of "99" starting at byte offset 1. IE, it writes bytes "9" and "9". I just want to write the actual one byte value 0x63 which happens to represent number 99. Thanks for your time. A: fwrite() takes strings. Try chr(0x63) if you want to write a 0x63 byte to the file. A: That's because fwrite() expects a string as its second argument. Try doing this instead: fwrite($fpr, chr(0x63)); chr(0x63) returns a string with one character with ASCII value 0x63. (So it'll write the number 0x63 to the file.)
[ "stackoverflow", "0025183571.txt" ]
Q: Saving an Image button's isSelected() property in onSaveInstanceState and restore it Lets say I have an image button, which change image onClick() thus isSelected() property is true. How can I save this property in onSaveInstanceState() so that I can later restore it while rotating the phone? A: First of all, save the isSelected() property in onSaveInstanceState() public final String STATE_SELECTED = "state_selected"; @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); savedInstanceState.putBoolean(STATE_SELECTED, button.isSelected()); } Then access and use this value in onRestoreInstanceState() @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); boolean selected = savedInstanceState.getBoolean(STATE_SELECTED); button.setSelected(selected); if (selected) // Do some stuff else //Do some other stuff } Hope this helps! Edit: In response to your comment, here's how you do this for an array of buttons: public final String STATE_SELECTED = "state_selected"; public Button[] buttons; // This is populated elsewhere @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); boolean[] selected = new boolean[buttons.length]; for (int i = 0; i < buttons.length; i++) selected[i] = buttons[i].isSelected(); savedInstanceState.putBooleanArray(STATE_SELECTED, selected); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); boolean[] selected = savedInstanceState.getBooleanArray(STATE_SELECTED); for (int i = 0; i < buttons.length; i++) button[i].setSelected(selected[i]); }
[ "stackoverflow", "0046186923.txt" ]
Q: Error in function to normalize data applied to a data frame I have downloaded the bike-sharing-dataset from the UCI Machine learning repository and am trying to implement a multivariate linear regression in R. Here is the format of the data: > head(data1) season mnth hr holiday weekday workingday weathersit temp atemp hum windspeed cnt 1 1 1 0 0 6 0 1 0.24 0.2879 0.81 0.0000 16 2 1 1 1 0 6 0 1 0.22 0.2727 0.80 0.0000 40 3 1 1 2 0 6 0 1 0.22 0.2727 0.80 0.0000 32 4 1 1 3 0 6 0 1 0.24 0.2879 0.75 0.0000 13 5 1 1 4 0 6 0 1 0.24 0.2879 0.75 0.0000 1 6 1 1 5 0 6 0 2 0.24 0.2576 0.75 0.0896 1 I am trying to normalize specific columns (that have not already been normalized) with the following function: normalize <- function(x) { return ((x - min(x)) / (max(x) - min(x))) } The problem is that when I run: dfNorm <- as.data.frame(lapply(data1["season", "mnth", "hr", "weekday", "weathersit"], normalize)) I get the following error: Error in [.data.frame(data1, "season", "month", "hour", "weekday", "weathersit") : unused arguments ("weekday", "weathersit") Why am I getting this error and how can I fix it? A: To modify in-place, I'd use dplyr::mutate. Something like this should work: library(dplyr) dfNorm <- data1 %>% mutate_at(.vars = vars(season, mnth, hr, weekday, weathersit), .funs = funs(normalize))
[ "academia.stackexchange", "0000118092.txt" ]
Q: Why do many graduate programs in mathematics (United States) still have foreign language requirements today (in 2010s)? As far as I know, nowadays most of the mathematical literature is written and published in English and mathematicians communicate with each other in English. Although there are certain number of books written in other languages (like EGA), but at the same time their counterparts also appear in English (like Stacks Project). However, many graduate programs still require their students to pass a language translation test in French, German or Russian (which a paper dictionary, not a dictionary app in cellphones, which seems even more ridiculous to me...). I wonder what makes it still necessary to have foreign language requirement as of 2010s. I believe my question has different focus than this one Mathematics Ph.D program foreign language requirement Where the questioner specifically asked for advice for the most useful language among French, German and Russian: I personally have no preference on which to learn, but I was wondering if there were other reasons that would make one language more advantageous over the others in terms of a general mathematical career. while I am asking why we ever need a second language for mathematical study in 2010s: A: Just an anecdotal answer: My mathematics PhD program (at UC Berkeley) had a requirement to pass a language exam. This involved translating to English 1-2 pages excerpted from a mathematics paper written in French, German, or Russian (student's choice). We were given several hours to do this, and the use of a paper dictionary. I did not, and still do not, speak a word of any of these three languages (unfortunately). But I took the exam in French and passed easily thanks to the high number of cognates between mathematical French and English, context clues (being somewhat familiar with the subfield of math helps), and the fact that I had plenty of time to look up any words I didn't know in the dictionary. The main thing I gained from this experience was confidence that with a little extra effort, I could actually read math written in French. Since then, I have at times had reason to use this skill that I didn't know I had. I believe Berkeley math did away with its language exam requirement the year I graduated (2016), and I think this was an entirely sensible thing to do. But I would encourage all grad students to get some experience reading papers written in a language they don't speak! A: Part of it is just inertia. But it is a small part, I think. When I studied maths in the previous century there was a two language requirement. Initially it was French and German. Russian was added as a third option when it was realized that a lot of great math was being created in the USSR that wasn't available in English (or French or German). Later, one could substitute a Programming Language for one of your two languages. However, even today, not everything that a working mathematician wants to know is available in English, so for a practical reason it is useful, still, to have language skills beyond English. Machine Translation has made great strides in the past decades, but mathematics is probably still very difficult to translate correctly. This is partly due to the smaller sample size of available texts on which to train translators. But, I would, myself, be hesitant to drop a language requirement from a modern mathematics graduate program for a completely different reason. Consider, as I do, that language skill is a help in mathematics itself. Among other things, mathematics is a language, and it requires a certain training of the mind in order to speak it well. Mathematics uses vocabulary and structure to express deep ideas - language. So, language training of any sort, trains the brain in a certain way that may actually assist in the mathematical way of thinking. I'm not sure I'd be adamant with my colleagues who wanted to replace the last language requirement in a program with something else, but I'd want to hear arguments about how that would make for better thinking. Another math course or two might be useful, but would it be better? Hard to say. A: As a thought experiment, let us assume a hypothetical scenario in which there was a tradition for mathematics graduate programs to require their graduate students to take a cooking class. Someone would then come to academia.se and ask: why do they have this requirement? Several well-meaning, well-intentioned, extremely intelligent people would then post answers offering quite rational explanations, which might go along the following lines: Why do mathematics graduate programs require students to take cooking classes? Mathematics is an intense activity that requires a lot of energy. Food provides energy. Hence, a mathematician who can cook well and efficiently will be more productive than one who can’t. Moreover, a mathematician who can make tasty food will be happier and free from the distraction of constantly thinking where to find tasty food. Again, they will end up being more productive and producing more and better mathematics. Mathematics is a social activity. If you can cook well, guess what? Lots of really good mathematicians will want to be your friends and collaborate with you. You’ll produce more and better research. Mathematics is a language, and cooking is also like a language. Learning how to read and execute a recipe, which is really an algorithm written in a kind of pseudocode with a particular grammar and syntax, is a skill that will carry over well to many areas of mathematics (combinatorics, logic, theoretical computer science, and much more). Cooking develops your brain. Cooking requires a substantially greater intellectual effort than ordering food at a restaurant. Naturally, having a better developed brain will make you a better mathematician. Cooking teaches you to care about the order of operations. Ever tried making a recipe and added a vital ingredient at the wrong stage, with disastrous results? I bet you’ll never put your operators in the wrong order in your next algebra paper! Etc etc. To summarize, the tradition of cooking classes in graduate programs is 100% logical, and should continue. It is not at all due to inertia. I’m sure graduate programs evaluate their requirements all the time, and are constantly considering the benefit provided by any requirement against the opportunity cost of not replacing that requirement by something else.
[ "math.stackexchange", "0003301752.txt" ]
Q: Find $g(1)$ where $g(x)$ is the inverse of $f(x)=\sin(x)-2x+1$ I was given the function$f(x)=\sin(x)-2x+1$ I was requested to prove that it's decreasing, which I did through its derivative. Since it's decreasing, it's monotonous and therefore injective. Thus, it has an inverse. So I was asked to find $g(1)$, where $g(x)$ is the inverse of $f(x)$. I have failed to find this inverse and I'm out of resources here (I'm only in the first year of my mathematics studies, so I'm quite a beginner). Does anybody know how can this problem be solved? A: Since $f(0)=1$ and since $g=f^{-1}$, $g(1)=0$.
[ "stackoverflow", "0041546766.txt" ]
Q: Docker: trouble connecting to mysql, network issue? I have a WordPress and MySQL container with a persistent volume. I have been trying to learn docker, and in the process have mistakenly deleted the old docker-compose.yml and all but the mysql volume. I have now recreated it to the compose file to the best of my ability, but whenever I boot the machine, it fails to connect to the MySQL server. Would anyone be able to point out where I'm going wrong. I suspect I have an issue with the link between the two, but I'm not sure. docker-compose.yml: version: '2' services: wp.spm: restart: always image: wordpress:latest ports: - "8080:80" environment: WORDPRESS_DB_HOST: localhost:3306 WORDPRESS_DB_USER: spm WORDPRESS_DB_PASSWORD: Ivietoo2Phah8xay WORDPRESS_DB_NAME: spm links: - mysql.5.7 working_dir: /var/www/html volumes: - ./wp-content:/var/www/html/wp-content mysql.5.7: restart: always image: mysql:5.7 ports: - 3306:3306 environment: MYSQL_ROOT_PASSWORD: root # TODO: Change this MYSQL_USER: spm MYSQL_PASS: Ivietoo2Phah8xay MYSQL_DATABASE: spm volumes: - db_data:/var/lib/mysql volumes: db_data: log: $ docker-compose up Pulling mysql.5.7 (mysql:5.7)... 5.7: Pulling from library/mysql 75a822cd7888: Pull complete b8d5846e536a: Pull complete b75e9152a170: Pull complete 832e6b030496: Pull complete fe4a6c835905: Pull complete c3f247e29ab1: Pull complete 21be3e562071: Pull complete c7399d6bf033: Pull complete ccdaeae6c735: Pull complete 713c7d65b0d3: Pull complete 86c18539deb2: Pull complete Digest: sha256:9ef4478a3aa597f59b2266d5702f55f29acc468b5bf3518c3c90cbca4e243823 Status: Downloaded newer image for mysql:5.7 Pulling wp.spm (wordpress:latest)... latest: Pulling from library/wordpress 75a822cd7888: Already exists e4d8a4e038be: Pull complete 81d4d961577a: Pull complete f0a3d7c702e3: Pull complete a4b7d2c4c9cc: Pull complete de3fbbff60a9: Pull complete 336c38203cc2: Pull complete 628c443fd26f: Pull complete 6b43451e2e60: Pull complete a4dc6da381e6: Pull complete 771a9ee2bb6a: Pull complete 3862c25af8ee: Pull complete a3bf90f1df74: Pull complete 4564f4870a3e: Pull complete ec9c03f98075: Pull complete 5f4dfa2bfbb4: Pull complete 69feb6fb40db: Pull complete 5f129a65fac7: Pull complete Digest: sha256:0bb659eafa22cdb9f14bc05d17be97132842eb122eb8ff346ecafe7553f48f22 Status: Downloaded newer image for wordpress:latest Creating googleserver_mysql.5.7_1 Creating googleserver_wp.spm_1 Attaching to googleserver_mysql.5.7_1, googleserver_wp.spm_1 mysql.5.7_1 | 2017-01-09T11:07:44.271254Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details). mysql.5.7_1 | 2017-01-09T11:07:44.278843Z 0 [Note] mysqld (mysqld 5.7.17) starting as process 1 ... wp.spm_1 | WordPress not found in /var/www/html - copying now... mysql.5.7_1 | 2017-01-09T11:07:44.347784Z 0 [Note] InnoDB: PUNCH HOLE support available mysql.5.7_1 | 2017-01-09T11:07:44.347937Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins mysql.5.7_1 | 2017-01-09T11:07:44.347956Z 0 [Note] InnoDB: Uses event mutexes mysql.5.7_1 | 2017-01-09T11:07:44.348024Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier mysql.5.7_1 | 2017-01-09T11:07:44.348048Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.3 mysql.5.7_1 | 2017-01-09T11:07:44.348060Z 0 [Note] InnoDB: Using Linux native AIO mysql.5.7_1 | 2017-01-09T11:07:44.356631Z 0 [Note] InnoDB: Number of pools: 1 mysql.5.7_1 | 2017-01-09T11:07:44.367564Z 0 [Note] InnoDB: Using CPU crc32 instructions mysql.5.7_1 | 2017-01-09T11:07:44.370949Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M mysql.5.7_1 | 2017-01-09T11:07:44.419506Z 0 [Note] InnoDB: Completed initialization of buffer pool mysql.5.7_1 | 2017-01-09T11:07:44.476953Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority(). mysql.5.7_1 | 2017-01-09T11:07:44.501029Z 0 [Note] InnoDB: Highest supported file format is Barracuda. wp.spm_1 | WARNING: /var/www/html is not empty - press Ctrl+C now if this is an error! wp.spm_1 | + ls -A wp.spm_1 | wp-content wp.spm_1 | + sleep 10 mysql.5.7_1 | 2017-01-09T11:07:44.614777Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables mysql.5.7_1 | 2017-01-09T11:07:44.615567Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ... mysql.5.7_1 | 2017-01-09T11:07:45.135167Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB. mysql.5.7_1 | 2017-01-09T11:07:45.137285Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active. mysql.5.7_1 | 2017-01-09T11:07:45.137414Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active. mysql.5.7_1 | 2017-01-09T11:07:45.138586Z 0 [Note] InnoDB: Waiting for purge to start mysql.5.7_1 | 2017-01-09T11:07:45.189557Z 0 [Note] InnoDB: 5.7.17 started; log sequence number 12168868 mysql.5.7_1 | 2017-01-09T11:07:45.194278Z 0 [Note] Plugin 'FEDERATED' is disabled. mysql.5.7_1 | 2017-01-09T11:07:45.195063Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool mysql.5.7_1 | 2017-01-09T11:07:45.223753Z 0 [Note] InnoDB: Buffer pool(s) load completed at 170109 11:07:45 mysql.5.7_1 | 2017-01-09T11:07:45.235736Z 0 [Warning] Failed to set up SSL because of the following SSL library error: SSL context is not usable without certificate and private key mysql.5.7_1 | 2017-01-09T11:07:45.237375Z 0 [Note] Server hostname (bind-address): '*'; port: 3306 mysql.5.7_1 | 2017-01-09T11:07:45.237759Z 0 [Note] IPv6 is available. mysql.5.7_1 | 2017-01-09T11:07:45.237877Z 0 [Note] - '::' resolves to '::'; mysql.5.7_1 | 2017-01-09T11:07:45.237961Z 0 [Note] Server socket created on IP: '::'. mysql.5.7_1 | 2017-01-09T11:07:45.295529Z 0 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode. mysql.5.7_1 | 2017-01-09T11:07:45.296334Z 0 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode. mysql.5.7_1 | 2017-01-09T11:07:45.304463Z 0 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode. mysql.5.7_1 | 2017-01-09T11:07:45.325375Z 0 [Note] Event Scheduler: Loaded 0 events mysql.5.7_1 | 2017-01-09T11:07:45.326559Z 0 [Note] Executing 'SELECT * FROM INFORMATION_SCHEMA.TABLES;' to get a list of tables using the deprecated partition engine. You may use the startup option '--disable-partition-engine-check' to skip this check. mysql.5.7_1 | 2017-01-09T11:07:45.326653Z 0 [Note] Beginning of list of non-natively partitioned tables mysql.5.7_1 | 2017-01-09T11:07:45.377612Z 0 [Note] End of list of non-natively partitioned tables mysql.5.7_1 | 2017-01-09T11:07:45.378560Z 0 [Note] mysqld: ready for connections. mysql.5.7_1 | Version: '5.7.17' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server (GPL) wp.spm_1 | Complete! WordPress has been successfully copied to /var/www/html wp.spm_1 | wp.spm_1 | Warning: mysqli::mysqli(): (HY000/2002): No such file or directory in - on line 19 wp.spm_1 | wp.spm_1 | MySQL Connection Error: (2002) No such file or directory wp.spm_1 | wp.spm_1 | Warning: mysqli::mysqli(): (HY000/2002): No such file or directory in - on line 19 wp.spm_1 | wp.spm_1 | MySQL Connection Error: (2002) No such file or directory A: I would say the problem is you are linking your wp instance with a database set up in the localhost, but that is not true, as your database is in the server mysql.5.7. I would try the next yaml file: version: '2' services: wp.spm: restart: always image: wordpress:latest ports: - "8080:80" environment: WORDPRESS_DB_HOST: mysql.5.7:3306 WORDPRESS_DB_USER: spm WORDPRESS_DB_PASSWORD: Ivietoo2Phah8xay WORDPRESS_DB_NAME: spm depends_on: - mysql.5.7 working_dir: /var/www/html volumes: - ./wp-content:/var/www/html/wp-content mysql.5.7: restart: always image: mysql:5.7 ports: - 3306:3306 environment: MYSQL_ROOT_PASSWORD: root # TODO: Change this MYSQL_USER: spm MYSQL_PASS: Ivietoo2Phah8xay MYSQL_DATABASE: spm volumes: - db_data:/var/lib/mysql volumes: db_data:
[ "physics.stackexchange", "0000533712.txt" ]
Q: Multiple observers watching a light source Every time I think I understand something about QED some very basic things just trip me up again. So, I realise a photon can be thought of as an observation that carries two parameters, its wave length and its direction of propagation. Also, I realise that if an observer observes a photon because of some interaction with matter (meaning electrons) - the classic example being a mirror, - the observation can be thought of to be built of all possible paths of the photon cancelling out each other and averaging out. I also appreciate you should not overthink this and it’s just what happens. I also understand the dual split + detector observation that illustrates a collapsing of the wavelike nature of photon observations into a particle like behaviour when it hits a detector at a split. However, I just can’t understand anymore how multiple observers can all look at a small source of EM, a light source, and all see the same at the same time. It’s driving me insane all of a sudden. Suppose billions of observations are made at the same time. All of humanity is looking at a small led in the vacuum of space. Why don’t they collapse the photons into only a couple of them reaching a couple of observers? Am I getting a traditional confusion of Copenhagen interpretation or just not seeing something silly? Also, if we consider matter being observed through its interaction with/by photons (which is maybe the only way to observe matter aside of gravity?), why do the photons not emerge as somewhat like pin needles sticking out and why do faraway observations not experience even more “holes” because of collapsed observations.. Sorry if this is trivial Copenhagen confusion. I’m just really confused and suddenly can no longer explain anything about the world. A: The EM wave of light is made up of gazillions of photons. This is why multiple observers can see the same event. But they aren’t detecting the same photons, rather they are detecting photons from the same source. However, if our optic system was capable of very high frame rates, high enough to resolve between photons in an EM wave, then we’d see in flashes. And this now will be unique for every observer. Take this experiment for example. Photons are sent one at a time through a double slit and captured on a screen. Each time, the photon only blips at one point on the screen. And many many photons later what we see is an interference pattern. Now, if you repeat the experiment, you won’t get the same sequence of detections but finally the pattern will still be that of interference. If our detectors aren’t fast enough to refresh, we won’t see the building up of the pattern but the pattern directly.
[ "stackoverflow", "0018300486.txt" ]
Q: how to compiler compile if statement main() { int k = 5; if(++k <5 && k++/5 || ++k<=8); // how to compiler compile this statement print f("%d",k); } // Here answer is 7 but why ? A: ++k < 5 evaluates to false (6 < 5 = false), so the RHS of the && operator is not evaluated (as the result is already known to be false). ++k <= 8 is then evaluated (7 <= 8 = true), so the result of the complete expression is true, and k has been incremented twice, making its final value 7. Note that && and || are short circuit boolean operators - if the result of the expression can be determined by the left hand argument then the right hand argument is not evaluated. Note also that, unlike most operators, short circuit operators define sequence points within an expression, which makes it legitimate in the example above to modify k more than once in the same expression (in general this is not permitted without intervening sequence points and results in Undefined Behaviour). A: Unlike many questions like this, it appears to me that your code actually has defined behavior. Both && and || impose sequence points. More specifically, they first evaluate their left operand. Then there's a sequence point1. Then (if and only if necessary to determine the result) they evaluate their right operand. It's probably also worth mentioning that due to the relative precedence of && and ||, the expression: if(++k <5 && k++/5 || ++k<=8) is equivalent to: if((++k <5 && k++/5) || ++k<=8). So, let's take things one step at a time: int k = 5; if(++k <5 && So, first it evaluates this much. This increments k, so its value becomes 6. Then it compares to see if that's less than 5, which obviously produces false. k++/5 Since the previous result was false, this operand is not evaluated (because false && <anything> still always produces false as the result). || ++k<=8); So, when execution gets to here, it has false || <something>. Since the result of false | x is x, it needs to evaluate the right operand to get the correct result. Therefore, it evaluates ++k again, so k is incremented to 7. It then compares the result to 8, and finds that (obviously) 7 is less than or equal to 8 -- therefore, the null statement following the if is executed (though, being a null statement, it does nothing). So, after the if statement, k has been incremented twice, so it's 7. In C++11, the phrase "sequence point" has been replaced with phrases like "sequenced before", as in: "If the second expression is evaluated, every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second expression." Ultimately, the effect is the same though. A: In following: for && "something" is evaluated when first condition is True for || "something" is evaluated when first condition is False ( (++k <5) && (k++/5) ) || (++k<=8) ( 6 < 5 AND something ) OR something ( False AND something ) OR something ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ False OR 7 < 8 False OR True ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ True So k comes out to be 7
[ "stats.stackexchange", "0000337736.txt" ]
Q: Regression: IV - DV non.sig. But moderator highly sig I am researching the effect of an innovation type on firm performance. In my quantile regression model, the relationship between my IV "innovation" and and DV "firm performance" is non-significant (p=,7). However, the moderator "firm size" is highly significant (p<,001). Is this possible? And how should this be interpreted? I don't get how firm size should influence the relationship of innovation and firm performance, if there initially is no relationship... Thanks! A: When you consider firms of different sizes together and investigate the effect of "innovation" on "firm performance" among these firms, one of the reasons you might fail to see an effect is the heterogeneity of firms with respect to firm sizes. This heterogeneity may introduce "noise" which obscures the effect of interest because you are not controlling for it. Of course, it is also possible that there is no such effect for these firms when considered together, which is why you are not able to detect it. However, when you look only at firms of the same size, you might see that, for those firms, there is an effect of "innovation" on "firm performance". This effect may be independent of firm size or may depend on firm size. The model where you ignore "firm size" (model 1) is therefore different from the model where you account for it (model 2). In model 1, you are concerned with the effect of "innovation" on "firm performance" among all firms, irrespective of their size. In model 2, you are concerned with the effect of "innovation" on "firm performance" among all firms of the same size. Model 2 can allow for the effect of "innovation" on "firm performance" to be the same among small firms as it is among moderate firms or among moderate firms (in which case, the model would include only "innovation" and "firm size", but not their interaction). Alternatively, it can allow for this effect to depend on firm size (in which case, the model would include "innovation", "firm size" and their interaction as predictor variables).
[ "stackoverflow", "0011288009.txt" ]
Q: How to parse the webpage in iphone, and how to get the part of data from table of that webpage ? I am new to iphone, i am trying to parse a webpage. In that webpage we table of contents headed with Country, code , location, population. And if we click on any country name then it navigates to another page. My intension is to get the county name and country code from this webpage and use in my app. Please help me in doing so. thank you A: You can make a request to the page using any 3rd party libraries for that purpose (MKNetworkKit, for example) or just the basic NSURLConnection. After that, you will receive the HTML on the response which can be parsed and used for whatever you want.
[ "stackoverflow", "0026051087.txt" ]
Q: About responsive sites, pixels, and density I have coded a responsive website, in which I have CSS media queries to detect the screen size(pixels) of the device the user is navigating with. Just standard medias. Example: @media (max-width: 1199px){ /*code*/ } @media (max-width: 991px){ /*code*/ } @media (max-width: 767px){ /*code*/ } When I test my website with my mobile, which is a Samsung Galaxy S4 with 1920x1080 pixels my website shows me the mobile version, which is in this case the @media query with a max-width of 767px. I understand that most things would be too small to read or be seen if my mobile respected exact measures like 12px font size. So my question is, how do I control which version of my website is shown on high resolution devices, because pixels media queries aren't working in my case. A: @media (max-width: 1199px){ /*code*/ } The max-width property in the media query works a little different. It is not the resolution of the screen. It is equivalent css pixel. Here are a couple of articles. A pixel identity crisis. A pixel is not a pixel is not a pixel. moz media query page. If you want to target device resolution you should use @media all and (max-device-width: 320px) { }. max-device-width:This property measures the device-width. If you write css using media query using this it will get a little complex (mobiles tabs and even desktops can have 1080p resolution screens). In order to target device resolutions you might have to look into properties like -device-pixel-ratio , orientation and device-height to give better control of layouts
[ "ru.stackoverflow", "0000440278.txt" ]
Q: Как найти ближайшее четное число, меньше или равное данному? Получаю число делением. Если четное — подходит, если нечетное — нужно изменить на четное, отняв единицу. Подскажите алгоритм решения. $perPage = 18 / 2; //18 это просто пример, делить нужно и другие числа echo $perPage; // дает 9, а требуется 8 A: Например так: $perPage = 18 / 2; // может быть и (19 / 2) echo (floor($perPage / 2) * 2); // выведет 8 A: $perPage = 18 / 2; $odd = ($perPage % 2 != 0); if ($odd) { $perPage--; } echo $perPage; A: Еще вариант: <?php $perPage = 18 / 2; echo intval($perPage / 2) * 2; UPD сделан после принятия ответа как правильный. В ответ на обсуждение в ответе от @Nick Volynkin. Провел тестирование скорости работы того или иного варианта в такой конструкции: $start = microtime(TRUE); for ($i = 2; $i < 100000; $i++) { // код примера } echo "time: ", microtime(TRUE) - $start, "\n"; Ответ от @Dmitriy Simushev, время выполнения ~ 0.60 сек. Ответ от @Nick Volynkin имеет примерно такое же время (т.е. там где заменили двойное деление на 2 на одинарное но на 4). Мой ответ, представленный выше, время выполнения ~ 0.54 сек. Ответ от @xaja, время выполнения ~ 0.10 сек. Смотрите UPD3. И наконец победитель ;) Спасибо @VladD'у за напоминание об этом способе: <?php $perPage = 18 / 2; echo (int)($perPage / 2) * 2; Время выполнения ~ 0.08 сек. UPD2 По поводу правильности решения: Если автор работает только с положительными числами, то все ответы перечисленные в UPD дают верный результат; Если на входе есть как положительные числа, так и отрицательные и получить всегда надо ближайшее четное, меньшее или равное данному, то единственный правильный ответ - это ответ от @xaja; Смотрите UPD3. Если же надо получить ближайшее четное по модулю, то правильными ответами являются все кроме ответа от @xaja. UPD3 Ответ от @xaja в таком виде $perPage = 18 / 2; $odd = ($perPage % 2 != 0); if ($odd) { $perPage--; } echo $perPage; выдает ошибочный результат для нечетного числа на входе.
[ "stackoverflow", "0032067772.txt" ]
Q: What is the best way to style the selected(clicked) item What is the best way to style the selected column of the following HTML code <div class="row"> <div class="col-md-3 portfolio-item starter"> <a href="#/starter"> <img class="img-responsive" src="images/starter.jpg" alt="starter"> </a> <h2><a href="#/starter">Starter</a></h2> </div> <div class="col-md-3 portfolio-item"> <a href="#/salads"> <img class="img-responsive" src="images/salads.jpg" alt="salads"> </a> <h2><a href="#/salads">Salads</a></h2> </div> <div class="col-md-3 portfolio-item"> <a href="#/main"> <img class="img-responsive" src="images/main.jpg" alt="main"> </a> <h2><a href="#/main">Main</a></h2> </div> <div class="col-md-3 portfolio-item"> <a href="#/dessert"> <img class="img-responsive" src="images/desserts.jpg" alt="desserts"> </a> <h2><a href="#/dessert">Desserts</a></h2> </div> </div> <!-- /.row --> I have 4 columns as above, when user selects(clicks) one of the column, i want to highlight it with some style A: Try this Add main-menu class and active class JQUERY $('.main-menu div').on('click',function(){ $('div').removeClass('active'); $(this).addClass('active'); }); CSS .active{ background-color:green; } DEMO
[ "stackoverflow", "0033944192.txt" ]
Q: ggplot2: color part of the line I stumble. I need your advice and suggestions. I need to apply different scheme for the part of the lines - color, dashed or increase the thickness for "very_important_features". I need to make them visually more appealing. dat <- rbind( x <- sort(sample(1:1000,size = 200) + sample(1:500,size = 200, replace = T)), y <- sort(sample(1:1000,size = 200) + sample(1:200,size = 200, replace = T)), z <- sort(sample(1:1000,size = 200) - sample(1:100,size = 200, replace = T))) rownames(dat) <- c("x","y","z") #colnames(dat) <- paste("feature",1:200,sep="_") library(reshape) dat.m <- melt(dat) ggplot(data=dat.m, aes(x=X2, y=value, group=X1, color = X1)) + geom_line() very_important_features <- unique(sort(sample(dat.m$X2, 100))) A: It's generally better practice to identify the thing you want to plot as a separate column in the data, so that it can be mapped to the plot aesthetics/layers. Here is an example: 1 - add variable to data frame: dat.m$important <- ifelse(dat.m$X2 < 60, "yes","no") 2 - Plot, using that variable as the thing that controls size ggplot(data=dat.m)+ aes(x=X2, y=value, group=X1, color = X1, size=important) + geom_line()+ scale_size_manual(values=c("yes"=3, "no"=1)) Here's the output: and now there's a handy legend showing you what line size means.
[ "stackoverflow", "0063470099.txt" ]
Q: Test Suite Environment Variables I'm facing a rookie challenge in Qurkus (I'm also new in Java, so sorry if I'm having a silly situation). I'm using ".env" file for local development vars and setting (non-secret) production vars in "application.properties". Things were fine but now that I'm trying to setup a test suite, vars from ".env" are overwriting the ones in "application.properties" (even then ones with "%test" profile) & blocks me to have a development and test environment simultaneously. To me this can be done by having a separate (source control indexed) env file for different %profiles like ".env.testing" and somehow assign it to test runner. This pattern is very common in other languages' testing frameworks, but I couldn't find a solution for that. Have any idea? Thanks A: It turned out that Quarkus supports configuration profiles in .env with a different format (but it's not mentioned in the docs). So we can simply keep our application.properties file like this: app.env=production and the .env file like this: _DEV_APP_ENV=development _TEST_APP_ENV=testing A more detailed doc can be found in this PR.
[ "scifi.stackexchange", "0000126246.txt" ]
Q: What are the listed magical wand components used in Harry Potter canon? Lots of things are used in the making of wands, Dragon Heartstrings, unicorn hairs, phoenix feathers, however some much more interesting and expanded lore could be derived from the use of other things in wands, like Basilisk scales, Bogart... Goo?, or some physical essence of dementor. I know that Fleur Delacour's wand uses Veela hair, and accord to this question/answer it is purely Olivander's choice to limit himself to the three primary core types. Is there any canon example of other parts being used to make a wand, and if so, is there an exhaustive list of magical components used? A: Rougarou hair For example, President Seraphina Picquery had a wand made by Violetta Beauvais, and thus containing a core of rougarou hair. From Pottermore: Violetta Beauvais, the famous wandmaker of New Orleans, refused for many years to divulge the secret core of her wands, which were always made of swamp mayhaw wood. Eventually it was discovered that they contained hair of the rougarou, the dangerous dog-headed monster that prowled Louisiana swamps. It was often said of Beauvais wands that they took to Dark magic like vampires to blood, yet many an American wizarding hero of the 1920s went into battle armed only with a Beauvais wand, and President Picquery herself was known to possess one. There were also wandmakers hailing from the United States who used a variety of cores in their wands, such as the feathers of a thunderbird, the spines of the White River Monster, or the hair of a wampus cat. Thestral hair Even in Europe, where Ollivander dominated, there were many other possible wand cores. The Elder Wand, for example, posssesses a core of thestral hair.: I decided that the core of the Elder Wand is the tail hair of a Thestral; a powerful and tricky substance that can be mastered only by a witch or wizard capable of facing death. Kelpie hair And of course, before Ollivander started using only the three Supreme Cores, a wide variety of materials were used in wands: Early in my career, as I watched my wandmaker father wrestling with substandard wand core materials such as kelpie hair, I conceived the ambition to discover the finest cores and to work only with those when my time came to take over the family business. Troll whisker As an example, the wand of Sir Cadogan is believed to have had a core of troll whisker. Blackthorn and troll whisker, nine inches, combustible. Basilisk horn The wand of Salazar Slytherin contained a piece of the horn of a basilisk, almost certainly the self-same beast he hid in the Chamber of Secrets: In all the years that she had lived with it, Isolt had never known that she held in her hand the wand of Salazar Slytherin, one of the founders of Hogwarts, and that it contained a fragment of a magical snake’s horn: in this case, a Basilisk.
[ "stackoverflow", "0061534248.txt" ]
Q: WebSphere in application.xml and @Resource injection I can't inject environment entries from application.xml using the @Resource annotation in my WebSphere 8.5.5 application. (I don't want to move the entry down to the component level ejb-jar.xml.) What am I missing? application.xml: <application xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_6.xsd" version="6"> <env-entry> <env-entry-name>fileName</env-entry-name> <env-entry-type>java.lang.String</env-entry-type> <env-entry-value>theValue</env-entry-value> </env-entry> With this, I do see "fileName" defined as "theValue" in the WebSphere Admin Console section Environment entries for the application. Yet I can't figure out how to access this from my EJB. StartupBean.java: @Singleton @Startup public class StartupBean { @Resource(name = "fileName") private String fileName = "default"; fileName is always "default", not "theValue". I tried a manual lookup using both "java:comp" and "java:app" (as suggested by this thread), but both throw NamingException Context ctx = new InitialContext(); fileName = (String) ctx.lookup("java:comp/env/fileName"); fileName = (String) ctx.lookup("java:app/env/fileName"); A: Resources declared in application.xml must use either the java:app/env or java:global/env prefix, so it should look like: <env-entry> <env-entry-name>java:app/env/fileName</env-entry-name> <env-entry-type>java.lang.String</env-entry-type> <env-entry-value>theValue</env-entry-value> </env-entry> Then, injection into the field would be as follows: @Resource(name = "java:app/env/fileName") private String fileName = "default";
[ "stackoverflow", "0056838314.txt" ]
Q: Maven (with tycho) fails while materialize-products I have an RCP Application which builds find on Eclipse 4.5.2 and 4.6.3; Today i tried to upgrade to Eclipse 2019-6; when i try to manfest a product with maven (mvn clean install) i get the following output: [INFO] --- tycho-p2-repository-plugin:1.4.0:archive-repository (default-archive-repository) @ at.biooffice.rcp.product --- [INFO] Building zip: D:\WS18\git\at.biooffice.rcp.product\target\at.biooffice.rcp.product-3.0.1-SNAPSHOT.zip [INFO] [INFO] --- tycho-p2-director-plugin:1.4.0:materialize-products (materialize-products) @ at.biooffice.rcp.product --- [INFO] Installing product at.biooffice for environment win32/win32/x86_64 to D:\WS18\git\at.biooffice.rcp.product\target\products\at.biooffice\win32\win32\x86_64 Installing at.biooffice 3.0.1.201907011447. Installation failed. Cannot complete the install because one or more required items could not be found. Software being installed: BioOffice 3.0.1.201907011447 (at.biooffice 3.0.1.201907011447) Missing requirement: toolingwin32.win32.x86_64org.eclipse.equinox.ds 3.0.1.201907011447 requires 'osgi.bundle; org.eclipse.equinox.ds 1.6.0.v20190122-0806' but it could not be found Cannot satisfy dependency: From: BioOffice 3.0.1.201907011447 (at.biooffice 3.0.1.201907011447) To: org.eclipse.equinox.p2.iu; toolingat.biooffice.configuration [3.0.1.201907011447,3.0.1.201907011447] Cannot satisfy dependency: From: toolingat.biooffice.configuration 3.0.1.201907011447 To: org.eclipse.equinox.p2.iu; toolingwin32.win32.x86_64org.eclipse.equinox.ds [3.0.1.201907011447,3.0.1.201907011447] There were errors. See log file: D:\WS18\git\at.biooffice.parent\workspace\.metadata\.log [INFO] ------------------------------------------------------------------------ [INFO] Reactor Summary: [INFO] [INFO] BioOffice 3.0.1-SNAPSHOT ........................... SUCCESS [ 2.483 s] [INFO] microsoftsqlserver 2.0.0-SNAPSHOT .................. SUCCESS [ 0.590 s] [INFO] org.eclipse.gemini.dbaccess.microsoftsqlserver 2.0.0-SNAPSHOT SUCCESS [ 0.869 s] [INFO] com.mysql.jdbc 5.1.38-SNAPSHOT ..................... SUCCESS [ 0.170 s] [INFO] org.eclipse.gemini.dbaccess.mysql 5.1.38-SNAPSHOT .. SUCCESS [ 0.298 s] [INFO] at.biooffice.osgi.service.dialog 3.0.1-SNAPSHOT .... SUCCESS [ 0.269 s] [INFO] lumo.osgi.service.notification 3.0.1-SNAPSHOT ...... SUCCESS [ 0.457 s] [INFO] lumo.osgi.service.notification.impl 3.0.1-SNAPSHOT . SUCCESS [ 0.471 s] [INFO] lumo.core.runtime 3.0.1-SNAPSHOT ................... SUCCESS [ 18.182 s] [INFO] at.biooffice.osgi.service.eclipselink 3.0.1-SNAPSHOT SUCCESS [ 2.032 s] [INFO] at.biooffice.rcp 3.0.1-SNAPSHOT .................... SUCCESS [ 2.129 s] [INFO] at.biooffice.osgi.service.eclipselink.impl 3.0.1-SNAPSHOT SUCCESS [ 2.474 s] [INFO] lumo.exports.csv 3.0.1-SNAPSHOT .................... SUCCESS [ 1.399 s] [INFO] lumo.exports.mssql 3.0.1-SNAPSHOT .................. SUCCESS [ 1.387 s] [INFO] lumo.exports.kml 3.0.1-SNAPSHOT .................... SUCCESS [ 1.365 s] [INFO] lumo.exports.shp 3.0.1-SNAPSHOT .................... SUCCESS [ 1.209 s] [INFO] lumo.exports.vcard 3.0.1-SNAPSHOT .................. SUCCESS [ 1.260 s] [INFO] lumo.exports.taxaendangered 3.0.1-SNAPSHOT ......... SUCCESS [ 1.276 s] [INFO] lumo.imports.xml.nls 3.0.1-SNAPSHOT ................ SUCCESS [ 1.272 s] [INFO] lumo.osgi.service.multimedia 3.0.1-SNAPSHOT ........ SUCCESS [ 1.254 s] [INFO] lumo.osgi.service.multimedia.impl 3.0.1-SNAPSHOT ... SUCCESS [ 1.380 s] [INFO] at.biooffice.osgi.service.dialog.impl 3.0.1-SNAPSHOT SUCCESS [ 1.540 s] [INFO] at.biooffice.update 3.0.1-SNAPSHOT ................. SUCCESS [ 1.262 s] [INFO] at.biooffice.osgi.service.map 3.0.1-SNAPSHOT ....... SUCCESS [ 1.224 s] [INFO] at.biooffice.osgi.service.map.impl 3.0.1-SNAPSHOT .. SUCCESS [ 1.537 s] [INFO] at.biooffice.views.attachedliterature 3.0.1-SNAPSHOT SUCCESS [ 1.365 s] [INFO] at.biooffice.views.bioobject 3.0.1-SNAPSHOT ........ SUCCESS [ 1.399 s] [INFO] at.biooffice.common.admin 3.0.1-SNAPSHOT ........... SUCCESS [ 1.278 s] [INFO] at.biooffice.views.collection 3.0.1-SNAPSHOT ....... SUCCESS [ 1.266 s] [INFO] at.biooffice.views.contact 3.0.1-SNAPSHOT .......... SUCCESS [ 1.281 s] [INFO] at.biooffice.views.determination 3.0.1-SNAPSHOT .... SUCCESS [ 1.265 s] [INFO] at.biooffice.views.dataexchange 3.0.1-SNAPSHOT ..... SUCCESS [ 3.052 s] [INFO] at.biooffice.views.excursion 3.0.1-SNAPSHOT ........ SUCCESS [ 1.257 s] [INFO] at.biooffice.views.literature 3.0.1-SNAPSHOT ....... SUCCESS [ 1.263 s] [INFO] at.biooffice.views.lookups 3.0.1-SNAPSHOT .......... SUCCESS [ 1.326 s] [INFO] at.biooffice.views.multimedia 3.0.1-SNAPSHOT ....... SUCCESS [ 1.329 s] [INFO] at.biooffice.views.report 3.0.1-SNAPSHOT ........... SUCCESS [ 2.193 s] [INFO] at.biooffice.views.nls 3.0.1-SNAPSHOT .............. SUCCESS [ 1.284 s] [INFO] at.biooffice.views.project 3.0.1-SNAPSHOT .......... SUCCESS [ 1.279 s] [INFO] at.biooffice.views.querymanager 3.0.1-SNAPSHOT ..... SUCCESS [ 1.798 s] [INFO] at.biooffice.views.site 3.0.1-SNAPSHOT ............. SUCCESS [ 1.313 s] [INFO] at.biooffice.views.taxon 3.0.1-SNAPSHOT ............ SUCCESS [ 1.601 s] [INFO] at.biooffice.views.welcome 3.0.1-SNAPSHOT .......... SUCCESS [ 1.339 s] [INFO] at.biooffice.views.loan 3.0.1-SNAPSHOT ............. SUCCESS [ 1.375 s] [INFO] at.biooffice.views.servicemonitor 3.0.1-SNAPSHOT ... SUCCESS [ 1.235 s] [INFO] jre.win32.win32.x86_64 8.0.66 ...................... SUCCESS [ 2.631 s] [INFO] at.biooffice.feature 3.0.1-SNAPSHOT ................ SUCCESS [ 0.967 s] [INFO] at.biooffice.feature.admin 3.0.1-SNAPSHOT .......... SUCCESS [ 0.226 s] [INFO] at.biooffice.feature.free.addons 3.0.1-SNAPSHOT .... SUCCESS [ 0.275 s] [INFO] at.biooffice.rcp.product 3.0.1-SNAPSHOT ............ FAILURE [ 37.278 s] [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 07:01 min [INFO] Finished at: 2019-07-01T16:54:21+02:00 [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal org.eclipse.tycho:tycho-p2-director-plugin:1.4.0:materialize-products (materialize-products) on project at.biooffice.rcp.product: Installation of product at.biooffice for environment win32/win32/x86_64 failed: Call to p2 director application failed with exit code 13. Program arguments were: [-metadataRepository, file:/D:/WS18/git/at.biooffice.rcp.product/target/,file:/D:/WS18/git/at.biooffice.rcp.product/target/targetPlatformRepository/, -artifactRepository, file:/D:/WS18/git/at.biooffice.rcp.product/target/,file:/resolution-context-artifacts@D%253A%255CWS18%255Cgit%255Cat.biooffice.rcp.product,file:/D:/WS18/git/at.biooffice.rcp.product/target/,file:/D:/WS18/git/at.biooffice.feature/target/,file:/D:/WS18/git/at.biooffice.feature.admin/target/,file:/D:/WS18/git/at.biooffice.feature.free.addons/target/,file:/D:/WS18/git/at.biooffice.common.admin/target/,file:/D:/WS18/git/lumo.core.runtime/target/,file:/D:/WS18/git/at.biooffice.osgi.service.dialog/target/,file:/D:/WS18/git/lumo.osgi.service.notification/target/,file:/D:/WS18/git/at.biooffice.views.lookups/target/,file:/D:/WS18/git/at.biooffice.views.nls/target/,file:/D:/WS18/git/at.biooffice.views.querymanager/target/,file:/D:/WS18/git/lumo.imports.xml.nls/target/,file:/D:/WS18/git/jre.win32.win32.x86_64/target/,file:/D:/WS18/git/lumo.osgi.service.multimedia/target/,file:/D:/WS18/git/lumo.osgi.service.multimedia.impl/target/,file:/D:/WS18/git/lumo.osgi.service.notification.impl/target/,file:/D:/WS18/git/microsoftsqlserver/target/,file:/D:/WS18/git/org.eclipse.gemini.dbaccess.microsoftsqlserver/target/,file:/D:/WS18/git/at.biooffice.osgi.service.dialog.impl/target/,file:/D:/WS18/git/at.biooffice.osgi.service.eclipselink/target/,file:/D:/WS18/git/at.biooffice.osgi.service.eclipselink.impl/target/,file:/D:/WS18/git/at.biooffice.views.bioobject/target/,file:/D:/WS18/git/at.biooffice.views.collection/target/,file:/D:/WS18/git/at.biooffice.views.contact/target/,file:/D:/WS18/git/at.biooffice.views.dataexchange/target/,file:/D:/WS18/git/at.biooffice.views.excursion/target/,file:/D:/WS18/git/at.biooffice.views.literature/target/,file:/D:/WS18/git/at.biooffice.views.multimedia/target/,file:/D:/WS18/git/at.biooffice.views.report/target/,file:/D:/WS18/git/at.biooffice.views.project/target/,file:/D:/WS18/git/at.biooffice.views.site/target/,file:/D:/WS18/git/at.biooffice.views.taxon/target/,file:/D:/WS18/git/at.biooffice.views.welcome/target/,file:/D:/WS18/git/at.biooffice.rcp/target/,file:/D:/WS18/git/at.biooffice.update/target/,file:/D:/WS18/git/at.biooffice.views.determination/target/,file:/D:/WS18/git/at.biooffice.views.attachedliterature/target/,file:/D:/WS18/git/at.biooffice.views.loan/target/,file:/D:/WS18/git/com.mysql.jdbc/target/,file:/D:/WS18/git/org.eclipse.gemini.dbaccess.mysql/target/,file:/D:/WS18/git/lumo.exports.kml/target/,file:/D:/WS18/git/lumo.exports.taxaendangered/target/,file:/D:/WS18/git/lumo.exports.vcard/target/,file:/D:/WS18/git/lumo.exports.shp/target/,file:/D:/WS18/git/lumo.exports.mssql/target/,file:/D:/WS18/git/lumo.exports.csv/target/,file:/D:/WS18/git/at.biooffice.osgi.service.map/target/,file:/D:/WS18/git/at.biooffice.osgi.service.map.impl/target/,file:/C:/Users/BlackPearl/.m2/repository/, -installIU, at.biooffice, -destination, D:\WS18\git\at.biooffice.rcp.product\target\products\at.biooffice\win32\win32\x86_64, -profile, DefaultProfile, -profileProperties, org.eclipse.update.install.features=true, -roaming, -p2.os, win32, -p2.ws, win32, -p2.arch, x86_64]. -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException [ERROR] [ERROR] After correcting the problems, you can resume the build with the command [ERROR] mvn <goals> -rf :at.biooffice.rcp.product so all bundles build successfully but the product does not! which referrs to: org.eclipse.equinox.p2.iu by definition i had both org.eclipse.rcp and org.eclipse.e4.rcp as requirement. this leads to this error i tried removing org.eclipse.rcp also org.eclipse.e4.rcp but in the end nothing works. any ideas how to fix this error? A: It looks like you have an explicit dependency on the org.eclipse.equinox.ds plug-in. Current versions of Eclipse have dropped that plug-in and replaced it with the org.apache.felix.scr plug-in.
[ "stackoverflow", "0013309330.txt" ]
Q: Change image source with value from array <html> <script type="javascript"> var building=new Array(10) building[1]="images_buildings/abudhabi.jpg" building[2]="images_buildings/auckland.jpg" building[3]="images_buildings/coffsharbour.jpg" building[4]="images_buildings/endinburge.jpg" building[5]="images_building/la.jpg" building[6]="images_building/london.jpg" building[7]="images_building/newyork.jpg" building[8]="images_buildings/singapore.jpg" building[9]="images_buildings/sydney.jpg" building[10]="images_buildings/toronto.jpg" var num = 0 function changepic() { num=num+1 if (num==11) {num=1} document.buildingpic.src=eval("building"+num+".src" ) } </script> </head> <body> <center> <img src="images_buildings/abudhabi.jpg" name="buildingpic" width="400" height="400" /> <p><A HREF="JavaScript:changepic()">next</A></p> </center> </p> </body> </html> I have tried to research but just couldnt find anything that helped me- once i resolve this i will be adding another pic array and a information array :/ but i was constructing it one at a time :) A: Here you go, try this instead. document.buildingpic.src=building[num]
[ "stackoverflow", "0003615758.txt" ]
Q: Which design pattern to choose i need a pointer i the right direction. I have been looking around and cant seem to find any design pattern (GoF) that will point me in the right direction. I am developing a small digital signage application prototype, where there is a simple server and an amount of player applications (displaying an image/video) connected to this server. My requirements are to be able to connect 100 players to a single server, and distribute 50Mb data to each. I plan on making small hubs (software hubs) in between the server and the players collecting the players (around 25 in each?) in hubs and having the hubs get and distribute the 50Mb data (divide and conquer, right?). The 50Mb is only for the prototype, i reckon that in real life displaying videos will be more around 300Mb to each. The reason for these hubs is that i would avoid having 100 players request 50Mb at the same time, instead only 4 (with 25 players each) hubs will request and redistribute. When using Hubs i will need to be able to move the players around between the hubs, that is remove a player from one hub and attach it to another hub. (one of my thoughts are that all players attached to the same hub must share content, so the hub will avoid having to download 25 different movies) Please, does anyone know how this is done in real life? Could you please comment on my concepts and/or point me in the right direction for at pattern/book that would help me solve this issue. A: Don't "choose" the design pattern before you design. Design first, and then compare with the patterns. Your design need not always adhere to the patterns. But, make sure your design doesn't adhere to anti-patterns. A: You need to take a step back from this. At the minute, you're trying to concentrate on the minutiae of your software architecture, without having considered (or at least mentioned) some important requirements. It looks like you're really just trying to stream video. So: Can you use an off the shelf video streaming product? This may be cheaper than building your own. If not: Will a broadcast model work for you, or does it have to be on demand? That is, let's say Client 1 requests Video A. If, a few minutes later, Client 2 also wants Video A, is it OK if Client 2 becomes another viewer of the same stream that Client 1 is receiving? Will this be delivered over the internet, or on a private network over which you have control? If you're using a private network and a broadcast model will work, you may be able to use UDP Multicast, which can offer significant bandwidth reduction over a pure on-demand solution. So before you start deciding on your software architecture, you need to consider your hardware constraints and how they impact on the choices available to you. Getting back to your proposed solution, I don't think it will scale very reliably. If one particular piece of content is very popular, then one of your hubs will be grossly overloaded, while others are idle. You may want to look into a more conventional load balancing technique which will allow you to scale out by simply adding more servers.
[ "stackoverflow", "0035842897.txt" ]
Q: SharedPreference gets cleared while navigating through one activity to another I am using SharedPreference to store my id, but it does not work. When app launches in Activity-A, I am storing id in prefs, and then go to Activity-B. In my Activity-B I have one button, on click of button I am going back to Activity-A, and I see that the id which I stored was not in preferece Activity-A @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); id = getIntent().getStringExtra("id"); editor = getApplicationContext().getSharedPreferences(MY_PREFS_NAME, 0).edit(); editor.putString("yourtextvalueKey", id); editor.commit(); prefs = getApplicationContext().getSharedPreferences(MY_PREFS_NAME, 0); text= prefs.getString("yourtextvalueKey", null); System.out.println("text of id"+text); Activity-B backaro.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(ActivityB.this,ActivityA.class); startActivity(intent); } }); A: Reason: You are getting the value from intent and saving it. Initially it gets saved and you can see that. But, when you move back to ActivityA on button click of ActivityB you don't pass any value to the intent. Which means id becomes null and it gets saved. So you are getting null as result. Update your code like this id = getIntent().getStringExtra("id"); if(id != null){ editor = getApplicationContext().getSharedPreferences(MY_PREFS_NAME, 0).edit(); editor.putString("yourtextvalueKey", id); editor.commit(); } prefs = getApplicationContext().getSharedPreferences(MY_PREFS_NAME, 0); text= prefs.getString("yourtextvalueKey", null); System.out.println("text of id"+text); Update: You could also pass an value in intent when you start activity on button click and you will get that value. But if you don't want to sent any value then you need to check it first.
[ "stackoverflow", "0034961939.txt" ]
Q: String was not recognized as a valid DateTime Error when try to sow date and time data into DateTimePicker from DataGridView I want to display Date and time (format: dd/MM/yyyy h:mm tt) from column "DateTime to DateTimePicker. but it shows an error String was not recognized as a valid DateTime. Private Sub dgvSchedule_RowEnter(sender As Object, e As DataGridViewCellEventArgs) Handles dgvSchedule.RowEnter 'DISPLAYS COLUMN VALUE IN TEXTBOXES If e.RowIndex >= 0 Then Dim row As DataGridViewRow row = Me.dgvSchedule.Rows(e.RowIndex) txtID.Text = row.Cells("Patient_ID_Number").Value.ToString dtpDate.Text = row.Cells("Date_Time").Value 'THIS IS WHERE THE ERROR OCCUR txtFirstname.Text = row.Cells("Firstname").Value.ToString txtLastname.Text = row.Cells("Lastname").Value.ToString txtPhoneNumber.Text = row.Cells("Phone_Number").Value.ToString End If End Sub A: What is the format of your 'Date_Time' column? If it's a MySQL datetime like this: 2016-01-23 23:30:55 then you can just use the DateTime.Parse of VB.NET Dim new_date As DateTime = DateTime.Parse("2016-01-23 23:30:55") DateTimePicker1.Value = new_date Note that the format is 'Custom' and the CustomFormat is dd/MM/yyyy h:mm tt DateTimePicker1.Format = DateTimePickerFormat.Custom DateTimePicker1.CustomFormat = "dd/MM/yyyy h:mm tt" So the final code could be: DateTimePicker1.Format = DateTimePickerFormat.Custom DateTimePicker1.CustomFormat = "dd/MM/yyyy h:mm tt" Dim new_date As DateTime = DateTime.Parse(row.Cells("Date_Time").Value.ToString()) DateTimePicker1.Value = new_date I also noticed that you are using: dtpDate.Text = row.Cells("Date_Time").Value instead of dtpDate.Value = row.Cells("Date_Time").Value Note that these are different: Text and Value.
[ "diy.stackexchange", "0000098559.txt" ]
Q: Why do the wires to my dryer's thermostat keep burning off? I have a Kenmore/Whirlpool dryer that a week ago stopped working. The motor and timing would work, but there was no heat produced. I disassembled the entire dryer and vacuumed and brushed every nook and cranny of lint. I ordered an entire set of thermostats, including a heating element. When I opened the back of the dryer, I noticed one of the leads to the running thermostat was burned off and the thermostat was charred and deformed. I tested the thermostat for continuity and it read OK. I respliced the wire and still no heat. I tested all the other thermostats and heater coils, including the motor switch and they all passed. I even went as far as testing the timer, which was also OK. I had a hard time believing the molten thermostat wasn't defective when everything I read said that if it has continuity. Finally, I gave in and replaced only the charred thermostat and it worked. A few days later, the dryer stopped working again, Same problem. I open the dryer and retested all the thermostats and heater. Everything was OK. I also tested the leads at the main circuit breaker and the leads to the dryer. Figuring at least one of the other thermostats has a false positive, I replaced them all, including the main fuse. It worked again and I thought I conquered the problem. Today, I did a load and found my clothes still damp. I turned on the dryer waited a few seconds and again, no heat. The obvious question is, what can be possibly be wrong? I never replaced the heating coils, but there was no need to. The only thing I could remotely see wrong was some fine soot on the heating element wires on one side. Could this be a hot spot? I was also puzzled by how the dryer thermostats never read bad. Yes, I did disconnect one of the leads. Obviously, the troubleshooting steps are wrong. I am at my wits end and a new dryer is out of the question. This dryer worked well for at least two decades and I am determind to solve this problem. EDIT 2 Since I my last edit, which has been a few years, I have replaced various components in the dryer, including thermostats, wires, etc. I discovered there were burn marks on the wire terminals and the component it lead to. The failure was fairly consistent and wondered why it keeps happening. Lo and behold, the terminals I was using were insulated crimp terminals and it was increasing the resistance of the wire causing it to burn out. I never suspected it because there was no apparent melting of the plastic insulator. I wanted to use non-insulated terminals, but they were very difficult to find and removing the insulation from the terminal connector made an unreliable connection. EDIT 1 I opened the dryer and tested all of the thermostats and one of the new ones installed above the coils failed. It had no continuity. I replaced it and now it works. What could be causing the thermostats to fail? I should also add that the ducts are totally clean and unobstructed. My guess is that the replacement parts are of shoddy quality. They were very cheap compared to the ones at Sears. $18 for all thermostats and a fuse versus $29 for just the one that was bad. I am worried that that there may be an electrical problem, venting problem (no changes) or the coil is overheating. A: Since I my last edit, which has been a few years, I have replaced various components in the dryer, including thermostats, wires, etc. I discovered there were burn marks on the wire terminals and the component it lead to. The failure was fairly consistent and wondered why it keeps happening. Lo and behold, the terminals I was using were insulated crimp terminals and it was increasing the resistance of the wire causing it to burn out. I never suspected it because there was no apparent melting of the plastic insulator. I wanted to use non-insulated terminals, but they were very difficult to find and removing the insulation from the terminal connector made an unreliable connection.
[ "stackoverflow", "0017316126.txt" ]
Q: Inserting a LinkedList into another LinkedList At the moment, I have a method in my LinkedList (not the Java's one) class that adds single nodes to a LinkedList and it looks like this: public void add(int index, T v) { if(isValidIntervalPosition(index)) { Node<T> n = new Node<T>(v); if(index == 0) { n.setNext(head); head = n; } else { Node<T> m = head; int count = 1; while(count < index) { m = m.getNext(); count++; } n.setNext(m.getNext()); m.setNext(n); } sz++; } } But I would like to implement another method that adds the nodes from an input LinkedList to the current LinkedList. Here is the skeleton: public void add(int position, LinkedList<T> list) { } I've been playing with it for a few hours with no result. How would I go about doing this if I already can insert single nodes? A: I think you can simply do public void add(int position, final LinkedList<T> list) { for(int i = 0; i < list.size(); i++) { add(position++, list.get(i)); } }
[ "stackoverflow", "0045563074.txt" ]
Q: Passing string variable in Javascript I'm dynamically creating a button. I can pass a variable with a numerical value (1) but I can't pass a string variable. Why? function test(test1) { alert(test1); } document.write("<input type='button' value='' id=j onclick='test(1)'/>"); A: Sure you can. You just need to add quotes. function test(test1) { console.log(typeof test1); } document.write("<input type='button' value='Click' id='j' onclick='test(\"abc\")'/>");
[ "stackoverflow", "0043889806.txt" ]
Q: Large XML Files in VS 2017 15.1 I am being told to ... 'sms-20170225122824.xml' is too large to open with XML editor. The maximum file size is '10' MB. Please update the registry key 'HKCU\Software\Microsoft\VisualStudio\15.0_65fa8ce7_Config\XmlEditor\MaxFileSizeSupportedByLanguageService' to change the maximum size. Not only does the key 15.0_65fa8ce7_Config not exist, so I created it manually (plus the sub-keys) but what type is MaxFileSizeSupportedByLanguageService? And why doesn't it exist already? A: Here is a small powershell to do the job for all users $vsWherePath = Join-Path ${env:ProgramFiles(x86)} "Microsoft Visual Studio\Installer\vswhere.exe" $installPath = &$vsWherePath -all -latest -property installationPath $vsregedit = Join-Path $installPath 'Common7\IDE\vsregedit.exe' & $VsRegEdit set "$installPath" "HKLM" "XmlEditor" "MaxFileSizeSupportedByLanguageService" string 100 If there are already settings in the users hive you can either delete them or set the value at user level - which also does not require admin privileges: $vsWherePath = Join-Path ${env:ProgramFiles(x86)} "Microsoft Visual Studio\Installer\vswhere.exe" $installPath = &$vsWherePath -all -latest -property installationPath $vsregedit = Join-Path $installPath 'Common7\IDE\vsregedit.exe' & $VsRegEdit set "$installPath" "HKCU" "XmlEditor" "MaxFileSizeSupportedByLanguageService" string 100 A: In Visual Studio 2015, you could find the registry key MaxFileSizeSupportedByLanguageService in 14.0_Config\XmlEditor of type string (REG_SZ). Not sure if this will work with VS 2017 though. According to Microsoft doc: "To deliver on a low-impact install of Visual Studio that also supports side-by-side installs, we no longer save most configuration data to the system registry..." (source) Edit: have a look at this answer on how to update the registry settings for Visual Studio 2017: https://stackoverflow.com/a/42871072/107675
[ "stackoverflow", "0018262736.txt" ]
Q: ARM/Thumb interworking in assembly I'm building a Windows Phone project with some bits of it in assembly. My assembly file is in ARM mode (CODE32), and it tries to jump to a C function that I know is compiled to Thumb. The code goes like this: ldr r12, [pFunc] mov pc, r12 pFunc dcd My_C_Function Here's the weird thing. The value at pFunc in the snippet is a pointer at a function thunk plus one. That is, the 0th bit is set, as if the jump target is meant to be Thumb and the jump instruction is meant to be BX. But the thunk is clearly ARM! The thunk loads the address of the function body plus one and executes a BX to it, properly switching modes. Trying to BX to that address would probably crash, because that would switch modes and trying to execute ARM code in Thumb mode is not a good idea. Trying to simply jump to that address (as the current code does) would probably crash too, because PC would end up unaligned. I could, in theory, manually clean up the 0th bit and then jump, but there's gotta be some error to my thinking. The thunk is generated by the C compiler - right? The C compiler knows that the thunk is ARM code. The address under pFunc is generated by the linker, since it's a cross-module call. So the low bit is placed there by the linker; why doesn't the linker know that those thunks are ARM? Any explanation, please? I don't have a WP8 device now, so I can't try it in real hardware. Staring hard at the generated code is the only debugging technique that I have :( EDIT: but what if those thunks are not ARM, but Thumb-2? Thumb-2 supports some 32-bit command IIRC. Is their encoding the same as in ARM mode? How does Thumb-2 decode commands, anyway? A: The details you want are specified in section "A2.3.2 Pseudocode details of operations on ARM core registers" of "ARM Architecture Reference Manual, ARMv7-A and ARMv7-R edition". Here is the relevant pseudocode (from the above manual) about writes to PC register: BXWritePC(bits(32) address) if CurrentInstrSet() == InstrSet_ThumbEE then if address<0> == '1' then BranchTo(address<31:1>:'0'); // Remaining in ThumbEE state else UNPREDICTABLE; else if address<0> == '1' then SelectInstrSet(InstrSet_Thumb); BranchTo(address<31:1>:'0'); elsif address<1> == '0' then SelectInstrSet(InstrSet_ARM); BranchTo(address); else // address<1:0> == '10' UNPREDICTABLE; If the low bit of the address (bit 0) is set, the processor will clear this bit, switch to Thumb mode, and perform a jump to the new address. This behaviour is correct for ARMv7 and later (i.e. applies to all Windows Phone devices, but not all Android/iOS devices). A: The disassembler (IDA Demo, specifically) misled me by uniting several commands into one line. It made a single mov line out of a mov-orr-orr sequence that was meant to assign a full 32-bit constant to a register. The thunks were Thumb after all. The linker works as designed. IDA is otherwise great. I knew in the back of my mind about this particular behavior regarding ARM, but this time it slipped. My bad, thanks and upvotes to everyone who tried to help.
[ "stackoverflow", "0004884216.txt" ]
Q: android capture pictures form camera do you know how to capture a picture form camera with a fixed resolution (ex: 400/400) without writing the picture to a file on sdcard and then loading it again? and after I have the image, how to put it in a textview? I've tried with editText.setCompoundDrawables but this is not a solution for me. I want image in upper left corner, not on top. Thanks A: Check out this tutorial: http://www.softwarepassion.com/android-series-taking-photos-with-andorid-built-in-camera/
[ "stackoverflow", "0005299582.txt" ]
Q: How to do form validation in drupal? How I validate form fields? For example, I want to ensure that two text boxes have the same value. A: Implements the hook_form_alter() to add a validation callback (throught the #validate) argument. In this callback you will have at your disposal the two values of the fields, you will simply have to had a statement to check the values and display an error message if the statement is not good. Example: function mymodule_form_alter(&$form, &$form_state, $form_id) { if ($form_id == 'myform') { $form['#validate'][] = 'myvalidation_function'; } } function myvalidation_function($form, &$form_state) { if ($form_state['values']['field_a'] != $form_state['values']['field_b']) { form_error('field_a', t('Field A and B must have the same values')); } }
[ "math.stackexchange", "0003478419.txt" ]
Q: Find the total number of 7-digit Find the total number of 7-digit natural numbers whose digits sum is 20. Solution: This is not a exactly answer, as well we can use a way to subtracts the cases when exists a digit greater than $9$. Let $x_1,\cdots, x_7$ the digits. As well there are ${25\choose 6}$ ways to give us the sums of numbers, but this permits $x_i>9$. We need to analyze a few cases (or you can abbreviate this if you're awesomely intellectual, I'm not). $Case~1)$ All the cases (ways) where $x_1>9$ and the others are less than or equal to $9$. Then you need to write $x_1=9+x_1'$. And why is this a particular case? Because Stars and Bars here admits numbers equal to zero, and in this ways $0$ is permitted. But see that this case counts ways that is not permitted by our hypothesis, is when$ (x_1,x_i,x_j,\cdots, x_{j+3})=(10,10,0,\cdots,0) $ To calculate the ways it's easy only have that $x_1'+x_2+\cdots +x_7= 11$ Then clearly all the ways are ${16\choose 6} - 6$ $Case~2)$ Some $x_i\neq x_1$ is greater than $9$. This is only ${15\choose 6} $ but for individual digits, then all the ways are $6 {15\choose 6} $ This give us that the quantity of numbers such that the sum of digits is $20$ are: $${25\choose 6}-\left({16\choose 6}+6 {15\choose 6}-6\right) $$ Correct A: We count the number of integers $x$ with $1\,000\,000\leq x\leq 9\,999\,999$ which have a digit sum equal to $20$ with the help of generating functions. It is convenient to use the coefficient of operator $[x^{n}]$ to denote the coefficient of $x^n$ in a series. We obtain \begin{align*} \color{blue}{[x^{20}]}&\color{blue}{\left(1+x+x^2+\cdots+x^9\right)^7-[x^{20}]\left(1+x+x^2+\cdots+x^9\right)^6}\tag{1}\\ &=[x^{20}]\left(\frac{1-x^{10}}{1-x}\right)^7-[x^{20}]\left(\frac{1-x^{10}}{1-x}\right)^6\tag{2}\\ &=[x^{20}]\left(1-7x^{10}+\binom{7}{2}x^{20}\right)\sum_{j=0}^\infty\binom{-7}{j}(-x)^j\\ &\qquad-[x^{20}]\left(1-6x^{10}+\binom{6}{2}x^{20}\right)\sum_{j=0}^\infty\binom{-6}{j}(-x)^j\tag{3}\\ &=\left([x^{20}]-7[x^{10}]+21[x^0]\right)\sum_{j=0}^\infty\binom{j+6}{6}x^j\\ &\qquad-\left([x^{20}]-6[x^{10}]+15[x^0]\right)\sum_{j=0}^\infty\binom{j+5}{5}x^j\tag{4}\\ &=\left(\binom{26}{6}-7\binom{16}{6}+21\binom{6}{6}\right)-\left(\binom{25}{5}-6\binom{15}{5}+15\binom{5}{5}\right)\tag{5}\\ &=\left(230\,230-56\,056+21\right)-\left(53\,130-18\,018+15\right)\\ &=174\,195-35\,127\\ &\,\,\color{blue}{=139\,068} \end{align*} Comment: In (1) we count the strings with length $7$ consisting of digits from $0$ to $9$ with digit-sum $20$. Since numbers do not start with a leading zero, we subtract all strings of length $6$ with digit-sum $20$. In (2) we use the finite geometric series formula. In (3) we expand the numerator omitting terms which do not contribute to $[x^{20}]$ and we use the binomial series expansion. In (4) we apply the rule $[x^{p-q}]A(x)=[x^p]x^qA(x)$ and we use the binomial identity $\binom{-p}{q}=\binom{p+q-1}{p-1}(-1)^q$. In (5) we select the coefficients accordingly.
[ "stackoverflow", "0012663491.txt" ]
Q: ref vs depends-on attributes in Spring I am confused between ref and depends-on attribute in Spring.I read the spring doc but I am still confused.I wish to know the exact difference between the two and in which case which one shall be used. A: From the official documentation: http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/context/annotation/DependsOn.html Beans on which the current bean depends. Any beans specified are guaranteed to be created by the container before this bean. Used infrequently in cases where a bean does not explicitly depend on another through properties or constructor arguments, but rather depends on the side effects of another bean's initialisation. A: Perhaps an example of a situation where depends-on is needed would help. I use Spring to load and wire my beans. Here is an example bean definition: <bean id="myBean" class="my.package.Class"> <property name="destination" value="bean:otherBeanId?method=doSomething"/> </bean> <bean id="otherBeanId" class="my.package.OtherClass"/> Notice that the property value is a string, which references otherBeanId. Because of the way this variable is resolved, Spring doesn't learn of the dependency, so it may destroy otherBeanId then myBean. This may leave myBean in a broken state for a little while. I can use depends on to fix this problem as follows: <bean id="myBean" class="my.package.Class" depends-on="otherBeanId"> <property name="destination" value="bean:otherBeanId?method=doSomething"/> </bean>
[ "movies.stackexchange", "0000034637.txt" ]
Q: How did Hank know about the bullet holes before removing the duct tape? This question was never answered in Breaking Bad. Hank spent a lot of time (nearly 2 episodes) looking for an RV. And when he sees it in the junk yard for the first time, he knew in advance that the door has bullet holes covered with duct tape. When Jessie asks him: How did you know these were bullet holes before removing the duct tape? Hank never answers. How did Hank know, and why didn't he answer the question? A: Hank … knew in advance that the door has bullet holes covered with duct tape. I vaguely remember thinking: Looks like a bullet pattern from when a gun was fired from immediately outside or inside the door - probably inside given the height of the pieces of tape. Hank could plainly see that the tape was there. Given the pattern of pieces of tape and his suspicions of what the RV had been used for (making extremely valuable illicit drugs), a 'pattern of bullet holes' would be near the top of his mind. As to why Hank did not answer - he knew they 'had him', in the sense that he did not have Probable Cause to suspect a crime (as opposed to suspicions and hunches) and therefore no authority to remove the pieces of tape. It would have been tainted evidence that the court would not accept, and more importantly, would have resulted in all evidence from the RV to be dismissed.. The reason cops do things like Hank did when he removed the tape, is that they are hoping to trick or panic the suspect into making a confession or revealing something that can be used as evidence. Then they 'fail to make a record' of the illegal part of what they did .. & hope that it does not come up in court. Alternately they might fib and claim that the tape was already partially peeled off when they saw the hole. In Hank's case, he had the (very legally savvy, and not shy) junk yard owner who had witnessed him removing the tape. I think it was already established by then that the owner was not only clever, but also unafraid of challenging police officers. After he was challenged by Jessie as well, Hank realized he would not get away with the usual tricks.
[ "travel.stackexchange", "0000051973.txt" ]
Q: Renting a car - Slovakia I'm planning to rent a car within 4 friends in Poland and drive down to Slovakia, I read that I've to buy one sticker to drive on highways. Is this still applies? How can I get them? A: You don't need any stickers in Poland, but you do need them in Slovakia, you can buy them at gas stations in SK. http://www.slovakia.com/travel/car/
[ "stackoverflow", "0035402632.txt" ]
Q: How to setup Log4j2 for an application deployed in WildFly 9? When I test my application with JUnit, it is printing the log as specified by layout pattern in log4j2.xml, but when I deploy my application in WildFly 9, I am no more getting the same format. Even the log level in Log4j2 is also not reflecting while deployed in server. JUnit log example: 2016-02-15 11:14:16,314 DEBUG [main] b.t.r.c.XAPool - a connection's state changed to IN_POOL, notifying a thread eventually waiting for a connection Server log example: 11:11:33,796 INFO [org.quartz.core.QuartzScheduler] (ServerService Thread Pool -- 89) Scheduler quartzScheduler_$_anindya-ubuntu1455514892022 started. Log4j2.xml: <Configuration status="WARN" name="myapp" monitorInterval="5"> <Appenders> <RollingFile name="RollingFile" fileName="${myapp.log-dir}/myapp.log" filePattern="${myapp.log-dir}/$${date:yyyy-MM}/myapp-%d{MM-dd-yyyy}-%i.log"> <PatternLayout> <Pattern>%d %p %c{1.} [%t] %m%n</Pattern> </PatternLayout> <Policies> <OnStartupTriggeringPolicy /> <SizeBasedTriggeringPolicy size="25 MB"/> </Policies> <DefaultRolloverStrategy max="100"> <Delete basePath="${myapp.log-dir}" maxDepth="2"> <IfFileName glob="*/myapp-*.log"> <IfLastModified age="7d"> <IfAny> <IfAccumulatedFileSize exceeds="1 GB" /> <IfAccumulatedFileCount exceeds="1" /> </IfAny> </IfLastModified> </IfFileName> </Delete> </DefaultRolloverStrategy> </RollingFile> </Appenders> <Loggers> <Logger name="com.company.myapp" level="trace" additivity="false"> <AppenderRef ref="RollingFile"/> </Logger> <Root level="info"> <AppenderRef ref="RollingFile"/> </Root> </Loggers> </Configuration> While starting the server, I am providing below starup properties as JAVA_OPTS: export JAVA_OPTS="$JAVA_OPTS -Dspring.profiles.active='qa' -Dlog4j.configurationFile=/home/anindya/1.0/log4j2.xml -myapp.log-dir=/home/anindya/log -Dorg.jboss.logging.provider=log4j" I have no specific setup in web.xml as it is Servlet 3.1 container. But I have a jboss-deployment-structure.xml in my WEB-INF as below: <jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.2"> <deployment> <!-- Exclusions allow you to prevent the server from automatically adding some dependencies --> <exclusions> <module name="org.apache.logging.log4j" /> </exclusions> </deployment> </jboss-deployment-structure> And finally, here are my classpath dependencies (only the relevant parts are mentioned here): hibernate-5.0.7.Final dependencies jbpm-6.3.0.Final dependencies spring-4.2.4.RELEASE dependencies commons-logging-1.2.jar log4j-1.2-api-2.5.jar log4j-api-2.5.jar log4j-core-2.5.jar log4j-jcl-2.5.jar log4j-slf4j-impl-2.5.jar log4j-web-2.5.jar jboss-logging-3.3.0.Final.jar With all of the above setup, I am still not able to configure Log4j2 in WildFly environment according to my log4j2.xml. Can someone please help? NOTE: I am running WildFly in standalone mode and I would like to avoid using jboss-cli. A: I managed to get it working by using the below jboss-deployment-structure.xml. <jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.2"> <deployment> <exclusions> <module name="org.apache.logging.log4j" /> </exclusions> <exclude-subsystems> <subsystem name="logging"/> </exclude-subsystems> </deployment> </jboss-deployment-structure> All I had to do is to exclude the logging subsystem. A: Late to the game but I needed support for log4j2 in Wildfly and thought I would share some details for anyone else facing this. This solution will let you configure logging through standalone.xml, that is no log4j2.xml will be used/picked up. The solution I chose is to bridge log4j2 to slf4j. Wildfly supports slf4j out-of-the-box. For the advanced users the solution in one sentence is 'Create a Wildfly module and use it', for others like me the solution follows a bit more detailed below... First create a wildfly module, I will not give all the details how this is done, but my module.xml ended up looking like this <module xmlns="urn:jboss:module:1.1" name="org.apache.logging.log4j2"> <resources> <resource-root path="log4j-api-2.11.1.jar"/> <resource-root path="log4j-to-slf4j-2.11.1.jar"/> </resources> <dependencies> <module name="org.slf4j" /> </dependencies> </module> (Basically make sure this xml is in your module path, typically you would add it at $JBOSS_MODULEPATH/org/apache/logging/log4j2/main/module.xml, and add the referenced jar-files in the same directly as well) Next step is to add a dependency to this module from my application. This is accomplished using a jboss-deployment-structure.xml. If you are not familiar with this file please look it up. Add a line like this <module name="org.apache.logging.log4j2" export="true" /> You might also need to exclude log4j-api-2.11.1.jar from your application deployment, I am not 100% sure it is needed but I always do when I create a module. After this you should be able to see log4j2 messages in your server.log I hope this can help someone out there!
[ "stackoverflow", "0037590762.txt" ]
Q: Resize ImageView with only one finger movement instead of two I'm trying to change an ImageView's height with only one finger movement (upside or downside). The code below changes height with two fingers (like pinching or reverse). How can I modify this code to do what I want? Thanks. public class MainActivity extends Activity { private ImageView iv; private Matrix matrix = new Matrix(); private float scale = 1f; private ScaleGestureDetector SGD; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); iv = iv=(ImageView)findViewById(R.id.imageView); SGD = new ScaleGestureDetector(this, new ScaleListener()); } public boolean onTouchEvent(MotionEvent ev) { SGD.onTouchEvent(ev); return true; } private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { @Override public boolean onScale(ScaleGestureDetector detector) { scale *= detector.getScaleFactor(); scale = Math.max(0.1f, Math.min(scale, 5.0f)); matrix.setScale(1, scale); iv.setImageMatrix(matrix); return true; } } } A: Use GestureDetector for scroll: @Bind(R.id.container) ViewGroup container; @Bind(R.id.image) ImageView image; private GestureDetectorCompat detector; private float yscale = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); ButterKnife.bind(this); image.setScaleType(ImageView.ScaleType.MATRIX); detector = new GestureDetectorCompat(this, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { Matrix m = new Matrix(); yscale += distanceY / container.getHeight(); m.setScale(1, yscale, 0, 0); image.setImageMatrix(m); return true; } }); } @Override public boolean onTouchEvent(MotionEvent event) { return detector.onTouchEvent(event); } detector.onTouchEvent(event); }
[ "stackoverflow", "0049419603.txt" ]
Q: Beginner Budget Program Error In Python I am in the process of creating a basic budget program in Python 3. It needs to create a series of three people and give them a salary, 2 expenses, and their left over cash at the end of the week. You will also be comparing their left over expenses to an amount of money they need to save every week. I believe I have it all finished except for this problem whenever I run the program, I get the following message: Traceback (most recent call last): File "/Users/----/Desktop/BudgetProgramTest.py", line 42, in personOneLeftOver = personOneSalary - personOneExpenses TypeError: unsupported operand type(s) for -: 'str' and 'tuple' How can I solve this error? What would be the correct way to code this? It would be easier to understand with the original code for my program: <prev> # Ask for each person's name personOne = input("What is your name?") personTwo = input("What is your name?") personThree = input("What is your name?") # Ask for each person's weekly salary personOneSalary = input("What is your weekly salary?") personTwoSalary = input("What is your weekly salary?") personThreeSalary = input("What is your weekly salary?") # Ask for personOne's expenditures personOneGas = input("How much do you spend on gas per week?") personOneGroc = input("How much do you spend on groceries per week?") personOneFast = input("How much do you spend on fast food per week?") personOneHob = input("How much do you spend on hobbies per week?") personOneExpenses = personOneGas, personOneGroc, personOneFast, personOneHob # Ask for personTwo's expenditures personTwoGas = input("How much do you spend on gas per week?") personTwoGroc = input("How much do you spend on groceries per week?") personTwoFast = input("How much do you spend on fast food per week?") personTwoHob = input("How much do you spend on hobbies per week?") personTwoExpenses = personTwoGas, personTwoGroc, personTwoFast, personTwoHob # Ask for personThree's expenditures personThreeGas = input("How much do you spend on gas per week?") personThreeGroc = input("How much do you spend on groceries per week?") personThreeFast = input("How much do you spend on fast food per week?") personThreeHob = input("How much do you spend on hobbies per week?") personThreeExpenses = personThreeGas, personThreeGroc, personThreeFast, personThreeHob # Set each person's left over money by subracting expenses from each person's weekly salary personOneLeftOver = personOneSalary - personOneExpenses personTwoLeftOver = personTwoSalary - personTwoExpenses personThreeLeftOver = personThreeSalary - personTwoExpenses # Set each person's goal to save each week (to compare in the future) personOneSavesGoal = personOneLeftOver * .10 peraonTwoSavesGoal = personTwoLeftOver * .10 personThreeSavesGoal = personThreeLeftOver * 10 # See if personOne has met their goal of saving 10% after expenses if PersonOneLeftOver >= personOneSavesGoal: print("Congratulations, you are on your way to financial freedom!") else: print(personOne, " needs to save more money.") # See if personTwo has met their goal of saving 10% after expenses if PersonTwoLeftOver >= personTwoSavesGoal: print("Congratulations, you are on your way to financial freedom!") else: print(personTwo, " needs to save more money.") # See if personThree has met their goal of saving 10% after expenses if PersonThreeLeftOver >= personThreeSavesGoal: print("Congratulations, you are on your way to financial freedom!") else: print(personThree, " needs to save more money.") # Display each person's name, weekly salary, expensive, weekly salary after expenses, and amount of moneuy needed to save print(personOne, "your weekly salary is: ", personOneSalary, " and your expenses are: ", personOneExpenses, ".") print("Your weekly salary is ", personOneLeftOver, " after your expenses. You need to save", personOneSavesGoal, ".") print(personTwo, "your weekly salary is: ", personTwosalary, " and your expenses are: ", personTwoExpenses, ".") print("Your weekly salary is ", personTwoLeftOver, " after your expenses. You need to save", personTwoSavesGoal, ".") print(personThree, "your weekly salary is: ", personThreeSalary, " and your expenses are: ", personThreeExpenses, ".") print("Your weekly salary is ", personThreeLeftOver, " after your expenses. You need to save", personThreeSavesGoal, ".") <prev> A: There are some errors on your code. 1 - input always return a string, therefore all the places which you need a number you must update to int(input(...)); Eg: personTwoGas = int(input("How much do you spend on gas per week?")) 2 - Whenever you sum a tuple or a list, you must use the sum(). Eg: personOneLeftOver = float(personOneSalary) - sum(personOneExpenses) Most likely there are more errors, just pointed those which might stop you from developing this task.
[ "stackoverflow", "0034680018.txt" ]
Q: Laravel 5: Insert (nested) array data from form in mysql db (convert syntax from mysqli) I am having problems converting existing mysqli syntax to Laravel suitable format. I am happy to make use of raw queries as long as it works. I have this mysqli syntax (which works - but not in Laravel obviously): $outID = array_map($mysqli_escape, $_POST['outcomeid']); $chID = array_map($mysqli_escape, $_POST['ChallengeRandom']); $pts = array_map($mysqli_escape, $_POST['PropOutcomePts']); $userID = array_map($mysqli_escape, $_POST['username']); $timestamp = array_map($mysqli_escape, $_POST['ctime']); $prID = array_map($mysqli_escape, $_POST['PropId']); $crID = array_map($mysqli_escape, $_POST['CrushId']); for($i=0;$i<count($outID);$i++) { $ins1 = 'INSERT INTO challenge_input (PropOutcomeId, ChallengeId, ChallengeUserId, InputTime, PropOutcomePts, PropId, CrushId) VALUES (\''.$outID[$i].'\', \''.$chID[$i].'\', \''.$userID[$i].'\', \''.$timestamp[$i].'\', \''.$pts[$i].'\', \''.$prID[$i].'\', \''.$crID[$i].'\')'; $query = mysqli_query($con,$ins1) or die(mysqli_error($con)); } The form output from the previous page looks like this (context: the form contains five questions, each with four answer options (which have outcomeid and outcomepts). Only if an outcomeid is checked - i.e., the answer that is chosen by the user - is an outcomeid passed in the form.): Crushtime[]:2016-01-28 16:00:00 PropId[]:35 CrushId[]:13 username[]:16 ctime[]:2016-01-08 15:55:28 ChallengeRandom[]:db167049-b617-11e5-a outcomeid[]:45 PropOutcomePts[]:200 PropOutcomePts[]:100 PropOutcomePts[]:100 PropOutcomePts[]:200 PropId[]:36 CrushId[]:13 username[]:16 ctime[]:2016-01-08 15:55:28 ChallengeRandom[]:db167049-b617-11e5-a PropOutcomePts[]:100 PropOutcomePts[]:100 PropOutcomePts[]:50 outcomeid[]:52 PropOutcomePts[]:200 PropId[]:38 CrushId[]:13 username[]:16 ctime[]:2016-01-08 15:55:28 ChallengeRandom[]:db167049-b617-11e5-a PropOutcomePts[]:100 outcomeid[]:54 PropOutcomePts[]:50 PropOutcomePts[]:100 PropOutcomePts[]:150 PropId[]:39 CrushId[]:13 username[]:16 ctime[]:2016-01-08 15:55:28 ChallengeRandom[]:db167049-b617-11e5-a PropOutcomePts[]:100 PropOutcomePts[]:50 outcomeid[]:59 PropOutcomePts[]:100 PropOutcomePts[]:150 PropId[]:40 CrushId[]:13 username[]:16 ctime[]:2016-01-08 15:55:28 ChallengeRandom[]:db167049-b617-11e5-a PropOutcomePts[]:200 PropOutcomePts[]:100 PropOutcomePts[]:50 outcomeid[]:64 PropOutcomePts[]:100 Code from comment foreach ($outID as $key => $n) { DB::insert('INSERT INTO challenge_input (PropOutcomeId, ChallengeId, ChallengeUserId, InputTime, PropOutcomePts, PropId, CrushId) VALUES (?,?,?,?,?,?,?)', array('outID' => $outID[$key], 'chID' => $chID[$key], 'userID' => $userID[$key], 'timestamp' => $timestamp[$key], 'pts' => $pts[$key], 'prID' => $prID[$key], 'crID' => $crID[$key])); } A: The keys for the array must match the column names: foreach ($outID as $key => $n) { DB::table('challenge_input')->insert(array('PropOutcomeId' => $outID[$key], 'ChallengeId' => $chID[$key], 'ChallengeUserId' => $userID[$key], 'InputTime' => $timestamp[$key], 'PropOutcomePts' => $pts[$key], 'PropId' => $prID[$key], 'CrushId' => $crID[$key])); }
[ "stackoverflow", "0061980277.txt" ]
Q: Homebrew python version different than Mac python version? I've searched a while and haven't found an answer to this particular issue. brew info python returns python: stable 3.7.7 (bottled), HEAD However, python -V and python3 -V return Python 3.6.1 :: Anaconda 4.4.0 (x86_64) Why is my Mac python version different than what I've installed with HB, and how can I fix it? Thank you! A: One version of python was installed using the Anaconda distribution. The other by Homebrew. It's not surprising that they are different versions. You should run in virtual environments and then you won't need to worry about 2 versions. Using the Anaconda distribution it is easy to set up a virtual environment to run that version.
[ "stackoverflow", "0043997546.txt" ]
Q: C++ Saving 2-dimensional database into file ISSUE I'm writing a small console app (name it student evidention), which has couple of functions, i.e it allows user to export database into text file. The problem which occurs during this process is that program actually saves only the first record of mentioned database. void saveDataToFile() { // ZAPISZ BAZĘ DANYCH DO PLIKU - ISTNIEJE PROBLEM Z OKREŚLENIEM ŚCIEŻKI ZAPISU ORAZ ZAPISYWANIEM JEDYNIE PIERWSZEGO REKORDU Z BAZY string fileName; ofstream fileTemp; cout << "Podaj nazwę pliku: "; cin >> fileName; fileTemp.open(fileName); fileTemp << "+--------------------------------------------------------------------------------------------------------+" << endl; fileTemp << "|\tImię\t|\tNazwisko\t|\tNr PESEL\t|\t Telefon\t|\tMail\t |" << endl << "+--------------------------------------------------------------------------------------------------------+" << endl; for (row; row < 20; row++) { for (col; col < 5; col++) { if (col == 0) { fileTemp << "\t" << studentDb[row][col] << "\t"; } else { fileTemp << studentDb[row][col] << "\t"; } } fileTemp << endl; } fileTemp.close(); } I have no idea what's wrong with that code, because the loop itself seems to be completely fine... I'd be glad for any tips for resolving this issue. Ignore lines written in polish - it has only some cosmetic, text-formatting functions in the program. EDIT. The way I create a new record: void createNewRecord() { // UTWÓRZ NOWY REKORD W BAZIE string *pNewRecord; pNewRecord = &studentDb[recordCounter][0]; cout << "Imię: "; cin >> *pNewRecord; pNewRecord = &studentDb[recordCounter][1]; cout << "Nazwisko: "; cin >> *pNewRecord; pNewRecord = &studentDb[recordCounter][2]; cout << "Numer PESEL: "; cin >> *pNewRecord; pNewRecord = &studentDb[recordCounter][3]; cout << "Numer telefonu: "; cin >> *pNewRecord; pNewRecord = &studentDb[recordCounter][4]; cout << "Adres e-mail: "; cin >> *pNewRecord; recordCounter++; cout << endl << "Nowy rekord został pomyślnie dodany do bazy." << endl; cout << "Czy chcesz kontynuować? (t/n): "; cin >> response; cout << endl; if (response == 't' || response == 'T') { cout << "Kontynuujesz dodawanie do bazy." << endl << endl; createNewRecord(); } else if (response == 'n' || response == 'N') { Sleep(1000); system("cls"); void displayMenuWindow(); } } A: Set the 'row' and 'col' variables to zero in the initializer portion of the 'for' loops. And make them local variables too (declare them as "int row=0").
[ "graphicdesign.stackexchange", "0000042313.txt" ]
Q: PharmGKB diagrams; how do I convert them into customizable svgs? I'd like to be able to convert this pathway (1) to SVG in a way that I can then edit (e.g., adding a legend to the diagram and edit some of the hyperlinks in the diagram). I have tried saving it as PNG (e.g., by right-clicking the pathway [in Chrome] and clicking, "Save image as...") and then using Inkscape to save this as a SVG. Any ideas? A: There's a link to a PDF version of the pathway in the right-hand sidebar. It looks like the diagram is embedded as a vector graphic in the PDF file, so you should be able to convert it to SVG or open it with Inkscape.
[ "stackoverflow", "0056989720.txt" ]
Q: Upload an image file takes too long on AWS S3 c++ SDK Using AWS S3 C++ SDK for uploading .jpg images to a certain IAM user introduce huge time delays that in any case are caused due to network traffic and latency issues. I am using free-tier S3 version and MSVC 2017 64bit for my application (on Windows 10 PC). Here is a sample code: Aws::SDKOptions options; Aws::InitAPI(options); Aws::Client::ClientConfiguration config; config.region = Aws::Region::US_EAST_2; Aws::S3::S3Client s3_client(Aws::Auth::AWSCredentials(KEY,ACCESS_KEY), config); const Aws::String bucket_name = BUCKET; const Aws::String object_name = "image.jpg"; Aws::S3::Model::PutObjectRequest put_object_request; put_object_request.SetBucket(bucket_name); put_object_request.SetKey(object_name); std::shared_ptr<Aws::IOStream> input_data = Aws::MakeShared<Aws::FStream>("PutObjectInputStream", "../image.jpg", std::ios_base::in | std::ios::binary); put_object_request.SetBody(input_data); put_object_request.SetContentType("image/jpeg"); input_data->seekg(0LL, input_data->end); put_object_request.SetContentLength(static_cast<long>(input_data->tellg())); auto put_object_outcome = s3_client.PutObject(put_object_request); When I upload images bigger than 100KB the total PutObject(put_object_request); time of execution exceeds 2min for a 520KB image. I have tried the same example using Python boto3 and the total upload time for the same image is around 25s. Have anyone faced the same issue? A: After a better look to AWS github repo I figure out the issue. The problem was that WinHttpSyncHttpClient was making timouts and reset upload activity internally thus not exiting the upload thread and finally aborting the transaction. By adding a custom timeout value the problem solved. I used multipart Upload to re-implement the example as it seems more robust and manageable. Although I thought that it is unavailable for C++ SDK, its not the case as the TransferManager does the same job for C++ (not by using S3 headers as Java, .NET and PHP does). Thanks KaibaLopez and SCalwas from AWS github repo who help me solve the issues (issue1, issue2). I am pasting an example code is case anyone face the same issue: #include "pch.h" #include <iostream> #include <fstream> #include <filesystem> #include <aws/core/Aws.h> #include <aws/core/auth/AWSCredentials.h> #include <aws/s3/S3Client.h> #include <aws/s3/model/Bucket.h> #include <aws/transfer/TransferManager.h> #include <aws/transfer/TransferHandle.h> static const char* KEY = "KEY"; static const char* BUCKET = "BUCKET_NAME"; static const char* ACCESS_KEY = "AKEY"; static const char* OBJ_NAME = "img.jpg"; static const char* const ALLOCATION_TAG = "S3_SINGLE_OBJ_TEST"; int main() { Aws::SDKOptions options; Aws::InitAPI(options); { Aws::Client::ClientConfiguration config; config.region = Aws::Region::US_EAST_2; config.requestTimeoutMs = 20000; auto s3_client = std::make_shared<Aws::S3::S3Client>(Aws::Auth::AWSCredentials(KEY, ACCESS_KEY), config); const Aws::String bucket_name = BUCKET; const Aws::String object_name = OBJ_NAME; const Aws::String key_name = OBJ_NAME; auto s3_client_executor = Aws::MakeShared<Aws::Utils::Threading::DefaultExecutor>(ALLOCATION_TAG); Aws::Transfer::TransferManagerConfiguration trConfig(s3_client_executor.get()); trConfig.s3Client = s3_client; trConfig.uploadProgressCallback = [](const Aws::Transfer::TransferManager*, const std::shared_ptr<const Aws::Transfer::TransferHandle>&transferHandle) { std::cout << "Upload Progress: " << transferHandle->GetBytesTransferred() << " of " << transferHandle->GetBytesTotalSize() << " bytes" << std::endl;}; std::cout << "File start upload" << std::endl; auto tranfer_manager = Aws::Transfer::TransferManager::Create(trConfig); auto transferHandle = tranfer_manager->UploadFile(object_name.c_str(), bucket_name.c_str(), key_name.c_str(), "multipart/form-data", Aws::Map<Aws::String, Aws::String>()); transferHandle->WaitUntilFinished(); if(transferHandle->GetStatus() == Aws::Transfer::TransferStatus::COMPLETED) std::cout << "File up" << std::endl; else std::cout << "Error uploading: " << transferHandle->GetLastError() << std::endl; } Aws::ShutdownAPI(options); return 0; }
[ "stackoverflow", "0023606082.txt" ]
Q: Why is the sprite generated different sizes in iPhone 5 and iPad retina? I was following these tutorial: http://www.raywenderlich.com/32954/how-to-create-a-game-like-tiny-wings-with-cocos2d-2-x-part-1 The hill texture is generated by passing vertices and texture coordinates to the draw method of the CCNode representing the terrain. The hills look fine on my iPod touch, and my iPhone. But when I view them in the iPad retina display, the hills seem smaller (as if the calculation was for a smaller display), and the alignment is incorrect. Instead of being drawn from y = 0 , they are drawn from slightly above the bottom of the screen (as if the hills are floating). Is there some kind of error in the calculation ? How to fix it ? EDIT: On my iPhone / iPod, the hills are so large that only two hills are on screen at a time. But on my iPad retina, there are 4 hills on screen at a time. So there is some kind of device dependent calculation. A: But when I view them in the iPad retina display, the hills seem smaller (as if the calculation was for a smaller display), That's indeed what happens. In High-DPI mode the OS reports a smaller physical display resolution so that applications using the Cocos2D API can use the same pixel distances and positions as on non-Retina displays. Cocos2D then internally scales everything appropriately. For OpenGL this fails, of course. Here's a tutorial on how to deal with the subject: http://www.david-amador.com/2010/09/setting-opengl-view-for-iphone-4-retina-hi-resolution/ The relevant code is this: int w = 320; int h = 480; float ver = [[[UIDevice currentDevice] systemVersion] floatValue]; // You can't detect screen resolutions in pre 3.2 devices, but they are all 320x480 if (ver >= 3.2f) { UIScreen* mainscr = [UIScreen mainScreen]; w = mainscr.currentMode.size.width; h = mainscr.currentMode.size.height; } if (w == 640 && h == 960) // Retina display detected { // Set contentScale Factor to 2 self.contentScaleFactor = 2.0; // Also set our glLayer contentScale Factor to 2 CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer; eaglLayer.contentsScale=2; //new line }
[ "stackoverflow", "0004991922.txt" ]
Q: Online Classroom: VSat, Leased line or something else? One of my friends is planning to set up a online classroom sort of environment and currently is evaluating the various ISP/Connection options he can have. Though he certainly needs a 100% up time of the internet connection, it can be compromised to like 99.X% for a good internet speed. Also since he is just starting up, 'price' too is a constraint but quality should not be compromised. VSat link is one of the options that we know that might work out but I am very confused googling on the benifts of a VSat link as compared to a leased line. I feel a 2 MBPS leased line(may be 2) can suffice. What should be the right connection? Any thoughts? A: VSat is going to have a noticeable delay if you're doing anything interactive. It's also prone to weather (heavy storms, snow, can affect the quality of the link). Also, are you in a remote area or a developing country? If you're not, then you should just go with some business DSL line.
[ "drupal.stackexchange", "0000188168.txt" ]
Q: What is the proper way to handle drupal_get_destination and drupal_goto? I am considering the following approach in my controller (the method which corresponds to a given route). $destination = \Drupal::destination()->getAsArray(); if (isset($destination['destination'])) { return new RedirectResponse(Url::fromUri($destination['destination'])); } else { return $this->redirect('acquia_connector.settings'); } Should I use different code to handle both route based and URL based redirects? A: Drupal automatically uses destination, you don't have to do anything. If a destination argument is given, it will override default. So you can simplify your code to a simple, hardcoded $this->redirect(...). The only exception is when you have links that you want to respect destination too (e.g. a cancel link on a confirm form), then you have to do it yourself. But the default confirm form already does that too AFAIK.
[ "gamedev.stackexchange", "0000034265.txt" ]
Q: Converting many faces to single mesh and reduce poly-count in Blender I'm not so familiar with 3D modelling, and I'm stuck on a simple task in Blender. I have a fairly complex model that's been imported as a .DAE file from SketchUp. This model is composed of many polygons, not as one single mesh but in many components, in fact over many hundreds of surfaces. As I said I'm new to Blender and want to learn. If I select one of the component surfaces, I can go into Edit mode and then use the Decimate modifier to reduce the poly-count. But it doesn't want to let me do this if I select the whole object! I think I need to combine all the surfaces into one mesh (?) and then apply the Decimate algorithm to gracefully reduce the poly-count. I've managed to do this before but unfortunately I forgot how and I need to try again to get the balance right on the poly-count. Appreciate the help. Alex A: select 2 or more "components" (in Blender terms, these are separate objects) ([B] will box-select, may be easier than shift-clicking through all the objects) [Ctrl] [J] "Join" I haven't used Blender in a long time. What helped me learn some commands was remembering the name of the command. If you bring up the spacebar menu and type in "Join", it will bring back a list of all the commands containing that word, including their keyboard shortcuts.
[ "stackoverflow", "0034488559.txt" ]
Q: Pointer to array with const qualifier in C & C++ Consider following program: int main() { int array[9]; const int (*p2)[9] = &array; } It compiles fine in C++ (See live demo here) but fails in compilation in C. By default GCC gives following warnings. (See live demo here). prog.c: In function 'main': prog.c:4:26: warning: initialization from incompatible pointer type [enabled by default] const int (*p2)[9] = &array; But If I use -pedantic-errors option: gcc -Os -s -Wall -std=c11 -pedantic-errors -o constptr constptr.c it gives me following compiler error constptr.c:4:26: error: pointers to arrays with different qualifiers are incompatible in ISO C [-Wpedantic] Why it fails in compilation in C but not in C++? What C & C++ standard says about this? If I use const qualifier in array declaration statement it compiles fine in C also. So, what is happening here in above program? A: GCC-gnu In GNU C, pointers to arrays with qualifiers work similar to pointers to other qualified types. For example, a value of type int (*)[5] can be used to initialize a variable of type const int (*)[5]. These types are incompatible in ISO C because the const qualifier is formally attached to the element type of the array and not the array itself. C standard says that (section: §6.7.3/9): If the specification of an array type includes any type qualifiers, the element type is so- qualified, not the array type.[...] Now look at the C++ standard (section § 3.9.3/5): [...] Cv-qualifiers applied to an array type attach to the underlying element type, so the notation “cv T,” where T is an array type, refers to an array whose elements are so-qualified. An array type whose elements are cv-qualified is also considered to have the same cv-qualifications as its elements. [ Example: typedef char CA[5]; typedef const char CC; CC arr1[5] = { 0 }; const CA arr2 = { 0 }; The type of both arr1 and arr2 is “array of 5 const char,” and the array type is considered to be const- qualified. —endexample] Therefore, the initialization const int (*p2)[9] = &array; is assignment of type pointer to array[9] of int to pointer to array[9] of const int. This is not similar to assigning int * to a const int * where const is applied directly to the object type the pointer points to. This is not the case with const int(*)[9] where, in C, const is applied to the elements of the array object instead of the object the pointer points to. This makes the above initialization incompatible. This rule is changed in C++. As const is applied to array object itself, the assignment is between same types pointer to const array[9] of int instead of type pointer to array[9] of int and pointer to array[9] of const int.
[ "diy.stackexchange", "0000111545.txt" ]
Q: Why is water profusely coming out of my shower head when the water is boiling in my water heater? I just got my water heater fixed as previously it wasn't heating up water. When I turned on the water heater later on, at first there was nothing wrong since it takes time for heating element to heat up the water to a hot temp. But once the water started to really get hot in the tank, then water started spurting out profusely, almost as if someone turned the knob to let some water out but not to the full shower 'strength'. It just kept spurting out really hot water until I decided it would be safe to turn off the heater until I figure out whats wrong. I'm guessing theres something wrong with the pressure seal on the shower head? Might it be that the pressure in the water tank is forcing out the hot water as the water begins to get very hot? Also, is it safe for my family to take a shower while its like this? Update: I realize the problem might actually be with the shower head. After inspecting it more closely I noticed its a bit busted up and its not spraying water well. One of my family members must've dropped it on the floor this morning. But I'll get a new shower head soon and we'll see if that fixes the problem. A: I just got my water heater fixed as previously it wasn't boiling water A water heater should not raise the temperature of the water to 100℃ (boiling). You should not have any boiling occurring anywhere inside your household hot-water systems (excluding vessels used for preparation of food or hot drinks such as kettles and saucepans). In my part of the world, a home water heater has a thermostat that determines the maximum temperature of the water, this thermostat cuts off the source of heat when the water reaches the set temperature. Perhaps you have a faulty thermostat, the wrong type of thermostat or one set to an incorrect value? is it safe for my family to take a shower while its like this? There are two main health aspects of water heating systems: preventing pathogens multiplying in the water preventing people from being scalded The first, primarily concerning Legionalla, is prevented by storing water at ⋝60℃ and ensuring it is ⋝55℃ at outlets. The latter conflicts somewhat with the first. You need lower temperatures to prevent scalding of vulnerable individuals (babies, elderly, etc) The UK HSE suggests water at the outlet needs to be less than 44℃ to prevent scalding. One way to reconcile this may be to have a thermostatic mixer close to the outlet - this will mix a small mount of cold water with the hot to reduce the temperature slightly. One place where you normally find these sorts of thermostatic mixer in the UK is under washbasins inside washrooms for the disabled. In most houses though, the temperature is just a compromise between these two risks and is not regulated using a thermostatic mixer. Many showers include a thermostatic control that prevents the shower producing water hot enough to cause scalding. I'm guessing theres something wrong with the pressure seal on the shower head? As Mike Baranczak commented, this is almost certainly not the cause of your problem. In the types of shower familiar to me, the shower head plays no role in shutting off the supply of water. You might have a shower head that can be rotated to produce various patterns of spray, some feeling softer and some feeling more vigourous, but this doesn't much affect the flow rate or shut off the flow. You shut off the flow of water using a valve much lower down than the shower head. This valve is part of the shower controls that you use to set temperature and flow rate. There is a valve that is either directly operated or operated by solenoid (often the case in electric showers which use electricity to heat an insulated element that heats cold water passing through the shower unit) Might it be that the pressure in the water tank is forcing out the hot water as the water begins to get very hot? The water heater should have some means of handling excess pressure. Often it will have a pressure relief valve that vents excess pressure safely. Some older designs have the pressure regulated by a header tank. If the pressure is high enough to force excessively hot water past a shut valve, there is probably something wrong with the heater, the valve or both. If you need more specific help, you could edit your question to add details of make and model of heater and shower contols and shower head, together with photos of those items.
[ "stackoverflow", "0045682090.txt" ]
Q: run part of python script as sudo I'm trying to run only a part of my script task.py in sudo mode. Ideally I would run task.py with the following structure: if __name__ == '__main__': print('running normal parts') . . . . [running normal commands] . . . . print('running sudo parts') . . . . [running sudo commands] . . . . where I don't have to enter a password for the sudo parts of the script so that I can just make a single call $ python task.py from command line. Is there a nice to tell Python to run the second block as sudo? I saw the subprocess module had a way to call a command with sudo privelages, but I'd rather not put the "sudo parts" into a separate script to do the "running sudo commands" part. A: I would highly recommend putting the sudo parts into a separate script just as the documentation recommended. That approach improves the security posture of your script dramatically as only the part necessary to execute with elevated privileges does (aka "least privilege"--a fundamental security principle). I haven't read that documentation in detail, but I suspect it also mentions limiting write privileges to the sudo portion of the script as well and any file or resource that it may read from.
[ "stackoverflow", "0018112627.txt" ]
Q: Filter Collection by Substring in Backbone.js If I were to want to do an autocomplete for a collection, what would be the best way? I'd like to see if a search string is in any (or a select few) attributes in my model. I was thinking something like... this.collection.filter(function(model) { return model.values().contains($('input.search]').val()); }) Edit I'm sorry, I must not have explained it well enough. If I have a collection with attributes... [ { first: 'John', last: 'Doe'}, { first: 'Mary', last: 'Jane'} ] I want to type in a into my search, catch the keyup event, and filter out { first: 'Mary', last: 'Jane'}, as neither John nor Doe contains an a. A: You can look at the model's attributes to do something like this... var search = $('input.search]').val(); this.collection.filter(function(model) { return _.any(model.attributes, function(val, attr) { // do your comparison of the value here, whatever you need return ~val.indexOf(search); });; });
[ "stackoverflow", "0006726797.txt" ]
Q: How can a list of objects (a part of a bigger Model) with with Add and Delete buttons in MVC be updated with AJAX calls? The situation is as follows: I have a ViewModel that has a property that's a List<Product>, where Product is a class with let's say properties Property1, Property2 and Property3. I have to render the ViewModel and I wish to render the List<Product> in an HTML table each row of which has a "Delete" button for that row. Underneath the afore-mentioned HTML table, there should be 2 buttons: 3.1 "Add" - used to add a new empty Product to the list 3.2 "Use default product list" - the List has to be loaded via an AJAX call to the GetDefaultProduct() action of the controller Clicking on a "Delete", "Add" or "Use default product list" button should not post the entire page The model contains some other lists of items as well - for the sake of example: List<Sales>, List<Orders> and so on. I'm hoping I can re-use the solution for the List for those lists as well. Is there a way to do this with ASP.NET MVC? If yes, what is the best way to do it with ASP.NET MVC? I did this with jQuery templating and I managed to implement this with simple operations, but I have to do it in an ASP MVC solution and I'm still trying to get the hang of the technology. I've been reading about the Editor template, RenderAction, Async action and partial views and I'm trying to compose a solution with them and I'll post it if it works. Thanks in advance for any suggestions and comments! UPDATE The solution lies (as Darin pointed out) in Steve Sanderson's blog post. However, it assumes that the reader is aware of under-the-covers way of how a List of objects should be rendered in a CRUD-friendly, indexed manner. So, in order to help anyone who wants to have an indexed list of omplex objects, I suggest reading mr. Haacked's blog post: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx. After you are done with it, you can move on to Sanderson's blog. By the way, take a good look at the BeginCollectionItem custom HTML helper - its implementation isn't a trivial one as one might think. The demo project is a sight for sore eyes - it's spot on and easy to understand. The proposed solution DOES use some jQuery.ajax() calls (for the Add link), but just out of bare necessity. PS: It's a bit frustrating that one has to read an explicit article from one of the developers of ASP.NET in order to find out that there's an implicit CoC (Convention-over-Configuration) in the default model binder - it just knows how to work with Lists, but no out-of-the-box HTML helper (or anything similar) doesn't let you in on this. Personally I think that CRUD-friendly rendering of List<object> is a very common scenario, not an edge case so it should be simpler to use and a part of the ASP.NET MVC out-of-the-box machinery. A: I would recommend you reading the following blog post. It would definitely put you on the right track for implementing an editing scenario of a variable length list.
[ "stackoverflow", "0018655034.txt" ]
Q: How to animate background property in jQuery? I'm using CSS sprites via background property and I can't animate it in jQuery. Is there a way or equivalent method how to achieve this? $(function(){ $(".webdesign").mouseover(function(){ $(".webdesign").animate({ background: "url("../images/category-hover.png") 0 0" }); }); }); I'm animating url property and position. A: You can't animate an url property, but sure you can animate the background position like this: $("body").animate({"background-position-y": "200px"}, "slow"); Example jsfiddle If you also want a transition to another image, I'd suggest you to use 2 divs with 100% size and position: absolute, so you can animate their left: and top: properties, and also to animate their opacity to blend over to another image.
[ "math.stackexchange", "0001119283.txt" ]
Q: Prove $d(x,y)=\arctan|x-y|$ is a metric I have to show that $d$ is a metric on the real numbers, and the first three axioms are straight forward, the triangle inequality poses a problem. I know we need to get $$ \begin{align*} d(x,y) &= \arctan|x-y| \\ &\le \arctan|x-z|+\arctan|z-y| \\ &= d(x,z)+d(z,y), \end{align*} $$ so what I've tried is $$\arctan|x-y| = \arctan|x-z+z-y| \le \arctan(|x-z|+|z-y|),$$ but I'm not even sure if this accomplishes anything because I don't know how to split it up. A: Lemma. When $d$ is a metric on a set $X$ and $f:\>{\mathbb R}_{\geq0}\to{\mathbb R}_{\geq0}$ is a monotonically increasing function with $f(0)=0$ and $f(t)>0$ for $t>0$ which is sublinear, i.e., $$f(u+v)\leq f(u)+f(v)\qquad\forall u, \>v\geq0\ ,$$ then $d':=f\circ d$ is again a metric on $X$. Proof. Only the triangle inequality needs verification: $$d'(x,z)=f\bigl(d(x,z)\bigr)\leq f\bigl(d(x,y)+d(y,z)\bigr)\leq f\bigl(d(x,y)\bigr)+f\bigl(d(y,z)\bigr)=d'(x,y)+d'(y,z)\ .$$ Therefore it remains to prove that $t\mapsto \arctan t$ is sublinear for $t\geq0$. This can be seen as follows. $$\arctan(u+v)=\int_0^{u+v}{dt\over 1+t^2}=\int_0^u{dt\over 1+t^2}+\int_0^v{dt'\over1+(u+t')^2}\leq\arctan u+\arctan v\ .$$ A: Completely orthogonal idea. It is trivial to show that $d_1(x,y)=|x-y|$ is a metric. Function $f(x)=\arctan(x)$ is strictly increasing, continuous (actually real-analytic) bounded function positive for $x\geq 0$. Try to prove that $d(x,y)=f(d_1(x,y))$ must be a metric for any such function $f$. Edit: Please see the comment bellow. The conditions I listed originally are not sufficient. A: Suppose that $\alpha, \beta \ge 0$. For $\alpha\beta < 1$, we have $$\arctan\alpha + \arctan\beta = \arctan\left(\tan\left(\arctan\alpha + \arctan\beta\right)\right)$$ $$=\arctan \frac{\alpha+\beta}{1-\alpha\beta} \ge \arctan (\alpha + \beta)$$ by the angle sum formula for tangent. On the other hand, for $\alpha\beta \ge 1$ with (say) $\alpha > 1$, we find that $\beta \ge \frac{1}{\alpha}$, so $$\arctan \alpha + \arctan\beta \ge \arctan \alpha + \arctan \frac{1}{\alpha} \ge \arctan\alpha + \frac{\pi}{2} - \arctan\alpha$$ $$\ge \frac{\pi}{2} > \arctan(\alpha+\beta)$$ since $\arctan x < \frac{\pi}{2}$ for all $x$. Substituting $\alpha = |x-z|$, $\beta=|z-y|$, we find $$\arctan|x-z| + \arctan|z-y| \ge \arctan |x-y|$$
[ "stackoverflow", "0027735980.txt" ]
Q: Clojure Performance optimzation vs Equivalent Java What are the best simple ways to speed up this function? The equivalent code in java is nearly 50 times faster according to Criterium. I bet if I use a java Array and reduce the amount of boxing that would all help, but I thought I'd post first here to see if there was any basic mistakes I was making that could easily be fixed. Note I've already indicated (double...) for Clojure, which greatly improved the performance, but still nothing like Java. I've also first converted the seq using (double-array...) instead of using (vec ...) inside the function, and that also improved performance, but again, nothing like Java. (defn cosine-similarity [ma mb] (let [va (vec ma), vb (vec mb)] (loop [p (double 0) na (double 0) nb (double 0) i (dec (count va))] (if (neg? i) (/ p (* (Math/sqrt na) (Math/sqrt nb))) (let [a (double (va i)) b (double (vb i))] (recur (+ p (* a b)) (+ na (* a a)) (+ nb (* b b)) (dec i))))))) Note that ma and mb are both seqs, containing 200 Doubles each. In the java version they are passed as double[] args. A: Using (double 0) has no performance benefit you wouldn't get from specifying 0.0 (a double literal) directly. You will get significantly better performance if you pass in ma and mb as double-array and hint the args as doubles, don't convert them to vector via vec, and use aget to do the element lookup. This should leave you with something very close to the java code's performance. The double calls inside the let block won't be needed if you use double arrays as the function args. the end result should look something like this: (defn cosine-similarity [^doubles ma ^doubles mb] (loop [p 0.0 na 0.0 nb 0.0 i (dec (count va))] (if (neg? i) (/ p (* (Math/sqrt na) (Math/sqrt nb))) (let [a (aget va i) b (aget vb i)] (recur (+ p (* a b)) (+ na (* a a)) (+ nb (* b b)) (dec i))))))
[ "stackoverflow", "0025346525.txt" ]
Q: Android, Database count for each record I have a ListView in my Class which will display a list of every category in the database table. In that list view I have three TextViews, ROWID CategoryName and CategoryCount respectively as so: private void populateCategoryList() { DatabaseHandler db = new DatabaseHandler(this); TextView tvCategoryItem = (TextView) findViewById(R.id.tvCategoryItem); TextView tvCatID = (TextView) findViewById(R.id.tvCatID); TextView tvCatCount = (TextView) findViewById(R.id.tvCatCount); Cursor cursor = db.getCategories(); // Allow activity to manage lifetime of the cursor. // DEPRECATED! Runs on the UI thread, OK for small/short queries. // startManagingCursor(cursor); //TODO Turned off because on back from contact details made a closed cursor error // Setup mapping from cursor to view fields: String[] fromFieldNames = new String[] { db.KEY_ROWID, db.KEY_CATEGORY }; int[] toViewIDs = new int[] { R.id.tvCatID, R.id.tvCategoryItem }; SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this, // Context R.layout.item_categorylist, // Row layout template cursor, // cursor (set of DB records to map) fromFieldNames, // DB Column names toViewIDs // View IDs to put information in ); /****** COUNT CODE ******/ // tvCatCount = (db.countCategory(category)); // Set the adapter for the list view lvCategories = (ListView) findViewById(R.id.lvCategories); lvCategories.setAdapter(myCursorAdapter); db.close(); You can see in the toFields above that I do not yet have a field set for the count. I will use tvCatCount for this. The question is, how and where do I insert the count code. In this case the count? I think that the countCategory will need to be a for loop where it should get the id of the current category entry for that row, call the db.countCategory and tehn set the value in the TextView to the returned result? Here is the db.countCategory code: public int countCategory(category){ SQLiteDatabase db = this.getWritableDatabase(); String[] categoryColumns = new String[] { KEY_ROWID, KEY_CATEGORY }; Cursor c = db.query(CATEGORY_TABLE, null, null, null, KEY_CATEGORY + "=" + category, null, null); int result = c.getCount(); c.close(); Log.i("DATABASE", "Category Count for id " + id + "is " + result); return result; } which should count every entry in the table equal to the value of "id". This code already works elsewhere, so I am not too worried about it, but to count for each row in a listview, that is a different animal. A: To show the count of expenses for each category, you would need a table with these columns: _id | CategoryName | Count To compute this, you have to join the categories table to the expenses table, and use GROUP BY to get one output row for each distinct category value: SELECT Category.rowid AS _id, Category.Name, COUNT(*) AS NumberOfExpenses FROM Category JOIN Expenses ON Category.rowid = Expenses.CategoryID GROUP BY Category.rowid
[ "stackoverflow", "0017892436.txt" ]
Q: Do multiple forms in an ASP.NET MVC view conflict? Given an MVC view like so: <form id="Form1"> <label for="LastName"> @Html.DisplayNameFor(m => m.LastName) </label> @Html.EditorFor(m => m.LastName) <button id="SubmitOne" onclick="SubmitOne_Click()">SubmitOne</button> </form> <form id="Form2"> <label for="LastName2"> @Html.DisplayNameFor(m => m.LastName2) </label> @Html.EditorFor(m => m.LastName2) <button id="SubmitTwo" onclick="SubmitTwo_Click()">SubmitTwo</button> </form> The javascript functions are irrelevant, this problem also occurs when they are empty or just have an alert. When SubmitOne is clicked, everything works as expected. However, when SubmitTwo is clicked the whole page refreshes, which isn't supposed to happen. If I comment out Form1, then Form2 works fine. What is going on here? Update: Here's the javascript: function SubmitOne_Click() { alert("One"); } function SubmitTwo_Click() { alert("Two"); } As a troubleshooting step, I stripped the view down to nothing but the form, and the script down to nothing as well. I do have references to Bootstrap, jqGrid, and jQuery in the _Layout, but nothing that currently uses them in this view. A: It turns out that I needed to add a type attribute to my buttons: <button type="button" id="SubmitTwo" onclick="SubmitTwo_Click()">SubmitTwo</button> This prevented the button from doing a full submit of the form. See also: How to prevent buttons from submitting forms
[ "dba.stackexchange", "0000144371.txt" ]
Q: Updating dbi_dbccLastKnownGood I have a VLDB and I offload the DBCC CHECKDB to another server. Is it possible to update the dbi_dbccLastKnownGood on the VLDB server so it passes any scripts that check that date like sp_Blitz? A: No, this feature was put in to record the last time that DBCC CHECKDB ran successfully. It would be extremely unlikely that a feature would be added that allows this value to be edited at will and effectively lie about the history. The only way to update this that does not actually involve hacking the database boot page is to execute DBCC CHECKDB. So you should customise these scripts to not report that issue or ignore this result if it is entirely expected that this database isn't being checked due to alternate arrangements.
[ "stackoverflow", "0056519440.txt" ]
Q: Getting this error: "Conversion from string "" to type 'Double' is not valid." visual studio Im trying to make a app for cafe. It has a simple interface coffee names with labels and quantity with numericupdown, receipt textbox and receipt button. I coded receipt button to show coffee name and quantity in receipt textbox like this: If (espresso.Value > 0) Then receipt.AppendText("Espresso" + vbTab + vbTab + espresso.Value.ToString + Environment.NewLine) that works fine but i want to add the price next to quantity of the coffee so i added these lines : Dim espressoprice As Double espressoprice = 3 Dim espressoquantity As Double = Convert.ToDouble(espresso.Value) Dim espressototal As Double espressototal = (espressoprice * espressoquantity) (espresso.value is numericupdown value) and changed the first codeline like this: If (espresso.Value > 0) Then receipt.AppendText("Espresso" + vbTab + vbTab + espresso.Value.ToString + vbTab + espressototal + Environment.NewLine) but i keep getting this error: "Espresso 2 " "Conversion from string "" to type 'Double' is not valid." What am i doing wrong please help. A: The proper solution to this problem is to use the correct operator. You are trying to perform string concatenation but you are using the addition operator. This: "Espresso" + vbTab + vbTab + espresso.Value.ToString + vbTab + espressototal + Environment.NewLine is actually performing multiple additions. Addition maps to concatenation for two Strings but for numbers, addition is mathematical, NOT textual. In order to add a String and a numeric value, the system has to implicitly convert one of them to the other type. You are obviously assuming that the number will be converted to a String but it's actually the opposite that is happening, i.e. the system is trying to convert a String to a number and it is failing. This is why you should not rely on implicit conversions. If you used the concatenation operator, as you should when performing concatenation, then there's only one way it can go: "Espresso" & vbTab & vbTab & espresso.Value.ToString & vbTab & espressototal & Environment.NewLine Notice that, in this case, you don't have to explicitly convert the number to a String because the concatenation operator is defined for Strings and numeric values. Concatenation is a String operation so you know for a fact that everything that can be treated as a String, will be. That said, there are better options anyway, e.g. receipt.AppendText(String.Concat("Espresso", vbTab, vbTab, espresso.Value, vbTab, espressototal, Environment.NewLine)
[ "stackoverflow", "0013462637.txt" ]
Q: Matching Items in Lists - Python So I know how to match items in two lists, but what I am curious about is how to link the two matches. For example, I have a browser based app and am using Jinja2 as my template language. My program pulls a list of PDF files which also have corresponding XML files. (The files are named similarly, i.e. foo.xml contains the data for foo.pdf) The list of PDF files is displayed on the page, and when the user clicks on the name of a file from the list of PDFs, that file's XML data, if it exists yet, would be displayed in a little pop-up. So, I guess my question would be, how do I connect the dots and specify the correct xml file to be displayed since col_list[0] is not always going to be the same file? Below is my code creating the list of pdf files: col_list = '<li class="ui-widget-content">'.join('%s</li>' % (os.path.splitext(filename)[0]) for filename in listfiles if filename.endswith('.pdf') ) Thanks! Edit: I'm going to give a different example in hopes of being less confusing. List 'A' is an ever-changing list of PDF files (foo.pdf, bar.pdf, etc.) List 'B' is an ever-changing list of XML files named the same as list 'A' (foo.xml, bar.xml, etc)I am looping over both lists, and creating variables for each list. If these lists were identical, I could simply call list_b[0] to get the xml data for the first file, which would also be the first PDF. But, since some PDFs do not have XML files yet, the order of the lists do not match up. Let's say list_b[0] is foo.xml and list_a[3] is foo.pdf How can I tell Python that I want the XML data for foo.pdf when the order of the lists is ever-changing? Sorry for the confusion. A: If I understand correctly: you want to use a set for the XML filenames, and look them up: pdfs = ['a.pdf', 'b.pdf', 'c.pdf', 'd.pdf'] xmls = ['a.xml', 'd.xml', 'b.xml'] xml_set = set(xmls) result = [] for pdf in pdfs: xml = pdf.replace('.pdf', '.xml') if xml in xml_set: result.append('Matched %s to %s' % (pdf, xml)) else: result.append("%s doesn't have a corresponding XML file" % (pdf,)) print result
[ "mathoverflow", "0000353080.txt" ]
Q: Positively curved manifold with collapsing unit balls Can we find a complete connected noncompact Riemannian manifold $(M^n,g)$ such that the curvature operator $Rm>0$ and $$ \inf_{p \in M} \text{Vol}_gB(p,1)=0? $$ A: The answer is negative if $\dim M=2$ and positive otherwise, as shown in the paper: Croke, C. B., & Karcher, H. (1988). VOLUMES OF SMALL BALLS ON OPEN MANIFOLDS: LOWER BOUNDS AND EXAMPLES. AMERICAN MATHEMATICAL SOCIETY (Vol. 309). https://www.ams.org/journals/tran/1988-309-02/S0002-9947-1988-0961611-7/S0002-9947-1988-0961611-7.pdf The negative result is an immediate consequence of Theorem A, while the positive one follows from Example 1. Their construction for the latter is as follows: Consider the $d$-dimensional hypersurface given by the paraboloid $\mathcal P = \{x\in \mathbb R^{d+1}\mid x_{d+1}=x_1^2+\ldots+x_d^2\}$. At any point $A$ of $\mathcal P$ one can consider its tangential cone $\mathcal C$, i.e., the Euclidean cone of vertex $V$ with axis along the line $AV$ and that intersects $\mathcal P$ tangentially. One then can consider $\tilde {\mathcal P}$ to be $\mathcal P$ with $\mathcal C$ "attached" (see the Figure at p.765). This is a piecewise $C^\infty$ hypersurface, with a conical singularity at $V$ and that is $C^1$ at the intersection $\mathcal P\cap \mathcal C$. Outside of these regions, the curvature of $\tilde {\mathcal P}$ is $K>0$, since the curvature of $\mathcal P$ is positive and the one of the cone is zero. Moreover, it is always possible to smooth a conical singularity preserving the $K>0$ bound, and the same is true for the $\mathcal P\cap \mathcal C$ part. (You can maybe look at this thesis, e.g., Lemma 3.2.4.) So we have constructed a smooth hypersurface with $K>0$, and where we can estimate the volume of balls contained in the smoothed conical region by the volumes of the corresponding regions in the non-smoothed cones. Moreover, this operation can be done with a sequence of tangent cones $\mathcal C_n$, as soon as they are sufficiently distant one from the other. The estimation of the volumes of the balls on the tangent cones is the object of the claim at the end of p.765. In particular, there the authors show that if the vertex of the cone is $V = (k+1,\ldots, 2k+1)$ for $k\ge 5$ (I'm fixing $r=1$), this volume is bounded by the volume of a "spherical spindle" : $$ \operatorname{vol}(B(V,1))\le C_d\sin^{d-2}\theta , $$ where $\theta$ is an angle bounded by $\tan^2\theta\le 6/k$. (Here I chose $\varepsilon =1\le k^2/(2k+2)$.) This shows that it is possible to attach to $\mathcal P$ a sequence of cones $\mathcal C_n$ with vertices $V_n\to +\infty$, and smooth them out so that $$ \lim_{n\to +\infty}\operatorname{vol}(B(V_n,1))\le (C_d+1) \lim_{n\to +\infty} \sin^{d-2}\left(\theta_n\right) = 0. $$ This proves that the obtained hypersurface (which has positive curvature) satisfies your requirement.
[ "stackoverflow", "0039988684.txt" ]
Q: JavaFx Error when passing array in root.getChildren().add() in the code below when i use only the line 54 ( line 55 comment ) , it works fine . But when i execute with line 55 in action , i get that error Caused by: java.lang.IllegalArgumentException: Children: duplicate children added: parent = Pane@16d2d0b Image white = new Image("/javafxapplication1/white.png"); ImageView whiteView = new ImageView(white); Image red = new Image("/javafxapplication1/red.png"); ImageView redView = new ImageView(red); ImageView[] whiteArray = new ImageView[3]; ImageView[] redArray = new ImageView[3]; //the points of columns int the board map int[][] whitepoints={{54,27},{235,27},{417,27}}; int[][] redpoints={{145,27},{325,27},{507,27}}; whiteArray[0]=whiteView; whiteArray[0].setLayoutX(whitepoints[0][0]); whiteArray[0].setLayoutY(whitepoints[0][1]); whiteArray[1]=whiteView; whiteArray[1].setLayoutX(whitepoints[1][0]); whiteArray[1].setLayoutY(whitepoints[1][1]); Pane root = new Pane(); imgView.fitWidthProperty().bind(primaryStage.widthProperty()); imgView.fitHeightProperty().bind(primaryStage.heightProperty()); root.getChildren().add(imgView); 54!!! root.getChildren().add(whiteArray[0]); 55!!! root.getChildren().add(whiteArray[1]); Scene scene = new Scene(root); primaryStage.setTitle("Backgammon!"); primaryStage.setScene(scene); primaryStage.show(); Thanks !!! A: In your code, whiteArray[0] and whiteArray[1] both refer to the same instance of ImageView (the one you previously called whiteView). You can't add the same ImageView to the scene graph twice. I think what you are trying to do is share the same Image between two different ImageViews: Image white = new Image("/javafxapplication1/white.png"); Image red = new Image("/javafxapplication1/red.png"); // maybe the same problem with this in code you haven't shown??? ImageView redView = new ImageView(red); ImageView[] whiteArray = new ImageView[3]; ImageView[] redArray = new ImageView[3]; //the points of columns int the board map int[][] whitepoints={{54,27},{235,27},{417,27}}; int[][] redpoints={{145,27},{325,27},{507,27}}; whiteArray[0]=new ImageView(white); whiteArray[0].setLayoutX(whitepoints[0][0]); whiteArray[0].setLayoutY(whitepoints[0][1]); whiteArray[1]=new ImageView(white); whiteArray[1].setLayoutX(whitepoints[1][0]); whiteArray[1].setLayoutY(whitepoints[1][1]); Pane root = new Pane(); imgView.fitWidthProperty().bind(primaryStage.widthProperty()); imgView.fitHeightProperty().bind(primaryStage.heightProperty()); root.getChildren().add(imgView); root.getChildren().add(whiteArray[0]); root.getChildren().add(whiteArray[1]);
[ "pt.stackoverflow", "0000233662.txt" ]
Q: Erro ao retornar StringStr Tenho a seguinte função em php ele me retorna uma string da pagina para que eu possa fazer if e else com a informação retornada, porem ocorre um erro: Parse error: syntax error, unexpected '=' in /storage/ssd3/854/1950854/public_html/config.php on line 22 como posso resolver isso ? (aparentemente a linha com o erro é a name porem não sei como resolver) function GetStr($string, $start, $end){ $str = explode($start, $string); $str = explode($end, $str[1]); return $str[0]; } name = "sair"; $valor = GetStr($resultado, 'name='","); echo $valor; A: Neste caso é um erro de sintaxe, a sua variável name está sem o cifão $, que é obrigatório para as variáveis conforme definição da linguagem PHP. Portanto incluindo o cifão deve funcionar: function GetStr($string, $start, $end){ $str = explode($start, $string); $str = explode($end, $str[1]); return $str[0]; } $name = "sair"; $valor = GetStr($resultado, 'name='","); echo $valor;
[ "physics.stackexchange", "0000007746.txt" ]
Q: What needs to happen for one to ingest radioactive particles and how likely is this? There are many stories about radioactivity and the relative danger of it in the news lately, but very little actual information. The radioactivity levels around Fukushima Daiichi are high, but seem negligible in just somewhat removed locations. The real danger seems to stem from ingesting radioactive particles. Just how likely is it for that to happen in any considerable distance from the reactor, say in Tokyo, and how dangerous for the human body is it really? How far can these particles travel in any dangerous concentration? A: I would like to add that radioactive isotopes are a constant background in all natural environments, and more so in stone and concrete buildings. The relevant question is how much more than the natural background is the artificial radiation induced by human activities. In a recent viewpoint in BBC news professor Alison gives relevant numbers. For example, the human body has about 50 becquerel per kilogram in the natural state. An interesting chart that puts radiation in perspective is here, and this is a graph from the scientist who provided the numbers for the chart. So when you see animated maps of how the radiation is spread from Japan, read the scales. You will see that the numbers are within natural variations. The immediate danger of death come for huge doses, look at the chart. Even for people next to the reactors there has been no such exposure. There are long term effects of ingesting or breathing in isotopes for the people in the region, which have to do with a larger cancer rate over twenty or thirty years. The rest of the world is nowhere close to such levels of exposure.
[ "photo.stackexchange", "0000004142.txt" ]
Q: How to manual focus Nikon Coolscan 4000 using Vuescan? How to be sure that the scanner (Nikon Coolscan 4000) focuses correctly and if not, how can I manually focus it using Vuescan? A: The Input Tab has a focus and auto focus option in Vuescan. + lots of experimenting. Don't forget to save your settings regularly in a way you can remember what they are.
[ "stackoverflow", "0033981778.txt" ]
Q: Call PHP function I have php function by multi parameter. I want to call this function with setting only last argument. Simple way is setting other argument empty. But it isn't good. Is any way to call this function with setting last argument and without setting other argument? See this example: function MyFunction($A, $B, $C, $D, $E, $F) { //// Do something } //// Simple way MyFunction("", "", "", "", "", "Value"); //// My example MyFunction(argument6: "Value") A: My suggestion is use array instead of using number of argument, For example your function call should be like this. $params[6] = 'value'; MyFunction($params); For identify that sixth parameter has set function MyFunction($params){ If ( isset($params[6]) ) // parameter six has value } I hope that it will be a alternate way
[ "worldbuilding.stackexchange", "0000138785.txt" ]
Q: Salty or fresh or brackish waters? So this is a small map of all the continents on the small planet of Parsas Decem. As far as most of the rivers go, I’ve got it figured out. What I’m wondering is, can salt water flowing in from the sea be filtered naturally by the soil, perhaps with specific desalinating minerals, into fresh water? If I can, I’ll try to post the map of just the north eastern quarter of Daichi. A: Saltwater does not move far inland, you are chasing a problem that doesn't exist. Saltwater intrusion of more than a kilometer is all but unheard of, and then only in the driest locations and only affecting deep wells. Saltwater is also displaced outward and downward by fresh water, the fresh water is renewed by rain anywhere inland. Look at the lower picture an example of measured salt water intrusion. Saltwater permeating inland is measured in feet. Unless you have and an inland sea that is not shown or have extreme flooding salt water intrusion is not an issue, and if you do that is a very different question. A: can salt water flowin in from the sea be filtered naturally by the soil, perhaps with specific desalinating minerals, into fresh water? You are looking for a way to naturally desalinize water. Sorry to disappoint you, but it requires energy to happen, thus I don't think it can happen by simple filtration. Desalination is a process that takes away mineral components from saline water. The closes you can get in a natural environment is one of the following: First reverse osmosis The leading process for desalination in terms of installed capacity and yearly growth is reverse osmosis (RO). The RO membrane processes use semipermeable membranes and applied pressure (on the membrane feed side) to preferentially induce water permeation through the membrane while rejecting salts. Reverse osmosis plant membrane systems typically use less energy than thermal desalination processes. Or also freeze-taw Freeze-thaw desalination uses freezing to remove fresh water from salt water. Salt water is sprayed during freezing conditions into a pad where an ice-pile builds up. When seasonal conditions warm, naturally desalinated melt water is recovered. This technique relies on extended periods of natural sub-freezing conditions. Or, finally, solar evaporation Solar evaporation mimics the natural water cycle, in which the sun heats the sea water enough for evaporation to occur. After evaporation, the water vapor is condensed onto a cool surface. A: Probably it is not what you asked for, but you could find it interesting This article explains that for the ancient Easter Island populations, the main water sources were brackish-water pools near the sea. the Rapanui probably got at least some of their drinking water from places along the coast where fresh groundwater seeped out of the island’s bedrock and into the sea. The resulting mixture would have been brackish but safe to drink, and it could have sustained populations of thousands on an island with few other reliable sources of fresh water I know that it is not a desalinization of sea water (of course it is the opposite, the partial salinization of underground water), but it could sustain some settlements along the coast and far from rivers, if the soil is too hard to dig wells far from the sea. And if the brackish water has a bad taste, you can always use it to brew beer :)
[ "stackoverflow", "0009650933.txt" ]
Q: Starting Sessions in Code Igniter starting at the top of the view: <?php ### CREATE SESSION ** $this->load->library('session'); $this->load->library('encrypt'); $newdata = array( 'session_id' => random hash, 'ip_address' => 'string - user IP address', 'user_agent' => 'string - user agent data', 'last_activity' => timestamp ); $session_id = $this->session->userdata('session_id'); ?> Getting this error: Parse error: syntax error, unexpected T_STRING, expecting ')' on line 5 how do I fix this? A: Looking at your new comments, to start a session all you need to do is: <?php //Start session $this->load->library('session'); //Try retriving data: $session_id = $this->session->userdata('session_id'); echo $session_id;
[ "stackoverflow", "0060143346.txt" ]
Q: C: I made a program to sort an array in ascending order and cannot figure the reason for a certain step in the for loops I am making a program to sort numbers in an array using the bubble sort method in c and I know how to do it but I cannot figure out what the second for loop's j<n-i-1subtraction of i from the length of the array is for. It is probably a simple explanation but I cannot for the life of me scramble my small brain for the answer. #include <stdio.h> #include <stdlib.h> int main() { int input[10],swap; printf("Input Numbers: "); scanf("%d%d%d%d%d%d%d%d%d%d",&input[0],&input[1],&input[2],&input[3],&input[4],&input[5],&input[6],&input[7],&input[8],&input[9]); int n=10; for(int i=0;i<n-1;i++){ for(int j=0;j<n-i-1;j++){ if(input[j]>input[j+1]){ swap=input[j]; input[j]=input[j+1]; input[j+1]=swap; } } } printf("Sorted List: {"); for(int i=0;i<10;i++){ if(i<9){ printf("%d, ",input[i]); } else{ printf("%d}",input[i]); } } return 0; } A: In the first iteration of the i loop, the greatest element is bubbled to the end of the n elements in the array. After that, we know the last element is done. So we only need to do the n-1 remaining elements. In the second iteration of the i loop, the next greatest element is bubbled to the end of the n-1 elements we were working on. After that, we know the last two elements are done. So we only need to do the n-2 remaining elements. This continues, so that in each iteration, we only need to work on n-i elements. Since elements j and j+1 are compared, we only need j to reach n-i-2, i.e., be less than n-i-1., as that will give j+1 up to n-i-1. (The number of elements from index 0 to index n-i-1 is n-i.)
[ "tex.stackexchange", "0000012739.txt" ]
Q: How do I use LaTeX to create a table of contents for a set of pdf files which I am merging into a single large pdf? I have a set of pdf files which I want to merge into a larger pdf files. Each individual pdf file is an article with sections. I am hoping to make the merged pdf file into a book format with each article being a chapter, whose sections and subsections correspond to that of the individual chapter. What I need is a table of contents page which shows the chapters, the sections, and subsections and links to them with this table of contents page being displayed in the sidebar of a pdf reader such as evince (which calls it an index). What I have right now: \documentclass{report} \author{<somename>} \title{<sometitle>} \date{<somedate>} \usepackage{pdfpages} \usepackage[pdfauthor={<somename>},% pdftitle={<sometitle>},% pdftex]{hyperref} \begin{document} \tableofcontents \clearpage\phantomsection \addcontentsline{toc}{chapter}{<chaptername>} \includepdf[pages=-,linktodoc=false]{file1.pdf} \clearpage\phantomsection \addcontentsline{toc}{chapter}{<chaptername>} \includepdf[pages=-,linktodoc=false]{file2.pdf} \clearpage\phantomsection \addcontentsline{toc}{chapter}{<chaptername>} \includepdf[pages=-,linktodoc=false]{file3.pdf} \clearpage\phantomsection \addcontentsline{toc}{chapter}{<chaptername>} \includepdf[pages=-,linktodoc=false]{file4.pdf} \end{document} Now file3.pdf and file4.pdf have sections and subsections in them. How do I display these sections and subsections in the table of contents and link from there to the actual page? (And I also would like this info to be displayed in the sidebar of a pdf reader such as evince). A: The entries in the "table of contents page [which is] being displayed in the sidebar of a pdf reader" are called PDF bookmarks in Adobe Acrobat. The hyperref and bookmark packages provide functionality to place own bookmarks into your PDF. You should go for the bookmark package (which loads hyperref internally). It allows you to place links from the sidebar to specific pages of the current (or even an external) PDF with specific page, view port and zoom levels. You would need to collect the pages (and maybe zoom settings) for each (sub-)section by yourself if you don't have the LaTeX source of them. An example for an bookmark entry which should appear in a certain hierarchy level and point to a certain page with a certain height (FitH) is: \bookmark[level=<num>,page=<num>,view={FitH 842}]{<title>} (See also the similar questions if you want to place links inside the document: PDF hyperlinks to a given page. pdfpages and linktodoc)
[ "stackoverflow", "0009397227.txt" ]
Q: How to resolve dependency packages when installing httpd-devel apr-devel apr-util-devel yum on centos 5.6 I am trying to install httpd-devel apr-devel apr-util-devel centos 5.6. i got dependency problem Resolving Dependencies --> Running transaction check ---> Package apr-devel.i386 0:1.2.7-11.el5_6.5 set to be updated --> Processing Dependency: apr = 1.2.7-11.el5_6.5 for package: apr-devel --> Processing Dependency: libapr-1.so.0 for package: apr-devel ---> Package apr-devel.x86_64 0:1.2.7-11.el5_6.5 set to be updated ---> Package apr-util-devel.i386 0:1.2.7-11.el5_5.2 set to be updated --> Processing Dependency: apr-util = 1.2.7-11.el5_5.2 for package: apr-util-devel --> Processing Dependency: openldap-devel for package: apr-util-devel --> Processing Dependency: libaprutil-1.so.0 for package: apr-util-devel --> Processing Dependency: db4-devel for package: apr-util-devel --> Processing Dependency: expat-devel for package: apr-util-devel ---> Package apr-util-devel.x86_64 0:1.2.7-11.el5_5.2 set to be updated ---> Package httpd-devel.i386 0:2.2.3-53.el5.centos.3 set to be updated --> Processing Dependency: httpd = 2.2.3-53.el5.centos.3 for package: httpd-devel ---> Package httpd-devel.x86_64 0:2.2.3-53.el5.centos.3 set to be updated --> Processing Dependency: httpd = 2.2.3-53.el5.centos.3 for package: httpd-devel --> Running transaction check ---> Package apr.i386 0:1.2.7-11.el5_6.5 set to be updated ---> Package apr-util.i386 0:1.2.7-11.el5_5.2 set to be updated --> Processing Dependency: libsqlite3.so.0 for package: apr-util --> Processing Dependency: libldap-2.3.so.0 for package: apr-util --> Processing Dependency: libdb-4.3.so for package: apr-util --> Processing Dependency: libexpat.so.0 for package: apr-util --> Processing Dependency: libpq.so.4 for package: apr-util --> Processing Dependency: liblber-2.3.so.0 for package: apr-util ---> Package db4-devel.x86_64 0:4.3.29-10.el5_5.2 set to be updated ---> Package expat-devel.x86_64 0:1.95.8-8.3.el5_5.3 set to be updated ---> Package httpd-devel.i386 0:2.2.3-53.el5.centos.3 set to be updated --> Processing Dependency: httpd = 2.2.3-53.el5.centos.3 for package: httpd-devel ---> Package httpd-devel.x86_64 0:2.2.3-53.el5.centos.3 set to be updated --> Processing Dependency: httpd = 2.2.3-53.el5.centos.3 for package: httpd-devel ---> Package openldap-devel.x86_64 0:2.3.43-12.el5_7.10 set to be updated --> Processing Dependency: cyrus-sasl-devel >= 2.1 for package: openldap-devel --> Running transaction check ---> Package cyrus-sasl-devel.x86_64 0:2.1.22-5.el5_4.3 set to be updated ---> Package db4.i386 0:4.3.29-10.el5_5.2 set to be updated ---> Package expat.i386 0:1.95.8-8.3.el5_5.3 set to be updated ---> Package httpd-devel.i386 0:2.2.3-53.el5.centos.3 set to be updated --> Processing Dependency: httpd = 2.2.3-53.el5.centos.3 for package: httpd-devel ---> Package httpd-devel.x86_64 0:2.2.3-53.el5.centos.3 set to be updated --> Processing Dependency: httpd = 2.2.3-53.el5.centos.3 for package: httpd-devel ---> Package openldap.i386 0:2.3.43-12.el5_7.10 set to be updated --> Processing Dependency: libsasl2.so.2 for package: openldap ---> Package postgresql-libs.i386 0:8.1.23-1.el5_7.3 set to be updated ---> Package sqlite.i386 0:3.7.0.1-1.el5.art set to be updated ---> Package sqlite.x86_64 0:3.7.0.1-1.el5.art set to be updated --> Running transaction check ---> Package cyrus-sasl-lib.i386 0:2.1.22-5.el5_4.3 set to be updated ---> Package httpd-devel.i386 0:2.2.3-53.el5.centos.3 set to be updated --> Processing Dependency: httpd = 2.2.3-53.el5.centos.3 for package: httpd-devel ---> Package httpd-devel.x86_64 0:2.2.3-53.el5.centos.3 set to be updated --> Processing Dependency: httpd = 2.2.3-53.el5.centos.3 for package: httpd-devel --> Finished Dependency Resolution httpd-devel-2.2.3-53.el5.centos.3.i386 from updates has depsolving problems --> Missing Dependency: httpd = 2.2.3-53.el5.centos.3 is needed by package httpd- devel-2.2.3-53.el5.centos.3.i386 (updates) httpd-devel-2.2.3-53.el5.centos.3.x86_64 from updates has depsolving problems --> Missing Dependency: httpd = 2.2.3-53.el5.centos.3 is needed by package httpd-devel- 2.2.3-53.el5.centos.3.x86_64 (updates) Error: Missing Dependency: httpd = 2.2.3-53.el5.centos.3 is needed by package httpd- devel-2.2.3-53.el5.centos.3.i386 (updates) Error: Missing Dependency: httpd = 2.2.3-53.el5.centos.3 is needed by package httpd- devel-2.2.3-53.el5.centos.3.x86_64 (updates) You could try using --skip-broken to work around the problem You could try running: package-cleanup --problems package-cleanup --dupes rpm -Va --nofiles --nodigest The program package-cleanup is found in the yum-utils package. can you anybody guide me how to resolve this issue?. I need to install this yum packages on the centos 5.6 machine. httpd version is httpd-2.2.21-1.w5 apche version is Server version: Apache/2.2.21 (Unix) Server built: Nov 14 2011 18:03:07 A: You don't even list your original command, so we can't be sure how you're trying to install it. From the output, my guess is that you have an old httpd/httpd-devel package holding you back. On top of that you have both i386 and x86_64 versions of them installed. Start by removing httpd-devel with yum remove httpd-devel.i386 http-devel.x86_64 then try again with yum -y install httpd-devel apr-devel
[ "stackoverflow", "0019741264.txt" ]
Q: Persist selected item between app running sessions I'm trying to make a behavior applying to Selector inheritors (ListView, ListBox etc) which will restore selected element and focus it on application launching. Also I want to focus selected element when switching between tabs. The main problem is to find a time point when ListView populated a list, done all its internal activities and is ready to be focused. I left out the part of behavior which cares about synchronisation of SelectedIndex with persistence system and cleanup code and show only the part refers to the interaction with control. public class PersistSelectedItemIndexBehavior : Behavior<Selector> { protected override void OnAttached() { base.OnAttached(); RestorePersistedSelectedIndex(); AssociatedObject.Loaded += AssociatedObject_OnLoaded; } private void AssociatedObject_OnLoaded(object sender, RoutedEventArgs e) { AssociatedObject.GotFocus += AssociatedObject_OnGotFocus; Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() => { AssosiatedObject.Focus(); ScrollSelectedItemIntoView( AssociatedObject.FindVisualChild<ScrollViewer>()); })); } private void AssociatedObject_OnGotFocus(object _, RoutedEventArgs __) { // do it only once on loading control AssociatedObject.GotFocus -= AssociatedObject_OnGotFocus; Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action( SetFocusOnSelectedElement)); } private void SetFocusOnSelectedElement() { var element = AssociatedObject.ItemContainerGenerator.ContainerFromItem( AssociatedObject.SelectedItem) as IInputElement; if (element != null) element.Focus(); } private void ScrollSelectedItemIntoView(ScrollViewer scrollViewer) { double position = AssociatedObject.SelectedIndex; position -= scrollViewer.ViewportHeight / 2 - 1; scrollViewer.ScrollToVerticalOffset(position); } } It works when there are a few items in the ListView, but if there are a several hundred items it does not. When ScrollSelectedItemIntoView is called Items.Count is 0 and SelectedIndex is -1. I need a combination of events and states which will clearly indicate that a ListView is ready to operate with it, is ready to scroll to the selected element and focus it. thanks in advance A: Finally I solved a problem. public class PersistSelectedItemIndexBehavior : Behavior<Selector> { protected override void OnAttached() { base.OnAttached(); AssociatedObject.Loaded += AssociatedObject_OnLoaded; DependencyPropertyDescriptor.FromProperty(Selector.SelectedIndexProperty, AssociatedObject.GetType()) .AddValueChanged(AssociatedObject, OnSelectedIndexChanged); RestorePersistedSelectedIndex(); } private void OnSelectedIndexChanged(object sender, EventArgs e) { DependencyPropertyDescriptor.FromProperty(Selector.SelectedIndexProperty, AssociatedObject.GetType()) .RemoveValueChanged(AssociatedObject, OnSelectedIndexChanged); Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() => ScrollSelectedItemIntoView(AssociatedObject.FindVisualChild<ScrollViewer>()))); } private void AssociatedObject_OnLoaded(object sender, RoutedEventArgs e) { AssociatedObject.GotFocus += AssociatedObject_OnGotFocus; } private void AssociatedObject_OnGotFocus(object sender, RoutedEventArgs routedEventArgs) { AssociatedObject.GotFocus -= AssociatedObject_OnGotFocus; Dispatcher.BeginInvoke(DispatcherPriority.Input, (Action)SetFocusOnSelectedElement); } private void SetFocusOnSelectedElement() { var element = AssociatedObject.ItemContainerGenerator.ContainerFromItem(AssociatedObject.SelectedItem) as IInputElement; if (element != null) element.Focus(); } private void ScrollSelectedItemIntoView(ScrollViewer scrollViewer) { double position = AssociatedObject.SelectedIndex; position -= scrollViewer.ViewportHeight / 2 - 1; scrollViewer.ScrollToVerticalOffset(position); Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(SetFocusOnSelectedElement)); } }
[ "stackoverflow", "0055971191.txt" ]
Q: Heroku deploy fails to find dependency given as GitHub pull request URL in requirements.txt There is an answer to my first question that I tried to do. I created virtual-env local repository, where I installed requirements.txt with: git+https://github.com/ramusus/kinopoiskpy@refs/pull/47/merge#egg=kinopoiskpy. It was installed successfully, although there was WARNING: Did not find branch or tag. And then I tried to push requirements.txt to my Heroku server and re-deploy. And I don't even know what's the problem. What should I do to fix this? A: Have you tried pointing to the source repository for the merge request as mentioned in the question marked as a possible duplicate of your first question? git+https://github.com/AlexanderNiMo/kinopoiskpy@4c888bf4f6b330b115d11fac3e0b8bb177b597bb
[ "stackoverflow", "0025651675.txt" ]
Q: What is more resourse-efficient? Consider this code I found in Daniel Shullers book on C# game programming: Monster { string _name; int _currentLevel = 1; int _currentExperience = 0; int _nextLevelExperience = 1000; public void LevelUp() { Console.WriteLine(_name + "has levelled up!"); _currentLevel++; _currentExperience = 0; _nextLevelExperience = _currentLevel * 1000; } } The question is: Is making a _nextLevelExperience field to be calculated this way is more efficient than, say making a data file which holds predefined all _nextLevelExperience values respective to _currentLevel and make program access and read the data. Is some small computation worth it? A: This calculation takes up 0 memory and has a negligible computation time. If the calculation is really that simple, then leave it as a calculation. Don't worry about performance until performance becomes an issue.
[ "stackoverflow", "0033170683.txt" ]
Q: KnockoutJS - UI not updating with built-in observableArray methods except push and pop When I do a push or pop operation on my observable array, it is reflected in the ui. However other operations on the array won't change anything in the UI. Here's an example of my case: <ul data-bind="foreach: addresses"> <!-- ko template: {name: 'AddressItemTemplate', data: {address: $data, page: 'update-page'} }--> <!-- /ko --> </ul> I use my template in two different pages and thats the reason I am using the template data like that. <script type="text/html" id="AddressItemTemplate"> <p data-bind="text: (page == 'update-page') ? 'updating' : 'declined'"</p> <p data-bind="text: address.title"></p> </script> Now on js side, ofc I declared the addresses as an observable array this.addresses = ko.observableArray([addresObject1, addressObject2, ...]) Somewhere on the page, I edit the address values. To have UI reflecting the changes, I do the following: //suppose we know that the first address is being edited var tmp_addresses = addresses(); tmp_addresses[0].title = 'blabla'; addresses(tmp_addresses); And there it is, in the viewModel, I can see that the content of the addresses has been updated, but not in the UI?? addresses.push(someAddressObject); or addresses.pop(); works (updates the UI with the new/removed element). But addresses.splice(0, 1, newAddressObject) does not do anything in the UI again. What am I missing here? How can push pop work and not the others?? Am I experiencing a bug in knockout framework? UPDATE I found out a way to do it, but there's something wrong. I'll come to that but first: I am well aware that if I use observable objects in the observable array, the changes would be reflected in UI. However that is exactly the thing I want to avoid. It is an overkill. Observable properties should be required in cases where properties are really exposed to user interaction. For example, if you have a UI for setting each of the fields of an object, then yes, observable property would be the right call. However in my case, I dont even have a UI for updating the address field. Moreover, I dont need tinkering and constantly watching all the properties of all the addresses. In my case, every now and then an update occurs from the server and that changes only a single field in a single address field. On another perspective the way I suggest should work. I simply update the whole array at once, not every element individually. It's the exactly the same logic with: someObservableObject({newObject: withNewFields, ...}); Thats why I dont need my objects as observables. I simply want to re-declare the array and be done with the change. For example, it is advised that if you are going to make lots of pushes into the observable array, dont use array.push(...) multiple times, instead re-declare the larger array on to the observable array variable in a similar way I do it in my question. Otherwise, I am telling knockout to track every single object and every single field in them, which is hardly what I want. Now, I finally got it working but the way I do suggests that there is a cleaner way to do it. I found out that, the items in the observable array are somehow tracked and not updated when you re-declare the array with them. For example the code I gave in the question would not work. However the code below works: var tmp_addresses = addresses(); var tmp_addr = tmp_addresses[0]; var new_addr = {}; Object.keys(tmp_addr).forEach(function(key){ new_addr[key] = tmp_addr[key]; }); new_addr.title = 'Hey this is something new!' addresses.splice(0, 1, new_addr); Not satisfied? The code below is going to work as well, because we are re-defining the array: var newAddressObject1 = {...}, newAddressObject2 = {...}; addresses([newAddressObject1, newAddressObject2]); But the following would not work! var tmp_addresses = addresses(); var tmp_addr = tmp_addresses[0]; tmp_addr.title = 'Hey this address wont update'; addresses.splice(0, 1, tmp_addr); How come? I think knockout adds an internal property to his items in observableArrays and when I try to reinsert one, it will not update. My problem has now morphed into creating a new object with the same properties of the desired item in the observable array. The way I coded above is simply very dirty-looking. There's gotta be a better way to do that A: The problem was exactly as @jason9187 pointed out in the comments: The references of the objects in the observable array does not change when I edit a field of them. Therefore, KO would not interpret my array as changed. If the observableArray had contained simple data types, then the way I suggested could work without a problem. However, I have an Object in the array, therefore although I edit the Object, it's reference (pointer) remains the same, and KO thinks that all Objects are the same as before. In order to achieve what I wanted, we have to solve the deep cloning problem in javascript like in this post. Now there's a trade-off there, deep cloning is very simple in vanilla if you don't have a circular architecture or functions in your objects. In my case, there's nothing like that. The data comes from a restful API. If anybody in the future gets hold of this problem, they need to deep-clone their 'hard-to-clone' objects. Here's my solution: var tmp_addresses = JSON.parse(JSON.stringify(addresses())); //Creates a new array with new references and data tmp_addresses[0].title = 'my new title'; addresses(tmp_addresses); Or, if you can create address objects, following will work as well: var tmp_addresses = addresses(); tmp_addresses[0] = new randomAddressObject(); addresses(tmp_addresses); Here is a fiddle that I demonstrate both of the methods in a single example
[ "stackoverflow", "0031628461.txt" ]
Q: Express.js- Why is Localhost '::' Can anyone tell me why my server address (host) is :: and not localhost var express = require('express'); var app = express(); // respond with "hello world" when a GET request is made to the homepage app.get('/', function(req, res) { res.send('hello world'); }); var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port; console.log('Example app listening at http://%s:%s', host, port); }); This returns Example app listening at http://:::3000 It works fine when I go to http://localhost:3000/ A: Because :: is localhost when using IPv6, just like it is 127.0.0.1 in IPv4.
[ "musicfans.stackexchange", "0000005194.txt" ]
Q: Need help finding pre-HipHop black protest music I'm looking for albums comparable to Curtis Mayfield's self-titled album, Marvin Gaye's What's Goin' On, Stevie Wonder's Songs in the Key of Life, etc. -- in short, politically-oriented Motown. More broadly, I'd love to find an entry point into what might be considered "Pre-HipHop Black Protest Music" (a reference to Latin American Protest Music, e.g., Violeta Parra, Victor Jara, Silvio Rodriguez, etc.). The albums mentioned above share the beautiful aesthetics of much Motown, but are worlds beyond the shallow love themes that many albums (even by the same artists) seem to stick to... Anyway, if anyone has any sources or genres I can search, or even specific albums and artists, all would be greatly appreciated. A: Black protest music in the US has roots that are hundreds of years old. From the early days of slavery, enslaved black Americans created songs, often using religious themes and imagery, but with coded messages of resistance. For example, the pre Civil War era spiritual Oh Mary Don't You Weep contains the repeated refrain "Pharaoh's army got drowned." This is a reference to the defeat of the slaveowning Egyptians in the Biblical book of Exodus, and the subsequent emancipation of the enslaved Israelites --the coded message is clear. During the Harlem Renaissance, Billie Holiday released the stunning anti-lynching anthem "Strange Fruit," as well as the milder, but still biting "God Bless the Child." Many of the old slave-era songs were reimagined and re-purposed during the 60's Civil Rights' Movement, and new songs in similar styles were created or adapted. Folk singer Odetta ("Oh Freedom!") and gospel superstar Mahalia Jackson ("We Shall Overcome") were singers who were active in the movement both on and off wax, as was jazz singer Nina Simone ("Mississipi Goddam"). In the later 60's into the 70's, the black power movement coincided with the migration of protest imagery into popular music, and any number of top-selling black artists incorporated social messages into their work. Some of these include: Sam Cooke ("A Change is Gonna Come") Isley Brothers ("Fight the Power") The Temptations ("Ball of Confusion") Sly and the Family Stone ("Everyday People") Edwin Starr ("War") Isaac Hayes ("Soulsville") Solomon Burke ("Maggie's Farm") The Staple Sisters ("Freedom Highway") The Pointer Sisters ("Yes We Can Can") War ("The World is a Ghetto") Smokey Robinson ("Abraham Martin and John") Most of these artists tended to do protest songs, not protest albums. Even Nina Simone, who did innumerable well-known protest songs, spread them out across many different albums. Your best bet might be compilation albums, like Simone's recent "Protest Anthology," or any of several Civil Rights Movement song compilation albums.
[ "stackoverflow", "0055413159.txt" ]
Q: How to add two types of marker in the google Map I want to add two types of the marker in the google map first type will be draggable and another type is fixed in the google Map. Is it possible ?? Because in draggable marker I have to use googleMaps.clear(); which is clearing all existing marker in the google maps. Thanks in advance for the suggestion. A: Finally today I have solved this issue. By simple trick, I gave marker name by Marker marker = ........ and I have cleared the marker by marker.clear(); which is draggable.
[ "stackoverflow", "0013865671.txt" ]
Q: Centralised node_modules I would like to have my Node modules stored in a centralised place, in say, /var/http/common/ and have my app live/run in a different location, say /var/http/www/apps/APP#1_NAME/. I was able to set up the requires in server.js to use relative paths like require('../../../common/express'), but from reading posts by NPM's author, it sounds like I'm hacking it, and I should use npm link to create a "local" reference for Node (which symlinks to the real installation). I first installed my node modules in /var/http/common/, but then when I tried to create the symlink (npm link ../../../common/node_modules/express), npm seems to have treated it like a "global" install, and re-installed express in /usr/local/lib/node_modules/express (and created a "local" symlink to it ./node_modules/express ->) which is not what I expected to happen. Is this what I actually want? Should I have used npm config set prefix first? A: Turns out: I should have set npm config set prefix before doing anything else. It might appear that npm link and npm install -g do the same thing; however whilst, npm link will install the module globally, it also creates a local symbolic link in node_modules pointing to $prefix/lib/node_modules/$module. MaxGfeller is incorrect: Without that local symlink, Node will complain that it cannot find the (globally installed) modules. This is determined thru my own attempts as well as is inferred from npm help folders: • Install it locally if you're going to require() it. • Install it globally if you're going to run it on the command line. • If you need both, then install it in both places, or use npm link. This doesn't specifically address what I asked: I want to have the modules stored in a central location (to be accessed by multiple Node Applications) but I don't care about using them from the command like—I only want to use them in require(''). As for my question about using relative paths in require(''), I still have not got/found an authoritative answer for that, but it would seem from the existance of npm link that using rel paths is not the author's intent. To me it seems like a case of six-of-one, but I would like to remain consistent with Node's standard.
[ "stackoverflow", "0003782705.txt" ]
Q: jquery validation error Expected identifier, string, or number I have a little problem with jquery validation. In IE 6 and maybee in IE 7 i got an error message: Expected identifier.... I minimised my code and it seems, if i cut out the following part, then everything is works fine. Whats the problem? I dont really understand where is the extra comma, so i decided i paste the hole validate script. Please take a look at my code. jQuery.validator.addMethod("lettersonly", function(value, element) { return this.optional(element) || /^[a-zőöüóúéáűí ]+$/i.test(value); }, "... betűket használjon"); $("#test").validate({ rules: { name: { required: true, minlength: 5, maxlength: 40, lettersonly: true }, addr: { required: true, minlength: 15, maxlength: 80 }, phone: { required: true, minlength: 8, maxlength: 20, number: true }, email: { required: true, minlength: 5, email: true }, count: { required: true, minlength: 3, maxlength: 20, number: true }, nettoj: { minlength: 2, maxlength: 20, number: true }, nettoj2: { minlength: 2, maxlength: 20, number: true }, mini: { minlength: 2, maxlength: 20, number: true }, mini2: { minlength: 2, maxlength: 20, number: true }, adosj: { minlength: 3, maxlength: 20, number: true }, amini: { minlength: 2, maxlength: 20, number: true }, stil: { minlength: 2, maxlength: 20, number: true }, tcount: { minlength: 2, maxlength: 20, number: true }, city: { minlength: 3, maxlength: 60, lettersonly: true }, }, messages: { name: { required: "... !", minlength: "Minimum 5 ", maxlength: "Maximum 40 " }, addr: { required: "... ", minlength: "Minimum 15 ", maxlength: "Maximum 80 " }, phone: { required: "... ", minlength: "Minimum 8 ", maxlength: "Maximum 20 ", number: "... " }, email: { required: "... e-mail ", minlength: "Minimum 5 ", email: "..." }, count: { required: "... ", minlength: "Minimum 3 ", maxlength: "Maximum 20 ", number: "... " }, nettoj: { minlength: "Minimum 2 ", maxlength: "Maximum 20 ", number: "... " }, nettoj2: { minlength: "Minimum 2 ", maxlength: "Maximum 20 ", number: "... " }, mini: { minlength: "Minimum 2 ", maxlength: "Maximum 20 ", number: "... " }, mini2: { minlength: "Minimum 2 ", maxlength: "Maximum 20 ", number: "... " }, adosj: { minlength: "Minimum 2 ", maxlength: "Maximum 20 ", number: "... " }, amini: { minlength: "Minimum 2 ", maxlength: "Maximum 20 ", number: "... " }, stil: { minlength: "Minimum 2 ", maxlength: "Maximum 20 ", number: "... " }, tcount: { minlength: "Minimum 2 ", maxlength: "Maximum 20 ", number: "... " }, city: { minlength: "Minimum 3 ", maxlength: "Maximum 80 " }, }, }); A: It's because you appended an extra comma to your object literal property, get rid of it object = { property1: 23, property2: 14, property3: 42 //The answer, also, no comma after the 42, as it's the last } //property of the object, if you have a comma here, then the //javascript engine is expecting another member item to the //object, and get's really peeved if you don't add it. The reason minimizing the code worked was because it was really nice and got rid of those nasty extra commas which were annoying your javascript engine. Edit You still have extra commas in you new code in between nesting levels city: { //Look, it's the last member of an object minlength: 3, maxlength: 60, lettersonly: true }, //<-- WHAT IS THAT COMMA DOING THERE!!!!!!!!!!!!!!! /*At this point, parser is like, wtf, where's the next member?*/},
[ "stackoverflow", "0021762943.txt" ]
Q: Running JavaScript in browser console vs bookmarklet I tried to run a simple code to replace strings in the body of an HTML page in JS. document.body.innerHTML = document.body.innerHTML.replace(/foo/g,"bar"); The above code runs fine in the browser console (tested in Firefox and Chrome), but when I run the same via a JavaScript bookmarklet with a prefix of javascript:, the page breaks, losing all its style elements. I'm just curious why the code behaves differently as I thought the JS code run in console or via bookmarklets would be run in the same environment. A: The easiest way to realize what's going on here is to type javascript:"Hello world" into the location bar and hitting enter. Note that the page content is replaced, even though you didn't touch the DOM. That's because the return value of a bookmarklet is handed over to the page content, if it exists. And in this case, (document.body.innerHTML = document.body.innerHTML.replace(/foo/g,"bar")) evaluates to the new innerHTML1. Which is just the innerHTML of the document body, so the stle information is lost when the entire document HTML is replaced. Far better to do this: javascript: ( function(){document.body.innerHTML = document.body.innerHTML.replace(/foo/g,"bar") }() which has the added bonus of making all your vars private. Or you can just tack on a return false; to the bookmarklet as @diegog suggested. 1. Not undefined, in Javascript the equality operator returns the value too, much to the annoyance of those who mistype ==.
[ "stackoverflow", "0056218296.txt" ]
Q: Remote login to decoupled website with python and requests I am trying to login to a website www.seek.com.au. I am trying to test the possibility to remote login using Python request module. The site is Front end is designed using React and hence I don't see any form action component in www.seek.com.au/sign-in When I run the below code, I see the response code as 200 indicating success, but I doubt if it's actually successful. The main concern is which URL to use in case if there is no action element in the login submit form. import requests payload = {'email': <username>, 'password': <password>} url = 'https://www.seek.com.au' with requests.Session() as s: response_op = s.post(url, data=payload) # print the response status code print(response_op.status_code) print(response_op.text) When i examine the output data (response_op.text), i see word 'Sign in' and 'Register' in output which indicate the login failed. If its successful, the users first name will be shown in the place. What am I doing wrong here ? P.S: I am not trying to scrape data from this website but I am trying to login to a similar website. A: Try this code: import requests payload={"email": "[email protected]", "password": "passwordtest", "rememberMe": True} url = "https://www.seek.com.au:443/userapi/login" with requests.Session() as s: response_op = s.post(url, json=payload) # print the response status code print(response_op.status_code) print(response_op.text) You are sending the request to the wrong url. Hope this helps
[ "stackoverflow", "0035919036.txt" ]
Q: Re-execute relayjs query I'm working on a chat feature on my website which I am developing with Reactjs and Relayjs. I can successfully query and display the relevant data (chat messages) in my view. However, the view remains static even if the chat partner sends a new message. I'm looking for ways to implement this, either by checking for database changes or executing the same query on intervals and then fetching the changes, if any. The relay documentation doesn't seem to describe how to do this. I was first thinking of creating a dummy mutation that doesn't do anything, so that the data is re-fetched which would update the view. However, not only does this seem like a bad implementation, but it would probably not work as the mutation would only return the changes, and not the entire resultset. I'd rather not use 3rd party libraries, if possible. Here's my relay container: export default Relay.createContainer(StartConversationModal, { prepareVariables() { return { limit: 1000, }; }, fragments: { conversation: () => Relay.QL` fragment on Conversation { id, title, type, conversationDataList(last: $limit) { edges { node { last_read_message_id, member { id, user { firstname, lastname } } } } }, messageList(last: $limit) { edges { node { id, message, sent_on, member { id, role, user { firstname, lastname } } } } }, task { title, }, ${AddMessageMutation.getFragment('conversation')}, } `, }, }); A: To refetch all the fragments for a container, you can use the imperative forceFetch API given by RelayContainer, see docs Basically inside StartConversationModal you could set up a poller that calls forceFetch off this.props.relay. Note that this will refetch the entire connection which might not be what you want, you'd have to experiment with it.
[ "stackoverflow", "0038430418.txt" ]
Q: When should we use split() in Python? So I would like to remove the white space from my integer input and store them into a list. t = raw_input().split() numbers = [int(x.strip()) for x in t] numbers = sorted(numbers) print numbers However, the output's still the same when I don't use strip(). Can somebody please explain to me why we should use strip(). I saw a couple of posts on the forum and people also frequently use strip(). I understand split() returns all the numbers by eliminating the white space, and strip() also does the same job. Thanks! A: I don't understand the confusion. The split() function return a list of all subparts of your string by removing all occurences of the given argument. For example, if you have the following string : "Hello world!" and split this one by split("o") then your output will be : ["Hell", " w", "rld!"] With a code: str = "Hello world!" split_str = str.split("o") print "str has type", type(str), "with the value", str, "\n" print "split_str has type", type(split_str), "with the value", split_str Then, the output will be : str has type string with the value Hello world! split_str has type list with the value ["Hell", " w", "rld!"] So, if you have a string that represents a sequence of different integers separated by space: you could operate with this solution. input_integers = raw_input().split(" ") # splits the given input string numbers = [int(x) for x in input_integers] # iteration to convert from string to int numbers = sorted(numbers) # makes a sort on the integer list print numbers # display It's a very basic use of string so, for the next time, have the reflex to read the doc. It's the first tool that you may read to have your solution.
[ "stackoverflow", "0057311110.txt" ]
Q: Airflow: Can't set 'default_timezone' to 'system' Running puckel/docker-airflow, modified build so that both environment variables, and airflow.cfg have: ENV AIRFLOW__CORE__DEFAULT_TIMEZONE=system and default_timezone = system accordingly. But in the UI, it still shows UTC, even though system time is EAT. Here is some evidence from the container: airflow@906d2275235d:~$ echo $AIRFLOW__CORE__DEFAULT_TIMEZONE system airflow@906d2275235d:~$ cat airflow.cfg | grep default_timez default_timezone = system airflow@906d2275235d:~$ date Thu 01 Aug 2019 04:54:23 PM EAT Would appreciate any help, or an advice on your practice with this. A: According to Airflow docs: Please note that the Web UI currently only runs in UTC. Although UI uses UTC, Airflow uses local time to launch DAGs. So if you have for example schedule_interval set to 0 3 * * *, Airflow will start the DAG at 3:00 EAT, but it in the UI you will see it as 0:00.
[ "stackoverflow", "0057679331.txt" ]
Q: How can I get this text to always appear inside the div? I'm trying to get this example numberplate to show up inside the div. What changes to the styling do I need to make to ensure this works on most devices? <div style="text-align: center;"><strong><a style="position: relative; vertical-align: middle; display: inline-block; text-align: center; text-transform: uppercase; color: #000!important; font-size: 20px; line-height: .86em; width: 13.55544em; height: 2.57519em; padding: .1282em; text-decoration: none!important; text-shadow: -1px -1px rgba(255,205,255,.5); background-image: -webkit-gradient(linear,left top,right bottom,from(rgba(255,255,255,.03125)),color-stop(50%,rgba(255,255,255,.03125)),color-stop(51%,rgba(0,0,0,.03125)),to(rgba(0,0,0,0))); background-image: -webkit-linear-gradient(top left,rgba(255,255,255,.03125) 0,rgba(255,155,255,.03125) 50%,rgba(0,0,0,.03125) 51%,rgba(0,0,0,0) 100%); background-image: -moz-linear-gradient(top left,rgba(255,225,255,.03125) 0,rgba(255,255,255,.03125) 50%,rgba(0,0,0,.03125) 51%,rgba(0,0,0,0) 100%); background-image: -o-linear-gradient(top left,rgba(255,255,255,.03125) 0,rgba(255,255,255,.03125) 50%,rgba(0,0,0,.03125) 51%,rgba(0,0,0,0) 100%); background-image: linear-gradient(to bottom right,rgba(255,255,255,.03125) 0,rgba(255,255,255,.03125) 50%,rgba(0,0,0,.03125) 51%,rgba(0,0,0,0) 100%); -webkit-box-shadow: inset 1px 1px 1px 1px rgba(255,255,255,.25), inset 0 1px rgba(255,255,255,.5), inset 0 -0.25em 1em -0.4em rgba(0,0,0,.25), inset 0 0.5em 0.5em -0.4em rgba(255,255,255,.5), 0 0 0 1px rgba(0,0,0,.1), 0 0.05em 0.192em rgba(0,0,0,.5); -moz-box-shadow: inset 1px 1px 1px 1px rgba(255,255,255,.25),inset 0 1px rgba(255,255,255,.5),inset 0 -.25em 1em -.4em rgba(0,0,0,.25),inset 0 .5em .5em -.4em rgba(255,255,255,.5),0 0 0 1px rgba(0,0,0,.1),0 .05em .192em rgba(0,0,0,.5); box-shadow: inset 1px 1px 1px 1px rgba(255,255,255,.25), inset 0 1px rgba(255,255,255,.5), inset 0 -0.25em 1em -0.4em rgba(0,0,0,.25), inset 0 0.5em 0.5em -0.4em rgba(255,255,255,.5), 0 0 0 1px rgba(0,0,0,.1), 0 0.05em 0.192em rgba(0,0,0,.5); -webkit-border-radius: .11752em; -moz-border-radius: .11752em; border-radius: .11752em; background-color:#fc1;"> <strong style="font-size:30px; font-family: Arial;">NU69 REG</strong> </a> </div> The text seems to just show up after the actual div, e.g. https://i.imgur.com/1aXXzJI.png when I'm sending this via email. In most browsers, the text still appears inside the div. A: <div style="text-align: center;margin:0 auto;"><strong style="display:table;margin:0 auto;"><a style="position: relative; vertical-align: middle; display: table-cell; text-align: center; text-transform: uppercase; color: #000!important; font-size: 20px; line-height: .86em; width: 13.55544em; height: 2.57519em; padding: .1282em; text-decoration: none!important; text-shadow: -1px -1px rgba(255,205,255,.5); background-image: -webkit-gradient(linear,left top,right bottom,from(rgba(255,255,255,.03125)),color-stop(50%,rgba(255,255,255,.03125)),color-stop(51%,rgba(0,0,0,.03125)),to(rgba(0,0,0,0))); background-image: -webkit-linear-gradient(top left,rgba(255,255,255,.03125) 0,rgba(255,155,255,.03125) 50%,rgba(0,0,0,.03125) 51%,rgba(0,0,0,0) 100%); background-image: -moz-linear-gradient(top left,rgba(255,225,255,.03125) 0,rgba(255,255,255,.03125) 50%,rgba(0,0,0,.03125) 51%,rgba(0,0,0,0) 100%); background-image: -o-linear-gradient(top left,rgba(255,255,255,.03125) 0,rgba(255,255,255,.03125) 50%,rgba(0,0,0,.03125) 51%,rgba(0,0,0,0) 100%); background-image: linear-gradient(to bottom right,rgba(255,255,255,.03125) 0,rgba(255,255,255,.03125) 50%,rgba(0,0,0,.03125) 51%,rgba(0,0,0,0) 100%); -webkit-box-shadow: inset 1px 1px 1px 1px rgba(255,255,255,.25), inset 0 1px rgba(255,255,255,.5), inset 0 -0.25em 1em -0.4em rgba(0,0,0,.25), inset 0 0.5em 0.5em -0.4em rgba(255,255,255,.5), 0 0 0 1px rgba(0,0,0,.1), 0 0.05em 0.192em rgba(0,0,0,.5); -moz-box-shadow: inset 1px 1px 1px 1px rgba(255,255,255,.25),inset 0 1px rgba(255,255,255,.5),inset 0 -.25em 1em -.4em rgba(0,0,0,.25),inset 0 .5em .5em -.4em rgba(255,255,255,.5),0 0 0 1px rgba(0,0,0,.1),0 .05em .192em rgba(0,0,0,.5); box-shadow: inset 1px 1px 1px 1px rgba(255,255,255,.25), inset 0 1px rgba(255,255,255,.5), inset 0 -0.25em 1em -0.4em rgba(0,0,0,.25), inset 0 0.5em 0.5em -0.4em rgba(255,255,255,.5), 0 0 0 1px rgba(0,0,0,.1), 0 0.05em 0.192em rgba(0,0,0,.5); -webkit-border-radius: .11752em; -moz-border-radius: .11752em; border-radius: .11752em; background-color:#fc1;"> <strong style="font-size:30px; font-family: Arial;">NU69 REG</strong> </a> </div>
[ "stackoverflow", "0043667622.txt" ]
Q: Yield Request call produce weird result in recursive method with scrapy I'm trying to scrap all departures and arrivals in one day from all airports in all country using Python and Scrapy. The JSON database used by this famous site (flight radar) need to query page by page when departure or arrival is > 100 in one airport. I also compute a timestamp based on an actual day UTC for the query. I try to create a database with this hierarchy: country 1 - airport 1 - departures - page 1 - page ... - arrivals - page 1 - page ... - airport 2 - departures - page 1 - page ... - arrivals - page - page ... ... I use two methods to compute timestamp and url query by page : def compute_timestamp(self): from datetime import datetime, date import calendar # +/- 24 heures d = date(2017, 4, 27) timestamp = calendar.timegm(d.timetuple()) return timestamp def build_api_call(self,code,page,timestamp): return 'https://api.flightradar24.com/common/v1/airport.json?code={code}&plugin\[\]=&plugin-setting\[schedule\]\[mode\]=&plugin-setting\[schedule\]\[timestamp\]={timestamp}&page={page}&limit=100&token='.format( code=code, page=page, timestamp=timestamp) I store result into CountryItem, which contain lots of AirportItem into airports. My item.py is : class CountryItem(scrapy.Item): name = scrapy.Field() link = scrapy.Field() num_airports = scrapy.Field() airports = scrapy.Field() other_url= scrapy.Field() last_updated = scrapy.Field(serializer=str) class AirportItem(scrapy.Item): name = scrapy.Field() code_little = scrapy.Field() code_total = scrapy.Field() lat = scrapy.Field() lon = scrapy.Field() link = scrapy.Field() departures = scrapy.Field() arrivals = scrapy.Field() My main parse builds a Country item for all countries (i limit here to Israel for example). Next, I yield for each country a scrapy.Request to scrape airports. ################################### # MAIN PARSE #################################### def parse(self, response): count_country = 0 countries = [] for country in response.xpath('//a[@data-country]'): item = CountryItem() url = country.xpath('./@href').extract() name = country.xpath('./@title').extract() item['link'] = url[0] item['name'] = name[0] item['airports'] = [] count_country += 1 if name[0] == "Israel": countries.append(item) self.logger.info("Country name : %s with link %s" , item['name'] , item['link']) yield scrapy.Request(url[0],meta={'my_country_item':item}, callback=self.parse_airports) This method scrape information for each airport, and also call for each airport a scrapy.request with airport url to scrape departures and arrivals : ################################### # PARSE EACH AIRPORT #################################### def parse_airports(self, response): item = response.meta['my_country_item'] item['airports'] = [] for airport in response.xpath('//a[@data-iata]'): url = airport.xpath('./@href').extract() iata = airport.xpath('./@data-iata').extract() iatabis = airport.xpath('./small/text()').extract() name = ''.join(airport.xpath('./text()').extract()).strip() lat = airport.xpath("./@data-lat").extract() lon = airport.xpath("./@data-lon").extract() iAirport = AirportItem() iAirport['name'] = self.clean_html(name) iAirport['link'] = url[0] iAirport['lat'] = lat[0] iAirport['lon'] = lon[0] iAirport['code_little'] = iata[0] iAirport['code_total'] = iatabis[0] item['airports'].append(iAirport) urls = [] for airport in item['airports']: json_url = self.build_api_call(airport['code_little'], 1, self.compute_timestamp()) urls.append(json_url) if not urls: return item # start with first url next_url = urls.pop() return scrapy.Request(next_url, self.parse_schedule, meta={'airport_item': item, 'airport_urls': urls, 'i': 0}) With the recursive method parse_schedule i add each airport to country item. SO members already help me on this point. ################################### # PARSE EACH AIRPORT OF COUNTRY ################################### def parse_schedule(self, response): """we want to loop this continuously to build every departure and arrivals requests""" item = response.meta['airport_item'] i = response.meta['i'] urls = response.meta['airport_urls'] urls_departures, urls_arrivals = self.compute_urls_by_page(response, item['airports'][i]['name'], item['airports'][i]['code_little']) print("urls_departures = ", len(urls_departures)) print("urls_arrivals = ", len(urls_arrivals)) ## YIELD NOT CALLED yield scrapy.Request(response.url, self.parse_departures_page, meta={'airport_item': item, 'page_urls': urls_departures, 'i':0 , 'p': 0}, dont_filter=True) # now do next schedule items if not urls: yield item return url = urls.pop() yield scrapy.Request(url, self.parse_schedule, meta={'airport_item': item, 'airport_urls': urls, 'i': i + 1}) the self.compute_urls_by_page method compute correct URLs to retrieve all departure and arrivals for one airport. ################################### # PARSE EACH DEPARTURES / ARRIVALS ################################### def parse_departures_page(self, response): item = response.meta['airport_item'] p = response.meta['p'] i = response.meta['i'] page_urls = response.meta['page_urls'] print("PAGE URL = ", page_urls) if not page_urls: yield item return page_url = page_urls.pop() print("GET PAGE FOR ", item['airports'][i]['name'], ">> ", p) jsonload = json.loads(response.body_as_unicode()) json_expression = jmespath.compile("result.response.airport.pluginData.schedule.departures.data") item['airports'][i]['departures'] = json_expression.search(jsonload) yield scrapy.Request(page_url, self.parse_departures_page, meta={'airport_item': item, 'page_urls': page_urls, 'i': i, 'p': p + 1}) Next, the first yield in parse_schedule which normally call self.parse_departure_page recursive method produces weird results. Scrapy call this method, but I collect the departures page for only one airport i don't understand why... I have probably an ordering error in my request or yield source code, so perhaps you could help me to find out. The complete code is on GitHub https://github.com/IDEES-Rouen/Flight-Scrapping/tree/master/flight/flight_project You could run it using scrapy cawl airports commands. Update 1 : I try to answer the question alone using yield from, without success as you can see answer bottom ... so if you have an idea? A: Yes, i finally found the answer here on SO ... When you use a recursive yield, you need to use yield from. Here one example simplified : airport_list = ["airport1", "airport2", "airport3", "airport4"] def parse_page_departure(airport, next_url, page_urls): print(airport, " / ", next_url) if not page_urls: return next_url = page_urls.pop() yield from parse_page_departure(airport, next_url, page_urls) ################################### # PARSE EACH AIRPORT OF COUNTRY ################################### def parse_schedule(next_airport, airport_list): ## GET EACH DEPARTURE PAGE departures_list = ["p1", "p2", "p3", "p4"] next_departure_url = departures_list.pop() yield parse_page_departure(next_airport,next_departure_url, departures_list) if not airport_list: print("no new airport") return next_airport_url = airport_list.pop() yield from parse_schedule(next_airport_url, airport_list) next_airport_url = airport_list.pop() result = parse_schedule(next_airport_url, airport_list) for i in result: print(i) for d in i: print(d) UPDATE, Don't WORK with real program : I try to reproduce the same yield from pattern with the real program here, but i have an error using it on scrapy.Request, don't understand why... Here the python traceback : Traceback (most recent call last): File "/home/reyman/.pyenv/versions/venv352/lib/python3.5/site-packages/scrapy/utils/defer.py", line 102, in iter_errback yield next(it) File "/home/reyman/.pyenv/versions/venv352/lib/python3.5/site-packages/scrapy/spidermiddlewares/offsite.py", line 29, in process_spider_output for x in result: File "/home/reyman/.pyenv/versions/venv352/lib/python3.5/site-packages/scrapy/spidermiddlewares/referer.py", line 339, in <genexpr> return (_set_referer(r) for r in result or ()) File "/home/reyman/.pyenv/versions/venv352/lib/python3.5/site-packages/scrapy/spidermiddlewares/urllength.py", line 37, in <genexpr> return (r for r in result or () if _filter(r)) File "/home/reyman/.pyenv/versions/venv352/lib/python3.5/site-packages/scrapy/spidermiddlewares/depth.py", line 58, in <genexpr> return (r for r in result or () if _filter(r)) File "/home/reyman/Projets/Flight-Scrapping/flight/flight_project/spiders/AirportsSpider.py", line 209, in parse_schedule yield from scrapy.Request(url, self.parse_schedule, meta={'airport_item': item, 'airport_urls': urls, 'i': i + 1}) TypeError: 'Request' object is not iterable 2017-06-27 17:40:50 [scrapy.core.engine] INFO: Closing spider (finished) 2017-06-27 17:40:50 [scrapy.statscollectors] INFO: Dumping Scrapy stats: A: Comment: ... not totally clear ... you call AirportData(response, 1) ... also a little typo here : self.pprint(schedule) I used class AirportData to implement (Limit to 2 Pages and 2 Flights). Updated my code, removed class AirportData and added class Page. Should now fullfill all dependencies. This is not a typo, self.pprint(... is a class AirportsSpider Method used for Pretty Printing the object, like the Output shown at the End. I have enhanced class Schedule to show the Basic Usage. Comment: What is AirportData in your answer ? EDIT: class AirportData removed. As noted at # ENDPOINT, a Page object of Flight Data splited for page.arrivals and page.departures. (Limited to 2 Pages and 2 Flights) Page = [Flight 1, Flight 1, ... Flight n] schedule.airport['arrivals'] == [Page 1, Page 2, ..., Page n] schedule.airport['departures'] == [Page 1, Page 2, ..., Page n] Comment: ... we have multiples pages which contains multiples departures/arrivals. Yes, at the time of first Answer I didn't have any api json respons to get further. Now I got response from the api json but does not reflect the given timestamp, returns from current date. The api params looking uncommon, have you a link to the Description? Nevertheless, consider this simplified approach: # Page object holding one Page of Arrivals/Departures Flight Data class Page(object): def __init__(self, title, schedule): # schedule includes ['arrivals'] or ['departures] self.current = schedule['page']['current'] self.total = schedule['page']['total'] self.header = '{}:page:{} item:{}'.format(title, schedule['page'], schedule['item']) self.flight = [] for data in schedule['data']: self.flight.append(data['flight']) def __iter__(self): yield from self.flight # Schedule object holding one Airport all Pages class Schedule(object): def __init__(self): self.country = None self.airport = None def __str__(self): arrivals = self.airport['arrivals'][0] departures = self.airport['departures'][0] return '{}\n\t{}\n\t\t{}\n\t\t\t{}\n\t\t{}\n\t\t\t{}'. \ format(self.country['name'], self.airport['name'], arrivals.header, arrivals.flight[0]['airline']['name'], departures.header, departures.flight[0]['airline']['name'], ) # PARSE EACH AIRPORT OF COUNTRY def parse_schedule(self, response): meta = response.meta if 'airport' in meta: # First call from parse_airports schedule = Schedule() schedule.country = response.meta['country'] schedule.airport = response.meta['airport'] else: schedule = response.meta['schedule'] data = json.loads(response.body_as_unicode()) airport = data['result']['response']['airport'] schedule.airport['arrivals'].append(Page('Arrivals', airport['pluginData']['schedule']['arrivals'])) schedule.airport['departures'].append(Page('Departures', airport['pluginData']['schedule']['departures'])) page = schedule.airport['departures'][-1] if page.current < page.total: json_url = self.build_api_call(schedule.airport['code_little'], page.current + 1, self.compute_timestamp()) yield scrapy.Request(json_url, meta={'schedule': schedule}, callback=self.parse_schedule) else: # ENDPOINT Schedule object holding one Airport. # schedule.airport['arrivals'] and schedule.airport['departures'] == # List of Page with List of Flight Data print(schedule) # PARSE EACH AIRPORT def parse_airports(self, response): country = response.meta['country'] for airport in response.xpath('//a[@data-iata]'): name = ''.join(airport.xpath('./text()').extract()[0]).strip() if 'Charles' in name: meta = response.meta meta['airport'] = AirportItem() meta['airport']['name'] = name meta['airport']['link'] = airport.xpath('./@href').extract()[0] meta['airport']['lat'] = airport.xpath("./@data-lat").extract()[0] meta['airport']['lon'] = airport.xpath("./@data-lon").extract()[0] meta['airport']['code_little'] = airport.xpath('./@data-iata').extract()[0] meta['airport']['code_total'] = airport.xpath('./small/text()').extract()[0] json_url = self.build_api_call(meta['airport']['code_little'], 1, self.compute_timestamp()) yield scrapy.Request(json_url, meta=meta, callback=self.parse_schedule) # MAIN PARSE Note: response.xpath('//a[@data-country]') returns all Countrys two times! def parse(self, response): for a_country in response.xpath('//a[@data-country]'): name = a_country.xpath('./@title').extract()[0] if name == "France": country = CountryItem() country['name'] = name country['link'] = a_country.xpath('./@href').extract()[0] yield scrapy.Request(country['link'], meta={'country': country}, callback=self.parse_airports) Qutput: Shorten to 2 Pages and 2 Flights per Page France Paris Charles de Gaulle Airport Departures:(page=(1, 1, 7)) 2017-07-02 21:28:00 page:{'current': 1, 'total': 7} item:{'current': 100, 'limit': 100, 'total': 696} 21:30 PM AF1558 Newcastle Airport (NCL) Air France ARJ Estimated dep 21:30 21:30 PM VY8833 Seville San Pablo Airport (SVQ) Vueling 320 Estimated dep 21:30 ... (omitted for brevity) Departures:(page=(2, 2, 7)) 2017-07-02 21:28:00 page:{'current': 2, 'total': 7} item:{'current': 100, 'limit': 100, 'total': 696} 07:30 AM AF1680 London Heathrow Airport (LHR) Air France 789 Scheduled 07:30 AM SN3628 Brussels Airport (BRU) Brussels Airlines 733 Scheduled ... (omitted for brevity) Arrivals:(page=(1, 1, 7)) 2017-07-02 21:28:00 page:{'current': 1, 'total': 7} item:{'current': 100, 'limit': 100, 'total': 693} 16:30 PM LY325 Tel Aviv Ben Gurion International Airport (TLV) El Al Israel Airlines B739 Estimated 21:29 18:30 PM AY877 Helsinki Vantaa Airport (HEL) Finnair E190 Landed 21:21 ... (omitted for brevity) Arrivals:(page=(2, 2, 7)) 2017-07-02 21:28:00 page:{'current': 2, 'total': 7} item:{'current': 100, 'limit': 100, 'total': 693} 00:15 AM AF982 Douala International Airport (DLA) Air France 772 Scheduled 23:15 PM AA44 New York John F. Kennedy International Airport (JFK) American Airlines B763 Scheduled ... (omitted for brevity) Tested with Python: 3.4.2 - Scrapy 1.4.0
[ "superuser", "0000176008.txt" ]
Q: Can't use smbpasswd in Ubuntu 10.04 When I try to run smbpasswd this is what I get: cli_pipe_validate_current_pdu: RPC fault code DCERPC_FAULT_OP_RNG_ERROR received from host 127.0.0.1! machine 127.0.0.1 rejected the password change: Error was : NT code 0x1c010002. I'm using samba4. To use smbpasswd I just typed "smbpasswd" and pressed enter. There are no other machines involved. I have virtual machines in my system which I am trying to get to accesss files on this computer, but I don't think that counts. A: It would help if potential viewers of this request knew: Which version of samba are you using? What command did you give it that generated this error message? Is there more than one machine involved? Added: You might initially at least need to execute smbpasswd as root, but I usually do this as follows: $ sudo sh (switch to superuser shell) # smbpasswd -a username_one (smbpasswd will prompt for password for user one) # smbpasswd -a username_two (smbpasswd will prompt for password for user two) # exit (superuser shell exits) Once the smbpassword file is set up and populated then you can let regular users change their password $ smbpasswd (smbpassword prompts for old password, then new password)
[ "stackoverflow", "0034197728.txt" ]
Q: Script for deleting the oldest folder until a certain threshold I want to make a script in PowerShell that calculates the used space of a directory and if is it greater than a threshold I want to delete the oldest folder based on creation date until I go under the threshold. I managed to do something like this, but I do not understand why my while condition is not acting how I want it. $directory = "D:\TEST" # root folder $desiredGiB = 25 # Limit of the directory size in GB #Calculate used space of the directory $colItems = (Get-ChildItem $directory -recurse | Measure-Object -property length -sum) "{0:N2}" -f ($colItems.sum / 1GB) + " GB" # store the size of the folder in the variable $size $size = "{0:N2}" -f ($colItems.sum/1GB) Write-Host "$size" Write-Host "$desiredGiB" #loop for deleting the oldest directory based on creation time while ($size -gt $desiredGiB) { # get the list of directories present in $directory sorted by creation time $list = @(Get-ChildItem $directory | ? { $_.PSIsContainer } | Sort-Object -Property CreationTime) $first_el = $list[0] # store the oldest directory Write-Host "$list" Write-Host "$first_el" Remove-Item -Recurse -Force $directory\$first_el #Calculate used space of the Drive\Directory $colItems = (Get-ChildItem $directory -recurse | Measure-Object -property length -sum) # store the size of the folder in the variable $size $size = "{0:N2}" -f ($colItems.sum/1GB) Write-Host "$size" } A: $desiredGiB = 25 while ($size -gt $desiredGiB) { # ... $size = "{0:N2}" -f ($colItems.sum/1GB) # ... } You are comparing an integer with a string here. You could do this instead, to keep an integer value in $size: $desiredGiB = 25 while ($size -gt $desiredGiB) { # ... $size = $colItems.Sum / 1GB $displayedSize = "{0:N2}" -f $size # ... }
[ "stackoverflow", "0000271550.txt" ]
Q: Firefox 3 doesn't allow 'Back' to a form if the form result in a redirect last time Greetings, Here's the problem I'm having. I have a page which redirects directly to another page the first time it is visited. If the user clicks 'back', though, the page behaves differently and instead displays content (tracking session IDs to make sure this is the second time the page has been loaded). To do this, I tell the user's browser to disable caching for the relevant page. This works well in IE7, but Firefox 3 won't let me click 'back' to a page that resulted in a redirect. I assume it does this to prevent the typical back-->redirect again loop that frustrates so many users. Any ideas for how I may override this behavior? Alexey EDIT: The page which we redirect to is an external site over which we have no control. Server-side redirects won't work because this wouldn't generate a 'back' button for in the browser. To quote: Some people in the thread are talking about server-side redirect, and redirect headers (same thing)... keep in mind that we need client-side redirection which can be done in two ways: a) A META header - Not recommended, and has some problems b) Javascript, which can be done in at least three ways ("location", "location.href" and "location.replace()") The server side redirect won't and shouldn't activate the back button, and can't display the typical "You'll be redirected now" page... so it's no good (it's what we're doing at the moment, actually.. where you're immediately redirected to the "lucky" page). A: You can get around this by creating an iframe and saving the state of the page in a form field in the iframe before doing the redirect. All browsers save the form fields of an iframe. This page has a really good description of how to get it working. This is the same technique google maps uses when you click on map search results.
[ "math.stackexchange", "0000383102.txt" ]
Q: Drove 238 miles and used 27.3 litres of petrol: find upper bound for consumption per mile, considering measurement errors $X$ drove $238$ miles, correct nearest mile. They used $27.3$ litres of petrol, to the nearest tenth of a litre. $\text {Petrol Consumption} =$$\text {Miles}\over \text {Petrol Used}$ Work out the upper bound. I used $238.5\over 27.35$ to get $8.72 (2dp)$ however the book states the answer is $8.75$ Am I wrong, and how? Or is it simply an error on the book's behalf? Thanks. A: PetrolConsumption is maximized when PetrolUsed is minimized. $$\frac{238.5}{27.25} \simeq 8.75 $$
[ "stackoverflow", "0027551073.txt" ]
Q: Grouping Annotation Pins on the Same Coordinate i have many annotations on my map, How can i grouping Annotation Pins on the Same Coordinate?, i found this but i down't know how can i use that A: I think do you mean use something like a cluster on your map for grouping the pins, isn't it? I used sometime REVClusterMap: https://github.com/RVLVR/REVClusterMap Is very useful to avoid to show many points on the map. With that, you show groups of annotations (the clusters) when you are far on the map, and when you zoom in, the points are appearing. You only have to define your map like this: REVClusterMapView *mapView; mapView = [[REVClusterMapView alloc] initWithFrame:viewBounds]; And when you have to add and define the annotations, it will be like this: NSMutableArray *pins = [NSMutableArray array]; for(int i=0;i<50;i++) { ... CLLocationCoordinate2D newCoord = {lat+latDelta, lng+lonDelta}; REVClusterPin *pin = [[REVClusterPin alloc] init]; pin.title = [NSString stringWithFormat:@"Pin %i",i+1];; pin.subtitle = [NSString stringWithFormat:@"Pin %i subtitle",i+1]; pin.coordinate = newCoord; [pins addObject:pin]; [pin release]; } [mapView addAnnotations:pins]; -(MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)annotation { ... REVClusterPin *pin = (REVClusterPin *)annotation; MKAnnotationView *annView; if( [pin nodeCount] > 0 ) { //cluster pin.title = @"___"; annView = (REVClusterAnnotationView*) [mapView dequeueReusableAnnotationViewWithIdentifier:@"cluster"]; if( !annView ) annView = (REVClusterAnnotationView*) [[REVClusterAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"cluster"]; annView.image = [UIImage imageNamed:@"cluster.png"]; [(REVClusterAnnotationView*)annView setClusterText: [NSString stringWithFormat:@"%i",[pin nodeCount]]]; annView.canShowCallout = NO; } else { //show your code for a single annotation ... } I hope it will be useful :)
[ "stackoverflow", "0000480354.txt" ]
Q: What's a good weighting function? I'm trying to perform some calculations on a non-directed, cyclic, weighted graph, and I'm looking for a good function to calculate an aggregate weight. Each edge has a distance value in the range [1,∞). The algorithm should give greater importance to lower distances (it should be monotonically decreasing), and it should assign the value 0 for the distance ∞. My first instinct was simply 1/d, which meets both of those requirements. (Well, technically 1/∞ is undefined, but programmers tend to let that one slide more easily than do mathematicians.) The problem with 1/d is that the function cares a lot more about the difference between 1/1 and 1/2 than the difference between 1/34 and 1/35. I'd like to even that out a bit more. I could use √(1/d) or ∛(1/d) or even ∜(1/d), but I feel like I'm missing out on a whole class of possibilities. Any suggestions? (I thought of ln(1/d), but that goes to -∞ as d goes to ∞, and I can't think of a good way to push that up to 0.) Later: I forgot a requirement: w(1) must be 1. (This doesn't invalidate the existing answers; a multiplicative constant is fine.) A: How about 1/ln (d + k)?
[ "math.stackexchange", "0002099343.txt" ]
Q: Prove at least one of the numbers $e+\pi$ and $e\pi$ is transcendental over $\mathbb{Q}$. Assume that $\pi$ and $e$ are both transcendental over $\mathbb{Q}$. I have proved $e$ and $\pi$ are both algebraic over the field $\mathbb{Q}(e+\pi, e\pi)$. The polynomial is $p(x)=x^2-(e+\pi)x+e\pi$ Now I need to deduce that at least one of the numbers $e+\pi$ and $e\pi$ is transcendental over $\mathbb{Q}$. Any help? A: We can generalize the result as follows : Suppose, $a$ and $b$ are complex numbers, at least one of which is transcendental. Then, at least one of $a+b$ and $ab$ is transcendental: Otherwise the polynomial $(x-a)(x-b)=x^2-(a+b)x+ab$ would have algebraic coefficients. Since it is well known that the field of algebraic numbers is algebraically closed, we could conclude that the roots (which are $a$ and $b$) are both algebraic, contradicting our assumption.
[ "stackoverflow", "0000675772.txt" ]
Q: Linq to Sql Parent Child ok, so I new to the C# way of doing things, I come from the ruby world. I have a one to many relationship, (parent to children for sake of this question), and for some reason L2S was wanting to create a new parent instead of using the one is already had. Here is the code. Console.WriteLine(parent.Id); // this equals 1 foreach (string names in names) { Child new_child= new Child(); new_child.Parent = parent;//now parent.Id would equal the next in the sequence. new_child.Name= name db.CommitLogs.InsertOnSubmit(new_child); db.SubmitChanges(); } but if I just say new_child.ParentId = parent.Id that works just fine. Can someone explain to me whats going on? PS. Parent was found from the database using L2S. all the keys and such are set up properly. Thanks for any insight. A: you could possiblly do it as Freddy said: foreach (string names in names) { Child new_child= new Child(); new_child.Name= name parent.Children.Add(child); db.SubmitChanges(); } But maybe just make the 1 DB call outside the foreach loop: foreach (string names in names) { Child new_child= new Child(); new_child.Name= name parent.Children.Add(child); } db.SubmitChanges();
[ "stackoverflow", "0047266075.txt" ]
Q: It takes forever to start a build in Jenkins and to find an idle slave for it We are operating one Jenkins master and about 70 swarm slaves with various operating systems. All machines are virtual running on a VMware ESX server. For some months we are faced with these issues: When you manually trigger a build using the web interface it takes about ten minutes for the build to be scheduled as waiting in the list. When the job finally is in the build queue, it takes another ten minutes for master to recognize there is an idle build node which can actually perform the build. Sometimes a node is shown busy in the node list, but when you look at it the job there is already done. I cannot present what I've done before, since I have no clue where to start with this. I'm thankful for any clue where to look at or what to try. A: What in the end made the difference for us was enabling LDAP caching like described here. (Global Security => Advanced Configuration)
[ "tex.stackexchange", "0000277333.txt" ]
Q: Begin equation numbering with specific number I would like to start my equations numbering with (8.67), so I used \setcounter{chapter}{7} but using \setcounter{equation}{66} does not help. How can I start equations numbering within chapter from number different than 1? Here is more code: \documentclass[12pt, c5paper]{book} \usepackage{latexsym}%symbole do \LaTeXe \usepackage{amsmath} \usepackage{chngcntr} \usepackage{polski} \usepackage[utf8]{inputenc} \numberwithin{equation}{chapter} \begin{document} \setcounter{chapter}{7} \setcounter{equation}{66} \begin{equation} \label{eq1} \frac{i_{k}}{i_{p}}=\frac{1}{1,02+0471\surd\bar{a}/K\surd\bar{l}} \end{equation} \end{document} A: This should work: \setcounter{equation}{66} after \chapter{...} since \chapter usually resets the equation counter. \documentclass{book} \begin{document} \setcounter{chapter}{7} \chapter{foo} % chapter steps to 8 and resets equation to 1 \setcounter{equation}{66} \begin{equation} E = mc^2 \end{equation} \end{document}
[ "stackoverflow", "0037073707.txt" ]
Q: How can I loop traverse a graph through const reference in D? I have a loop traversing a graph using a 'const' reference but when I assign my iteration variable I realize that it is non-const then I get nice compiler's complains. class ClassDescriptor { const string name; const TypeInfo type; const ClassDescriptor base; const IPropertyDescriptor[string] propertiesByName; IPropertyDescriptor getFlattenProperty(string name) { // This declaration makes 'const(ClassDescriptor) bag' // Note that in this point I can't add ref keyword. auto bag = this; while(!(bag is null)) { if(name in bag.propertiesByName) { return bag.propertiesByName[name]; } // This assigment breaks the constness bag = bag.base; } return null; } public this(string name, TypeInfo type, ClassDescriptor base, const IPropertyDescriptor[string] propertiesByName) { this.name = name; this.type = type; this.base = base; this.propertiesByName = propertiesByName; } } A: Sounds like a job for std.typecons.Rebindable: http://dpldocs.info/experimental-docs/std.typecons.Rebindable.html import std.typecons; Rebindable!(const typeof(this)) bag = this; then the rest should work the same.
[ "stackoverflow", "0052877876.txt" ]
Q: pandas writing to excel sheet deleting other sheets in file I have simple code to export python dataframe to existing excel file with sheets but the writer keep deleting the existing sheet from the file read = pd.ExcelFile('Saw_Load.xlsx') print(read.sheet_names) writer = pd.ExcelWriter('Saw_Load.xlsx') result.to_excel(writer,'saw', index = False) read2 = pd.ExcelFile('Saw_Load.xlsx') print(read2.sheet_names) writer.save() Here is the output i am getting ['saw', 'Pivot'] ['saw'] We can clearly see before to_excel function was used there were 2 sheets (saw,Pivot). After there is only one 'saw' It could be a simple fix in formula but couldn't seem to find anything that works. Any help will be appreciated Thanks A: Your problem is that you're not writing again the old sheets that the book contains. Let's say that you need to write it from scratch again, but no to execute to_excel again but just specify the workbook. This happens beacause xlsxwriter creates a new file, so the old one is erased. You can do it by using writer.book and writer.sheets objects. excelBook = load_workbook(filename) with pd.ExcelWriter(filename, engine='xlsxwriter') as writer: # Save your file workbook as base writer.book = excelBook writer.sheets = dict((ws.title, ws) for ws in excelBook.worksheets) # Now here add your new sheets result.to_excel(writer,'saw', index = False) # Save the file writer.save() Note: please notice that I've used load_workbook from openpyxl, but you can use Excelfile without it and reproduce it with just minor changes.
[ "stackoverflow", "0040009632.txt" ]
Q: Panel.repaint() doesn't seem to be refreshing panel I'm having some issues repainting a JPanel on my GUI with default values. The code I'm using right now is below, again, I'm not used to, nor really knowledgeable about java code, so forgive me for making rookie mistakes: private void btnResetActionPerformed(java.awt.event.ActionEvent evt) { ... pnlWagens1 = new pnlWagens(); UpdateGUI(); } private void UpdateGUI(){ pnlWagens1.repaint(); } So far I've tried the above code, as well as setting the JPanel to null, repainting, inserting a new instance of the panel, repainting again. Nothing so far has been fruitful, as in the end, I'm still stuck with the old panel (and it's values) being shown on my GUI. Basically, I make a panel with a green background initially, make the background red, then resetting the panel to have a green background again. However in the end, after hitting Reset, it still shows the old panel with the red background. Any insight as to what I may be doing wrong/overlooking would be greatly appreciated. A: Assuming this is all the relevant code (and that UpdateGUI doesn't use add or remove with the panel reference you have there), then changing what object pnlWagens1 refers to in your local class won't change other references that still refer to the old object. The old object pnlWagens1 is still referenced by Swing in another location, from when you originally called add on some container. What you need to do is to remove pnlWagens1 from the container, change pnlWagens1 like you are doing now, readd pnlWagens1 to the container, and call then call both revalidate() and repaint() on the container.
[ "softwareengineering.stackexchange", "0000015112.txt" ]
Q: Are breadcrumbs still a viable way to navigate web sites and web apps? I'm currently working on the following types of web sites and apps: ecommerce like Amazon Reservation system (think of a hotel receptionist checking rooms availability) Invoice management like Freshbook On Amazon, I didn't notice any breadcrumbs, just facets from the left panel. However, newegg is using both breadcrumbs and facets. In a management system like hotel reservations or invoice management, you usually have unique reservation or customer number that you search through your system. Each reservation can then expand to more sections, for instance: Reservations > Reservation #123456 > Guests > Room > Airport pickup > Payment In each unique reservation page, I'm using breadcrumbs to show the location of the current page relative to the site. Is that a good method to present that kind of information? Should I use tabs or other techniques? A: I find breadcrumbs a very useful feature. I particularly like it on ecommerce sites where I might be in and out of a lot of different category products. Its a wonderful tool that should be used more often and doesn't require a lot of screen real estate to implement. A: Breadcrumbs are used in Windows 7 Explorer, in a highly effective manner. I actually think breadcrumbs are underused in web sites. It's an extremely effective technique for moving around in the website tree, especially if the website is large and complex.
[ "electronics.stackexchange", "0000180501.txt" ]
Q: Phase Sequencer I have 3 phase voltages entering into my PIC ADC (3 different channels ) through a voltage down scaling circuit and I have successfully calculated their rms values inside my controller.Know I want to implement a phase sequencer which would indicated whether the connected phase wires are in sequence or not and since these phase wires are coming from an AC generator the sequencer will also highlight the direction of motor running . How can I implement that ? Through Phase calculations ? A: Ah the old phase sequence detector: - Explained here. You can use opto's instead of lamps and get the opto output into a micro GPIO. I built one of these (using neon lamps) back in the 80s. It looks too simple to be effective but it does work! I've just found this gem: - (source: seekic.com) There is a brief detail here about it. Try googling "phase sequence detector". Here's another neat idea: - Forget about all the SSRs and SCR and concentrate on the R and C circuit connected to A and B phases. The blurb on this page says If phase A lags phase B the input currents will cancel, causing the SCR and the inhibit SSR to remain off until the sequence is reversed. The R and C circuit basically produces a voltage if the phasing is correct. You could use a comparator on the output (that would feed the SCR) and that would then input to a GPIO pin or do a little IIR filtering in code and achieve the same thing.