id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_softwareengineering.84542
I'm a very ambitious university student who wishes to learn pretty much everything there is to know about computers (bash me if you want, I love learning). Recently I thought it would be a fun project (albeit a lengthy one) to design and build my own kernel.I got some basic info and I've gathered that I need to master Assembly and C/C++ to really make this work. While I'm working on those, I'd like to learn HOW a kernel actually works from a programming perspective. I've spent hours browsing the linux kernel's code but that can only take you so far.What are the basic steps in building a kernel? Things you need to address? Order or doing things? I know I'm biting off a lot but I'm determined enough to handle it.
Advice for an ambitious student on building your own kernel
c;assembly;kernel
What you need to do is design the operating system. Even if, for example, you decide it should be a UNIX-like system, there are still lots of decisions to make. How much like UNIX do you want it to be? Which parts of UNIX do you like and which do you think need improvement?If you aren't set on its being UNIX-like, you end up with even more questions to answer: should processes form a tree, or are they flat? What kinds of inter-process communication do you want to support? Do you want it to be multi-user, or just multi-tasking (or possibly single-tasking)? Do you want it to be a real-time system? What degree of isolation do you want to provide between tasks? Where do you want it to fall on the monolithic vs. micro-kernel scale? To what degree (if any) do you want it to support distributed operation?I'd generally advise against studying the Linux kernel for your inspiration. That's nothing against the Linux kernel itself, but a simple fact that Linux is intended primarily for production use, not education. It has lots of optimization, backward compatibility hacks, etc., that are extremely useful for production but more likely to distract than educate.If you can find it, a copy of Lion's book (Lions' Commentary on UNIX 6th Edition, with Source Code, by John Lions) is a much easier starting point. 6th Edition UNIX was still small and simple enough to read and understand fairly quickly, without being an oversimplified toy system.If you're planning to target the x86 (at least primarily) you might also want to look at MMURTL V 1.0 by Richard Burgess. This presents a system for the x86 that uses the x86 hardware much more as the CPU designers originally intended -- something most real systems eschew in favor of portability to other CPUs. As you might guess, this tends to be oriented much more heavily toward the hardware end of things. Printed copies seem to be expensive and hard to find, but you can download the text and code for free.Fortunately, there are quite a few more possibilities as well -- Operating System Design and Implementation, by Andrew Tanenbaum and Albert Woodhull, for example.
_cogsci.1624
Most of the times, we associate symmetry with beauty. The symmetry may be in architectural/interior design for instance. Why would this be so ?
Why do humans prefer symmetrical arrangement of objects?
perception;evolution;aesthetics
Indicator of genetic fitness argumentThere is an evolutionary psychology argument. As with most evolutionary psychology arguments, the strength of the evidence is typically a bit fuzzy.Symmetry in many aspects of the human body is functional. Such symmetry might be seen as the natural state that arises from a healthy life and a youthful body. In contrast various genetic abnormalities, diseases, and the like can give rise to asymmetry (e.g., scars, moles, freckles, ageing processes, deformities, etc.). The argument might continue that it is adaptive for us to seek out sexual partners who appear genetically and environmentally fit where symmetry may be one indication of this fitness. One could even extend the evolutionary argument to suggest that it would be adaptive to avoid certain types of diseased individuals in order to reduce the risk of catching some disease, where various forms of asymmetry may be indicative of this.How does this explain our desire for symmetry in physical objects? The perception of beauty in the environment might be seen as an extension of perceptions of beauty in other people. Little and Jones also summarise this perspectiveOne explanation for the preference for symmetrical faces comes from a postulated link to an evolutionary adaptation to identify high-quality mates (see Thornhill & Gangestad (1999) for review). Symmetry in human faces has been linked to potential heritable fitness (goodgenes) because symmetry is a useful measure of the ability of an organism to cope with developmental stress (both genetic and environmental). As the optimal developmental outcome of most characters is symmetry, deviation from perfect symmetry can be considered a reflection of challenges to development. Only high-quality individuals can maintain symmetrical development under environmental and genetic stress and therefore symmetry can serve as an indicator of phenotypic quality as well as genotypic quality (e.g. the ability to resist disease: see Mller (1997) and Mller & Thornhill (1998) for reviews). This logic would lead to a preference for high symmetry mates as evolution will have favoured individuals who had preferences for high-quality mates over low-quality mates. Indeed, morphological symmetry appears to be related to reproductive success in many species, including humans (Gangestad & Thornhill 1997a; Mller & Thornhill 1998). For example, more symmetrical human males have more sexual partners than less symmetrical men (Thornhill & Gangestad 1994) and symmetrical males are also more likely to be chosen as extra-pair partners (Gangestad & Thornhill 1997b). Thus the link between symmetry and attractiveness may reflect that preferences for symmetrical individuals may be potentially adaptive.Perceptual argumentEnquist and Arak (1994) articulate a perceptual clarity argument. They wrote (my bolding):Humans and certain other species find symmetrical patterns more attractive than asymmetrical ones. These preferences may appear in response to biological signals13, or in situations where there is no obvious signalling context, such as exploratory behaviour4,5 and human aesthetic response to pattern68. It has been proposed9,10 that preferences for symmetry have evolved in animals because the degree of symmetry in signals indicates the signaller's quality. By contrast, we show here that symmetry preferences may arise as a by-product of the need to recognize objects irrespective of their position and orientation in the visual field. The existence of sensory biases for symmetry may have been exploited independently by natural selection acting on biological signals and by human artistic innovation. This may account for the observed convergence on symmetrical forms in nature and decorative art.ReferencesEnquist, M., Arak, A. & others (1994). Symmetry, beauty and evolution. Nature, 372, 169-172.Little, A.C. & Jones, B.C. (2003). Evidence against perceptual bias views for symmetry preferences in human faces. Proceedings of the Royal Society of London. Series B: Biological Sciences, 270, 1759-1763. PDF
_softwareengineering.342184
When we mean e-mail payload, are we talking about the whole message provided after DATA command or just the Body part of the message (without headers like From, Subject, Message-ID etc)?S: 220 smtp.server.com Simple Mail Transfer Service ReadyC: HELO client.example.comS: 250 Hello client.example.comC: MAIL FROM:<[email protected]>S: 250 OKC: RCPT TO:<[email protected]>S: 250 OKC: DATAS: 354 Send message content; end with <CRLF>.<CRLF>C: <The message data (body text, subject, e-mail header, attachments etc) is sent>C: .S: 250 OK, message accepted for delivery: queued as 12345C: QUITS: 221 Bye
What is an email payload?
email
19.1.1. email.message: Representing an email messageAn email message consists of headers and a payload (which is also referred to as the content). Headers are RFC 5322 or RFC 6532 style field names and values, where the field name and value are separated by a colon. The colon is not part of either the field name or the field value. The payload may be a simple text message, or a binary object, or a structured sequence of sub-messages each with their own set of headers and their own payload. The latter type of payload is indicated by the message having a MIME type such as multipart/* or message/rfc822.In general, the payload is the part of transmitted data that is the actual intended message. The payload excludes any headers or metadata sent solely to facilitate payload delivery.
_unix.55753
I use getopts to parse arguments in bash scripts aswhile getopts :hd: opt; do case $opt in d ) echo directory = $OPTARG; mydir=$OPTARG; shift $((OPTIND-1)); OPTIND=1 ;; h ) helptext graceful_exit ;; * ) usage clean_up exit 1 esacdoneexeparams=$*exeparams will hold any unparsed options/arguments. Since I want to use exeparams to hold options for a command to be executed within the script (which can overlap with the scripts own options), I want to use -- to end the options passed to the script. If I pass e.g.myscript -d myscriptparam -- -d internalparamexeparams will hold -- -d internalparamI now want to remove the leading -- to pass these arguments to the internal command. Is there an elegant way to do this or can I obtain a string which holds just the remainder without -- from getopts?
How to deal with end of options -- in getopts
bash;getopts
How about:# ... getopts processing ...[[ $1 = -- ]] && shiftexeparams=($@)Note, you should use an array to hold the parameters. That will properly handle any arguments containing whitespace. Dereference the array with ${exeparams[@]}
_unix.279332
I'm new to shell programming and I have created a script that opens a connection to a server of mine. I want to have this script listen for an input from a client node and use that to run a function. This is my process.Run script > opens listener > on second computer use netcat to connect > run a function in the script on the server called nodefunctionI have server_port coded to '4444'File name: run_hangmannc -l -k -v -p 4444 | bash hangmanFile name: hangman#!/bin/bashmsg_timeout=0host_ows=1server_port=4444dubOws=xxx.xxx.xxx.xxxinitServer() { hostIP=`ip -o addr show dev eth0 | awk '$3 == inet {print $4}' | sed -r 's!/.*!!; s!.*\.!!'` hostOws=`echo $hostIP | cut -d . -f 4`} servermsg(){ #message //if = --n, echos on same line if [ $1 != --n ] then echo `date +%T` [SERVER] $1 else echo -n `date +%T` [SERVER] fi}owsmsg(){ #message //if = --n, echos on same line if [ $1 != --n ] then echo `date +%T` [OWS] $1 else echo -n `date +%T` [OWS] fi}playermsg() { if [ $1 != --n ] then echo `date +%T` [PLAYER] $1 else echo -n `date +%T` [PLAYER] fi}question(){ #question, read, example servermsg $1 if [ -n $3 ] then servermsg $3 fi read $2 echo }owsArray(){ # for targetOws in $player_list do owsArray+=(OWS$targetOws) done echo -n ${owsArray[*]} echo}openSocket() { servermsg Starting the Game Listener servermsg Opening Listener on port $server_port #nc -k -l $server_port |bash #nc -kl -q 1 -p $server_port # This should create the listener & This is where everything stops. servermsg Now listening on port $server_port}initServerowsmsg Starting server on OWS$hostOws...question Enter all the OWSs that will play: player_list Example: 1 9 14 23echo $player_listquestion Type a category hint: game_cat Example: Type of Animalquestion Type your word: game_word Example: zebraquestion How many guesses: game_guesses Example: 7servermsg OWS$host_ows has created a Hangman sessionservermsg Players are:; servermsg --n; owsArrayservermsg Your word is ${#game_word} letters long and players have $game_guesses guessesquestion If this is all correct press enter, or CTRL+C to cancelopenSocket# I think I need a While script here to read the RAW input and run the playermsg function with the input?I run the run_hangman file and then I connect to it via my node computer. I enter the following line and echo 1 2 3 because that is what I need. I also can't enter 1 2 3 directly into the window running run_hangman as if I press enter it goes to a new line.echo 1 2 3 >/dev/tcp/xxx.xxx.xxx.xxx/4444The server shows that it connectedListening on [0.0.0.0] (family 0, port 4444)14:52:24 [OWS] Starting server on OWS225...14:52:24 [SERVER] Enter all the OWSs that will play:14:52:24 [SERVER] Example: 1 9 14 23Connection from [xxx.xxx.xxx.xxx] port 4444 [tcp/*] accepted (family 2, sport 41564)Connection closed, listening again.1 2 3Now once it gets to openSocket it will allow me to send one more echo and then it closes on the server. I need to get what I presume is a while statement and have it listen for an input like playermsg 'has started a game' and have it actually run that function on the server.Will I be able to get this to run, almost seems like it has to be in the background? I've been using nc(1) for reference and some websites said to try -d and that didn't work either.
netcat daemon for calling functions in sh script
tcp;daemon;function;netcat
I got it figured out. I did indeed need a while statement.openSocketwhile read -r value; do val=${value:10} if [[ $value == playermsg* ]]; then val=${value:10} playermsg $val elif [[ $value == servermsg* ]]; then val=${value:10} servermsg $val else echo Returned $value echo Value was $val fidoneSo now on the second computer I simply runecho playermsg testing >/dev/tcp/xxx.xxx.xxx.xxx/4444Then the server displays the following:15:29:36 [SERVER] Starting the Game Listener15:29:36 [SERVER] Opening Listener on port 444015:29:36 [SERVER] Now listening on port 444015:29:37 [PLAYER] testing
_unix.7556
Some people told me FreeBSD is NOT Unix, is that right? I'm confused.I checked some articles, but the expressions are pretty vague, and I need some clarification.
Some people told me FreeBSD is NOT Unix, is that right? Confused
freebsd
It all come down to whether you are speaking legally, or from a technology viewpoint. Legally, FreeBSD, like Linux, cannot use the trademarked term Unix. From a technology point of view, FreeBSD is as much Unix as Solaris, HP-UX, or any of the other commercial versions that have paid to be able to be legally called Unix.
_unix.166465
I have this really typical problem. I have an XML file that I have to post to a server. I was told by the network engineer of that site to use the cURL function. The function that he provided to me was...curl --data-binary @/opt/somefile.xml http://1.2.3.4/gateway/submit?source=FOO&conversationid=1234567When I run this command I keep getting the error Bad URL, returning 400 statusI have been stuck on this problem for quite a while now and I am getting seriously frustrated. I have tried running...curl http://1.2.3.4/gateway/submit?source=FOO&conversationid=1234567and I am getting a response from the machine Test Message along with some identification parameters of the host system. What this would probably mean that the URL of the destination is OK and it is being accessed via the cURL command. Are there any special requirements for sending XML files via --data-binary?Does the XML need to be formatted in a special way?Is the syntax of the cURL command incorrect?
Posting XML through cURL using --data-binary
curl
The & is interpreted by the shell you should use quotes (') around the URL:curl --data-binary @/opt/somefile.xml 'http://1.2.3.4/gateway/submit?source=FOO&conversationid=1234567'
_codereview.15640
Please comment on the same. How can it be improved?Specific improvements I am looking for:Memory leaksC++ styleMaking code run fasterRAII#include<iostream>#include<algorithm>template <typename T>class Stack {private: T* array_; int length_; T* last_; void expandArray();public: Stack(int length = 8) : array_(new T[length]), length_(length), last_(array_) {} Stack<T>& push(const T&); Stack<T>& pop();};template<typename T>void Stack<T>::expandArray() { T* array_temp = new T[length_ << 1]; std::copy(array_, array_ + length_, array_temp); std::swap(array_, array_temp); delete[] array_temp; last_ = array_ + length_ - 1; length_ <<= 1;}template<typename T>Stack<T>& Stack<T>::push(const T& data) { if (last_ == (array_ + length_ - 1)) { expandArray(); } last_[0] = data; last_++; std::cout << [ << data << ] pushed. << std::endl; return *this;}template<typename T>Stack<T>& Stack<T>::pop() { if(array_ != last_) { last_--; std::cout << [ << last_[0] << ] popped. << std::endl; } else { std::cout << Nothing to pop. << std::endl; } return *this;}int main() { Stack<std::string> s; s.push(std::string(a)) .push(std::string(b)) .push(std::string(c)) .push(std::string(d)); s.pop().pop().pop().pop().pop();}
Stack implementation using arrays
c++;array;stack
First of all, I would specify that your stack is using a dynamically allocated array, as opposed to just an array, as I at first expected a C array when looking at the title. That varies from person to person, though.On to more important things:I would not print anything in the stack functions. If someone wants information on what they're pushing and popping, let them do it themselves.You seem to be missing a peek function.Either throw an exception or add an assert to pop for the array_ == last_ case.length_ should actually be called capacity_.expandArray may leak memory if the copy throws. I would use an std::vector<T*> internally for this stuff.You don't check that length > 0 in the constructor.I would not allocate so anything by default.You lack all three of a copy constructor, assignment operator, and destructor, so you'll definitely leak memory. You should also have a move constructor and a move assignment operator, but those aren't as critical.You provide no way to check whether the stack is empty.
_unix.163964
I'm trying to assign some variables from a lookup file with a shell script.I have something working but it seems unnecessary slow.Script:while read line do code=`echo $line | awk -F' ' '{print $1}'`; device=`echo $line | awk -F' ' '{print $2}'`; state=`echo $line | awk -F' ' '{print $3}'`; if [[ $code == $message ]] then echo Translated: $device-$state; fidone <CODE-LIST.txtCODE-LIST.txt:MQTT-CODE DEVICE STATE1-1-32-16236607 RGB_LED ON1-1-32-16203967 RGB_LED OFFIs there a faster way to do this? (Maybe awk or sed)Thanks for the help!
Shell script to assign values from a lookup table is too slow
linux;shell script;sed;awk;string
How about:while read code device state junk; do if [[ $code == $message ]]; then echo Translated: $device-$state fidone <CODE-LIST.txtUsing extra processes (i.e. forking awk everytime) will slow it a lot. read will read multiple fields, separated by $IFS (default value is all white space). The last variable listed will receive the rest of the line if any.I'm just wondering where $message is supposed to come from. Outside the code snippet perhaps?EDIT:If the code part will only occur once in the input, then you can break out of the loop once it's been found, that will speed things up as well.
_unix.169886
I'm using less to parse HTTP access logs. I want to view everything neatly on single lines, so I'm using -S.The problem I have is that the first third of my terminal window is taken up with metadata that I don't care about. When I use my arrow keys to scroll right, I find that it scrolls past the start of the information that I do care about!I could just delete the start of each line, but I don't know if I may need that data in the future, and I'd rather not have to maintain separate files or run a script each time I want to view some logs.ExampleThis line:access.log00002:10.0.0.0 - USER_X [07/Nov/2013:16:50:50 +0000] GET /some/long/URLWould scroll to: ng/URLQuestionIs there a way I can scroll in smaller increments, either by character or by word?
Horizontal scrolling in smaller increments with less -S
less;scrolling
The only horizontal scrolling commands scroll by half a screenful, but you can pass a numeric argument to specify the number of characters, e.g. typing 4 Right scrolls to the right by 4 characters. Less doesn't really have a notion of current line and doesn't split a line into words, so there's no way to scroll by a word at a time.You can define a command that scrolls by a fixed number of characters. For example, if you want Shift+Left and Shift+Right to scroll by 4 characters at a time:Determine the control sequences that your terminal sends for these key combinations. Terminals send a sequence of bytes that begin with the escape (which can be written \e, \033, ^[ in various contexts) character for function keys and keychords. Press Ctrl+V Shift+Left at a shell prompt: this inserts the escape character literally (you'll see ^[ on the screen) instead of it being processed by your shell, and inserts the rest of the escape sequence. A common setup has Shift+Left and Shift+Right send \eO2D and \eO2C respectively.Create a file called ~/.lesskey and add the following lines (adjust if your terminal sends different escape sequences):#command\eO2D noaction 4\e(\eO2c noaction 4\e)Then run lesskey, which converts the human-readable ~/.lesskey into a binary file ~/.less that less reads when it starts.
_unix.84116
AFAIK, support for the xVM Hypervisor - basically Xen - has been dropped in Solaris 11. Is there an alternative/replacement for it? How does it compare to Xen?Obviously there is zones if you want to run Solaris, and there is VirtualBox if you want a virtual computer in a separate program. But is there anything similar to Hypervisor/Xen?
Solaris11: Alternative to xVM Hypervisor?
solaris;virtual machine;virtualization
For running Solaris in dom0, no. Oracle has euthanized it. xVM worked on Solaris 10 but it broke during the development cycle of OpenSolaris (it's completely broken and unusable on snv_134, but probably earlier). Neither Oracle nor the Illumos community has shown any interest in getting a Solaris kernel running in dom0.Oracle's replacement product is OracleVM. On Sparc that means Solaris LDOMs. On x86 that means Xen with Oracle Linux in dom0.In the Illumos community, Joyent has ported Linux's KVM to the Illumos kernel. It's available at least from SmartOS, but I believe it's also available in OpenIndiana and OmniOS**.If you want Xen I suggest Debian. If you want ZFS* I suggest OmniOS or SmartOS and use KVM.* FreeBSD still can't run dom0.** As years have passed, KVM is available in most, if not all illumos distributions and Joyent has resurrected LX-brand zones as part of SmartOS and are now also in OmniOS.
_unix.260128
Just installed Nagios on SERVER (10.20.8.106) and attached a CLIENT (10.20.10.11). So I defined my host and and a service for check_nrpe. It is working. So I have check_nrpe plugin in the plugins(/usr/lib64/nagios/plugins/) directory of SERVER and CLIENT. I didn't know which check_nrpe was executed.On the SERVER:$/usr/lib64/nagios/plugins/check_nrpe -H 10.20.10.11NRPE v2.15On the CLIENT:$usr/lib64/nagios/plugins/check_nrpe -H 10.20.8.106connect to address 10.41.8.106 port 5666: No route to hostconnect to host 10.41.8.106 port 5666: No route to hostThe above confirmed to me that the check_nrpe plugin in SERVER's plugin directory was executed. So why do we have the plugins directory in the CLIENT? At first I thought, SERVER executes them from the plugin directory of CLIENT. And the plugins at SERVER side were used for doing checks on the same machine.I am confused at this moment.Can anybody clarify.
Nagios plugins are executed from server plugins or client plugins?
nagios;nrpe
We have the plugins directory in the monitored host (CLIENT), because you installed the nagios plugins.Nagios monitoring host executes the check_nrpe plugin specified for example as the following command:$USER1$/check_nrpe -H $HOSTADDRESS$ -c check_disk$HOSTADDRESS$ is the IP address of your CLIENT machine (monitored host).On the monitored host the nrpe daemon runs on default port 5666 and when it receives the command from the Nagios server, it checks its config file for the corresponding command in /etc/nagios/nrpe.cfg:command[check_disk]=/usr/lib64/nagios/plugins/check_disk -e -m -w 20% -c 10%As you can see the /usr/lib64/nagios/plugins/check_disk is needed on the monitored host to check the available disk space. The Nagios server dosen't execute the check_disk plugin, instead it asks the monitored host to execute it and to reply with results.
_softwareengineering.139488
I currently have a web application and I would like to add a messaging feature to it.In order to do that, I use JMS(actually OpenMQ, the implementation provided with Glassfish 3).The problem is that I do not know how to get the message notification from the background(from the listener) to the foreground.I am using JSF as a framework, if it does have an importance.Could you please tell me how should I notify the user about a received message(like a chat).Any suggestions are welcomed.
How to get JMS to front end
java;message queue;messaging
You may be interested in Comet, a programming model that allows the server to push data to a client. There are implementations for JSF, look at this blog post about Richfaces integration for an example.HTML 5 specifies WebSockets that can be used for server push, but not all browsers support it.The simple alternative is to simply poll the server at regular intervals, that might create a lot of unnecessary messages though.
_webapps.28158
Why my Facebook profile says I have 155 friends but I'm only seeing 150 when I ran thishttp://www.peacegig.com/facebook-apps/backup-friends/index.php?zip-request=trueI saw unknown person list as Facebook friend I can't even unfriend nor block. What's going on with Facebook?
Why my Facebook profile says I have 155 friends but I'm only seeing 150? I saw fake a friend but now can't see
facebook
null
_webapps.4279
Traditionally, you backup your computer's data to the web, but anyone who uses a lot of webapps puts a lot of data out there. Is there a good tool to backup all my gmail mail, facebook pictures and status updates, google docs, etc. to my computer? Preferably automatically.
Is there a good tool to backup the data from all my webapp accounts to my computer?
webapp rec;backup;download;data liberation
null
_unix.271872
Trying to install Arch Linux on a partition of my hard drive, my only option is to connect to Internet with WiFi. Ubuntu (on another partition) shows with lspci that WiFi chip-set is Broadcom BCM4311 and lspci -k shows Ubuntu is using ssb module and b43-pci-bridge driver which works fine.Arch Linux bootable USB with lspci -k shows that it is using the same module and driver but ifconfig shows no wireless interface. Here it is mentioned that BCM4311 works with b43-firmware-classic from AUR. Now, how can I install b43-firmware-classic to use my wireless chip-set, before even installing Arch Linux itself. I ran git clone on Ubuntu and downloaded Arch Linux b43-firmware-classic from AUR on my Ubuntu root partition. However I'm not sure where to go from there.
Install Arch Linux with wifi but wifi chipset not detected
arch linux;broadcom
null
_scicomp.23654
The lifting operator $\mathbf{r}(\mathbf{v_h})$ for the '2nd version' of Bassi-Rebay scheme for elliptic problems in $d$ dimensions is defined as$$\int_{\Omega_h} \mathbf{w}_h \cdot \mathbf{r}(\mathbf{v}_h)\,\mathrm{d}\mathbf{x} = -\int_{E} \{\mathbf{w}_h\}\cdot \mathbf{v}_h \,\mathrm{d}S, $$ where$$\mathbf{v}_h \in \mathbf{V}_h,\:\mathbf{w}_h \in \mathbf{V}_h\\V_h = \{v_h \in L^2(\Omega_h) : \bigl. v_h\bigr|_K\in \mathbb{P}_k(K) \:\forall K\in \mathcal{T}_h\}\\\mathbf{V}_h = \{v_h \in \bigl(L^2(\Omega_h)\bigr)^d : \bigl. v_h\bigr|_K\in \bigl(\mathbb{P}_k(K)\bigr)^d \:\forall K\in \mathcal{T}_h\},$$and $E$ is an edge of element belonging to triangulation $\mathcal{T}_h$.The weak form for Laplace equation discretized with BR2 then contains terms such as$$\int_{\Omega_h} \bigl(\nabla v_h\bigr) \cdot \mathbf{r}\bigl([\![u_h]\!]\bigr)\,\mathrm{d}\mathbf{x},\quad u_h, v_h \in V_h,$$for which the definition of the lifting operator can be used to convert the integral over $\Omega_h$ into surface integral over element edge.There are also face terms such as$$\int_{E} [\![v_h]\!] \cdot \mathbf{r}\bigl([\![u_h]\!]\bigr)\,\mathrm{d}S.$$How should these be evaluated? The only approach I can think of is to use the definition of the lifting operator with all test functions $\mathbf{w}_h$ belonging to one element in order to assemble a local linear system where the expansion coefficients of $\mathbf{r}(\mathbf{v}_h)$ are unknowns (i.e. I would assume that $\mathbf{r}(\mathbf{v}_h)$ can be represented as a linear combination of basis functions). If I do that, then I can work with the lifting operator restricted to element traces. This seems to be a bit strange to me though and I'm afraid I completely missed the point.Remark - notation:Let $E$ be an internal edge shared by two elements $K^{+}$ and $K^{-}$ and let $\mathbf{n}^{+}$ and $\mathbf{n}^{-}$ be outer normals of $K^{+}$ and $K^{-}$ on this edge. The jump $[\![\cdot]\!]$ and average $\{\cdot\}$ operators are defined as follows:$[\![v_h]\!] = v_h^{+}\mathbf{n}^{+} + v_h^{-}\mathbf{n}^{-}$ for $v_h \in V_h$$[\![\mathbf{v}_h]\!] = \mathbf{v}_h^{+} \cdot \mathbf{n}^{+} + \mathbf{v}_h^{-} \cdot \mathbf{n}^{-}$ for $\mathbf{v}_h \in \mathbf{V}_h$$\{v_h\} = \frac{1}{2}(v_h^{+} + v_h^{-})$, $v_h \in V_h$$\{\mathbf{v}_h\} = \frac{1}{2}(\mathbf{v}_h^{+} + \mathbf{v}_h^{-})$, $\mathbf{v}_h \in \mathbf{V}_h$The superscript ${}^{\pm}$ refers to trace quantities restricted to edge (face in 3D) from $K^{+}$ and $K^{-}$, respectively.
Discretization of lifting operator in BR2 scheme
finite element;discontinuous galerkin
That seems to be the right way to solve for the lifting operators, see for example Appendix A in Discontinuous Galerkin methods for the Navier-Stokes equationsusing solenoidal approximations by Montlaur et al (there is also an authors copy if you search for the title), it is for the Compact DG Method but as far as I'm aware all of the lifting operators are equivalent up to some small change to modify the behavior slightly (e.g. CDG is a compact modification of the Local Discontinuous Galerkin method)
_unix.251021
I tried to install fedora 23 on dual-boot with an usb stick today, I followed this video tutorial : https://www.youtube.com/watch?v=gOP_FtP1e9UI'm in UEFI mode, so I installed fedora and everything worked perfectly until I had to reboot, then I got this error:Reboot and Select proper Boot device or insert Boot Media in selected Boot Device and press a key. I searched a lot for this error and it seems that a lot of people have problems with it. So I tried to resolve it by restarting my computer, going into the BIOS settings and changing the order of my boot device so my hard disk was in first place and my CD/DVD was in second place, I saved and restarted, it didn't work.I also tried to put the CD/DVD in first place and it didn't work either, my BIOS version is 2.15.1227. I can only put my usb stick back and load fedora in live mode, so I tested the command to see in wich mode I am and I am still in UEFI. Here is my boot order : I disabled the secure boot and the hibernation mode is on.Even after changing the boot order, I still get the error, I don't know what to do, any help would be appreciated,regards.EDIT : I finally solved it by reInstalling Fedora in the right mode (UEFI) thanks to lakedevu
Booting problem after trying to dual boot fedora 23 and windows 8.1 [SOLVED]
fedora;boot;windows;bios
I assume Fedora OS has been successfully installed according to your context of question, but it's unable to boot properly. I had this issue a while ago to dual boot between Windows 10 and Mint Linux too. Try to set your HDD in highest priority in boot sequence as Fedora has been partitioned on your HDD - it has to look into HDD first to find the boot loader. Also, try to look for 'secure boot' option on the BIOS settings and ensure to have it 'disabled' because UEFI mode mandates secure boot enabled in Windows 8 or later versions. additional option to try:Above is my BIOS settings. I have 'Quiet Boot' set to Enabled. Last option could be fixing your boot loader file by using 'boot repair', not sure if it's compatible with Fedora OS as I've only seen articles regarding Ubuntu based OS. I really hope you have this issue resolved, but if not by above methods, you can search google about dual-boot in UEFI mode and ensure to have everything set up correctly.
_unix.144480
I believe I have installed multiple packages that use the same shell command to run. I know one of them, but I only vaguely recall installing the other and thus cannot uninstall it. I believe they're causing issues with each other, so I need to uninstall the one that I can't remember. Is there a simple way to find which package is invoked using a certain shell command? This is on RHEL 6.5.
Find package that uses a specific shell command
rhel;package management
Try:yum whatprovides <command>From man yum:provides or whatprovides Is used to find out which package provides some feature or file. Just use a specific name or a file-glob-syntax wildcards to list the packages available or installed that provide that feature or file.Example:yum whatprovides /bin/lscoreutils-5.97-34.el5_8.1.x86_64 : The GNU core utilities: a set of tools : commonly used in shell scriptsRepo : baseMatched from:Filename : /bin/lscoreutils-5.97-34.el5_8.1.x86_64 : The GNU core utilities: a set of tools : commonly used in shell scriptsRepo : installedMatched from:Other : Provides-match: /bin/ls
_unix.132371
I have a jar file which I need to run at startup in all distros of Linux. My previous question here, gave me an idea a rough idea on X-servers. Since I wasn't able to perform startup, I moved on to the idea of adding a .desktop file to /etc/xdg/autostart. This works for ubuntu and I am currently testing it in Linux Mint both cinnamon and mate versions. I did a small research for other distros but they don't seem to have the /etc/xdg/autostart instead they have /xdg-autostart but I need to run my jar file in all distros of Linux. I tried crontab but @reboot didn't work in ubuntu 14.04 for me. Another problem is I need to remove the file I am placing to startup when I uninstall the jar. If I edit rc.local, I won't be able to revert the edit. Is there a common way in which I can do startup in Linux
Run jar on startup in all *nix based systems
linux;shell;shell script;java;startup
There is no universal method for creating a system service on all GNU/Linux distros, since they use a variety of init systems. Once upon a time they all used more or less the same SysV style init (excepting some which used a more BSD style system), which allowed for the writing of generic init scripts that would require little modification from distro to distro.Currently, SysV is still used by a number of distros, such as Debian and RHEL / CentOS. However, the newer init systems -- systemd (Fedora, Arch, et. al.) and upstart (Ubuntu)1 do include mechanisms for backward support of SysV style init scrips, so if you are looking for the method most easily adopted for use on the most systems, that is still it.Keep in mind that linux is not an operating system in the sense that Windows 8 or OSX are operating systems. Linux is an OS kernel used on a wide variety of platforms (e.g., Android); colloquially GNU/Linux refers to the collection of OS distributions discussed above, but these are not all the same. There is no serious intention or desire to unify these, just as there is no serious intention or desire to unify Windows and OSX so that, e.g., someone could ask How can I run my jar file at start up on both OSX and Windows? -- you are out of luck, you will need to package it separately for each of them. That is, in fact, how software in the linux world generally is distributed; there are separate packages for each and every distro.1 BUT Ubuntu (and Debian) are moving to systemd, meaning upstart will likely disappear, and most of the major distros will have a common init system.
_cstheory.9625
I was considering the following game on an undirected unweighted graph $G=(V,E)$ (not necessarily simple). Two players, Police and Runaway, take moves in turn. Police can cut an arbitrary subset of edges in a single move and Runaway can move from a current vertex to an adjacent vertex (cutting an edge means that corresponding vertices became not adjacent). Runaway starts at vertex $s$ and wants to make it into vertex $t \neq s$; Police wants to interfere her. Police move first. Let the game cost for Police be equal to the number of cutted edges. An $s-t$ minimal cut size is an obvious upper bound for this value, but sometimes Police can do better. For example, consider a $K_{n,2}$ graph ($n > 2$) where $s$ and $t$ both belong to the smaller (second) part. Minimal cut between $s$ and $t$ equals $n$, though cutting only 2 edges is enough (Police cuts empty set on her first move hence forcing Runaway to move away from $s$, then she cuts 2 edges adjacent to Runaway's location). Efficient computation of that cost seems to be an interesting problem.I came up with a clumsy (still polynomial-time) algorithm which basically does loads of min-cut computations on $G$ subgraphs for this (however I'm not completely sure in the correctness). I wonder if it is a known problem or not, maybe there is some elegant solution? Please provide any related info.
Graph connectivity related game
ds.algorithms;graph theory;graph algorithms;gt.game theory;max flow min cut
null
_unix.266614
This is a question I have from the first day I've heard about open source codes. We see new versions of Linux kernel once in a while, means that people are still working on it. Who are these developers and who pays them and why someone pays developer to develop something free?
If Linux is open source, how its developers get paid?
linux;open source
It depends on what code you're talking about. The difference between most proprietary software and FOSS is that FOSS is developed by stakeholders rather than a single proprietor. Hardware companies want to sell more hardware so they contribute code to help make Linux work on their products to increase the value for the consumer. Administrative stuff can be developed out in the community (like the initial versions of OpenStack were, and how cgroups came out of google) or it can be created by companies that sell consultation, training, and support (such as with Docker, most databases, most commercial distros, etc). There are also the odd random contributions by government agencies, academic researchers, and what have you. Along with just random people who know how to code and want to be able to say they contributed something to a successful project.Appliance vendors seem like they would want to contribute upstream but I don't know if that's actually common practice. It would be interesting to see what companies like F5 and Citrix would develop.The nonprofit behind the Linux kernel even publishes a detailed report of who contributes and how much.
_unix.115110
I am trying to run an incremental search using lynx.Imagine a page, for example, an index_of page which contains several folders which also contain other subfolders and files. I want to run lynx in a way that I can enter automatically in each folder/page and search for a string, so it returns me the link which contains the string found. For example, if I am looking for a specific datasheet in http://datasheets.chipdb.org/ so I would try something like find . -name mydatasheet.pdf |lynx -dump http://datasheets.chipdb.orgbut that I could run in all subfolders recursively. Maybe some grep or whatever.How could it be done?
Lynx incremental search
grep;find;search;lynx
Maybe I don't understand your question but if I were trying to find a link to a pdf file I would write a python script. Something like:#!/usr/bin/env pythonimport urllib2import refrom bs4 import BeautifulSoupdef find_links ( url ): try: soup = BeautifulSoup(urllib2.urlopen( url ).read()) except: return links = soup.findAll( a ) for link in links: pdfurl = link.get('href') m = re.search( ^\?, pdfurl) if m: continue m = re.search( .pdf$, pdfurl) if m: print Found a pdf in %s/%s % (url, pdfurl) else: find_links( %s/%s % ( url, pdfurl) )find_links( http://datasheets.chipdb.org )Or a Perl script that uses WWW::Mechanize.
_codereview.17923
Is this the best way to check if two floating point numbers are equal, or close to being equal?template <class T>bool IsEqual(T rhs, T lhs){ T diff = std::abs(lhs - rhs); T epsilon = std::numeric_limits<T>::epsilon( ) * std::max(std::abs(rhs), std::abs(lhs)); return diff <= epsilon ;}
Checking if two floating point numbers are equal
c++;floating point
No, not really. You want a third parameter that gives an acceptable difference -- this can be number of decimals, percent of value, or a fixed value, but it needs to be coming from outside to really be useful.A function that does it with a constant diff, might be useful in some limited circumstances, but not generally.
_unix.267544
I am running a Centos7 server with rsyslog for logging. The service is on (sudo systemctl is-enabled rsyslog) outputs enabled. I have also configured the service to start at boot-time. However, the /var/log/secure file is still empty despite deliberate attempts to fail SSH login. The other log files (mailer, spool, cron except messages) are all also empty.Where am I going wrong in this? Any help is welcome.Update:Output of ls -ld /var/log:drwxr-xr-x. 11 root root 4096 Mar 4 11:06 /var/logand output of ls -l /var/log:drwxr-xr-x. 2 root root 6 Oct 7 17:53 anacondadrwxr-x---. 2 root root 94 Mar 4 13:39 audit-rw-r--r--. 1 root root 549 Nov 30 16:33 boot.log-rw-------. 1 root utmp 0 Mar 1 03:13 btmp-rw-------. 1 root utmp 1920 Feb 11 15:25 btmp-20160301drwxr-xr-x. 2 chrony chrony 6 Nov 24 03:05 chrony-rw-r--r--. 1 root root 14056 Nov 30 16:33 cloud-init.log-rw-r--r--. 1 root root 34623 Mar 4 10:19 cloud-init-output.log-rw-r--r--. 1 root root 0 Feb 28 03:40 cron-rw-r--r--. 1 root root 0 Feb 1 03:09 cron-20160207-rw-r--r--. 1 root root 0 Feb 7 03:09 cron-20160214-rw-r--r--. 1 root root 8948 Feb 18 21:01 cron-20160223-rw-r--r--. 1 root root 0 Feb 23 12:41 cron-20160228-rw-r--r--. 1 root root 35746 Mar 4 10:19 dmesg-rw-r--r--. 1 root root 35859 Mar 3 11:48 dmesg.old-rw-------. 1 root root 1948 Dec 29 12:08 grubbydrwx------. 2 root root 4096 Mar 1 20:14 httpd-rw-r--r--. 1 root root 292876 Mar 4 15:59 lastlog-rw-------. 1 root root 0 Feb 28 03:40 maillog-rw-------. 1 root root 0 Feb 1 03:09 maillog-20160207-rw-------. 1 root root 0 Feb 7 03:09 maillog-20160214-rw-------. 1 root root 3583 Feb 18 19:07 maillog-20160223-rw-------. 1 root root 0 Feb 23 12:41 maillog-20160228-rw-------. 1 root root 120630 Mar 4 10:49 messages-rw-------. 1 root root 0 Feb 1 03:09 messages-20160207-rw-------. 1 root root 0 Feb 7 03:09 messages-20160214-rw-------. 1 root root 42189 Feb 18 21:03 messages-20160223-rw-------. 1 root root 0 Feb 23 12:41 messages-20160228drwxr-xr-x. 2 ntp ntp 6 Jan 25 19:57 ntpstatsdrwx------. 2 root root 6 Jun 10 2014 pppdrwxrwxrwx. 3 root root 25 Nov 30 16:55 rsyslog_custom-rw-------. 1 root root 0 Feb 28 03:40 secure-rw-------. 1 root root 0 Feb 1 03:09 secure-20160207-rw-------. 1 root root 0 Feb 7 03:09 secure-20160214-rw-------. 1 root root 17991 Feb 18 20:20 secure-20160223-rw-------. 1 root root 0 Feb 23 12:41 secure-20160228-rw-------. 1 root root 0 Feb 28 03:40 spooler-rw-------. 1 root root 0 Feb 1 03:09 spooler-20160207-rw-------. 1 root root 0 Feb 7 03:09 spooler-20160214-rw-------. 1 root root 0 Feb 14 03:34 spooler-20160223-rw-------. 1 root root 0 Feb 23 12:41 spooler-20160228-rw-------. 1 root root 0 Oct 7 17:43 tallylogdrwxr-xr-x. 2 root root 22 Dec 9 18:55 tuned-rw-rw-r--. 1 root utmp 241152 Mar 4 15:59 wtmp-rw-------. 1 root root 1926 Mar 4 13:20 yum.log-rw-------. 1 root root 13145 Dec 29 16:02 yum.log-20160101
/var/log/secure and other log files are empty even after restarting rsyslog.service
logs;rsyslog
null
_unix.109918
I had followed a tutorial to install Linux Mint 16 Cinnamon and it works perfectly fine, currently using it to post this question. But when grub loads the only 3 options I am given, are Linux Mint, Linux Mint (Compatibility Mode) and system startup. My computer has come pre-installed with windows 8 on it, both the recovery and windows partition are still visible on the disk usage analyzer. When I installed Linux I had legacy mode turned on but if I turn it off, Linux still works fine.I've tried the sudo update-grub command and it reads as followsGenerating grub.cfg ...Found linux image: /boot/vmlinuz-3.11.0-12-genericFound initrd image: /boot/initrd.img-3.11.0-12-generic No volume groups foundAdding boot menu entry for EFI firmware configurationdoneI would still like to dual boot Linux alongside Windows, what do I need to do to achieve this?
Windows 8.1 not appearing on grub after Linux Mint 16
linux;boot;windows
null
_codereview.158921
I have two local maven projects A, and B. B is dependent on A. A|- resources/log4j2.xmlB|- resources/META-INF/log4j.xml|- Maven Dependencies |- A |- And other dependencies...Both A, and B exports the log4j xmls to jar. However, as I only need the B/resources/META-INF/log4j.xml to my final B.jar, I tried to delete the log4j2.xml from A while packing B.jar. To do the same, I used truezip:remove in B/pom.xml as follows:<build>...<plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>truezip-maven-plugin</artifactId> <version>1.1</version> <executions> <execution> <id>remove-a-file-in-sub-archive</id> <goals> <goal>remove</goal> </goals> <phase>verify</phase> <configuration> <fileset> <directory>B-jar-with-dependencies.jar</directory> <includes> <include>log4j2.xml</include> </includes> </fileset> </configuration> </execution> </executions> </plugin></plugins>...</build>Note that this is executed verify state (post packaging) of lifecycle.Though it is working as expected, I am wondering whether there is any side-effect of this or not. Any light in this regard would be great.
Excluding resources from maven dependencies while exporting project to jar
java;maven
null
_datascience.22138
I have graph data which has 250 million nodes and over 500 million edges. My files are roughly 230GB is size, this includes the node and edge files.I am having major difficulties visualising the data. By visualisation I mean, generating aesthetic plots. The data has attributes such as node number, name, total money going in, total money going out and edges. I'd like to use such attributes to help generate colourful plots that signify groups and communities. I have already tried NetworkX, Pandas, Neo4J, Gephi and R-Studio. All of which crash and are unable to do anything on my data.Can anyone please recommend alternatives to create such visualisations?
How to visualise very large graphs with 250M nodes and 500M+ edges?
dataset;bigdata;visualization;data
null
_webmaster.43223
I was going through Webmaster Tools and I noticed that under 'links to your site' there's only 40 links showing. Down from 700+ yesterday. I don't think it was anything to do with the quality of the sites linking in because some of them were quite high ranking blogs so I don't think it's Penguin related. This has happened to me once before on a previous site and after about a month or so they came back, so it's not something I'm super worried about, but it's really odd. Has anyone else experienced this? Or know why it happens?Update - All links seem to have returned 20/2/13
90% of 'links to your site' disappeared in Google Webmaster Tools
google;google search console
Its not just you. Here is a thread about the problem on WebmasterWorld: http://www.webmasterworld.com/google/4542427.htmHere is a thread about it in the Google webmaster help: http://productforums.google.com/d/topic/webmasters/HB8ZdK_DDyw/discussionThis issue has been forwarded to Google engineers who are apparently looking into a problem with the webmaster tools.Update: Search Engine Roundtable is reporting that Google has fixed this bug as of February 12, 2013. http://www.seroundtable.com/google-webmaster-tools-links-back-16349.htmlhttp://www.seroundtable.com/google-webmaster-tools-links-back-16349.html
_codereview.37684
I want to extract some values in i-commas() from lines like this: <P k=9,0,1 vt=191 v=100.99936 z= />Example:getCharVal ( cp, char k=\, 9)where cp is a pointer the line above should return 9,0,1The function:#define ENDTAG />#define ICOMMAS ''char * getCharVal ( char *cp, char *att, size_t s){ char * val; char * endTagP; if (cp == NULL)return NULL; cp = strstr(cp, att)+strlen(att); if (cp == NULL) return NULL; char * endP = strchr(cp, ICOMMAS); if (endP == NULL) return NULL; endTagP = strstr(cp, ENDTAG); if (endTagP == NULL) return NULL; if (endP > endTagP) return NULL; size_t valsize = endP - cp ; if (valsize > s) return NULL; val = malloc(valsize + 1); memcpy (val, cp, valsize); val[valsize]='\0'; cp = endTagP; return val;}This code is ugly. Could anyone give me hints on how to write it better?
Small function for getting character value
c;strings;parsing;xml
I've modified your code to make it more normal C99, including adding constto parameters that your function does not change, improving (to my taste) thevariable names, moving variable definition to the point of their first use andusing strndup to duplicate the tag (not universally available but easilywritten).char *getCharVal(const char *ch, const char *att, size_t size){ if (!ch) { return NULL; } ch = strstr(ch, att); if (!ch) { return NULL; } ch += strlen(att); char *end = strchr(ch, ''); if (!end) { return NULL; } char *endTag = strstr(ch, ENDTAG); if (!endTag) { return NULL; } if (end > endTag) { return NULL; } size_t valSize = end - ch; if (valSize > size) { return NULL; } return strndup(ch, valSize);}Note also that yourcp = strstr(cp, att)+strlen(att);if (cp == NULL) return NULL;will never fail because even if att is not found you have added its lengthto the NULL pointer that strstr would return.A beneficial change would be to omit the check for size (although perhaps yourapplication is such that this check is more necessary than it appears).Finally, I think your interface is ugly. It would be much cleaner to pass thethe pure attribute k. However, I can see that passing k=\ is anoptimisation that makes the function much simpler to implement.
_vi.2764
Recently there was an add-on to NeoVim which allows opening terminal in a vim buffer. This has appealing possibilities to send text from one vim window to another replicating, for example, a REPL like behavior.In the past I was using tmux for this kind of configuration. However now I would like to try it out using only NeoVim.My question is - how can I send a block of text from one vim split to another? Or maybe rather - how can I automate the sequence of selecting text, yanking it, changing splits and then pasting?
Send text from one split window to another
split;vim windows;neovim
Basically when you have text selected, you want to remap a key sequence to copy, switch to terminal, paste, and then possibly switch windows back and reselect the text. If you have two splits open, this would look something like:vnoremap <F5> y<c-w>wp<c-w>pgvexplanation:xnoremap <F5> Remap F5 in visual/select mode (could be any key combo) y copy selected text <c-w>w switch to next window p paste (for terminals this sends the text to the terminal) <c-w>p switch to previous window gv reselectIf there are more than two splits and the terminal is not the one after where your text is selected, you'd want to either use a different mapping that works for your layout (i.e. <c-w>t moves to the top left window) or you'd want to write a function that loops through all windows and finds the right one.
_datascience.22101
As I am new to TensorFlow, I would like to do image recognition in TensorFlow using Python. For this Image Recognition I would like to train my own image dataset and test that dataset. Please answer me how to train a dataset and how to select the dataset..
How to train an image dataset in TensorFlow?
python;dataset;tensorflow;training;image recognition
null
_webmaster.48497
I am getting my hands wet with ASP and I have been following the tutorials. I deployed the site and in Azure and it worked great. Today I started actually designing the site. And when I published, it looks as if it doesn't read any of the files I just updated, added, and modified. It works on my localhost, but not in the Azure. I thought when you publish, everything goes up, including the new files.I don't have enough reputation to add a picture so, you'll forgive me.SO, basically, how do I get my entire site uploaded?In case anyone does stop by, I was able to pull this out just recently:CA0058 Error Running Code Analysis CA0058 : The referenced assembly 'DotNetOpenAuth.AspNet, Version=4.0.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246' could not be found. This assembly is required for analysis and was referenced by: C:\Users\lotusms\Desktop\LOTUS MARKETING\ASP.NET\WebsiteManager\WebsiteManager\bin\WebsiteManager.dll, C:\Users\lotusms\Desktop\LOTUS MARKETING\ASP.NET\WebsiteManager\packages\Microsoft.AspNet.WebPages.OAuth.2.0.20710.0\lib\net40\Microsoft.Web.WebPages.OAuth.dll. [Errors and Warnings] (Global)CA0001 Error Running Code Analysis CA0001 : The following error was encountered while reading module 'Microsoft.Web.WebPages.OAuth': Assembly reference cannot be resolved: DotNetOpenAuth.AspNet, Version=4.0.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246. [Errors and Warnings] (Global)Could this have something to do with the problem?
ASP.NET website deployment
asp.net;azure;publishing
null
_codereview.100795
Let \$D\$ be a \$N\times N\$ positive definite matrix. I am minimizing a quadratic funtion $$ f(w)=w^T D\ w$$ with respect to the weight vector \$ w=(w_1, w_2, ..., w_N)\$, subject to the following constraints:\$\displaystyle\sum_n w_n =1\$\$w_n\geq 0\$\$w_n \geq \theta \$ or \$ w_n = 0 \quad \forall n\$, for some threshold \$\theta>0\$.The last constraint means that if the optimizer finds a non-zero solution, then it should be at leastas large as a threshold \$\theta\$. I am using solve.QP() from quadprog for the optimization and so I have to inputthe constraints in the form \$A^T w \geq b\$. The last constraint is problematic, since I don't see any way of writting it in that form.What I am doing to deal with this, so far, is this:Ignore the last constraint and find a solution that satisfies the rest of the constraintsSet weights under the threshold \$ \theta\$ to zero, manually, afterwards and then divide the removed weight ammountequally to the rest of the weights that satisfy the last constraint.I expect that this gives an approximation for what the optimizer would have found as a solution, if I could include the last constraint from the begining. Using this solution the value for the function \$ f\$ is close to the initial solution, but of course differs, depending on \$\theta\$. I was wondering if there is some way to implement this, by including the last constraint in the optimization somehow.Toy example:library(quadprog)library(corpcor) #Sample matrix to work with:set.seed(0)Dmat <- cov( volcano+15*rnorm(87*61) ); Dmatis.positive.definite(Dmat)N <- ncol(Dmat) dvec <- rep(0, N)#Constraints:##sum equals 1:a0 <- rep(1, N) b0 <- 1##everything positive:a1 <- diag(1, N)b1 <- rep(0, N)#combine the constraints:Amat <- cbind(a0,a1)bvec <- append(b0,b1)#Solve:sol <- solve.QP(Dmat = Dmat, dvec, Amat, bvec, meq = 1)w <- zapsmall(sol$solution) ; w#Manually set weights under a certain threshold to zerotheta <- .01w[w < theta] <- 0 ; w #scale to sum up to 1:w <- w/sum(w) #Compare function values:t(sol$solution) %*% Dmat %*% sol$solution/2t(w)%*%Dmat%*%w/2
Optimization with a lower value constraint for positive solutions
performance;r
null
_softwareengineering.211295
I haven't found much on this, but what I did find doesn't explain it well enough (at least for me). What makes the application I make portable?Or what defines a portable application?Is there a specific difference that makes an app portable or not? I always thought if I just made an executable file and some images I could just copy that folder and take it to another computer on a flash drive. But, if you could what is the purpose of having portable apps? I know I have asked a range of questions, but I suspect an answer that addresses one of the questions will cover them all.
Apps being portable
applications;portability
The Wikipedia definition is clear enough.A portable app is one that can run in a compatible computer without having to install it. This app can be run from a external storage and writes its data and configuration files to this device, as opossed to in the machine hardrive.The concept of portable app is distinct from software portability which is the ability to compile software into different platform excutables or be run in different platform virtual machines.
_webapps.102063
Often when I'm googling something, the description in the results page lists something extremely relevant to my search, but of course is just a cut off summary. When I use the link to go to that page, that information often doesn't exist there anymore. Sometimes I can visit the cached version and it is there, but often it's a result that says basically the search terms were only on pages that pointed to this page.Is there any way to get Google to give me the actual page it got it's description from?
Is it possible to see where Google search results get their descriptions from?
google search
null
_unix.10147
I just got a new dedicated server with CentOS and I'm trying to debug some network problems. In doing so, I found over one thousand iptables entries. Is this the default on a CentOS system? Is there some firewall package that might be guilty of doing that?
1000 iptables entries on CentOS?
centos;iptables;firewall
Is this the default on a CentOS system?No. The default one is below.Is there some firewall package that might be guilty of doing that?Probably. You don't say what the entries are but if they're banning CIDR blocks I'd guess your server has a firewall like APF or CSF that can subscribe to blacklist like Spamhaus' DROP and that is how your rules are being generated. Alternatively, there might be some cron job which does it all. If you do a grep -rl iptables /etc/* that will tell you all the files that mention iptables and hopefully track down what is generating your entries.Here's the default iptables from /etc/sysconfig/iptables:# Firewall configuration written by system-config-securitylevel# Manual customization of this file is not recommended.*filter:INPUT ACCEPT [0:0]:FORWARD ACCEPT [0:0]:OUTPUT ACCEPT [0:0]:RH-Firewall-1-INPUT - [0:0]-A INPUT -j RH-Firewall-1-INPUT-A FORWARD -j RH-Firewall-1-INPUT-A RH-Firewall-1-INPUT -i lo -j ACCEPT-A RH-Firewall-1-INPUT -p icmp --icmp-type any -j ACCEPT-A RH-Firewall-1-INPUT -p 50 -j ACCEPT-A RH-Firewall-1-INPUT -p 51 -j ACCEPT-A RH-Firewall-1-INPUT -p udp --dport 5353 -d 224.0.0.251 -j ACCEPT-A RH-Firewall-1-INPUT -p udp -m udp --dport 631 -j ACCEPT-A RH-Firewall-1-INPUT -p tcp -m tcp --dport 631 -j ACCEPT-A RH-Firewall-1-INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibitedCOMMIT
_webapps.73715
My wife's laptop has Chrome installed. She uses it under her Chrome username. I sometimes use it with my Chrome username. Since installing the Google Hangouts extension on my Chrome account (on my own laptop), she now gets my Hangouts popups on her computer when using Chrome under her username. This seems like a glitch in how the Hangouts extension interacts with multiple Chrome users. Is there a way to prevent this presumably unintended behavior?
How to prevent Google Hangouts Chrome extension from popping up for other users of the same Chrome installation?
google chrome;google hangouts
null
_unix.155775
I have files named as 0-n.jpg for n from 1 to 500, for example.The problem is that some guy using Windows didn't use leading zeros so when I do ls I obtain0-100.jpg0-101.jpg...0-10.jpg...0-199.jpg0-19.jpg0-1.jpgSo I'd like to rename them to insert the leading zeros, so that the result of ls could be 0-001.jpg0-002.jpg...0-100.jpg...0-499.jpg0-500.jpgIn other words, I'd like all files with the same file name lengths.I tried this solution but I'm getting a sequence of errors likebash: printf: 0-99: invalid number
How to rename to fixed length
shell script;rename
If your system has the perl-based rename command you could do something like rename -- 's/(\d+)-(\d+)/sprintf(%d-%03d,$1,$2)/e' *.jpgTesting it using the -v (verbose) and -n (no-op) options:$ rename -vn -- 's/(\d+)-(\d+)/sprintf(%d-%03d,$1,$2)/e' *.jpg0-10.jpg renamed as 0-010.jpg0-19.jpg renamed as 0-019.jpg0-1.jpg renamed as 0-001.jpg
_codereview.69691
Given the following algebraic data type, a Rose Tree:data Tree a = Node { rootLabel :: a, subForest :: [Tree a]} I attempted a foldTree function to fold over this list: (credit to this class's homework from 2013:treeFold :: (b -> [b] -> b) -> (a -> b) -> Tree a -> btreeFold f g tree = f (g (rootLabel tree)) (map (g . rootLabel) (subForest tree))test*Party> let tree = Node { rootLabel = 100, subForest = [] }*Party> let tree2 = Node { rootLabel = 200, subForest = [tree] }*Party> add tree2300Please review this implementation.Given my definition of treeFold, I don't see how I could fold over a Tree Char, producing a [Char]/String result. My understanding is that, for the return type, b, it can't be [a].
Implement `fold` on a Rose Tree
haskell;tree
The implementation isn't correct, because it doesn't traverse sub-trees. ConsiderNode 1 [Node 2 [Node 3 []]]Then your folding function will only fold over 1 and 2, but not over 3.If you have a recursive structure like this, a folding function over it must also be recursive. Otherwise it won't be able to traverse arbitrarily large recursive structure.For the other question: If you specialize the folding function astreeFold :: ([Char] -> [[Char]] -> [Char]) -> (Char -> [Char]) -> Tree Char -> [Char]by setting b = [Char], you get what you're looking for - converting a Tree Char to String. You just need to supply the two function for folding, for exampletreeFold (\x ys -> x ++ concat ys) (: [])Update: The signature also isn't correct. The general rule is that the folding function should have one additional argument for each constructor of the data type where recursive types (here Tree a) are replaced by the result of the fold:treeFold :: (a -> [b] -> b) -> Tree a -> bFor example for a list you have 2 constructors: (:) :: a -> [a] -> [a] and [] :: [a], so its folding function isfoldr :: (a -> b -> b) -> b -> [a] -> b
_softwareengineering.220783
I hope you bear with me here. It's difficult to explain this problem, especially so without direct reference to the specific domain.I work on a component of a larger system which performs computationally expensive pre-processing in order that the real-time component can perform it's functions quickly. My product effectively creates a big lookup dataset for the main component to query.My product computes the results of a finite set of scenarios (a few hundred thousand) any one of which may be performed by a customer. The component uses a k-shortest paths algorithm and a number of rules engines to consider each scenario and build up the lookups, operating on reference data that represents the problem domain.For the scenarios that are very commonly performed by our customers the test cases are easy; the expected outcomes are easy to devise and assert acceptance tests. However, for the scenarios that are not popular, the expected outcomes are difficult to establish and in any case their outcomes may be changed by changes to the reference data which are virtually impossible to predict. In other words, changes to the reference data changes the inputs to the shortest-path algorithm which in turn may change the output.Creating acceptance tests for these unpopular cases is also tricky, because the business doesn't know what it doesn't know, and so has no baseline against which it can be tested.Whenever a tester comes back to me with a defect, 99.9% certainty it's because conditions in the reference data have changed, rather than because of any code changes. I therefore spend a load of time chasing defects that are data issues. I think what confuses the situation is that the reference data is key to the functionality of the system, and the system without a specific set of reference data would produce no results that had any meaning to the business. I could create a set of fake reference data against which to test, but any assertion against this engineered reference data would be invalid in the real world.I would be very interested to hear any perspectives on this especially from those who have encountered similar problems. I am anxious not to simply shrug my shoulders and reply data issue but get to the root of the problem and work out how to build and test this thing in a reliable, repeatable and valuable way.
Software without a testable goal
design;testing;acceptance testing
null
_softwareengineering.194545
I'm trying to improve my OOP code and I think my User class is becoming way too fat.In my program a user has rights over lists. Read, Write, Update, Delete.So I made a User classclass User{protected $_id;protected $_email;protected $_username;protected $_hashedPassword;//...Various setters/getterspublic function canRead(List $list){ //Database query verifies if user has READ rights}public function canUpdate(List $list){ //Database query verifies if user has UPDATE rights}//etc...}Should canRead, canUpdate, canWrite, canDelete methods be moved to another class (UserAccessCheck or something...)?If not, should the actual SQL be moved into the List object (listCanBeReadByUser()) ?
Should a User class only contain attributes and no methods apart from getters/setters?
object oriented design
What you are doing is putting together a mechanism for access control (lists) or ACL. In general, as Ritesh says, it's a bad idea to do that all in one class.This answer on SO has a nicer, OO way of dealing with access control.Rather than extending your User class, you should wrap your User class inside a SecureContainer. See the linked-to answer for details, but then the overall call would be:// assuming that you have two objects already: $currentUser and $controller$acl = new AccessControlList( $currentUser );$controller = new SecureContainer( $controller, $acl );// you can execute all the methods you had in previous controller // only now they will be checked against ACL$controller->actionIndex();This allows the User class to focus on what it needs to do, and allows the AccessControlList class to focus on what it needs to do.
_unix.341396
I'm using Debian Jessie and have created a systemd service for launching a script on a tty like this:[Unit]Description=My Test Script[Service]Type=simpleExecStart=/bin/bash /home/tester/test.sh StandardInput=tty-forceStandardOutput=ttyStandardError=ttyTTYPath=/dev/tty2TTYReset=noTTYVHangup=noTTYVTDisallocate=noRestart=alwaysRestartSec=3[Install]WantedBy=default.targetMy script test.sh is just a readline:#!/bin/bashread -p Backspace test: exit 0What happens? I can find the script running on tty2just as expected; however, if I enter something and then use backspace to remove characters, it starts outputting things backward with enclosing slashes.Example of inputting characters:Backspace test: abcOn backspace three times, which should remove abc, it instead becomes:Backspace test: abc\cba/Additionally, stty -a gives erase = ^? and if I login on a tty and start test.sh, everything works as expected.Why does this happen?Edit: Solved by adjusting the terminal line settings using stty; more specifically, the option echoprt is of interest:* [-]echoprt echo erased characters backward, between '\' and '/'
Script started on tty at boot does not handle backspace correctly
debian;systemd;tty;getty
null
_webmaster.77683
I've developed a site, and I'd like to apply the exact same theme with the same HTML markup but different CSS styling to multiple different sites on different domains. The sites will be related in genre, but they will have completely different content.I plan use a tiered linkage approach, where that one of these sites is at the bottom layer (most important), and all the other sites link (one way) to this site. Kind of like this:Will using the same theme AND linking these same-genre sites together likely result in an SEO penalty from Google?
Multiple sites, same markup, different content, tier linkage = SEO penalty?
seo;google;html;backlinks;content
null
_scicomp.1757
I managed to reduce certain computational problem to the Gauss-Seidel solution of the following linear system: $$Ax=Ly,$$ where $A, L\in\mathbb{R}^{n\times n}$ are weighted Laplacian matrices (symmetric, positive semi-definite; negative off-diagonal entries, with rows(collumns) summing (in absolute values) to positive diagonal entries; matrix eigenvalue $0$ corresponds to $1_n$ eigenvector of the nullspace), and $x,y\in\mathbb{R}^{n\times 2}$ are vectors with the unknown $x$. The solution has the form $$x_i^{[k+1]} = \left.\left(b_i - \sum_{j=1}^{i-1}a_{ij}x_j^{[k+1]} - \sum_{j=i+1}^{n}a_{ij}x_j^{[k]}\right)\middle/a_{ii}\right.,$$ where $b_i$ is the $i^{th}$ entry of $Ly$. Note that, with Gauss-Seidl, the update of $x_i$ takes effect immediately, i.e., calculation for the following $x_{i+1}$ is based on the new value of $x_i$ that has been computed just before. Now, suppose an iteration consists of a single update of all $x_i$ in some arbitrary order. In other words, each $x_i$ is considered only once (and is updated only once) in an iteration. My question is: could it be guaranteed that after a single iteration with initial $x^{[0]}=y$, the solution $x^{[1]}$ has all unique coordinates, i.e., there are not two rows of $x^{[1]}$ that are equal?You could assume that the initial $x^{[0]}=y$ has non-unique coordinates. If the uniqueness cannot be resolved this way, I would appreciate a suggestion on the coordinate traversal order to increase the chance of achieving uniqueness (i.e., no two coordinates take the same value).
Unique coordinates (solutions) in a single Gauss-Seidel iteration
linear algebra;matrices;iterative method;computational geometry;linear solver
The order in which you update the new solution has a big impact on the values produced from the initial data to the first approximation. Some updated values will be the same as the jacobi iteration, while others will contain the latest information a la Gauss-Seidel. Given a specific ordering, there may be two values that are the same if the initial vector $x_0$ has non-unique values. But for two different orderings, if the the solution vector is large, and the order of updating the gauss-seidel formula is random, the more unlikely it is that you will produce similar 1st iterations. I'm not sure if there is a proof for that different orderings produce unique 1st iterations, but even if it is possible for them to be non-unique, the probability is very unlikely.
_codereview.116057
I have a problem with some remote devices at a lot of my manufacturing sites. There are two major problems:the network is unreliable in terms of maintaining connectionsmachines have duplicate IP addressesBoth of these are, naturally, catastrophic. To detect these conditions, I wrote a small program that loads a list of devices (and a description) and pings them all every 10 minutes, dumping the results to a couple log files.I use icmp4j and OpenCSV as dependencies. Import statements are implied. The server running it will be a very beefy server: 24 core Xeon X5650s with 72GB of RAM. Obviously, this isn't the only thing on it, but suffice it to say we'd have to push pretty hard to cause a CPU or memory problem.I'm interested in any real feedback. If there's a better way to do one of the tasks, if any problems jump out, anything that might bite me in the butt down the road. I'd also consider comments on style, obviously avoiding holy wars and respecting differences of opinion. I'm particularly interested in how I'm passing messages around, what can be done to clean that up because I fear it might get ugly as the program creeps bigger.public class Main { // just a simple struct to attach a description to a hostname... static class Host { Host(String name, String desc) { this.name = name; this.desc = desc; } String name; String desc; public String toString() { return name + + desc; } } /** * * @param args * @throws FileNotFoundException not expected because we should create any file we don't already have * @throws InterruptedException not expected because nothing should be interripting us */ public static void main(String[] args) throws FileNotFoundException, InterruptedException { final List<Host> hosts = loadHosts(); // keep track of IP addresses and what hosts they belong to // we find multiple hosts have the same IP address (WTF) so if we try to ping different hosts // and they hit the same IP, there's a problem! final Map<String, Host> ips = new HashMap<>(); final SimpleDateFormat sdf = new SimpleDateFormat(yyyy-MM-dd-HH-mm-ss); // the date at which the current log started Calendar logDate = new GregorianCalendar(); String dateStr = sdf.format(logDate.getTime()); while (true) { Calendar currDate = new GregorianCalendar(); // if we are on a new week, roll over the log if(currDate.get(Calendar.WEEK_OF_YEAR) != logDate.get(Calendar.WEEK_OF_YEAR)) { logDate = new GregorianCalendar(); dateStr = sdf.format(logDate.getTime()); } // we'll use this later and compare it to 'now'... long then = System.currentTimeMillis(); // create new or append to existing CSV log file - rollover happens here try (final CSVWriter log = new CSVWriter(new FileWriter(new File(log + dateStr + .csv), true))) { for (final Host host : hosts) { // ping the host 5 times - this is the critical business logic step String[] data = ping(host, 5); // convenient holder objects for the host Host newHost = new Host(data[HOST_INDEX], data[DESC_INDEX]); // fetch the old host associated with that IP Host oldHost = ips.put(data[IP_INDEX], newHost); // see if this doesn't pass the sniff test if(oldHost != null && data[IP_INDEX] != NO_IP && !oldHost.equals(data[HOST_INDEX])) { data[DUP_IP_INDEX] = dupe; // yeah I know we're logging every single dupe, but they don't happen often, so this is not going to kill us try(FileWriter dupes = new FileWriter(new File(dupes.log),true)){ dupes.write(new Date() + + oldHost + and + newHost + share ip + data[IP_INDEX]); dupes.write(\n); dupes.flush(); dupes.close(); } } // OpenCSV is super easy to work with, I picked it up in like ten minutes. Hurray! log.writeNext(data); // yes, we flush every time. In reality we don't have to do this, but we want to in case something errors during the next write // this is going to write about 200 times every ten minutes, or an average of less than once a second. // even if they all went through perfect it's going to take around 1 minute to do all 200 pings... the server is a beast, // this is nothing... if this becomes a performance or maintence problem we'll address it then log.flush(); } } catch (IOException e) { // aanndd i won't be doing much about this, because 1) i don't expect it to happen and 2) i can't really recover if it does e.printStackTrace(); } long now = System.currentTimeMillis(); long diff = now - then; // I love TimeUnit! It just makes this thoughtless! // we want to have a total of ten minutes between each run long durr = TimeUnit.MINUTES.toMillis(10); // so we subtract how long we took on this trip and long waitDurr = durr - diff; System.out.println(Finished run, waiting + waitDurr + milliseconds to run again); if (waitDurr > 100) { Thread.sleep(waitDurr); } } } // just some static values that make it SO much easier when you have to add a value in the middle static final String NO_IP = no ip available; static final int HOST_INDEX = 0; static final int DESC_INDEX = 1; static final int IP_INDEX = 2; static final int DUP_IP_INDEX = 3; static final int TIMESTAMP_INDEX = 4; static final int DATE_INDEX = 5; static final int ERROR_INDEX = 6; static final int RESULTS_START = 7; static String[] ping(Host host, int attempts) { // Icmp4j - who would have thought? Turns out they can't do multi-threaded pings though, so I fear some of it // may be inaccurate - if I have to I can pump a ping command through the command line... IcmpPingRequest ping = IcmpPingUtil.createIcmpPingRequest(); ping.setHost(host.name); ping.setTimeout(500); String[] results = new String[attempts+RESULTS_START]; // prepopulate results matrix results[HOST_INDEX] = host.name; results[DESC_INDEX] = host.desc; results[IP_INDEX] = NO_IP; results[DUP_IP_INDEX] = none; results[TIMESTAMP_INDEX] = String.valueOf(System.currentTimeMillis()); results[DATE_INDEX] = new Date().toString(); results[ERROR_INDEX] = ; // yeah we're using string concat later... it's not pretty but it's low useage for (int i = RESULTS_START; i < results.length; i++) { try { IcmpPingResponse resp = IcmpPingUtil.executePingRequest(ping); results[IP_INDEX] = StringUtils.defaultString(resp.getHost(), results[IP_INDEX]); // this particular ping failed, mark as -1 and append its error message if(!resp.getSuccessFlag()) { results[ERROR_INDEX] += resp.getErrorMessage() + ; ; results[i] = -1; } else { results[i] = String.valueOf(resp.getDuration()); } } catch (Exception e) { // the whole request failed, mark -1s and append its error message results[ERROR_INDEX] += e.getMessage() + ; ; Arrays.fill(results, RESULTS_START, results.length, -1); return results; } } return results; } static List<Host> loadHosts() throws FileNotFoundException { List<Host> hosts = new ArrayList<Host>(); try (Scanner sc = new Scanner(new File(hosts.txt))) { while(sc.hasNextLine()) { String hostline = sc.nextLine().trim(); // this allows us to // * skip blank lines // * comments (starting with # or $ or something // * NO_HOST, which I used to filter the data that was given to me to build the hosts file from if(hostline.isEmpty() || !Character.isLetterOrDigit(hostline.charAt(0)) || hostline.contains(NO_HOST)) { System.out.println(skipped host + hostline); continue; } // it is decreed that the first word of a valid line is its name, and everything after that is its description String[] split = hostline.split(\\s+, 2); String name = split[0]; String desc = split.length < 2 ? : split[1]; Host host = new Host(name,desc); System.out.println(added host + host); hosts.add(host); } } System.out.println(number of hosts: + hosts.size()); return hosts; }}
Small Java auto-pinger, single class program
java
null
_unix.107207
I saw a question in SuperUser titled How do I restart a frozen screen in Ubuntu without losing any open windows? and I think it would be helpful, but the problem is I can't switch to any of the TTYs.I'm trying to switch to tty 1 with Ctrl+Alt+F1 and it doesn't work, and honestly I even can't say if it has ever been worked before.The problem already occured one time about one month ago and fixed after 3 hours of waiting but this time the difference is that the cursor is moving and the clock is working right. Moreover all system monitor indicators show current state of hardware so it seems that the processor, disc, RAM and swap are also working. It happened during moving a terminal window to another part of workspace which is displayed on second monitor. And, what is strange, I can see mini dialog box with the resolution of the window that I have never seen before.Trying to unplug the second monitor didn't help. What can I do to unfreeze it and to not lose unsaved data?Shortcut Super+D made GNOMEs windows unfrozen so in similar cases this should be helpful.
Windows in Gnome on Ubuntu 10.10 are frozen
ubuntu;gnome;freeze
null
_webmaster.14928
I've been coding for a while and it's just struck me, what's better to use in terms of SEO:<b>Hello</b>or<strong>Hello</strong>
Which is better to use or for SEO?
seo;html
According to Matt Cutts are treated exactly the same. FYI, <i> and <em> are also treated the same.Video where Matt Cutts says they have the same weight
_unix.261200
Pretty new to Linux, I heard that I should never use --nodeps option when I do a rpm -e command.Why does this option exist then?
In which case can I use the option '--nodeps' of rpm command?
rpm;options
It exists for broadly the same reasons rm will allow you to delete the filesystem root, or dd will allow you to overwrite the physical hard drive:Linux and unix have a long history of giving you all the ammo you need when you really insist on shooting yourself in the foot.Less flippantly, when something has gone badly wrong during a package install, whether due to a badly built package or an outage at the worst possible moment, it's possible to wind up with your package manager's dependency database in gridlock -- IE, it can't resolve the problem because attempting any of the solutions would violate the dependencies of the other packages involved. In that case, you can use --nodeps, or for dpkg, the --force-* options to manually and forcibly remove the offending package, and then immediately issue what commands are necessary to fix the now broken dependencies. That's something you should only do if you're really sure of what you're doing, however; as a rule of thumb, if you aren't sure what use --nodep is, don't use it. You're essentially taking all the safeties off, and gods help you if you screw something up while doing it.
_cs.14753
I am doing bachelors in Electronics & Communication Engg.. But most of my work happened to be in Web development.. I am thinking to do my bachelor thesis which very closely overlaps with my recent work.Are there any specific areas in CS, EE (may be Computer Networking in broad terms) that I can take up?
What areas in EE overlap closely with CS
computer networks;research
null
_unix.144940
I have two text files, and I want to copy a bunch of lines from one to the other. File one has a list of packages, and I want to copy it to list two. This list of packages isn't at the start of file one, but have a tag %packages at the start of the list, and a tag %end at the end. I'm wondering how I can copy all lines between %packages and %end from file 1 into file 2?
How do I Copy and Paste lines between a start and end keyword?
shell;text processing;grep
To copy all lines between %packages and %end from file1 into file2:awk '$1==%end {f=0;next} f{print;next} $1==%packages {f=1}' file1 >>file2This solution is designed to remove the lines %packages and %end. (If you want those lines to be transferred as well, there is an even simpler solution below.)Since awk implicitly loops over all lines in a file, the above commands are applied to each line in file1. It uses a flag, called f, to determine if we are within the packages section of file1. Every line within the packages section is printed to stdout which is redirected to file2.Let us consider the awk commands, one by one:$1==%end {f=0;next}This command checks to see if the line begins with %end. If it does, the flag f is set to zero and we skip to the next line.f{print;next}This command checks to see if the flag f is nonzero. If it is nonzero, then the line is printed and we skip to the next line.$1==%packages {f=1}This command checks to see if the line starts with %packages. If so, it sets the flag f to one so that lines after this will be printed.Including the marker lines:The above excludes the marker lines %packages and %end. If you want those included, then use:awk '/^%packages/,/^%end/ {print}' file1 >>file2
_webapps.49331
I want to filter my LinkedIn contacts in order to delete some of them. How can I easily find and delete all my contacts who, say, are girls, aged between 26 and 32 and are from Tel-Aviv?
How to filter LinkedIn contacts
linkedin
null
_unix.381275
I have a script which need to look into a lst file and read the line and print the line if there is nothing left in the list it need to exit the script but the below script is looping itself and the lst file has two numbers(man,san) can any one help me out.vi do.lst mansancode:= cat /ora/do.lst while read -r line do if [[ -z $line ]] then echo The list is empty exit else lst_no=${line}, echo ${line} is processing now fi done
Read line issue
bash;shell
Everything looks fine, you just need to pipe a cat into the loop:cat /ora/do.lst | while read -r line do if [[ -z $line ]] then echo The list is empty exit else lst_no=${line}, echo ${line} is processing now fidoneThis is obviously not the optimal way to process lines, but I assume it's just for learning purpose.A little better would be to at least avoid useless cat and unnecessary pipe:while read -r line; do...done </ora/do.lstor even better, to preserve stdin for commands inside loop:while read -r line <&3; do...done 3</ora/do.lstHowever, if your file has many lines you may want to consider rewriting the script in awk, perl or other tool dedicated for text-processing task. Shell loops are not optimized in this regards.
_unix.243952
Firstly, I tried to install Kali 2.0 from usb. Clicked install/graphicInstall. But it complained that there was no dvd disk with the packages in. Then, I went liveUSB and installed from there. I had Kali and Win8 on the disk. But grub didn't load. It just skipped to Windows. Then I tried to install Kali to another disk(SSD). But it just showed string 'Loading operating System...' and neither Grub, nor Kali started. By the way, I tried both EFI and non-EFI settings in BIOS.So, how to install Kali successfully?(I have kali persistence on one external disk and it works great!)
How to install Kali?
debian;system installation;grub;bios
null
_cs.77066
The below example confused me:lw $r0, 4($r0)sw $r0, 4($r0)add $r0, $r0, $r0Using MIPS 5 stage execution what are the hazards we have 1) without forwarding 2) with forwarding only in the stage of execution (exe or alu) 3) with forwarding. Add nops to eliminate hazards.
lw and sw hazards example MIPS
computer architecture;mips
null
_unix.305126
I found how to insert a line after a certain line in bashsed -i '/oh-my-zsh.sh/aplugins=(git symfony2)' ~/.zshrcResult:source $ZSH/oh-my-zsh.shplugins=(git symfony2)But I would like to insert my line before source $ZSH/oh-my-zsh.sh.How is it possible?
Insert a line before a certain line in a file
text processing
The 'a' in '...sh/aplug... is for 'add' and puts the new text after the search pattern. Replace it with 'i' for 'insert' to put the text before the search pattern. Like this:sed -i '/oh-my-zsh.sh/iplugins=(git symfony2)' ~/.zshrc'This answer and MUCH more can be found at: Sed - An Introduction and Tutorial by Bruce Barnett.
_unix.292521
sqlite -echo test.sqlite < test44.sql > test44.out 1>&2.sqlite -echo test.sqlite < test44.sql > test44.out 2>&1.I used the first command to get an output of (stdout and stderr) in test44.out instead of the second command. After using my original command, I am getting the same output for the both commands.
What are the possible correct combination for std-out(2) and std-err(1)?
bash
With 1>&2 you redirect standard output to wherever standard error is going. This is not done often.With 2>&1 you do the opposite, which is more common.Doing this:$ echo hello world >hello.out 1>&2hello world$ cat hello.outI get hello world on the error stream, but >hello.out also creates an empty hello.out file (or truncates it if it exists).It's the last redirection on the line that wins, but the file is created when the redirection is parsed left-to-right, before the command is executed.In you case (those . at the end of the command lines that you have is probably a typo, right?):$ sqlite -echo test.sqlite <test44.sql >test44.out 1>&2This ought to work in the equivalent way as my echo test above since sqlite (or at least sqlite3 on OpenBSD that I'm testing with), outputs the executed SQL commands to standard output.
_unix.268885
is there a (FreeDesktop) Linux command to open an open-with dialog similar to xdg-open?I'm searching for some general desktop environment independent solution for showing something like this:Of course there is xdg-open to open the file with the default app, but how do I give users a choice to open a file in a different app? I'm also not looking for mimeopen that changes the current default application.
Is there a FreeDesktop command to open an open-with dialog similar to xdg-open?
desktop environment;freedesktop;file opening;xdg open
null
_cs.67746
What is the minimum number of comparisons required to determine if an integer appears more than $n/2$ times in a sorted array of $n$ integers?I am trying binary search on the array A.Algorithm(A): x = A[mid], where mid is the middle element of the array.Compare x with A[n/4] and A[3n/4].If x = A[n/4] and x A[3n/4] then search in A[1] to A[3n/4 + 1].If x A[n/4] and x = A[3n/4] then search in A[n/4 + 1] to A[n].If x A[n/4] and x A[3n/4] then it is a no instance.If x = A[n/4] and x = A[3n/4] then it is a yes instance.Running Time: $T(n) = T(3n/4) + O(1)$ which is $O(\log n)$ in asymptotic sense. At each step I am doing two comparisons so $2\log_4n$ if $n = 4^k$.Is there any better (optimal) algorithm to solve the problem mentioned above?Also, I don't know how to prove the lower bound.
Determining if an integer appears more than $n/2$ times
algorithms;algorithm analysis;lower bounds
You are asking two questions. I will only answer the second one. Consider the following set of possible inputs: the array is contains either $n/2$ or $n/2+1$ copies of $0$, all elements preceding it are $-1$, and all elements following it are $+1$.I claim that any algorithm which works correctly for this set of inputs must query, in the YES instances, the first and the last position of the stretch of zeroes. Indeed, if it never queries the first position for example, then the input could have been the NO instance in which the value at that position is replaced by $-1$.Since the first and last position of zero are at distance exactly $n/2$, and are the only two positions at that distance of equal value, we see that any correct algorithm for your problem can be modified (without any additional comparisons) to give an algorithm for the following problem:Given an array consisting of $n/2+1$ zeroes, preceded by $-1$ entries and followed by $1$ entries, find the location of the zeroes.Since there are $n/2$ different answers to this problem, the usual decision tree argument shows that any comparison-based algorithm must make $\log_3 n - O(1)$ three-way comparisons, or $\log_2 n - O(1)$ two-way comparisons of the form $x=y$ or $x \neq y$?. This shows that for two-way comparisons, your algorithm is nearly optimal. (Note that $2\log_4 n = \log_2 n $.)
_webapps.4991
I'm looking to merge a couple pdf files for a one-off and don't want to install anything on my pc. Anyone know of any webapps which will let me merge pdf files?
Is there a good webapp for manipulating pdf files?
webapp rec;pdf
null
_reverseengineering.4546
How should I decide file is malware or not. Before reverse engineering any file, I should be suspect the file. What are the various ways to decide if exe is malicious? Thanks
How to decide file is malware or not?
malware
This is a million dollar question and I doubt anybody will be able to provide a convincing answer. There are many methods used by antivirus software & analysts. One is to perform a stupid matching with known malware signatures. Another could be to statically analyze the application, extract the control flow (by reconstructing the CFG) of the application and deploy heuristics & pattern matching algorithms in order to determine if the application performs suspicious tasks. This can usually be done after analyzing known malware & building profiles of their behaviors (suspicious syscall call graph, ...). There are numerous techniques and this field is still open for research (this document describes an interesting one), some are extremely advanced and may necessitate sharp mathematical skills, and others are hard to program. Mainly, because none of them follow the standard algorithmic approach and rather use machine learning, genetic algorithms, and sometimes AI. I suggest you going through this Securelist article, and this publication too if you're interested by more material.
_softwareengineering.154287
I am developing a software project in Java/Swing licensed under GPL v3.Later, I want to create a Android application which uses the algorithms of the Java/Swing application. This Android app will be a commercial product (sold on Google Play Store).Is this a problem, when I use my OWN GPL code in a commercial SW developed by me?
Use my own GPL licensed code in a commercial product
android;licensing;gpl;commercial
If you are the sole copyright holder (i.e., the owner), you can do anything you want with the code, including doing a derivative version of the code where the only change is to the license. Licenses are just descriptions of the conditions placed by the owner(s) on the non-owning users of the code. They do not constrain the owner.When there is multiple ownership, things get more complex (formally, all copyright holders have to agree in order to change the license). There's a gray area about what sort of contribution would be required by someone for them to be a copyright holder; its almost certainly not done by mechanical count of lines modified as a substantive contribution could be very short and a non-substantive one very long (e.g., converting all the indentation to tabs or spaces). We can't assess the extent to which this applies in your situation, except to point out that someone else downloading and using the code doesn't obligate you to grant them ownership rights.If you write all of it yourself, you don't need to pay much attention at all to the complexity in the previous paragraph. You can just go ahead and do what you want to do.A separate point is if you are working for a company that is the owner of the code. In that case, it's the company's decision and you're just acting on the company's behalf. It's no more complex than before provided the company is the sole owner of the code.
_codereview.49460
I want to improve this code to make it look more professional, be loaded quicker and make it cross-browser compatible. Do note that it is not a finished site. I want to know the best practice for doing certain things before I proceed any further.HTML:<!DOCTYPE html><html><head><title></title> <link rel=stylesheet type=text/css href=css.css></script></head><body><div id=menu><div id=img>Bild</div><div id=gallery>Gallery</div><div id=stats>Stats</div><div id=members>Members</div><div id=groupMe>GroupMe</div><div id=knd>K&D</div><div id=apply>Apply</div></div><div id=guildinfo><span class=info>Back >></span></div><div id=wars>Knights & Dragons - Wars<table id=warslist><tr> <td>1.</td> <td>4.</td> <td>7.</td></tr><tr> <td>2.</td> <td>5.</td> <td>8.</td></tr><tr> <td>3.</td> <td>6.</td> <td>9.</td></tr></table><span class=info>Guild info >></span><span id=previous><a href=previouswars.html>Click here to see all previous wars</a> </span></div><div id=content></div><div id=banner><b>MVP</b></div><div id=content2><div id=imgHolder></div><div class=fontstyling center>Duplo - Lv 52</div><div id=spanHolder><span>Class: Assassin</span><br><span>Level: 52</span><br><span>Vip level: 2</span><br><span>Ship level: 29</span><br><span>Unlocked exploration areas: 4</span><br><span id=arenaRank>Arena rank: (<span id=yellowColor>1</span>) 3696</span><br><span>Total contribution: 5624</span></div></div><script src=http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js></script><script src=javascript.js type=text/javascript></script></body></html>CSS:html, body { margin: 0px; padding: 0px; width: 100%; height: 100%; background: url(img/background.jpg) no-repeat fixed; background-size: cover;}a { text-decoration: none; color: yellow;} #menu { width: 316px; height: 100px; margin-top: 20px; margin-left: 50px;}#img { background: url(img/icon.png); background-size: cover; width: 100px; height: 100px; float: left;} .menuDivs { width: 70px; height: 30px; color: yellow; background: url(img/brown.jpg); font-family: Arial; font-size: 14px; text-align: center; float: right; margin: 20px 2px -18px 0px; vertical-align: bottom; line-height: 30px; border-radius: 5px;}#wars { width: 450px; height: 170px; border: 1px solid black; border-radius: 10px; background: url(img/brown.jpg); top: 20px; left: 380px; position: absolute; font-family: Tahoma; font-size: 18px; color: yellow; text-align: center; line-height: 30px; opacity: 0;}#warslist { width: 400px; height: 100px; color: white; margin: auto; font-size: 13px; text-align: left;}.info { position: absolute; top: 0px; right: 15px; font-size: 11px; color: white;}#previous { position: absolute; bottom: 0px; right: 15px; font-size: 11px;}#guildinfo { width: 450px; height: 170px; border: 1px solid black; border-radius: 10px; background: url(img/brown.jpg); top: 20px; left: 380px; position: absolute; opacity: 0; z-index: -1; line-height: 30px;}#content { /* main content*/ width: 700px; padding: 50px; min-height: 100%; background: rgba(0, 0, 0, 0.7); margin: 100px auto auto 50px; color: white; font-family: Tahoma; font-size: 15px; border-radius: 9px; word-wrap: break-word;}#content2 { /*secondary content (right)*/ width: 380px; min-height: 80%; background: rgba(0, 0, 0, 0.7); top: 380px; right: 88px; position: absolute; border-radius: 15px;}#banner { width: 480px; height: 150px; background: url(img/banner.png); background-size: cover; top: 320px; right: 40px; position: absolute; z-index: 1; text-align: center; line-height: 70px; font-size: 20px; color: black; font-family: Tahoma;} #imgHolder { width: 270px; height: 300px; border: 2px solid black; margin: 50px auto 5px auto; background: url(img/mvp.png) no-repeat -50px; background-size: cover;}.fontstyling { font-family: Tahoma; font-size: 15px; color: white;}.center { text-align: center; margin-bottom: 20px;}.marginLeft { margin: auto auto auto 80px;} #yellowColor { color: yellow;}JavaScript:$(document).ready(function() { $(.info).click(function() { if($(#guildinfo).css('z-index') === '-1'){ $(#guildinfo).css('z-index', '1'); $(#guildinfo).animate({ opacity:'1' }); //end of animate } else{ $(#guildinfo).animate({ opacity:'0' }); setTimeout(function() { $(#guildinfo).css('z-index', '-1'); }, 500); } }); //end of info function $(#knd).click(function() { if($(#wars).css('opacity') === '0') { $(#wars).animate({ opacity:'1' }); //end of animate } else { $(#wars).animate({ opacity:'0' }); //end of animate } }); //end of KND click function $(#gallery, #stats, #members, #groupMe, #apply, #knd).addClass(menuDivs); $(#spanHolder).find(span).addClass(marginLeft fontstyling); $(#arenaRank).find(span).removeClass(marginLeft);}); //end of doc ready function
Guild Wars: Knights & Dragons
javascript;html;css
HTML:HTML5 allows omitting the type attribute from link, script and style tags. You can safely remove it from your link tag.You should move jQuery to the bottom of your documents. Otherwise it'll be loaded before your document gets rendered.You use a lot of ID's where you shouldn't. I generally advice avoiding ID's whereever it's possible, because working with classes is easier in terms of CSS specificity.Overwriting an ID rule with a class is hard. Also ID's should only be used when you can definitely say there will only be one of these elements on this page.You rarely indent your HTML code. Do it. It allows you to see the structure you're building and leaves less space for mistakes like not closing certain tags.The content inside your ID spanholder (again, this should be a class) looks like tabular data. Thus you could use a table for it.That said, what about your table with the ID warslist. Should this be a table? Why?Use descriptive names. The filenames css.css and javascript.js are pretty redundant, because the extension already tells you what to expect from this file.CSS:Why do you select both html and body in your first CSS rule? That only makes sense for your declaration of height: 100%;This is, what you should have:body { margin: 0; background: url(img/background.jpg) no-repeat fixed; background-size: cover;}html, body { height: 100%;}I removed the units behind 0, you don't need it for zero values. I also removed the padding declaration, because body doesn't have a padding you would reset in all User Agent Styles of modern browsers.The declaration width: 100%; is also not necessary, because both elements are block level elements. Block elements automatically take up the available space.You should declare your basic font rules in the body rule above as well.body { /* Using shorthand instead of... */ font: 14px/1.5 Tahoma, Arial, sans-serif; /* ...this: font-size: 14px; line-height: 1.5; font-family: Tahoma, Arial, sans-serif; */}After this you could specifiy some basic rulesets for stuff like headings and maybe a few variations for smaller text (meta data, etc.).
_softwareengineering.81705
I have found a GPL library (no dual license), which does exactly what I need. Unfortunately, the GPL license on the library is incompatible with the license of a different library I use. I have therefore decided to rewrite the GPL library, so the license can be changed. My question is: How extensive do the changes need to be to the library in order to be able to change the license? In other words, what is the cheapest way to do this?
Rewriting GPL code to change license
licensing;gpl
I'm not a lawyer, but AFAIK if you have seen the GPLed library code any emulation library you write would be tainted and may be declared a derived work by a judge if it is too similar in his appreciation.So the process would be to write a functional spec and have someone which hasn't seen the GPLed code write the library.Edit: Note that with the way you formulate your question How extensive do the changes need to be to the library in order to be able to change the license? the answer is AFAIK clear: whatever you do, if you just modify the library you must respects the term of the license which makes you able to modify it in the first place.
_softwareengineering.36561
(Let me start off by asking - please be gentle, I know this is subjective, but it's meant to incite discussion and provide information for others. If needed it can be converted to community wiki.)I recently was hired as a junior developer at a company I really like. I started out in the field doing QA and transitioned into more and more development work, which is what I really want to end up doing. I enjoy it, but more and more I am questioning whether I am really any good at it or not. Part of this is still growing into the junior developer role, I know, but how much? What are junior developers to expect, what should they be doing and not doing? What can I do to improve and show my company I am serious about this opportunity? I hate that I am costing them time by getting up to speed. I've been told by others that companies make investments in Junior devs and don't expect them to pay off for a while, but how much of this is true? There's got to be a point when it's apparent whether the investment will pay off or not.So far I've been trying to ask as many questions I can, but I've you've been obsessing over a simple problem for some time and the others know that, there comes a time when it's pretty embarrassing to have to get help after struggling so long. I've also tried to be as open to suggestion as possible and work with others to try to refactor my code, but sometimes this can be hard clashing with various team members' personal opinions (being told by someone to write it one way, and then having someone else make you rewrite it).I often get over-stressed and judge myself too harshly, but I just don't want to have to struggle the rest of my life trying to get things work if I just don't have the talent. In your experience, is programming something that almost everyone can learn, or something that some people just don't get? Do others feel this way, or did you feel that way when starting out? It scares me that I have no other job skills should I be unsuited for having the skills necessary to code well.
Woes of a Junior Developer - is it possible to not be cut out for programming?
skills
null
_unix.191885
When I run nix-shellnix-shell ~/dev/nixpkgs -A pythonPackages.some-packageand then edit phases of pythonPackages.some-package, how to reload nix-shell environment with new changes? Quit nix-shell and rerun is one option, but are there alternatives?
Quickly reload nix expression in nix-shell?
nixos;nix
No other simple options, sorry. I can only think of rewriting nix-shell to accomplish what you want. Probably it's not even that hard. Reparse the expression, cleanup the env and refill the env.
_scicomp.5554
Is it possible to calculate the color frequency of a pixel?I mean, I get a pixel that is red but where this red sits on the spectrum in hertz?Is this even possible to do even in a limited way?thanks.
Color frequency of a pixel
algorithms
null
_codereview.18266
I have an application where I am receiving big byte array very fast around per 50 miliseconds.The byte array contains some information like file name etc. The data (byte array ) may come from several sources.Each time I receive the data, I have to find the file name and save the data to that file name.I need some guide lines to how should I design it so that it works efficient.Following is my code...public class DataSaver{ private Dictionary<string, FileStream> _dictFileStream; public void SaveData(byte[] byteArray) { string fileName = GetFileNameFromArray(byteArray); FileStream fs = GetFileStream(fileName); fs.Write(byteArray, 0, byteArray.Length); } private FileStream GetFileStream(string fileName) { FileStream fs; bool hasStream = _dictFileStream.TryGetValue(fileName, out fs); if (!hasStream) { fs = new FileStream(fileName, FileMode.Append); _dictFileStream.Add(fileName, fs); } return fs; } public void CloseSaver() { foreach (var key in _dictFileStream.Keys) { _dictFileStream[key].Close(); } }}How can I improve this code ? I need to create a thread maybe to do the saving.
Design guideline for saving big byte stream in c#
c#
null
_cogsci.1843
I remember reading a case study on this years ago and I am trying to track it down.The study involved asking people who held strong opinions on varied subjects to defend the opposite opinion in a hypothetical debate. At the end of the debate the people had come to adopt the viewpoint they were defending, regardless of the hypothetical nature of the actual debate.Does anyone know the name of this phenomenon, or better yet, have a link explaining it?
Phenomenon causing people to change their opinion when they are asked to hypothetically defend an opposing viewpoint?
terminology;social psychology
null
_softwareengineering.299165
In my reasearch of Dependendcy Injection so far I haven't seen an example object being treated as both a client and a service (meaning a service [value, factory, etc] which has its own dependencies).Can a component be both a client and a service without breaking some fundamental aspect of DI? Is this normal to do in DI? For clarification, I'm asking if a component can both be a dependency, and have dependencies, making it both a client and a service in Dependency Injection.
Can a DI object be both a client and a service simultaneously?
dependency injection
Yes. Think of the classic DI example - a Logger - which itself might take dependencies on a FileSystemWriter and a DatabaseWriter.
_cs.35817
Let $X$ and $Y$ be two sets of points in $\mathbb{R}^3$. Assume that the cardinality of $Y$ is larger (much larger if you want) than $X$. For each $x_i \in X$, I need to find all $y \in Y$ such that the distance between $x_i$ and $y$ is less than a (fixed) radius $R$. That is, for each $x_i$, I want the set $E_i = \{y \in Y: \|x_i-y\|\ \leq R\}$.Now this looks to me like a nearest-neighbors type problem just with two different sets of points. If I'm correct, usually something like an R-tree or kd-tree is good for finding nearest neighbors within a single set $X$. But this seems a bit different. I could naively just iterate through $X$ and find the $y_j \in Y$ such that $\|x_i-y_j\| \leq R.$ and I suppose store that in a gigantic array, but this seems like the worst possible method. On the bright side, this is at least embarassingly parallel so there is that at least.Any suggestions would be greatly appreciated and I apologize if this is a trivial question (I'm not a computer scientist!) Also, if this is the incorrect place to ask such a question, please let me know. If the question is unclear or requires additional information, just let me know. Thanks!
Good data structure for finding all points in one set a distance from each point in another set
data structures;computational geometry;numerical algorithms
null
_unix.127141
I have two CentOS 5.4 Directory Servers that sync information on a daily bases. I'm wanting to replace them with two RHEL 6.4 Directory Servers. Before the existing two are decommissioned all four need to be syncing on a daily basis until we are certain there aren't going to be any issues.Essentially the RHEL DS and the CentOS DS directory servers are the same things so I'm betting that they can sync, but my main question is if a RHEL 6 DS can sync with a RHEL/CentOS 5 DS? Again I'm thinking they can because the database should be nearly the same for both, but I'm hoping someone knows for certain. If they can't natively sync I'm hoping find the best way to configure them so that they can. My last issue is that the RHEL6 DS will have an additional schema (Samba). If the older DS doesn't have that schema will it just be left out when the servers sync?
Can a RHEL 6.4 DS sync with a CentOS 5.4 DS
centos;rhel;ldap;openldap
null
_cs.12154
Let G be a directed graph with non-negative weights. We call a path between two vertices an odd path if its weight is odd.We are looking for an algorithm for finding the weight of the shortest odd path between any two vertices in the graph.If possible, describe one algorithm that is reduction-based (that is, make some modification to the graph so that application of Floyd-Warshall, or any other known algorithm, and then deciphering the answer will give the result, see http://en.wikipedia.org/wiki/Reduction_(complexity)) and one that is direct (that is, make some modification to Floyd-Warshall in order for it to solve this problem).
Shortest path with odd weight
algorithms;graph theory;graphs;shortest path
DirectI answered this here:https://stackoverflow.com/questions/11900830/using-floyd-warshall-algorithm-to-determine-an-odd-matrix/11902296#11902296Basically:Run the algorithm twice (literally a for loop that runs 2 times around the F-W loops) because the path may be longer than the number of verticesSave both the best odd and best even path costs for each pair of vertices - instead of cost[v1][v2] I use cost[v1][v2][evenness].Proof that running the algorithm twice is sufficient: let's assume a path in the graph has more than 2V vertices -> at least one vertex C must appear 3 times -> it must appear at least twice with the same evenness-of-path-up-to-this-point E. So the path is of the form (with C(E) meaning vertex C appearing with evenness E):P0 - C(E) - P1 - C(E) - P2where P0, P1 and P2 are segments of the path (perhaps empty). But this path has the same evenness, initial and final state as:P0 - C(E) - P2And due to non-negative weights, the former path can't be shorter. So running the algorithm twice is sufficient.ReductionFrom G, create G' in the following way:For each vertex Vi in G, add Vi_odd and Vi_even to G' (a simple implementation is: i_even := 2*i, i_odd := 2*i+1, and the inverse, i = i_either/2)For each edge in G, let Vi be the source vertex, Vj the target vertex, W the weight. If W is odd, add edges (Vi_odd, Vj_even) and (Vi_even, Vj_odd) with weight W. If W is even, add edges (Vi_even, Vj_even) and (Vi_odd, Vj_odd) with weight W.Run F-W on G'. The weight of the path from Vi_even (initial path weight is 0 = even) to Vj_odd in G' is the weight of the shortest odd path from Vi to Vj in G. The weight of the path from Vi_even to Vj_even is the shortest even path.
_unix.184574
I have Linux Mint Version 7.1 Rebecca. What do I need to write in the command line in order to find this information. I tried uname -a , but I got informations about my computer name, Kernel Version etc. but not the name itself.
How can I get my Linux distribution name and version using the command line ?
command line;distributions
null
_unix.167686
We can cut and paste current line in bash with ctl+u and ctl+y But I have read here that bash doesn't have clipboard concept, so how those shortkeys working?(or in another way: what they doing?)
clipboard in bash
bash;clipboard;line editor
Killing and yanking text are readline features. bash normally uses readline but you could argue that it is not really a part of bash.You can test that withbash --noediting
_unix.69098
I'm running a Python program on my Linux server, and depending on some external data it has to run again at xx minutes or hours from now.So let's say it runs at 6 AM, and then it has to run again at 7 AM.Then, at 7AM, it checks some things and it has to run again at 15:45, and then the next day at 2.05AM, and then the next day at 4.05AM etc.As you can see there is no predefined logic in the times it has to run, it has to be defined at the time it runs.The only task schedule mechanism I know is crontab, bu I'm not sure how to add tasks to it without running crontab -e and besides that crontab seems more for recurring tasks and in my case I would add a crontab job and after running it once remove it again and add a new one.The only thing I could come up with was to set the next rundate in a textfile, and let a crontab job check it every minute to see if it is time to run the program.
How can I schedule a python program to run from another python program?
cron;python;scheduling
crontab should be used for jobs that you want to have repeated regularly. An alternative is at. With this utility you can schedule jobs that you want to execute only once, but in the future.From within the python-script, you should be able to add a command to the queue of at. The link page together with the man-page should give you enough information to get going.As per @Michel's comment, this will benewruntime = (datetime.datetime.now() + datetime.timedelta(minutes=5)).strftime(%H:%M %d.%m.%Y)command = 'echo python mainprog.py | at ' + newruntimeos.system(command)
_unix.24134
Suppose I have a dir tree like this:ROOTDIR --SUBDIR1 ----SUBDIR2 ----SUBDIR3I am looking for a command such that when I input:$ [unknown command] ROOTDIRThe whole dir tree can be deleted if there is no file but only dirs inside the whole tree. However, say if there is a file called hello.pdf under SUBDIR1:ROOTDIR --SUBDIR1 --hello.pdf ----SUBDIR2 ----SUBDIR3Then the command must only delete SUBDIR2 and below.
Remove empty directory trees (removing as many directories as possible but no files)
shell;directory;rm
Alexis is close. What you need to do is this:find . -type d -depth -empty -exec rmdir {} \;That will first drill down the directory tree until it finds the first empty directory, then delete it. Thus making the parent directory empty which will then be deleted, etc. This will produce the desired effect (I do this probably 10 times a week, so I'm pretty sure it's right). :-)
_codereview.64601
I'm using the following code to initialise 8 I/O-ports (i.e. GPIO pins on a Raspberry Pi). That's 4 x 2 pins, each duo controls a switch, A to D, and each duo consists of a pin for On and a pin for Off. def init_switches(): switch = { 'A': dict(On = 22, Off = 12), 'B': dict(On = 19, Off = 11), 'C': dict(On = 18, Off = 16), 'D': dict(On = 15, Off = 13) } # define all individual pins as output for ID in switch: for pin in switch[ID]: GPIO.setup(switch[ID][pin], GPIO.OUT) return switchI chose this way, a set of dicts, because it allows me to say:switch = init_switches()switch['A']['On'] The last line makes for nice readable code. However the nested for loop is not so elegant. Isn't there a more concise way?Edit: I'm deliberately iterating over keys to get to values. Values are pin numbers. Pin numbering is not arbitrary, but has to do with hardware design. It came out this way because it allowed the easiest circuitry to the switch controller. I'm deliberately hiding all that from the coding, because it's a different chapter altogether.
Iterate over items in a set of dicts
python;dictionary;set
In both nested loops, it seems you really need the values of dictionaries.You iterate over the keys just to use them to get the values:for ID in switch: for pin in switch[ID]: GPIO.setup(switch[ID][pin], GPIO.OUT)A more direct approach would be to iterate over the values instead of the keys:for pins in switch.values(): for pin in pins.values(): GPIO.setup(pin, GPIO.OUT)A minor thing, the definition of switch doesn't follow PEP8,because of the spaces around the = when setting the dictionary keywords.This is the recommended style:switch = { 'A': dict(On=22, Off=12), 'B': dict(On=19, Off=11), 'C': dict(On=18, Off=16), 'D': dict(On=15, Off=13)}
_unix.302479
I want to use ag to print the classes and their methods in a python file. I thought that this would be easy using:ag --context=0 --nocolor -os '^\s*(def|class)\s+[_A-Za-z]*' prog.pybut for reasons I don't understand this is also matching blank lines. For example, if you make prog.py the followingclass MyFavouriteClass def __init__ def __contains__ blah class MyNextFavouriteClass def _repr_ def __iter__then it returns the full file, including the blank lines, except for the line containing blah. Of course, I can always pipe the output into something else to remove the blank lines but I'd rather get it right the first time. I suspect that the problem has nothing to do with the regular expression and, instead, that it's a feature of ag's --context, --after and --before flags but I can't find a combination of these that does what I want.Any ideas?
Why is ag printing blank lines from this file?
regular expression;search;ag
It's not the --context, but the \s* at the start of your regex pattern.It seems ag doesn't search line-by-line like normal grep, but looks at the whole file in one go (or at least several lines at a time). A bit like this Perl one-liner would:perl -0777 -ne 'print $&\n while /^\s*(def|class)\s+[_A-Za-z]*/msg' ../prog.pySo, since \s matches any whitespace, including newlines, it matches the previous empty line, the newline, spaces in front of the next, and then the def keyword. If you add an empty line before the blah line, it's not printed, since blah doesn't fit the pattern.To get rid the unwanted match, use /^ *... or /^[ \t]*... instead of /^\s*.... (space+asterisk in the first one)
_unix.251518
I'm trying to configure my keyboard in this way:I have 3 layouts, 2 of which I use fairly often (eng, rus) and 1 I use occasionally (e.g. when I'm writing some official letters) - cz. The difference between cz and eng keyboard layouts make it difficult to for example write code with this layout, and I use it rare enough to have it out of basic layouts cycle. So the question is: can I somehow configure X to cycle through 2 layouts by-default[en/ru] and turn on cz layout when its needed by pressing CapsLock? Thanks,
Configuring keyboard layouts: 3-way switch, 3rd layout when CapsLock is on
xorg;keyboard layout
null
_unix.226683
I am trying to install Debian Jessie on my new laptop. I downloaded the amd64 Live CD, but the UEFI doesn't recognize my Debian DVD ROM.I disabled the secure UEFI option, but it didn't work, UEFI doesn't show CD/DVD boot option. I attempted to boot with an Ubuntu Live CD and it works fine.I thought that Debian supported UEFI boot.Any ideas?Note: My laptop is a Dell Inspiron 15 5000 Series with Windows 8.1.
Debian 8 UEFI support
debian;uefi;debian installer
Yesterday I installed Debian on a recent Asus Pxx model using the netinstall-iso using a usb-stick and I was able to finish the install without any problems or warnings. - secure boot MUST be disabled and this is often only possible cq visible upon setting a bios-password.Have you tried writing the iso to a stick ?
_softwareengineering.139666
I very often find myself in situations where I should have opened a parentheses, but forgot and end up furiously tapping the left arrow key to get to the spot I should have put it, and doing the same to get back to where I was - that, or removing one hand from the keyboard to do it with the mouse. Either way, it's a stupid mistake on my part and a poor use of time going back to fix it. For example, if typing something likevar x = 100 - var1 + var2;I might get to the end of the statement and realize I wanted to subtract the sum of var1 and var2 from 100 and not add var2 to the difference of 100 and var1. I can't really expect an IDE to prevent my mistakes, but I was thinking there could be a simple enough feature that would save time when they're made. Specifically, some kind of function that, after a closing parenthesis is added where there isn't an opening one, would start ghosting in an opening parenthesis at different statements and allow the user to switch between them. For example:Say you have the following statement:var x = oldY * oldX + newY / newX - left - right;If you put a closing parenthesis after right and pressed the shortcut, the IDE would do:var x = oldY * oldX + newY / newX - ( left - right);press left, and then:var x = oldY * oldX + newY / ( newX - left - right);...then:var x = oldY * oldX + ( newY / newX - left - right);Anyway... Does this feature exist? If not, should it exist? What do senior programmers do when this happens?
Programming IDEs feature to add a forgotten open parentheses?
ide;experience;mistakes
Senior programmers use the Next/Previous word, start of line end of line hot keys to navigate the code - if you ever get a chance, watch a vi expert in action. These things 'just happen' - you don't think left, left, left, left, Brace, right right right, you think brace over there and your fingers do it for you. Senior devs also don't worry too much about the time taken to type. We are not the Typing Pool - paid for word/minute. We add a parenthesis (or any artifact that makes the code readable, let alone correct) when needed, as we know the time to write it is trivial compared the time it will be read thousands of times.Further senior developers would not write var x = oldY * oldX + ( newY / newX - left - right);As it's very odd code that does not 'look' right, meaning even more time will be spent reading it and trying to second guess what the original write wanted it to do (Any developer should be able to work out what it does).
_codereview.37418
I have made an application to display images in the form of gallery, from terminal if you are standing at the same location then it will open those images in the gallery if it does not have it will prompt to select the directory.below is the module: gallery.pyimport sysimport osimport utilsfrom PyQt4 import QtGui, QtCoreclass MyListModel(QtCore.QAbstractTableModel): def __init__(self, window, datain, col, thumbRes, parent=None): Methods in this class sets up data/images to be visible in the table. Args: datain(list): 2D list where each item is a row col(int): number of columns to show in table thumbRes(tuple): resolution of the thumbnail QtCore.QAbstractListModel.__init__(self, parent) self._slideShowWin = window self._thumbRes = thumbRes self._listdata = datain self.pixmap_cache = {} self._col = col def colData(self, section, orientation, role): if role == QtCore.Qt.DisplayRole: return None def headerData(self, section, orientation, role): if role == QtCore.Qt.DisplayRole: if orientation in [QtCore.Qt.Vertical, QtCore.Qt.Horizontal]: return None def rowCount(self, parent=QtCore.QModelIndex()): return len(self._listdata) def columnCount(self, parent): return self._col def data(self, index, role): method sets the data/images to visible in table if index.isValid() and role == QtCore.Qt.SizeHintRole: return QtCore.QSize(*self._thumbRes) if index.isValid() and role == QtCore.Qt.TextAlignmentRole: return QtCore.Qt.AlignCenter if index.isValid() and role == QtCore.Qt.EditRole: row = index.row() column = index.column() try: fileName = os.path.split(self._listdata[row][column])[-1] except IndexError: return return fileName if index.isValid() and role == QtCore.Qt.ToolTipRole: row = index.row() column = index.column() try: fileName = os.path.split(self._listdata[row][column])[-1] except IndexError: return exifData = \n.join(list(utils.getExifData((self._listdata[row][column])))) return QtCore.QString(exifData if exifData else fileName) if index.isValid() and role == QtCore.Qt.DecorationRole: row = index.row() column = index.column() try: value = self._listdata[row][column] except IndexError: return pixmap = None # value is image path as key if self.pixmap_cache.has_key(value) == False: pixmap=utils.generatePixmap(value) self.pixmap_cache[value] = pixmap else: pixmap = self.pixmap_cache[value] return QtGui.QImage(pixmap).scaled(self._thumbRes[0],self._thumbRes[1], QtCore.Qt.KeepAspectRatio) def flags(self, index): return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable def setData(self, index, value, role=QtCore.Qt.EditRole): if role == QtCore.Qt.EditRole: row = index.row() column = index.column() try: newName = os.path.join(str(os.path.split(self._listdata[row][column])[0]), str(value.toString())) except IndexError: return utils._renameFile(self._listdata[row][column], newName) self._listdata[row][column] = newName self.dataChanged.emit(index, index) return True return Falseclass GalleryUi(QtGui.QTableView): Class contains the methods that forms the UI of Image galery def __init__(self, window, imgagesPathLst=None): super(GalleryUi, self).__init__() self._slideShowWin = window self.__sw = QtGui.QDesktopWidget().screenGeometry(self).width() self.__sh = QtGui.QDesktopWidget().screenGeometry(self).height() self.__animRate = 1200 self.setUpWindow(imgagesPathLst) def setUpWindow(self, images=None): method to setup window frameless and fullscreen, setting up thumbnaul size and animation rate if not images: path = utils._browseDir(Select the directory that contains images) images = slideShowBase.ingestData(path) thumbWidth = 200 thumbheight = thumbWidth + 20 self.setWindowFlags( QtCore.Qt.Widget | QtCore.Qt.FramelessWindowHint | QtCore.Qt.X11BypassWindowManagerHint ) col = self.__sw/thumbWidth self._twoDLst = utils.convertToTwoDList(images, col) self.setGeometry(0, 0, self.__sw, self.__sh) self.showFullScreen() self.setColumnWidth(thumbWidth, thumbheight) self._lm = MyListModel(self._slideShowWin, self._twoDLst, col, (thumbWidth, thumbheight), self) self.setShowGrid(False) self.setWordWrap(True) self.setModel(self._lm) self.resizeColumnsToContents() self.resizeRowsToContents() self.selectionModel().selectionChanged.connect(self.selChanged) def selChanged(self): if self._slideShowWin: row = self.selectionModel().currentIndex().row() column = self.selectionModel().currentIndex().column() # if specific image is selected the slideshow opens paused. self._slideShowWin.playPause() self._slideShowWin.showImageByPath(self._twoDLst[row][column]) def animateUpSlideShow(self): animate the slideshow window back up to view mode and starts the slideShowBase where it was paused. self.animateUpGallery() self.animation = QtCore.QPropertyAnimation(self._slideShowWin, geometry) self.animation.setDuration(self.__animRate); self.animation.setStartValue(QtCore.QRect(0, self.__sh, self.__sw, self.__sh)) self.animation.setEndValue(QtCore.QRect(0, 0, self.__sw, self.__sh)) self.animation.start() self._slideShowWin.activateWindow() self._slideShowWin.raise_() self._slideShowWin.playPause() def animateUpGallery(self): animate the gallery window up to make slideshow visible self.animGallery = QtCore.QPropertyAnimation(self, geometry) self.animGallery.setDuration(self.__animRate); self.animGallery.setStartValue(QtCore.QRect(0, 0, self.__sw, self.__sh)) self.animGallery.setEndValue(QtCore.QRect(0, -(self.__sh), self.__sw, self.__sh)) self.animGallery.start() def keyPressEvent(self, keyevent): Capture key to exit, next image, previous image, on Escape , Key Right and key left respectively. event = keyevent.key() if event == QtCore.Qt.Key_Escape: if self._slideShowWin: self._slideShowWin.close() self.close() if event == QtCore.Qt.Key_Up: if self._slideShowWin: self.animateUpSlideShow()def main(imgLst=None): method to start gallery standalone app = QtGui.QApplication(sys.argv) window = GalleryUi(None, imgLst) window.raise_() sys.exit(app.exec_())if __name__ == '__main__': curntPath = os.getcwd() if len(sys.argv) > 1: curntPath = sys.argv[1:] main(utils.ingestData(curntPath))and dependent module utils.pysome of the methods in the below are used by module slideshow which can also launch the image gallery from which a 2D list containing image paths.import osimport sysimport exifreadfrom PyQt4 import QtGuidef isExtensionSupported(filename): Supported extensions viewable in SlideShow reader = QtGui.QImageReader() ALLOWABLE = [str(each) for each in reader.supportedImageFormats()] return filename.lower()[-3:] in ALLOWABLEdef imageFilePaths(paths): imagesWithPath = [] for _path in paths: dirContent = getDirContent(_path) for each in dirContent: selFile = os.path.join(_path, each) if ifFilePathExists(selFile) and isExtensionSupported(selFile): imagesWithPath.append(selFile) return list(set(imagesWithPath))def ifFilePathExists(selFile): return os.path.isfile(selFile)def getDirContent(path): try: return os.listdir(path) except OSError: raise OSError(Provided path '%s' doesn't exists. % path)def getExifData(filePath): Gets exif data from image try: f = open(filePath, 'rb') except OSError: return tags = exifread.process_file(f) exifData = {} if tags: for tag, data in tags.iteritems(): if tag != 'EXIF Tag 0x9009': yield %s: %s % (tag, data)def convertToTwoDList(l, n): Method to convert a list to two dimensional list for QTableView return [l[i:i+n] for i in range(0, len(l), n)]def _renameFile(fileToRename, newName): method to rename a image name when double click try: os.rename(str(fileToRename), newName) except Exception, err: print errdef _browseDir(label): method to browse path you want to view in gallery selectedDir = str(QtGui.QFileDialog.getExistingDirectory(None, label, os.getcwd())) if selectedDir: return selectedDir else: sys.exit()def generatePixmap(value): generates a pixmap if already not incache pixmap=QtGui.QPixmap() pixmap.load(value) return pixmapdef ingestData(paths): This method is used to create a list containing images path to slideshow. if isinstance(paths, list): imgLst = imageFilePaths(paths) elif isinstance(paths, str): imgLst = imageFilePaths([paths]) else: print You can either enter a list of paths or single path return imgLstI need a code review for the implementation, any Suggestions/hints is welcome that I can use to improve the code and more testable?
Feedback on logic implementation of PyQt4 based Image gallery using QTableView
python;design patterns
Disclaimer: this is not a design pattern review, but rather a Pythonization one.Not always returning a value: MyListModel.colData() MyListModel.headerData(). Even though Python implicitly returns None if you don't specify a return value or return statement at all, it is better to return explicitly in all the code branches, or have a catch-all return:def colData(self, section, orientation, role): if role == QtCore.Qt.DisplayRole: return None return NoneInconsistent return statements: in MyListModel.data(), MyListModel.setData() and others you mix return statements with value and the ones without value. Consider returning None explicitly.In MyListModel.data() the check index.isValid() is repeated over and over again, a single check would be sufficient:if not index.isValid(): return Noneif role == QtCore.Qt.SizeHintRole: return QtCore.QSize(*self._thumbRes)Always use a file as a context manager, this way you wouldn't leak open files (e.g. in getExifData), even if your code with throw during file processing:try: with open(filePath, 'rb') as f: # Work with fileexcept OSError: returnUse list comprehensions and generator expressions, they rock! Here's how I would rewrite getExifData:def get_exif_data(file_path): Gets exif data from image try: with open(file_path, 'rb') as f: return (%s: %s % (tag, data) for tag, data in exifread.process_file(f).iteritems() if tag != 'EXIF Tag 0x9009') except OSError: returnHere's the imageFilePaths:def image_file_paths(paths): images = { joined_path for path in paths for each in get_dir_content(path) for joined_path in [os.path.join(path, each)] if if_file_path_exists(joined_path) if is_extension_supported(joined_path) } return list(images)You should really follow pep8, name your methods with_underscore_separators, but do notCamelCase them.Methods/functions should not have unexpected side-effects like printing error messages on their own (see _renameFile, ingestData) or even worse - perform exit (see _browseDir). Consider raising appropriate exceptions, e.g. ValueError would be a perfect fit for parameter type-checking.
_unix.303024
I have a TP-Link WDR4300 router with OpenWRT BarrierBreaker (vargalex build ver. 1.1.7).I use due to my Raspberry (SMB, PMA, Plex, etc) DDNS (duckdns.org) to reach my Router outside of my LAN (I've tried to configure VPN on the router, but somehow I can't find the right configuration). My services are using theese ports: 139, 445, 8080, 8081, 8877, 56565 but somewhy 53 (dnsmasq) port is opened from WAN and I can't block it.netstat outputs:netstat -annetstat -plnnslookup output:> server <myremoteaddress>.duckdns.orgDefault Server: remoteconnection.duckdns.orgAddress: <myipaddress>> google.com.Server: <myremoteaddress>.duckdns.orgAddress: <myipaddress>Non-authoritative answer:Name: google.comAddresses: xxxx:yyyy:400d:zzzz::200e ***.***.72.20 ***.***.72.34 ***.***.72.45 ***.***.72.24 ***.***.72.49 ***.***.72.44 ***.***.72.39 ***.***.72.25 ***.***.72.30 ***.***.72.54 ***.***.72.40 ***.***.72.29 ***.***.72.50 ***.***.72.59 ***.***.72.55 ***.***.72.35I'm using Google DNS (8.8.8.8, 8.8.4.4).I've tried to add some rule to block port 53, unsuccessfully...There are the rules what I've added to the firewall config (/etc/config/firewall) and connected to the desired port:config rule option src 'wan' option name 'block_port_53' option dest_port '53' option target 'REJECT' option proto 'all'config rule option target 'ACCEPT' option proto 'tcp udp' option dest_port '53' option name 'Guest DNS' option src 'guest' option enabled '0'config rule option src 'wan' option dest 'lan' option name 'restrict_dns_53_lan' option dest_port '53' option target 'REJECT'config rule option src 'wan' option dest_port '53' option name 'restrict_dns_forward' option target 'REJECT' option proto 'tcp udp' option dest 'lan'Guest DNS is currently disabled and it is for the Guest WiFi (it's the Guest DNS zone).What am I doing wrong?The main reason to block port 53 is the chinese bots which is trying to rebind my DNS. My router's System Log is full of this:Jul 4 20:12:53 dnsmasq[2524]: possible DNS-rebind attack detected: 9406151-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.myxns.cnJul 4 20:12:53 dnsmasq[2524]: possible DNS-rebind attack detected: 9406163-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.ffdns.netJul 4 20:12:53 dnsmasq[2524]: possible DNS-rebind attack detected: 9406153-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.myxns.cnJul 4 20:12:54 dnsmasq[2524]: possible DNS-rebind attack detected: 9406166-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.ffdns.netJul 4 20:12:54 dnsmasq[2524]: possible DNS-rebind attack detected: 9406154-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.myxns.cnJul 4 20:12:54 dnsmasq[2524]: possible DNS-rebind attack detected: 9406157-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.ffdns.netJul 4 20:12:54 dnsmasq[2524]: possible DNS-rebind attack detected: 9406156-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.myxns.cnJul 4 20:12:54 dnsmasq[2524]: possible DNS-rebind attack detected: 9406148-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.myxns.cnJul 4 20:12:54 dnsmasq[2524]: possible DNS-rebind attack detected: 9406149-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.myxns.cnJul 4 20:12:54 dnsmasq[2524]: possible DNS-rebind attack detected: 9406155-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.myxns.cnJul 4 20:12:54 dnsmasq[2524]: possible DNS-rebind attack detected: 9406160-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.ffdns.netJul 4 20:12:55 dnsmasq[2524]: possible DNS-rebind attack detected: 9406164-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.ffdns.netJul 4 20:12:55 dnsmasq[2524]: possible DNS-rebind attack detected: 9406158-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.ffdns.netJul 4 20:12:55 dnsmasq[2524]: possible DNS-rebind attack detected: 9406150-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.myxns.cnJul 4 20:12:55 dnsmasq[2524]: possible DNS-rebind attack detected: 9406161-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.ffdns.netJul 4 20:12:55 dnsmasq[2524]: possible DNS-rebind attack detected: 9406147-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.myxns.cnJul 4 20:12:55 dnsmasq[2524]: possible DNS-rebind attack detected: 9406152-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.myxns.cnJul 4 20:12:56 dnsmasq[2524]: possible DNS-rebind attack detected: 9406162-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.ffdns.netJul 4 20:12:57 dnsmasq[2524]: possible DNS-rebind attack detected: 9406159-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.ffdns.netJul 4 20:12:58 dnsmasq[2524]: possible DNS-rebind attack detected: 9406165-0-1896986649-4159633587.ns.113-17-184-25-ns.dns-spider.ffdns.netJul 4 20:15:24 dnsmasq[2524]: possible DNS-rebind attack detected: 4376755-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.ffdns.netJul 4 20:15:24 dnsmasq[2524]: possible DNS-rebind attack detected: 4376759-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.ffdns.netJul 4 20:15:24 dnsmasq[2524]: possible DNS-rebind attack detected: 4376746-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.myxns.cnJul 4 20:15:24 dnsmasq[2524]: possible DNS-rebind attack detected: 4376741-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.myxns.cnJul 4 20:15:24 dnsmasq[2524]: possible DNS-rebind attack detected: 4376750-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.myxns.cnJul 4 20:15:26 dnsmasq[2524]: possible DNS-rebind attack detected: 4376756-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.ffdns.netJul 4 20:15:26 dnsmasq[2524]: possible DNS-rebind attack detected: 4376752-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.ffdns.netJul 4 20:15:26 dnsmasq[2524]: possible DNS-rebind attack detected: 4376760-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.ffdns.netJul 4 20:15:26 dnsmasq[2524]: possible DNS-rebind attack detected: 4376754-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.ffdns.netJul 4 20:15:26 dnsmasq[2524]: possible DNS-rebind attack detected: 4376758-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.ffdns.netJul 4 20:15:26 dnsmasq[2524]: possible DNS-rebind attack detected: 4376753-0-3084195388-824858262.ns.183-213-22-60-ns.dns-spider.ffdns.netPlease help me get rid of them.
OpenWRT - Can't block DNS port (53) from WAN-LAN direction
dns;port forwarding;openwrt;dnsmasq
Have you tried option proto 'tcpudp'? Both the documentation & how this works in iptables implies this is needed, when you specify port numbers. tcpudp is actually the default. So you don't want to use all or tcp udp (nor udp, as DNS can use both protocols in normal operation).[openwrt] Match incoming traffic directed at the given destination port or port range, if relevant proto is specified.[iptables] These extensions can be used if `--protocol tcp' is specified. It provides the following options: ... --destination-port
_cstheory.18533
Consider this problem: Find a tiling of an $m \times n$ rectangle by minimum number of integer-sided squares.Is there any polynomial time (in $m$ and $n$) algorithm to do this? What is the best known algorithm?
Tiling a rectangle with the fewest squares
ds.algorithms;co.combinatorics
null
_unix.342962
I'm trying to compare a new file (e.g., new.txt) to an old file (e.g., old.txt) to see what was added in the new file. I'm trying to add the newly added information to a new file called newCourses.txt and the modified information to modifiedCourses.txt. If this is not possible with a diff, what are the alternatives without installing a package or software?old.txt2016 2BUSI 4850 K002 BUSINESS MW 02:10P-09:30P2016 2BUSI 4840 K002 PRESPECH MW 07:10P-09:30P2016 2BUSI 4820 K002 SCHLOFSC MW 07:10P-09:30P2016 2BUSI 4870 K002 HISTORYZ MW 04:10P-09:30Pnew.txt2016 2BUSI 4850 K002 BUSINESS MW 07:10P-09:30P2016 2BUSI 4840 K002 PRESPECH MW 07:10P-09:30P2016 2BUSI 4820 K002 SCHLOFSC MF 07:10P-09:30P2016 2BUSI 4870 K002 HISTORYZ MW 06:10P-09:30P2017 4NONE 2938 K112 RECREATI TS 11:10P-11:55PThe output when I do diff old.txt new.txt:1c1< 2016 2BUSI 4850 K002 BUSINESS MW 02:10P-09:30P---> 2016 2BUSI 4850 K002 BUSINESS MW 07:10P-09:30P3,4c3,5< 2016 2BUSI 4820 K002 SCHLOFSC MW 07:10P-09:30P< 2016 2BUSI 4870 K002 HISTORYZ MW 04:10P-09:30P\ No newline at end of file---> 2016 2BUSI 4820 K002 SCHLOFSC TF 07:10P-09:30P> 2016 2BUSI 4870 K002 HISTORYZ MW 06:10P-09:30P> 2017 4NONE 2938 K112 RECREATI TS 11:10P-11:55P\ No newline at end of fileHow can I output it to two different files such asnewCourses.txt would contain2017 4NONE 2938 K112 RECREATI TS 11:10P-11:55Pand modifiedCourses.txt would contain2016 2BUSI 4850 K002 BUSINESS MW 07:10P-09:30P2016 2BUSI 4820 K002 SCHLOFSC TF 07:10P-09:30P2016 2BUSI 4870 K002 HISTORYZ MW 06:10P-09:30P
Saving diffs to two files for modified and new additions
text processing;command line;diff
You could use awk:awk 'NR==FNR{ z[$5]=$0; next}{ if ($5 in z){ if ($0!=z[$5]){print >modifiedCourses.txt}} else { print >newCourses.txt}}' old.txt new.txtThis reads old.txt and saves the lines into an array (the indices are the names of the courses) and then reads new.txt and for each course it checks if it's an index of the array: if it is, it checks if the line has changed and if so it prints it to modifiedCourses.txt ; if not an index, it prints the line to newCourses.txtYou can change $0 to $7 if the only change that matters is the hours.
_unix.190308
I am trying to install synergy from here. When I run it I get the error:system tray unavailable, quittingI am running Freya. Any help would be appreciated or the name of different software to share my mouse and keyboard with a Windows machine.
Synergy and ElementaryOS
elementary os;synergy
null
_unix.282048
I have deleted (because of errors) the /tmp folder, which contains the pulseaudio folder.The question is: how to restart pulseaudio without restarting X11?If I restart X11, pulseaudio works fine. I have triedstart-pulseaudio-x11 which gives this errorN: [pulseaudio] main.c: User-configured server at {54116d3eeebf4e5b5e1f50d757286535}unix:/tmp/pulse-l7iX3tHbLHHy/native, refusing to start/autospawn.Connection failure: Connection refusedpa_context_connect() failed: Connection refusedI have tried this pulseaudio --startand it gives this errorN: [pulseaudio] main.c: User-configured server at {54116d3eeebf4e5b5e1f50d757286535}unix:/tmp/pulse-l7iX3tHbLHHy/native, refusing to start/autospawn.How do I restart pulseaudio?p.s. Of course I have killed the previous pulseaudio daemon.
Pulseaudio: how to restart without restart X11 if delete tmp?
pulseaudio
null
_codereview.159659
I have implemented the CoR pattern in c++11 using smart_ptr for association between chain of receivers. The client owns all the receiver objects(which can be created and destroyed at runtime) and the receiver object maintain weak_ptr for subsequent request handler.// ChainOfResponsibility.cpp : Defines the entry point for the console application.//#include stdafx.h#include <memory>#include <tuple>#include <string>#include <iostream>#include <vector>// Event, sent from sender to many receivers. The first parameter decides who should handle.using Event = std::tuple<int, std::string>;//Abstract class which manages the link to the subsequent classes.class Handler {public: Handler(std::shared_ptr<Handler> successor = nullptr) :m_successor(successor) {} virtual void handle(Event e) = 0; virtual ~Handler() {}protected: std::weak_ptr<Handler> m_successor;};//clients need to implement handle functionclass Agent : public Handler {public: Agent(std::shared_ptr<Handler> successor = nullptr):Handler(successor) {} void handle(Event e) override { if (std::get<0>(e) == 1) { std::cout << Agent handled the request: + std::get<1>(e) << std::endl; } else { try { std::shared_ptr<Handler> ptr(m_successor); ptr->handle(e); } catch(std::bad_weak_ptr) { std::cout << No successor handler << std::endl; } } } virtual ~Agent() override {}};class Supervisor : public Handler {public: Supervisor(std::shared_ptr<Handler> successor = nullptr) :Handler(successor) {} void handle(Event e) override { if (std::get<0>(e) == 2) { std::cout << Supervisor handled the request: + std::get<1>(e) << std::endl; } else { try { std::shared_ptr<Handler> ptr(m_successor); ptr->handle(e); } catch (std::bad_weak_ptr) { std::cout << No successor handler << std::endl; } } } virtual ~Supervisor() override {}};class Boss : public Handler {public: Boss(std::shared_ptr<Handler> successor = nullptr) :Handler(successor) {} void handle(Event e) override { if (std::get<0>(e) == 3) { std::cout << Boss handled the request: + std::get<1>(e) << std::endl; } else { try { std::shared_ptr<Handler> ptr(m_successor); ptr->handle(e); } catch (std::bad_weak_ptr) { std::cout << No successor handler << std::endl; } } } virtual ~Boss() override {}};int main() { //three receivers owned by the client auto boss = std::make_shared<Boss>(); auto supervisor = std::make_shared<Supervisor>(boss); auto agent = std::make_shared<Agent>(supervisor); //events std::vector<Event> events; events.push_back(std::make_tuple(1, Technical support)); events.push_back(std::make_tuple(2, Billing query)); events.push_back(std::make_tuple(1, Product information query)); events.push_back(std::make_tuple(5, Police issue)); events.push_back(std::make_tuple(3, Enterprise client request)); for (auto e : events) { agent->handle(e); } //receivers may be released at run time. boss.reset(); for (auto e : events) { agent->handle(e); } return 0;}Please review this and suggest me the improvemnt.Assumption: Performance is not a primary concern.Please suggest me an elegant implementation if you have seen somewhere else.
Chain-of-Responsibility in C++11 using smart pointers
c++;c++11;design patterns
First nit: boss and supervisor strike me as basically synonymous. So it's kind of confusing that you're using both of them as identifiers in your program. Are these identifiers supposed to be meaningful, or are they just placeholders like Alice or Bob?Also a nit: If your destructor doesn't do anything, don't write it.virtual ~Boss() override {}is just a waste of characters. (The definition of ~Handler() is important because you have to hang the virtual specifier on it; but the definition of ~Boss() is perfectly redundant.)//receivers may be released at run time.boss.reset();I think I don't get it. If this line had instead read supervisor.reset(), wouldn't boss have become unreachable, as far as handling requests was concerned? (Because requests go first to agent; then to agent->m_successor if it's non-null; but supervisor is gone, so handling just stops there.)This seems like a bug in your design.void handle(Event e) override { // ... ptr->handle(e);This function call makes a copy of Event e, which might be expensive since Event contains an arbitrarily long std::string. You could fix this in either of two ways: either by changing the function signature tovoid handle(const Event& e)(throughout the whole hierarchy, of course), or else by changing the function call to ptr->handle(std::move(e)); // move, don't copyI know you said performance isn't a concern, but any time you're using exception handling for control flow you should really reconsider your design. Instead of throwing and catching bad_weak_ptr, I'd recommend if (std::get<0>(e) == 1) { std::cout << Agent handled the request: + std::get<1>(e) << std::endl; } else if (auto ptr = m_successor.lock()) { ptr->handle(e); } else { std::cout << No successor handler << std::endl; }As for how your list of handlers should be defined: almost certainly you should just use a list of handlers (i.e. std::list<Handler> or std::list<std::weak_ptr<Handler>> if you really want to keep your original design's ability to have handlers drop out of the list at random).I don't think that a Handler ought to have any idea of its parent; unless... do you think that the parent of a given handler is part of its identity? For example, in my example above, do you think it does actually make sense that if an Agent's Supervisor dies, the Agent would have no way of contacting his late Supervisor's Boss, so certain requests would go unhandled? If that really is a feature-not-a-bug, then okay.Lastly, even if everything else about this design were good, it's unsettling how easy it would be for someone to write a Handler class that just dropped messages on the floor.class Stockboy : public Handler {public: Stockboy(std::shared_ptr<Handler> successor = nullptr) :Handler(successor) {} void handle(Event e) override { if (std::get<0>(e) == 7) { std::cout << Stockboy handled the request: + std::get<1>(e) << std::endl; } }};IMO, it would be better to take the responsibility for forwarding unhandled messages and move that responsibility right out of the Handler class. Give it to a Dispatcher class whose job is to find the right Handler and call it. The Dispatcher might hold a mapping of ints to handlers so that it could find the right recipient quickly; or it might just query each handler in turn until some handler reports success.
_unix.183572
while read wholelinedo echo ${wholeline} --outputs John Jones #grab all the lines that begin with these values #grep '^John Jones' workfile2 --works, prints contents of workfile2 where the 1st matches grep '^${wholeline}' workfile2 # --does not work. why? it should be the same result.done < workfile1workfile1 contains the value John Jones at the beginning of the line in the file.workfile2 contains the value John Jones at the beginning of the line in the file.How can I change that second grep statement so that it works?It is picking up nothing.
Script to `grep` a file with variable
bash;text processing;grep
You are using single quotes, try using double quotes. For the shell to expand variables, you need to use double quotes. while read wholelinedo echo ${wholeline} --outputs John Jones #grab all the lines that begin with these values #grep '^John Jones' workfile2 # --works, prints contents of workfile2 # where the 1st matches grep ^${wholeline} workfile2 # --does work now, since shell # expands ${wholeline} in double quotesdone < workfile1
_codereview.139904
I finally got around to redoing my Temperature conversion program. I incorporated many elements of everyone's comments, and am uploading the finished program. Any new, or problems that I missed? Maybe a few very late here where I am working. Main focus of this redo was keeping my functions short and single purposed. #include <stdio.h>void inter_face();void welcome();void option_prompt();void input_temp_prompt();int get_option();float get_input_temp();void display_F_to_C(float);void display_C_to_F(float);void display_off();void display_error();float F_to_C(float);float C_to_F(float);enum { F_TO_C = 1, C_TO_F = 2, OFF = 3 } option_type;int main(){ inter_face(); getchar();}void inter_face(){ int option = -1; float input_temp = 0.0; welcome(); while (option != OFF) { option_prompt(); option = get_option(); if (option == F_TO_C || option == C_TO_F) { input_temp_prompt(); input_temp = get_input_temp(); } switch (option) { case F_TO_C: display_F_to_C(F_to_C(input_temp)); break; case C_TO_F: display_C_to_F(C_to_F(input_temp)); break; case OFF: display_off(); break; default: display_error(); } } } void welcome(){ printf(Temperature conversion Calculator!!\nPlease select an option:); printf(\n1.) F to C\t2.) C to F\t3.) off\n\n);} void option_prompt(){ printf(Option: );}void input_temp_prompt(){ printf(Temp: );}float get_input_temp(){ float input_temp = 0; scanf_s(%f, &input_temp); return input_temp;}int get_option(){ int option; scanf_s(%d, &option); return option;} void display_F_to_C(float converted_temp){ printf(Celsius: %f\n, converted_temp);}void display_C_to_F(float converted_temp){ printf(Fahrenheit: %f\n, converted_temp);}void display_off() { printf(OFF\n);}void display_error(){ printf(Incorrect input, try again\n);}float F_to_C(float input_temp) { return (5.0 / 9.0) * (input_temp - 32);}float C_to_F(float input_temp){ return (9.0 / 5.0) * (input_temp)+32;}
Simple Temperature Converter 2 in C
beginner;c;unit conversion
Firstly, I don't quite understand why are you declaring so much functions that consist of a single line dedicated to printing a string. They are only used once and in one file, so there's no need to use a function or constant. I suggest you to get rid of them and replace calls to these functions with their bodies. Also, put break; inside default case (Here you can learn more about the reason why you should do this): switch (option) { case F_TO_C: printf(Celsius: %f\n, F_to_C(input_temp)); break; case C_TO_F: printf(Fahrenheit: %f\n, C_to_F(input_temp)); break; case OFF: printf(OFF\n); break; default: printf(Incorrect input, try again\n); break; } Secondly, I recommend to use puts() instead of printf() when printing simple strings as it is obviously simpler and places a newline automatically (And you use it often throughout your code). Note that this doesn't involve cases when printing formatted strings. switch (option) { case F_TO_C: printf(Celsius: %f\n, F_to_C(input_temp)); break; case C_TO_F: printf(Fahrenheit: %f\n, C_to_F(input_temp)); break; case OFF: puts(OFF); // No need for printf()! break; default: puts(Incorrect input, try again); // No need for printf() as well! break; }Thirdly, I'd suggest to move the body of inter_face() function to main() as it is not used anywhere else and basically creates a run loop, so I don't see any reasons why you should place it in a separate function. In addition to this, you probably want to define your functions before they're used, thus moving all functions above main(). It's not necessary as the compiler will find them anyway, yet I reckon the source code looks better that way (Just imagine reading a book from the end to the beginning).float F_to_C(float input_temp) { return (5.0 / 9.0) * (input_temp - 32);}float C_to_F(float input_temp){ return (9.0 / 5.0) * (input_temp)+32;}float get_input_temp(){ float input_temp = 0; scanf_s(%f, &input_temp); return input_temp;}int get_option(){ int option; scanf_s(%d, &option); return option;} int main(){ int option = -1; float input_temp = 0.0; printf(Temperature conversion Calculator!!\nPlease select an option:); printf(\n1.) F to C\t2.) C to F\t3.) off\n\n); while (option != OFF) { printf(Option: ); option = get_option(); if (option == F_TO_C || option == C_TO_F) { printf(Temp: ); input_temp = get_input_temp(); } switch (option) { case F_TO_C: printf(Celsius: %f\n, F_to_C(input_temp)); break; case C_TO_F: printf(Fahrenheit: %f\n, C_to_F(input_temp)); break; case OFF: puts(OFF); // No need for printf()! break; default: puts(Incorrect input, try again); // No need for printf() as well! break; } } getchar();}Fourthly, you should put function prototypes, enumerations and other objects that carry data (Of course, prototypes do not carry data, yet they belong in header files) into a separate header file (For instance, main.h). That way your source file looks a lot cleaner, and if someone wants to use these functions elsewhere, he can easily find this header file with needed prototypes within.Fifthly, I'd consider either merging or getting rid of get_option() and get_input_temp() functions as they perform the same task, just with different data types. I suggest to create a single function called get_input() that returns a float (Since float can be compared to int without requiring you worry about loosing precision) instead if you don't want to put them inside main() as we did with other redundant functions before. You may then compare these variables normally as usual arithmetic conversions from int to float will occur when comparing float to int (You can learn more about such conversions here, here and here).#include main.h // Prototypes and enum are there! float F_to_C(float input_temp) { return (5.0 / 9.0) * (input_temp - 32);}float C_to_F(float input_temp){ return (9.0 / 5.0) * (input_temp)+32;}float get_input(void){ float input = 0; scanf_s(%f, &input); return input;}int main(){ int option = -1; float input_temp = 0.0; printf(Temperature conversion Calculator!!\nPlease select an option:); printf(\n1.) F to C\t2.) C to F\t3.) off\n\n); while (option != OFF) { printf(Option: ); option = get_input(); if (option == F_TO_C || option == C_TO_F) { printf(Temp: ); input_temp = get_input(); } switch (option) { case F_TO_C: printf(Celsius: %f\n, F_to_C(input_temp)); break; case C_TO_F: printf(Fahrenheit: %f\n, C_to_F(input_temp)); break; case OFF: puts(OFF); // No need for printf()! break; default: puts(Incorrect input, try again); // No need for printf() as well! break; } } getchar();}Also, be sure to check chux's answer. It contains even more useful tips and tricks to improve your code. Especially scanf_s() checks, option = -1 change and math simplification.
_unix.108330
Is there any way to highlight the searched term in tmux copy mode?Below is my tmux config:# remap prefix to Control + aset -g prefix C-aunbind C-bbind C-a send-prefixbind a send-prefix# force a reload of the config fileunbind rbind r source-file ~/.tmux.conf# set window start from 1set -g base-index 1# scrollback buffer n linesset -g history-limit 5000# C-a C-a for the last active windowbind-key C-a last-window# Highlight active windowset-window-option -g window-status-current-bg red# Default colorsset -g status-bg blackset -g status-fg white#unbind %bind - split-window -v#unbind ''bind | split-window -hsetw -g aggressive-resize onbind-key T swap-window -t 1# To ensure keyboard shortcuts inside Vim still work, we need to enable XTerm keybindings.# And to be sure Vim's colors aren't distorted, we enable 256 color mode#setw -g xterm-keys on#set-option -g default-terminal screen-256color# make copy mode use hjklsetw -g mode-keys vi # I especially like being able to search with /,? when in copy-modeset -g status-keys vibind-key -t vi-edit Up history-upbind-key -t vi-edit Down history-down# set shellset -g default-command /bin/bashset -g default-shell /bin/bash# smart pane switching with awareness of vim splitsbind -n C-h run (tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys C-h) || tmux select-pane -Lbind -n C-j run (tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys C-j) || tmux select-pane -Dbind -n C-k run (tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys C-k) || tmux select-pane -Ubind -n C-l run (tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys C-l) || tmux select-pane -Rbind -n C-\ run (tmux display-message -p '#{pane_current_command}' | grep -iq vim && tmux send-keys 'C-\\') || tmux select-pane -l#Sets the appearance of the left sidebarset -g status-left-length 40set -g status-left #[fg=colour39] #S #[fg=yellow] #(whoami)#Sets the appearance of the centersetw -g window-status-fg colour211setw -g window-status-bg defaultsetw -g window-status-attr dimsetw -g window-status-current-fg whitesetw -g window-status-current-bg greensetw -g window-status-current-attr brightsetw -g window-status-activity-bg redsetw -g window-status-activity-fg whitesetw -g window-status-bell-fg whitesetw -g window-status-bell-bg redsetw -g window-status-bell-attr bold#Sets the appearance of the right sidebar, i.e time and clock.set -g status-right #[fg=colour136, bright] %d %b %Rset -g status-utf8 onset -g status-interval 60set -g status-justify centre
tmux copy mode search highlight
tmux;colors
I found this information about tmux search highlighting :According to the developer1, this isn't currently possible in tmux. http://sourceforge.net/mailarchive/message.php?msg_id=27427973Source:How do I highlight a search result in tmux?
_cs.57829
The question:Let $L_1,L_2,...$ be an enumeration of $\mathcal{R}$ and define $A_i = \{\langle M\rangle \ | \ L(M) = L_i\}$. Let $L$ be a language in $\mathcal{RE}$ such that $L \subset \{\langle M\rangle \ | \ \text{M is a TM that always halts}\}$. Prove that there exists an $i$ for which $LA_i = $.Hint $\downarrow$Hint: Build a TM that returns some (which?) element of $L$ and apply a diagonalization argument.My approachI thought of the Hint but I am not sure that the language I get is decidable and I don't know how to prove that all its always halting TMs are not in $L$.
Prove that there is no computable enumeration of all decidable languages
computability;turing machines;undecidability
WLOG assume we are talking about languages over a binary alphabet $\{0,1\}$. Let $M'$ be an enumerating Turing Machine for $L$, i.e., every element of $L$ is eventually output by $M'$. Let $\langle M_j \rangle$ denote the $j$th TM output by $M'$. Define$$L_D = \{ x \mid M_x(x) \text{ does not accept} \},$$where $x$ is interpreted as a number in base 2. Note that $L_D$ is decidable: given $x$ you can decide if $x \in L_D$ by running $M'$ until it outputs $x$th TM $M_x$ and then running $M_x$ on $x$ and flipping the output. This is a decider since all TMs output by $M'$ halt on all inputs. Thus $L_D$ appears in the enumeration of R, say, as $L_k$ for some $k$.It is left to show that $L \cap A_k = \emptyset$. Suppose that there exists a TM $M$ such that $\langle M \rangle \in L \cap A_k$. Then let $\ell$ be the smallest number such that $\langle M \rangle$ is output as the $\ell$th element by the enumerator $M'$, i.e. $M = M_\ell$. Therefore, we have $\ell \in L(M) \iff \ell \in L(M_\ell) \iff \ell \notin L_D \iff \ell \notin L_k \iff \ell \notin L(M)$, which is a contradition.
_unix.62733
I'm running GRUB 2.00 on a Gentoo Linux system.I compile my own kernels manually, and then I install them in /boot with make install. I have the following kernels in /boot at the moment:# ls -1 /boot/vmlinuz*/boot/vmlinuz-3.7.4-gentoo-5/boot/vmlinuz-3.7.4-gentoo-first/boot/vmlinuz-3.7.4-gentoo-fourth/boot/vmlinuz-3.7.4-gentoo-thirdRunning grub2-mkconfig results in the following output:# grub2-mkconfig -o /boot/grub2/grub.cfgGenerating grub.cfg ...Found linux image: /boot/vmlinuz-3.7.4-gentoo-thirdFound linux image: /boot/vmlinuz-3.7.4-gentoo-fourthFound linux image: /boot/vmlinuz-3.7.4-gentoo-firstFound linux image: /boot/vmlinuz-3.7.4-gentoo-5doneIf I now read the resulting /boot/grub2/grub.cfg file, I notice that the following entries have been created:A main default entry which starts vmlinuz-3.7.4-gentoo-thirdA submenu with the all the other entries (including recovery ones), in the same order as the grub2-mkconfig commandThe problem is that at boot time I'd like to load by default the fifth revision of my kernel (vmlinuz-3.7.4-gentoo-5), not the third one (vmlinuz-3.7.4-gentoo-third). I also prefer not to access the submenu for choosing the right kernel to load.How can I change this behaviour? How can I tell GRUB that I want to run the fifth revision of my kernel by default and not the older third revision? In general, how can I change the default entry line to match the kernel I want and not a seemingly random one picked by GRUB?I also tried putting the following lines in /etc/default/grub:GRUB_DEFAULT=savedGRUB_SAVEDEFAULT=trueThis doesn't fix the problem the way I desire. But at least GRUB seems to remembers the latest kernel I booted from and automatically selects it from the submenu. It's just that I don't like to access the submenu.
How to correctly set up the right GRUB 2 default menu entry?
grub2
null
_unix.274739
i would like to capture as backreference something like this.Example:(a-z)But somehow anything I have tried, didn't workI try this:\(([a-z])\)\ or \('('[a-z]')'\)\
backreference sed
sed
>> echo (f) | sed 's/\(([a-z])\)/x\1x/'x(f)x\(([a-z])\) is what you want.
_cs.49901
I was reading Doug McIlroy: McCarthy Presents Lisp and the phrase symbolic differentiation of univariate expressions triggered a faint memory of a demonstration of differentiation done in haskell using higher order functions. (I think my memory is of using the language to produce a function that is the differential of a function given.) However I haven't been able to find any other reference to the above phrase in lisp or ML-based languages. Does anyone have more information on this, and is symbolic differentiation of univariate expressions the same thing as the memory I described?
The symbolic differentiation of univariate expressions
terminology;functional programming;mathematical programming;computer algebra
null
_softwareengineering.48575
I need to develop a simple declarative language to drive an application. I have various computational modules, some of them depending on other modules which also need setup. The problem is that I don't know how to manipulate the keywords. I will explain myself with an exampleTask optimizeUnits metersSystem { // input data}Optimizer { type Simplex convergenceCriteria 0.001}PointEvaluator { type MyEvaluatorTechnique convergenceCriteria = 0.1}this is a solution, which has header very generic entities which describe the meaning of each section, but I could also have sections that explicity concern specific techniquesTask { type optimize optimizer Simplex}Units metersSystem { // input data}Simplex { convergenceCriteria 0.001 PointEvaluator MyEvaluatorTechnique}MyEvaluatorTechnique { convergenceCriteria = 0.1}I would like to hear your opinion on which method may sound better in terms of design correctness, and pros and cons of both solutions. One thing I don't like in the first solution is, for example, the fact that depending on the type, I may have options that do not make sense for that specific type. In the second solution, however, I am setting up not the generic task (which then uses specific types of subsystem). Instead, I specify the specific subsystems performing the task.
Declarative input language strategies
design;declarative programming
Designing DSL's is hard.So hard, that I suggest that you avoid it until you are compelled to create the DSL.My suggestion is this.Create a proper class hierarchy.Create pleasant, easy-to-use initializers and constants. Get things to work as simple object construction.Later, after things work, and after you see what the DSL must express, consider designing a DSL.Some class Definitions.class Task( object ): passclass Optimizer( Task ): def __init__( self, optimizer ): passclass Simplex( object ): def __init__( self, evaluator ):class Evaluator( object ): def __init__( self, convergence ): passclass MyEvaluatorTechnique( Evaluator ): passA Configurationconfig = Optimizer( Simplex(), MyEvaluatorTechnique( convergence=0.001 ) )This avoids a lot of complexity of writing a parser and handling keywords. Instead, you use the parser for another language (i.e. Python or Java or Lua or something)
_codereview.88022
Ive written a basic implementation of Breakout using Java 8 & Slick (~400 lines of code). Please let me know of any design/OOP improvements that can be made (any improvements in general are welcome, but Im specifically looking for design & OOP improvements).Game - the main classpackage breakout;import org.newdawn.slick.AppGameContainer;import org.newdawn.slick.GameContainer;import org.newdawn.slick.SlickException;import org.newdawn.slick.state.StateBasedGame;public class Game extends StateBasedGame{ public static final String gameName = Breakout!; public static final int play = 0; public static final int gameWon = 1; public static final int gameOver = 2; public static final int FRAME_HEIGHT = 500; public static final int FRAME_WIDTH = 640; public Game(String gameName){ super(gameName); UserInfo userInfo = new UserInfo(); this.addState(new Play(userInfo)); this.addState(new GameWon(userInfo)); this.addState(new GameOver(userInfo)); } @Override public void initStatesList(GameContainer gc) { try { this.getState(play).init(gc, this); this.enterState(play); }catch(SlickException e){ e.printStackTrace(); } } public static void main(String[] args) { // a game container that displays the game as a stand alone application AppGameContainer appGC; try{ appGC = new AppGameContainer(new Game(gameName), FRAME_WIDTH, FRAME_HEIGHT, false); appGC.setVSync(true); // sets FPS to screen's refresh rate appGC.start(); }catch(SlickException e){ e.printStackTrace(); } }}Ball class - sets the position and deals with collisions with brickspackage breakout;import org.newdawn.slick.Image;import org.newdawn.slick.SlickException;public class Ball implements Collision { private Image image; private int ballDiameter; private int positionX = 450; private int positionY = 250; private int velocityX; private int velocityY; public Ball(String imageLocation) throws SlickException{ float scalingFactor = 0.06f; image = new Image(imageLocation); image = image.getScaledCopy((int) (scalingFactor * image.getWidth()), (int) (scalingFactor * image.getHeight())); ballDiameter = image.getWidth(); velocityX = -3; velocityY = 3; } public void move(){ positionX += velocityX; positionY += velocityY; collideWithVerticalWall(); collideWithHorizontalWall(); } public void collide(Brick brick){ int tolerance = 3; if(!brick.isDestroyed()) { if (Collision.topSide(this, brick, tolerance) || Collision.bottomSide(this, brick, tolerance)) { flipVelocityY(); brick.changeImage(); } if (Collision.leftSide(this, brick, tolerance) || Collision.rightSide(this, brick, tolerance)) { flipVelocityX(); brick.changeImage(); } } } private void collideWithHorizontalWall(){ if(positionY <= 0){ // ignore this comment: || positionY >= Game.FRAME_HEIGHT - ballDiameter flipVelocityY(); } } private void collideWithVerticalWall(){ if(positionX <= 0 || positionX >= Game.FRAME_WIDTH - ballDiameter){ flipVelocityX(); } } public void flipVelocityX(){ velocityX = -velocityX; } public void flipVelocityY(){ velocityY = -velocityY; } // GETTERS @Override public int getHeight(){ return ballDiameter; } public Image getImage(){ return image; } @Override public int getPositionX(){ return positionX; } @Override public int getPositionY(){ return positionY; } @Override public int getWidth(){ return ballDiameter; }}Brick class - contains the images and etc for each brickpackage breakout;import org.newdawn.slick.Image;import org.newdawn.slick.SlickException;import java.util.stream.IntStream;public class Brick implements Collision { public static final String[] imageLocations = {res/brick_pink.png, res/brick_pink_cracked.png, res/brick_transparent.png}; public static final int[] points = {0, 10, 20}; public static final int pointsPerBrick = IntStream.of(points).sum(); private Image[] images; private int imageIndex = 0; private int brickHeight; private int brickWidth; private int positionX; private int positionY; private UserInfo userInfo; public Brick(String[] imageLocations, UserInfo userInfo, int positionX, int positionY) throws SlickException{ float scalingFactor = 0.25f; images = new Image[imageLocations.length]; for(int i = 0; i < imageLocations.length; i++) { images[i] = new Image(imageLocations[i]); images[i] = images[i].getScaledCopy((int) (scalingFactor * images[i].getWidth()), (int) (scalingFactor * images[i].getHeight())); } brickHeight = images[imageIndex].getHeight(); brickWidth = images[imageIndex].getWidth(); this.userInfo = userInfo; this.positionX = positionX; this.positionY = positionY; } public void changeImage(){ if(imageIndex < images.length - 1) { imageIndex++; brickHeight = images[imageIndex].getHeight(); brickWidth = images[imageIndex].getWidth(); userInfo.incrementScore(points[imageIndex]); } } public boolean isDestroyed(){ return imageIndex == images.length - 1; } // GETTERS @Override public int getHeight(){ return brickHeight; } public Image getImage(){ return images[imageIndex]; } @Override public int getPositionX(){ return positionX; } @Override public int getPositionY(){ return positionY; } @Override public int getWidth(){ return brickWidth; }}Collision interface - interface that determines whether objects collide (contains default methods)package breakout;// Deals with the collisions in this game. Any class that implements this interface have objects that are Collidable// and can therefore use these methods.public interface Collision { // TODO need to neaten these conditions up. Not sure how. static boolean bottomSide(Collision self, Collision other, int tolerance){ // tolerance is included as the ball's velocity is 3, so the ball may not exactly touch the paddle when it // reaches it because it's moving in increments of 3. return other.getPositionX() + other.getWidth() >= self.getPositionX() && other.getPositionX() <= self.getPositionX() + self.getWidth() && other.getPositionY() <= self.getPositionY() + self.getHeight() && other.getPositionY() >= self.getPositionY() + self.getHeight() - tolerance; } static boolean leftSide(Collision self, Collision other, int tolerance){ return other.getPositionY() + other.getHeight() >= self.getPositionY() && other.getPositionY() <= self.getPositionY() + self.getHeight() && other.getPositionX() + other.getWidth() >= self.getPositionX() && other.getPositionX() + other.getWidth() <= self.getPositionX() + tolerance; } static boolean rightSide(Collision self, Collision other, int tolerance){ return other.getPositionY() + other.getHeight() >= self.getPositionY() && other.getPositionY() <= self.getPositionY() + self.getHeight() && other.getPositionX() <= self.getPositionX() + self.getWidth() && other.getPositionX() >= self.getPositionX() + self.getWidth() - tolerance; } static boolean topSide(Collision self, Collision other, int tolerance){ return other.getPositionX() + other.getWidth() >= self.getPositionX() && other.getPositionX() <= self.getPositionX() + self.getWidth() && other.getPositionY() + other.getHeight() >= self.getPositionY() && other.getPositionY() + other.getHeight() <= self.getPositionY() + tolerance; } // GETTERS int getPositionX(); int getPositionY(); int getWidth(); int getHeight();}GameWon class - game state that tells the user that they've completed the levelpackage breakout;import org.newdawn.slick.GameContainer;import org.newdawn.slick.Graphics;import org.newdawn.slick.Image;import org.newdawn.slick.SlickException;import org.newdawn.slick.state.BasicGameState;import org.newdawn.slick.state.StateBasedGame;public class GameWon extends BasicGameState { private UserInfo userInfo; public GameWon(UserInfo userInfo){ this.userInfo = userInfo; } @Override public int getID(){ return Game.gameWon; } @Override public void init(GameContainer gc, StateBasedGame sbg){ } @Override public void render(GameContainer gc, StateBasedGame sbg, Graphics g) { try{ Image backgroundImage = new Image(res/background.jpg); g.drawImage(backgroundImage, 0, 0); g.drawString(Well done, you completed the game! Your score: + userInfo.getScore(), 100, 100); }catch(SlickException e){ e.printStackTrace(); } } @Override public void update(GameContainer gc, StateBasedGame sbg, int delta){ }}GameOver class - game state that tells the user their score after not being able to complete the levelpackage breakout;import org.newdawn.slick.GameContainer;import org.newdawn.slick.Graphics;import org.newdawn.slick.Image;import org.newdawn.slick.SlickException;import org.newdawn.slick.state.BasicGameState;import org.newdawn.slick.state.StateBasedGame;public class GameOver extends BasicGameState { private UserInfo userInfo; public GameOver(UserInfo userInfo){ this.userInfo = userInfo; } @Override public int getID(){ return Game.gameOver; } @Override public void init(GameContainer gc, StateBasedGame sbg){ } @Override public void render(GameContainer gc, StateBasedGame sbg, Graphics g) { try{ Image backgroundImage = new Image(res/background.jpg); g.drawImage(backgroundImage, 0, 0); g.drawString(Game over. Your score: + userInfo.getScore(), 150, 100); }catch(SlickException e){ e.printStackTrace(); } } @Override public void update(GameContainer gc, StateBasedGame sbg, int delta){ }}Paddle class - contains all the methods and etc to do with the paddlepackage breakout;import org.newdawn.slick.Image;import org.newdawn.slick.Input;import org.newdawn.slick.SlickException;public class Paddle implements Collision { private Image image; private int paddleHeight; private int paddleWidth; private int positionX; private int positionY; private int velocity = 3; public Paddle(String imageLocation) throws SlickException{ double scalingFactor = 0.2; this.image = new Image(imageLocation); image = image.getScaledCopy((int) (scalingFactor * image.getWidth()), (int) (scalingFactor * image.getHeight())); paddleHeight = image.getHeight(); paddleWidth = image.getWidth(); positionX = (Game.FRAME_WIDTH - image.getWidth()) / 2; positionY = Game.FRAME_HEIGHT - image.getHeight(); } public void collide(Ball ball){ int tolerance = 3; // collide with top side if(Collision.topSide(this, ball, tolerance) || Collision.bottomSide(this, ball, tolerance)){ ball.flipVelocityY(); } // collide with left or right side if(Collision.leftSide(this, ball, tolerance) || Collision.rightSide(this, ball, tolerance)){ ball.flipVelocityX(); } } public void move(Input input){ // Prevents paddle from moving outside of the frame if(getPositionX() > 0) { moveLeft(input); } if (getPositionX() < Game.FRAME_WIDTH - paddleWidth){ moveRight(input); } } private void moveLeft(Input input){ if(input.isKeyDown(Input.KEY_LEFT)){ adjustPositionX(-velocity); } } private void moveRight(Input input){ if(input.isKeyDown(Input.KEY_RIGHT)){ adjustPositionX(velocity); } } // GETTERS @Override public int getHeight(){ return paddleHeight; } public Image getImage(){ return image; } @Override public int getPositionX(){ return positionX; } @Override public int getPositionY(){ return positionY; } @Override public int getWidth(){ return paddleWidth; } // SETTERS public void adjustPositionX(float delta){ positionX += delta; }}Play class - game state when the user is playing the levelpackage breakout;import org.newdawn.slick.GameContainer;import org.newdawn.slick.Graphics;import org.newdawn.slick.Image;import org.newdawn.slick.Input;import org.newdawn.slick.SlickException;import org.newdawn.slick.state.BasicGameState;import org.newdawn.slick.state.StateBasedGame;public class Play extends BasicGameState{ private Image backgroundImage; private UserInfo userInfo; private Paddle paddle; private Ball ball; private Brick[] bricks; private int numBricks = 3; public Play(UserInfo userInfo){ this.userInfo = userInfo; } @Override public int getID(){ return Game.play; } @Override public void init(GameContainer gc, StateBasedGame sbg){ bricks = new Brick[numBricks]; try{ backgroundImage = new Image(res/background.jpg); paddle = new Paddle(res/bat_yellow.png); ball = new Ball(res/ball_red.png); for(int i = 0; i < bricks.length; i++) { // the maths here is used to position the bricks in rows of 10 bricks[i] = new Brick(Brick.imageLocations, userInfo, (i % 10) * 60 + 20, ((i / 10) + 1) * 40); } } catch(SlickException e){ e.printStackTrace(); } } @Override public void render(GameContainer gc, StateBasedGame sbg, Graphics g){ g.drawImage(backgroundImage, 0, 0); g.drawImage(paddle.getImage(), paddle.getPositionX(), paddle.getPositionY()); g.drawImage(ball.getImage(), ball.getPositionX(), ball.getPositionY()); for(Brick brick : bricks) { g.drawImage(brick.getImage(), brick.getPositionX(), brick.getPositionY()); } g.drawString(Score: + userInfo.getScore(), 520, 10); } @Override public void update(GameContainer gc, StateBasedGame sbg, int delta){ Input input = gc.getInput(); paddle.move(input); ball.move(); paddle.collide(ball); for(Brick brick : bricks) { ball.collide(brick); } // Player loses when ball goes out of screen if(ball.getPositionY() > Game.FRAME_HEIGHT){ sbg.enterState(Game.gameOver); } // Player wins when all bricks have been destroyed if(userInfo.getScore() == numBricks * Brick.pointsPerBrick){ sbg.enterState(Game.gameWon); } }}UserInfo class - a class that contains info about the user's game (currently only contains the score)package breakout;public class UserInfo { private int score; // GETTERS public int getScore(){ return score; } // SETTERS public synchronized void incrementScore(int value){ score += value; }}
Breakout game using Java 8 & Slick
java;object oriented;game
In Game:public static final int play = 0;public static final int gameWon = 1;public static final int gameOver = 2;Use an enum for this.In Block:public boolean isDestroyed(){ return imageIndex == images.length - 1;}Don't abuse state variables. If you have fire blocks that need to loop through an animation, this will give you the strangest of bugs. Store something like health or hitsRemaining to keep track of destruction progress.public interface Collision {That's a naming violation. Interfaces shouldn't be nouns. This is a thing, not a capability. Try Collidable (Although your spellchecker will tell you it's not a word... it might be). This naming thing really tripped me up.static boolean bottomSide(Collision self, Collision other, int tolerance){ // tolerance is included as the ball's velocity is 3, so the ball may not exactly touch the paddle when it // reaches it because it's moving in increments of 3. return other.getPositionX() + other.getWidth() >= self.getPositionX() && other.getPositionX() <= self.getPositionX() + self.getWidth() && other.getPositionY() <= self.getPositionY() + self.getHeight() && other.getPositionY() >= self.getPositionY() + self.getHeight() - tolerance;}static boolean leftSide(Collision self, Collision other, int tolerance){ return other.getPositionY() + other.getHeight() >= self.getPositionY() && other.getPositionY() <= self.getPositionY() + self.getHeight() && other.getPositionX() + other.getWidth() >= self.getPositionX() && other.getPositionX() + other.getWidth() <= self.getPositionX() + tolerance;}static boolean rightSide(Collision self, Collision other, int tolerance){ return other.getPositionY() + other.getHeight() >= self.getPositionY() && other.getPositionY() <= self.getPositionY() + self.getHeight() && other.getPositionX() <= self.getPositionX() + self.getWidth() && other.getPositionX() >= self.getPositionX() + self.getWidth() - tolerance;}static boolean topSide(Collision self, Collision other, int tolerance){ return other.getPositionX() + other.getWidth() >= self.getPositionX() && other.getPositionX() <= self.getPositionX() + self.getWidth() && other.getPositionY() + other.getHeight() >= self.getPositionY() && other.getPositionY() + other.getHeight() <= self.getPositionY() + tolerance;}Hmm.Have you considered defining these functions?int getTopY();int getBottomY();int getLeftX();int getRightX();Also... you're dealing with rectangles here. That's a very big assumption to make - keep that in mind, or you'll have circles colliding blocks they clearly went past.In Paddle:public class Paddle implements Collision { private Image image; private int paddleHeight; private int paddleWidth;Paddle.paddleHeight is redundant. Use Paddle.height instead. There are a few exceptions, but most of the time you should strip the class name if it's in front of a variable. One of those exceptions would be Line.lineNumber if you had a parser of some sort - Line.number would be too arbitrary.public void move(Input input){ // Prevents paddle from moving outside of the frame if(getPositionX() > 0) { moveLeft(input); } if (getPositionX() < Game.FRAME_WIDTH - paddleWidth){ moveRight(input); }}private void moveLeft(Input input){ if(input.isKeyDown(Input.KEY_LEFT)){ adjustPositionX(-velocity); }}private void moveRight(Input input){ if(input.isKeyDown(Input.KEY_RIGHT)){ adjustPositionX(velocity); }}Flip your functions around. Perform the keyboard checks in move, and the boundary checks in moveLeft and moveRight. Then you don't have to pass Input around.In Play: for(Brick brick : bricks) { ball.collide(brick); }Function naming, again. To me this reads as Ball (moves to collide or) collides with brick. It's not. It's a hitTest that, if hits, handles collisions. Consider finding a better name for this function. I don't have any suggestions since this function is doing two things (checking collision and handling the aftermath), but splitting it up seems like it would require to do the collision testing twice, which seems like a shame. // Player wins when all bricks have been destroyed if(userInfo.getScore() == numBricks * Brick.pointsPerBrick){Contrast this snippet:private boolean checkPlayerWon(){ for(Brick b : bricks){ if(!b.isDestroyed()){ return false; } } return true;}This way you actually check if all the blocks are destroyed, rather than tie up your scoring mechanics for a victory condition.
_unix.335416
I need to transfer files from remote FTP server to my unix server. Usually, I transfer using:scp -r '[email protected]:/remote-path' '/local'the problem now is that this server uses ACTIVE and I think that's the reason why SCP is not backing up the files. To be honest I am not familiar with ACTIVE type connection and I cannot find anything in the manual about this type of connection.Is it possible to use SCP to transfer files on ACTIVE FTP?
using SCP for active/port type connection?
ubuntu;scp
scp and ftp are two different protocols. If you have ssh access to the server, it doesn't matter what mode ftp is. Just use scp as you normally would.If you don't have ssh access, the answer is no, you cannot use scp if you don't have access via ssh to the remote machine.
_scicomp.7278
Following on from the earlier question I am trying to derive a finite-difference scheme for the advection equation which is conservative. It was suggested that for advection equation with variable velocity,$$\frac{\partial u}{\partial x} + \frac{\partial}{\partial x}\left( \boldsymbol{v}(x)u\right) = 0$$that the chain rule should not be applied if conservation is required because the flux of $u$ is the fundamental quantity.The product $\boldsymbol{v}(x)u$ is not conservative transport if $\boldsymbol{v}(x)$ is not divergence-free (i.e., constant in 1D). You should stick with the conservative form and resist the urge to apply the chain rule when evaluating conservation properties.Question Is the following a reasonable approach for discretization?I have kept the flux together (i.e the product $\boldsymbol{v}_ju_j$) while applying the discretization. However to write as a matrix equation where $u_j$ is the unknown they eventually must be separated.I have a slight concern that this is incorrect because the only difference between the constant velocity case and the varying velocity case is that that $\boldsymbol{v}$ becomes a vector.If we applied the chain rule we could get exactly the same equation but with the additional $u \frac{\partial\boldsymbol{v(x)}}{\partial x}$ term which is treated as a source term.For example, if we apply Crank-Nicolson scheme to the advection equation,$$\frac{u_{j}^{n+1} - u_{j}^{n}}{\Delta t} + \left[ \frac{1-\beta}{2\Delta x} \left( \boldsymbol{v}_{j+1}^{n} u_{j+1}^{n} - \boldsymbol{v}_{j-1}^{n} u_{j-1}^{n} \right) + \frac{\beta}{2\Delta x} \left( \boldsymbol{v}_{j+1}^{n+1} u_{j+1}^{n+1} - \boldsymbol{v}_{j-1}^{n+1} u_{j-1}^{n+1} \right) \right] = 0$$Using the following substitution,$$ \boldsymbol{r}_j^n = \frac{\boldsymbol{v}_j^n}{2}\frac{\Delta t}{\Delta x}$$and move the $n+1$ terms to the l.h.s gives,$$u_{j}^{n+1} + \beta\boldsymbol{r}_{j+1}^{n+1} u_{j+1}^{n+1} - \beta\boldsymbol{r}_{j-1}^{n+1} u_{j-1}^{n+1} = u_{j}^{n} - (1-\beta)\boldsymbol{r}_{j+1}^{n} u_{j+1}^{n} + (1-\beta)\boldsymbol{r}_{j-1}^{n} u_{j-1}^{n} $$We can write this as the matrix equation,$$ \begin{pmatrix} 1 & \beta r_2^{n+1} & & 0 \\ -\beta r_1^{n+1} & 1 & \beta r_3^{n+1} & \\ & \ddots & \ddots & \ddots \\ & -\beta r_{J-2}^{n+1} & 1 & \beta r_J^{n+1} \\ 0 & & -\beta r_{J-1}^{n+1} & 1 \\ \end{pmatrix} \begin{pmatrix} u_{1}^{n+1} \\ u_{2}^{n+1} \\ \vdots \\ u_{J-1}^{n+1} \\ u_{J}^{n+1} \end{pmatrix} = \begin{pmatrix} 1 & -(1 - \beta)r_2^n & & 0 \\ (1 - \beta) r_1^n & 1 & -(1 - \beta)r_3^n & \\ & \ddots & \ddots & \ddots \\ & (1 - \beta) r_{J-2}^n & 1 & -(1 - \beta)r_J^n \\ 0 & & (1 - \beta) r_{J-1}^n & 1 \\ \end{pmatrix} \begin{pmatrix} u_{1}^{n} \\ u_{2}^{n} \\ \vdots \\ u_{J-1}^{n} \\ u_{J}^{n} \end{pmatrix}$$Update I Corrected a sign error suggested by @Geoff-Oxberry.
Conservative finite-difference expression for the advection equation
finite difference;hyperbolic pde;advection
In 1-D, the first discretization you've presented is correct. The matrix equation does not look right, though. For starters, it's not clear what your boundary conditions would be or how you would incorporate them.In $N$ dimensions, the advection equation looks like\begin{align}\frac{\partial{u}}{\partial{t}} + \sum_{i=1}^{N}\frac{\partial}{\partial{x^{i}}}(v^{i} u) &= 0,\end{align}adopting the convention that superscripts refer to components of vectors; you would discretize this equation in similar fashion to the 1-D case.If $v$ (or in $N$-D, $\mathbf{v}$) is a known function of $x$ (respectively, $\mathbf{x}$), then the values $v_{j}$ (resp., $\mathbf{v}_{j}$) become coefficients for the various $u_{j}$ terms in the discrete equation.