id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_unix.60375 | I have an alix board on which I have installed debian4alix (sqeeze). After using it for a while I noticed that the write performance of the board was pretty low. I ran the following test:dd count=100 bs=1M if=/dev/urandom of=/var/www/cgrid/testThis yielded the following:100+0 records in100+0 records out104857600 bytes (105 MB) copied, 328.903 s, 319 kB/sThis is the same speed I get when running the test on the compact flash card that the OS is installed on or on a flash disk. I had tested the flash disk performance on a linux desktop PC and achieved speeds around 15.3 MB/s using the same tests. My read speed on the alix board is around 9MB/s (tested with hdparm -t)I would like to know if the slow write speeds I am receiving is a result of the operating system ( since it is not running directly off the compact flash card but off a ramdisk) or from the embedded hardware solution being really slow. | Alix Board write performance | debian;performance;embedded;storage | I am quite certain the board is slower then desktop in terms hardware. But urandom make it worse.The board is using a 500MHz CPU vs 2-3GHz desktop CPU. With if=/dev/urandom, your test is more about how fast the system can handle urandom. You are comparing CPU performance, not I/O.Additionally, if the board only have 256M of ram, the OS may start swapping when creating 100M ram disk file. If that happen, it will have a big hit on test result. Maybe test with 50M file.Use if=/dev/zeroDon't use if=/dev/urandom. It is a very costly call for this test. Instead use if=/dev/zero.Test 1 - Write 100M to diskFollowing is my test result from a virtual machine, also writing 100M.if=/dev/zerojohn@U64D211:~$ time dd count=100 bs=1M if=/dev/zero of=test100+0 records in100+0 records out104857600 bytes (105 MB) copied, 0.493612 s, 212 MB/sreal 0m0.540suser 0m0.020ssys 0m0.516sif=/dev/urandomjohn@U64D211:~$ rm testjohn@U64D211:~$ time dd count=100 bs=1M if=/dev/urandom of=test100+0 records in100+0 records out104857600 bytes (105 MB) copied, 10.8723 s, 9.6 MB/sreal 0m10.909suser 0m0.004ssys 0m10.893sjohn@U64D211:~$ Test 2 - Write 100M to /dev/nullTo show how costly is urandom, lets write to /dev/null, so no writing to disk.if=/dev/zerojohn@U64D211:~$ time dd count=100 bs=1M if=/dev/zero of=/dev/null100+0 records in100+0 records out104857600 bytes (105 MB) copied, 0.0240906 s, 4.4 GB/sreal 0m0.061suser 0m0.012ssys 0m0.052sif=/dev/urandomjohn@U64D211:~$ time dd count=100 bs=1M if=/dev/urandom of=/dev/null100+0 records in100+0 records out104857600 bytes (105 MB) copied, 10.4979 s, 10.0 MB/sreal 0m10.555suser 0m0.024ssys 0m10.513sSo when writing to /dev/null, almost 99% of time is spent by urandom system call.PS1: VM has 4G of ram.PS2: File caching do/may have affect the test result to some extend, but the difference between the if option is so huge that it is safe to ignore caching factor. And the effect should apply to both cases anyway.PS3: I did not average out the test results. But I did run each multiple times with very similar result. |
_softwareengineering.154080 | We are crawling and downloading lots of companies' PDFs and trying to pick out the ones that are Annual Reports. Such reports can be downloaded from most companies' investor-relations pages.The PDFs are scanned and the database is populated with, among other things, the:TitleContents (full text)Page countWord countOrientationFirst lineUsing this data we are checking for the obvious phrases such as:Annual reportFinancial statementQuarterly reportInterim reportThen recording the frequency of these phrases and others. So far we have around 350,000 PDFs to scan and a training set of 4,000 documents that have been manually classified as either a report or not.We are experimenting with a number of different approaches including Bayesian classifiers and weighting the different factors available. We are building the classifier in Ruby. My question is: if you were thinking about this problem, where would you start? | How to identify a PDF classification problem? | algorithms;ruby | I think you should match phrase in first few (say 500 words) as normally these report contains information whether they are quarterly or annual in first few pages only(like 1Q2012, FY2012 etc). Along with it you can have words which should not be there in annual report.Much simpler would be to figure out if report is annual or not from the site from where you are downloading this report, so while downloading/crawling only look for this information on the site itself. |
_unix.280917 | I am running Xubuntu and have several programs automatically starting when the computer powers up. All the programs starting at once is causing me issues with having the programs talk to each other. Instead, I would like to stage the starting of each program with program A starting first, then five seconds later program B starts and so on. How do I do this? | How to delay a program from starting on boot up - Xubuntu | startup;xubuntu | I would implement it like this (probably not an Xubuntu friendly way, but should work):create a startup script which will start all required program, and make that script the only auto-started program with Xubuntu tools.Script can look like this:#!/bin/shprogram1 &sleep 5program2 &sleep 5program3 &Or like this, which will look better if you have multiple programs to launch:#!/bin/shPROGS=( program1 args program3 program2 # ...)for prog in ${PROGS[@]}; do ${prog} & # no quotes here, because we want to support args sleep 5done |
_softwareengineering.149970 | I feel that I am good at writing code in bits and pieces, but my designs really suck. The question is, how do I improve my designs - and in turn become a better designer?I think schools and colleges do a good job of teaching people how to become good at mathematical problem solving, but let's admit the fact that most applications created at school are generally around 1000 - 2000 lines long, which means that it is mostly an academic exercise which doesn't reflect the complexity of real world software - on the order of a few hundred thousand to millions of lines of code. This is where I believe that even projects like topcoder / project euler also won't be of much help, they might sharpen your mathematical problem solving ability - but you might become an academic programmer; someone who is more interested in the nice, clean stuff, who is utterly un-interested in the day to day mundane and hairy stuff that most application programmers deal with.So my question is how do I improve my design skills? That is, the ability to design small/medium scale applications that will go into a few thousand of lines of code? How can I learn design skills that will help me build a better html editor kit, or some graphics program like gimp? | I can write code... but can't design well. Any suggestions? | design;skills | The only way to become really good at something is to try, fail spectacularly, try again, fail again a little less than before, and over time develop the experience to recognize what causes your failures so that you can manage potential failure situations later on. This is as true of learning to play a musical instrument, drive a car, or earn some serious PWN-age in your favourite first person shooter, as it is of learning any aspect of software development.There are no real shortcuts, but there are things you can do to avoid having problems get out of hand while you are gaining experience. Identify a good mentor. There is nothing better than being able to talk about your issues with someone who has already paid their dues. Guidance is a great way to help fast-track learning.Read, read some more, practice what you've been reading, and repeat for the entire lifetime of your career. I've been doing this stuff for more than 20 years, and I still get a kick out learning something new every day. Learn not just about up front design, but also emergent design, testing, best practices, processes and methodologies. All have varying degrees of impact on how your designs will emerge, take shape, and more importantly, how they last over time.Find time to tinker. Either get involved with a skunkwork project through your workplace, or practice on your own time. This goes hand-in-hand with your reading, by putting your new knowledge into practice, and seeing how such things will work. This is also the stuff that makes for a good discussion with your mentor.Get involved with something technical outside of your workplace. This could be a project, or a forum. Something that will allow you to test out your theories and ideas outside of your immediate circle of peers in order to maintain a fresh perspective on things.Be patient. Recognize that earning experience takes time, and learn to accept that you need to back off for a while in order to learn why and where you have failed.Keep a diary or a blog of your tasks, your thoughts, your failures and your successes. This isn't strictly necessary, however I have found that it can be of great benefit to you to see how you have developed over time, how your skills have grown and your thoughts have changed. I come back to my own journals every few months and look at the stuff I wrote 4-5 years ago. It's a real eye-opener discovering just how much I'd learned in that time. It's also a reminder that I got things wrong from time to time. It's a healthy reminder that helps me improve. |
_cs.57309 | Standard (right) regular grammars have three kinds of rules:A <- A <- aA <- a BThis is OK for a theoretical point of view, but a big inconvenience to be usable in practice. A practical regular grammar should allow us to use commodity operators (|,*,+,?,.,(,)), character sets and group multiple rules in a single one. For example, the following regular grammar describes fractional numbers:start <- digit+ dot digit* | digit* dot digit+digit <- [0-9]dot <- '.'The question is, what restrictions must be applied to RHS non-terminals to keep this grammars regular (if it is possible at all)?NOTEQ - Why regular grammars instead of regular expressions?A - Regular expressions are OK for simple languages, but they are write-only for more complex ones. On the other hand, well written extended regular grammars are allot more readable and maintainable and allows us to extend them with captures and rule actions easily. | Can an (extended) regular grammar have multiple nonterminals in its RHS? | regular languages;formal grammars;regular expressions | null |
_unix.222778 | I have 2 machines running on Linux. One has ssh2 configured SOURCE and another has ssh1 configured DESTINATION. How do I generate a key pair in SOURCE whose public key can be understood by DESTINATION? Ideally I need to generate a SSH1 key pair using my installed ssh-keygen in a SOURCE. | How to generate SSH1 key using ssh-keygen for SSH2 | ssh keygen | Generate v1/v2 SSH keys with ssh-keygen -t rsa1 or ssh-keygen -t rsa. Then you can copy your key from SOURCE to DESTINATION (and vice-versa) with ssh-copy-id. |
_unix.27428 | I came across the following command:sudo chown `id -u` /somedirand I wonder: what is the meaning of the ` symbol. I noticed for instance that while the command above works well, the one below does not:sudo chown 'id -u' /somedir | What does ` (backquote/backtick) mean in commands? | shell;quoting | This is a backtick. Backtick is not a quotation sign, it has a very special meaning. Everything you type between backticks is evaluated (executed) by the shell before the main command (like chown in your examples), and the output of that execution is used by that command, just as if you'd type that output at that place in the command line.So, what sudo chown `id -u` /somedireffectively runs (depending on your user ID) is:sudo chown 1000 /somedir \ \ \ \ \ \ \ `-- the second argument to chown (target directory) \ \ `-- your user ID, which is the output of id -u command \ `-- chown command (change ownership of file/directory) `-- the run as root command; everything after this is run with root privilegesHave a look at this question to learn why, in many situations, it is not a good idea to use backticks. |
_unix.134040 | I developed one webcam server using my Raspberry Pi and Logitech webcam and Motion library. I'm able to view the stream by using Raspberry Pi's IP. If I use an IP camera instead of a normal webcam, how can I access the stream. Any ideas? | Raspberry Pi webcam server streaming via an IP? | raspberry pi;raspbian;camera;motion | I guess it depends on cameras. In the past, I have successfully done what OP asks by using cameras streaming H.264 over RTP, controlled by RTSP. In order to do this, an RTP client is required in order to access the camera and get a hold of the stream. I have used live555. My first try was with openRTSP from CLI. |
_softwareengineering.143578 | I am Localizing my php application. I have a dilemma on choosing best method to accomplish the same.Method 1: Currently am storing words to be localized in an array in a php file<?php$values = array ( 'welcome' => 'bienvenida' ); ?>I am using a function to extract and return each word according to requirementMethod 2: Should I use a txt file that stores string of the same?<?php$welcome = 'bienvenida'; ?>My question is which is a better method, in terms of speed and effort to develop the same and why?Edit: I would like to know which method out of two is faster in responding and why would that be? also, any improvement on the above code would be appreciated!! | Localization in php, best practice or approach? | php;localization | null |
_codereview.32842 | Wouldn't it be better to always pass parameters by reference to avoid creating unnecessary copies? #include <iostream>void deliver(const std::string& message){ std::cout << message;}void say(const std::string message){ std::cout << message;}int main(){ std::string message = Hello World; deliver(message); /* VS */ say(message); return 0;}If not, why not?Because I'm really starting to think references and pointers are useless.I've been coding in C++ for a year and a half and never even once had to use a reference or pointer.I've made countless programs and just finished making my biggest one ever, a 5000 lines game, divided in 28 separate files without using any of them. | Passing parameters by reference | c++;reference | Generally, the order of what you want to pass by looks like this for user-defined classes (ignoring C++11, for the moment):Pass by const&. This should be the default way of passingparameters. Pass by &. If you need to modify the parameter for whatever reason, thenyou'll need to pass a reference or pointer to it. However, you should prefer references to pointers (explained below).Pass by value. Unless you really need to make a copy of the value, there's not much reason to pass by value compared to passing by const&. However, if you're going to be making a copy of the parameter in the function body either way, then you may want to simply pass by value in the first place.For a good example of when explicit pass by value makes sense, see the copy-and-swap idiom.However, this is muddied by a number of considerations:Is the class small? Does it only encapsulate a few (simple) data members? For example, something like a std::pair. In this case, it may actually be better to just pass by value.For fundamental data types (int, char, double, and so on), it's better to simply pass by value. There's no performance benefit to passing by reference, and in fact, it can often be slower.With move semantics in C++11, this advice changes considerably. We now have an extra possibility: pass by rvalue reference (&&). Passing by value and using std::move then becomes a distinct possibility, especially when we want to be explicit about ownership. You may want to read this Stackoverflow post for a bit more information. Dave Abrahms (one of the principle authors of boost) has also written about this topic.I haven't mentioned pointers at all until now. Really, the only difference between references and pointers is that references cannot be null. Sticking to references means that you eliminate a whole host of possible bugs to do with dereferencing null pointers. In modern C++, passing by pointer is rare. In fact, it should always be wrapped up in a stack allocated class that deals with the ownership semantics and eliminates the possibility of resource leaks (say, unique_ptr or shared_ptr). These are then passed by one of the ways mentioned above.Finally, one must use pass by reference or (smart) pointer when using dynamic dispatch - that is, when dealing with inheritance.This post may be far more than you ever wanted to know, but the answer is effectively it depends. Deciding how to pass a parameter requires some actual thought, but boils down to some (subset) of the following considerations:Is it a primitive data type or a class encapsulating only a few primitive datatypes?Does it encapsulate some resource? If so, after the call, who do I want to own the resource?Do I need to modify it in the function I'm passing it to? If so, can I rewrite the function in some way so that I don't have to, as this often makes it more difficult to understand the program.Is inheritance involved? Do I want to be able to pass a derived class where a base class parameter is involved?Am I going to simply make a copy of the parameter in the function body? If so, perhaps passing by value is the best idea (again, see the copy and swap idiom).Should I provide overloads so I can have the option of passing a const reference vs passing an rvalue reference?What will give me the best performance? What is easiest to reason about and maintain?(Note: I realise this isn't really a code review as such. If this is too off topic, feel free to remove it). |
_scicomp.23872 | In order to numerically solve the following differential equation:\begin{equation} \text{Fr}\{f\} := v(k)\dfrac{\partial f(z,k)}{\partial z} - F(z) \dfrac{\partial f(z,k)}{\partial k} = -\dfrac{f-f_0}{\tau}\end{equation}I have used the finite volume method, and have discretized the left hand side to:\begin{equation}\text{Fr}'\{f\} := v(k_j)\Delta k \Bigg[ f(z_{i+},k_j) - f(z_{i-},k_j) \Bigg] - F(z_i)\Delta z \Bigg[ f(z_{i},k_{j+}) - f(z_{i},k_{j-}) \Bigg] \end{equation} for every box.The so-called flux averaging approximation,\begin{align} & f(z_{i+},k_j) = \dfrac{f(z_i,k_j)+f(z_{i+1},k_j)}{2} \\ & f(z_{i-},k_j) = \dfrac{f(z_i,k_j)+f(z_{i-1},k_j)}{2}\end{align}will lead to instability especially if the flux term is weak.This could be avoided by applying the upwind scheme. In this case:\begin{equation} f(z_{i+},k_j) = \begin{cases}f(z_{i},k_j) & v(k_j)>0 \\f(z_{i+1},k_j) & v(k_j)<0\end{cases}\end{equation}\begin{equation} f(z_{i-},k_j) = \begin{cases}f(z_{i-1},k_j) & v(k_j)>0 \\f(z_{i},k_j) & v(k_j)<0\end{cases}\end{equation}I have implemented the above upwinding method, and my results seem accurate for very small values of $F(z_i)$ throughout the system.However, when $F(z_i)$ gets large, the obtained results lose accuracy and deviate from the correct result.The reason to this deviation, I guess, is that the analytical solution to $\text{Fr}\{f\}=0$ is an exponential function. Since the equations are linearly discretized, the discretization cannot follow the large exponential changes accurately.Do you have any idea for increasing the accuracy of the above discretization while holding on to unconditional stability? | High order unconditionally stable discretization for a scalar hyperbolic PDE | pde;finite volume;discretization;hyperbolic pde | null |
_unix.386996 | I am in the process of writing a bash script that will make a POST request to a remote server every time a new file is created in a directory. I use RSYNC to sync several directories to a main directory. The main directory is then being watched by inotifywait which will trigger a script execution when it detects new files. The problem is the way RSYNC is creating the files I read here Rsync temporary file extension that RSYNC uses mktemp which creates file names like .filesynced.x12fj1 but will then rename them to filesynced after it has finished copying.So in my inotifywait bash script I am getting the filenames of the temp files not the filename after it has been renamed. I am wondering if someone can point me in the right direction so that I can get the filename after it has been moved and renamed.#!/bin/bashinotifywait -m -q -e close_write /edi-files | while read path action file; do echo The file '$file' appeared in directory '$path' via '$action' # send contents of $file to api endpoint. doneCRON JOB:*/1 * * * * rsync -avz --no-perms --no-o --no-g --remove-source-files /home/dir3/upload/ /home/dir2/upload/ /home/dir1/upload/ /edi-files/CURRENT OUTPUT:The file '.xxxxxxx1.ATM.8I2mrS' appeared in directory '/edi-files/' via 'CLOSE_WRITE,CLOSE'The file '.xxxxxxx2.ATM.MnIMPP' appeared in directory '/edi-files/' via 'CLOSE_WRITE,CLOSE'The file '.xxxxxxx3.txt.3FSceN' appeared in directory '/edi-files/' via 'CLOSE_WRITE,CLOSE'The file '.xxxxxxx4.txt.GoIDCK' appeared in directory '/edi-files/' via 'CLOSE_WRITE,CLOSE' | inotifywait and rsync is printing temporary file names | bash;rsync;inotify | null |
_scicomp.8481 | I'm a huge advocate of test-driven development in scientific computing. It's utility in practice is just staggering, and really alleviates the classic troubles that code developers know. However, there are inherent difficulties in testing scientific codes that aren't encountered in general programming, so TDD texts aren't terribly useful as tutorials. For example:In general you don't know an exact answer for a given complex problem a priori, so how can you write a test?The degree of parallelism changes; I recently encountered a bug where using MPI tasks as a multiple of 3 would fail, but a multiple of 2 worked. Additionally, common testing frameworks don't seem very MPI-friendly due to the very nature of MPI -- you have to re-execute a test binary to alter the number of tasks.Scientific codes often have a lot of tightly coupled, interdependent and interchangeable parts. We've all seen the legacy code, and we know how tempting it is to forgo good design and use global variables.Often a numerical method may be an experiment, or the coder doesn't fully understand how it works and is trying to understand it, so anticipating results is impossible.Some examples of tests that I write for scientific code:For time integrators, use a simple ODE with an exact solution, and test that your integrator solves it to within a given accuracy, and the order of accuracy is correct by testing with varying step sizes.Zero-stability tests: check that a method with 0 boundary/initial conditions remains at 0. Interpolation tests: given a linear function, assure that an interpolation is correct.Legacy validation: isolate a chunk of code in a legacy application that is know to be correct, and pull some discrete values out to use for testing.It still often comes up that I can't figure out how to properly test a given chunk of code, aside from manual trial and error. Can you provide some examples of tests you write for numerical code, and/or general strategies for testing scientific software? | Strategies for unit testing and test-driven development | testing | null |
_unix.363934 | WinSCP 5.5.3 (build 4214)CentOS GNU/Linux 2.6.32-642.15.1.el6.x86_64Login configuration: SCP protocol, port 22, everything else is default.The error:Connection has been unexpectedly closed.Server sent command exit status 254.Error skipping startup message. Your shell is probably incompatible with the application (BASH is recommended).getent on the remote Unix server reports that my login shell is indeed /bin/bash, which does exist with perms 755.I've looked all over the WinSCP help forum for a solution. Nothing there makes any sense - in most cases, I can't even parse the replies to the person having the error.I tried looking up scp server status 254, and found a tip here to turn off PAM (in /etc/ssh/sshd_config, set UsePAM to no). Same error.What more can I do to diagnose this problem? | WinSCP closes; server exit status 254; Your shell is probably incompatible with the application | centos;scp | null |
_datascience.14948 | What is the sizing limitation for Oracle 11g? Can I use it as big data platform? From the following link I understand that there is no limitation for the records, only the columns are bounded to 1000. So if my big data has less than 1000 per table but contains many records can I use Oracle 11g as big data platform? | Is Oracle 11g is able to ingest big data? | bigdata | There is no reason why you cannot use Oracle 11g to create large databases. The 1000-column limit is a theoretical one, not a practical one imo. The theoretical database size limit is in petabytes. You should question why you would want to put that much data in a single database and be prepared to pay for the infrastructure to support it. This is a good summary link - http://awads.net/wp/2010/02/15/oracle-database-limits-you-may-not-know-about/Having administered and tuned dbs of 50TB and more, the limits you should be more concerned with are for query performance. Ask Oracle about licensing as well before you proceed. |
_webmaster.105970 | I manage a small brick and mortar business that has a website mainly as advertisement to get people to come to our business in person. How do I get my website to move higher (towards page 1) of google search results for people searching for specific keywords and phrases related to my business and geographic location? We can't afford a proper web designer or IT technician so I'm trying to do as much on my own as possible. Thanks | how do I move up in search engine results for specific keywords or phrases? | search;website promotion | null |
_unix.377770 | I am trying to extract text between specific first match(_ and -). for example, I need to get number 5 from below:MQSeriesRuntime_5-U200491-7.5.0-4.x86_64I tried awk field seperator (awk -F) but thats getting me the entire text after _.can I get help with this please. | extract text between 2 different matches | linux;awk;sed | null |
_unix.17747 | As per the following example, and as in my recent question In bash, where has the trailing newline char gone?, I want to know why it happens x=$(echo -ne a\nb\n) ; echo -n $x | xxd -p # Output is: 610a62 # The trailing newline from the 'echo' command# has been deleted by Command SubstitutionI assume there must be some very significant reason for a shell action, namely Command Substitution, to actually delete some data from the command output it is substituting...but I can't get my head around this one, as it seems to be the antithesis of what it is supposed to do.. ie. to pass the output of a command back into the script process... Holding back one character seems weird to me, but I suppose there is a sensible reason for it... I'm keen to find out what that reason is... | Why does shell Command Substitution gobble up a trailing newline char? | shell;text processing;command substitution | Because the shell was not originally supposed to be a full programming language.It is quite difficult to remove a trailing \n from some command output.However, for display purposes almost all commands end their output with \n, so there has to be a simple way to remove it when you want to use it in another command. Automatic removal with the $() construction was the chosen solution.So, maybe you'll accept this question as an answer:Can you find a simple way to remove the trailing \n if this was not done automatically in the following command?> echo The current date is $(date), have a good day!Note that quoting is required to prevent smashing of double spaces that may appear in formated dates. |
_unix.311796 | I'm having some pretty terrible issues when i connect an external screen with my laptop.Laptop specs:Asus Zenbook UX303UB 13.3 (1920x1080)CPU: i7-6500U, 2.5GHzRAM: 8GB DDR3STORAGE: 256GB SSDGPU: 940M 2 GBLinux Mint 18 KDEWhen i connect the monitor sometimes the taskbar is not on the primary monitor set, also sometimes when i unplug the monitor KDE freezes up (ctrl+alt+f1 still works though) and all i can do is restart or reconnect the external monitor.If i shutdown the laptop and unplug the monitor, on next boot the login screen works fine but when the KDE splash screen gets to about 75% it appears to crash as there is a black screen with a cursor on the edge of the screen (where the 2 screens would meet if the external one is connected) and i can only move it up or down, at this point i can't access anything and the only thing that helps is connecting the external monitor and the laptop screen is unusable. this has happened a few times now and today i wasn't able to fix this, i'm writing this post from Cinnamon desktop which i installed just to be able to use the laptop.Any ideas? | Linux Mint 18 KDE external monitor | linux mint;kde | null |
_softwareengineering.334795 | Consider the following (example) code:class A{private: int *_a;public: A() { /* initialize _a to something */ } ~A() { /* deallocate _a */ } void setA(int i) const { _a[i] = 3; }};This code compiles and will perform as expected (i.e., if you call setA with some input i, it will set the ith element of _a to 3). My concern is with the const modifier attached to the function setA. There is no danger of a compiler error (or worse, undefined behavior) due to this modifier - the class A only contains a pointer to the data that is being modified, not the data itself. With that said, I can't help but feel that using the const modifier for a function that does in fact modify the data that A is in charge of maintaining is wrong, somehow. Am I being oversensitive here, or is this truly bad practice? | Declaring a function const when changing member data | c++ | In your example it is probably very bad idea to modify _a[i].Having said that I would like to elaborate a bit more:const is a very useful keyword. If you read some Bjarne's or Scott's books, there is written to use const as often as possible. Moreover changing data in function declared const is not only possible, it is sometimes good practice! Just remember that care is needed when deciding if your case is one of those 'some' times. Why on Earth they would put keyword mutable in C++ if it should not be used?An example (from one of aforementioned authors if I remember correctly) of good usage of mutable:Consider class Polygon:class Polygon{ void calculate_area() { /* we calculate m_area */ } std::vector<Vertex> m_vertexes; double m_area;public: Polygon(std::initializer_list<Vertex> v_list): m_vertexes(v_list) {} double area() const { return m_area; } void add_vertex(Vertex v) { m_vertexes.push_back(v); calculate_area(); }};It is quite straightforaward, isn't it? We don't want to calculate area every time we are asked to return it, so we store its value in m_area member variable and return this variable. Method double area() is const, it doesn't change anything after all. The thing is we have to compute area every time we change our Polygon! Let's say we add a hundred vertexes one by one... A hundred area recalculations! 99 of those totally unnecessary. We want to recalculate only if we are asked to deliver area. So what do we do?We use mutable!class Polygon{ void calculate_area() const { /* we calculate m_area */ m_recalculate_area = false; } std::vector<Vertex> m_vertexes; mutable bool m_recalculate_area = false; mutable double m_area = 0.0;public: Polygon(std::initializer_list<Vertex> v_list): m_vertexes(v_list) { m_recalculate_area = true; } double area() const { if(m_recalculate_area) { calculate_area(); } return m_area; } void add_vertex(Vertex v) { m_vertexes.push_back(v); m_recalculate_area = true; }};The effect is pretty nice: for a user of our class method double area() still doesn't modify object it's working on, so it is still const. But inside we gained a lot! Area will be recalculated only when there is need for it. If nobody asks for area it won't be calculated at all!So, as I understand it, const should indicate that as far as class user is concerned method does not modify object. User of our API is usually not interested in implementation details. If he is, then we have documentation :) .But beware: using mutable because it's few lines of code less or something like that is a huge mistake. If you make your method const then keep your word and use mutable with utmost care only! Otherwise you, and users of your code soon will be in big trouble. |
_unix.165347 | My problem is pretty simple, but I must admit, I don't know any elegant solution. I have a problem, that I often accidentally click different icon that I wanted. It's really very unpleasant, so I've decided to write a bash script, which will ask me if I really want to launch the program ( especially Eclipse, because it's pretty large and so it takes lots of time to load ). I had written it, then added its location to the eclipse.desktop file... And now there's my problem. The Eclipse launcher works, but if I launch only Terminal, Eclipse icon shows up instead of original Terminal's.Do you know how could I solve this, if I wanted to keep my bash script working?Here is my bash script eclipseLaunch.sh:#!/bin/bashecho Do you really want to launch Eclipse? (yes = y)read answerif [[ $answer = y ]]; then ~/.eclipse/eclipsefiAnd here is my eclipse.desktop file:[Desktop Entry]Type=ApplicationEncoding=UTF-8Name=EclipseExec=gnome-terminal -e bash -c \~/.eclipse/eclipseLaunch.sh; exec bash\Icon=/home/martin/.eclipse/icon.xpmTerminal=false | Launch BASH script by clicking icon and preserve terminal icon | bash;shell script;icons;desktop file | Finally I've solved it. After this solution I had to restart PC.I've changed my eclipse.desktop file to this:[Desktop Entry]Type=ApplicationEncoding=UTF-8Name=EclipseExec=bash -c ~/.eclipse/eclipseLaunch.sh; exec bashIcon=/home/martin/.eclipse/icon.xpmTerminal=trueAnd eclipseLaunch.sh to this:#!/bin/bashecho Do you really want to launch Eclipse? (yes = y)read answerif [[ $answer = y ]]; then nohup ~/.eclipse/eclipse &else kill $PPIDfi |
_unix.37069 | What is the difference between the following methods of chaining commands?cmd1; cmd2cmd1 && cmd2 | What is the difference between && and ; when chaining commands | bash;shell | Assume there is command1 && command2.In this case command2 will be executed if and only if command1 returned zero exit status.; is just a command separator. Thus command2 will be executed whatever command1 returned.$> [[ a = b ]] && echo ok $> [[ a = b ]]; echo ok ok |
_softwareengineering.137340 | I'm sure we've all been in the situation where we've inherited code that was overly public, becomes obsolete or needs to be refactored. In these situations, it is easy to spend many days analysing the API surface to see where methods or classes are consumed; with the .Net runtime, it seems logical that it should be relatively trivial to map these inter-assembly dependencies, but there doesn't seem to be any tools out there that do this already?For example, let's suggest that we have a CRM class library that encapsulates the interface to all the customer data; it's not unreasonable that a quotations application may rely on this, but it seems non-trivial to identify on which bits. A naive approach would be to say that the public interfaces (types, etc.) is the API surface, but it may be the case that some of these interfaces are only public for consumption in a particular use case, that may become invalid.Is it possible to automatically determine and map the inter-assembly dependencies for a given set of assemblies? | Is it possible to analyse the API surface of a set of class libraries to automatically determine inter-assembly dependencies? | .net;refactoring;dependency analysis | null |
_unix.282895 | How to create a collation of images in the format:image_name_1 [IMAGE#1]image_name_2 [IMAGE#2]image_name_3 [IMAGE#3]...Using Imagemagick I can say something like:montage -label '%f' -mode concatenate -tile 1x foo*.png out.pngBut this adds the file name below the image + it does not account for name width.Where the file name is printed (as in conventional cartesian y-axis) is of no concern as far as it is to the left of the correct image.Which tool is of no concern as long as it is available for 32-bit Linux. | Collate image list with name | scripting;imagemagick;image manipulation | I'm no ImageMagick expert, so there is probably a better way to do this, but you can do this in 2 steps, first adding the text to the left of each image into an intermediate file, then doing the montage. for file in foo*.pngdo convert $file -splice 100x0 -gravity west -annotate +10+0 '%f' /tmp/$(basename $file)donemontage -mode concatenate -tile 1x /tmp/*.png out.pngYou need to adjust the splice value 100 to be wide enough for your widest filename label. An interesting alternative that uses a single command is convert \ $(for file in foo*.png do echo '(' label:$(basename $file) -gravity center $file +append ')' done) -gravity west -append out.pngwhere you use +append to join the label and image together horizontally, then -append to join the results vertically. It is not exactly what you need, but could be a starting point for further experimentation. |
_codereview.57773 | I've come across the following piece of code in a Razor view<table class=key-left> <tr> <td>Company</td> @foreach (Customer c in Model.SelectedInstallers) { <td>@c.Name</td> } </tr> <tr class=even> <td>Address</td> @foreach (Customer c in Model.SelectedInstallers) { <td> @c.Street<br /> @c.City<br /> @c.County<br /> @c.Postcode </td> } </tr> <tr> <td>Contact Details</td> @foreach (Customer c in Model.SelectedInstallers) { <td> @c.Telephone<br /> @c.Website </td> } </tr> <tr class=even> <td>Remove</td> @foreach (Customer c in Model.SelectedInstallers) { <td><a href=# class=ins-qt-remove remove title=Remove this Installer from your list data-account-no=@c.AccountNumber>Remove installer</a></td> } </tr></table>Now would it better to stay with this code or change it to do one loop with multiple stringbuilders:StringBuilder company = new StringBuilder();StringBuilder address = new StringBuilder();StringBuilder contact = new StringBuilder();StringBuilder remove = new StringBuilder();foreach (Customer customer in Model.SelectedInstallers){ company.AppendFormat(\n <td class=\company\>{0}</td>, customer.Name); address.AppendFormat(\n <td class=\address\>{0}<br />{1}<br />{2}<br />{3}</td>, customer.Street, customer.City, customer.County, customer.Postcode); contact.AppendFormat(\n <td class=\contact\>{0}<br />{1}</td>, customer.Telephone, customer.Website); remove.AppendFormat(\n <td class=\remove\><a href=\{0}\ class=\remove-link\>Remove<span class=\hide-element\> {1} from the list</span></a></td>, removeUrl, customer.Name);}<table id=compamies-list class=rows-@Model.SelectedInstallers.Count> <tr class=first-row> <th scope=row>Company</th> @Html.Raw(company.ToString()) </tr> <tr class=even> <th scope=row>Address</th> @Html.Raw(address.ToString()) </tr> <tr class=odd> <th scope=row>Contact Details</th> @Html.Raw(contact.ToString()) </tr> <tr class=even> <th scope=row>Remove</th> @Html.Raw(remove.ToString()) </tr></table>Or does it not matter if there is only going to be a maximum of ten installers | Multiple loops versus multiple stringbuilders | c#;optimization;asp.net mvc 4 | Stay with the first solution:It is easier to read.Using such a template is the least-obfuscated method to generate the output HTML, as the structure of the template directly corresponds to the structure of the output.Another important aspect is that when embedding HTML into C# strings, you have to use many escapes.This makes it harder to read.I would expect the first template to have comparable or better performance.Instead of micro-optimizing, one should usually optimize for maintainability first, and let the compiler do its thing. Before optimizing for performance, do a benchmark to find real bottlenecks.I strongly suspect that the template engine is implemented in a non-moronic way, which means that internally a string builder is used.Your second solution on the other hand incurs additional overhead by maintaining multiple string builders which are then joined to an intermediate string which are then stuffed into the template that intermediate string is unnecessary.But what about having fewer loops? The answer is that it doesn't matter from a theoretical perspective: Executingforeach (x in things) a(x);foreach (x in things) b(x);foreach (x in things) c(x);does the same amount of work asforeach (x in things){ a(x); b(x); c(x);}In practice there is some small overhead per loop, but this overhead is usually negligible when compared with the actual work done inside the loop. Do a benchmark to see if this overhead matters.It appears to be more secure.In your second solution, you directly interpolate arbitary strings into the HTML via AppendFormat.Unless you have very good input validation, this would allow for spectacular injection attacks.Better be safe than sorry, and escape everything.This is much easier if you use the templating engine rather than doing everything yourself it's too easy to forget something.There is another consideration from an UX standpoint:When reading tabular data, I expect each row to contain a record, and columns to contain different fields for that record.This makes such data easy to parse by humans and computers alike.Swapping the axes of your table also means that your template is ever simpler:<table> <tr> <th>Company</th> <th>Address</th> <th>Contact Details</th> <th>Remove</th> </tr> @foreach (Customer c in Model.SelectedInstallers) { <tr> <td> @c.Name </td> <td> @c.Street <br /> @c.City <br /> @c.County <br /> @c.Postcode </td> <td> @c.Telephone<br /> @c.Website </td> <td> <a href=# title=Remove this Installer from your list data-account-no=@c.AccountNumber> Remove installer </a> </td> </tr> }</table>While displaying data row after row scales very well to a large number of records, displaying items horizontally next to each other so that each item occupies a column makes it much easier to compare the data. However, this only scales well up to three items (in my experience), and horizontal scrolling is a big no-no.Some notes regarding the HTML: The headings of columns or rows should use the <th> element. While you do this in the second template, the first template only uses plain <td>s.To style different rows differently, it is tedious to apply classes like first-row, even, or odd.These not only invite name collisions, but can also be done with much less effort via CSS pseudo-classes such as :nth-child:/* tr.first-row */tr:first-child { ... }/* tr.even */tr:nth-child(even) { ... }/* tr.odd */tr:nth-child(odd) { ... }The disadvantage of this solution is that it won't work on older MSIE versions.But in this case this wouldn't be a problem as the functionality of the table is not impaired this is an example of progressive enhancement. |
_unix.338979 | I'm a unix admin at a college. I've two web servers. One of them is for faculty and one of them is for the official college web team. The offical web server proxies requests for faculty web pages, so even though they're two separate servers, from the faculty and browser point of view, it appears as one server. In order to save the faculty some confusion, I forward port 22 (using socat) on the official server to the faculty server and make sshd on the the official server listen on a different port. This way, faculty can ssh to mycollege.edu, even though that's the DNS name of the official server. It means the web team gets confused more often, but that's way better than several hundred confused faculty.I use Fail2Ban to keep the brute force ssh logins to a somewhat more manageable quantity. This doesn't work for these two web servers because every ssh connection to the faculty server comes from the official server, and I obviously don't want to block connections from the official server.What I want to do, is find a way to track failed logins across the servers, so I can have the official server block the source IP. The problem is, the official server knows the source IP but not which logins failed and the faculty server knows which logins failed, but not the source IP.I should be able to do this by tracking the source port on the connections between the offical and faculty servers. Official knows source IP of original connection and the source port for the subsequent connection to the faculty server. The faculty server knows the source port from the official server and weather the login failed. Basically, I would keep a log of foreign source IPs and internal source ports on the official (outward facing) server and a log of internal source ports and login failures on the faculty (internal) server. Then I could send the log entries from the faculty server to the official server and the official server could analyze it and firewall as appropriate.SO! Here's my questions:Is this a crazy idea with a much simpler solution?If this isn't crazy, what's the best way to gather that internal source port info? Socat (on external, official host) can log some stuff, but what it appears to call the source port doesn't match anything in connections I'm watching on the internal/faculty host (using tcpdump). | tracking proxied TCP connection | ssh;firewall;proxy;tcp;socat | null |
_codereview.91720 | I recently wrote a name generator that uses a DTMC underneath (I asked about it here) and, since I'm not entirely confident I did it right, I wrote a script to check my code, or at least its output.It works pretty well, but, being new to the language, I want to know how to make it more idiomatic. Performance boosts (in terms of speed and memory efficiency) would also be a plus, but since this is just a simple test script they're not as important.# arguments: '-dDELIMITER'if ARGV[0] == '-h' [ 'Should be used in the form:', '<invocation of name_gen.rb> | <ruby> name_gen_test.rb -d<delimiter>', 'The delimiter MUST be specified in name_gen.rb and it MUST NOT be ``.' ].each { |line| puts line }endDELIMITER = ARGV[0] || abort('You must specify a delimiter as the sole command-line argument')connections = Hash.new { |hash, key| hash[key] = Hash.new 0 }start = Hash.new 0until (cur_line = STDIN.gets).nil? cur_line.chomp! individual_syllables = cur_line.split DELIMITER individual_syllables.each_with_index { |from, index| start[from] += 1 if index == 0 connections[from][individual_syllables[index + 1] || !!false] += 1 }end# % of start per syllable# % of connections to each syllable it connected toputs 'Start:'total_start_count = start.values.inject(:+).to_fmax_len = start.keys.inject (0) { |memo, cur| (cur.length > memo) ? cur.length : memo}start.each { |text, percent| puts #{text.ljust max_len} : #{(percent * 100 / total_start_count).round.to_i}% # Get the percent -> Truncate -> convert to string -> justify}putsEND_MARKER = '[end]'puts 'Connections:'connections.each { |from, links| total_connection_count = links.values.inject(:+).to_f max_len = links.keys.inject(END_MARKER.length) { |memo, cur| ((cur ? cur : '').length > memo) ? cur.length : memo } puts #{from}: links.each { |to, probability| next unless to puts #{to.ljust max_len} : #{(probability * 100 / total_connection_count).round.to_i}% } puts #{END_MARKER} : #{(links[false] * 100 / total_connection_count).round.to_i}%}This is the name generator; this script is meant to be used something like this (on Windows, at least):ruby name_gen.rb dict.txt 10000 -d_ | ruby name_gen_test.rb _if the dictionary of syllables is located at 'dict.txt'.Here's an example dictionary file:a|1|1|b,2;c,2b|0|3|a,0;c,2c|0|0|a,1;b,1And an example output for the script:Start: a : 100%Connections: a: c : 40% b : 40% [end] : 20% c: a : 50% b : 50% [end] : 0% b: c : 40% [end] : 60%For anyone interested, the final code is available here. | Analyzer for randomly generated names | ruby | The ruby style guide suggests to use 2 spaces per indentation level.You can use heredocs for multi-line strings, keep in mind that they preserve white space, here is a nice trick that could be used:help = <<-END.gsub(/^\s+\|/, '') |Should be used in the form:, |<invocation of name_gen.rb> | <ruby> name_gen_test.rb -d<delimiter>, |The delimiter MUST be specified in name_gen.rb and it MUST NOT be ``. ENDhelp.each_line { |line| puts line }for multiline blocks please use do...end instead of {...}:individual_syllables.each_with_index do |from, index|start[from] += 1 if index == 0connections[from][individual_syllables[index + 1] || !!false] += endI don't understand why you use !!false, since !!false == false. Also I don't think it is needed here.Do not put a space between a method name and the opening parenthesis:max_len = start.keys.inject (0)Avoid nested ternary operators, it makes the code hard to understand.((cur ? cur : '').length > memo) ? cur.length : memo# becomescur ||= ''[cur.length, memo].max |
_ai.221 | Currently, many different organizations do cutting-edge AI research, and some innovations are shared freely (at a time lag) while others are kept private. I'm referring to this state of affairs as 'multipolar,' where instead of there being one world leader that's far ahead of everyone else, there are many competitors who can be mentioned in the same breath. (There's not only one academic center of AI research worth mentioning, there might be particularly hot companies but there's not only one worth mentioning, and so on.)But we could imagine instead there being one institution that mattered when it comes to AI (be it a company, a university, a research group, or a non-profit). This is what I'm referring to as monolithic. Maybe they have access to tools and resources no one else has access to, maybe they attract the best and brightest in a way that gives them an unsurmountable competitive edge, maybe returns to research compound in a way that means early edges can't be overcome, maybe they have some sort of government coercion preventing competitors from popping up. (For other industries, network or first-mover effects might be other good examples of why you would expect that industry to be monolithic instead of multipolar.)It seems like we should be able to use insights from social sciences like economics or organizational design or history of science in order to figure out, if not which path seems more likely, how we would know which path seems more likely.(For example, we may be able to measure how much returns to research compound, in the sense of one organization coming up with an insight meaning that organization is likely to come up with the next relevant insight, and knowing this number makes it easier to figure out where the boundary between the two trajectories is located.) | How would we know if AI development will continue to be multipolar, or will become monolithic? | research;ai community | null |
_cs.32114 | BACKGROUND:Recently I tried to solve a certain difficult problem that gets as input an array of $n$ numbers. For $n=3$, the only solution I could find was to have a different treatment for each of the $n!=6$ orderings of the 3 numbers. I.e., there is one solution for the case $A>B>C$, another solution for $A>C>B$, etc. (the case $A>C=B$ can be solved by any one of these two solutions).Thinking of the case $n=4$, it seems that the only way is, again, to consider all $n!=24$ different orderings and develop a different solution for each case. While the solution in each particular case is fast, the program itself would be very large. So the runtime complexity of the problem is small, but the development time complexity or the program size complexity is very large. This prompted me to try and prove that my problem cannot be solved by a short program. So I looked for references for similar proofs.The first concept that I found is Kolmogorov complexity; however, the information I found about this topic is very general and includes mostly existence results. QUESTION:Can you describe a specific, real-life problem $P$, such that any program solving $P$ on an input array of size $n$ must have a size of at least $\Omega(f(n))$, where $f(n)$ is some increasing function of $n$?Since the answer obviously depends on the selection of programming language, assume that we program in Java, or in a Turing machine - whichever is more comfortable for you.Every undecidable problem trivially satisfies this requirement because it has no solution at all. So I am looking for a decidable language. | What problem cannot be solved by a short program? | complexity theory;programming languages;kolmogorov complexity | I assume that what you actually want is an enumeration of problems suchthat the corresponding programs form an increasing sequence in size.Here is an exemple of such an enumeration.However, I only prove that the size increases beyond any bound, hence it is not in $O(1)$, whichseemed to be your main point. I could try better, but I am wonderingwhat in this answer might not be acceptable in your view of the question.If I understand correctly, you want an enumeration $P_n$ of problems thatare all decidable with an algorithm $A_n$, such that there is nouniform decision procedure for the union of these problems, because ifthere was one, it would be a short program when $n$ gets large,i.e. it would be $O(1(n))$.That implies that the enumeration $A_n$ is not computable. If it werecomputable, the one would be able to compute the algorithm $A_n$ fromthe knowledge of $n$, thus having a uniform procedure for the union ofall the problems in the enumeration.Hence we can only look for examples such that there is no computableenumeration $A_n$ of algorithms such that $A_n$ solves $P_n$.Before going into that, we need to define the size of a Let $T_n$ be a enumeration by Gdel numbers $n$ ofTuring Machines. Such a Gdel enumeration is computable. Then let $P_n$ be thefollowing problem: if $T_n$ halts on all inputs, then $P_n$ consistsin recognizing the recursive set recognized by $T_n$, else $P_n$ consistsin recognizing the empty set $\emptyset$.Since we are looking for lower bounds on the size of the algorithm$A_n$ that solves $P_n$, we have to define the size of a TM. For a TM,its Gdel number can be taken as the size of the machine, i.e. thecorresponding algorithm. Indeed the number of states and transitionsincreases necessarly with $n$, if only because of the pigeon holeprinciple, though it is not necessarily uniform (and it depends on anarbitrary definition of size anyway).Then, for any TM $T_n$ that always halt, we note ${\mu(n)}$ the smallest Gdelnumber of a TM $T_{\mu(n)}$ such that it always halt and recognizes thesame recursive set as $T_n$. Hence $T_{\mu(n)}$ is the smallest TM thatactually is an algorithms to solve $P_n$, i.e. it is $A_n$. If $T_n$may not halt, then for $A_n$ we simply use always an algorithmcorresponding to a TM $T_\emptyset$ the recognizes theset $\emptyset$, always the same one.Each problem $P_n$ is decidable, and $A_n$ is a decision procedure.However, the enumeration $A_n$ is not computable, but we have shownthat it is unavoidable.It is easy to show that, given any constant $C$, there is an $n$ suchthat the size $|A_n|$ of $A_n$ is greater than $C$. The reason issimply that the number of machines smaller than $C$ is finite, whilethe number of recursive sets recognized by TMs is infinite.So that is an example of a problem (more precisely a problemenumeration) that cannot be solved by a short program, i.e. such thatthere is no constant bound on the length of solutions for each $P_n$.We can always add to each problem $P_n$ that it requires any solutionto first read an array of size $n$, so as to meet the constraint inthe question. But there is little point to it. |
_cs.20042 | Let $A$ and $B$ be regular languages. Let $C$ be their difference, i.e $C = B \setminus A$.Given NFAs for $A$ and $B$, is it possible to directly construct an NFA for $C$ without (implicitly or explicitly) converting them to DFAs first? | Direct construction of NFA for the difference of regular languages | automata;finite automata | The short answer is yes.Probably the easiest way to explain it is with an example; turning this into a formal algorithm should be straightforward.The first NFA, $M$, accepts the language $(a\cup b)^*$:$$q_0 = \epsilon \cup a q_0 \cup b q_0$$with the start state being $q_0$.This is probably not notation that you're used to, but the reason for using this will become clear soon; it's basically saying the same thing as the context-free grammar:$$ S \rightarrow \epsilon $$$$ S \rightarrow a S $$$$ S \rightarrow b S $$You can see how this is also a description of a NFA. Each term on the right-hand side is either a transition $aq_i$, which means read an $a$ and go to state $q_i$, or $\epsilon$ which means that the state is a final state.The second NFA, $M$, accepts the language $(a\cup b)^*aa(a\cup b)^*$, that is, any string which contains $aa$. The start state is $q_1$; I've used unique state names for reasons that will become obvious in a moment. I deliberately picked an NFA which has some nondeterminism just to show that this works for that case.$$q_1 = a q_1 \cup b q_1 \cup a q_2$$$$q_2 = a q_3$$$$q_3 = \epsilon \cup a q_3 \cup a q_3$$We would like to construct a NFA which accepts the language:$$Q_0 = q_0 \setminus q_1$$expanding one level gives:$$Q_0 = (\epsilon \cup a q_0 \cup b q_0) \setminus (a q_1 \cup b q_1 \cup a q_2)$$$$ = \epsilon \cup a (q_0 \setminus (q_1 \cup q_2)) \cup b (q_0 \setminus q_1)$$$$ = \epsilon \cup a Q_1 \cup b Q_0$$where:$$Q_1 = q_0 \setminus (q_1 \cup q_2)$$Note that we already had a state which handled the $b$ transition correctly. For the $a$ transition, we didn't, so we introduced one.We continue:$$Q_1 = q_0 \setminus (q_1 \cup q_2)$$$$= (\epsilon \cup a q_0 \cup b q_0) \setminus (a q_1 \cup b q_1 \cup a q_2 \cup a q_3)$$$$= \epsilon \cup a (q_0 \setminus (q_1 \cup q_2 \cup q_3)) \cup b (q_0 \cup q_1)$$$$= \epsilon \cup a Q_2 \cup b Q_0$$where:$$Q_2 = q_0 \setminus (q_1 \cup q_2 \cup q_3)$$continuing again, going a little more slowly this time:$$Q_2 = q_0 \setminus (q_1 \cup q_2 \cup q_3)$$$$= (\epsilon \cup a q_0 \cup b q_0) \setminus ((a q_1 \cup b q_1 \cup a q_2) \cup (a q_3) \cup (\epsilon \cup a q_3 \cup b q_3))$$$$= a (q_0 \setminus (q_1 \cup q_3)) \cup b (q_0 \setminus (q_1 \cup q_3))$$$$= a Q_2 \cup b Q_2$$Note that we used the fact that $\epsilon \setminus \epsilon = \varnothing$.So in summary, we have the following NFA with start symbol $Q_0$:$$Q_0 = \epsilon \cup a Q_1 \cup b Q_0$$$$Q_1 = \epsilon \cup a Q_2 \cup b Q_0$$$$Q_2 = a Q_2 \cup b Q_2$$You can verify for yourself that this accepts the language.There are several things to notice about this.First off, the process must terminate; there are only a finite number of possible transition states which could be created.Secondly, the running time could be exponential in the worst case; each transition state is of the form $\bigcup_i q_i \setminus \bigcup_j q_j$ where the left-hand side of the set minus is a subset of the states from the first machine and the right-hand side is the same for the second machine. There is a finite number of such subsets, but there could be exponentially many in general, and sometimes there will be. And the reason is......the final answer is a DFA! It's not hard to see that this will always be the case. Your question only asked for a method that didn't convert the two NFAs to DFAs first, and you never said anything about not constructing a DFA for the final answer.Basically what we've done here is folded the NFA-to-DFA conversion algorithm together with the DFA difference algorithm, so one algorithm does both. I think this satisfies the requirements of your question. |
_softwareengineering.17843 | I read few articles on web to find out how Agile, XP, Scrum, pair programming are different from each other / related to each other and I derived the following line:Scrum and XP are almost same. XP has shorter period of releases than ScrumPair programming is employed in both Agile and XP methodologiesBut I was unable to identify how Agile is different from XP.More than providing a URL, I would be happy to read your experience and thoughts on this. | How is Agile different from XP? | project management;agile;scrum;pair programming;extreme programming | You are confusing the issue. Being agile means that you are following a bunch of values and practices from the agile manifesto. Thats it. XP and Scrum are development processes that follows those values. Both are just as agile. The big difference between Scrum and XP is that Scrum does not contain practices specifically for programming, whereas XP has lots of them (TDD, continuous integration, pair programming). |
_unix.195975 | With this Dockerfile:FROM php:5.4-fpmRUN apt-get -qqy update \ && apt-get -qqy install git \ libcurl4-gnutls-dev \ libmcrypt-dev \ libpng12-dev \ libxml2-dev \ libxslt-dev \ && docker-php-ext-install curl \ bcmath \ gd \ mcrypt \ mysql \ soap \ xsl \ zip \ && rm -rf /var/lib/apt/listsI get the error rm: cannot remove '/var/lib/apt/lists': Directory not emptyBut if I separate out the rm into another RUN statement, suddenly the error goes away.FROM php:5.4-fpmRUN apt-get -qqy update \ && apt-get -qqy install git \ libcurl4-gnutls-dev \ libmcrypt-dev \ libpng12-dev \ libxml2-dev \ libxslt-dev \ && docker-php-ext-install curl \ bcmath \ gd \ mcrypt \ mysql \ soap \ xsl \ zipRUN rm -rf /var/lib/apt/listsrm is just /bin/rm in the php:5.4-fpm container. Why is docker build unable to remove /var/lib/apt/lists in the first case, and why is it exiting with a nonzero exit status even with the -f flag? | Cannot (force) remove directory in Docker build | rm;docker | According to the Docker development discussion this is the number 1 known issue in the Docker docs. Here is the current release note reference.Unexpected File Permissions in Containers An idiosyncrasy in AUFS prevents permissions from propagating predictably between upper and lower layers. This can cause issues with accessing private keys, database instances, etc. For complete information and workarounds see Github Issue 783.The mentioned workaround can be found on Github here |
_unix.306481 | How can I setup a Bacula job so that when it writes its files, it only writes to tapes that are completely empty? For this particular job, I don't want it to share any tapes with other backup jobs. | Tell Bacula to use only empty tapes | backup;bacula | null |
_codereview.36275 | This is roughly what my data file looks like:# Monid U B V R I u g r i J Jerr H Herr K Kerr IRAC1 I1err IRAC2 I2err IRAC3 I3err IRAC4 I4err MIPS24 M24err SpT HaEW mem compMon-000001 99.999 99.999 21.427 99.999 18.844 99.999 99.999 99.999 99.999 16.144 99.999 15.809 0.137 16.249 99.999 15.274 0.033 15.286 0.038 99.999 99.999 99.999 99.999 99.999 99.999 null 55.000 1 NMon-000002 99.999 99.999 20.905 19.410 17.517 99.999 99.999 99.999 99.999 15.601 0.080 15.312 0.100 14.810 0.110 14.467 0.013 14.328 0.019 14.276 0.103 99.999 0.048 99.999 99.999 null -99.999 2 N...and it's a total of 31mb in size. Here's my python script that pulls the Mon-###### IDs (found at the beginning of each of the lines).import redef pullIDs(file_input): '''Pulls Mon-IDs from input file.''' arrayID = [] with open(file_input,'rU') as user_file: for line in user_file: arrayID.append(re.findall('Mon\-\d{6}',line)) return arrayIDprint pullIDs(raw_input(Enter your first file: ))The script works but for this particular file it ran for well into 5 minutes and I eventually just killed the process due to impatience. Is this just something I'll have to deal with in python? i.e. Should this be written with a compiled language considering the size of my data file?Further info: This script is being run within Emacs. This, by the checked answer, explains why it was running so slow. | Why is this program for extracting IDs from a file so slow? | python;optimization;array | You said in comments that you don't know how to create a self-contained test case. But that's really easy! All that's needed is a function like this:def test_case(filename, n): Write n lines of test data to filename. with open(filename, 'w') as f: for i in range(n): f.write('Mon-{0:06d} {1}\n'.format(i + 1, ' 99.999' * 20))You can use this to make a test case of about the right size:>>> test_case('cr36275.data', 200000)>>> import os>>> os.stat('cr36275.data').st_size34400000That's about 34 MiB so close enough. Now we can see how fast your code really is, using the timeit module:>>> from timeit import timeit>>> timeit(lambda:pullIDs('cr36275.data'), number=1)1.3354740142822266Just over a second. There's nothing wrong with your code or the speed of Python.So why does it take you many minutes? Well, you say that you're running it inside Emacs. That means that when you run>>> pullIDs('cr36275.data')Python prints out a list of 200,000 ids, and Emacs reads this line of output into the *Python* buffer and applies syntax highlighting rules to it as it goes. Emacs' syntax highlighting code is designed to work on lines of source code (at most a few hundred characters but mostly 80 characters or less), not on lines of output that are millions of characters long. This is what is taking all the time.So don't do that. Read the list of ids into a variable and if you need to look at it, use slicing to look at bits of it:>>> ids = pullIDs('cr36275.data')>>> ids[:10][['Mon-000001'], ['Mon-000002'], ['Mon-000003'], ['Mon-000004'], ['Mon-000005'], ['Mon-000006'], ['Mon-000007'], ['Mon-000008'], ['Mon-000009'], ['Mon-000010']] |
_unix.97017 | I'm trying to configure zsh to closely fit how bash behaves before I fully switch, and one behavior I'm trying to modify in zsh is when it inserts a Tab character.I see how it could be helpful for writing functions interactively, but I prefer bash's behavior of listing the directory contents. Ideally, I would like to cycle through the directories using a menu, but my main priority is to list directories like Bash after one or two Tab presses instead of inserting a Tab.I did try to look this up, but everything I found only pertained to disabling Tab Completion entirely.EDIT: I mistakenly thought bash's default completion on empty input was to list the directory when I posted this, I feel like it may have caused some confusion with what I was asking.My main objective is to prevent zsh from inserting a Tab when there is only whitespace. | Zsh - Disable Tab Insert | zsh;keyboard shortcuts | Setting the insert-tab tag to false will prevent a tab from being inserted when there are no characters to the left of the cursor.zstyle ':completion:*' insert-tab false |
_cs.48256 | Given the language $L = \{w \in \{a,b\}^* \, | \, |w| = n \cdot \sqrt{n} \text{ and } n \geq 42\}$ and the assignement to proof that $L \notin CFL$ with the Pumping lemma. Assuming $L \in CFL$, would it be possible to start with defining a language $L' := L \cap a^+$ which has to be context-free since $CFL$ is closed under intersection with $REG$. Now I would have to proof that $L' = \{w \in a^+ \, | \, |w| = n \cdot \sqrt{n} \text{ and } n \geq 42\}$ isn't regular because the alphabet contains only one symbol. Let $k$ be the constant of the Pumping lemma and $m > k$ and $m > 42$. So $z = a^{m^2\cdot\sqrt{m^2}} = a^{m^3} \in L'$.$|z| = |uvw| = m^3 ...$ How to continue? | Proof that a given language is not context-free | context free;pumping lemma | You're off to a good start. You recognize that all you have to do is show that the language $L'$ isn't regular. You let $k$ be the integer of the PL and choose an integer $m$ with $m>k$ and $m>42$ so you choose to pump the string $z=a^{m^3}$. Write this as $uvw$ with $|v|=t$ and $0<t<k$. Now we'll have $|uv^2w|=m^3+t<m^3+m$. This string can't be in $L'$ since it's strictly smaller than the next largest string in $L'$, namely the one with length $(m+1)^3$, since obviously $$m^3+m<m^3+3m^2+3m+1$$Since $L'$ isn't regular, $L$ can't be a CFL. |
_unix.378121 | I have a bash script that will execute a script of my choosing against a server over ssh. My problem is that I also want to use an input file with common variables so I don't have to change them in each script. So far my attempts at getting it to source the two files have resulted in it trying to find one of them on the remote machine.inputJBLGSMR002,IP.IP.IP.IP,root,pers,perssourcelist#!/bin/bashvar1=Some stuffvar2=Some stuff 2Script#!/bin/bash##set -xinput=/home/jbutryn/Documents/scripts/shell/input/nodelist.csvsourcelist=/home/jbutryn/Documents/scripts/shell/Tools/slisttools=/home/jbutryn/Documents/scripts/shell/Tools#is.there () { if grep -wF $1 $2 > /dev/null 2>&1 ; then echo true else echo false fi}#nodethere=$(is.there $1 $input)#if [[ $nodethere = true ]]; then ipconn=$(awk -F ',' '/'$1'/ {print $2}' $input) usrconn=$(awk -F ',' '/'$1'/ {print $3}' $input)elif [[ $nodethere = false ]]; then echo Couldn't find $1 in database exit 1fi#if [[ -f $tools/$2 ]]; then echo Please enter your password for $1: read -s SSHPASS eval export SSHPASS='$SSHPASS' sshpass -e ssh $usrconn@$ipconn < $tools/$2elif [[ ! -f $tools/$2 ]]; then echo Couldn't find $2 script in the Tools exit 1fiI have this test script to see if it's passing the variables to the remote machine:Test Script#!/bin/bash#touch testlogecho $var1 >> ./testlogecho $var2 >> ./testlogAnd this is what I've tried so far to get the sourcelist to pass through:if [[ -f $tools/$2 ]]; then echo Please enter your password for $1: read -s SSHPASS eval export SSHPASS='$SSHPASS' sshpass -e ssh $usrconn@$ipconn < $sourcelist; $tools/$2This one will create a blank testlog file on the local machineif [[ -f $tools/$2 ]]; then echo Please enter your password for $1: read -s SSHPASS eval export SSHPASS='$SSHPASS' sshpass -e ssh $usrconn@$ipconn <'EOF' source $sourcelist bash $tools/$2 logout EOFThis one will create a blank testlog file on the local machineI've also tried using source bash . to call the files but I still can't seem to get both local files to pass to the remote machine. Anyone know how this can be done? | How can I pass two files through ssh? | bash;ssh;sshpass | It's a bit difficult to understand what you're really trying to do.If you want to concatenate the content of $sourcelist and $tools/$2 and execute it in Bash, you can use cat with those two files and pipe to ssh like this:cat $sourcelist $tools/$2 | sshpass -e ssh $usrconn@$ipconn |
_softwareengineering.229853 | I feel kind of lost in this backend development process I am attempting right now. Most of the usual development practices I use while developing client-side applications don't apply here... Let me provide some context.The debugging processWhile developing a client side application (iOS, Java desktop app, or whatever), it is easy to quickly setup the project on your favorite IDE, get it running on your machine or a testing device, and debug the hell out of it as much as you like.On the other hand, it's not as trivial to hook a debugger to your backend code, and especially if it is python code running on Google App Engine (GAE). That's what I am using, and ... yeah. Linters and all help A LOT, but still, semantic issues cannot be resolved that way, obviously.I am currently going over my recently written backend code and just burying it with logging.debug('msg') statements, asserts and whatnot. This is the only thing I can think of. Is this normal for backend developers? Does logging and digging through logs usually how backend devs iterate on their applications?Parallelism and request drivenThis might be a bit more specific to GAE and other non-blocking backends, honestly. Single threaded servers don't suffer from this problem... Anyways, so when you are dealing with parallelism and everything is driven by socket events, how do backend developers usually test if their backend works?I did the most naive thing of all time, which is to open python console and using the requests library just send requests and test bit by bit. Then, I went ahead and wrote a kivy app to help me send the requests from a GUI interface and see what is going on, but it's taking more time to maintain the kivy app than develop the backend!! I tried to check for test frameworks for GAE, but they didn't seem easy to get, so I was wondering if they are worth it? Would I be able to simulate 100s of clients using my backend using test frameworks? What do people use these days (For GAE specifically)?Visualizing the flowBecause of my inexperience with backend development, it is surprisingly hard hard for me to keep a clear image of the request/response cycle in my head. I know the basics, I have written a few backend apps, but as soon as it get just a little complex, I have to keep reminding myself where the request goes through by looking at the entry point, and all the steps till the response is made. I am sure if I were able to somehow visualize it, I don't have to keep going back over and over. Instead, I would easily know where a bug would originate, for example, or where is the best place to add a certain feature.In any case, I was wondering if there is some sort of standard thing to design the request flow. I don't know, maybe a UML diagram or something?I tried to sketch it out, but I ended up with a mess. Like, I would sketch the backend design based on the features and requirements, but then the actual logic and model would be left out. Then, I try to include those in the diagram, and it becomes overly complex and cluttered with many weird arrows and boxes. I need something to backend development, like ER diagrams is for relational database design.Yeah, Sorry. I talk a lot, and I am lost in this world. Help? | Backend development philosophy | development process;tools;server;server side;google app engine | Debugging / TESTING!Unit test the heck out of your backend code. It's usually easier than unit testing frontend code, because the code isn't waiting for arbitrary clicks or keypresses. It's all this data comes in, this data goes out. Aggressive unit testing will speed you up phenomenally because you don't have to go all the way back to the start to validate each little bit of code. And then you'll have those tests around as regression testing.There is a TDD (Test-driven development) that says you should write your tests first, and then fill in the code that makes them work. But I can only do that halfway, and claim that I'm using London style. But if that appeals to you, it is a good practice.As a high water mark: in Python, I aim for 100% test coverage & it's pretty easy hitting that.I'm one of those guys who almost never uses a debugger. Rather, I use unit tests to make gurantees about behavior and sensible logging. But that's just my preference.ParallelismMore important to get the thing working at all IMHOVisualizingI find these diagrams essential for my work: sequence diagram, and (less so) ER diagram and state diagramCheck out http://websequencediagrams.com . It will save your life on a complicated project, and even on simple ones really help visualize the client-server interactions.If you draw a sequence diagram, not only will it show the client-server interactions, but every arrow pointing at your service is an API method you must implement. Pretty handy & very direct.Yes, I use ER diagrams for both database design and class design when the data reaches a certain complexity.Sometimes a state diagram can be very useful.My opinion is that backend development is easier than frontend devleopment because I see my job as moving bytes from here to there. But that may be just because I'm really bad at frontend development. |
_unix.250811 | If I set the EDITOR environment variable to emacs in bash, running crontab -e will open the crontab in emacs. When I set it in fish with set -U EDITOR emacscrontab opens with vim. What can I do to get crontab to open with emacs? | Programs don't see fish environment variables | environment variables;fish | null |
_webapps.95018 | I have an old and a new Google account to work on Drive. On my old Drive I have a lot of shared folders from customers. Now I don't want to ask all my customers to invite my new account to their folders again.Is there a way I can merge/combine my old account to my new account? I've read this article, but I was hoping there would be a more easy way. | How to merge/combine two Google Drive accounts? | google drive;google account | null |
_unix.109655 | I got curious about why not so many people have Solaris in their desktops and laptops. I wonder whether it's a good idea at all, or something just for the absolute geek.Could I maybe give it a try either in an open server online or through a live-cd?What difficulties would I expect to find and what version is good for beginners? | Moving to Solaris (from Linux) | solaris | null |
_unix.379100 | I can't remove /etc/group- -- why not?root@dom:/etc# whoamirootroot@dom:/etc# pwd/etcroot@dom:/etc# rm -f /etc/group-rm: cannot remove /etc/group-: Device or resource busyroot@dom:/etc# fuser -v /etc/group-root@dom:/etc# mountsysfs on /sys type sysfs (rw,nosuid,nodev,noexec,relatime)proc on /proc type proc (rw,nosuid,nodev,noexec,relatime)udev on /dev type devtmpfs (rw,relatime,size=10240k,nr_inodes=2040032,mode=755)devpts on /dev/pts type devpts (rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000)tmpfs on /run type tmpfs (rw,nosuid,relatime,size=3280816k,mode=755)/dev/sde1 on / type ext4 (rw,relatime,errors=remount-ro,data=ordered)securityfs on /sys/kernel/security type securityfs (rw,nosuid,nodev,noexec,relatime)tmpfs on /dev/shm type tmpfs (rw,nosuid,nodev)tmpfs on /run/lock type tmpfs (rw,nosuid,nodev,noexec,relatime,size=5120k)tmpfs on /sys/fs/cgroup type tmpfs (ro,nosuid,nodev,noexec,mode=755)cgroup on /sys/fs/cgroup/systemd type cgroup (rw,nosuid,nodev,noexec,relatime,xattr,release_agent=/lib/systemd/systemd-cgroups-agent,name=systemd)pstore on /sys/fs/pstore type pstore (rw,nosuid,nodev,noexec,relatime)cgroup on /sys/fs/cgroup/cpuset type cgroup (rw,nosuid,nodev,noexec,relatime,cpuset)cgroup on /sys/fs/cgroup/cpu,cpuacct type cgroup (rw,nosuid,nodev,noexec,relatime,cpu,cpuacct)cgroup on /sys/fs/cgroup/devices type cgroup (rw,nosuid,nodev,noexec,relatime,devices)cgroup on /sys/fs/cgroup/freezer type cgroup (rw,nosuid,nodev,noexec,relatime,freezer)cgroup on /sys/fs/cgroup/net_cls,net_prio type cgroup (rw,nosuid,nodev,noexec,relatime,net_cls,net_prio)cgroup on /sys/fs/cgroup/blkio type cgroup (rw,nosuid,nodev,noexec,relatime,blkio)cgroup on /sys/fs/cgroup/perf_event type cgroup (rw,nosuid,nodev,noexec,relatime,perf_event)systemd-1 on /proc/sys/fs/binfmt_misc type autofs (rw,relatime,fd=22,pgrp=1,timeout=300,minproto=5,maxproto=5,direct)debugfs on /sys/kernel/debug type debugfs (rw,relatime)mqueue on /dev/mqueue type mqueue (rw,relatime)hugetlbfs on /dev/hugepages type hugetlbfs (rw,relatime)fusectl on /sys/fs/fuse/connections type fusectl (rw,relatime)/dev/sda1 on /var type ext4 (rw,relatime,errors=remount-ro,data=ordered)/dev/sdd1 on /opt type ext4 (rw,relatime,errors=remount-ro,data=ordered)/dev/sdc1 on /mediafiles type ext4 (rw,relatime,errors=remount-ro,data=ordered)/dev/sdb1 on /mediafiles/blurays type ext4 (rw,relatime,errors=remount-ro,data=ordered)rpc_pipefs on /run/rpc_pipefs type rpc_pipefs (rw,relatime)tmpfs on /run/user/0 type tmpfs (rw,nosuid,nodev,relatime,size=1640408k,mode=700)tmpfs on /run/user/1000 type tmpfs (rw,nosuid,nodev,relatime,size=1640408k,mode=700,uid=1000,gid=1000)root@dom:/etc# uname -aLinux dom 3.16.0-4-amd64 #1 SMP Debian 3.16.43-2+deb8u2 (2017-06-26) x86_64 GNU/Linuxroot@dom:/etc# lsof +D /etcCOMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEopenvpn 1855 nobody cwd DIR 8,65 4096 13634055 /etc/openvpnjsvc 2070 root 3r REG 8,65 1649 13634356 /etc/java-8-openjdk/jvm-amd64.cfgjsvc 2070 root 4r REG 8,65 1649 13634356 /etc/java-8-openjdk/jvm-amd64.cfgjsvc 2078 root 3r REG 8,65 1649 13634356 /etc/java-8-openjdk/jvm-amd64.cfgjsvc 2078 root 4r REG 8,65 1649 13634356 /etc/java-8-openjdk/jvm-amd64.cfgjsvc 2079 root 3r REG 8,65 1649 13634356 /etc/java-8-openjdk/jvm-amd64.cfgjsvc 2079 root 4r REG 8,65 1649 13634356 /etc/java-8-openjdk/jvm-amd64.cfgmc 3538 root cwd DIR 8,65 12288 13631489 /etcbash 3547 root cwd DIR 8,65 12288 13631489 /etcmc 5549 root cwd DIR 8,65 12288 13631489 /etcbash 5551 root cwd DIR 8,65 12288 13631489 /etclsof 5928 root cwd DIR 8,65 12288 13631489 /etclsof 5929 root cwd DIR 8,65 12288 13631489 /etcroot@dom:/etc# ls -l /etc/group--rw------- 1 root root 1168 Jul 17 21:53 /etc/group-root@dom:/etc# ls -l /|grep etcdrwxr-xr-x 153 root root 12288 Jul 17 21:57 etcroot@dom:/etc# | Debian - cannot delete /etc/group- -- Device or resource busy | debian;files;rm;firejail | null |
_unix.60965 | Qt applications are deleting non-latin characters from ISO-8859 encoded files on my Gentoo system. Actually I'm trying to merge two German files with KDiff3 and P4Merge (making Whlen out of Whlen). Both tools don't display the Umlauts and when the file is saved, they also disappear in the file. The Dejavu Monospace font is used, Courier New shows the same behavior.If UTF-8 encoded files are presented to the tools, all non-latins are handled correctly.GTK Meld (and all other GTK apps) handles the chars (ISO-8859-1 and UTF-8) quite well. I believe its my Locale configuration, but can't discern what's amiss...Any ideas?Configs: $ locale -a C POSIX de_DE de_DE.iso88591 de_DE.iso885915@euro de_DE.utf8 de_DE@euro deutsch en_US en_US.iso88591 en_US.utf8 german $ locale LANG=en_US.UTF-8 LC_CTYPE=en_US.UTF-8 LC_NUMERIC=en_US.UTF-8 LC_TIME=en_US.UTF-8 LC_COLLATE=C LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8 LC_PAPER=en_US.UTF-8 LC_NAME=en_US.UTF-8 LC_ADDRESS=en_US.UTF-8 LC_TELEPHONE=en_US.UTF-8 LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=en_US.UTF-8 LC_ALL=Qt use flags for x11-libs/qt-core-4.8.2:4:exceptions glib iconv qt3support ssl (-aqua) -c++0x -debug -icu -pch(-optimized-qmake%) (-qpa%) | Encoding Problem: Qt Apps delete all non ASCII chars from files | gentoo;character encoding;locale;qt | null |
_cogsci.7847 | The term Shiny Object Syndrome is used to describe the tendency to start new ideas without thinking them through, especially in business.Does this phrase represent an actual clinical diagnosis? Are there people who are more likely than others to be distracted by shiny objects? Can shiny objects cause further effects other than distraction? | Is there really a Shiny Object Syndrome? | cognitive psychology;attention | null |
_softwareengineering.253968 | Recently, I was in a situation where I wanted to release a simple piece of JavaScript software under an open source license.However, I withdrew from it because the software contained several open source components that were released under different licenses.Under what license should the bundled software be released (given that various third party components are mixed into the software at code level)? | How to release bundled software with different licenses? | licensing | If parts of the bundle are under licenses that don't allow sublicensing (which is true for the majority of licenses), then you can't distribute that bundle under a single license.The best option in that case is to explicitly state that different parts of the software are distributed under different licenses and to clearly indicate which parts fall under which license (down to identifying individual function if needed).This can also be used if a single file contains parts that are under different licenses.This is under the assumption that the licenses are compatible with each other and that you are thus allowed to distribute the software and that the bundle form one piece of software (it is not just a convenient collection of independent pieces of software).If you have a bundle of independent pieces of software, then that bundle is not considered a work under copyright law and thus doesn't have a copyright of its own. |
_codereview.96927 | I would like to create a wrapper for a Boost conditional variable:class Cond_wrap{private: boost::condition_variable cond; boost::mutex mutex; bool work_to_do;public: Cond_wrap() { work_to_do = false; } void notify_all() { boost::mutex::scoped_lock lock(mutex); work_to_do = true; cond.notify_all(); } void wait() { boost::mutex::scoped_lock lock(mutex); while(!work_to_do) { cond.wait(lock); work_to_do = false; } } bool timed_wait(unsigned int timeout) { boost::mutex::scoped_lock lock(mutex); if(!work_to_do) { if(cond.timed_wait(lock, boost::chrono::milliseonds(timeout))) { work_to_do = false; return true; } else { return false; } } else { return false; }};Cond_wrap condition_wrap;void worker_func(){ { condition_wrap.notify_all(); } std::cout << After notify << std::endl;}int main(){ boost::thread work(worker_func); work.detach(); { boost::this_thread::sleep_for(boost::chrono::milliseonds(500)); condition_wrap.wait(); //there is work to do } return 0;}What is the main goal of that wrapper? I would like to avoid a situation in which a condition will be notified before I call waiter. Regarding this, I want to provide a help variable bool which should remember if a condition was previously set.Small example of what I mean:boost::condition_variable cond;boost::mutex mutex;void worker_func(){ cond.notify_all(); std::cout << After notify << std::endl;}void main(){ boost::mutex::soped_lock lock(mutex); boost::thread work(worker_func); boost::this_thread::sleep_for(boost::chrono::milliseonds(500)); cond.wait(lock); // here is deadlock}The wrapper is also provides an easier way of using a Boost conditional variable. | Boost condition variable wrapper | c++;boost;synchronization | The short answer here is: don't do this. It does not make boost::condition_variable easier to use. You're actually just limiting what you can do with it. You're not even exposing the entire interface... But if you insist on doing such a thing, your wrapper is close. You're not handling spurious wakeup in timed_wait() - that can return true even without being signaled. You should just take advantage of the fact that the various wait() overloads also take a predicate:void wait(){ boost::mutex::unique_lock lock(mutex); cond.wait(lock, [this]{ return work_to_do; }); work_to_do = false;}bool timed_wait(unsigned int timeout){ boost::mutex::unique_lock lock(mutex); if (cond.timed_wait(lock, boost::chrono::milliseconds(timeout), [this]{ return work_to_do; }) { work_to_do = false; return true; } else { return false; }}Really adding predicates is the way to handle calling wait() after the notify was called. The wrapper is not a good solution to this in my opinion. |
_webapps.13664 | On Youtube's browse page I am shown the most viewed videos in my country. Even if I change my country in the settings, it will still show the same results.I would like to see the most viewed videos of each category without the location bias. | How to browse videos on Youtube without location bias? | youtube | null |
_codereview.92919 | Things to deal with this problem.An infinite Arithmetic progression.A prime number. - p.The starting number of an Arithmetic Progression. - a.Common difference in the arithmetic progression given to him. - d.You have to print the first index of a number in that Arithmetic Progression, which is a multiple of the given prime number, p.Input format: The first line contains a number, tc, denoting the number of test cases. After that follow tc number of test cases, each is 2 lines - the first contains two integers, a and d - a depicts the first term in the AP, d depicts the common difference. The next line contains the prime number.Output format: You have to print the FIRST index (0-based) of the multiple of the given prime number in the given AP. If no such element exists in this infinite AP, then print -1.Constraints: 0 <= a, d, <= 10^18 1 <= p <= 10^9My code: public static void main(String[] args) throws NumberFormatException, IOException{StringBuilder output = new StringBuilder(); BufferedReader reader= new BufferedReader(new InputStreamReader(System.in)); int noOfTestCaseT=Integer.parseInt(reader.readLine().trim()); while (noOfTestCaseT != 0){ noOfTestCaseT--; String[] inputAandD = reader.readLine().split( ); long firstElement = Long.parseLong(inputAandD[0].trim()); long commonDifference = Long.parseLong(inputAandD[1].trim()); long primeNo = Long.parseLong(reader.readLine().trim()); firstElement %= primeNo; commonDifference %= primeNo; int result = 0; if(commonDifference == 0) output.append(-1); else if (firstElement == 0) output.append(0); else{ long inverseMod = getPowerValue(commonDifference, primeNo); result = (int) ((inverseMod * (primeNo-firstElement)) % primeNo) ; output.append(result); } output.append(\n); } System.out.println(output); } private static long getPowerValue(long base, long primeNo) { long exp = primeNo -2; long powerResult = 1; while (exp > 0){ if ((exp & 1) == 1) powerResult = (powerResult * base) % primeNo; base = (base * base) % primeNo; exp = exp >> 1 ; } return powerResult; }How could I can optimize this code further so that its performance improves (though the solution is within the given time limit and I really want to know what are the possible improvement I can make)? | First index of number in the arithmetic progression (which is multiple of prime) | java;performance;programming challenge | Time elapsed is almost all in overheadI'm not sure you can do any better than what you've done. I tested your program and it ran extremely fast. In fact, I determined that most of the time was probably being spent bringing up the JVM. I ran your program with varying test inputs (up to 100000 test case input), and also ran your program without computing the result (just reading the input and outputting one number per test case). The timings showed that most of the time was being spent just bringing up the JVM (or some other Java related overhead):100000 test case (times are in seconds)0.14: bringing up the JVM0.19: parsing the input and generating output0.12: calculating the answer0.45: total time100 test case0.14: bringing up the JVM0.02: parsing the input and generating output0.01: calculating the answer0.17: total timeSo I believe that your actual algorithm runs for about 0.01 seconds out of 0.17 total time.C program was faster (less overhead?)I converted your program to C and tested it to see if it would run any faster. It did run faster, probably because of the lack of overhead:100000 test case (C program)0.29: total time100 test case (C program)0.01: total timeHere is the C program, just to show you that it is exactly the same as your java program:#include <stdio.h>static long long getPowerValue(long long base, long long primeNo);int main(void){ int noOfTestCaseT = 0; long long firstElement, commonDifference, primeNo; scanf(%d, &noOfTestCaseT); while (noOfTestCaseT != 0){ noOfTestCaseT--; scanf(%lld %lld %lld, &firstElement, &commonDifference, &primeNo); firstElement %= primeNo; commonDifference %= primeNo; if(commonDifference == 0) puts(-1\n); else if (firstElement == 0) puts(0\n); else { long long inverseMod = getPowerValue(commonDifference, primeNo); int result = (int) ((inverseMod * (primeNo-firstElement))%primeNo); printf(%d\n, result); } } return 0;}static long long getPowerValue(long long base, long long primeNo){ long long exp = primeNo -2; long long powerResult = 1; while (exp > 0){ if ((exp & 1) == 1) powerResult = (powerResult * base) % primeNo; base = (base * base) % primeNo; exp = exp >> 1 ; } return powerResult;}A slightly faster inverse mod functionFrom wikipedia, I copied this algorithm for finding the inverse mod. Supposedly, it is slightly faster than the algorithm you are using. Using the 100000 test case input, I found that it was a little bit faster, but not by much (maybe 10% faster). Here is the function (it replaces your getPowerValue function):private static long inverse(long a, long n){ long t = 0; long newt = 1; long r = n; long newr = a; while (newr != 0) { long quotient = r / newr; long tmp; tmp = newt; newt = t - quotient * newt; t = tmp; tmp = newr; newr = r - quotient * newr; r = tmp; } if (t < 0) t += n; return t;} |
_softwareengineering.231871 | Can you recommend a nice way of checking a particular value between calls to a set of functions?E.g. something like this in Python (might not be terribly 'Pythonic'):self.error_code = 0 # this will be set by each function if an error has occurredself.function_list = [self.foo, self.bar, self.qux, self.wobble]...def execute_all(self): while not self.error_code and self.function_list: func = self.function_list.pop() # get each function func(error_code) # call it if self.error_code: # do somethingThe idea is that subsequent functions won't be called if self.error_code is set and all functions will be called in order if all is good.Anyone can think of a better alternative to that in Python or maybe a language-agnostic approach?I want to avoid having that code in each function call (e.g. if self.error code: return) so that I don't end up with the same check across all functions. | Check some value between each function call | python;coding style;error handling;method chaining | null |
_webmaster.100464 | I went into adsense today with my usual opera browser. Things were good until I saw this new blue pop-up with a white box that showed take a look. I clicked on it and it showed a new page with an error message in the background and in the foreground an orange box. I switched to firefox, and more things came up but the side panel contained no text. Now I want to revert to the old adsense so I can access all my settings without trying to figure out each word.Is there a way to revert it? | How to revert to old google adsense interface | google adsense | For now it is possible to revert. Click on the hamburger menu (top left) and then at the bottom of the menu there is Back to previous AdSense. At some point Google will force you to use the new only.Google designed the new AdSense interface according to material design principles. On the plus side, the new interface is much better on mobile devices. I like the feature on the home page where you can hide the info you don't want to see on a daily basis.I don't like several things about it: They recently change the homepage numbers to be like 8.19K impressions which I find hard to digest. They also took away the 28 day comparison which is the thing I look at most frequently. |
_softwareengineering.304357 | I'm planning to open source an Android app that I developed against the API of a (small regional) social network.This app is the 'official' version for the website and thus allowed to use the logo and name of the website.I plan to open source it under the GPL, but:I cannot put the logo or name under the GPL (I don't own the rights)I plan to integrate icons from the Android Material Design Icon library (Creative Commons)Is there any proper way to do this while keeping everything in a single repository on Github?(Given that the app is free I can't exactly consult a lawyer.) | Integrate non-free (with permission) / differently licenced logos in GPL repository | licensing;open source;gpl;android;creative commons | null |
_softwareengineering.72740 | This is a sister question to: Is it bad to use Unicode characters in variable names?As is my wont, I'm working on a language project. The thought came to me that allowing multi-token identifiers might improve both readability and writability:primary controller = new Data Interaction Controller();# vs.primary_controller = new DataInteractionController();And whether or not you think that's a good idea*, it got me musing about how permissive a language ought to be about identifiers, and how much value there is in being so.It's obvious that allowing characters outside the usual [0-9A-Za-z_] has some advantages in terms of writability, readability, and proximity to the domain, but also that it can create maintenance nightmares. There seems to be a consensus (or at least a trend) that English is the language of programming. Does a Chinese programmer really need to be writing when email_address is the international preference?I hate to be Anglocentric when it comes to Unicode, or a stickler when it comes to other identifier restrictions, but is it really worth it to allow crazy variable names?tl;dr: Is the cost of laxity higher than the potential benefit?Why or why not? What experiences and evidence can you share in favour of or opposed to relaxed restrictions? Where do you think is the ideal on the continuum?* My argument in favour of allowing multi-token identifiers is that it introduces more sane points to break long lines of code, while still allowing names to be descriptive, and avoiding ExcessiveCamelCase and a_whole_lot_of_underscores, both of which are detrimental to readability. | How permissive should a language be about identifiers? | programming languages;language design;naming | That's rather hard to say. More permissive grammars are more difficult to parse. Ruby's optional parentheses are a good example of this. The lack of extant languages with this feature may not prove that it's a bad idea, but it doesn't help validate it either. There isn't much else to go on.If you think it's a good idea and it's relatively easy to execute, why not go ahead and do it? That's the only real way to get a definitive answer to questions like this. |
_softwareengineering.264910 | Graphics processing units (GPUs) are very common and allow for efficient, parallel processing of floating point numbers.PPUs (Physics Processing Units) used to be a buzzword several years ago but never really caught on and this kind of calculation is now handled by GPUs as well.Both of these types of hardware are specialized in the processing of a specific kind of data.Looking at the kinds of applications being developed worldwide, it seems that a great many of them have to do with text processing. Particularly when web development is considered.It seems to me that it would make sense to implement basic string operations (concatenation, reversal, maybe search, character-level operations such as replacement) at hardware level, possibly making those operations orders of magnitude faster than they are when performed on a typical CPU.Does this sort of hardware exist? If it doesn't, what makes it infeasible? Varying length? Arbitrary encoding? I believe these are a bit similar to what we've got in case floating point numbers (varying precision, different encodings possible).I know some vendors sell devices specifically designed to handle text processing/search. The Google Search Appliance is an example thereof but as far as I know, it's just a normal computer with dedicated software and the hardware does not feature anything as exotic as a processor specifically design to crunch text. | Hardware accelerated text processing | hardware;cpu;text processing;gpu | (Disclaimer: I don't have information on the percentages of occurrence of various elementary string operations found in common software. The following answer is just my two cents of contribution to address some of your points.)To give a quick example, Intel provides SIMD instructions for accelerating string operations in its SSE 4.2 instruction set (link to wikipedia article). Example of using these instructions to build useful language-level string functions can be found on this website.What do these instructions do?Given a 16-byte string fragment (either 16 counts of 8-bit characters or 8 counts of 16-bit characters), In Equal Each mode, it performs an exact match with another string fragment of same length.In Equal Any mode, it highlights the occurrence of characters which match a small set of characters given by another string. An example is aeiouy, which detects the vowels in English words.In Range comparison mode, it compares each character to one or more character ranges. An example of character range is azAZ, in which the first pair of characters specifies the range of lower-case English alphabets, and the second pair specifies the upper-case alphabets.In Equal ordered mode, it performs a substring search. (All examples above are taken from the above linked website, with some paraphrasing.)Before beginning a discussion on this topic, it is necessary to gather the prerequisite knowledge needed for such discussion.It is assumed that you already have college-level introductory knowledge of:CPU architectureDigital design and synthesis, which teaches introductory level of Hardware Description Language, such as Verilog or VHDL.And finally, a practicum project where you use the above knowledge to build something (say, a simple 16-bit ALU, or a multiplier, or some hardware input string pattern detection logic based on state machine), and perform a cost counting (in logic gates and silicon area) and benchmarking of the things being built.First of all, we must revisit the various schemes for the in-memory representation of strings. This is because the practicum in hardware design should have informed you that a lot of things in hardware had to be hard-wired. Hardware can implement complex logic but the wiring between those logic are hard-wired.My knowledge in this aspect is very little. But just to give a few examples, rope, cord, twine, StringBuffer (StringBuilder) etc. are all legit contenders for the in-memory representation of strings.Even in C++ alone, you still have two choices: implicit-length strings (also known as null-terminated strings), and explicit-length strings (in which the length is stored in a field of the string class, and is updated whenever the string is modified).Finally, in some languages the designer has made the decision of making string objects immutable. That is, if one wish to modify a string, the only way to do so is to:Copy the string and apply the modification on-the-fly, orRefer to substrings (slices) of the original immutable string and declare the modifications that one wish to have applied. The modification isn't actually evaluated until the new result is consumed by some other code.There is also a side question of how strings are allocated in memory.Now you can see that, in software, a lot of wonderful (or crazy) design choices exist. There has been lots of research into how to implement these various choices in hardware. (In fact, this has been a favorite way of formulating a master's thesis for a degree in digital design.)All this is fine, except that due to economic reasons, a hardware vendor cannot justify the cost of supporting a language/library designer's crazy ideas about what a string should be.A hardware vendor typically has full access to every master's thesis written by every student (in digital design) in the world. Thus, a hardware vendor's decision of not including such features must be well-informed.Now let's go back to the very basic, common-sense question: What string operations are among the most-frequently performed in the typical software, and how can they benefit from hardware acceleration?I don't have hard figures, but my guess is that string copying verbatim is probably the #1 operation being performed.Is string copying already accelerated by hardware? It depends on the expected lengths of strings. If the library code knows that it is copying a string of several thousand characters or more, without modification, it could have easily converted the operation into a memcpy, which internally uses CPU SIMD (vectorized instructions) to perform the memory movement.Furthermore, on these new CPU architectures there is the choice of keeping the moved string in CPU cache (for subsequent operations) versus removing it from the CPU cache (to avoid cache pollution).But how often does one need to copy such long strings?It turns out that the standard C++ library had to optimize for the other case:https://stackoverflow.com/questions/21694302/what-are-the-mechanics-of-short-string-optimization-in-libcThat is, strings with lengths in the low-ten's occur with such high frequency that special cases have to be made to minimize the overhead of memory management for these short strings. Go figure. |
_softwareengineering.147149 | I am recently building a basic ray tracer in C# from scratch, as a learning/teaching project. A previous release of the project (let's call it A) does reflections and diffuse shading. The program renders the scene at around 900ms. Now I've just made a release B which adds specular highlights. Naturally, I assumed rendering time would increase. Imagine my surprise when the same scene rendered in a speedy 120ms! The results are absolutely the same (since the objects in the scene don't actually have specular highlights). Curious, I tried to narrow down what part of the code is actually making it faster. I think I've narrowed it down to a calculation that is made in both the reflection component, and the specular component (calculating the reflection vector). For each iteration of the ray tracing, both calculate the same vector (same inputs, same output), but there is no data sharing between the two. So I was wondering if C# is somehow caching the results which would account for the performance increase?Here's the code for the reflection renderingprivate Color TraceReflection(Ray ray, Vector3D normal, Vector3D hitPoint, IPrimitive hitObject, int Level) { //Calculate reflection direction var reflectionDir = (ray.Direction - (2 * (ray.Direction * normal) * normal)).Normalize(); //Create reflection ray from just outside the intersection point, and trace it var reflectionRay = new Ray(hitPoint + reflectionDir * Globals.Epsilon, reflectionDir); //Get the color from the reflection var reflectionColor = RayTrace(reflectionRay, Level + 1); //Calculate final color var resultColor = reflectionColor * hitObject.PrimitiveMaterial.ReflectionCoeff; return resultColor; }And here's the specular highlight function:public Color GetColor(IPrimitive HitObject, ILight Light, Vector3D ViewDirection, Vector3D LightDirection, Vector3D Normal) { //Caulcate reflection vector var reflectionDirection = (LightDirection - (2 * LightDirection * Normal) * Normal).Normalize(); var dot = reflectionDirection * ViewDirection; //if the dot product is zero or less that means the angle between the two vectors is 90 or more and no highlighting occurs. if (dot > 0) { var specularPower = HitObject.PrimitiveMaterial.SpecularCoeff * Math.Pow(dot, HitObject.PrimitiveMaterial.SpecularExponent); var highlightColor = HitObject.PrimitiveMaterial.DiffuseColor * specularPower; return highlightColor; } return new Color(); }UPDATEThe previous numbers were when both programs were running in debug mode. I just switched them both to release, and the numbers are what I was expecting them to be in the first place (270ms without specular. 380ms with specular). So it seems the debug mode, somehow, is the culprit. | Does C# Cache Calculation Results? | c#;caching | It's entirely possible that, in debug mode, the compiler is much more relaxed about when and where it optimizes code - so that your non-specular implementation is compiled as a significantly less optimized executable (since it's not doing that badly), while the specular implementation hits a threshold and is bumped to a slower but more optimized compilation mode. |
_webmaster.17880 | I know how to do this in an Apache2 config file and my own DNS configuration... But here I'm forced to host the site at Google Apps and the DNS at Goddady.com. What's the easiest way to alias example.com to www.example.com in this situation? I'm sure I need a forwarding mechanism. Without introducing an intermediary Apache server just for this purpose, if at all possible.. | When using Google Sites with a Godaddy domain, how do you alias example.com to www.example.com? | 301 redirect;godaddy;google apps;no www | null |
_webapps.101247 | How can I find all Google Docs documents shared with me that I didn't add to My Drive yet?I can do it one by one (right click on a document in Shared With Me folder. If it has Move to My Drive menu option, it wasn't added yet, otherwise it did).But this is slow and inefficient, especially if I have lots of documents shared with me but very few that aren't in My Drive already.Is there an efficient way to filter all Google Docs documents shared with me that I didn't add to My Drive yet? | How can I find all Google Docs documents shared with me that I didn't add to My Drive yet? | google drive;search | null |
_codereview.148171 | I wrote this program as an assignment for an introductory programming course in Java, which I then decided to improve past the minimum assignment requirements. It allows two human players to play Connect Four. (If you don't know this game, its rules are explained in the code below.)I would appreciate any feedback such as feature suggestions, bug fixes, optimizations, or other improvements!/*ConnectFourby JugheadNovember 27th, 2016This program lets two human players play Connect Four.*/import java.util.Scanner;public class ConnectFour { public static void main(String[] args) { int turnAlternator, turnNumber, match, player, player1Wins, player2Wins; final int NUMBER_OF_ROWS, NUMBER_OF_COLUMNS, MINIMUM_CHAIN_TO_WIN; String player1GamePiece, player2GamePiece; boolean gameOver; String[][] gameBoard; Object [] gameOverAndPlayer1WinsAndPlayer2Wins; //Object array of following variables: gameOver, player1Wins, and player2Wins. System.out.println( ____ ___ _ _ _ _ _____ ____ _____ _____ ___ _ _ ____ \n / ___/ _ \\| \\ | | \\ | | ____/ ___|_ _| | ___/ _ \\| | | | _ \\ \n + | | | | | | \\| | \\| | _|| | | | | |_ | | | | | | | |_| |\n| |__| |_| | |\\ | |\\ | |__| |___ | | | _|| |_| | |_| | _ | \n + \\____\\___/|_| \\_|_| \\_|_____\\____| |_| |_| \\___/ \\___/|_| \\_\\\n\n + Connect Four is a two-player connection game in which the players\nfirst choose a colour and then take turns dropping colored discs\nfrom the top into a seven-column, six-row grid. + The pieces fall\nstraight down, occupying the next available space within the column.\nThe objective of the game is to connect four of one's own discs of\nthe same color next to each other vertically, horizontally, or\ndiagonally before your opponent.\n); //Intro text. NUMBER_OF_ROWS = 6;//Number of game board rows. NUMBER_OF_COLUMNS = 7;//Number of game board columns. MINIMUM_CHAIN_TO_WIN = 4;//Minimum number of sequential game pieces needed to win. player1GamePiece = ;//Sets Player 1 game piece. player2GamePiece = ;//Sets Player 2 game piece. gameOverAndPlayer1WinsAndPlayer2Wins = new Object[] {false, 0, 0}; //Setting default values for gameOverAndPlayer1WinsAndPlayer2Wins. gameOver = (boolean)gameOverAndPlayer1WinsAndPlayer2Wins[0]; player1Wins = (int)gameOverAndPlayer1WinsAndPlayer2Wins[1]; player2Wins = (int)gameOverAndPlayer1WinsAndPlayer2Wins[2]; outerLoop://Tracks number of matches played. for (match = 1; ; match++) { gameBoard = emptyBoard(NUMBER_OF_ROWS, NUMBER_OF_COLUMNS);//Resets game board. turnNumber = 1; System.out.println(_____________________________________________\nMatch: + match + | Turn: + turnNumber + \n);//Match and turn info. turnNumber++; printBoard(gameBoard);//Displays board. player = startingPlayerTurn(player1Wins, player2Wins);//Decides starting player turn. for (turnAlternator = player; ; turnAlternator++, turnNumber++) {//Tracks turn number and alternates between player turns. if (turnAlternator % 2 == 0) { player = 2; } else { player = 1; } dropPiece(gameBoard, getColumn(player, NUMBER_OF_COLUMNS, player1GamePiece, player2GamePiece) - 1, player, NUMBER_OF_COLUMNS, player1GamePiece, player2GamePiece);//Drops game piece into selected column. System.out.println(); System.out.println(_____________________________________________\nMatch: + match + | Turn: + turnNumber + \n);//Match and turn info. printBoard(gameBoard); gameOverAndPlayer1WinsAndPlayer2Wins = checkForWin(gameBoard, gameOverAndPlayer1WinsAndPlayer2Wins, NUMBER_OF_COLUMNS, MINIMUM_CHAIN_TO_WIN, player1GamePiece, player2GamePiece);//Checks game board for winning conditions. gameOver = (boolean)gameOverAndPlayer1WinsAndPlayer2Wins[0];//Updates gameOverAndPlayer1WinsAndPlayer2Wins. player1Wins = (int)gameOverAndPlayer1WinsAndPlayer2Wins[1]; player2Wins = (int)gameOverAndPlayer1WinsAndPlayer2Wins[2]; if (gameOver == true) {//If game is over, restarts the match. System.out.println(_____________________________________________\nPlayer 1 wins: + player1Wins + | Player 2 wins: + player2Wins);//Number of times each player has won. if (player1Wins >= 10 && player2Wins == 0) {//If Player 2 is brutally losing, ends the game. System.out.println(_____________________________________________\nPlayer 2, you should just give up now...); System.exit(0); } if (player2Wins >= 10 && player1Wins == 0) {//If Player 1 is brutally losing, ends the game. System.out.println(_____________________________________________\nPlayer 1, you should just give up now...); System.exit(0); } gameOver = false; gameOverAndPlayer1WinsAndPlayer2Wins[0] = gameOver; continue outerLoop; } } } } public static String[][] emptyBoard (int NUMBER_OF_ROWS, int NUMBER_OF_COLUMNS) {//Generates empty game board. int row, column; String[][] emptyBoard; for (row = 0, emptyBoard = new String [NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]; row < emptyBoard.length; row++) { for (column = 0; column < emptyBoard[row].length; column++) { emptyBoard[row][column] = [ ]; } } return emptyBoard; } public static void printBoard (String[][] gameBoard) {//Displays game board. int row, column, columnLabel; for (row = 0; row < gameBoard.length; row++) {//Prints each game board tile. for (column = 0; column < gameBoard[row].length; column++) { System.out.print(gameBoard[row][column]); } System.out.println(); } System.out.print( ); for (columnLabel = 1; columnLabel <= gameBoard[row - 1].length; columnLabel++) {//Adds column labels. System.out.print(columnLabel + ); } System.out.println(); } public static String[][] dropPiece (String[][] gameBoard, int column, int player, int NUMBER_OF_COLUMNS, String player1GamePiece, String player2GamePiece) {//Drops game piece into selected column. int row; outerLoop: for (row = gameBoard.length - 1; row >= -1; row--) { if (row < 0) {//If chosen column is full, asks for a different column. System.out.println(Column + (column + 1) + is already full.); dropPiece(gameBoard, getColumn(player, NUMBER_OF_COLUMNS, player1GamePiece, player2GamePiece) - 1, player, NUMBER_OF_COLUMNS, player1GamePiece, player2GamePiece); break; } if (gameBoard[row][column].equals([ ])) {//Drops game piece into next available row of the selected column. if (player == 1) { gameBoard[row][column] = [ + player1GamePiece + ]; break outerLoop; } if (player == 2) { gameBoard[row][column] = [ + player2GamePiece + ]; break outerLoop; } } } return gameBoard; } public static Object[] checkForWin (String[][] gameBoard, Object [] gameOverAndPlayer1WinsAndPlayer2Wins, int NUMBER_OF_COLUMNS, int MINIMUM_CHAIN_TO_WIN, String player1GamePiece, String player2GamePiece) {//Checks game board for winning conditions. int row, column, player1MaximumChain, player2MaximumChain, diagonalStartPoint, player1Wins, player2Wins, columnNumber, fullColumns; boolean gameOver; gameOver = (boolean)gameOverAndPlayer1WinsAndPlayer2Wins[0];//Updates Object array gameOverAndPlayer1WinsAndPlayer2Wins. Utilizing gameOverAndPlayer1WinsAndPlayer2Wins allows method checkForWin to return multiple data types. player1Wins = (int)gameOverAndPlayer1WinsAndPlayer2Wins[1]; player2Wins = (int)gameOverAndPlayer1WinsAndPlayer2Wins[2]; horizontalOuterLoop://Scanning in lines from left to right, checks game board for horizontal chains. Starts checking at top-left and stops checking at bottom-left. for (row = 0, player1MaximumChain = 1, player2MaximumChain = 1; row < gameBoard.length; row++) { for (column = 0; column < gameBoard[row].length - 1; column++){ if (gameBoard[row][column].equals([ + player1GamePiece + ]) && gameBoard[row][column + 1].equals([ + player1GamePiece + ])) { player1MaximumChain++; if (player1MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 1 won horizontally. player1Wins++; System.out.println(\nPlayer 1 won horizontally!); gameOver = true; break horizontalOuterLoop; } } else if (gameBoard[row][column].equals([ + player2GamePiece + ]) && gameBoard[row][column + 1].equals([ + player2GamePiece + ])) { player2MaximumChain++; if (player2MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 2 won horizontally. player2Wins++; System.out.println(\nPlayer 2 won horizontally!); gameOver = true; break horizontalOuterLoop; } } else { player1MaximumChain = 1; player2MaximumChain = 1; } } player1MaximumChain = 1; player2MaximumChain = 1; } verticalOuterLoop://Scanning in lines from top to bottom, checks game board for vertical chains. Starts checking at top-left and stops checking at top-right. for (row = 0, column = 0, player1MaximumChain = 1, player2MaximumChain = 1; column < gameBoard[row].length; column++) { for (row = 0; row < gameBoard.length - 1; row++){ if (gameBoard[row][column].equals([ + player1GamePiece + ]) && gameBoard[row + 1][column].equals([ + player1GamePiece + ])) { player1MaximumChain++; if (player1MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 1 won vertically. player1Wins++; System.out.println(\nPlayer 1 won vertically!); gameOver = true; break verticalOuterLoop; } } else if (gameBoard[row][column].equals([ + player2GamePiece + ]) && gameBoard[row + 1][column].equals([ + player2GamePiece + ])) { player2MaximumChain++; if (player2MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 2 won vertically. player2Wins++; System.out.println(\nPlayer 2 won vertically!); gameOver = true; break verticalOuterLoop; } } else { player1MaximumChain = 1; player2MaximumChain = 1; } } player1MaximumChain = 1; player2MaximumChain = 1; } diagonalDownRightOuterLoop1://Scanning in lines from top-left to bottom-right, checks game board for diagonal chains. Starts checking at bottom-left and stops checking at top-left. for (diagonalStartPoint = gameBoard.length - 2, player1MaximumChain = 1, player2MaximumChain = 1; diagonalStartPoint >= 0; diagonalStartPoint--) { for (row = diagonalStartPoint, column = 0; row < gameBoard.length - 1 && column < gameBoard[row].length - 1; row++, column++) { if (gameBoard[row][column].equals([ + player1GamePiece + ]) && gameBoard[row + 1][column + 1].equals([ + player1GamePiece + ])) { player1MaximumChain++; if (player1MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 1 won diagonally. player1Wins++; System.out.println(\nPlayer 1 won diagonally!); gameOver = true; break diagonalDownRightOuterLoop1; } } else if (gameBoard[row][column].equals([ + player2GamePiece + ]) && gameBoard[row + 1][column + 1].equals([ + player2GamePiece + ])) { player2MaximumChain++; if (player2MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 2 won diagonally. player2Wins++; System.out.println(\nPlayer 2 won diagonally!); gameOver = true; break diagonalDownRightOuterLoop1; } } else { player1MaximumChain = 1; player2MaximumChain = 1; } } player1MaximumChain = 1; player2MaximumChain = 1; } diagonalDownRightOuterLoop2://Scanning in lines from top-left to bottom-right, checks game board for diagonal chains. Starts checking at top-left and stops checking at top-right. for (diagonalStartPoint = 1, player1MaximumChain = 1, player2MaximumChain = 1; diagonalStartPoint < gameBoard[0].length - 1; diagonalStartPoint++) { for (row = 0, column = diagonalStartPoint; row < gameBoard.length - 1 && column < gameBoard[row].length - 1; row++, column++) { if (gameBoard[row][column].equals([ + player1GamePiece + ]) && gameBoard[row + 1][column + 1].equals([ + player1GamePiece + ])) { player1MaximumChain++; if (player1MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 1 won diagonally. player1Wins++; System.out.println(\nPlayer 1 won diagonally!); gameOver = true; break diagonalDownRightOuterLoop2; } } else if (gameBoard[row][column].equals([ + player2GamePiece + ]) && gameBoard[row + 1][column + 1].equals([ + player2GamePiece + ])) { player2MaximumChain++; if (player2MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 2 won diagonally. player2Wins++; System.out.println(\nPlayer 2 won diagonally!); gameOver = true; break diagonalDownRightOuterLoop2; } } else { player1MaximumChain = 1; player2MaximumChain = 1; } } player1MaximumChain = 1; player2MaximumChain = 1; } diagonalDownLeftOuterLoop1://Scanning in lines from top-right to bottom-left, checks game board for diagonal chains. Starts checking at bottom-right and stops checking at top-right. for (diagonalStartPoint = gameBoard.length - 2, player1MaximumChain = 1, player2MaximumChain = 1; diagonalStartPoint >= 0; diagonalStartPoint--) { for (row = diagonalStartPoint, column = gameBoard[row].length - 1; row < gameBoard.length - 1 && column > 0; row++, column--) { if (gameBoard[row][column].equals([ + player1GamePiece + ]) && gameBoard[row + 1][column - 1].equals([ + player1GamePiece + ])) { player1MaximumChain++; if (player1MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 1 won diagonally. player1Wins++; System.out.println(\nPlayer 1 won diagonally!); gameOver = true; break diagonalDownLeftOuterLoop1; } } else if (gameBoard[row][column].equals([ + player2GamePiece + ]) && gameBoard[row + 1][column - 1].equals([ + player2GamePiece + ])) { player2MaximumChain++; if (player2MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 2 won diagonally. player2Wins++; System.out.println(\nPlayer 2 won diagonally!); gameOver = true; break diagonalDownLeftOuterLoop1; } } else { player1MaximumChain = 1; player2MaximumChain = 1; } } player1MaximumChain = 1; player2MaximumChain = 1; } diagonalDownLeftOuterLoop2://Scanning in lines from top-right to bottom-left, checks game board for diagonal chains. Starts checking at top-right and stops checking at top-left. for (diagonalStartPoint = gameBoard[0].length - 2, player1MaximumChain = 1, player2MaximumChain = 1; diagonalStartPoint > 0; diagonalStartPoint--) { for (row = 0, column = diagonalStartPoint; row < gameBoard.length - 1 && column > 0; row++, column--) { if (gameBoard[row][column].equals([ + player1GamePiece + ]) && gameBoard[row + 1][column - 1].equals([ + player1GamePiece + ])) { player1MaximumChain++; if (player1MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 1 won diagonally. player1Wins++; System.out.println(\nPlayer 1 won diagonally!); gameOver = true; break diagonalDownLeftOuterLoop2; } } else if (gameBoard[row][column].equals([ + player2GamePiece + ]) && gameBoard[row + 1][column - 1].equals([ + player2GamePiece + ])) { player2MaximumChain++; if (player2MaximumChain >= MINIMUM_CHAIN_TO_WIN) {//Checks if Player 2 won diagonally. player2Wins++; System.out.println(\nPlayer 2 won diagonally!); gameOver = true; break diagonalDownLeftOuterLoop2; } } else { player1MaximumChain= 1; player2MaximumChain = 1; } } player1MaximumChain = 1; player2MaximumChain = 1; } for (columnNumber = 0, fullColumns = 0; gameOver != true && columnNumber < NUMBER_OF_COLUMNS; columnNumber++) {//If the game board is full but neither player has won, the game is drawn. if (!gameBoard[0][columnNumber].equals([ ])) { fullColumns++; if (fullColumns >= NUMBER_OF_COLUMNS) { System.out.println(\nPlayer 1 and Player 2 drew the game!); gameOver = true; } } } gameOverAndPlayer1WinsAndPlayer2Wins[0] = gameOver;//Updates gameOverAndPlayer1WinsAndPlayer2Wins. gameOverAndPlayer1WinsAndPlayer2Wins[1] = player1Wins; gameOverAndPlayer1WinsAndPlayer2Wins[2] = player2Wins; return gameOverAndPlayer1WinsAndPlayer2Wins; } public static int getColumn (int player, int NUMBER_OF_COLUMNS, String player1GamePiece, String player2GamePiece) {//Gets column choice from user. int inputAsInt; String gamePiece; if (player == 1) { gamePiece = player1GamePiece; } else { gamePiece = player2GamePiece; } Scanner scanner = new Scanner(System.in); System.out.println(_____________________________________________\nPlayer + player + , choose the column for your + gamePiece + piece.);//Shows the current player and their game piece. outerLoop: while (true) { while(!scanner.hasNextInt()) {//If input is not integer, asks user again. System.out.println(Your choice must be an integer. Try again!); scanner.next(); } inputAsInt = scanner.nextInt(); if (inputAsInt >= 1 && inputAsInt <= NUMBER_OF_COLUMNS) {//Saves input (if valid). break outerLoop; } else {//If input is not valid column, asks user again. System.out.println(Your choice must be between 1 and + NUMBER_OF_COLUMNS + . Try again!); continue; } } return inputAsInt; } public static int startingPlayerTurn (int player1Wins, int player2Wins) {//Decides starting player turn. int player; if (player1Wins == player2Wins) {//If both players have won equally often, starting player turn is randomly chosen. player = (int)((Math.random() * 2) + 1); } else if (player1Wins > player2Wins) {//If Player 1 has won more often, starting player turn is given to Player 2. player = 2; } else {//If Player 2 has won more often, starting player turn is given to Player 1 instead. player = 1; } return player; }} | Connect Four in Java | java;beginner;game;array;connect four | null |
_codereview.68107 | Is there a more clever way of writing this piece of code? It does work but I thought there might be a better way of returning a matrix from multiplying the parameter by itself.public static void Main(string[] args){ int[,] m1 = CreateMatrix(5); }static int[,] CreateMatrix(int rowscols){ int[,] result = new int[rowscols, rowscols]; int res = rowscols * rowscols; int counter= 0; for (int i = 0; i < rowscols; ++i) { for (int k = 0; k < rowscols; ++k) { result[i, k] = (res - counter); counter += 1; } } return result;} | Returning multiplied matrix array | c#;matrix | null |
_unix.42063 | I am trying to install the correct LAN card drivers on openSuse 12.1. This is the output of the log file for the autorun.sh script:-------------------------------Sun Jul 1 21:50:45 IDT 2012-------------------------------Sun Jul 1 21:59:26 IDT 2012make -C src/ cleanmake[1]: Entering directory `/home/shelly/r8168-8.031.00/src'make -C /lib/modules/3.1.0-1.2-desktop/build SUBDIRS=/home/shelly/r8168-8.031.00/src cleanmake: Entering an unknown directorymake: Leaving an unknown directorymake[1]: Leaving directory `/home/shelly/r8168-8.031.00/src'How can I figure out what went wrong? | What went wrong with this driver install? | opensuse;make | null |
_softwareengineering.300455 | I receive zip files and they have as content 8 different files, each with it's own metadata inside.I have to combine these files into 1 object containing certain metadata. The big issue here is that there will not always be 8 files and the metadata i want to retrieve could be in any of these files stored in there own way.for now i have created a factory method that initiates the correct parser for each file type and the parser returns the object with the metadata it was able to parse.Now when this is done i have 8 object's i have to merge into 1 result object with the metadata gathered from these results.so i could have something like thisobject Meta1 Meta2 Meta3 Meta4 Meta51 A - 15 RT -2 - - 15 - HIGH3 A - 15 RT HIGH4 - 65 - RT HIGHThis needs to have only 1 object as output:Meta1 Meta2 Meta3 Meta4 Meta5A 65 15 RT HIGHNow i'm wondering what would be the best strategy to solve this issueHave my parsers accept my Object as parameter, try to map the data and override if present and then return the Object to be passed again in the next ParserParse all the Object and try to merge them somehow in the endAnother strategy? | Parsing an object from multiple source files | design patterns;object oriented design | Here I describe some similar work I did. Perhaps it will work for you. I had 7 different file formats across 2 different files. What I must assume is that your meta-data is effectively keys. Otherwise how can one possibly know which records to merge?Create a CommonData classA single class to hold any record from any file.A property for each possible meta-field from any incoming fileA property to hold the entire recordAs you clearly illustrate - Where meta-fields are the same, there is only one. I.E. only 1 Meta1, Meta2Populate only the appropriate meta fields for a given file/record format. An enum identifing the record type - what file it comes from essentially; or for me, the file format.Has an IEqualityComparerCommonDataEqualityComparerImplements IEqualityComparerIn my solution your meta data were my keys that defined equality for each given record type (file).The equality-comparer object is passed into the CommonData constructor.An enum to identify each source file or unique file format. The Factorytakes the raw record and it's type - enum valueFactory passes to appropriate parser based on the enum valueFactory returns new CommonData object, with it's record-type-specific CommonDataEqualityComparer implementation.CommonDataCollectionBetween the equality-comparer implementations and RecordType property we can find, match, etc. records for each file type. |
_unix.134896 | I have the following line in the rsyslog config file:*.*;auth,daemon,kern,user -/dev/logiand it does what it should, but I wanted to send some iptables logs to a different file, so I added the following content to the rsyslog.conf file::msg,contains,IPTABLES: /var/log/iptables& stopand I created /dev/fw device , but I have no idea how to send new content of the file to that device. Is there a way to do it? | How to redirect logs to a fifo device? | logs;rsyslog;fifo | I finally found a solution.This is the fifo device I create when system boots:LOG_DEV=/dev/logiif [ ! -r $LOG_DEV ]; then mkfifo $LOG_DEV chmod 640 $LOG_DEV chown root:morfik $LOG_DEVfiI just added this to the /etc/init.d/rsyslog file.Having that device I can send all logs there by placing the following line in the /etc/rsyslog.conf file:*.* -/dev/logiIt's the fist line in the rules section, so every log goes there and continues processing other rules in the config file. The next rule in that file is::msg,contains,IPTABLES: /var/log/iptables& stopWhich sends the iptables logs to a specific file, and after doing so, rsyslog just stops processing the entries that contain IPTABLES: phrase. The next rules are just normal rules in the rsyslog config file. So I just got what I wanted -- all logs are sent to the fifo device + a separate log file for iptables entries. |
_unix.23334 | I have this kind of GCC multilib wrapper set up:#file: gcc#!/usr/bin/env bashgcc -m32 $@which essentially just wraps a 64-bit multilib gcc to act as a non-multilib 32-bit gcc. When I build something (like binutils for example), this spawns hundreds of bash processes, until even fork fails. How can I work around this? | Simple wrapper scripts spawning 100s of bash processes | linux;bash;shell script | It appears you named your script gcc, put it in the path, and then called it recursively. Either name your script something different or use an explicit path to the gcc executable you actually want to use. |
_unix.223164 | when I run ls -l /dev/null /dev/zero /dev/tty I get:crw-rw-rw- 1 root root 1, 3 Aug 9 09:05 /dev/nullcrw-rw-rw- 1 root tty 5, 0 Aug 9 09:05 /dev/ttycrw-rw-rw- 1 root root 1, 5 Aug 9 09:05 /dev/zerowhat do the numbers 1 and 5 (after the group) indicate? | ls -l numbers between the size and the group | ls | Those files are special files called devices.They don't have a size parameter, but two number called major and minor number.Major is somehow related to type of device (terminal, disks, network interface, filesystems).Minor is related instance number.I use the word related, you simply do not count, different disk might have different major number. Computing of this two value is complex, and is mostly done by your OS.HP-UX use insf -e to create those deviceSolaris use devfsadm -c disk for diskAIX use cfgadm -a (from memory)EDIT:b) you seldom have a use for those number, as I mention misceleanous utilities manage them for you. a) you mostly cannot manualy compute those number. You know them or not. I use them only once, in HP-UX 11Iv1, volume group creation involve using mknod /dev/vgX c 64 0x010000 , 64 being major and 0X010000 being minor. It was user responsabilities to manage minor number. |
_reverseengineering.9209 | i'm getting started with some reverse engineering lately , especially on linux and ELF format , but i'm struggling here.For now i'm only using GDB to disassemble binaries , and even though i can read and understand the assembly code in general , i don't know where to look , or what register to check to find the Flag (i'm talking about CTFs here)so what i'm asking for are books , or videos , something to get me used to GDB and give me the thinking methodology (if there's such a thing).Thanks ! | Books on reversing with GDB? | disassembly;gdb | Special for beginners Dennis Yurichev wrote this book:Reverse Engineering for BeginnersYou can find it and download on his site for free.Topics discussed: x86/x64, ARM/ARM64, MIPS, Java/JVM.Topics touched: Oracle RDBMS, Itanium, copy-protection dongles, LD_PRELOAD, stack overflow, ELF, win32 PE file format, x86-64, critical sections, syscalls, TLS, position-independent code (PIC), profile-guided optimization, C++ STL, OpenMP, win32 SEH. |
_webmaster.57298 | Are there any stats about how many Google/Bing users may be selecting country (as in the pic) in the SERP?As Susan says in here that geotargeting in GWT only works when users select a country as in the pic above. If it's small percentage then there won't be much use geotargeting wesite/pages by Webmasters. | How many users see Google search results just for their own country? | geotargeting;country specific;search results | null |
_computerscience.4340 | my code :A.layout('neato', args='-Gsep=+250 -Gsplines=ortho -Goverlap=false')A.draw('1.svg')#do something, add new nodes with pos to A,add_some_nodes_to_A()for node in A.nodes(): node.attr['pos'] += '!' node.attr['pin'] = 'true'A.layout('neato', args='-Gsep=+250 -Gsplines=ortho -Goverlap=false - Gnotranslate=true')A.draw('2.svg')1.svg :2.svg : before the second layout, all A's nodes have pined, why the nodes move in 2.svg? | why pygraphviz layout() move the nodes which has 'pin = true'? | vector graphics | null |
_cs.48286 | I'm studying my notes for a formal language course and it them it statesThe vast majority of languages over a finite alphabet cannot be represented by a finite specification.I don't understand this. What is meant by specification? It then goes on to show why this is true by showing some sets of the alphabet are countably infinite and others are uncountably infinite. | What is meant by a language have a finite specification? | formal languages | null |
_softwareengineering.241054 | I have a use case where I need to create say two javascript objects & use their properties in one another. eg - var Object1 = { settings: { property1: 'someValue', property2: 'someValue' }}var Object2 = { foreignProperty: Object1.settings.property1;}I wanted to know if its alright to use a reference object for settings if I know that I will be using the settings property a lot. eg- var Object1Settings, Object1 = { settings: { property1: 'someValue', property2: 'someValue' }}var Object1Settings = Object1.settings;var Object2 = { foreignProperty: Object1Settings.property1;}Is this approach acceptable in terms of right ways of coding & performance?Thanks | Is it alright to create another reference to a javascript object just for ease of access | javascript | Not only it increases readability, but such code also runs way faster.Generally when programming I believe this is the order of priorities:ReadibilityCPU performanceSaving memoryBased on this you can see, that caching any value is probably a good idea. It costs memory and saves you CPU cycles.But I hope you do know that changing Object2.foreignProperty will render original Object1.settings.property1 unchanged. |
_unix.327865 | I've just installed the mariadb package and doesn't work (doesn't start), I've these outputs:systemctl status -l mariadb.service mariadb.service - MariaDB database server Loaded: loaded (/usr/lib/systemd/system/mariadb.service; disabled; vendor preset: disabled) Active: inactive (dead)journalctl | grep mariadb | tail action org.freedesktop.systemd1.manage-units for system-bus-name::1.110 [systemctl start mariadb.service] (owned by unix-user:velzm) dic 04 08:17:21 nmveliz systemd[1]: mariadb.service: Main process exited, code=exited, status=1/FAILURE dic 04 08:17:21 nmveliz systemd[1]: mariadb.service: Unit entered failed state. dic 04 08:17:21 nmveliz systemd[1]: mariadb.service: Failed with result 'exit-code'.systemctl status mariadb.service mariadb.service - MariaDB database server Loaded: loaded (/usr/lib/systemd/system/mariadb.service; disabled; ven Active: failed (Result: exit-code) since Sat 2016-12-03 16:44:12 CST; Process: 1959 ExecStart=/usr/sbin/mysqld $MYSQLD_OPTS $_WSREP_NEW_CLUST Process: 1906 ExecStartPre=/bin/sh -c [ ! -e /usr/bin/galera_recovery ] Process: 1903 ExecStartPre=/bin/sh -c systemctl unset-environment _WSRE Main PID: 1959 (code=exited, status=1/FAILURE)dic 03 16:44:12 nmveliz mysqld[1959]: 2016-12-03 16:44:12 1396413908 dic 03 16:44:12 nmveliz mysqld[1959]: 2016-12-03 16:44:12 1396419816 dic 03 16:44:12 nmveliz mysqld[1959]: 2016-12-03 16:44:12 1396419816 dic 03 16:44:12 nmveliz mysqld[1959]: 2016-12-03 16:44:12 1396419816 dic 03 16:44:12 nmveliz mysqld[1959]: 2016-12-03 16:44:12 1396419816 dic 03 16:44:12 nmveliz mysqld[1959]: 2016-12-03 16:44:12 1396419816 dic 03 16:44:12 nmveliz systemd[1]: mariadb.service: Main process ex dic 03 16:44:12 nmveliz systemd[1]: Failed to start MariaDB database dic 03 16:44:12 nmveliz systemd[1]: mariadb.service: Unit entered fa dic 03 16:44:12 nmveliz systemd[1]: mariadb.service: Failed with res lines 1-18/18 (END)journalctl -xedic 03 16:56:30 nmveliz mysqld[2707]: 2016-12-03 16:56:30 1401676738dic 03 16:56:30 nmveliz mysqld[2707]: 2016-12-03 16:56:30 1401676738dic 03 16:56:30 nmveliz mysqld[2707]: 2016-12-03 16:56:30 1401676738dic 03 16:56:31 nmveliz mysqld[2707]: 2016-12-03 16:56:31 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:32 nmveliz mysqld[2707]: 2016-12-03 16:56:32 1401676738dic 03 16:56:33 nmveliz mysqld[2707]: 2016-12-03 16:56:33 1401676738dic 03 16:56:33 nmveliz mysqld[2707]: 2016-12-03 16:56:33 1401670818dic 03 16:56:33 nmveliz mysqld[2707]: 2016-12-03 16:56:33 1401676738dic 03 16:56:33 nmveliz mysqld[2707]: 2016-12-03 16:56:33 1401676737dic 03 16:56:33 nmveliz mysqld[2707]: 2016-12-03 16:56:33 1401676738dic 03 16:56:33 nmveliz mysqld[2707]: 2016-12-03 16:56:33 1401676738dic 03 16:56:33 nmveliz mysqld[2707]: 2016-12-03 16:56:33 1401676738dic 03 16:56:33 nmveliz systemd[1]: mariadb.service: Main process exdic 03 16:56:33 nmveliz systemd[1]: Failed to start MariaDB database-- Subject: Unit mariadb.service has failed-- Defined-By: systemd-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel-- -- Unit mariadb.service has failed.-- -- The result is failed.dic 03 16:56:33 nmveliz systemd[1]: mariadb.service: Unit entered fadic 03 16:56:33 nmveliz systemd[1]: mariadb.service: Failed with resdic 03 16:56:33 nmveliz sudo[2649]: pam_unix(sudo:session): session | Antergos MariaDB problems | arch linux;mysql;mariadb;antergos | null |
_unix.136642 | For network catastrophe simulations of our server environment, we are looking for a way to intentionally timeout a TCP socket. Are there any simple ways for existing sockets? Also, little C test-case program would be a plus.We have already tried putting down network interfaces during TCP buffer reading, and reading from disconnected mounted resources (samba).Out test server is Ubuntu 12.04.4. | How to make a TCP socket time out | socket;timeout | To cause an exiting connection to timeout you can use iptables. Just enable a DROP rule on the port you want to disable. So to simulate a timeout for your Samaba server, while an active connection is up, execute the following on the server:sudo iptables -A INPUT -p tcp --dport 445 -j DROPThe DROP target will not reply with a RST packet or ICMP error to the packet's sender. The client will stop receiving packets from the server and eventually timeout. Depending on if/how you have iptables configured, you may want to insert the rule higher into the INPUT ruleset. |
_unix.309150 | I am trying to decrease the size of my .ppt presentations by converting them to .odp/.wps-format, since they take several GBs memory because of big pictures and audio content in slides. I would like to store the presentations in smaller space without losing quality i.e. picuters and audio. WPS OfficeWPS office > Save as > jpg of every slide; which does a very good work in extracting the images; I have not found yet any terminal tool for the task of many .ppt files; the 2-month-old release is alpha but much more stable than the previous ones (> 100 Mb .ppt files) and can render much better .ppt files than LibreOffice presentation. I already contacted the company about the task with a link to this thread. I already sent a related question in their Linux Community of the application but they have not approved it yet here.LibreOfficeI do when I have soffice in my PATH but getmasi@masi:~/$ ppt2odp test.ppt Failed to connect to /usr/lib/libreoffice/program/soffice.bin (pid=10643) in 6 seconds.Connector : couldn't connect to socket (Success)Error: Unable to connect or start own listener. Aborting.masi@masi:~/$OS: Debian 8.5 64 bitLinux kernel: 4.6Hardware: Asus Zenbook UX303UA | How to minimise size of .ppt presentations without losing Pictures and Audio in LibreOffice/WPS-office? | libreoffice;wps office | There is no sufficient extraction tool for the task at the monte, so you cannot minimise the presentation size sufficiently for the task requirement. WPS can render such documents best in Linux. The only workaround is manually store at least audios in the presentations at the moment. There should exist reliable tools for the extraction of pictures in the presentations. |
_webmaster.38196 | I'm using cPanel to host my website. I need to enable 'mod_rewrite' on this Shared Hosting cPanel account to run my script. I've tried to Google the solutions high and low but did not find any luck yet.Those tutorials that I found only work well with VPS and some of them said that, only hosting provider can change and enable it. But, some of them said that, it can be done easily by editing the .htaccess file.My question:If I want to edit the .htaccess file, what should I include in that file?What the 'rules' and 'conditions' that should be included? | Enable 'mod_rewrite' Using .htaccess File On cPanel Shared Hosting Server | apache;htaccess;mod rewrite | null |
_unix.15095 | I have the following problem. I collected data on reaction time from over 100 participants for an experiment I am running. Unfortunately, the separators between fields were not consistent, but after a lot of heartache with sed, I have managed to solve this problem.The experiment was divided into blocks (5 for each participant) and what I need is each block to be outputted on its own line, separated by commas. Here is a sample of my datafile:Participant: 2456, Test: Optimism IAT. Format is stimulus , correct(1)/incorrect(0) , time(ms). Writes 10 trials per line.17/01/2011, 12:46:03 ,Block 1: , Theirs , 1 , 1921 , Myself , 1 , 928 , Them , 1 , 716 , Theirs , 1 , 720 , Myself , 1 , 533 , Me , 1 , 596 , Themselves , 1 , 527 , Myself , 1 , 656 , Mine , 1 , 551 , Myself , 1 , 624 , Themselves , 1 , 570 , Me , 1 , 514 ,Block 1 Time,: 8856 ,Block 2: , Failing , 1 , 1835 , Happy , 1 , 1118 , Sad , 1 , 673 , Succeeding , 1 , 690 , Improving , 1 , 795 , Succeeding , 1 , 602 , Worse , 1 , 586 , Succeeding , 1 , 553 , Improving , 1 , 619 , Disimproving , 1 , 659 , Succeeding , 1 , 596 , Failing , 1 , 539 ,Block 2 Time,: 9265 ,Block 3: , Succeeding , 1 , 2881 , Disimproving , 1 , 1072 , Mine , 1 , 1120 , Me , 1 , 627 , Happy , 1 , 669 , Theirs , 1 , 1539 , Worse , 1 , 841 , Me , 1 , 862 , Sad , 1 , 1370 , Succeeding , 1 , 1115 , Worse , 1 , 855 , Theirs , 1 , 792 , Them , 1 , 627 , Better , 1 , 735 , Me , 1 , 626 , Happy , 1 , 622 , Succeeding , 1 , 616 , Mine , 1 , 646 , Them , 1 , 599 , Disimproving , 1 , 607 , Better , 1 , 799 , Myself , 1 , 1408 , Me , 1 , 463 , Better , 1 , 839 , Failing , 1 , 602 , Mine , 1 , 633 , Better , 1 , 525 , Sad , 1 , 573 , Worse , 1 , 770 , Me , 1 , 508 , Theirs , 1 , 613 , Disimproving , 1 , 649 , Improving , 1 , 701 , Theirs , 1 , 590 , Disimproving , 1 , 716 , Better , 1 , 714 ,Block 3 Time,: 29924 ,Block 4: , Them , 1 , 1659 , Myself , 1 , 1036 , Themselves , 1 , 595 , Me , 1 , 509 , Myself , 1 , 648 , Themselves , 1 , 542 , Myself , 1 , 536 , Mine , 1 , 537 , Theirs , 1 , 615 , Mine , 1 , 520 , Me , 1 , 596 , Mine , 1 , 471 ,Block 4 Time,: 8264 ,Block 5: , Mine , 1 , 1527 , Myself , 1 , 1235 , Disimproving , 0 , 2001 , Theirs , 1 , 981 , Succeeding , 1 , 1994 , Happy , 1 , 1454 , Failing , 1 , 1941 , Theirs , 1 , 1151 , Failing , 0 , 1358 , Me , 1 , 790 , Failing , 1 , 717 , Mine , 1 , 585 , Myself , 1 , 821 , Themselves , 1 , 793 , Disimproving , 1 , 965 , Succeeding , 1 , 727 , Worse , 1 , 961 , Theirs , 1 , 1259 , Mine , 1 , 578 , Better , 1 , 1112 , Mine , 1 , 1207 , Happy , 1 , 843 , Worse , 1 , 1064 , Failing , 1 , 699 , Happy , 1 , 700 , Myself , 1 , 516 , Them , 1 , 794 , Me , 1 , 526 , Sad , 1 , 1118 , Improving , 1 , 826 , Mine , 1 , 540 , Succeeding , 1 , 952 , Myself , 1 , 536 , Themselves , 1 , 851 , Improving , 1 , 865 , Mine , 1 , 582 ,Block 5 Time,: 35569 As you can see, each of the blocks take up multiple lines. I need them to take up one line in the following formatParticipant Date Time Block Word1 Correct1 Time1.....Word36 Correct36 Time362456 1 Happy 1 1200 sad 0 1500...1234 5 sad 0 1100 happy 1 900The issue is that blocks 3 &5 have 36 stimuli while blocks 1,2 &4 have 12. I need the participant, datetime and block time in each row also.Here is the script that got the data into the form you see here, but it doesn't give me each block on one line only which is what i need. Your help would be greatly appreciated. BEGIN{ FS=\\; RS=#; OFS=,; ORS=\n;}{ for(i=1;i<=NF;i++) {printf %-10s, $i; printf ,;} }I'm using gawk version 3.1.6 on Ubuntu 10.04. | Need help processing a text file with awk to conform to CSV flat file format | linux;awk;csv | If I understand correctly, your problem is coping with input where each record comes in multiple lines, and you don't detect the end of a record but rather the beginning of a new record: a new record begins whenever a line does not begin with a comma.Here's some awk boilerplate you can use to pre-process the input into records.function process (record) { RS = *, *; /*gawk allows RS to be a regexp; some implementations would require setting RS=, and manually trimming spaces*/ $0 = record; /*automatically sets $1, $2, ..., and NF*/ record = ; /*your code goes here*/}{ if (/^ *,/) {record = record $0} else {process(record); record=$0} }END { if (record != ) {process(record)} }' |
_unix.44249 | What's the best way to check if two directories belong to the same filesystem?Acceptable answers: bash, python, C/C++. | How to check if two directories or files belong to same filesystem | filesystems;files | It can be done by comparing device numbers.In a shell script on Linux it can be done with stat:stat -c %d /path # returns the decimal device number In python:os.lstat('/path...').st_devoros.stat('/path...').st_dev |
_cs.72470 | TL;DR:There're lecture notes about a very simple reduction from maximum flow with edge demands problem to the maximum flow problem. But I can't get the new capacities at the picture:E.g., look at the diagonal: 15 - 0 = 14 (?). From my point of view there're a lot of off-by-one errors. | Maximum flow with edge demands: can't understand the example of transition to transformed graph in the lecture notes | graphs;network flow;max cut | null |
_softwareengineering.294519 | I'm writing a Rails app which uses ActiveRecord ORM and a Postgres DB. I've got two attributes which are similar but are separate fields in the database. The assignment and saving of these is kinda complicated so I've put that side of things in their own method. The pseudo-code is as followsmyObject.attr_a = get_the_stuff_from( ref_one )myObject.attr_b = get_the_stuff_from( ref_two )myObject.assign_and_save( attr_a )myObject.assign_and_save( attr_b )Basically, how can I tell the assign_and_save method to distinguish between attr_a and attr_b so that they get saved into their respective columns in the database. I was thinking of using an additional flag for the method signature, but I think that stunts its re-usability.What would you recommend? | Pattern for passing in a field as a parameter | design patterns;object oriented;patterns and practices | Given that you're using Rails, the most common way to achieve what you're trying to do is to use a before_save or before_create ActiveRecord callback.class Model < AR::Base before_save :normalize_attributes private def normalize_attributes # Whatever logic you need endendmy_object.attr_a = get_the_stuff_from(ref_one)my_object.attr_b = get_the_stuff_from(ref_two)my_object.saveDepending on your logic, maybe get_the_stuff_from is better located in the model itself, so you might prefer something like:class Model < AR::Base def set_attributes(stuff_for_a: nil, stuff_for_b: nil) # Something like, depending on your logic: self.a ||= get_the_stuff_from(stuff_for_a) self.b ||= get_the_stuff_from(stuff_for_b) end private def get_the_stuff_from(ref) # Whatever logic you need endend# Eithermy_object.set_attributes(stuff_for_a: ref_one)my_object.set_attributes(stuff_for_b: ref_two)# Ormy_object.set_attributes(stuff_for_a: ref_one, stuff_for_b: ref_two)my_object.saveBut I don't know enough of your logic to say if the ||= is enough, but hopefully this will help. |
_softwareengineering.325743 | Let's say I have a class MyClass ... which has a data member xclass MyClass1 : def __init__(self) : self.x = 1Also a method which does something with xShould I pass self.x as a parameter?class MyClass2 : def __init__(self) : self.x = 1 def multiple_of_x(self, x) : return x * 2Or just use self.x within the method?class MyClass3 : def __init__(self) : self.x = 1 def multiple_of_x(self) : return self.x * 2I'm asking which is the more correct approach to object oriented programming? | Object Oriented Python methods and their parameters | object oriented;python;class design;methods | An object is a bundle of state and behavior. The behavior (methods) inherently defaults to having access to the object's state (attributes). As such, it should use that whenever it can.Think about it this way. If you had a method that needed four or five different pieces of data from the object to return a result, what would happen in each of your cases? In the first case, you'd be passing in those four or five things, every time. And you'd have to get that information from the object itself, resulting in a call like this:myobj.myfunction(myobj.w, myobj.x, myobj.y, myobj.z)The second approach would give you this:myobj.myfunction()Both give you the same result. The first has a bit more flexibility in case you ever want to pass in something that isn't part of the object. But if that's the case, why would you need the state of the object in the first place? |
_unix.128561 | Unfortunately the infrastructure I work in has static root passwords that are very rarely refreshed. So people leaving the company will have our root passwords and it can potentially be leaked to others inside the organization.So with that problem stated, what is the best method of executing a password refresh policy on linux/unix platforms?If it's the modification of the sudoers files on each host and disabling root passwords, how do you manage these sudoers files and keep everything up to date and consistent?If it's just using root keys, what can be done to protect/refresh these keys on a regular basis?Basically, how are others using tools to perform regular refreshes to ensure security? | Root Password Policy and Refresh | linux;sudo;root;password | null |
_codereview.106112 | I have this tiny library for implementing simple command line languages. It is not flexible enough for handling actual programming languages, but hopefully it may help implementing simpler REPL's faster/cleaner.CommandParser.java:package net.coderodde.commandparser;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;import java.util.Objects;/** * This class implements a command parser. * * @author Rodion rodde Efremov * @version 1.6 (Sep 30, 2015) */public class CommandParser { private final List<CommandDescriptor> commandDescriptorList = new ArrayList<>(); private boolean isSorted = true; public void add(CommandDescriptor commandDescriptor) { Objects.requireNonNull(commandDescriptor, The input command descriptor is null.); if (commandDescriptor.size() == 0) { return; } commandDescriptorList.add(commandDescriptor); isSorted = false; } public void process(String command) { if (!isSorted) { Collections.sort(commandDescriptorList, comparator); isSorted = true; } for (CommandDescriptor descriptor : commandDescriptorList) { if (descriptor.parse(command)) { return; } } } private static final class CommandDescriptorComparator implements Comparator<CommandDescriptor> { @Override public int compare(CommandDescriptor o1, CommandDescriptor o2) { CommandToken token1 = o1.getToken(0); CommandToken token2 = o2.getToken(0); if (token1.getTokenType() == CommandToken.TokenType.IDENTIFIER) { return 1; } else if (token2.getTokenType() == CommandToken.TokenType.IDENTIFIER) { return -1; } else { return 0; } } } private static final CommandDescriptorComparator comparator = new CommandDescriptorComparator();}CommandDescriptor.java:package net.coderodde.commandparser;import java.util.ArrayList;import java.util.List;import java.util.Objects;/** * This class implements a command descriptor. * * @author Rodion rodde Descriptor * @version 1.6 (Sep 30, 2015) */public class CommandDescriptor { private final List<CommandToken> commandTokenList = new ArrayList<>(); private final CommandAction commandActionOnMatch; public CommandDescriptor(CommandAction commandActionOnMatch) { this.commandActionOnMatch = commandActionOnMatch; } public void addCommandToken(CommandToken token) { Objects.requireNonNull(token, The input token is null.); commandTokenList.add(token); } public int size() { return commandTokenList.size(); } CommandToken getToken(int index) { return commandTokenList.get(index); } public boolean parse(String command) { String[] parts = command.trim().split(\\s+); if (parts.length < commandTokenList.size()) { return false; } for (int i = 0; i < commandTokenList.size(); ++i) { CommandToken token = commandTokenList.get(i); if (!token.matches(parts[i])) { return false; } } // We have a match. if (commandActionOnMatch != null) { commandActionOnMatch.act(parts); } return true; }}CommandToken.java:package net.coderodde.commandparser;import java.util.Objects;/** * This class implements a command token which may be a keyword, identifier or * value. * * @author Rodion rodde Efremov * @version 1.6 (Sep 30, 2015) */public class CommandToken { public enum TokenType { KEYWORD, IDENTIFIER, VALUE_INT, VALUE_LONG, VALUE_FLOAT, VALUE_DOUBLE } private final TokenType tokenType; private final String datum; private final IdentifierValidator identifierValidator; public CommandToken(TokenType tokenType, String datum, IdentifierValidator identifierValidator) { Objects.requireNonNull(tokenType, Input token type is null.); if (tokenType == TokenType.KEYWORD && datum == null) { throw new IllegalArgumentException(A keyword string is null for + a keyword token.); } if (tokenType == TokenType.IDENTIFIER && identifierValidator == null) { throw new IllegalArgumentException( A identifier validator is null for an identifier token.); } this.tokenType = tokenType; this.datum = datum; this.identifierValidator = identifierValidator; } TokenType getTokenType() { return tokenType; } boolean matches(String s) { Objects.requireNonNull(s, The input word is null.); s = s.trim(); switch (tokenType) { case KEYWORD: { return datum.equals(s); } case IDENTIFIER: { return identifierValidator.isValidIdentifier(s); } case VALUE_INT: { try { Integer.parseInt(s); return true; } catch (NumberFormatException ex) { return false; } } case VALUE_LONG: { try { Long.parseLong(s); return true; } catch (NumberFormatException ex) { return false; } } case VALUE_FLOAT: { try { Float.parseFloat(s); return true; } catch (NumberFormatException ex) { return false; } } case VALUE_DOUBLE: { try { Double.parseDouble(s); return true; } catch (NumberFormatException ex) { return false; } } default: throw new IllegalStateException(Should not get here ever.); } }}CommandAction.java:package net.coderodde.commandparser;/** * This class specifies a functional interface for a routine that handles a * particular command. * * @author Rodion rodde Efremov * @version 1.6 (Sep 30, 2015) */@FunctionalInterfacepublic interface CommandAction { public void act(String[] tokens);}IdentifierValidator.java:package net.coderodde.commandparser;/** * * @author rodionefremov */@FunctionalInterfacepublic interface IdentifierValidator { public boolean isValidIdentifier(String s);}Demo.java:import java.util.HashMap;import java.util.Map;import java.util.Scanner;import net.coderodde.commandparser.CommandAction;import net.coderodde.commandparser.CommandDescriptor;import net.coderodde.commandparser.CommandParser;import net.coderodde.commandparser.CommandToken;import net.coderodde.commandparser.CommandToken.TokenType;import net.coderodde.commandparser.IdentifierValidator;public class Demo { private static final class MyNewAction implements CommandAction { private final Map<String, Double> variableMap; MyNewAction(Map<String, Double> variableMap) { this.variableMap = variableMap; } @Override public void act(String[] tokens) { String varName = tokens[1]; double value = Double.parseDouble(tokens[2]); variableMap.put(varName, value); } } private static final class MyDelAction implements CommandAction { private final Map<String, Double> variableMap; MyDelAction(Map<String, Double> variableMap) { this.variableMap = variableMap; } @Override public void act(String[] tokens) { String varName = tokens[1]; variableMap.remove(varName); } } private static final class MyPlusAction implements CommandAction { private final Map<String, Double> variableMap; MyPlusAction(Map<String, Double> variableMap) { this.variableMap = variableMap; } @Override public void act(String[] tokens) { String varName1 = tokens[0]; String varName2 = tokens[2]; if (!variableMap.containsKey(varName1)) { System.out.println(varName1 + : no such variable.); return; } if (!variableMap.containsKey(varName2)) { System.out.println(varName2 + : no such variable.); return; } System.out.println(variableMap.get(varName1) + variableMap.get(varName2)); } } private static final class MyShowAction implements CommandAction { private final Map<String, Double> variableMap; MyShowAction(Map<String, Double> variableMap) { this.variableMap = variableMap; } @Override public void act(String[] tokens) { String varName = tokens[0]; if (!variableMap.containsKey(varName)) { System.out.println(varName + : no such variable.); return; } System.out.println(variableMap.get(varName)); } } private static final IdentifierValidator myIdentifierValidator = new IdentifierValidator() { @Override public boolean isValidIdentifier(String s) { if (s.isEmpty()) { return false; } char[] chars = s.toCharArray(); if (!Character.isJavaIdentifierStart(chars[0])) { return false; } for (int i = 1; i < chars.length; ++i) { if (!Character.isJavaIdentifierPart(chars[i])) { return false; } } return true; } }; private static CommandParser buildCommandParser(Map<String, Double> map) { CommandParser parser = new CommandParser(); MyNewAction newAction = new MyNewAction(map); MyDelAction delAction = new MyDelAction(map); MyPlusAction plusAction = new MyPlusAction(map); MyShowAction showAction = new MyShowAction(map); //// Start creating command descriptors. // 'new' command. CommandDescriptor descriptorNew = new CommandDescriptor(newAction); descriptorNew.addCommandToken(new CommandToken(TokenType.KEYWORD, new, null)); descriptorNew.addCommandToken(new CommandToken(TokenType.IDENTIFIER, null, myIdentifierValidator)); descriptorNew.addCommandToken(new CommandToken(TokenType.VALUE_DOUBLE, null, null)); // 'del' command. CommandDescriptor descriptorDel = new CommandDescriptor(delAction); descriptorDel.addCommandToken(new CommandToken(TokenType.KEYWORD, del, null)); descriptorDel.addCommandToken(new CommandToken(TokenType.IDENTIFIER, null, myIdentifierValidator)); // '+' command. Adding two variable. If you want to add with constants // as well, just adde more descriptors with particular IDENTIFIER // tokens. CommandDescriptor descriptorPlus = new CommandDescriptor(plusAction); descriptorPlus.addCommandToken(new CommandToken(TokenType.IDENTIFIER, null, myIdentifierValidator)); descriptorPlus.addCommandToken(new CommandToken(TokenType.KEYWORD, +, null)); descriptorPlus.addCommandToken(new CommandToken(TokenType.IDENTIFIER, null, myIdentifierValidator)); // 'show' command. CommandDescriptor descriptorShow = new CommandDescriptor(showAction); descriptorShow.addCommandToken(new CommandToken(TokenType.IDENTIFIER, null, myIdentifierValidator)); parser.add(descriptorNew); parser.add(descriptorDel); parser.add(descriptorPlus); parser.add(descriptorShow); return parser; } public static void main(String[] args) { Map<String, Double> variableMap = new HashMap<>(); CommandParser parser = buildCommandParser(variableMap); Scanner scanner = new Scanner(System.in); while (true) { System.out.print(> ); String command = scanner.nextLine().trim(); if (command.equals(quit)) { break; } parser.process(command); } System.out.println(Bye!); }}A simple session might go this way:> new A 29> new B 26> A29.0> B26.0> B + A55.0> del B> B + AB: no such variable.> quitBye! | Simple REPL command parser in Java | java;console;library | null |
_webapps.22033 | When I do Ctrl+F in Google Docs, it shows the document find view. What I would like is the browser find view when in Google Chrome. What keys do I need to press to do a browser Ctrl+F in Google Docs in Google Chrome? Currently the web app will take control of that hotkey combination when opened. | Ctrl + F not working for browser page search when using Google Docs | google drive;search;google chrome | You are looking for a keyboard solution that will open the Chrome find bar even when Ctrl+F is redefined on the page.Judging by the keys you normally use, you are a Windows user. On Windows, press Alt+F, then press F. This solution uses menu shortcuts to open the find bar.Alternatively, you can mouse click the wrench button and mouse click Find.... |
_webmaster.95301 | I have some questions about German SEO. Some words we are optimizing have high monthly search, and good rank in Google.de, but these pages focusing on the keywords don't have any traffic. What's wrong with it?PS: The keywords'monthly searches data is from Google Adwords, and the rank is checked manually (with German IP). | The German keywords with high monthly searches and good ranks in Google haven't any traffic | seo;google search;keywords;google adwords;traffic | null |
_opensource.5878 | I have developed a software and I will publish it for free. But this software includes the following programs:The app is developed using Electron (License: MIT)Electron uses Chromium (It is combined with different licenses)NOTE: Once the application is packaged, automatically Electron and Chromium license files are included in the root folder.node.js (License)nginx (License) - Also there other license files (zlib, openssl etc) in the downloaded packagePHP (License: PHP License) - Also it includes other license files of other apps it includes.Fet Scheduler (License: GNU AGPL v3)Laravel (License: MIT)My files are Laravel Controllers, Models and Views. Once the app is started, first nginx and PHP start and then my PHP website is displayed in a chromium browser.All of these apps included in one setup file.What can be the correct license for this app? A single license file or multiple license files in their folders (PHP, nginx etc.)? | What must be the license of a software including other apps with different licenses? | licensing;mit;relicensing;agpl 3.0 | null |
_unix.75981 | Red Hat docs say:To see which installed packages on your system have updates available, use the following command:yum check-updateWhat command must I run to view all available versions for a package installed on my system?Example: yum check-update tells me java6 update #43 is available, but what if I want update #40? | Yum Check Available Package Updates | rhel;yum | It won't focus specifically on one package because it's using a regex to do the matching but I often use this:$ yum list available java\*java-1.4.2-gcj-compat.i386 1.4.2.0-40jpp.115 installedjava-1.6.0-openjdk.i386 1:1.6.0.0-1.36.1.11.9.el5_9 installedAvailable Packagesjava-1.4.2-gcj-compat-devel.i386 1.4.2.0-40jpp.115 base java-1.4.2-gcj-compat-javadoc.i386 1.4.2.0-40jpp.115 base java-1.4.2-gcj-compat-src.i386 1.4.2.0-40jpp.115 base java-1.6.0-openjdk.i386 1:1.6.0.0-1.40.1.11.11.el5_9 updates java-1.6.0-openjdk-demo.i386 1:1.6.0.0-1.40.1.11.11.el5_9You can make it smarter by filtering the output using grep. |
_cs.54688 | When reading up on the UCT1 algorithm (I'm writing a Monte Carlo tree search), I'm having trouble with the formula.$$\frac{w_i}{n_i} + \sqrt{\frac{\ln t}{n_i}}$$Wikipedia, this guy, and this guy all say that $t$, or whatever else they use for that variable, equals the total number of simulations. What does this mean, exactly? The total number of simulations in the entire tree? The child nodes of that particular node? The sibling nodes? So, what is the $t$ is this equation? Thanks! | UCT1 Algorithm: What does total number of simulations mean? | algorithms;trees;search trees;monte carlo | The UCT1 algorithm is actually an algorithm for a multi-armed bandit. There is a machine with several arms. At each round you pull one of the arms and get some reward. Your goal is to maximize your total reward. In this algorithm, $t$ is the round number $t = 1$ in the first round, $t = 2$ in the second round, and so on.When using UCT1 to perform Monte Carlo tree search, you treat each explored node as a multi-armed bandit. Monte Carlo tree search consists of several rounds of simulations: in each round a complete game is played out. The value of $t$ for a particular node is the number of rounds at which you passed through the node. |
_unix.382299 | I have a text file with list of .XML files.I need an absolute path of each XML in file.Tried following shell script but after lots of try,find command is not working inside do tag. #!/bin/sh NAMES=`cat list2.txt` for NAME in $NAMES; do echo $NAME find $PWD -type f -name $NAME doneHelp me to solve this. | Need absolute path for each line from a text file using shell script | find | null |
_codereview.54139 | I've written a small script to benchmark our LAMP hosted servers that assess the performance based on three factors:Disk I/ODatabase I/O (mysql)Database I/O (sqlite)The logic is as follows:get the type of test performed using a querystring value.generate a big random string of 100KB.If (disk-i/o)write this line to a random file 500 times.else if (mysql i/o)insert this as record in a mysql table 500 times.else if (sqlite i/o)insert this as record in a sqlite table 500 times.Write back to response all variables such as the big string ($payload), time taken to write ($wtime), etc..The program is working fine, but the database i/o is taking way more time than the file i/o. In one test instance, file i/o took only 1.5 seconds, whilst db i/o took 43 seconds! Can you help me with streamlining this code?<?php//index.php$mysqlserver = 'localhost';$mysqlusername = 'test';$mysqlpassword='test';$mysqldatabase='test';$iterations=500;$payload=; //generate a random string of 108KB and a random filename$fname='';$rtime=0; //in milliseconds$wtime=0;$gentime=0;$type='';$db = null;$mysqli = null;if (isset($_REQUEST['type'])) $type=$_REQUEST['type'];//generate:$start = microtime(true);for($i=0;$i<108000;$i++) //generate a big string{ $n=rand(0,57)+65; $payload = $payload.chr($n);}$gentime=round((microtime(true) - $start)*1000);//write test:$start = microtime(true); if ($type=='sqlite') //sqlite test { $db = new SQLite3(benchmark.db); $db->exec('create table temp(t text)'); $db->exec(begin); $stmt = $db->prepare(insert into temp values(:id)); for($i=0;$i<$iterations;$i++) { $stmt->bindValue(':id', $payload, SQLITE3_TEXT); $stmt->execute(); //$db->exec(delete from temp); }; $db->exec(commit); } else if ($type=='mysql') //mysql test { $mysqli = new mysqli($mysqlserver, $mysqlusername, $mysqlpassword, $mysqldatabase); $mysqli->query('create table temp(t varchar(108000))'); $mysqli->query('begin transaction'); for($i=0;$i<$iterations;$i++) $mysqli->query(insert into temp values('{$payload}')); $mysqli->query('commit'); } else // Disk I/O { $fname = chr(rand(0,57)+65).chr(rand(0,57)+65).chr(rand(0,57)+65).chr(rand(0,57)+65).'.txt'; for($i=0;$i<$iterations;$i++) file_put_contents($fname,$payload); }$wtime=round((microtime(true) - $start)*1000);//read test:$start = microtime(true);$result = '';if ($type=='sqlite'){ for($i=0;$i<$iterations;$i++) { $result = $db->query(select t from temp limit 1); $result = $result->fetchArray()['t']; //$db->exec(delete from temp); }; //var_dump($result);}else if ($type=='mysql'){ $stmt = $mysqli->prepare('select t from temp limit 1'); if ($stmt) { for($i=0;$i<$iterations;$i++) { $stmt->execute(); $stmt->bind_result($result); $stmt->fetch(); }; }}else{ for($i=0;$i<$iterations;$i++) $result = file_get_contents($fname);}$rtime=round((microtime(true) - $start)*1000);//cleanup: if ($type=='sqlite') { $db->exec(drop table temp); $db->close();}else if ($type=='mysql') { $mysqli->query('drop table temp');}else { unlink($fname);}//return:$result = array( 'type'=>($type==''?'disk':$type), 'iterations'=>$iterations, 'generate_time'=>$gentime, 'write_time'=>$wtime, 'read_time'=>$rtime, 'server_software'=>$_SERVER[SERVER_SOFTWARE], 'payload'=>$result,);echo json_encode($result); | Benchmarking our LAMP servers with this php script | php;mysql;linux;sqlite | To address the database code stuff. I don't know much about PHP, but I've heard from good sources don't concatenate SQL queriesThat said, I feel that part of the reason your database calls are slower is because you are just passing ad-hoc scripts to the RDBMS so it has to figure out the execution plan each time since it is not stored. Best practice for performance is to let the RDBMS do as much of the DB work as possible, as that is what it's good at. Let's suppose you ran this script just once in MySQL:DROP TEMPORARY TABLE IF EXISTS tt_mysqli_benchmark;CREATE TABLE tt_mysqli_benchmark ( t VARCHAR(108000) );-- Ad hoc code to create stored procedureCREATE PROCEDURE sp_mysqli_benchmark ( IN p_payload VARCHAR(108000) );BEGIN DELIMITER // DELETE FROM tt_mysqli_benchmark ; INSERT INTO tt_mysqli_benchmark (t) VALUES (p_payload);DELIMITER ;END;Then this section of your PHP script: else if ($type=='mysql') //mysql test { $mysqli = new mysqli($mysqlserver, $mysqlusername, $mysqlpassword, $mysqldatabase); $mysqli->query('create table temp(t varchar(108000))'); $mysqli->query('begin transaction'); for($i=0;$i<$iterations;$i++) $mysqli->query(insert into temp values('{$payload}')); $mysqli->query('commit'); }Would become: else if ($type=='mysql') //mysql test { $mysqli = new mysqli($mysqlserver, $mysqlusername, $mysqlpassword, $mysqldatabase); $mysqli->query(CALL sp_mysqli_benchmark('{$payload}')); }My PHP syntax may be slightly off. As you can see though, the PHP is cleaner, and only parameters are passed to the RDBMS, which makes it better able to optimize it, and lets it remember the execution plan for next time since the procedure is stored. I don't know as much about SQLite but it likely is very similar, if not simpler. |
_vi.4606 | I try to do a substitution from a vim script and to operate over a captured group like so:let string = {b1} {b2} ({b3})echo substitute(string, {\([^}]*\)}, a, g)It doesn't match anything and the result doesn't change.If I remove the \( \):echo substitute(string, {[^}]*}, a, g)Then the whole {b1} is replaced with a, when I only want to replace the content of it: {a}.I have read that the pattern in the substitute command always work in magic mode. And that in the magic mode, the capture group is: \( \).Do you know the trick to make this work?Edit:Thanks to Christian Brabandt I was able to make it work (see his answer below). I had to change the \( \) to \zs \ze also. | Capture group in substitute function | vimscript;regular expression;substitute | In double-quote strings, the backslash has a special meaning. And will probably be skipped when parsing the quoted string. The details can be seen at :h expr-quote. You would have to double the slashes to make that work. Therefore, it is usually easier to read and maintain using single quoted strings. See :h literal-string as there the backslash won't be skipped. |
_cogsci.6189 | Since I lack of academic formation please be tolerant if I write something not correct.As you know the Myers-Briggs Type Indicator (MBTI) test is based on 4 personality dimensions (E/I, S/N, T/F, J/P) each of which can assume two possible values (I think the name is trait) for a total of 16 clusters. linkThere are gender differences with regard to a number of psychological variables (see for example gender roles and wikipedia Sex differences in human psychology). These differences may be due to education, culture, hormonal difference and so on.According to the stereotype, many women are more judging than men. Does any empirical evidence show that the prevalence of Judging is higher in women compared to men? | Are woman more Judging than men in the MBTI? | personality;gender;mbti | The MBTI is widely used in applied contexts, such as for personnel selection. Nevertheless, it is hardly used in scientific research on personality because its theoretical basis questionable, because its validity is limited, and because its reliability is inferior to other established measures of personality (for a starting point to criticisms of the MBTI see McCrea & Costa, 1989 and this earlier post). For these reasons it is unlikely that you will find reliable data on gender differences in the MBTI.However, it has been shown that the MBTI traits overlap with those of the Big Five (the most widely adopted model of personality) and gender differences with regard to the Big Five have been studied extensively. The MBTI Judging dimension and its Perceiving counterpart overlap to a large extent with the Big Five trait conscientiousness (e.g., Furnham, 1996, McCrea & Costa, 1989). This is not surprising if you look at how Judging vs. Perceiving and conscientiousness are measured:Judging vs. Perceiving is measured by having people choose between sentence pairs such asI like to have things decided. vs. I like to stay open to respond to whatever happens.I like to make lists of things to do. vs. I appear to be loose and casual. I like to keep plans to a minimum.I like to get my work done before playing. vs. I like to approach work as play or mix work and play.I plan work to avoid rushing just before a deadline. vs. I am stimulated by an approaching deadline.Conscientiousness is measured by items such asI get chores done right away.I carry out my plans.I stick to my chosen path.Thus, there appears to be a clear semantic overlap between the two constructs.Are there gender differences with regard to conscientiousness? According to a large scale meta analysis (with data from more than 23.000 participants from 26 nations, Costa et al. 2001), 1. there are far more personality differences within the genders than between genders 2. for conscientiousness there doesn't seem to be a detectable gender difference.ReferencesCosta Jr., P., Terracciano, A., & McCrae, R. R. (2001). Gender differences in personality traits across cultures: Robust and surprising findings. Journal of Personality and Social Psychology, 81, 322331. doi:10.1037/0022-3514.81.2.322Furnham, A. (1996). The big five versus the big four: the relationship between the Myers-Briggs Type Indicator (MBTI) and NEO-PI five factor model of personality. Personality and Individual Differences, 21, 303307. doi:10.1016/0191-8869(96)00033-5McCrae, R. R., & Costa, P. T. (1989). Reinterpreting the Myers-Briggs Type Indicator From the Perspective of the Five-Factor Model of Personality. Journal of Personality, 57, 1740. doi:10.1111/j.1467-6494.1989.tb00759.x |
_unix.326127 | I am running a small linux server at home, and I am writing a script to log the temperature of the CPU cores every 5 seconds, but I need timestamps for it to be useful. So far I have something that saves the output of the sensors command into a file, and I have a command that prints the date and time. I just need to figure out how to combine those two.sensors | grep ^Core* >> temps.log saves temps in temps.log in following format:Core 0: +39.0C (high = +76.0C, crit = +100.0C)Core 1: +40.0C (high = +76.0C, crit = +100.0C)and for the date I can either do date +%m/%d/%y-%H:%M:%S which returns mm/dd/yy-hh:mm:ssI googled around and saw someone suggesting the use of gawk but I have absolutely no idea how gawk works. | How do I append/prepend a timestamp to grep output? | grep;logs;timestamps;gawk;temperature | If I understand correctly, what you want to accomplish is to prepend the current date to every line that is output by grep. This is an easy task for a bash script:sensors | grep ^Core |\( DATE=$(date +%m/%d/%y-%H:%M:%S) while read LINE do echo $DATE $LINE done) >> temps.log |
_unix.108952 | We have recently purchased Gigabyte 990xe-ud3 motherboards. It came with Realtek LAN conroller. However with CentOS 6.5 it is not working, i.e. although it shows that it's connected with network, it is really not. On searching I found r8169 drivers to be likely a problem so I followed remedy given in foxhop.net article about Realtek NIC r8169 dropping packets in Ubuntu and Fedora.But it's still the same. Though Broadcom network card works perfectly.lspci output for Realtek card:4:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 06) Subsystem: Gigabyte Technology Co., Ltd Motherboard Flags: bus master, fast devsel, latency 0, IRQ 58 I/O ports at d000 [size=256] Memory at d2104000 (64-bit, prefetchable) [size=4K] Memory at d2100000 (64-bit, prefetchable) [size=16K] Capabilities: [40] Power Management version 3 Capabilities: [50] MSI: Enable+ Count=1/1 Maskable- 64bit+ Capabilities: [70] Express Endpoint, MSI 01 Capabilities: [b0] MSI-X: Enable- Count=4 Masked- Capabilities: [d0] Vital Product Data Capabilities: [100] Advanced Error Reporting Capabilities: [140] Virtual Channel Capabilities: [160] Device Serial Number 01-00-00-00-68-4c-e0-00 Kernel driver in use: r8169 Kernel modules: r8169lspci output for Broadcom card:Ethernet controller: Broadcom Corporation NetXtreme BCM5722 Gigabit Ethernet PCI Express Subsystem: Broadcom Corporation NetXtreme BCM5722 Gigabit Ethernet PCI Express Flags: bus master, fast devsel, latency 0, IRQ 59 Memory at fe300000 (64-bit, non-prefetchable) [size=64K] Expansion ROM at <ignored> [disabled] Capabilities: [48] Power Management version 3 Capabilities: [50] Vital Product Data Capabilities: [58] Vendor Specific Information: Len=78 <?> Capabilities: [e8] MSI: Enable+ Count=1/1 Maskable- 64bit+ Capabilities: [d0] Express Endpoint, MSI 00 Capabilities: [100] Advanced Error Reporting Capabilities: [13c] Virtual Channel Capabilities: [160] Device Serial Number 00-10-18-ff-fe-ea-59-47 Capabilities: [16c] Power Budgeting <?> Kernel driver in use: tg3 Kernel modules: tg3Is there any way to get it working with some other drivers etc? | Realtek r8169 not working in CentOS 6.5 | centos;realtek | null |
_softwareengineering.271300 | This code: Double.parseDouble(ABC)throws a NumberFormatException.Why is it wrong to expect a Double.NaN (NaN is literally Not-A-Number).A working example is this:public static void main(String[] args) { System.out.println(Is ABC a number? + Double.isNaN(Double.parseDouble(ABC));}I expect Is ABC not a number? true as output. Why must this be an Exception? | Why Double.parseDouble(ABC) not returns Double.NaN? | java;parsing | NaN has a very specific meaning as the result of an undefined numerical operation such as division by zero or taking the square root of a negative number (within the realm of real numbers). It's not an appropriate return value from code that parses a floating point number. Code like that should signal an error when it comes across text that can't be parsed as a number.Also, as others have mentioned, it's a consistency issue. Only floating point values even have a NaN. Integer and boolean types don't. parseX() should behave the same way in all cases where possible. This is called the principle of least surprise. That is, design things in the most consistent way possible to avoid surprising others using your APIs. |
_webmaster.95830 | I handle the SEO of the company's website. Last month we peaked at a national Alexa Rank of around 30,000, but in the past 3 weeks it has gone down to 50,000. The executives at my company consider Alexa Rank as a major growth indicator. Traffic has plateaued/minute increase over the past 3 weeks. Though, I am continuously addressing avenues for SEO on the website, we are seeing a downward trend.Question is that is Alexa a good representation of growth? | Is Alexa Rank a true representation of growth? | seo;pagerank;ranking;alexa | null |
_unix.111462 | How can I remove all software installed on my Linux distribution? I'm using Debian:$ uname -aLinux debian 3.2.0-4-amd64 #1 SMP Debian 3.2.51-1 x86_64 GNU/LinuxI want to go back to the original installed software.Is there any built-in way to do it in a single command? | How to remove all software | debian;software installation;package management | null |
_unix.353061 | For a project I want to use wget in a cron to download a data file. In the wget statement, a start- and enddate have to be defined in the following format: wget --post-data=stns=235&vars=TEMP&start=YYYYMMDDHH&end=YYYYMMDDHHSince I want it to be done by a cron job, I would like the start- and enddate to be set automatically. More specific, I would like the startdate to be set to '1 hour ago' and the enddate to 'now'. There has been a similar question in the post Using date -1day with wget. Here the suggested solution was to put the variables between single quotes, but this did not work. E.g.:[...]start='`date -d yesterday +%Y%m%d%H'&end=`date +%Y%m%d%H`I simply got the error Error 400: Bad request when trying to execute the wget-statement in the terminal.Thank you. | Using date variable with wget --post-data | shell script;cron;date;wget | Within a cron job, % is special and must be escaped. Also, backquote syntax is best avoided. I would suggest something like the following:wget --post-data=start=$(date ... +\%Y\%m\%d\%H)&end=$(date ... +\%Y\%m\%d\%H)&... |
_unix.207278 | I'm new in Unix, am trying to extract specific file(by using one command) form this kind of folder structure:.../file1.ear/file2.war/folder1/folder2/fileToExtract.txt What I do now is extract the first ear file to a folder (unzip), then extract the second war file to a folder and only then I am able to open the txt file in Unix. | Extract specific file from complex war archive structure | zip | null |
_datascience.8792 | Is there a fundamental difference between building a set on N logistic regressions in 1 vs all fashion, as compared to training a single mutlinomial logistic regression? Put another way, are there any optimization techniques that treat the 1 to N classes logistic regression problem in a way that's markedly different from N independent regressions? Intuitively is seems like the answer ought to be yes, since there should be a lot of information sharing between various problems if two classes are similar. But since I'm not entirely well versed on how common 1 to N solvers actually work, I can't tell if I'm right or these problems are treated in ways that fundamentally the same. I think that we can see that there could be a difference between the two models, but I'm not entirely sure. Googling the matter revealed a few arcane discussing about the subject, but I was unable to find an authoritative discussion of the matter. | Difference between multinomia logistic regression and N 1 vs all binary | logistic regression;multiclass classification | null |
_unix.342219 | I am working on configuring a VLAN on NixOS. I successfully set it up with the following Nix config:networking.vlans = { vlan46 = { id = 46; interface = eth1; }; };networking.interfaces.vlan46.ipAddress = 10.0.3.10;networking.interfaces.vlan46.prefixLength = 24;The issue is that whenever I reboot the machine, the IP is no longer assigned to the VLAN interface. When digging a little bit, I found that a systemd service named network-addresses-vlan46.service is in a failed state. When I start that service manually, the IP is assigned again.These are journalctl events right after the reboot:Feb 03 09:56:12 nixos-machine systemd[1]: Starting Vlan Interface vlan46...Feb 03 09:56:12 nixos-machine vlan46-netdev-start[671]: RTNETLINK answers: Network is downFeb 03 09:56:12 nixos-machine systemd[1]: vlan46-netdev.service: Main process exited, code=exited, status=2/INVALIDARGUMENTFeb 03 09:56:12 nixos-machine systemd[1]: Failed to start Vlan Interface vlan46.Feb 03 09:56:12 nixos-machine systemd[1]: vlan46-netdev.service: Unit entered failed state.Feb 03 09:56:12 nixos-machine systemd[1]: vlan46-netdev.service: Failed with result 'exit-code'.Feb 03 09:56:12 nixos-machine systemd[1]: Found device /sys/subsystem/net/devices/vlan46.Feb 03 09:56:12 nixos-machine systemd[1]: Starting Address configuration of vlan46...Feb 03 09:56:12 nixos-machine network-link-vlan46-start[682]: Configuring link...Feb 03 09:56:12 nixos-machine network-addresses-vlan46-start[681]: bringing up interface...Feb 03 09:56:12 nixos-machine systemd[1]: Starting Link configuration of vlan46...Feb 03 09:56:12 nixos-machine network-addresses-vlan46-start[681]: RTNETLINK answers: Network is downFeb 03 09:56:12 nixos-machine systemd[1]: network-addresses-vlan46.service: Main process exited, code=exited, status=2/INVALIDARGUMENTFeb 03 09:56:12 nixos-machine systemd[1]: Failed to start Address configuration of vlan46.Feb 03 09:56:12 nixos-machine systemd[1]: network-addresses-vlan46.service: Unit entered failed state.Feb 03 09:56:12 nixos-machine systemd[1]: network-addresses-vlan46.service: Failed with result 'exit-code'.Feb 03 09:56:12 nixos-machine systemd[1]: Started Link configuration of vlan46.Feb 03 09:56:16 nixos-machine ntpd[532]: Listen normally on 6 vlan46 [fe80::a00:27ff:fea6:4b5b%4]:123Feb 03 09:56:19 nixos-machine ntpd[857]: Listen normally on 7 vlan46 [fe80::a00:27ff:fea6:4b5b%4]:123Not sure why it's detecting network as down and failing while it is successful when I start the service manually.Any ideas? Thanks. | VLAN configuration on NixOS: IP is no longer mapped after reboot | nixos;vlan | null |
_softwareengineering.313424 | For my thesis I am trying to extract some data from Excel.I want to create a list with the name as in excel and then append the values to said list so I can work with it. EDITI realize I was unclear in my last post. This is simply because it was hard to find material on openpyxl (I didn't find the documentation that useful)After some research I accomplished some things:I will first explain the processIn excel I have many columns with a header=name of stockand below values for said stock.Step 1 would be read the columns and differentiate between namesstep 2 create a dictionary from those columns with the key being the name of stockstep 3 is to calculate an average with a function that excludes the input stock from the average .so avg(dictionary,stock i) would calculate the average of my dictionary values while excluding stock iWB=load_workbook(filename=)ws = WB.activeStockslist={}i=0for col in ws.columns: print(we are at column; +str(i)) i+=1for cell in col: if cell.value== or cell.value==None: print (empty column) break if type(cell.value)==unicode: print ( we entered name) Stock=str(cell.value) else: Stockslist.setdefault(Stock,[]).append(cell.value)This creates a dictionary with the values,now lets calculate the average while excluding a certain stock def CalcAverage(stockslist,stock):#stockslist is a dict, stock is a key in said dictionary stocki=Stockslist.pop(stock)#remove stock we wanna exclude from dictionary avgvalues=[]#create a list that will constitute average values for k,v in Stockslist.iteritems(): print k avgvalues.append(sum(v)/float(len(v))) return avgvalues,stockinow my question is suppose I have: stockslist={APPLE:[1,2,3],TESLA:[4,5,6],GOOGLE:[7,8,9]}I don't want to create a list that has the average value for apple values and so on. This has been explained many times before on Stack ExchangeI want to get a list that comprises the mean in a pairwise progression kind of wayso AVGVALUE would be avgvalues=[1+4+7/3, avg of 2Nd values of Stockslist and so on..]So not as in my code above where I calculate the average per stock and then append it. | OPENPYXL tutorial / help with AVERAGE DICTIONARY | python;excel | null |
_unix.104202 | I changed my username about a month ago, and although I have forgotten the specificities of how I had done so, I'm pretty sure I followed the instructions on the Arch Wiki. Since then, some programs, such as gnome-boxes, have been mistakenly identifying me by my old username - zheoffec:[marcoms@baguette16 Downloads]$ gnome-boxes (gnome-boxes:10440): Boxes-WARNING **: libvirt-broker.vala:86: Failed to start storage pool: cannot open path '/home/zheoffec/.local/share/gnome-boxes/images': No such file or directoryOf course, my new $HOME is /home/marcoms/, and running grep -i zheoffec * --recursive as root from the root directory only returns strings from .bash_history and fish_history (fish is another shell).How can I remove all traces of my old username? | Changing username still leaves old traces | bash;arch linux;users;home | Changing usernames afterwards like this can be problematic since the username is often times hard coded into files throughout your $HOME directory. I usually create a new account with the new name and then migrate files from the old file to the new, but you can also identify them like so:$ grep -r zheoffec $HOMEExample$ grep -r saml /home/saml/home/saml/scripts/r.rb:#!/home/saml/.rvm/rubies/ruby-1.9.2-p180/bin/rubyBinary file /home/saml/parking_lot/db/db1080p.zip matchesBinary file /home/saml/Dropbox/personal/Dropbox/pidgin.tar matches/home/saml/Dropbox/personal/.viminfo:'0 2 5 /home/saml/bin/dropbox.sh/home/saml/Dropbox/personal/.viminfo:-' 2 5 /home/saml/bin/dropbox.sh/home/saml/Dropbox/personal/.viminfo:-' 1 0 /home/saml/bin/dropbox.sh/home/saml/Dropbox/personal/.viminfo:> /home/saml/bin/dropbox.shIf you decide to create a new account and then copy key pieces of data from the old I'd also recommend using rsync to copy files from the old account to the new one as needed. This allows you to copy the data as you go and build up a script that includes key directories of files.Additionally I'll often copy the dot files .* to a subdirectory in the new location called dotfiles and once I'm in the new account will use rsync to copy subdirectories from dotfiles as needed. |
_webapps.30458 | How do I delete All Mail box on left (archived) without deleting other labels' content? Reason is a virus in Gmail archived messages which I cannot locate due to the large amount of archived messages. It is not in my labeled messages | how to delete ALL Mail without deleting mail with labels? | gmail;gmail labels | null |