id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_softwareengineering.167744
I'm really struggling with my software specs. I am not a professional programmer but enjoy doing it for fun and made some software that I want to sell later but I'm not happy with the code quality. So I wanted to hire a real developer to rewrite my software in a more professional way so it will be maintainable by other developers in the future.I read and found some sample specs and made my own by applying their structure to my document and wanted to get my developer friend to read it and give me advice. After an hour and a half he understood exactly what I was trying to do and how I did it(my algorithms,stack,etc.). How can I get better at explaining things to developers? I add many details and explanations for everything(including working code) but I'm unsure the best way I can learn to pass detailed domain knowledge(my software applies big data, machine learning, graph theory to finance). My end goal is to get them to understand as much as possible from the document and then ask anything they do not understand, but right now it seems they need to extract alot of information from me. How can I get better at communicating domain knowledge to developers?
How can I get better at explaining complex software processes to developers?
design;learning;project management;requirements
I would suggest learning more about the upstream activities in software development, especially requirements engineering and system architecture. These two activities are the direct interface from the customer and user needs and environment to the person or people who are building software. These activities are not only directly derived from the inputs from the user and customer, but they also provide the inputs into system-level and acceptance testing.When I was taught about requirements engineering and high level design, I was always taught to involve the right stakeholders from the sponsoring organization - the customer, the user, the people who will be maintaining the system, and so on. These people shouldn't just be involved in making decisions, but also understanding how the system is going to be built and what will be needed from them throughout the project. Taking the initiative and learning these areas on your own would help with interfacing with people who will be building the software.If you want specific resources, Karl Wiegers has two books on requirements engineering - Software Requirements and More About Software Requirements. I can also recommend two books on how software architectures and designs are created - Software Systems Architecture: Working With Stakeholders Using Viewpoints and Perspectives and Software Architecture in Practice.
_unix.167306
I have a text file with following data. Name Feature Marry Lecturer Marry Student Marry Leader Bob Lecturer Bob Student Som StudentI have only 3 features for every person i.e. Lecturer, Student and Leader.The example above is just a sample and in my real data I have many more Persons having these features.Now, I want to make a Unix script by which I can check that which of the 3 features is missing for respective person.I understand that it can be done by making key value relationship, but I'm not able to figure it out correctly.Im running bash shell on SunOS 5.10 i386.
Finding missing value in text file
shell script;text processing;scripting
If you have the list of names in list.txt you can do:for i in Student Leader Lecturer; do grep -F $i list.txt | cut -d ' ' -f 1 | sort > $i.out ; doneTo get the names in 3 separate sorted files, which you can compare with diffuse (or xxdiff or diff3):diffuse *.outIf you just want to have files with the names of the persons missing each label, you can first generate a file with all names and use uniq -u to find the ones that are not in that list (the really unique ones):sed -n '1!p' list.txt | cut -d ' ' -f 1 | sort -u > names.allfor i in Student Leader Lecturer; do fgrep $i list.txt | cut -d ' ' -f 1 | cat - names.all | sort | uniq -u > $i.missing ; doneIf you want to do this from a script and a file feature with:Leader StudentLecturerand the source table in example.txt, you can use:#!/bin/bashrm -f *.missing names.allfeature=featuresed -n '1!p' example.txt | cut -d ' ' -f 1 | sort -u > names.allfor i in $(cat $feature)do fgrep $i example.txt | cut -d ' ' -f 1 | cat - names.all | sort | uniq -u > $i.missing done
_cs.14552
We have a DAG. We have a function on the nodes $F\colon V\to \mathbb N$ (loosely speaking, we number the nodes). We would like to create a new directed graph with these rules: Only nodes with the same number can be contracted into the same new node. $F(x) \neq F(y) \Rightarrow x' \neq y'$. (However, $x' \neq y'\nRightarrow F(x) \neq F(y)$.)We add all the old edges between new nodes: $(x,y) \in E \land x' \neq y' \iff (x',y')\in E'$.This new graph is still a DAG.What is the minimal $|V'|$? What is an algorithm creating a minimal new graph?
Minimal size of contracting a DAG into a new DAG
algorithms;graphs;np complete;reductions
One approach to solving this problem would be to use integer linear programming (ILP). Let's tackle the decision version of the problem: given $k$, is there a way to contract same-color vertices to get a DAG of size $\le k$?This can be expressed as an ILP instance using standard techniques. We're given the color of each vertex in the original graph. I suggest that we label each vertex with a label in $\{1,2,\dots,k\}$; all vertices with the same label and same color will be contracted. So, the decision problem becomes: does there exist a labelling, such that contracting all same-color same-label vertices yields a DAG?To express this as an integer linear program, introduce an integer variable $\ell_v$ for each vertex $v$, to represent the label on vertex $v$. Add the inequality $1 \le \ell_v \le k$.The next step is to express the requirement that the contracted graph must be a DAG. Notice that if there is a labelling of the form listed above, without loss of generality there exists such a labelling where the labels induce a topological sort on the contracted graph (i.e., if $v$ precedes $w$ in the contracted graph, then $v$'s label is smaller than $w$'s label). So, for each edge $v\to w$ in the original graph, we'll add the constraint that either $v$ and $w$ have the same label and same color, or else $v$'s label is smaller than $w$'s label. Specifically, for each edge $v\to w$ in the initial graph where $v,w$ have the same color, add the inequality $\ell_v \le \ell_w$. For each edge $v \to w$ where $v,w$ have different colors, add the inequality $\ell_v < \ell_w$.Now see if there is any feasible solution to this integer linear program. There will be a feasible solution if and only if the labelling is of the desired form (i.e., contracting all same-color same-label vertices yields a DAG). In other words, there will be a feasible solution if and only if there is a way to contract the original graph to a DAG of size $\le k$.We can use any integer linear programming solver; if the ILP solver gives us an answer, we have an answer to the original decision problem.Of course, this isn't guaranteed to complete in polynomial time. There are no guarantees. However, ILP solvers have gotten pretty good. I would expect that, for a reasonable-sized graph, you've got a decent chance that an ILP solver might be able to solve this problem in a reasonable amount of time.It's also possible to encode this as a SAT instance and use a SAT solver. I don't know whether that would be more effective. The ILP version is probably easier to think about, though.(I hope this is right. I haven't checked every detail carefully, so please double-check my reasoning! I hope I haven't gone awry somewhere.)Update (10/21): It looks like ILPs of this form can be solved in linear time, by processing the DAG in topologically sorted order and keeping track of the lower bound on the label for each vertex. This has me suspicious of my solution: have I made a mistake somewhere?
_unix.42512
I have dual screen monitor setup.There are applications (like VLC), where everything works out of the box. If you fullscreen a video, you can use your other screen normally. This is the setup I would expect.Then there are mostly Linux games and ones you can run via Wine. If you run a fullscreen game, other screen just turns black, violet or flickers like crazy. Moreover, when you exit the game, the second screen is off, so I have to restart X.Does anyone know how I make this work better? Is this just a matter of those applications not using the appropriate library, or are there more fundamental issues with mutli-monitor support right now?Added later: Apparently there is no solution, Xorg is just fundamentally broken:http://www.maketecheasier.com/run-fullscreen-games-in-linux-with-dual-monitors/2010/03/01
Fullscreen applications and dual monitor setup ( + cursor grab )
linux;window manager;xrandr;multi monitor
null
_cstheory.10650
I would like to ask how could someone modify FloodSet algorithm to work in a general network,where process failures happen..Is it possible for it to work if a crucial [1] failure happens?[1]: As crucial i mean a failure in a process that cuts the network in two separate pieces
FloodSet in general networks
dc.distributed comp
null
_reverseengineering.2843
I'm trying to get to IAT of a PE file. My plan is eventually overwrite some values so I can hook some stuff to help with unpacking, etc. I'm using this post https://stackoverflow.com/questions/7673754/pe-format-iat-questions as a guide. I'm currently on number 4 and that's where things are getting a little fuzzy for me. I'm able to get a pointer to an entry within the DataDirectory array. I chose the 13th entry because from my research http://msdn.microsoft.com/en-us/library/windows/desktop/ms680305%28v=vs.85%29.aspx it looks like that will lead me to the IAT. I'm not sure I'm on the right track because this DataDirectory has the value for size = 0 and virtualaddress = 172. Is the virtualsize of 172 an offset that must be added to some base address? I'm just working with a simple C program with no debug info that prints, Hello World. Any help is greatly appreciated. Not sure how much showing the code will help my methodology but I'll post the relevant parts below. Any help is appreciated. Thanks!pDOSHeader = ctypes.cast(hModule, ctypes.POINTER(IMAGE_DOS_HEADER)).contentse_lfanew_offset = pDOSHeader.e_lfanewoffset_to_NTHeaders = e_lfanew_offset + hModulepNTHeaders = ctypes.cast(offset_to_NTHeaders,ctypes.POINTER(IMAGE_NT_HEADERS)).contentspImage_NT_Headers = pNTHeaders.OptionalHeaderpDataDirectory = pImage_NT_Headers.DataDirectorypDataDirectory_IAT = pDataDirectory[13]
Using Python CTypes to get to the IAT
python;iat
null
_unix.29688
From my understanding of nginx docs, locations can't be nested (or rather if they are the effects aren't inheritable) and proxy_pass can't belong at the server {} level. So my configuration at the moment is like this, I know I can alleviate some by using filepaths but let's pretend I want different cache headers on different paths whilst using proxy_pass. Presumably there is a better way to write this without the repition:server { listen 80; server_name salessystem.acmecorp.com; location /extjs/ { ## proxy_buffers 128 256k; proxy_pass http://localhost:5400/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; add_header 'X-UA-Compatible' 'IE=Edge;chrome=1'; expires max; gzip on; gzip_http_version 1.1; gzip_vary on; gzip_comp_level 7; gzip_proxied any; gzip_types text/html text/css text/pdf application/json application/x-javascript text/javascript; access_log off; break; } location / { ## proxy_buffers 128 256k; proxy_pass http://localhost:5400/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; add_header 'X-UA-Compatible' 'IE=Edge;chrome=1'; expires epoch; gzip on; gzip_http_version 1.1; gzip_vary on; gzip_comp_level 7; gzip_proxied any; gzip_types text/html text/css text/pdf application/json application/x-javascript text/javascript; access_log off; break; }}
Nginx Configuration - Cache headers on certain paths
nginx
I think of the following for your nginx configuration : since it is just the expires header that differs for your two different locations, although both matching the proxy to the sameserver.try putting both the locations in the single blockbased on the query string, (or location match string) set a differentexpires headertag.server { listen 80; server_name salessystem.acmecorp.com; location ~* (/extjs/|/) { ## proxy_buffers 128 256k; proxy_pass http://localhost:5400/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; add_header 'X-UA-Compatible' 'IE=Edge;chrome=1'; expires max; if ($query_string ~ \/extjs\/) { expires epoch; } gzip on; gzip_http_version 1.1; gzip_vary on; gzip_comp_level 7; gzip_proxied any; gzip_types text/html text/css text/pdf application/json application/x-javascript text/javascript; access_log off; break; }}Please however test according to your needs, especially near the regex matches at location and query_string value matching.However it is not clear, why would you want to extjs to be served out of a proxied server (seems like a dynamic app server), since they are just plain text files if my assumption is right. The requests pertaining to extjs need not go through the proxy or app logic system just incase while they can be served independently through the filesystem. I think of keeping it in its seperate location itself, and have the unique gzip/expires directives unique to it in its own location block while the other common directives can be held in the server block itself.For example:server { ... common gzip directives common header setters common expires setters ... location / { proxy to backend app server settings unique to / location .. } location /extjs { settings unique to /extjs location expires header reset ... }}
_scicomp.7609
I want to determine the spectral radius of a large non-symmetric matrix $A$ whose dominant eigenvalues are a pair of complex conjugates. My first instinct was to use a power iteration with a starting vector $x$ in the complex plane. I do recall that this method tends to have trouble when the dominant eigenvalue is complex and indeed my numerical experiments seem agree with this assessment. Is there a way I can modify the power iteration to converge to one of the two dominant eigenvalues in the complex plane? Is it more advisable to use a arnoldi algorithm to determine the spectral radius?
Estimating the spectral radius when the dominant eigenvalues are complex conjugates
eigenvalues
The power method indeed does not converge in the presence of multiple dominant eigenvalues of the same magnitude. (If you follow the proof, you can see that the iterates will get closer and closer to the subspace spanned by the dominant eigenvectors, but not to any particular vector in this eigenspace).A restarted Arnoldi method is in fact the way to go, but it can be quite a bit simplified since you are only interested in the dominant eigenvalue. Recall that the Arnoldi method consists in computing a unitary matrix $Q\in\mathrm{C}^{n\times k}$ (consisting of basis vectors of the Krylov space spanned by $v,Av,A^2v,\dots A^{k-1}v$ for some given vector $v$) and then solving the smaller eigenvalue problem for $Q^*AQ$ (using the fact that it is in upper Hessenberg form).The idea is now to restart every second step, i.e., given an iterate $x^k$, compute an orthonormal basis of the span of $\{x^k, Ax^k\}$ (since $x^k$ is assumed to be normalized, you only need to orthogonalize $Ax^k$ against $x^k$). Since projection methods best approximate the extremal eigenvalues, the eigenvalues of the projected matrix $Q^*AQ$ will converge to the complex conjugate pair of dominant eigenvalues. In fact, since you are only interested in one of the two eigenvalues, you can just take the Rayleigh quotient for $x^k$; the full iteration (started from a normalized complex vector x) is w = A*x;l = w'*x;w = w-l*x;x = w/norm(w);where l converges to one of the dominant eigenvalues.(This is Problem P-4.2 in Saad's book Numerical Methods for Large Eigenvalue Problems).Edit: Paul explicitly asked about power methods, but for the sake of later readers I should caution that the above works only if $A$ is real and in fact has a pair of complex conjugate dominant eigenvalues. If this is not known a priori, it's better to do several power iterations (with a real starting vector), orthonormalize the last two iterates, compute the eigenvalues of the projected $2\times 2$ matrix, and repeat if necessary:for k = 1:kmax x = w/norm(w); w = A*x;endw = w-(x'*w)*x;w = w/norm(w);Q = [x,w];l = max(eig(Q'*A*Q));(Depending on the available routines for dense linear algebra, that might even be faster for the original question as well due to the better convergence of Krylov methods. In fact, if you have access to ARPACK or something equivalent, eigs(A,1) (or its equivalent) will be pretty hard to beat, especially if you need high accuracy.)
_unix.354087
I can't use Ctrl+Start in mate-terminal. It is interpreted a Start. Same with End.Therefore, when using vi in non-GUI mode, I can't move to start/end of file using those key combinations.showkey confirms the issue. When typing both with and without Ctrl in mate-terminal, I get the same output, while I get different outputs in xterm:xtermshowkey -aPress any keys - Ctrl-D will terminate this program^[[H 27 0033 0x1b 91 0133 0x5b 72 0110 0x48^[[1;2H 27 0033 0x1b 91 0133 0x5b 49 0061 0x31 59 0073 0x3b 50 0062 0x32 72 0110 0x48mate-terminalshowkey -aPress any keys - Ctrl-D will terminate this program^[OH 27 0033 0x1b 79 0117 0x4f 72 0110 0x48^[OH 27 0033 0x1b 79 0117 0x4f 72 0110 0x48Seems related to this very old issue: https://bugs.launchpad.net/ubuntu/+source/vte/+bug/342436, in which gnome-terminal is said to be affected as well.Is there a fix or at least a workaround for this?
Ctrl+Start/End not working in mate-terminal
gnome terminal;mate terminal
null
_cs.43849
I am solving a large (~1e5 equations & unknowns) set of nonlinear equations using Newton-Raphson iterations. Currently I am using the GPU accelerated Krylov methods implemented in ViennaCL to solve the linear system to get the update increment. I am solving the system on a single 24 core, 64GB workstation with a NVIDIA Quadro K4000 GPU. However as the number of unknowns exceeds 1e5 and/or the Jacobian matrix gets more dense, there is not enough memory on the GPU to fit the compressed Jacobian matrix on the device. Using the CPU cores allows the Jacobian matrix to fit into memory, however the compute time is very long.I would like to use a cluster of the above mentioned workstations to solve either the nonlinear system or the linear update increment system, however I am not sure how to go about decomposing the system of equations into pieces that can be tackled via a distributed memory approach. The equations include radiative transfer, and therefore it is not easy to decompose the domain geometrically as the Jacobian matrix is dense. Does anyone know about distributed memory approaches to solving large dense linear equation systems? All help is greatly appreciated!PS I have looked into the parallelised nonlinear solvers implemented in PETSc, however this is a clunky c library and one must write there entire problem in terms of the PETSc interface which I would like to avoid if possible. I would be more interested in understanding the details as to how a distributed memory parallelised nonlinear or linear solver works...
solving large nonlinear systems in parallel
distributed systems;parallel computing;linear algebra
The main point of Krylov-Newton is that it does not require computing and storing the whole Jacobian matrix. It only requires the ability to apply the matrix to a vector. The stardard approach is to do a little bit of pencil and paper work to figure out how to express the action of the derivative without actually computing and storing the whole matrix. If this is not possible, one can try to figure out a compressed representation of the matrix.For problems where the matrices are dense, but the long range interactions are low rank (I think many radiative transfer problems would fall in this category..?), fast multipole or H-matrix type methods tend to be very effective.It's difficult to give further advice without knowing more specifics of the problem.
_webmaster.14126
I want to make search engines display only the title of my web page on their search results.And I don't want to show any descriptions and any texts of my page on the search results.For example, this site is displayed like:Stack OverflowA language-independent collaboratively edited question and answer site for programmers.stackoverflow.com/ - Cached - SimilarIn this case, I don't want to make search engines display the text A language-independent collaboratively edited question and answer site for programmers..And I want to make them display like:Stack Overflowstackoverflow.com/ - Cached - Similar
How to make search engines display only the title of a web page on their search results?
search engines
<meta name=robots content=nosnippet /> tells search engines to not include a snippet in search results.
_webmaster.67975
I am using the event tracking in GA (JS code) to track 2 buttons on my site.I can see the clicks coming through in real time, but when I click on behavior > Events, I do not see anything (no events at all).I have tried to filter and it doesn't work.What is the common cause for this problem?
GA Event Tracking Not Saving Events
google analytics
null
_unix.29128
Linux's /proc/<pid>/environ does not update (as I understand it, the file contain the initial environment of the process).How can I read a process's current environment?
How to read environment variables of a process
linux;process;environment variables
/proc/$pid/environ does update if the process changes its own environment. But many programs don't bother changing their own environment, because it's a bit pointless: a program's environment is not visible through normal channels, only through /proc and ps, and even not every unix variant has this kind of feature, so applications don't rely on it.As far as the kernel is concerned, the environment only appears as the argument of the execve system call that starts the program. Linux exposes an area in memory through /proc, and some programs update this area while others don't. In particular, I don't think any shell updates this area. As the area has a fixed size, it would be impossible to add new variables or change the length of a value.
_webapps.103631
When searching Google for a term like weather or temperature it helpfully provides a widget with your location's weather information. In the wind tab, I always assumed that the size of the arrows was proportional to the wind speed, until today. The arrows for 15 and 16 are drastically different, despite being 1mph difference, while the arrows for 9 and 15 are extremely close to being the same size, despite the 6mph difference.I've tried searching for an explanation, but couldn't find anything. What exactly does the arrow size mean?
What does the size of wind arrows signify?
google search;weather
null
_cs.42779
I assume no, because a Turing machine that can only move right feels like it is not a Turing machine. But, I wonder if I can add a Reset to the right moving Turing machine that resets the what head is pointing at all the way to the left of the TM. However, doesn't this make it left moving??hmm...
Is a single tape Turing machine equal in power to a Turing machine that can only move right?
complexity theory
The usual answer would be that they are indeed much less powerful, somewhat like a finite state automaton, if I am not mistaken.But there is a catch. Imagine a TM with two heads, one which is reading, another which is writing. Both only move right! If the reading head is always left of the writing head, the part of the tape in between can act as a queue, which makes the machine Turing complete.
_codereview.110771
Already read this, but OP is using some other method.My website finds the time till new year. But this website claims to be accurate to the tenth of a second. So what I found out was my timer and their timer is off by about a minute. var daysSpan = document.getElementById(days);var hoursSpan = document.getElementById(hours);var minutesSpan = document.getElementById(minutes);var secondsSpan = document.getElementById(seconds);var c=1;function updateClock(){ var t = Date.parse('January 1 2016 00:01:05') - Date.parse(new Date()); if (t<=0 && c==1) { c--; window.open(http://www.its2016.weebly.com,_self); } var seconds = Math.floor( (t/1000) % 60 ); var minutes = Math.floor( (t/1000/60) % 60 ); var hours = Math.floor( (t/(1000*60*60)) % 24 ); var days = Math.floor( t/(1000*60*60*24) ); daysSpan.innerHTML = days; hoursSpan.innerHTML = hours; minutesSpan.innerHTML = minutes; secondsSpan.innerHTML = seconds;}setInterval(updateClock,1000);My area of suspicion is this, I have a feeling that all the divisions and multiplications are making it very inaccurate. var seconds = Math.floor( (t/1000) % 60 ); var minutes = Math.floor( (t/1000/60) % 60 ); var hours = Math.floor( (t/(1000*60*60)) % 24 ); var days = Math.floor( t/(1000*60*60*24) );So how can I make my calculations more accurate?
Countdown to January 1 2016
javascript;html;mathematics
null
_scicomp.27312
Suppose we have the negative, inhomogeneous advection equation:$$\left(\frac{\partial}{\partial x}-\frac{1}{c}\frac{\partial}{\partial t}\right)v(t,x)=u(t,x)\qquad(t\in\mathbb{R}_{+},x\in\mathbb{R})$$I want to solve it numerically, backward in time and forward in space.Now, I have tried a few schemes without avail. For example, the Crank-Nicolson scheme going backwards in time:In particular, we may discretise as$$\frac{1}{c}\frac{\mathrm{d}}{\mathrm{d}t}v_\ell(t)=\underbrace{\frac{v_{\ell+1}(t)-v_\ell(t)}{\Delta x}-u_\ell(t)}_{G_\ell(t)}+\mathcal{O}(\Delta x)\qquad\Delta x\to 0$$where we have taken the forward difference of the spatial derivative.Then applying the Crank-Nicolson scheme yields$$\frac{1}{c}\frac{v^{n+1}_\ell-v^n_\ell}{\Delta t}=\frac{1}{2}[G_\ell(t^{n+1})+G_\ell(t^n)]=\frac{1}{2}\left[\frac{v^{n+1}_{\ell+1}-v^{n+1}_\ell+v^n_{\ell+1}-v^n_\ell}{\Delta x}-u^{n+1}_\ell-u^n_\ell\right]$$Hence$$v^{n+1}_\ell-\frac{c\Delta t}{2\Delta x}(v^{n+1}_{\ell+1}-v^{n+1}_\ell)=v^n_\ell+\frac{c\Delta t}{2}\left[\frac{v^n_{\ell+1}-v^n_\ell}{\Delta x}-u^{n+1}_\ell+u^n_\ell\right]$$i.e.$$\left(\mathrm{I}-\frac{c\Delta t}{2\Delta x}\mathrm{A}\right)v^{n+1}_\ell=\left(\mathrm{I}+\frac{c\Delta t}{2\Delta x}\mathrm{A}\right)v^n_\ell-\frac{c\Delta t}{2\Delta x}(u^{n+1}_\ell+u^n_\ell)$$where$$\mathrm{A}=\begin{pmatrix}-1 & 1 & & 0\\&\ddots & \ddots\\& & -1 & 1\\0 & & & -1\end{pmatrix}$$Now, since we want to go backwards in time, we replace $\Delta t$ with $-\Delta t$ and we get$$v^{n-1}_\ell=\left(\mathrm{I}+\frac{c\Delta t}{2\Delta x}\mathrm{A}\right)^{-1}\left[\left(\mathrm{I}-\frac{c\Delta t}{2\Delta x}\mathrm{A}\right)v^n_\ell+\frac{c\Delta t}{2\Delta x}(u^{n-1}_\ell+u^n_\ell)\right]$$Now, I try to implement this on Matlab via%% ParametersL = 5; % size of domain T = 5; % measurement timedx = 1e-2; % spatial stepdt = 1e-3; % time stepx0 = 0; % point of measurementc = 1; % speed of advection%%t = 0:dt:T; % time vectorx = [0:dx:L]'; % position vectornt = length(t); % number of time stepsnx = length(x); % number of position stepsmu = dt/dx;I = eye(nx,nx+1); % identity matrixA = spdiags(ones(nx,1)*[-1 1],0:1,nx,nx);%% Solve Backward Advection Equation% preallocate the memoryv = zeros(nx,nt);u = zeros(nx,nt);% final condition, sinc function centered around x = .5v(:,nt) = sinc((x-x0)/dx);for k = nt-1:1 v(:,k-1) = (I+(c/2)*mu*A)\((I-(c/2)*mu*A)*v(:,k)+(c/2)*mu*(u(:,k-1)+u(:,k)));endMy solution simply blows up on the boundary of the domain and is zero everywhere else. I have similar results using backwards Euler instead of Crank-Nicolson. Where am I going wrong?I provide two plots:
Why can I not solve the negative advection equation (backwards in time)?
matlab;pde;hyperbolic pde;advection;crank nicolson
null
_cogsci.16815
What qualitative studies, e.g. open ended interviews, are there into mindfulness therapy?I've been skeptical about its use, wondered if it was kinda faddy. But it occurs to me that a lot of despair type emotions may have their root in being unable to relax and enjoy life. Surely meditation is linked with that?
What qualitative studies are there into mindfulness?
emotion;therapy
Wikipedia often provides references to scientific studies and the Wikipedia article on Mindfulness is no exception.The main section of the article has...Studies have also shown that rumination and worry contribute to mental illnesses such as depression and anxiety,[13][14] and that mindfulness-based interventions are effective in the reduction of both rumination and worry.[13][15]Mindfulness practice is being employed in psychology to alleviate a variety of mental and physical conditions, such as bringing about reductions in depression symptoms,[16][17][18] reducing stress,[17][19][20] anxiety,[16][17][20] and in the treatment of drug addiction.[21][22][23] Recent studies demonstrate that mindfulness meditation significantly attenuates pain through multiple, unique mechanisms.[24] It has gained worldwide popularity as a distinctive method to handle emotions.Clinical studies have documented both physical and mental health benefits of mindfulness in different patient categories as well as in healthy adults and children.[3][25][26]plusResearch on the neural perspective of how mindfulness meditation works suggests that it exerts its effects in components of attention regulation, body awareness and emotional regulation.[34] When considering aspects such as sense of responsibility, authenticity, compassion, self-acceptance and character, studies have shown that mindfulness meditation contributes to a more coherent and healthy sense of self and identity.[35][36] Neuroimaging techniques suggest that mindfulness practices such as mindfulness meditation are associated with changes in the anterior cingulate cortex, insula, temporo-parietal junction, fronto-limbic network and default mode network structures.[37][38] Further, mindfulness-induced emotional and behavioral changes have been found to be related to functional and structural changes in the brain.[38]There is also a scientific research sectionMindfulness has gained increasing empirical attention ever since 1970.[120][unreliable source?] According to a 2015 systematic review and meta-analysis of systematic reviews of RCTs, evidence supports the use of mindfulness programs to alleviate symptoms of a variety of mental and physical disorders.[25] Other reviews report similar findings.[19][22][33] Further, mindfulness meditation appears to bring about favorable structural changes in the brain,[32][37][121] and may also prevent or delay the onset of mild cognitive impairment and Alzheimer's disease.[122] Mindfulness proved to be effective also in enhancing peoples capacity to self-regulate.[123]ReferencesThese are provided in the full articleThis question is close to being put on hold or closed and to indicate why, it would produce a posting which is much longer than the standard laid out in the help center,if your question could be answered by an entire book, or has many valid answers, it's probably too broad for our formatplus, there are so many referenced studies and articles of scientific research connected to this (I counted 25 in total - 156 in the full article) that providing a full list of references here would take me an age to provide in full (with weblinks etc.) on this site.
_softwareengineering.339127
I have released many open source software under Apache 2.0, now I'm providing a SaaS using that software.Basically, I need to prevent people just taking my software and just rebrand it to provide it in SaaS, being in direct compatition with my own SaaS.AFAIK Apache 2.0 make that possible, even the rebranding (changing my software name, logos, powered by xxx messages, etc. even rebranding the documentation), without making any contribution to the open source project.My question is how to prevent that? Does the Apache 2.0 consider this situation? Can my software be better covered by a different license?
How to prevent unfair use of open source software licensed under Apache 2.0
licensing;apache license;foss
You could add a license term similar to the term from the Affero GPL v3 mentioned here: if you run the program on a server and let other users communicate with it there, your server must also allow them to download the source code corresponding to the program that it's runningYou could also consider to put your programs fully under Affero GPL v3, or offer dual licensing.If a competitor will follow your license terms is a completely different question, especially when he is located in a country with a different jurisdiction than yours. If you want to prevent yourself against such folks, you need to keep your source code in private.
_unix.158555
I created a partition called /dev/sda3 as a swap partition, and changed the ID to 82 (Linux Swap) via fdisk. If this partition was recognized as a swap partition (seen in the output of fdisk -l and blkid), then why couldn't I proceed straight to swapon /dev/sda3? Why did I have to execute mkswap /dev/sda3?Another question, is partition information exclusive from data? So if I changed a filesystem type via fdisk would data be affected?fdisk -lDisk /dev/sda: 21.5 GB, 21474836480 bytes255 heads, 63 sectors/track, 2610 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytesSector size (logical/physical): 512 bytes / 512 bytesI/O size (minimum/optimal): 512 bytes / 512 bytesDisk identifier: 0x0008d6ed Device Boot Start End Blocks Id System/dev/sda1 * 1 32 256000 83 LinuxPartition 1 does not end on cylinder boundary./dev/sda2 32 1566 12317696 83 Linux/dev/sda3 1566 2610 8390105 82 Linux swap / Solarisblkid/dev/sda3: LABEL=SWAP UUID=63f1807e-7cc6-4339-92b2-b1958fcf285e TYPE=swap
Why do I need mkswap if swap space has been created via fdisk?
swap;fdisk
fdisk creates a partition but doesn't format it. Before you can use your swap partition, you need to format it first. This is done with mkswap.The same rules apply for any other file systems. You need to create the partition and format it before using it.
_scicomp.6860
I have a 53534x3 matrix with x, y and z coordinates.I want to find the element of matrix within ranges as follows:% coordinate range;x1(x<-25|x>0);x2(x<0|x>25);y1(y<-40|y>0);y2(y<0|y>40);z1(z<45|z>0);z2(z<0|z>82);and insert them into a new matrix, so that it becomepoint1=[x1, y1, z1];point2=[x2, y2, z2];I need to find the distance between the two points.% define points;xd=x2-x1;yd=y2-y1;zd=z2-z1;Distance=sqrt(xd*xd+yd*yd+zd*zd);Is loop preferrably efficient?
Matlab element within ranges and distance between two points
matlab;matrix;elements
I'm suspecting a typo in at least some of the conditionals. For instance, z<45|z>0 is trivially true. But I'm going to pretend its not and write the code out anyway, so that if you correct it (perhaps z<-45|z>0) you'll still have the right structure.x = A(:,1); y = A(:,2); z = A(:,3); i1 = find((x<-25|x>0)&(y<-40|y>0)&(z<45|z>0),1,'first'); i2 = find((x<0|x>25)&(y<0|y>40)&(z<0|z>82),1,'first'); point1 = A(i1,:); point2 = A(i2,:); Distance = norm(point1-point2);Like Dr. Sam showed, using tight for loops in MATLAB is truly disastrous for performance. Obviously, as Wolfgang pointed out, MATLAB is using optimized for loops internally to iterate through the elements of the vectors, but that's compiled code. If you were doing this with compiled C, you'd use for loops too, and avoid a lot of the temporary generation that MATLAB is doing here.
_unix.358606
I am having a recurring problem when using perf with Intel-PT event. I am currently performing profiling on a Intel(R) Xeon(R) CPU E5-2620 v4 @ 2.10GHz machine, with x86_64 architecture and 32 hardware threads with virtualization enabled. I specifically use programs/source codes from SpecCPU2006 for profiling.I am specifically observing that the first time I perform profiling on one of the compiled binaries from SpecCPU2006, everything works fine and the perf.data file gets generated, which is as expected with Intel-PT. As SpecCPU2006 programs are computationally-intensive(use 100% of CPU at any time), clearly perf.data files would be large for most of the programs. I obtain roughly 7-10 GB perf.data files for most of the profiled programs. However, when I try to perform profiling the second time on the same compiled binary, after the first one is successfully done -- my server machine freezes up. Sometimes, this happens when I try profiling the third time/the fourth time (after the second or third profiling completed successfully). This behavior is highly unpredictable. Now I cannot profile any more binaries unless I have restarted the machine again.I have also posted the server error logs which I get once I see that the computer has stopped responding.Clearly there is an error message saying Fixing recursive fault but reboot is needed!. This happens for particularly large enough SpecCPU2006 binaries which take more than 1 minute to run without perf. Is there any particular reason why this might happen ? This should not occur due to high CPU usage, as running the programs without perf or with perf but any other hardware event(that can be seen by perf-list) completed successfully. This only seems to happen with Intel-PT.Please guide me in using the steps to solve this problem. Thanks.
Running perf record with Intel-PT event on compiled binaries from SPECCpu2006 crashes the server machine
cpu;intel;perf
null
_webmaster.8586
In Google Analytics, I've been following several tutorials to export a list of keywords, but something is going wrong. This is what I try:1.) click traffic sources2.) click keywords3.) Click Export4.) Click CSVThe resulting file shows two columns. Column A is dates. Column B is visits. I am trying to export a file so that Column A is keywords and Column B is visits.
How can I export a keyword list from Google Analytics?
google;google analytics;analytics;keywords
Scroll down a little. The keywords are below the dates.
_softwareengineering.130679
We all have definitely used typedefs and #defines one time or the other. Today while working with them, I started pondering on a thing.Consider the below 2 situations to use int data type with another name:typedef int MYINTEGERand#define MYINTEGER intLike above situation, we can, in many situations, very well accomplish a thing using #define, and also do the same using typedef, although the ways in which we do the same may be quite different. #define can also perform MACRO actions which a typedef cannot.Although the basic reason for using them is the different, how different is their working? When should one be preferred over the other when both can be used? Also, is one guaranteed to be faster than the other in which situations? (e.g. #define is preprocessor directive, so everything is done way earlier than at compiling or runtime).
typedefs and #defines
c++;c;programming practices
A typedef is generally preferred unless there's some odd reason that you specifically need a macro.macros do textual substitution, which can do considerable violence to the semantics of the code. For example, given:#define MYINTEGER intyou could legally write:short MYINTEGER x = 42;because short MYINTEGER expands to short int.On the other hand, with a typedef:typedef int MYINTEGER:the name MYINTEGER is another name for the type int, not a textual substitution for the keyword int.Things get even worse with more complicated types. For example, given this:typedef char *char_ptr;char_ptr a, b;#define CHAR_PTR char*CHAR_PTR c, d;a, b, and c are all pointers, but d is a char, because the last line expands to:char* c, d;which is equivalent tochar *c;char d;(Typedefs for pointer types are usually not a good idea, but this illustrates the point.)Another odd case:#define DWORD longDWORD double x; /* Huh? */
_unix.193541
I try to join Active Directory and Samba 4 in Ubuntu 12.04.05.When I run host -t SRV _kerberos._udp.test.sg I get the error: Host _kerberos._udp.test.sg not found: 3(NXDOMAIN)meanwhile$# host -t SRV _ldap._tcp.test.sg _ldap._tcp.test.sg has SRV record 0 0 389 4ecapsvsg6.test.sg.$# host -t A 4ECAPSVSG6.test.sg4ECAPSVSG6.test.sg has address 10.153.64.5My /etc/samba/smb.conf:# Global parameters[global] workgroup = TEST realm = TEST.SG netbios name = 4ECAPSVSG6 server role = active directory domain controller dns forwarder = 10.153.64.5 security = ads use kerberos keytab = true password server = 4ecapsvsg6.test.sg allow dns updates = nonsecure and secure bind interfaces only = no server services = +smb -s3fs dcerpc endpoint servers = +winreg +srvsvc passdb backend = samba4 server services = smb, rpc, nbt, wrepl, ldap, cldap, kdc, drepl, winbind, ntp_signd, kcc, dnsupdate, dns My /etc/krb5.conf:[libdefaults] default_realm = TEST.SG krb4_config = /etc/krb.conf krb4_realms = /etc/krb.realms kdc_timesync = 1 ccache_type = 4 forwardable = true proxiable = true[realms] 4ECAP.SG = { kdc = 4ecapsvsg6.test.sg:88 admin_server = 4ecapsvsg6.test.sg:749 default_domain = test.sg }[domain_realm] .test.sg = TEST.SG test.sg = TEST.SG[login] krb4_convert = true krb4_get_tickets = falseMy /etc/hosts: 127.0.0.1 localhost 127.0.1.1 4ecapsvsg6 # The following lines are desirable for IPv6 capable hosts ::1 ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters 10.153.64.5 4ecapsvsg6.test.sg 4ecapsvsg6What is the solution? Without it I cannot run join domain with command:sudo net ads joinwhich comes out error likeFailed to join domain: failed to lookup DC info for domain 'TEST' over rpc: Logon failureI did kinit administrator and klist, result: Ticket cache: FILE:/tmp/krb5cc_0 Default principal: [email protected] Valid starting Expires Service principal 26/03/2015 14:29:04 27/03/2015 00:29:04 krbtgt/[email protected] renew until 27/03/2015 14:29:00
Kerberos Join Active Directory Failure
active directory;kerberos;samba4
After i google this past week, lucky i found this site http://edoceo.com/howto/samba4Happens to be i need to edit my dnsmasq (/etc/dnsmasq.conf) add this line :srv-host=_kerberos._tcp.test.sg,4ecapsvsg6.test.sg,88 srv-host=_kerberos._tcp.dc._msdcs.test.sg,4ecapsvsg6.test.sg,88 srv-host=_kerberos._udp.test.sg,4ecapsvsg6.test.sg,88srv-host=_kpasswd._tcp.test.sg,4ecapsvsg6.test.sg,464 srv-host=_kpasswd._udp.test.sg,4ecapsvsg6.test.sg,464and disable Bind9 (which installed along with Samba4 by default)Now the problems gone :)Only one problems remains, how to connect to AD (which i'll open another thread for that)
_codereview.87263
public static <T> void heapSort( T[] array, Comparator<? super T> comparator) { int length = array.length; int start = (length - 1) /2; //right-most parent node //build heap while (start > -1) maxHeapify(array, start--, length, comparator); //move max to end, and rebalance. while (length > 1) { swap(array, 0, length - 1); length--; maxHeapify(array, 0, length, comparator); }}private static <T> void maxHeapify( T[] array, int node, int length, Comparator<? super T> comparator) { int left = 2*node + 1; if (left >= length) return; int right = left + 1; int newNode = node; if (comparator.compare(array[left], array[node]) > 0) newNode = left; if (right < length && comparator.compare(array[right], array[newNode]) > 0) newNode = right; if (newNode != node) { swap(array, node, newNode); maxHeapify(array, newNode, length, comparator); }}I wrote a merge sort that seems to be using about half as many comparisons. Am I doing something wrong here?
Can this heap sort be further optimized to have fewer comparisons?
java;performance;algorithm;sorting
null
_softwareengineering.346823
Recently, I was given a task of re-writing a really old piece of software. The whole software itself is well written, except for the one thing that worries me, classes containing a huge amount of code. A lot of that is nothing but really really big validation chains that go like:if (!isFooValid(dataObject.getFoo())) throw new FooException(...);if (!isBarValid(dataObject.getBar())) throw new BarException(...);And that inspired me to write an API that can help in decoupling the validation chains.As far as my understanding goes, validation is generally a Composite Pattern, and if we break it down and separate the what we want to from the how we want to do it, we get:If foo is valid then do something.And we got an abstraction: is valid.So I went up on decoupling how do we get the abstraction is valid, I came up with a design idea.I can have a Result object, that contains the message about validation with a simple true/false to check whether it was successful or not.public interface Result { // StandardResult is the default implementation of Result. // Using the default constructor gives an instance that indicates // SUCCESS state of validation. public static final Result OK = new StandardResult(); public Throwable getError(); public boolean isOk(); public String getMessage(); }I can have a Validator<T> object, that has the validation logic, and then returns a Result object that contains information about what happened.public interface Validator<T> { public Result validate(T target); }This enables me to do stuff like:Result r = new SomeStringValidator().validate(This String);And similarly, I can do the validation chains using a Chain of Responsibility pattern.public class ChainValidator<T> implements Validator<T> { // This list contains all the validators that are in the chain. private final List<Validator<T>> validators = new ArrayList<Validator<T>>(); public CompositeResult<T> validate(T target) { CompositeResult<T> result = new CompositeResult<T>(); for (Validator<T> v : validators) { Result validationResult = null; try { validationResult = v.validate(target); } catch (Exception ex) { // Creating it with StandardResult(Throwable) would give // an instance that indicates FAILED state. validationResult = new StandardResult(ex); } result.put(v, validationResult); } return result; } private final class CompositeResult<T> implements Result { private final Map<Validator<T>, Result> delegate = new HashMap<Validator<T>, Result>(); private Throwable failCause; public boolean isOk() { for (Result r : delegate.values()) { if (!r.isOk()) { failCause = r.getError(); return false; } } return true; } public String getMessage() { return delegate.toString(); } public void put(Validator<T> validator, Result resut) { delegate.put(validator, resut); } public Throwable getError() { return failCause; } }}This works but it leaves me with a few questions:The very first guideline to API designing says Do not Return Null to Indicate the Absence of a Value, but here I am returning a null object in Result#getError() method.Does the use of generics on my example sound like code smell?This one is going to be opinion basedIs it worthy of making it into an API instead of just 4 classes?Source code could be found here.
Developing an API to delegate/decouple long Validation Chains
java;api design
null
_reverseengineering.1971
I have binary data representing a table.Here's the data when I print it with Python's repr():\xff\xff\x05\x04test\x02A\x05test1@\x04\x03@@\x04\x05@0\x00\x00@\x05\x05test2\x03\x05\x05test1\x06@0\x00\x01@\x00Here's what the table looks like in the proprietary software.        test1                test1test1test          test1test1                test1test2                                                        test1                test1                test1                        test1                test1                                                        test1                test1                I was able to guess some of it:It's column by column then cell by cell, starting at the top left cell.The \x04 in \x04test seems to be the length (in bytes I guess) of the following word.@ mean the last valueAnyone knows if the data is following a standard or have any tips how to decode it?Thanks!Here's an example with python :from struct import unpackdef DecodeData(position): print position, position firstChar = data[position:][:1] size_in_bytes = unpack('B', firstChar)[0] print firstChar: {0}. size_in_bytes: {1}.format(repr(firstChar), size_in_bytes) return size_in_bytesdef ReadWord(position, size_in_bytes): word = unpack('%ds' % size_in_bytes, data[position:][:size_in_bytes])[0] print word:, worddata = \xff\xff\x05\x04test\x02A\x05test1@\x04\x03@@\x04\x05@0\x00\x00@\x05\x05test2\x03\x05\x05test1\x06@0\x00\x01@\x00position = 0print position += 1DecodeData(position)print \\xff - ?print position += 1DecodeData(position)print \\x05 - ?print position += 1size_in_bytes = DecodeData(position)position += 1ReadWord(position, size_in_bytes)print position += size_in_bytesDecodeData(position)position += 1DecodeData(position)print '2A' : could be to say that test has 2 empty cells before itprint position += 1size_in_bytes = DecodeData(position)position += 1word = unpack('%ds' % size_in_bytes, data[position:][:size_in_bytes])[0]print word:, wordposition += size_in_bytesDecodeData(position)print @: mean that there's another test1 cellprint position += 1DecodeData(position)position += 1DecodeData(position)print \\x04\\x03 - Could be that the next value is 3 cells downprint position += 1DecodeData(position)print position += 1print @@ - Seems to mean 3 repetitionsprint position += 1DecodeData(position)position += 1DecodeData(position)print \\x04\\x05 - Could be that the next value is 5 cells downprint position += 1DecodeData(position)print @ - repetitionprint position += 1DecodeData(position)print position += 1DecodeData(position)position += 1DecodeData(position)print \\x00\\x00 - That could mean to move to the first cell on the next columnprint position += 1DecodeData(position)print @ - repetitionprint position += 1DecodeData(position)print \\x05 - ?print position += 1size_in_bytes = DecodeData(position)position += 1word = unpack('%ds' % size_in_bytes, data[position:][:size_in_bytes])[0]print word:, wordposition += size_in_bytesprint DecodeData(position)print \\x03 - Could be to tell that the pervious word 'test2' is 3 cells downprint position += 1DecodeData(position)print \\x05 - ?print position += 1size_in_bytes = DecodeData(position)position += 1word = unpack('%ds' % size_in_bytes, data[position:][:size_in_bytes])[0]print word:, wordposition += size_in_bytesprint DecodeData(position)print \\x06 - Could be to tell that the pervious word 'test1' is 6 cells downprint position += 1DecodeData(position)print @ - repetitionprint position += 1DecodeData(position)print \\0 - ?print position += 1DecodeData(position)position += 1DecodeData(position)print \\x00\\x01 - Seems to mean, next column second cellprint position += 1DecodeData(position)print @ - repetitionprint position += 1DecodeData(position)print \\x00 - end of data or column
Any idea how to decode this binary data?
unpacking;file format
Here's an explanation for what I think the individual symbols mean. I'm basing this around the presumption that a little selector is going through the cells, one by one.\xFF = Null cell\x05 = A string is following, with \xNumber coming after the string to define how far to displace the string from the selector's current position, if at all. \xNumber string = A string of length number\x2A = Could be a byte that says not to displace the current string, and also to assume that the next piece of data is defining a string to be placed in the next cell. Questionable meaning.\x04 \xNumber = Move selector ahead \xNumber cells and place previous string into there.0 \x00 \x0Number = New column, move selector into row \xNumber, and place previous string into there.@ = Place previously used string in the cell following the current one.So here's my interpretation of the data you're giving us:\xFF\xFF = two null cells\x05 = A cell, singular, with a string, placed following the null cells, because of the \x2A following the string \x04 test = The string.\x2A \x05 test1 = Another string placed into the cell following. No number needed, since \x2A implies that it's being placed right after test@ = Place test1 into the cell after the test1 string was first placed.\x04 \x03 = Move selector ahead three cells and place test1 where it lands.@@ = Place into the two cells following also.\x04 \x05 @ = Skip four cells, place into two cells.0 = New column.\x00 \x00 @ = Using string last defined (test1), place into first two cells of the column. \x05 \x05 test2 \x03 = Place a cell three cells afterwords.\x05\x05test1\x06 = Place test1 into a cell 6 after test2@ = Place test1 again, too.0 = move to next column\x00\x01 = Place previous string at location 01 @ = And also at location 02\x00 = DoneExplanation: My method was to look for a pattern, check if the pattern withstood further scrutiny - the first pattern I checked seemed to - and clear up any minor issues I had with it. Seems to have worked.
_webmaster.37631
Let's say I have two sites that cover the same vertical/topic. one in the USA and one in Canada. Both sites have local-related content, which is obviously unique by location. However they will share common news or blog pages.How do I avoid getting hit with duplicate content on both sites for those news/blog pages?If the content is exactly the same, I'm guessing I would have to pick which site's content I want to noindex,nofollow, is that correct, and if so, is that all I have to add on the URL links to those pages, and the pages' meta tags?
How to handle possible duplicate content across multiple sites?
seo;duplicate content;local seo
You can use the canonical tag to tell the search engines that it is the same content, but on a different URLAlso consider using the source tag
_webmaster.13896
The documentation states that Any supported language code. is supported, but then says:Which language is used in the interface for the pre-defined themes. The following languages are supported: - English en - Dutch nl - French fr - German de - Portuguese pt - Russian ru - Spanish es - Turkish trIf the language of your site isn't supported, you can always use custom theming to put reCAPTCHA in your language.If the first statement is meant to mean:Any language. It isn't true because Japan (ja/jp/jpn) isn't supported as far as I can see. (Plus then, the last statement disproves the first one.) Languages in the list (above), then what about Italian? it is supported but not in the list.So which languages are actually supported?
Which languages are supported by reCAPTCHA?
google;language;captcha
Pre-defined:Completely supported:EnglishPartially supported:DutchFrenchGermanPortugueseRussianSpanishTurkish play sound again, download sound as MP3, and entire manual (JavaScript-independent) challenge in English.Barely supported:Italianplay sound again, download sound as MP3, entire manual (JavaScript-independent) challenge, plus audio challenge &=and help popup in English.Custom Translations:Custom translations can be written for any language, but the audio challenge, help popup, and manual (JavaScript-independent) challenge will always be in English.The custom translations are defined using Javascript that's why they won't work when the manual challenge is being used. Note: The manual challenge is displayed in an iframe (can't edit it) and includes the following text (always in English):We need to make sure you are a human. Please solve the challenge below, and click the I'm a Human button to get a confirmation code. To make this process easier in the future, we recommend you enable JavascriptNote: Latin/Roman alphabet is the only supported alphabet.
_codereview.152759
I am trying to write fast/optimal code to vectorize the product of an array of complex numbers. In simple C this would be:#include <complex.h>complex float f(complex float x[], int n ) { complex float p = 1.0; for (int i = 0; i < n; i++) p *= x[i]; return p;}However, gcc can't vectorize this and my target CPU is the AMD FX-8350 which supports AVX. To speed it up I have tried:typedef float v4sf __attribute__ ((vector_size (16)));typedef union { v4sf v; float e[4];} float4;typedef struct { float4 x; float4 y;} complex4;static complex4 complex4_mul(complex4 a, complex4 b) { return (complex4){a.x.v*b.x.v -a.y.v*b.y.v, a.y.v*b.x.v + a.x.v*b.y.v};}complex4 f4(complex4 x[], int n) { v4sf one = {1,1,1,1}; complex4 p = {one,one}; for (int i = 0; i < n; i++) p = complex4_mul(p, x[i]); return p;}Can this code be improved for AVX and is it as fast as it can get?
Vectorizing the product of an array of complex numbers
performance;c;vectorization;gcc
null
_unix.338815
I recently clean installed Mint 18 KDE on a MacBook Air, and the Update Manager in the system tray has no default behavior. I would like it to open the Update Manager, but instead I have to right click it and choose Update Manager. I've been trying to find the configuration for that item in the system tray so that I can enable a default behavior, but either I haven't found the correct config file, or I was unable to determine the correct setting. Can anyone point me to the correct file and the correct setting?Thanks in advance,syserss
Linux Mint 18 Sarah KDE Update Manager
linux mint;kde
null
_unix.75231
I am installing Oracle grid 11gR2 using silent install with response file. I am getting error after Collecting interface information for node 1 in logs.I have a feeling that this could be due to option oracle.crs.config.privateinterconnects=eth0:xxx.xxx.xxx.xxx:1,eth1:xxx.xxx.xxx.xxx:2Here I have specified only for 1 node. Do I need to specify interconnects for both nodes.ERROR message: One or more nodes have interfaces not configured with a subnet that is common across all nodes.
Oracle 11gR2 grid silent installation: error for privateinterconnects
software installation;cluster;oracle database;private network
null
_softwareengineering.68101
Do you spend your working hours learning new stuff, reading tech blogs, books on programming etc.? What's your opinion on it? Can an employer have benefits allowing developers to spend about 1-1.5 hrs a day on learning. Will it be repaid in future (with better productivity etc.)?
Do you spend your working hours on learning?
learning;self improvement
I am of the mindset that it is essential for a good development environment to allow for an hour or two at most for exploration and learning, barring when it's crunch time on an application of course. An environment which doesn't do this is a red flag in my book because it tells me they don't value improvement.EDITWorst of all is the place that reprimands it's developers for reading blogs/technical sites instead of writing code. That, to me, indicates an environment that doesn't care about it's developers beyond what they can squeeze out of them.
_codereview.97820
Here's the challenge:Once upon a time in a strange situation, people called a number ugly if it was divisible by any of the one-digit primes (\$2\$, \$3\$, \$5\$ or \$7\$). Thus, \$14\$ is ugly, but \$13\$ is fine. \$39\$ is ugly, but \$121\$ is not. Note that \$0\$ is ugly. Also note that negative numbers can also be ugly: \$-14\$ and \$-39\$ are examples of such numbers.One day on your free time, you are gazing at a string of digits, something like:123456You are amused by how many possibilities there are if you are allowed to insert plus or minus signs between the digits. For example you can make:1 + 234 - 5 + 6 = 236which is ugly. Or:123 + 4 - 56 = 71which is not ugly. It is easy to count the number of different ways you can play with the digits: Between each two adjacent digits you may choose put a plus sign, a minus sign, or nothing. Therefore, if you start with N digits there are \$3^{N-1}\$ expressions you can make. Note that it is fine to have leading zeros for a number. If the string is '01023', then '01023', '0+1-02+3' and '01-023' are legal expressions. Your task is simple: Among the \$3^{N-1}\$ expressions, count how many of them evaluate to an ugly number.Input Sample:Your program should accept as its first argument a path to a filename. Each line in this file is one test case. Each test case will be a single line containing a non-empty string of decimal digits. The string in each test case will be non-empty and will contain only characters '\$0\$' through '\$9\$'. Each string is no more than 13 characters long. E.g.1901112345Output Sample:Print out the number of expressions that evaluate to an ugly number for each test case, each one on a new line. E.g.01664Is the code understandable? How can it be improved? #include <iostream>#include <fstream>#include <algorithm>#include <iterator>#include <vector>#include <bitset>#include <cmath>#include <sstream>#include <numeric>using namespace std;const int one_prime[4] = {2,3,5,7};bool isUgly(int number){ if(number == 0) return true; for(int i=0; i<4; i++) { if(number % one_prime[i] == 0) return true; } return false;}vector<string> makeBinary(size_t perm){ vector<string> output; size_t eraseLength = bitset<32>(perm).to_string().find_first_of('1'); while(perm--) { string binary = bitset<32>(perm).to_string(); binary.erase(binary.begin(), binary.begin() + eraseLength); output.push_back(binary); } return output;}vector<string> getPartitions(const vector<string>& binarySet, const string& input){ vector<string> binOperator; for(size_t idx = 0; idx < binarySet.size(); idx++) { string str(input); for(size_t pos = 0,opCount = 1; (pos = binarySet[idx].find('1',pos) )!= string::npos; pos++,opCount++) str.insert(pos+opCount, ); binOperator.push_back(str); } return binOperator;}vector<int> makePartitionsToNum(const string& str){ vector<int> numbers; stringstream split(str); string buf; while(split >> buf) { int value; istringstream toNum(buf); toNum >> value; numbers.push_back(value); } return numbers;}void getReadyNumbers(vector<int>* readyNumbers, const vector<int> &numbers){ if(numbers.size() == 1) { (*readyNumbers).push_back(numbers[0]); } else if(numbers.size() == 2) { (*readyNumbers).push_back(numbers[0] + numbers[1]); (*readyNumbers).push_back(numbers[0] - numbers[1]); } else { size_t possiblePerm = pow(2,static_cast<double>(numbers.size() - 1) ); vector<string> binSet(makeBinary(possiblePerm)); for(size_t i=0; i<binSet.size(); i++) { int result = numbers[0]; for(size_t binCounter=1; binCounter<numbers.size(); binCounter++) { if(binSet[i][binCounter - 1] == '1') { result += numbers[binCounter]; } else { result -= numbers[binCounter]; } } (*readyNumbers).push_back(result); } }}void PrintSolution(const vector<int>& readyNumbers){ size_t UglyNumberCount = 0; for(size_t i=0; i<readyNumbers.size(); i++) { if(isUgly(readyNumbers[i])) { UglyNumberCount++; } } cout << UglyNumberCount << endl;}int main(int argc, char *argv[]){ ifstream stream(argv[1]); string input; while (getline(stream, input)) { size_t perm = pow(2,static_cast<double>(input.size() - 1) ); vector<string> binarySet(makeBinary(perm)); vector<string> partitionSet (getPartitions(binarySet, input)); vector<int> readyNumbers; for(size_t idx=0; idx<partitionSet.size(); idx++) { vector<int> numbers(makePartitionsToNum(partitionSet[idx])); getReadyNumbers(&readyNumbers,numbers); } PrintSolution(readyNumbers); } return 0;}
Ugly_Numbers challenge
c++;beginner;programming challenge
null
_unix.176035
I use Fedora. There are a number of programmes packaged in a security spin. Included desktop files work but open the programmes with root priviliges. How can I edit the desktop file shown here to open the target without root. I have tried every obvious edit I can think of but am not having any luck.#!/usr/bin/env xdg-open[Desktop Entry]Name=argusExec=gnome-terminal -e su -c 'argus -h; bash'TryExec=argusType=ApplicationCategories=System;Security;X-SecurityLab;X-Reconnaissance;
.desktop file. Correct exec path
command line;gnome shell;freedesktop;.desktop
#!/usr/bin/env xdg-open[Desktop Entry]Name=argusExec=gnome-terminal -e sh -c 'argus -h; bash'TryExec=argusType=ApplicationCategories=System;Security;X-SecurityLab;X-Reconnaissance;This matches behavior most closely. It could be improved upon by someone who knows argus better than I
_datascience.18226
I have a collection of data for a multiplayer game (2000 games, 10 players each). I would like to create clusters from this data, each containing the ids of 3 players that had played against each other.
Detecting patterns from a collection of data
python
You can use Python networkx module to find all 3-cliques:import networksG = nx.Graph() # The clique locator does not work with digraphsG.add_edges_from([('A','B'),('A','D'),('A','C'),('B','D'),('C','D'),('D','E')])[clique for clique in nx.enumerate_all_cliques(G) if len(clique)==3] #[['B', 'A', 'D'], ['A', 'D', 'C']]Finding all clique may take a lot of time and memory. Luckily, nx.enumerate_all_cliques is a generator that produces smaller cliques first, so you can stop retrieving cliques after you get a clique with more than 3 nodes:cliques=[]for c in nx.enumerate_all_cliques(G): if len(c) < 3: continue if len(c) > 3: break cliques.append(c)print(cliques)
_codereview.9555
For flexing my newly acquired Django & Python muscles, I have set up a mobile content delivery system via Wap Push (Ringtones, wallpapers, etc).The idea is that a keyword comes in from an sms via an URL, let's say the keyword is LOVE1 and the program should search if this keyboard points to a Ringtone or an Image. For this I have created a parent model class called Categoria (Category) and two subclasses Ringtone and Wallpaper. This subclasses have a variable called archivo (filename) which points to the actual path of the content.Dynpath is a dynamic URL which has been created to download the content, so it is available only for X amount of time. After that a Celery scheduled task deletes this dynamic URL from the DB.I have a piece which has code smell which I would like to have some input from everyone here.Modelclass Contenido(models.Model): nombre = models.CharField(max_length=100) fecha_creacion = models.DateTimeField('fecha creacion') keyword = models.CharField(max_length=100)class Ringtone(Contenido): grupo = models.ManyToManyField(Artista) archivo = models.FileField(upload_to=uploads) def __unicode__(self): return self.nombreclass Wallpaper(Contenido): categoria = models.ForeignKey(Categoria) archivo = models.ImageField(upload_to=uploads) def __unicode__(self): return self.nombreclass Dynpath(models.Model): created = models.DateField(auto_now=True) url_path = models.CharField(max_length=100) payload = models.ForeignKey(Contenido) sms = models.ForeignKey(SMS) def __unicode__(self): return str(self.url_path)ViewHere is my view which checks that the Dynamic URL exists and here is where the code (which works) gets a little suspicious/ugly: def tempurl(request,hash): p = get_object_or_404(Dynpath, url_path=hash) try: fname = str(p.payload.wallpaper.archivo) except DoesNotExist: fname = str(p.payload.ringtone.archivo) fn = open(fname,'rb') response = HttpResponse(fn.read()) fn.close() file_name = os.path.basename(fname) type, encoding = mimetypes.guess_type(file_name) if type is None: type = 'application/octet-stream' response['Content-Type'] = type response['Content-Disposition'] = ('attachment; filename=%s') % file_name return responseI am talking explictitly this snippet: try: fname = str(p.payload.wallpaper.archivo) except DoesNotExist: fname = str(p.payload.ringtone.archivo)I would have loved to do something like:fname = p.payload.archivoBut it would not let me do that, from the docs:Django will raise a FieldError if you override any model field in any ancestor model.I took a look at generics, but could not make it work with them. Any ideas on a better way of doing this?
Mobile content delivery system
python;django
You have 2 models (Ringtone extends Contenido). As I understand you store same nombre, fecha_creacion, keyword in both models and every update/delete/insert operation on the first model must be synchronized with another one. You can avoid this, make foreign key to base model:class Contenido(models.Model): nombre = models.CharField(max_length=100) fecha_creacion = models.DateTimeField('fecha creacion') keyword = models.CharField(max_length=100)class Ringtone(models.Model): contenido = models.ForeignKey(Contenido) grupo = models.ManyToManyField(Artista) archivo = models.FileField(upload_to=uploads)class Wallpaper(models.Model): contenido = models.ForeignKey(Contenido) categoria = models.ForeignKey(Categoria) archivo = models.ImageField(upload_to=uploads)Then in your Viewsdef tempurl(request,hash): p = get_object_or_404(Dynpath, url_path=hash) try: obj=Wallpaper.objects.get(contenido_id=p.id) except Wallpaper.DoesNotExist: try: obj=Ringtone.objects.get(contenido_id=p.id) except Ringtone.DoesNotExist: raise Http404 fname = str(obj.archivo) # use with statement with open(fname,'rb') as fn: response = HttpResponse(fn.read())Uhh.. Is it still complicated? If you can retrieve content type (ringtone or wallpaper) and save it in Dynpath field, solution will be easier.P.S. Please write your code in English not Spanish )
_softwareengineering.115019
I stumbled upon an article by Den Delimarsky on What is a ContentPresenter? which says:In WPF there is an element called ContentPresenter, that is often used inside control templates, as well as inside the root application markup.I don't understand the inside the root application markup part, because I thought that ContentPresenter can only used inside of a ControlTemplate.The role of the ContentPresenter is quite clear when used in a ControlTemplate, but what are the valid reasons to use ContentPresenter outside of a template's markup?
What are the valid reasons to use ContentPresenter outside of template?
.net;wpf
null
_codereview.27000
I wrote an example program about UNIX semaphores, where a process and its child lock/unlock the same semaphore. I would appreciate your feedback about what I could improve in my C style. Generally I feel that the program flow is hard to read because of all those error checks, but I didn't find a better way to write it. It's also breaking the rule of one vertical screen maximum per function but I don't see a logical way to split it into functions.#include <semaphore.h>#include <stdio.h>#include <errno.h>#include <stdlib.h>#include <unistd.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <sys/mman.h>int main(void){ /* place semaphore in shared memory */ sem_t *sema = mmap(NULL, sizeof(sema), PROT_READ |PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS, -1, 0); if (!sema) { perror(Out of memory); exit(EXIT_FAILURE); } /* create, initialize semaphore */ if (sem_init(sema, 1, 0) < 0) { perror(semaphore initilization); exit(EXIT_FAILURE); } int i, nloop=10; int ret = fork(); if (ret < 0) { perror(fork failed); exit(EXIT_FAILURE); } if (ret == 0) { /* child process*/ for (i = 0; i < nloop; i++) { printf(child unlocks semaphore: %d\n, i); sem_post(sema); sleep(1); } if (munmap(sema, sizeof(sema)) < 0) { perror(munmap failed); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); } if (ret > 0) { /* back to parent process */ for (i = 0; i < nloop; i++) { printf(parent starts waiting: %d\n, i); sem_wait(sema); printf(parent finished waiting: %d\n, i); } if (sem_destroy(sema) < 0) { perror(sem_destroy failed); exit(EXIT_FAILURE); } if (munmap(sema, sizeof(sema)) < 0) { perror(munmap failed); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }}
UNIX semaphores
c;linux
Your code is good, especially the error checks. Error checking always takesup space and can be distracting, but good error checking is a mark of goodcode (and of a good programmer).As you say, main is a bit long, but it can be shortened quite nicely byextracting the two for-loops into functions. You can also remove the duplicatemunmap call. Here's what you get after the semaphore initialisation:int pid = fork();if (pid < 0) { perror(fork); exit(EXIT_FAILURE);}else if (pid == 0) { child(sema, nloops);}else { parent(sema, nloops); int stat; wait(&stat); if (sem_destroy(sema) < 0) { perror(sem_destroy); exit(EXIT_FAILURE); }}if (munmap(sema, sizeof *sema) < 0) { perror(munmap); exit(EXIT_FAILURE);}exit(EXIT_SUCCESS);Note that I renamed ret as pid, as it holds a process ID. And I added await call after the parent loop completes so that the parent waits for thechild to exit (stat holds the child exit status). I also removed the wordfailed from the perror calls, as the message perror prints will makeit clear that the call failed.Some other points: my Mac's mmap takes MAP_ANON not MAP_ANONYMOUS -which system are you using? And also there is a MAP_HASSEMAPHORE flag thatwould be appropriate here, although your system may not have it (no ideaexactly what it does though).Finally, the mmap/munmap calls use sizeof(sema) which is the size of thepointer. If it works, I would guess that mmap is actually mapping a wholepage and ignoring the size. However, it should be sizeof *sema or sizeof(sema_t)
_softwareengineering.39146
My company has retained an outside firm to develop an iPhone app for us. As the only internal developer with any knowledge of Objective-C, I've been assigned to develop the relevant APIs on our site, but also to do anything I can to make sure the whole thing comes together on time.Any suggestions for things I should do or things I should watch out for, particularly from those who've been down this road before?
Tips for / pitfalls of working on an outsourced project
project management;outsourcing
I outsourced more than 300 IT projects of all sizes over the past 10 years. I've been the outsourced developer myself.Here are the most problematic problems I encountered multiple times and the suggestions to avoid them (I learn the hard way). Those mistakes cost me hundred of thousands dollars, so I hope you will save as much thanks to the suggestions so I'm even and can rest in piece :)require access to the repository. If not possible, request to be sent the full source every week for review.You don't want to discover at the end of the project the code did not meet your quality standards such as missing comments, documentation, poor coding practices, etc. Reviewing the work frequently will allow you to give feedback early in the development phase.ensure that they signed appropriate NDA and IP assignment documents.That's one of the common mistakes. Things went bad the company you outsourced the project to claim full ownership of their work. Or worse, they decide to use what you paid for for their own business. Ensure that a proper NDA and intellectual property rights assignment is signed.they often use custom framework of libraries that comes without source code. Verify it is acceptable to you.Sometimes the developers or company you hired decide to use custom framework or library they wrote. This may be a problem if you are so dependent to them changing your developer is almost impossible. Sometimes the development shop will give you full right on the code they wrote specifically for you but not their libraries. It's as problematic. Ensuring that you will have the possibility to continue your project without them is a really important possibility you want to keep. ensure that they use standards in the technology of choice.Even if they doesn't use specific custom libraries, you may face another problem: specific way of coding that don't meet industry standards. In the worst case, you have to rewrite everything to make any maintenance possible without them.if deadline is important, request penalties in case they miss it.This is one is sometimes not specified explicitly. What happens if they miss the deadline? Let's say they face a strong internal problem preventing them to deliver on time? Will you have the budget to develop in another dev shop in urgency?As a general rule, I would add that the specification is very important in that kind of work. So you have lot of responsibilities there. With time, I learnt that it's preferable to propose a first small project to a company to test it first, and reserve bigger projects to trusted providers you work with before.
_datascience.11846
So let's explain my problem. I have a set of items which have a score from 0 to 100. This set is dynamic which means that several values are expected to be added from moment to moment. In each item is named an owner of item. One owner can have one ore more items. What i need to do is to compute a value which represent a score per owner based on his items values. Any ideas what to try?UPDATE: Before start the computation I set a predefined score per owner. I have to compare the result with that score and in ideally case should be the same. That items values should be changed on each iteration in order to obtain ideal case. Beside the strategie which i can apply do you have any suggestion to verify fast the accuracy?UPDATE 2: I know what represent the items. And also what represent the owner. Let's say that i want to measure how dangerous is the owner. Owner have several weapons each one with a score of dangerousness. I want to compare different owners. For example, one which had 200 items with score of 20 and 300 with 40 and another have 350 with 50. Of course the list with items is bigger than 100 and most probably one owner will have several items. I need a strategy to compute score and compare with assumed score. Then i need to see how good is the strategy. So my questions in fact are? What tools provide mathematics to treat such quantities? What tools provide mathematics to measure (what to measure in) strategy?
Decision calculus from data
machine learning;decision trees
null
_webmaster.43301
I've created a simple video & photo sharing website. I want to arrange the preview (thumbnail view) of photos and videos in a tile-like format (like windows 8 start screen) in the home page.I'm confused as to which tag I should use: table or div. I think it's quite easy to do it using tables, but I don't want to use it because it's solely used for tabular data. I also think that it could cause problems down the road (perhaps getting messy during maintenance.)The other option is to use a div tag, but I don't know how I would go about doing this with a div tag.Which one should I go for? A table or a div? If I should use a div, how would I implement this?
How to arrange items in a tile like format in a web page?
website design
The nice thing about tables is that they are very easy to define a grid with a fixed number of rows and columns. If the content in one cell is over-sized, the table will expand to accommodate it.On the other hand, divs can be more dynamic. You can have 10 of them across when the window is maximized and 4 across when it is narrower with dynamic layout between the two. For divs, you will want to make each one a fixed size (both width and height), put some padding around them, and make sure they float left. Here is some CSS that I am using on my homepage to make a tile layout. Each div has a class=item on it. I'm using min-height rather than height so that the divs expand vertically if I put too much stuff in them. Older IE versions didn't support this, but I think it works ok now..item {padding:.2cm;float:left;width:6cm;min-height:5cm;border:thin black ridge;margin:.1cm;font-size:medium;}
_webmaster.82305
A partner sends us traffic two ways:Visitors click on a link on their site and land on oursVisitors interact with our widget on their site, eventually saving some info and clicking through to land deeper in our checkout process.Visitors coming from path 1 are currently marked as medium=referral by the browser and thus tracked in Google Analytics. Visitors from path 2 are tagged medium=affiliate by our own UTM parameters. Should we leave it split like that or is it better to unify that traffic as one medium?
Should We Track an Affiliates Traffic as Medium=affiliate or =referral?
google;google analytics;analytics;url parameters;parameters
If you have a host of legacy data with this separation, you are better off leaving it as it is. You can usually sort this out in your reports, so having consistent data is best.In contrast, if this is a new partner, you should keep the medium consistent and use affiliate. You never know what dimensions or metrics will reveal important data. If you have to set up segments or manage report filters because of this medium inconsistency, it may be troublesome to get to the correct view quickly. Keep in mind that the optional campaign content parameter can be used to differentiate the specific content that was clicked.
_webmaster.71519
Both title attribute and link anchor text does provide positive influence to SEO.Example:<a href=www.companyA.com>Service Provided</a><a href=www.companyB.com title=Service Provided>Company B</a>But how much is the different of influence between two? Company A or B will have better position in SEO?
Title Attribute vs Link Anchor Text in SEO
seo;links;title attribute
Putting keywords in the title attribute doesn't give SEO value to the linked site and the page of the link. However, the anchor of a link gives SEO value to the linked site and the page of the link.Consequently, regarding optimizing the SEO value of a link, keywords in the anchor needs to be seriously considered instead of the title attribute.However, the title attribute of a link is important as well but for users, not SEO.
_codereview.6821
This code will be used to map a set of unique keys to a container of objects that are unique to that key. I would like to be able to reuse this code in future projects hence the template, and not hard coding the types into the class. You can also access the code here.main.cpp#include <set>#include <string>#include <fstream>#include file_to_map.hint main(int argc, char *argv[]){ file_to_map<std::string, std::multiset<std::string> > ftm(opengl_functions); std::ifstream ifs; ifs << ftm; std::cout >> ftm; return 0;}file_to_map.h#ifndef FILE_TO_MAP_H_#define FILE_TO_MAP_H_#include <map>#include <vector>#include <string>#include <fstream>#include <iostream>#include <iterator>#include <algorithm>template <class T> struct print{ print(std::ostream &out) : os(out) {} void operator() (T x) { os << x << ' ' << std::endl; } std::ostream & os; };template <class key, class container>class file_to_map{public: file_to_map() { m_file = ; } file_to_map(std::string file) { m_file = file; } ~file_to_map() { } std::map<key, container>& getMap() { return m_map; } friend std::ostream& operator>> (std::ostream &out, file_to_map<key, container> &obj) { typedef typename std::map<key, container>::const_iterator mapItr; mapItr mbi = obj.m_map.begin(); mapItr emi = obj.m_map.end(); while (mbi != emi) { out << -- << mbi->first << -- << std::endl; ++mbi; } return out; } friend std::istream& operator<< (std::ifstream &in, file_to_map<key, container> &obj) { if (in.is_open()) in.close(); if (obj.m_file == ) return in; in.open(obj.m_file.c_str(), std::ios::in); if (in.fail() || in.bad()) { in.close(); return in; } std::vector<key> tmp; typedef std::istream_iterator<key> string_input; copy(string_input(in), string_input(), back_inserter(tmp)); typename std::vector<key>::iterator bvi = tmp.begin(); typename std::vector<key>::iterator evi = tmp.end(); while (bvi != evi) { obj.m_map[*(bvi)] = container(); ++bvi; } in.close(); return in; }private: std::map<key, container> m_map; std::string m_file;};#endif//FILE_TO_MAP_H_Makefilefile_to_map : file_to_map.h main.cpp g++ -o file_to_map -Wall ./file_to_map.h ./main.cpp
File to map class
c++;hash table
For one thing, you have operators << and >> reversed for the streams.I wouldn't recommend overloading ifstream operator, at least not like this. operator>> does not normally open and close files, it reads a value from an already open stream. Basically your class is just asking the caller to provide what the class could create itself. Neither would chaining this operator use do any good, because the returned stream is not good anyway.Personally I think that operator>> should either be able to parse what operator<< outputs, or it shouldn't be implemented at all.The constructor itself should load the file and/or the class should provide a named method for loading a file.As to populating the map keys, is it really necessary to put the keys in a vector first?
_softwareengineering.201108
I understand PKI reasonably well from a conceptual point of view - i.e. private keys/public keys - the math behind them, use of hash & encryption to sign a certificate, Digital Signing of Transactions or Documents etc. I have also worked on projects where openssl C libraries were used with certs for securing communication and authentication. I am also extremely familiar with openssl command line tools.However, I have very little experience with web based PKI enabled projects & hence I am trying to design and code a personal project for understanding this better.The requirementsThis is the website for a bank. All Internet Banking users are allowed use any certificate issued by a few known CAs (verisign, Thawte, entrust etc). The Bank is not responsible for procuring certificates for the user. These certificates will be used for authentication to the banks website either instead of or as an add-on to username/password login. The platforms/OS etc are still not fixed. Assume that enrollment has been done - i.e. bank knows the certificate going to be used by each user.DesignI was wondering what's the best way to do authentication?I saw that Apache has a way to enable 2 way ssl - in this case, i think navigating to the website would automatically ask for a cert from the user. But I am not sure if this is enough because it seems that all it verifies is whether a certificate is signed by a trusted CA & also may be whether it falls in a white list of subject lines of the certificates etc. But this is not enough for a bank case because you need to be able to associate a bankuserid with a certificate.IIS seems to have a way by which I can have a certificate stored for each user in Active Directory. This is what I understood from reading few MSDN articles. You turn on 2 way SSL in IIS & then when the user tries to navigate to the website, IIS will send a request to the browser with a list of approved CAs and browser will let the user pick an appropriate certificate from his certstore and sends it to backend. I am assuming that IIS will do 2 thingsEnsure that the user has the private key corresponding to the cert (by under the cover negotiations)Based on the AD User-Cert Mapping, IIS will report the username to the application.Do the authentication explicity by calling crypto functions rather depending on depending on the webserver to do it.Show a user screen where he uploads a certificate and the application ensures the user has the private key corresponding to the cert (by asking the front-end to sign some string using the cert).The application has a database some of data is stored which allows each user to be mapped to his userid. This may be the whole cert corresponding to each useridthe CA and cert serial number corresponding to each user id.I was wondering which is the commonly used method? What are the best practices?If I should go with #3, what are the best ways to do this?
Login to a Web App using PKI Certs
web applications;security;authentication;certificate
null
_unix.210420
I have a native install of Kali Linux on my custom PC which has an Intel Core i5 4690K CPU and an NVIDIA GTX960 GPU. The monitor plugged into my DVI port is working but my 2nd monitor plugged into HDMI is not. In fact, Kali is not even detecting the second monitor. I've tried to follow Blackmore Ops' guide to install the NVIDIA drivers figuring I need the proprietary drivers. However when I call nvidia-xconfig to generate the new config files and reboot, I get trapped on a black screen with a cursor and the only way to get out is to Ctrl+Alt+F1 to recovery mode and remove the conf file. I've been grinding at this for hours and am hopelessly stuck.There is a suggestion on page four of the guide to simply remove nouveau to get it to work. I tried it as specified with apt-get remove -purge nouveau but I get the outputE: Command line option 'p' [from -purge] is not known.and when I try without -purge I getE: Command line option 'p' [from -purge] is not known.But I know it's there because when I issue lsmod | grep nouveau I get output.As I said, I feel hopelessly stuck.
Dual Monitor Support in Kali Linux
drivers;nvidia;kali linux;dual monitor
Figured it out. I went to NVIDIA's website and downloaded their Linux drivers. It was a pain figuring out how to install them because of an x server error but it turns out I had to kill gdm3. Once I did that they installed and now it works.
_unix.48797
I was wondering if there was a way to use the highest available resolution in the syslinux.cfg file?I know i can do:MENU RESOLUTION 1024 768but without knowing available resolutions beforehand, is there a way to just choose the highest and have multiple backgrounds for different sizes etc?
syslinux / vesamenu.c32 - using highest available screen resolution?
boot loader;resolution;syslinux
null
_unix.375839
Is there anyway to achieve 2-factor authentication with luks so that if a key is compromised, if the other part is not in hand, the data is still secure?
luks - is there 2-factor authentication
luks
null
_unix.167450
So I have a 3TB hard drive /dev/sdc that I am trying to create a partition on. Before this point, I had the issues described below, I transfered the drive to a Windows 7 computer and created a GPT on it from there. Windows 7 only recognized it as being around 800 GB, not the 3 TB it should be.Here are the details of the hard drive:root@VMHost:~# hdparm -i /dev/sdc/dev/sdc: Model=ST3000DM001-1CH166, FwRev=CC24, SerialNo=W1F2TRVD Config={ HardSect NotMFM HdSw>15uSec Fixed DTR>10Mbs RotSpdTol>.5% } RawCHS=16383/16/63, TrkSize=0, SectSize=0, ECCbytes=4 BuffType=unknown, BuffSize=unknown, MaxMultSect=16, MultSect=16 CurCHS=16383/16/63, CurSects=16514064, LBA=yes, LBAsects=5860533168 IORDY=on/off, tPIO={min:120,w/IORDY:120}, tDMA={min:120,rec:120} PIO modes: pio0 pio1 pio2 pio3 pio4 DMA modes: mdma0 mdma1 mdma2 UDMA modes: udma0 udma1 *udma2 udma3 udma4 udma5 udma6 AdvancedPM=yes: unknown setting WriteCache=enabled Drive conforms to: unknown: ATA/ATAPI-4,5,6,7 * signifies the current active modeHere is the MBR (first 512 bytes) of the hard drive after creating the GPT from Windows 7:root@VMHost:~# dd if=/dev/sdc bs=512 count=1 | xxd1+0 records in1+0 records out512 bytes (512 B) copied, 0.000573978 s, 892 kB/s0000000: 0000 0000 0000 0000 0000 0000 0000 0000 ................0000010: 0000 0000 0000 0000 0000 0000 0000 0000 ................0000020: 0000 0000 0000 0000 0000 0000 0000 0000 ................0000030: 0000 0000 0000 0000 0000 0000 0000 0000 ................0000040: 0000 0000 0000 0000 0000 0000 0000 0000 ................0000050: 0000 0000 0000 0000 0000 0000 0000 0000 ................0000060: 0000 0000 0000 0000 0000 0000 0000 0000 ................0000070: 0000 0000 0000 0000 0000 0000 0000 0000 ................0000080: 0000 0000 0000 0000 0000 0000 0000 0000 ................0000090: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000a0: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000b0: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000c0: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000d0: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000e0: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000f0: 0000 0000 0000 0000 0000 0000 0000 0000 ................0000100: 0000 0000 0000 0000 0000 0000 0000 0000 ................0000110: 0000 0000 0000 0000 0000 0000 0000 0000 ................0000120: 0000 0000 0000 0000 0000 0000 0000 0000 ................0000130: 0000 0000 0000 0000 0000 0000 0000 0000 ................0000140: 0000 0000 0000 0000 0000 0000 0000 0000 ................0000150: 0000 0000 0000 0000 0000 0000 0000 0000 ................0000160: 0000 0000 0000 0000 0000 0000 0000 0000 ................0000170: 0000 0000 0000 0000 0000 0000 0000 0000 ................0000180: 0000 0000 0000 0000 0000 0000 0000 0000 ................0000190: 0000 0000 0000 0000 0000 0000 0000 0000 ................00001a0: 0000 0000 0000 0000 0000 0000 0000 0000 ................00001b0: 0000 0000 0000 0000 19d0 7cdc 0000 0000 ..........|.....00001c0: 0200 eeff ffff 0100 0000 ffff ffff 0000 ................00001d0: 0000 0000 0000 0000 0000 0000 0000 0000 ................00001e0: 0000 0000 0000 0000 0000 0000 0000 0000 ................00001f0: 0000 0000 0000 0000 0000 0000 0000 55aa ..............U.Now, if I execute parted /dev/sdc on it, I get the following:root@VMHost:~# parted /dev/sdcGNU Parted 2.3Using /dev/sdcWelcome to GNU Parted! Type 'help' to view a list of commands.(parted) printError: The backup GPT table is corrupt, but the primary appears OK, so that will be used.OK/Cancel? OWarning: Not all of the space available to /dev/sdc appears to be used, you can fix the GPT to use all of the space (an extra 4294967296 blocks) or continue with the current setting?Fix/Ignore? IModel: ATA ST3000DM001-1CH1 (scsi)Disk /dev/sdc: 3001GBSector size (logical/physical): 512B/4096BPartition Table: gptNumber Start End Size File system Name Flags 1 17.4kB 134MB 134MB Microsoft reserved partition msftres(parted) mklabel gptWarning: The existing disk label on /dev/sdc will be destroyed and all data on this disk will be lost. Do you want to continue?Yes/No? Yes(parted) printError: /dev/sdc: unrecognised disk label(parted) quitInformation: You may need to update /etc/fstab.In the case above, I had it Ignore the error instead of Fix it. Before, I had tried having it Fix the error and still come to the same thing. As you see, once I do a mklabel gpt it appears to successfully complete, but then I receive the following error on any subsuquent requests:Error: /dev/sdc: unrecognised disk labelFinally, when I attempt to get the MBR from the drive, I receive the followingroot@VMHost:~# dd if=/dev/sdc bs=512 count=1 | xxd1+0 records in1+0 records out512 bytes (512 B) copied, 0.000411262 s, 1.2 MB/s0000000: ffff ffff ffff ffff ffff ffff ffff ffff ................0000010: ffff ffff ffff ffff ffff ffff ffff ffff ................0000020: ffff ffff ffff ffff ffff ffff ffff ffff ................0000030: ffff ffff ffff ffff ffff ffff ffff ffff ................0000040: ffff ffff ffff ffff ffff ffff ffff ffff ................0000050: ffff ffff ffff ffff ffff ffff ffff ffff ................0000060: ffff ffff ffff ffff ffff ffff ffff ffff ................0000070: ffff ffff ffff ffff ffff ffff ffff ffff ................0000080: ffff ffff ffff ffff ffff ffff ffff ffff ................0000090: ffff ffff ffff ffff ffff ffff ffff ffff ................00000a0: ffff ffff ffff ffff ffff ffff ffff ffff ................00000b0: ffff ffff ffff ffff ffff ffff ffff ffff ................00000c0: ffff ffff ffff ffff ffff ffff ffff ffff ................00000d0: ffff ffff ffff ffff ffff ffff ffff ffff ................00000e0: ffff ffff ffff ffff ffff ffff ffff ffff ................00000f0: ffff ffff ffff ffff ffff ffff ffff ffff ................0000100: ffff ffff ffff ffff ffff ffff ffff ffff ................0000110: ffff ffff ffff ffff ffff ffff ffff ffff ................0000120: ffff ffff ffff ffff ffff ffff ffff ffff ................0000130: ffff ffff ffff ffff ffff ffff ffff ffff ................0000140: ffff ffff ffff ffff ffff ffff ffff ffff ................0000150: ffff ffff ffff ffff ffff ffff ffff ffff ................0000160: ffff ffff ffff ffff ffff ffff ffff ffff ................0000170: ffff ffff ffff ffff ffff ffff ffff ffff ................0000180: ffff ffff ffff ffff ffff ffff ffff ffff ................0000190: ffff ffff ffff ffff ffff ffff ffff ffff ................00001a0: ffff ffff ffff ffff ffff ffff ffff ffff ................00001b0: ffff ffff ffff ffff ffff ffff ffff ffff ................00001c0: ffff ffff ffff ffff ffff ffff ffff ffff ................00001d0: ffff ffff ffff ffff ffff ffff ffff ffff ................00001e0: ffff ffff ffff ffff ffff ffff ffff ffff ................00001f0: ffff ffff ffff ffff ffff ffff ffff ffff ................So parted wrote over everything in the MBR with all 1's.Finally, if I attempt to write over the MBR with all 0's, the following occurs:root@VMHost:~# dd if=/dev/zero of=/dev/sdc bs=512 count=11+0 records in1+0 records out512 bytes (512 B) copied, 0.00132826 s, 385 kB/sroot@VMHost:~# dd if=/dev/sdc bs=512 count=1 | xxd1+0 records in1+0 records out512 bytes (512 B) copied, 0.00602964 s, 84.9 kB/s0000000: ffff ffff ffff ffff ffff ffff ffff ffff ................0000010: ffff ffff ffff ffff ffff ffff ffff ffff ................0000020: ffff ffff ffff ffff ffff ffff ffff ffff ................0000030: ffff ffff ffff ffff ffff ffff ffff ffff ................0000040: ffff ffff ffff ffff ffff ffff ffff ffff ................0000050: ffff ffff ffff ffff ffff ffff ffff ffff ................0000060: ffff ffff ffff ffff ffff ffff ffff ffff ................0000070: ffff ffff ffff ffff ffff ffff ffff ffff ................0000080: ffff ffff ffff ffff ffff ffff ffff ffff ................0000090: ffff ffff ffff ffff ffff ffff ffff ffff ................00000a0: ffff ffff ffff ffff ffff ffff ffff ffff ................00000b0: ffff ffff ffff ffff ffff ffff ffff ffff ................00000c0: ffff ffff ffff ffff ffff ffff ffff ffff ................00000d0: ffff ffff ffff ffff ffff ffff ffff ffff ................00000e0: ffff ffff ffff ffff ffff ffff ffff ffff ................00000f0: ffff ffff ffff ffff ffff ffff ffff ffff ................0000100: ffff ffff ffff ffff ffff ffff ffff ffff ................0000110: ffff ffff ffff ffff ffff ffff ffff ffff ................0000120: ffff ffff ffff ffff ffff ffff ffff ffff ................0000130: ffff ffff ffff ffff ffff ffff ffff ffff ................0000140: ffff ffff ffff ffff ffff ffff ffff ffff ................0000150: ffff ffff ffff ffff ffff ffff ffff ffff ................0000160: ffff ffff ffff ffff ffff ffff ffff ffff ................0000170: ffff ffff ffff ffff ffff ffff ffff ffff ................0000180: ffff ffff ffff ffff ffff ffff ffff ffff ................0000190: ffff ffff ffff ffff ffff ffff ffff ffff ................00001a0: ffff ffff ffff ffff ffff ffff ffff ffff ................00001b0: ffff ffff ffff ffff ffff ffff ffff ffff ................00001c0: ffff ffff ffff ffff ffff ffff ffff ffff ................00001d0: ffff ffff ffff ffff ffff ffff ffff ffff ................00001e0: ffff ffff ffff ffff ffff ffff ffff ffff ................00001f0: ffff ffff ffff ffff ffff ffff ffff ffff ................As you can see, dd thinks it completed successfully, but upon checking the drives MBR, it is still all 1's.I have two hard drives that are doing this, two of the three drives I used to build a RAID as mentioned in this question: mdadm RAID 5 and parted unrecognized disk labelDoes anyone know how I may get my drives back to a working state where I could then attempt to build a RAID again?UPDATE: Yes, it can handle 3 TB drives. I have removed the non-working drives from the computer, so they are not displayed here, but the working drives are here, which includes two 3 TB drives.lex@VMHost:~$ sudo parted --listModel: ATA ST1000DM003-1CH1 (scsi)Disk /dev/sda: 1000GBSector size (logical/physical): 512B/4096BPartition Table: msdosNumber Start End Size Type File system Flags 1 1049kB 256MB 255MB primary ext2 boot 2 257MB 1000GB 1000GB extended 5 257MB 1000GB 1000GB logical lvmModel: ATA ST3000DM001-1CH1 (scsi)Disk /dev/sdb: 3001GBSector size (logical/physical): 512B/4096BPartition Table: gptNumber Start End Size File system Name Flags 1 1049kB 3001GB 3001GB ntfs Basic data partition msftdataModel: ATA ST3000DM001-1CH1 (scsi)Disk /dev/sdc: 3001GBSector size (logical/physical): 512B/4096BPartition Table: gptNumber Start End Size File system Name Flags 1 1049kB 3001GB 3001GB raidAs for the motherboard being used, it is Gigabyte GA-990FXA-UD5 (http://www.gigabyte.com/products/product-page.aspx?pid=3891#ov)As for the lsof /dev/sdc, cat /proc/mdstat, and dmesg | grep -C3 sdc commands, I will put one of the hard drives back into the computer when I get home from work today and post the results of those commands.UPDATE: I have inserted the two drives back into the computer and executed the three commands that were listed in the comments. I chose one of the problem drives, sdd:root@VMHost:/home/lex# lsof /dev/sddroot@VMHost:/home/lex# cat /proc/mdstatPersonalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]unused devices: <none>root@VMHost:/home/lex# dmesg | grep -C3 sdd[ 2.214863] sd 3:0:0:0: [sdc] Mode Sense: 00 3a 00 00[ 2.214924] sd 3:0:0:0: [sdc] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA[ 2.215017] scsi 5:0:0:0: Direct-Access ATA ST3000DM001-1CH1 CC24 PQ: 0 ANSI: 5[ 2.215162] sd 5:0:0:0: [sdd] 5860533168 512-byte logical blocks: (3.00 TB/2.72 TiB)[ 2.215167] sd 5:0:0:0: Attached scsi generic sg4 type 0[ 2.215170] sd 5:0:0:0: [sdd] 4096-byte physical blocks[ 2.215273] sd 5:0:0:0: [sdd] Write Protect is off[ 2.215278] sd 5:0:0:0: [sdd] Mode Sense: 00 3a 00 00[ 2.215306] scsi 5:0:1:0: Direct-Access ATA ST3000DM001-1CH1 CC24 PQ: 0 ANSI: 5[ 2.215311] sd 5:0:0:0: [sdd] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA[ 2.215586] sd 5:0:1:0: [sde] 5860533168 512-byte logical blocks: (3.00 TB/2.72 TiB)[ 2.215591] sd 5:0:1:0: [sde] 4096-byte physical blocks[ 2.215625] sd 5:0:1:0: Attached scsi generic sg5 type 0[ 2.215705] sd 5:0:1:0: [sde] Write Protect is off[ 2.215710] sd 5:0:1:0: [sde] Mode Sense: 00 3a 00 00[ 2.215757] sd 5:0:1:0: [sde] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA[ 2.264662] sdd: sdd1 sdd2[ 2.267284] sdc: sdc1[ 2.267722] sd 3:0:0:0: [sdc] Attached SCSI disk[ 2.269904] sdb: sdb1[ 2.270426] sd 2:0:0:0: [sdb] Attached SCSI disk[ 2.295403] random: lvm urandom read with 81 bits of entropy available[ 2.321435] sd 5:0:0:0: [sdd] Attached SCSI disk[ 2.326279] firewire_core 0000:04:0e.0: created device fw0: GUID 0049e550854d0d00, S400[ 2.330185] sde: sde1 sde2[ 2.330654] sd 5:0:1:0: [sde] Attached SCSI disk
Hard Drive reporting all 1's after parted
hard disk;dd
null
_softwareengineering.201524
Simon Peyton Jones himself recognizes that reasoning about performance in Haskell is hard due to the non strict semantics.I have yet to write a significant project in haskell so I wonder: can I reason about performance only at the beginning of a project (when choosing basic data structures & IO library) and whenever a problem arise, deal with it with the profiler?To put it differently, is it possible (ie not too painful) to postpone dealing with performance when you have performance issues, or do you have to learn to predict how GHC will run your code (for exemple: infer what the strictness analyser will decide)?
When is it a good time to reason about performance in Haskell?
performance;haskell
The other answers provide broad advice about performance reasoning. This answer specifically addresses non-strict semantics.While laziness does make it harder to reason about performance, it isn't as complicated as you might think. Although laziness is quite useful in some situations, most of the time a lazy language gets used in the same way that a strict language would be used. Consequently, performance reasoning for strict languages can be applied (with a few adjustments) to lazy languages.In terms of time complexity, eager evaluation does strictly more work than lazy evaluation. Both strategies produce the same result in most cases. (More precisely, if eager evaluation doesn't run into any errors, it produces the same result as lazy evaluation.) Therefore, to reason about the time complexity of a Haskell program, you can pretend that it evaluates eagerly. In those infrequent situations where laziness matters, this estimate will be too high and should be revised downwards.While lazy evaluation gives you lower time complexity than eager evaluation, it sometimes gives you higher space complexity, i.e. space leaks. Higher space complexity can be fixed by adding strictness annotations to make a program execute more eagerly. Profiling tools are pretty good at tracking down the cause of space leaks. I'd categorize this as either correctness debugging or performance debugging, depending on the severity.
_webmaster.43673
This is a follow up question to Archiving web content annually. One site or sites by year?We are completing the import of tens of thousands scientific abstracts into a single site. The most recent two years of abstracts were hosted on separate domains (conference2012.org, conference2011.org) and represents around 3,000 pages. I have the ability to add redirects to every single document on the smaller sites and redirect to the new, main site. However, I am uncertain if Google will slap a Panda, Penguin, or Farmer penalty on the new site for receiving so many redirects from two other domains. But if I don't redirect, I'm concerned that I'll get nailed by the duplicate content penalty before the old sites de-index.How do I set up this type of migration?
Does Google penalize for too many redirects from different domains?
seo;redirects;301 redirect
Merging a small number of sites into one shouldn't be a problem. In fact, Matt Cutts made a webmaster help video expressly for this situation: http://www.youtube.com/watch?v=l7M22teF3Ho
_vi.7116
Since importing a package and not using it in Go is a compilation error,fixing the import manually can be a bit of a pain while debugging, so I'm currently using this to fix it up automatically before saving: Filter all lines through cmd, and silently undo it if there's an errorfun! s:write_cmd(cmd) let l:save = winsaveview() keepjumps silent %!goimports if v:shell_error != 0 normal! u endif call winrestview(l:save)endfunaugroup ftype_go autocmd! autocmd BufWritePre *.go call s:write_cmd('goimports')augroup endThis works, but has at least two problems:Pressing u undoes this.:!! now runs goimports (and not, for example, :!go run % which Imanually typed).Perhaps others side-effects I haven't noticed yet?How can I transparently filter my buffer to an external command (meaning it won't cause any side-effects)?
How can I filter a buffer to an external command on save without causing any side effects?
external command;undo redo
null
_webmaster.32128
I am using Google Custom Search for my site. I want Google to provide at most 2 searches from a site. I am not sure whether it is possible or not, but it seems there is no such option on Google CSE.For example, my CSE has 10 listed sites. What I want is that whenever a user makes a search then search results should show at most two links from a site. In general CSE is returning multiple results from one site only and these come on page 1. If it is at most 2 from a site then the user has a better chance to have links from other sites too.
Customizing Google Custom Search
google custom search
null
_unix.277701
Running BIND 9.10.3-P4-RedHat-9.10.3-12.P4.fc23 and DHCP Server 4.3.3-P1. DNS Zones report no errors and appear to work (dig, nslookup, nsupdate, dnssec, rpz, etc.). DHCP starts up without complaint, assigns ip, but log file messages similar to: Unable to add forward map from pc2.blkdiamonds.lan. to 10.0.2.63 appears for each client.I've read man pages, forum posts, dhcp-users lists and archives but I haven't been able to determine what's different in my configuration that causes the DHCP server to send the client's forward map back to the client? Any ideas will greatly be appreciated.DHCP.CONF (partial) is a follows:default-lease-time 600;max-lease-time 7200;ddns-updates on;update-static-leases on;use-host-decl-names on;ddns-update-style interim;authoritative;include /etc/named/_blkdiamonds.ddns.update.key;log-facility local7;ping-check true;ddns-domainname blkdiamonds.lan.;ddns-rev-domainname in-addr.arpa.;server-identifier roxie.blkdiamonds.lan;local-address 10.0.2.254;one-lease-per-client on;do-forward-updates true;....shared-network benu { ignore client-updates; deny unknown-clients; # wr0 subnet 10.0.2.0 netmask 255.255.255.0 { authoritative; ignore client-updates; deny unknown-clients; ddns-domainname blkdiamonds.lan.; ddns-rev-domainname in-addr.arpa.; range 10.0.2.160 10.0.2.167; option broadcast-address 10.0.2.255; option domain-name-servers 10.0.2.254; option ntp-servers 10.0.2.254; option routers 10.0.2.254; option time-servers 10.0.2.254; group { host pc2-wifi.blkdiamonds.lan { hardware ethernet 88:25:2c:bc:11:1a; fixed-address 10.0.2.63; ddns-hostname Roy-fallen-pc2-wifi; }...Another subnet
How do I troubleshoot DDNS forwarding problem?
dhcp;dnssec
null
_codereview.162815
This question is inspired by http://anydice.com - a dice probability calculator web application.Anydice language has three run-time types: a number, a sequence and a die. There is also a number of unary and binary operations defined on these types. Each binary operation can take any type pair (out of the 3) as arguments, there are separate definitions of what each operation does for each possible pair of types. Some operations are not commutative.For simplicity let's consider a single binary operation, which I'll call OpAccess, or @. My goal is to design a set of classes that represent the run-time values, so that if the access operation is executed on two of such values the correct operation implementation (depending on argument types) is called.The main problem is that at compile time it is not known yet what run-time type a value has, yet, it's required to dispatch the correct operation implementation during the run-time.Let's start with defining the base class for our values:abstract class Primitive { public abstract Primitive OpAccess(Primitive right);}Our value will use itself as the left argument in the OpAccessoperation and accept the right argument as the parameter.Having this base we can design our value classes as follows:class Number : Primitive{ public override Primitive OpAccess(Primitive right) { return OpAccess((dynamic)right); } public Primitive OpAccess(Number right) { Console.WriteLine(Number @ Number); return null; } public Primitive OpAccess(Sequence right) { Console.WriteLine(Number @ Sequence); return null; } public Primitive OpAccess(Die right) { Console.WriteLine(Number @ Die); return null; }}class Sequence : Primitive{ public override Primitive OpAccess(Primitive right) { return OpAccess((dynamic)right); } public Primitive OpAccess(Number right) { Console.WriteLine(Sequence @ Number); return null; } public Primitive OpAccess(Sequence right) { Console.WriteLine(Sequence @ Sequence); return null; } public Primitive OpAccess(Die right) { Console.WriteLine(Sequence @ Die); return null; }}class Die : Primitive{ public override Primitive OpAccess(Primitive right) { return OpAccess((dynamic)right); } public Primitive OpAccess(Number right) { Console.WriteLine(Die @ Number); return null; } public Primitive OpAccess(Sequence right) { Console.WriteLine(Die @ Sequence); return null; } public Primitive OpAccess(Die right) { Console.WriteLine(Die @ Die); return null; }}Now if we run something like:Primitive a = new Sequence();Primitive b = new Die();a.OpAccess(b);b.OpAccess(a);We will get:Sequence @ DieDie @ SequenceSince all operation will be defined differently the number of resulting methods is not an issue, it's really this many different ways to do an operation.What worries me more is that I had to duplicatepublic override Primitive OpAccess(Primitive left){ return OpAccess((dynamic)left);}in each class and do not have an easy way around it. Remember, it's just one operation we are considering here, there will be more than a dozen of those in reality. Also, I have no idea if the use of dynamic becomes a performance problem. (Manual dispatch with switch/case should be faster).But maybe I'm attacking this problem from the completely wrong angle? What do you think?Note: this is in the context of writing a parser and an interpreter for Anydice language.UpdateAdditional research prompted by Peter Taylor's answer uncovered the following article, which is most illuminating: Double Dispatch is a Code Smell
Designing classes for non-standard arithmetics
c#;object oriented
You might want to define the base type like thisabstract class Primitive{ public Primitive OpAccess(Primitive right) { switch (right) { case Number number: return OpAccess(number); // ... other types default: throw new ArgumentOutOfRangeException(); } } protected abstract Primitive OpAccess(Number right); // ... other OpAccess}where there is only one public method and the new C# 7 switch takes care of the dispatch and derived classes need to implement only the concrete protected overloads:class Sequence : Primitive{ protected override Primitive OpAccess(Number right) { Console.WriteLine(Sequence @ Number); return null; } // ... other OpAccess}dynamic is no longer necessary.
_codereview.93439
I want to go through each line of the a .csv file and compare to see if the first field of line 1 is the same as first field of next line and so on. If it finds a match then I would like to ignore those two lines that contains the same fields and keep the lines where there is no match.Here is an example dataset (no_dup.txt):Ac_Gene_ID M_Gene_IDENSGMOG00000015632 ENSORLG00000010573ENSGMOG00000015632 ENSORLG00000010585ENSGMOG00000003747 ENSORLG00000006947ENSGMOG00000003748 ENSORLG00000004636Here is the output that I wanted:Ac_Gene_ID M_Gene_IDENSGMOG00000003747 ENSORLG00000006947ENSGMOG00000003748 ENSORLG00000004636Here is my code that works, but I want to see how it can be improved:import sysin_file = sys.argv[1]out_file = sys.argv[2]entries = {}entries1 = {}with open(in_file, 'r') as fh_in: for line in fh_in: if line.startswith('E'): line = line.strip() line = line.split() entry = line[0] if entry in entries: entries[entry].append(line) else: entries[entry] = [line]with open('no_dup_out.txt', 'w') as fh_out: for kee, val in entries.iteritems(): if len(val) == 1: fh_out.write({} \n.format(val))with open('no_dup_out.txt', 'r') as fh_in2: for line in fh_in2: line = line.strip() line = line.split() entry = line[1] if entry in entries1: entries1[entry].append(line) else: entries1[entry] = [line]with open(out_file, 'w') as fh_out2: for kee, val in entries1.iteritems(): if len(val) == 1: fh_out2.write({} \n.format(val))The output that I am getting:[[[['ENSGMOG00000003747',, 'ENSORLG00000006947']]]] [[[['ENSGMOG00000003748',, 'ENSORLG00000004636']]]]
Comparing two columns in two different rows
python;csv;hash table;bioinformatics
null
_codereview.26008
I need objects in python that I can compare, reference to and hash.In principal a tuple or list would be good enough just thata list I cannot hash and the tuple I cannot change,except replacing it which means losing references to it.So I created a class for it, but still have the feeling there should be a simpler/better solution to it.class MyClass: def __init__(self, k, l=0, m=0): self.k = k self.l = l self.m = m def __hash__(self): n_attr = len(self.__dict__) return sum(hash(attr)/n_attr for attr in self.__dict__.values()) def __eq__(self, other): return all(sa==oa for sa, oa in zip(self.__dict__.values(), other.__dict__.values()))Now I can do what I need: creating some objectsx = MyClass(1,2,3)y = MyClass(7)z = MyClass(7,1,0)and some referencesa = x; b = y; c = y; d = zand compare, manipulate ...b == c # Trueb == d # Falseb.l = 1b == c # still Trueb == d # now Trues = {a, d, (a,b)}b in s # Truec in s # True(a,c) in s # TrueI wished I could just forget about the class and do x = 1,2,3y = 7,z = 7,1etc ...Is writing this class the best way to approach this problem? Or did I miss something?edit:After the comment by WinstonEwert I confirmed that the objects cause breakage as keys in dictionarys = {a: 'a', b: 'b'}s[c] # 'b'c.l = 99s[c] # key errors # key errorand decided to replace dictionaries that use these objects as keys byclass MyDict: def __init__(self, d={}): self._data = d.items() def __getitem__(self, key): for k, v in self._data: if k == key: return v raise KeyError def __setitem__(self, key, value): for i, (k, v) in enumerate(self._data): if k == key: self._data[i] = key, value return self._data.append((key,value)) def __contains__(self, key): for k, v in self._data: if k == key: return True return FalseNow I have the desired behaviors = MyDict()s[a] = 'a's[b] = 'b's[c] # 'b'c.l = 99s[c] # still 'b'And I do not need MyClass any more and can use listx = [1,2,3]y = [7,0,0]z = [7,1,0]
Class for simple python object to be hashed and referenced
python
The python dictionary assumes that the keys are immutable. It assumes they will not change. That's why mutable classes in python (such as lists) don't hash. Its to prevent you from putting them in dicts which just won't work. As a result the entire premise of your class is wrong. You shouldn't do that. To follow what python expects, an object should return the same hash and be equal to the same objects throughout its lifetime. If it can't it shouldn't support hashing.We might be able to suggest a better way to do this, but you'll need to show more of how you want to use this class.
_cogsci.11016
We have been running an experiment trying to collect ABR data using the Brainvision EP-PreAmp and Actichamp system. We ran several successful tests with short versions of our experiment, about 10-15 minutes of recording. We were able to process the data in eeglab and saw the components we were expecting.We have recently been running our full experiment, recording for about 45-50 minutes. The files are necessarily much bigger. The test .eeg files were ~150mb and the full .eeg files are ~550mb. All of our Brainvision equipment seems to working (amps, batteries, electrodes), and we are able to get our impedances low before recording. However, when we import the vhdr files into eeglab, it looks like there's no data there. We are thinking this might be an eeglab problem - perhaps the file is too large and something's getting lost in the import? Any advice would be greatly appreciated.
EEG data processing: large data file seems empty
methodology;eeg;data
null
_datascience.356
I attack this problem frequently with inefficiency because it's always pretty low on the priority list and my clients are resistant to change until things break. I would like some input on how to speed things up. I have multiple datasets of information in a SQL database. The database is vendor-designed, so I have little control over the structure. It's a sql representation of a class-based structure. It looks a little bit like this:Main-class table -sub-class table 1 -sub-class table 2 -sub-sub-class table ... -sub-class table nEach table contains fields for each attribute of the class. A join exists which contains all of the fields for each of the sub-classes which contains all of the fields in the class table and all of the fields in each parent class' table, joined by a unique identifier.There are hundreds of classes. which means thousands of views and tens of thousands of columns.Beyond that, there are multiple datasets, indicated by a field value in the Main-class table. There is the production dataset, visible to all end users, and there are several other datasets comprised of the most current version of the same data from various integration sources. Daily, we run jobs that compare the production dataset to the live datasets and based on a set of rules we merge the data, purge the live datasets, then start all over again. The rules are in place because we might trust one source of data more than another for a particular value of a particular class.The jobs are essentially a series of SQL statements that go row-by-row through each dataset, and field by field within each row. The common changes are limited to a handful of fields in each row, but since anything can change we compare each value.There are 10s of millions of rows of data and in some environments the merge jobs can take longer than 24 hours. We resolve that problem generally, by throwing more hardware at it, but this isn't a hadoop environment currently so there's a pretty finite limit to what can be done in that regard.How would you go about scaling a solution to this problem such that there were no limitations? And how would you go about accomplishing the most efficient data-merge? (currently it is field by field comparisons... painfully slow).
How to best accomplish high speed comparison of like data?
efficiency;scalability;sql
null
_softwareengineering.207674
I'm new to developing software and have been handling feature requests for an internal web-app I built. Sometimes the feature requests are straight-forward and require minimal business logic for me to implement, so I talk to the person for a bit, write their requirements down, and get to work.However, I'm starting to work on feature X where X has dark-corners of business-logic and special-case scenarios keep on popping-up because I didn't ask the right questions and/or the person I'm speaking with didn't think about mentioning it.So I'm curious, how do professionals handle this process? Some things that I thought of are:Require feature requests be written down with the appropriate requirements.Understand their job well-enough so I can do mine.An example to illustrate a similar problem is, implementing government regulations in code. I researched the regulations, created a flowchart and went from there. I could have saved a couple days had someone well-versed in said regulations, written the requirements down and handed them to me.I'm doing the same thing for feature X, except, nothing is written down so I'm unable to deduce their business logic without going through a step-by-step process through their job. Even that fails sometimes, because some special-case wasn't present that day.Using the above example, is it the responsibility of the developer to research this or something that should be provided?Any suggestions for making this process go a bit smoother?
How to formalize feature requests
design;feature requests
The problem you depict has no general solution. You have internal clients (I guess from your question), which are professionals in their field, but of course not specialists in formalizing requirements.In short: it's your task as a programmer to understand the domain well enough to build software. Try to build up a glossary of terms/grasp the language your client speak. Do not expect their logic to be perfect.Also, do not try to make requirements extraction process itself too formal. Iterative development process may help the clients to see missing pieces. Prototypes are also useful. Some clients may be stressed that you do not understand things, which are obvious (to them). Just observing their business process may give you lot of insights.Read those regulations yourself when possible. Try to find someone, if you don't understand specific moments.Unless your clients are technically inclined, it's futile to impose formalities (or even your process) on them. Even worse to speak software-domain language instead of problem-domain language.However, every situation is unique. The best thing is to gather more experience in the problem domain. Just be open-minded to understand problem-domain to the extent needed to build software. Friendly atmosphere also helps a lot. People may get tired of dull req gathering sessions.There are some books on the topic. For example, some parts of http://www.amazon.com/Just-Enough-Requirements-Management-Development/dp/0932633641 (Just Enough Requirements Management: Where Software Development Meets Marketing by Alan Mark Davis) can help to understand how reqs gathering is done on larger scale. Of course, famous Code Complete by Steve McConnell can also give some good insights.Even if your organization has someone, whose job is writing requirements, it may help to participate in the process to at least give earlier feedback on technical feasibility. If there is no person for that, all that is developer's responsibility.
_unix.159069
In a debian host with many users, I want to allow different users to create their own VMs, completely independent of each other.The closest relevant (non-root) way I have seen in guides is by connecting to the qemu:///system hypervisor . This is the system hypervisor which is shared among all users. What is more the disk image file will be owned by root (or kvm) user, meaning that the whole filesystem path to the location of the disk image file must be world readable. For the above and other reasons I want to run my VMs purely and completely as non root user. That is as qemu:///session . So the main question is how do I do that? Are there any guides I could use?I went as far as trying to create new virtual bridge iface, but even though I am member of the netdev group I get permission denied errors when I do the following: virsh -c qemu:///session net-create /etc/libvirt/qemu/networks/mynet.xmlnote than mynet.xml is just like default network but at a different subnet.
how can I create a KVM guest 100% as a non root user?
networking;kvm;not root user;virsh
What you're using isn't KVM directly, but a management library called libvirt. You can specify a user which will have access to libvirt's setup (and thus creating VMs and pretty much running virsh commands) by adding the users to the libvirtd and kvm groups on the host.You can also use policykit to manage access, the procedure is described in the libvirt Wiki: http://wiki.libvirt.org/page/SSHPolicyKitSetup
_codereview.166324
I made a playground to try find prime factors of any given number, and it works, and I'm happy with the first function, even if not correctly named - I don't know what to name it.My main need for improvement is in the second half. I can't for the life of me think of a way of looping through a list until the functions output is constant. I thought of recursion, but I didn't understand it. This is what I came up with, and I'd like to see how I can improve it because it's sloppy and ugly.import UIKitfunc primeFact(tree: [Int]) -> Array<Int> { var newTree = tree for element in newTree{ for divisor in 2..<element{ if element%divisor == 0{ newTree = newTree.filter { $0 != element} newTree+=[(element/divisor),divisor] break } } } return newTree}var initial = primeFact(tree: [992])var temp = [Int]()while true { if primeFact(tree: initial) == initial{ break } temp = primeFact(tree: initial) initial = temp}print(primeFact(tree: initial))
Prime Factorisation in Swift
primes;swift;iteration
null
_unix.21107
If I: dd if=/dev/cdrom of=cdrom.isothen I will always get the exact same, bit-by-bitly same image that is the same as the original CDROM? Or are there any methods that prevents copying all the bits from the CDROM? Asking for archiving old games on old CDROMS
If I dd a CDROM, then I always get the exact copy of the CDROM?
dd;archive;data cd
No, dd can be not sufficient. As examples:If you have a multi-track cd-rom with data and audio track mixed, using dd you will copy only the first data session.Many old video-games cd (on Play-Station 1) use as copy-protection some fake session on the cd. You have to replicate them to obtain a working cd.I successfully used cdparanoia to backup quite all my old game cds.
_softwareengineering.214821
I'm currently trying to figure out the best techniques for organizing GUI view hierarchies, that is dividing a window into several panels which are in turn divided into other components.I've given a look to the Composite Design Pattern, but I don't know if I can find better alternatives, so I'd appreciate to know if using the Composite is a good idea, or it would be better looking for some other techniques.I'm currently developing in Java Swing, but I don't think that the framework or the language can have a great impact on this.Any help will be appreciated.---------EDIT------------I was currently developing a frame containing three labels, one button and a text field. At the button pressed, the content inside the text field would be searched, and the results written inside the three labels. One of my typical structure would be the following:MainWindow | Main panel | Panel with text field and labels. | Panel with search buttonNow, as the title explains, I was looking for a suitable way of organizing both the MainPanel and the other two panels.But here came problems, since I'm not sure whether organizing them like attributes or storing inside some data structure (i.e. LinkedList or something like this).Anyway, I don't really think that both my solution are really good, so I'm wondering if there are really better approaches for facing this kind of problems.Hope it helps
What are the best ways to organize view hierarchies in GUI interfaces?
design patterns;gui
null
_unix.15353
How can I list the number of connections per client on the FORWARD chain of an OpenWRT router? I know how to list the number of connections per IP address on the router:netstat -ntu | tail -n +3 | # list open TCP and UDP connectionsawk '{print $5}' | cut -d: -f1 | # extract client IP addressessort | uniq -c | sort -nr # show number of occurrences and sort by itI want to do the same with connections that are going through the router's FORWARD chain.
Find connections per ip on an OpenWRT router?
openwrt;routing
If I understand your question correctly (which is always dubious with your questions), this isn't possible. Forwarding doesn't keep any state: the router receives a packet, analyses it, sends it onwards to its next destination, and forgets what the packet was. You can count or log packets, but you can't keep track of connections at that level.It would make sense to count current NAT connections. All the connections that the netfilter subsystem keeps track of are listed in /proc/net/ip_conntrack. You can extract the client address withsed -ne 's/^.*src=\([^ ]*\).*/\1/p' /proc/net/ip_conntrack
_unix.122865
I'm setting up a Raspberry Pi as a proxy access point which accesses the internet via my USB tethered smartphone and is connected to my Windows PC via Ethernet. The internet works fine on the Pi, but I can't get my computer to connect to the Pi as it should. This is my computer's ipconfig when wired up to the Pi: Ethernet adapter Local Area Connection 4: Connection-specific DNS Suffix . : Link-local IPv6 Address . . . . . : fe80::1d6b:1514:ccb5:28cc%23 IPv4 Address. . . . . . . . . . . : 169.254.123.199 Subnet Mask . . . . . . . . . . . : 255.255.0.0 Default Gateway . . . . . . . . . : Ethernet adapter Ethernet: Connection-specific DNS Suffix . : Link-local IPv6 Address . . . . . : fe80::c0e:bb47:359a:cf33%13 Autoconfiguration IPv4 Address. . : 169.254.207.51 Subnet Mask . . . . . . . . . . . : 255.255.0.0 Default Gateway . . . . . . . . . : And here is my /etc/network/interfaces file on the Pi. auto loiface lo inet loopbackallow-hotplug usb0iface usb0 inet dhcpiface eth0 inet staticaddress 192.168.20.1network 192.168.20.0netmask 255.255.255.0broadcast 192.168.20.255gateway 192.168.20.1I've also tried it with this configuration, with the same results: iface eth0 inet staticaddress 192.168.42.200network 192.168.42.0netmask 255.255.255.0broadcast 192.168.42.255gateway 192.168.42.129192.168.42.129 is the gateway that my smartphone uses, for reference. Any help would be greatly appreciated.
Why won't my computer connect to my Linux access point?
networking;routing;raspberry pi;access point
null
_unix.344856
I've been working on the Ubuntu terminal for just a few days now and I need some help asap.I was wondering how I would take data that was in this format as a tab-delimited file:A red green B yellow orange C blue purple And to use commands like grep, paste, cut, cat, etc. to turn it into the following:A redB yellowC BlueA greenB orangeC purple
Take two columns in a tab delimited file and merge into one
text processing;command line
null
_cstheory.27274
This is a proof that I've gone back to many times over the last few years and while I can read it and easily verify the steps, it seems like it's a proof, where I will always essentially forget the details, i.e. if I read it today, I would struggle to write down a full proof tomorrow without actually spending quite a bit of effort. I'm talking about the proof that's e.g. in Goldreich's Foundations of Crypto book, which I believe is standard (I've never seen a different proof).As complexity theory is not my field, I would hope that people who are more experienced in the field could make sense of the proof by answering the following questions:What part of the proof are completely standard techniques?What part of the proof if any is a trick.The basic idea is easy: Given a weak one-way function, repeat it many times, so that any inverter of the repeated function needs to invert all the pieces. Dealing with the lack of independence in processing the components in the inversion is then the tricky part and I'm hoping that there's a way to split it up into standard arguments. At least understanding it in useful pieces that might be applicable elsewhere would be nice, if possible.
Understanding the weak-OWF exists -> OWF exists proof
cr.crypto security;one way function
null
_softwareengineering.333339
I have a code snippet in Java: int y = ++x * 5 / x-- + --x;So my confusion was since x--(postfix) has higher precedence than ++x(prefix) operator so x-- should be executed first then ++x.But a book states otherwise.Am I right in my thinking?
Operators precedence
operators;operator precedence
null
_unix.25236
I have VirtualBox instance of Centos 5. The screen size is quite small (800*600) and I'd like to increase it to 1280*1080. Under the Gnome preferences for Screen Resolution I only get the option for 600*800 or 640*480.I've tried editing my xorg.conf (based on this tutorial http://paulsiu.wordpress.com/2008/09/08/creating-and-managing-centos-virtual-machine-under-virtualbox/) but it doesn't seem to have made a difference. Here is a snippet from the edited section:Section Screen Identifier Screen0 Device Card0 Monitor Monitor0 DefaultDepth 24 SubSection Display Viewport 0 0 Depth 24 Modes 1280x800 EndSubSectionEndSectionDoes anyone know how to do this?
Increasing Screen Size/Resolution on a VirtualBox Instance of Centos
centos;virtualbox;display settings
A maximum resolution of 800x600 suggests that your X server inside the virtual machine is using the SVGA driver. SVGA is the highest resolution for which there is standard support; beyond that, you need a driver.VirtualBox emulates a graphics adapter that is specific to VirtualBox, it does not emulate a previously existing hardware component like most other subsystems. The guest additions include a driver for that adapter. Insert the guest additions CD from the VirtualBox device menu, then run the installation program. Log out, restart the X server (send Ctrl+Alt+Backspace from the VirtualBox menu), and you should have a screen resolution that matches your VirtualBox window. If you find that you still need manual tweaking of your xorg.conf, the manual has some pointers.There's a limit to how high you can get, due to the amount of memory you've allocated to the graphics adapter in the VirtualBox configuration. 8MB will give you up to 1600x1200 in 32 colors. Going beyond that is mostly useful if you use 3D.
_codereview.56193
I study data structures on coursera's course, and there is an extra exercise to create a Queue data structure.I created it:class Queue { Integer[] data; int head, tail; public Queue() { data = new Integer[2]; head = 0; tail = 0; } public int size() { return tail - head; } public boolean isEmpty() { return size() == 0; } private void realign() { java.util.Arrays.sort(data, new java.util.Comparator<Object>() { public int compare(Object o1, Object o2) { if (o1 == null) return 1; else if(o2 == null) return -1; else return 0; } }); tail -= head; head = 0; } private void resize() { if (tail == data.length && size() != data.length) { realign(); } if (data.length == size()) { int newLength = data.length * 2; //Duplication Integer[] newData = new Integer[newLength]; System.arraycopy(data, 0, newData, 0, data.length); data = newData; } else if (size() == data.length / 4 && size() != 0) { int newLength = data.length / 2; //Duplication Integer[] newData = new Integer[newLength]; System.arraycopy(data, 0, newData, 0, data.length); data = newData; } } public void enqueue(Integer item) { if (item == null) { throw new NullPointerException(); } resize(); data[tail] = item; tail++; return; } public int dequeue() { if (isEmpty()) { throw new java.util.NoSuchElementException(); } int res = data[head]; data[head] = null; head++; if (head == tail) { head = tail = 0; } return res; }}And a test suit for it:import org.junit.Test;import static org.junit.Assert.*;import java.util.*;public class QueueTest { @Test public void testQueueN() { Queue q = new Queue(); int N = 65; for(int i = 0; i < N; i++) { q.enqueue(i); } assertFalse(q.isEmpty()); for(int i = 0; i < N; i++) { assertEquals(i, q.dequeue()); assertEquals(N - i -1, q.size()); } assertTrue(q.isEmpty()); } @Test public void testEnDeEn() { Queue q = new Queue(); q.enqueue(2); assertEquals(1, q.size()); assertEquals(2, q.dequeue()); q.enqueue(5); assertEquals(5, q.dequeue()); } @Test(expected=java.util.NoSuchElementException.class) public void testDeOnEmpty() { Queue q = new Queue(); q.dequeue(); } @Test(expected=NullPointerException.class) public void testEnWithNull() { Queue q = new Queue(); q.enqueue(null); }}Please, review it from perspective of implementation and performance.Update: I improved(thanks to @Vogel612) this code a little bit. Improved version
Queue over resizable array implementation
java;queue
Learn from what already existsThere is an interface defined in java.util.Queue. It makes sense to implement it in your solution.If you don't need some of the methods of the interface, you can just throw new UnsupportedOperationException(); for the time being, and implement them later when you need them.The interface methods will guide your design in the right direction. For example, you implemented methods to add elements at the end and remove from the head, but you did not implement the converse: add at the head and remove from the end. Looking at the methods required by java.util.Queue, you would have spotted that.An existing interface like java.util.Queue also helps you use standard method naming. You called your methods enqueue and dequeue, when they would have been better as add and poll, respectively, following the standard.GeneralizeThe interface in java.util is defined with a type parameter, as Queue<E>. Indeed your implementation would work just fine with any kind of object, not only integers. You could follow the example and generalize your implementation so it can work with anything.If you don't know how to go about that, you can get ideas from an existing implementation, for example the PriorityQueue of OpenJDKAllow null valuesYour implementation doesn't allow null values. I suppose it's because that would break your realign method. If you think about it, that realign method is ugly. Suppose you have 1000 elements, if you call dequeue followed by enqueue, your call will move 999 elements one by one, and in a really awkward way with that comparator and sorting.Hint: realigning could be part of your resizing logic. Now you are resizing the array with:System.arraycopy(data, 0, newData, 0, data.length);But you can do better than that, using head and tail:System.arraycopy(data, head, newData, 0, tail - head);You could get rid of the ugly realign method and allow nulls by refactoring your code (see my solution at the bottom).Don't Repeat YourselfThis code appears twice:Integer[] newData = new Integer[newLength];System.arraycopy(data, 0, newData, 0, data.length);data = newData;This calls for a helper method:private void resize(int newLength) { Integer[] newData = new Integer[newLength]; System.arraycopy(data, head, newData, 0, tail - head); data = newData; tail -= head; head = 0;}ConstantsIt's good to use constants for clearer logic, and also to avoid duplication. For example:private static final int INITIAL_CAPACITY = 2;private static final int SHRINK_TRIGGER_RATIO = 4;private static final int RESIZE_FACTOR = 2;// ...public Queue() { data = new Integer[INITIAL_CAPACITY]; // ...}if (tail == data.length) { resize(data.length * RESIZE_FACTOR);}// ...if (size() == data.length / SHRINK_TRIGGER_RATIO) { resize(data.length / RESIZE_FACTOR);}When to resize?Your implementation is asymmetric: grow or shrink if needed when adding items. I haven't put a lot of thought into this, but it would seem to make sense to make this symmetric: grow if needed when adding items, shrink if needed when removing items.Unit test case namingFirst of all, it's great that you added many unit tests, covering most of your implementation and corner cases. But your test case names are not very good. It's good to make test case names long and descriptive, for example testDequeueOnEmpty instead of testDeOnEmpty, and testEnqueueDequeueEnqueue instead of testEnDeEn.Although it may seem trivial, I would also add a simple test for emptiness alone:@Testpublic void testIsEmpty() { Queue q = new Queue(); assertTrue(q.isEmpty()); q.enqueue(4); assertFalse(q.isEmpty()); q.dequeue(); assertTrue(q.isEmpty());}Suggested implementationHere's an alternative implementation based on yours that supports null values and without the ugly realign method:public class Queue { private static final int INITIAL_CAPACITY = 2; private static final int SHRINK_TRIGGER_RATIO = 4; private static final int RESIZE_FACTOR = 2; private Integer[] data; private int head, tail; public Queue() { data = new Integer[INITIAL_CAPACITY]; head = 0; tail = 0; } public int size() { return tail - head; } public boolean isEmpty() { return tail == head; } private void resize(int newLength) { Integer[] newData = new Integer[newLength]; System.arraycopy(data, head, newData, 0, tail - head); data = newData; tail -= head; head = 0; } public void enqueue(Integer item) { if (tail == data.length) { resize(data.length * RESIZE_FACTOR); } data[tail] = item; tail++; } public Integer dequeue() { if (isEmpty()) { throw new java.util.NoSuchElementException(); } Integer item = data[head]; data[head] = null; head++; if (head == tail) { head = tail = 0; } if (size() == data.length / SHRINK_TRIGGER_RATIO) { resize(data.length / RESIZE_FACTOR); } return item; }}
_unix.302970
I was just looking at this question and wrote a noddy program to demonstrate unsetenv() modifying /proc/pid/environ. To my surprise it has no effect!Here's what I did:#include <stdio.h>#include <unistd.h>#include <stdlib.h>int main(void){ printf(pid=%d\n, getpid()); printf(sleeping 10...\n); sleep(10); printf(unsetenv result: %d\n, unsetenv(WIBBLE)); printf(unset; sleeping 10 more...\n); sleep(10); return 0;}However, when I runWIBBLE=hello ./test_programthen I see WIBBLE in the environment both before and after the unsetenv() runs:# before the unsetenv()$ tr '\0' '\n' < /proc/498/environ | grep WIBBLEWIBBLE=hello# after the unsetenv()$ tr '\0' '\n' < /proc/498/environ | grep WIBBLEWIBBLE=helloWhy doesn't unsetenv() modify /proc/pid/environ?
Why doesn't unsetenv() modify /proc/pid/environ?
environment variables;glibc
When a program starts, it receives its environment as an array of pointers to some strings in the format var=value. On Linux, those are located at the bottom of the stack. At the very bottom, you have all the strings tucked one after the other (that's what's shown in /proc/pid/environ). And above you have an array of pointers (NULL terminated) to those strings (that's what goes into char *envp[] in your int main(int argc, char* argv[], char* envp[]), and the libc would generally initialise environ to).putenv()/setenv()/unsetenv(), do not modify those strings, they don't generally even modify the pointers. On some systems, those (strings and pointers) are read-only.While the libc will generally initialise char **environ to the address of the first pointer above, any modification of the environment (and those are for future execs), will generally cause a new array of pointers to be created and assigned to environ.If environ is initially [a,b,c,d,NULL], where a is a pointer to x=1, b to y=2, c to z=3, d to q=5, if you do a unsetenv(y), environ would have to become [a,c,d,NULL]. On systems where the initial array list is read-only, a new list would have to be allocated and assigned to environ and [a,c,d,NULL] stored in there. Upon the next unsetenv(), the list could be modified in place. Only if you did unsetenv(x) above could a list not be reallocated (environ could just be incremented to point to &envp[1]. I don't know if some libc implementations actually perform that optimisation).In anycase, there's no reason for the strings themselves stored at the bottom of the stack to be modified in any way. Even if an unsetenv() implementation was actually modifying the data initially received on the stack in-place, it would only modify the pointers, it wouldn't go all the trouble of also erasing the strings they point to. (that seems to be what the GNU libc does on Linux systems (with ELF executables at least), it does modify the list of pointers at envp in place as long as the number of environment variables doesn't increase.You can observe the behaviour using a program like:#include <sys/types.h>#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <string.h>extern char **environ;int main(int argc, char* argv[], char* envp[]) { char cmd[128]; int i; printf(envp: %p environ: %p\n, envp, environ); for (i = 0; envp[i]; i++) printf( envp[%d]: %p (%s)\n, i, envp[i], envp[i]);#define DO(x) x; puts(\nAfter #x \n); \ printf(envp: %p environ: %p\n, envp, environ); \ for (i = 0; environ[i]; i++) \ printf( environ[%d]: %p (%s)\n, i, environ[i], environ[i]) DO(unsetenv(a)); DO(setenv(b, xxx, 1)); DO(setenv(c, xxx, 1)); puts(\nAddress of heap and stack:); sprintf(cmd, grep -e stack -e heap /proc/%u/maps, getpid()); fflush(stdout); system(cmd);}On Linux with the GNU libc (same with klibc, musl libc or dietlibc except for the fact that they use mmapped anonymous memory instead of the heap for allocated memory), when run as env -i a=1 x=3 ./e, that gives (comments inline):envp: 0x7ffc2e7b3238 environ: 0x7ffc2e7b3238 envp[0]: 0x7ffc2e7b4fec (a=1) envp[1]: 0x7ffc2e7b4ff0 (x=3) # envp[1] is almost at the bottom of the stack. I lied above in that # there are more things like the path of the executable # environ initially points to the same pointer list as envpAfter unsetenv(a)envp: 0x7ffc2e7b3238 environ: 0x7ffc2e7b3238 environ[0]: 0x7ffc2e7b4ff0 (x=3) # here, unsetenv has reused the envp[] list and has not allocated a new # list. It has shifted the pointers though and not done the optimisation # I mention aboveAfter setenv(b, xxx, 1)envp: 0x7ffc2e7b3238 environ: 0x1bb3420 environ[0]: 0x7ffc2e7b4ff0 (x=3) environ[1]: 0x1bb3440 (b=xxx) # a new list has been allocated on the heap. (it could have reused the # slot freed by unsetenv() above but didn't, Solaris' version does). # the b=xxx string is also allocated on the heap.After setenv(c, xxx, 1)envp: 0x7ffc2e7b3238 environ: 0x1bb3490 environ[0]: 0x7ffc2e7b4ff0 (x=3) environ[1]: 0x1bb3440 (b=xxx) environ[2]: 0x1bb3420 (c=xxx)Address of heap and stack:01bb3000-01bd4000 rw-p 00000000 00:00 [heap]7ffc2e794000-7ffc2e7b5000 rw-p 00000000 00:00 0 [stack]On FreeBSD (11-rc1 here), a new list is allocated already upon unsetenv(). Not only that, but the strings themselves are being copied onto the heap as well so environ is completely disconnected from the envp[] that the program received on start-up after the first modification of the environment:envp: 0x7fffffffedd8 environ: 0x7fffffffedd8 envp[0]: 0x7fffffffef74 (x=2) envp[1]: 0x7fffffffef78 (a=1)After unsetenv(a)envp: 0x7fffffffedd8 environ: 0x800e24000 environ[0]: 0x800e15008 (x=2)After setenv(b, xxx, 1)envp: 0x7fffffffedd8 environ: 0x800e24000 environ[0]: 0x800e15018 (b=xxx) environ[1]: 0x800e15008 (x=2)After setenv(c, xxx, 1)envp: 0x7fffffffedd8 environ: 0x800e24000 environ[0]: 0x800e15020 (c=xxx) environ[1]: 0x800e15018 (b=xxx) environ[2]: 0x800e15008 (x=2)On Solaris (11 here), we see the optimisation mentioned above (where unsetenv(a) ends up being done with a environ++), the slot freed by unsetenv() being reused for b, but of course a new list of pointers has to be allocated upon the insertion of a new environment variable (c):envp: 0xfeffef6c environ: 0xfeffef6c envp[0]: 0xfeffefec (a=1) envp[1]: 0xfeffeff0 (x=2)After unsetenv(a)envp: 0xfeffef6c environ: 0xfeffef70 environ[0]: 0xfeffeff0 (x=2)After setenv(b, xxx, 1)envp: 0xfeffef6c environ: 0xfeffef6c environ[0]: 0x806145c (b=xxx) environ[1]: 0xfeffeff0 (x=2)After setenv(c, xxx, 1)envp: 0xfeffef6c environ: 0x8061c48 environ[0]: 0x8061474 (c=xxx) environ[1]: 0x806145c (b=xxx) environ[2]: 0xfeffeff0 (x=2)
_unix.139009
At the last boot, two USB devices were not powered:The Logitech G5 mouse works most of the time, but this time I had to plug it in (in the same motherboard USB port) three or four times before it would power up.The Wi-Fi USB dongle connected to the front panel which usually (not sure about always) does not get powered during boot.It seems the issue is power related, which is a bit of a mystery: All the USB devices work fine on Windows every time, my PSU is pretty beefy, and more importantly, I'd been running Arch Linux with the same hardware for months before this problem occurred. People have suggested at least disabling USB autosuspension, some old_scheme_first magic setting, disabling ehci_hcd and turning it off and on again, but with no explanation I'm reluctant to try fixing by accident. Does anyone know a well explained solution or some way to debug this in more detail? apropos -a usb log returns nothing, and it seems quite difficult to know which one of my 7+ USB devices is to blame.From dmesg of the last boot, in which both these devices were unpowered:usb 4-5: device descriptor read/64, error -110usb 4-5: new high-speed USB device number 5 using ehci-pciusb 4-5: device descriptor read/64, error -110usb 4-5: device descriptor read/64, error -110usb 4-5: new high-speed USB device number 6 using ehci-pciusb 4-5: device not accepting address 6, error -110usb 4-5: new high-speed USB device number 7 using ehci-pciusb 4-5: device not accepting address 7, error -110hub 4-0:1.0: unable to enumerate USB device on port 5usb 10-1: new full-speed USB device number 2 using uhci_hcdusb 10-1: device descriptor read/64, error -110usb 10-1: device descriptor read/64, error -110usb 10-1: new full-speed USB device number 3 using uhci_hcdusb 4-3: USB disconnect, device number 2usb 4-3: new high-speed USB device number 8 using ehci-pcihub 4-3:1.0: USB hub foundhub 4-3:1.0: 4 ports detectedusb 3-4: USB disconnect, device number 3usb 3-4: new high-speed USB device number 5 using ehci-pciusb 3-4: device not accepting address 5, error -71usb 4-5: new high-speed USB device number 10 using ehci-pcicfg80211: Calling CRDA to update world regulatory domainrtl8192cu: Chip version 0x11usb 4-3.1: new full-speed USB device number 11 using ehci-pcirtl8192cu: MAC address: e8:4e:06:14:7a:77rtl8192cu: Board Type 0rtl_usb: rx_max_size 15360, rx_urb_num 8, in_ep 1rtl8192cu: Loading firmware rtlwifi/rtl8192cufw_TMSC.binusbcore: registered new interface driver rtl8192cuieee80211 phy0: Selected rate control algorithm 'rtl_rc'rtlwifi: wireless switch is onsystemd-udevd[695]: renamed network interface wlan0 to wlp0s29f7u5rtl8192cu: MAC auto ON okay!input: Microsoft X-Box 360 pad as /devices/pci0000:00/0000:00:1d.7/usb4/4-3/4-3.1/4-3.1:1.0/input/input14usbcore: registered new interface driver xpadrtl8192cu: Tx queue select: 0x05usb 9-2: new full-speed USB device number 2 using uhci_hcdhidraw: raw HID events driver (C) Jiri Kosinausbcore: registered new interface driver usbhidusbhid: USB HID core driverinput: Logitech USB Gaming Mouse as /devices/pci0000:00/0000:00:1d.1/usb9/9-2/9-2:1.0/0003:046D:C041.0001/input/input15hid-generic 0003:046D:C041.0001: input,hidraw0: USB HID v1.11 Mouse [Logitech USB Gaming Mouse] on usb-0000:00:1d.1-2/input0hid-generic 0003:046D:C041.0002: hiddev0,hidraw1: USB HID v1.11 Device [Logitech USB Gaming Mouse] on usb-0000:00:1d.1-2/input1mousedev: PS/2 mouse device common for all miceIPv6: ADDRCONF(NETDEV_UP): wlp0s29f7u5: link is not readyusb 6-2: new full-speed USB device number 2 using uhci_hcdusb 6-2: not running at top speed; connect to a high speed hubusb-storage 6-2:1.0: USB Mass Storage device detectedscsi16 : usb-storage 6-2:1.0wlp0s29f7u5: authenticate with cc:33:bb:13:8a:f4wlp0s29f7u5: send auth to cc:33:bb:13:8a:f4 (try 1/3)wlp0s29f7u5: authenticatedwlp0s29f7u5: associate with cc:33:bb:13:8a:f4 (try 1/3)wlp0s29f7u5: RX AssocResp from cc:33:bb:13:8a:f4 (capab=0x431 status=0 aid=56)wlp0s29f7u5: associatedIPv6: ADDRCONF(NETDEV_CHANGE): wlp0s29f7u5: link becomes ready
USB error -110 (power exceeded) but works when reconnecting
arch linux;usb
null
_unix.386319
If I start ksh or mksh, my upwards arrow does nothing:$ ksh$ ^[[A^[[A^[[A^[[A^[[ABut it works with bash if I start bash and press the upwards arrow.$ bashdeveloper@1604:~$ ssh [email protected] -p 2223I have no history if I start ksh or mksh. I even set the $HISTFILE variable and still no history if I start a new shell. What can I do about it? Is it true that the Korn shell can't remember history between sessions while the bash shell can?If I like the Korn shell and I want a better and more extensive history, is it possible to use that functionality with ksh?
How to enable ksh command history between sessions
shell;ksh;mksh
null
_vi.12640
I just don't undstand the VIM help for pattern matching and substitution. I've tried.I have many lines of code, like so:G1 X139.164 Y115.348 E8.40357 ; perimeterG1 X138.903 Y115.845 E8.57778 ; perimeterG1 X136.919 Y119.355 E9.82896 ; perimeterG1 X135.204 Y125.148 F250 G1 X133.565 Y124.281 E11.75686 F250 I want to remove uppercase E and everything following it on each line - or truncate each line, beginning with the E.Things I've tried::%s/E\>//g:1,$/E\>\.//:%s/E\>\zs.*//Please help.
How to truncate every line after pattern
substitute
Your last attempt is almost correct. I would use this::%s/E.*//The OCD part of me would also want to remove any spaces before the E. That could be done with::%s/\s*E.*//The \> was causing your attempts to fail because by default numbers are considered part of the word. See :help \> and :help iskeyword for more info.The \zs isn't necessary in this case since you are trying to replace the entire search pattern. If you were to use it, you would want it in front of the E since you want to remove the E as well. The \zs would be useful if, for example, you only wanted to remove the E and everything after on lines starting with G2. Then you could do something like::%s/^G2.*\zs\s*E.*//
_codereview.44662
I have a list of opened nodes, with each step about 3000 nodes are opened and I want to put to the opened list only those nodes that are not already there. For now I'm just comparing each new one to all of the ones already in the opened list and only add it if it's not there. But that is around n*3000^2 comparisons for the nth step and makes the progress slower and slower each step. Is there a way to do it faster. Or at least is there a structure that would be better than ArrayList.This is part of the bigger code, but basically the method I use:public void addEverything() { List<gameState> list = current.neighbours; for (gameState state : list) { if (!isOpened(state)) { opened.add(state); } }}public boolean isOpened(gameState state) { for (int i = 0; i < opened.size(); i++) { if (state.isSame(opened.get(i))) return true; } return false;}As for the isSame() method from the gameState class, it just returns true when the two gameStates are considered the same.
Comparing list elements in an effective way
java;performance
Instead of implementing isSame implement equals and hashCode. After that you could use a HashSet (or LinkedHashSet if the order of elements is important). Set is a collection that contains no duplicate elements and inserting/searching is much faster than searching in a list.Set<GameState> opened = new LinkedHashSet<GameState>();public void addEverything() { List<GameState> list = current.neighbours; for (GameState state : list) { opened.add(state); }}If you need a list, you can convert it back after the loop:List<GameState> openedList = new ArrayList<GameState>(opened);See also: Overriding equals and hashCode in JavaAccording to the Java Code Conventions, class names in Java usually starts with uppercase letters.
_softwareengineering.161840
I am confronted with the problem of migrating a huge monolithic java web application towards a more service oriented approach. The application has grown for years from what it was originally desinged for and is still growing. That means a lot of changed customer requriements where development under time pressure with few concernce about code quality. That led to very very complex code structure (no modular packaging, a lot of complex inheritants, mix of functionality in classes and as good as no documentation).Now step by step funcionality shall be extracted and run as service.Replacement/Redevelopment is currently out of questions. So the code should be extraced and wrapped so it can be replaced later with a new cleaner version.The problem I now have to deal with is that it is really hard to identify the code that represents a functionality and extracting it without breaking other functionalities or even the whole application.Any ideas how I can approach this problem? I am open to everything.
Advise on How To migrate a huge monolithic java application towards something service-oriented
architecture;services;reverse engineering
null
_webmaster.25826
i have a problem with my site http://www.cyprusproperty-4sale.com/123456789.aspit looks OK in IE9 but not in Firefox, IE8 & IE7.Could you please help me with that?
Website looks OK in IE9, but not in Firefox, IE8 and IE7
website design
null
_webmaster.99998
Is this what is supposed to happen? If so, why?Here's an example (test code here):<script type=application/ld+json>{ @context: http://schema.org, @type: WebPage, @id: http://example.com/}</script><script type=application/ld+json>{ @context: http://schema.org, @type: BreadcrumbList, itemListElement:{ @type: ListItem, position: 1, item:{ @id: http://example.com/, name: Lecture 12: Graphs, networks, incidence matrices } }}</script>
When a WebPage (or similar type) uses an ID that matches a breadcrumb ID, why does the WebPage become part of the BreadcrumbList?
schema.org;google rich snippets tool;breadcrumbs;webpage
Yes, I think it makes sense that Googles SDTT does this. Its just a usability question if the WebPage item should be displayed as top-level item in addition; it doesnt affect the semantics.In the first script data block, you say that the WebPage has the URI http://example.com/. In the second script data block, you say that the value of the item property has the same URI, http://example.com/.Because these two items have the same URI, they have to be the same thing. You may want to use the breadcrumb property to make clear that the BreadcrumbList belongs to the WebPage:<script type=application/ld+json>{ @context: http://schema.org, @type: WebPage, @id: http://example.com/, breadcrumb: { @type: BreadcrumbList, itemListElement:{ @type: ListItem, position: 1, item:{ @id: http://example.com/, name: Lecture 12: Graphs, networks, incidence matrices } } }}</script>As you can see in the SDTT, the properties you provide for the item property will be displayed under the top-level WebPage item.(N.B.: Googles SDTT seems to be bugged for cases where different types get provided for the same URI.)
_unix.85034
I wanted to add mpd informations to my conky and therefore I created a script which role is to get the cover from ID3 tagsThis script is called using the {exec 'path'} commandMy probleme is that since I added this feature, my conky refuses to stand on his own :If I launch it from a terminal usingconky -c `path.conkyrc` &it will stop when closing the terminal. I tried using the -d option as wellI also tried to launch it at startup with a sh script run at startup : It works well at first but if I open a terminal, conky will close with the terminal i openned ... strangeremoving the call to {exec 'path'} solves everything so it is clearly the problem originFor the record, the script i am using is#!/bin/shMPD_MUSIC_PATH=/media/Media/MusicTMP_COVER_PATH=/tmp/mpd-track-coverexiftool -b -Picture $MPD_MUSIC_PATH/$(mpc --format %file% current) > $TMP_COVER_PATH &
{exec} cause Conky to stop
conky
The issue wasn't conky closing but it going behind everything, including the wallpaper.Changing the window settings solved the problem:own_window yesown_window_type normalown_window_transparent noown_window_argb_visual yesown_window_type normalown_window_class conky-semiown_window_hints undecorate,sticky,skip_taskbar,skip_pager,belowown_window_argb_value 128own_window_colour 000000
_codereview.79094
var saveUser = function(name, profile){ assert(typeof name === 'string') assert(profile instanceof Profile) return new bluebird.Promise(function(resolve, reject){ // async code saving user to DB })}Orvar saveUser = function(name, profile){ return new bluebird.Promise(function(resolve, reject){ try { assert(typeof name === 'string') assert(profile instanceof Profile) } catch(err){ return reject(err) } // async code saving user to DB })}Which way is better?It is good idea to catch validation errors and throw custom ValidationError instead?
Handling argument validation in JavaScript
javascript;validation;node.js;comparative review
null
_unix.43966
I'm using biosdevname on a CentOS 6.3 server to name my interfaces in a rational way. On our new Dell PowerEdge C6145, we have 2 embedded ports and two PCI cards with 4 ports each.On our other Dell 815 servers with a similar configuration, we get em1, em2, (and actually em3 and em4 on those), and then p1p1, p1p2, p1p3, p1p4, and p2p1, p2p2, p2p3, p2p4.For whatever reason this system gives 120 for the slot number rather than 1. Now, I can accept that it might not be slot one internally, but it's definitely also not the one hundred and twentieth.I updated to biosdevname 0.4.1 from Fedora Rawhide but am getting the same result.Since our puppet configuration is expecting the other names, this is a hassle. We can work around it, but I'd rather only do the workaround if there is a rational explanation either a bug needing a temporary fix, or something that I don't understand which makes the large number actually sensible.So, is there such a explanation?
biosdevname is giving me p120p1 instead of p1p1 -- is this correct?
networkcard
null
_unix.100888
I'm running Linux Mint Debian Edition with Update Pack 7. I'm trying to connect to a WPA enterprise network using TTLS and PAP, with no luck.The problem seems to be in authentication. Visually, NetworkManager keeps asking my password time after time. The password is correct and works both on Android, Ubuntu and ArchLinux Manjaro. I have seen it work on a LMDE UP6 before in which now also doesn't work (UP7).Here is the log I'm getting (with time removed for readability)NetworkManager[2641]: get_secret_flags: assertion `is_secret_prop (setting, secret_name, error)' failedNetworkManager[2641]: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) scheduled...NetworkManager[2641]: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) started...NetworkManager[2641]: <info> (wlan0): device state change: need-auth -> prepare (reason 'none') [60 40 0]NetworkManager[2641]: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) scheduled...NetworkManager[2641]: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) complete.NetworkManager[2641]: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) starting...NetworkManager[2641]: <info> (wlan0): device state change: prepare -> config (reason 'none') [40 50 0]NetworkManager[2641]: <info> Activation (wlan0/wireless): connection 'EduRoam CACert' has security, and secrets exist. No new secrets needed.NetworkManager[2641]: <info> Config: added 'ssid' value 'eduroam'NetworkManager[2641]: <info> Config: added 'scan_ssid' value '1'NetworkManager[2641]: <info> Config: added 'key_mgmt' value 'WPA-EAP'NetworkManager[2641]: <info> Config: added 'password' value '<omitted>'NetworkManager[2641]: <info> Config: added 'eap' value 'TTLS'NetworkManager[2641]: <info> Config: added 'fragment_size' value '1300'NetworkManager[2641]: <info> Config: added 'phase2' value 'auth=PAP'NetworkManager[2641]: <info> Config: added 'ca_path' value '/etc/ssl/certs'NetworkManager[2641]: <info> Config: added 'ca_path2' value '/etc/ssl/certs'NetworkManager[2641]: <info> Config: added 'ca_cert' value '/home/darkhogg/.eduroam/ca.pem'NetworkManager[2641]: <info> Config: added 'identity' value '[email protected]'NetworkManager[2641]: <info> Config: added 'anonymous_identity' value '[email protected]'NetworkManager[2641]: <info> Config: added 'bgscan' value 'simple:30:-45:300'NetworkManager[2641]: <info> Config: added 'proactive_key_caching' value '1'NetworkManager[2641]: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) complete.NetworkManager[2641]: <info> Config: set interface ap_scan to 1NetworkManager[2641]: <info> (wlan0): supplicant interface state: disconnected -> scanningNetworkManager[2641]: <info> (wlan0): supplicant interface state: scanning -> authenticatingNetworkManager[2641]: <info> (wlan0): supplicant interface state: authenticating -> associatedNetworkManager[2641]: <info> (wlan0): supplicant interface state: associated -> disconnectedNetworkManager[2641]: <info> (wlan0): supplicant interface state: disconnected -> scanningNetworkManager[2641]: <info> (wlan0): supplicant interface state: scanning -> authenticatingNetworkManager[2641]: <info> (wlan0): supplicant interface state: authenticating -> associatingNetworkManager[2641]: <info> (wlan0): supplicant interface state: associating -> associatedNetworkManager[2641]: <info> (wlan0): supplicant interface state: associated -> disconnectedNetworkManager[2641]: <info> (wlan0): supplicant interface state: disconnected -> scanningNetworkManager[2641]: <info> (wlan0): supplicant interface state: scanning -> authenticatingNetworkManager[2641]: <info> (wlan0): supplicant interface state: authenticating -> associatingNetworkManager[2641]: <info> (wlan0): supplicant interface state: associating -> associatedNetworkManager[2641]: <info> (wlan0): supplicant interface state: associated -> disconnectedNetworkManager[2641]: <info> (wlan0): supplicant interface state: disconnected -> scanningNetworkManager[2641]: <info> (wlan0): supplicant interface state: scanning -> authenticatingNetworkManager[2641]: <info> (wlan0): supplicant interface state: authenticating -> associatingNetworkManager[2641]: <info> (wlan0): supplicant interface state: associating -> associatedNetworkManager[2641]: <info> (wlan0): supplicant interface state: associated -> disconnectedNetworkManager[2641]: <info> (wlan0): supplicant interface state: disconnected -> scanningNetworkManager[2641]: <warn> Activation (wlan0/wireless): association took too long.NetworkManager[2641]: <info> (wlan0): device state change: config -> need-auth (reason 'none') [50 60 0]NetworkManager[2641]: <warn> Activation (wlan0/wireless): asking for new secretsNetworkManager[2641]: <info> (wlan0): supplicant interface state: scanning -> authenticatingNetworkManager[2641]: <info> (wlan0): supplicant interface state: authenticating -> disconnectedNetworkManager[2641]: <warn> Couldn't disconnect supplicant interface: This interface is not connected.The network is eduroam, used by my university to provide WiFi access. More information can be found here. In particular, I'm from Spain, in Univerdad Complutense de Madrid. This may be relevant as I understand every university implements it more or less as they want.I have unsuccessfully followed multiple tutorials involving wpa_supplicant scripts and configuration, and the result is always the same: Authentication fails and it asks my password again on a loop.
NetworkManager failing to authenticate to WPA-EAP using TTLS and PAP in LMDE
debian;linux mint;networkmanager;wpa supplicant
Recent updates to wpa_supplicant have apparently solved this problem. (I am no longer using Linux Mint. I have since switched to Manjaro, which uses wpa_supplicant 2.1 at the time of this writing.)
_cstheory.25850
I'm trying to understand the connections between a few different concepts fundamental to dependent type theory.Dependent functions ($\Pi$-types)Including non-dependent functions ($A \rightarrow B$)Dependent pairs ($\Sigma$-types)Including non-dependent products ($A \times B$)Coproducts ($A + B$)Homotopy Type Theory says the following about $\Sigma$s and $\Pi$s:[ $\Sigma$ ] is called a dependent pair type, or $\Sigma$-type, because in set theory it corresponds to an indexed sum (in the sense of a coproduct or disjoint union) over a given type.The name $\Pi$-type is used because this type can also be regarded as the cartesian product over a given type(I don't think I fully understand this point)In a non-dependent setting I'm accustomed to calling coproducts sums because the number of inhabitants of a coproduct is the sum of its constituent types' inhabitants - $|A+B| = |A| + |B|$. Likewise I call dependent pairs products because $|(A,B)| = |A| \cdot |B|$. Also functions can be called exponentials - $|A \rightarrow B| = |B|^{|A|}$!Now for the question.Why does it make sense in Type Theory to use $\Sigma$ for products and $\Pi$ for exponentials? It seems like everything is shifted between non-dependent and dependent types.sums approximately correspond to dependent coproductsproducts approximately correspond to dependent sumsexponentials approximately correspond to dependent productswhat about dependent exponentials?What's the deeper connection?
Dependent Sums and Products
type theory;dependent type
I think what's confusing you is that $A \times B$ is both a product and a coproduct:It is the product of two factors, namely $A$ and $B$.It is the coproduct of $A$-many copies of $B$.Once you realize this, you will see that we can obtain $A \times B$ as both a $\sum$ and a $\prod$:Take $P : \mathtt{bool} \to \mathsf{Type}$ where $P(\mathtt{false}) = A$ and $P(\mathtt{true}) = B$. Then$$\sum_{b : \mathtt{bool}} P(b) \simeq A + B$$and$$\prod_{b : \mathtt{bool}} P(b) \simeq A \times B$$Take $Q : A \to \mathsf{Type}$ where $P(x) = B$ for all $x : A$. Then$$\sum_{x : A} Q(x) \simeq A \times B$$and$$\prod_{x : A} Q(x) \simeq (A \to B)$$We should therefore not pay attention to $A \times B$ when deciding on a good naming scheme for these two constructs.The dependent exponential is exactly a dependent product.
_codereview.122686
#include <iostream>#include <string>#include <algorithm>#include <time.h>int faults = 0;int hangman(); int i = hangman();int main(){srand(time(NULL));while (i == 1){ std::string words[7]{Alpha, Cornwall, Crepuscular, Blind, Steroid, Plunder, Talisman}; std::string word = words[rand() % 7]; int n; n = rand() % word.length(); char underscore = '_'; char checkAnswer = word.at(n); word.at(n) = underscore; std::cout << word; char answer; std::cin >> answer; if (answer == checkAnswer){ std::cout << Correct!; } else{ faults++; hangman(); }}} int hangman(){ if (faults == 0){ std::cout << |---------------------- << std::endl; std::cout << | | << std::endl; std::cout << | << std::endl; std::cout << | << std::endl; std::cout << | << std::endl; return 1;}else if (faults == 1){ std::cout << |---------------------- << std::endl; std::cout << | | << std::endl; std::cout << | O << std::endl; std::cout << | << std::endl; std::cout<<| << std::endl; return 1;}else if (faults == 2){ std::cout << |---------------------- << std::endl; std::cout << | |<<std::endl; std::cout << | O << std::endl; std::cout << | | << std::endl; std::cout << | << std::endl; ; return 1;}else if (faults == 3){ std::cout << |---------------------- << std::endl; std::cout << | | << std::endl; std::cout << | O << std::endl; std::cout << | | << std::endl; std::cout << | / << std::endl; ; return 1;}else if (faults == 4){ std::cout << |---------------------- << std::endl; std::cout << | | << std::endl; std::cout << | O << std::endl; std::cout << | | << std::endl; std::cout << | X << std::endl; return 1;}else if (faults == 5){ std::cout << |---------------------- << std::endl; std::cout << | | << std::endl; std::cout << | O << std::endl; std::cout << | | << std::endl; std::cout << | X << std::endl; std::cout << - << std::endl; return 1;}else if (faults == 6){ std::cout << |---------------------- << std::endl; std::cout << | | << std::endl; std::cout << | O << std::endl; std::cout << | | << std::endl; std::cout << | X << std::endl; std::cout << - - << std::endl; return 1;}else if (faults == 7){ std::cout << |---------------------- << std::endl; std::cout << | | << std::endl; std::cout << | O << std::endl; std::cout << | | << std::endl; std::cout << | X << std::endl; std::cout << - - << std::endl; std::cout << Dead.Dead.The hangman is dead!You lose! << std::endl; return 0;}}
Console HangMan game
c++;hangman
null
_softwareengineering.348670
I have 2 third-party providers, both do a similar function(this could be logging, messaging, etc), and both have events that the client must subscribe to.I want to know what design patterns or methods I need so that I could swap out one with the other without changing any code. My main concern is how to abstract the events. One provider will have certain events that needs wiring up to handlers with certain signatures, and the other will have its own.Should I have some kind of dictionary of delegates that is exposed via a field on the interface?I use C#.
How to swap between 2 third-party providers when both implement different events?
c#;design patterns;event handling
null
_softwareengineering.170334
Now, in c++ '...' became a first class operator.In speech, how do you pronounce it?So far I've heard:dot dot dottriple dotellipsisrelated: Is it OK to replace ... with ellipsis in writing?e.g. The ellipsis operator expands the packEDIT (clarification): We are all aware that '...' as a punctuation mark is indeed called ellipsis. But in the context of C++ we don't pronounce the names of the punctuation mark. For example, the '&' operator, depends on the context is pronounced as 'and', 'bitwise and', 'address of', 'logical and' (when && is used), or 'reference'. It is rarely pronounced as 'ampersand'.In speeches, I've a feeling that 'dot dot dot' is used more often. For example: http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Variadic-Templates-are-Funadic (an excellent presentation about variadic templates).On the other hand, 'dot dot dot' is awkward hard to pronouce ('d' and 't' are both pronounce with the tongue).Can we pronounce it 'unpack'?
How do you pronounce the '...' operator
c++;c++11
in the context of C++ we don't pronounce the names of the punctuation markI disagree with your premise. In my experience people refer to the meaning of the symbol when that's what they're talking about, but use the name when they need to refer to the symbol itself:I see your problem: you're using bitwise AND instead of logical AND -- you need to use two ampersands for logical AND.The trouble with ... in C and C++ is that it's not an ellipsis character. I'm sure it's meant to represent an ellipsis, and its meaning is similar to what an ellipsis represents in English, but I'd guess that most compilers would choke on a real ellipsis (). That surely wasn't an issue in the old days, when ASCII and EBCDIC were all there was and ellipses could only be simulated with .... These days, though, you might cause some confusion if you said:I see your problem: that function should take variadic arguments -- add an ellipsis to the declaration.To be really precise in such a situation, you should say dot dot dot. If you're just talking about existing code, though, it'd be fine to say elipsis:You can see from the ellipsis that foo(int bar, ...) takes a variable number of arguments.Can we pronounce it 'unpack'?Only if you don't care about being understood, or if you plan to preface your comments with I'm going to pronounce 'dot-dot-dot' as 'unpack.'
_webmaster.53987
I'm looking to register a few more domains for my company, I have my-company.com at the moment, but now require my-company.com.au and my-company.nl and others, for example .ie.I'm running through my options and wondering what is the best.Duplicate all the content on the .com package and make a replica at the other domainsBuy the other domains but do a 301 redirect back to the .com domainCreate a full new website with different content for the new domains, thus having no text duplicationWe currently sell all over the world so would like to raise our search rankings in various countries. Can this be done by buying the domain in the country, and if so, how will the above methods affect our search rankings?Any other suggestions are welcome!
What are the search engine affects of registering the same domain on multiple top level domains?
seo;google;search engines;bing;yahoo
null
_codereview.125532
I have written a LaTeX package to visualize B+ trees.The main purpose is to provide a simple but powerful package which provides a convenient interface.However, this is my first LaTeX package and I would also like to know where I can do better.So I'd like to get reviews from these two points of view:Simplicity of the implementation and convenience of the interfaceImprovements/Criticism from a LaTeX point of viewHere's my package code and an example of how to use it.btreevis.sty\NeedsTeXFormat{LaTeX2e}\ProvidesPackage{btreevis}[2015/06/24 B+ Tree Visualization Package]%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PACKAGES%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\RequirePackage{tikz} \RequirePackage{ifthen} \RequirePackage{etoolbox}%\RequirePackage{calc}%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LIBRARIES%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TikZ\usetikzlibrary{arrows, matrix, calc}%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% COUNTERS (GLOBAL)%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% The number of pointers per node (often referred to as m in B+ tree context)\newcount\noOfPointersPerNode%% Used to number pointers and keys consecutively inside a B+ tree node\newcount\pointerCounter%% Used in the connect macros to know where the arrows have to start\newcount\pointerNumber%% Used in the connect macros to hold the number of the current (source) node to% connect to\newcount\nodeNumber%% Used in the connect macros to hold the number of the next (destination) node% to connect to\newcount\nextNodeNumber%% Used temporarily in the connect macros\newcount\tempCounter%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DEFAULT STYLES (GLOBAL)%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Default style of a B+ tree node. Provides all important properties a B+ tree% node should have such that the resulting B^+ tree looks beautiful.% May be overridden by an own style.\tikzstyle{BTreeNodeDefault} = [ draw, matrix, matrix of nodes, % must be used; otherwise the matrix content generation does not work ampersand replacement=\&, % if inner sep != 0, there is a border around the matrix of nodes inner sep = 0, nodes = { draw, rectangle, % better readability; otherwise node border and content do overlay inner sep = 1mm, % workaround to make nodes look better; % better in the sense that all nodes in the matrix of nodes have the same % height and depth independent of their content text height = \heightof{ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmopqrstuvwxyz0123456789}, text depth = \depthof{ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmopqrstuvwxyz0123456789}, % scaling factor of nodes; nodes have to be scaled independently from the % whole tikzpicture (at least in some cases) scale = 1 }]% Default style of a B+ tree.% May be overriden by own styles but has all important properties.\tikzstyle{BTreeDefault} = [ % scaling factor of the whole picture scale = 1, % must be used; otherwise the tree environment draws its own connecting arrows edge from parent/.style = {}]%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% MACROS (PACKAGE INTERNAL)%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Helper macro (only for package internal usage).% Creates the content for two nodes (to be used in a matrix of nodes).% One with a given content (a key node) and one corresponding pointer node% (left of the key node). The naming of both key and pointer nodes is done% automatically. This macro is used to generate the content of the matrix of% nodes for a B+ tree node in the macro \CreateBTreeNode[4].%% Be careful when modifying this macros: Because the content just generates a% part of a matrix no blank lines should be inserted in this macros (this may% causes strange errors when compiling).%% Naming schema: l#3-n#4-k#2 for search keys and l#3-n#4-p#2 for pointers.%% Arguments:% #1 ... The value to be inserted into the node. If empty an empty node is% generated.% #2 ... The pointer/key number, e.g. if #2 is 2, the pointer nodes third% part of the name is '-p2' and the value nodes third part of the name% is '-k2'% #3 ... The level number, e.g. if #3 is 3, the nodes first part of the name% is 'l3'% #4 ... The node number, e.g. if #4 is 4, the nodes second part of the name% is '-n4'%% Example of the usage:% \@create@key@matrix@node{3}{1}{2}{1}%% (Never needed because it is more of an internal macro to draw the B+ tree).% Generates two nodes: the left (pointer) node named 'l2-n1-p1' containing no% value and a node right of it named 'l2-n1-k1' containing the value '3'. So% if the initial matrix was an empty matrix of nodes [], the subsequent matrix% contains two nodes [| 3].%%\newcommand{\@create@key@matrix@node}[4] {% % empty pointer node (left) |(l#3-n#4-p#2) [fill=gray!50]| {\vphantom{1}} \&% % check presence of argument #1 \ifx&#1&% % empty key node (right) |(l#3-n#4-k#2)| {\hphantom{1}} \&% \else% % key node with value (right) |(l#3-n#4-k#2)| {#1} \&% \fi%}%%%% Helper macro (only for package internal usage).% Creates the content for an empty node (to be used in a matrix of nodes).% The naming of this node is done automatically. This macro is used to generate% the content of the matrix of nodes for a B+ tree node in the macro% \CreateBTreeNode[4].%% Naming schema: l#2-n#3-p#1%% Arguments: % #1 ... The pointer number, e.g. if #1 is 2, the pointer nodes third part of% the name is '-p2'% #2 ... The level number, e.g. if #2 is 3, the nodes first part of the name% is 'l3'% #3 ... The node number, e.g. if #3 is 4, the nodes second part of the name% is '-n4'%% Example of the usage:% \@create@key@matrix@node{5}{2}{1}%% (Never needed because it is more of an internal macro to draw the B+ tree).% Generates a single empty node named 'l2-n1-p5' (which is in most cases is% the rightmost part of a B+ tree node). So if the initial matrix is% [| 3 | 5], the subsequent matrix is [| 3 | 5 |].%%\newcommand{\@create@pointer@matrix@node}[3] {% % empty pointer node |(l#2-n#3-p#1) [fill=gray!50]| {\vphantom{1}} \&%}%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% MACROS (GLOBAL)%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Just a setter to set the \noOfPointersPerNode variable.%% Arguments:% #1 ... The value to be assigned to \noOfPointersPerNode%% Example of the usage:% \setNoOfPoinersPerNode{4}%% Sets \noOfPointersPerNode to 4.%%\newcommand{\SetNoOfPoinersPerNode}[1]{% \noOfPointersPerNode = #1%}%%%% Generates the content of a complete B+ tree node (matrix of nodes) for given% values supplied as comma-separated list. This generated content is stored into% a variable supplied as argument. If the comma-separated list contains less% than (\noOfPointersPerNode - 1) elements, the remaining nodes are left empty% but are generated to be visualized. Hence, if \noOfPointersPerNode is set to 4% and only a list of 2 elements is supplied as key list, the node contains of% the two keys and two empty nodes ([| key1 | key2 | | |]).% The other way round, if the comma-separated list contains more than% \noOfPointersPerNode elements, the oversupplied elements are simply ignored% and thus are not contained in the matrix of nodes.% The generated matrix of nodes is not named because this is not needed to% connect the nodes. However, the nodes inside this matrix of nodes are named% (see macros \@create@key@matrix@node and \@create@key@matrix@node).%% Todo: Encapsulate the part inside the \whiledo and \ifthenelse, respectively,% into an own macros (if possible; may not be possible because of the% expanding of the arguments/counters). By now this is more or less% duplicated code.%% Arguments:% #1 ... The level of the node (used for naming in called macros)% #2 ... Number of the node of level #1% #3 ... Values as comma-separated list% #4 ... Name of the variable the B+ tree node content is stored to%% Example of the usage:% \SetNoOfPoinersPerNode{4}% \CreateBTreeNode{0}{1}{{5}}{\levelZeroNodeOne}% \node[BTreeNodeDefault] {\levelZeroNodeOne};%% The first line set the number of pointers per node to a maximum of 4. The% second line generates the content of the matrix of nodes, stored in% \levelZeroNodeOne. \levelZeroNodeOne afterwards contains of a matrix of% nodes [| 5 | | |]. So \levelZeroNodeOne can be used as content for the% subsequent call of node, which then has to be a matrix of nodes% (\levelZeroNodeOne is a matrix content separated by & and \\).%%\newcommand{\CreateBTreeNode}[4] {% % initialize pointer counter (is then incremented for each pointer generated) \pointerCounter = 1% % initialize variable the node content is stored into (set it empty) \let#4\empty% % for each value of the comma-separated list \foreach \x in #3 {% % only insert until the maximum number of pointers per node is reached \ifthenelse{\not{\the\pointerCounter < \noOfPointersPerNode}}{\breakforeach}{% % expand first two arguments upfront (necessary) \edef\tmpexpand{{\x}{\the\pointerCounter}}% % the \@create@key@matrix@node macros generates a part of the whole node % matrix and this content is then appended here % also the arguments are expanded accordingly \expandafter\gappto\expandafter#4\expandafter{% \expandafter\@create@key@matrix@node\tmpexpand{#1}{#2}% }% % increment pointer counter \global\advance\pointerCounter by 1% }% }% % here the remaining empty key nodes of the matrix are produced (if there are % less keys than (number of pointers per node - 1) supplied) \whiledo{\the\pointerCounter < \noOfPointersPerNode}{% % expand first two arguments upfront (necessary) \edef\tmpexpand{{}{\the\pointerCounter}}% % the \@create@key@matrix@node macros generates a part of the whole node % matrix and this content is then appended here (in essence, here the empty % nodes are generated and appended). % also the arguments are expanded accordingly \expandafter\gappto\expandafter#4\expandafter{% \expandafter\@create@key@matrix@node\tmpexpand{#1}{#2}% }% % increment pointer counter \global\advance\pointerCounter by 1% }% % here the last pointer node is appended to the matrix \expandafter\gappto\expandafter#4\expandafter{% \expandafter\@create@pointer@matrix@node% \expandafter{\the\pointerCounter}{#1}{#2}% }% % append the line of the matrix of nodes is finished (with \\) \gappto#4{\\}%}%%%% Connects all pointers of a given node on a given (source) level to all its% children of a given (destination level) with an arrow (solid). This only works% if the nodes of the B+ tree are named like mentioned in the% \@create@key@matrix@node and \@create@pointer@matrix@node, respectively.% % Arguments:% #1 ... Number of source (tree) level% #2 ... Number of source node (parent node)% #3 ... Number of destination (tree) level% #4 ... Number of (child) nodes to be connected with parent% #5 ... Number of the first (child) node to be connected with parent%% Example of the usage:% \ConnectBTreeNodes{0}{1}{1}{2}{1}%% Generates arrows from node 1 of the top level (0) to 2 child nodes of the% subsequent level (1) of the tree. We have 2 children on the subsequent level% and the first node to be connect (on the subsequent level) is node 1. A node% contains 3 search keys, hence it has 4 pointers. The incoming arrows on any% node on the subsequent level arrives at the north center of the node.%%\newcommand{\ConnectBTreeNodes}[5] {% % initialize temporary counter (just used to iterate) \tempCounter = 0% % draw a vertical arrow (connect) from the source node to each child node \whiledo{\the\tempCounter < #4} {% % compute current node number: % temporary counter + the number of the node to start with \nodeNumber = \the\tempCounter% \advance\nodeNumber by #5% % compute current pointer number: temporary counter + 1 \pointerNumber = \the\tempCounter% \advance\pointerNumber by 1% % draw an arrow from south of the computed pointer number to middle of the % north of the node with the previously computed number \draw[->, >=stealth] (l#1-n#2-p\the\pointerNumber.south) -- ($(l#3-n\the\nodeNumber-p1.north)!0.5!(l#3-n\the\nodeNumber-p\the\noOfPointersPerNode.north)$);% % increment temporary counter \global\advance\tempCounter by 1% }%}%%%% Connects all leaf nodes of a given (leaf) level with a dotted arrow. The arrow% starts at .east of the rightmost node inside the leaf and ends at .west% of the leftmost node inside the next leaf. This only works if the nodes of the% B+ tree are named like mentioned in in the \@create@key@matrix@node and% \@create@pointer@matrix@node, respectively.%% Arguments:% #1 ... Number of the (tree) level of the leaves% #2 ... Number of leaf nodes to be connected%% Example of the usage:% \ConnectBTreeLeaves{2}{5}%% Generates arrows between 5 nodes of the leaf level (here 2).%%\newcommand{\ConnectBTreeLeaves}[2] {% % initialize node number (used to iterate) \nodeNumber = 1% % draw horizontal, dotted arrows (connect) between all leaf nodes % arrows are drawn from left to right \whiledo{\the\nodeNumber < #2} {% % compute next node number: current node number + 1 \nextNodeNumber = \nodeNumber% \advance\nextNodeNumber by 1% % draw a dotted arrow between two leaf nodes (from left to right) \draw[->, >=stealth, dotted] (l#1-n\the\nodeNumber-p\the\noOfPointersPerNode.east) -- (l#1-n\the\nextNodeNumber-p1.west);% % increment node number \global\advance\nodeNumber by 1% }%}%\endinputexample-simple.tex\documentclass{article}% Use btreevis package\usepackage{btreevis}\begin{document} \begin{center} \begin{tikzpicture}[ % Use default B+ tree style BTreeDefault, % Sibling and level distance for 1 level. % These have to be adapted for almost every B+ tree if % - the number of pointers per node and/or % - the matrix content and/or % - the number of levels and/or % - the number of children % changes. level 1/.style = { sibling distance = 8em, level distance = 6em } ] % Set number of pointers per node (this should be done always upfront) \SetNoOfPoinersPerNode{4} % Generate content of (tree) level 0 (root level) \CreateBTreeNode{0}{1}{{3, 9}}{\levelZeroNodeOne} % Generate content of (tree) level 1 \CreateBTreeNode{1}{1}{{1, 2}}{\levelOneNodeOne} \CreateBTreeNode{1}{2}{{3, 4, 6}}{\levelOneNodeTwo} \CreateBTreeNode{1}{3}{{9, 10}}{\levelOneNodeThree} % Generate B+ tree nodes using the previously generated node contents \node[BTreeNodeDefault] {\levelZeroNodeOne} child { node[BTreeNodeDefault] {\levelOneNodeOne} } child { node[BTreeNodeDefault] {\levelOneNodeTwo} } child { node[BTreeNodeDefault] {\levelOneNodeThree} }; % Connect B+ tree nodes (vertical, solid arrows) \ConnectBTreeNodes{0}{1}{1}{3}{1} % Connect B+ tree leaf nodes (horizontal, dotted arrows) \ConnectBTreeLeaves{1}{3} \end{tikzpicture} \end{center}\end{document}If necessary, I could also provide an advanced example, but the code is quite long (although most of the lines are explanatory comments).Simple example (code above):Advanced example (as mentioned, I could provide the code for this too):
B+ Tree Visualization in LaTeX/TikZ
tree;graphics;tex
null
_unix.239922
I'm having trouble connecting to my xpra server. I've installed Xpra version v0.14.10, on my raspberry pi 2 which running on Raspbian Jessie Distro. I connect to my RPi through putty with X11 forwarding Enabled, and X display location being: localhost:0:0I run the command:sudo xpra start :1337 --start-child=xterm --bind-tcp=0.0.0.0:1337on the server side (RPi) and on my windows I try connecting to the xpra server using the Xpra Launcher. My settings are:Mode: TCPEncoding: H.264Quality: AutoSpeed: Auto192.168.0.24 : 1337No passwordWhen I try to connect it outputs an error in red:server requested disconnect: server error (error accepting new connection)Has anyone encountered this problem before? How do you fix it? Thank you.
Xpra server error (error accepting new connection)
linux;x11;xpra
null
_unix.194380
I came across the following line of code (source):IFS=$'\r'I'm not quite sure how to interpret that line (specifically why there is a $ character before the newline). It seems like the special variable named IFS is being set to a variable named the newline character?What does this line do, and what part of Bash allows this?
What does $'\r' mean?
bash
null
_webmaster.28104
Possible Duplicate:What Forum Software should I use? I am looking to start a new forum, with a traditional forum layout (like webhostingtalk, for example).In this space, I know phpBB and SMF are strong contenders. I do not know for sure the names of other great forum software that might exist...My most important need is that it should be easy to modify the display area, at the least, without having to dig too much into the core. Drupal excels in this area with its templating system, but the forum module doesn't look like the forum interface most people are used to...It would be a great plus if the software has alternative Captchas like question based or invisible Captcha. If it doesn't, I would like to be able to code it in without much trouble (that is, the software exposes a good API)
Which free PHP based forum is the easiest to extend or customize?
forum;free;open source
null
_codereview.20476
I am curious to know if there is a faster, better, and more efficient way to accomplish this program that acquires employee information: <?phpsession_start();//require 'functions.php';//require 'DB.php';$employeeID = $_SESSION['employeeID'];$clockIn = $_GET['clockIn'];$clockOut = $_GET['clockOut'];$timeToday = date(g:i a);$dateToday = date(m/d/y);$jobDescription = $_GET['jobDesc'];$equipType = $_GET['equipTypeRan'];$unitNumber = $_GET['unitNumber'];$unitHours = $_GET['unitHours'];if (isset($clockIn)) { echo You clocked in at: . $timeToday . on . $dateToday; try { $conn = new PDO('mysql:host=localhost;dbname=timecard', 'username', 'password'); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->prepare('INSERT INTO timeRecords (employeeID, date, timeIn) VALUES (:employeeID, :dateToday, :timeIn)'); $stmt->execute(array(':employeeID' => $_SESSION['employeeID'], ':dateToday' => $dateToday, ':timeIn' => $timeToday)); } catch(PDOException $e){ echo'ERROR: ' . $e->getMessage(); } $conn = null;} else if (isset($clockOut)) { try { $conn = new PDO('mysql:host=localhost;dbname=timecard', 'username', 'password'); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->prepare('UPDATE `timeRecords` SET `timeOut`= :timeOut WHERE `date`= :dateToday AND `employeeID`= :employeeID'); $stmt->execute(array(':employeeID' => $_SESSION['employeeID'],':dateToday' => $dateToday, ':timeOut' => $timeToday)); $stmt = $conn->prepare('SELECT `timeIn` FROM `timeRecords` WHERE `date`= :dateToday AND `employeeID` = :employeeID'); $stmt->execute(array(':employeeID' => $_SESSION['employeeID'], ':dateToday' => $dateToday)); $stmt->setFetchMode(PDO::FETCH_BOTH); $results = $stmt->fetch(); $timeInDB = $results[0]; } catch(PDOException $e){ echo'ERROR: ' . $e->getMessage(); } $time_one = new DateTime($timeInDB); $time_two = new DateTime($timeToday); $difference = $time_one->diff($time_two); echo You clocked in at: . $timeInDB . <br>; echo You clocked out at: . $timeToday . <br>; echo $difference->format('Total working time %h hours %i minutes');}else {try{ $conn = new PDO('mysql:host=localhost;dbname=timecard', 'username', 'password'); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->prepare(SELECT COUNT(*) FROM timeRecords WHERE `timeOut` IS NULL AND `employeeID`= :employeeID AND `date`= :dateToday); $stmt->execute(array(':employeeID' => $employeeID, ':dateToday' => $dateToday)); } catch(PDOException $e){ echo'ERROR: ' . $e->getMessage(); }if($stmt->fetchColumn() > 0){ try{ $conn = new PDO('mysql:host=localhost;dbname=timecard', 'username', 'password'); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->prepare('UPDATE `timeRecords` SET `jobDescription`= :jobDescription, `equipType`= :equipType, `unitNumber`= :unitNumber, `unitHours`= :unitHours, `timeOut`= :timeOut WHERE `employeeID`= :employeeID AND `date`= :dateToday AND `timeOut` IS NULL'); $stmt->execute(array(':employeeID' => $employeeID, ':timeOut' => $timeToday, ':dateToday' => $dateToday, ':jobDescription' => $jobDescription, ':equipType' => $equipType, ':unitNumber' => $unitNumber, ':unitHours' => $unitHours)); $stmt = $conn->prepare('INSERT INTO timeRecords (employeeID, date, timeIn) VALUES (:employeeID, :dateToday, :timeIn)'); $stmt ->execute(array(':employeeID' => $employeeID, ':dateToday'=> $dateToday, ':timeIn' => $timeToday)); } catch(PDOException $e){ echo'ERROR: ' . $e->getMessage(); } echo There was an update;} else { echo There was no Match;} require 'summary.php';}?>
Acquiring employee information
php;mysql;pdo
null
_unix.326634
I was trying to make a bootable Ubuntu stick. However, even though the stick could easily handle the ISO size, in the writing the size of the 2GB stick was exceeded. Now I want to clear off the stick so it can be used. I am not succeeding! Please note that I cannot even dismount the stick. I would like to avoid reformatting. Transcript follows:me-user@my-site:/media$ dfFilesystem 1K-blocks Used Available Use% Mounted onudev 1714260 4 1714256 1% /devtmpfs 353072 1180 351892 1% /run/dev/sda5 467009128 21992532 421270856 5% /none 4 0 4 0% /sys/fs/cgroupnone 5120 0 5120 0% /run/locknone 1765356 172 1765184 1% /run/shmnone 102400 28 102372 1% /run/user/home/me-user/.Private 467009128 21992532 421270856 5% /home/me-user/dev/sdb2 2346 0 2346 0% /media/me-user/Ubuntu 16.04.1 LTS amd64me-user@my-site:/media$ ls -a me-user/U*. ..me-user@my-site:/media$ ls -a me-user. .. Ubuntu 16.04.1 LTS amd64me-user@my-site:/media$ sudo rm -rf /media/me-user/U*rm: cannot remove /media/me-user/Ubuntu 16.04.1 LTS amd64: Device or resource busyme-user@my-site:/media$ lsof +D /media/me-userme-user@my-site:/media$ sudo umount /dev/sdb2me-user@my-site:/media$ dfFilesystem 1K-blocks Used Available Use% Mounted onudev 1714260 4 1714256 1% /devtmpfs 353072 1180 351892 1% /run/dev/sda5 467009128 21992576 421270812 5% /none 4 0 4 0% /sys/fs/cgroupnone 5120 0 5120 0% /run/locknone 1765356 172 1765184 1% /run/shmnone 102400 28 102372 1% /run/user/home/me-user/.Private 467009128 21992576 421270812 5% /home/me-user/dev/sdb2 2346 0 2346 0% /media/me-user/Ubuntu 16.04.1 LTS amd64me-user@my-site:/media$ cdme-user@my-site:~$ sudo rmdir /media/linton/U*rmdir: failed to remove /media/me-user/Ubuntu 16.04.1 LTS amd64: Device or resource busyLater.... following comment suggesting using fdisk:me-user@my-site:~$ sudo fdisk /dev/sdbWARNING: GPT (GUID Partition Table) detected on '/dev/sdb'! The util fdisk doesn't support GPT. Use GNU Parted.So, I am now trying to use GNU Parted to format the disk, but I have to go to school on this.Many days later...I solved my problem. What I wanted to do was to make the USB usable again and I did not need to save existing data. What caused the problem was trying to make an Ubuntu live disk using 2GB stick. Although both the ISO and the final product are well under 2GB, somehow the installation depends on having at least 2GB free space!? My 2GB USB stick did not have enough space and sw was damaged.fdisk and other MBR programs did not work because the installation of the Ubuntu Live ISO also changed the stick to the GPT format. I never was able to get gdisk (which does understand GPT) to solve the problem and I don't know why. I had problems with read-only and other errors while using it. Also, it demands system reboots to finalize the changes.After many hours of research and learning more about disk formatting, I discovered the disk manager in Gnome which I was able to run in Ubuntu XFCE, Mint Cinnamon, and Korora XFCE from the application menu or text search. Doing this with its graphical interface described here for example. Using this utility, it was so easy that I don't think it necessary to lay it all out here. Basically, I reformatted the drive in MBR format and then created a single FAT partition. (Gdisk is very confusing for this in that it does not offer FAT among its 30+ choices by that name.) That was it!
How do I delete files on my USB stick and dismount it?
mount;usb;rm
The solution was to use the Disk Manager utility. See above in edited problem description.
_unix.151880
I want to sync a directory between two systems. To make it more interesting the syncing must only be done in one direction, i.e.:if a file is deleted in the source directory, it must also be deleted in the destination, if it was previously transfereddeleted files in the destination directory must not be deleted in the sourcepartially transfered files (e.g. because of network problems) must be finished on the next syncnew files in the source directory must be transfered to the destinationdeleted files in the destination directory must not be re-transferedThat means the source system has basically a master role, except that deleted files in the destination will not be forced back.Both Linux systems have rsync/ssh/scp available.New files in the source directory are created in such a way that one can use their mtime to detect them, e.g.:if mtime(file) > date-of-last-sync then: it is a new file that needs to be transferedAlso, existing files are not changed in the source directory, i.e. the sync does not need to check for differences in already (completely) transfered files.
One-way-sync a directory, but leave deleted files deleted on the destination
rsync;synchronization
null
_datascience.13778
My situation is that I have many thousands of devices which each have their own specific LSTM model for anomaly prediction. These devices behave wildly differently so I don't think there is any way to have a shared global model, unfortunately. Periodically I will update each device model with the new data from the device - so maybe once per day I will load an additional daily batch of readings and use the properties of stateful LSTM training to update the model.Each of these models is very small, containing at most 10-20 thousand readings in their whole history, and fitting into memory on even a modest GPU. Training from scratch is relatively quick, and updating a single batch should be even more so, as typically there are only 48 new readings/day (30 minute intervals), but going as high as 1440 readings/day.My question is - what is an optimal architecture for handling all of these models and updates? They are all independent and small, so I don't see a need for anything distributed, but there are so many of them that I am unsure how to proceed. I am thinking that perhaps using something like an AWS 'large' GPU cluster, with each GPU loading a serialized model from the DB, updating with a new batch of data, and writing back could work - however, I suspect that having to repeatedly compile the models will be a blocker and that being able to do only 4 at a time is woefully insufficient. Alternatively, it may be possible to do the 'initial' training on some kind of powerful GPU rig, and then do the batch updates on CPU's, which would make it easier to run many instances in parallel. Is this an example of where Spark might be useful? Any advice is appreciated - including 'your premise is absurd, why would you do this!' This is only one of many ways available to do the anomaly detection, so if the architecture implementation is unfeasible, I will abandon the LSTM's altogether and try something simpler.
Scalable training/updating of many small LSTM models
machine learning;apache spark;scalability;parallel
null
_softwareengineering.81951
For example, I'm changing color pallettes throughout a site i'm coding and would love it if i could reference that color somehow instead of replacing the hex value for every item. I know the following doesn't work but i'd like something similar.color1 = red;color2 = blue;color3 = green;h1 {color: color1;background-color: color2;}h2 {color: color2;background-color: color3;}
Can you reference one data value by a name throughout a stylesheet?
css
This is among several missing features in CSS. You can still get this functionality, but you need to move outside the box. Take a look at Less CSS. It's really quite nice.
_softwareengineering.341857
I have a problem with design a few simple classes. I want a four classes: one recursively delete directory, another copy one dir to another same way. Another two does same as first two but they add observable behaviour: calculates few parameters like estimated time or percents of doing operation and fire up observers.What is the best way of design them?the simpliest way to do this this scheme: but I have problems with violation of DRY principle in code that calculates percents and other values in observable class. I may be move that code to abstract class but i need to extends that abstract class and appropriate Copy or Delete class, this is forbidden in javaI have decision to implement strategy pattern but this uml and my code still smell.what is the best solution here, where are my mistakes?
Problem with OOP design
java;design patterns;object oriented;uml
You have some alternatives. Each one has benefits and downsides. There's no magic formula to programming; you have to make choices based on your best guess about what will work.Make it part of the base classYou could implement it as part of the base Action class.public abstract class Action { private List<Listener> listeners; public Action() { this.listeners = new ArrayList<Listener>(); } public void addListener(Listener l) { this.listeners.add(l); } // You'll need a remove listener function, too. public final void performAction() { for(Listener l: this.listeners) { l.notify(/* args here*/); } this.innerPerformAction(); } protected abstract void innerPerformAction();}The main benefit to this is that every Action can have listeners. No one can inistantiate one that isn't capable of notifying another piece of code.Implement a wrapperComposition might be a good fit here.public class ObservableAction extends Action { private List<Listener> listeners; private Action action; public ObservableAction(Action a) { this.listeners = new ArrayList<Listener>(); this.action = a; } public void addListener(Listener l) { this.listeners.add(l); } public void performAction() { // Do observing here this.action.performAction(); }}Then,Action deleteAction = new ObservableAction(new DeleteAction());This one makes more sense if you need more targetted observations, in only some places. Or if you can't modify Action at all (e.g., it's in a third party library).