id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_unix.337350 | I added VMware using user# ./VMwarexxxxx.bundleNow I don't know how to uninstall it? I also used the following commands: user# chmod +x VMware-Workstation | How to uninstall apps that added using ./install command? | software installation;uninstall | null |
_webapps.40901 | Is there a way to do a real exact match in Google?Quotes or plus do not make it exact.I'm trying to search for the phrase offset 0, but the results contain offset: 0, which is not the same and not what I'm looking for.I've encountered such a problem with many other queries, too. | Force Google Search to do absolutely exact match | google search | null |
_ai.2920 | I am looking for a solution that I can use with identifying cars.So I have a database with images of cars. About 3-4 per car. What I want to do is upload a picture to the web of car(Picture taken with camera/phone) and then let my pc recognize the car. Example: Lets say I have these 2 pictures in my database(Mazda cx5)(I can only upload 2 links at max. atm. but you get the idea).Now I am going to upload this picture of a mazda cs5 to my web app:Now I want an AI to recognize that this picture is of an Mazda CX5 with greyish color. I have looked on the net and found 2 interesting AI's I can use:Tensorflow and Clarifai, but I don't know if these are going to work so my question to you what would be my best bet to go with here? | Image recognition | image recognition;tensorflow | null |
_unix.290915 | I have to check the log & monitor the I/O output, the log is generated per secondI seems a hard job to monitor the log which get generated every second, I am looking for some awk command which give me only output of that line which exceeds the threshold above 210.00 or decrease below 180.00 Is there a way to get the only output which gets crosses the thresholdSample output:Jun 20, 2016 interval i/o MB/sec bytes read resp read write resp resp queue cpu% cpu% rate 1024**2 i/o pct time resp resp max stddev depth sys+u sys13:28:40.040 6571 190.00 23.75 131072 77.89 80.840 80.827 80.885 90.911 2.783 15.4 0.1 0.113:28:41.041 6572 198.00 24.75 131072 79.29 80.800 80.491 81.984 94.508 2.865 16.0 0.0 0.013:28:42.041 6573 198.00 24.75 131072 85.35 80.803 80.719 81.295 90.176 2.650 16.0 0.0 0.013:28:43.041 6574 198.00 24.75 131072 79.29 80.813 80.789 80.902 92.090 2.687 16.0 0.0 0.013:28:44.041 6575 197.00 24.63 131072 80.20 81.195 81.020 81.905 91.351 3.385 16.0 0.0 0.013:28:45.041 6576 198.00 24.75 131072 85.35 80.805 80.814 80.752 90.865 2.795 16.0 0.0 0.013:28:46.040 6577 198.00 24.75 131072 80.81 80.816 80.733 81.166 94.233 2.946 16.0 0.0 0.013:28:47.040 6578 198.00 24.75 131072 78.28 80.810 80.746 81.042 91.541 2.882 16.0 0.0 0.013:28:48.040 6579 198.00 24.75 131072 79.29 80.784 80.788 80.770 92.255 2.799 16.0 0.1 0.013:28:49.041 6580 197.00 24.63 131072 82.23 80.811 80.637 81.619 94.005 3.311 16.0 0.0 0.013:28:50.041 6581 199.00 24.88 131072 81.41 80.829 80.678 81.489 90.607 2.851 16.0 0.0 0.0 | Setting Threshold on log Output | awk | If you want all lines with column 3 outside your limits then simplyawk '$3>=210 || $3<=180 {print}'If you want just the first such line until the data is back inside the limits then:awk '$3>=210 { if(!hi)print; hi=1; lo=0; next } $3<=180 { if(!lo)print; lo=1; hi=0; next } { hi = 0; lo = 0 }' |
_unix.101160 | The program Boblight does not run in background. There is no noticeable difference between executing sudo boblightdand sudo boblightd& How can I solve this problem that the console will not block further inputs?pi@raspberrypi ~/boblight/boblightd-for-raspberry-master $ sudo boblightdBoblightd 2.0 (optimized version for raspberry) (c) 2013 Speedy1985 and Heven)(InitLog) start of log /root/.boblight/boblightd.log(PrintFlags) starting boblightd(CConfig::LoadConfigFromFile) opening /etc/boblight.conf(CConfig::CheckConfig) checking config lines(CConfig::CheckConfig) config lines valid(CConfig::BuildConfig) building config(CConfig::BuildConfig) built config successfully(main) starting devices(CClientsHandler::Process) opening listening TcpSocket on *:19333(CDevice::Process) ambilight: starting with output /dev/spidev0.0(CDevice::Process) ambilight: setting up(CDevice::Process) ambilight: setup succeededpi@raspberrypi ~/boblight/boblightd-for-raspberry-master $ sudo boblightd&[1] 2289pi@raspberrypi ~/boblight/boblightd-for-raspberry-master $Boblightd 2.0 (optimized version for raspberry) (c) 2013 Speedy1985 and Heven)(InitLog) start of log /root/.boblight/boblightd.log(PrintFlags) starting boblightd(CConfig::LoadConfigFromFile) opening /etc/boblight.conf(CConfig::CheckConfig) checking config lines(CConfig::CheckConfig) config lines valid(CConfig::BuildConfig) building config(CConfig::BuildConfig) built config successfully(main) starting devices(CClientsHandler::Process) opening listening TcpSocket on *:19333(CDevice::Process) ambilight: starting with output /dev/spidev0.0(CDevice::Process) ambilight: setting up(CDevice::Process) ambilight: setup succeeded | How to start a program in the background | shell;sudo;background process | null |
_unix.206467 | I am thinking how you can replace [^\]% marks but not \% marks in the sed -command of this answer. I think look-behind is not necessary. My current Sed command but I think Perl is a must here cat something | sed 's#%.*</#</#' which removes also everything after the % sign i.e. all comments in LaTeX but not percentage values. My unsuccessful Perl attemptcat something | perl 's#[^\]%.*</#</#'where I do not know how I make Perl to take the standard output of cat. Data------------------------------Protocol of pre-eclampsia------------------------------Monitoring in 90\% casesAntihypertensives when % this is a comment, please, remove me!$SBP/DBP > 160/110$; slowly. ------------------------------Desired output------------------------------Protocol of pre-eclampsia------------------------------Monitoring in 90\% casesAntihypertensives when$SBP/DBP > 160/110$; slowly. ------------------------------How can you replace % signs but not \%? If you can do this by Sed, please, comment. | To replace % marks but not \% in Perl Regex | sed;perl | Like many, if not most, text parsing tools, perl can take input from the command line, there's no need for cat. You just need -e which lets you pass a script as a command line parameter and -n which means run the script on each line of input. ALternatively, you can use the -p switch which means run the script on each line of input, then print that line. These two commands are equivalent (but the second is a classic useless use of cat, use the first) :perl -pe 's/foo/bar/' filecat file | perl -pe 's/foo/bar/'Now, if I understand correctly, you want to delete all LaTeX comments (though that's not what your question states). If so, a lookbehind is the easiest way:perl -pe 's/(?<!\\)%.*//' file Your regex should also work, you just need to keep the character you matched before the % and escape the backslash:perl -pe 's/(^|[^\\]+)%.*/$1/' fileYou can do the same thing with GNU sed:sed -r 's/(^|[^\\])%.*/\1/' file |
_datascience.16537 | I am working on detecting text in images using street view dataset(SVT), in this dataset for each image we are given with all the words present in the image and the corresponding bounding box enclosing them. I am stuck up on how to pre process these output labels so that I would be able to train a CNN for detecting text(bounding boxes) in the test image.Should I take in account the particular word in the output label somehow?Please suggest suitable strategy and methodology. Thank you! | Pre processing the training data for detecting multiple bounding boxes for text recognition in wild (Street view text dataset) | deep learning | null |
_codereview.2883 | I wanted to launch a bash script (read: bash not sh script) as a root not as the user calling it, however bash ignore setuid on scripts, so I chose to write a very small script that takes a script/arguments and call it with setuid set.This worked well and I went even further to verify that the script has setuid set on, executable and setuid() called on the owner of the file and not as root, to avoid any misuse of the program and I ended up with the program below.#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/types.h>#include <sys/stat.h>int main(int argc, char **argv){ char *command; int i, file_owner, size = 0; struct stat status_buf; ushort file_mode; // Check argc if (argc < 2) { printf(Usage: %s <script> [arguments]\n, argv[0]); return 1; } // Make sure the script does exist if(fopen(argv[1], r) == NULL) { printf(The file %s does not exist.\n, argv[1]); return 1; } // Get the attributes of the file stat(argv[1], &status_buf); // Get the permissions of the file file_mode = status_buf.st_mode; // Make sure it's executable and it's setuid if(file_mode >> 6 != 567) { printf(The file %s should be executable and should have setuid set, please chmod it 0106755.\n, argv[1]); return 1; } // Get the owner of the script file_owner = status_buf.st_uid; // setuid setuid(file_owner); // Generate the command for (i = 1; i < argc; i++) { size += strlen(argv[i]); } command = (char *) malloc( (size + argc + 11) * sizeof(char) ); sprintf(command, /bin/bash %s, argv[1]); if (argc > 2) { for (i = 2; i < argc; i++) { sprintf(command, %s %s, command, argv[i]); } } // Execute the command system(command); // free memory free(command); return 0;}The exercise was not only to solve my problem, but it was also a way to get more into C, so what do you suggest? Is there anything I should improve? | Calling a script with a setuid set | c;bash | Check for errors in stat, setuid, fork, and execvp, to name a few. If the exec fails in the child you should call exit.Do you really want the p in execvp? This is not guaranteed to be the same as the argv[1] you just stat-ed. If argv[1] is ls your stat will look for a file at ./ls and it will likely find the program in /bin. I would use execve and either do that PATH lookup yourself or simply omit that part and require the user to specify a full path for something in PATH (eg. /bin/ls instead of just ls).The stat + observe state + exec thing is a race condition. Another process can change the attributes on the file in that timing window. This may or may not be important to you. Given that this is a security-ish program I would say it may very well be.Instead of returning 0, you might want to return the child process's exit code (which you can get with waitpid.) You might also want to return nonzero when the functions I mention in #1 fail. This way a shell script or something calling you programmatically can determine success or failure. |
_unix.352115 | I have an issue with creating symbolic links with ln, with the relative and the force flag set.The scenario is as follows:$ tree. folder1 file folder2I create the link:$ ln -sfr folder1/file folder2$ tree. folder1 file folder2 file -> ../folder1/fileThis is as I want it. But when I re-execute the command, I don't understand why the link is now pointing to itself:$ ln -sfr folder1/file folder2$ tree. folder1 file folder2 file -> fileExecuting the command a third time corrects the error:$ ln -sfr folder1/file folder2$ tree. folder1 file folder2 file -> ../folder1/fileRe-executing the command multiple times toggles between two states. I really wonder why this is. According to the manual this should be no issue.The ln version used (as shipped with Ubuntu 14.10):$ ln --versionln (GNU coreutils) 8.21[...] | Inconsistent behaviour creating symbolic links with relative and force flag | ln | This is a bug and appears in the coreutils from version 8.16 to 8.21. It was fixed in 8.22. From the release notes of version 8.22:ln --relative now updates existing symlinks correctly. Previously it based the relative link on the dereferenced path of an existing link. [This bug was introduced when --relative was added in coreutils-8.16.]https://savannah.gnu.org/forum/forum.php?forum_id=7815 |
_unix.296773 | How can I install/emerge a package manual in gentoo?I cannot download this package (ZLIB), because it gets blocked by our IT-Firewall (invalid decompression table). They scan each http/ftp request and cannot open the archive properly (maybe wrong/incompatible decompression software). However, I need to install this package - IT is informed but I want a fast alternative...I have download it manual from home but how can I emerge this package manual when I have already downloaded it? | Manual emerge package zlib | linux;gentoo;emerge | Copy the downloaded file to /usr/portage/distfiles/ directory, then execute emerge command as usual. Make sure you have downloaded the exact version which you are going to install. |
_reverseengineering.5889 | Since I love to play with the WinAPI or debugging in general, I decided to write a small unpacker for the open source PE executable packer UPX today (Windows version).In order to accomplish this, I proceeded as follow:CreateProcess API all with DEBUG and DEBUG_ONLY_THIS_PROCESS flags.GetThreadContext API call in order to read value of EIP.ReadProcessMemory API call loop searching for the last JMP instruction.Overwriting the E9 with CC in order to set an INT3 breakpoint on the address.Entering DebugEvent loop waiting for the breakpoint. Once reached, reset byte back to E9, decrease EIP by one and jump to the address (OEP) of the target.After reaching the OEP, I proceed as follows in order to dump the process:Read ImageBase, Base of code, ImageSize, ... from original PE headersReadProcessMemory(hProcess, header32.ImageBase, buffer, header32.SizeOfImage, bytes_read)Save buffer content to payload.bin, update the PE header of the file with new EntryPoint (OEP) and set RawDataOffset and RawDataSize of each section to its corresponding VirtualAddress/VirtualSize.After creating the dump with fixed OEP & RAW offsets/sizes for the sections, I fix the dump with ImpREC (right now manually, but I plan to use ImpREC.dll or the ImpREC lite source in order to assemble everything in one tool at a later point).The thing that confuses me though, is the fact, that the resulting binaries worked perfectly fine (exact match with the MUP) for one test case (a small hello world fasm application) and my dump file was exactly the same I had received through OllyDump, but when I tried to do the same unpacking with an UPX packed version of putty.exe, my dumped memory varied from the one OllyDump had dumped starting at RAW offset 0x73970 (exact match before that address). However - the file size is again the same one (and all bytes before that offset match), just after that certain address the bytes magically won't match anymore (they are still non-zero though).I studied the source code in OllyDump.c thoroughly regarding this difference, but as for now I didn't find my mistake... In some cases my dumps are equal to the ones generated by OllyDump and in some they aren't. Or is the mistake probably in my approach already?Note: Source code omitted on purpose, since it's a few hundred lines long and super messy as for now. Can/will add further details if required or if I missed something, please just let me know in the comments. | An issue when unpacking UPX | unpacking;dumping;upx | Hard to tell what the reason for the differences might be without actually seeing the differences, but one guess is that you're doing ReadProcessMemory(hProcess, header32.ImageBase, buffer, header32.SizeOfImage, bytes_read), while the other tool may be doing foreach(section) {ReadProcessMemory(hProcess, header32.ImageBase + section.RVA, buffer, section.VirtualSize, bytes_read)}; this may cause the caves between sections to differ.(BTW, I assume your header32.ImageBase is the actual base address of the module in memory, not just the image base address from the PE headers, since ASLR could relocate it at runtime.) |
_cstheory.8883 | During my work i came up with the following problem:I am trying to find an $n \times n$ $(0,1)$-matrix $M$, for any $n > 3$, with the following properties:The determinant of $M$ is even.For any non-empty subsets $I,J\subseteq\{1,2,3\}$ with $|I| = |J|$, the submatrix $M^I_J$ has odd determinant if and only if $I=J$. Here $M^I_J$ denotes the submatrix of $M$ created by removing the rows with indices in $I$ and the columns with indices in $J$.So far, I tried to find such a matrix via random sampling but I am only able to find a matrix that has all properties except the first one, i.e., the matrix always has an odd determinant. I tried various dimensions and different input/output sets without any success. So this makes me think: Is that there is a dependency among the requirements, which prevents them from being simultaneously true?orIs it possible that such a matrix exists and can someone give me an example?Thanks,Etsch | Can such a matrix exist? | graph theory;co.combinatorics;linear algebra;matrices;boolean matrix | No such matrix exists.The Desnanot-Jacobi identity says that for $i \neq j$, $$ \det M_{ij}^{ij} \det M = \det M_i^i \det M_j^j -\det M_i^j \det M_j^i $$so using this, we get$$ \det M_{12}^{12} \det M = \det M_{1}^{1} \det M_{2}^{2} - \det M_{1}^{2} \det M_{2}^{1} $$But your requirements force the left-hand-side to be 0 (mod 2) and the right-hand-side to be 1 (mod 2), showing they are incompatible. |
_softwareengineering.188017 | It has been my experience, when building websites, that most of the logic of a system is executed when user input is accepted, be it via POSTs, GETs etc. I would like to know what processes or methodologies exist in Python (leaning towards using Python), PHP, and Ruby that allow web applications to perform tasks automatically without user input. For instance performing tasks at a certain time or condition or event. I have no experience with, and little understanding of, triggers, events, or cron, and all of the articles I ran across on google during my searches assumed a high familiarity with those concepts. I simply desire a description of ways one could go about handling non-reactive processes in a web application. | Automation Approaches: Events/Triggers/Cron | automation;event programming;conditions | You have pretty much answered the question yourself: cron jobs are the standard way of doing this.In PHP, you don't have much of a choice about this: the entire language is built with an execution model in mind where you get a clean slate with each request, and the language isn't very suitable for implementing long-running processes - you can do it, but you have to be very careful about not leaking memory.In Python, it depends on how you hook your code into a web server; if you use a web server that is integrated into your own code in a long-running process, you can trigger automatic processing directly from there, which means that you don't need cron in those cases. If, however, you follow a fresh-process-for-each-request paradigm like PHP does (mod_python does this IIRC) then you're pretty much limited to cron jobs or similar schedulers.I don't know enough about Ruby to make any qualified comments, but I assume that the situation is similar to that in Python.And of course, you can always implement a long-running process outside of your regular website, that just uses the same persistence backend and shares some code; such a process could then implement its own scheduling and even act upon other events. For example, you could set up a process that wakes up when a particular file changes, does some processing, then goes back to sleep. This approach has two advantages:Since there is only ever one such process, you don't have to worry about race conditions such as those caused by a cron job taking so long that individual iterations start overlapping - your process simply does one iteration at a time.You can act on events immediately without adding a lot of scheduling overhead. With cron jobs, you have to make a choice between frequent polling (shorter latency, more overhead) and less frequent polling (less overhead, longer latencies), but a process that just waits for a file to change has almost zero overhead while inactive.It's harder to set up though, and you'll probably want some sort of watchdog mechanism in case the process dies. |
_cs.35365 | I'm so bad at solving the problem of the type:If $A$ is an NP-complete problem, $B$ is reducible to $A$, then $B$ is... That I have to come here and ask these silly questions each and every time I encounter them.Is there a good way of using the Venn Diagram shown below to tackle these kind of problem?For example, how can I prove that If $A$ is an NP-complete problem, $B$ is reducible to $A$, then $B$ can be NP-hard using the above diagram?If not possible, what would be another way to drill this into my head? | How can I use the NP complexity Venn diagram to quickly see which class of NP problem can be poly reducible to another class? | complexity theory;proof techniques;complexity classes;intuition | As Raphael said the definitions are important, especially if you try to create proofs. These definitions are not always captured in the Venn diagram. The definition of NP-complete is not made clear from the diagram and will not help you to reason about If A is an NP-complete problem, $B$ is reducible to $A$, then $B$ is.... You cannot see from the diagram that this must mean that $B$ is NP.To answer your question if it is not possible how you will be able to drill it into your head is much more complicated. But again the first step needs to be the definitions. If you know that NP-completeness implies two properties of $A$ by definition, then you can take the next step. What does $B$ reducible to $A$ means when regarding these two properties. Do the properties of $A$ tell anything about $B$?The second property says that any problem in NP reduces to $A$ in polynomial time. So if $B$ reduce to $A$ in polynomial time then $B$ is in NP. |
_unix.154641 | I am attempting to load as the default DirectoryIndex home.html, but the site keeps jumping to index.php. Website is built on WordPress.httpd.confDirectoryIndex index.html home.html index.php index.html.var.htaccess<IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^home\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L]</IfModule>Any help on this matter would be greatly appreciated. | Incorrect Directory Index | configuration;apache httpd;wordpress;htaccess;mod rewrite | null |
_softwareengineering.108487 | I have a code where I have to work on Half precision floating point representationnumbers. To achieve that I have created my own C++ class fp16 with all operators(arithmetic logical, relational) related to this type overloaded with my custom functions, while using a Single precision floating point number with a Half precision floating point number.Half precision floating point = 1 Sign bit , 5 exponent bits , 10 significand bits = 16 bitSingle precision floating point = 1 Sign bit, 8 exponent bits, 23 significand bits = 32 bits So what I do to convert from a Single precision floating point number to a Half precision floating point number:- For significand bits - I use truncation i.e. loose 13 bits from the 32 bits to get 10 bits significand for half precision float.What should I do to handle the exponent bits. How do I go from 8 exponent bits to 5 exponent bits?Any good reading material would help. | Conversion of a number from Single precision floating point representation to a Half precision floating point | floating point;numeric precision | null |
_webapps.5723 | Possible Duplicate:Can I set an e-mail to send on a timer within gmail? I'd like to schedule an email at a later time and date with Gmail. Is this possible? They have many goodies in their labs section of Gmail preferences, but I do not recall seeing this labs add-on. | can I schedule to send mail later on with duration on gmail? | gmail;google apps email;date;scheduling | Try the Boomerang extension |
_unix.280660 | I am writing a script which uses hot corners to play specific musical notes when hovering in corners, and depending on the musical sequence to execute a specific command.The script is called with parameter -d from bottom left, -e from b-right, -g from top-left, -b from top-right, appends the sequence in a file (for_hot) and compares the sequence with my associative array. Plays a succesful musical B'' when the sequence is recognized.2 issues: Sometimes the commands won't execute;I don't manage to poweroff.Here is the script, please note I am a noob in linux so don't hate my code, my question, me too much:#!/bin/bash#switch###############################case $1 in-d) play -q -n synth 3 pluck 293.665 &sleep 0.5echo -n d >> ~/bin/for_hot;;;-e) play -q -n synth 3 pluck 311.127 &sleep 0.5echo -n e >> ~/bin/for_hot;;;-g) play -q -n synth 3 pluck 391.995 &sleep 0.5echo -n g >> ~/bin/for_hot;;;-b) play -q -n synth 3 pluck 466.164 &sleep 0.5echo -n b >> ~/bin/for_hot;;;esac#######################################midi mappings########################declare -A commandscommands=( [egbd]=firefox -n [ebgb]=idea [ebb]=notify-send $instr [egdgb]=echo pass | sudo -S poweroff[ee]=nemo /home/mintbwoy);######################################s=$(<~/bin/for_hot);for pattern in ${!commands[@]};doecho $pattern - ${commands[$pattern]};if [[ $s == *$pattern* ]]thenecho -n > ~/bin/for_hot;play -q -n synth 3 pluck 932.328 &var=$(${commands[$s]});$var;notify-send [$pattern] = ${commands[$pattern]} $var;fidone###################################### | Linux Mint Corners Musical Sequence Associative Array | shell script;linux mint;scripting;audio;associative array | null |
_unix.67860 | If I have a logrotate config file like this,# matches multiple ones/var/log/project/*.log { ... prerotate ... endscript ...} So how does the glob work here? If I have 3 log file matches that pattern, would the prerotate script get executed for 3 times or only once? I didn't find any clue in logrotate (8) | How does logrotate treat globbing? | logrotate;glob | It's executed three times, once for each matching file. There's a hint in the man page:sharedscripts Normally, prerotate and postrotate scripts are run for each log which is rotated and the absolute path to the log file is passed as first argument to the script. That means a single script may be run multi- ple times for log file entries which match multiple files (such as the /var/log/news/* example). If sharedscripts is specified, the scripts are only run once, no matter how many logs match the wildcarded pattern, and whole pattern is passed to them. However, if none of the logs in the pattern require rotating, the scripts will not be run at all. If the scripts exit with error, the remaining actions will not be executed for any logs. This option overrides the nosharedscripts option and implies create option.But of course, you only find that once you know to look there. (Also, I experimentally verified with logrotate -v ;) ) |
_webmaster.12240 | Some time ago (about 12 months) I created a number of targeted pages for our main product site. Out main product can be called several different things and clearly it's not possible to optimize our home page for all of them so we created new pages called 'secondary-term-1.htm' and 'secondary-term-2.htm'. These contained unique content and at the time I linked to them our site map and our blog. And that was it.A year later these pages are now ranking quite well and I want to expand on this concept and create new landing pages for other terms. I believe these landing pages are useful to people searching using different terms and relating this back to our product. I also think they are useful in explaining how our product is useful to different market segments.What is the current thinking with respect to Google as far as these landing pages go? Are we likely to be penalized in some way? This site is our main money maker and I am ultra cautious with what we can and cannot do on it. | Google and Landing Pages | seo;google;landing page | If you stick with Google guidelines you will be fine. If you have 5 pages targeting different terms about the same thing and their content is different there will be no problem; if you create 100 pages, copy-paste content and then replace just the keyword, maybe you will get in troubles. http://www.google.com/support/webmasters/bin/answer.py?answer=35769 |
_reverseengineering.11044 | I'm trying to automate disassembly of a firmware image using IDA Pro 6.5 and IDA Python. One of the process I want to implement is to locate strings and create a data segment around them.Using the GUI, I have little issue doing so. However when using the idautils.Strings() API call, I can retrieve a list of StringItem objects, but I fail to access the actual string data with str() or unicode(). Below is the failing function, which is taken from IDA Python Google Code archive:def find_strings(): s = idautils.Strings(False) s.setup(strtypes=Strings.STR_UNICODE | Strings.STR_C) for i, v in enumerate(s): if v is None: print(Failed to retrieve string index %d % i) else: print(%x: len=%d type=%d index=%d-> '%s' % (v.ea, v.length, v.type, i, str(v)))When ran into IDA, the following error is reported:Traceback (most recent call last): File <string>, line 1, in <module> File <string>, line 8, in find_stringsTypeError: 'StringItem' object is not callableWhen replacing the str(v) argument with the constant aaa in the print function, I get a list of StringItem objects without any problem:Python>find_strings()208e: len=8 type=3 index=0-> 'aaa'21b0: len=55 type=0 index=1-> 'aaa'229d: len=6 type=0 index=2-> 'aaa'22c5: len=5 type=0 index=3-> 'aaa'22d3: len=33 type=0 index=4-> 'aaa'...If I attempt to use the unicode() function instead, I get the following error:Python>find_strings()208e: len=8 type=3 index=0-> 'Traceback (most recent call last): File <string>, line 1, in <module> File <string>, line 8, in find_stringsTypeError: coercing to Unicode: need string or buffer, NoneType foundFrom my understanding, it seems that the StringItem contains no strings for an unknown reason (or an issue with the plugin, specific version of Python maybe?), however they are displayed in the GUI.I'm seeking advice on either what I'm doing wrong, or an alternative way to extract the strings using the IDApython plugin. ThanksUpdatesThe code above appears valid after adding the missing parenthesis as mentioned in the comments. However this was only a typo in the post and not the source of the issue. The find_strings worked fine in other typical binaries. Further proof is that by using the idc.GetString(self.ea, self.length, self.type) also returned NoneType.Diff mentioned that the get_ascii_contents2 is failing and thus returning null, which is very likely the cause. What is unclear is why the function is failing, while the GUI succeeds in locating most of the strings.The first string at 0x208E is a trash Unicode string. The string at 0x21B0 is an actual ASCII string composed of 37 chars. I cannot post the complete string due to disclosure/legal issues. Notice that when displayed in the hex editor, the byte order of the ASCII view is inverted for an unknown reason. The bitness of the overall firmware is 16bit.434F 5059 5249 4748 5420 A920 ... 4544 2000 0000 : OCYPIRHG T ... DE.Finally, note that the function MakeStr works without any issue. I have the following code, when used at 0x21B0, will successfully create a string within a data segment:def create_string(self, _startea, _endea, _segname=.const, _unicode=False): if (SegStart(_startea) == idc.BADADDR): self.create_data_segment(_startea, _endea, .const) else: segtype = GetSegmentAttr(_startea, SEGATTR_TYPE) if (segtype != IDAEngine.SEG_TYPE_DATA): DelSeg(_startea, 0) self.create_data_segment(_startea, _endea, _segname) result = MakeStr(_startea, _endea) if (result == IDAEngine.FAIL): print [-] Failed to create a string at 0x{:x} to 0x{:x}..format(_startea, _endea)At this point, I believe the structure of the firmware is to blame (combination of bitness, lack of symbols and an obsolete but supported microprocessor), however I couldn't pinpoint the exact issue. For now, since I can use find_strings() to retrieve the offsets and then use MakeStr on strings with a certain length and the manually vetting the real strings. Final RemarksFor posterity, I never really solved the issue, however I can confirm the underlying binary file was responsible for raising an exception in get_ascii_contents2. I've reloaded the same file, however as a raw binary file in one large segment and the function worked flawlessly. | IDAPython Strings constantly returns NoneType with str() | ida;idapython;idapro plugins | This took some digging, however it appears you're hitting an interesting edge case that the original author of the scripts didn't consider.str(StringItem) calls the following code inside idautils.py; def __str__(self): return self._toseq(False)Which leads to _toseq in idautils.py; def _toseq(self, as_unicode): if self.is_2_bytes_encoding(): conv = idaapi.ACFOPT_UTF16 pyenc = utf-16 elif self.is_4_bytes_encoding(): conv = idaapi.ACFOPT_UTF8 pyenc = utf-8 else: conv = idaapi.ACFOPT_ASCII pyenc = 'ascii' strbytes = idaapi.get_ascii_contents2(self.ea, self.length, self.type, conv) return unicode(strbytes, pyenc, 'replace') if as_unicode else strbytesIf we dig into the get_ascii_contents2 inside py_bytes.hpp method we see that this method could actually return a NoneType if get_ascii_contents2 fails;if ( !get_ascii_contents2(ea, len, type, buf, len+1, &used_size, flags) ){ qfree(buf); Py_RETURN_NONE;}Essentially, the code is fine, however you should add a check or exception handling if a str(StringItem) returns the with a TypeNone since it is possible for this type of value to be returned.You could help debug further by providing what the hex data is at ea of 0x208e with the length of 8 as shown in your output;208e: len=8 type=3 index=0-> |
_softwareengineering.247368 | I develop quite often scripts that are primary used as a console application but later they are used in other scripts, webservices and other things where it is very convenient, to just import the script and call methods directly rather than using a Process and parsing stdout.The question is now, what is a good design strategy to develop such scripts? I have an example here in python:def main(): # do stuff print(Found several results here:) for foo in bar: print(result: %s % foo)if __name__ == __main__(): main()this one could be easily rewritten to something like this:def main(): result = some_function() print(Found several results here:) for foo in result: print(result: %s % foo)def some_function(): # do stuff return barif __name__ == __main__(): main()But in most of my cases this is not so easy. But how to deal with this problem when the program does quite a lot of output, like different analyses or several steps or the return value of an API function would be something like a list of dict of list of tuples (or even more complicated structures)? Would it be good to encapsulate every step into a single method and run them one after another? What design patterns can be used to write good progamms that can be easily reused as APIs? | What is a good strategy to develop apps that run in console and as API? | design patterns;code reuse | If you are working on a script where you know (or suspect) that it will later be used as a library in a larger project, then it is easier to start out with writing the functionality in a library and then tagging on a driver script to use the library from the command line.There are no specific design patterns to help in creating good API's. It requires mostly a shift in thinking from a script that produces human readable output to a library whose output can be easily used by other software components. The biggest change there is that a library usually does not interact directly with the user. |
_unix.63284 | Possible Duplicate:Cant rename a directory that I own I am trying to understand why when a dir X is owned by user A cannot rename it when parent dir of X is owned by user B. Can anyone please explain?$ls -l ~drwxr-xr-x 11 root root 4096 Jan 31 09:43 mymedia~/mymedia$ ls -ldrwxr-xr-x 6 rag rag 4096 Jan 31 08:34 Entertainment~/mymedia$ mv Entertainment/ entertainmentmv: cannot move `Entertainment/' to `entertainment': Permission denied | why cannot rename subdir when parent dir owner is not the same user | linux;permissions;files | When you rename a file, you don't change the file, you change its parent directory. A file name is an entry in a directory. Think of phone directories, to change the name associated with a phone number in a directory, you need to modify the directory, not the phone line. The name is associated with the phone line only in that directory. That phone number may be in another directory under a different name (hard links).There's a caveat though for renaming directories as directories contain a reference to their parent (their .. entry). To be able to move a directory, it's not enough to have write permission to the old parent (to remove the entry) and the new parent (to add a new entry), you also need to have write permission to the directory itself to update the .. entry (if the old and new parent are different). |
_softwareengineering.343197 | Is it true that most of the times source code for Linux programs can be compiled into Mac OS programs and vice versa? | Is it true that Linux and Mac OS programs' source are interchangeable? | compiler;linux;source code;mac | null |
_unix.305182 | I'm developing a JavaScript application which calls some bash scripts to change network settings. Restarting network interface takes too long (like 20 sec or more) on some networks:ifdown eth0; ifup eth0I wonder whether I need to always restart interface when I edit /etc/network/interfaces (change IP, netmask, gateway, set DHCP), /etc/resolv.conf (changes DNS), /etc/apt/apt.conf (proxy for apt).Also I think about restarting DHCP client in some situations (but not sure when this would be sufficient). Could you please shed light on this issue. | Speed up ifdown / ifup | debian;networking | Most options can be changed dynamically using tools like ifconfig, route, ip, ndd, etc. so you might consider to use a different strategy: change options dynamically using other tools and save the options to the configuration file to be persistent.Changes to /etc/resolv.conf and /etc/apt/apt.conf are immediately in effect. |
_codereview.133962 | The program can be used to hide an image within another image and later extract the hidden image. This is done by concealing the secret image within the lowest bits of the apparent image. Example of a cat hidden within a tree.I split it into 2 programs to make commandline args parsing easier, Crypt and Decrypt.Info.h//Info.h#pragma once#include <stdint.h>const int keySpace = 6;typedef uint16_t PTYPE;unsigned int bitMax(int bits) { return (unsigned int)pow(2, bits) - 1;}Crypt.h//Crypt.h#include CImg.h#include Info.h#include <stdexcept>#include <bitset>#include <map>#include <sstream>using namespace cimg_library;using std::string;std::map<string, string> parseCMD(int argc, char *argv[]);template<typename T>void encrypt(CImg<T>& apparent, CImg<T>& secret, std::map<string, string> args) { if (!apparent.containsXYZC(secret.width() - 1, secret.height() - 1, secret.depth() - 1, secret.spectrum() - 1)) { //Check that secret fits inside apparent. throw std::invalid_argument(Secret is out of bounds of apparent.); } int bitDepth = std::stoi(args[bitdepth]) / apparent.spectrum(); int secretBitDepth = std::stoi(args[secretbitdepth]) / secret.spectrum(); apparent.normalize(0, bitMax(bitDepth)); secret.normalize(0, bitMax(secretBitDepth)); T secretMask = ~bitMax(secretBitDepth); cimg_forXYZC(apparent, x, y, z, v) { apparent.atXYZC(x, y, z, v) = (apparent.atXYZC(x, y, z, v) & secretMask) | secret.atXYZC(x, y, z, v); //Set apparent's *secretBitDepth* least significant bits to secret's value. }}//Sets the R value of the first *keySpace* pixels of apparent to the binary value of the rotational key.template<typename T>void sign(CImg<T>& img, int key) { if (key > bitMax(keySpace)) { std::stringstream ss; ss << Key is too large to fit into << keySpace << bits.; throw std::invalid_argument(ss.str()); } std::bitset<keySpace> bitKey(key); for (int i = 0; i < keySpace; i++) { img.atXYZC(i, 0, 0, 0) = bitKey[i]; }}Crypt.cpp//Crypt.cpp#include Crypt.h#include <tclap/CmdLine.h>int main(int argc, char *argv[]) { auto args = parseCMD(argc, argv); CImg<PTYPE> secret(args[secret0].c_str()); CImg<PTYPE> apparent(args[apparent].c_str()); if (args[resize] == true) { enum class Interpolation { NoneRawMem = -1, NoneBoundaryCondition, NearestNeighbour, MovingAverage, Linear, Grid, Cubic, Lanczos }; secret.resize(apparent, (int)Interpolation::NearestNeighbour); } encrypt<PTYPE>(apparent, secret, args); if (args[signature] == true) { sign(apparent, std::stoi(args[secretbitdepth]) / secret.spectrum()); } apparent.save(args[output].c_str()); return 0;}//All argument parsing is done here and returned in an argMap<arg, value>.//For multiarguments, the number of the args is passed in argMap[<name>num] and they can be accessed via argMap[<name>0] ... argMap[<name>n]std::map<string, string> parseCMD(int argc, char *argv[]) { try { TCLAP::CmdLine cmd(An Image Steganography tool., ' ', 0.1); std::map<string, string> argMap; TCLAP::ValueArg<string> apparent(a, apparent, Apparent image to hide secret within., true, , string, cmd); TCLAP::ValueArg<string> output(o, output, Output image., false, Hidden.png, string, cmd); TCLAP::ValueArg<string> bitDepth(b, bitdepth, Resulting Color Bit Depth of output image., false, 8, integer, cmd); TCLAP::ValueArg<string> secretBitDepth(z, secretbitdepth, How many bits each secret is going to take up., false, 8, integer, cmd); TCLAP::MultiArg<string> secret(s, secret, Secret image(s) to hide into apparent., true, string, cmd); TCLAP::SwitchArg resize(r, resize, Resize all secrets to apparent?, cmd, false); TCLAP::SwitchArg signature(g, signature, Embed the rotational key inside the image?, cmd, false); cmd.parse(argc, argv); for (TCLAP::ArgListIterator it = cmd.getArgList().begin(); it != cmd.getArgList().end(); it++) { TCLAP::ValueArg<string>* valArg = dynamic_cast<TCLAP::ValueArg<string>*>(*it); TCLAP::SwitchArg* switchArg = dynamic_cast<TCLAP::SwitchArg*>(*it); TCLAP::MultiArg<string>* multiArg = dynamic_cast<TCLAP::MultiArg<string>*>(*it); if (valArg) { argMap[(*it)->getName()] = valArg->getValue(); } else if (switchArg) { argMap[(*it)->getName()] = switchArg->getValue() == false ? false : true; } else if (multiArg) { argMap[multiArg->getName() + num] = std::to_string(multiArg->getValue().size()); for (int i = 0; i < multiArg->getValue().size(); i++) { argMap[multiArg->getName() + std::to_string(i)] = multiArg->getValue()[i]; } } } return argMap; } catch (TCLAP::ArgException &e) { std::cerr << error: << e.error() << for arg << e.argId() << std::endl; }}Decrypt.h//Decrypt.h#include CImg.h#include Info.h#include <map>#include <bitset>#include <vector>using namespace cimg_library;using std::string;std::map<string, string> parseCMD(int argc, char *argv[]);template<typename T>int getKey(CImg<T>& img) { std::bitset<keySpace> bitKey; for (int i = 0; i < keySpace; i++) { bitKey[i] = img.atXYZC(i, 0, 0, 0); } return static_cast<int>(bitKey.to_ulong());}template<typename T>void rotateDecrypt(CImg<T>& img, int rotateKey) { std::vector<int> bitDepths = {8, 24, 48}; T secretMask = bitMax(rotateKey); cimg_forXYZC(img, x, y, z, v) { img.atXYZC(x, y, z, v) &= secretMask; } img.normalize(0, bitMax(*std::upper_bound(bitDepths.begin(), bitDepths.end(), rotateKey)));}Decrypt.cpp//Decrypt.cpp#include Decrypt.h#include <tclap/CmdLine.h>int main(int argc, char *argv[]) { auto args = parseCMD(argc, argv); CImg<PTYPE> apparent(args[apparent].c_str()); int key = 0; if (args[signature] == true) { key = getKey(apparent); } else { key = std::stoi(args[key]); } bool soleImage; istringstream(args[soleimage]) >> std::boolalpha >> soleImage; rotateDecrypt(apparent, key); apparent.save(args[output].c_str()); return 0;}//All argument parsing is done here and returned in an argMap<arg, value>.std::map<string, string> parseCMD(int argc, char *argv[]) { try { TCLAP::CmdLine cmd(An Image Steganography tool., ' ', 0.1); std::map<string, string> argMap; TCLAP::ValueArg<string> output(o, output, Output image., false, unhidden.png, string, cmd); TCLAP::ValueArg<string> key(k, key, Rotational key., false, 8, integer, cmd); TCLAP::ValueArg<string> apparent(a, apparent, Input apparent encrypted image., false, 8, integer, cmd); TCLAP::SwitchArg signature(s, signature, Embed the rotational key inside the image?, cmd, false); cmd.parse(argc, argv); for (TCLAP::ArgListIterator it = cmd.getArgList().begin(); it != cmd.getArgList().end(); it++) { TCLAP::ValueArg<string>* valArg = dynamic_cast<TCLAP::ValueArg<string>*>(*it); TCLAP::SwitchArg* switchArg = dynamic_cast<TCLAP::SwitchArg*>(*it); if (valArg) { argMap[(*it)->getName()] = valArg->getValue(); } else if (switchArg) { argMap[(*it)->getName()] = switchArg->getValue() == false ? false : true; } } return argMap; } catch (TCLAP::ArgException &e) { std::cerr << error: << e.error() << for arg << e.argId() << std::endl; }} | Image Stenography using LSB technique | c++;beginner;image;steganography | Include all the headers you needInfo.h doesn't include required header for pow function (math.h)Use const references when you don't want to modify parameters to avoid unnecessary copyingencrypt function in Crypt.htemplate<typename T> void encrypt(CImg<T>& apparent, CImg<T>& secret, std::map<string, string> args)should betemplate<typename T> void encrypt(CImg<T>& apparent, CImg<T>& secret, std::map<string, string> const& args)Do the all the conversions you need before supplying parameters to functionsint bitDepth = std::stoi(args[bitdepth]) / apparent.spectrum();This is not good since args[bitdepth] can simply not convert into integer, you should've processed the arguments separately. The same holds for other arguments. This means you should rewrite parseCMD function or use some arguments parsing library. |
_unix.93566 | I was practicing ftp but faced an issue: ls command isn't working on ftp> . Why? I checked on 2 remote servers but ls didn't work on either and gave different output when ls was executed. Please see below for the 2 remote boxes.The below shows my remote server where I installed vsftpd today.ravbholua@ravbholua-Aspire-5315:~$ ftp rsConnected to ravi.com.220 (vsFTPd 3.0.2)Name (rs:ravbholua): 331 Please specify the password.Password:230 Login successful.Remote system type is UNIX.Using binary mode to transfer files.ftp> pwd257 /home/ravbholuaftp> ls500 Illegal PORT command.ftp: bind: Address already in useftp> The below is for a different remote machine where I have to send some files. But as ls on ftp> isn't working, how will I transfer files from my local box to that box because I can't be confirmed without ls whether the files have been transferred or not.ravbholua@ravbholua-Aspire-5315:~$ ftp 125.21.153.140Connected to 125.21.153.140.220---------- Welcome to Pure-FTPd [TLS] ----------220-You are user number 1 of 10 allowed.220-Local time is now 04:34. Server port: 21.220-This server supports FXP transfers220 You will be disconnected after 2 minutes of inactivity.Name (125.21.153.140:ravbholua): peacenews331 User peacenews OK. Password requiredPassword:230 OK. Current restricted directory is /Remote system type is UNIX.Using binary mode to transfer files.ftp> ls200-FXP transfer: from 123.63.112.168 to 10.215.10.80200 PORT command successfulPlease note that for the above machine, once I ran ls on ftp>, the prompt didn't come back.On both the remote machines, I got different output when executed ls on ftp> | ls command in ftp> not working! | vsftpd;pure ftpd | FTP is an ancient protocol. It relies on two TCP connections: a control connection over which commands are exchanged, and data connections for the content of files and also for the output of commands such as ls. What's happening here is that the control connection is established, but the data connections aren't going through.By default (active mode), data connections are established from the sender to the receiver. For the output of ls, the data is sent by the server, so the server attempts to open a connection to the client. This worked well when FTP was invented, but nowadays, clients are often behind a firewall or NAT which may or may not support active FTP. Switch to passive mode, where the client always initiates the data connection.Check the manual of your ftp command to see how to switch to passive mode by default. For a one-time thing, typing the command passive usually does the trick.You may wish to switch to a nicer FTP client such as ncftp or lftp. |
_softwareengineering.258080 | A project I'm involved in has suffered a change in scope, and before I set about trying to cook up some homegrown solution, I'm wondering if there is something out there -- some framework, for example -- that will spare me from having to design and debug my own code. Let me try to explain the details as simply as possible.Original projectThis is a data migration project, an ETL. Originally, there were multiple source databases, multiple ETL engines (allowing for failover), and 1 single data warehouse database. The data warehouse was going to keep the data from the individual sources straight, and it was going to be replicated, behind the scenes: meaning, my ETL would only have to worry about writing to the 1 data warehouse. I had a plan for that.The project's changeNow, the customer is worried about mixing the individual source data into a single data warehouse. They want separate data warehouses. This would be simple enough, but for the fact that they still want the ETL engines working per the original agreement. Let me explain that.The project's requirements (in a nutshell)Let's imagine the following:4 source databases4 ETL engines4 data warehouses (which may each be on a separate server)Given the above, the ETL engines should be able to work round-robin, a single ETL engine pulling from any of the 4 source databases and writing to the appropriate data warehouse. If 1 or more source databases goes down, or 1 or more ETL engines goes down, or 1 or more data warehouses goes down, the ETL process should still continue, merrily along, performing ETL where it can be done.My problemIf there were 1 data warehouse, I could coordinate this; if the ETL engines had only a single data source and data warehouse pair they were assigned to, I could handle this; but now things have gotten complicated. I'm really not up on the fancier frameworks -- or even, perhaps the concepts -- that handle something like this. Perhaps there is a name to a scenario like this (and it's a well-known problem), but I don't even know the name.Technologies usedNote: We already have a working prototype, delivered and tested by the customer, that performs the ETL on 1 source and 1 destination. Here is what we are using:Jython (Python, running on the JVM) for the ETLMicrosoft SQL Server for the source databasesMySQL for the data warehouse databasesMy question (again)Is there some kind of framework that coordinates a process like this, where the ETL engines can service all the source-destination pairs, provide failover, and yet won't be stepping on one another's toes, or is this something I have to code up myself.In closing, I hope the above is clear. If I can do anything to clarify the above, please ask. Thanks. | Coordinating a complicated data migration process | java;frameworks;concurrency;enterprise architecture;etl | null |
_softwareengineering.313182 | I am doing GUI tests for my network application and I'm wondering if I should stub out mock responses, or if it's OK to keep using the network for the GUI tests. It seems to me the main benefits of stubbing the responses are:SpeedRobustness - no false errors because of network problemsAnd the cons are:Server interaction (real world) - doesn't test thisTime to implement and maintain mock up (for a large application)Are the pros worth the cons? Are GUI tests about testing the actual application and if it runs for a real user connected to the server, or are they more similar to regular unit tests, but for the GUI - are they just trying to test the GUI and don't care about server interaction.EDITThis question specifically relates to GUI tests, not regular unit tests, and is questioning the value of stubbing mock responses in the GUI tests vs. using the server normally. | GUI Testing With Network | unit testing;testing;gui | Unit tests are for testing your code, not real-world scenarios. Specifically, unit tests should validate that your code produces correct outputs for given inputs. Nothing more.Server latency and responsiveness are certainly worth testing, but not with unit tests. Those would be covered by system tests.The risk of relying on networking for unit tests is they may fail due to problems outside the scope of the unit of code being tested. If you have a CI server with automated unit testing (you should), your build might fail if e.g. MIS takes the remote server down for maintenance. That is a false negative: the failure indicates a problem in your code, when the problem is an unresponsive server. |
_webmaster.46845 | I was just messing around with Google Sites and noticed that as soon as I made my site the homepage had a PR of 9 (before it crosses your mind all the links it makes are nofollow).The homepage of the test site I was playing around with is https://sites.google.com/site/samsnewsite030413/Why does this happen as PR is on a per-page basis, and as the page is brand new how does it have a PR? I've seen a similar thing happen with Github project pages; they seem to have a PR8 as soon as they are made, it's not like they are running off a standard URL with JavaScript bringing in the content - they seem to be static pages with their own URLs. | New site has PR9 as soon as it is made, why/how? | pagerank | It's not PageRank of your home page but PageRank of https://sites.google.com.You can check PageRank of Github home page here and you will see PR8.This comes from HTTPS misunderstood. If you want the real PageRank of your page, check it with HTTP. I have checked it and your PageRank is N/A. |
_codereview.115857 | Sorry, if you were looking for fresh baked pies, I only have a web client to help you sell them.I've recently picked up server-side JavaScript and have added it to my toolbox, and while I've had a great time learning so far, I've got some code which needs another pair of eyes to review it.A quick objective summary: this code uses three big JS libraries: Node.js, Express, and Socket.io. For data storage, I've tied in MongoDB. What's going on is a simple back-and-forth communication between the server code (index.js) and the client code (not listed, I don't want that reviewed yet. If you really need it, I'll edit it in).For some background, especially if you're not familiar with this technology: with socket.io, there are two main methods: emit and on. Emit sends a packet, either direction. On receives data, from either direction too. With my code, I first listen for a connection, and then emit some data to the client, and then listen for a response. When a response is heard, the server sends data back in return.Index.js/*** Setup app details**/use strict;var express = require('express');var app = express();var http = require('http').Server(app);var io = require('socket.io')(http);var moment = require('moment');/*** Setup database details**/var mongodb = require('mongodb').MongoClient;var assert = require('assert');var objectID = require('mongodb').ObjectID;var url = 'mongodb://localhost:27017/pps';// Setup all public static files (Styles, scripts, images, etc.)app.use(express.static('public'));// Route the main page to index.htmlapp.get('/', function (req, res) { res.sendFile(__dirname + '/index.html');});var COLLECTIONS = {};mongodb.connect(url, function (err, db) { assert.equal(null, err); COLLECTIONS = { FLAVORS: db.collection('Flavors'), UF_ORDERS: db.collection('UnfinishedOrders'), F_ORDERS: db.collection('FinishedOrders') };});/*** Socket.io Connection with event handling**/io.on('connection', function (socket) { simpleEmit('flavors', COLLECTIONS.FLAVORS); simpleEmit('orders', COLLECTIONS.UF_ORDERS); simpleEmit('finished orders', COLLECTIONS.F_ORDERS); mongodb.connect(url, function (err, db) { assert.equal(null, err); socket.on('add flavor', function (msg) { insertFlavor(db, msg, function () { simpleEmit('flavors', COLLECTIONS.FLAVORS); }); }); socket.on('update flavor', function (msg) { updateFlavor(db, msg, function () { simpleEmit('flavors', COLLECTIONS.FLAVORS); }); }); socket.on('delete flavor', function (msg) { deleteFlavor(db, msg, function () { simpleEmit('flavors', COLLECTIONS.FLAVORS); }); }); socket.on('add order', function (msg) { insertUnfinishedOrder(db, msg, function () { simpleEmit('orders', COLLECTIONS.UF_ORDERS); }); }); socket.on('finish order', function (data) { getOrderDetails(db, 'UnfinishedOrders', data, function (data) { insertFinishedOrder(db, data, function () { deleteUnfinishedOrder(db, data, function () { simpleEmit('orders', COLLECTIONS.UF_ORDERS); simpleEmit('finished orders', COLLECTIONS.F_ORDERS); }); }); }); }); socket.on('delete order', function (msg) { deleteOrder(db, msg, function () { simpleEmit('orders', COLLECTIONS.UF_ORDERS); }); }); });});/*** Emit Call**/function simpleEmit(command, collection) { mongodb.connect(url, function (err, db) { assert.equal(null, err); var data = []; var cursor = collection.find(); cursor.each(function (err, doc) { assert.equal(err, null); if (doc !== null) { data.push(doc); } else { //console.log('SENDING... ' + command, data) io.emit(command, data); db.close(); } }); });}/*** Database Calls**/var insertFlavor = function (db, data, callback) { db.collection('Flavors').insertOne({ flavor: data[0], color: data[1] }, function (err, result) { assert.equal(err, null); callback(result); });};var getFlavors = function (db, callback) { var data = []; var cursor = db.collection('Flavors').find(); cursor.each(function (err, doc) { assert.equal(err, null); if (doc !== null) { data.push(doc); } else { callback(data); } });};var updateFlavor = function (db, data, callback) { db.collection('Flavors').updateOne( { flavor: data[0] }, { $set: { flavor: data[1] } }, function (err) { assert.equal(err, null); callback(); });};var deleteFlavor = function (db, data, callback) { db.collection('Flavors').deleteOne( { flavor: data }, function (err) { assert.equal(err, null); callback(); });};var insertUnfinishedOrder = function (db, data, callback) { db.collection('UnfinishedOrders').insertOne({ customer: data[0], flavor: data[2], date: data[1], notes: data[3] }, function (err, result) { assert.equal(err, null); callback(result); });};var getUnfinishedOrders = function (db, callback) { var data = []; var cursor = db.collection('UnfinishedOrders').find(); cursor.each(function (err, doc) { assert.equal(err, null); if (doc !== null) { data.push(doc); } else { callback(data); } });};var deleteOrder = function (db, data, callback) { db.collection('UnfinishedOrders').deleteOne( { _id: objectID(data) }, function (err) { assert.equal(err, null); callback(); });};var getOrderDetails = function (db, collection, data, callback) { var cursor = db.collection(collection).find({_id: objectID(data[0])}); cursor.each(function (err, doc) { assert.equal(err, null); if (doc !== null) { callback([doc, data[1]]); } });};var deleteUnfinishedOrder = function (db, data, callback) { db.collection('UnfinishedOrders').deleteOne( { _id: objectID(data[0]._id) }, function (err) { assert.equal(err, null); callback(); });};var insertFinishedOrder = function (db, data, callback) { db.collection('FinishedOrders').insertOne({ customer: data[0].customer, flavor: data[0].flavor, date-finished: +moment(), price: data[1] }, function (err, result) { assert.equal(err, null); callback(result); });};var getFinishedOrders = function (db, callback) { var data = []; var cursor = db.collection('FinishedOrders').find(); cursor.each(function (err, doc) { assert.equal(err, null); if (doc !== null) { data.push(doc); } else { callback(data); } });};/*** Listen for the initial connection**/http.listen(3000, function () { console.log('Node.js listening at http://localhost:3000/');});There are a few issues I have with this code...A lot is repeated. In an attempt to cut back on emit code, I made simpleEmit(). It works great. Any ideas on how I could do something similar to clean up the many on methods?Because almost every function requires the database, I had a lot of mongodb.connects at one point. I've cleaned them up mostly, but I'm wondering if I'm handling this connection correctly. I was forced to take out the close() method on mongodb. Will this hurt me? (This is what makes the title relevant!)Everything is in the global scope, should I change this? If so, in what way?Anything else goes! | Baking homemade pies has made me so many new connections | javascript;node.js;express.js;socket.io | Not entirely sure why you'd keep calling connect and close. As far as my DB knowledge goes, you open a connection once and keep it open. Here's an answer from StackOverflow regarding the issue. So I suggest that once you get the db object, you simply just pass it on. In this case, simpleEmit should be handed over the db object.I recommend that you use promises in your API. It appears that your mongo API already supports promises. You can simply reuse the db from the initial call. connect appears to return a promise.// Your only connect call which resolves to a db objectvar connectionPromise = mongodb.connect(url);// Hook your collection shorthandconnectionPromise.then(db => { COLLECTIONS = { FLAVORS: db.collection('Flavors'), UF_ORDERS: db.collection('UnfinishedOrders'), F_ORDERS: db.collection('FinishedOrders') };});// Hook up your socket connections only when we connect to the dbconnectionPromise.then(db => { io.on('connection', socket => { /* socket listeners */ }});The db methods also appear to return promises. insertOne returns a Promise according to the docs.// Here's a sample of how a db operation call would look likefunction insertFinishedOrder(db, data, callback) { return db.collection('FinishedOrders').insertOne({ customer: data[0].customer, flavor: data[0].flavor, date-finished: +moment(), price: data[1] });};// Here's an example of a caller with multiple calls one after the othersocket.on('finish order', function (data) { getOrderDetails(db, 'UnfinishedOrders', data) .then(data => insertFinishedOrder(db, data)) .then(data => deleteUnfinishedOrder(db, data)) .then(() => simpleEmit(db, 'finished orders', COLLECTIONS.F_ORDERS));});Now if you rewrote everything to take advantage of promises, notice how insertFinishedOrder and finish order is also simplified. insertFinishedOrder simply just returns a promise for finish order to consume. finish order takes advantage of promises to appear linear instead of nested.Now that we've started to consider promises, I notice that there are several functions that are not async like getFlavors. So that we can be consistent with the promise-returning api we have, wrap the operation in a promise. Also, each is deprecated. Use forEach.function getFlavors(db, callback) { return new Promise((resolve, reject) => { var data = []; var cursor = db.collection('Flavors').find(); cursor.forEach(doc => (doc !== null) ? data.push(doc) : resolve(data);); });}Also suggesting to use a function declaration instead of function expressions. With function declarations, you take advantage of what they call hoisting, where in variable and function declarations are visible regardless of where they are placed. But it's also a best practice to put your functions together so you don't have to go out and hunt them. |
_vi.7842 | I have some 30 characters in a line. When I press 80|, it should move 50 character to the right, thus move the cursor to 80th character. (30, 50, 80 are for examples)How to achieve this using mapping or commands?I tried :nmap <Bar> a<Space>It doesn't work. | Move to non-existing Nth column | insert mode;normal mode | You can use 'virtualedit' to allow moving to columns that don't contain text. If you set virtualedit=all, then 80| will place the cursor on column 80.No spaces will be inserted until you actually perform some text editing there, though. If your sole goal is to just extend the line to an arbitrary column, then a simple mapping taking advantage of 'virtualedit' can do that.nnoremap <Bar> <Bar>i <Esc>Or if you only want 'virtualedit' active for the mapping, something like:fun! ExpandLine(col) let ve = &ve set virtualedit=all exe 'normal! '.a:col.'|i ' let &ve = veendfunnnoremap <silent> <Bar> :<C-u>call ExpandLine(v:count)<CR> |
_unix.6927 | I am creating a cloning script to automate a minimalistic installation of Cent OS 5.5 on about 100 workstations of various hardware and age (2-10 years). The workstations are all either IDE or SATA. I am currently developing the script and testing it on VMs (ESXi 4) with virtual IDE disks. In the initrd I have commented out scsi_mod.ko, sd_mod.ko & scsi_transport_spi.ko, and it seems to work just fine for booting a VM that uses an IDE disk. The problem is that I don't have easy access to the physical workstations and there are no virtual SATA disks for ESXi, so I cannot test with SATA disks.Are the above SCSI modules needed on a workstation that only has a SATA disk? Are any SCSI modules needed for SATA disks (with a stock CentOS 5.5 kernel)?Thanks,Lars | Are any SCSI modules needed in initrd if only SATA and IDE disks are used? | linux;sata;scsi | null |
_unix.358797 | I am not able to mount the partition created using sfdisk.I am able to see the partitions .I gave the following commandsmkfs.ext3 -q -m 0 -L data /dev/mmcblk0p3e2fsck -p /dev/mmcblk0p3mkdir -p /mnt/data3mount -t ext3 /dev/mmcblk0p3 /mnt/data3but i am getting the error like ~# mount -t ext3 -v /dev/mmcblk0p3 /mnt/data3EXT3-fs (mmcblk0p3): error: can't find ext3 filesystem on dev mmcblk0p3. mount: wrong fs type, bad option, bad superblock on /dev/mmcblk0p3,missing codepage or helper program, or other error In some cases useful info is found in syslog - try dmesg | tail or so.Anybody have any idea how to fix it??? | Partition created using sfdisk is not mounting | linux;partition;sfdisk | null |
_cs.42827 | Due to Tarski's result, it is well-known that the first-order theory of reals $(\mathbb{R},+,\cdot,<,=,0,1)$ is decidable. I am working on a paper where I need an extension of this result. More precisely, I would like to consider formulas that involve rational functions, rational coefficients, minima and maxima. Trigonometric functions or exponential functions, instead, are excluded.While this seems to me to be a straightforward consequence of Tarski's result (essentially, rewrite any formula with the above functions into one with polynomials only; e.g., rewrite $\sqrt[2]{x}$ into $\exists z (z^2 = x)$; for two polynomials $p$ and $q$, rewrite the formula $p / q \leq 1$ into $p \leq q$ and so on).To my surprise, I could not find any paper that formally establishes this. Before providing the proof on my own, I wanted to ask around whether someone is aware of a paper that establishes this result. | Extension of Tarski's result on the decidability of reals | decision problem;first order logic | null |
_webmaster.43594 | I am working on a website for a client that is requesting a way to verify your age. I have debated on creating a cookie that stores your age but I am unsure on a few things.How does SEO play into this if I create a landing page prior to the physical address?Is there a better way to possibly go about doing this other than a cookie?Should I create a separate page or code it within the header of the index page?This is something similar I am trying to accomplish. | Age verification in website | seo;cookie;landing page;age verification | With regard to SEO, the content of the site may not be accessible to crawlers unless you provide a means of distinguishing crawler traffic from human users. You could parse the user agent string and allow traffic from search engine crawlers to bypass the age gate. Ordinary users would not know how to exploit this to not have to verify their age, so I don't think this is an issue. For Google, see http://support.google.com/webmasters/bin/answer.py?hl=en&answer=1061943. Otherwise, if the crawler can access the page, there should not be a significant impact on SEO (but see below).With regard to how to store this information, doing it server-side requires a means of identifying the computer users are accessing the site with, so this isn't really an option. The only other realistic choice is HTML5 Local Storage, which won't work with older browsers, so cookies are probably the best way to go.Coding the age gate into the header of the index will not work for other pages. You could reference the code in every page of the site which must remain behind the age gate, which this would make it easier for crawlers to read the content, but you must remember to place the reference on every page on the site which requires it, and the age gate may end up in the search engine's index, which may not be what you want. |
_webmaster.78406 | I have a vps set with an padres and i also have a domain name at a hosting provider. I want to connect the domain name to the padres of the vpsmy hosting provider doesn't give support how to fix that. Can anyone help me? maybe a manualthanks | Configure my vps and domain name | webserver | null |
_unix.341300 | I have pfSense router with 2 WANs. I noticed, that if one WAN is down, then I can't ping 8.8.8.8 from router. Simultaneously, I am able to ping this address from within LAN, i.e. it can pass through router.How is this possible?I checked pinger (by Web interfcate) and found, that it doesn't use this address to check gateway alive. Previously I was using it but now de-configured.What else can still bind 8.8.8.8 to one of WANs and hot to catch it?UPDATEMy suscpicion is that only one WAN available from the router itsellf, because one of them is marked default. When default WAN is down, then no internet is available for router at all.Simultaneously, they have special multi tier thing to load balance two WANs, which makes that router still serves internet for LAN machines.Is this possible? | Can't ping 8.8.8.8 from router, but can ping it from LAN? | freebsd;routing;pfsense;nslookup | null |
_unix.330418 | I know that the assignment of disks to /dev names can vary at boot, but how the heck can it vary in a session? I'd swear that happened to me yesterday, /dev/sdb and /dev/sdc changed places, and I think it's happened before tho /dev/sda (which is an IDE drive) never gets involved in that. | harddisks change /dev name while running | filesystems;hard disk;hardware | Presuming this is Linux, drive letters should only change if the drives disconnect and reconnect. That happens routinely with external USB, but with internal SATA it generally indicates a problem. Common causes include (at least) a loose or defective cable; power supply issues; drive firmware issues; defective and/or dying hard drive; defective SATA controller. I've see, for example, drives that were on there way out and would sometimes hit some bad sectors, then they'd time out and ignore Linux's SATA resets. So they'd get disconnected. But an hour or two later, they'd finally sort themselves out and re-connect. The solution (of course!) was to replace the failing drives.Any disconnect/reconnect (or other drive problems) should leave kernel messages; check dmesg, /var/log/kern.log, or journalctl -b 0 -k, etc. for disk messages. Also check drive status with smartctl.Finally, at least on Linux with udev, there are stable names in /dev. Look in /dev/disk/by-id/. You can use those names with dd, etc. |
_webapps.52634 | I have an array of values: A B C1 TypeID MaterialTypeID Quantity2 18 34 2563 18 35 5124 20 34 3865 20 36 773Now I need a formula where I can search for lets say TypeID=20 and MaterialTypeID=34 and the formula gives me the Quantity=386. | VLOOKUP or INDEX+MATCH | google spreadsheets | Ok, I found the solution:=INDEX(C:C;MATCH(D6&D7;A:A&B:B;0))where D6 and D7 are my search criteria... |
_codereview.100986 | I'm new to Ruby and don't know all the methods, so I was thinking there would probably be and easier way to do something like this. I'd love any input on how to refactor this. define_singleton_method(:delete) do |id| revised_words = [] @@words.each do |word| if word.id() != id revised_words.push(word) else Definition.delete_by_word_id(id) end end @@words = revised_words end | Custom delete method refactoring | ruby | null |
_unix.299400 | When I ran device query, I got this error:./deviceQuery Starting... CUDA Device Query (Runtime API) version (CUDART static linking)NVIDIA: no NVIDIA devices foundcudaGetDeviceCount returned 30-> unknown errorResult = FAIHowever, I have already installed the best proprietary driver out there for this graphic card via mhwd (Manjaro hardware detection), so basically I got the bumblebee hybrid card video-hybrid-intel-nvidia-bumblebeeBut despite installing the appropriate driver, the card doesn't get detected. Why?I ran inxi -G which gives:Graphics: Card-1: Intel 4th Gen Core Processor Integrated Graphics Controller Card-2: NVIDIA GM107M [GeForce GTX 860M] Display Server: X.Org 1.17.4 driver: intel Resolution: 1920x1080 GLX Renderer: Mesa DRI Intel Haswell Mobile GLX Version: 3.0 Mesa 12.0.1Thank you so much for your help. | Detection of NVIDIA GTX860M graphics card in Manjaro Linux? | drivers;nvidia;manjaro;proprietary drivers | null |
_unix.359910 | I execute the following code in Bash:bash /dev/fd/10 10<<-'SES' cat <<EMR >> /etc/apache2/apache2.conf # <Directory /var/www/> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> EMRSESBut the execution breaks and I get:warning: here-document at line 2 delimited by end-of-file (wanted `EMR')I don't understand what the error means and I already added - between the operator and the name of the containing heredoc to allow tabulations. I made sure there are no spaces after the opener (operator+name) or after the delimiter.Note: If you copy the code above to test it in your computer, you need to change all leading spaces to tabs (tabulations) as StackExchange changed the original tabulations to spaces.Possible causes to rule out:There are several possible causes for this, here are some I've ruled out:1. Problematic hidden characters:I edit the file with Notepad++ and I turned on the Show all symbols mode to make sure all indents are tabulation based (see red arrows) and that all End Of Line chars (EOLs) are LF unix based (there aren't any CR chars):Moreover, the encoding is UTF-8, so it's not an encoding problem.2. Pseudo dash symbol (<<-):It seems as the added hyphen (<<-) doesn't do its job of stripping all leading tabs because when I manually delete all leading tabs whatsoever (or all leading tabs before each delimiter) the heredoc does work as expected. One can suggest that the hyphen isn't really a dash symbol, but why won't it be? I have no way to validate that.3. Bash bug:Other people not-using Windows, and using different Bash-containing Linux distros didn't have this, so this is most likely not a Bash bug. I've also tested this with the Bash development section at GNU.Corrupted pasting of copied data from Notepad++ might be it:If I paste the heredoc from Notepad++ into a nano file, it seems the leading tabs are all in place - they aren't deleted are transformed into spaces in pasting.Moreover, cat script.sh | grep ^ and cat script.sh | grep -x '\s*EMR' (when done in the files directory), come out empty.Yet, in a later pasting I found another corruption problem that is most likley to cause this (see my answer). | Heredocument error I can't understand (delimited by end of file) | bash;here document | The problem is undoubtedly, 100% Windows related, and deals with the TTY window-size. The narrower the window size is, the more carriage returns created by Windows in pasting.Solution:As suggested to me by Benno Schulenberg of the Nano development team, adding the following code in the end of /etc/nanorc solved this problem:bind ^J enter mainThis will on the other hand disable formation of Trailing whitespaces, but on the other hand, will add Line Feeds (LF chars) to the data copied from Windows, so it won't appear in one long row.Correspondence between me and Benno.I also reported here in length. |
_unix.9149 | When I need to create a new server I've always chosen Centos mainly for it's compatibility with Red Hat which i consider the standard de-facto for the general purpose linux server.Now the problem is that Red Hat 6 has been out for quite a while and there is no sign of the Centos 6 (event Centos 5.6 iso is still missing).As in the need to create a new server what will you do? Stay whit the old Centos 5.5 or switch to the recently released Scientific Linux 6.0?I looked on SL 6.0 website and they declare great attention to compatibility with RH, I've never tried it by myself so I just wanted someone's real life opinion. | Centos or Scientific Linux | centos;rhel;distribution choice;scientific linux | null |
_webapps.78520 | I have a drop down of 500+ items. How can we mass upload information for a particular dropdown field? | Cognito Forms: Importing a list of 500+ items to populate a drop down | cognito forms | null |
_codereview.146504 | Is this thread safe?I have a program that executes an SQL command on a number of files (selected by the user).Here is where I create the threads:var allThreads = new List<Task<bool>>();if (fileList != null){ foreach (var file in fileList) { var fileName = Path.GetFileName(file); if (File.Exists(file)) { Log.AddToLog(Beginning to Process File: + fileName); if (!ValidateFile(file)) { Log.AddToLog(String.Format(Error! {0} is not a valid file for the {1}. Skipping this file., fileName, JsonSettingsList.NameId)); IsErrorsInLog = true; } else { var fileToProcess = file; //need to make copy for threading loop, otherwise it acts screwy var newTask = Task.Factory.StartNew<bool>(() => ProcessFile(fileToProcess)); allThreads.Add(newTask); } } else { Log.AddToLog(String.Format(CultureInfo.CurrentCulture, File {0} Does not Exist. File not processed., fileName)); IsErrorsInLog = true; } } //check result, if any of them return true, then there are errors in the log, and the user needs to be alerted. foreach (var task in allThreads) { try { var didThreadFail = task.Result; if (!IsErrorsInLog) { IsErrorsInLog = didThreadFail; } } catch (AggregateException aggEx) { foreach (Exception ex in aggEx.InnerExceptions) { Log.AddToLog(string.Format(Caught exception '{0}', ex.Message)); IsErrorsInLog = true; } } finally { task.Dispose(); } }}and then here is the code where I am actually accessing the database, inside of the ProcessFile() function://initialize oracle connection oraConnection.Open();using (var command = new OracleCommand(sqlText, oraConnection)){ command.Transaction = command.Connection.BeginTransaction(); foreach (var line in fileByLine.Where((i, index) => index > 0)) { if (!String.IsNullOrWhiteSpace(line)) { //add parameters command.ExecuteNonQuery(); } } command.Transaction.Commit(); Log.AddToLog(Successfully Processed + filePath);}oraConnection.Close();The comments are where I have omitted unnecessary code for the sake of simplicity. | Executing an SQL command on a number of files | c#;thread safety;concurrency | if (fileList != null)You can reduce nesting (which is usually a good thing) by turning this into if (fileList == null) { return; }The same applies toif (File.Exists(file))It's better to haveif (!File.Exists(file)) { continue; }But even better then this would be to filter the list before you start processing it:fileList.Where(File.Exists)Checking the fileList for null is an indicator that some other part of the code might be implemented in a wrong way_. In C# we prefer to have an empty list rather then a null.Parallel.ForEachHave you already tried the Parallel.ForEach? It would greatly simplify your code:Parallel.ForEach(fileList.Where(File.Exists), fileName => { // process the file});This method has a lot of overloads so you'll probably find something that suits your needs.With one of them you could for example create a connection for each parallel loop and dispose it at the end of the processing.Here's a bigger example that might work for you. This will use the same connection for several files.try{ var parallelOptions = new ParallelOptions {#if DEBUG MaxDegreeOfParallelism = 1#else MaxDegreeOfParallelism = Environment.ProcessorCount#endif }; var parallelLoopResult = Parallel.ForEach ( source: fileList.Where(File.Exists), parallelOptions: parallelOptions, localInit: () => new { Connection = /* init the oracle connection*/ }, body: (fileName, loopState, i, local) => { // process the file // use the local.Connection return local; // pass the connection to the next loop }, localFinally: local => { local.Connection.Dispose(); } );}catch (AggregateException ex){ // handle exceptions}See this question on SO, it compares your solution with Parallel.ForEach:Parallel.ForEach vs Task.Factory.StartNew |
_unix.157189 | I have a Raspberry Pi with Raspian installed on it and I am experiencing troubles sending out emails.I have installed SSMTP and usually inside my scripts I'm sending out emails to notify me when a job is completed:echo $(date) Job completed | mail -s My subject [email protected] was working fine until a couple of months ago, when I stopped receiving emails. I tried to manually launch the script and I receive this error:send-mail: 550 Your authenticating ID must match your sending address.I suspect there's something wrong in my SSMTP configuration, that at the beginning my email provider wasn't checking and now it's not working. Here you can find my ssmtp.conf file:## Config file for sSMTP sendmail## The person who gets all mail for userids < 1000# Make this empty to disable rewriting.root=postmaster# The place where the mail goes. The actual machine name is required no# MX records are consulted. Commonly mailhosts are named mail.domain.commailhub=mail# Where will the mail seem to come from?#rewriteDomain=# The full hostnamehostname=raspberrypi# Are users allowed to set their own From: address?# YES - Allow the user to specify their own From: address# NO - Use the system generated From: addressFromLineOverride=YESAuthUser=myUserAuthPass=myPasswordmailhub=mysite.smtp.com:587UseSTARTTLS=YESI think there's something wrong, but I'm not a sysadmin and I don't have so much experience with mail services, any suggestions? | SSMTP returns error 550 | email;raspbian;ssmtp | authenticating ID must match your sending address.The server mysite.smtp.com: (or more specifically, the MTA its running) rejects your mail, because you authenticate as one user (myUser), but send a mail as another user. |
_unix.168609 | I just bought a new computer and I intalled Debian on it. I am having a hard time with the wifi connection. It seems that Debian can not see the wlan0 network interface.To provide some details, my version of Debian is:Linux 3.2.0-4-amd64 #1 SMP Debian 3.2.63-2+deb7u1 x86 GNU/LinuxUsing lspci --n I found that my wireless controller is the following:02:00.0 Netwrok Controller [0280]: Intel Corporation Device [8086:08b1] (rev 73)that should correspond to an Intel(r) Wireless-N 7260.At this page (https://packages.debian.org/wheezy-backports/firmware-iwlwifi) I found that I should need the non-free firmware-iwlwifi package from wheezy backports.Hence I modified my sources.list file to accept also non-free packages from wheezy-backports and I installed the above package.Anyway nothing happens and I still don't have a wlano interface. Any idea on how to solve this? | wifi not working on new debian machine | debian;wifi;backports | null |
_codereview.107702 | This small application is used to approximate conflicts in a schedule. Using a minimal time span of 30 minutes in my example, the application should be able to figure if there's a conflict in +/- 30 minutes range. To compute my approximation, I based my code on this SO's question. The idea is to use bitwise manipulation and, splitting your schedule in parts (30 minutes in my case), attribute one bit to each 30 minutes slot in a day.Example :1:00 to 3:00 (AM) = 001111 The first zeros represent the hour from 0:00 to 1:00, then the four other bits represent from 1:00 to 3:00.1:30 to 4:00 (AM) = 00011111The three first zeros are from 0:00 to 1:30, then the 5 setted bits are for the timespan of 1:30 to 4:00.I'm using a long to keep these values, which means that : \$24hours/day*60minutes/hours= 1440 minutes/day\$and : \$1440minutes/30minutes/bit=48bits\$The last 16 bits of the long are useless (at least, for the moment).In order to respect my 30 minute TimeSpan, I round my DateTime to respect the said TimeSpan using these methods : public static class DateTimeExtension{ /// <summary> /// Rounds down a date according to the timespan /// </summary> /// <param name=dateTime>DateTime to round</param> /// <param name=roundValue>Timespan unit used to round</param> /// <returns>Rounded unit</returns> /// <example> /// 2015/01/01 13:15 with TimeSpan.FromMinute(30) will round to 13:00 /// </example> public static DateTime RoundDown(this DateTime dateTime, TimeSpan roundValue) { var delta = dateTime.Ticks % roundValue.Ticks; return new DateTime(dateTime.Ticks - delta, dateTime.Kind); } /// <summary> /// Rounds up a date according to the timespan /// </summary> /// <param name=dateTime>DateTime to round</param> /// <param name=roundValue>Timespan unit used to round</param> /// <returns>Rounded unit</returns> /// <example> /// 2015/01/01 13:15 with TimeSpan.FromMinute(30) will round to 13:30 /// </example> public static DateTime RoundUp(this DateTime dateTime, TimeSpan roundValue) { var delta = (roundValue.Ticks - (dateTime.Ticks % roundValue.Ticks)) % roundValue.Ticks; return new DateTime(dateTime.Ticks + delta, dateTime.Kind); }}I'll explain the flow of the program rapidly : We create a Schedule, add ScheduleUnits in it, the call ComputeApproximatedScheduleConflicts() to get an approximation (+/- 30 minutes) of the conflicts using a & operator, then we create a ScheduleConflit per instance of conflict to print the to the console afterwards.The conflict approximation might need some explaining : Say I have a ScheduleUnit (call it Unit1) from 1:00 to 3:00 (AM) And another Schedule Unit (call it Unit2) from 2:30 to 4:30 (AM)The bit representation of those units are respectively Unit1 : 001111Unit2 : 000001111The bitwise & comparison would result of :001111 & 000001111 = 000001000Meaning we have a conflict between 2:30 and 3:00/// <summary>/// A schedule unit in time, must start and end on the same day/// </summary>public struct ScheduleUnit{ public Guid Id { get; } public DayOfWeek DayOfWeek { get; } public DateTime Start { get; } public DateTime End { get; } /// <summary> /// Builds an instance of the ScheduleUnit class /// </summary> /// <param name=start>Starting time of the unit</param> /// <param name=end>Ending time of the unit</param> /// <remarks>Both start and end mus be on the same day.</remarks> public ScheduleUnit(DateTime start, DateTime end) { if(start.DayOfWeek != end.DayOfWeek) throw new NotSupportedException(No support for schedule conflict unit on separated days.); Id = Guid.NewGuid(); Start = start; End = end; DayOfWeek = start.DayOfWeek; }}/// <summary>/// A schedule's conflict/// </summary>public class ScheduleConflict{ public IEnumerable<ScheduleUnit> UnitsInConflict { get; } /// <summary> /// Builds an instance of the ScheduleConflict class /// </summary> /// <param name=unitsInConflicts>Units in conflict</param> public ScheduleConflict(params ScheduleUnit[] unitsInConflicts) { UnitsInConflict = new List<ScheduleUnit>(unitsInConflicts); } public override string ToString() { return $Conflict in {String.Join(,,UnitsInConflict.Select(c => c.Id))}{Environment.NewLine}Between { UnitsInConflict.Min(c => c.Start)} and { UnitsInConflict.Min(c => c.End)}; }}/// <summary>/// A time schedule that manages conflicts/// </summary>public class Schedule{ private readonly TimeSpan _minimalUnitTimeSpan; public ICollection<ScheduleUnit> ScheduleUnits { get; } /// <summary> /// Builds an instance of the Schedule class /// </summary> /// <param name=minimalUnitTimeSpan>Minimal timespan that an unit can occupy</param> public Schedule(TimeSpan minimalUnitTimeSpan) { _minimalUnitTimeSpan = minimalUnitTimeSpan; ScheduleUnits = new List<ScheduleUnit>(); } /// <summary> /// Computes an approximation of conflicts in the schedule based on the minimal unit's time span /// </summary> /// <returns>List of conflicts</returns> public IEnumerable<ScheduleConflict> ComputeApproximatedScheduleConflicts() { List<ScheduleConflict> conflicts = new List<ScheduleConflict>(); foreach (var dayOfWeek in Enum.GetValues(typeof(DayOfWeek))) { conflicts.AddRange(ComputeApproximatedScheduleConflictsForADay((DayOfWeek)dayOfWeek)); } return conflicts; } /// <summary> /// Computes an approximation of conflicts for one day in the schedule based on the minimal unit's time span /// </summary> /// <param name=dayOfWeek>Day of the week to compute</param> /// <returns>List of conflicts</returns> public IEnumerable<ScheduleConflict> ComputeApproximatedScheduleConflictsForADay(DayOfWeek dayOfWeek) { var dailyUnits = (from unit in ScheduleUnits where unit.DayOfWeek == dayOfWeek select new { ConflictBits = ApproximateConflictBits(unit, _minimalUnitTimeSpan), Unit = unit }).ToList(); var copyDailyUnits = dailyUnits.ToList(); foreach (var dailyUnit in dailyUnits) { foreach (var dailyUnitCompared in copyDailyUnits) { //The AND operator will find conflicting times. long conflicts = dailyUnit.ConflictBits & dailyUnitCompared.ConflictBits; if (conflicts == 0 || dailyUnitCompared == dailyUnit) continue; yield return new ScheduleConflict(dailyUnit.Unit,dailyUnitCompared.Unit); } copyDailyUnits.Remove(dailyUnit); } } /// <summary> /// Computes an approximation of the conflicts in the schedule using bit shifting. /// </summary> /// <param name=scheduleUnit>Unit to compute</param> /// <param name=minimalUnitTimeSpan>Minimal time span a unit can occupy</param> /// <returns>Int64 where setted bits represent a time slot in conflict according to minimal unit timespan</returns> /// <example> /// Where MinimalUnitTimeSpan = 30 /// And unit between 1:00 and 3:00 /// returns : 001111 /// If units between 1:30 and 4:00 /// returns : 00011111 /// </example> private static long ApproximateConflictBits(ScheduleUnit scheduleUnit, TimeSpan minimalUnitTimeSpan) { int startBlocks = (int)(scheduleUnit.Start.TimeOfDay.TotalMinutes) / minimalUnitTimeSpan.Minutes; int endBlocks = ((int)(scheduleUnit.End.TimeOfDay.TotalMinutes) / minimalUnitTimeSpan.Minutes) - 1; long timeBits = 1; for (int i = 0; i < startBlocks; i++) timeBits <<= 1; long bitPointer = timeBits; for (int i = startBlocks; i < endBlocks; i++) timeBits |= (bitPointer <<= 1); return timeBits; }}class TimeConflictsFinder{ static void Main(string[] c) { TimeSpan scheduleSpan = TimeSpan.FromMinutes(30); DateTime dt1 = new DateTime(2015, 01, 01, 1, 0, 0); DateTime dt2 = new DateTime(2015, 01, 01, 1, 30, 0); var scheduleUnit1 = new ScheduleUnit(dt1,dt1.AddHours(2)); var scheduleUnit2 = new ScheduleUnit(dt2,dt2.AddHours(2).AddMinutes(30)); Schedule schedule = new Schedule(scheduleSpan); schedule.ScheduleUnits.Add(scheduleUnit1); schedule.ScheduleUnits.Add(scheduleUnit2); var conflicts = schedule.ComputeApproximatedScheduleConflicts(); foreach (var scheduleConflict in conflicts) { Console.WriteLine(scheduleConflict); Console.WriteLine(-------------------------------------------------); } Console.ReadKey(); }} | Schedule conflicts approximating program | c#;datetime | Have to run off to a long meeting, but this doesn't look right:/// <summary>/// Builds an instance of the ScheduleUnit class/// </summary>/// <param name=start>Starting time of the unit</param>/// <param name=end>Ending time of the unit</param>/// <remarks>Both start and end mus be on the same day.</remarks>public ScheduleUnit(DateTime start, DateTime end){ if(start.DayOfWeek != end.DayOfWeek) throw new NotSupportedException(No support for schedule conflict unit on separated days.); Id = Guid.NewGuid(); Start = start; End = end; DayOfWeek = start.DayOfWeek;}The comment clearly says the start and end must be the same day and merely checking DayOfWeek does not help much. It could be today (Thursday) and Thursday a week ago. I think you would need to check 2 things:1) start and end have the same .Kind, and2) start and end have the same .Date. |
_webapps.30791 | I am able to upload an image to a card, but it won't show a thumbnail as the cover image of the card. The image I uploaded is from my computer, not from Google Drive. We have seen this behavior when uploading from Google Drive, but not from computer.Any ideas? | Trello card covers | trello | null |
_unix.87067 | BackgroundRecently I upgraded php to version 5.5. Within this upgrade module for json was moved out from php5 package into a new package php5-json. So I installed it.Now the connection with firephp (and firebug).Before sending, firephp::log encodes the variable with json_encode.There might occur an issue with json_encode. The json_encode may fail to encode the input variable. This might happen in a string with unencoded unicode or a string with some ill encoded characters.Behaviour in previous version of phpIn firebug instead of the value with the wrong coding white space appears.After the wrong value firebug continues to display next values which arrived from firephp.Behaviour with separate php5-jsonWhen the ill encoded value arrives to firebug, following error message appears:SyntaxError: JSON.parse: unexpected character chrome://firephp/content/lib/renderer.js Line 159 After this listing logs from firephp stops.QuestionI understand that there was an 'unexpected character'. But I'd just like to move on and see the following messages. Not stop on the first unexpected character.What shall I do to solve the issue? Or at least get back to the previous bevior?Software versions:Debian testing jessie Linux host 3.10-2-amd64 #1 SMP Debian 3.10.5-1 (2013-08-07) x86_64 GNU/Linux php5 5.5.1+dfsg-2 php5-json 1.3.1+dfsg-1 iceweasel 22.0 FirePHPCore-0.3.2 Firebug 1.11.4 Firephp 0.7.2 Edit:I also can see in Firebug header X-Wf-1-1-1-2:[{Type:LOG,Label:$someVar,File:/home/GIT/www/some/path/someFile.php,Line:156},]Which does miss the value part and thus is not valid JSON, which is why the rendering fails.The header with the correct message, which gets printed:[{Type:LOG,Label:POST data,File:/home/GIT/www/some/path/someFile.php,Line:22},{data:{myarray:[117]},getA:true,getB:true}]Edit2:I submitted this as a bug in Debian 719942. But it doesn't seem that someone is willing to have a look at it :-( | Package php5-json breaks firephp | debian;php;firefox;json | Background:There is a licensing conflict with Linux distributions over a clause in Crockford's license which states:The Software shall be used for Good, not Evil.This does not agree with the Free Software Foundations (FSF) freedom 0:The freedom to run the program for any purpose. (source) The solution to it shall be a newly written library pecl-json-c packaged as php5-json. The newly used json library doesn't seem to be compatible with firephp. But if you will use software for Good, not Evil, you might want to restore the original Crockford's library.Steps to restore the Crockford's library1) Get the original json 1.2.1 library and unzip it.2) Install php5-dev (in Debian sudo apt-get install php5-dev) which comes with phpize tool. (source: How to create PHP extensions).3) As jacekk suggests you need to replace one occurrence of function_entry in json.c with zend_function_entry.4) As Star suggests you need to replace ZVAL_DELREF with Z_DELREF_P in three places in file JSON_parser.c.5) Then you change directory to the json-1.2.1 and run phpize./configuremake6) Unfortunatelly you can't remove the package php5-json, because it will take with it the whole php. Instead you need to locate the library json.so (dpkg -L php5-json | grep json.so will do).7) As the root replace the Remi's json.so with Crockford's json.so you just compiled. DrawbacksWith the next upgrade of php5-json you'll get back Remi's library.You are now using non-free software.You are messing-up with your system.Some people claim that the Remi's library has more features, which is probably true, because the Crockford's library is from 2005. |
_computerscience.3615 | I have a base 3D mesh of an object that I want to texturize. I also have a 360 degrees video of the real-world object.What are good ways to use the video to texturize the mesh? Are there existing tools to do that? (paid or free)Edit: I have complete control over the camera and object positions, I can measure the distances and whatever needed. I can also put markers on the object. | How to texturize a 3D model from video? | algorithm;3d;3dtexture | null |
_webapps.73866 | I have created forms in Cognito for several languages and if I have read the location settings help page right the settings only change on the country you register in, not by form.Am I able to change this? | Change location settings across all Cognito Forms | cognito forms | null |
_datascience.14203 | I am currently working on the data set from this link. But I am unable to read these files from Pandas? Has anyone tried to play with such files?I am trying the following:import pandas as pddf = pd.read_csv(m_4549381c276b46c6.0000)But I get the following errorError tokenizing data. C error: Buffer overflow caught - possible malformed input file. | Pandas: how to read certain file type in pandas | python;pandas | null |
_scicomp.10452 | I have two 50000 x 50000 binary matrices A and B for solving A*x=lambda*B*x eigenvalue problem. These matrices are sparse. I am trying to solve using PETSC and SLEPC. My memory requirement shoots off like more than 200 GB of RAM ! I used mpirun in 16 cores and 96GB RAM with swap of 130GB. Is there a way to solve this problem.? Am I doing something wrong ?Kindly let me know. | How to reduce RAM requirement in PETSC and SLEPCreading large binary matrices | petsc | null |
_webmaster.52886 | I have a website that is not on ASP anymore, it's a Drupal 7 website now.I need to use an .htaccess file to redirect with code 301 all pages with .asp extension to the 404 page or a specific URL.(Background story: Drupal will catch non-existing pages such as domain.com/test and redirect to 404 page. But Drupal will not catch non-existing pages with ASP extension such as domain.com/test.asp and it will instead serve a generic Not Found Apache page.)For example, if someone tries to access domain.com/test.asp, the user should be taken to domain.com/404I have searched and searched but I can't find a solution to this particular problem. How can I code that in an .htaccess file? | 301 redirect all pages with a specific extension | seo;htaccess;apache;301 redirect;drupal | null |
_cs.9556 | I'm in a course about computing and complexity, and am unable to understand what these terms mean. All I know is that NP is a subset of NP-complete, which is a subset of NP-hard, but I have no idea what they actually mean. Wikipedia isn't much help either, as the explanations are still a bit too high level. | What is the definition of $P$, $NP$, $NP$-complete and $NP$-hard? | complexity theory;terminology;complexity classes;p vs np;reference question | I think the Wikipedia articles $\mathsf{P}$, $\mathsf{NP}$, and $\mathsf{P}$ vs. $\mathsf{NP}$ are quite good. Still here is what I would say: Part I, Part II[I will use remarks inside brackets to discuss some technical details whichyou can skip if you want.]Part IDecision ProblemsThere are various kinds of computational problems. However in an introduction to computational complexity theory course it is easier to focus on decision problem, i.e. problems where the answer is either YES or NO. There are other kinds of computational problems but most of the time questions about them can be reduced to similar questions about decision problems. Moreover decision problems are very simple. Therefore in an introduction to computational complexity theory course we focus our attention to the study of decision problems.We can identify a decision problem with the subset of inputs that have answer YES. This simplifies notation and allows us to write $x\in Q$ in place of $Q(x)=YES$ and $x \notin Q$ in place of $Q(x)=NO$.Another perspective is that we are talking about membership queries in a set. Here is an example:Decision Problem: Input: A natural number $x$, Question: Is $x$ an even number?Membership Problem:Input: A natural number $x$, Question: Is $x$ in $Even = \{0,2,4,6,\cdots\}$?We refer to the YES answer on an input as accepting the input and to the NO answer on an input as rejecting the input.We will look at algorithms for decision problems anddiscuss how efficient those algorithms are in their usage of computable resources.I will rely on your intuition from programming in a language like Cin place of formally defining what we mean by an algorithm and computational resources.[Remarks: 1. If we wanted to do everything formally and precisely we would need to fix a model of computation like the standard Turing machine modelto precisely define what we mean by an algorithm and its usage of computational resources.2. If we want to talk about computation over objects that the model cannot directly handle,we would need to encode them as objects that the machine model can handle,e.g. if we are using Turing machines we need to encode objects like natural numbers and graphs as binary strings.]$\mathsf{P}$ = Problems with Efficient Algorithms for Finding SolutionsAssume that efficient algorithms means algorithms that use at most polynomial amount of computational resources. The main resource we care about is the worst-case running time of algorithms with respect to the input size,i.e. the number of basic steps an algorithm takes on an input of size $n$. The size of an input $x$ is $n$ if it takes $n$-bits of computer memory to store $x$,in which case we write $|x| = n$.So by efficient algorithms we mean algorithms that have polynomial worst-case running time.The assumption that polynomial-time algorithms capture the intuitive notion of efficient algorithms is known as Cobham's thesis. I will not discuss at this pointwhether $\mathsf{P}$ is the right model for efficiently solvable problems andwhether $\mathsf{P}$ does or does not capture what can be computed efficiently in practice and related issues. For now there are good reasons to make this assumption so for our purpose we assume this is the case. If you do not accept Cobham's thesis it does not make what I write below incorrect, the only thing we will lose is the intuition about efficient computation in practice. I think it is a helpful assumption for someone who is starting to learn about complexity theory.$\mathsf{P}$ is the class of decision problems that can be solved efficiently, i.e. decision problems which have polynomial-time algorithms.More formally, we say a decision problem $Q$ is in $\mathsf{P}$ iffthere is an efficient algorithm $A$ such that for all inputs $x$, if $Q(x)=YES$ then $A(x)=YES$, if $Q(x)=NO$ then $A(x)=NO$.I can simply write $A(x)=Q(x)$ but I write it this way so we can compare it to the definition of $\mathsf{NP}$.$\mathsf{NP}$ = Problems with Efficient Algorithms for Verifying Proofs/Certificates/WitnessesSometimes we do not know any efficient way of finding the answer to a decision problem,however if someone tells us the answer and gives us a proofwe can efficiently verify that the answer is correctby checking the proof to see if it is a valid proof.This is the idea behind the complexity class $\mathsf{NP}$.If the proof is too long it is not really useful, it can take too long to just read the proof let alone check if it is valid. We want the time required for verification to be reasonable in the size of the original input, not the size of the given proof! This means what we really want is not arbitrary long proofs but short proofs.Note that if the verifier's running time is polynomial in the size of the original input then it can only read a polynomial part of the proof. So by short we mean of polynomial size.Form this point on whenever I use the word proof I mean short proof.Here is an example of a problem which we do not know how to solve efficiently but we can efficiently verify proofs:PartitionInput: a finite set of natural numbers $S$,Question: is it possible to partition $S$ into two sets $A$ and $B$ ($A \cup B = S$ and $A \cap B = \emptyset$) such that the sum of the numbers in $A$ is equal to the sum of number in $B$ ($\sum_{x\in A}x=\sum_{x\in B}x$)?If I give you $S$ and ask you if we can partition it into two sets such thattheir sums are equal, you do not know any efficient algorithm to solve it. You will probably try all possible ways of partitioning the numbers into two sets until you find a partition where the sums are equal or until you have tried all possible partitions and none has worked. If any of them worked you would say YES, otherwise you would say NO. But there are exponentially many possible partitions so it will take a lot of time. However if I give you two sets $A$ and $B$, you can easily check if the sums are equal and if $A$ and $B$ is a partition of $S$. Note that we can compute sums efficiently. Here the pair of $A$ and $B$ that I give you is a proof for a YES answer. You can efficiently verify my claim by looking at my proof and checking if it is a valid proof. If the answer is YES then there is a valid proof, and I can give it to you and you can verify it efficiently. If the answer is NO then there is no valid proof. So whatever I give you you can check and see it is not a valid proof.I cannot trick you by an invalid proof that the answer is YES.Recall that if the proof is too big it will take a lot of time to verify it, we do not want this to happen, so we only care about efficient proofs, i.e. proofs which have polynomial size.Sometimes people use certificate or witness in place of proof. Note I am giving you enough information about the answer for a given input $x$ so that you can find and verify the answer efficiently.For example, in our partition example I do not tell you the answer, I just give you a partition, and you can check if it is valid or not. Note that you have to verify the answer yourself, you cannot trust me about what I say.Moreover you can only check the correctness of my proof.If my proof is valid it means the answer is YES.But if my proof is invalid it does not mean the answer is NO.You have seen that one proof was invalid, not that there are no valid proofs.We are talking about proofs for YES.We are not talking about proofs for NO.Let us look at an example: $A=\{2,4\}$ and $B=\{1,5\}$ is a proof that $S=\{1,2,4,5\}$ can be partitioned into two sets with equal sums. We just need to sum up the numbers in $A$ and the numbers in $B$ and see if the results are equal, and check if $A$, $B$ is partition of $S$.If I gave you $A=\{2,5\}$ and $B=\{1,4\}$, you will check and see that my proof is invalid. It does not mean the answer is NO, it just means that this particular proof was invalid. Your task here is not to find the answer, but only to check if the proof you are given is valid. It is like a student solving a question in an exam and a professor checking if the answer is correct. :) (unfortunately often students do not give enough information to verify the correctness of their answer and the professors have to guess the rest of their partial answer and decide how much mark they should give to the students for their partial answers,indeed a quite difficult task).The amazing thing is that the same situation applies to many other natural problems that we want to solve:we can efficiently verify if a given short proof is valid, but we do not know any efficient way of finding the answer. This is the motivation why the complexity class $\mathsf{NP}$ is extremely interesting(though this was not the original motivation for defining it). Whatever you do (not just in CS, but also in math, biology, physics, chemistry, economics, management, sociology, business, ...) you will face computational problems that fall in this class.To get an idea of how many problems turn out to be in $\mathsf{NP}$ check out a compendium of NP optimization problems.Indeed you will have hard time finding natural problems which are not in $\mathsf{NP}$.It is simply amazing.$\mathsf{NP}$ is the class of problems which have efficient verifiers, i.e. there is a polynomial time algorithm that can verify if a given solution is correct. More formally, we say a decision problem $Q$ is in $\mathsf{NP}$ iffthere is an efficient algorithm $V$ called verifier such that for all inputs $x$, if $Q(x)=YES$ then there is a proof $y$ such that $V(x,y)=YES$,if $Q(x)=NO$ then for all proofs $y$, $V(x,y)=NO$.We say a verifier is soundif it does not accept any proof when the answer is NO. In other words, a sound verifier cannot be tricked to accept a proof if the answer is really NO.No false positives.Similarly, we say a verifier is complete if it accepts at least one proof when the answer is YES.In other words, a complete verifier can be convinced of the answer being YES.The terminology comes from logic and proof systems.We cannot use a sound proof system to prove any false statements.We can use a complete proof system to prove all true statements.The verifier $V$ gets two inputs, $x$ : the original input for $Q$, and $y$ : a suggested proof for $Q(x)=YES$.Note that we want $V$ to be efficient in the size of $x$. If $y$ is a big proof the verifier will be able to read only a polynomial part of $y$. That is why we require the proofs to be short. If $y$ is short saying that $V$ is efficient in $x$ is the same as saying that $V$ is efficient in $x$ and $y$ (because the size of $y$ is bounded by a fixed polynomial in the size of $x$).In summary, to show that a decision problem $Q$ is in $\mathsf{NP}$ we have to give an efficient verifier algorithm which is sound and complete.Historical Note:historically this is not the original definition of $\mathsf{NP}$. The original definition uses what is called non-deterministic Turing machines. These machines do not correspond to any actual machine model and are difficult to get used to (at least when you are starting to learn about complexity theory). I have read that many experts think that they would have used the verifier definition as the main definition and even would have named the class $\mathsf{VP}$ (for verifiable in polynomial-time) in place of $\mathsf{NP}$ if they go back to the dawn of the computational complexity theory. The verifier definition is more natural, easier to understand conceptually, and easier to use to show problems are in $\mathsf{NP}$.$\mathsf{P}\subseteq \mathsf{NP}$Therefore we have $\mathsf{P}$=efficient solvable and $\mathsf{NP}$=efficiently verifiable. So $\mathsf{P}=\mathsf{NP}$ iff the problems that can be efficiently verified are the same as the problems that can be efficiently solved.Note that any problem in $\mathsf{P}$ is also in $\mathsf{NP}$, i.e. if you can solve the problem you can also verify if a given proof is correct:the verifier will just ignore the proof! That is because we do not need it, the verifier can compute the answer by itself, it can decide if the answer is YES or NO without any help.If the answer is NO we know there should be no proofs and our verifier will just reject every suggested proof. If the answer is YES, there should be a proof, and in fact we will just accept anything as a proof.[We could have made our verifier accept only some of them, that is also fine, as long as our verifier accept at lest one proof the verifier works correctly for the problem.]Here is an example: SumInput: a list of $n+1$ natural numbers $a_1,\cdots,a_n$, and $s$,Question: is $\Sigma_{i=1}^n a_i = s$?The problem is in $\mathsf{P}$ because we can sum up the numbers and then compare it with $s$, we return YES if they are equal, and NO if they are not.The problem is also in $\mathsf{NP}$. Consider a verifier $V$ that gets a proof plus the input for Sum. It acts the same way as the algorithm in $\mathsf{P}$ that we described above. This is an efficient verifier for Sum.Note that there are other efficient verifiers for Sum, and some of them might use the proof given to them. However the one we designed does not and that is also fine. Since we gave an efficient verifier for Sum the problem is in $\mathsf{NP}$. The same trick works for all other problems in $\mathsf{P}$ so $\mathsf{P} \subseteq \mathsf{NP}$.Brute-Force/Exhaustive-Search Algorithms for $\mathsf{NP}$ and $\mathsf{NP}\subseteq \mathsf{ExpTime}$The best algorithms we know of for solving an arbitrary problem in $\mathsf{NP}$ are brute-force/exhaustive-search algorithms.Pick an efficient verifier for the problem(it has an efficient verifier by our assumption that it is in $\mathsf{NP}$) andcheck all possible proofs once by one. If the verifier accepts one of them then the answer is YES.Otherwise the answer is NO. In our partition example, we try all possible partitions and check if the sums are equal in any of them.Note that the brute-force algorithm runs in worst-case exponential time.The size of the proofs is polynomial in the size of input.If the size of the proofs is $m$ then there are $2^m$ possible proofs.Checking each of them will take polynomial time by the verifier.So in total the brute-force algorithm takes exponential time.This shows that any $\mathsf{NP}$ problem can be solved in exponential time, i.e. $\mathsf{NP}\subseteq \mathsf{ExpTime}$. (Moreover the brute-force algorithm will use only a polynomial amount of space, i.e. $\mathsf{NP}\subseteq \mathsf{PSpace}$ but that is a story for another day). A problem in $\mathsf{NP}$ can have much faster algorithms, for example any problem in $\mathsf{P}$ has a polynomial-time algorithm. However for an arbitrary problem in $\mathsf{NP}$ we do not know algorithms that can do much better. In other words, if you just tell me that your problem is in $\mathsf{NP}$ (and nothing else about the problem)then the fastest algorithm that we know of for solving it takes exponential time.However it does not mean that there are not any better algorithms, we do not know that. As far as we know it is still possible (though thought to be very unlikely by almost all complexity theorists) that $\mathsf{NP}=\mathsf{P}$ and all $\mathsf{NP}$ problems can be solved in polynomial time.Furthermore, some experts conjecture that we cannot do much better, i.e. there are problems in $\mathsf{NP}$ that cannot be solved much more efficiently than brute-force search algorithms which take exponential amount of time.See the Exponential Time Hypothesis for more information.But this is not proven, it is only a conjecture.It just shows how far we are from finding polynomial time algorithms for arbitrary $\mathsf{NP}$ problems.This association with exponential time confuses some people: they think incorrectly that $\mathsf{NP}$ problems require exponential-time to solve (or even worse there are no algorithm for them at all). Stating that a problem is in $\mathsf{NP}$ does not mean a problem is difficult to solve, it just means that it is easy to verify, it is an upper bound on the difficulty of solving the problem, and many $\mathsf{NP}$ problems are easy to solve since $\mathsf{P}\subseteq\mathsf{NP}$.Nevertheless, there are $\mathsf{NP}$ problems which seem to be hard to solve. I will return to this in when we discuss $\mathsf{NP}$-hardness. Lower Bounds Seem Difficult to ProveOK, so we now know that there are many natural problems that are in $\mathsf{NP}$ and we do not know any efficient way of solving them and we suspect that they really require exponential time to solve. Can we prove this? Unfortunately the task of proving lower bounds is very difficult. We cannot even prove that these problems require more than linear time! Let alone requiring exponential time.Proving linear-time lower bounds is rather easy: the algorithm needs to read the input after all. Proving super-linear lower bounds is a completely different story.We can prove super-linear lower boundswith more restrictions about the kind of algorithms we are considering,e.g. sorting algorithms using comparison,but we do not know lower-bounds without those restrictions.To prove an upper bound for a problem we just need to design a good enough algorithm. It often needs knowledge, creative thinking, and even ingenuity to come up with such an algorithm. However the task is considerably simpler compared to proving a lower bound. We have to show that there are no good algorithms. Not that we do not know of any good enough algorithms right now, but that there does not exist any good algorithms, that no one will ever come up with a good algorithm. Think about it for a minute if you have not before, how can we show such an impossibility result? This is another place where people get confused. Here impossibility is a mathematical impossibility, i.e. it is not a short coming on our part that some genius can fix in future. When we say impossible we mean it is absolutely impossible, as impossible as $1=0$. No scientific advance can make it possible. That is what we are doing when we are proving lower bounds. To prove a lower bound, i.e. to show that a problem requires some amount of time to solve, means that we have to prove that any algorithm, even very ingenuous ones that do not know yet, cannot solve the problem faster. There are many intelligent ideas that we know of (greedy, matching, dynamic programming, linear programming, semidefinite programming, sum-of-squares programming, and many other intelligent ideas) and there are many many more that we do not know of yet. Ruling out one algorithm or one particular idea of designing algorithms is not sufficient, we need to rule out all of them, even those we do not know about yet,even those may not ever know about! And one can combine all of these in an algorithm, so we need to rule out their combinations also. There has been some progress towards showing that some ideas cannot solve difficult $\mathsf{NP}$ problems, e.g. greedy and its extensions cannot work,and there are some work related to dynamic programming algorithms,and there are some work on particular ways of using linear programming.But these are not even close to ruling out the intelligent ideas that we know of (search for lower-bounds in restricted models of computation if you are interested).Barriers: Lower Bounds Are Difficult to ProveOn the other hand we have mathematical results called barriers that say that a lower-bound proof cannot be such and such, and such and such almost covers all techniques that we have used to prove lower bounds! In fact many researchers gave up working on proving lower bounds after Alexander Razbarov and Steven Rudich's natural proofs barrier result. It turns out that the existence of particular kind of lower-bound proofs would imply the insecurity of cryptographic pseudorandom number generators and many other cryptographic tools.I say almost because in recent years there has been some progress mainly by Ryan Williams that has been able to intelligently circumvent the barrier results, still the results so far are for very weak models of computation and quite far from ruling out general polynomial-time algorithms.But I am diverging. The main point I wanted to make was that proving lower bounds is difficult and we do not have strong lower bounds for general algorithms solving $\mathsf{NP}$ problems.[On the other hand, Ryan Williams' work shows that there are close connections between proving lower bounds and proving upper bounds.See his talk at ICM 2014 if you are interested.]Reductions: Solving a Problem Using Another Problem as a Subroutine/Oracle/Black BoxThe idea of a reduction is very simple: to solve a problem, use an algorithm for another problem.Here is simple example: assume we want to compute the sum of a list of $n$ natural numbers and we have an algorithm $Sum$ that returns the sum of two given numbers. Can we use $Sum$ to add up the numbers in the list? Of course!Problem:Input: a list of $n$ natural numbers $x_1,\ldots,x_n$, Output: return $\sum_{i=1}^{n} x_i$. Reduction Algorithm:$s = 0$for $i$ from $1$ to $n$ 2.1. $s = Sum(s,x_i)$ return $s$ Here we are using $Sum$ in our algorithm as a subroutine. Note that we do not care about how $Sum$ works, it acts like black box for us, we do not care what is going on inside $Sum$. We often refer to the subroutine $Sum$ as oracle. It is like the oracle of Delphi in Greek mythology, we ask questions and the oracle answers them and we use the answers.This is essentially what a reduction is: assume that we have algorithm for a problem and use it as an oracle to solve another problem. Here efficient means efficient assuming that the oracle answers in a unit of time, i.e. we count each execution of the oracle a single step.If the oracle returns a large answer we need to read it and that can take some time, so we should count the time it takes us to read the answer that oracle has given to us. Similarly for writing/asking the question from the oracle. But oracle works instantly, i.e. as soon as we ask the question from the oracle the oracle writes the answer for us in a single unit of time. All the work that oracle does is counted a single step, but this excludes the time it takes us to write the question and read the answer. Because we do not care how oracle works but only about the answers it returns we can make a simplification and consider the oracle to be the problem itself in place of an algorithm for it. In other words,we do not care if the oracle is not an algorithm, we do not care how oracles comes up with its replies.For example, $Sum$ in the question above is the addition function itself (not an algorithm for computing addition).We can ask multiple questions from an oracle, and the questions does not need to be predetermined: we can ask a question and based on the answer that oracle returns we perform some computations by ourselves and then ask another question based on the answer we got for the previous question.Another way of looking at this is thinking about it as an interactive computation. Interactive computation in itself is large topic so I will not get into it here, but I think mentioning this perspective of reductions can be helpful.An algorithm $A$ that uses a oracle/black box $O$ is usually denoted as $A^O$.The reduction we discussed above is the most general form of a reduction and is known as black-box reduction(a.k.a. oracle reduction, Turing reduction).More formally:We say that problem $Q$ is black-box reducible to problem $O$ and write $Q \leq_T O$ iff there is an algorithm $A$ such that for all inputs $x$, $Q(x) = A^O(x)$.In other words if there is an algorithm $A$ which uses the oracle $O$ as a subroutine and solves problem $Q$.If our reduction algorithm $A$ runs in polynomial time we call it a polynomial-time black-box reduction or simply a Cook reduction(in honor of Stephen A. Cook) and write $Q\leq^\mathsf{P}_T O$.(The subscript $T$ stands for Turing in the honor ofAlan Turing).However we may want to put some restrictions on the way the reduction algorithm interacts with the oracle. There are several restrictions that are studied but the most useful restriction is the one called many-one reductions(a.k.a. mapping reductions). The idea here is that on a given input $x$, we perform some polynomial-time computation and generate a $y$ that is an instance of the problem the oracle solves.We then ask the oracle and return the answer it returns to us. We are allowed to ask a single question from the oracle and the oracle's answers is what will be returned.More formally,We say that problem $Q$ is many-one reducible to problem $O$ and write $Q \leq_m O$ iff there is an algorithm $A$ such that for all inputs $x$, $Q(x) = O(A(x))$.When the reduction algorithm is polynomial time we call it polynomial-time many-one reduction or simply Karp reduction (in honor of Richard M. Karp) and denote it by $Q \leq_m^\mathsf{P} O$.The main reason for the interest in this particular non-interactive reduction is that it preserves $\mathsf{NP}$ problems: if there is a polynomial-time many-one reduction from a problem $A$ to an $\mathsf{NP}$ problem $B$, then $A$ is also in $\mathsf{NP}$.The simple notion of reduction is one of the most fundamental notions in complexity theory along with $\mathsf{P}$, $\mathsf{NP}$, and $\mathsf{NP}$-complete (which we will discuss below).The post has become too long and exceeds the limit of an answer (30000 characters).I will continue the answer in Part II. |
_cstheory.37167 | Often I find myself needing to know the best error correcting code for a certain quantum scenario. For example, suppose my logical systems are 3-dimensional; then what's the most efficient encoding to resist at most 4 single-system errors? Of, suppose my logical systems are qubits; then what's the most efficient encoding to resist 5 single-qubit phase errors?Presumably for many questions like this, the answers are known. Is there a good survey that gives the state-of-the-art? | Cutting edge of quantum error correction | quantum computing;quantum information | null |
_cs.6379 | I am working on problem (15-11) Inventory planning from Introduction to Algorithms (CLRS, 3rd Ed).15-11: Inventory Planning, p.411The Rinky Dink Company makes machines that resurface ice rinks. The demand for such products varies from month to month, and so the company needs to develop a strategy to plan its manufacturing given the fluctuating, but predictable, demand. The company wishes to design a plan for the next $n$ months. For each month $i$, the company knows the demand $d_i$, that is, the number of machines that it will sell. Let $D = \displaystyle\sum_{i=1}^{n} d_i $ be the total demand over the next $n$ months. The company keeps a full-time staff who provide labor to manufacture up to m machines in a given month, it can hire additional, part-time labor, at a cost that works out to c dollars per machine. Furthermore, if, at the end of a month, the company is holding any unsold machines, it must pay inventory costs. The cost for holding j machines is given as a function $h(j)$ for $u = 1, 2, ... , D$, where $h(j) \ge 0$ for $1 \le j \le D$ and $h(j) \le h(j+1)$ for $j \le 1 \le D - 1$. Give an algorithm that calculates a plan for the company that minimizes its costs while fulfilling all the demand. The running time should be polynomical in $n$ and $D$.In other words, problem asks to create dynamic programming algorithm that solves this problem.So far, I came up the the following solution, and not sure if it is any good.Optimal sub-problem:Let $MinCost(i,j)$ be the function that returns minimized cost of operation for past $i$ months, $j$ is the number of unsold machines left at the end of the month $i$.(Goal, is to calculate $MinCost(n,0)$, in other words, at the end of planning period(month $n$), there are no unsold machines.) So, the DP recurrence is given by $MinCost(0,0) = 0$ and$\quad MinCost(i,j) = \min\{MinCost(i-1,j-k) + c(k,j,i) + h(j) \mid 1 \le k \le D \}$for $i+j > 0$; here, $c(k,j,i)$ is the function that calculates the costs of the production.If my optimal sub-problem is correct, how do I create an algorithm to solve it? | Inventory planning problem solved through dynamic programming | algorithms;dynamic programming;check my algorithm | null |
_datascience.10713 | Learning about random forest for the first time and I'm not clear if at each level, if we've already used a feature to make a decision, whether we can use the same feature again at further levels. | Does random forest re-use features at each node when generating a decision tree? | random forest | null |
_webmaster.106832 | We are building car selling website where users can upload their second hand cars to be sold to other interested buyers. Currently we have a simple form where we ask user the vehicle and personal details before uploading the car on our website. We want to move up this page's search engine rankings. I just read that freshness or frequently changing pages rank higher in SEO. What if we start showing customers testimonials somewhere on this page. As these would be randomly picked, would keep on constantly changing, would it help me in improving search engine rankings of this page? | Do web pages that change constantly rank higher than pages with static content? | seo;ranking;fresh content | null |
_hardwarecs.7068 | what is the best GPU/Card to use for my work-only rig. I do mainly dev work, Webdesign, massive multitasking with sometimes over 50 browser tabs open on each monitor. I don't game on this PC at all. My current Hardware: CPU: i5 4690 @ 3.50GHzGeforce GTX 750Ti32 GB RAM Total of 3 Screens: 2 WQHD screens with a res of 2560 x 1440 1 FHD ScreenScreens are connected with HDMI and 2 with DVI since the Card does not have DP. | Multi monitor frustration | graphics cards;memory;multiple monitors | null |
_unix.128242 | Can anyone please expain me step by step below AWK script written.I have the below code written in my script to format the flat file data. Just wanted to understand so that i can reuse -- I am not a unix guy but task has being assigned to me.kindly help!awk -vsep=$SEPARATOR 'NR>2{if(NF){if(!s){gsub( *sep[ \t]*,sep);printf %d%s\n,NR-2,$0}}else s=1}' file_name > new_file # where $SEPARATOR = ';'Thanks in Advance. | Please explain the Awk script provided below | shell script;awk | null |
_unix.155631 | The documentation on Linux RHEL seems to assume you have a connected machine and will be installing through that connection. I need to set up RHEL completely offline using CD-ROMs only (no USB). Is this possible? If so, what is the general strategy? | Possible to install Linux RHEL completely offline? | rhel;system installation | null |
_cs.69655 | I've shown before many results to BPP[a,b]=BPP such as:BPP[a+1/n,a], BPP[0.05,0.01], BPP[2^-n,1-2^-n]...mostly by using chernoff bounds.recently I encountered the PP class, so I'm looking for some rule of thumb on how to know if a language is in BPP or PP according to the two possibilities.I noticed that for example a language with TM with [3/4, 3/4+1/2^n] probabilities is in PP.Also, I think I can rule RP/CO-RP if the one of the constants is 0,1 | what is the minimum difference that holds does BPP[a,b]=BPP | complexity theory;randomized algorithms | null |
_softwareengineering.333803 | After reading an article [1] regarding making GitHub a developer's resume, I began researching on open-source licensing and copyright articles. A question [2] in this forum was asked if an open-source code is found without license, can it be forked or modified for another purpose and the accepted answer was no, because the creator reserved his copyright and did not provide any license permitting other people to do so. I find this suitable for my needs because I want to create a portfolio and upload it to GitHub, for the sole purpose of showcasing my skills through my projects in code-level while reserving all the rights to myself since I don't want others to modify my projects for their purposes as well. But when I came across another article [3], which said that by uploading to GitHub, I am permitting other GitHub users to view and fork my repository. So is there another way to display my source code publicly while restricting all users for modifying my project for other purposes?Citations:http://anti-pattern.com/github-is-your-resume-nowOpen source code with no license... can I fork it?http://choosealicense.com/no-license/ | Is there a way to display your source code publicly with the restriction of collaborative modification? | licensing;open source;copyright | null |
_softwareengineering.210926 | The big question I have in my mind: how many developers are brownfield (enterprise) compared to greenfield (all new code, from the ground up).I'm constantly reading breathless articles about the latest technology, only to find out that It Just Won't Work On Our Enterprise Software codebase. People aren't ready for automated testing (because the logic is in the click-handlers and/or database). People aren't ready for ORM tools because we have horrendous amount of logic in stored procs and triggers. People aren't ready for WPF because our existing stuff is all WinForms. We can't get the latest version of Reactive Extensions because existing code used RX 1.0 and there are breaking changes that will require more testing effort than is justified by the return. Etc., etc., etc.Very few articles seem to be oriented toward the brownfield developer, for whatever reason (can't sell ads for articles that start off with you probably can't use this, but...?).So, I'm truly wondering: is the software development industry just chock full of greenfield developers, developing new projects for clients which are then released and enjoy a short existence until complete replacement for whatever reason? Or are there hordes of brownfield programmers silently laboring away in the ADO.NET T/SQL VB.NET software mines, looking wistfully up at the sunshine of Entity Framework 5.0 and Haskell, et cetera?How do we even measure that? Salaries (wages??) paid to software engineers* in the two categories? How do we measure THAT? Maybe... revenue generated from selling said software? (There's an assumption that the crappy old software sold by XYZ Corp. actually has maintainers).My question: Does anybody have any numbers that speaks to how much of the industry is green field vs. brown field? | Greenfield vs. brownfield revenue? (attempting to get an idea of measure of effort expended on the two) | industry;greenfield;brownfield | It is a well-known fact that most software development effort is spent maintaining existing software, not writing new software. Why? Because the first version of a program is only written once. Every subsequent version builds on the original, and steady revenue comes from steadily maintaining, promoting and upgrading an existing product, not from constantly creating brand new inventions.The life cycle of a software product can vary greatly. Some software systems written for banking on mainframes have life cycles measured in decades, while other programs only have an effective life of a few years (or less). For that reason, any attempt to quantify the relative percentage of effort on greenfield vs brownfield development would not be representative of the industry as a whole. |
_unix.122649 | SSH allows a remote user to issue some command without interactively logging in to the server, as the last line of ssh usage indicates:usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec] [-D [bind_address:]port] [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file] [-L [bind_address:]port:host:hostport] [-Q protocol_feature] [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port] [-R [bind_address:]port:host:hostport] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]] [user@]hostname [command]When ssh is invoked with a remote command, the .bash_history file does not get updated (i.e., the remote command is not added to .bash_history). I managed to simulate this effect by adding the following command to /etc/ssh/sshd_config:ForceCommand if [[ -z $SSH_ORIGINAL_COMMAND ]]; then bash; else printf $SSH_ORIGINAL_COMMAND\n >> .bash_history; bash -c $SSH_ORIGINAL_COMMAND; fiThe above command checks whether the environment variable $SSH_ORIGINAL_COMMAND is empty:If so, no remote command is issued, and we simply run bash.Otherwise, $SSH_ORIGINAL_COMMAND is added to .bash_history, and the remote command within $SSH_ORIGINAL_COMMAND is executed.It works as expected, but I need a bit more: I want the current timestamp to be added to .bash_history as well. To this end, I added the following command to /etc/ssh/sshd_config:ForceCommand if [[ -z $SSH_ORIGINAL_COMMAND ]]; then bash; else printf #`date +%s`\n$SSH_ORIGINAL_COMMAND\n >> .bash_history; bash -c $SSH_ORIGINAL_COMMAND; fiBut when I try to ssh to the server, I receive the following error:bash: -c: line 0: unexpected EOF while looking for matching `'bash: -c: line 1: syntax error: unexpected end of fileConnection to 127.0.0.1 closed.If I remove # before date +%s, it works correctly. But I need # to be printed before the timestamp, as it is the correct format for the .bash_history file. | Logging ssh remote commands to `bash_history` | bash;sshd | A # in sshd_config is interpreted as the beginning of a comment and everything following it is ignored. Although (according to sshd_config(5)) may be used to quote arguments containing spaces, they do not quote #. That also explains the error you get. sshd only passes the following to bash:if [[ -z $SSH_ORIGINAL_COMMAND ]]; then bash; else printf The second cannot be found as the command line ends just after the first one.To prevent this behaviour the literal # must not be used:As printf is used here anyway, using its capabilities to use backslash-escaped characters comes in handy. # can be written as \x23 (hexadecimal), \43 (octal), \u23 (Unicode, hexadecimal up to 4 hex digits) or even \U23 (Unicode, hexadecimal up to 8 hex digits). The same works for echo -e. Note that the \ has to be quoted, so use either \43, '\43' or \\43.In cases where you do not need echo or printf, you can get bash (works on zsh, too) to do the replacement by using $'string'. For example: to do touch foo#bar, you could write touch $'foo\x23bar'. If the value has less than the maximum amount of allowed digits (3 for octal, 2 for hexadecimal and 4 or 8 respectively for Unicode) you should use leading zeroes to avoid misinterpretations. For example: $'foo\u23bar' evaluates to foor while $'foo\u0023bar' gives the expected foo#bar. Avoid using # (literal or otherwise) alltogether by putting all functionality into a script and then just put ForceCommand /path/to/script in your configuration.The second option also allows you to forgo printf by using the format option of date more extensively. Instead ofprintf \x23`date +%s`\n$SSH_ORIGINAL_COMMAND\n >> .bash_historyYou can writedate $'+\x23%s'${SSH_ORIGINAL_COMMAND//%/%%} >> .bash_history |
_codereview.128909 | I have the following code where I need to execute 2 Linq-to-SQL statements. If I do not have the Any() in the if statement, then I receive error when the result is no data. However, I am not sure if my approach is efficient enough. Do you have any suggestions?My goal is to achieve the following with single Linq statement. I need to get the Sum, and get 0 if there are no results. if (db.BadgeAssignments.Any(bba => bba.UserIdReceiver == newbadgeassignment.UserIdReceiver && bba.BadgeAssociated.CourseId == courseId)) { currUserScore = db.BadgeAssignments .Where(bba => bba.UserIdReceiver == newbadgeassignment.UserIdReceiver && bba.BadgeAssociated.CourseId == courseId) .Sum(bba => bba.BadgeAssociated.Points); } | Calculating the .Sum() in Linq-to-SQL | c#;entity framework;linq to sql | You have:if (db.BadgeAssignments.Any(bba => bba.UserIdReceiver == newbadgeassignment.UserIdReceiver && bba.BadgeAssociated.CourseId == courseId))And later:.Where(bba => bba.UserIdReceiver == newbadgeassignment.UserIdReceiver && bba.BadgeAssociated.CourseId == courseId)The two lambdas:bba => bba.UserIdReceiver == newbadgeassignment.UserIdReceiver && bba.BadgeAssociated.CourseId == courseIdbba => bba.UserIdReceiver == newbadgeassignment.UserIdReceiver && bba.BadgeAssociated.CourseId == courseIdIdentical. .Any is \$O(n)\$, meaning worst-case, it will have to iterate all elements of the source to find one that matches the predicate; Where is also \$O(n)\$, meaning it will traverse all elements of the source to find all that match the predicate.currUserScore = db.BadgeAssignments .Where(bba => bba.UserIdReceiver == newbadgeassignment.UserIdReceiver && bba.BadgeAssociated.CourseId == courseId) .Sum(bba => bba.BadgeAssociated.Points);This does it once, and will return 0 if no match is made while iterating BadgeAssignments... and that leaves you with a single linq statement =)The predicate could be simplified further if you encapsulated it into a separate method:currUserScore = db.BadgeAssignments .Where(bba => IsMatch(bba, userId, courseId)) .Sum(bba => bba.BadgeAssociated.Points);The IsMatch function (//todo: find a better name) is the lambda's body:return bba.UserIdReceiver == userId && bba.BadgeAssociated.CourseId == courseId; |
_unix.40159 | I have two animations (.gif files) I want to run side-by-side. Can this be done with ImageMagick?Moreover, I want to start one of the gifs after thirty frames of the other have passed. Can this be done as well? Otherwise, I can manually insert thirty frames of blackness into one image, but it would be easier to automate this step with ImageMagick, because I will potentially be doing this many times. | Running two animations side-by-side using ImageMagick | command line;imagemagick | This script does the job :#!/bin/bash# $1 : first gif# $2 : second gifmkdir firstcd firstconvert $1 x%04d.gifcd ..mkdir secondcd secondconvert $2 x%04d.gifcd ..for filename in first/*do filename=`basename $filename` montage -tile 2x1 -geometry 512x512 first/$filename second/$filename concat$filenamedoneconvert concat* output.gifrm -rf firstrm -rf secondrm concat* |
_softwareengineering.83713 | my visually impaired sister uses a webcam with DIY stand as a digital magnifier to read printed texts.We wanted to initiate a project to create a software - in fact only a modified webcam viewer (like Cheese in Linux). Is it possible to have one SW for both platforms (Windows and Linux) = almost the same code, same filters and GUI, and just use the video stream using some standard protocol? Because most people use Win, but we would like to support Linux primarily.I am not sure if this is possible in windows. We need the software to take the video stream and apply some color and other effects like those described in this article. The idea is to maintain only one application (best would be open-source) with a small differences for both platforms. For the GUI, the GTK seems to be optimal as it is accessible for ScreenReader SW. Such app would not only help the visually impaired but also the elderly people.So, is this possible or is this idea really stupid?thanks :-D | Webcam software for both Windows and Linux possible? | windows;linux;accessibility | null |
_unix.24268 | I have a WD My Passport USB 3.0 500 GB hard diskI have successfully installed various OSes like Ubuntu, Pinguy, Mint etc. but so far I'm unsuccessful in installing Arch Linux.I used the net install CD and the installation is smooth, only when I reboot and boot off my hard disk I get an error saying cannot find filep (something along similar lines) and when I try booting again (without a reboot), I get:error 18 and and boot cylindar size exceeds maximum value type error.I tried rootdelay=8 from the Beginners' Guide on the Arch Wiki and after scavenging through forums even enabled usb in the hook file while installing.I still can't boot.If it's of any further help I have dual boot Windows 7 and Ubuntu on my laptop. My usb is partitioned as following:here is my menu.lst http://pastebin.com/FdAiHnXZand the errors | Arch Linux cannot boot | boot;arch linux | null |
_codereview.22822 | I have been trying to make a simple quiz program in Python. What I plan to make is, say, a quiz of 3 rounds and each round having 3 questions. And at the end of the every round, the program will prompt the user to go for the bonus question or not.print(Mathematics Quiz)question1 = Who is president of USA?options1 = a.Myslef\nb. His dad\nc. His mom\nd. Barack Obama\nprint(question1)print(options1)while True: response = input(Hit 'a', 'b', 'c' or 'd' for your answer\n) if response == d: break else: print(Incorrect!!! Try again.) while True: response = input(Hit 'a', 'b', 'c' or 'd' for your answer\n) if response == d: stop = True break else: print(Incorrect!!! You ran out of your attempts) stop = True break if stop: break# DO the same for the next questions of your round (copy-paste-copy-paste).# At the end of the round, paste the following code for the bonus question.# Now the program will ask the user to go for the bonus question or notwhile True: bonus = input(Would you like to give a try to the bonus question?\nHit 'y' for yes and 'n' for no.\n) if bonus == y: print(Who invented Facebook?) print(a. Me\nb. His dad\nc. Mark Zuckerberg\nd. Aliens) while True: response = input(Hit 'a', 'b', 'c' or 'd' for your answer\n) if response == c: break else: print(Incorrect!!! Try again.) while True: response = input(Hit 'a', 'b', 'c' or 'd' for your answer\n) if response == c: stop = True break else: print(Incorrect!!! You ran out of your attempts) stop = True break if stop: break break elif bonus == n: break else: print(INVALID INPUT!!! Only hit 'y' or 'n' for your response)# Now do the same as done above for the next round and another bonus question.Now this code is very long for a single question and I don't think this is the true programming. I don't want to copy-paste it again and again. I was wondering is there any way to shorten the code using class or defining functions or something like that? | Simple quiz program | python;quiz | import stringNUMBER_OF_ATTEMPTS = 2ENTER_ANSWER = 'Hit %s for your answer\n'TRY_AGAIN = 'Incorrect!!! Try again.'NO_MORE_ATTEMPTS = 'Incorrect!!! You ran out of your attempts'def question(message, options, correct, attempts=NUMBER_OF_ATTEMPTS): ''' message - string options - list correct - int (Index of list which holds the correct answer) attempts - int ''' optionLetters = string.ascii_lowercase[:len(options)] print message print ' '.join('%s: %s' % (letter, answer) for letter, answer in zip(optionLetters, options)) while attempts > 0: response = input(ENTER_ANSWER % ', '.join(optionLetters)) # For python 3 #response = raw_input(ENTER_ANSWER % ', '.join(optionLetters)) # For python 2 if response == optionLetters[correct]: return True else: attempts -= 1 print TRY_AGAIN print NO_MORE_ATTEMPTS return Falseprint(Mathematics Quiz)# question1 and question2 will be 'True' or 'False' question1 = question('Who is president of USA?', ['myself', 'His Dad', 'His Mom', 'Barack Obama'], 3)question2 = question('Who invented Facebook?', ['Me', 'His Dad', 'Mark Zuckerberg', 'Aliens', 'Someone else'], 2)I'm not sure which python you are using. Try both line 20 or line 21 to see which works best for you. Overall this function allows you to enter in questions with as many responses as you want and it will do the rest for you.Good luck. |
_unix.57404 | How can I perform a command on the selected items ?for example calling vim, or gimp for the 5 text or image files selected.I tried to make use of the inlined command line at the bottom, but it doesn't take my selection into account | Perform commands on selected items in Midnight Commander | files;mc | Press F2 for user menu and then choose Do something on tagged files or press @. In popup window you can provide your command.It is important to notice that for each file command will be executed separately. It will be something like:for file in files: COMMAND filenot COMMAND file1 file2 |
_codereview.140052 | I am updating a class in legacy code and having some issue with my calcPressure method. I want to make it nice and clean but there is some convolution in the process.Namely the calcPressure method I have does this:computes a value from existing valueswrites that value into an in-class parameterreturns the value to the callerprints debug output while computingprepares output for View (JSON, document...innerHtml)IssuesIn general, the code is all interconnected and it works, so part of me feels why do I want to mess with it. But part of me feels that Separation of Concerns (SOC) is super-broken. After all, the same internal pressure parameter that originates inside PHP class goes all the way into JS view, from being computed in PHP, transferred to JS and displayed in the browser. So if I make pressure private for example, or rename it, my view will become broken, since it depends on having the same parameter name in JS as in PHP for it to work.More specifically my method seems to do an awful lot. I'm questioning whether I should only have it compute data and return it without assigning the in-class parameter. Or if I should only assign the in-class parameter and not return anything. Right now it does both. I wonder if I should redirect debugging information to be a part of view and not be a part of the method somehow (computation/debug output separation). Codeclass Spec{ function load() { $result = db_query(SELECT * from spec where id = {$this->id}); $row = db_fetch_array($result); $this->n = $row['n']; $this->sg = $row['sg']; $this->q = $row['q']; } /** * Computes and returns Pressure * Outputs debug info * Assigns internal parameter * * @return number */ function calcPressure() { $res = abs($this->n * sqrt($this->q) / 15164.93 * $this->sg); dump( *** <u>Pressure</u> = $res); $this->pressure = $res; return $res; } public $pressure; public $sg; public $q; public $n; public $id;}PHP side$spec = new Spec();/* * Load of static parameters ($q, $sg, $n) from DB omitted for clarity */$spec->id = 5;$spec->load();$spec->calcPressure();$json = json_encode($spec);JS/View side<script>var x = <?=$json?>;/* * Populates HTML pages with computed pressure information */document.getElementById('pressure').innerHTML = x.pressure;</script>Dumpfunction dump($sql){print <pre>;print_r($sql);print</pre> . PHP_EOL;} | Compute and Display Engineering Information | php;object oriented;design patterns | null |
_codereview.5508 | Algorithm that I had to write is a perfect case for while, or do..while loop, however I found out that if I will implement it with a for loop I will save few lines of code and also scope of variables will be more appropriate. Take a look at the following code: for ( var i = 1, offset = -1; currentPosition.top === fakePosition.top && offset !== 0; i++ ) { fakePosition.top -= i * 10; offset = this.documentView.getOffsetFromPosition( fakePosition ); fakePosition = this.documentView.getRenderedPosition( offset ); }As you can see second parameter is very atypical as for for loops. My mine reason to switch to this loop was fact that I need iterator (i) and offset variables inside loop (and only there).What do you think about this approach? | What do you think about this usage of for loop in JavaScript? | javascript | As you can see second parameter is very atypical as for for loopsWhich is why it shouldn't be a for loop, because as you write yourself(!) [it] is a perfect case for while, or do..while loop. Saving a few lines of code and variable scope is not a good reason to obscure the code. You will (or should) be losing any perceived time/line benefit in writing the comments necessary to explain your trickery. If you want to limit variable scope, declare a new scope or function. As @Raynos alludes to in the comments, you should avoid magic, or rather, complicated expressions in your for loops (and other conditional statements). It might not look bad to you now (though it probably will in X months), but consider what happens when your boss/client asks you to add support for a special case. Very quickly it'll look like this: for ( var i = 1, offset = -1; currentPosition.top === fakePosition.top && offset !== 0 && currentPosition.top != -1 /* browser XYZ gives bogus answer */ && offset < fakePosition.bottom /* handle condition explained in ticket #123 */; i++ ) { fakePosition.top -= i * 10; offset = this.documentView.getOffsetFromPosition( fakePosition ); fakePosition = this.documentView.getRenderedPosition( offset ); } |
_webmaster.99300 | Google Analytics can show you which previous page brought your visitors to a page, but it can't tell you which button it was.So I set up event tracking for buttons and links, to figure out later which button was clicked.Are these button-clicks Events Without Interaction?One example in the documentation states that if you were tracking clicks on a Read More button by means of events, you would set Event without Interaction to false, since it should create a new page view (it's opening the next page).Other parts of the documentation only mention influences on the calculation of bounce rate.For my understanding that's just wrong:The Click-Event is called. This does not change anything, except for forwarding the info to AnalyticsThe browser handles the click by changing page. This will be tracked as a new page view, since the tracking code is loaded freshly.With that understanding you'd only set Event without Interaction to false if your script, not your browser, handles the page load.Or does the Event Without Interaction prevent the following page load from being tracked? | How track clicks on links, what does event without interaction influence | google analytics;event tracking | Interaction Events do influence the bounce rate.Analytics defines a bounce as someone loading your site and then leaving with 0 interactions. Consider a visitor landing on your article page, clicks the read more button and then exits the browser.If you attach a GA event to clicking the read more button and set it to be an Event without interaction = true then this would count as a bounce. If Event without interaction = false is set, then this user would not count as a bounce because he had an interaction on the site. A good example where you want to use non-interaction events are scroll depth tracking via events. That way a user coming to your site and scrolling all the way to the bottom, then leaving without a subsequent pageview it would be recorded as a bounce as GA intends it.Event without interaction has no affect on subsequent pageloads or how the browser handles anything. Loading a second page would automatically make the session a non-bounce session since loading page #2 is considered an interaction with the site. |
_softwareengineering.21467 | I just saw this lecture by Spolsky, where he questions the need for choices and confirmation dialogs. At some point he has a MacOS settings window and he mentions that now some are getting rid of the OK button. The window indeed has no OK (or cancel) button. Changing a setting makes it change, when you're done configuring, you close that window, period.Being a long time Windows user and a recent Mac owner, the difference is noticeable at first. I looked for the OK button for a while, only to find out, quite naturally and painlessly, that there was none. I expressed satisfaction and went on my merry way.However, I'm curious to know if this UI design pattern would succeed in the Windows-based world. Granted that if Microsoft brought it out with say Windows-8 (fat chance, I know), people would get used to it eventually. But is there some experience out there of such an approach, of changing the confirmation paradigm on a platform where it's so prevalent? Did it leave users (especially the non-technical ones) confused, frustrated, scared, or happy?TL;DR: Remove OK/cancel confirmation, what happens?EDIT:Mac GUI for appearance settings. | UI design and confirmation paradigm | design;gui | I find a nice middle ground is when some text is temporarily displayed (not in a pop-up) saying your change has been successfully saved or something similar to Google Doc's auto-saving |
_softwareengineering.140574 | HTML5 introduces a wide variety of tools such as Geolocation. Many browsers support them, but some do not yet.Should web developers rely on them to build professional applications for industry? The features are powerful, but not all browsers support these features.What are some ways (perhaps Javascript libraries?) to reliably test for browser support for HTML5 features such as Geolocation? | What are some ways to reliably test for browser support for HTML5 features such as Geolocation? | html5 | Modernizr supports detection of many features in HTML5 capable browsers, including geolocation. |
_codereview.163747 | I'm working on a SparseGraph which reflects the mathematical notion of a graph. All code included here works in all of the basic test cases that I've tried. However, I'm most concerned about the iterators (which iterate through each edge in the graph). Other concerns are style, readability, and other matters involving aesthetics. Particularly, I would like to know if the assumptions I made for the iterator classes are reasonable (for some definition of reasonable).The only file that needs to be reviewed is SparseGraph.h. I'll add some other classes (that don't necessarily need to be reviewed) which should be helpful for anyone who would like to try out the SparseGraph.Graph_Enums.h/* Graph_Enums.h This header contains a helpful enumeration when working with graphs. AldenB May 16, 2017*/#ifndef GRAPH_ENUMS_H#define GRAPH_ENUMS_Henum{ invalid_node_index = -1};#endif // GRAPH_ENUMS_HSparseGraph.h/* Sparse_Graph.h A sparse graph is a minimal collection of nodes and edges to represent a graph. This sparse graph is represented using an adjacency list. AldenB May 16, 2017*/#ifndef SPARSE_GRAPH_H#define SPARSE_GRAPH_H#include <iostream>#include <vector>#include <list>#include Graph_Enums.htemplate <typename NodeType, typename EdgeType>class SparseGraph{public: class const_iterator; class const_reverse_iterator; using Node = NodeType; using Edge = EdgeType; using NodeList = std::vector<Node>; using EdgeList = std::list<Edge>; using AdjacencyList = std::vector<EdgeList>;private: //NOTE: Any node with an index of invalid_node_index will be treated as a non-existent node //no matter where it is in the node list. //Each node index keys into its location in the NodeList //For example, a node with an index of 3 will be at index 3 //in the NodeList. This is so we can have a O(1) lookup time //for nodes NodeList m_nodes; //The AdjacencyList holds all edges associated with a node. //For example, index 3 of the AdjacencyList holds an EdgeList //containing all the edges connected to the node with an index //of 3. AdjacencyList m_adj_list; bool edge_exists(int from, int to);public: SparseGraph() {} ~SparseGraph() {} //----NODE STUFF-------------------------------------------------------- //add_node() will only add nodes that currently do not exist. //set_node() will only change nodes that already exist void add_node(const Node& node); void set_node(const Node& node); //remove_node() removes the node with the specified index. //it will also remove all edges associated with the specified node. void remove_node(int index); //node access //unchecked access Node& operator[](int index); const Node& operator[](int index) const; //checked access Node& at(int index); const Node& at(int index) const; //----EDGE STUFF-------------------------------------------------------- //add_edge() will only add edges that do not exist //set_edge() will only change edges that already exist void add_edge(const Edge& edge); //this will actually remove both edges connected to from and to. //i.e. Edge(from, to) and Edge(to, from) void remove_edge(int from, int to); //checked access Edge& get_edge(int from, int to); const Edge& get_edge(int from, int to) const; //----OTHER------------------------------------------------------------- void clear(); const_iterator begin() const; const_iterator end() const; const_reverse_iterator rbegin() const; const_reverse_iterator rend() const; template<typename Node, typename Edge> friend std::ostream& operator<<(std::ostream& os, const SparseGraph<Node, Edge>& graph);};//----SparseGraph::const_iterator-------------------------------------------//this const_iterator is meant to iterate through every Edge in the AdjacencyList.//Note that operator++() and operator--() will skip over empty EdgeLists.//It is the user's responsibility to ensure that edge_it is not initialized to//the end of ANY EdgeList in the AdjacencyList.template <typename NodeType, typename EdgeType>class SparseGraph<NodeType, EdgeType>::const_iterator{private: using NodeIterator = typename SparseGraph<NodeType, EdgeType>::AdjacencyList::const_iterator; using EdgeIterator = typename SparseGraph<NodeType, EdgeType>::EdgeList::const_iterator; NodeIterator m_node_it; EdgeIterator m_edge_it; const NodeIterator m_end;public: const_iterator(NodeIterator node_it, EdgeIterator edge_it, NodeIterator end) : m_node_it{node_it}, m_edge_it{edge_it}, m_end{end} {} //prefix operator++() const_iterator& operator++() { //move to the next element m_edge_it++; //if we are at the end of an EdgeList, move to the beginning of //the next non-empty EdgeList while(m_edge_it == m_node_it->end() && ++m_node_it != m_end) { m_edge_it = m_node_it->begin(); } return *this; } //postfix operator++() const_iterator operator++(int) { auto temp = *this; ++(*this); return temp; } //prefix operator--() const_iterator& operator--() { //are we at the beginning of an EdgeList? if(m_edge_it == m_node_it->begin()) { //move to the previous non-empty EdgeList. while((--m_node_it)->empty()) {}; //set the edge iterator to the last element of the EdgeList. m_edge_it = --(m_node_it->rbegin().base()); } //we are not at the beginning of an EdgeList else { m_edge_it--; } return *this; } //postfix operator--() const_iterator operator--(int) { const_iterator temp = *this; --(*this); return temp; } //----operator*() const typename SparseGraph<NodeType, EdgeType>::Edge& operator*() const { return *m_edge_it; } //operator->() const typename SparseGraph<NodeType, EdgeType>::Edge* operator->() const { return &(*m_edge_it); } //----operator==() bool operator==(const const_iterator& other) const { return m_node_it == other.m_node_it && m_edge_it == other.m_edge_it; } //----operator!=() bool operator!=(const const_iterator& other) const { return !(*this == other); }};//----SparseGraph::reverse_const_iterator-----------------------------------//the reverse_const_iterator should work semantically and holds the same assumptions as the const_iteratortemplate <typename NodeType, typename EdgeType>class SparseGraph<NodeType, EdgeType>::const_reverse_iterator{private: using RNodeIterator = typename SparseGraph<NodeType, EdgeType>::AdjacencyList::const_reverse_iterator; using REdgeIterator = typename SparseGraph<NodeType, EdgeType>::EdgeList::const_reverse_iterator; RNodeIterator m_rnode_it; REdgeIterator m_redge_it; const RNodeIterator m_rend;public: const_reverse_iterator(RNodeIterator rnode_it, REdgeIterator redge_it, RNodeIterator rend) : m_rnode_it{rnode_it}, m_redge_it{redge_it}, m_rend{rend} {} //prefix operator++() const_reverse_iterator& operator++() { //move to the previous element m_redge_it++; //if we are past the beginning of an EdgeList, move to the last element of //the previous non-empty EdgeList while(m_redge_it == m_rnode_it->rend() && ++m_rnode_it != m_rend) { m_redge_it = m_rnode_it->rbegin(); } return *this; } //postfix operator++() const_reverse_iterator operator++(int) { auto temp = *this; ++(*this); return temp; } //prefix operator--() const_reverse_iterator& operator--() { //are we at the last element of an EdgeList? if(m_redge_it == m_rnode_it->rbegin()) { //move to the next non-empty EdgeList. while((--m_rnode_it)->empty()) {}; //set the reverse edge iterator to the first element of the EdgeList. m_redge_it = m_rnode_it->begin(); } //we are not at the last element of an EdgeList else { m_redge_it--; } return *this; } //postfix operator--() const_reverse_iterator operator--(int) { const_reverse_iterator temp = *this; --(*this); return temp; } //----operator*() const typename SparseGraph<NodeType, EdgeType>::Edge& operator*() const { return *m_redge_it; } //operator->() const typename SparseGraph<NodeType, EdgeType>::Edge* operator->() const { return &(*m_redge_it); } //----operator==() bool operator==(const const_reverse_iterator& other) const { return m_rnode_it == other.m_rnode_it && m_redge_it == other.m_redge_it; } //----operator!=() bool operator!=(const const_reverse_iterator& other) const { return !(*this == other); }};//----SPARSE_GRAPH----------------------------------------------------------//----PRIVATE FUNCTIONS-----------------------------------------------------template <typename NodeType, typename EdgeType>bool SparseGraph<NodeType, EdgeType>::edge_exists(int from, int to){ //assume that from is within the bounds of the AdjacencyList for(const Edge& e : m_adj_list[from]) { if(e.to() == to) { return true; } } return false;}//----PUBLIC FUNCTIONS------------------------------------------------------//----add_node()template <typename NodeType, typename EdgeType>void SparseGraph<NodeType, EdgeType>::add_node(const NodeType& node){ //range check if(node.index() < 0) { throw std::runtime_error{SparseGraph::add_node(): Bad node index.}; } //Don't overwrite an existing node unless it's invalid. if(node.index() < m_nodes.size()) { if(m_nodes[node.index()].index() == invalid_node_index) { m_nodes[node.index()] = node; return; } throw std::runtime_error{SparseGraph::add_node(): Node already exists.}; } //add an empty EdgeList for each node. while(m_nodes.size() < node.index()) { m_adj_list.push_back(EdgeList()); m_nodes.push_back(NodeType(invalid_node_index)); } m_adj_list.push_back(EdgeList()); m_nodes.push_back(node);}//----set_node()template <typename NodeType, typename EdgeType>void SparseGraph<NodeType, EdgeType>::set_node(const NodeType& node){ //range and validity check; we can only set to valid nodes. if(node.index() < 0 || node.index() >= m_nodes.size() || m_nodes[node.index()].index() == invalid_node_index) { throw std::runtime_error{SparseGraph::set_node(): Set to non-existent node.}; } m_nodes[node.index()] = node;}//----remove_node()template <typename NodeType, typename EdgeType>void SparseGraph<NodeType, EdgeType>::remove_node(int index){ //range check if(index < 0 || index >= m_nodes.size()) { throw std::runtime_error{SparseGraph::remove_node(): Node index out of bounds.}; } //validity check if(m_nodes[index].index() == invalid_node_index) { throw std::runtime_error{SparseGraph::remove_node(): Node does not exist.}; } m_nodes[index].set_index(invalid_node_index); //look through every EdgeList in the AdjacencyList //and remove any Edge that is connected to this node. for(int i = 0; i < m_adj_list.size(); ++i) { for(auto it = m_adj_list[i].begin(); it != m_adj_list[i].end(); ++it) { if(it->from() == index || it->to() == index) { it = m_adj_list[i].erase(it); --it; } } }}//----operator[]()template <typename NodeType, typename EdgeType>NodeType& SparseGraph<NodeType, EdgeType>::operator[](int index){ return m_nodes[index];}//----operator[]() consttemplate <typename NodeType, typename EdgeType>const NodeType& SparseGraph<NodeType, EdgeType>::operator[](int index) const{ return m_nodes[index];}//----at()template <typename NodeType, typename EdgeType>NodeType& SparseGraph<NodeType, EdgeType>::at(int index){ //range check if(index < 0 || index >= m_nodes.size()) { throw std::runtime_error{SparseGraph::at(): Index out of bounds.}; } return m_nodes[index];}//----at() consttemplate <typename NodeType, typename EdgeType>const NodeType& SparseGraph<NodeType, EdgeType>::at(int index) const{ //range check if(index < 0 || index >= m_nodes.size()) { throw std::runtime_error{SparseGraph::at(): Index out of bounds.}; } return m_nodes[index];}//----add_edge()template <typename NodeType, typename EdgeType>void SparseGraph<NodeType, EdgeType>::add_edge(const Edge& edge){ //range check if(edge.from() < 0 || edge.from() >= m_adj_list.size() || edge.to() < 0 || edge.to() >= m_adj_list.size()) { throw std::runtime_error{SparseGraph::add_edge(): Edge index out of bounds.}; } //existence check if(edge_exists(edge.from(), edge.to())) { throw std::runtime_error{SparseGraph::add_edge(): Edge already exists.}; } //make sure the Edge is added for both directions Edge reverse_edge = edge; reverse_edge.set_from(edge.to()); reverse_edge.set_to(edge.from()); m_adj_list[edge.from()].push_back(edge); m_adj_list[reverse_edge.from()].push_back(reverse_edge);}//----remove_edge()template <typename NodeType, typename EdgeType>void SparseGraph<NodeType, EdgeType>::remove_edge(int from, int to){ //range check if(from < 0 || from >= m_adj_list.size() || to < 0 || to >= m_adj_list.size()) { throw std::runtime_error{SparseGraph::remove_edge(): Edge index out of bounds.}; } //look for the Edge in its EdgeList and remove it if it's there. for(auto it = m_adj_list[from].begin(); it != m_adj_list[from].end(); ++it) { if(it->to() == to) { m_adj_list[from].erase(it); //also erase the Edge coming from the opposite direction for(auto opp_it = m_adj_list[to].begin(); opp_it != m_adj_list[to].end(); ++opp_it) { if(opp_it->to() == from) { m_adj_list[to].erase(opp_it); } } return; } } throw std::runtime_error{SparseGraph::remove_edge(): Edge does not exist.};}//----get_edge()template <typename NodeType, typename EdgeType>EdgeType& SparseGraph<NodeType, EdgeType>::get_edge(int from, int to){ //range check if(from < 0 || from >= m_adj_list.size() || to < 0 || to >= m_adj_list.size()) { throw std::runtime_error{SparseGraph::get_edge(): Edge does not exist.}; } //search for the Edge in its EdgeList. for(EdgeType& e : m_adj_list[from]) { if(e.from() == from && e.to() == to) { return e; } }}//----get_edge() consttemplate <typename NodeType, typename EdgeType>const EdgeType& SparseGraph<NodeType, EdgeType>::get_edge(int from, int to) const{ //range check if(from < 0 || from >= m_adj_list.size() || to < 0 || to >= m_adj_list.size()) { throw std::runtime_error{SparseGraph::get_edge(): Edge does not exist.}; } //try to find the Edge in its EdgeList for(const EdgeType& e : m_adj_list[from]) { if(e.from() == from && e.to() == to) { return e; } }}//----clear()template <typename NodeType, typename EdgeType>void SparseGraph<NodeType, EdgeType>::clear(){ m_nodes.clear(); m_adj_list.clear();}//----begin()template <typename NodeType, typename EdgeType>typename SparseGraph<NodeType, EdgeType>::const_iterator SparseGraph<NodeType, EdgeType>::begin() const{ //Move to the first non-empty EdgeList in the AdjacencyList typename AdjacencyList::const_iterator begin_it = m_adj_list.begin(); while(begin_it != m_adj_list.end() && begin_it->empty()) { begin_it++; } return SparseGraph<NodeType, EdgeType>::const_iterator(begin_it, begin_it->begin(), m_adj_list.end());}//----end()template <typename NodeType, typename EdgeType>typename SparseGraph<NodeType, EdgeType>::const_iterator SparseGraph<NodeType, EdgeType>::end() const{ return SparseGraph<NodeType, EdgeType>::const_iterator(m_adj_list.end(), m_adj_list.back().end(), m_adj_list.end());}//----rbegin()template <typename NodeType, typename EdgeType>typename SparseGraph<NodeType, EdgeType>::const_reverse_iterator SparseGraph<NodeType, EdgeType>::rbegin() const{ typename AdjacencyList::const_reverse_iterator rbegin_it = m_adj_list.rbegin(); while(rbegin_it != m_adj_list.rend() && rbegin_it->empty()) { rbegin_it++; } return SparseGraph<NodeType, EdgeType>::const_reverse_iterator(rbegin_it, rbegin_it->rbegin(), m_adj_list.rend());}//----rend()template <typename NodeType, typename EdgeType>typename SparseGraph<NodeType, EdgeType>::const_reverse_iterator SparseGraph<NodeType, EdgeType>::rend() const{ return SparseGraph<NodeType, EdgeType>::const_reverse_iterator(m_adj_list.rend(), m_adj_list.front().rend(), m_adj_list.rend());}//----operator<<()template <typename NodeType, typename EdgeType>std::ostream& operator<<(std::ostream& os, const SparseGraph<NodeType, EdgeType>& graph){ if(graph.m_adj_list.size() == 0) { return os << <empty>; } for(unsigned int i = 0; i < graph.m_adj_list.size(); ++i) { os << i; if(graph.m_nodes[i].index() == invalid_node_index) { os << (invalid); } os << :; for(const EdgeType& e : graph.m_adj_list[i]) { os << << e.to(); } //don't add a newline to the last line if(i < graph.m_adj_list.size()-1) { os << '\n'; } } return os;}#endif // SPARSE_GRAPH_HGraph_Node/* Graph_Node.h A graph node is exactly what you'd expect: a node on a graph. AldenB May 16, 2017*/#ifndef GRAPH_NODE_H#define GRAPH_NODE_H#include Graph_Enums.hclass GraphNode{public: GraphNode() : m_index{invalid_node_index} {} explicit GraphNode(int index) : m_index{index} {} virtual ~GraphNode() {} int index() const {return m_index;} void set_index(int index) {m_index = index;} bool operator==(const GraphNode& other) { return index() == other.index(); } bool operator!=(const GraphNode& other) { return !(*this == other); }private: int m_index;};std::ostream& operator<<(std::ostream& os, const GraphNode& node){ return os << ( << node.index() << );}#endif // GRAPH_NODE_HGraph_Edge.h/* Graph_Edge.h A graph edge represents a unidirectional connection between two nodes on a graph. Alden Bernitt May 16, 2017*/#ifndef GRAPH_EDGE_H#define GRAPH_EDGE_H#include Graph_Enums.hclass GraphEdge{public: GraphEdge() : m_from{invalid_node_index}, m_to{invalid_node_index} {} GraphEdge(int from, int to) : m_from{from}, m_to{to} {} virtual ~GraphEdge() {} int from() const {return m_from;} int to() const {return m_to;} void set_from(int from) {m_from = from;} void set_to(int to) {m_to = to;} bool operator==(const GraphEdge& other) { return from() == other.from() && to() == other.to(); } bool operator!=(const GraphEdge& other) { return !(*this == other); }private: //a node can be minimally represented by its index. int m_from; int m_to;};std::ostream& operator<<(std::ostream& os, const GraphEdge& edge){ return os << ( << edge.from() << , << edge.to() << );}#endif // GRAPH_EDGE_H | SparseGraph: A representation of a mathematical graph | c++;graph;template;iterator | null |
_webapps.40511 | I setup my Google Voice number to forward to my AT&T cell phone number. There are two features of the forwarding behavior I'm not very fond of: When someone calls, they get a recorded voice asking for theirname. People tend to assume this is voicemail, and not realize thatmy phone is ringing, and after they follow the instructions I willbe picking up.When I pick up the phone, it tells me the name of the personcalling and asks whether I'd like to answer the call or send it tovoice mail (I'd rather it simply assume I'd like to answer so Ididn't have to wait or bother with the keypad).I don't think its relevant, but I'm using an iPhone 4. Is there anyway to setup Google Voice call forwarding which avoids either of these two issues? | How can I customize Google Voice behavior when forwarding calls? | google voice;iphone | In Google Voice, go to Settings | Calls and turn off Call Screening.Callers will no longer be asked to say their name, nor will you be prompted to press 1 to accept the call.More information at Google Support. |
_codereview.43490 | import java.math.BigInteger;import java.util.Random;public class Primetest { private static int size=15; private static Random r=new Random(); private static BigInteger two=new BigInteger(2); private static BigInteger three=new BigInteger(3); public static void main(String[] args) { while(true) { BigInteger p=new BigInteger(size,r); if(isprime(p)==true) { System.out.println(prime=+p); break; } } } public static boolean isprime(BigInteger n) { if(n.compareTo(BigInteger.ONE)==0 || n.compareTo(two)==0) { return true; } BigInteger half=n.divide(two); for(BigInteger i=three; i.compareTo(half)<=0;i=i.add(two)) { if(n.mod(i).equals(BigInteger.ZERO)) { return false; } } return true; } }This code selects a random prime BigInteger number. I want a 2048 bit BigInteger prime number, but it only works with 15 bit. Can anybody help me? | BigInteger prime testing | java;primes;random | null |
_webapps.37950 | When I create a new GitHub Issue, I can assign a user. Then both myself and this user will then become participants in the Issue and receive updates. I sometimes want other users to also receive notifications on the ticket even if they are not the current assignee. How can I add other users to the Issue at the time of Issue creation? | How can I copy in or include other GitHub users to an issue? | github | You just need to include their username in the issue.When you @mention a GitHub username anywhere in the context of an issue or pull request, that person is notified and subscribed to future updates.So if you wanted a GitHub user by the username, tornadosandwich, to be notified that you want them to see the issue, just put @tornadosandwich in the body of the issue and it will notify them.Would like to know what @tornadosandwich thinks about this.This will only work if the user has allowed it. If they never respond or acknowledge being included they may have unchecked both boxes in their account settings under the Notification Center:Participating When you participate in a discussion or someone brings you in with an @mention. |
_softwareengineering.94969 | I am into programming since last 3 years. But I seems to be lost in it. I am not able to get good at it even though I code everyday.suppose I solve one problem, I will wander from solution to solution and implement some other solution. I cant focus much. I get many defects for the code I write. I afraid of code I dont know why if I dont finish it on time my boss will fire me etc. I enjoy coding but not all the time. How to increase patience?I always wonder how do I become the best coder like many exceptional programmers. I know this sounds subjective but I think this will help programmer community to get good at it especially for average like me or beginner programmers. | Techniques to increase logic at programming | logic | I personally would suggest begin with smaller hurdles; try taking on coding in smaller chunks and get more in to the intermediate victories. It sounds like you either get overwhelmed or bored if something lasts too long or doesn't show progress. I can say definitively I've been in the same boat.Think of it like tackling a sandwich: You don't eat the entire thing in one bite, you break it down. Do the same thing with your projects, tasks, etc. Depending on what level you're at, you may want to ask your supervisor/manager to break it down for you. If you're responsible for your own work load, set little finish lines for yourself that are accomplish-able (don't set a goal you'll never reach, this just makes you more discouraged and puts you in an undesirable position). i.e. By noon I want to have this class defined, By 2 I want this interface implemented, etc.My company is notorious for beginning and ramping up for a project, allowing me to get to the 90% mark, then slipping the rug out from underneath me to move on to the next big thing. I start getting discouraged that I never get anything done, and gets me in a funk (if you will). Finally I pushed back and told them I wasn't moving on until I finish what I was nearly completed on. This did wonders for my esteem, moral, and energy (though I can't say the same about my employers :shrug:) |
_unix.21267 | Is there a command or plugin that I can use to show all the lines I have edited in a Vim session? I would like to be able to have all the changes I have made highlighted when working in co-workers projects and lost in lines of code. | VIM: show all lines edited in session | vim | The changesPlugin seems to work just fine for this type of thing.http://www.vim.org/scripts/script.php?script_id=3052Once installed, just run :EC after making changes to a file. |
_cstheory.16593 | I'm developing a route planner, and I was reading some graph theory.I read a little bit of Dijkstra's shortest path, shooting star and turn restrictions, and I tend to think that this algorithms are thought to be used for searching a short path between two nodes, node A and node B (or in some variant, edge A and edge B).I was wondering if it's a variant of some shortest path algorithm to find the shortest path between two set of nodes. I could define this problem better like this:Input:GraphList of initial nodesList of end nodesOutput:Node ANode BShortest pathI can think of a trivial solution: Take each of the 'initial nodes' apply dijkstra against each of the 'final nodes', select the minimal path from all returned paths, but I'm trying to find if exists some algorithm to solve this task. | Algorithm to find shortest path from a set of nodes to another set of nodes? | graph theory;graph algorithms | Create a new node $s$ and connect it to every node in the first list.Create a new node $t$ and connect it to every node in the second list.Find a shortest path between $s$ and $t$. |
_vi.8311 | According to :h compatible:(...) when a |vimrc| or |gvimrc| file exists, Vim will use the Vim defaults, otherwise it will use the Vi defaults.But when I try:$ mv ~/.vimrc vimrc$ vim -c 'set cp?'Vim tells me:nocompatibleIf I force it by:$ vim -u NONE -c 'set cp?'Vim correctly answers me withcompatibleI'm confident I have no ~/.gvimrc, what could cause this vim behaviour? | Removed my vimrc but vim still starts in nocp mode | vimrc | Thanks to DJ McMayhem pointing me in the right direction I found that Linux distros meddle with the nocompatible behaviour of vim. Since I cannot expect that everyone here know unix jargon, where I use $ I'm working as a normal user and where I use # i do commands as the superuser (root).1. Vim ignores /etc/vimrc for the purpose of setting nocompatibleWith :scriptnames I found vim loads the /etc/vimrc script. I then removed both vimrc scripts and tested:$ mv ~/.vimrc ~/vimrc.bak# mv /etc/vimrc /etc/vimrc.bak$ vim -c 'set cp?'And gotcompatibleThat is what we expected, but I tested further. I have created a /etc/vimrc containing set ff=unix (completely unrelated from nocp) and checked:# echo set ff=unix > /etc/vimrc$ vim -c 'set cp?'And surprisingly I got:compatibleMoreover :scriptnames clearly indicated:1: /etc/vimrcAdding a ~/.vimrc on the other hand triggers nocompatible correctly:$ echo set ff=unix > ~/.vimrc$ vim -c 'set cp?'nocompatibleVim did not understood the existence of /etc/vimrc as a vimrc file for the purpose of setting nocompatible, but it did understood the existence of ~/.vimrc. In unix philosophy that is correct, since it is a multi-user system by default the existence of a global configuration file shall never make a difference for a user.2. /etc/vimrc is created by the package manager on *nix systemsThe suspicion about the strange behaviour I got in the question falls on the contents of the original /etc/vimrc file (currently backed up as /etc/vimrc.bak). Looking through it I found this line:runtime! archlinux.vimI'm running vim on archlinux therefore it makes some sense. I found the file at /usr/share/vim/vimfiles/archlinux.vim and it does contain:set nocompatibleas the first non-comment line! That explains it all.ConclusionI then checked on a centos and a debian machines. It turns out that in one way or another (by using runtime or directly in /etc/vimrc) they all perform:set nocompatibleexplicitly, inside the configuration that is maintained by the package manager (yum, apt, pacman). That is bad practice!Moral of the story: Your Linux distro is likely meddling in the global vim configuration files. Be sure to check these files before arguing about strange behaviour of vim. |
_unix.267613 | Someone put a lot of malicious code onto every single wordpress instance on my server. For the second time. (At least) Every js file has been modified. There is a pattern though, the code always looks like this: /*[file-name]*/[malicious code]/*file-name*/is there any way that I could use grep and sed to get rid of those fragments? A previous attack put similar code in the files, which I got rid of using grep -rnwl './' -e [/*]d754948f7cc08347e64716505bd652ae[*/].*[/*]d754948f7cc08347e64716505bd652ae[*/] | xargs sed -i s/[/*]d754948f7cc08347e64716505bd652ae[*/].*[/*]d754948f7cc08347e64716505bd652ae[*/]//gis there any way to modify this exprssion to use each file name instead of a fixed string like d754948f7cc08347e64716505bd652ae? | Search file name within file | sed;grep;regular expression;wordpress;javascript | null |
_scicomp.18911 | My question concerns coordinate maps and non-equally spaced fourier transforms.I have dependent variables $(X(\xi),Y(\xi))$, where $\xi\in(0,2\pi)$. In general, $Y$ is assumed even and expanded as a Fourier series, ie$$Y(\xi) = \sum_{k=-N}^{N} Y_k e^{-ik\xi},$$where $N$ is taken to tend towards infinity and the reality condition implies $Y_{-k} = Y_k$Now, my governing equations are derived from a lagrangian. I won't go into the full details of it, since they are anscillary for the question, but it is illustrative to look at the potential energy term, V, which takes the form$$V=\int_0^{2\pi} Y(\xi)^2 \frac{dX(\xi)}{d\xi} \ d\xi,$$with $X-\xi$ being the Hilbert transform of $Y$ (because (X,Y) are real and imaginary parts of an analytic function in $\mathbb{C}$). That is, $$X = \xi + \sum i \sigma_k Y_k e^{-ik\xi},$$with $\sigma_i$ being 1 for $i>0$, 0 when $i=0$, and -1 when $i<0$. Substituting in the Fourier expansion, $V$ can be written entirely in terms of the $Y_k$s. The Euler-Larange equations then returns a set of governing (algebraic) equations are found and a system of equations is solved for a given $N$. It turns out that for the solutions I desire, the series converges very slowly, and this has to do with the fact that $Y(\xi)$ is very localized. After going through Boyd's book (in particular, see chapter 16), it seems like one way to deal with this is to map the independent variable into a different, non-uniformly spaced map. One example is to send $$\xi\to \theta-sin(\theta)$$ (Boyd calls this a Kepler mapping), for $\theta \in(0,2\pi)$, which will tend to crowd more points towards the ends of the domain, which is where my functions are localized. This seems promising to me, and I would like to pursue it. To this end, I take a change of coordinates at the level of the integral $V$, shown above, to find $$V = \int_0^{2\pi} Y(\theta)^2 \frac{d X(\theta)}{d \theta} \ d\theta$$.From here it is unclear to me how one takes a Fourier type expansion (needed to allow for the easy computation of the Hilbert transform) on this non-uniform grid. Any suggestions would be greatly appreciated,Nick | Coordinate transformations and analytic form of non-uniformly gridded fourier transform | fourier transform | Unless I'm missing something obvious, if you transform $Y=Y_\xi(\xi)$ to use $Y=Y_\theta(\theta) = Y_\xi(\theta-\sin\theta)$, then the function $w(\xi)=X(\xi)+iY(\xi)$, which, as you say, was analytic in $\xi$, would be analytic in $\theta$ also, with $w(\theta) = w(\xi=\theta-\sin\theta)$, so that whatever Fourier series $Y(\theta)$ has w.r.t. $\theta$, $X$ would have the same expression as before in terms of the new variable $\theta$ and the new Forier coefficients $Y_k^{(\theta)}$ (it's a generic expression, independent of the coordinates being used to write it down).This is assuming that the rest of your equations can be rewritten in terms of $\theta$ as well: I don't know a good way to relate two Fourier series obtained by a change of variable. But this is not the same as doing a discrete Fourier transform on a non-uniform grid, anyway, because you seem to be using a Galerkin-type method, and evaluating all the necessary integrals in closed form by hand. In fact, I don't quite see where in your question a discrete Fourier transform is being used. |
_codereview.86876 | I work on a .NET application that very loosely follows an n-tier kind of architecture (the business objects (not logic) and data access are split out). We are now looking to start refactoring the code into an MVP architecture. Based on some previous work done by someone else, I just refactored a screen into what I hope is MVP.The form code:Imports System.Windows.FormsImports ExceptionLibrary.UIExceptionCatcherImports BusinessEntity.OEImports OurClient.MainModule.Constants<System.ComponentModel.ToolboxItem(False)> _Partial Public Class AutoService Inherits UILibrary.CustomViewControl Implements IAutoService Private _objAutoServiceBE As New AutoServiceBE Private _isEditMode As Boolean Private _intCurrentUserId As Integer Private _intNewAddedAutoServiceId As Integer Private _intAutoServiceID As Integer Public Event Close(ByVal sender As Object, ByVal e As EventArgs) Implements IAutoService.Close Public Event Save(ByVal sender As Object, ByVal e As EventArgs) Implements IAutoService.Save Public Event FormLoad(ByVal e As EventArgs) Implements IAutoService.ViewLoad Public Property AutoService As BusinessEntity.OE.AutoServiceBE Implements IAutoService.AutoService Get Return _objAutoServiceBE End Get Set(value As BusinessEntity.OE.AutoServiceBE) _objAutoServiceBE = value End Set End Property Public Property AutoServiceCode As String Implements IAutoService.AutoServiceCode Get Return txtCode.Text End Get Set(value As String) txtCode.Text = value End Set End Property Public Property AutoServiceName As String Implements IAutoService.AutoServiceName Get Return txtName.Text End Get Set(value As String) txtName.Text = value End Set End Property Public Property AutoServiceID() As Integer Implements IAutoService.AutoServiceID Get Return _intAutoServiceID End Get Set(ByVal value As Integer) _intAutoServiceID = value End Set End Property Public Property AutoServiceTypeList As IList(Of BusinessEntity.OE.AutoServiceBE) Implements IAutoService.AutoServiceTypeList Get Return cboAutoServiceType.DataSource End Get Set(value As IList(Of BusinessEntity.OE.AutoServiceBE)) With cboAutoServiceType .DisplayMember = AutoServiceTypeName .ValueMember = AutoServiceTypeID .DataSource = value .SelectedItem = Me.SelectedAutoServiceType End With End Set End Property Public Property CursorType As Cursor Implements IAutoService.CursorType Get Return Me.Cursor End Get Set(value As Cursor) Me.Cursor = value End Set End Property Public Property ViewDisplayModeType As UILibrary.CustomViewControl.ViewDisplayMode Implements IAutoService.ViewDisplayMode Get Return Me.DisplayMode End Get Set(value As UILibrary.CustomViewControl.ViewDisplayMode) Me.DisplayMode = value End Set End Property Public Property EditMode() As String Implements IAutoService.EditMode Get Return _isEditMode End Get Set(ByVal value As String) _isEditMode = value End Set End Property Public Property NewAddedAutoServiceId() As Integer Implements IAutoService.NewAddedAutoServiceId Get Return _intNewAddedAutoServiceId End Get Set(ByVal value As Integer) _intNewAddedAutoServiceId = value End Set End Property Public Property IsNameSelected As Boolean Implements IAutoService.IsNameSelected Get Return txtName.Focused End Get Set(value As Boolean) txtName.Focus() txtName.SelectAll() End Set End Property Public WriteOnly Property IsNameFailed As Boolean Implements IAutoService.IsNameFailed Set(value As Boolean) ShowFailFrame(txtName) End Set End Property Public Property IsCodeSelected As Boolean Implements IAutoService.IsCodeSelected Get Return txtCode.Focused End Get Set(value As Boolean) txtCode.Focus() txtCode.SelectAll() End Set End Property Public WriteOnly Property IsCodeFailed As Boolean Implements IAutoService.IsCodeFailed Set(value As Boolean) ShowFailFrame(txtCode) End Set End Property Public Property PvcCloseResult As DialogResult Implements IAutoService.PvcCloseResult Get Return CloseResult End Get Set(value As DialogResult) CloseResult = value End Set End Property Public Property PvcIsViewDirty As Boolean Implements IAutoService.PvcIsViewDirty Get Return IsViewDirty End Get Set(value As Boolean) IsViewDirty = value End Set End Property Public ReadOnly Property PvcValidateRequiredFields As Boolean Implements IAutoService.PvcValidateRequiredFields Get Return ValidateRequiredFields() End Get End Property Public WriteOnly Property PvcSaveCallback As [Delegate] Implements IAutoService.PvcSaveCallback Set(value As [Delegate]) CallbackFunctionForSave = value End Set End Property Public Property UserID As Integer Implements IAutoService.UserID Get Return _intCurrentUserId End Get Set(value As Integer) _intCurrentUserId = value End Set End Property Public Property SelectedAutoServiceType As BusinessEntity.OE.AutoServiceBE Implements IAutoService.SelectedAutoServiceType Get Return cboAutoServiceType.SelectedItem End Get Set(value As BusinessEntity.OE.AutoServiceBE) cboAutoServiceType.SelectedItem = value End Set End Property Public Sub New() InitializeComponent() End Sub Protected Overrides Sub OnLoad(ByVal e As EventArgs) Try _presenter.OnViewReady() MyBase.OnLoad(e) Cursor = Cursors.WaitCursor Hide() TitleBarText = AutoService DisplayStyle = ViewDisplayStyle.DialogBox ViewAcceptButton = btnSave ViewCancelButton = btnClose Me.UserID = SQLDataServices.GlobalUserID Me.AutoService.CreateUserID = Me.UserID AddHandlers() InitializeDirtyTracking() InitializeValidationTracking() RaiseEvent FormLoad(e) cboAutoServiceType.Select() Catch ex As Exception HandleException(ex, Me.ToString, OnLoad, True, True) Me.Enabled = False Finally Me.Show() Cursor = Cursors.Default End Try End Sub Private Sub OnClick_btnSave(ByVal sender As System.Object, ByVal e As System.EventArgs) RaiseEvent Save(sender, e) End Sub Private Sub OnClick_btnClose(ByVal sender As System.Object, ByVal e As System.EventArgs) CloseResult = DialogResult.Cancel RaiseEvent Close(sender, e) Me.ParentForm.Close() End Sub Private Sub AddHandlers() AddHandler btnSave.Click, AddressOf OnClick_btnSave AddHandler btnClose.Click, AddressOf OnClick_btnClose End Sub Private Sub InitializeDirtyTracking() IsViewDirty = False AddToDirtyTracker(cboAutoServiceType) AddToDirtyTracker(txtName) AddToDirtyTracker(txtCode) End Sub Private Sub InitializeValidationTracking() AddToValidationTracker(cboAutoServiceType) AddToValidationTracker(txtName) AddToValidationTracker(txtCode) End Sub Private Sub SaveToDB() Implements IAutoService.SaveToDB RaiseEvent Save(Me, Nothing) End Sub Public Sub ShowView() Implements IAutoService.Show ViewServices.ShowSmartPart(Me, WorkspaceNames.MDIWorkspace, True) End Sub Public Sub CloseView() Implements IAutoService.CloseView RaiseEvent Close(Me, Nothing) Me.ParentForm.Close() End SubEnd ClassThe presenter code:Imports System.Windows.FormsImports CommonUILibrary.UserMessageImports ExceptionLibrary.UIExceptionCatcherImports OurClient.Infrastructure.InterfacePartial Public Class AutoServicePresenter Inherits Presenter(Of IAutoService) Private _dataService As IAutoServiceDataService Public Overrides Sub OnViewReady() MyBase.OnViewReady() End Sub Public Sub SubscribeToEvents() AddHandler View.Close, AddressOf OnClose AddHandler View.Save, AddressOf OnSave AddHandler View.ViewLoad, AddressOf OnViewLoad End Sub Public Sub OnClose(ByVal sender As Object, ByVal e As EventArgs) End Sub Public Sub OnSave(ByVal sender As Object, ByVal e As EventArgs) View.CursorType = Cursors.WaitCursor Try If SaveToDatabase() Then View.PvcCloseResult = DialogResult.OK View.CloseView() End If Catch ex As Exception HandleException(ex, Me.ToString, OnClick_btnSave, True, True) Finally View.CursorType = Cursors.Default End Try End Sub Public Sub OnViewLoad(e As EventArgs) View.AutoServiceTypeList = _dataService.GetAutoServiceTypes() If View.ViewDisplayMode = ViewDisplayMode.Edit Then View.AutoService = _dataService.GetAutoService(View.AutoServiceID) View.AutoServiceName = View.AutoService.AutoServiceName View.AutoServiceCode = View.AutoService.AutoServiceCode View.SelectedAutoServiceType = _dataService.GetAutoServiceType(View.AutoServiceTypeList, View.AutoService.AutoServiceTypeID) Else View.AutoServiceName = View.AutoServiceCode = View.SelectedAutoServiceType = _dataService.GetAutoServiceType(View.AutoServiceTypeList, View.AutoService.AutoServiceTypeID) End If End Sub Public Sub UpdateGridView() If WorkItem.SmartParts.Contains(AutoServiceNames) Then Dim objSetupAutoServiceNames As SetupAutoServiceNames = WorkItem.SmartParts.Get(Of SetupAutoServiceNames)(AutoServiceNames) objSetupAutoServiceNames.OnPopulateGrid() End If End Sub Private Function SaveToDatabase() As Boolean Dim intResult As Integer = -1 If ValidateView() Then SetViewDataToBE() If View.ViewDisplayMode = ViewDisplayMode.Add Then 'new autoservice intResult = _dataService.AddAutoService(View.AutoService) If intResult > 0 Then UpdateGridView() AppDataCache.UpdateCache(AppDataCache.SubjectAreaName.OrderEntry, True) View.PvcIsViewDirty = False ShowInformation(Auto Service added successfully.) ElseIf intResult = -1 Then View.IsNameFailed = True ShowWarning(An Auto Service with the same name already exists.) View.IsNameSelected = True ElseIf intResult = -2 Then View.IsCodeFailed = True ShowWarning(An Auto Service with the same code already exists.) View.IsCodeSelected = True ElseIf intResult = -3 Then View.IsNameFailed = True ShowInformation(Please call the help desk to reuse the Auto Service Name for this Auto Service Type.) View.IsNameSelected = True ElseIf intResult = -4 Then View.IsCodeFailed = True ShowInformation(Please call the help desk to reuse the Auto Service Code for this Auto Service Type.) View.IsCodeSelected = True Else ShowWarning(Failed to add the Auto Service.) End If Else : View.ViewDisplayMode = ViewDisplayMode.Edit 'autoservice in edit mode intResult = _dataService.EditAutoService(View.AutoService) If intResult > 0 Then UpdateGridView() AppDataCache.UpdateCache(AppDataCache.SubjectAreaName.OrderEntry, True) View.PvcIsViewDirty = False ShowInformation(Auto Service updated successfully.) ElseIf intResult = -1 Then View.IsNameFailed = True ShowWarning(An Auto Service with the same name already exists.) View.IsNameSelected = True ElseIf intResult = -2 Then View.IsCodeFailed = True ShowWarning(An Auto Service with the same code already exists.) View.IsCodeSelected = True ElseIf intResult = -3 Then View.IsNameFailed = True ShowWarning(Please call the help desk to reuse the Auto Service Name for this Auto Service Type.) View.IsNameSelected = True ElseIf intResult = -4 Then View.IsCodeFailed = True ShowWarning(Please call the help desk to reuse the Auto Service Code for this Auto Service Type.) View.IsCodeSelected = True Else ShowWarning(Failed to update the Auto Service.) End If End If End If View.NewAddedAutoServiceId = intResult Return (intResult > 0) End Function Public Function ValidateView() As Boolean Dim blnReturn As Boolean = True If View.PvcValidateRequiredFields Then 'All' Name should not be created If (View.AutoServiceName.Trim.ToLower = All.ToLower) Then View.IsNameFailed = True ShowWarning(Auto Service Name cannot be + ' + View.AutoServiceName + ' ) View.IsNameSelected = True blnReturn = False End If Else blnReturn = False End If Return blnReturn End Function Private Sub SetViewDataToBE() 'assigning control values to the object With View.AutoService .AutoServiceName = View.AutoServiceName .AutoServiceCode = View.AutoServiceCode If View.SelectedAutoServiceType IsNot Nothing Then .AutoServiceTypeID = View.SelectedAutoServiceType.AutoServiceTypeID End If .AutoServiceID = View.AutoServiceID .CreateUserID = View.UserID End With If View.ViewDisplayMode = ViewDisplayMode.Add And View.SelectedAutoServiceType IsNot Nothing Then View.AutoServiceTypeList.Add(View.SelectedAutoServiceType) End If End Sub Public Sub New() MyBase.New() _dataService = New AutoServiceDataService End SubEnd ClassThe DataService code:Public Class AutoServiceDataService Implements IAutoServiceDataService Public Function AddAutoService(ByRef objAutoServiceBE As BusinessEntity.OE.AutoServiceBE) As Integer Implements IAutoServiceDataService.AddAutoService Dim intReturn As Integer = 0 intReturn = OurClientDAL.OEService.AutoServiceNameDAL.InsertAutoService(objAutoServiceBE) Return intReturn End Function Public Function EditAutoService(ByRef objAutoServiceBE As BusinessEntity.OE.AutoServiceBE) As Integer Implements IAutoServiceDataService.EditAutoService Dim intReturn As Integer = 0 intReturn = OurClientDAL.OEService.AutoServiceNameDAL.UpdateAutoService(objAutoServiceBE) Return intReturn End Function Public Function GetAutoService(intAutoServiceID As Integer) As BusinessEntity.OE.AutoServiceBE Implements IAutoServiceDataService.GetAutoService Return OurClientDAL.OEService.AutoServiceNameDAL.GetAutoServiceByID(intAutoServiceID) End Function Public Function GetAutoServiceType(ByVal lstAutoService As List(Of BusinessEntity.OE.AutoServiceBE), _ ByVal intAutoServiceTypeID As Integer) As BusinessEntity.OE.AutoServiceBE Implements IAutoServiceDataService.GetAutoServiceType Dim objReturn As New BusinessEntity.OE.AutoServiceBE For Each objAutoService As BusinessEntity.OE.AutoServiceBE In lstAutoService If objAutoService.AutoServiceTypeID = intAutoServiceTypeID Then objReturn = objAutoService Exit For End If Next Return objReturn End Function Public Function GetAutoServiceTypes() As IList(Of BusinessEntity.OE.AutoServiceBE) Implements IAutoServiceDataService.GetAutoServiceTypes Return OurClientDAL.OEService.AutoServiceNameDAL.GetAutoServiceType() End FunctionEnd ClassI initially asked a similar question over at Stack Overflow, though it garnered little attention. I have reprhased it in the context of a code review so I can make sure that I am doing this right. | Model-View-Presenter | vb.net;mvp | null |
_unix.253567 | Given the following made-up segment from an output file from hashdeep:7241,11111111111111111111111111111111,\01-data\file11237241,22222222222222222222222222222222,\01-data\file241,33333333333333333333333333333333,\01-data\file3How would I get about it to format it like: 7241,11111111111111111111111111111111,\01-data\file11237241,22222222222222222222222222222222,\01-data\file2 41,33333333333333333333333333333333,\01-data\file3I'd like to use sed (as that's what I'm beginning to get to grips with), but is there a way to tell sed to only change characters if they occur in a specific column or specific columns? Of course if there is another way to do it, I'd be just as happy to hear about that.The reason for this is that I want to sort the output on the filenames, so that I can compare two output files, without having to use the -j0 (single-thread) option on hashdeep. | CSV columnar reformat with SED (or anything other coreutil) | text processing;sed | null |
_codereview.140959 | I've been wanting to go async with my HTTP calls but all the methods I tried have not worked, so I resolved to implement this as a task and then improve upon it.This is what I've come up with so far. Any noticeable improvements or unused techniques to make this go even faster and still produce viable images?Public Shared Sub ProcessFolder(targetFolder As String) Dim ListParams As New List(Of ImgThreadParams)() Dim gtin As String = vbNullString Dim files = GetXlsxFiles(targetFolder) Dim excel As Application = New Application() Try For Each fileName As String In files 'Dim book = New LinqToExcel.ExcelQueryFactory(System.IO.Path.GetFileName(fileName)) Dim w As Workbook = excel.Workbooks.Open(fileName) ' Get sheet. Dim sheet As Worksheet = w.Sheets(1) ' Get range. Dim r As Range = sheet.UsedRange() 'move range to 2d array Dim rArray(,) As Object = r.Value(XlRangeValueDataType.xlRangeValueDefault) 'setup variables to hold column numbers for quick parsing in the next loop Dim GtinC As Integer = 0 Dim Img1 As Integer = 0 Dim Img2 As Integer = 0 Dim Img3 As Integer = 0 Dim Img4 As Integer = 0 Dim Img5 As Integer = 0 Dim Img6 As Integer = 0 Dim Img7 As Integer = 0 Dim Img8 As Integer = 0 Dim Img9 As Integer = 0 Dim Img10 As Integer = 0 Dim ic As Integer = 0 'pull the desired data from the range without looping over undesired data. For j As Integer = 1 To r.Columns.Count() If rArray(4, j).ToString().StartsWith(GTIN) Then GtinC = j ElseIf rArray(4, j).ToString.StartsWith(Image) And Not rArray(4, j).ToString().EndsWith(Description) And Not rArray(4, j).ToString().Contains(File) Then ic = ic + 1 Select Case ic Case 1 Img1 = j Case 2 Img2 = j Case 3 Img3 = j Case 4 Img4 = j Case 5 Img5 = j Case 6 Img6 = j Case 7 Img7 = j Case 8 Img8 = j Case 9 Img9 = j Case 10 Img10 = j Case Else Exit Select End Select End If Next Dim additem As Boolean = False 'Do Some checking on the quality of the links passed.. For i As Integer = 5 To r.Rows.Count() Dim itp As ImgThreadParams = New ImgThreadParams() itp.gtin = rArray(i, GtinC) If (rArray(i, Img1) IsNot Nothing) Then If (Uri.IsWellFormedUriString(rArray(i, Img1), UriKind.Absolute)) Then itp.lUrls.Add(rArray(i, Img1)) additem = True End If End If If (rArray(i, Img2) IsNot Nothing) Then If (Uri.IsWellFormedUriString(rArray(i, Img2), UriKind.Absolute)) Then itp.lUrls.Add(rArray(i, Img2)) End If End If If (rArray(i, Img3) IsNot Nothing) Then If (Uri.IsWellFormedUriString(rArray(i, Img3), UriKind.Absolute)) Then itp.lUrls.Add(rArray(i, Img3)) End If End If If (rArray(i, Img4) IsNot Nothing) Then If (Uri.IsWellFormedUriString(rArray(i, Img4), UriKind.Absolute)) Then itp.lUrls.Add(rArray(i, Img4)) End If End If If (rArray(i, Img5) IsNot Nothing) Then If (Uri.IsWellFormedUriString(rArray(i, Img5), UriKind.Absolute)) Then itp.lUrls.Add(rArray(i, Img5)) End If End If If (rArray(i, Img6) IsNot Nothing) Then If (Uri.IsWellFormedUriString(rArray(i, Img6), UriKind.Absolute)) Then itp.lUrls.Add(rArray(i, Img6)) End If End If If (rArray(i, Img7) IsNot Nothing) Then If (Uri.IsWellFormedUriString(rArray(i, Img7), UriKind.Absolute)) Then itp.lUrls.Add(rArray(i, Img7)) End If End If If (rArray(i, Img8) IsNot Nothing) Then If (Uri.IsWellFormedUriString(rArray(i, Img8), UriKind.Absolute)) Then itp.lUrls.Add(rArray(i, Img8)) End If End If If (rArray(i, Img9) IsNot Nothing) Then If (Uri.IsWellFormedUriString(rArray(i, Img9), UriKind.Absolute)) Then itp.lUrls.Add(rArray(i, Img9)) End If End If If (rArray(i, Img10) IsNot Nothing) Then If (Uri.IsWellFormedUriString(rArray(i, Img3), UriKind.Absolute)) Then itp.lUrls.Add(rArray(i, Img10)) End If End If If (additem = True) Then ListParams.Add(itp) additem = False End If Next 'Clean Up rArray = Nothing w.Close() Runtime.InteropServices.Marshal.ReleaseComObject(r) Runtime.InteropServices.Marshal.ReleaseComObject(sheet) Runtime.InteropServices.Marshal.ReleaseComObject(w) Runtime.InteropServices.Marshal.ReleaseComObject(excel) Next Dim Folder As DirectoryInfo = System.IO.Directory.CreateDirectory(System.IO.Directory.GetCurrentDirectory() + \Image) If ListParams.Count > 4 Then Dim tCount As Integer = Math.Round(ListParams.Count / 10, MidpointRounding.ToEven) Dim L1 As New List(Of ImgThreadParams) For i As Integer = 0 To tCount L1.Add(ListParams(i)) Next Dim L2 As New List(Of ImgThreadParams) For i As Integer = tCount + 1 To tCount * 2 L2.Add(ListParams(i)) Next Dim L3 As New List(Of ImgThreadParams) For i As Integer = tCount * 2 + 1 To tCount * 3 L3.Add(ListParams(i)) Next Dim L4 As New List(Of ImgThreadParams) For i As Integer = tCount * 3 + 1 To tCount * 4 L4.Add(ListParams(i)) Next Dim L5 As New List(Of ImgThreadParams) For i As Integer = tCount * 4 + 1 To tCount * 5 L5.Add(ListParams(i)) Next Dim L6 As New List(Of ImgThreadParams) For i As Integer = tCount * 5 + 1 To tCount * 6 L6.Add(ListParams(i)) Next Dim L7 As New List(Of ImgThreadParams) For i As Integer = tCount * 6 + 1 To tCount * 7 L7.Add(ListParams(i)) Next Dim L8 As New List(Of ImgThreadParams) For i As Integer = tCount * 7 + 1 To tCount * 8 L8.Add(ListParams(i)) Next Dim L9 As New List(Of ImgThreadParams) For i As Integer = tCount * 8 + 1 To tCount * 9 L9.Add(ListParams(i)) Next Dim L10 As New List(Of ImgThreadParams) For i As Integer = tCount * 9 + 1 To ListParams.Count - 1 L10.Add(ListParams(i)) Next Dim t1, t2, t3, t4, t5, t6, t7, t8, t9, t10 As Threading.Thread t1 = New Threading.Thread(AddressOf ThreadedGetGtinImages) t2 = New Threading.Thread(AddressOf ThreadedGetGtinImages) t3 = New Threading.Thread(AddressOf ThreadedGetGtinImages) t4 = New Threading.Thread(AddressOf ThreadedGetGtinImages) t5 = New Threading.Thread(AddressOf ThreadedGetGtinImages) t6 = New Threading.Thread(AddressOf ThreadedGetGtinImages) t7 = New Threading.Thread(AddressOf ThreadedGetGtinImages) t8 = New Threading.Thread(AddressOf ThreadedGetGtinImages) t9 = New Threading.Thread(AddressOf ThreadedGetGtinImages) t10 = New Threading.Thread(AddressOf ThreadedGetGtinImages) t1.Start(L1) t2.Start(L2) t3.Start(L3) t4.Start(L4) t5.Start(L5) t6.Start(L6) t7.Start(L7) t8.Start(L8) t9.Start(L9) t10.Start(L10) Else Dim t1 As Threading.Thread t1 = New Threading.Thread(AddressOf ThreadedGetGtinImages) t1.Start(ListParams) End If Catch ex As Exception End TryEnd SubPublic Shared pc As Integer = 1Public Shared imgCount As Integer = 1Public Shared Sub pCompleted() Console.WriteLine((pc * 10).ToString() + % Completed) pc = pc + 1End Sub'I am not entirely sure this is the proper way to iterate over a lists in a list but it seems to work..Public Shared Async Sub ThreadedGetGtinImages(ThreadParams As List(Of ImgThreadParams)) Dim items As IEnumerable(Of Task(Of Boolean)) = From item As ImgThreadParams In ThreadParams From url In item.lUrls Where url IsNot Nothing Select GetGtinImages(item.gtin, url) Dim downloadItems As Task(Of Boolean)() = items.ToArray() Dim bReturns As Boolean() = Await Task.WhenAll(downloadItems) pCompleted()End SubPublic Shared Function GetGtinImages(sGTIN As String, sURL As String, Optional sFolder As String = ) As Task(Of Boolean) Return Task.Factory.StartNew(Of Boolean)( Function() As Boolean Dim sFileExtension As String Using wc As WebClient = New WebClient() Dim myWebHeaderCollection As WebHeaderCollection Try Dim dBytes As Byte() = wc.DownloadData(address:=sURL) If (wc.ResponseHeaders(HttpResponseHeader.ContentLength) > 0) Then myWebHeaderCollection = wc.ResponseHeaders Dim sContentType As String = myWebHeaderCollection.Get(Content-Type) If (sContentType.Length > 0) Then Dim sImageContents As String() = sContentType.Split(;) Dim sImage As String = sImageContents(0).Split(/)(0).ToLower Dim sImageType As String = sImageContents(0).Split(/)(1).ToLower If sImage.Equals(image) = True Then Select Case sImageType Case jpeg sFileExtension = .jpg Case png sFileExtension = .png Case bmp sFileExtension = .bmp Case gif sFileExtension = .gif Case tiff sFileExtension = .Tiff Case Else Return False End Select sFolder = System.IO.Directory.GetCurrentDirectory() + \Image Using Fi As FileStream = New FileStream(sFolder + \ + sGTIN + _ + imgCount.ToString + sFileExtension, FileMode.CreateNew) Fi.Write(dBytes, 0, dBytes.Length) Fi.Flush() Fi.Close() End Using imgCount = imgCount + 1 Return True End If End If End If Catch ex As Exception wc.Dispose() Return False End Try End Using Return True End Function)End FunctionPublic Shared Sub Main() ProcessFolder(System.IO.Directory.GetCurrentDirectory()) Console.ReadLine()End Sub | Multithreaded download of images from a spreadsheet | multithreading;excel;vb.net;http;async await | null |
_unix.381926 | I have a rather big list(1million or so) and another huge list(17gb), I need to match the lines in list1 with the first part of a delimited file 2 as such:List1:98433259@3490345394@4394335053@23List254353456@35:nancy98433259@34:jack94335053@23:james32409533@86:robertOutput:98433259@34:jack94335053@23:jamesI have tried grep -Fwf list1 list2 but it is way too slowIs there any faster way to do this? | Matching lines from one file to lines in another file | linux;awk;sed;grep;gawk | null |
_unix.183622 | I'm on Archx64 with bspwm as WM. I have both gcc and clang installed and updated to latest versions. I want build systems to ask me everytime to choose either g++ or clang ++ to compile.I need clang++ as default compiler for my own stuff , but I have cmake that usually chooses compilers on its own. So I exported C and CXX as clang and clang++ in .bashrc . Everything runs fine as expected, but the problem arises when I need to compile something with g++ and the program looks for /usr/bin/c++ and finds clang++ instead of g++. I need , everytime some program tries to compile its stuff , it could ask me beforehand , which compiler to use. Is it possible?My current method is to export each time and restart my machine :p which is insane amounts of stupidity. | How to influence which compiler is chosen by build systems like CMake | gcc;cmake | There is no real general answer. If some tool insists on some tool it will do so.If setting environment variables works for you, there is no need to reboot. You can simply call your command like this:CXX=g++ cmake ...This will run cmake with the CXX environment variable set to g++.If you really want to do what you asked for you could replace /usr/bin/c++ (or whatever command is needed by your tool) by a shell script asking for the needed compiler and then calling that compiler. - But be really sure you know what you are doing if you decide to go that way. |
_webmaster.78060 | What effect does turning off caching in all browsers have on SEO? | What effect does turning off caching in all browsers have on SEO? | seo;cache;cache control | It slows down your page loading speed which can potentially be a negative ranking signal. |
_codereview.127350 | My goal is to read from standard input, break up the input into words, case-insensitively, and produce a report to standard output, where each line is a word followed by a space followed by its count. The output should be sorted by words.This is my code:use std::collections::BTreeMap;use std::io;use std::io::BufRead;fn main() { let mut counts: BTreeMap<String, isize> = BTreeMap::new(); let stdin = io::stdin(); for line_result in stdin.lock().lines() { match line_result { Ok(line) => { let lowercase_line = line.to_lowercase(); let words = lowercase_line.split(|c: char| { !(c.is_alphabetic() || c == '\'') }).filter(|s| !s.is_empty()); for word in words { *(counts.entry(word.to_string()).or_insert(0)) += 1; } }, Err(e) => { panic!(Error parsing stdin: {:?}, e); } } } for (key, value) in counts.iter() { println!({} {}, key, value); }}My questions are:Is BTree the proper dictionary?I know that there is a regex crate, but I would like to stay with things in standard Rust. That said, splitting is a terrible way to break up lines because you have to filter empties. Is there a way to just match the words, rather than splitting on non-word sequences?Is matching on the Err part of the result proper? Or should we let the script crash? Is panicking okay?I noticed one is not allowed to say let words = line.to_lowercase().split(...) because of the infamousborrowed reference does not live long enough` but is there a cleaner way?Is there a nicer way to count words in a map? I don't like the asterisk.I wish I didn't have to do an explicit lock on stdin.Rust has a lot of things going for it, but when I compare what I got to the much prettier Julia version of this script, namely...counts = Dict{AbstractString, UInt64}()for line in eachline(STDIN) for word in matchall(r[a-z\']+, lowercase(line)) counts[word] = get(counts, word, 0) + 1 endendfor (word, count) in sort(collect(counts)) println($word $count)end...I'm thinking I don't know Rust very well, or, that's just the way things are. I mean, I know as a systems language, it's really hard to make vectors and strings. And they tell me I will learn to love the borrow checker. :) Hopefully someone with expertise in idiomatic Rust can be of service here. I'm not expecting it to be as short as the Julia code but I do fear my Rust is not idiomatic enough. | Idiomatic word counting in Rust | regex;file;dictionary;rust | There is no proper dictionary, there are just different trade-offs. In this case, we have that HashMap gives us better asymptotic random access whereas BTreeMap gives us sortedness.Sorting the a HashMap after-the-fact is well and good, but BTreeMap is already sorted so it seems like the better choice.Rust very heavily gives tasks out to crates. This is guided by RFC 1242, and you might notice regex is in rust-lang-nursery. This means it is official and it is standard rust; it's just not in the standard library.Plus, it's as easy as adding regex = 0.1 to your Cargo.toml, so that's no reason to avoid it.Ignoring that, thatlet words = line.to_lowercase().split(...) doesn't work is just a fact of life right now, although that will eventually get fixed with non-lexical lifetimes.These importsuse std::io;use std::io::BufRead;are nicer asuse std::io::{self, BufRead};The large matchmatch line_result { Ok(line) => { ... }, Err(e) => { panic!(Error parsing stdin: {:?}, e); }}would be nicer aslet line = match line_result { Ok(line) => line, Err(e) => panic!(Error parsing stdin: {:?}, e),};...or evenlet line = line_result.unwrap_or_else( |e| panic!(Error parsing stdin: {:?}, e));But in this case the error handling doesn't add anything, so I'd just unwrap. All of these examples panic; a method that doesn't would involve error handling by printing and then returning from the function. Printing is normally worse to debug (no tracebacks) but nicer for end-users.Instead of*(counts.entry(word.to_string()).or_insert(0)) += 1;which always allocates a new String, one can index with a borrowed &str. Sadly this isn't supported by the entry API right now, but you can hack around it:if let Some(count) = counts.get_mut(word) { *count += 1; continue;}counts.insert(word.into(), 1);Note the use of if let/continue instead of match is because of lexical lifetimes.Since this is currently pretty ugly and the speedup probably doesn't matter, I'll leave this as a hypothetical. You say you don't like the asterisk, but that's kind'a how it's meant to be done. I guess you could go the Julia route (get + unwrap_or + insert), but that's not really better.After a few miscellaneous changes, the code for me looks likeextern crate regex;use std::collections::BTreeMap;use std::io::{self, BufRead};use regex::Regex;fn main() { let word_re = Regex::new(r[a-z']+).unwrap(); let mut counts: BTreeMap<String, isize> = BTreeMap::new(); let stdin = io::stdin(); for line in stdin.lock().lines() { let line = line.unwrap().to_lowercase(); let matches = word_re.find_iter(&line); let words = matches.map(|(x, y)| &line[x..y]); for word in words { *counts.entry(word.into()).or_insert(0) += 1; } } for (key, value) in counts.iter() { println!({} {}, key, value); }}This isn't as nice as the Julia code, but it's giving you a lot of opportunities to be a lot more efficient, and it's catching a lot more errors. It's true that locking stdin feels like a chore on 50-line examples, but it fits Rust's macro-goals of faster, safer APIs. |
_webmaster.85083 | I have a situation for which the standard canonical prev / next doesn't seem applicable.On the first page, I have a form which collects information from the user. After the form is submitted, the site then generates 5 pages of data based upon that initial form-page input.The standard canonical approach of using prev/next to indicate sequential pages is not actually what I need. What I need is a canonical indication that all pages require that starting page. Or does one set the prev value on all pages to page 1?Currently I redirect all subsequent pages back to the initial form page if they don't have the required GET data passed in the URL string. I would think that solves the issue, but Webmaster Tools still tells me I have duplicate meta content on the 5 results pages. Is this a case for prev next? ie: Page 5 doesn't follow page 4 at all if page 1 hasn't yet been submitted.How do I best tag these results pages to indicate that they are dependent on the starting form page? | Canonical tag for pages requiring a starting form | seo;best practices;canonical url | null |
_webmaster.5091 | Trying to create folders for links where the parent has no content, it's just a folder. Need to be able to insert #, but Drupal is saying it's not a link. Just want the user to click it and nothing happen, the child of that menu item will already be being displayed without a click.Version: Drupal 6 (appears worked in D5)I've attempted the following: '', #, <#>, empty, <empty>, null, <null>, blank, <blank>, <none>, none, <answer> ...just kidding.ERROR: The path '<insert_non-url>' is either invalid or you do not have access to it.Question, just ask -- thanks! | How do you create links with a NULL or # in Drupal? | drupal | I always use the Special Menu Items module, which allows you to enter nolink as path. A 'nolink' menu item will render as a normal menu item without <a> tag, but you can style it differently if needed. |
_unix.306327 | I have to run script in one Terminal (Server) and jar file in Second Terminal (User) at same time and millisec matters. Is it Possible. Thanks | Two commands to run simultaneously in two terminals | linux;terminal | null |
_codereview.128807 | Can you help me verify my test result? I'm testing different malloc() implementations with a small program that allocates gigabytes many times:int main(int agrc, char **argv) { int i; for (i = 0; i < 1000000; i++) { void *p = malloc(1024 * 1024 * 1024); free(p); } return (0);}If I run it and time it, then it takes 5 seconds:$ time ./gig real 0m5.140suser 0m0.384ssys 0m4.752sNow I try my custom malloc() with exactly the same program and it seems unreasonable faster.$ time ./gb_quickfitreal 0m0.045suser 0m0.044ssys 0m0.000sWhy is the custom malloc() so much faster? I used the quick malloc() algorithm. void *malloc_quick(size_t nbytes) /* number of bytes of memory to allocate */{ Header *moreroce(unsigned); int index, i; index = qindex(nbytes); /* * Use another strategy for too large allocations. We want the allocation * to be quick, so use malloc_first(). */ if (index >= NRQUICKLISTS) { return malloc_first(nbytes); } /* Initialize the quick fit lists if this is the first run. */ if (first_run) { for (i = 0; i < NRQUICKLISTS; ++i) { quick_fit_lists[i] = NULL; } first_run = false; } /* * If the quick fit list pointer is NULL, then there are no free memory * blocks present, so we will have to create some before continuing. */ if (quick_fit_lists[index] == NULL) { Header* new_quick_fit_list = init_quick_fit_list(index); if (new_quick_fit_list == NULL) { return NULL; } else { quick_fit_lists[index] = new_quick_fit_list; } } /* * Now that we know there is at least one free quick fit memory block, * let's use return that and also update the quick fit list pointer so that * it points to the next in the list. */ void* pointer_to_return = (void *)(quick_fit_lists[index] + 1); quick_fit_lists[index] = quick_fit_lists[index]->s.ptr; /* printf(Time taken %d seconds %d milliseconds, msec/1000, msec%1000);*/ return pointer_to_return;}I'm sure there is a catch because I don't have much experience in this detailed level of C. Why are the results so different? Does the system malloc() only have one algorithm?Can I be sure that the test is correct? If I run Valgrind with the test, it reports no error . I try again run the test, check with Valgrind that the test doesn't generate error with Valgrind and get the result again$ time ./gb_quickfit real 0m0.759suser 0m0.584ssys 0m0.172sdac@dac-Latitude-E7450:~/ClionProjects/omalloc/openmalloc/overhead$ time ./a.out real 0m0.826suser 0m0.644ssys 0m0.180sNow the result is more reasonable, my custom malloc is only slightly faster. The reason I got so large difference first time might have been of errors in the test allocating too much. The second test looks like:/* returns an array of arrays of char*, all of which NULL */char ***alloc_matrix(unsigned rows, unsigned columns) { char ***matrix = malloc(rows * sizeof(char **)); unsigned row = 0; unsigned column = 0; if (!matrix) abort(); for (row = 0; row < rows; row++) { matrix[row] = calloc(columns, sizeof(char *)); if (!matrix[row]) abort(); for (column = 0; column < columns; column++) { matrix[row][column] = NULL; } } return matrix;}/* deallocates an array of arrays of char*, calling free() on each */void free_matrix(char ***matrix, unsigned rows, unsigned columns) { unsigned row = 0; unsigned column = 0; for (row = 0; row < rows; row++) { for (column = 0; column < columns; column++) { /* printf(column %d row %d\n, column, row);*/ free(matrix[row][column]); } free(matrix[row]); } free(matrix);}int main(int agrc, char **argv) { /* int i; for (i = 0; i < 1000000; i++) { void *p = malloc(1024 * 1024 * 1024); free(p); }*/ int x = 10000; char *** matrix = alloc_matrix(x, x); free_matrix(matrix, x, x); return (0);} | Testing different implementations of malloc() | c;memory management;benchmarking | It's very possible that the memory is not really being allocated in RAM, but is in the virtual address space. I couldn't guess why your implementation causes this, but if you keep the memory allocated and sleep, you may find (assuming your on Linux, I don't know about Windows) that the memory is allocated but not backed by anything till you use it, due to the size. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.