id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_unix.100980 | When I run auditctl -l I got:# auditctl -lNo rulesFile system watches not supportedAnd I've already have AUDITSYSCALL enable in kernel, # zgrep AUDIT /proc/config.gzCONFIG_AUDIT_ARCH=yCONFIG_AUDIT=yCONFIG_AUDITSYSCALL=yCONFIG_AUDIT_TREE=ySo what could be wrong here? I'm using auditctl version 1.0.12 with kernel 2.6.32 | auditctl reports File system watches not supported on a very old system | kernel;audit | null |
_unix.377606 | I am trying to setup the environment-modules for a Ubuntu system. I have placed some tools and applications in the /opt directory and would like to use the environment-module to select between different versions. The question is where do I place the directory for the environment-modules? Some of the guides I have seen online show the user's home folder, but I would like to setup the system for all users.Thanks/regards. | Where to place the directory (i.e., MODULEPATH) for environment-modules | linux | null |
_cs.77573 | Let $\text{MOD}_2 : \{0,1\}^n \rightarrow \{0,1\}$ be a parity function where $$\text{MOD}_2(x_1,\dots,x_n) = \sum_i x_i \bmod 2$$It is known [See e.g. Lemma 5 of this lecture note] that any polynomial $f(x_1,\dots,x_n) \in \mathbb{R}[x_1,\dots,x_n]$ of degree at most $\sqrt{n}$ must disagree with $\text{MOD}_2$ on at least a constant fraction of inputs. Is this true for a polynomial with degree $n^{0.5+\epsilon}$ for some small constant $\epsilon>0$ ? How about a polynomial with degree $o(n)$? | Lower bound of degree of polynomial approximating parity | polynomials;reference question | You can show a polynomial of degree $O(\sqrt{n\log n})$ can agree with parity on all but $o(1)$ fraction of the inputs. (In fact, this argument should work for anything of degree $\omega(\sqrt{n})$). Let $S = x_1 + x_2 + \dots + x_n$. Note that $\text{MOD}_2(x_1, x_2, \dots, x_n)$ can be written as a single-variable function of $S$. By Lagrange interpolation, there exists a univariate polynomial of degree $O(\sqrt{n\log n})$ in $S$ (and hence in the $x_i$s) that agrees with $\text{MOD}_2$ on the interval $S \in [(n-\sqrt{n\log n})/2, (n+\sqrt{n\log n})/2]$. By the central limit theorem, this range of $S$ accounts for all but $o(1)$ of the $2^n$ inputs $(x_1, x_2, \dots, x_n)$. |
_codereview.42262 | So, I am not sure if I should have Vertex extend Point, because the equals() and compareTo() functions are already parameterized with Point. I guess I don't really need compare to...Does this structure look good? I used a Map instead of a TreeMap because as3commons and the default flex packages do not have this structure defined. How easy will this be if I were to create it.Things that I am in the process of working out now:I know I need to add removeVertex() (and removeEdge()?)If I want to create an Edge class, I supposed I would make the following changes:// Since this is undirected, do I need 2 edges, because I have src and dest?public class Edge { public var src:Vertex; public var dest:Vertex; public var data:Object; public function Edge(src:Vertex, dest:Vertex, data:Object=null) { // Set instance variables }}public class Graph { public var edges:IMap; // <Object, Edge> public function addEdge(from:Object, to:Object, data:Object):void { edges.add(data, new Edge(v, w)); }}My main gripe would be about juggling all of these data types.public var adjList:IMap; // <Vertex, Set>public var vertices:IMap; // <Object, Vertex>public var edges:IMap; // <Object, Edge>This may make if difficult to intelligently traverse the graph.Reference classes and files:Vertex.aspackage core { import flash.geom.Point; public class Vertex extends Point { public var data:Object; public function Vertex(data:Object=null, x:Number=0, y:Number=0) { super(x, y); this.data = data; } // Implement... override public function clone():Point { return new Vertex(data, x, y); } override public function toString():String { return data.toString(); } // Implement... override public function equals(toCompare:Point):Boolean { return super.equals(toCompare) && this.compareTo(toCompare as Vertex) == 0; } // Implement... public function compareTo(other:Vertex):int { return 0; } }}Graph.aspackage core { import org.as3commons.collections.Map; import org.as3commons.collections.Set; import org.as3commons.collections.framework.IMap; import org.as3commons.collections.framework.ISet; public class Graph { public var adjList:IMap; // <Vertex, Set> public var vertices:IMap; // <Object, Vertex> private static const EMPTY_SET:ISet = new Set(); private var _numVertices:int; private var _numEdges:int; public function Graph() { adjList = new Map(); vertices = new Map(); _numVertices = _numEdges = 0; } public function addVertex(data:Object):Vertex { var v:Vertex = vertices.itemFor(data); if (v == null) { v = new Vertex(data); vertices.add(data, v); adjList.add(v, new Set()); _numVertices++; } return v; } public function getVertex(data:Object):Vertex { return vertices.itemFor(data); } public function hasVertex(data:Object):Boolean { return vertices.hasKey(data); } public function hasEdge(from:Object, to:Object):Boolean { if (!hasVertex(from) || !hasVertex(to)) return false; return (adjList.itemFor(vertices.itemFor(from)) as Set).has(vertices.itemFor(to)); } public function addEdge(from:Object, to:Object):void { var v:Vertex, w:Vertex; if (hasEdge(from, to)) return; _numEdges += 1; if ((v = getVertex(from)) == null) v = addVertex(from); if ((w = getVertex(to)) == null) w = addVertex(to); (adjList.itemFor(v) as Set).add(w); (adjList.itemFor(w) as Set).add(v); } public function adjacentTo(value:*):ISet { if (value is Object && hasVertex(value as Object)) { return adjList.itemFor(getVertex(value as Object)) as Set; } if (value is Vertex && adjList.has(value as Vertex)) { return adjList.itemFor(value as Vertex) as Set; } return EMPTY_SET; } public function getVertices():ISet { var set:ISet = new Set(); for each (var v:Vertex in vertices.toArray()) { set.add(v); } return set; } public function numVertices():int { return _numVertices; } public function numEdges():int { return _numEdges; } public function toString():String { var s:String = ; for each (var v:Vertex in vertices.toArray()) { s += v + : ; var set:ISet = adjList.itemFor(v) as Set; for each (var w:Vertex in set.toArray()) { s += (w + ); } s += \n; } return s; } }}App.mxml<?xml version=1.0 encoding=utf-8?><s:Application xmlns:fx=http://ns.adobe.com/mxml/2009 xmlns:s=library://ns.adobe.com/flex/spark xmlns:mx=library://ns.adobe.com/flex/mx creationComplete=onComplete(event)> <fx:Script> <![CDATA[ import core.Graph; import core.Vertex; import mx.events.FlexEvent; protected function onComplete(event:FlexEvent):void { main(); } public static function main(args:Vector.<String>=null):void { var G:Graph = new Graph(); G.addEdge(A, B); G.addEdge(A, C); G.addEdge(C, D); G.addEdge(D, E); G.addEdge(D, G); G.addEdge(E, G); G.addVertex(H); // print out graph trace(G); trace('Verticies:', G.numVertices()); trace('Edges :', G.numEdges()); trace(); // print out graph again by iterating over vertices and edges for each (var v:Vertex in G.getVertices().toArray()) { var str:String = v + : ; for each (var w:Vertex in G.adjacentTo(v.data).toArray()) { str += w + ; } trace(str); } } ]]> </fx:Script></s:Application> | Actionscript Graph data structure implementation | graph;actionscript 3;actionscript | null |
_cs.44997 | I have a collection of vectors $v_1,v_2\in [0,1]^n$ and I want to find similar pairs quickly. For similarity, I want to use the Euclidean distance metric $L: [0,1]^n \times [0,1]^n \longrightarrow R$. $n$ will be around $200$.I've implemented Locality Similar Hashing (LSH) for word based documents, and I'm curious if there's an adaptation of it which will work for real based vectors.I read here on Computer Science Stackoverflow that universal hashing will work. If I have the vector $s=(0.55, 0.34, 0.90, 0.99)$ I can break it up into two sub vectors $s_1=(0.55, 0.34)$ and $s_2=(0.90, 0.99)$ and apply a universal hash to each:$h_n= a\cdot s_n \space mod \space p$Where $a$ is a random vector and $p$ is prime. I can now define a space of bins, where each $h_n$ defines a bin in this space. Each vector with a subvector in $h_n$ is mapped to the bin $h_n$The problem is that this method is too precise. The vectors $(0.57, 0.34)$ and $(0.55, 0.34)$ are very similar but will get mapped to different bins.I'm wondering if it's there's any theoretical and practical issues with either truncating the last digit or rounding up/down such that both vectors are now mapped to a bin representing the vector $(0.5, 0.3)$This I believe is equivalent to multiplying all the vector elements by 10 and truncating the decimals, leading back to normal LSH.I'm quite new at all this, so please forgive the slight errors in notation or understanding. | Finding similar high dimensional real vectors | hash;cluster | One approach: QuantizationOne approach is to quantize the values, then apply an existing LSH that works on discrete values. In other words, you split up the space $[0,1]$ into several ranges, map each real number to its containing range, and then apply an existing LSH that works with discrete values. This is essentially equivalent to first truncating each coordinate of the vector, then applying some discrete LSH.For example, suppose you split the interval $[0,1]$ up into ten ranges, $[0,0.1)$, $[0.1,0.2)$, ..., $[0.8,0.9)$, and $[0.9,1.0]$. Now you can map any value in $[0,1]$ to its corresponding range -- this is basically just truncating to keep only the first digit in the decimal representation. Map each interval to a digit from 0 to 9: e..g, $[0,0.1) \mapsto 0$, etc. In this way, given any vector $v \in [0,1]^n$, you can get a new vector $w \in \{0,1,\dots,9\}^n$. For instance, the vector $v=(0.55,0.34,0.90,0.99) \in [0,1]^4$ maps to the new vector $w=(5,3,9,9) \in \{0,\dots,9\}^n$.The new vector $w$ is in a discrete space, rather than in a continuous space. Now if you have a LSH that works on this discrete space, you can apply it to $w$. For instance, suppose $h_1:\{0,\dots,9\}^n \to \mathbb{R}$ is a locality-sensitive hash (LSH) on this discrete space. Let $f:[0,1]^n \to \{0,\dots,9\}^n$ be the mapping that sends each real number to its corresponding range, i.e., $f(v)=(g(v_1),\dots,g(v_n))$ where $g(x)= \lfloor 10x \rfloor$ is the truncation map $g:[0,1] \to \{0,\dots,9\}$. Define $h_0 : [0,1]^n \to \mathbb{R}$ by$$h_0(v) = h_1(f(v)).$$Then $h_0$ is a LSH on continuous values.If you plan to generate multiple different LSHs, it's probably slightly better to apply the following tweak. Pick a random $n$-vector number $r \in [0,0.1)^n$. Now the LSH for $[0,1]^n$ is defined to be $h_0(v) = h_1(f(v+r))$ as above, where $f:[0,1]^n \to \{0,1,\dots,10\}^n$ is the truncation map defined as above and $h_1:\{0,1,\dots,10\}^n\to\mathbb{R}$ is a LSH on discrete values. This tweak lets you generate multiple independent LSH's for $[0,1]^n$. If you are only picking a single hash function, you can skip this step.There's nothing special about base-10. Instead of using base-10, you can also use base-2 or any other base. The performance will depend upon the base you use as well as the specific discrete LSH you choose, so you might need to play with the options to see which is best overall. I suspect you will find that the optimal choice of base is base $b=2$ or $b=3$ (and, if your discrete LSH is based upon hashing a random subset of the coordinates, choosing a subset of size proportional to $\sqrt{n}/b$), but it's not possible to give a hard-and-fast rule: the optimum depends to some extent on the distribution of your data. That's why I suggest trying a few different parameter choices to see which seems to work best on your data.This is basically the truncation idea in your original post (truncate all real values, then apply a discrete LSH), but now we apply it to the entire vector, rather than trying to split the vector in half. Of course, the discrete LSH might itself work by picking a few randomly chosen coordinates and hashing only those coordinates (e.g., using a universal hash).Another approach: Use a LSH designed for continuous valuesThere are also some LSH's that are designed specifically for continuous real numbers. I don't know if there are any for the Euclidean distance.A totally different approach: nearest-neighbor data structuresFinally, it's worth mentioning that there are also other approaches to this problem that don't involve LSH's at all. There are some data structures that are designed to support nearest-neighbor search (or approximate nearest-neighbor search). You might look at metric trees, k-d trees, and nearest-neighbor search.However, beware of the curse of dimensionality. If the dimension $n$ is large, none of these approaches are likely to work well: high dimensions are just plain hard. For instance, one rule of thumb I've seen is that k-d trees tend not to work well when $n \ge 30$. I'm not sure any of these techniques will be terribly effective when $n$ is large: nearest-neighbor search in high dimensions is hard. |
_unix.317048 | I have a problem where when I execute commands such as systemctl status , output is written on to previous lines of bash output . normally output is written some 20 lines above the current line...PS1 does not seem to be the issue since I am using PS1=$ to keep it simple . Also tried solution mentioned in :Bash overwrites the first line, PS1 bash promptI am using putty to connect to ubuntu on a embedded target . I do not see this problem for e.g if I do a cat on a file . | bash prompt control overwrites previous lines | bash;putty | null |
_softwareengineering.220676 | Why does Mono for Android cost money if the mono project is opensource and therefore everything based on it must be opensource? | Why does Mono for Android cost money if the mono project is opensource and therefore everything based on it must be opensource? | open source;mono | null |
_softwareengineering.232282 | As part of my workflow, I need to do all these steps in one transaction - I need to ftp files to 2 different FTP servers. - There is also a spreadsheet that gets generated which needs to be FTP'ed. Can this be streamed, instead of downloading and then pushed to FTP server.I am using Ruby Net::SFTP and Net::FTP libraries to send the files.I would like it to be robust. I am not sure if I need to do anything else or of this is good enough.Just to be clear, this is already working in production, I am not stuck, just looking to exchange design/architecture ideas on how to improve this. | How to check robustness in a service that includes multiple points of failure in workflow, including FTP | design;ruby;ftp | Ahh, with FTP, the simple answer is - you don't. What you can do is to retrieve the file you sent to the FTP server, and check it is the same as the original file. If they match, all worked as well as you'd hoped.This gets tricky if you're not allowed to read from the FTP server (as some credit card acquirers do), security is set up such that you're allowed to write to some directories but not read from them. In these cases, the server tends to have a service that generates a summary report of your upload that you can retrieve from a read-only directory. In the case of acquirers that do not do this, you just have to cross your fingers and wait for them to complain usually on the following day. |
_softwareengineering.190080 | Say you have been programming for over 10 years. You know many languages, with few of those at very detailed level. You have been designing architecture for solutions, worked on and delivered larger projects. You have been studying patterns, best practices, effective coding guidelines, unit testing, multi-threading, etc.And then you slowly develop a feeling that most of the books you read, give less and less valuable information per 100 pages of text. So they start giving diminishing returns. You still learn, but you no longer improve by leaps and bounds.Why does learning become less productive compared to how it was before?Back then, it used to change your way of thinking, taught you new things and broadened your horizons that later improved either your current profession, or allowed to invent/manage/build something new. Why is it no longer the case? | What can a technically proficient senior software developer study to keep improving | learning;self improvement;skills;senior developer | null |
_unix.31947 | Using version control systems I get annoyed at the noise when the diff says No newline at end of file.So I was wondering: How to add a newline at the end of a file to get rid of those messages? | How to add a newline to the end of a file? | bash;shell;text processing;newlines | To recursively sanitize a project I use this oneliner:git ls-files | while read f; do tail -n1 $f | read -r _ || echo >> $f; done |
_unix.1725 | If I want to find out which directory under /usr/ports contains a port like gnome-terminal, how can I do that? Is there an easy command? At the moment I use things likeecho */gnome-terminalbut is there a website or guide which tells you this without having to use a trick? | How do I find where a port is? | freebsd | There are several ways that you can find a port, including your echo technique. To start, there is the ports site where you can search by name or get a full list of available ports. You can also try:whereis <program>but this--like using echo--won't work unless you type the exact name of the port. For example, gnome-terminal works fine but postgres returns nothing. Another way is:cd /usr/portsmake search name=<program>but keep in mind that this won't return a nice list; it returns several \n delimited fields, so grep as necessary. I've used both of the above methods in the past but nowadays I just use find:find /usr/ports -name=<program> -printLastly, I will refer you to the Finding Your Application section of the handbook which lists these methods along with sites like Fresh Ports which is handy for tracking updates. |
_unix.104325 | In Emacs I can run a shell using following commands - M-x termM-x shellM-x eshellWhat is the difference between these three? | What is the difference between shell, eshell, and term in Emacs? | shell;emacs | shell is the oldest of these 3 choices. It uses Emacs's comint-mode to run a subshell (e.g. bash). In this mode, you're using Emacs to edit a command line. The subprocess doesn't see any input until you press Enter. Emacs is acting like a dumb terminal. It does support color codes, but not things like moving the cursor around, so you can't run curses-based applications.term is a terminal emulator written in Emacs Lisp. In this mode, the keys you press are sent directly to the subprocess; you're using whatever line editing capabilities the shell presents, not Emacs's. It also allows you to run programs that use advanced terminal capabilities like cursor movement (e.g. you could run nano or less inside Emacs).eshell is a shell implemented directly in Emacs Lisp. You're not running bash or any other shell as a subprocess. As a result, the syntax is not quite the same as bash or sh. It allows things like redirecting the output of a process directly to an Emacs buffer (try echo hello >#<buffer results>). |
_unix.214692 | I'm new to iptables but configured a simple natting today on my raspian:# Always accept loopback traffic/sbin/iptables -A INPUT -i lo -j ACCEPT# Allow established connections, and those not coming from the outside/sbin/iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT/sbin/iptables -A INPUT -m state --state NEW -i tun0 -j ACCEPT/sbin/iptables -A FORWARD -i tun0 -o eth2 -m state --state ESTABLISHED,RELATED -j ACCEPT# Allow outgoing connections from the LAN side./sbin/iptables -A FORWARD -i eth2 -o tun0 -j ACCEPT# Masquerade./sbin/iptables -t nat -A POSTROUTING -o tun0 -j MASQUERADE# Don't forward from the outside to the inside./sbin/iptables -A FORWARD -i tun0 -o tun0 -j REJECT# Enable routing.echo 1 > /proc/sys/net/ipv4/ip_forwardSo as you can see I also use openvpn and redirect the traffic to the tunnel interface.I'd like to create an exception for example for the port range 900 to 999 and source 192.168.1.5 to be excluded and sent directly to interface eth1 and avoid the vpn encryption.How can I create such a rule?Thanks a lot for your input.EDIT: I tried something likeiptables -t nat -A POSTROUTING -p tcp --dport 900:999 --out-interface eth1 -j MASQUERADEBut it doesn't seem to have the expected effect... | Iptables exception for specific port | iptables;routing;vpn;openvpn | null |
_unix.131577 | Through the command line I draw one or several of the patterns found text.xml file:perl -ln0e 'while(/<PMResult.*?<\/PMResult>/gs) { $x=$&;print $x if $x=~/BCCEL-[1-3]/}' text.xmlI need to create a new file with this pattern found; the new file will have the first three lines of Text.xml file before of pattern and have the last two lines of Text.xml file after the pattern. | How to print the first three lines and last two lines of a file using perl? | scripting;perl | null |
_unix.387845 | I have recently installed vim8 from its source code. It is showing the following characters when opening vim with or without file:$q qDoes it serve any specific purpose or I have made something unusual mistake while installations.It is coming even on nerdtree directory structure at top.Thanks for the helps | vim 8.0.987 starting every blank file with strange characters | linux;vim | It's either a bug in the latest source or an inadvertently exposed terminal incompatibility.All of the following fixes work for me:set t_SH=orif !empty($TERM_PROGRAM) && $TERM_PROGRAM == 'Apple_Terminal' set t_SH=endiforautocmd VimEnter * redraw!(Source) |
_unix.362328 | I'm trying to get the current date of my school server (I don't have root access) to complete this task: Write a script that will countdown to Friday(example: output would be Today is Sunday, you have 5 days until Friday). You should use the time and day from the server, not the user. | Get server date to compute days until Friday | linux;shell script;date | Since you tagged Linux, you have a powerful date utility at your disposal. Here's how I might approach such a task (depending on what you want to have happen if today is Friday -- this will take you into the next week):now=$(date +%s)fri=$(date +%s -d next Friday)days=$(( (fri - now) / 86400))echo Today is $(date +%A), you have $days until Friday |
_unix.258730 | I am trying to remove all occurrences of 2016/01/30 14:52:51: but the last one. I tried this:awk '{gsub(//,2016/01/30 14:52:51: ,$1);print}'to replace all but the last occurrence with nothing, but that just duplicated 2016/01/30 14:52:51: 4 times with slightly different numbers. | How do I remove all but the last occurrence of a string? | shell script;text processing | There is more than one problem with the script, plus the problem statement needs some clarification:the gsub call has the regular expression in the wrong parameterupdating $1 has no effect on $0 (the value used in the print statement)OP did not clarify if the intent was to leave the last occurrence on a line untouched, or only the last line containing the date (the latter is more likely).Here is a script which incorporates those fixes and assumptions:#!/bin/shawk 'BEGIN { row=0; fixup = -1; }{ before[row] = $0; gsub(2016/01/30 14:52:51: , , $0); if ( $0 != before[row] ) { fixup = row; } after[row++] = $0;}END { if (fixup >= 0) { after[fixup] = before[fixup]; } for (n = 0; n < row; ++n) { print after[n]; }}'(using two arrays is less efficient, but allows further modification with less effort than without the before array).I tested this by making an input file (foo.in):1awk '{gsub(//,2016/01/30 14:52:51: ,$1);print}'2awk '{gsub(//,2016/01/30 14:52:51: ,$1);print}'3awk '{gsub(//,2016/01/30 14:52:51: ,$1);print}'4awk '{gsub(//,2016/01/30 14:52:51: ,$1);print}'and running the script like this:./foo <foo.inand got1awk '{gsub(//,,$1);print}'2awk '{gsub(//,,$1);print}'3awk '{gsub(//,,$1);print}'4awk '{gsub(//,2016/01/30 14:52:51: ,$1);print}' |
_unix.224967 | I am running Ubuntu 14.04 inside VMware workstation 11.1. I testing changing the color depth and now I am hitting a login/logout loop. When the login screen comes up I select my account, type in the password and it immediately refreshes the login page. I was following the instructions Here. I was running these commands as root. Specifically, I did exactly what the answer provided:Xorg :1 -configurestartx -- :1 -depth 8I managed to get to a shell prompt as root using recovery mode and ran the command again this time setting it to 24 thinking it was just not able to run 8 bit. However after changing it to 24 it still has the same behavior. So back to the root shell again I go. I tried dpkg --configure xorg and xserver-xorg but both return fatal errors. I then removed the xorg.conf file that xorg -configure creates. No luck. I went into my user home directory and I notice an .xsession-errors file. I open it up an see this:At this point I am out of ideas to restore the behavior so I can log into accounts. Also, in VMware I notice an error with Unity that says it can't enter unity mode because the guest OS resolution can't be changed. Pretty sure this is the result of what I did. Any suggestions? | Login/logout loop on Ubuntu 14.04 | linux;ubuntu;xorg;login | null |
_unix.328270 | Let's say I want to prioritize a few processes that are running on a device with high memory pressure. These processes are UI processes (Android, specifically) and are running very slowly in this state. When I grep for my process in ps -eo min_flt,maj_flt,cmdI can see that my major page faults are very high (thousands for a UI actions like opening a new Android activity). If renice my processes to a lower niceness (higher priority), can I expect to see less maj page faults? Increasing priority should give it more CPU resources, but I'm not sure if that will speed up the process if the bottleneck is memory pressure/page faults. | Will renicing (lower) a process make it faster under memory pressure? | memory;android;nice | null |
_cs.70747 | Is the following language decidable?L = {(M) : M performs at least 100 steps on every accepted input.}I tried to use reduction from the halting problem, but still no dice. | Prove that this language is decidable or undecidable | formal languages;turing machines | Yes, it is decidable. There is a limited amount of input that any Turing machine could look at in 100 steps, so you can test a simulation of any given machine $M$ against all of those possibilities. |
_softwareengineering.194655 | I am confused when I read this (regarding singleton design pattern):How do we ensure that a class has only one instance and that the instance is easily accessible? A global variable makes an object accessible, but it doesn't keep you from instantiating multiple objects.So what is the use of singleton pattern if we can create multiple instances?SOURCE:Design Patterns - Elements Of Reusable Object Oriented Software (1995) - Gamma, Helm, Johnson, Vl | Is it allowed to make multiple instances of a singleton class? | design patterns;singleton | Without the full text this is not sure, but my (somehow educated) guess:They only warn that a global variable is not the right way to ensure that you have a singleton. The following text should then show how to do this inside the class that should be a singleton. |
_softwareengineering.298247 | As someone who's worked effectively with Agile before, I am trying to convince my current employers of its benefits. However, management are insistent that we retain the ability to make upfront estimates in order to assess the business value of projects.Most of my customers are internal, and I was recently tasked with going round teams and asking them for ideas on business processes to automate. I was then to find out how much time this was taking them, work out how much time the solution would save and estimate the total development time. That way, managers could attempt to measure how effective a solution was likely to be in terms of time saved.However, it looks to me like there's no way to approach this requirement in an Agile way. Flexible requirements means that not only will estimates of time taken be wrong, so will estimates of potential time saved. I explained as much, explained why it was likely to be problematic, but was told it was non-negotiable.The question How to sell Agile development to (waterfall) clients has some useful advice on how to sell Agile to external customers. I'm not trying to sell it to external clients: I'm trying to work out how I can best reconcile the demands of internal management while retaining a methodology I believe works well.Is there any way to approach this task in a flexible manner which allows me to retain at least some Agile benefits? | Is it possible to take a flexible agile approach to projects that require estimates of both time taken and time saved? | agile | As other answers have stated, Management has every right to get a high level estimate upfront of a project. They are not unreasonable for trying to determine ROI.One of the approaches that I like about Agile however is that the scope of a project is not fixed. It can be initially sized out at the Feature and Epic level, then business can determine ROI based on what are the most important features. Maybe the fancy UI with bells and whistles has low business value, but the workflow engine for handling claims has a high ROI.When you lump the whole project together then it harder to meet ROI than if you focus on the critical business functionality that is desired.Here is a way that I have done this:Take your WBS milestones and turn each of these into a deliverable featureThis allows you to categorize your project into mini subprojects that have varying business value. Each of these should stand on their own in terms of business value.T-Shirt Size the Effort on FeaturesThis is a very easy way to get a rough idea about how big or involved a particular feature might be. Perhaps low value features still have a great ROI if they look like easy wins.Break Down a Feature into StoriesGo through the exercise to find a small feature that is well understood and break it down into stories initially. Estimate these stories by points. Now you have a basis whereSmall -> 40 pointsThis will be a basis of comparison to other featuresAssociate story point effort to all FeaturesCompare your Small Feature to other features. For example,Medium Feature Y feels like it is twice the size and effort of Small Feature X of 40 story points.Medium Feature Y is probably 80 story points. Continue this until you have story points estimated at a high level for all features.Estimate your Team VelocityLooking at your development team, try to determine how many story points could this team effectively deliver in a given sprint. If you have previous Agile projects as an example with this team that is a great place to start. If you do not have such history behind the team then go through a mock Sprint Planning with your team where you start looking at your Small feature that you have detailed out. What kinds of hourly estimates are people giving for their tasks on these stories?Based on how much work the team thinks they can deliver in 2 weeks, use that total story point number as the average potential velocity of your team!Find your Projected Completion DateIf your team in mock sprint planning feels comfortable delivering 25 story points in a sprint, and your total backlog looks like 300 story points for the gold Cadillac version of your project, then it looks like your team would ideally take 12 sprints or 24 weeks to complete everything.Now it is trivial to turn cost of resources on your team into dollars per week to arrive at a cost for ROI vs. Business Value. The negotiation can continue on what the most important features are and then your project management becomes basically a Knapsack Problem. |
_datascience.9392 | I have data in the following form:table 1id, feature1, predict 1, xyz,yes2, abc, yestable2id, feature21, class11, class21, class32, class2I could perform a one many join and train on the resultant set- which is one way to go about it. But If I rather wanted to maintain the length of the resultant set equal length of table 1, what is the technique? | Handling a feature with multiple categorical values for the same instance value | machine learning;dataset;data cleaning;feature extraction | One possible approach is to perform an encoding, where each level of the feature2 corresponds to a new feature (column).This way you may describe the 1:N relation between the feature 1 and 2Here a small example in R> table1 <- data.frame(id = c(1,2), feature1 = c(xyz,abc), predict = c(T,T))> table2 <- data.frame(id = c(1,1,1,2), feature2 = c(class1, class2, class3, class2))> > ## encoding> table(table2) feature2id class1 class2 class3 1 1 1 1 2 0 1 0The new object contains the (now unique) id and setting of the feature2.You need only to merge (join) the result to the table1 (basically same task a DB join - which variance: inner, outer or full depends on your requirements). |
_unix.58281 | Do MD5 checksums contain a checkbit?I have to copy some MD5 checksums by hand (there's no other way) and was wondering whether there is any code out there that can validate a checksum as being valid in the same way one can validate a credit card number.Just to be clear, I'm not asking how to generate an MD5 sum from a file so that I can compare it with the sum I've been given, I'm asking if it's possible (and I doubt it is) to validate that an MD5 sum is a genuine MD5 sum without actually making any reference back to the bytes that have been used to generate the sum.I want to identify a possible typo. | Sanity checking MD5 sums | checksum;hashsum | Basically, it does not have any checksum bit. To identify a typo, you might try sharing an a checksum (for example, MD5) of your MD5 sum over the same channel and check it. |
_softwareengineering.113759 | I thought that many object-oriented languages have a reserved keyword for methods which do not modify the state of an object. These methods often have names that start with get. AFAIK a getter is always related to a single object attribute and accessor is too general, so readonly may the right term for this kind of methods (?). To give an example:object Timespan { attribute start attribute end // getter, not changing the state readonly method getStart { return start } readonly method getEnd { return end } // also not changing the state readonly method getDuration { return ( end - start ) }}The compiler/interpreter should check that readonly methods have no side-effect by modifying object attributes. I wonder why this language feature is not more common - just naming a method getFoo does not ensure that it won't modify the object. | Which popular object-oriented languages support readonly methods? | object oriented;methods | null |
_unix.379562 | I'have an RFID Reader with linux kernel 3.0 (BusyBox v1.14.3) on board.BusyBox has installed JamVM 1.54.I need to execute an stored procedure on SQL Server 2008. I have created a little program in Javaimport java.sql.DriverManager;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class TestStored { public static void main(String[] args) throws SQLException, ClassNotFoundException { Class.forName(com.microsoft.sqlserver.jdbc.SQLServerDriver); Connection conn = DriverManager.getConnection(jdbc:sqlserver://IPSERVER\\SQLINSTANCE;user=User;password=psw;database=DB); System.out.println(test); String SPsql = EXEC INS_TEST ?; // java.sql.Connection PreparedStatement ps = conn.prepareStatement(SPsql); ps.setEscapeProcessing(true); ps.setQueryTimeout(10000); ps.setInt(1, 99); boolean a = ps.execute(); Statement sta = conn.createStatement(); String Sql = select * from tab_test; ResultSet rs = sta.executeQuery(Sql); while (rs.next()) { System.out.println(rs.getString(num)); } }}I have tried this code on Lubuntu and everything work.When I try this code on BusyBox I received these errors:java.nio.channels.NotYetConnectedExceptionorSQLServerException: Connection reset by peer ClientConnectionIdWhat can I do?Thanks | BusyBox and jdbc | busybox;sqlserver | null |
_cstheory.10020 | Irreversible computations can be intuitive. For example, it is easy to understand roles of AND, OR, NOT gates and design a system without any intermediate, compilable layer. The gates can be directly used as they conform to human's thinking.I have read a paper where it was stated that it is obviously correct way to code irreversibly, and compile to reversible form (can't find the paper now).I am wondering if there exists a reversible model, that is as easy to understand as AND, OR, NOT model. The model should be therefore direct use of reversibility. So no compilation. But also: no models of form: $f(a) \rightarrow (a,f(a))$ (ie. models created by taking irreversible function $f$ and making it reversible by keeping copy of its input). | Examples of reversible computations | reference request;computability;machine models | The paper you mention is probably one of Paul Vitnyi's, possibly Time, Space, and Energy in Reversible Computing.However, not everyone takes the viewpoint that simulation of irreversible computations is the main point. There is some research into what reversible computing can do in addition to such simulations, the beginnings of which is in Bennett's seminal paper Logical Reversibility of Computation on reversible Turing machines. See this paper for an elaboration of these ideas.In terms of reversible logic circuits, there has been significant effort from the quantum computing community to build non-trivial circuits for arithmetic, e.g. Quantum networks for elementary arithmetic operations, some of which are purely classical, i.e., reversible. These implement a reversible variant of, say, addition, where one of the operands is conserved, but they do not rely on irreversible thinking, do not use a history, and display a significant amount of ingenuity in their design. |
_webmaster.2562 | When is it suitable to use background music on a web site? Do users like this? | Music on a web page? | website design | In general I dislike background music on a website. It slows down load time, it surprises users who have their speakers turned on, and its annoying. It is similar to flashing text on a web page.The only time it makes sense to me is for a site about music or for a band. Then it can be expected.The better solution is to have a player on you web page like @aslum suggested that way people can choose to play your music or not. |
_softwareengineering.332094 | Under static scoping, by its definition, how can we determine the scope of a variable inside a recursive function?For example, in a pseudo-language,int i=1;function myfun(){ if (i > 4){ printf(%d\n, i); } else { ++i; myfun(); }}myfun();i changes in each call to myfunAccording to static scoping, it seems to me that it should print out 1 for i. But if I remember correctly in C, which is statically scoped, it will print out 5.If it prints out 5, then what is the difference between dynamic scoping and static scoping for a variable inside a recursively defined function?Thanks. | How does static scoping apply to recursive functions? | programming languages;scope | null |
_cs.33505 | I'm a person using english as the second language and reading CLRS book at a slow pace due to my poor english. I have a problem with understanding the meaning of the word 'alternative'. In page 303 on CLRS, says:we should convince ourselves that exhaustively checking all possible parenthesizations does not yield an efficient algorithm.Denote the number of alternative parenthesizations of a sequence of n matrices by P(n). Since we can split a sequence of n matrices between the kth and (k+1)st matrices for any k = 1,2,...,n-1 and then parenthesize the two resulting subsequences independently, we obtain the recurrence ...(omitted)What is the word 'alternative parenthesizations'? is this word equivalent to the 'all possible parenthesizations' in the above block quote? searching dictionary for the word 'alternative' is not helpful to me. Thank you in advance. | What is alternative parenthesizations? | terminology | null |
_webmaster.23511 | They've linked the CMS, mail (which is http://www.campaignmonitor.com), social sites management, some kind of online payment solutions, and word press all under one log-in.I'm mostly a graphic designer -- People much smarter than me... How is this done? Can anybody point me in the right direction to get something similar to this?. here's a link of their youtube giving an overview of it:http://www.youtube.com/watch?feature=player_embedded&v=eGKv8YDZvbo | how are they doing this for their CMS?? And how can I do something similar | looking for a script;cms;code | null |
_codereview.145274 | I wrote this in 78 minutes as part of an application to an internship program. We were allowed to use whatever language we wanted, so I picked Rust because that's what I use the most. I'm a Sophomore CS/Data Science major and I just wanted to get a feel for how you more experienced among us feel about what I made.I'm not asking for detailed analysis (I know it works and that that it fits the prompt), I'm just looking for broad feedback and any random observations.Prompt TL;DR:server picks a random numberclients try to guess itif client guesses it, server raises their balance by 1 and picks new number//! XternCoin Application//! Casey Primozic - 2016//!//! Requires latest Rust nightly// turn on the unstable testing feature#![feature(test)]extern crate rand;extern crate test;use std::sync::{Arc, Mutex};use rand::{thread_rng, Rng};use std::collections::HashMap;use std::sync::atomic::{Ordering, AtomicUsize};use std::thread;use std::convert::From;/// The server which manages the Proof of Work check and dispenses the currency////// The server is threadsafe and can be duplicated over an arbitary number of threads/// so that any number of users can mine simultaneously.#[derive(Clone)]struct CoinServer { // concurrent hashmap to store the balances of all users // this allows shared mutable access to the balance database through `lock()`. pub balances: Arc<Mutex<HashMap<String, f64>>>, // only public for sake of the test pub random_num: Arc<AtomicUsize>,}impl CoinServer { /// Function which takes a user's id and a user's guess, /// and returns whether or not their guess was correct. pub fn handle_guess(&mut self, user_id: String, guess: u64) { // convert the String to a u64 for comparison if self.random_num.load(Ordering::Relaxed) == guess as usize { self.inc_balance(user_id); self.get_new_rand(); } } /// Adds one to the user's balance, creating an entry for it if /// it doesn't exist. fn inc_balance(&mut self, user_id: String) { // lock the balances let mut balances = self.balances.lock().unwrap(); // insert user if not already in database if !balances.contains_key(&user_id) { balances.insert(user_id, 1f64); return } // credit the user for the correct guess let balance = balances.get_mut(&user_id).unwrap(); *balance += 1f64; } /// Function which takes a userid and returns /// how many coins they have. pub fn get_coins(&mut self, user_id: String) -> f64 { let balances = self.balances.lock().unwrap(); if !balances.contains_key(&user_id) { return 0f64 } *balances.get(&user_id).unwrap() } pub fn new() -> CoinServer { let mut server = CoinServer { balances: Arc::new(Mutex::new(HashMap::new())), random_num: Arc::new(AtomicUsize::new(0)) }; server.get_new_rand(); server } // I'm using a text editor to debug this: https://ameo.link/u/3ew.png /// Creates a new random number for users to try to guess fn get_new_rand(&mut self) { // entropy source let mut rng = rand::thread_rng(); // generate random number from 0 to 100000 let rand_num: usize = rng.gen_range(0, 100000); self.random_num.store(rand_num, Ordering::Relaxed); }}/// A function which, when called, pretends to be a user of/// XternCoin and uses the other two functions you've written/// to accumulate coins by guessing random numbers in a loopfn start_guessing(user_id: String, mut server: CoinServer, iterations: usize) { // entropy source let mut rng = rand::thread_rng(); for _ in 0..iterations { let guess: u64 = rng.gen_range(0, 100000); // make guess and let server verify it server.handle_guess(user_id.clone(), guess); }}fn main() { let server = CoinServer::new(); // spawn 10 threads to start guessing for i in 0..10 { let mut server_clone = server.clone(); thread::spawn(move || { let user_id = format!({}, i); // initiate mining start_guessing(user_id.clone(), server_clone.clone(), 100000); println!(Balance for {} after this mining session: {}, user_id.clone(), server_clone.get_coins(user_id)); }); } // block so the miners can mine thread::park();}// TODO: tests1/// Check to make sure that user balances are created and incremented#[test]fn test_mining() { let mut server = CoinServer { balances: Arc::new(Mutex::new(HashMap::new())), random_num: Arc::new(AtomicUsize::new(42)) // cheat for the test }; let user_id = Test.to_string(); server.handle_guess(user_id.clone(), 42); // make sure we got credited assert_eq!(server.get_coins(user_id), 1f64); // server generated a new random number assert!(server.random_num.load(Ordering::Relaxed) != 42); // test passes: https://ameo.link/u/3ey.png}Cargo.toml:[package]name = xtversion = 0.1.0authors = [Casey Primozic <[email protected]>][dependencies]rand = 0.3 | Internship coding challenge post-mortem | programming challenge;concurrency;rust | Making private fields public only for the sake of tests is undesirable; you should instead add new methods which are only available in tests, e.g.#[cfg(test)]fn get_random_number(&self) -> usize { self.random_num.load(Ordering::Relaxed)}Expressed simply: testing your own code shouldnt have any impact on the API exposed to library users.AtomicUsize is already Sync; no need to wrap it in Arc.user_id should be &str rather than String in most places. Basically, you should never need to clone the String after the first time when you insert it into balances (to remedy that, you could use Arc<String> instead if you wished; not sure if I would or not). Youre doing a lot more memory allocation than is necessary.Unwrapping is undesirable. See if you can avoid it. get_coins can be rewritten thus (note how this also makes it only one lookup rather than two, so its faster as well):pub fn get_coins(&mut self, user_id: String) -> f64 { *self.balances.lock().unwrap().get(&user_id).unwrap_or(&0)}HashMap has some really nice things for efficiency. Just as get returned an Option in the previous point (which rendered the contains_key part superfluous), inc_balance can use the Entry API to do less work:fn inc_balance(&mut self, user_id: String) { // Credit the user for the correct guess, // inserting the user if not already in the database *self.balances.lock().unwrap().entry(user_id).or_insert(0) += 1;}(Note: at present this actually doesnt play optimally with using &str for user_id as it requires you to clone the user ID every time you call inc_balance rather than only the first time a user ID is encountered. RFC PR 1769 would fix that.)use std::convert::From; is unnecessary (From is in the prelude).#![feature(test)] shouldnt be necessary; you dont appear to be using any unstable features (mostly just benchmarking, really).Something to bear in mind: youre locking the entire balances table to make any changes at present. This is probably undesirable. If you were doing this seriously, youd be using a proper database which would take care of this stuff properly. Just thought Id mention it. |
_unix.191330 | I'm on Debian Wheezy stable with Gnome 3.4 and have several default extensions, which on the 'Installed Extensions' page at https://extensions.gnome.org/local/ (using Iceweasel's Gnome Shell Integration plugin), are not able to be removed like the ones I have added from extensions.gnome.org myself.These include (for me anyway - and this may not be the complete list as I probably have one or two of them enabled and thus no quick way to know all of them):Alternative Status MenuApplications MenuAuto Move WindowsDockGajim IM integrationPlaces Status IndicatorSystemMonitorUser ThemeswindowNavigatorWorkspace IndicatorInspecting the HTML of the Installed Extensions page, I see no way to hack it via Firefox's developer tool (at least with my limited HTML knowledge and only from a quick look) to somehow make those extensions uninstallable via that page.Is it as simple as deleting (e.g. for the first one) the folder /usr/share/gnome-shell/extensions/alternative-status-menu@gnome-shell-extensions.gcampax.github.com, then restarting Gnome Shell and it'll be removed from the list?I want to do it correctly, without introducing problems later. | How to remove Gnome's default pre-installed extensions? | gnome;gnome3;gnome shell;uninstall | null |
_codereview.157368 | During a code review the following approach of delivering content conditionally dependent upon the state of the user was rejected as adverse to performance due to its multiple use of RenderAction, and instead the approach of RenderPartial was preferred. In order to take this approach it would be necessary to include conditional logic in the view, thus violating separation of concern. What would you advise as the optimum approach for conditionally including a partial view without including logic in the view? Header.cshtml@Model HeaderModel<p>Some markup</p>@Html.RenderAction(AuthenticatedUserPanel, Model.SubModel)@Html.RenderAction(UnauthenticatedUserPanel, Model.SubModel)Controller.csController(IContext context){ _context = context;}public ActionResult AuthenticatedUserPanel(Model model){ if(_context.IsAuthenticated()) { return View(AuthenticatedUserPanel.cshtml, model) } return EmptyContentResult();}public ActionResult UnauthenticatedUserPanel(Model model){ if(!_context.IsAuthenticated()) { return View(UnauthenticatedUserPanel.cshtml, model) } return EmptyContentResult();}I could possibly include the name of the target view to render in my model e.g. So that my logic for determining which view to use is contained within my ModelAdapter, but this approach feels temperamental and more error prone? Header.cshtml@Model HeaderModel<p>Some markup</p>@Html.RenderAction(Model.TheViewToRender, Model.SubModel) | Rendering content conditional on the authentication state of the user | c#;mvc;authentication | null |
_cogsci.8486 | What are the effects of MRIs and other electromagnetic devices on the human brain? Naturally they could move metals to or through the brain cell's membrane. I can also see the experience of being in a strange position, meditating, and attempting to be as still as possible for an hour and a half, might cause some long term effect. Have the effects of MRIs and other electromagnetic devices been studied comparatively on human psychology or neurology? Could you also mention the mental health aspects? | Have the effects of MRIs and other electromagnetic devices on human psychology been studied? | neurobiology;abnormal psychology;neuroimaging;fmri | null |
_webapps.88056 | I want to filter an array returned by a filter to remove blank columns. Here is a picture of an example sheet:Here is the example sheet. I am filtering the large table by the rows that are of type b. I am retrieving the columns via the key on the left. This is a very basic example of my sheet, where there may be many rows of type b, but there are only two columns of type b. The column headers may be the same as other headers, and they may change based on the key.I understand how to perform a two-dimensional filter by putting the results of one filter inside of another. However, I cannot figure out how to filter the result of a filter by itself. If I have a formula that returns 5 columns and 3 rows. How do I say: I want to filter out all columns that are blank. This would normally be something like Filter(A1:E5, A:E <> ) where A1:E5does not actually exist on the spreadsheet, but is instead an array in a formula (Not sure what that is technically called).Hopefully this is better explained than my last question, if it is not, please let me know. | How do I filter the array returned by a filter or other formula? | google spreadsheets | null |
_codereview.165649 | I think that my code contains a lot of if and else statements that are probably not required.I suppose that this code could be condensed to a shorter form where the logic applied would look clearer than it does now. Suggestions are welcome and any help in refactoring would be highly appreciated.public class Segregate{ public static void doSegregation(int[] a){ int i = 0; int j = a.length-1; while(i<=j){ if(a[i]==a[j]){ if(a[i]==1 && a[j]==1){ j--; } else if(a[i]==0 && a[j]==0){ i++; } } else{ if(a[i]>a[j]){ int temp = a[i]; a[i] = a[j]; a[j] = temp; i++; j--; } else if(a[i]<a[j]){ i++; } } } } public static void main(String[] args){ int[] a = {1,0,1,0,1,1,0,1,1,1}; System.out.println(Array before segragation : ); for(int i=0; i<a.length; i++){ System.out.print(a[i]+ ); } System.out.println(); doSegregation(a); System.out.println(Array after segragation : ); for(int i=0; i<a.length; i++){ System.out.print(a[i]+ ); } } } | Segregate an array of 0s and 1s | java;array;sorting | null |
_unix.16599 | I am using Ubuntu server as a samba server. The solution I am looking for is whenever the disks are inserted (cd or dvd) they should get auto-mounted to /cdrom directory. Are there any tools for achieving this? I installed ivman, and it is running as a daemon. But it is doing nothing. EDIT 1: Tried autofs, and it doesn't work as well. There is a bug report on launchpad which suggests that autofs for lucid is broken. | Auto mount cd or dvd on CLI based ubuntu server | ubuntu;samba;automounting;data cd | Personally I would go the autofs-route. But as you stated autofs might be broken on Lucid (I'm not an Ubuntu-User).You could also try udev-wrappers or rules. The Arch Linux wiki has something on that. https://wiki.archlinux.org/index.php/Udev#UDisks |
_unix.104540 | I have been wondering this for quite a while. Let's say that you have a Debian server that you keep updated via APT. Usually (every 1-2 months) there are some kernel updates, which will update the GRUB entries to boot from it next time.This is okay, but if you care about uptime and SLA, it would be difficult to reboot just to use the updated kernel. I guess this is the usual way to go, but is it actually how it works? | Is it necessary to reboot after a kernel upgrade (via APT)? | kernel;apt;upgrade | null |
_cs.11148 | I am trying to understand Tarjan's strongly connected component algorithm and I have a few questions (the line numbers I am referring to are from Algoritmy.net):On line 33 why is node.lowlink = min(node.lowlink, n.index) shouldn't it be same as line 31: node.lowlink = min(node.lowlink, **n.lowlink**)?Do we have to generate the components on line 40 in the while loop as we pop? Isn't it true that when the algorithm finishes, all the vertices grouped by lowLink should be the SCC?Is it ever true that after we recurse in line 30, n may not be in stack? If not and (1) is true we can simplify line 29-33 as follows:if n.index == -1 tarjanAlgorithm(n, scc, s, index)if stack.contains(n) node.lowlink = min(node.lowlink, n.lowlink)I went ahead and implemented the algorithm in Scala. However, I dislike the code - it is very imperative/procedural with lots of mutating states and book-keeping indices. Is there a more functional version of the algorithm? I believe imperative versions of algorithms hide the core ideas behind the algorithm unlike the functional versions. I found someone else encountering the same problem with this particular algorithm but I have not been able to translate his Clojure code into idomatic Scala.Note: If anyone wants to experiment, I have a good setup that generates random graphs and tests your SCC algorithm vs running Floyd-WarshallHere is the full pseudocode ( Algoritmy.net, MIT licensed).index = 0/** Runs Tarjan's algorithm* @param g graph, in which the SCC search will be performed* @return list of components*/List executeTarjan(Graph g)Stack s = {}List scc = {} //list of strongly connected componentsfor Node node in gif (v.index is undefined)tarjanAlgorithm(node, scc, s)return scc/** Tarjan's algorithm* @param node processed node* @param SCC list of strongly connected components* @param s stack*/procedure tarjanAlgorithm(Node node, List scc, Stack s)v.index = indexv.lowlink = indexindex++s.push(node) //add to the stackfor each Node n in Adj(node) do //for all descendantsif n.index == -1 //if the node was not discovered yet // <--- line 29tarjanAlgorithm(n, scc, s, index) //searchnode.lowlink = min(node.lowlink, n.lowlink) //modify parent's lowlink // <--- line 31else if stack.contains(n) //if the component was not closed yetnode.lowlink = min(node.lowlink, n.index) //modify parents lowlink // <--- line 33if node.lowlink == node.index //if we are in the root of the componentNode n = nullList component //list of nodes contained in the componentdon = stack.pop() //pop a node from the stackcomponent.add(n) //and add it to the component // <--- line 40while(n != v) //while we are not in the rootscc.add(component) //add the compoennt to the SCC list | Tarjan's Strongly Connected Component algorithm | algorithms;graphs | null |
_softwareengineering.95839 | I have a client requirement where I need to expose a web service which takes XML. Client will consume my web service and send XML .This web service need to be async.Could you please suggest any good proven approach ? with advantage / disadvantage | WCF service which takes XML file | wcf;web services | null |
_unix.365932 | In the few years I've been using Linux as my main system, specifically Fedora, I've always seen my hostname set to just localhost, with the exception of when I connect to some networks and it becomes my IP. Today I experienced the following behavior which I'm having trouble understanding though. I set up an Ubuntu installation on another partition of my laptop, setting a computer name / hostname during the Ubuntu install. When I rebooted back into Fedora though, Fedora had updated my hostname to the name I set in the Ubuntu install.I always thought the hostname was configured and stored on the partition of the distro installation, and indeed the contents of /etc/hostname on Fedora still read localhost.localdomain, but running the hostname command shows the new hostname. Both installs share an efi boot partition, but are otherwise discrete. I'm wondering from where and why the Fedora install is reading the new hostname? | What determines the Linux hostname? | ubuntu;fedora;hostname | The hostnameprogram performs a uname syscall, as can be seen from running:strace hostname...uname({sysname=Linux, nodename=my.hostname.com, ...}) = 0...From the uname syscall man page, it says the syscall retrieves the following struct from the kernel: struct utsname { char sysname[]; /* Operating system name (e.g., Linux) */ char nodename[]; /* Name within some implementation-defined network */ char release[]; /* Operating system release (e.g., 2.6.28) */ char version[]; /* Operating system version */ char machine[]; /* Hardware identifier */ #ifdef _GNU_SOURCE char domainname[]; /* NIS or YP domain name */ #endif };So the domain name comes from the NIS / YP system, if we believe the comment. So more than likely, there may be a NIS / YP service on your network that is trotting back the name to you that is set by the ubuntu OS. |
_unix.57623 | How can you specify the line where you want tmux's command prompt to appear?I want to see the panes when executing tmux commands that require pane numbers (e.g. join-pane, etc) but as the command prompt is displayed on top of the pane numbers, I have to cancel it, memorize the pane number and type the command again. | Specifying tmux command-prompt line | tmux | I think you are confusing two things windows and panes. A window basically fills the whole terminal and is divided into several panes. The status line lists the windows with their numbers and name, which defaults to the name of the program currently running in the active pane in that window. You can modify the status line with set status-left or set status-right and use the #P character sequence, which displays the number of the active pane. However, I'm afraid this is as far as you can get (unless you patch tmux of course). |
_unix.165574 | #!/usr/bin/env bash if [ $outDir == ] then echo $PWD ,We are here , $outDir , with $outDir = $PWD echo Yes fiOutput on terminal:/home/Documents/folderName ,We are here , , with ./pipeline.sh: line 28: : command not foundYesI am unable to assign the current directory to $outDir.I tried outDir = $PWD and $outDir=$PWD and $outDir=$PWD , but nothing worked. However, echo $PWD works perfectly fine.Why it doesn't work? | Error while assigning current directory to a variable | bash;shell script | It looks you're trying to assign $PWD to $outDir only in the event that $outDir is unset or of null value, yes?The following is equivalent, I think:printf 'We are here: %s\n $outDir = %s\n' \ $PWD ${outDir:=$PWD}If $outDir is already assigned a value then, for printf's second argument, that prints its value, else it simultaneously assigns the value of $PWD to $outDir and prints it.Of course, though here the ${outDir:=$PWD} variable call self-corrects a null or unset value, it makes no attempt to verify it is actually a directory. The same is true of your check above. And so probably better than either of these is:cd -- ${outDir:=$PWD} || exit; cd - >/dev/nullcd will not only verify that the user's selection for $outDir is correct, it will also print an error if it is not or is not accessible to the user. cd - will just bring you back to where you were before testing with cd in the first place in the event of a successful test. The >/dev/null redirection is just to keep cd - from printing $PWD which it will do when used otherwise.If the user has not assigned $outDir, however, then its value is just assigned to the value of $PWD as before, which implies a successful test and two cd $PWD commands in succession as the - is substituted for $OLDPWD - which is here also $PWD. |
_unix.295298 | I would like to know how to import a large and complex csproj intoMonoDevelop 5.10 with Ubuntu 16.04 and the ASP.NET addin I tried this method recently ,https://stackoverflow.com/questions/9220290/open-a-csproj-with-monodevelop, where we create a new empty solution and then copy your projects and thier sources into the solution folder, then right click on the solution in the solution explorer and choose Add > Add Existing Project.However this method works fine in production but is cumbersome in development where one is frequently making C# code changes and recompiling.With this method , there are two directory hierarchies and file protection commands such as chmod -R, chown -R and chgrp -R to contend with in order to achieve a build with no errors and runs correctly with mod_mono_server4. Furthermore, Monodevelop pc files must be pointed at the imported project's directory tree with absolute pathnames which have to be changedfor each programmer's home directory.I tried installing Monodevelop pc files with relative pathnames into /usr/lib/pkgconfig to no avail today. The problem is that one has to delete all the existing csproj Hint Paths first and reenter them manually in the csproj corresponding to the host project directory tree.Another problem with MonoDevelop is that after it is successfully compiled, one has to reboot the Ubuntu 16.04 box every time.My question is how to simplify this method to reduce the time consuming and the error prone aspects of it.Any help is greatly appreciated. | How to import a large and complex csproj into MonoDevelop 5.10 with Ubuntu 16.04 and the ASP.NET addin? | ubuntu;mono | null |
_unix.125227 | OS: Funtoo.I have bound NGINX to port 81 (I want to run it alongside my Apache server for a short time for ease of transition), and it listens at the port (If I point at another port, using wget I get Connection refused, but using port 81 I get connected) but it never serves an HTML response of any kind!When running a wget on the port, from the localhost, I get:# wget localhost:81-2014-04-16 23:56:45- http://localhost:81/Resolving localhost... 127.0.0.1Connecting to localhost|127.0.0.1|:81... connected.HTTP request sent, awaiting response...On another computer...$ wget 192.168.18.42:81-2014-04-16 23:57:19- http://192.168.18.42:81/Connecting to 192.168.18.42:81... connected.HTTP request sent, awaiting response...Nothing ever happens after that. The documents exist, it's the normal Funtoo nginx.conf.UPDATE: I can make it listen to port 80, but it still rattles me that I can't get it to work on any port....netstat -aWn | grep 81 | grep LISTENtcp 60 0 0.0.0.0:81 0.0.0.0:* LISTENEdit:Configuration files:user nginx nginx;worker_rlimit_nofile 6400;error_log /var/log/nginx/error_log info;events { worker_connections 1024; use epoll;}http { include /etc/nginx/mime.types; # This causes files with an unknown MIME type to trigger a download action in the browser: default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] ' '$request $status $bytes_sent ' '$http_referer $http_user_agent ' '$gzip_ratio'; client_max_body_size 64m; # Don't follow symlink if the symlink's owner is not the target owner. disable_symlinks if_not_owner; server_tokens off; ignore_invalid_headers on; gzip off; gzip_vary on; gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript text/x-js image/x-icon image/bmp; sendfile on; tcp_nopush on; tcp_nodelay on; index index.html; include /etc/nginx/sites-enabled/*;}Server block:server { listen *:81; root /usr/share/nginx/html; location / { index index.html; }} | Nginx listens at a port, only responds if set to port 80 | configuration;nginx;funtoo | Turns out the big problem? Nginx had set worker_processes to 0. I added a line setting it to auto in the top of my nginx.conf, and all was well with the world!Thank you all for your time and patience. |
_webapps.90804 | So if somebody retweets something on Twitter and you click to view it, but click onto the original account that tweeted it and like it from there, will the person who retweeted it get a notification? | Can people see that you've liked their retweet on Twitter? | twitter;retweet | null |
_codereview.91235 | While writing this review, I edited the code until it became something quite different from the original. In addition to the issues I mentioned, I ended up adding features:More operators / commands, including trigonometry in degree and radian modes.Support for multiple commands on a line, separated by whitespace. Each line is transactional: if any part fails, the stack remains unchanged.A rudimentary help system, while maintaining a spartan interface.Readline support with tab completion when running in a TTY, and a quiet mode for accepting input from a pipe.Concerns:I overrode Array#dup to do something completely different.In interactive mode, I want all output on stdout. In non-interactive mode, I want only the real output on stdout, and only critical error messages on stderr. The switching mechanism for the two modes seems cumbersome.require 'readline'# Mixin for an Arraymodule RPNOperators def +; push(pop + pop); end def -; push(-pop + pop); end def *; push(pop * pop); end def /; push(1.0 / pop * pop); end def ^; x = pop; push(pop ** x); end def deg(quiet=false) @conv = Math::PI / 180 info 'In degree mode. (Use the rad command to switch to radian mode)' unless quiet end def rad(quiet=false) @conv = 1.0 info 'In radian mode. (Use the deg command to switch to degree mode)' unless quiet end def pi; push(Math::PI); end def cos; push(Math.cos(pop * @conv)); end def sin; push(Math.sin(pop * @conv)); end def tan; push(Math.tan(pop * @conv)); end def acos; push(Math.acos(pop) / @conv); end def asin; push(Math.asin(pop) / @conv); end def atan; push(Math.atan(pop) / @conv); end def e; push(Math::E); end def chs; push(-pop); end def inv; push(1.0 / pop); end def cbrt; push(Math::cbrt(pop)); end def sqrt; push(Math::sqrt(pop)); end def ln; push(Math::log(pop)); end def log; push(Math::log10(pop)); end def clear; super; end def drop; pop; end def dup; x = pop; push(x); push(x); end def roll; unshift(pop); end def rolld; push(shift); end def swap; x = pop; y = pop; push(x); push(y); end def quit throw :quit end def help(stream=$stdout) stream.puts Available commands: stream.puts RPNOperators.public_instance_methods.join(' ') stream.puts if deg? then deg else rad end end private def deg?; @conv != 1.0; end def rad?; @conv == 1.0; end def info(s) puts s endendclass RPNCalculator class InvalidCommand < Exception; end class StackUnderflowError < Exception; end class Stack < Array include RPNOperators def initialize(*args) super rad(true) end def pop(*n) raise StackUnderflowError.new if (n[0] || 1) > size super end def shift(*n) raise StackUnderflowError.new if (n[0] || 1) > size super end end def initialize @stack = Stack.new Readline.completion_proc = proc do |s| available_commands.grep(/^#{Regexp.escape(s)}/) end end def run catch(:quit) do loop do case input = prompt('> ') when nil throw :quit when /\s/ command(*input.split(/\s+/)) else command(input) end end end raise @error if @error end def command(*cmds) error_stream = $stdin.tty? ? $stdout : $stderr last_command = nil begin transaction do cmds.each do |cmd| last_command = cmd case cmd when /\A[+-]?\d*\.?\d+\Z/ @stack.push(cmd.to_f) else if available_commands.include?(cmd) @stack.send(cmd.to_sym) else raise InvalidCommand.new end end end end rescue InvalidCommand error_stream.puts Invalid input: \#{last_command}\ @stack.help(error_stream) error_stream.puts error_stream.puts Stack (top to bottom): rescue StackUnderflowError error_stream.puts #{last_command}: not enough operands rescue Exception => e error_stream.puts e end display end def available_commands @available_cmds ||= RPNOperators.public_instance_methods(false).map { |sym| sym.to_s } end private def prompt(s) input = $stdin.tty? ? Readline.readline(s, true) : gets input.nil? ? nil : input.strip end def display puts @stack.reverse.map { |n| '%-8g' % n }.join(' ') end def transaction begin # Can't use @stack.dup, which has been overridden to do something else! saved_stack = @stack.clone @error = nil yield rescue Exception => e @error = e @stack = saved_stack raise end endendbegin RPNCalculator.new.runrescue Exception exit(1)end | RPN calculator with interactive and non-interactive modes | ruby;error handling;console;calculator | Neat! I'm digging the dual TTY/pipe support, although it does introduce some complexity. My gut feeling is that I'd probably prefer a calculator object that is agnostic about the source of its input and the destination of its output, but which can be subclassed as necessary.But you've chosen this direction, and I'm not saying the alternative would necessarily be nicer, so I'll take it as given, and focus on the internals.Between RPNOperators and Stack's own methods do you even need to subclass Array? Or would it be neater to simply let Stack be a plain object that wraps an array? I'm only asking because subclassing array means Stack inherits a lot of methods, not all of which are necessarily desirable. But it's your call; the argument can be made either way. Personally, I just prefer specialized APIs and object composition, to crowded APIs caused by subclassing very generic classes like Array. But it's as much opinion as anything.A compromise might be to wrap the array, and use Forwardable to delegate relevant methods to it with minimal hassle. No need to duplicate the Array methods that you do want.In any event, not subclassing Array would of course avoid (most) violations of the Liskov principle. You'd still be overriding #dup from Object, but you'd avoid overriding #+, #-, and #* from Array.Stack#pop and Stack#shiftInstead of making them variadic, it'd be nicer to define the parameter of each with a default value (n = 1), since that's what appears to be intended. And the super methods aren't variadic either.Edit: I was wrong here. As pointed out in the comments, passing an argument to Array#pop causes it to always return an array, even if n = 1. So Array#pop is actually 0-1 variadic, but the closest you can get is to make a 0-n variadic. So, with that in mind, I'll instead recommend n.first instead of n[0] - just to still recommend something :)Also, note that super will still complain if more than 1 argument is passed.Readline.completion_procYou could do available_commands.select { |cmd| cmd.start_with?(s) } - seems more straightforward to me than interpolating a regex with an escaped string.#commandThis is a rather large method. A lot of is of course the exception handling, but it's also got a lot of nesting.One thing you might do right away is to pull the if..else out of the case statement's own else branch:case cmdwhen /\A[+-]?\d*\.?\d+\Z/ # Use a named constant instead? @stack.push(cmd.to_f)when *available_commands # splat! @stack.send(cmd.to_sym)else raise InvalidCommand.newendI'd also suggest making your custom exception classes take a constructor argument (or several), so you can pass the invalid command and possibly other pieces of state along with the exception, rather than rely on the local last_command variable. (You could also be cheeky and do raise cmd, and then do rescue RuntimeError => failed_command, but that's pretty hacky.)You can also avoid a level of nesting since rescue statements don't need to be in an explicit begin...end block, and you have ensure:def command(*cmds) # ...rescue InvalidCommand # ...rescue StackUnderflowError # ...rescue Exception => e # ...ensure displayendLastly, and this is just because I like short methods, you could extract the meat (the case statement) into a private #eval_command (or something) method, so the transaction block becomes just:transaction do cmds.each(&method(:eval_command))endException classesJust a minor naming thing, but I'd either drop the -Error suffix from StackUnderflowError or add it to InvalidCommand, just to keep them consistent.stdout/stderrUnless I'm mistaken, $stdin.tty? isn't likely to change during the lifetime of an RPNCalculator object. So you could set the output and error streams as instance variables in the constructor. You could also add a (private) #warn method which would shadow the global Object#warn, writing to either stderr or stdout as necessary. It would let you call the more symmetrical methods puts and warn, instead of puts and error_stream.puts.#available_commandsTiny, tiny thing, but .map { |sym| sym.to_s } can be just .map(&:to_s).Overriding #dupAs mentioned, you can't completely avoid overriding a #dup method because your class will always inherit it from Object. Though I suppose you call the command something other than dup and solve the problem that way ;) |
_softwareengineering.69050 | I have been writing code so far in conventional text editors that come with the OS so far or use an IDE in some cases. I know there are some advanced text editors like Emacs and Vim available solely for the purpose of coders. How important are they really? Should a programmer dealing with PHP, Python etc. learn these editors? What are the advantages that they provide over conventional editors like Notepad++, Scribes etc.? | Must a programmer learn text editors like Emacs and Vim? How important are they? | programming practices;text editor;vim;emacs;developer tools | Vim is a really good tool once you familiarize yourself with it.It starts up faster than any IDE or text editor I've used, and it has syntax highlighting and it indents the code correctly in most cases.It also helps you focus on the coding process itself, you won't be using the mouse at all to deal with it, that'll save you a lot of time when you're just writing code.It has a wealth of plugins for whatever it is you're doing, as well.I haven't used emacs to be honest, but I'm sure there are people here who like it, I personally don't like having to press Ctrl or Alt all the time.EditVim's usefulness also depends on what you're writing.If you're an API developer (Java, C#...etc) you'll most probably be more comfortable with an IDE.But if you write scripts (Bash, Perl...etc), Vim might be the way to go, since you need to write something fast, Vim is fast, and does everything you need. |
_cstheory.22191 | Many top notch computer science researchers and research groups) maintain active blogs that keep us updated on the latest research in the authors' fields of interest. In most cases, blog posts are easier to understand than formal papers, because they omit most of the gory technical details and emphasize intuition (which papers generally omit).Thus, it would be useful to have a list of recommended blogs, in the same spirit as other lists of recommended resources:What papers should everyone read?What books should everyone read?What are the recent TCS books whose drafts are available online?What videos should everybody watch?What lecture notes should everyone read?Of course one can follow the excellent Theory of Computing Blog Aggregator, but that list is rather overwhelming, especially for beginners.Please highlight why you recommend them. | What CS blogs should everyone read? | soft question | null |
_unix.23887 | A brief introduction to my question: the command ps will print the information of system processes.But when I login as root and change the permission x of pschmod -x /bin/pschmod u+x /bin/psls -l /bin/ps -rwxr--r-- 1 root root ...... psThen I create a new shell script file call_ps_via_root.sh#!/bin/bashpsand set the x permissionchmod +x /bin/call_ps_via_root.shls -l /bin/call_ps_via_root.sh-rwxr-xr-x 1 root root ...... call_ps_via_root.shAfter this, I login with a normal user sammy, and I type ps, it will print Permission deniedand I type /bin/call_ps_via_root.sh It is still denied. How can I make it work by call_ps_via_root.sh? | Call 'ps' as a normal user in Linux | linux;permissions;ps | You can't: if you make /bin/ps only executable by root, it will be only executable by root. You can't just wrap a script around it to bypass the permission check.set-user-idIf you want that a normal user calls ps as root you have to look at the set-uid permission. From the setuid article on Wikipedia:setuid and setgid (short for set user ID upon execution and set group ID upon execution, respectively)1 are Unix access rights flags that allow users to run an executable with the permissions of the executable's owner or group. They are often used to allow users on a computer system to run programs with temporarily elevated privileges in order to perform a specific task. While the assumed user id or group id privileges provided are not always elevated, at a minimum they are specific.See also the man page of chmodsudoIf instead you want a normal user to execute something executable by root only use sudo. It will allow you to configure which user will be able to execute what. |
_softwareengineering.348023 | Suppose you're building an MVC web application in ASP.NET, and you have to display some formatted text. A very simple example might be:Click any of the links below, or click here to cancel. Contact Customer Service with any questions.What do you store in the resource file, and what do you code inline in your view?For example, do you hardcode the target of the link in the resource? Or do you put {0} and populate it with string.Format in the View? Or store the link text as a separate resource and put the markup in the View, including the target?What if the instructions are long, and need to be displayed in a tabular format? Do you put the <TABLE> <TR> and <TD> tags into the resource? Or do you have to put those tags in your View and create resources for each cell?If you put HTML markup in some of your resources, you have to dodge the automatic HTML-escape mechanism employed by Razor (e.g. use Html.Raw). How do you remember which resources can be inserted directly and which need to be unescaped? Do you keep formatted resources in a separate resource file? Use a naming convention? Cross your fingers?Bottom line: How do you deal with the common requirement of formatting part of a resource? | How do you format part of a resource? | c#;mvc;asp.net;resources;globalization | null |
_unix.203707 | Hi I want to be able to edit the list of name like this using either AWK or SED.Sample input list file:johnpaulroselilyDesired output:I am john of earth;I am paul of earth;I am rose of earth;I am lily of earth;I want the semicolons at the end too. i don't want to use shell scripts of for loops. | Add string to list using either AWK or SED? | sed;awk;gawk | Using sed:$ sed 's/.*/I am & of earth;/' file.txt I am john of earth;I am paul of earth;I am rose of earth;I am lily of earth; |
_webmaster.774 | In response to my domain name suggestion on meta, Kris said:Something about having a domain name begin with a digit just feels ... off to me.Does it affect site ranks on search engines? Do you think people will be less likely to visit it?Is this just a programmer response, since most variable names can't start with a digit? | Are there any downsides to starting a domain name with a digit? | seo;domains | Well, the people at 37signals or 7dana might disagree with that. If it makes sense to use a number at the start of the domain, use it. If not ... don't. I'd surely hate to type out one-hundred-and-one-dalmations, when 101dalmations would do just fine :)I think the key here is to avoid nonsensical domains altogether, i.e. something like '303wee' when in fact you are selling designer handbags.I don't think its going to effect your ranking any more or any less than any other bad name that did not start with a number. A bad name is just a bad name regardless. |
_hardwarecs.1434 | In this question I received the response to which graphics model should I go with. Now, as I started calculating using this decibel calculator, the fact that I am trying to buy quiet 8.9 dB fans (total = 20.9 dB) will be negligable if a graphics card will generate 36 dB (which is what I found here) - than the total noise will be 37.081 dB.However, on Tomshardware I found this to be more nuanced, but also incomplete (no MSI card).What graphics card manufacturer would you recommend for GTX960 noise-wise, provided the price differences are negligible? Or maybe there are other considerations under 250$ for gaming setup (i5-6500, 8GB ram, 240GB SDD, 4 140mm fans, MSI170 pro gaming mobo, 1280 x 1024 res) that are significantly quieter?[EDIT]I am aware of 'silent mode', where fans turn off on idle, which is apparently implemented by all manufacturers in GTX 960 (source). The question is about the fan noise under load. | Graphics card with quiet fans | gaming;graphics cards;quiet computing | So after the extended research I found the following evidence:10 minutes of constant load test by Toms Hardware :Asus Strix GeForce GTX 960: 35 dBEVGA GeForce GTX 960 SSC: 35 dBZOTAC AMP! GeForce GTX 960: 36.5 dBMSI Gaming 2G GeForce GTX 960: 34 dBAnd the rest of makes in yet another Toms Hardware test:Asus GTX 960 StriX OC: 35.8 dBGainward GTX 960 Phantom OC: 35.9 dBGalax/KFA GTX 960 EX OC: 36.2 dBGigabyte GTX 960 WindForce OC: 35.8 dBGigabyte GTX 960 Gaming G1: 34.6 dBinno3D GTX 960 iChill: 36.4 dBPalit GTX 960 Super JetStream: 36.6 dBFrom the above I conclude, that the quietest card is MSI Gaming 2G GeForce GTX 960 and Gigabyte GTX 960 Gaming G1, because it's hard to compre between tests. |
_softwareengineering.300473 | I want to create a little GPS tracking program. Simplified: Users can create Tracks.To make things scale Track and User are two separate AR's. Track contains an AuthorUser which it refers to by UserID.The following rules apply:A User can create an unlimited amount of Tracks. Users can be removed from the system. In that case all the created Tracks of the User need to be removed.I want to use DDD+ES for this. Knowing the AR's can only be created/loaded by ID, how should I delete/modify all Tracks when a UserRemovedEvent is triggered?Please note the query model is completely decoupled and might lag in time since it is async event-based updated. | How to query Aggregate Root to react to event from other AR | cqrs;event sourcing | null |
_webapps.56575 | Here is what the normal profile picture in Facebook chat looks like:But what or why is the little bit of blur showing on the profile picture (not the speech balloon with dots) in this next image? I'm using the Facebook chat on Windows 7 desktop and it's on the profile picture on the chat icon.It sometimes happens and sometimes doesn't. I think it started to occur recently over the past week or so.I'm not sure what they're doing when it happens, but I believe it lasts until the user is done typing. | Facebook chat profile picture (next to the speech bubble icon with dots) is showing up blurred | facebook;facebook chat | null |
_unix.117790 | If I select text in my terminal (in my case urxvt) and then click with the middle mouse button into an emacs window (GTK), it pastes the selected text from terminal. Since I don't want this behaviour for the middle mouse button I usually add this to my .emacs file:(define-key global-map [mouse-2] nil)However then I am not able to paste text from a terminal at all. So how can I fix this (for example that a selection from a terminal is inserted by C-y)?This worked in my old box but since upgrading to ubuntu 13.10 and emacs24 it doesn't. So it must be possible, but I don't know how to. | Howto copy and text from termial to (GTK-)emacs? | emacs;clipboard | From the Emacs manual, section 12.3.1 Using the Clipboard:Prior to Emacs 24, the kill and yank commands used the primary selection, not the clipboard. If you prefer this behavior, change x-select-enable-clipboard to nil, x-select-enable-primary to t, and mouse-drag-copy-region to t. In this case, you can use the following commands to act explicitly on the clipboard: clipboard-kill-region kills the region and saves it to the clipboard; clipboard-kill-ring-save copies the region to the kill ring and saves it to the clipboard; and clipboard-yank yanks the contents of the clipboard at point. The key setting you want is x-select-enable-primary to t. You can also use a mix of the settings described there, depending on exactly what behavior you like. |
_datascience.13277 | I have applied the sequential forward selection to my dataset having 214 samples and 515 features (2 class problem). The feature selection algorithm has selected 8 features. Now I have applied the svm (MATLAB) on these 8 features. I have also tried to see the performance after adding more features. The table given below gives the correct rate of the algorithm (training data set) along with the feature set used. The result obtained is:8 features = 0.939210 features = 0.943912 features = 0.967214 features = 0.967216 features = 0.9626 18 features = 0.976620 features = 0.9672 As visible, the accuracy seems to increase. Is it because of over fitting? Should I use the default feature set as given by the sequentialfs function of Matlab or should I force it to deliver more features to get more accuracy?I have uploaded the validation training and testing performance (70-15-15). Now can you tell me if my data is being over-fitted or not? | Is there a problem of over fitting in my dataset? | feature selection;svm;matlab;overfitting | It is not possible to tell whether a machine learning algorithm is overfitting based purely on the training set accuracy. You could be right, that using more features with a small data set increases sampling error and reduces the generalisation of the SVM model you are building. It is a valid concern, but you cannot say that for sure with only this worry and the training accuracy to look at.The usual solution to this is to keep some data aside to test your model. When you see a high training accuracy, but a low test accuracy, that is a classic sign of over-fitting. Often you are searching for the best hyper-parameters to your model. In your case you are trying to discover the best number of features to use. When you start to do that, you will need to make multiple tests in order to pick the best hyper-parameter values. At that point, a single test set becomes weaker measure of true generalisation (because you have had several attempts and picked best value - just by selection process you will tend to over-estimate the generalisation). So it is common practice to split the data three ways - training set, cross-validation set and test set. The cross-validation set is used to check accuracy as you change the parameters of your model, you pick the best results and then finally use the test set to measure accuracy of your best model. A common split ratio for this purpose is 60/20/20.Taking a pragmatic approach when using the train/cv/test split, it matters less that you are over or under fitting than simply getting the best result you can with your data and model class. You can use the feedback on whether you are over-fitting (high training accuracy, low cv accuracy) in order to change model parameters - increase regularisation when you are over-fitting for example.When there are a small number of examples, as in your case, then the cv accuracy measure is going to vary a lot depending on which items are in the cv set. This makes it hard to pick best hyper-params, because it may just be noise in the data that makes one choice better than another. To reduce the impact of this, you can use k-fold cross-validation - splitting your train/cv data multiple times and taking an average measure of the accuracy (or whatever metric you want to maximise).In your confusion matrices, there is no evidence of over-fitting. A training accuracy of 100%* and testing accuracy of 93.8% are suggestive of some degree of over-fit, but the sample size is too low to read anything into it. You should bear in mind that balance between over- and under- fit is very narrow and most models will do one or the other to some degree. * A training accuracy of 100% is nearly always suggestive of overfit. Matched with e.g. 99% test accuracy, you may not be too concerned. The question is at worst could I do better by increasing regularisation a little? However, matched with ~60% test accuracy it is clear you have actually overfit - even then you might be forced to accept the situation if that's the best you could achieve after trying many different hyperparameter values (including some attempts with increased regularisation). |
_unix.267614 | Let's say I have,On screen 1:workspace A: a web browser, extended (not full-screened with F11, just maxed out).workspace B: a terminal with Vi for example.On screen 2:a web browser, full-screened.When I switch, with Ctrl+Alt+or, from workspace A to workspace B on screen 1, my cursor switch to screen 2 if, and only if, I have something full-screened.I lose my cursor focus and it's annoying when I'm editing a file with Vi, while watching a video in full screen on my second screen, check something on chrome and go back to my Vi instance as what I type is now typed on my chrome instance on my other screen.Is it possible to force my cursor to stay on my first screen when I have a full-screened window in my second screen?I'm on Debian Jessie and Gnome 3. | How to keep my cursor focus when switching of workspace if I have a fullscreened window on another screen? | debian;gnome;workspaces;fullscreen | null |
_unix.125706 | I'm having problems with yum and I am trying to re-install it. I've download yum.3.2.0-40-el6.centos.noarch.rpm.When I try:$ rpm -ivh yum.3.2.0-40-el6.centos.noarch.rpmI get:error: can't create transaction lock on /var/lib/rpm/.rpm.lock (Permission denied)I tried running su - and I'm getting this error:-bash: su: command not found`I get the same permission denied error if I try to uninstall yum and force ignore dependencies (without forcing to ignore dependencies, it fails uninstall with a few dependencies). | why can't I install packages with rpm? I get transaction lock | centos;yum;root;rpm | null |
_cogsci.15193 | As there is evidence of massive-scale emotional contagion through social networks, I'd like to know if any study has been made regarding predictive keyboards.Given the popularity of predictive keyboards in the mobile space, I would say that there is a good chance that similar effect can be measured.Such keyboards come with pre-trained models that usually adapt to the user's behavior, even faster if it has the grants and features to analyze previous user written content. I believe that it can lead to self feeding spirals on the psychological side and, depending on the age group, neurological effects but I would like to know what has been researched already.The question on the title is meant to be a focused starting point as, depending on the answer I would have the vocabulary to actually make many others (some probably very obvious given the above mentioned). | Is there any study about the impact on the continuous use of predictive keyboard by neurologically and psychologically health individuals? | social psychology;cognitive neuroscience;emotion;experimental psychology;computational modeling | null |
_softwareengineering.135910 | First of all, is not a programming matter, is a programmer afair.I'm the new web programmer in my company.I'm here just for 2 weeks. And they want me to teach Wordpress, configure & install it, and things like that.But they have a intranet too to make all the compatibility stuff, tracking clients, ordering event, auto-emailing.Well, the intranet is very nice, and they spent 1 or 2 years with a programmer to do that.But the problem is:The intranet is great for the user (a bad UI experience but works well).They have it from 4 or 5 years now.But if you go to the code, it is annoying.Seriously, it's really really really heavy, code duplicated, insecure. All works ok, but all is wrong in code view.Some points:The site keeps 4GB of disk space (without DB!)There where thousands of files, folders, with no orderA lot of files are duplicatedThere were, at least, 20-40 files you have to configure to change the database sourceSome config files are in .ini, so i can download from anywhereThe sites was coded for 4.0 or 3.x, miraculously it works on 5.x with some warnings.The site was coded without any kind of scalability, they just copy and paste files and keep working, no includes, nothing.For example: I see, at least 40 files called check_in.php in different folders.Functions called: paste() paste_2()...What points you will use to convince your boss to take care of that and refactor all the whole site?It's a pain in the ass. I know refactor all gonna be hard, but I think it's the better way to continue my work.Because they want me to make modifications on that and I have to spent 3 hours just to understand from where comes that **** function called paste() and what exactly do.Ah, one more good point.There's no documentation at all. | How to explain your non-programmer boss you need to refactor a whole site? | php;refactoring | The amount of change one should effect is contentious. What happens if you decide on a 'big bang' approach, estimate that it should take two months to refactor completely, and end up taking six? I'm not questioning your competence - it's just that projects like these can easily spiral out of control.You could make a case for a gentle, iterative refactoring. So maybe you take a day to centralise the configuration files, and then move to other projects. Then two weeks later, you add autoloading. Get small changes live each time, and then wait for a bit for them to bed in. This way you remain productive on new projects, whilst slowly improving your codebase.You should do these things on a separate branch, and if there are other tech people that your changes will touch (programmers, dbas, etc) then get them to buy into your changes before you do them. |
_unix.93658 | What does ; mean in single line scripts like this:while true; do sudo -n true; sleep 60; kill -0 '$$' || exit; done 2>/dev/null &Does it mean new line, or next command? | What is the use of ; in a single line command? | bash;shell;command line;bash script | It's a separator of commands. Though in the first instance, it might be better to think of it as ending the while statement.For example, if you wanted to do a loop while some command returns success, you would do something likewhile test -f /foo; do some_command; done`The semicolon is used to indicate the end of the arguments to test. Otherwise it would think that do is another argument to test.However you can use newlines instead of the semicolon. The following would be exactly equivalent to the example above, just without any semicolonswhile test -f /foodosome_commanddoneIn fact with bash, if you run the above command, and then after it finishes (or you CTRL+C it), if you go back in history (up arrow keys or whatnot), you'll notice it replaces the multi-line command with one using semicolons instead.So yes, the syntax for things like if and while break normal shell behavior.I've personally always thought the syntax is weird, as the do looks strange. But you get used to it. |
_hardwarecs.1298 | I am looking for some sturdy (they will be travelling quite a lot) noise cancelling or, at this price, more likely noise isolating in-ear earphones. I will mostly be listening to classical music and voices, so bass is not as important to me as it may be to others.My research so far has brought me across the Sennheiser CX 175 however; I have read a somewhat worrying number of reviews that mention less than perfect build quality.I am wanting to spend somewhere less than 50 ($75) and I would rather spend less for best quality per money than max out my budget. | Sturdy noise cancelling/isolating earbuds | audio;headphones;earphones | null |
_unix.359070 | > cat b.txt function first { sleep 1 echo $(echo $$) }function second { openssl enc -aes-256-cbc -k $(first) }echo nyi | second | second | second> > time sh -x b.txt + echo nyi+ second+ second+ second++ first++ sleep 1++ first++ sleep 1++ first++ sleep 1+++ echo 32383+++ echo 32383++ echo 32383++ echo 32383+ openssl enc -aes-256-cbc -k 32383+++ echo 32383+ openssl enc -aes-256-cbc -k 32383++ echo 32383+ openssl enc -aes-256-cbc -k 323832;<VpHFqAHOSdd4X#}real 0m1.026suser 0m0.016ssys 0m0.025s> Question: why doesn this script runs for at least 3 seconds? There is a sleep 1 in the first function and it should be called 3 times in the second function. According to the real 0m1.026s it seems that the sleep is only executed once. Or if it is parallel (??) then how can I make it linear? | Function in function will not be called multiple times if requested? | shell;pipe;function | The parts of a pipeline are started (close to) simultaneously.All three invocations of second will start at the same time. The three subshells that this gives rise to will invoke first to expand $(first) and the three sleep 1 calls will happen concurrently (you can see in the trace output that they do happen).It's only the I/O that serializes a pipeline, i.e. one process in the pipeline waiting for input from the previous, or waiting to have its output read by the next.To have the bits of the pipeline start, run and exit in sequence:echo nyi | second >out1second <out1 >out2second <out2That is, run them separatedly and store the intermediate results in files. |
_vi.6237 | When I type o, it will insert a new line, and it is exactly new line without any indentation. The cursor will go to the beginning. How can I insert a new line with the indentation of the line above? | How can I insert a new line with the indentation of the line above? | indentation | null |
_webmaster.107342 | Adsense now supports the creation of a Responsive Link unit (in addition to the normal Responsive units that were available long time ago).However, if you create a Responsive Link unit and place the code in your website, it shows very limited sizes such as 728x15, 468x15 etc which are very bad sizes in terms of CTR.The following article shows how to modify the responsive ad code according to your needs:https://support.google.com/adsense/answer/6307124?hl=enDoes anyone know if the above article applies also to Responsive Link units? What I want to do is to create a Responsive Link unit and modify the code (according to the article above) in order to show 300x250 Link Unit sizes which are not available normally when creating a Link ad. This Link Unit size of 300x250 has much higher CTR than the normal link ad sizes.Can I do the above with a responsive link ad or its against the Adsense TOS? I have contacted the Adsense forum but nobody has answered my question.I have tried the following code modification on my website and works fine (it displays a nice 300x250 unit consisting of 6 links):<style type=text/css>.link_unit_slot { width: 300px; height: 250px; }</style> <script async src=//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js></script><!-- ResponsiveLinks --><ins class=adsbygoogle link_unit_slot style=display:block data-ad-client=ca-pub-xxxxxxx data-ad-slot=xxxxxxxx data-ad-format=link></ins><script>(adsbygoogle = window.adsbygoogle || []).push({});</script>Do you think the above is against Adsense TOS? I would appreciate any feedback. | Can I modify the code for an Adsense responsive link unit within the AdSense policies? | google;google adsense;google adsense policies | null |
_unix.362702 | The following code used to work in my .tmux.conf:# Mac OS X:bind-key -n -t emacs-copy M-w copy-pipe reattach-to-user-namespace pbcopy# Move tmux copy buffer into x clipboardunbind-key M-wbind-key -n M-w run tmux save-buffer - | xclip -i -selection clipboard \; display-message 'Copying to clipboard'It stopped working just recently, so I can't copy text anymore from tmux to elsewhere. I am guessing this is the result of upgrading tmux or reattach-to-user-namespace.I now get the following error:invalid or unknown command: bind-key -n -t emacs-copy M-w copy-pipe reattach-to-user-namespace pbcopyHere are the versions I am using (from brew)./usr/local/Cellar/tmux/2.4/bin/tmux/user/local/bin/reattach-to-user-namespace/2.5What may have changed, and how can I go about restoring my ability to copy from tmux to the system? | Unable to copy from tmux (2.4+) to the OS X clipboard | osx;tmux | null |
_unix.62901 | I need an idiots guide to installing Xen Hypervisor on CentOS 5.9We attempted to install it on 6.3 before, but completely failed, so we reverted to 5.9 to see if we had more luck. We had issues trying to find the right kernel download etc and RPM's weren't working correctly, and it was just a mess in general. So I was wondering if anybody knew of a great step by step guide to installing Xen Hypervisor on CentOS 5.9 for idiots, that is still 100% working? | Guide to installing Xen on CentOS 5.9 (That is still valid) | centos;virtual machine;xen | null |
_softwareengineering.306001 | I'm wondering what the exact definition of the header-field Sec-Websocket-Key is. The field is used for Websocket connections. The client asks the server to upgrade from HTML to Websocket. The request can look like this:GET /chat HTTP/1.1Host: server.example.comUpgrade: websocketConnection: UpgradeSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==Origin: http://example.comSec-WebSocket-Protocol: chat, superchatSec-WebSocket-Version: 13The Sec-WebSocket-Key field is defined as follows [RFC6455]:The |Sec-WebSocket-Key| header field is used in the WebSocket opening handshake. It is sent from the client to the server to provide part of the information used by the server to prove that it received a valid WebSocket opening handshake. This helps ensure that the server does not accept connections from non-WebSocket clients (e.g., HTTP clients) that are being abused to send data to unsuspecting WebSocket servers.The |Sec-WebSocket-Key| header field MUST NOT appear more than once in an HTTP request.And also in [RFC6455]:For this header field, the server has to take the value (as present in the header field, e.g., the base64-encoded [RFC4648] version minus any leading and trailing whitespace) and concatenate this with the Globally Unique Identifier (GUID, [RFC4122]) 258EAFA5-E914-47DA- 95CA-C5AB0DC85B11 in string form, which is unlikely to be used by network endpoints that do not understand the WebSocket Protocol. A SHA-1 hash (160 bits) [FIPS.180-3], base64-encoded (see Section 4 of [RFC4648]), of this concatenation is then returned in the server's handshake. Concretely, if as in the example above, the |Sec-WebSocket-Key| header field had the value dGhlIHNhbXBsZSBub25jZQ==, the server would concatenate the string 258EAFA5-E914-47DA-95CA-C5AB0DC85B11 to form the string dGhlIHNhbXBsZSBub25jZQ==258EAFA5-E914-47DA-95CA- C5AB0DC85B11. The server would then take the SHA-1 hash of this, giving the value 0xb3 0x7a 0x4f 0x2c 0xc0 0x62 0x4f 0x16 0x90 0xf6 0x46 0x06 0xcf 0x38 0x59 0x45 0xb2 0xbe 0xc4 0xea. This value is then base64-encoded (see Section 4 of [RFC4648]), to give the value s3pPLMBiTxaQ9kYGzzhZRbK+xOo=. This value would then be echoed in the |Sec-WebSocket-Accept| header field.I've completly understood the purpose of this field. However, I can not find any information on how exactly it is generated. Probably it is not just a random string with random length and a random charset. | Exact definition of Sec-Websocket-Key in Websocket Protocol | websockets;protocol | null |
_codereview.134518 | I have this simple cache mechanism for a repeated task in service. It uses static variable to store the information. Please suggest on how is it and if it could be better.Premise: I need to verify transaction from stores. There can be lots of transactions happening repeatedly from multiple stores. Thus, this simple cache manager for getting the store information. I want it to be simple yet effective and fast.StoreCacheManager.cspublic class StoreCacheManager{ private static List<StoreCacheInformation> _merchantStores = new List<StoreCacheInformation>(); private DBEntities _db; private TimeSpan _cacheTime = new TimeSpan(1, 0, 0);//1 Hour public TimeSpan CacheTimeSpan { get { return _cacheTime; } } public StoreCacheManager(DBEntities db) { _db = db; } public async Task<StoreCacheInformation> Get(int storeId) { if (_merchantStores.Any()) { var store = _merchantStores.FirstOrDefault(i => i.StoreID == storeId); if (store != null) { // Check if Cache time has expired if (store.CacheDateTimeUtc.Add(_cacheTime) < DateTime.UtcNow) { lock (_merchantStores) { _merchantStores.Remove(store); } } else { return store; } } } return await GetAndCache(storeId); } private async Task<StoreCacheInformation> GetAndCache(int storeId) { var store = await GetStoreInfo(storeId); if (store != null) { lock (_merchantStores) { _merchantStores.Add(store); } } return store; } private async Task<StoreCacheInformation> GetStoreInfo(int storeId) { var storeInfo = await _db.Stores.Where(i => i.StoreID == storeId).Select(i => new StoreCacheInformation() { CountryCode = i.CountryObj.CountryCode, MerchantID = i.VendorOrgID ?? 0, TelephoneCode = i.CountryObj.TelephoneCountryCode, StoreID = storeId, //todo: deviceId and Token }).FirstOrDefaultAsync(); if (storeInfo != null) { storeInfo.CacheDateTimeUtc = DateTime.UtcNow; } return storeInfo; }}StoreCacheInformation.cspublic class StoreCacheInformation{ public int MerchantID { get; set; } public int StoreID { get; set; } public string TelephoneCode { get; set; } public string CountryCode { get; set; } public DateTime CacheDateTimeUtc { get; set; } public string DeviceId { get; set; } public string AuthToken { get; set; }} | Simple Cache Mechanism | c# | ConcurrencyIf you want to implement it thread-safe, you have also lock the whole transaction. For instance: store != null assumes that there is no item in cache. Imagine that after that check another thread added one. That would result in a cache where the same item is cached twice.Conside to use a thread-safe collection (e.g. ConcurrentDictionary) instead of using locking..Net Framework already provides a thread-safe cache: MemoryCache.I am not very familiar with the entity framework, but as far as I know is the DbContext not thread-safe. Therefore it is not a good idea to use a single instance of it in multithreaded environments.Code Style_merchantStores, _db and _cacheTime should be read-only.Methods that return a Task should be called xxxAsyncThe property setter in StoreCacheInformation should be private or at least internal. Otherview external code may modify the state of the cached items.For many cached items, it is better to use a dictionary instead of list. |
_softwareengineering.137830 | On personal projects (or work), if one gets stuck on a problem, or waiting to figure out a solution to the problem, if you jump to another section of your code, don't you think it will be a good reason your application will be buggy or worse yet never get completed?Assuming you are not using git and code each feature to a specific branch, things can get out of hand since you have 3 different features you are working on, and you have unresolved issues in each.So when you get done to work, you get stressed out because you have these hanging issues and half-baked code lingering about.What's the best way to avoid this problem? (if you have it)I'm guessing using something like git and creating a branch per feature is the safest way to avoid this bad habit.Any other suggestions? | Jumping around to work on different features when you get stuck, is it a source of project failures? | productivity | null |
_unix.31939 | I am dual booting arch linux on my mac mini 3,1. Am trying to get the WiFi to work and have hit a block. Am a Linux noob so have a couple of questions which I will put in bold. Following these instructions. I have identified my card as BCM4321, which from the tables I read I can use the b43 driver/module (is a driver really just a module?) which is already in the kernel. I ran lsmod and sure enough can see that b43 is loaded. Checked iwconfig and can see wlan0 IEE 802 ect. If I run ip link set wlan0 up (which i'm guessing turns on the card/wifi?) I'm notified about the need for some firmware. Ok so reading the instructions from the above website I need to get this firmware which I am pretty sure would solve the aforementioned issue, but my main problem is how do I get the firmware without physically connecting the mac to router via ethernet. I have a laptop that I'm currently using with W7 and F16 on and a pendrive which currently has the arch installation media on it, I am hoping i can stick the firmware on a pendrive and load from there if so how?Whilst writing this I have thought that I should just be able to wget the tarballs from here, put those on the pendrive and then try loading transferring them into arch, will still ask this question in case of failure :-) | Help with getting wifi up and running in Arch Linux on Mac Mini 3,1 | arch linux;wifi;firmware;broadcom | I should just be able to wget the tarballs from http://linuxwireless.org/en/users/Drivers/b43 put those on the pendrive and then try loading transfering them into archThat is exactly what to do. Unfortunately, Broadcom does not provide distribution licensing for the firmware, so you have to download their full proprietary driver from their website, then extract the firmware from it. This can be done on any system. There are directions on the site you linked about how to do this. At one point, it has you download a different driver version depending on what kernel version you have. Archlinux systems usually have the latest kernel, but if you just installed from an installation medium, it may be older; do uname -a on the Arch system to find out what kernel version you have. Once you have it, place it in the /lib/firmware/ directory of your Arch system.. |
_codereview.112318 | I need validation for all DTO objects using System.ComponentModel.DataAnnotations. You can see how I implemented. Idea is to have one abstract class that will be inherited in all dto classes.This abstract class have check if object is valid and get all validation results.Is this good approach?What do you think?dto base class : public abstract class DtoBase : IValidatableObject { public virtual IEnumerable<ValidationResult> GetValidationResult() { return Validate(new ValidationContext(this)); } public bool IsValid() { return Validate(new ValidationContext(this)).Count() == 0; } public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { var results = new List<ValidationResult>(); Validator.TryValidateObject(this, validationContext, results, true); return results; } }dto work item : public class WorkItemDto : DtoBase { public WorkItemDto() { } public int Id { get; set; } [StringLength(500, MinimumLength = 200)] public string Description { get; set; } [Range(20, 5000)] public int ItemNumValue { get; set; } public ICollection<ItemUsageDto> Usage { get; set; } }Example how to use in wpf or in mvc project (it have to work in any client): var item = new WorkItemDto(); item.Description = my descryption; item.ItemNumValue = 5; item.Id = 7; var isValid = item.IsValid(); var allResults = item.GetValidationResult(); | Validation for DTO using DataAnnotations | c#;validation | null |
_unix.189477 | I am running ubuntu 14.04 on thinkpad x201 tablet. I have tested the tablet modus once and the played a bit with the buttons under the screen (so rotated the screen). But now at the starting the netbook the reversed screen has been some how set as the default position for the screen. does any ubuntu user know how to fix this back to the normal position? I appreciate any help | Thinkpad x201 Tablet, rotating Screen | xorg;monitors;thinkpad | RandR may fit your needs. You want to have a look at the --rotate option:xrandr --output LVDS --rotate leftYou can ask for output devices using xrandr -q. |
_cstheory.38021 | A very simple questions. Let B be the BWT (BurrowsWheeler transform) of a string S. My question is, due to grouping of consecutive characters in BWT, is it possible to somehow know the number of equal characters that follow given the first character of its kind (or at least some lower bound on the number of such characters). So let say B=...caaaaabaccccccacc... then, is it possible to know that after the first a there will be at least 2 consecutive a's or maybe the exact number of a's that follow?Or alternatively one can pose a complementary question, a flip side of the above question (I write the question in order to better describe the problem):Is there a better way to find breaks in BWT aside from checking each character and comparing it with the previous one. That is, let say I want to locate ab break. I would need to go from left to right and compare second character with the first one and then third with the second and so on until I find out where the pair mismatches. Is there a way to check every second character and come to the same result, because if this is possible then there exist a lower bound on the number of same consecutive characters (which is 2)? | BWT: is it possible to predict the next character in a sequence? | string matching;string search | null |
_webmaster.68304 | Will changing links to remove query string parameters that are no longer used have any negative impact on search engine rankings?Say I have a page about.php on my site, and all of my links to this page are of the formhttp://www.example.com/about.php?foo=barand I've made some changes to the script such that the parameter foo is no longer used.I would like to remove the unused parameter from the links so the URL will look cleaner, but I am concerned that this could cause problems with SEO.Is it safe to remove ?foo=bar from my links? | Will removing unused query string parameters negatively affect SEO? | seo;query string | On the long term, no, but on the short term there might be some fluctuation.There are two possibilities to mitigate this issue:- In Google Webmaster Tools, in Crawl > URL Parameters, you can tell Google which parameters to ignore.- Set a canonical without the old parameter on url pages still having the old parameter. |
_codereview.169229 | I have started to read Robert C. Martin Clean Code book.To learn and gain more expreiences I wrote a single Log class. So I want some suggestions to improve this code..This is a part of the Log class:public class FileLogger : ILog{ private string directoryPath = string.Empty; private string fileName = string.Empty; public FileLogger(string logDirectoryPath, string logFileName) { if (string.IsNullOrEmpty(logDirectoryPath)) { throw new ArgumentException(nameof(logDirectoryPath), Write some error message...); } if (string.IsNullOrEmpty(logFileName)) { throw new ArgumentException(nameof(logFileName), Write some error message...); } this.directoryPath = logDirectoryPath; this.fileName = logFileName; } public void LogMessage(string message) { try { if (!string.IsNullOrEmpty(message)) { if (!LogDirectoryExists(directoryPath)) { CreateLogDirectory(directoryPath); } WriteToLogFile(message); } } catch (Exception ex) { //Catch exception, do something... } } private bool LogDirectoryExists(string logDirectoryPath) { return Directory.Exists(logDirectoryPath); } private void CreateLogDirectory(string logDirectoryPath) { Directory.CreateDirectory(logDirectoryPath); } private void WriteToLogFile(string message) { using (var logFile = new FileStream(Path.Combine(directoryPath,fileName), FileMode.Append, FileAccess.Write)) { using (var logFileWriter = new StreamWriter(logFile)) { logFileWriter.Write(message); } } }}I wrote 3 different function to write a message to a log. I try to use SRP and Command Query Separation, but I don't sure this is a good in this way. Maybe there are another problems with this code, example naming or variable declarations. | Write a message to a log | c#;beginner;file;logging | After discussion in comments your code became much better.Also if directoryPath and fileName will not be changed after initialization in constructor you can define these fields as readonly:private readonly string directoryPath = string.Empty;private readonly string fileName = string.Empty;This codeusing (var logFile = new FileStream(Path.Combine(directoryPath,fileName), FileMode.Append, FileAccess.Write)){ using (var logFileWriter = new StreamWriter(logFile)) { logFileWriter.Write(message); }}can be replaced withFile.AppendAllText(Path.Combine(directoryPath, fileName), message);Also ArgumentException's constructor takes message as first argument and paramName as second, so you need to call it like this:throw new ArgumentException(Write some error message..., nameof(logDirectoryPath)); |
_unix.56523 | I have set up two monitors in my system. One is powered by the HDMI port and the other one is powered by the normal analogue port of the same GPU (Nvidia Ge-force 210).I just setup twin display in Nvidia settings but can't see cinnamon's panel on the second monitor. How can I fix this? | Adding the panel to the second monitor | linux mint;dual monitor;cinnamon | null |
_unix.319574 | I have some scripts that work perfectly when I invoke them directly but not when invoked via a keyboard macro.I've tired looking at bash logs and history but I don't think those locations only show information about scripts I directly invoked. How can I find logs and history about my scripts that I'm not invoking directly? | View logs for non-interactive shell script? | bash;logs;command history | null |
_scicomp.20832 | This might be better somewhere else, but I'll give it a try here first.I'm implementing a finite volume scheme for an axisymmetric problem in C, and am looking for a more efficient way to handle all of the necessary parameters each function needs. Is a pointer to a struct better, more efficient, or easier in implementation than a list of the function parameters? I personally think the struct is easier to handle when writing the code, but my professor, who loves Fortran, probably doesn't agree. Is the use of structs in scientific computing accepted? Tolerated? Something that should be avoided?Thanks for your thoughts. | Use of structs in Axisymmetric Finite Volume method | finite volume;c;programming paradigms | null |
_webapps.26851 | I have registered a domain name and created an email account for that domain using Google Apps. I want to know what will happen to my Google Apps account associated with that domain after its registration expires or if Im not going to use it (the domain I mean). | Do I need to verify my domain name again for Google Apps after it expires? | gmail;google apps;domain | When the domain name expires so will the MX records for that domain. As you have already verified the domain with Google theoritically you will still be able to send email as that domain (since you are using Google servers to send) however you will no longer recieve incoming mail.Its possible that Google might detect the domain is no longer registered and prevent you from sending mail. That being said, Google wont disable or delete your apps account when your domain expires (provided you continue to pay the subscription) - all your data will remain and the account will still function, just without email (eg. you will still be able to use your Google docs) |
_unix.58449 | When giving presentations, I use the html/css/js-based showoff. It has a presenter mode which shows the notes and the progress in a good way for me. It seems like the idea is that somehow a second browser gets the changes I do in this mode, but that does not work.Therefore I thought of putting just the part of the presenter mode which displays the current slide (this is a 1024x768 area) on another device, namely the beamer display.As X has such a vast tooling box, I figured this could be possible. The presentation has been given with mirrored displays, which went good enough. What remains is the curiosity if it would have been possible:Can I display part of a window on the second device?I use xmonad as window manager normally. If this is supported by another window manager, I could switch just for presentations.UPDATEI am more interested in the way this could be achieved by X11 means (or related tools) than just having the presenation run fine. That's just the incident that created my interest in such a solution.SECOND UPDATEI am still looking for a pure X11-solution, but the problem at hand is of course solved. | Can I display part of a window on the second device? | ubuntu;xorg;x11 | I don't know a thing about showoff, but I did use dzslides in a similar way. Things to check are:Does you window manager support multiple displays? (E.g. after xrandr --output VGA1 --right-of LVDS1, does it handle the other one?) XMonad should,, i3 provides good multihead support, too.Your presenter console should control the other window in normal presentation mode. What happens when you open both modes in separate windows? I.e. when showoff saysYour ShowOff presentation is now starting up.To view it plainly, visit [ #{url} ]To run it from presenter view, go to: [ #{url}/presenter ]try opening both URLs in two windows.If, as I hope it does, the presenter view window controls the plain view one, just move the plain view window to the other monitor (this depends on how your WM handles multiple monitors). If it doesn't, you could consider filing an issue...This should be easier than X11 hackery. |
_unix.109543 | I'm running a Hydra on Rasppberry PI. There were some problems with the program, but aside from these, there is a hidden memory leak in the program. The source is pretty big and really can't find the problem.Unfortunatelly, upon reaching memory limit, the program doesn't crash - instead it returns bunch of error messages. When I say bunch, I mean hundreds. So I thought the if I can't un-allocate the memory within the program, I might need to reset whole process. So I need to:Guard the process resource usageStop the process gracefully (similar to Ctrl+C, the program says received signal 2 then)Start the process againI must do this until fix the program to die on errors - or not to produce them in the first place.If you know hydra and you're curious about the errors I've found at least something in the code:[ERROR] Fork for children failed: Cannot allocate memory[ERROR] socketpair creation failed: Too many open filesThe second part of the errors comes from perror C system function. It's sort of last error. | Reset running process when certain ammount of memory is consumed | debian;raspberry pi;raspbian;hydra | #1 - GodHere's an idea using the process monitoring framework God. This application is written in Ruby but can be used to watch other processes, and guard against them doing things, such as dying or, in your case, use up too much RAM. Ruby setupAssuming you have Ruby installed -- you can use rvm (aka. Ruby Version Manager) to do this if you don't, but it will need to be installed and/or run as root. This is a requirement of god. You could also just install Ruby from your distro's repositories if it's available. God setupWith a working Ruby installation you install the God gem like so:$ [sudo] gem install godExampleYou can then use this simple God config to do what you want.# /path/to/simple.godGod.watch do |w| w.name = hydra w.start = <command to run hydra> w.keepalive(:memory_max => 150.megabytes, :cpu_max => 50.percent)endThen invoke it like this:$ god -c /path/to/simple.god -DNow if Hydra exceeds either the CPU utilization or the memory used, God will restart it. NOTE: By default these properties will be checked every 30 seconds and will be acted upon if there is an overage for three out of any five checks.Going furtherTake a look at the documentation on God's website. The above example is from there and they do a much more thorough job of covering the details.#2 - Process Resouce MonitorAnother alternative is Process Resource Monitor. The feature list shows that it can monitor per process resources.per-process/per-user rule based resource limitsexcerpt of descriptionProcess Resource Monitor (PRM) is a CPU, Memory, Processes & Run (Elapsed) Time resource monitor for Linux & BSD. The flexibility of PRM is achieved through global scoped resource limits or rule-based per-process / per-user limits. A great deal of control of PRM is maintained through a number of ignore options, ability to configure soft/hard kill triggers, wait/recheck timings and to send kill signals to parent/children process trees. Additionally, the status output is very verbose by default with support for sending log data through syslog.ExampleTo monitor Hydra we could create a rule file like this, /usr/local/prm/rules//hydra.cmd:IGNORE=MAX_CPU=50MAX_MEM=150MAX_PROC=0# we dont care about the process run time, set value 0 to disable checkMAX_ETIME=0KILL_TRIG=3# we want to set a bit longer soft rechecks as sometimes the problem fixes# itselfKILL_WAIT=20KILL_PARENT=1KILL_SIG=9KILL_RESTART_CMD=/etc/init.d/hydra restartprm runs via cron, /etc/cron.d/prm on 5 minute intervals. According to the docs this should probably be left alone. |
_cstheory.38288 | Given a 2HornSAT problem, its possible in linear time to find the minimum solution to the problem, i.e., a solution that minimizes the number of variables set to 1.Now let us consider the following restricted variant of that problem:Input: A positive integer $K$ and a 2SAT instance in which all clauses are mixed, i.e., have a positive literal and a negative literal.Output: Is there a satisfying assignment such that exactly $K$ variables are set to 1?Is this problem NP-complete? I am struggling with its reduction but it seems this might be difficult. | totally-mixed 2SAT with exact cardinality? | cc.complexity theory;np hardness | Your problem is NP-complete.I prove NP-hardness below by reduction from the clique problem (given a graph and a number, does the graph have a clique of that many vertices).reductionSuppose we are given a clique instance consisting of a graph $G = (V, E)$ with $m = |E|$ and $n = |V|$ and a number $k$. Then we will produce an instance of your problem consisting of a formula $\phi$ and a number $K$ as described belowFirst of all, we set $K = k + (n+1) \times {k \choose 2}$.Next, lets describe the variables used in $\phi$. For each vertex $v \in V$, $\phi$ will include a variable $x_v$. For each edge $e \in E$, $\phi$ will include $n+1$ variables: $y_e^0, y_e^1, \ldots, y_e^n$.Finally, lets describe the clauses included in $\phi$. Each clauses has the form $(a \vee \neg b)$, which is logically equivalent to $(b \to a)$, so I will write all clauses in implication form. For each edge $e \in E$, we include clauses $(y_e^n \to y_e^0)$, $(y_e^0 \to y_e^1)$, $(y_e^1 \to y_e^2)$, ..., and $(y_e^{n-1} \to y_e^n)$. The effect of these clauses is to enforce the equality of all the $y_e^i$s (for any fixed $e$) in any satisfying assignment. Next, for any edge $(u, v) \in E$, we also include clauses $(y_{(u,v)}^0 \to x_u)$ and $(y_{(u,v)}^0 \to x_v)$. The effect of these clauses is that in any satisfying assignment, if the variables $y_{(u,v)}^i$ associated with an edge are true then the variables $x_u$ and $x_v$ associated with the endpoints must also be true.clique $\to$ satisfying assignmentSuppose that there is a clique $C$ of size $k$ in $G$. Then we can create a satisfying assignment for $\phi$ with exactly $K = k + (n+1) \times {k \choose 2}$ true variables.In particular, for $v \in V$, set $x_v$ to true iff $v \in C$, and for $e \in E$, set $y_e^i$ to true iff both endpoints of $e$ are in $C$.There are $n+1$ variables $y_e^i$ for each $e$, and there are exactly $k \choose 2$ edges in $G$ with both endpoints in $C$ (since $C$ is a clique). Thus there are $(n+1) \times {k \choose 2}$ variables of the form $y_e^i$ that are set to true under this assignment. Furthermore, $|C| = k$, so there are exactly $k$ variables of the form $x_v$ set to true under this assignment. As desired, this assignment has exactly $K = k + (n+1) \times {k \choose 2}$ true variables.Notice that $y_e^i = y_e^j$ for every edge $e$ and pair of indices $i, j$. Thus, the clauses of the form $(y_e^i \to y_e^{(i+1)~\text{mod}~(n+1)})$ are satisfied under this variable assignment. Next, consider any edge $(u, v)$. If $y_{(u, v)}^0$ is true, then both $u$ and $v$ are vertices in $C$, so therefore both $x_u$ and $x_v$ are also true. Thus, clauses $(y_{(u,v)}^0 \to x_u)$ and $(y_{(u,v)}^0 \to x_v)$ are also satisfied.Since all clauses are satisfied, this is a satisfying assignment (which we already noted has exactly $K$ true variables).satisfying assignment $\to$ cliqueNext suppose we have a satisfying assignment of $\phi$ with exactly $K = k+ (n+1) \times {k \choose 2}$ true variables.Any satisfying assignment has $y_e^0 = y_e^1 = \cdots = y_e^n$. Then let $y_e = y_e^0$. Define $n_y$ to be the number of true $y_e$s. Similarly, define $n_x$ to be the number of true $x_v$s. Notice that the number of true variables in the assignment is equal to $n_x + (n+1) \times n_y$. Furthermore, $0 \le n_x < n+1$ since there are only $n$ different $x_v$s. Thus, we can conclude that $n_x = K~\text{mod}~(n+1) = k$ and $n_y = \lfloor \frac{K}{n+1} \rfloor = {k \choose 2}$.Let $C = \{v \in V~|~x_v~\text{is true}\}$ and let $E' = \{e \in E~|~y_e~\text{is true}\}$. Note that $|C| = n_x$ and $|E'| = n_y$ by definition. Then $E'$ is a set of ${k \choose 2}$ edges, and $C$ is a set of $k$ edges. Notice that if $(u,v) \in E'$, then $y_{(u,v)}$ is true, and therefore $y_{(u,v)}^0$ is true; as a result, since clauses $(y_{(u,v)}^0 \to x_u)$ and $(y_{(u,v)}^0 \to x_v)$ must be satisfied, we can conclude that $x_u$ and $x_v$ are also true, and therefore that $u,v \in C$. Thus, if $e \in E'$ and $v$ is an endpoint of $e$ then $v \in C$. Thus the set of endpoints of edges in $E'$ is a subset of $C$. Then $E'$ is a set of ${k \choose 2}$ edges whose set of endpoints numbers at most $|C| = k$. A set of ${k \choose 2}$ edges has only $k$ endpoints in total only in the case that the $k$ endpoints are a clique. In other words, it must be the case that $C$ is a clique and the edges in $E'$ are the edges in the clique.Thus we have identified a clique of size $k$ in $G$. |
_cogsci.8682 | Is cognitive science apart of psychology? If I major in psychology, will it be easy for me to be a cognitive scientist? | Is cognitive science a concentration of psychology? | terminology | null |
_unix.1674 | I notice that ncurses's terminfo database on /usr/share/terminfo is about 7MB (I compiled it myself). This is too large if I want to deploy it on an embedded Linux of 64MB disk space.Is there a way to reduce its size by deleting unneeded entries and keep the most-used ones? And what's is this actually for?EDIT: Is there any info or reference for commonly used terminfo for regular PCs or SSH clients? | How to reduce ncurses terminfo size | embedded;ncurses;strip | With ansi, cygwin, linux, vt100, vt220, and xterm terminfo definitions, I expect you'd be able to hit 98% of the terminal emulations that you'll encounter in the wild. Even terminal emulators that have a different native mode can likely be directed to emulate vt100/vt220 modes, often without user intervention. |
_softwareengineering.326247 | I have a need to implement REST API which would support a complex filtering, so user would be able to make such requests:Products?$filter=Price le 3.5 or Price gt 200The API server will use a layered architecture and it will have a layer, which will abstract database access. And here is the problem - on one hand I need to implement flexible filtering and on the other - abstract database access.I wonder - are there proven solutions for that? | How to abstract DB access and yet support flexible filtering? | design;design patterns;architecture;rest;layers | null |
_unix.78914 | for i in $(xrandr); do echo $i ; donefor i in $(xrandr); do echo $i; donefor i in $(xrandr); do echo $i; doneI understand why 1 differs from 2. But why does 3 give a different output from 2? Please explain the output too. How do quotes work on newlines? | Quoted vs unquoted string expansion | bash;shell;quoting;echo;whitespace | An unquoted variable (as in $var) or command substitution (as in $(cmd) or `cmd`) is the split+glob operator in Bourne-like shells.That is, their content is split according to the current value of the $IFS special variable (which by default contains the space, tab and newline characters)And then each word resulting of that splitting is subject to filename generation (also known as globbing or filename expansion), that is, they are considered as patterns and are expanded to the list of files that match that pattern.So in for i in $(xrandr), the $(xrandr), because it's not within quotes, is split on sequences of space, tab and newline characters. And each word resulting of that splitting is checked for matching file names (or left as is if they don't match any file), and for loops over them all.In for i in $(xrandr), we're not using the split+glob operator as the command substitution is quoted, so there's one pass in the loop on one value: the output of xrandr (without the trailing newline characters which command substitution strips).However in echo $i, $i is unquoted again, so again the content of $i is split and subject to filename generation and those are passed as separate arguments to the echo command (and echo outputs its arguments separated by spaces).So lesson learnt:if you don't want word splitting or filename generation, always quote variable expansions and command substitutionsif you do want word splitting or filename generation, leave them unquoted but set $IFS accordingly and/or enable or disable filename generation if needed (set -f, set +f).Typically, in your example above, if you want to loop over the blank separated list of words in the output of xrandr, you'd need to:leave $IFS at its default value (or unset it) to split on blanksUse set -f to disable filename generation unless you're sure that xrandr never outputs any * or ? or [ characters (which are wildcards used in filename generation patterns)And then only use the split+glob operator (only leave command substitution or variable expansion unquoted) in the in part of the for loop:set -f; unset -v IFSfor i in $(xrandr); do whatever with $i; doneIf you want to loop over the (non-empty) lines of the xrandr output, you'd need to set $IFS to the newline character:IFS='' |
_computergraphics.5330 | On the Wikipedia page for the Phong model, it says that the ambient term is a constant, and just gets added on to the other terms. But on other pages like LearnOpenGL it says you should take the ambient term and multiply it by the color of the object. Which one is correct? | Ambient Lighting | rendering;lighting | Correct is the OpenGL way. If you had a white light ( let's say vec3(255,255,255) )and just simply added it to a blue object ( vec3(0,0,255) ), the object would seem to be white, which is wrong. But if you were to multiply these colors, the object would be fully illuminated and correctly blue (which is the desired product).The thing with ambient light is that it is only influenced by the ambient light intensity and by the color of the object, which means it is not influenced by the lights position, direction or anything of the sort. That is why you can think of it as simply adding it as a constant.We use ambient light mostly to simulate reflected light in the scene, which is very hard to simulate otherwise (without raytracing). It's a fairly good and cheap alternative. |
_webapps.42485 | I have a web app, and I want to take a good screenshot of it, for its landing page.This is an example. Anyone know how to do it, on on a macbook airHere is an example | Web app for taking high res screenshots of my app | screenshot | First of all, use a computer app instead of a web app to take screenshot. Here are some good screenshot application for MacNext you need to set your screen resolution to the highest possible resolution and it must take the screenshot in a pretty good resolution. Also check if there's some settings for the screenshot application regarding to the resolution of images. Take the screenshot without any appOn Mac you can take screenshots without any additional app. See this to know how http://osxdaily.com/2010/05/13/print-screen-mac/Then you can use the image on the clipboard to edit in an image editing software. Read this for a trick to get high resolution screenshots in photoshop http://www.turbophoto.com/Photoshop-Tricks/screenshot-photoshop-trick/index.htm |
_unix.349467 | I want to assign a part of my current working directory path name to a variable and use it in a script inside the directory itself.For eg:If my pwd is :/home/desktop/project/ABC/abc/abc_123, is there a command to assign ABC to a variable, say $PROJECT_NAME? I tried dirname, but it seems to be returning '.' for input 'pwd', and anyway I need one more step behind than what dirname can supposedly return. | How to retrieve a part of a path name and assign it to a variable? | path;variable;tcsh;variable substitution | Since you're tagging with tcsh:set project = $cwd:h:h:t:qWould set $project to the tail of the head of the head of the current directory (or basename of the dirname of the dirname). :q quotes the resulting text so no further expansions (like splitting or globbing) are done on it.pwd is the command to print the current working directory. That command is not built-in tcsh. The current working directory is (unsurprisingly, or at least less surprisingly that with ksh's $PWD) in the $cwd variable in tcsh. |
_unix.164751 | I am not able to call a shell script program from javascript(for example if someone will click a button in webpage then a script will run and will throw some output)??? | How to call a shell script from Javascript code? | bash;javascript | null |
_codereview.111764 | There are 12 gates. Using our face recognition system, we check every person who tries to enter each gates. My MVC web application is to show the result data to the gate-keeper. And this is the important part. The people in the control center look closely at the current situations in real time.To put it simply, always two connections for a gate.Development EnvironmentEntity Framework 6ASP.NET MVC5SignalR for bidirectional communication with IIS8.5Simple FlowFace recognition completedThe recognition server is going to change a flag on a databaseMy polling job will catch that change within 0.3 secondsSend the result data to the clientswhile (true){ Thread.Sleep(300); using (DisplayModel DPModel = new DisplayModel(NameOrConnstring)) { // Get the result data if there are any flag changes. var ResultData = DPModel.GateDisplay .Where(x => x.g_flag != false) .Select(x => new { x.a_acu_data_id, x.g_status }).ToList(); // If no result data was received and no observers were found ( gate connections ), skip this polling. if (ResultData.Count > 0 && Observers.Count > 0) { // the first loop for each gates. foreach (var Gatedata in ResultData) { string GateName = Gatedata.a_acu_data_id; // See if a client has this current gate ID if (Observers.ContainsKey(GateName)) { // Get the result data produced by the face recognition server GateViewDataModel ProcessedData = DPModel.DisplayViewData .Where(x => x.GATE_NUM == GateName) .Select(x => new GateViewDataModel { COMPANY_NAME = x.COMPANY_NAME, NAME = x.NAME, ENRO_IMG = x.ENRO_IMG, GATE_NUM = x.GATE_NUM, LOG_IMG = x.LOG_IMG, G_STATUS = x.G_STATUS, MODE = x.MODE, PERMIT_AREA = x.PERMIT_AREA }).ToList<GateViewDataModel>().First(); if (ProcessedData.ENRO_IMG != null && ProcessedData.ENRO_IMG.Length > 0) ProcessedData.CONVERTED_ENRO_IMAGE = Convert.ToBase64String(enc.Decrypt(ProcessedData.ENRO_IMG, key)); if (ProcessedData.LOG_IMG != null && ProcessedData.LOG_IMG.Length > 0) ProcessedData.CONVERTED_LOG_IMG = Convert.ToBase64String(enc.Decrypt(ProcessedData.LOG_IMG, key)); // No need to send the original binary data. ProcessedData.ENRO_IMG = new byte[] { 0 }; ProcessedData.LOG_IMG = new byte[] { 0 }; // the second, nested loop for all the connections to this current gate. foreach (KeyValuePair<string, IHubCallerConnectionContext<dynamic>> dic in Observers[GateName]) { // Server sent event by SignalR dic.Value.Caller.onReceived(GateName, ProcessedData); } // Initilaize the flag. var Entity = DPModel.GateDisplay.Single(x => x.a_acu_data_id == GateName); if (Entity != null) { Entity.g_flag = false; DPModel.SaveChanges(); } } } } }}This code is set to run forever right after my application startup.What I just can't change isThe way I receive the result data. It would be ideal if the face recognition server could send the data directly to the each clients every time it finishes the recognition job. But unfortunately, it doesn't and I don't have enough time to change that right now.PerformanceWhen my polling catches all the changes at once (this will rarely happen though...), there's going to be 12 loops with two nested loops (two clients are supposed to get the data: one is for the gate-keeper and another is for the people in control center). It takes about 0.8s or 1.8s to complete distribution of the result data to each clients.This is \$O(n^2)\$, isn't it? | A polling method and nested loop | c#;entity framework;signalr | null |
_codereview.155875 | Just the beginning of graphs API in Python:# Simple graph API in Python, implementation uses adjacent lists.# Classes: Graph, Depth_first_search, Depth_first_paths# Usage:# Creating new graph: gr1 = Graph(v) - creates new graph with no edges and v vertices;# Search object: gr2 = Depth_first_search(graph, vertex) - creates search object,# gr2.marked_vertex(vertex) - returns true if given vertex is reachable from source(above)# Path object: gr3 = Depth_first_paths(graph, vertex)- creates a new path object,# gr3.has_path(vertex) - thee same as above# gr3.path_to(vertex) - returns path from source vertex (to the given)class Graph: class graph def __init__(self, v_in): constructor - takes number of vertices and creates a graph with no edges (E = 0) and an empty adjacent lists of vertices self.V = v_in self.E = 0 self.adj = [] for i in range(v_in): self.adj.append([]) def V(self): returns number of vertices return self.V def E(self): returns number of edges return self.E def add_edge(self, v, w): void, adds an edge to the graph self.adj[v].append(w) self.adj[w].append(v) self.E += 1 def adj_list(self, v): returns the adjacency lists of the vertex v return self.adj[v] def __str__(self): to string method, prints the graph s = str(self.V) + vertices, + str(self.E) + edges\n for v in range(self.V): s += str(v) + : for w in self.adj[v]: s += str(w) + s += \n return sclass Depth_first_search: class depth forst search, creates an object, constructor takes graph and a vertex def __init__(self, gr_obj, v_obj): self.marked = [False] * gr_obj.V self.cnt = 0 self.__dfs(gr_obj, v_obj) def __dfs(self, gr, v): void depth first search, proceed recursively, mutates marked - marks the all possible to reach from given (v) vertices; also mutates cnt - number of visited vert self.marked[v] = True self.cnt += 1 for w in gr.adj_list(v): if self.marked[w] == False: self.__dfs(gr, w) def marked_vertex(self, w): returns True if given vertex (w) is reachable from vertex v return self.marked[w] def count(self): returns number of visited verticles (from given in the constructor vertex) return self.cntclass Depth_first_paths: class depth first paths, solves single paths problem: given graph and a vertex (source vertex), find a path to another vertex. def __init__(self, gr_obj, v_obj): self.marked = [False] * gr_obj.V self.edge_to = [0] * gr_obj.V self.s = v_obj self.__dfs(gr_obj, v_obj) def __dfs(self, gr, v): void recursive depth first search, mutates array marked, mutates counter (cnt), and creates a path (filling an array edge_to) self.marked[v] = True for w in gr.adj_list(v): if self.marked[w] == False: self.edge_to[w] = v self.__dfs(gr, w) def has_path(self, v): returns true if there is a path from the source vertex to the given, else false return self.marked[v] def path_to(self, v): returns path from source to the given vertex if self.has_path(v) == False: return None path = [] x = v while x != self.s: path.insert(0, x) x = self.edge_to[x] path.insert(0, self.s) return pathI've used classes not function because there is no need for global variables. How do you think build the rest graph algorithms on it? | Simple Graph in Python | python;algorithm;python 3.x;graph;api | I've reviewed your code and I can make the following remarks. I'm only going to review the Graph class for now so lets start:class Graph: class graphHere the comment is redundant. We know its a Graph and we know its a class. Also note for completeness I like to write class Graph(object)def __init__(self, v_in): constructor - takes number of vertices and creates a graph with no edges (E = 0) and an empty adjacent lists of vertices self.V = v_in self.E = 0 self.adj = [] for i in range(v_in): self.adj.append([])Again the comment is redundant We know its a constructor and what it initializes. However as you may notice the real problem here is not the comment but what it describes. Those V, E, v_in parameters are too short and do not mean anything. If I were to read the method body and not the class name I wouldn't be able to understand that they denote Vertices and Edges. So a better name for them would be vertices, edges and input_vertices. Note that we use lowercase names for class properties.def V(self): returns number of vertices return self.Vdef E(self): returns number of edges return self.EMore redundant notes as we know they return something. However the method names are wrong. Why V and E? And why do they return a number? I would suspect to return a list or an Object that I can query. A better name would be again vertices and edges.def add_edge(self, v, w): void, adds an edge to the graph self.adj[v].append(w) self.adj[w].append(v) self.E += 1def adj_list(self, v): returns the adjacency lists of the vertex v return self.adj[v]That's not too bad although I would remove the void remark and add a better explanation about the input assumptions. For example what happens if do add_edge(set((1,2,3)), frozenset((4,5,6)))? Traceback error. So its better to specify that it assumes the input is integers.def __str__(self): to string method, prints the graph s = str(self.V) + vertices, + str(self.E) + edges\n for v in range(self.V): s += str(v) + : for w in self.adj[v]: s += str(w) + s += \n return sOk nothing wrong here. I would only rename s to output or response so that I understand the meaning.In general I would say to try to keep the names consistent and meaningful so a reader will not have to guess whats going on. |
_cstheory.2651 | Given RegEx A and B where the size of the compiled DFAs are m and n respectively, what is the upper bound on the size of the compile DFA for A|B? It shouldn't be hard to show that it can't be more than n*m but can a lower upper bound be shown?What about other related case:What is the expected case for real world examples? Is it less than n+m?What about the three part case with A, B and C? | upper bound on the size of a DFA for A|B given the DFAs for A and B? | fl.formal languages;regular expressions;dfa | null |
_unix.369764 | I have a very large list of hostnames from which I am trying to print the TLD (.com, .net, .info, etc.) of each host. The problem is that the hosts have their TLDs in different fields, so I can't tell cut or awk to statically print one field.Some example hostnames:examplehost.net # tld is 2nd field (period delimited)subdomain.otherhost.com # tld is 3rd fieldsubdomain.othersubdomain.yetanotherhost.info # tld is 4th fieldAs a little workaround, I've just been adding a space to the end of each host that way I can include it in my regex pattern and grep for it.sed 's/$/ /g' listofhosts.txt | grep -Eo '\.[a-z]{1,10} 'I was curious if there is a more elegant way to accomplish this. | How can I use sed/grep/awk to print the TLD's from a list of hostnames that have the TLD in different fields? | shell script;text processing | null |
_unix.42157 | While backing up some data (a 200 GB home directory) with rsync, I got an I/0 error for a particular file, after which rsync continued on normally with its backup. The problem source file showed as having a file size of 72 bytes. I cancelled rsync, and ran the same command again. This time that same file showed to be transferring data.. lots of data ...and more data, and more... I checked the destination file's size, and it was up to 13 GB! so I used Ctrl-c to cancel rsync. On checking the source file size again, in Nautilus, it showed a size of 60.0 PB (Peta Bytes!) on a 500 GB drive. Now, the main point of all this: Would/could deleting this file cause loss of data in other files, seeing that the file system can perceive it to be much bigger than it actually is... The file system is ext4.. I could just skip over it with an rsync exception, but I'm particularly interested in what could happen if it is deleted. UPDATE: Both target and source are ext4 Regarding suggestions of it being a sparse file: If it is a sparse file, why would it show different sizes from one minute to the next? The file was certainly(?) not in use at the time. It is a ~/.macromedia/Flash_Player/#SharedObjects/someting-or-other.sol file, of which there are many more such .sol files in that directory .. plus it did show an I/0 error on the first pass. Also, according to man rsync, the suggested -S option is to handle sparse files efficiently, not properly, so that suggests to me that even though I wasn't using -S it should copy a sparse file accurately in either case: which it didn't, and even it if it is a sparse file, being 60.0 Peta Bytes seems surely(?) to be an error in the file system, somewhere... and that is my main concern: If there is a glytch in the file system, could deleting that file have repercussions on other files? More specifically: as it wrote 13 GB of data, and climbing! when I cancelled it, could it also delete 13 GB - 60 PB of data when I delete it? | File size of 60.0 PB is wrong. Can deleting it cause data loss? | filesystems;hardware;io;corruption | It looks like the source filesystem is damaged, typically either due to a kernel bug or to bad RAM (a damaged disk is more likely to result in unreadable files than corrupted data). At this point, all bets are off. However, if the corruption was very localized, it's only that one file's inode that's corrupted, and other files are undamaged, so you can safely delete the file. Note that there is no way to test this assumption.My recommendation is to:Do a RAM test, or plug the disk into another machine.Ensure that you have backed up all your data.Check the health of the disk with SMART, if possible.Run fsck.If the disk is still good, go on using it. |
_unix.325636 | Found this while checking one of DB servers. The machines are Dell PowerEdge R720, running Red Hat Linux and a look through /proc/cpuinfo revealed 32 CPUs with 8 core each. It makes 32*8 = 256 cores. Does it mean, atleast theoretically, that this server can still not be overloaded CPUwise even if top or w outputs load average as 256? (if we chose to ignore whether memory and IO is capable of running that many processes at a time)[root@mercury ~]# cat /proc/cpuinfo | egrep 'processor|cores' | tail -4processor : 30cpu cores : 8processor : 31cpu cores : 8[root@mercury ~]# | Cores-per-CPU and load average | cpu;load average | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.