id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_unix.122189 | I'd like to override some hardcoded paths stored in pre-compiled executables like /usr/share/nmap/ and redirect them to another dir.My ideal solution should not require root priviledges, so creating a symlink is not ok.(Also recompiling it's not an option) | override hardcoded paths in executables | executable;sandbox;portable | I've just found this ptrace-based chroot reimplementation: PRoot.The bind function is just what i was looking for!This is more reliable than replacing strings in the executable + can be easily used in scripts... |
_cs.47942 | Can quantum computer become perfect chess player?Can it determine whether (when both players are perfect) win white or black? (or is it dead heat?) | Can quantum computer become perfect chess player? | quantum computing | I've already answered essentially this question, on Chess Stack Exchange. The executive summary is that chess doesn't seem particularly well-suited to quantum computation's strengths so there's no particular reason to believe that a quantum computer would be any better at it than a classical one. |
_webapps.65787 | I have just created a Tumblr blog using the Indy theme. After creating a new post, I noticed that the notes do not show up, just a short line.I tried searching for an option to make the notes visible, but I could not find it. As it was pointed out, apparently not all themes display notes.How do I make the notes visible if using the Indy theme? What changes do I have to make to its HTML? Here is my blog if you need to see what I am talking about: empathetic-moose.tumblr.comThank you. | Making notes visible when using a Tumblr theme that doesn't show them | tumblr;tumblr themes | null |
_unix.155291 | I need to provide user access to Ubuntu 14.04 Server, only limited to certain folder. To enjoy the ssh security and not to open up new service and ports (ie, ftp), I'd like to stick with sftp. However, just creating a user and enabling ssh access is too generous - the user then can log on via ssh and see whatever there is that is viewable by everybody.I need the user to find themselves in a specific directory after login, and, according to their privileges, read/write files, as well as create folders where permitted. No access to any file or directory above the user's root folder.What would be the suggested method to achieve this? Is there some very restricted shell type for this? I tried with$ usermod -s /bin/false <username>But that does not let the user to cd into subfolders of their base folder. | Provide sftp read/write access to folder and subfolders, restrict all else | ssh;permissions;sftp | If you want to restrict a user to SFTP, you can do it easily in the SSH daemon configuration file /etc/ssh/sshd_config. Put a Match block at the end of the file:Match User bobForceCommand internal-sftpChrootDirectory /path/to/rootAllowTCPForwarding noPermitTunnel noX11Forwarding noIf the jail directory is the user's home directory as declared in /etc/passwd, you can use ChrootDirectory %h instead of specifying an explicit path. This syntax allows specifying a group of user accounts as SFTP-only all users whose group as declared in the user database is sftponly will be restricted to SFTP:Match Group sftponlyForceCommand internal-sftpChrootDirectory %hAllowTCPForwarding noPermitTunnel noX11Forwarding no |
_datascience.865 | I need to build parse tree for some source code (on Python or any program language that describe by CFG).So, I have source code on some programming language and BNF this language.Can anybody give some advice how can I build parse tree in this case?Preferably, with tools for Python. | How to build parse tree with BNF | python;parsing | I suggest you use ANTLR, which is a very powerful parser generator. It has a good GUI for entering your BNF. It has a Python target capability. |
_unix.216538 | I'm trying to install LMDE 2 'Betsy' 64-Bit dual-booting with Windows 8.1 and both systems encrypted separately, Windows with truecrypt and LMDE with luks. When booting I want to be asked for the truecrypt volumes password and when I press Esc GRUB should start and boot the encrypted Linux. I want to have a LVM partition for my data which will be my home directory in Linux and which I plan to access with https://github.com/t-d-k/LibreCrypt . My problem is that I can't get GRUB working.Most of the following steps I took from https://wiki.ubuntuusers.de/system_verschl%C3%BCsseln and changed them to fit my needs.Here is my setup although Windows is not encrypted yet:/dev/sda1 Windows Recovery ntfs/dev/sda2 Boot ext4 300MiB/dev/sda3 Windows 8.1 truecrypt/dev/sda4 crypt-luks crypt-luksAnd here is what I did:Boot LMDE 2 from USB stick.Select German as language.Do the other stuff until I have to select a partition. There I enter Expert Mode where I get asked to mount my target System under /Ziel but it needs to be /target. I start to get the system ready with:cryptsetup -c aes-xts-plain64 -s 512 -h sha512 luksFormat /dev/sda4cryptsetup luksOpen /dev/sda4 lukslvmpvcreate /dev/mapper/lukslvmvgcreate vglmde /dev/mapper/lukslvmThen I create my logical volumes:lvcreate -L 8G -n swap vglmdelvcreate -L 25G -n root vglmdelvcreate -l 100%FREE -n home vglmdeI format these partitions with labels:mkswap /dev/mapper/vglmde-swap -L swapmkfs.ext4 /dev/mapper/vglmde-root -L rootmkfs.ext4 /dev/mapper/vglmde-home -L homeThen I mount the logical root partition in /target to continue installing:mkdir /targetmount /dev/mapper/vglmde-root /targetmkdir /target/bootmount /dev/sda2 /target/bootmkdir /target/homemount /dev/mapper/vglmde-home /target/homeThen I continue the installation. When asked I choose that GRUB should be installed in /dev/sda2 because that is my boot partition.After the dialog Installation paused shows up, I perform the following steps:mount -o rbind /dev /target/devmount -t proc proc /target/procHere I get the message that proc is already mounted on /target/procmount -t sysfs sys /target/sysHere it says that sys is already mounted or /target/sys is busy.cp /etc/resolv.conf /target/etc/resolv.confchroot /target /bin/bashThen I make sure the required packages are up-to-date.apt-get updateapt-get install cryptsetup lvm2To set up the /etc/crypttab I first get the UUID and then append to the crypttab replacing with the UUID.blkid /dev/sda4echo lukslvm UUID=<MY_UUID> none luks >> /etc/crypttabThen I append some necessary modules.echo dm-crypt >> /etc/modulesecho ohci_pci >> /etc/initramfs-tools/modulesupdate-initramfs -u -k all -tAnd I edit the /etc/fstab .echo /dev/sda2 /boot ext4 defaults 0 2 >> /etc/fstabecho /dev/mapper/vglmde-root / ext4 defaults,errors=remount-ro 0 1 >> /etc/fstabecho /dev/mapper/vglmde-swap none swap sw 0 0 >> /etc/fstabecho /dev/mapper/vglmde-home /home/ ext4 defaults 0 2 >> /etc/fstabThen I update GRUB and leave chroot.update-grubexitsyncAnd continue the installation.When asked if I want to reboot I say yes and......at reboot I get the following output:error: no such partitionEntering rescue mode...grub rescue>Now I can't figure out where I went wrong. Am I right that GRUB should have loaded normally when there is no other boot-able partition?P.S. When debugging the following commands let you use the installed system when on a live disc.Mounting the encrypted Volumecryptsetup luksOpen /dev/sda4 lukslvmSearch and add the volume groups.vgscanvgchange -a yMount the volumes as usualmount /dev/mapper/vglmde-root /mnt | Problem with GRUB for dual-boot installation of LMDE 2 (and Windows) on encrypted luks-lvm (truecrypt) | grub2;dual boot;luks;lmde | null |
_unix.237817 | I have a process that receives a video file (RAW) and transcodes it with FFMPEG generating three (different resolutions) resultant files. I'm using a distributed task queue system (Celery) to process every process from FFMPEG in a different asynchronous task.The three tasks run, according to the flowConvert videoUpload result to a bucket in cloudDelete resultAnd a last task upload the RAW video (used for transcoding) to bucket, and delete it.If I start the three tasks asynchronously, and delete the RAW file just after, will the tasks (that are using the RAW file) be interrupted by deleting the file?PS: I assuming that, the RAW file is loaded in memory, and opened three times, while the transcoding task were started. | Delete file while it is in use | files;concurrency | The assumption that the complete RAW file is in memory is not true. Normally, when a file is opened the process gets a file descriptor which can be used to read/write the file.When a file is opened by a process and then is deleted while the file is still open does not actually delete the file instantly. The file is actually deleted when there are no processes anymore with handles (file descriptors) to that file. You can use lsof to see if the file still has handles and when you delete such file it is often listed with the (deleted) text appended to the line.Disk space is also not reclaimed when an open file is deleted so it is safe to still use the file as long as it is open. When the deleted file does not have active file descriptors anymore the filesystem will reclaim the consumed disk space. |
_datascience.641 | I'm currently searching for labeled datasets to use to train a model to extract named entities from informal text (think something similar to tweets). Because capitalization and grammar are often lacking in the documents in my dataset, I'm looking for out of domain data that's a bit more informal than the news articles and journal entries that many of today's state of the art named entity recognition systems are trained on. Any recommendations? So far I've only been able to locate 50k tokens from twitter published here: https://github.com/aritter/twitter_nlp/blob/master/data/annotated/ner.txt | Dataset for Named Entity Recognition on Informal Text | dataset;nlp | null |
_softwareengineering.216750 | MotivationThe main idea is to explore and understand the limits of how far one can go with the basic LINQ primitives (Select, SelectMany, Concat, etc.). These primitives can all be considered functional operations on a theoretical sequence type. Taking examples from Haskell:Select 'lifts' a function into the sequence (like fmap in Haskell)Concat is compositionAggregate is the sequence type's catamorphism (fold)SelectMany 'extracts' information from the sequence (the Monad bind, >>= operation)etc. (and I'm sure there are better abstractions for the above)So the question is whether or not the basic sequence (Enumerable) operations in C# are enough to construct an infinite sequence. More concretely it is the following problem:ProblemI'm curious to know if there's a way to implement something equivalent to the following, but without using yield:IEnumerable<T> Infinite<T>(){ while (true) { yield return default(T); }}Is it possible to do sue using the built-in LINQ operators only? The short answer is that theoretically yes, but practically not because of how Linq is implemented (causing stack overflows).That's why here are less restrictive rules:RulesAlternatively a less restrictive question would go by the rulesYou can't use the yield keyword directlyUse only C# itself directly - no IL code, no constructing dynamic assemblies etc.You can only use the basic .NET lib (only mscorlib.dll, System.Core.dll? not sure what else to include). However if you find a solution with some of the other .NET assemblies (WPF?!), I'm also interested.Don't implement IEnumerable or IEnumerator.NotesAn example theoretically correct definition is:IEnumerable<int> infinite = null;infinite = new int[1].SelectMany(x => new int[1].Concat(infinite));This is correct but hits a StackOverflowException after 14399 iterations through the enumerable (not quite infinite).I'm thinking there might be no way to do this due to the C#'s compiler lack of tail recursion optimization. A proof would be nice :) | Is it possible to implement an infinite IEnumerable without using yield with only C# code? | c#;linq;clr | Even if your assertion was true, proving it would be infeasible, because the proof would have to go through all implementations of IEnumerable in the framework and prove for each one of those that it can't be infinite.And your assertion actually isn't true, there is at least one implementation of IEnumerable in the framework that can be infinite: BlockingCollection.GetConsumingEnumerable():What you would do is to create a bounded BlockingCollection that's filled in an infinite loop from a separate thread. Calling GetConsumingEnumerable() will then return an infinite IEnumerable:var source = new BlockingCollection<int>(1);Task.Run(() => { while (true) source.Add(1); });return source.GetConsumingEnumerable(); |
_webapps.1383 | I assume probably most of you use Google Reader for following and reading RSS or Atom feeds. My question is are there any web alternatives that some of you have used and are happy with? | Are there other web alternatives of Google Reader? | webapp rec;google reader;rss | null |
_scicomp.11787 | I am comparing the performance several finite difference methods of solving an initial-boundary value problem. There are several dimensions to this comparison:Number of cellsNumber of timestepsSolution Method:Explicit (one sweep on a single thread, no iterations)Alternating Direction Explicit (two sweeps on separate threads, no iterations)Alternating Direction Implicit (two sweeps on one thread [TDMA] with three sub-timesteps, no iterations)Fully Implicit (any number of threads, using an iterative BICGSTAB solver)Question:My question is this: What metric should I use to compare the relative performance for various combinations of number of cells, number of timesteps, and solution method? There is some information on performance metrics on David J. Lilja's website. He seems to consider execution time (wall and CPU) as the best metric. But I'm wondering if there might be a more suitable metric for my application.Here is what I've considered so far:Wall time and CPU time: This is easy to measure, but the problem is that it is only representative for computer architecture where the program is executed. I'm doing most of my testing on a 24 core machine...which won't be representative of typical applications. It would be nice not to have to include a description of the machine's architecture every time I publish results. Are there meaningful ways to normalize measured time to avoid this problem?Number of Operations: Sum of (N_iterations*N_sweeps*N_sub-timesteps*N_cells)/(N_threads) across all timesteps.This is repeatable and platform independent, but it doesn't include some of the overhead of setting up the initial-boundary value problem and creating matrices, etc. It also makes some simplifying assumptions about threading overhead.It would also be nice to give a rough estimate of parallel and serial performance, so that someone could get a sense of what the speed up would be for a given number of processors (i.e., a way to extrapolate from the results on my 24 core machine). | Performance metrics to compare initial-boundary value problem solutions | linear algebra;pde;performance;iterative method;explicit methods | null |
_unix.32593 | I upgraded to PHP5.3 using this tutorial: http://www.debiantutorials.com/how-to-install-upgrade-to-php-5-3-on-debian-lenny/It removed the following packages:Removing php-pear ...Removing php5-pgsql ...Removing php5-mysql ...Removing php5-mcrypt ...Removing php5-ldap ...Removing php5-gd ...Removing php5-curl ...Removing php5-sasl ...Removing php5-cli ...All seemed well, it warned me those packages would be removed, which was fine, I figured I could just install them after. But now, when I try, it warns me that I am missing dependencies:The following packages have unmet dependencies: php5-cli: Depends: libc6 (>= 2.11) but 2.7-18lenny7 is to be installed Depends: libdb4.8 but it is not installable Depends: libgssapi-krb5-2 (>= 1.6.dfsg.2) but it is not installable Depends: libk5crypto3 (>= 1.6.dfsg.2) but it is not installable Depends: libkrb5-3 (>= 1.6.dfsg.2) but it is not installable Depends: libncurses5 (>= 5.7+20100313) but 5.7+20081213-1 is to be installed Depends: libreadline6 (>= 6.0) but it is not installable Depends: libssl0.9.8 (>= 0.9.8m-1) but 0.9.8g-15+lenny16 is to be installed Depends: libxml2 (>= 2.7.4) but 2.6.32.dfsg-5+lenny5 is to be installedE: Broken packagesWhat can I do to fix this issue and get these back? | Debian: Upgraded to php 5.3 and lost phpcli, php-pear, etc | linux;debian;apt;php | null |
_unix.159732 | Okay, I've been trying to repair my GRUB for awhile on my version of Lubuntu 14, and nothing seems to work. It seems that an update has broken my GRUB, so that now when I try to boot on the computer, it only takes me to a black screen where I can type, but none of the inputs do anything. After resetting it once or twice, it takes me a screen of options, where I select recovery mode, and then from the recovery mode menu to boot normally, which does indeed make it boot normally. I tried Boot Repair twice, and it said it works, but nay. I actually got two separate paste messages too after each attempted repair. I'm not sure if anyone will care for the first, but here's the second: http://paste.ubuntu.com/8503260 . What should I do? | Update Corrupted GRUB; Can't Boot Right | linux | null |
_unix.85658 | So I have a custom in-house app developed by a 3rd party. When the app is running, I can verify it is running with the screen -ls command. As long as screens are running for rails and freeswitch then I know the app is properly up and running. We have a specific bash script to stop the services related to the app, and 2nd script to start the services related to the app. My question is how can I combine both these scripts to restart the app into 1 script that works like the following:Run script 1 - stop appWait until app has shutdown (screen processes are no longer running)Run script 2 - start appWait until app has startedCheck screen sockets to make sure a rails and freeswitch process is running. If not, then go back to step 1 and repeat. Right now to restart the app:I manually run the stop script via /tools/stop_app.shThis then outputs to the terminal to show services shutting down. Once complete, it returns me back to the terminal prompt. Now I manually run the start script via /tools/start_app.shThis doesn't output anything, but once it has completed it returns me to the terminal prompt. I then run screen -ls to verify all services for the app is running. (sometimes a service such as freeswitch doesn't start.)If not, then I re-run the stop/start scripts. It might be asked why don't I just put everything into one script. Well this custom app is very finicky and due to limited support from the developers, we need to make sure to utilize the exact tools they provided. Hence 1 script that calls the 2 separate scripts provided by the developers. By integrity check I am referring to checking the screen processes to make sure that the ruby and freeswitch screens are running. For the cron, I would like to perform this app restart automatically on a weekly basis. Note, when I say bash script I am not sure if it correct to say bash or shell. I have no script preference as long as it is a language that usually comes installed by default in Ubuntu Linux. | Cron automated bash script to run run 1 bash script then another, plus integrity check | bash;shell;ubuntu;cron;gnu screen | null |
_unix.269036 | My Chief Security Officer (CSO) want to log the activity of the privileged account (root). I know I can configure sudo to log user input (key strokes) and console/terminal output (stdout/stderr), as explained in How to log commands within a sudo su -?. But the content is always logged to a file locally. That file can easily be wiped by the root user ! I have enable logging in /etc/sudoers:Defaults>root log_input, log_outputDefaults iolog_dir=/var/log/sudo-ioor equivalentroot ALL = (ALL) LOG_INPUT: LOG_OUTPUT: ALLHow to protect/secure the file from deletion ? | How to protect/secure the sudo log_input/log_output logs? | sudo;root;logs | null |
_webmaster.82729 | Pre-HTML5 we used div and ul tags to markup navigation bars and a lot of times the navigation is at the top of the HTML document. In the absence of meta description content, Google uses its own logic to determine what to use in place of the description to show in the search results. Turns out it picks the text in the navigation bar instead of the page contents.Will using nav tags to markup navigation make Google skip the navigation? What tags will indicate to Google that the enclosed content is the main page content?Please avoid suggesting the use description meta tag to solve this problem. I am more of trying to understand the behaviour and result when not using description meta tags. | Will Google skip nav tags when considering what content to use as page descriptions? | google search;html5;serps;navigation | null |
_webmaster.65423 | I recently noticed that my web page have problems with Google and good search results.Many of the existing SEO tools suggests that my website uses bad URLs for SEO. I'm using a single PHP file that handles all the sections via parameters.By example:www.alanmarth.com/index.php (Main Page)www.alanmarth.com/index.php?seccion=servicios (Services)www.alanmarth.com/index.php?seccion=blog (Recent news)www.alanmarth.com/index.php?seccion=blog&cat=2 (News category)www.alanmarth.com/index.php?seccion=blog&id=3 (A single entry)Is this ok? If it isn't, how can I solve it without having to rewrite my entire site? | Is using URL parameters bad for SEO? | php;wordpress;htaccess;seo | Regarding: Is this ok?No, its not good/intuitive for your users and hence not good for SEO. You should be using something like thiswww.alanmarth.com/ (Main Page)www.alanmarth.com/servicios (Services)www.alanmarth.com/blog (Recent news)www.alanmarth.com/blog/nameOfCategory2 (News category)www.alanmarth.com/blog/titleOfBlog3 (A single entry)Regarding: how can I solve this without having to rewrite all my site?Are you talking about re-writing whole site code base or just the urls that are planted here and there? Re-writing whole code base is not necessary but you will have to replace the urls everywhere with the new SEO friendly urls. So you need to do following changes:add to .htaccess file in your root folder with the following lines:RewriteCond %{REQUEST_FILENAME} !-fRewriteRule ^ index.php [QSA,L]this will lead all your requests to be served by index.phpparse the $_SERVER['REQUEST_URI'] to figure out what section and category is this request all about. Like if the request uri is /blog this means that $_GET['seccion']=blog in your code. So map it accordingly. And so on.Not much needs to be changed after that. |
_unix.361069 | i am trying to set up psad (port scan detection system) but it doesn't work.I think that something is wrong with my iptables, because psad always send[-] You may just need to add a default logging rule to the /sbin/ip6tables 'filter' 'INPUT' chain on nameOfcomp. For more information, see the file FW_HELP in the psad sources directory or visit:http://www.cipherdyne.org/psad/docs/fwconfig.html# iptables -LChain INPUT (policy ACCEPT)target prot opt source destination ACCEPT all anywhere anywhere ACCEPT icmp anywhere anywhere LOG all anywhere anywhere LOG level warningDROP all anywhere anywhere REJECT all anywhere anywhere reject-with icmp-port-unreachableChain FORWARD (policy ACCEPT)target prot opt source destination ACCEPT all anywhere anywhere ACCEPT icmp anywhere anywhere LOG all anywhere anywhere LOG level warningDROP all anywhere anywhere REJECT all anywhere anywhere reject-with icmp-port-unreachable# ip6tables -LChain INPUT (policy ACCEPT)target prot opt source destination ACCEPT all anywhere anywhere ACCEPT ipv6-icmp anywhere anywhere LOG all anywhere anywhere LOG level warningDROP all anywhere anywhere REJECT all anywhere anywhere reject-with icmp6-port-unreachableChain FORWARD (policy ACCEPT)target prot opt source destination ACCEPT all anywhere anywhere ACCEPT ipv6-icmp anywhere anywhere LOG all anywhere anywhere LOG level warningDROP all anywhere anywhere REJECT all anywhere anywhere reject-with icmp6-port-unreachablePlease somebody tell me what with my iptables? How to set them up to make psad works? | psad service Linux | iptables;psad | null |
_codereview.117715 | I recently found an interesting series that describes the specifics of how interpreters and compilers work, explaining each step (with code) and encouraging the reader to do exercises.My code is mostly based on the boilerplate provided in the first tutorial. The description didn't really seem clear enough to me, so I went on to consult the actual code. That was probably the best idea in my case, as it helped me grasp the very basics of lexical analysis.Once I'd had the code working, I reread the article and by then I felt confident enough to approach the exercises.I had no problem with getting my code to satisfy the conditions in the exercises.However, I'm not sure whether my approach was good. I used regular expressions to tokenize the input and remove whitespaces at the same time. That kind of solution seemed robust; the code worked, but I felt a bit uneasy about it (though I couldn't really explain to myself why the use of regular expressions here was wrong). I then looked at the code in the second tutorial that solved all the exercises, and it didn't use regular expressions at all — instead, it iterated over each character (including whitespaces).I coded my lexer in JavaScript and run it in Node.js (though it can be run in virtually every environment that supports ES6 classes).What kind of feedback do I expect? I would like to see my doubts about regular expressions explained (does any lexer do that? If not, why?), but there are probably many things about the code that can be done better — and I will really appreciate the answers which suggest improvements. There are also a few more questions at the bottom of this post.Note: The script does not yet respond to user input, the input sequence needs to be hardcoded as a string.See below for explanations on certain parts of the code.'use strict';class Token { constructor(type, value) { this.type = type; this.value = value; }}['EOF', 'INT', 'MATHOP'].forEach(function (el) { // #1 Token[el] = el;});class Interpreter { constructor(source) { this.source = source; this.pos = 0; this.currentToken = null; } eat(type) { if (this.currentToken.type === type) { this.currentToken = this.getNextToken(); } else { throw new Error('Unexpected token of type ' + this.currentToken.type); } } getNextToken() { if (this.pos >= this.source.length) { return new Token(Token.EOF, null); } var s = this.source.slice(this.pos); // #2 var re; // #3 if (re = /^\s*([0-9]+)/.exec(s)) { this.pos += re[0].length; return new Token(Token.INT, +re[1]); } if (re = /^\s*([-+*/])/.exec(s)) { this.pos += re[0].length; return new Token(Token.MATHOP, re[1]); } throw new Error('Erroneous input'); } expr() { this.currentToken = this.getNextToken(); var left = this.currentToken; this.eat(Token.INT); var op = this.currentToken; this.eat(Token.MATHOP); // #4 var right = this.currentToken; this.eat(Token.INT); switch (op.value) { case '+': return left.value + right.value; case '-': return left.value - right.value; case '*': return left.value * right.value; case '/': return left.value / right.value; } }}var i = new Interpreter('11 * 23'); // #5console.log(i.expr());Explanations:At first, all I had was Token.EOF = 0; and so on, each token being assigned a unique, successive number. That wasn't really useful, as stack traces would display the number and I'd have to either remember the type or look it up in the code. I thought that string equivalents would be much more useful, and, to automate the task, I used a forEach() call here. The strings are identical to the keys of Token, so one could think I could stick to strings only and never use variables for that. I think that would get out of control quickly, so, to keep things in place, I assigned the string values as Token's properties. I'd like to know if this is a good idea.Once the number of characters to drop in the beginning (calculated in earlier calls to getNextToken(), initially 0) is known, slice the string.This variable is used in the following if statements and serves two purposes — it keeps the result of the regex match, but also passes null on to the if statement if there is no match. Is this clever, or too clever?The actual regexes ensure that any whitespace preceding the expected token is dropped.The second part of the tutorial mentioned above uses separate tokens for both the + and - signs. My code unifies all the basic arithmetic operators and uses the token's value to determine the operation to be performed. This is what I would like to see criticized as well. I know that in the future I would have to take operator precedence into account, but I think I could solve it sticking to this way.Currently this is the only way to pass input to the interpreter. Once it gets more complex, I will ensure that the input can be supplied in a user-friendly way. | Simple lexical analysis - basic calculator | javascript;regex;math expression eval;lexical analysis | I'm not a compiler guy, but I'll offer some feedback, anyway. Hope it helps.Nice work.Regular expressions are a powerful tool, but they can become difficult to maintain and sometimes to get right. You used them, they work, seems fine. I'd suggest making it a point to always use simple regular expressions (which you did). If you need more complex matching, using multiple simple regular expressions in a sequence or loop or in combination with character / string comparisons seems to work pretty well. To answer your questions:1: Using integers does make error messages harder to read, so switching to strings for token types is a good idea, IMO. But, instead of adding properties onto the Token class I'd suggest doing something like the following:var tokenTypes = Object.freeze({ EOF: 'EOF', INT: 'INT', MATHOP: 'MATHOP'});In the past I've done something like this to make error messages and what not easier to read:var tokenTypes = Object.freeze({ EOF: 'tokenType { EOF }', INT: 'tokenType { INT }', MATHOP: 'tokenType { MATHOP }'});2: Slicing the string is fine. If there is more to the question, then please elaborate.3: Use of the re variable to store the match is not too clever. I recommend against assignment inside the if condition, though, it's just something that can be error prone, in general. Down the road you may make an edit and forget to have only one =, or something like that. It's usually considered against best-practices, but is not invalid or anything.4: As I'm not a compiler guy, take this for what it's worth (there is probably obvious conventional wisdom that I don't know about). Using a single token type for these four operations seems fine to me. They all have similar characteristics. But, it will likely be an issue if you broaden this MATHOP usage to operators that have different characteristics, like the unary - (e.g. 1 + -(3 + 4)). Having said that, you may end up keeping these four operators under one BINARY_OP type. You may end up wanting to group on precedence, though.5: Not a question.One thing I want to note, the eat and getNextToken methods are organized in a way that is a little strange, to me. You consume a token (move pos forward), then when you are getting the next token after that, check the type of the previous token. I like to have separate getNNNToken methods for the various tokens I have. For instance, you might have getIntToken() and getOpToken(). Each of these can attempt to consume the correct type of token, and if it fails return undefined. The method that called them can decide if that is an error or if another type of token should be attempted, like getEofToken().As a side note, a scanner I wrote for a DSL: JavaScript and Python. It uses a mix of regular expressions and character comparisons for consuming content. The scanner has a start property and a pos property, and any time a token is created the content spans from start to pos-1. Then, start is moved forward to pos. |
_webapps.99859 | Sometimes I will get a Google Photos notification that Google Photos has created a new stylalised image. How can I disable these notifications? | Disable Google Photos Notification of New Photo Created | google photos | null |
_webapps.28741 | I want to create a Gmail filter that identifies all sent mail. If I were to do the same for all the spam message, I know I could use is:spam. Is there a similar command for sent mail? Something like is:sentmail? | Is there a is: filter for mail in my Gmail sent folder? | gmail | Sent messages are labeled as sent, so you can use that to search for them. Either is:sent, in:sent or label:sent should work. |
_softwareengineering.181545 | I have a print operation to perform for my customer documents.I need the other standard operations to be performed as well, like add,update, delete.so, I have following: For creating new customer:URI = /customer/{id}, type = POST,Methodname = CreateCustomer()For updating:URI: /customer/{id}, type = PUT, method =UpdateCstomer()For Delete customer:URI = /customer/{id}, type =DELETE, Methodname = DeleteCustomer()For View:URI: /customer/{id}, type = GET, method = GetCustomer()Now, if I need to print a document for that customer, I need a print function.My URI may look like this: /customer/{id}, type = POST , method = PrintCustomer().But I have used that URI and POST type for CreateCustomer.I wanted the URI to look like this:/customer/Print/{id}, type = POST , method = PrintCustomer().But I cannot have Print verb in my URI. Whats the best way to do this?I thought about /customer/document/{id} as the URI... but I will run into the same issue.I would have the CRUD operations on the document. So, again I run out of what I would used for print.Please advise. | Represent actions(verbs) in REST URI | rest | null |
_unix.172370 | When installing a module, I noticed the following:ModSecurity for Apache/2.8.0 (http://www.modsecurity.org/) configured.[Tue Dec 09 19:01:10 2014] [notice] ModSecurity: APR compiled version=1.4.5; loaded version=1.4.5[Tue Dec 09 19:01:10 2014] [notice] ModSecurity: PCRE compiled version=8.2 ; loaded version=8.02 2010-03-19Is it possible to run a command to see all loaded libraries and also their versions? Also is there pcre library on macos which I can use to compile mod_security to match the one that Apache is using? | Configuration of compiled Apache2 | apache httpd | null |
_unix.99425 | Running Ubuntu 13.10 with a fully compiled ffmpeg. I know the code for the actual conversion is ffmpeg -i video.mp4 -codec copy video.aviI just need a plain and simple Bash script to do that for, say, forty or fifty of the .mp4 files. | Batch Convert .mp4 to .avi with ffmpeg | conversion;ffmpeg | If you have a list of file you can use something like:cat list-of-files.txt | while read file; do ffmpeg -i $file -codec copy ${file%%.mp4}.avi; doneor simplycd /path/; ls *.mp4 | while read file; do ffmpeg -i $file -codec copy ${file%%.mp4}.avi; done |
_datascience.266 | Being new to machine-learning in general, I'd like to start playing around and see what the possibilities are.I'm curious as to what applications you might recommend that would offer the fastest time from installation to producing a meaningful result.Also, any recommendations for good getting-started materials on the subject of machine-learning in general would be appreciated. | What are some easy to learn machine-learning applications? | machine learning | I would recommend to start with some MOOC on machine learning. For example Andrew Ng's course at coursera.You should also take a look at Orange application. It has a graphical interface and probably it is easier to understand some ML techniques using it. |
_unix.186574 | No documentation, keystone employee leaves ... All I have is the known URL that is called. How do I determine the account that executes this site so I can find the httpd.conf file and scripts? Furthermore I have no access to the machine until I provide the account I need ... Catch 22, um I don't know the account.The only thing going is the port number is a four digit non common number.So I asked our admin to grep for this port number in all conf files but he claims there were only 2 hits and both irrelevant. URL formatted like this ... https://mytestsite.company.com:4680/vendorXCBLIs there a command I should have executed? Or a file I should request? Thanks for any insight.Oh, and I'm new to Solaris and Unix.Regards, danProblem solved, I was given the wrong machine name, doh! Everything falls together when I'm looking at the right machine. Noobie shock syndrome.Thanks for the response. | How can I determine the Unix account that a URL is associated with? | solaris;web | null |
_unix.88064 | I have Debian 7 with grub 1.99 in sda1 and Chakra OS without grub in sda2 I want to make a dual boot via grub 1,99, how? | Add Chakra os benz to grub 1.99 | debian;boot;grub2;dual boot | null |
_unix.197975 | Recently, I've been fiddling around with Linux's terminal commands to try and get a better feel for the system.I was happy to know that I could give commands a different name in order to call them, using the alias command. For example,alias print=echoIn this case, the echo would be replaced by print.The only problem is that it only seems to stay for one terminal session. Without the use of third party software, is there a way that I can keep these aliases permanently? If there are software alternatives, I'll be glad to hear them.I'm just looking for a way to do this without downloading anything. | bash: Saving aliases beyond one session | bash;alias;session | null |
_codereview.152434 | I have a bit of EF Lambda code which returns a list of data from the db table, then orders by a field called IsDefaultAt first, the code wasvar listOfData = Db .TableName .Where(u => u.UserId == userId) .OrderBy(u => u.IsDefault) .ToList();Which when writing down, sounds correct. However is wrong as this will order by 0 > 1, and True = 1.So I changed the statement to;var listOfData = Db .TableName .Where(u => u.UserId == userId) .OrderBy(u => u.IsDefault ? 0 : 1) .ToList();However, I could have also written this 2 other ways..OrderBy(u => !u.IsDefault)OR.OrderByDescending(u => u.IsDefault)Now in my mind, u.IsDefault ? 0 : 1 reads better, and the other two could be misread as the not wanting the default value first.What is your view on this? | Ordering data by boolean | c#;entity framework;lambda | I wouldn't use either ordering on the server side because it looks like the ordering only matters for displaying the data. I cannot imagine why it should matter from the programmatic point of view.Let the client, its view, its display control, or whatever sort the items according to its needs. |
_unix.148255 | I am a Linux Mint 17 - Cinnamon user, and have been using it for the past 1 month. I am new to this OS, and trying to learn how to work in a linux environment.My system boots extremely slowly (takes about 20 minutes), and when it does boot the desktop is very unresponsive. Double clicks and keystrokes take way too long to register, though the mouse moves around normally. The whole thing started yesterday after my system shut down because of a power cut. I was not upgrading or installing anything. While looking for clues as to what went wrong, on rebooting, I pressed the arrow keys a bit and this took me to a logging screen (?) listing a bunch of (boot?) tasks and their status.There were a bunch of * xyz task [ok]followed by:* Starting load fallback graphics devices [fail]Followed by more [OK]s, followed by:* Starting SMB/CIFS file and active directory server [fail] After a few more [OK]s the system boots, and there I have the slowdown problems described above. I am dual booting this on my desktop along with windows 7. The entire Linux mint system is on a different hard disk, as is my windows installation. My PC specifications include:a core i7 processor.8GB RAM.a Nvidia GTX 670 Graphics Card. | Slow boot and slow desktop, along with indecipherable log messages | linux mint;graphics;cifs;smb | null |
_codereview.138476 | I was bored the other day and decided to have a crack at Project Euler Problem 54 for some fun. Given a file containing one thousand poker hands dealt to two players, the task is to count the number of hands won by Player 1.This is the first project Euler problem i have completed and thought it would be good to get some feedback as i feel to help myself improve on my coding style and optimise the solution.Card Class public class Card {private String card;private String suit;private cardValue value;public String getSuit() { return suit;}public cardValue getValue() { return value;}public Card(String card) { this.card = card; this.value = convertValue(this.card.substring(0, 1)); this.suit = this.card.substring(1, 2);}public cardValue convertValue(String v){ switch(v){ case 2: return cardValue.Two; case 3: return cardValue.Three; case 4: return cardValue.Four; case 5: return cardValue.Five; case 6: return cardValue.Six; case 7: return cardValue.Seven; case 8: return cardValue.Eight; case 9: return cardValue.Nine; case T: return cardValue.T; case J: return cardValue.J; case Q: return cardValue.Q; case K: return cardValue.K; case A: return cardValue.A; default: return cardValue.fail; }}public String getCard() { return card;}@Overridepublic String toString() { return this.card;}}Hand classimport java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.HashMap;import java.util.HashSet;import java.util.List;import java.util.Map;import java.util.Set;public class Hand {private List<cardValue> broadwayList = Arrays.asList(cardValue.A, cardValue.T, cardValue.J, cardValue.K, cardValue.Q);private List<cardValue> wheelList = Arrays.asList(cardValue.A, cardValue.Two, cardValue.Three, cardValue.Four, cardValue.Five);private ArrayList<Card> handList = new ArrayList<Card>();String hand;public ArrayList<Card> getHand() { return handList;}public Hand(String hand) { this.hand = hand; createHand(hand);}public void createHand(String cards) { handList.removeAll(handList); for (String part : cards.split(\\s+)) { Card currentCard = new Card(part); handList.add(currentCard); }}public int getHighestCardValue(ArrayList<Card> hand) { ArrayList<cardValue> cardValues = new ArrayList<cardValue>(); for (Card c : hand) { cardValues.add(c.getValue()); } cardValue maxCard = Collections.max(cardValues); return maxCard.value;}public cardValue getHigherSet(ArrayList<Card> hand) { Map<cardValue, Integer> freqMap = checkFrequency(hand); for (Map.Entry<cardValue, Integer> e : freqMap.entrySet()) { cardValue card = e.getKey(); int freq = e.getValue(); switch (freq) { case 2: return card; case 3: return card; case 4: return card; } } return cardValue.fail;}@Overridepublic String toString() { return this.hand.toString();}public Map<cardValue, Integer> checkFrequency(ArrayList<Card> hand) { Map<cardValue, Integer> freqMap = new HashMap<cardValue, Integer>(); for (Card c : hand) { if (freqMap.containsKey(c.getValue())) { freqMap.put(c.getValue(), freqMap.get(c.getValue()) + 1); } else { freqMap.put(c.getValue(), 1); } } return freqMap;}public boolean checkFlush(ArrayList<Card> hand) { String suit = hand.get(0).getSuit(); int suitCount = 0; HashMap<cardValue, String> tempMap = new HashMap<cardValue, String>(); for (Card c : hand) { tempMap.put(c.getValue(), c.getSuit()); } for (String s : tempMap.values()) { if (s.equals(suit)) { suitCount++; } } if (suitCount == 5) { return true; } return false;}public boolean checkPair(ArrayList<Card> hand) { Map<cardValue, Integer> freqMap = checkFrequency(hand); if (freqMap.containsValue(2)) { return true; } return false;}public boolean checkTwoPair(ArrayList<Card> hand) { Map<cardValue, Integer> freqMap = checkFrequency(hand); if (Collections.frequency(freqMap.values(), 2) == 2) { return true; } return false;}public boolean checkThreeOfAKind(ArrayList<Card> hand) { Map<cardValue, Integer> freqMap = checkFrequency(hand); if (freqMap.containsValue(3)) { return true; } return false;}public boolean checkFourOfAKind(ArrayList<Card> hand) { Map<cardValue, Integer> freqMap = checkFrequency(hand); if (freqMap.containsValue(4)) { return true; } else { return false; }}public boolean checkFullHouse(ArrayList<Card> hand) { Map<cardValue, Integer> freqMap = checkFrequency(hand); Set<Integer> fullHouseCheck = new HashSet<Integer>(freqMap.values()); System.out.println(freqMap.keySet()); if (fullHouseCheck.contains(2) && fullHouseCheck.contains(3)) { return true; } else { return false; }}public boolean checkStraight(ArrayList<Card> hand) { ArrayList<cardValue> straightList = new ArrayList<cardValue>(); int count = 0; int j = 0; for (Card c : hand) { straightList.add(c.getValue()); } Collections.sort(straightList); if (straightList.containsAll(wheelList)) { return true; } for (int i = 0; i < 4; i++) { if (straightList.get(j + 1).showValue() == straightList.get(i) .showValue() + 1) { count++; j++; } } if (count == 4) { return true; } return false;}public boolean checkStraightFlush(ArrayList<Card> hand) { if (checkFlush(hand) == true && checkStraight(hand) == true) { return true; } return false;}public boolean checkRoyalFlush(ArrayList<Card> hand) { ArrayList<cardValue> valueList = new ArrayList<cardValue>(); if (checkFlush(hand) == true) { for (Card c : hand) { valueList.add(c.getValue()); } if (valueList.containsAll(broadwayList)) { return true; } } return false;}public handRankings evaluateHand(ArrayList<Card> hand) { if (checkRoyalFlush(hand)) { return handRankings.royalFlush; } else if (checkStraightFlush(hand)) { return handRankings.straightFlush; } else if (checkFourOfAKind(hand)) { return handRankings.fourOfAKind; } else if (checkFullHouse(hand)) { return handRankings.fullHouse; } else if (checkFlush(hand)) { return handRankings.Flush; } else if (checkStraight(hand)) { return handRankings.Straight; } else if (checkThreeOfAKind(hand)) { return handRankings.threeOfAKind; } else if (checkTwoPair(hand)) { return handRankings.twoPairs; } else if (checkPair(hand)) { return handRankings.onePair; } else { return handRankings.highCard; }}}cardValue enumpublic enum cardValue{ Two(2), Three(3), Four(4), Five(5), Six(6), Seven(7), Eight(8), Nine(9), T(10), J(11), Q(12), K(13), A(14), fail(15); int value; cardValue(int v) { value = v; } int showValue(){ return value; }}handRankings enumpublic enum handRankings { highCard(1), // Highest value card. onePair(2), // Two cards of the same value. twoPairs(3), // Two different pairs. threeOfAKind(4), // Three cards of the same value. Straight(5), // All cards are consecutive values. Flush(6), // All cards of the same suit. fullHouse(7), // Three of a kind and a pair. fourOfAKind(8), // Four cards of the same value. straightFlush(9), // All cards are consecutive values of same suit. royalFlush(10); // Ten, Jack, Queen, King, Ace, in same suit. int value; handRankings(int v) { value = v; }}Main classpublic class Main {public static void main(String[] args) { Main m = new Main(); m.parseHands();}public void parseHands() { int p1wins = 0; int p2wins = 0; try { for (String line : Files.readAllLines(Paths.get(poker.txt))) { Hand hand1 = new Hand(line.substring(0, 14)); Hand hand2 = new Hand(line.substring(14, 29).trim()); handRankings result1 = hand1.evaluateHand(hand1.getHand()); handRankings result2 = hand2.evaluateHand(hand2.getHand()); // checking a pair or higher set hand int pairValue1 = hand1.getHigherSet(hand1.getHand()).value; int pairValue2 = hand2.getHigherSet(hand2.getHand()).value; // finding the highest value card in the hand int highCardValue1 = hand1.getHighestCardValue(hand1.getHand()); int highCardValue2 = hand2.getHighestCardValue(hand2.getHand()); if (result1 == result2) { if (result1 == handRankings.onePair || result1 == handRankings.twoPairs || result1 == handRankings.threeOfAKind || result1 == handRankings.fourOfAKind) { if (pairValue1 > pairValue2) { p1wins++; System.out.println(player 1 wins\n + hand1.toString() + + result1); } else { p2wins++; System.out.println(player 2 wins\n+ hand2.toString() + + result2); } } else { if (highCardValue1 > highCardValue2) { p1wins++; System.out.println(player 1 wins\n + hand1.toString() + + result1); } } } else { if (result1.value > result2.value) { p1wins++; System.out.println(player 1 wins\n + hand1.toString() + + result1); } else { p2wins++; System.out.println(player 2 wins\n + hand2.toString() + + result2); } } } System.out.println(\n + p1wins); System.out.println(\n + p2wins); } catch (Exception e) { System.out.println(e); }}} | Project Euler #54 in Java: Comparing poker hands of two players | java;programming challenge;playing cards | null |
_softwareengineering.325980 | I don't know much about how computers work internally, so I also don't know much about multithreading, and when it takes place. I know it is important in databases or web applications and such, where a lot of different machines try to access or modify the same resources, but what about classic code, like calculations?I thought about using LinkedList in my code but I read it is not thread-safe (C#). So the question is if I even have to care.The concrete problem is this: I have a class Interval that represents closed intervals, internally stored as two double values (lower and upper bound). I have a method that takes one interval I and a list L of disjoint intervals in ascending order. The method modifies L such that it is equivalent to joining the intervals of the list with I; the order is preserved.Example:L is: [-3, 0], [2, 4], [5, 18], [21, 22]I is: [3, 6]resulting modified L: [-3, 0], [2, 18], [21, 22]The algorithm finds certain border intervals (the leftmost and rightmost interval of L that intersect with I, and the intervals next to these two), Removes all intervals between them and Adds a new interval between them. So this is the place where I need to know if thread-safety is a thing here.So, how do I know? | How do I know if I have to care about thread safety? | multithreading | You need to care about thread safety if you have multiple threads accessing the same shared (mutable) data structure. If the algorithm you describe runs in a single thread, you dont have to worry. An ordinary C# program is single-threaded by default. You have to actively start new threads in order to get a multithreaded program. If you dont do that, you are safe. |
_webmaster.98774 | We created an almost identical copy of our web page which has been created in WordPress. Now, it runs on Django/Python so we have to change hosting to make it work. But there is an AdWords campaign running on our web. I'm curious, whether changing the backend and hosting could have any negative influence on AdWords? The domain remains the same. | Has switching hosting and backend any influence on Google Adwords? | google adwords | null |
_cstheory.1168 | This question is (inspired by)/(shamefully stolen from) a similar question at MathOverflow, but I expect the answers here will be quite different. We all have favorite papers in our own respective areas of theory. Every once in a while, one finds a paper so astounding (e.g., important, compelling, deceptively simple, etc.) that one wants to share it with everyone. So list these papers here! They don't have to be from theoretical computer science -- anything that you think might appeal to the community is a fine answer.You can give as many answers as you want; please put one paper per answer! Also, notice this is community wiki, so vote on everything you like!(Note there has been a previous question about papers in recursion-theoretic complexity but that is quite specialized.) | What papers should everyone read? | big list;soft question | null |
_softwareengineering.286091 | I've just wanted to get to know what these particular settings really do:Project Properties -> Libraries -> Java PlatformProject Properties -> Sources -> Source/Binary FormatAfter a little bit of googling I know, that: [1] By choosing a Java Platform I declare the minimum Java version which can run my jar file. I can't run my jar with Java 6 when I set the project's JDK to 7 or 8.[2] Second option ensures that I compile my sources with specified java version. Moreover, netbeans will check if I do not use any syntax unavailable in a specified java.If I set my project as compatible with min Java 7 (Java Platform and Source format set to 7) I will have problems while running my jar file using jre 6 (it will be impossible). Let me know if my thinking is now correct.However there is one thing I do not understand and it forces me to think, that I make somewhere a mistake... Namely, it is possible to set, for instance, Java 8 as a Java Platform (so my app is compatible with Java 8+) but in source/binary format I can choose Java 6 or even Java 5. Why such a configuration is possible? What are the advantages of writing a source code using syntax from Java 6 when I use a Java 8 as a project's Java Platform?? | Java platform vs Source/Binary format settings in Netbeans | java;compiler;netbeans;settings;jre | null |
_codereview.69554 | I am currently attempting to become proficient in C++ and started by implementing a basic binary search tree. Most of the programming I have done is in Ada, Python and C. I would like to be able to program efficiently in modern C++ and become familiar with current best practices. I do not have any major questions or concerns beyond the fact that I am not entirely comfortable with the usage of smart pointers. I was hoping some people would simply be willing to critique this code and explain any major problems they may see. I am considering adding an iterator interface but am unsure if I will move forward with that right now. The tree currently works properly for my test cases.Header File#ifndef BST_H#define BST_H#include <memory>template <class BST>class BinarySearchTree{private:/*----------------------------------------------------------------------// Type Declarations //*---------------------------------------------------------------------*/struct node_t;typedef std::unique_ptr<node_t> node_p;struct node_t//Represents one node of tree data{ BST data; node_p left; node_p right; //node_t constructor node_t(const BST &item):data(item), left(nullptr), right(nullptr){}};//Type representing connections of a node.enum limb_t {Right, Left};/*----------------------------------------------------------------------// Class Variables //*---------------------------------------------------------------------*/node_p root;int tree_size;/*----------------------------------------------------------------------// Private functions //*---------------------------------------------------------------------*/bool _search(const BST &item, node_t * &parent, node_t * ¤t) const;/*Function searches the tree for the value of item Sets the parent and current node to the the location of the item if found. Returns boolean value for the result of the search*/void remove_with_children(node_t * &node);/*Replaces the target node's data with the minimum data found in the right subtree Deletes the node with the minimum data is then deleted.*/node_t * find_min_r_sub(const node_t &node) const;/*Function locates the minumum data in the given nodes right subtree Returns a node pointer to the item containing the minimum data*/void remove_with_child(node_t * &parent, node_t * ¤t);/*Replaces the node to be deleted with the existing node on the parent nodes left or right limb Node is deleted after the the move is made*/void remove_leaf(node_t * &parent, node_t * ¤t);/*Function deletes the target node.*/bool has_child(const node_t &node, const limb_t limb) const;/*Reports True if child is found on given node on given limb. False if not*/bool is_empty(void) const;/*Checks if tree is empty Returns boolean value for if tree is empty or not*//*----------------------------------------------------------------------// Private Print Functions //*---------------------------------------------------------------------*/void _postorder(const node_p &node) const;/*Recursively prints the BST in postorder format.*/void _preorder(const node_p &node) const;/*Recursively prints the BST in preorder format.*/void _inorder(const node_p &node) const;/*Recursively prints the BST in inorder format.*/public:/*----------------------------------------------------------------------// Constructor and Destructor //*---------------------------------------------------------------------*/BinarySearchTree(void);/*Creates tree object, Sets root to a nullptr and tree_size to 0.*/~BinarySearchTree(void);/*Destroys the tree object Resets the root node and sets tree_size to 0.*//*----------------------------------------------------------------------// Public Functions //*---------------------------------------------------------------------*/bool insert(const BST &item);/*Inserts item into the tree. Returns true if insertions was successful. Does not allow duplicate items to be inserted.*/bool remove(const BST &item);/*Removes given item from the tree. Returns false if item not in the tree, true if removal was successful.*/bool search(const BST &item) const;/*Calls private serch function and searches for the given item Results are returned as a boolean falue.*//*----------------------------------------------------------------------// Public Print Functions //*---------------------------------------------------------------------*/void inorder(void) const;/*Public function for printing tree in inorder format.*/void preorder(void) const;/*Public function for printing tree in preorder format.*/void postorder(void) const;/*Public function for printing tree in postorder format.*/};#endifClass Body#include BinarySearchTree.h#include <iostream>template <class BST>BinarySearchTree<BST>::BinarySearchTree(void){ root = nullptr; tree_size = 0;}template <class BST>BinarySearchTree<BST>::~BinarySearchTree(void){ root.reset(); tree_size = 0;}template <class BST>bool BinarySearchTree<BST>::insert(const BST &item){ node_p new_leaf(new node_t(item)); if(is_empty()) { root = std::move(new_leaf); } else { node_t * current = root.get(); node_t * parent = nullptr; while(current) /*-Node searches for null position to insert new node if item is not in tree. -Each iteration traverses one node and sets next node.*/ { parent = current; if(current->data > item) { current = current->left.get(); } else if (current->data < item) { current = current->right.get(); } else { //The case that the item is found in the tree. return false; } } if(parent->data > item) //Insert item. { parent->left = std::move(new_leaf); } else { parent->right = std::move(new_leaf); } } //Increment tree size. tree_size++; return true;}template <class BST>bool BinarySearchTree<BST>::remove(const BST &item){ if(is_empty()) { return false; } node_t * parent; node_t * current; if(_search(item, parent, current)) { if(has_child(*current, Left) && has_child(*current, Right)) { //node has a left and right child. remove_with_children(current); } else if(has_child(*current, Left) != has_child(*current, Right)) { //node has a single child. remove_with_child(parent, current); } else { //node has no children. remove_leaf(parent, current); } //Decrement tree size. tree_size--; } else { //node was not found. return false; } return true;}template <class BST>bool BinarySearchTree<BST>::_search(const BST &item, node_t * &parent, node_t * ¤t) const{ parent = nullptr; current = root.get(); while(current) /*-Loop searches for item in the tree. -Each iteration traverses and checks one node.*/ { if(item == (current)->data) { return true; } else { parent = current; if(item > current->data) { current = current->right.get(); } else { current = current->left.get(); } } } return false;}template <class BST>void BinarySearchTree<BST>::remove_with_children(node_t * &node){ node_t * min_parent; min_parent = find_min_r_sub(*node); if(min_parent) { //Node is set with min value and the minimum node deleted node->data = min_parent->left->data; min_parent->left.reset(); } else { //min_parent is null, so the the min value is the nodes right child. node->data = node->right->data; node->right.reset(); }}template <class BST>typename BinarySearchTree<BST>::node_t * BinarySearchTree<BST>::find_min_r_sub(const node_t &node) const{ node_t * parent = nullptr; node_t * current = node.right.get(); while(current->left) /*- Loop traverses subtree as far left as possible. - Each iteration traverses one node.*/ { parent = current; current = current->left.get(); } return parent;}template <class BST>void BinarySearchTree<BST>::remove_with_child(node_t * &parent, node_t * ¤t){ if(!parent) { //node is root if(current->left) { root = std::move(current->left); } else { root = std::move(current->right); } } else if(current == parent->left.get()) { if(current->left) { parent->left = std::move(current->left); } else { parent->left = std::move(current->right); } } else { if (current->left) { parent->right = std::move(current->left); } else { parent->right = std::move(current->right); } }}template <class BST>void BinarySearchTree<BST>::remove_leaf(node_t * &parent, node_t * ¤t){ if(!parent) { //node is root root.reset(); } else if(current == parent->left.get()) { parent->left.reset(); } else { parent->right.reset(); }}template <class BST>bool BinarySearchTree<BST>::has_child(const node_t &node, const limb_t limb) const{ if(((node.left) && (limb == Left)) || ((node.right) && (limb == Right))) { return true; } return false;}template <class BST>bool BinarySearchTree<BST>::is_empty(void) const{ if(tree_size == 0) { return true; } return false;}template <class BST>bool BinarySearchTree<BST>::search(const BST &item) const{ node_t * current node_t * parent return (_search(item, parent, current));}template <class BST>void BinarySearchTree<BST>::inorder() const{ inorder(root);}template <class BST>void BinarySearchTree<BST>::_inorder(const node_p &node) const{ if(node) { if(node->left) { inorder(node->left); } std::cout<< <<node->data<< ; if(node->right) { inorder(node->right); } } else return;}template <class BST>void BinarySearchTree<BST>::preorder(void) const{ preorder(root);}template <class BST>void BinarySearchTree<BST>::_preorder(const node_p &node) const{ if(node) { std::cout<< <<node->data<< ; if(node->left) { preorder(node->left); } if(node->right) { preorder(node->right); } } else return;}template <class BST>void BinarySearchTree<BST>::postorder(void) const{ postorder(root);}template <class BST>void BinarySearchTree<BST>::_postorder(const node_p &node) const{ if(node) { if(node->left) { postorder(node->left); } if(node->right) { postorder(node->right); } std::cout<< <<node->data<< ; } else return;} | Binary search tree with templates | c++;c++11;tree;template;pointers | There's quite a bit of code here so I haven't gone over it in great detail but the basics seem sound. Here's a few comments on things that jumped out at me at a quick skim though, some are pretty minor but are just suggestions for more idiomatic C++:This is a fairly major issue: generally the definitions of all templates need to be in a header file and not in a .cpp file. With your code as written, you will get linker errors if you try and use your BinarySearchTree class from another translation unit (another .cpp file). You can use explicit template instantiation to work around this if you know in advance the full set of instantiations you need but for a generic container class like this that may be instantiated with arbitrary types all your implementation should be in a header (you can separate it into a detail header for code organization purposes). It's conventional in C++ to use T for template type parameters when the meaning of the parameter is obvious (such as the contained type in a container). Naming your contained type template parameter BST seemed a slightly odd choice to me.Smart pointers are designed to manage ownership automatically and unique_ptrs default constructor initializes it to nullptr. It looks a little redundant to me to explicitly initialize your left and right node_ps with nullptr in the node_t constructor and your root in the BinarySearchTree constructor. Related to the above, it's redundant to call root.reset() in your BinarySearchTree destructor. Members of an object are automatically destroyed in the correct order, you should generally leave resource management up to types like unique_ptr that just do the right thing for you and only explicitly define a destructor for classes that manage resources.It's also redundant to set tree_size to 0 in your destructor - the object is going away so you are clearing a value you will never be able to access. I'd just delete your entire BinarySearchTree destructor as the implicitly generated destructor will be correct for this class.It's not idiomatic C++ to put void in the parameter list for functions that take no arguments (although it's permitted for backwards compatibility with C). Your default constructor and destructor (if you needed one) should just have empty argument lists.It's considered best practice in C++ to prefer pre-increment unless you need post-increment semantics (e.g. ++tree_size rather than tree_size++). This is because pre-increment can be more efficient for user defined types.You may want to consider taking 'sink' arguments (like the item parameter of your node_t constructor and of your insert() function by value and then std::move() them into their destinations. Alternatively you can provide two overloads, one taking a const T& argument and one taking a T&& which can be slightly more efficient by avoiding an extra move. Your insert() function doesn't handle movable types correctly and will not compile for move only types since it takes it's argument by const T& but attempts to std::move() them. Another option is to ignore move semantics for now and just accept copying (move semantics are a somewhat advanced C++ feature if you are trying to implement template classes that use them rather than to simply use them as a consumer of libraries). A handy tip when implementing templated container classes is to create helper classes for unit testing that record the number of copies / moves etc. This makes it easier to catch mistakes like your faulty insert() implementation by verifying that you are getting the number of moves and copies you expect.When designing container classes like this, consider using the same names and idioms in the interface as similar standard library types. For example, your search() function is generally named find() in similar standard library classes like std::set when it returns an iterator or count() when it returns the number of matching elements and insert() generally returns a pair<iterator, bool> or just an iterator indicating if the element was inserted and where it was inserted. It would also be good here to provide an iterator interface similar to standard library types, although it would require a fair bit of code to implement. |
_unix.43969 | I've a directory on a NAS mount (from NetApp), that contains ~6300 image files, total size of this directory is ~ 300 MB. I get two different performances of time ls:First time (or after waiting 5-7 minutes): time lsreal 0m4.505suser 0m0.061ssys 0m0.258sSubsequent times: time lsreal 0m0.340suser 0m0.038ssys 0m0.075sI'm fairly new to storage and disks, but my questions are:what causes ls to be slow in some instances and 10+ times fast in others?how would I go about troubleshooting this issue?Update:Here is what I got back from the sysadmin on how NAS is mounted:nashost:/vol/cmsprd/files /app/files nfs noquota,proto=tcp 0 0and here is what I see running for nfs on the host:ps -ef | grep nfsroot 3234 2 0 Mar21 ? 00:00:02 [nfsiod]I'm still looking for the connection speed.Thanks! | What could cause a NAS mount to respond slowly? | performance;nfs;disk | null |
_codereview.111188 | I have written this snippet to find r-permutations of n, i.e. if I have an array of n=3 {0,1,2}, then r=2 permutations will be {{0, 1}, {0, 2}, {1, 0}, {1, 2}, {2, 0}, {2, 1}}.Can somebody review it and help me optimize / reduce its complexity (I don't want to use recursive function):_getAllPermutation: function(input, allPermutations, usedIndices, r) { var index = 0, usedIndex = null; for (; index < input.length; index++) { usedIndex = input.splice(index, 1)[0]; r--; usedIndices.push(usedIndex); if (input.length === 0 || r === 0) { allPermutations.push(usedIndices.slice()); } if (r > 0) { this._getAllPermutation(input, allPermutations, usedIndices, r); } input.splice(index, 0, usedIndex); r++; usedIndices.pop(); }} | `r` permutations of `n` | javascript;combinatorics | null |
_unix.360748 | I just installed Kubuntu 17.04. It broke my audio config. What is weird is that if I run from live-USB, the audio works perfectly.How can I dump the config from the live session and restore it in the installed version? | Copying audio config | audio | null |
_softwareengineering.298363 | When I want to create an object which aggregates other objects, I find myself wanting to give access to the internal objects instead of revealing the interface to the internal objects with passthrough functions.For example, say we have two objects:class Engine;using EnginePtr = unique_ptr<Engine>;class Engine{public: Engine( int size ) : mySize( 1 ) { setSize( size ); } int getSize() const { return mySize; } void setSize( const int size ) { mySize = size; } void doStuff() const { /* do stuff */ }private: int mySize;};class ModelName;using ModelNamePtr = unique_ptr<ModelName>;class ModelName{public: ModelName( const string& name ) : myName( name ) { setName( name ); } string getName() const { return myName; } void setName( const string& name ) { myName = name; } void doSomething() const { /* do something */ }private: string myName;};And lets say we want to have a Car object which is composed of both an Engine and a ModelName (this is contrived obviously). One possible way to do so would be to give access to each of these/* give access */class Car1{public: Car1() : myModelName{ new ModelName{ default } }, myEngine{ new Engine{ 2 } } {} const ModelNamePtr& getModelName() const { return myModelName; } const EnginePtr& getEngine() const { return myEngine; }private: ModelNamePtr myModelName; EnginePtr myEngine;};Using this object would look like this:Car1 car1;car1.getModelName()->setName( Accord );car1.getEngine()->setSize( 2 );car1.getEngine()->doStuff();Another possibility would be to create a public function on the Car object for each of the (desired) functions on the internal objects, like this:/* passthrough functions */class Car2{public: Car2() : myModelName{ new ModelName{ default } }, myEngine{ new Engine{ 2 } } {} string getModelName() const { return myModelName->getName(); } void setModelName( const string& name ) { myModelName->setName( name ); } void doModelnameSomething() const { myModelName->doSomething(); } int getEngineSize() const { return myEngine->getSize(); } void setEngineSize( const int size ) { myEngine->setSize( size ); } void doEngineStuff() const { myEngine->doStuff(); }private: ModelNamePtr myModelName; EnginePtr myEngine;};The second example would be used like this:Car2 car2;car2.setModelName( Accord );car2.setEngineSize( 2 );car2.doEngineStuff();My concern with the first example is that it violates OO encapsulation by giving direct access to the private members.My concern with the second example is that, as we get to higher levels in the class hierarchy, we could wind up with god-like classes that have very large public interfaces (violates the I in SOLID).Which of the two examples represents better OO design? Or do both examples demonstrate a lack of OO comprehension? | Does returning pointer to composed objects violate encapsulation | object oriented;c++;encapsulation | I find myself wanting to give access to the internal objects instead of revealing the interface to the internal objects with passthrough functions.So, why then is it internal?The objective is not to reveal the interface to the internal object but to create a coherent, consistent, expressive interface. If an internal object's functionality needs to be exposed and a simple pass-through will do, then pass-through. Good design is the goal, not avoid trivial coding.Giving access to an internal object means:The client has to know about those internals to use them.The above means desired abstraction is blown out of the water. You expose the internal object's other public methods and properties, allowing the client to manipulate your state in unintended ways.Significantly increased coupling. Now you are at risk of breaking client code should you modify the internal object, change it's method signature, or even replace the whole object (change the type).All of this is why we have the Law of Demeter. Demeter does not say well, if it's just passing through, then it's ok to ignore this principle. |
_reverseengineering.14701 | Novice Android security researcher here. Recently I was tasked with the task/challenge of exposing a certain app's hardcoded local keystore password.I've decompiled it with JEB2 and obviously within huge mess of code I can see various references to the cryptographic algorithms, hashing and encoding routines (OCRA1, HMAC, SHA1, AES, base64 etc.) utilized in the classes and methods of the prototypes, related calls etc.Now, from the experienced pentester's viewpoint would it be possible to reveal the hardcoded pass through app's heap dumps or maybe traffic interception with the BurpSuite's mitm attack via fake certificate between the client/server point? If so, how would I then discern it from the ocean of other strings?!If that's not possible what is the proper way to proceed from then on taking into account lack of experience in reading java or reverse engineering crypto stuff?Regards | Android App's hardcoded local keystore password r3versing | decompilation;android;obfuscation;encryption;decryption | First thing I'd try to search for uses of standard implementation of the key store, KeyStore class. This class is external for the application and should be referenced by name.If this key store uses standard API it probably uses the the KeyStore.load function which gets the desired password as a second parameter.final void load(InputStream stream, char[] password) : Loads this KeyStore from the given input stream.Good luck. |
_codereview.97034 | I wrote some code to translate numbers ( for now just positive, up to the 32bit limit ) into English words.Everything works and I'm happy. I searched through the site looking for a comparison code but I couldn't find a C++ version that goes above 999 to use as exampleI had a few assumptions:No need for and, just spaces ( Ex: two hundred three )I never wrote much code ( yes this is a big program for me ), so I have no idea how to manage it correctly, I think it's pretty much spaghetti-code at the moment, that's why I tried adding some documentation to clarify things.The algorithm I used feels like it's overcomplicated and more patched together than planned out.#include <iostream> // std::cout, std::cin, std::endl#include <vector> // std::vector#include <algorithm> // std::reverseconst std::vector<std::string> first_twenty_vocabular = { zero , one , two , three , four , five , six , seven , eight , nine , ten , eleven , twelve , thirteen , fourteen , fifteen , sixteen , seventeen , eighteen , nineteen };const std::vector<std::string> magnitude_vocabular = { hundred , thousand , million , billion };const std::vector<std::string> decine_vocabular = { twenty , thirty , fourty , fifty , sixty , seventy , eighty , ninety };// HERE THE MAGIC HAPPENS.std::string Stringer(std::vector<int> src); // Translate the number up to the hundreds, if the number is bigger it sends it to MagnitudeSplitte() for splitting it up.std::string MagnitudeSplitter(std::vector<int> src); // Splits a number too big for Stringer to handle into smaller chunks (using VectorSplitter()) of max 3 digits, translate them with Stringer() and appends the right magnitude.std::vector<int> VectorSplitter(std::vector<int> &V); // Splits the number by the hundreds. // Ex: 12004 is split into 12 and 004. // 1222333 is split into 1 and 222333. // 111222 is split into 111 and 222.// ######################################################// THESE FUNCTIONS ARE HELPER FUNCTIONS TO Stringer().std::string units(std::vector<int> src); // Translate the singe digits numbers.std::string decine(std::vector<int> src); // Transalte the double digits numbers. // ( Considered the structure of the vocabular vectors, i'm considering merging both units and decine into the same function.)std::string hundreds(std::vector<int> src); // Transalte the triple digits numbers.// #############################################################// TOOLS.void FlipVector(std::vector<int>& V) { std::reverse(V.begin(), V.end());}void PrintVector(std::vector<int> v) { int len = v.size(); for (int i = 0; i < len; ++i) { std::cout << v[i];} std::cout << std::endl;}std::vector<int> Splitter(int src_num) { // Convert the input number into a vector. std::vector<int> v_Digits; if (src_num == 0) { v_Digits.push_back(0); return v_Digits; } else { while(src_num >= 10) { v_Digits.push_back(src_num%10); src_num /= 10; } v_Digits.push_back(src_num); return v_Digits; }}// ###################################################std::string units(std::vector<int> src) { std::string uni_str = first_twenty_vocabular[src[0]]; return uni_str;}std::string decine(std::vector<int> src) { std::string dec_str = ; if (src[0] == 0) { if (src[1] == 0) { return dec_str; } else { dec_str.append(first_twenty_vocabular[src[1]]); return dec_str; } } else if (src[0] == 1) { dec_str.append(first_twenty_vocabular[10+src[1]]); return dec_str; } else { dec_str.append(decine_vocabular[src[0]-2]); if(src[1] == 0) { return dec_str; } else { dec_str.append(first_twenty_vocabular[src[1]]); return dec_str; } }}std::string hundreds(std::vector<int> src) { std::string hundred_string = ; if(src[0] == 0) { std::vector<int> dec_vec= {src[1],src[2]}; std::string dec_str = decine(dec_vec); hundred_string.append(dec_str); return hundred_string; } else { hundred_string.append(first_twenty_vocabular[src[0]]); hundred_string.append(hundred ); std::vector<int> dec_vec= {src[1],src[2]}; std::string dec_str = decine(dec_vec); hundred_string.append(dec_str); return hundred_string; }}std::string Stringer(std::vector<int> src) { std::string num_string = ; int len = src.size(); if( src[0] < 0 ) { num_string.append(minus ); for (int i = 0; i < len; ++i) { src[i] = -i; } } if (len == 1) { std::string add = units(src); num_string.append(add); } else if (len == 2) { std::string add = decine(src); num_string.append(add); } else if (len == 3) { std::string add = hundreds(src); num_string.append(add); } else { return MagnitudeSplitter(src); } return num_string;}std::vector<int> VectorSplitter(std::vector<int> &V){ std::vector<int> first_digits; int len = V.size(); if (len%3 == 0) { for(int i = 0; i < 3; ++i) { first_digits.push_back(V[0]); FlipVector(V); V.pop_back(); FlipVector(V); } } else { for( int i = 0; i < (len-(3*(len/3))); ++i) { first_digits.push_back(V[0]); FlipVector(V); V.pop_back(); FlipVector(V); } } return first_digits;}std::string MagnitudeSplitter(std::vector<int> src) { int len = src.size(); std::string tot_str = ; if (len == 3) { return Stringer(src); } else { std::vector<int> first_digits = VectorSplitter(src); int new_len = first_digits.size(); std::string add = Stringer(first_digits); int sum_values = 0; // To know if there are only zeroes. for ( int i = 0; i < new_len; ++i) { sum_values += first_digits[i]; } tot_str.append(add); if (sum_values) { // Appends the right magnitude only if the relative chunk is significative ( with something in it). tot_str.append(magnitude_vocabular[(len-1)/3]); } std::string return_str = Stringer(src); tot_str.append(return_str); } return tot_str;}int main() { std::cout << insert your number: ; int x; std::cin >> x; std::vector<int> v_result = Splitter(x); // Face down, ass up. FlipVector(v_result); // Face up, ass down (poor boy) PrintVector(v_result); std::cout << Stringer(v_result) << std::endl;} | Integer to English Conversion | c++;c++11;converting;numbers to words | From the top down, first, given what you want to do, your function had better look like this:std::string toEnglish(int x);Your Stringer() function sort of does this, but with a really weird name. In fact, all your functions have really weird names. Splitting into a vector of digits doesn't seem particularly useful to the problem at hand either. And your negative check is definitely wrong:for (int i = 0; i < len; ++i) { src[i] = -i; }That'll just overwrite your src with values that had nothing to do with it.The rest of Stringer()'s logic is really confusing as well. So we have:if (len == 1) { std::string add = units(src); num_string.append(add);} else if (len == 2) { std::string add = decine(src); num_string.append(add);} else if (len == 3) { std::string add = hundreds(src); num_string.append(add);} else { return MagnitudeSplitter(src);}return num_string;Which would be exactly equivalent to:switch (len) {case 1: return units(src);case 2: return decine(src);case 3: return hundreds(src);default: return MagnitudeSplitter(src);}MagnitudeSplitter then checks for the length being 3, which we know will never happen. But really, why are these different cases at all? On top of that, you're copying your objects at every point instead of taking by reference to const. I find it very hard to follow your decine and hunrdeds functions. I am not sure if they're correct. I think the best code review I could give you is...Let's start over. With English number words, the way to do it is to divide the number into blocks of 3 and do each one. So I would expect a helper function like;/* Given a number 1-999, convert it to English. Examples: 2 -> two 127 -> one hundred twenty seven */std::string blockToEnglish(int x);Which we could use like:std::string toEnglish(int x) { if (x == 0) return zero; std::vector<int> blocks; while (x > 0) { blocks.push_back(x % 1000); x /= 1000; } std::vector<std::string> block_words; for (size_t i = 0; i != blocks.end(); ++i) { if (blocks[i]) { block_words.append(blockToEnglish(blocks[i])); } } // TODO as exercise: combine block_words into one // string with the millions, etc separators // as well as handle negatives} |
_cs.12480 | What does $A^B$ mean where A and B are complexity classes?The Polynomial Hierarchy page says:$A^B$ is the set of decision problems solvable by a Turing machine in class A augmented by an oracle for some complete problem in class BIn that case what is a Turing machine in class A?(besides just a machine of some sort that can solve problems in A, because that doesn't give any insight as to what it means to augment such a machine with an oracle)The motivation for this question was: What is a Turing Machine in class coNP. | What does $A^B$ mean? | turing machines;complexity classes | null |
_unix.118093 | Being able to put a script in /etc/cron.daily is really nice because I can do it easily from a configuration management system or a package. However, my understanding is that all the entries in /etc/cron.daily will run sequentially. How can I make a script in /etc/cron.daily not hold up the other tasks? Would something like the following work?#!/bin/bash#do something long:nohup sleep 1000000000 &;#instead of sleep, this could point to another script that takes a while to execute | Running cron.daily in parallel | bash;cron | Yes, if you background the process in the script, the next one will be started. Scripts in /etc/cron.daily are run by run-parts (from man cron):Support for /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly and /etc/cron.monthly is provided in Debian through the default setting of the /etc/crontab file (see the system-wide example in crontab(5)). The default sytem-wide crontab contains four tasks: run every hour, every day, every week and every month. Each of these tasks will execute run-parts providing each one of the directories as an argument. These tasks are disabled if anacron is installed (except for the hourly task) to prevent conflicts between both daemons.So, you can simulate by running it manually. For example:$ ls /etc/cron.daily/test1 test2$ cat test1#!/bin/bashecho starting 1 >> /tmp/hahasleep 1000000000 & $ cat test2#!/bin/bashecho starting 2 >> /tmp/hahasleep 1000000000 &$ sudo run-parts /etc/cron.daily$ cat /tmp/hahastarting 1starting 2In the example above, I created two scripts that simply run sleep 1000000000 &. Because of the &, the process is sent to the background and run-parts moves on to the next script. So, nohup is not needed, all you need is the & at the end of the line that will take a while. |
_cs.74809 | The following quote is from the book The art of computer programming:(..) sentence would presumably be used only if either $j$ or $k$ (not both) has exterior significance.In most cases we will use notation (2) only when the sum is finite - that is, when only a finite number of values $j$ satisfy $R(j)$ and have $a_j \neq 0$. If an infinite sum is required, for example $$\sum_{j=1}^{\infty} = \sum_{j \geq 1}a_j = a_1 + a_2 + a_3+\cdots$$ with infinitely many nonzero terms, the techniques of calculus must be employed; the precise meaning of (2) is then $$\qquad\qquad \sum_{R(j)} a_j = \left(\lim_{n\rightarrow\infty} \sum_{R(j) \atop 0\leq j \leq n} a_j\right) + \left(\lim_{n\rightarrow\infty} \sum_{R(j) \atop 0\leq j \leq n} a_j\right),\qquad\qquad(3)$$(...)And why are they exactly the same? I showed a math professor and he thinks they're labelled wrong but couldn't figure it out. I don't even get why there are two. Sorry if the question isn't clear enough. I'm referring to the two infinite sums. As far as (2) is concerned he is only referring to what is on the left hand side of the equation with the two infinite sums. Its just a way of representing any possible series. So essentially my question is how does making any series go to infinity make two of them? Or am I misunderstanding?Also I tried to post this in math stack exchange and it wouldn't let me so I came here since its from the book, the art of computer programming. | Can someone explain why there are two summations here? | mathematical analysis | null |
_unix.144515 | Our Unix team often uses Samba to join machines to the domain. The command they have traditionally used is:net join ADS -w [domain name] -U [username]I am one of our AD admins and I am trying to find out how to get them to be able to join to a specific OU so we can have all of the Samba machines organized in AD. From all of my research, it seems that this should work:net join ads Servers/Samba -w [domain] -U [username] This still allows the machine to join to the domain without issue but it keeps ending up in the 'computers' container and we receive no errors. I have made sure on the AD side that the user they are using have join domain rights and create/delete computer objects on both the servers OU tree and the computers container. What am I missing? I can't find much documentation on the Samba net commands without having access to a unix box with it. Also, I noticed in most examples people always had 'net ads join...' rather than 'net join ads...' - our Unix admin got errors when trying to use net ads join. I do not know why our syntax seems different then most examples I found but I wanted to point it out.Here are some sites that support my research:https://www.samba.org/samba/docs/man/Samba-HOWTO-Collection/domain-member.htmlhttp://www.members.optushome.com.au/~wskwok/poptop_ads_howto_6a.htm | Samba 3.5.9 - join domain specific OU - net join ads | samba;active directory | null |
_webmaster.7130 | Nowadays often what was accomplished with an <img> tag is now done with something like a <div> with a CSS background image set using a CSS 'sprite' and an offset.I was wondering what kind of an effect his has on SEO, as effectively we lose the alt attribute (which is indexed by Google), and are stuck with the 'title' attribute (which as far as I understand is not indexed).Is this a significant disadvantage? | Are CSS sprites bad for SEO? | seo;css | CSS sprites should only be used for decorative elements for this reason - use <img> for elements which are specific to a page and use sprites for decorative elements which are not contextually relevant to the content presented.If you need a button image for your navigation items it makes much more sense to add that image as a background on the navigation link rather than markup like this:<a href=/> <img src=/images/home.gif title=Home alt=Home Button /> Home</a>(i.e. wherever the image's content is redundant to text content on the page or the image's content could best be described as decoration)As an added bonus of separating site template elements as sprites, you'll later be able to change the site's skin by changing the stylesheet instead of overwriting the old design image files or rewriting all your HTML markup. |
_cstheory.2215 | I'm new to the site. On mathoverflow this would be community wiki, but I don't see how to set that here. Not a research question, but hopefully of interest to professional theoretical computer scientists.I am a 2nd year grad student in theory, and I was wondering what advice the community had for what I should be doing now to aim for a career in academia. I know I should do great research -- yes, I try. :-) I am looking for less obvious advice. How important are social aspects? Going to conferences, knowing great people? Am I at a big disadvantage if my advisor/school are not famous? Does a blog help/hurt my chances?Thanks! | How to get a job | soft question;career;advice request | null |
_unix.107256 | Is there an application that works like TeamViewer but only works for SSH?I'm configuring a server, and want to place it anywhere but still be able to access ith with putty. Is there a service or application I can use to access it? Much a like TeamViewer, but I don't want the desktop, only SSH | Is there a way to use ssh remotely without configure the firewall? | ssh | null |
_unix.235615 | Looking at etc/group and etc/passwd files, I see accounts listed in various groups in the etc/group file that do not appear in the etc/passwd files. Can these accounts still log in to the AIX server? | Can an AIX user that appears in etc/group but not etc/passwd still log into a server? | aix;group;access control;passwd | null |
_unix.337104 | I have a Linux distro in my laptop, with 3.18.17, 32-bit Kernel.Running top has listed below output,I am aware a little about nice and renice of process in Linux. Looking into top, I understood there are 6 processes, which have nice value of -20. I am totally convinced why kworker, khelper and crypto have -20 nice value. Can anyone tell me what is kintegrityd and why it has -20 nice value? | What is kintegrityd and why it has -20 nice value? | top;nice | null |
_codereview.166363 | I read about this game and tried to make my own algorithm to solve this.I asked it on StackOverflow for the appropriate algorithm and logic to solve this problem.With the help of answers over there and my modifications I implemented it,I posted my code there also and through suggestions in comments I was suggested to ask it here.Constraints I made: An N X N matrix having one empty slot ,say 0, would be plotted having numbers 0 to n-1.Now we have to recreate this matrix and form the matrix having numbers in increasing order from left to right beginning from the top row and have the last element 0 i.e. (N X Nth)element.For example,Input :8 4 07 2 51 3 6Output:1 2 34 5 67 8 0Now the problem is how to do this in minimum number of steps possible. As in game(link provided) you can either move left, right, up or bottom and shift the 0(empty slot) to corresponding position to make the final matrix.The output to printed for this algorithm is number of steps say M and then Tile(number) moved in the direction say, 1 for swapping with upper adjacent element, 2 for lower adjacent element, 3 for left adjacent element and 4 for right adjacent element.N could be in range [200,500]Like, for2 <--- order of N X N matrix3 10 2Answer should be: 3 4 1 2 where 3 is M and 4 1 2 are steps to tile movement.So I have to minimise the complexity for this algorithm and want to find minimum number of moves. Please suggest me the most efficient approach to solve this algorithm.It's taking too much time and I want to reduce its time complexity further and make it more efficient. Any suggestions would be appreciable.My code: // Program to print minimum moves from root node to destination node// for N*N -1 puzzle algorithm.// The solution assumes that instance of puzzle is solvable#include <iostream>#include <stdio.h>#include <string.h>#include <queue>using namespace std;//Some Global Declrationsint inDex=0,shift[100000],N,initial[500][500],final[500][500];// state space tree nodesstruct Node{ // stores parent node of current node // helps in tracing path when answer is found Node* parent; // stores matrix int mat[500][500]; // stores blank tile cordinates int x, y; // stores the number of misplaced tiles int cost; // stores the number of moves so far int level;};// Function to allocate a new nodeNode* newNode(int mat[500][500], int x, int y, int newX, int newY, int level, Node* parent){ Node* node = new Node; // set pointer for path to root node->parent = parent; // copy data from parent node to current node memcpy(node->mat, mat, sizeof node->mat); // move tile by 1 postion swap(node->mat[x][y], node->mat[newX][newY]); // set number of misplaced tiles node->cost = INT_MAX; // set number of moves so far node->level = level; // update new blank tile cordinates node->x = newX; node->y = newY; return node;}// bottom, left, top, rightint row[] = { 1, 0, -1, 0 };int col[] = { 0, -1, 0, 1 };// Function to calculate the the number of misplaced tiles// ie. number of non-blank tiles not in their goal positionint calculateCost(int initial[500][500], int final[500][500]){ int count = 0; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (initial[i][j] && initial[i][j] != final[i][j]) count++; return count;}// Function to check if (x, y) is a valid matrix coordinateint isSafe(int x, int y){ return (x >= 0 && x < N && y >= 0 && y < N);}// Comparison object to be used to order the heapstruct comp{ bool operator()(const Node* lhs, const Node* rhs) const { return (lhs->cost + lhs->level) > (rhs->cost + rhs->level); }};// Function to solve N*N - 1 puzzle algorithm using// Branch and Bound. x and y are blank tile coordinates// in initial statevoid solve(int initial[500][500], int x, int y, int final[500][500]){ // Create a priority queue to store live nodes of // search tree; priority_queue<Node*, std::vector<Node*>, comp> pq; // create a root node and calculate its cost Node* root = newNode(initial, x, y, x, y, 0, NULL); root->cost = calculateCost(initial, final); // Storing the previous node Node* prev = newNode(initial,x,y,x,y,0,NULL); // Add root to list of live nodes pq.push(root); // Finds a live node with least cost, // add its children to list of live nodes and // finally deletes it from the list. while (!pq.empty()) { // Find a live node with least estimated cost Node* min = pq.top(); // Store the shifts 1,2,3,4 for top,bottom,left and right respectively. if(min->x > prev->x) { shift[inDex] = 4; inDex++; } else if(min->x < prev->x) { shift[inDex] = 3; inDex++; } else if(min->y > prev->y) { shift[inDex] = 2; inDex++; } else if(min->y < prev->y) { shift[inDex] = 1; inDex++; } prev = pq.top(); // The found node is deleted from the list of // live nodes pq.pop(); if (min->cost == 0) { // Print the number of moves cout << min->level << endl; return; } // do for each child of min // max 4 children for a node for (int i = 0; i < 4; i++) { if (isSafe(min->x + row[i], min->y + col[i])) { // create a child node and calculate // its cost Node* child = newNode(min->mat, min->x, min->y, min->x + row[i], min->y + col[i], min->level + 1, min); child->cost = calculateCost(child->mat, final); // Add child to list of live nodes pq.push(child); } } }}int main(void){ cin >> N; // Initial configuration int i,j,k=1; for(i=0;i<N;i++) { for(j=0;j<N;j++) { cin >> initial[j][i]; } } // Putting numbers from 1 in increasing order. for(i=0;i<N;i++) { for(j=0;j<N;j++) { final[j][i] = k; k++; } } // Value 0 is used for empty space final[N-1][N-1] = 0; int x = 0, y = 1,a[100][100]; solve(initial, x, y, final); // Printing the steps taken while moving tiles. for(i=0;i<inDex;i++) { cout << shift[i] << endl; } return 0;}Input:23 10 2Output:3142 | Minimum number of moves to solve game of fifteen | c++;algorithm;time limit exceeded;matrix;sliding tile puzzle | null |
_unix.120856 | I need to display the complete address with curl, when it find results with '301' status code.This is my variable.search=$(curl -s --head -w %{http_code} https://launchpad.net/~[a-z]/+archive/pipelight -o /dev/null | sed 's#404##g') echo $search301The above works, but only display if the site exists with '301' status code.I wantecho $searchhttps://launchpad.net/~mqchael/+archive/pipelightUPDATEThis is my new variable, maybe can explain what I need. This variable will help me to search and install a ppa in Ubuntu o similar.ppa=$(curl https://launchpad.net/ubuntu/+ppas?name_filter=$packagename | grep '<td><a href=/~' | grep >$packagename< )echo $ppaExample:ppa=$(curl https://launchpad.net/ubuntu/+ppas?name_filter=Pipelight | grep '<td><a href=/~' | grep >Pipelight< )echo $ppa <td><a href=/~mqchael/+archive/pipelight>Pipelight</a></td>The problem here is I can't extract mqchael (this name is variable), also pipelight is only a example. This is the format final when I will apply my variable.ppa:mqchael/pipelight | How to display the complete address with curl in searching? | curl | This should do what you want:curl https://launchpad.net/ubuntu/+ppas?name_filter=Pipelight | awk -F/ '/>Pipelight</{print $2}'Explanation:The -F/ sets the filed delimiter to /, and the />Pipelight</ means run the commands in the {} only on lines matching >Pipelight<. So, at least in the example you posted, the line with >Pipelight< is:<td><a href=/~mqchael/+archive/pipelight>Pipelight</a></td>So, since awk is splitting on /, the first field will be <td><a href= and the second will be ~mqchael. Which is why {print $2} will print ~mqchael. If you also want to get rid of the tilde (~), use this:curl https://launchpad.net/ubuntu/+ppas?name_filter=Pipelight | awk -F/ '/>Pipelight</{print $2}' | sed 's/~//' |
_unix.313093 | I use zsh's menu-based tab completion. I press Tab once, and a list of possible completions appears. If I press Tab again, I can navigate this list with the arrow keys. However, is it possible to navigate them with the vi-like H, J, K, L keys instead?I use emacs mode for command-line input, with bindkey -e in ~/.zshrc. I also use zim with zsh. If relevant, the commands that specify the tab-completion system are here. | Can I navigate zsh's tab-completion menu with vi-like hjkl keys? | zsh;autocomplete;line editor | Yes, you can by enabling menu select:zstyle ':completion:*' menu selectzmodload zsh/complist...# use the vi navigation keys in menu completionbindkey -M menuselect 'h' vi-backward-charbindkey -M menuselect 'k' vi-up-line-or-historybindkey -M menuselect 'l' vi-forward-charbindkey -M menuselect 'j' vi-down-line-or-history |
_softwareengineering.221338 | When we look at the the overlap between the Ruby Community - we see the following overlaps:Think Relevance (now Cognitect) has switched from Ruby to ClojureJay Fields has switched from Ruby to ClojureDavid Chelimsky - author of RSpec - has left the Ruby RSpec project to join CognitectIs there some linguistic similarity that has lead to this crossover? | Is there a reason for the crossover from the Ruby community to the Clojure Community? | ruby;clojure | In a way, Ruby is a stealth lisp. It allows (and encourages) more metaprogramming than most other languages of its class, even the directly comparable Python. I am thinking here of the famous post, Ruby is an Acceptable Lisp. There are limitations, however; functions are not really first-class objects (calling a lambda or a Proc is horrific, for example), you can't truly redefine the language as you can with macros, and so on.It makes sense that people who are attracted to Ruby, which has until this point been the most practical and popular language that encouraged a lot of metaprogramming, would be attracted to a language which has better libraries (via the JVM), runs faster than Ruby, is truly functional, is dynamically typed, and encourages metaprogramming to an even greater degree than Ruby. I would hypothesize that you'll also see a greater crossover from the Python and Haskell communities to Scala. |
_cs.74787 | I'm currently studying computer architectures module, and during the workshop I came a across a series of questions that I struggled to being to answer.The question goes;*You have an L1 data cache, L2 cache, and main memory. The hit rates and hit times foreach are:50% hit rate, 2 cycle hit time to L1.70% hit rate, 15 cycle hit time to L2.100% hit rate, 200 cycle hit time to main memory.What fraction of accesses are serviced from L2? From main memory?My answer: (200*0.7)/15 = 9.3To be completely honest, I don't know how to approach these type's of questions, I'd be grateful if someone could point me to resources. | Calculating fractions of accesses from various levels of memory? (L2 - Main) | cpu cache;memory access | The order of accesses is L1 → L2 (→ L3) → main memory. The chance of missing is $1 - p$ where $p$ is the hit chance.In order for an access to hit L2 cache, it must have missed the L1 cache, and hit the L2 cache. So the chance is $(1 - 0.5) \cdot 0.7 = 0.35$.In order for an access to hit main memory, it must have missed the L1 cache, missed L2 cache and hit main memory. So the chance is $(1 - 0.5)\cdot (1 - 0.7) \cdot 1 = 0.15$. |
_webmaster.58095 | I have a robots.txt with the following in it: User-agent: *Disallow: http://tests.compkerworld.com/report_question_error.php?question_id=*&url=*Sitemap: http://tests.compkerworld.com/sitemap.xmlMy sitemap.xml, which is auto-generated, has all the URLs even those disallowed using robots.txt. I have no problem if the search engines crawl all the pages, but I want to know if such an entry will create any kind of conflict for crawlers.One more question: is the above syntax for disallowing correct? | Will there be a conflict between my Sitemap.xml and robots.txt? | sitemap;web crawlers;robots.txt;xml sitemap | null |
_softwareengineering.91984 | If I was interested in interview questions like Describe how you explained a difficult technical issue to a non-technical person I would use the Googles to search on communication skill interview questions.. But, what I really would like is to have someone actually explain to me some sort of relatively difficult technical issue. So I'm interested in are answers that identify a useful topic for this purpose or examples of what others have do to create scenarios for the purpose of evaluating a candidate's communications. In other words some exercise that actually forces the candidate to communicate something challenging rather than describe some time in their past when they were required to do so. | How to Evaluate a Programmer's Communication Skills | interview;communication | Agree with many of the comments, that this seems overly contrived/complicated but...It seems you have a few choicesAsk a question from a domain outside of the field of expertise - Explain how a transmission works Which helps you see how they communicate their understanding of black box systems.Ask a question from inside the programming domain - Explain how distributed version control works Which helps you understand how they understand something you both know and have experience in.Ask a question that targets their understanding but not yours - Explain to me the X algorithm/system/interaction you worked on for those five years from 2003-2008 Which helps you understand how they communicate their (deep) understanding to a novice. (note - you can also separately test for correctness of their understanding in another part of the interview, you don't need to test for communication and correctness together)I'm probably missing one or two :-) |
_codereview.173434 | I am trying to send a message consisting of a few byte using visual studios c++. The device requires serial communication and I am using array Byte^.The message to be send should start with 02 ASCII(h) i.e. STX. This is followed by 'A1C0' which when send using array would correspond to 0x41, 0x31, 0x43, 0x30 in ASCII(h). The other user input value is for a variable kV which is converted into hex after user provide it; e.g. if a user enter 7700, my code is supposed to convert it to a string of hex i.e. '1E14' which when sent using array should correspond to 0x31, 0x45, 0x31, 0x34.The issue I am faced with is that to calculate the checksum, I am required to add all the ASCII(h) which my array consist of and then take the totals one complement. I am struggling to add all these ASCII(h) primarily because I am sending A1C0 and 1E14 as hex and depends on computer to interpret them in ASCII(h). In this situation I am struggling, with how to add all these ASCII(h) which in described case would require me to add ASCII(h): 2+41+31+43+30+31+45+31+34 = 1C2 and then take the totals ones complement i.e 3D which in ASCII(h) is represented 0x33, 0x44. Following the checksum, I am required to send 03, i.e. ETX to tell the device that the message has ended. So the complete message to be send will contain STX, A1C0, kV, checksum and ETX which from my given explanation in this example will look like: 0x02, 0x41, 0x31, 0x43, 0x30, 0x31, 0x45, 0x31, 0x34, 0x33, 0x44, 0x03. I know to add elements in an array, but that is not simply what I want here. Before reaching out here: I tried to also look online, but was not able to accomplish correctly what I wanted from these links:https://social.msdn.microsoft.com/Forums/vstudio/en-US/6b85f124-d9de-46d5-a569-aecf08146f3a/sum-of-char-array-as-bytes?forum=vcgeneral http://forums.codeguru.com/showthread.php?383059-Perform-hex-addition-in-C-C I will really appreciate some help here! My current code is below:static void message(SerialPort^ port){array<Byte>^ message = gcnew array<Byte>message[0] = 0x02; // STXmessage[1] = 'A1C0'; // A1C0 in ASCII(h) represents 0X41, 0x31, 0x43, 0x30kV<< std::hex << decimal_value; // user entered int decimal_value for kV using Cin - for example user entered 7700, converted to hex --- hex value of 7700 is 1E14std::string power ( kV.str() );message[2] = power; // ASCII(h) of power (which is hex 1E14) represents 0x31, 0x45, 0x31, 0x34unsigned short CHKSUM = ???; // PROBLEM: Calculating total --- adding all the Ascii(h) bytes in the array togethercout << hex << CHKSUM << endl; CHKSUM = ~CHKSUM; // Take one's complement cout << hex << CHKSUM << endl;std::stringstream CHKSUM;message[3] = CHKSUM;message[4] = 0x03; // ETXport->Write(message, 0, message->Length);} | Visual C++: Adding together ASCII(h) representation of bytes in a array | beginner;array;serial port;c++ cli | null |
_unix.20825 | I'm a long term Ubuntu user who is considering migrating from Ubuntu to Debian (mainly because of Unity and the fact that my school has a Debian mirror). I haven't installed Debian on a system before. But again, I am fairly comfortable with reading manuals and working with the command line. Here is my installation plan (after spending some time reading the Debian wiki):Download the Live CD image and use dd to make a Live USB (I think this is the easiest way?)Install DebianConfigure repos using debgenPost-installIt is the post install part I am most confused about. I'd like to know some specific things:Is there an alternative package to ubuntu-restricted-extras on Debian?What the best way to get around with the font smoothing problem in Debian?How much functionality can I expect from Ubuntu Tweak on Debian?Any other tips are also welcome. I found a solution to the font rendering problem here | Migrating from Ubuntu to Debian | ubuntu;debian;system installation | Speaking as a long time Debian user I say take the plunge. You're familiar with Ubuntu, so there will be a lot you're already comfortable with. Don't expect to get 100% feature parity on day one though.Some specific answers:ubuntu-restricted-extras looks like it's basically Flash and gstreamer plugins. For flash, just install flashplugin-nonfree or get it right from Adobe and plop it into Firefox. For the gstreamer plugins there are unofficial sources available (although I don't know exactly where) for multimedia packages.There's a post here about font smoothing on Debian. I've never tried it, but the author claims it works well.Ubuntu Tweak is all stuff that Debian folks generally prefer to do manually. You'll learn a lot, and have fun doing it.And a final note, don't bother using debgen. Just use the Debian mirror for the country you're in (e.g., the U.S. is ftp.us.debian.org). After install your school's mirror to /etc/apt/sources.list. |
_unix.205128 | I'm learning Linux, and I'm a little confused right now. In the below screenshot, I was not able to understand the third shortcut of Table 2-1.It says that cd ~user_name will change the working directory to the home directory of the user_name. But, when I entered this command, I was in the same directory i.e, ~$ and not in /home$. Why?Are they both same ?I think the formal one is the user directory and the later one is the home directory.Sorry if I asked something foolish, and thank you in advance! | What is the difference between home$ and ~$? | linux;ubuntu;command line;directory;directory structure | null |
_softwareengineering.325844 | I have a question about what the best design pattern to use would be. I have 2 specific scenarios, the first one fits neatly into a Unit of Work(UoW) pattern. The second is a little bit more fiddly. Basically, in certain business scenarios, I have a need to save some data even if all others information fails to save due (reasons not including database server going down). For example, we get information about people having paid balances on their account. So the first table we save information to is the Payments table, before moving on to saving other entities including audit rows. However, we consider the audit rows to be less important than having a record inserted about the payment having been made. Using the traditional UOW pattern, the rollback would not allow us to commit the Payment record either.So I'm a little bit stuck as to how I would implement such a mechanism without having multiple patterns in our domain layer.I have also considered having the important records be their own UoW and then the audit records as a separate UoW. What would be considered the better way forward? Our basic stack is C#, MVC, Entity Framework and AutofacAny guidance would definitely be appreciated. | Best design pattern for two specific scenarios, the first one fits neatly into a Unit of Work(UoW) pattern | c#;design;design patterns;unit of work | null |
_unix.158501 | I have extracted a large (3.9GB) tar.bz2 file using the following command:tar -xjvf archive.tar.bz2The extract proceeds fines but exits printing:bzip2: (stdin): trailing garbage after EOF ignoredIs there a problem with the archive/extract? Has the integrity of my data been compromised? | tar exits with bzip2: (stdin): trailing garbage after EOF ignored after extract | tar;bzip2 | trailing garbage means there is extraneous data at the end of the file that is not part of the bz2 format; so bz2 can't make any sense of the additional data (hence garbage).If you want to provoke the error:$ echo Hello World | bzip2 > helloworld.bz2$ echo Something not bzip2... >> helloworld.bz2$ bunzip2 < helloworld.bz2Hello Worldbunzip2: (stdin): trailing garbage after EOF ignoredThe first command creates a valid bzip2 file that contains the message Hello World.The second command appends Something not bzip2... to the bzip2 file. This is trailing garbage because it's not bzip2 compressed.Running that through bunzip2 produces the valid data, but prints a warning about the extraneous, ignored data.In the end, the data that was originally compressed is still intact, but something odd happened at the end of the file. It may be worth looking at it in a hex editor; sometimes you can tell what happened, sometimes you can't.$ hexdump -C helloworld.bz2 00000000 42 5a 68 39 31 41 59 26 53 59 d8 72 01 2f 00 00 |BZh91AY&SY.r./..|00000010 01 57 80 00 10 40 00 00 40 00 80 06 04 90 00 20 |.W...@..@...... |00000020 00 22 06 86 d4 20 c9 88 c7 69 e8 28 1f 8b b9 22 |.... ...i.(...|00000030 9c 28 48 6c 39 00 97 80 53 6f 6d 65 74 68 69 6e |.(Hl9...Somethin|00000040 67 20 6e 6f 74 20 62 7a 69 70 32 2e 2e 2e 0a |g not bzip2....|This example is obvious, since you usually do not see plain text like this in bzip2 compressed data.The big question is whether the garbage was appended (like in the example above, leaving the original data intact), or if some kind of corruption happened. It's impossible to tell from the error message (bzip2 itself does not really know); however if it was a random corruption, you'd usually see some tar error messages too. |
_unix.234819 | I've got a directory, containing lots of weekly generated files with names like db_20130101_foo.tgz db_20130108_foo.tgz db_20130115_foo.tgz ...and so on. Over the years, the disks will get pretty full. As the files contain data for several weeks, we can remove older files. I want to remove every file, but always keep the last file of each month. How will i be able to accomplish this, without having to copy & paste filenames manually to rm, which is a lot of work and pretty error-prone? | Remove all but the latest backup file monthwise | shell;scripting;regular expression;backup | This oneliner will give you the files you want to delete:(ls -1 db_*_foo.tgz; echo) | awk '{prevym=ym; prevfile=file; ym=substr($0,4,6); file=$0; if (ym==prevym)print prevfile}'The first part just lists ALL the files (and adds an extra line to the end of the list, to simplify the later awk command). The awk part just checks each line to see if the ym (yearmonth) changed from one line to the next.Test and make sure that the above lists the files you DO want to delete. Then, to delete all of the files, simply pipe the command into:...ABOVE_COMMAND... | xargs rm |
_unix.117751 | When I type command groups ubuntu, the output would we like,ubuntu : ubuntu adm dialout cdrom floppy audio dip video plugdev netdev adminI am interested in the cdrom group. What does the group cdrom mean? It means user ubuntu can use cdrom device in the OS? If a user who is not in the group cdrom, can he/she use cdrom device in the OS? | Confusion about group `cdrom` in linux system | devices;group;data cd | null |
_webmaster.103156 | is there any way to see the data sent by the browser without firebug? Some other tool? I need to see which data is sent by the browser in some websites and the firebug console sometimes is blank. I've read somewhere that if the script writes to the console variable , the console wont show anything. | Seeing data sent by the browser without firebug | browsers;post | null |
_unix.280099 | HTTP stream from my MPD lags, i.e. audio from Pulse and HTTP output are not in sync, with HTTP output lagging Pulse. This also means that starting/pausing/stopping music from MPD is not reflected immediately on the HTTP stream. Also, the perceived lag on HTTP stream keeps increasing with time. When I first start MPD, the lag is ~2sec, but this balloons to almost half a minute after playing continuously for an hour or so.Following is the setup from my ~/.mpdconfaudio_output { type pulse name My Pulse Output}audio_output { type httpd name My HTTP Stream encoder vorbis # optional, vorbis or lame port 6601 bind_to_address any # optional, IPv4 or IPv6# quality 5.0 # do not define if bitrate is defined bitrate 128 # do not define if quality is defined format 44100:16:1# max_clients 0 # optional 0=no limit always_on yes} | Music Player Daemon MPD - Lagging HTTP stream | ubuntu;audio;mpd | null |
_unix.234151 | I'm running sudo-1.8.6 on CentOS 6.5. My question is very simple: How do I prevent SHELL from propagating from a user's environment to a sudo environment?Usually people are going the other way- they want to preserve an environment variable. However, I am having an issue where my user zabbix whose shell is /sbin/nologin tries to run a command via sudo. Sudo is preserving the /sbin/nologin so that root cannot run subshells. (Update: This part is true, but it is not the SHELL environment variable. It is the shell value that is being pulled from /etc/passwd that is the problem.)I include a test that illustrates the problem; this is not my real-world use case but it simply illustrates that the calling user's SHELL is preserved. I have a program that runs as user zabbix. It calls /usr/bin/sudo -u root /tmp/doit (the programming running as zabbix is a daemon, so the /sbin/nologin shell in the password file does not prevent it). /tmp/doit is a shell script that simply has:#!/bin/shenv > /tmp/outfile(its mode is 755, obviously). In outfile I can see that SHELL is /sbin/nologin. However, at this point the script is running as root, via sudo, so it should not have the previous user's environment variables, right?Here is my /etc/sudoers:Defaults requirettyDefaults !visiblepwDefaults always_set_homeDefaults env_resetDefaults env_keep = COLORS DISPLAY HOSTNAME HISTSIZE INPUTRC KDEDIR LS_COLORSDefaults env_keep += MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPEDefaults env_keep += LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGESDefaults env_keep += LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONEDefaults env_keep += LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITYDefaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin:/usr/local/sbin## Allow root to run any commands anywhere root ALL=(ALL) ALL#includedir /etc/sudoers.dAnd here is my /etc/sudoers.d/zabbix:Defaults:zabbix !requirettyzabbix ALL=(root) NOPASSWD: /tmp/doitEdit: A little more information:The process running the sudo is zabbix_agentd, from the Zabbix monitoring software. There is an entry in the /etc/zabbix/zabbix_agentd.d/userparameter_disk.conf file which looks like:UserParameter=example.disk.discovery,/usr/local/bin/zabbix_raid_discovery/usr/local/bin/zabbix_raid_discovery is a Python script. I have modified it to simply do this:print subprocess.check_output(['/usr/bin/sudo', '-u', 'root', '/tmp/doit'])/tmp/doit simply does this:#!/bin/shenv >> /tmp/outfileI run the following on my Zabbix server to run the /usr/local/bin/zabbix_raid_discovery script:zabbix_get -s client_hostname -k 'example.disk.discovery'Then I check the /tmp/outfile, and I see:SHELL=/sbin/nologinTERM=linuxUSER=rootSUDO_USER=zabbixSUDO_UID=497USERNAME=rootPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin:/usr/local/sbinMAIL=/var/mail/rootPWD=/LANG=en_US.UTF-8SHLVL=1SUDO_COMMAND=/tmp/doitHOME=/rootLOGNAME=rootSUDO_GID=497_=/bin/envThat SHELL line really bugs me. The file is owned by root, so I know it's being created by the root user, but the shell is from the calling user (zabbix). | How to prevent the caller's shell from being used in sudo | bash;sudo;environment variables | Then answer is that sudo has a bug. First, the workaround: I put this in my /etc/sudoers.d/zabbix file:zabbix ALL=(root) NOPASSWD: /bin/env SHELL=/bin/sh /usr/local/bin/zabbix_raid_discoveryand now subcommands called from zabbix_raid_discovery work.A patch to fix this will be in sudo 1.8.15. From the maintainer, Todd Miller:This is just a case of it's always been like that. There's notreally a good reason for it. The diff below should make the behaviormatch the documentation. - todddiff -r adb927ad5e86 plugins/sudoers/env.c--- a/plugins/sudoers/env.c Tue Oct 06 09:33:27 2015 -0600+++ b/plugins/sudoers/env.c Tue Oct 06 10:04:03 2015 -0600@@ -939,8 +939,6 @@ CHECK_SETENV2(USERNAME, runas_pw->pw_name, ISSET(didvar, DID_USERNAME), true); } else {- if (!ISSET(didvar, DID_SHELL))- CHECK_SETENV2(SHELL, sudo_user.pw->pw_shell, false, true); /* We will set LOGNAME later in the def_set_logname case. */ if (!def_set_logname) { if (!ISSET(didvar, DID_LOGNAME))@@ -984,6 +982,8 @@ if (!env_should_delete(*ep)) { if (strncmp(*ep, SUDO_PS1=, 9) == 0) ps1 = *ep + 5;+ else if (strncmp(*ep, SHELL=, 6) == 0)+ SET(didvar, DID_SHELL); else if (strncmp(*ep, PATH=, 5) == 0) SET(didvar, DID_PATH); else if (strncmp(*ep, TERM=, 5) == 0)@@ -1039,7 +1039,9 @@ if (reset_home) CHECK_SETENV2(HOME, runas_pw->pw_dir, true, true);- /* Provide default values for $TERM and $PATH if they are not set. */+ /* Provide default values for $SHELL, $TERM and $PATH if not set. */+ if (!ISSET(didvar, DID_SHELL))+ CHECK_SETENV2(SHELL, runas_pw->pw_shell, false, false); if (!ISSET(didvar, DID_TERM)) CHECK_PUTENV(TERM=unknown, false, false); if (!ISSET(didvar, DID_PATH)) |
_codereview.69847 | I have a table in my database with 35000 unique URLs. I use them to create my XML sitemaps for the site. I have setup crontab jobs to create automatically new URLs, delete non existing URLs and determine if a URL is valid.For the last part I use the following function:function get_url_status($url){ $httpCode = 0; $headers = get_headers($url); $http_header_info = $headers[0]; $httpCode = substr($http_header_info, 9, 3); if ($httpCode=='200') { // check in page for noindex and dissable that url $metas = get_meta_tags($url); if ( isset($metas['robots']) && strpos( strtolower($metas['robots']), 'noindex')!==false ) { $httpCode = 410; } }return $httpCode;}This will return to me the HTTP status code - 200 for legal URLs that will be included in sitemap, 400 for not found, 410 for URLs with noindex in them, 301 for redirections, etc.In my XML sitemaps I include only URLs with status code 200.My problem is that this function takes around 40 minutes to check the URLs in database. Is there a way to speed things up? | Detecting headers status takes too long | php;performance;http | null |
_unix.226843 | At first, there is no key mapping. The Caps Lock key on my keyboard behaves as Caps Lock.lone@debian:~$ xmodmap -pke | grep Caps_Lockkeycode 66 = Caps_Lock NoSymbol Caps_Locklone@debian:~$ xmodmap -pm | grep locklock Caps_Lock (0x42)Then I remap my Caps Lock key to function as Escape key.lone@debian:~$ xmodmap -e remove Lock = Caps_Lock -e keycode 66 = Escapelone@debian:~$ xmodmap -pke | grep Caps_Locklone@debian:~$ xmodmap -pm | grep locklockNow when I press the Caps Lock key, I see it behaving like Escape key. I tested this in vi editor.Now I map the Caps Lock key to behave again as Caps Lock key.lone@debian:~$ xmodmap -e keycode 66 = Caps_Locklone@debian:~$ xmodmap -pke | grep Caps_Lockkeycode 66 = Caps_Lock NoSymbol Caps_Locklone@debian:~$ xmodmap -pm | grep locklockNow when I press the Caps Lock key, it indeed behaves as Caps Lock. My question is: Why wasn't it necessary to perform add Lock = Caps_Lock again to make the Caps Lock key behave as Caps Lock.The above output shows that there is no key set to 'lock' modifier. How is it that the Caps Lock key behaves like Caps Lock key then? | Why does Caps Lock key behave as Caps Lock key without the Lock modifier? | x11;xmodmap | null |
_webmaster.76399 | I have noticed that Groupon.com or Zillow.com knows what city I am located in quite reliably and without asking permission.Does anyone know what they or similar big players do to get your location? Are they using private ip-based databases or something else? I need to know what city a user is in, are there any online services that I can use to get a user's location for free? | How do websites such as Groupon or Zillow detect user location? | geolocation | They are most likely using geolocation by IP address or hostname. There are many services that provide data for this. One that I know of that's easy to use is http://freegeoip.net. They have an API that you can call 10,000 times per hour to get geolocation data.For example, if you make an HTTP GET request to http://freegeoip.net/json/stackoverlow.com, you can get data back in multiple formats. This example returns JSON:{ ip: 69.172.201.208, country_code: US, country_name: United States, region_code: NY, region_name: New York, city: New York, zip_code: 10004, time_zone: America/New_York, latitude: 40.689, longitude: -74.021, metro_code: 501} |
_webmaster.29259 | The target is to provide the proper semantic for a page that briefly lists existent articles.At the moment my idea is the following:<body> <article> <header> <h1>Latest Articles</h1> </header> <article> <header> <h1><a href=/article-1>First Article's Heading</a></h1> <p>First article's brief description.</p> </header> </article> <article> <header> <h1><a href=/article-2>Second Article's Heading</a></h1> <p>Second article's brief description.</p> </header> </article> <article> <header> <h1><a href=/article-3>Third Article's Heading</a></h1> <p>Third article's brief description.</p> </header> </article> </article></body>The page (let's call it an archive page) has the main article element containing children articles.Each child has only header because the article does not represent the full version but just a brief.Please, tell me if my version is semantically right (and why it is). Otherwise, propose your version.UPDATED (AFTER THE ANSWER WAS ACCEPTED)Example above is not full what may confuse and cause misunderstanding.I'll try to clear this providing a fuller example with comments.<body> <!-- Header is the same for all pages. --> <header> <h1>Website Title</h1> <p>Website description.</p> </header> <!-- Article presents the main content of specific page. --> <article> <header> <h1>Latest Articles</h1> <p>Last three articles in chronological order.</p> </header> <!-- This page lists existent articles. --> <!-- They are not inside a section element because it isn't a section of something larger but independent articles. --> <article> <header> <h1>First Article's Heading</h1> <p>Supplement to the first article's heading.</p> <p><a href=/article-1 rel=bookmark>Read more</a></p> </header> </article> <article> <header> <h1>Second Article's Heading</h1> <p>Supplement to the second article's heading.</p> <p><a href=/article-2 rel=bookmark>Read more</a></p> </header> </article> <article> <header> <h1>Third Article's Heading</h1> <p>Supplement to the third article's heading.</p> <p><a href=/article-3 rel=bookmark>Read more</a></p> </header> </article> <footer> <nav> <h1>Navigate Through Pages</h1> <p><a href=/page/1 rel=next>Newer</a></p> <p><a href=/page/3 rel=prev>Older</a></p> </nav> </footer> </article> <!-- Footer is the same for all pages. --> <footer> <p><small>Copyright (c) ...</small></p> </footer></body>I just wanted to ensure if the semantic is corrent. It is. The question is clear. | What's the proper structure of an HTML5 page that briefly lists other articles? | html5 | Frankly, I'd do it exactly the same as I would in HTML4.<body> <h1>Latest Articles</h1> <h2><a href=/article-1>First Article's Heading</a></h2> <p>First article's brief description.</p> <h2><a href=/article-2>Second Article's Heading</a></h2> <p>Second article's brief description.</p> <h2><a href=/article-3>Third Article's Heading</a></h2> <p>Third article's brief description.</p></body>That's all you need. All your extra markup is providing no new information. This contains the same semantic information and the document outline is identical. If you need wrappers for styling, add <div>s as necessary. |
_unix.284828 | I'm using Debian unstable and I have a graphical problem after my computer suspend. My Xfce desktop is not correctly rendered on the wakeup, I can see my background through the panel (see screenshot) dmesg log shows an error i915 [...] has bogus alignment. Here is dmesg during the suspend action:[44434.416880] wlp2s0: deauthenticating from 14:0c:76:6f:f2:61 by local choice (Reason: 3=DEAUTH_LEAVING)[44434.437532] cfg80211: World regulatory domain updated:[44434.437538] cfg80211: DFS Master region: unset[44434.437541] cfg80211: (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp), (dfs_cac_time)[44434.437545] cfg80211: (2402000 KHz - 2472000 KHz @ 40000 KHz), (N/A, 2000 mBm), (N/A)[44434.437549] cfg80211: (2457000 KHz - 2482000 KHz @ 40000 KHz), (N/A, 2000 mBm), (N/A)[44434.437552] cfg80211: (2474000 KHz - 2494000 KHz @ 20000 KHz), (N/A, 2000 mBm), (N/A)[44434.437555] cfg80211: (5170000 KHz - 5250000 KHz @ 80000 KHz, 160000 KHz AUTO), (N/A, 2000 mBm), (N/A)[44434.437559] cfg80211: (5250000 KHz - 5330000 KHz @ 80000 KHz, 160000 KHz AUTO), (N/A, 2000 mBm), (0 s)[44434.437562] cfg80211: (5490000 KHz - 5730000 KHz @ 160000 KHz), (N/A, 2000 mBm), (0 s)[44434.437564] cfg80211: (5735000 KHz - 5835000 KHz @ 80000 KHz), (N/A, 2000 mBm), (N/A)[44434.437568] cfg80211: (57240000 KHz - 63720000 KHz @ 2160000 KHz), (N/A, 0 mBm), (N/A)[44434.531857] PM: Syncing filesystems ... done.[44434.540113] PM: Preparing system for sleep (mem)[44434.540324] (NULL device *): firmware: direct-loading firmware iwlwifi-6000-4.ucode[44434.540338] Freezing user space processes ... (elapsed 0.001 seconds) done.[44434.541893] Freezing remaining freezable tasks ... (elapsed 0.001 seconds) done.[44434.543071] PM: Suspending system (mem)[44434.543088] Suspending console(s) (use no_console_suspend to debug)[44434.543385] sd 0:0:0:0: [sda] Synchronizing SCSI cache[44434.543522] sd 0:0:0:0: [sda] Stopping disk[44434.558538] e1000e: EEE TX LPI TIMER: 00000011[44435.211800] PM: suspend of devices complete after 668.537 msecs[44435.227791] PM: late suspend of devices complete after 15.977 msecs[44435.229946] ehci-pci 0000:00:1d.0: System wakeup enabled by ACPI[44435.230164] ehci-pci 0000:00:1a.0: System wakeup enabled by ACPI[44435.230718] e1000e 0000:00:19.0: System wakeup enabled by ACPI[44435.230726] xhci_hcd 0000:00:14.0: System wakeup enabled by ACPI[44435.243838] PM: noirq suspend of devices complete after 16.039 msecs[44435.244332] ACPI: Preparing to enter system sleep state S3[44435.263885] ACPI : EC: EC stopped[44435.263886] PM: Saving platform NVS memory[44435.263897] Disabling non-boot CPUs ...[44435.264334] Broke affinity for irq 30[44435.265847] smpboot: CPU 1 is now offline[44435.266740] Broke affinity for irq 28[44435.266745] Broke affinity for irq 30[44435.266750] Broke affinity for irq 31[44435.267795] smpboot: CPU 2 is now offline[44435.268978] Broke affinity for irq 1[44435.268983] Broke affinity for irq 8[44435.268986] Broke affinity for irq 9[44435.268989] Broke affinity for irq 12[44435.268992] Broke affinity for irq 16[44435.268996] Broke affinity for irq 21[44435.269000] Broke affinity for irq 27[44435.269003] Broke affinity for irq 28[44435.269006] Broke affinity for irq 30[44435.269010] Broke affinity for irq 31[44435.270029] smpboot: CPU 3 is now offline[44435.271974] ACPI: Low-level resume complete[44435.272028] ACPI : EC: EC started[44435.272029] PM: Restoring platform NVS memory[44435.273248] microcode: CPU0 microcode updated early to revision 0x1c, date = 2015-02-26[44435.273281] Enabling non-boot CPUs ...[44435.273360] x86: Booting SMP configuration:[44435.273361] smpboot: Booting Node 0 Processor 1 APIC 0x2[44435.274290] microcode: CPU1 microcode updated early to revision 0x1c, date = 2015-02-26[44435.277098] cache: parent cpu1 should not be sleeping[44435.277332] CPU1 is up[44435.277380] smpboot: Booting Node 0 Processor 2 APIC 0x1[44435.280573] cache: parent cpu2 should not be sleeping[44435.280750] CPU2 is up[44435.280789] smpboot: Booting Node 0 Processor 3 APIC 0x3[44435.284081] cache: parent cpu3 should not be sleeping[44435.284425] CPU3 is up[44435.292188] ACPI: Waking up from system sleep state S3[44435.629721] xhci_hcd 0000:00:14.0: System wakeup disabled by ACPI[44435.630713] ehci-pci 0000:00:1a.0: System wakeup disabled by ACPI[44435.630804] ehci-pci 0000:00:1d.0: System wakeup disabled by ACPI[44435.631744] PM: noirq resume of devices complete after 17.691 msecs[44435.632341] PM: early resume of devices complete after 0.553 msecs[44435.645325] e1000e 0000:00:19.0: System wakeup disabled by ACPI[44435.645806] rtc_cmos 00:02: System wakeup disabled by ACPI[44435.649552] sd 0:0:0:0: [sda] Starting disk[44435.865510] usb 1-1.5: reset high-speed USB device number 4 using ehci-pci[44435.865588] [drm:intel_opregion_init [i915]] *ERROR* No ACPI video bus found[44435.869545] usb 2-1.8: reset full-speed USB device number 3 using ehci-pci[44435.977520] ata5: SATA link down (SStatus 0 SControl 300)[44435.977552] ata1: SATA link up 6.0 Gbps (SStatus 133 SControl 300)[44436.125239] ata1.00: ACPI cmd ef/10:06:00:00:00:00 (SET FEATURES) succeeded[44436.125243] ata1.00: ACPI cmd f5/00:00:00:00:00:00 (SECURITY FREEZE LOCK) filtered out[44436.125246] ata1.00: ACPI cmd b1/c1:00:00:00:00:00 (DEVICE CONFIGURATION OVERLAY) filtered out[44436.125328] ata1.00: ACPI cmd 00/00:00:00:00:00:a0 (NOP) rejected by device (Stat=0x51 Err=0x04)[44436.126376] ata1.00: ACPI cmd ef/10:06:00:00:00:00 (SET FEATURES) succeeded[44436.126379] ata1.00: ACPI cmd f5/00:00:00:00:00:00 (SECURITY FREEZE LOCK) filtered out[44436.126397] ata1.00: ACPI cmd b1/c1:00:00:00:00:00 (DEVICE CONFIGURATION OVERLAY) filtered out[44436.126472] ata1.00: ACPI cmd 00/00:00:00:00:00:a0 (NOP) rejected by device (Stat=0x51 Err=0x04)[44436.126682] ata1.00: configured for UDMA/133[44436.293577] usb 2-1.8.2: reset full-speed USB device number 4 using ehci-pci[44436.386794] PM: resume of devices complete after 754.391 msecs[44436.387345] PM: Finishing wakeup.[44436.387349] Restarting tasks ... [44436.410524] i915 0000:00:02.0: BAR 6: [??? 0x00000000 flags 0x2] has bogus alignment[44436.410648] i915 0000:00:02.0: BAR 6: [??? 0x00000000 flags 0x2] has bogus alignment[44436.410735] i915 0000:00:02.0: BAR 6: [??? 0x00000000 flags 0x2] has bogus alignment[44436.410986] pci_bus 0000:01: Allocating resources[44436.411010] pci_bus 0000:02: Allocating resources[44436.411064] pci_bus 0000:03: Allocating resources[44436.411081] i915 0000:00:02.0: BAR 6: [??? 0x00000000 flags 0x2] has bogus alignment[44436.411119] i915 0000:00:02.0: BAR 6: [??? 0x00000000 flags 0x2] has bogus alignment[44436.411180] i915 0000:00:02.0: BAR 6: [??? 0x00000000 flags 0x2] has bogus alignment[44436.411200] i915 0000:00:02.0: BAR 6: [??? 0x00000000 flags 0x2] has bogus alignment[44436.411311] i915 0000:00:02.0: BAR 6: [??? 0x00000000 flags 0x2] has bogus alignment[44436.425615] done.How can I fix it? | Intel Graphic error: i915 [...] has bogus alignment | debian;suspend;intel graphics | null |
_unix.184871 | I have Arch, Ubuntu, and GRUB2 installed on a BTRFS filesystem. I'm aware that GRUB cannot write to BTRFS for a variety of good reasons, and therefore cannot save environment variables to /boot/grub/grubenv.I have un-used space at the start and at the end of my disk (due to alignment), and I'm led to believe that the BTRFS file system has some kind of arbitrary storage area too.Is there some way I can configure GRUB to use any of these areas to store persisntent environment variables, instead of it trying (and failing) to use the /boot/grub/grubenv file? | Configure where GRUB2 environment block is located | grub2;environment variables;btrfs | null |
_softwareengineering.74249 | I have a huge program that I have been developing for almost 2 years. It will probably go commercial in about 6-9 months, but seeing as it is just me developing it, I'd had almost zero feedback about the code (efficiency, maintainability, proper use of best practices, etc.). I would really like to have someone or several people review it for feedback.So:Are there places that I can get this service. Are sites like oDesk the way to go?Is it safe? Would an NDA be sufficient to protect IP or are there other ways of going about protecting IP?Are there particular qualities I should look at in a reviewer, other than they know the language and maybe some of the issues?In fact, I don't even know if the 3 questions above are the right ones to ask and I should be asking different ones first.Any advice on this subject? | Is Open Market Code Review a Good Idea? | code reviews | null |
_cogsci.10302 | I quite enjoy playing games which requires many repetitions of the level in order to get right. These games are often constant-speed scrolling obstacle-course type games where the player must navigate obstacles correctly to finish the level. Often many of repetitions of the level are necessary. For example, geometry dash (not affiliated with them at all, I promise!).I often wonder if there are any benefits to playing these games. I know that the repetitive nature creates neural pathways in the brain, but I don't think this newly developed ability is going to be used outside of one game in particular. A friend of mine mentioned that perhaps these games would improve neuroplasticity, and some research indicates that certain types of games do have cognitive health benefits, (for example, in older adults). However, I haven't been able to find any information about this type of game in particular.Do these types of repetitive games have any neurological benefit outside of an improved ability to play a particular game? | What benefit is there to playing highly repetitive games? | video games | Lumosity has a research section that explains how their repetitive games help in day-to-day activities. They claim it's peer reviewed, although all of the papers are published to their site. However, Science based medicine had this to say about a study with games similar to Lumosity...This one study, of course, is not definitive. It is possible that more training is needed before significant benefits are seen. Perhaps video games are more effective because they are more engaging and players will spend more time playing.What this study shows, however, is that products sold as brain training games had no documented benefits after six weeks of use.Putting this study into the context of the overall research, it does make us more cautious about concluding that there are general cognitive benefits to brain training games or entertainment video games. Benefits are likely to be closely related to the specific tasks involved in training, and not transfer to unrelated tasks.But there is already enough published evidence showing visual tracking, multitasking, and executive function benefits from action and strategic video games respectively that this study will not be the final word. When there is conflicting research, more study is needed.This study is most applicable to brain training products, and shows that the marketing claims for these products are not justified. There is very unlikely to be any benefit, or any specific advantage, to scientifically designed brain training applications. For now, you are better off just playing a video game.So, more or less, there isn't any information suggesting that these repetitive brain games actually help develop skills outside of learning to play the game better. |
_softwareengineering.149310 | I have a list of temperature levels (0 - 30 degrees) in different parts of a city. I would like to visualize the different temperature levels in the different parts of the city. Hot places should be displayed in red and cold ones blue. If the user zoom out he will get the avarage temperature color of the city and if zoomed in he will get the average color of the temperate color of that place.I think that what I need is referred to as heatmaps. Is that the correct?I am not too expert in visualization techniques and would appreciate explanatory pseudocode to illustrate the internal workings and main building blocks for heatmap algorithms, and how I could handle the zooming. | Visualizing temperature levels across a city | visualization;heatmap | That sort of thing is exactly what a heatmap is for. As to how to build one, think about a collection of points on the map laid out in a grid. Each point has a temperature associated with it; you then map each temperature value to a color, say withRed: 80Orange: 70and so on. That's your basic heatmap.Now, in the real world you don't generally have exactly rectangular grids, so you have to interpolate. That means finding the nearest points for which you have data and computing an assumed temperature based on some rule. Usually this would be linear -- that is, if you want to compute the value for a point halfway between two other points, you would assign it half the difference in temperatures.This looks like a decent article here: http://www.spatialanalysisonline.com/Output/ContentsFiguresAndTables.html?n=GridInteAndCont.htmlNow, when you do the zooming, all you do is compute a new matrix of numbers for the new grid, map the old vertices to the new grid vertex and average the values. |
_cogsci.13905 | Is there any evidence that a little bit of inner anger is healthy when engaging in problem solving? I personally feel this way, but feel that people around me misinterpret my anger as being directed at them and the world around me instead of at the problem I'm trying to solve. Thanks. | Anger and problem solving | problem solving;mood | null |
_codereview.36672 | I've been playing around with Clojure for a while now, and one of the tasks I occasionally find awkward is parsing input. For example, I took part in the facebook hacker cup recently, where part of the challenge was to read input like this:54..##..##........4..##..###.......4#####..##..#####5####################.....5#########################Where the first line is the number of cases to follow and the first line of each case is the number of lines in that case. It seems fairly obvious to me that the output of parsing this should be a list of cases, but there's no obvious way to know when to split the data without reading part of the data first. (In this particular case I know I could look for lines with numbers vs. lines with #s, but I'm more interested in a general solution)I ended up implementing this like:(defn read-stdin [] (line-seq (java.io.BufferedReader. *in*)))(defn my-iterate [f n input] Calls iterate on input and returns the final result (nth (iterate f input) n))(defn parse-grid Parses a text grid of .s and #s and returns a set of coord pairs for each # element [lines] (set (filter identity (for [[row line] (map-indexed vector lines) [col c] (map-indexed vector line)] (if (= c \#) [row col] nil)))))(defn parse-case Takes a case-array and some lines, parses out a single case, adds it to the case-array and returns along with the remainder of the lines. Meant to be used with iterate [[cases [first-line & lines]]] (let [problem-size (read-string first-line)] [(conj cases {:size problem-size :blacks (parse-grid (take problem-size lines))}), (drop problem-size lines)]))(defn parse-cases [[first-line & rest-lines]] (let [num-cases (read-string first-line)] (first (my-iterate parse-case num-cases [[] rest-lines]))))(def read-cases-stdin (comp parse-cases read-stdin))The parse-case function is my main worry here - it feels really awkward to have to return a vector of the current case list and the rest of the input, and have to deal with unpacking it again on the next iteration of the function. Is there a more idiomatic way of going about doing this?Any other general feedback on my code would also be welcome. | Idiomatic input parsing in clojure | clojure | I think your main problem is that you're using iterate where partitioning and mapping would work just fine.I would create a simple helper function that splits the input line-seq into cases. Normally you could use partition for this, but since the number of lines can vary from case to case, you would have to use loop/recur. (See my split-cases function below. Also, note that we don't really care about the number of cases on the first line; we completely ignore it via destructuring.)Now, believe it or not, all you have to do is map your parse-grid function over the result of (split-cases ...) and you'll end up with a list of sets of coordinates, one for each case. I think your parse-grid function is very nice. It's concise and it makes good use of map-indexed and destructuring. The only thing I would tweak is that I would leverage the built-in :when syntax of Clojure's for macro to filter out the coordinates of the non-# characters. Then you can take out the filter identity part because there are no longer any nil values to remove.So, here is how I would revise your code:(defn split-cases [[_ & lines]] Returns a seq of cases, each of which is a seq of #/. lines. (loop [result [] [number-of-lines & lines] lines] (if (seq lines) (recur (conj result (take number-of-lines lines)) (drop number-of-lines lines)) result)))(defn parse-grid [grid] Parses a text grid of .s and #s and returns a set of coord pairs for each # element (set (for [[row line] (map-indexed vector grid) [col c] (map-indexed vector line)] :when (= c \#)] [row col])))(defn read-stdin [] (line-seq (java.io.BufferedReader. *in*)))(defn parse-cases-stdin [] (map parse-grid (split-cases (read-stdin)))) |
_unix.322772 | We have two different Kyocera printers running for printing invoices. The invoices are PDF files that have been generated by wkhtmltopdf (previously dompdf with the same issues). Printing these invoices used to work fine, but suddenly without any interference only part of the files are printed. Different invoices result in different but all still broken prints. I'm talking about e.g. four lines of text and a single rectangle, or the lines of a table and the image header only.CUPS, which I'm using to print, shows me the following error for each PDF:W [12/Nov/2016:09:45:01 +0100] [Job 80] /var/spool/cups/d00080-001: file is damagedW [12/Nov/2016:09:45:01 +0100] [Job 80] /var/spool/cups/d00080-001 (file position 34956): xref not foundW [12/Nov/2016:09:45:01 +0100] [Job 80] /var/spool/cups/d00080-001: Attempting to reconstruct cross-reference tableI am clueless as to why this happens, as every other PDF reader can show generated invoices just fine. Printing the same files with Acrobat Reader will not cause any of these problems.What part of the system is causing this problem? How did this start happening suddenly without me (the only one touching the printing system) even being at the office. Is there a workaround?PS: The printers are a Kyocera ECOSYS P2135dn and a Kyocera FS-1370DN. Both using their identically named official driver installed from the kyocera website. I am running Ubuntu 16.04 LTS with CUPS 2.1.3. | Printing PDF with CUPS | ubuntu;pdf;printing;cups | null |
_cs.69354 | imho this is not at all a duplicate, because the other question does not address the recursive case $T(d,n) = ....T(d-1,T(d-1,n))....$, which appears to be part of the Taylor expansion of this function. Also I don't know how to write this as a Taylor expansion. If I would, I would still not know how to solve this specific instance.Consider the following function. Maybe it could be more efficient, but I'm only interested in the output value, not the runtime complexity. All variables are whole numbers.function branch(currentDepth, maxDepth, n, k) { if (currentDepth == maxDepth) { return n; } sum = 0; for (i=0; i<=k; i++) { tmpN = branch(currentDepth+1, maxDepth, n, i); sum += branch(currentDepth+1, maxDepth, tmpN, k-i); } return sum;}For $2 < k << n$ and $2 < d = O(\log n)$, is there a formula in terms of $d$, $k$ and $n$ (either exact, big-O or Theta), that predicts the output forbranch(0, d, n, k);Will it be exponential in $n$? Can we maybe solve this for small $k$? ($k\le7$).Application: the output value is a factor of the runtime complexity of a Fixed Parameter algorithm I made up, but I don't think it will beat existing algorithms. However I still wanted this solved. | Can the output value be solved and/or written as Taylor expansion? | time complexity;recurrence relation | It is better to use as parameters maxDepth-currentDepth, n, k. Call the resulting function $f_k(d,n)$.When $k = 0$,$$f_0(d,n) = \begin{cases}n & d = 0, \\f_0(d-1,f_0(d-1,n)) & d > 0.\end{cases}$$You can prove by induction that the solution is $f_0(d,n) = n$.When $k=1$,$$f_1(d,n) = \begin{cases}n & d = 0, \\f_1(d-1,f_0(d-1,n)) + f_0(d-1,f_1(d-1,n)) & d > 0,\end{cases}$$which reduces to$$f_1(d,n) = \begin{cases}n & d = 0, \\2f_1(d-1,n) & d > 0.\end{cases}$$The solution is$$f_1(d,n) = 2^d n.$$When $k = 2$, using the preceding formulas we get$$f_2(d,n) = \begin{cases}n & d=0, \\2f_2(d-1,n) + 4^{d-1} n & d > 0.\end{cases}$$Unrolling the recursion gives$$\begin{align*}f_2(d,n) &= 4^{d-1} n + 2\cdot 4^{d-2} n + 2^2 \cdot 4^{d-3} n + \cdots + 2^{d-1} n + 2^d n \\ &=(2^{2d-2} + 2^{2d-3} + \cdots + 2^{d-1}+2^d) n \\ &=(2^d+1)2^{d-1} n.\end{align*}$$Let us approximate this by $2^{2d-1}n$.When $k = 3$, the preceding formulas show that$$f_3(d,n) \approx\begin{cases}n & d = 0, \\2f_3(d-1,n) + 2^{3d} n & d > 0.\end{cases}$$Unrolling the recursion gives$$f_3(d,n) \approx (2^{3d} + 2^{3(d-1)+1} + 2^{3(d-2)+2} + \cdots + 2^{3(1)+d-1} + 2^d)n \approx \frac{4}{3} 2^{3d}n. $$Continuing in this way, we find that up to constants, if $f_k(d,n) = \Theta(2^{r_kd}n)$ then $r_{k+1} = \max_{1 \leq \ell \leq k} (r_\ell + r_{k+1-\ell})$ (except for the base cases $k \leq 1$). For example, we have$$\begin{align*}&r_0 = 0 \\&r_1 = 1 \\&r_2 = 2 \\&r_3 = 3 \\&r_4 = 4\end{align*}$$and so on. Indeed, induction shows that $f_k(d,n) = \Theta_k(2^{kd}n)$. With more effort, we could estimate the hidden constant. |
_softwareengineering.119625 | I've got a question concerning node.js performance.There is quite lot of benchmarks and a lot of fuss about great performance of node.js. But how does it stand in real world? Not just process empty request at high speed.If someone could try to compare this scenario:Java (or equivalent) server running an application with complex business logic between receiving request and sending response.How would node.js deal with it? If there was need for a lot of JavaScript processing on server side, is node.js really so fast that it can execute JavaScript, and stand a chance against more heavyveight competitors? | Real performance of node.js | node.js | null |
_unix.1381 | since OpenSolaris is more or less abandoned by Oracle, is there a nice alternative that implements the unique features of OSOL? ZFS is one thing, but I liked the image creation system, that let you create images of a master system and then distribute it quickly to other computers. This was an effort to simplify creation of clusters.According to the Wikipedia page of OSOL, there's Illumos, which is a fork of OSOL, with all closed source parts replaced by open source parts. Illumos is in active development.But is Illumos an alternative to OSOL, with all it's features? Is anyone using it and could tell us his or hers experiences? | The future of OpenSolaris | solaris;history;zfs;opensolaris | Illumos is not a full replacement to OSOL and I don't think it will be in the future since it's intended to be a base from which others can build a distribution. But check the Nexenta OS, this system is heavily based on OSOL and they are one of the main sponsors behind the Illumos project. Although I haven't used it personally and I wouldn't know whether it has what you need. |
_webapps.13042 | If we archive a mail in gmail, is storage saved?I mean, is the file compressed well? Gmail can search in archived mail. If it was really compressed, the searching was very hard job. But they can. So I'm very curious about what gmail's archive mean. | Can gmail's archive feature save storage? | gmail;gmail archive | Google is probably doing something to save space. Maybe they are indexing and then compressing (older) emails. But your space usage is counted from non-compressed emails.So in short: archiving do not save your space at all.Whole point of Archive is to move email from inbox. Point is that whatever is in your inbox is something important you should react on, and other things are archived. |
_unix.364164 | For a few days i'm breaking my head over the following:the partition table is reported to be messed up, but it's not.grub-legacy gives problems with some partitions during actual boot-up, but not when invoked in a shell when linux is up-and-running.I suspect the two symptoms are related, but i'm not sure.Background information:Grub-legacy has been booting from an XFS on /dev/sda4 a.k.a. (hd0,3) for years without trouble.Things got messed up when resizing the FAT32 filesystem on sda1 using Gparted (apparently there is a bug in libparted 3.2 responsible for this). Suddenly grub couldn't access sda4 anymore.Here is the output from fdisk concerning th broken-not-broken partition table:Welcome to fdisk (util-linux 2.27.1).Changes will remain in memory only, until you decide to write them.Be careful before using the write command.Command (m for help): pDisk /dev/sda: 74.5 GiB, 80026361856 bytes, 156301488 sectorsUnits: sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisklabel type: dosDisk identifier: 0x85068506Device Boot Start End Sectors Size Id Type/dev/sda1 2048 8390655 8388608 4G c W95 FAT32 (LBA)/dev/sda2 * 8390656 29296639 20905984 10G 7 HPFS/NTFS/exFAT/dev/sda3 29296640 136712191 107415552 51.2G f W95 Ext'd (LBA)/dev/sda4 136712192 156301487 19589296 9.3G 83 Linux/dev/sda5 29298688 33492991 4194304 2G 83 Linux/dev/sda6 33495040 75438079 41943040 20G 83 Linux/dev/sda7 75440128 83828735 8388608 4G 83 Linux/dev/sda8 83830784 88025087 4194304 2G 83 Linux/dev/sda9 88027136 94318591 6291456 3G 82 Linux swapPartition table entries are not in disk order.Command (m for help): xExpert command (m for help): fNothing to do. Ordering is correct already.parted lists the partition table as follows:# parted /dev/sda unit s print free Model: ATA WDC WD800JB-00JJ (scsi)Disk /dev/sda: 156301488sSector size (logical/physical): 512B/512BPartition Table: msdosDisk Flags: Number Start End Size Type File system Flags 63s 2047s 1985s Free Space 1 2048s 8390655s 8388608s primary fat32 boot, lba 2 8390656s 29296639s 20905984s primary ntfs 3 29296640s 136712191s 107415552s extended lba 5 29298688s 33492991s 4194304s logical ext2 6 33495040s 75438079s 41943040s logical ext3 7 75440128s 83828735s 8388608s logical ext3 8 83830784s 88025087s 4194304s logical ext3 9 88027136s 94318591s 6291456s logical linux-swap(v1) 94318592s 136712191s 42393600s Free Space 4 136712192s 156301487s 19589296s primary ext2About grub during boot-up:it reports Error 5: partition table invalid or corrupt for sda7 and sda8.it reports Filesystem type unknown for sda4, though it's a simple ext2 (by now).I've searched many many forums/wikis/etc, but haven't solved this puzzle yet.I've only come to realise my partition table is 1MiB-aligned (hence the 2048 sector gaps).I've done some partition deletion/recreation/reformatting/checking etc, without success.I'm running slackware 14.2 (salix, actually) with kernel 3.10. All linux filesystems are ext2 or ext3.I'm very curious to find the cause of these symptoms. Please help me to tackle this. | fdisk: partition table not in disk order but Order is correct already? and GRUB-legacy issues | grub legacy;partition table | null |
_webapps.53898 | I want to know how people write in their status continue reading at the end, which is actually a link to their page? | How do people write in their status continue reading? | facebook;facebook pages | null |
_unix.285259 | In bash, I have an array containing a list of links, e.g.http://xkcd.com/archivehttp://what-if.xkcd.com/http://blag.xkcd.com/http://store.xkcd.com/I also have a variable named $URL. I would like to set the variable $URL to a random item in the list. | Set variable to random item in array | shell script | You could use RANDOM variable defined by bash:URL=${URLLIST[ $(( RANDOM % ${#URLLIST[@]} )) ] }where URLLIST is the an array containng your urls:URLLIST=( \ http://xkcd.com/archive \ http://what-if.xkcd.com/ \ http://blag.xkcd.com/ \ http://store.xkcd.com/ \) |
_unix.300113 | virsh list returns an empty list but the gui virt-manager has 2 defined QEMU/KVM virtual machines. How come virsh list doesn't list anythng ? | How to list domains in virsh? | virtual machine | The virsh list command only runs things running.If you want things defined but not running thenvirsh list --allAnd remember each type of namespace is distinct so you may need --connect as welle.g.$ virsh -c lxc:/// list Id Name State----------------------------------------------------$ virsh -c lxc:/// list --all Id Name State---------------------------------------------------- - helloworld shut off$ virsh -c qemu:///system list Id Name State---------------------------------------------------- 37 fedora24 running$ virsh -c qemu:///system list --all Id Name State---------------------------------------------------- 37 fedora24 running - docker shut off - kali shut off - test1 shut off |
_unix.189251 | How can I read a dash file from the terminal other than delimiting it with ./For example to read a - file we can read it by cat ./-file_nameQ: Is there an alternative way to achieve the same thing? | How to read dash files | bash;cat | For commands which get input from stdin, you can use redirection:cat <-file_name |
_softwareengineering.164419 | Context: I'm taking several classes this semester in which I'll be coding. Here is a list of possible languages I'll be using:JavaC (system and embedded level)C++ (contest programming)VHDL (for FPGA work)PythonSchemeIs it possible to keep all these languages floating around in one's head? How can one code without having to look up reference material every time they start working? | When using several languages for different projects, how do you keep the different syntaxes straight? | programming languages | C++ alone is a massive language as is Java. I could reasonably expect a skilled, veteran to remember all of Scheme, Python, or C but there is no shame to be had in using references. I'd argue that learning generically applicable programming techniques and remembering the elements of style for each language over trying to remember the entire syntax. I'm not sure that's possible in some cases, particularly given how much languages can change.I work at a technical bookstore and I routinely sell reference manuals to skilled, experienced professionals. Better to have knowledge that there is such a technique for thing x and not remember the exact syntax or semantics than to not know that thing x exists. That's why these things exist. You are plugging along and think I know of something that would work nicely here and perhaps you find it to be wrong for that language but the reference if it's any good and you've a solid grasp on the fundamentals will give you pointers (sometimes literally) toward a solution. |
_webapps.100855 | In Google Sheets I have a search box that brings up the information for a person when you type in their id. It works perfectly up until ID 512, which is row 374. The formula below is what I use.=IFERROR(VLOOKUP(C3,'Main Database'!B21:S590,3,True),) | VLookup Stops Working After 500 Rows | google spreadsheets | null |
_unix.254709 | From A Practical Guide to Linux Commands, Editors, and ShellProgramming By Mark G. SobellAlthough you can use bash to execute a shell script, this technique causes the script to run more slowly than giving yourself execute permission and directly invoking the script.Why is that?How is running a script like an executable different from running itby a shell explicitly?Do both follow the same steps as:A command on the command line causes the shell to fork a new process, creating a duplicate of the shell process (a subshell). The new process attempts to exec (execute) the command. Like fork, the exec routine is executed by the operating system (a system call). Because the command is a shell script, exec fails. When exec fails, the command is assumed to be a shell script, and the subshell runs the commands in the script. Unlike a login shell, which expects input from the command line, the subshell takes its input from a filenamely, the shell script. | How is running a script like an executable different from running it by a shell explicitly? | bash | null |
_reverseengineering.13873 | I want to ask if somebody is aware of tools/projects which are similar to the Appcall feature of IDA Pro[1] for Android Apps?I'm looking for the possibility to run certain methods detected in the smali code without running the whole APK.Thanks in advance for your help :-)[1] http://www.hexblog.com/?p=113 | Call Android method without running whole Android-App | android;gdb;dynamic analysis | You should be able to write a separate application that dynamically loads the dex file from the app that you are interested in using DexClassLoader, allowing you to construct classes and call methods from that dex file. You can get the path to the other apk using PackageManager.getApplicationInfo(). The sourceDir field of the returned ApplicationInfo object will have the path to the apk. |
_webapps.84853 | I cannot set profile picture visibility for one of my profiles in Gmail. I have tried following this guide. I have also looked at How do I change my Gmail profile picture?The problem I am facing is as follows:Only one accout of two is affected. For the accout that is functioning normally I can upload the picture and then set the visibility as shown on a screenshot below:For affected account I can upload the picture, but visibility options are not present:Notes:My preferred option is Visible to everyone. But when options are not visible, the behavior defaults to not visible to anyone at all even myself.Both accounts names have the same form: xyz.abcdef@gmail.comI don't have Google+ account and don't want to create oneWhat I have tried so far:Removing picture completely, signing out and trying again (no luck)Acccessing gmail from older HTML version of app (no option to upload the picture)Sending feedback to Google (waiting for response) | Gmail profile picture visibility | gmail;profile picture | null |
_unix.38105 | Can a partition have a UUID without a filesystem? | Can unformatted partitions have UUIDs? | linux;partition;block device | null |
_codereview.95144 | I'm trying to focus on learning so I can get an entry level position and the best way for me to learn right now is to have someone review and provide areas of improvement. This project isn't entirely complete but almost. I am going to include the code for some of the classes but not all of them. Just a few button actions left to finish. All criticism is welcomed.public class CreateAndShowUI { public static void createUI() { Model model = new Model(); MainPanel mainPanel = new MainPanel(model, new CSVFileController(model)); JFrame frame = new JFrame(); frame.getContentPane().add(mainPanel.getMainPanel()); frame.setUndecorated(true); frame.setPreferredSize(new Dimension(1100, 550)); frame.addMouseListener(new ApplicationMouseAdapters.FrameMouseAdapter()); frame.addMouseMotionListener(new ApplicationMouseAdapters.FrameMouseMotionListener( frame)); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } public static final Font getHeaderFont() { return new Font(Consolas, Font.BOLD, 16); } public static final Font getFont() { return new Font(Consolas, Font.BOLD, 14); } public static final Font getTableFont() { return new Font(Consolas, Font.PLAIN, 16); } public static final Color getButtonColor() { return new Color(230, 230, 230); } public static void main(String[] args) { createUI(); }}The MainPanel Class which basically creates the main JPanel for the JFrame. This JPanel has two child panels and one menu bar.public class MainPanel { private Model model; private CSVFileController controller; private JPanel mainPanel; private Dialog dialog; private MenuBar menuBar; private ButtonPanel buttonPanel; private JScrollPane buttonScrollPane, listScrollPane; private JTable table; private JLabel search; private JTextField searchTF; private JButton xButton; public MainPanel(Model model, CSVFileController controller) { this.model = model; this.controller = controller; createMainPanel(); } private void createMainPanel() { mainPanel = new JPanel(new MigLayout(, , []13[])); dialog = new Dialog(); table = new JTable(new ProductTableModel()); setTableColumnWidth(table.getModel()); table.getTableHeader() .setPreferredSize( new Dimension(table.getColumnModel() .getTotalColumnWidth(), 48)); table.getTableHeader().setResizingAllowed(false); table.getTableHeader().setReorderingAllowed(false); table.getTableHeader().setFont(CreateAndShowUI.getFont()); table.setFont(CreateAndShowUI.getTableFont()); table.addMouseListener(new ApplicationMouseAdapters.TableMouseAdapter( dialog, table.getModel(), controller)); setTableEditorFont(table); menuBar = new MenuBar(); mainPanel.add(menuBar.getMenuBar()); search = new JLabel(Search); mainPanel.add(search, cell 0 0, gap 10px); searchTF = new JTextField(, 30); mainPanel.add(searchTF, cell 0 0); xButton = new JButton(new CloseAction(X)); xButton.setFocusable(false); xButton.setFont(CreateAndShowUI.getFont()); xButton.setBackground(new Color(158, 7, 7)); xButton.setForeground(Color.WHITE); mainPanel.add(xButton, cell 0 0, gap 283px, wrap); buttonPanel = new ButtonPanel(); buttonScrollPane = new JScrollPane(buttonPanel.getButtonPanel(), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); buttonScrollPane.setViewportView(buttonPanel.getButtonPanel()); buttonScrollPane.setPreferredSize(new Dimension(250, 990)); mainPanel.add(buttonScrollPane); listScrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); listScrollPane.setPreferredSize(new Dimension(850, 990)); mainPanel.add(listScrollPane, cell 0 1); } public JPanel getMainPanel() { return mainPanel; } public JPanel getButtonPanel() { return buttonPanel.getButtonPanel(); } public JTable getTable() { return table; } public JMenuBar getMenuBar() { return menuBar.getMenuBar(); } public final void setTableEditorFont(JTable table) { DefaultCellEditor editor = (DefaultCellEditor) table .getDefaultEditor(Object.class); Component component = editor.getComponent(); component.setFont(table.getFont()); editor.setClickCountToStart(1); } public final void setTableColumnWidth(TableModel tableModel) { final TableColumnModel columnModel = table.getColumnModel(); if (tableModel.getColumnCount() == 6) { columnModel.getColumn(0).setPreferredWidth(200); columnModel.getColumn(1).setPreferredWidth(300); columnModel.getColumn(2).setPreferredWidth(80); columnModel.getColumn(3).setPreferredWidth(75); columnModel.getColumn(4).setPreferredWidth(80); columnModel.getColumn(5).setPreferredWidth(75); } } public class ButtonPanel { private JPanel panel; public ButtonPanel() { panel = new JPanel(new MigLayout()); addButtons(); } private void addButtons() { List<Supplier> supplierList = model.getSuppliers(); for (Supplier supplier : supplierList) { JButton button = new JButton( new SupplierButtonActions.ShowSupplierProductsAction( supplier.getName(), getTable(), model)); button.setFocusable(false); button.setFont(CreateAndShowUI.getFont()); button.setBackground(CreateAndShowUI.getButtonColor()); button.setPreferredSize(new Dimension(230, 30)); button.setHorizontalAlignment(SwingConstants.CENTER); panel.add(button, wrap); } } public JPanel getButtonPanel() { return panel; } } public class MenuBar { private JMenuBar menuBar; private JMenu application, suppliers, orders; private JMenuItem viewOrders, newSupplier, addProduct, close; public MenuBar() { createMenuBar(); } private void createMenuBar() { menuBar = new JMenuBar(); close = new JMenuItem(new CloseAction(Close)); close.setPreferredSize(new Dimension(125, 25)); close.setFont(CreateAndShowUI.getHeaderFont()); application = new JMenu(Application); application.setFont(CreateAndShowUI.getHeaderFont()); application.setPreferredSize(new Dimension(125, 70)); application.add(close); menuBar.add(application); newSupplier = new JMenuItem( new DialogActions.AddSupplierPanelAction(dialog, New)); newSupplier.setPreferredSize(new Dimension(125, 25)); newSupplier.setFont(CreateAndShowUI.getHeaderFont()); addProduct = new JMenuItem(new DialogActions.AddProductPanelAction( dialog, model, Add Products)); addProduct.setPreferredSize(new Dimension(125, 25)); addProduct.setFont(CreateAndShowUI.getHeaderFont()); suppliers = new JMenu(Suppliers); suppliers.setFont(CreateAndShowUI.getHeaderFont()); suppliers.setPreferredSize(new Dimension(125, 70)); suppliers.add(newSupplier); suppliers.add(addProduct); menuBar.add(suppliers); viewOrders = new JMenuItem(View); viewOrders.setFont(CreateAndShowUI.getHeaderFont()); viewOrders.setPreferredSize(new Dimension(125, 25)); orders = new JMenu(Orders); orders.setFont(CreateAndShowUI.getHeaderFont()); orders.setPreferredSize(new Dimension(125, 70)); orders.add(viewOrders); menuBar.add(orders); } public JMenuBar getMenuBar() { return menuBar; } }}The KeywordPanel class which is one of the panels for JDialog. This panel is added dynamically to a dialog based on a specific action taken by the user. public class KeywordPanel { private CSVFileController controller; private Product product; private Dialog dialog; private JPanel keywordPanel; private JTextField[] textFields; private JLabel searchLbl; private JButton close, remove; public KeywordPanel(CSVFileController controller, Dialog dialog, Product product) { this.controller = controller; this.product = product; this.dialog = dialog; createKeywordPanel(); } public void createKeywordPanel() { keywordPanel = new JPanel(new MigLayout()); searchLbl = new JLabel(KeyWords); searchLbl.setFont(CreateAndShowUI.getFont()); keywordPanel.add(searchLbl, wrap); textFields = new JTextField[] { new JTextField(), new JTextField(), new JTextField(), new JTextField(), new JTextField() }; for (JTextField textField : textFields) { textField.setFont(CreateAndShowUI.getFont()); textField.setPreferredSize(new Dimension(242, 30)); keywordPanel.add(textField, wrap); } remove = new JButton(new KeywordPanelController.RemoveAction(Remove, controller, product)); remove.setBackground(CreateAndShowUI.getButtonColor()); remove.setFont(CreateAndShowUI.getFont()); keywordPanel.add(remove); close = new JButton(new KeywordPanelController.SaveAndCloseAction( Save & Close, controller, dialog, product, textFields)); close.setBackground(CreateAndShowUI.getButtonColor()); close.setFont(CreateAndShowUI.getFont()); keywordPanel.add(close, cell 0 6, gapx 30px);}public void setCategoryTextFields(int index, String category) { textFields[index] .addMouseListener(new KeywordPanelController.TextFieldMouseAdapter( textFields[index])); textFields[index].setEditable(false); textFields[index].setBackground(Color.WHITE); textFields[index].setText(category); } public void setLocation(int x, int y) { keywordPanel.setLocation(x, y); } public JPanel getKeywordPanel() { return keywordPanel; }}Main model for the application:public class Model { private Map<Supplier, List<Product>> supplierProductList; private List<Product> productList; public Model() { this.supplierProductList = new TreeMap<Supplier, List<Product>>(); } public void addSupplier(Supplier supplier) { if (!supplierProductList.containsKey(supplier)) { this.supplierProductList.put(supplier, new ArrayList<Product>()); } } public ArrayList<Supplier> getSuppliers() { return new ArrayList<Supplier>(supplierProductList.keySet()); } public void addProduct(String name, Product product) { for (Supplier supplier : supplierProductList.keySet()) { if (supplier.getName().equals(name) && !supplierProductList.get(name).contains(product)) { this.productList = supplierProductList.get(name); this.productList.add(product); this.supplierProductList.put(supplier, productList); } } } public void addProductList(Supplier supplier, List<Product> productList) { this.supplierProductList.put(supplier, productList); } public ArrayList<Product> getProducts(String name) { for (Supplier supplier : getSuppliers()) { if (supplier.getName().equals(name)) return new ArrayList<Product>(supplierProductList.get(supplier)); } return null; }}This is the CSVFileController class. This is used to update the model and the files based on user interaction with the view.public class CSVFileController { private Model model; private BufferedReader reader; private BufferedWriter writer; private String line; public CSVFileController(Model model) { this.model = model; this.reader = null; this.writer = null; this.line = ; updateModel(); } public void updateModel() { List<Supplier> suppliers = new ArrayList<Supplier>(); try { reader = new BufferedReader(new FileReader(Suppliers.csv)); while ((line = reader.readLine()) != null) { String[] dataArray = line.split(,); suppliers.add(new Supplier(dataArray[0], Integer .parseInt(dataArray[1]))); } for (Supplier supplier : suppliers) { List<Product> productList = new ArrayList<Product>(); reader = new BufferedReader(new FileReader(supplier.getName() + .csv)); while ((line = reader.readLine()) != null) { String[] dataArray = line.split(,); if (dataArray.length == 6) { productList.add(new Product(supplier, dataArray[0], dataArray[1], Integer.parseInt(dataArray[2]), Integer.parseInt(dataArray[3]), Double .parseDouble(dataArray[4]), Integer .parseInt(dataArray[5]))); } else { List<String> categories = new ArrayList<String>(); for (int x = 6; x < dataArray.length; x++) { categories.add(dataArray[x]); } productList.add(new Product(supplier, dataArray[0], dataArray[1], Integer.parseInt(dataArray[2]), Integer.parseInt(dataArray[3]), Double .parseDouble(dataArray[4]), Integer .parseInt(dataArray[5]), categories)); } } model.addProductList(supplier, productList); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { closeReader(reader); } } public void adjustProductCategories(Product product) { List<Product> supplierProductList = model.getProducts(product .getSupplier().getName()); try { writer = new BufferedWriter(new FileWriter(product.getSupplier() .getName() + .csv)); for (ListIterator<Product> iterator = supplierProductList .listIterator(); iterator.hasNext();) { Product prod = iterator.next(); if (prod.getId() == product.getId()) { iterator.remove(); iterator.add(product); model.addProductList(product.getSupplier(), supplierProductList); } writer.write(prod.toString()); writer.newLine(); } } catch (IOException ex) { ex.printStackTrace(); } finally { closeWriter(writer); } } public void closeWriter(BufferedWriter bw) { try { if (bw != null) { bw.close(); } } catch (IOException e) { e.printStackTrace(); } } public void closeReader(BufferedReader br) { try { if (br != null) { br.close(); } } catch (IOException e) { e.printStackTrace(); } }}This is the controller for the KeywordPanel: public class KeywordPanelController { public static class RemoveAction extends TextAction { private CSVFileController controller; private Product product; public RemoveAction(String name, CSVFileController controller, Product product) { super(name); this.controller = controller; this.product = product; } @Override public void actionPerformed(ActionEvent e) { JTextComponent textField = (JTextField) getFocusedComponent(); if (!textField.isEditable()) { product.getCategories().remove(textField.getText().trim()); product.setCategories(product.getCategories()); controller.adjustProductCategories(product); textField.setText(); textField.setEditable(true); } } } public static class TextFieldMouseAdapter extends MouseAdapter { private JTextField textField; public TextFieldMouseAdapter(JTextField textField) { this.textField = textField; } @Override public void mouseClicked(MouseEvent evt) { textField.setSelectionColor(new Color(142, 15, 6)); textField.setSelectedTextColor(new Color(255, 255, 255)); textField.setSelectionStart(0); textField.setSelectionEnd(textField.getText().trim().length()); } } public static class SaveAndCloseAction extends AbstractAction { private JTextField[] textFields; private Product product; private CSVFileController controller; private Dialog dialog; public SaveAndCloseAction(String name, CSVFileController controller, Dialog dialog, Product product, JTextField[] textFields) { super(name); this.controller = controller; this.textFields = textFields; this.product = product; this.dialog = dialog; } @Override public void actionPerformed(ActionEvent e) { List<String> categories = new ArrayList<String>(); for (JTextField textField : textFields) { if (new ValidateString().validate(textField.getText().trim())) { categories.add(textField.getText().trim()); } } product.setCategories(categories); controller.adjustProductCategories(product); dialog.getDialog().dispose(); } }}The Product class which is a POJO. I'm not entirely sure if this should be considered a model class or not.public class Product { private Supplier supplier; private List<String> categoryList; private int minQty, qtyOnHand, orderQty; private double cost; private String productDescription, id; public Product(Supplier supplier, String id, String productDescription, int qtyOnHand, int minQty, double cost, int orderQty, List<String> categories) { this.supplier = supplier; this.qtyOnHand = qtyOnHand; this.orderQty = orderQty; this.id = id; this.minQty = minQty; this.cost = cost; this.productDescription = productDescription; this.categoryList = categories; } public Product(Supplier supplier, String id, String productDescription, int qtyOnHand, int minQty, double cost, int orderQty) { this.supplier = supplier; this.qtyOnHand = qtyOnHand; this.orderQty = orderQty; this.id = id; this.minQty = minQty; this.cost = cost; this.productDescription = productDescription; } public Product(String id, String productDescription, int qtyOnHand, int minQty, double cost, int orderQty) { this.qtyOnHand = qtyOnHand; this.orderQty = orderQty; this.id = id; this.minQty = minQty; this.cost = cost; this.productDescription = productDescription; } public int getQtyOnHand() { return qtyOnHand; } public void setQtyOnHand(int qtyOnHand) { this.qtyOnHand = qtyOnHand; } public int getOrderQty() { return orderQty; } public void setOrderQty(int orderQty) { this.orderQty = orderQty; } public String getId() { return id; } public void setId(String id) { this.id = id; } public double getCost() { return cost; } public void setCost(double cost) { this.cost = cost; } public String getProductDescription() { return productDescription; } public void setProductDescription(String productDescription) { this.productDescription = productDescription; } public int getMinQty() { return minQty; } public void setMinQty(int minQty) { this.minQty = minQty; } public List<String> getCategories() { return categoryList; } public void setCategories(List<String> categories) { this.categoryList = categories; } public Supplier getSupplier() { return supplier; } public void setSupplier(Supplier supplier) { this.supplier = supplier; } public boolean isCategorized() { if (categoryList == null) { return false; } else { return true; } } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(id).append(,).append(productDescription).append(,) .append(qtyOnHand).append(,).append(minQty).append(,) .append(cost).append(,).append(orderQty); if (isCategorized()) { for (String category : categoryList) { builder.append(,).append(category); } } return builder.toString(); }} | CSV File Reader Project | java;mvc;swing;csv | null |
_reverseengineering.15140 | My problem is: hexrays thinks that semicolon is visible character. In IDAPython idaapi.is_visible_char(';') returns TrueIn picture you can see field_100C; highlighted, but field_100C not highlighted.In ida.cfg I have following NameChars (this is ARM LE):NameChars = _0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz; In any other NameChars array semicolon is not added.So, how can this behaviour get fixed? Is there idapython call of some sorts? Can plugins be a reason for this? Is there GUI option to check?Found this, but it didnt helphttps://www.hex-rays.com/products/ida/support/sdkdoc/name_8hpp.html | Incorrect semicolon usage in decompiled variables | ida;idapro plugins | Still don't know what was the root of the problem, but PC restart helped...';' stopped magically appearing in NameChars array. |
_unix.291086 | I have a lynx configuration file in ~/.lynx.cfg.To make lynx use it, I have in my environment $LYNX_CFG pointing at that file.Content:# DefaultCOLOR:0:black:white# HyperlinksCOLOR:1:black:white# Status LineCOLOR:2:black:white# EmphasisCOLOR:4:black:white# Hyperlink in emCOLOR:5:black:white# Selected hyperlinkCOLOR:6:black:black# SearchCOLOR:7:black:whiteJUSTIFY:TRUEThe JUSTIFY:TRUE line is correctly applied, but never the COLOR:*:I'm on OS X Yosemity, in Tmux, using Iterm2, and the lynx version is:Lynx Version 2.8.8rel.2 (09 Mar 2014)libwww-FM 2.14, SSL-MM 1.4.1, OpenSSL 1.0.2h, ncurses 5.7.20081102What could cause the issue? | Lynx colors not applied | colors;lynx | null |
_bioinformatics.842 | I'm currently attempting association analysis with an extremely small set of patient exomes (n=10), with no control or parental exomes available. Downloading the ExAC VCF of variant sites (http://exac.broadinstitute.org/downloads) or the 1000G integrated call sets (http://ftp.1000genomes.ebi.ac.uk/) and combining this with our pooled patient VCFs has not been successful (I suspect the approach of attempting to merge such large VCFs generated from different pipelines is rather naive).Looking at the primary literature, I have gathered it should be possible to use these resources to help increase statistical power for our analysis. My question is how do I take these large .vcfs with many samples and successfully merge them to our patient .vcfs, such that the combined VCF can be used downstream to run analysis packages? (PODKAT, PLINK, etc.) | What is a good pipeline for using public domain exomes as controls? | public databases;variants;sequencing;exome | null |
_datascience.20510 | I am implementing a module which finds based on user interactions on an online portal to find which attributes of a certain product and what values for those products influence the buyer to choose the said Item.My employers have suggested me to use Genetic Algorithm to achieve this. I have started implementing and found even the initial population generation to be a bit ineffective. Before I go further with this I would like your thoughts whether 'Genetic Algorithm' is the right way or is there a better way to go about this.For me each genome is a list of attributes and their corresponding values. Eg. genome 1: Color: Black, Material: wool, thread count:5 genome 2: Color: white, Handwash: yes, Dry clean only: NoIts a mixture of different attributes and their values. Am I going about this the wrong way? | How effective is Genetic Algorithm for finding Attribute-Value relationships | data mining;genetic algorithms | null |