id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_unix.237091 | I have one array SPLNO with approx 10k numbers.Now i want to search the subscriber number from MDN.TXT file (containing approx 1.5 lac record)from the array.if subscriber number found in array it will perform below operation.my issue is that it's taking more time because for one number it's search whole array of 10k records. therefore for 1.5 lac records it's looping around (1.5lac*10K). please suggest efficient ways.Sample SPLNO.TXT:918542054921|30|1|2918542144944|12|1|2918542155955|12|1|2918542166966|12|1|2918542255955|12|1|2918542355955|12|1|2918542455955|12|1|2918542555955|12|1|2918542955955|12|1|2 Sample MDN.TXT:854216696685423559558542555955 awk -F| 'FNR==1 { ++counter}counter==1 {SPLNOPULSE[$1]=$4;SPLNOAMT[$1]=$3;SPLNOMAXLEN[$1]=$2;next}{for ( mdn in SPLNOMAXLEN) { if ( ($1 ~ ^mdn && length($1) <=SPLNOMAXLEN[mdn]) || (91$1 ~ ^mdn && length(91$1) <=SPLNOMAXLEN[mdn]) ) { print found } else print not found } } ' SPLNO.TXT MDN.TXT | Efficient way to search array in text file by AWK | text processing;awk;array;for | null |
_cs.30350 | I've seen two different concepts referred to by the term function:A small part of a program specified by the composition of constants and other functions as paramaters, such as the functions in LispA set of tuples, as referred to in formal logic, which is not necessarily computableThe first concept is very fundamental to software design. The second concept is very fundamental to formal reasoning. However, a task I've been working on is analyzing software with formal logic, so the conflation of the terms is a bother.Is there any agreed upon, concise, unambiguous terminology to distinguish these two ideas? I can think of several verbose terms, such as Computable Function and General Function, but imagine having to type that out with the specification of every modular component. Any references, ideas, or supported opinions are appreciated, thanks. | Terminology about the word Function : General vs Computable | terminology;logic | null |
_unix.62782 | I'm getting the Cannot save _ Unexpected error: Error renaming temporary file: Text file busy in Gedit 2 when I try to save in a shared folder with Virtualbox (Debian). I've searched and apparently it's a Gedit problem. None of the solutions seem ideal or work for me.Would it be possible to create a shell script (external tools plugin) that saves the file somewhere else, then copies it back in shell? So I'll need to grab wherever Gedit's stored the temporary (live?) file.Or if this is not possible/won't work/bad practice, does anyone know a good way to get around this? I really like Gedit and prefer to use it.Currently, this is my script. I tell external tools not to save but pass the document as input (stdin)bin=while read LINE; do echo ${LINE} # do something with it here bin=${bin}${LINE}\ndoneecho $bin > /home/me/data2/test.txtIt works fine except it doesn't preserve tabs. I'my only editing plain text files. Edit: this also seems to skip the last line | Gedit cannot save in shared folder (Virtualbox) | debian;mount;virtualbox;gedit;shared disk | null |
_webmaster.5385 | (Note that I am going to use screenshots here because I suspect writing about this will change the behavior over time.)If you do a Google search foruiviewcontroller best practiceseither with or without the quotes, you end up with results like this:Note that none of these pages resolve to the actual Stack Overflow question containing those words in the title. They resolve to either a) sites that are mirroring our creative commons data and correctly pointing back to the source question without nofollow, as properly specified by our attribution requirements or b) our own internal links to the question, but not the actual question itself. The actual page with the title ...Custom UIView and UIViewController best practices?... does exist at this URL ...http://stackoverflow.com/questions/3300183/custom-uiview-and-uiviewcontroller-best-practices... and apparently it is present in Google's index!But why does it not appear when we search for uiviewcontroller best practices? We know thatGoogle contains this page in its indexOur search terms match the title of the questionStack Overflow has much higher pagerank than the other sites that are mirroring this question under Creative CommonsI don't get it. What are we doing wrong here? | Page appears indexed in Google but not findable for any search terms? | google;indexing;creative commons | null |
_softwareengineering.337121 | I'm currently working on the project with the new team and they are using Repository pattern which is new to me. In this repository, they're currently doing 1.If we are offline, we will load data from file2.Otherwise, we will make an api call to get data from server.I did some researches and noticed that Repository is providing basic CRUD operations to local database. However, if we consider Repository acts like Data Access Layer, it can make an api call to retrieve data remotely as well.Which one is the correct way to follow. Any ideas ? | How do I describe the Repository pattern? | design;design patterns;repository | The purpose of a Repository is to provide an abstraction layer for data access. That abstraction layer should shield the user of the repository from the details of accessing the data. Things like connection strings, data sources, switching to a different data source... Your user shouldn't have to worry about those things.In other words, the user of a Repository should not have to be concerned about where the data is coming from. That is an implementation detail. How you implement that detail is entirely up to you and your software's specific requirements. |
_cogsci.9619 | I am doing an EEG experiment about imagined speech recognition. Which frequencies will have the most relevant information? I chose the frequency band [4-40] Hz as a start, mainly because of signal processing considerations. Filtering out the remaining frequencies basically removes the DC voltage and most of the EOC artifacts. Which frequencies should I select?Also which channels will contain the signal (i.e., the most relevant data)? | What are proper EEG frequency bands and electrode placements for imagined speech? | eeg;signal detection;speech;signal processing | A study by DZmura et al. (2009) in which two syllables were spoken in imagination showed that imagined speech information was present in EEG alpha, beta and theta bands. The beta band (13-18 Hz) proved most informative. The most informative electrodes were located mainly near the top of the head (vertex) where electromyographic artifacts had least influence.They used various signal processing steps (standard low-pass filtering to remove 60 Hz line artifact, DC filtering, signal enveloping etc.) to clean up their signal. Please refer to the reference list for specific signal processing details. References - DZmura et al. Lecture notes in computer science 2009;40-8. HCI International - Brigham & Kumar, iCBBE 2010 |
_unix.309596 | I don't actually want to do this; the Law of Unintended Consequences looms large over this idea. I'm just curious if the capability even exists. Similar functionality might be handy for some scripts as a break out step.Suppose I want to write this into a ${HOME}/.logout file:#! /bin/bashcd /path/to/git/working/projectif [ $( git status | wc -l ) -gt 5 ]then echo Check in your work before you leave. <STOP THE LOG OUT PROCESS AND RETURN TO THE SHELL PROMPT>fiHow would I do that last bit? Would a break do it? | Cancelling a logout and returning to a shell | shell script;shell | First configure a trap in the session for the exit behavior: trap ~/.logout EXITIf you want you can add this trap behavior to the bashrc, and then .logout script will be executed every time the users try to exit the shell. And then you can write the .logout script: #!/bin/bashcd /path/to/git/working/projectif [ $( git status | wc -l ) -gt 5 ]then echo Check in your work before you leave. bash fiThen when you try to exit the session the script .logout will be executed, and the bash will show up to check if the user does the right thing. If the users does whatever is right with git, the session will end normally. |
_cs.59515 | My trees are rooted and have at most two children at every vertex. I need references that help me solve any or all of the questions below:How many isomorphism classes of trees with n vertices are there?What are the classical algorithms to decide if two given trees are isomorphic?Is there a nice (computable?) isomorphism invariant?Of course, the answers may depend on the structure used to define the trees, but I guess the correct choice of structure is part of the answer I am seeking. | Binary rooted tree isomorphism | algorithms;graph theory;reference request;combinatorics;trees | There is a classical linear time algorithm for rooted tree isomorphism due to Aho, Hopcroft and Ullman. The algorithm actually uses a simple isomorphism invariant. See for example lecture notes of Vikram Sharma. Using this, you can solve unrooted tree isomorphism in linear time, as described for example in Smal's slides. Another classic algorithm is due to Buss. |
_codereview.47396 | I am putting together a fairly simple server that listens for a connection then creates this thread - textbook Java code - then accepts data on that connection.I am following a protocol that the manufacturer has laid out for start of message (0xfd) and EOM (0xfe) as below. I then simply populate a byte array with using a bytecounter.I think this is the simplest doing so, and it seems to work fine. Is there any possible problem with taking this approach? I want to be sure using a bytecounter with an array is acceptable. I can't see anyway that bytecounter could get out of sync or anything like that. I like to keeps things simple. Is there anything wrong with this code with regard to stuffing the inbyte[] array?public void run() {try { boolean socketalive = true; MSG_ID = 0; disIn = new DataInputStream( in ); disOut = new DataOutputStream ( out ); String msg = null; StringBuilder hexforlog; byte[] c ; int i = 0; int bytecounter = 0; byte[] inbyte ; while( true ){ i = 0; bytecounter = 0; inbyte = new byte[1024]; byte b ; try{ /* read from network until end of message byte is received */ while( ( b = disIn.readByte() ) != (byte)0xfe ){ /* checking for start of message */ if( b == (byte)0xfd ){ inbyte = new byte[1024]; inbyte[0] = b; bytecounter = 1; } else { inbyte[bytecounter] = b; bytecounter++; } } }catch ( java.io.EOFException ioef ){ System.out.println(EOF recieved bytes ); break; } /*test for link verification */ if( bytecounter == 15 ){ byte SOURCEbyte = inbyte[2]; byte DESTbyte = inbyte[3]; /* swap bytes per protocol */ inbyte[2] = (byte)DESTbyte; inbyte[3] = (byte)SOURCEbyte; disOut.write( java.util.Arrays.copyOfRange(inbyte,0,16) ); disOut.flush(); } /* process the data as per manufacturer spec */ else if( bytecounter> 16 ){ arrayindex = 12; int SOM = inbyte[0]; int CLASS = inbyte[1]; int SOURCE = inbyte[2]; int DEST = inbyte[3]; int MSG_PRG_NUMBER = inbyte[4]; int SPARE1 = inbyte[5]; int SPARE2 = inbyte[6]; int SPARE3 = inbyte[7]; LENGTH = twoBytesToInt( new byte[] { inbyte[8], inbyte[9] } ); NUM_MSG = twoBytesToInt( new byte[] { inbyte[10], inbyte[11] } ); System.out.println(LENGTH: + LENGTH + NUM_MSG: + NUM_MSG ); System.out.println(Setting NUM_MSG to 1 ); NUM_MSG = 1; for ( int j=0; j<NUM_MSG; j++ ) { MSG_ID = twoBytesToInt( new byte[] { inbyte[arrayindex], inbyte[arrayindex+1] } ); System.out.println(MSG_ID: + MSG_ID ); MSG_LENGTH =twoBytesToInt( new byte[] { inbyte[arrayindex+2], inbyte[arrayindex+3] } ); System.out.println(MSG_LENGTH: + MSG_LENGTH ); arrayindex = arrayindex+4; //first go around 15 currentarray = java.util.Arrays.copyOfRange( inbyte, arrayindex, arrayindex+MSG_LENGTH+1); arrayindex = arrayindex+MSG_LENGTH ; //process messages if(MSG_ID == 50){ processMessage50( currentarray ); } else if(MSG_ID == 70){ processMessage70( currentarray); } } } } disIn.close(); disOut.close();} catch (IOException e) { e.printStackTrace();}} | Keeping track of byte count in a binary protocol handler | java;array;io;socket;device driver | null |
_unix.238881 | I would like to add:function ps_mem { python /home/vagrant/ps_mem/ps_mem.py -p $@}To the end of ~/.bashrc from the command-line. I have tried using:printf function ps_mem {\n python /home/vagrant/ps_mem/ps_mem.py -p $@ \n} >> ~/.bashrcAnd while it almost worked, the input field $@ was ignored, making this:function ps_mem { python /home/vagrant/ps_mem/ps_mem.py -p}Instead, be added to the end of ~/.bashrc. | How do I append multiple lines involving variables to the end of a bash script? | shell script;bashrc;printf | Other answers have been given which will work, but in the spirit of helping you do it exactly the way you were trying to (since it's a totally fine way to do it):Here is the original:printf function ps_mem {\n python /home/vagrant/ps_mem/ps_mem.py -p $@ \n} >> ~/.bashrcHere is a version that works:printf 'function ps_mem {\n python /home/vagrant/ps_mem/ps_mem.py -p $@ \n}' >> ~/.bashrcI recommend adding double quotes around $@ also:printf 'function ps_mem {\n python /home/vagrant/ps_mem/ps_mem.py -p $@ \n}' >> ~/.bashrcVariable expansion is enabled in double quotes; disabled in single quotes. |
_unix.284895 | Ive changed from Windows to Ubuntu 16.04 recently and when I'm running Eclipse Mars 2 (4.5.2), it reacts really slow or delayed. When I try to do anything like creating a new project, importing or just open the about Eclipse window, nothing is happening for a couple of seconds. When finally for example the import dialog finally shows up, eclipse hangs at the following steps when I want to choose e.g. the folder from where things should be imported. The only operation for me is to cancel the application and restart. During those operations the CPU usage seems to be normal, which means not 100% of utilization. It doesn't seem like the machine is working on a lot of stuff in the background (since Im running no other applications than firefox), it rather feels like if you have a extremely bad ping in an online game. Other applications are working quite normal.My system: intel i5 cpu 2,50ghz, 4gb ramI did not download an installer, just the official latest 64bit *.tar.gz file. Then I extracted it to /user/home/Eclipse and ran the application without installation. Did someone else face these issues? How can I check if maybe some basic drivers for my system are missing? | Eclipse Mars reacts delayed and crashes on Ubuntu 16 | ubuntu;eclipse | null |
_softwareengineering.199345 | I a little while ago I joined a new development team and recently we had our first major release. We've used Git since the beginning of the project and by now are somewhat comfortable with it. However, now that the product is in the field, we are discovering new issues/processes that need to be established. Up to this point, everything we've done was by referencing the very popular successful branching model post, which indeed has been very helpfulCurrently we have the following branches, all live and all being updated:master - only released, stable code (tagged every time release is cut)develop - wide open. used for long term developmenthotfix-1.0.1 - branched off master's 1.0.0 tag for small, very targetted fixes which are already lining uprelease-1.1 - This is a small incremental release that we want to push relatively soon so we wanted to manage it separately from develop and to limit scope of changes.These are the merging rules we are establishing:If a code change is made in release-1.1, it must be merged up to develop.If a code change is made in hotfix-1.0.1, it must be merged up to release-1.1. Nobody except for one team member should merge anything into master and that merge only happens when a product version is about to be shipped.My questions are:When should the merges take place? As soon as the fix is applied in lower-level branch? Or periodically in chunks of changes? If periodically, how do you typically determine merge period?Who should do the merges? Person making the original code change? Or one individual who would be designated as Director of Git Services?Reason I'm asking all this is because it seems that while Git is very flexible (and I do love that part about it), it also allows you to easily shoot yourself in the foot. With just few commands, someone could easily, and hopefully not on purpose, merge new development right into hotfix that should ship out in 2 days.Many of us are new to Git and we are still feeling our way around the tool. I was thinking how my other companies/teams handled such concepts in the past and I think the biggest difference is that most other source control products that I've used, work with individual commits, so each developer could be responsible for making sure his fixes are applied to the correct places. But with Git, when one developer runs:git checkout release-1.1git merge hotfix-1.0.1... after his commit, those commands will end up merging an entire branch including code that he has never seen before and may not be the best person to resolve, if there are any conflicts. | Looking for good practices on managing branches and developers in Git | git;builds;release management | null |
_unix.198233 | I have a bind9 testing environment in Debian wheezy that I am trying to set up two A records that are returned in a fixed order. In my named.conf.options file I have the following configuration:options { ... rrset-order { order fixed; };};This is functional to the point that my records are always returned in the same order, but the problem is that bind is choosing to sort them numerically (smallest numbers first) and I am trying to sort them the other direction.Based on this link I understand that the fixed keyword should set the response to whatever order I've got in my configuration file. However, I cannot alter the order of the returned results by changing the order of the records in the zone file.Does anyone know how to return multiple A records for a DNS address in a specific order? | How to return multiple DNS A records in a specific order using bind9? | debian;bind;bind9 | Bind9 on Wheezy doesn't allow for that option. Also one must ask himself why one wants/needs this as it breaks when it hits the cache of some recursor. Also for failover purposes it is not really suited as most clients don't have the code to make that happen.If you maintain the client code, then having a look into SRV resource records that allow you to set priority and load settings for every record. But this depends on the rest of your problem that you try to solve. |
_scicomp.7150 | I'm using the Crank-Nicolson finite difference scheme to solve a 1D heat equation. I'm wondering if the maximum/minimum principle of the heat equation (i.e. that the maximum/minimum occurs at the initial condition or on the boundaries) also holds for the discretized solution. This is probably implied by the fact that Crank-Nicolson is a stable and convergent scheme. But it seems that you might be able to prove this directly via a linear algebra argument using the matrices created from the Crank-Nicolson stencil.I'd appreciate any pointers to literature on this. Thanks. | Is the maximum/minimum principle of the heat equation maintained by the Crank-Nicolson discretization? | linear algebra;pde;numerics;finite difference;crank nicolson | The maximum principle for Crank-Nicolson will hold if$$\mu \doteq \frac{k}{h^2} \leq 1$$for timestep $k$ and grid spacing $h$. In general, we can consider a $\theta$-scheme of the form$$u^{n+1} = u^n + \frac{\mu}{2}\left( (1-\theta)Au^n + \theta Au^{n+1}\right)$$where $A$ is the standard Laplacian matrix and $0 \leq \theta \leq 1$. If $\mu(1-2\theta) \leq \frac{1}{2}$, then the scheme is stable. (This can easily be shown by Fourier techniques.) However, the stronger criterion that $\mu(1-\theta) \leq \frac{1}{2}$ is needed for the maximum principle to hold in general.For a proof, see Numerical Solutions of Partial Differential Equations by K. W. Morton. In particular, look at Sections 2.10 and 2.11 and Theorem 2.2.There's also a nice way to see that the maximum principle will not hold in general for Crank-Nicolson without a constraint on $\mu$.Consider the heat equation on $[0,1]$ with a discretization containing 3 points, including the boundary. Let $u_i^k$ denote the discretization at timestep $k$ and grid point $i$. Assume Dirichlet boundary, so that $u^k_0 = u^k_2 = 0$ for all $k$. Then Crank-Nicolson reduces to$$\left(1 - \frac{\mu}{2}(-2)\right)u^{n+1}_1 = \left(1 + \frac{\mu}{2}(-2)\right)u^n_1,$$which can be further reduced to$$u^{n+1}_1 = \left(\frac{1-\mu}{1+\mu}\right)u^n_1.$$If we consider the initial condition of $u_1^0 = 1$, then we have$$u^n_1 = \left(\frac{1-\mu}{1+\mu}\right)^n,$$and though it will always be the case that $u^n_1 \leq 1$, we will nonetheless have that $u^n_1 < 0$ for odd $n$ unless $\mu \leq 1$. Thus the maximum/minimum principle is violated unless $\mu \leq 1$. This is particularly noteworthy in light of the fact that Crank-Nicolson is stable for any $\mu$.In response to foobarbaz's request, I've added a sketch of the proof.The key is to write the scheme in the form\begin{align*}(1+2\theta\mu)u^{n+1}_j &= \theta\mu(u^{n+1}_{j-1} + u^{n+1}_{j+1})\\ &+ (1-\theta)\mu(u^n_{j-1} + u^n_{j+1})\\ &+ [1-2(1-\theta)\mu]u^n_j\end{align*}The hypothesis that $\mu(1-\theta)\leq \frac{1}{2}$ is exactly equivalent to the fact that all of the above coefficients are nonnegative.Now suppose that the maximum is attained at an interior point $u^{n+1}_j$. Note that all of $u^{n+1}_{j-1}$, $u^{n+1}_{j+1}$, $u^n_{j-1}$, $u^n_{j+1}$, $u^n_j$ are less than or equal to $u^{n+1}_j$ by assumption. If any of these is strictly less than $u^{n+1}_j$, then the above equality and the nonnegativity of the coefficients imply that\begin{align*}(1+2\theta\mu)u^{n+1}_j &> \theta\mu(u^{n+1}_{j-1} + u^{n+1}_{j+1})\\ &+ (1-\theta)\mu(u^n_{j-1} + u^n_{j+1})\\ &+ [1-2(1-\theta)\mu]u^n_j\\ &= (1+2\theta\mu)u^{n+1}_j\end{align*}which is a contradiction. It follows that the maximum must also be attained at all of the temporal and spatial neighbors of $u^{n+1}_j$, and a connectedness argument then implies that the discretization of $u$ must be constant in space and time, so that the maximum is still attained on the boundary. Note that this connectedness argument mirrors the proof of the analytic (i.e., not discretized) maximum principle. |
_codereview.111932 | My task:Write nested for loops to produce the following output with each line 48 characters wide:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+~~+~~+~~+~~+~~+~~+~~+~~+~~+~~+~~+~~+~~+~~+~~+~+~++~++~++~++~++~++~++~++~++~++~++~++~++~++~++~+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~This is my idea, but I guess it's pretty much redundant. If so, how can I minimize redundancy here? My output is correct, by the way.public class Exercises { public static void main (String[] args){ for (int i = 1; i <= 4; i++){ for (int j = 1; j <= 12; j++){ System.out.print(~); } } System.out.println(); System.out.print(~); for (int i = 1; i <=15; i++){ System.out.print(+~~); } System.out.println(+~); System.out.print(+~); for (int i = 1; i <= 15; i++){ System.out.print(++~); } System.out.println(+); for (int i = 1; i <= 4; i++){ for (int j = 1; j <= 12; j++){ System.out.print(~); } } }} | Writing nested for loops to produce certain output | java;programming challenge;ascii art | for (int i = 1; i <= 4; i++){ for (int j = 1; j <= 12; j++){ System.out.print(~); }}System.out.println();can easily be:for (int i = 0; i < 48; i++) { System.out.print('~');}System.out.println();Some edits:Improved formatting: ){ to ) {Simplified to one for loop that runs from 0 to 47 (start at 0, run to less than 48)Print a single char instead of a String with one char in it to improve performanceThis: System.out.print(~);for (int i = 1; i <=15; i++){ System.out.print(+~~);} System.out.println(+~);Can be this:for (int i = 0; i < 16; i++){ System.out.print(~+~);}System.out.println();What changed:Better formattingLoops and prints the ~+~ pattern System.out.print(+~);for (int i = 1; i <= 15; i++){ System.out.print(++~); } System.out.println(+);to:for (int i = 0; i < 16; i++){ System.out.print(+~+);}System.out.println();Changes made:Better formattingLoops and prints the +~+ patternAll of the fixes have some things in common:Indentation and formattingFind the correct patternOther changes:Use methods:Currently all your code is in the main method. Split it up.Final code:public class Exercises { public static void main (String[] args){ printTildes(); printTPT_Pattern(); printPTP_Pattern(); printTildes(); } private static void printTildes() { for (int i = 0; i < 48; i++){ System.out.print(~); } System.out.println(); } private static void printTPT_Pattern() { for (int i = 0; i < 16; i++){ System.out.print(~+~); } System.out.println(); } private static void printPTP_Pattern() { for (int i = 0; i < 16; i++){ System.out.print(+~+); } System.out.println(); }} |
_codereview.120023 | I'm very new to C++ and Arduino, with a background in Python. I've written this code for a countdown timer and a simple menu to set the time available to each player, using button handling code from here.It works as expected, but I don't know whether this is good idiomatic C++/Arduino code or if I could be using better data structures, standard library functions, etc and would be grateful for any tips.// Chess clock using the LiquidCrystal library#include <LiquidCrystal.h>/*******************************************************This program uses the LCD panel and keypad to create achess timer.The main display, which shows the active player and thetwo countdown timers, is as follows:P1 ChessClock P2MM:SS -- MM:SSThe menu display, used to set the minutes available foreach player, is: MENU Player1 mins: MM Jamie Bull, February 2016********************************************************///================================================================// This code is from a sample library on how to use the LCD keypad// http://www.dfrobot.com/wiki/index.php?title=Arduino_LCD_KeyPad_Shield_%28SKU:_DFR0009%29// select the pins used on the LCD panelLiquidCrystal lcd(8, 9, 4, 5, 6, 7);// define some values used by the panel and buttonsint lcd_key = 0;int adc_key_in = 0;#define btnRIGHT 0#define btnUP 1#define btnDOWN 2#define btnLEFT 3#define btnSELECT 4#define btnNONE 5// read the buttonsint read_LCD_buttons(){ adc_key_in = analogRead(0); // read the value from the sensor // buttons when read are centered at these values: 0, 144, 329, 504, 741 // we add approx 50 to those values and check to see if we are close // We make this the 1st option for speed reasons since it will be the most likely result if (adc_key_in > 1000) return btnNONE; if (adc_key_in < 50) return btnRIGHT; if (adc_key_in < 250) return btnUP; if (adc_key_in < 450) return btnDOWN; if (adc_key_in < 650) return btnLEFT; if (adc_key_in < 850) return btnSELECT; return btnNONE; // when all others fail, return this...}//================================================================// Code below here is mine// Initialise some global parametersboolean isUsingMenu = false; // whether we are in the time-setting menuboolean isGameOver = false;String playIndicator = -- ; // for the centre of the display when no player is activeclass Player { // Represents a player. public: int minutes; // number of minutes allowed boolean isActive; // is the player's clock counting down? String menuText; // text for the time-setting menu long secondsRun; // seconds run while the player was active void IncrementMinutes(); void DecrementMinutes(); int SecondsRemaining();};void Player::IncrementMinutes() { if (this->minutes < 99) { this->minutes += 1; }};void Player::DecrementMinutes() { if (this->minutes > 1) { this->minutes -= 1; }};int Player::SecondsRemaining() { // number of seconds remaining on the player's clock int minsAllowed = this->minutes; int secondsRunSoFar = this->secondsRun; return minsAllowed * 60 - secondsRunSoFar;};String timeString(long seconds){ // Convert seconds to an MM:SS display. int runSecs = seconds % 60; int runMins = seconds / 60; // number of seconds for the MM:SS display String displaySeconds; if (runSecs < 10) { displaySeconds = 0 + String(runSecs); } else { displaySeconds = String(runSecs); } // number of minutes for the MM:SS display String displayMinutes; if (runMins < 10) { displayMinutes = 0 + String(runMins); } else { displayMinutes = String(runMins); } // Create and return the formatted string String displayString = displayMinutes + : + displaySeconds; return displayString;}// initialise the playersPlayer p0 = {0, true, , 0}; // dummy player, active when player clocks are not counting downPlayer p1 = {5, false, Player1 mins: , 0};Player p2 = {5, false, Player2 mins: , 0};// set a pointer to the first player to be shown in the time-setting menuPlayer* menuPlayer = &p1;void updateCounters(){ // Update the counters for each player if (p0.isActive) { p0.secondsRun += millis()/1000 - ( p0.secondsRun + p1.secondsRun + p2.secondsRun ); } if (p1.isActive) { p1.secondsRun += millis()/1000 - ( p0.secondsRun + p1.secondsRun + p2.secondsRun ); } if (p2.isActive) { p2.secondsRun += millis()/1000 - ( p0.secondsRun + p1.secondsRun + p2.secondsRun ); }}void setup(){ lcd.begin(16, 2); lcd.setCursor(0,0); lcd.print(P1 ChessClock P2);}// Main loopvoid loop(){ updateCounters(); // do this every loop lcd_key = read_LCD_buttons(); if (isUsingMenu) { switch (lcd_key) { case btnUP: { // increase minutes menuPlayer->IncrementMinutes(); delay(250); break; } case btnDOWN: { // decrease minutes menuPlayer->DecrementMinutes(); delay(250); break; } case btnLEFT: { // set pointer to player 1 as player to change time for menuPlayer = &p1; break; } case btnRIGHT: { // set pointer to player 2 as player to change time for menuPlayer = &p2; break; } case btnSELECT: { // return to timer screen isUsingMenu = false; delay(500); // delay required otherwise the button fires repeatedly break; } case btnNONE: { // update menu display lcd.setCursor(0,0); lcd.print( MENU ); lcd.setCursor(0,1); String playerMins; if (menuPlayer->minutes < 10) { playerMins = + String(menuPlayer->minutes); } else { playerMins = String(menuPlayer->minutes); } lcd.print(menuPlayer->menuText + playerMins); break; } } } else { switch (lcd_key) { case btnLEFT: { // player 1 playIndicator = <- ; p0.isActive = false; p1.isActive = true; p2.isActive = false; lcd.setCursor(5,1); lcd.print(playIndicator); break; } case btnRIGHT: { // player 2 playIndicator = -> ; p0.isActive = false; p1.isActive = false; p2.isActive = true; lcd.setCursor(5,1); lcd.print(playIndicator); break; } case btnUP: { // pause the timers p0.isActive = true; p1.isActive = false; p2.isActive = false; playIndicator = -- ; break; } case btnDOWN: { // not used break; } case btnSELECT: { if (isGameOver){ // select button resets the game p0.secondsRun += (p1.secondsRun + p2.secondsRun); p1.secondsRun = 0; p2.secondsRun = 0; p0.isActive = true; p1.isActive = false; p2.isActive = false; playIndicator = -- ; isGameOver = false; delay(500); break; } else { // activate the menu isUsingMenu = true; p0.isActive = true; p1.isActive = false; p2.isActive = false; delay(500); // delay required otherwise the button fires repeatedly break; } } case btnNONE: { if (isGameOver) { // do nothing and wait for btnSELECT to reset the game break; } else { // check if either player is out of time if (p1.SecondsRemaining() <= 0) { // player 1 lost lcd.setCursor(0,0); lcd.print( Game Over! ); lcd.setCursor(0,1); lcd.print( Player 1 loses ); isGameOver = true; break; } else if (p2.SecondsRemaining() <= 0) { // player 2 lost lcd.setCursor(0,0); lcd.print( Game Over! ); lcd.setCursor(0,1); lcd.print( Player 2 loses ); isGameOver = true; break; } else { // update timer display lcd.setCursor(0,0); lcd.print(P1 ChessClock P2); lcd.setCursor(0,1); lcd.print(timeString(p1.SecondsRemaining())); lcd.setCursor(5,1); lcd.print(playIndicator); lcd.setCursor(11,1); lcd.print(timeString(p2.SecondsRemaining())); } break; } } } }} | Chess countdown timer for Arduino LCD Keypad | c++;beginner;timer;arduino | null |
_unix.120583 | I cloned the git repository of xbindkeys using:git clone git://git.sv.gnu.org/xbindkeys.gitI want to compile it. How can I do this? Where can I find the compile instructions?What are the dependencies? | How to compile xbindkeys | x11;compiling | After downloading it when I run the ./configure command it complained about 2 libraries missing:checking for XCreateWindow in -lX11... noconfigure: WARNING: Xbindkeys depends on the X11 libraries!checking for guile... noconfigure: error: guile required but not foundI had to install these 2 packages:$ sudo apt-get install guile-1.8-dev tk-devAfterwards a typical ./configure and make worked fine. |
_webmaster.24721 | I have ran in to an issue with my design. It looks fine when viewing it on a monitor that isn't widescreen but once I go to a widescreen monitor the extra space is truly irritating.What should I do to take away from that feeling of unused space on the edges of the site.Oh, and please don't critique any other aspects of the site than layout. Yes, I know there are images that are .png that should be .jpg. | How should I utilize the empty space around a static layout? | website design | null |
_vi.12991 | I installed some plugins which is supported above vi version 7.4. When i open files with vi command its will show the plugin not supported with version 7.3. After that i was opened with vim command its working. Then i check the version using vi command its showing version 7.3 , in vim version is 8.x. So i checked origin vi command using which vim , which returns /usr/bin/vi.Its the softlink of another version vim. So I want to remove old version of vim without remove installed pluginsOS:MAC | Version conflict between vi and vim | macvim;version | null |
_softwareengineering.168606 | I'm seeing a lot of instantiable classes in the C++ and Java world that don't have any state.I really can't figure out why people do that, they could just use a namespace with free functions in C++, or a class with a private constructor and only static methods in Java.The only benefit I can think of is that you don't have to change most of your code if you later decide that you want a different implementation in certain situations. But isn't that a case of premature design? It could be turned into a class later, when/if it becomes appropriate.Am I getting this wrong? Is it not OOP if I don't put everything into objects (i.e. instantiated classes)? Then why are there so many utility namespaces and classes in the standard libraries of C++ and Java?Update:I've certainly seen a lot examples of this in my previous jobs, but I'm struggling to find open source examples, so maybe it's not that common after all. Still, I'm wondering why people do it, and how common it is. | Why am I seeing so many instantiable classes without state? | java;c++;object oriented;class;object | I'm seeing a lot of instantiable classes in the C++ and Java world that don't have any state.Some possibile reasons to create classes without ivars of their own:State is or could be contained in a superclass.Class implements some interface and needs to be instantiable so that instances can be passed to other objects.Class is intended to be subclassed. Handy way to group related functions. (Yes, there may be better or different ways to do the same.)Am I getting this wrong? Is it not OOP if I don't put everything into objects (i.e. instantiated classes)?OOP is a paradigm, not a law of nature. There are some languages where everything is an object, so you really don't have a choice. Other languages (e.g. C) don't provide any support for OOP at all, but you can still program in an object oriented style. I'd say you can have OOP if you don't do everything in classes... you might say that you just have less OOP in that case. |
_unix.15381 | Yesterday I did apt-get upgrade on my Debian/testing and broke a php5 package. Ieven tried to remove & purge with apt and dpkg clean apt cache. When installed again clean, it fails with following error message:Setting up libapache2-mod-php5 (5.3.6-12) ...readlink: invalid option -- 'm'BusyBox v1.17.1 (Debian 1:1.17.1-10) multi-call binary.Usage: readlink [-fnv] FILEDisplay the value of a symlinkOptions: -f Canonicalize by following all symlinks -n Don't add newline -v Verboseucf: Unable to determine The new filedpkg: error processing libapache2-mod-php5 (--configure):subprocess installed post-installation script returned error exit status 1Any ideas how to solve this Debian way? | PHP package won't install correctly | linux;debian;apt;php | null |
_codereview.45405 | I have a RoR 4 app, and its model have these associations:has_many :accreditationshas_one :legal, -> { where(kind_cd: Accreditation.legal) }, class_name: 'Accreditation'has_many :departments, -> { where(kind_cd: Accreditation.department) }, class_name: 'Accreditation'So, you see that these associations similar, but legal & departments have more conditions than accreditations. Can I replace class_name: 'Accreditation' with something like using :accreditations? | Rails refactoring has_many | ruby;ruby on rails | I don't see what you will gain with your hypothetical using syntax, let's say there is one... your code will look like this:has_many :accreditationshas_one :legal, -> { where(kind_cd: Accreditation.legal) }, using: :accreditationshas_many :departments, -> { where(kind_cd: Accreditation.department) }, using: :accreditationsHow is it better than your current code? It is not more expressive, nor is it more succinct, nor DRY.Also, these associations are similar to some extent, but they look as DRY as you can make them - one is has_one, while the others are has_many, one uses the default idiom, while the others have names different than the associated class, conditions are different (and though one might argue you can predict the filter by the association name, one is singular, and the other is plural...)In short, I think your current code is good enough - any change will only harm readability. |
_codereview.155931 | I been getting into javascript patterns and would love to get some feedback. I notice that I got some general helper functions. Is this a good approach of dealing with it?// carousel.jsvar Carousel = (function() { var timeout = 340; function init() { applyForTheseQueries(); $(window).on('resize', Helpers.debounce(function() { applyForTheseQueries(); }, timeout)); } function applyForTheseQueries() { var $carousel = $('.js-slick'); var query = $carousel.data('query'); var mediaQuery = Helpers.executeFunctionByName(query, window); if (mediaQuery && !$carousel.hasClass('init-done')) { $carousel.addClass('init-done').slick(); } else if (!mediaQuery && $carousel.hasClass('init-done')) { $carousel.removeClass('init-done').slick('unslick'); } } return { init: init };})();$(function() { Carousel.init();});// helpers.jsvar Helpers = (function() { function executeFunctionByName(functionName, context) { var args = [].slice.call(arguments).splice(2); var namespaces = functionName.split(.); var func = namespaces.pop(); for (var i = 0; i < namespaces.length; i++) { context = context[namespaces[i]]; } return context[func].apply(context, args); } function debounce(func, wait, immediate) { var timeout; return function() { var context = this; var args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; return { executeFunctionByName: executeFunctionByName, debounce: debounce };})(); | Module with helper functions to initialize or reinitialize a Slick carousel | javascript;revealing module pattern | null |
_unix.330781 | To setup nginx on centos7, I used to run:grep nginx /var/log/audit/audit.log | audit2allow -M nginxseand it worked fine, but apparently on an updated system, it is different. audit2allow complains:You must specify the -p option with the path to the policy file.How can I do use it as before to fix the security policy problem? | audit2allow asks for a path when setting up nginx | nginx;selinux | null |
_codereview.4216 | I have a set of classes that abstract away calls to a set of web services. I have 6 classes in this particular group, 4 of which contain a simple function that, while small, is still duplicated. What happens is that if some exception or business rule violation happens in the service, they package it up as a fault object in the response. Otherwise, the fault object is null. As a result, the functions simply check to see if that object is not null and, if so, take the reason provided and throw an exception up the chain. So in one class, it might look like private void ThrowIfContainsFault(AlphaResponse response){ if (response.Fault != null) { throw new WhateverException(response.Fault.reasonText); }}And then the other classes, the response object will be of a different type, but the Fault property is the same and the block of code is the same. private void ThrowIfContainsFault(BravoResponse response)private void ThrowIfContainsFault(CharlieResponse response)private void ThrowIfContainsFault(DeltaResponse response)(Note: These class names are changed for readability, there is no common ancestor for these response objects.)My first thought is that I could simply change the functions to receive the Fault object directly and forget the response object, and that's valid. But my overall concern is that while these methods literally do the same thing, the classes themselves are not particularly related, so introducing a common base hierarchy for a single (protected) method does not strike me as a suitable fit. Here's my throwaway thought that I'm not even sure I like: Define an empty interface that each class can implement, then define an extension method against that interface. internal interface IFaultThrower{ }internal static class IFaultThrowerExtension{ internal static void ThrowIfNotNull(this IFaultThrower thrower, Fault fault) { if (fault != null) { throw new WhateverException(fault.reasonText); } }}This would allow the related classes to get rid of their own private methods and invoke this common one. // this.ThrowIfContainsFault(response); this.ThrowIfNotNull(response.Fault);Again, not sure I like it, but I'm also not sure I like the same general idea creeping into multiple classes, either. | Duplicated code in web service consumption | c# | I think it is a bad idea to introduce an empty interface to just add an extension method to it. You should think about an interface as a contract and not merely a way to introduce syntax sugar :)I believe instead of playing with extension methods it is enough to introduce a separate, helper, internal class whose only purpose would be to throw an exception if fault object is null: internal class FaultResponseChecker { internal static void ThrowIfNotNull(Fault fault) { if (fault != null) { throw new WhateverException(fault.reasonText); } } }If you, as I, don't like static methods, then you can use IoC container to inject IFaultResponseChecker into the constructor of every class. |
_cs.80047 | How to find the minimum (or close to minimum) cost path that visits a subset of nodes within a graph? What algorithms can I use?I googled and found: http://lcm.csa.iisc.ernet.in/dsa/node181.htmlBut the problem doesn't look like a minimum-cost spanning trees.This is because the subset of nodes that I want to visit is not all of the nodes in a graph. Sometimes there is no direct path between a node that I want to visit with any other nodes that I want to visit. This means creating a subgraph that contains only the nodes I want to visit won't help because I definitely have to go through some of the nodes that I dont want to visit. | Algorithm to find a low cost path that visits specific nodes in a graph | algorithms;graphs;shortest path | null |
_unix.82637 | I have a problem with a MySql application that write on a SD card or a Compact Flash. After a data loss ( a power failure , for example) , if I try to retrieve the data of my db , it fails and the error code is : incorrect format table. If i try to see the files of my DB in file-system mounted, I obtain: can't stat file or directory (I/O error). Someone have suggestion to overcome this? to prevent or recovery the contents of my db?The scenario is a) a filesystem with ext2 filesystem ( to prevent SD card multiple writings)b) SD cards or DOM or Compact Flash as physical supportc) the OS ( TinyCore Linux Embedded ) it's loaded in RAMd) the is MySql MyIsam db | Data loss prevention ( or recovery) in a MySql db in embedded systems | linux;mysql;embedded | null |
_reverseengineering.13047 | I've start reversing some android application. I have a little experience in this subject, but i got stuck on a little matter.The app i'm trying to reverse uses JNI (java native interface), meaning some of the code is not java - it is assembly.. To my knowing, the native code should be somewhere in the classes.dex file too (together with the dalvik bytecode).My problem is that the tool i'm using that knows to convert the dex file into a java code (dex2jar) doesn't seem to know how to handle the native code inside the classes.dex file. So my questions are: Is there any tool that knows to do this conversion? If not, does someone have general knowledge about the whereabouts of native code in dex files (if it is there)? | reversing apk - getting native code in classes.dex | android;apk | No, native code isn't in classes.dex. If an android apk file has native code, the apk itself, when unzipping, should have a lib subdirectory, which may have architecture-dependent subdirectories armeabi. armeabi-v7a. x86 and possibly others, and those will contain the native code objects. Sometimes, shared objects may be in other directories as well, especially if they belong to some libraries the application linked in.For example, i unzipped the apk of one application that i know to have native code:$ unzip -l net.skoobe.reader-1.apk[ stuff omitted ] 2291 2016-03-14 10:27 NDK_LICENSES 18549 2016-03-14 10:27 assets/www/error.js 345568 2016-03-14 10:27 assets/armeabi/lib64libcrittercism-v3.so 308716 2016-03-14 10:27 assets/armeabi-v7a/lib64libcrittercism-v3.so 345696 2016-03-14 10:27 assets/arm64-v8a/lib64libcrittercism-v3.so 5088 2016-03-14 10:25 lib/armeabi/librsjni.so 2890256 2016-03-14 10:26 lib/armeabi/libskoobe.so 5088 2016-03-14 10:25 lib/armeabi/libRSSupport.so 2792064 2016-03-14 10:26 lib/armeabi-v7a/libskoobe.so 4555592 2016-03-14 10:26 lib/x86/libskoobe.so 18560 2015-03-26 19:09 lib/armeabi-v7a/librsjni.so 420320 2015-03-26 19:09 lib/armeabi-v7a/libRSSupport.so 26636 2015-03-26 19:09 lib/x86/librsjni.so 518512 2015-03-26 19:09 lib/x86/libRSSupport.so 159719 2016-03-14 10:27 META-INF/MANIFEST.MF[ more stuff omitted ] |
_unix.382885 | I'm trying to run a script: #!/bin/sh A=multichain-cli chain97 issue 1XRnkvTc1Ev3q8UnSyynu1Qb9ss1E3aJWZn2bQ '{name:Test_Asset,open:true}' 100 echo $A exit I'm trying to pass Test_Asset as a parameter: #!/bin/sh B=$1 A=multichain-cli chain97 issue 1XRnkvTc1Ev3q8UnSyynu1Qb9ss1E3aJWZn2bQ '{name:$B,open:true}' 100 echo $A exitAsset is created with Name as $B. I want asset to be created with the Value of B, not $B literally. | Pass parameter to single quoted command | bash;shell script;quoting | null |
_unix.272065 | Objective:Install Skype plugin into Pidgin communication program on Linux.Prerequisite:Having installed the latest version of Pidgin. | How to install Skype plugin into Pidgin on Linux | linux;skype;pidgin | The plugin name is skypewebIts Github page is https://github.com/EionRobb/skype4pidgin/tree/master/skypewebOn most Linux distributions its compilation and installation should be simple, just follow:sudo apt-get install libglib2.0-dev libjson-glib-dev libpurple-devgit clone git://github.com/EionRobb/skype4pidgin.gitcd skype4pidgin/skypewebmakesudo make installTested and working with Pidgin 2.10.12 and Skypeweb plugin 1.1. |
_opensource.4407 | I have a project that I have licensed under the GPL3. In it, I have a section of code which implements a bessel filter, which I ported from the python scipy implementation. I'm unclear on how scipy code is licensed - is it OK to simply include that code in my GPL project, or do I have to add something additional since it was derived from a python library? | Porting python library code into GPL project | gpl 3;porting | Scipy proper has a clear BSD license so there is not un-clear.When porting code, I prefer to keep the original license of the code in all cases (even if the license may not require it). I would typically port the files in files that match more or less the ported files structure and keep these clearly under their original license. To avoid confusion and meet the BSD requirements I would also copy the Scipy license in a header comment in these files together with some notes explaining that this is port, available under the original ported code license and eventually describing some of the changes. Not all of this is required, but this is to me the right thing to do. |
_softwareengineering.203313 | Singleton is a common pattern implemented in both native libraries of .NET and Java. You will see it as such:C#: MyClass.InstanceJava: MyClass.getInstance()The question is: when writing APIs, is it better to expose the singleton through a property or getter, or should I hide it as much as possible?Here are the alternatives for illustrative purposes:Exposed(C#):private static MyClass instance;public static MyClass Instance{ get { if (instance == null) instance = new MyClass(); return instance; }}public void PerformOperation() { ... }Hidden (C#):private static MyClass instance;public static void PerformOperation(){ if (instance == null) { instance = new MyClass(); } ...}EDIT:There seems to be a number of detractors of the Singleton design. Great! Please tell me why and what is the better alternative. Here is my scenario:My whole application utilises one logger (log4net/log4j). Whenever, the program has something to log, it utilises the Logger class (e.g. Logger.Instance.Warn(...) or Logger.Instance.Error(...) etc. Should I use Logger.Warn(...) or Logger.Warn(...) instead?If you have an alternative to singletons that addresses my concern, then please write an answer for it. Thank you :) | Hide or Show singleton? | java;c#;design patterns;.net | I think hiding Singleton is a bad idea. If you don't have a way to get a reference to the created instance via a getInstance() method, how you are going to do it considering that Singleton classes do not have public constructors? There is no way to get that reference. That means that if you decide to hide the Signbleton, your only option is to check in every public static method of the Signletone class whether the instance was already instantiated and if not, do it. So your code becomes something like this:class BadSingletone { private static MyClass instance; public static void PerformOperation() { if (instance == null) { instance = new MyClass(); } ... } public static void PerformSomeOtherOperation() { if (instance == null) { instance = new MyClass(); } ... } public static void PerformYetAnotherOperation() { if (instance == null) { instance = new MyClass(); } ... }}littered with all those instantiation checks. You can of course encapsulate the check in a separate function but you will again have to call it in every public static function of the class. And what if you accidentially forget to include it in one of the functions? Users of the class will not be too happy about it.So, to my mind, hiding Singleton does not make sense - it makes you litter your code with unneccessary checks. |
_unix.270460 | Well, tried everything: alsa, alsa-utils, alsamixer, pulseaudio, puvecontrol and a lot more. Even I changed from ubuntu to Linux mint, but I can't get sound from hdmi (laptop connected to led tv). I have a desktop pc with linux mint connected to a led tv with the same hdmi cable and works. I'm trying to make it work for a laptop Asus X555LA-XX688H. The HDMI option does not show up in sound settings neither in pavucontrol settings.aplay -Ldefault Playback/recording through the PulseAudio sound servernull Discard all samples (playback) or generate zero samples (capture)pulse PulseAudio Sound Serversysdefault:CARD=PCH HDA Intel PCH, ALC233 Analog Default Audio Devicefront:CARD=PCH,DEV=0 HDA Intel PCH, ALC233 Analog Front speakerssurround40:CARD=PCH,DEV=0 HDA Intel PCH, ALC233 Analog 4.0 Surround output to Front and Rear speakerssurround41:CARD=PCH,DEV=0 HDA Intel PCH, ALC233 Analog 4.1 Surround output to Front, Rear and Subwoofer speakerssurround50:CARD=PCH,DEV=0 HDA Intel PCH, ALC233 Analog 5.0 Surround output to Front, Center and Rear speakerssurround51:CARD=PCH,DEV=0 HDA Intel PCH, ALC233 Analog 5.1 Surround output to Front, Center, Rear and Subwoofer speakerssurround71:CARD=PCH,DEV=0 HDA Intel PCH, ALC233 Analog 7.1 Surround output to Front, Center, Side, Rear and Woofer speakersdmix:CARD=PCH,DEV=0 HDA Intel PCH, ALC233 Analog Direct sample mixing devicedsnoop:CARD=PCH,DEV=0 HDA Intel PCH, ALC233 Analog Direct sample snooping devicehw:CARD=PCH,DEV=0 HDA Intel PCH, ALC233 Analog Direct hardware device without any conversionsplughw:CARD=PCH,DEV=0 HDA Intel PCH, ALC233 Analog Hardware device with all software conversionsuname -r3.13.0-24-genericI tried with oem-audio-hda-daily too. But I have and other problem: I can't see additional drivers option in linux mint 17.3. Only Software origins.lshw -C display*-display descripcin: VGA compatible controller producto: Broadwell-U Integrated Graphics fabricante: Intel Corporation id fsico: 2 informacin del bus: pci@0000:00:02.0 versin: 09 anchura: 64 bits reloj: 33MHz capacidades: msi pm vga_controller bus_master cap_list rom configuracin: driver=i915 latency=0 recursos: irq:64 memoria:b1000000-b1ffffff memoria:c0000000-cfffffff ioport:4000(size=64)I don't know what to do... | Linux mint 17.3 without HDMI sound output | drivers;audio;alsa;pulseaudio;hdmi | I fixed updating the kernel version. 3.18.29 worked for me.aplay -L | grep hdmihdmi:CARD=HDMI,DEV=0hdmi:CARD=HDMI,DEV=1hdmi:CARD=HDMI,DEV=2 |
_webmaster.67558 | I have a new website that I tried to list in DMOZ, but as of now it's still not listed.Please tell me what I have to do so that my website will get listed in DMOZ. | How can I add my website to DMOZ? | dmoz | null |
_webmaster.13385 | I have a website with some images, and I want them to be in the middle, now on my screen they are in the middle. Because I've put them there by moving them to one side, when I get my friends to look at it, the image is off to one side.On a 13.5 screen it will look to be in the middle. | How to get an image 100% in the middle of every single screen in the world | html;css | null |
_cs.77350 | Problem:Looking for an efficient algorithm to find the largest value that exists in all columns.Constraints:The values in each column are always decreasingMy algorithm:Check the first row for matchUse the lowest value from first row to search for matchUse the value from row x, column y to search for matchIncrease row index until nIncrease column index until nExamples:Best case$$A=\begin{bmatrix}17 & 17 & 17\\ 14 & 14 & 16\\ 13 & 10 & 15\\ 11 & 8 & 13\end{bmatrix}$$Select Row1,Col1 to match17, 17, 17Result is 17Average case$$B=\begin{bmatrix}13 & 10 & 15\\ 11 & 8 & 13\\ 10 & 7 & 12\\ 9 & 5 & 10\end{bmatrix}$$Select Row1,Col1 to match13, 10, 15Select lowest value in Row1 (10)10, 10, 10Result is 10Worst case$$C=\begin{bmatrix}14 & 14 & 16\\ 13 & 10 & 15\\ 11 & 8 & 13\\ 10 & 7 & 12\end{bmatrix}$$Select Row1,Col1 to match14, 14, 16Select lowest value in Row1 (14)14, 14, xSelect Row2,Col1 to match13, x, 13Select Row2,Col2 to match10, 10, xSelect Row2,Col3 to matchx, x, 15Select Row3,Col1 to match11, x, xSelect Row3,Col2 to matchx, 8, xSelect Row3,Col3 to match13, x, 13Select Row4,Col1 to match10, 10, x(repeated!)Select Row4,Col2 to matchx, 7, xSelect Row4,Col3 to matchx, x, 12Result is no matches | Greatest matching values in matrix | algorithms | null |
_softwareengineering.158602 | I'm primarily an ASP.NET developer but this question really applies regardless of language. So obviously it is a good idea to prevent external attacks that arise from session hijacking and csrf attacks as well. But what about internal attacks when the data involved is temporary, needed for the entire session but also sensitive and worth stealing? There is the naturally just only hire trustworthy people route, but lets say that doesn't apply.Say it is a given you already have code reviews and strict production data access permissions to prevent theft by developers. The application encrypts sensitive data before storing to prevent theft by dbas.How do you protect your temporary sensitive data against web server admins? It seems that they could retrieve information by inspecting web server logs, traffic sniffing and inspection of process memory contents. Naturally I would say production web server admins do not have access to the raw source code. | How to handle security of temporary data on web server? | web development;security | null |
_unix.223636 | I was wondering if it's possible to include an attachment with sendmail. I am generating the following emailfile.eml files with the following layoutFrom: Company Name <[email protected]>To: [email protected]: [email protected]: Generated OutputMime-Version: 1.0This will be the body copy even though it's terribleI am sending these emails using# /usr/sbin/sendmail -t < emailfile.emlThis part is working file but I would like to include an attachment to this email and I have not figured out how to do it | Sendmail Attachment | centos;email;sendmail | With mutt you can simply use:echo This is the message body | mutt -a /path/to/file_to_attach -s subject of message -- [email protected] mail command:mail -a /opt/emailfile.eml -s Email File [email protected] < /dev/null-a is used for attachments.You can use SendEmail:sendemail -t [email protected] -m Here is the file. -a attachmentFile |
_unix.23739 | I have successfully built both libfreenect (driver for Xbox Kinect) and libusb (which is a dependency).However, if I try to open the Kinect using the freenect_init(...) function, it returns -99. I tracked down the error to the funtion libusb_init(...) which is returning this error, LIBUSB_ERROR_OTHER.As I use a minified custom kernel configuration (version: 2.6.37) I think I missed to enable an important config option.Kernel config is available on pastebin.com.The Kinect gets successfully recognized (reported in dmesg including correct product/vendor information).Does anyone has an idea how to get rid of this error?UPDATE:After setting the LIBUSB_DEBUG environment variable to 3 I got the following message:[op_init] could not find usbfs | libusb_init() returns -99 | linux;kernel | libusb requires that the VFS usbfs is mounted. After adding the following line to /etc/fstab the problem was solved:usbfs /proc/bus/usb usbfs defaults 0 0 |
_cs.47593 | I'm trying to find out how many circuits exist in a graph $G$, given its adjacency matrix.Yet, the only thing I know is how to find out if there is a circuit in a graph $G(X,U)$ given a list of out-neighbours for each vertex. To do that, you just delete every vertex with no out-neighbours, and update the adjacency lists for the remaining vertices. If repeating this operation deletes all the vertices, the graph had no circuit; otherwise, it has a circuit.For example,\begin{array}{|l|cr|}x & \Gamma^+(x)\\\hlinea & b,c,d\\b & d,e\\c & d,f \\e & d,h \\f & g,i \\g & h, e \\h & \emptyset\\i & g,h \\\end{array} Whenever $\Gamma^+(x)$ is empty, we can delete $x$.\begin{array}{|l|cr|}x & \Gamma^+(x)\\\hlinea & b,c,d\\b & d,e\\c & d,f \\e & d,\not h \\f & g,i \\g & \not h, e \\\not h & \not\emptyset\\i & g,\not h \\\end{array} Therefore, a circuit exists in $G$.Yet, it only tells me if there is a circuit in my graph. How may I find all circuits?for instance with: $$\begin{bmatrix} 0 & a & b & c & d & e & f & g & h & i \\ a & 0 & 1 & 1 & 1 & 0 & 0 & 0 & 0 & 0 \\ b & 0 & 0 & 0 & 1 & 1 & 0 & 0 & 0 & 0 \\ c & 0 & 0 & 0 & 1 & 0 & 1 & 0 & 0 & 0 \\ d & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 \\ e & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 1 & 0 \\ f & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 1 \\ g & 0 & 0 & 0 & 1 & 1 & 0 & 0 & 1 & 0 \\ h & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ i & 0 & 0 & 0 & 0 & 0 & 0 & 1 & 1 & 0 \\\end{bmatrix}$$What algorithm should I use to find all the circuits of this graph? Even a hint would be appreciated. | Finding all circuits in a graph | algorithms;graph theory | null |
_unix.243223 | Just had a warning that my Gmail's been accessed from the following IP: 151.230.107.114 which routes to something called htc_frisbee.com , which doesn't appear to be a real website. Could this just be a proxy for my phone, and is the traceroute I ran useful in any way? Could anyone suggest other apps, particularly ones accessible from Linux Mint and the apt-get command, which might help work out where this access came from? | Access from unknown IP tracks to non-existent website | linux mint;apt;ip;remote;traceroute | The IP address 151.230.107.114 is a dynamical one which belongs to Sky Broadband. You can see this from:whois 151.230.107.114Sky Broadband is a United Kingdom ISP.What Google is indicating you is the fact that the last time you connected to them, this was from this IP address and it is different from your usual one. This is the main reason of this warning. |
_codereview.109182 | Here is my method that I use to get one entity in an ASP.NET Web API application.[EnableQuery]public virtual HttpResponseMessage GetById([FromODataUri]int id){ // get concrete entity from repository var entity = repository.GetById(id); // check entity if (entity == null) { var message = string.Format(No {0} with ID = {1}, GenericTypeName, id); return ErrorMsg(HttpStatusCode.NotFound, message); } // problem return Request.CreateResponse(HttpStatusCode.OK, SingleResult.Create(repository.Table.Where(t => t.ID == id)));}I'm using SingleResult for OData request (because $expand for single entity does not work if I do not create SingleResult). But in this case I repeatedly do almost the same action repository.GetById(id); and repository.Table.Where(t => t.ID == id).How can I improve it? | Method GetById and SingleResult | c#;asp.net mvc;asp.net web api | You can wrap the single entity into an IQueryable. Something like this should work:SingleResult.Create(new[]{entity}.AsQueryable());You could write a helper function that uses this trick to convert from a single T to an IQueryable<T>. There may even be a built-in way of doing this. |
_unix.124782 | How can I dim only select screens of my multiple-monitor linux system?I have 5 monitors connected to my computer 4 *15 inch and one 27 inch.sometimes i want to use only the main screen (27) and have the rest black or in power saveHow can i do this? I'm running ubuntu linux 13.10 with kde.To blackout all screens I use xset dpms force off but this will be undone as soon as i touch the mouse or keyboard. | Selective dim screens | xorg;monitors;multi monitor | null |
_unix.192158 | I know this is to be done by creating a .contract file in /usr/share/contractor.For example, one like this will add a menu option to open a folder as root.[Contractor Entry]Name=Open folder as rootIcon=gksu-root-terminalDescription=Open folder as rootMimeType=inode;application/x-sh;application/x-executable;Exec=gksudo pantheon-files -d %UGettext-Domain=pantheon-filesHow to adjust such a contractor file for the 'make executable' option? What about a 'Run' option for the executable files? | How to add 'Make executable' and 'Run' entries to Elementary OS file manager context menu? | executable;elementary os;file manager;menu;pantheon | sudo gedit /usr/share/contractor/make_executable.contractAdd this content and save:[Contractor Entry]Name=Make executableIcon=name.of.icon.wantedDescription=Make a file executableMimeType=inode;application/x-sh;application/x-executable;Exec=gksudo chmod +x %UShould do the trick.But it is possible that in elementaryOS a file that was made executable may still lack the option of being run from context menu or click: it may open instead in a text editor, etc.To add a 'Run' menu entry to run such a file create a new contractor entry sudo gedit /usr/share/contractor/run.contractlike this:[Contractor Entry]Name=Run Icon=runDescription=RunMimeType=inode;application/x-sh;application/x-executable;Exec=sh %U |
_unix.150872 | Owing to a corporate strategy I am moving human user authentication from an implementation of LDAP locally to a centralized Active Directory domain. The problem is that we have a tightly constrained sudoers setup within LDAP. Our Windows admins are unable to mirror this setup without considerable work and possibly not even completely if the time is devoted. An idea that was posed was this:Authenticate to Active Directory but maintain sudoers management within our existing LDAP infrastructure.The question then is it possible to either authenticate using an alternate method/server for AD so I can have LDAP for sudoers and something alternative for passwd in /etc/nsswitch.conf?Due to scale, maintaining local /etc/sudoers files for each guest would be administratively prohibitive and a step back in terms of architecture and scalability. | Authenticating To Multiple LDAP Servers | authentication;ldap;sles | null |
_codereview.165295 | I'm looking to optimize my for loop to search faster. I've turned off ScreenUpdating, EnableEvents, Calculation, and DisplayStatusBar to speed it up a litte. I have about 10,000 rows to search for in the FAR tab. It works by reading the FAR tab rows and if it matches the master account list (Account_Range) located in the Input tab, it won't delete the row. It will then update the rows (not shown above). I ran this and it took exactly an hour to run. Sub DeleteRowsWithArray()Dim dontDelete() As VariantDim actRange As rangeSet actRange = Sheets(Input).range(Account_Range)dontDelete = actRangeDim i As Long, j As LongDim isThere As BooleanSheets(FAR).SelectFor i = Cells(Rows.Count, B).End(xlUp).Row To 3 Step -1 For j = LBound(dontDelete) To UBound(dontDelete) If StrComp(range(B & i), dontDelete(j, 1), vbTextCompare) = 0 Then isThere = True End If Next j If Not isThere Then range(B & i).Delete shift:=xlUp End If isThere = FalseNext iEnd Sub | Delete unmatched rows in Excel | vba;excel;time limit exceeded | null |
_cs.4746 | How to prove that BFS directed-graph traversal algorithm terminates?(I copy the pseudocode from here) Input: A graph G and a root v of G. procedure BFS(G,v): create a queue Q enqueue v onto Q mark v while Q is not empty: t Q.dequeue() if t is what we are looking for: return t for all edges e in G.incidentEdges(t) do o G.opposite(t,e) if o is not marked: mark o enqueue o onto Q | How to prove that BFS directed-graph traversal algorithm terminates? | algorithms;algorithm analysis;correctness proof | The only potentially non-terminating construct used here is the while loop. So you need to prove that Q eventually becomes empty.Q contains vertices from the graph. The only operations that add elements to Q are the enqueue operations. Each adds a single vertex. So proving the termination of the algorithm is equivalent to proving that only a finite number of enqueue operations are performed.The first call to enqueue at the beginning of the program adds one vertex and marks it. The second call to enqueue adds a vertex that was not marked yet, and the vertex is marked at the same time.Since a vertex is never unmarked, the set of marked vertices can only grow.The set of marked vertices is included in the set of all vertices. Note that the graph is be assumed to be finite (in an infinite graph, the search might not terminate). Hence there are at most $|G|$ mark operations where $|G|$ is the number of vertices in the graph. Since each enqueue operation has a corresponding mark, there are at most $|G|$ enqueue operations. Therefore there are at most $|G|$ dequeue operations. Since there is one dequeue operation at each loop iteration, there are at most $|G|$ iterations of the while loop, a finite number. |
_webapps.41976 | Looking for a web app or browser that can save a complete web page including css style sheet includes and css background images.I have tried IE9, Firefox and Chrome browsers. | Web page Save as including css includes and css background images | webapp rec | null |
_softwareengineering.330508 | System consists of several micro-services and each of them is in charge of it's own context, such as booking, payment, products and notifications.Let's imagine we have a traveler who is seeking accommodation on website. Accommodation is listed by retrieving information from products micro-service.Traveler found what he wants and decided to make a reservation.He selects date, number of nights, people etc, and submits a request to booking micro-service. Request contains all payment details and booking details.Here comes the fun part:Request creates a reservation record with status pending and publishesevent, reservation_created.Payment service pools for that event, creates a credit card authorization and publishes event authorization_successfull with booking ID inside event payload.Product micro-service pools for authorization_successful event and checks if accommodation is really available for the requested period. If everything is ok, accommodation will be marked as occupied for desired period and publish availability_updated event.Booking micro-service will pool for that event and change reservation status to approved, which will then publish new event, so notifications micro-service can pool for it, and send necessary emails. Now, I have several questions:This looks nice in theory, but am I over-complicating things, or this is a way to go to achieve decoupling?By going with this approach, I can't inform traveler Reservation complete since there is a long running process involved in the background. My guess is that info message should be more like Reservation requested, you will receive confirmation email shortly, or i should pool one of service endpoints with loading screen, or even use web sockets to send notification back? | User interface and process that involves asynchronous communication between several microservices | rest;domain driven design;distributed computing;microservices;eventual consistency | null |
_unix.187491 | I know that random number generators on computers are only pseudo-random, but are the PRNGs on Live Boot USB or DVDs even less random? Is there a way to seed them after booting?Specifically curious about Xubuntu 14 on USB. | How random is the pseudo random number generators on live boot disks? Is there a way to seed it? | live usb;livecd;random | null |
_codereview.61502 | I have a main form which does processing for an extended period of time. Normally, progress bars are used to show either the loading status or simply show the program is still running/hasn't freezed. For this form, I wanted to give it a more snazzy look by reusing a common loading GIF found on the web that many users would be familiar with. This is how I implement said GIF:ShowLoadingGif(); //Heavy liftingHideLoadingGif();private void ShowLoadingGif(){ this.Enabled = false; Point formCenterPt = new Point() { X = this.Location.X + (this.Width/2), Y = this.Location.Y + (this.Height/2) }; loadingThread = new Thread(() => ShowLoading(formCenterPt)); loadingThread.IsBackground = true; loadingThread.Name = Loading gif; loadingThread.Start();} private void HideLoadingGif(){ try { this.Enabled = true; if(loadingThread.IsAlive) loadingThread.Abort(); } catch (Exception ex) { Log(String.Concat(Loading gif thread release failed: ,ex)); }}private void ShowLoading(Point parentCenter){ frmLoadingGif loading = new frmLoadingGif(); Point offsetPt = new Point() { X = parentCenter.X - (loading.Width /2), Y = parentCenter.Y - (loading.Height/2) }; loading.StartPosition = FormStartPosition.Manual; loading.Location = offsetPt; loading.ShowDialog();}What this does is produces a loading GIF (I grabbed mine from ajaxloader) in the center of the form while processing is ongoing, and also disables the form. My question is, whether or not what I did was overkill for something as simple as an inprogresss status, or if using threads in this way is the best way to do it. I realize that using a control on the main form would have been easier, but I couldn't find a way to do so with a GIF while also making the background completely transparent. Why have I chosen to use a form for showing the GIF?The alternative would have been to add the picture box to the main form. However, this didn't seem the best solution because I wanted to center the GIF to the form itself, and with the TableLayoutPanel I was using, you can't simply change the location of a control in that manner (please correct me if I'm wrong here). I also wanted to keep the transparency, threading, and other attributes of the picturebox control separate from the main form so I could reuse it elsewhere.Finally, I wanted to show the GIF loading on top of the current form, and not just in the corner/bottom in its own section like a progress bar would. As you'll see in the picture, the loading GIF is shown on top of the control behind it, a DataGridView. | Loading GIF form on a Windows console app using threads | c#;multithreading;thread safety;winforms;animation | null |
_webmaster.47668 | My Virtualmin has a domain with an SSL cert enabled. All domains are on the same IP.The other domains have SSL disabled, and the problem is that if I request a https page for these domains they redirect to the domain with SSL. I just want a no response or a missing page response from the server. How can I configure this? | Virtualmin: https domain showing up for all other domains that have ssl disabled | https;webmin | null |
_unix.266668 | On a linux server with dhcpd that acts as the internet gateway for all clients of the LAN: how can I monitor the internet usage based on IP/MAC address, and deny internet access if a certain bandwidth consumption has been exceeded? | Monitor and limit internet bandwidth per network client | linux;networking;monitoring;bandwidth | On Linux, you could get this done with some scripting:Create firewall rules with iptables so that all bandwidth for each client passes through a separate rule. The firewall subsystem in the kernel will count network packets and bytes that a particular rule matched. You can see the counters if you run iptables -vL. You might want to use the -n option too, for performance: iptables -vnLWrite a script that runs from cron and which checks how much data has been used by every client. Then if it's over a particular amount, have the script modify the firewall so that the client can not access the Internet anymoreNote that iptables' counters get reset when the firewall is cleared (i.e., after reboot, or when you do iptables -F. As such, you might want to have the script state its conclusions to some database or something. |
_codereview.97859 | This is a follow-on to my previous question: Enforcing set environment variablesWhile learning more about JavaScript, node, and the bluemix environment, I have been using the loading of process environment variables as a starting point for understanding how the systems work.This part of the system checks to see if a 'default' value exists for an environment variable. If there is a default, and the variable is not set, then the variable is set to the default's value. Default values are stored in a file in a pre-defined directory (the same folder as the script file).After taking in the review suggestions, and some other suggestions from colleagues, I have changed the code mechanism to use a map/filter/process system on the files. This makes the code quite a bit neater.Note: this code is a file/module in a node.js application deployed in a Bluemix host.Again I am looking for any further insights in to how the code can be improved, and if any edge cases exist. Performance is not critical, but as I am just learning JavaScript I would appreciate any insights in to any bad practices that should be avoided so that issues are avoided later on.In particular, I am concerned that the code is not as asynchronous as it could be, though it is a requirement that all the variables are set before the code terminates (nothing asynchronous can be incomplete)./*jshint node:true*//* * Load various pre-determined environment variables * (files in this folder with .env extension). * Only if they have not previously been set in the environment. * * This makes the setting of Bluemix style variables quite easy. */var fs = require('fs');var path = require('path');var env = /\.env$/;function isEnv(fileName) { return fileName.match(env);}function processEnv(fileName) { var key = fileName.replace(env, ); if (process.env.hasOwnProperty(key)) { return; } var filePath = path.join(__dirname, fileName); var data = fs.readFileSync(filePath, 'utf8'); process.env[key] = data;}fs.readdirSync(__dirname) .filter(isEnv) .forEach(processEnv); | Mapping file data to environment variables | javascript;node.js;file system;bluemix | This code is very clean and is definitely a clear improvement from your last version.Your code is easy to understand and follow, now that's it's more broken up (aside from one big block of code).I recommend storing your regexular expression for locating the extension .env like this:var env = new RegExp(\.env$/, );The reason is for this: RegExp.test.The test method of a RegExp object does the following:Returns true if the regexular expression matches the input string.Returns false if the regexular expression does not match the input string.Now, your isEnv function does this:return env.test(fileName);Why is this better? Well...The test method of RegExp only has to worry about the regexular expression matching at all.The match method of a string has to worry about the regexular expression matching AND it has to worry about creating and returning an array of all the matches.That being said, the test method is obviously faster than using match. |
_unix.242337 | I'm renting a vps with debian 8 on it.I'm trying to set up my iptables, following this blog:http://bencane.com/2012/09/iptables-linux-firewall-rules-for-a-basic-web-server/The problem is that my setup doesn't seem to be correct.I first update my server by apt-get updateThen I add the rules to iptables, install iptables-persistent but trying to do the commandiptables-persistent save and I get is a directory rather than the saving process... when I install iptables-persistent this saves the ipv4 ipv6 settings, and using cat /etc/iptables/rules.v4 I see my rules.There is a last step typing in the command ls -la /etc/rc2.d/ | grep iptables should show something but mine does not.in my /etc/init.d/ directory I'm supposed to have iptables-persistent but it's actually in /usr/share/doc/ so I moved it to /etc/init.d/ but this does not seem to solve the problem as trying the command /etc/init.d/iptables save does not work, I get is a directory I think it is supposed to be a script file.I'm not really sure what is going on.The contents of iptables-persistent is a .gz changelog file so that's probably why the command doesn't work right? | Debian 8 iptables-persistent setup is not correct? | linux;debian;iptables;iptables persistent | The documentation you have linked is outdated. The binary package you need is now named netfilter-persistent. But don't worry, you have it already installed because iptables-persistent is now a plugin to netfilter-persistent, which was installed with it. So everything was okay and you should really move the documentation directory back to where it belongs.Concerning the usage: Just replace all calls to iptables-persistent with netfilter-persistent and it should work as advertised. (But you probably should set chmod go-rwx /etc/iptables to make the directory containing the rules not readable for anyone except root.) |
_vi.11666 | I've been having a ridiculously hard time getting C/C++ code folding to work with set foldmethod=syntax. To debug my issue I've stripped down my vimrc to only this:set foldmethod=syntaxsyntax on also tried putting this firstNow when I open a cpp file, nothing is folded.Then, doing :syntax off followed by :syntax on will fold the cpp file.Any idea why that does something not already done by the trivial vimrc? | Folding doesn't work for C/C++ | syntax highlighting;folding;filetype c++;filetype c | After some detective work I tracked down the cause of my issue being that I had a .vim file in my plugin directory that redefined OperatorChars, which broke the syntax based folding for C and C++. |
_unix.270945 | Today I am experiencing problems on my laptop running Fedora 22 with a external USB 3 Seagate hard drive. I plugged the drive in and it wouldn't mount, instead showing low_memory errors in dmesg. Rebooting fixed it initially, but when later on I tried plugging in the disk it wouldn't mount again - this the relevant bit of dmesg:usb 4-4: new SuperSpeed USB device number 6 using xhci_hcd[ 2354.749660] usb 4-4: New USB device found, idVendor=0bc2, idProduct=ab24[ 2354.749680] usb 4-4: New USB device strings: Mfr=2, Product=3, SerialNumber=1[ 2354.749684] usb 4-4: Product: BUP Slim BK[ 2354.749686] usb 4-4: Manufacturer: Seagate[ 2354.749688] usb 4-4: SerialNumber: NA7KR1X0[ 2354.752380] scsi host11: uas[ 2354.752387] kworker/0:2: page allocation failure: order:7, mode:0x208c020[ 2354.752390] CPU: 0 PID: 8715 Comm: kworker/0:2 Tainted: P OE 4.4.4-200.fc22.x86_64 #1[ 2354.752392] Hardware name: LENOVO 62743QG/62743QG, BIOS H1ET84WW(1.22) 11/26/2013[ 2354.752398] Workqueue: usb_hub_wq hub_event[ 2354.752401] 0000000000000286 000000001bd47e87 ffff8801219fb4d0 ffffffff813b515e[ 2354.752404] 000000000208c020 0000000000000000 ffff8801219fb560 ffffffff811b2fea[ 2354.752406] 0000000000000007 000000008179fbae ffff88021e5e8e00 ffffffffffffff80[ 2354.752409] Call Trace:[ 2354.752415] [<ffffffff813b515e>] dump_stack+0x63/0x85[ 2354.752419] [<ffffffff811b2fea>] warn_alloc_failed+0xfa/0x160[ 2354.752422] [<ffffffff811b6ec1>] __alloc_pages_nodemask+0x361/0xbc0[ 2354.752427] [<ffffffff81202a1c>] alloc_pages_current+0x8c/0x110[ 2354.752430] [<ffffffff811b51b9>] alloc_kmem_pages+0x19/0x90[ 2354.752434] [<ffffffff811d2f4e>] kmalloc_order_trace+0x2e/0xe0[ 2354.752438] [<ffffffff8120e722>] __kmalloc+0x232/0x260[ 2354.752442] [<ffffffff8138989d>] init_tag_map+0x3d/0xc0[ 2354.752445] [<ffffffff81389965>] __blk_queue_init_tags+0x45/0x80[ 2354.752448] [<ffffffff813899b4>] blk_init_tags+0x14/0x20[ 2354.752452] [<ffffffff81520b40>] scsi_add_host_with_dma+0x80/0x300[ 2354.752457] [<ffffffffa00c1423>] uas_probe+0x3e3/0x520 [uas][ 2354.752461] [<ffffffff8158acad>] usb_probe_interface+0x1bd/0x300[ 2354.752465] [<ffffffff814eeeb2>] driver_probe_device+0x222/0x490[ 2354.752467] [<ffffffff814ef221>] __device_attach_driver+0x71/0xa0[ 2354.752470] [<ffffffff814ef1b0>] ? __driver_attach+0x90/0x90[ 2354.752472] [<ffffffff814eca67>] bus_for_each_drv+0x67/0xb0[ 2354.752474] [<ffffffff814eeb8c>] __device_attach+0xdc/0x170[ 2354.752477] [<ffffffff814ef293>] device_initial_probe+0x13/0x20[ 2354.752479] [<ffffffff814ede42>] bus_probe_device+0x92/0xa0[ 2354.752481] [<ffffffff814eb9fb>] device_add+0x40b/0x680[ 2354.752484] [<ffffffff8157a7b9>] ? usb_enable_lpm+0x89/0x90[ 2354.752487] [<ffffffff81588b71>] usb_set_configuration+0x511/0x8e0[ 2354.752490] [<ffffffff815934be>] generic_probe+0x2e/0x80[ 2354.752492] [<ffffffff8158aab2>] usb_probe_device+0x32/0x70[ 2354.752495] [<ffffffff814eeeb2>] driver_probe_device+0x222/0x490[ 2354.752497] [<ffffffff814ef221>] __device_attach_driver+0x71/0xa0[ 2354.752499] [<ffffffff814ef1b0>] ? __driver_attach+0x90/0x90[ 2354.752501] [<ffffffff814eca67>] bus_for_each_drv+0x67/0xb0[ 2354.752503] [<ffffffff814eeb8c>] __device_attach+0xdc/0x170[ 2354.752506] [<ffffffff814ef293>] device_initial_probe+0x13/0x20[ 2354.752508] [<ffffffff814ede42>] bus_probe_device+0x92/0xa0[ 2354.752509] [<ffffffff814eb9fb>] device_add+0x40b/0x680[ 2354.752513] [<ffffffff814c0400>] ? add_device_randomness+0x50/0x140[ 2354.752516] [<ffffffff8157e047>] usb_new_device+0x277/0x4b0[ 2354.752519] [<ffffffff8158028d>] hub_event+0x103d/0x1590[ 2354.752524] [<ffffffff810bc596>] process_one_work+0x156/0x430[ 2354.752527] [<ffffffff810bc8be>] worker_thread+0x4e/0x450[ 2354.752531] [<ffffffff8179b955>] ? __schedule+0x3a5/0xa00[ 2354.752533] [<ffffffff810bc870>] ? process_one_work+0x430/0x430[ 2354.752536] [<ffffffff810bc870>] ? process_one_work+0x430/0x430[ 2354.752538] [<ffffffff810c2648>] kthread+0xd8/0xf0[ 2354.752540] [<ffffffff810c2570>] ? kthread_worker_fn+0x160/0x160[ 2354.752543] [<ffffffff817a048f>] ret_from_fork+0x3f/0x70[ 2354.752545] [<ffffffff810c2570>] ? kthread_worker_fn+0x160/0x160[ 2354.752564] Mem-Info:[ 2354.752571] active_anon:316599 inactive_anon:48172 isolated_anon:0 active_file:647763 inactive_file:660760 isolated_file:0 unevictable:0 dirty:3065 writeback:0 unstable:0 slab_reclaimable:99971 slab_unreclaimable:20297 mapped:57919 shmem:49646 pagetables:9709 bounce:0 free:118581 free_pcp:639 free_cma:0[ 2354.752576] Node 0 DMA free:15884kB min:20kB low:24kB high:28kB active_anon:0kB inactive_anon:0kB active_file:0kB inactive_file:0kB unevictable:0kB isolated(anon):0kB isolated(file):0kB present:15984kB managed:15900kB mlocked:0kB dirty:0kB writeback:0kB mapped:0kB shmem:0kB slab_reclaimable:0kB slab_unreclaimable:16kB kernel_stack:0kB pagetables:0kB unstable:0kB bounce:0kB free_pcp:0kB local_pcp:0kB free_cma:0kB writeback_tmp:0kB pages_scanned:0 all_unreclaimable? yes[ 2354.752585] lowmem_reserve[]: 0 3109 7566 7566[ 2354.752602] Node 0 DMA32 free:270468kB min:4540kB low:5672kB high:6808kB active_anon:503680kB inactive_anon:79744kB active_file:1043728kB inactive_file:1125396kB unevictable:0kB isolated(anon):0kB isolated(file):0kB present:3266876kB managed:3187136kB mlocked:0kB dirty:4684kB writeback:0kB mapped:96256kB shmem:81308kB slab_reclaimable:97220kB slab_unreclaimable:27128kB kernel_stack:2704kB pagetables:16068kB unstable:0kB bounce:0kB free_pcp:1456kB local_pcp:144kB free_cma:0kB writeback_tmp:0kB pages_scanned:0 all_unreclaimable? no[ 2354.752609] lowmem_reserve[]: 0 0 4456 4456[ 2354.752612] Node 0 Normal free:187972kB min:6504kB low:8128kB high:9756kB active_anon:762716kB inactive_anon:112944kB active_file:1547324kB inactive_file:1517644kB unevictable:0kB isolated(anon):0kB isolated(file):0kB present:4691968kB managed:4563068kB mlocked:0kB dirty:7576kB writeback:0kB mapped:135420kB shmem:117276kB slab_reclaimable:302664kB slab_unreclaimable:54044kB kernel_stack:5136kB pagetables:22768kB unstable:0kB bounce:0kB free_pcp:1100kB local_pcp:236kB free_cma:0kB writeback_tmp:0kB pages_scanned:0 all_unreclaimable? no[ 2354.752616] lowmem_reserve[]: 0 0 0 0[ 2354.752619] Node 0 DMA: 1*4kB (U) 1*8kB (U) 2*16kB (U) 1*32kB (U) 1*64kB (U) 1*128kB (U) 1*256kB (U) 0*512kB 1*1024kB (U) 1*2048kB (M) 3*4096kB (M) = 15884kB[ 2354.752643] Node 0 DMA32: 6*4kB (UME) 8*8kB (UME) 11101*16kB (UME) 2803*32kB (UME) 46*64kB (ME) 0*128kB 0*256kB 0*512kB 0*1024kB 0*2048kB 0*4096kB = 270344kB[ 2354.752652] Node 0 Normal: 2*4kB (UM) 2*8kB (UM) 8980*16kB (ME) 1326*32kB (UME) 26*64kB (M) 0*128kB 0*256kB 0*512kB 0*1024kB 0*2048kB 0*4096kB = 187800kB[ 2354.752661] Node 0 hugepages_total=0 hugepages_free=0 hugepages_surp=0 hugepages_size=2048kB[ 2354.752663] 1358227 total pagecache pages[ 2354.752664] 0 pages in swap cache[ 2354.752665] Swap cache stats: add 0, delete 0, find 0/0[ 2354.752666] Free swap = 0kB[ 2354.752674] Total swap = 0kB[ 2354.752675] 1993707 pages RAM[ 2354.752676] 0 pages HighMem/MovableOnly[ 2354.752677] 52181 pages reserved[ 2354.752678] 0 pages cma reserved[ 2354.752679] 0 pages hwpoisoned[ 2354.753318] uas: probe of 4-4:1.0 failed with error -12and also the amount of memory/swap at the time (free -m): total used free shared buff/cache availableMem: 7584 1237 493 196 5852 6029Swap: 0 0 0As it seemed to be because of limited memory, I cleared the memory cache (echo 3 | sudo tee /proc/sys/vm/drop_caches) and tried again, and it worked :). Here is the dmesg:[ 2714.892041] tee (14048): drop_caches: 3[ 2724.745378] usb 4-4: USB disconnect, device number 6[ 2726.561479] usb 4-2: new SuperSpeed USB device number 7 using xhci_hcd[ 2726.573070] usb 4-2: New USB device found, idVendor=0bc2, idProduct=ab24[ 2726.573075] usb 4-2: New USB device strings: Mfr=2, Product=3, SerialNumber=1[ 2726.573077] usb 4-2: Product: BUP Slim BK[ 2726.573079] usb 4-2: Manufacturer: Seagate[ 2726.573081] usb 4-2: SerialNumber: NA7KR1X0[ 2726.575116] scsi host12: uas[ 2726.576138] scsi 12:0:0:0: Direct-Access Seagate BUP Slim BK 0302 PQ: 0 ANSI: 6[ 2726.576923] sd 12:0:0:0: Attached scsi generic sg3 type 0[ 2726.576926] sd 12:0:0:0: [sdc] Spinning up disk...[ 2727.577320] ...ready[ 2729.581063] sd 12:0:0:0: [sdc] 3907029167 512-byte logical blocks: (2.00 TB/1.82 TiB)[ 2729.581070] sd 12:0:0:0: [sdc] 2048-byte physical blocks[ 2729.828378] sd 12:0:0:0: [sdc] Write Protect is off[ 2729.828387] sd 12:0:0:0: [sdc] Mode Sense: 4f 00 00 00[ 2729.828631] sd 12:0:0:0: [sdc] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA[ 2729.835161] sdc: sdc1 sdc2 sdc3[ 2729.836456] sd 12:0:0:0: [sdc] Attached SCSI diskAnd the free -m: total used free shared buff/cache availableMem: 7584 1785 5186 228 612 5472Swap: 0 0 0This seems odd as I have had the setup for ages and previously have had no issues - the only recent changes I can think of are me filling the drives as I am trying to reinstall another machine:Filesystem Size Used Avail Use% Mounted on/dev/sda6 59G 49G 7.2G 88% //dev/sda7 71G 70G 1.2G 99% /media/Music/dev/sda8 112G 97G 16G 87% /media/Storage/dev/sda5 111G 84G 21G 81% /home/dev/sdc1 448G 434G 14G 97% /run/media/wilf/Seagate Backup Plus Drive/dev/sdc2 917G 867G 3.3G 100% /run/media/wilf/Ext1/dev/sdc3 477G 428G 25G 95% /run/media/wilf/Ext2and perhaps the system being updated. So please:Why did this happen (and how can I fix it)?Would having some swap help with issue?Shouldn't memory cache clear itself if needed anyway (linuxatemyram and all that)? | Why can't I mount the disk now with limited memory? | usb;automounting;ram;external hdd | null |
_datascience.4827 | Is there any way to use package dplyr on RStudio having R base 3.0.2 ? I am not interested in plyr package.ThanksNavin | Can we use package dplyr on R base 3.0.2? | data mining | null |
_codereview.38570 | I'm doing a CodingBat exercise and would like to learn to write code in the most efficient way. On this exercise, I was just wondering if there's a shorter way to write this code.monkeyTrouble(true, true) truemonkeyTrouble(false, false) truemonkeyTrouble(true, false) falsepublic boolean monkeyTrouble(boolean aSmile, boolean bSmile) { if (aSmile && bSmile) { return true; } if (!aSmile && !bSmile) { return true; } return false; } | Simpler boolean truth table? | java | null |
_webapps.37091 | I have a few .js, .html, and .css files on my GitHub. I'd like to make these files publicly accessible as libraries to anyone with an internet connection.Is this possible?Currently, the URLs to my pages are GitHub versions of the code not the actual file. I just want a URL for the actual file. | Exporting / publishing a file on Github | github | The raw files for GitHub repositories are stored at:https://raw.github.com/user/repository/branch/filenameFor example:https://raw.github.com/slhck/dotfiles/master/.zshrcYou can access this file by clicking the Raw button for a file: |
_softwareengineering.178916 | Possible Duplicate:what are the best tips for storing images in a database? In those study cases of image storage, An image that change only once in a while, if it changes at all (like an image for an article)The image case from above is not only one image but over 10, that link to the same articleAn image that have changes very often (like a banner image for a website)The image above is hugeWhat is the best approach for each case? What is the right/faster way to do this task in each scenario ? | Store image as logic file (in db by using binary format) or physical file (in the server) | web development;code quality;performance | Sorry to provide a link only answer, but this microsoft research paper goes into great detail on the advantages of file system vs database for file storage:To BLOB or Not To BLOB |
_codereview.11318 | I've just started with coffeescript, and I saw http://blog.8thlight.com/uncle-bob/2012/04/20/Why-Is-Estimating-So-Hard.html which has a little programming problem, so I figured I'd do it in coffeescript (which seemed easy enough to do... )anyways, I ended up with :-lineEndings = ( s, len ) -> words = s.split ' ' line = '' result = '' words.map ( word ) -> if line.length == 0 line = word else if line.length + 1 + word.length <= len line = line + ' ' + word else result = result + line + '\n' line = word result + linegetty = Four score and seven years ago our fathers brought forth upon this continent a new nation, conceived in liberty and dedicated to the proposition that all men are created equal console.log lineEndings getty, 13I'm looking for any ways I could make this simpler coffeescript.( I just used nodejs with coffescript installed to test this ) | Is there any way to make this CoffeScript code simpler / smaller | coffeescript | null |
_webmaster.20782 | Possible Duplicate:How to find web hosting that meets my requirements? I looking for a MongoDB managed hosting solution, here are 3 I found comparable.Has anyone have some insights in which one to use? | MongoDB Hosting: MongoLab vs MongoHQ vs MongoMachine | looking for hosting;mongodb | Johnny...sorry about that. Lots of good stuff happening at MongoHQ right now so we have gotten a bit behind in responding to non-emergency requests. Our offering includes replica sets, user controlled backups and powerful web tools on top of arguably the world's largest provisioned MongoDB data layer. We have been around since the pre 1.0 days and have certainly learned over the last few years how to effectively run MongoDB in the cloud.Also, we recently acquired MongoMachine. So, we are building our solutions for their customers as well. Busy but exciting!Happy to help.JasonMongoHQ |
_webmaster.31401 | I consider myself to be an inexperienced user/administrator when it comes to running my VPS. I can get by with a few CLI commands, I can set up Webmin and I can set up Yum repos, but beyond the very basic stuff, I'm out of my depth.So far, I'm running Apache. I don't know it particularly well, but I can get by with editing httpd.conf if I'm told what to edit.I've heard good things about Nginx and that it's not as resource-hungry as Apache. I'd like to give it a go, but I can't find any information about its suitability for administrators like me, with little experience of sysadmin or web server config.Webmin now has support for Nginx, so getting it installed and running probably won't be too much of a problem. What I'm wondering is, from a site administrator perspective, is running Nginx as transparent as running Apache? IE, at the moment, I can just throw up Wordpress and Drupal sites without having much to worry about or having to make any config changes to Apache. Would Nginx be as transparent? | Nginx or Apache for a VPS? | apache;webserver;nginx | I've been using Apache for the last several years, because it is easy to use and configure, runs smoothly over vast networks, and has many available modules to perform various tasks.Apache is process-based, and nginx is event-based. This means, it doesn't need to create a new thread for each thing it has to process.Keeping it short, I think you're best off (if things work properly) sticking with Apache. You can always set up a second server with Nginx and slowly migrate the site(s) and services over.The only thing I ever use Nginx for is creating reverse proxies to route Apache-served content from local servers to the outside world. Nginx is also better at mitigating DOS (Denial of Service) attacks. Rather than create an unmanageable number of threads like Apache tends to, it drops the requests.Overall, it really depends what kind of traffic you're getting on your server, and if it would help at all to make the switch. |
_webmaster.71602 | Our company need to migrate domain from:www.example.it -> www.example.euThe example.it have some links with 301 redirects like:example.it/index.php?id=10&link=slug (301 redirect to) -> example.it/c10/slugand one more redirect:example.it/10/static-keyword/slug (301 redirect to) -> example.it/c10/slugNow we want to migrate the site. How should I redirect the website?1) Leave old redirect in example.it and than only original links redirect to example.eu. In example:example.it/index.php?id=10&link=slug (301 redirect to) -> example.it/c10/slug (301 redirect to) -> example.eu/c10/slugexample.it/10/static-keyword/slug (301 redirect to) -> example.it/c10/slug (301 redirect to) -> example.eu/c10/slug2) All links redirect to example.eu and then do all other redirects. In example:example.it/index.php?id=10&link=slug (301 redirect to) -> example.eu/index.php?id=10&link=slug (301 redirect to) -> example.eu/c10/slugexample.it/10/static-keyword/slug (301 redirect to) -> example.eu/10/static-keyword/slug (301 redirect to) -> example.eu/c10/slug | How to redirect domain from www.example.it to www.example.eu? | seo;redirects;301 redirect;migration | If possible, try to use only one 301 redirection. 301 redirects transfer SEO juice, but you lose a part of it for every one of them (around 10-15%).You should make a rule to redirect specific cases first, like:example.it/index.php?id=10&link=slug (301 redirect to) -> example.eu/c10/slug...Then, if none of these rules are triggered, you should apply example.it -> example.eu redirection.That way, all your specific pages will redirect immediately to a proper URL and the rest of them will redirect to the same URL on a different domain. |
_codereview.58862 | For now, I have two views using Twig:messages.html.twigitem.html.twigThe first one is the view which displays all of the users' posts in my forum. When a user post a new message, it's done via Ajax so the server returns a view with the posts information. That view is item.html.twigSo I have something like:messages.html.twig{% for item in posts %} <div class=post> Posted by {{ item.author }}<br> {{ item.body }} </div>{% endfor %}(well much more information in each posts of course)item.html.twig <div class=post> Posted by {{ item.author }}<br> {{ item.body }} </div>But the code is now duplicated and if I have to add a functionality or if I change my class names, I'll have to edit both of the views.Would it be okay, in terms of performances, if I just included the item.html.twig in messages.html.twig like:{% for item in posts %} {% include 'item.html.twig' with {item: item} %}{% endfor %}I don't know if there's a better solution so I would like to hear about ideas to improve my code. | Should I include a view for each message? | php;html;twig | I would strongly recommend you to go for the include solution. You will probably take a small performance hit, but that should not outweigh the benefits of having code that is much easier to maintain. Whenever you have to duplicate code, you are doing something wrong.Also, if you find performance really important, may I suggest not sending the rendered (sub)view trough ajax. It would be much better to send just the data as JSON over the wire. It will be much smaller, and the server does not need to take time to render anything. You can then parse the JSON in your js to render the view there. There are templating languages for js that you could use, there is even a js version of twig (I haven't used it yet, so I don't know if it is any good, but I like the idea...) |
_unix.184965 | I'm trying to edit a file from a remote computer connected via ssh. How can I open the remote file on my local computer to edit? | Open file from remote computer on host computer | ssh;remote | You can mount the remote directory with sshfs, after that, the file is accessible in your local directory tree.Example:sshfs user@domain:/remote/directory/ /local/directory/It's all in the man pages.Or just copy the file over with scp/rsync, edit it, and copy it back. |
_unix.134847 | As part of a sort of esoteric hack I'm putting together, I've modified my /etc/passwd and /etc/shadow files to result in a user called (Niet) with a shell pointing to a custom script I have written.This all works great, and I can do:ssh @localhostEnter the password, log in, and I get the output of my custom script (currently just Hello, World!, wait five seconds, then disconnect).It works beautifully!There's only one problem. I can't seem to SSH in directly from tools like PuTTY. In fact, the only way I've been able to connect is by SSHing in to my normal user, then doing the ssh to localhost as above.I have tried putting @example.com in the hostname field and similarly in the autologin username option, but both result in trying to log in as ???? which obviously fails. This is in spite of ensuring the character encoding is set to UTF-8.Similarly, I've tried not using auto-login, but... well...login as: @example.com's password:Access deniedNot quite what I'm after.I am well aware that what I have done with this username is a complete hack and I should probably be hit with a brick for it. But it does work, I just seem to be having a problem with my computer's PuTTY communicating with the server, since the server is perfectly able to communicate with itself.Am I missing an option or something to make this work? | Non-standard logins | ssh;character encoding;putty | null |
_unix.292835 | I make bus timetable booklets for drivers every day, and I have 4 PDF files:Special Instruction Sheet (Every day different)Bus daily timetable (which is always different)Bus Assistant daily report (internal form, always the same)Bus Driver Daily Report (internal form, always the same) So I can print them double-sided and stapled from a photocopier, I have been using PDFEscape.com to manually put them into the following order:A=front side of A4 paper. B=reverse side of A4 paper. 1a. Special Instructions1b. BLANK PAGE2a. Timetable2b. BLANK PAGE3a. Timetable3b. BLANK PAGE.......R-2a. Timetable second-last pageR-2b. BUS ASSISTANT FORMR-1a. Timetable last pageR-1b. BUD DRIVER FORMThe timetables are individual PDFs exported from a scheduling program, and the problem is they are not always the same number of pages (usually 1-5, but can be up to 15). It is so time-consuming. Does anyone know what script I could write that will do this?Thanks in advance! | Merge PDF document but with conditions | scripting;pdf;merge | null |
_unix.326086 | I have installed the default workstation group dnf install @workstation-product-environmentNow I want to remove all unnecessary KDE packages butdnf remove @kde-desktop-environtment gives me this error. Dependencies resolved.Error: The operation would result in removing the following protected packages: dnf, systemd.and dnf remove @kde wants to remove packages that I just installed that are not related to KDE (such as tkinter, redhat-menus, gnome-shell, and gnome-session)how can I remove KDE without breaking my system? | Fedora 24 switch from KDE spin to Default (GNOME) | fedora;package management;kde;desktop environment;dnf | null |
_unix.226162 | Help. The TV I'm trying to use as a monitor has overscan issues, it overscans both 1080p and 720p resolutions. For my use, I'd rather have borders compared to a cut off screen. I'm trying to get Linux Mint to output video to an external monitor like this.In mirror mode:AND still work as the primary display if the laptop is closedWindows 10 does the above ^ fine. But I can't get Linux Mint to preform the same way.I tried entering in thisxrandr --output eDP1 --primary --auto --output HDMI1 --auto --same-as eDP1but all I got was this:So my TV still overscans the top and side portion.How do I get it centered? And have borders so apps and programs can't go beyond the 1366x768 resolution?I posted the same plea for help, with perhaps just a few more details, on the Linux help forums | Mirror screen with 2 different resolution displays, -with borders on larger resolution screen? | linux;xrandr;monitors;dual monitor;multi monitor | null |
_unix.179004 | My SD card will suddenly not automount. It works on another Mac.Can someone provide a solution to mount with Terminal?$ diskutil list/dev/disk2#: TYPE NAME SIZE IDENTIFIER0: FDisk_partition_scheme *16.0 GB disk21: Windows_FAT_32 NO NAME 16.0 GB disk2s1 | How do I mount an SD card? | mount;osx | null |
_softwareengineering.150669 | I am currently creating a web application that allows users to store and share files, 1 MB - 10 MB in size.It seems to me that storing the files in a database will significantly slow down database access.Is this a valid concern? Is it better to store the files in the file system and save the file name and path in the database? Are there any best practices related to storing files when working with a database?I am working in PHP and MySQL for this project, but is the issue the same for most environments (Ruby on Rails, PHP, .NET) and databases (MySQL, PostgreSQL). | Is it a bad practice to store large files (10 MB) in a database? | database;database design;mysql;file handling | Reasons in favor of storing files in the database:ACID consistency including a rollback of an update which is complicated when the files are stored outside the database. This isn't to be glossed over lightly. Having the files and database in sync and able to participate in transactions can be very useful.Files go with the database and cannot be orphaned from it.Backups automatically include the file binaries.Reason against storing files in the database:The size of a binary file differs amongst databases. On SQL Server, when not using the FILESTREAM object, for example, it is 2 GB. If users need to store files larger (like say a movie), you have to jump through hoops to make that magic happen.Increases the size of the database. One general concept you should take to heart: The level of knowledge required to maintain a database goes up in proportion to the size of the database. I.e., large databases are more complicated to maintain than small databases. Storing the files in the database can make the database much larger. Even if say a daily full backup would have sufficed, with a larger database size, you may no longer be able to do that. You may have to consider putting the files on a different file group (if the database supports that), tweak the backups to separate the backup of the data from the backup of the files etc. None of these things are impossible to learn, but do add complexity to maintenance which means cost to the business. Larger databases also consume more memory as they try to stuff as much data into memory as possible.Portability can be a concern if you use system specific features like SQL Server's FILESTREAM object and need to migrate to a different database system. The code that writes the files to the database can be a problem. One company for whom I consulted not so many moons ago at some point connected a Microsoft Access frontend to their database server and used Access' ability to upload anything using its Ole Object control. Later they changed to use a different control which still relied on Ole. Much later someone changed the interface to store the raw binary. Extracting those Ole Object's was a new level of hell. When you store files on the file system, there isn't an additional layer involved to wrap/tweak/alter the source file. It is more complicated to serve up the files to a website. In order to do it with binary columns, you have to write a handler to stream the file binary from the database. You can also do this even if you store file paths but you don't have to do this. Again, adding a handler is not impossible but adds complexity and is another point of failure.You cannot take advantage of cloud storage. Suppose one day you want to store your files in an Amazon S3 bucket. If what you store in the database are file paths, you are afforded the ability to change those to paths at S3. As far as I'm aware, that's not possible in any scenario with any DBMS.IMO, deeming the storage of files in the database or not as bad requires more information about the circumstances and requirements. Are the size and/or number of files always going to be small? Are there no plans to use cloud storage? Will the files be served up on a website or a binary executable like a Windows application? In general, my experience has found that storing paths is less expensive to the business even accounting for the lack of ACID and the possibility of orphans. However, that does not mean that the internet is not legion with stories of lack of ACID control going wrong with file storage but it does mean that in general that solution is easier to build, understand and maintain. |
_unix.12500 | Where could I set the username/password if the HTTP/HTTPS proxy requires it?Is Firefox securely storing the username/password? | How to set username/password in Firefox when using proxy with auth? | linux;firefox | null |
_softwareengineering.301136 | As far as I understand, a planning poker session usually is started by picking one item and assigning it a value (say, 1). This item will then serve as a reference for the rest of the session. From then on, all values will be relative to the first one.Question 1: There seems to be no frame of reference to compare this session to past planning poker sessions, though. If the first item picked and assigned a '1' at session A is actually a bit harder to complete than the first item picked and assigned a '1' at session B, then points at session A and B will be of different value. This means that the total amount of points completed in sprint A and sprint B will not be comparable, defeating the whole purpose of estimation. Where is my mistake?Question 2: Say the team uses the typical numbers (...13, 20, 40, 100). They decide that item1 = 20 and item2 = 40. Does this only mean item1 < item2 or does it also mean that item2 will take twice as long to complete? | In Scrum, are story points assigned at different planning poker sessions worth the same? | agile;project management;scrum;estimation | Question 1: There seems to be no frame of reference to compare this session to past planning poker sessions, though.There should be. Have your scrum master bring in one medium sized story from the previous sprint. You then have a reference point from which to start. When you point a new story, start by asking if the story is bigger than, smaller than, or about the same size as the story from the previous sprint. Use that information to size appropriately.Question 2: Say the team uses the typical numbers (...13, 20, 40, 100). They decide that item1 = 20 and item2 = 40. Does this only mean item1 < item2 or does it also mean that item2 will take twice as long to complete?It only means that item 1 < item 2. From a practical point of view you can maybe think 2 is roughly twice as big, but that's only a very, very rough estimate. It could be that an 8 point story is 10 or 15 times as big as a 1. As the numbers get bigger, the greater the chance that the estimation is wrong. This is arguably why waterfall fails us -- we try to estimate projects that are several months long. Humans suck at that, but we're pretty good at judging just a single day's worth of work. For example, given a 1 point story, you are probably quite accurate on that assessment. It's hard to be off too far when you think the work will take about a day or less. However, if you have another story that you've pointed at 8 or 13 or 40 or 100 -- whatever scale you use -- you will be much more likely to be wrong. That is why stories should be kept as small as possible. |
_softwareengineering.197444 | This question is purely hypothetical. I use WordPress a lot and know the filter structure from an implementation point of view. I'm now wondering what's the best way to implement such a structure (not the way WordPress uses, but the best way). I will give a short overview of what the WordPress filter structure is. After that, I'll list my requirements and thoughts. At last, I'll ask some questions.WordPress' filter structureWordPress sends nearly every data through a filter function before it outputs the data to the browser. The WordPress Codex gives information in the Plugin API and the Filter Reference. For a plugin developer, it's quite easy to add a filter:Create the PHP function that filters the data.Hook to the filter in WordPress, by calling add_filter()Put your PHP function in a plugin file, and activate it. Let's look at these steps in some more detail:A filter function is a PHP function that takes one parameter, the input, and returns the output. It should not echo or print anything. The add_filter function (reference) looks like: add_filter ( 'hook_name', 'your_filter', [priority], [accepted_args] );hook_name is the action hook at which the filter should be called.your_filter is the name of your filter function.priority gives the, well, the priority of the filter (default: 10), where lower numbers are more important.accepted_arguments tells WordPress the filter function will take more parameters, but let's leave that out here, it's not one of my requirements.I don't have to explain this step, I think.RequirementsI'd like to know how to implement a filter structure like WordPress has and for the sake of an actual answerable question, I have made up a hypothetical case with some requirements.My case is a forum, in which I have several cases in which I'd want to use filters for the content, like:A linkify filter to make bare URLs into nice, working hyperlinksA smiley filter to replace ASCII smileys like ':D' into an image (sorry for the imgur abuse)I think the advantages of using filters for this would be:Code clarityFilters can be easily reusedMaking it easy to implement that a user can switch a filter on and offEasy implementation of additional filters in the futureMy thoughtsI imagine WordPress keeps a multidimensional array like $filters[$hook][$filter]. Here is $hook the name of the hook when the filter has to be called and $filter an array of the filter settings, basically those that were passed to the add_filter() function. When an action hook point is reached, WordPress can iterate through the $filters[$current_hook] array and execute every filter.QuestionsIs this the best way to include a filter system with the requirements I listed? If so, why? If not, why not; and what would be a better system and why?As I said I want users to be able to switch filters on and off. I thought of adding a enabled_filters column to the user table in the database, which would be a bitmask of the enabled filters. That would mean every filter would have a unique identifier, but more important that there aren't very much filters possible. So this wouldn't be the way to go.I also thought of adding a table enabled_filters with columns userId, filterName and enabled, to set the filters on and off with a new row. With using the filter name in every row, this would cost some data space on much users and filters, so a better but similar idea would be adding a table filters with id and filterName, and changing the filterName column of the enabled_filters table into a filterId column. This would also allow an additional field in the filters table, allow_disable, to disable the disabling of the filter.Is this second approach a good one, or are there better options? Key requirement is that I don't want to have to modify the base system when adding a filter.WordPress wants programmers to not print anything in a filter function, but return a new string. That means you'll have a variable $return in your filter function, to which you append new data all the time with $return .= '...';. Using echo or print() could be easier for programmers, also to make it easier to port existing code (which uses print functions) to a filter function. The filter system could use the ob_* functions to capture the printed data instead of sending it to the browser. Would this be a good way to implement filters? Are there any disadvantages, like speed? The last question is about when to use filters, and when not. It seems clear to me that the listed cases (linkify and smileys) are cases where filters are well-used. For things like signatures or avatars, to stick with the forum, it's different. I've tried to figure out why it feels different, and think it's because that would limit the use of a filter to one place. For example, avatars and profile overview filters could only be used next to a post. One of the nice things of a filter is that you can add the same filter function to a different action hook, so that you can pass both the post and the signature content through the linkify filter. Am I right here? Is it true that one shouldn't use filters for avatars, profile overviews and signatures? What can be said about general rules when and when not to use a filter? If I were to write documentation on my system for third-party developers, what should I write down on this topic? | Building a WordPress-like filter system | php;architecture;wordpress;filtering | ImplementationIs this the best way to include a filter system with the requirements I listed? If so, why? If not, why not; and what would be a better system and why?WordPress is a grown system with the goal to be backward compatible all the time. Thus, it still uses techniques to mimic things, that can be done more straight with modern PHP. The hook system mimics the Observer pattern. WordPress' hooks are events in this context.StorageI want users to be able to switch filters on and off. Your second approach is reasonable with slightly different semantics. You need a table for the filters and a map for the user's setting. You can even add per-filter configurations (serialized).+-----------+| Filters |+-----------+| +id | // unique filter id| +name | // unique name (ie., [part of] filename)| +title | // human readable name| +enabled | // whether or not the filter is available to users| +settings | // default settings managed by admin+-----------++---------------+| FilterUserMap |+---------------+| +user_id | // the user| +filter_id | // the filter| +enabled | // whether or not the user has enabled the filter| +settings | // the user's preferrences+---------------+OutputThe filter system could use the ob_* functions to capture the printed data instead of sending it to the browser. Would this be a good way to implement filters? Are there any disadvantages, like speed? Performance should never be your first concern. Most important is the readability and maintainability of the code. Using the output buffering is a good approach, if you add larger chunks of HTML, because that increases readability very much. Usually a filter will change the content instead of add something, so you mostly end up using preg_* functions.Nevertheless, I guess, output buffering will be faster than string concatenation, since it is done on a level closer to the machine, but I don't have any figures.UsageIs it true that one shouldn't use filters for avatars, profile overviews and signatures? What can be said about general rules when and when not to use a filter? If I were to write documentation on my system for third-party developers, what should I write down on this topic?No, I don't think so. It is normal that a filter does not fit into all situations. Think of html_specialchars, strip_tags, or mysqli_real_escape_string as some of PHP's native filter functions - they have special use cases and are not suitable everywhere.You could define a FilterInterface extending PHP's SplObserver interface, and use it to implement special filter classes, so can control, where what kind of filter is usable. |
_webapps.90071 | I'm working with some faculty members studying public health and social media. I'd like to be able to insert a number of YouTube URLs to videos I do not own and pull the public stats (views, likes/dislikes, video length, owner, comment count). It seems that the API options require that you own the videos to get any of this data.I've got a way to do most of what I need through xpath but want to make sure I'm not missing something obvious in the API. | API option for analytics data on YouTube videos I do not own | youtube | null |
_computerscience.4541 | Simply put, what does the transparency data of an EXR file represent? | Explanation of a the transparency of an .EXR file | image processing;image | null |
_unix.104420 | I have a shell script and when invoking it ./test it asks for an input.I 've seen a quicker way just by writing at once ./test myInput ,how is that achievable? | How to use command line arguments in a shell script | shell script;arguments | You can access the command line arguments in your shell script with the special variables $1, $2 until $9. $0 is the name of your script.If you need access more than 9 command line arguments, you can use the shift command. Example: shift 2 renames $3 to $1, $4 to $2 etc.Please remember to put the arguments inside doubles quotes (e.g. $1), otherwise you can get problems if they contain whitespaces. |
_unix.154547 | In Windows you can type Super+e to launch the file explorer. I find this really useful, particularly because almost every action I take starts with search for a file or folder.Is there an equivalent keyboard shortcut to launch Nemo in Linux Mint? (In an ideal world, there'd also be a way to run a file/folder search from the keyboard) | Keyboard shortcut to launch Nemo | linux mint;keyboard shortcuts;nemo | I do not know the exact answer to your question. But this may help.I am using Fedora and not Mint however I still believe this should work.There are different shortcut keys assigned for a particular type of command execution.You can find them in your System -> Preferences -> [System] ->Keyboard Shortcuts.You will also see various different kind of keys (symbols) used in there likeXF86Mute for Audio Mute, XF86Calculator for Calculator. These i think are related to the special keys which comes in your PC/laptop. If you are not able to determine the one for opening the HOME folder or the SEARCH button just change it in there like i changed SEARCH for Windows Key + S and for HOME DIR i made it Windows Key + H. |
_unix.260756 | Very short summary:cat $file | patch produces a Bad file descriptor-error, butpatch < $file works, when libtrash is preloaded with LD_PRELOAD, and only on bigger projects.Description:For this example, I work on the vanilla linux-3.18.21 kernel sources as downloaded from [1] (and extracted the archive, of course).I want to patch it with TuxOnIce as downloaded von [2], and extracted.In this example I show some big project, since with just small files everything works okay.I work within the top level linux source directory, and from there the patch is located at ../patches/tuxonice-for-linux-3.18.21-2015-09-08.patch. No symlinks involved, everything on the same filesystem.The following happens:$ cat ../patches/tuxonice-for-linux-3.18.21-2015-09-08.patch | patch -p1 --dry-runpatch: **** can't open file Documentation/kernel-parameters.txt : Bad file descriptor(exitcode: 2)but:$ patch -p1 --dry-run < ../patches/tuxonice-for-linux-3.18.21-2015-09-08.patch checking file Documentation/kernel-parameters.txtchecking file Documentation/power/tuxonice-internals.txt[...](runs successfully).The problem has something to do with libtrash.so loaded via the LD_PRELOAD environment variable:By default, I have export LD_PRELOAD=/usr/lib/libtrash.so. [3]If I export LD_PRELOAD='' or unset LD_PRELOAD, it works fine.If I just switch off the functioning of libtrash (but keep it preloaded), by export TRASH_OFF=YES, which is the way provided by libtrash, the problems persist.It definitely has to do with libtrash and not with LD_PRELOAD itself, since when I export LD_PRELOAD='/usr/lib/libgtk3-nocsd.so.0' (the file exists) the patching with cat $file | patch works.In fact, I expect cat $file | $programme to result in the same as $programme < $file, but it doesn't.It's a practical nuisance, since in practice instead of using cat, I would use things like xzcat or bzcat on the compressed patch files so that I don't need to decompress them in an extra step first.I use bash, but that doesn't matter (within zsh the same). patch is GNU patch version 2.7.5, glib-config --version shows 1.2.10, I use an arch linux distribution and this problem did persist already for at least several months, including updates. Kernel 3.18.21.Here are two outputs with strace, once strace-ing cat, once strace-ing patch, with export LD_PRELOAD=/usr/lib/libtrash.so and export TRASH_OFF=YES:Command:$ strace cat ../patches/tuxonice-for-linux-3.18.21-2015-09-08.patch | patch -p1 --dry-runOutput:http://pastebin.com/TD81znz6Command:$ cat ../patches/tuxonice-for-linux-3.18.21-2015-09-08.patch | strace patch -p1 --dry-runOutput:http://pastebin.com/snvN3YCu(Sorry for linking it, if I would put it directly stackexchange won't accept my post without telling me why).I am not familiar with dynamic linking, strace and so on.Does anyone know what goes on? If that is a bug somewhere, where would it be? (patch, libc, libtrash, dynamic linker, ..., ..., ?)xzcat /usr/src/linux-3.18.21.tar.xz | tar -xv works (but xzcat some.patch.xz | patch does not), so it has at least some specificity with patch.[1] linux kernel: https://cdn.kernel.org/pub/linux/kernel/v3.x/linux-3.18.21.tar.xz[2] TuxOnIce: http://tuxonice.nigelcunningham.com.au/downloads/all/tuxonice-for-linux-3.18.21-2015-09-08.patch.bz2[3] libtrash: http://pages.stern.nyu.edu/~marriaga/software/libtrash/ | patch: bad file descriptor in combination with pipe and LD_PRELOAD/ libtrash | pipe;io redirection;dynamic linking;stdin;patch | libtrash is broken:For example, in helpers.c:char* make_absolute_path_from_dirfd_relpath(int dirfd, const char *arg_pathname){ char *abs_path = NULL; if (arg_pathname == NULL) { return NULL; } else if (arg_pathname[0] == '/' || dirfd == AT_FDCWD) { return arg_pathname; } else if (dirfd <= 0) { errno = EBADF; return NULL; }A value of 0 for a file descriptor is perfectly legitimate. Since you're using redirection, you're reading from stdin, which is file descriptor 0. I suspect that's what's breaking somewhere in libtrash. |
_softwareengineering.318335 | Having quite big codebase and external libraries, in C application,what would be pros and cons of two approaches (or suggest other):(assume that there are NONE api provided calls for this)Edit from comment: Goal is to select nicer approach in long term - for manipulation of some elements from engine etc, where some elements might belong to GUI, or other module (both conceptually, from other translation module, separated to put it in one word).pass pointer to struct containing various pointers for some gui labels, buttons, etc, to engine, and later = to every engine function that needs to manipulate those items. keep global static handles to some gui labels, buttons, etc in gui_help.c, initialized by gui - and provide access to them with some getter(name_what) exposed from gui_help.hMinimal example (removed header guardians, mem management, error checks etc):Scroll below this for quick Python snipplet to setup exact of below locally.// ## main.c ###include gui.hint main(int argc, char *argv[]){ gui(); return 0;}// ## gui.h ##void gui();typedef struct { int many_variables_and_pointers; } gui_struct; // ## gui.c ###include gui.h#include gui_help.h#include engine.hvoid gui(){ gui_struct gs; gs.many_variables_and_pointers = init_a_from_gui_help(); //gs.other_variables_and_pointers = init_b_from_gui_help(); //...foo, bar // engine callbacks are registered here. // GUI LOOPS here in engine event loop, other threads handle user interaction. engine_loop();}// ## gui_help.h ##init_a_from_gui_help();//init_b_from_gui_help();// ## gui_help.c ##int init_a_from_gui_help(){ return 42;}// ## engine.h ##void engine_loop();void some_engine_callback_example_1(void* data);void some_engine_callback_example_2();// ## engine.c ##void engine_loop(){ volatile int a; while(1){ a = 1; } printf(%d, a);}void some_engine_callback_example_1(void* data){ // data->some_gui_element->manipulate(); // would require initializing struct data with gui elements, // and passing pointer to this struct from engine to any other call, // possibly nesting several stack levels, limiting somewhat encapsulation // Possible synchronization issues as well?}void some_engine_callback_example_2(){ // my_local_gui_element_pointer_copy = getter(label1); // my_local_gui_element_pointer_copy.manipulate(); // would require #include gui_help.h, exposing api, // and keeping static global handles to labels, buttons, etc.}Python snipplet to setup this locally, compacted to prevent scrolling this page even more.# Python - THIS CODE GENERATES ABOVE STRUCTURE, for easier browsing. Run in new dir.a = [main.c, gui.h, gui.c, gui_help.h, gui_help.c, engine.h, engine.c]main_c = #include gui.h\nint main(int argc, char *argv[]){\ngui();\nreturn 0;\n}gui_h = void gui();\ntypedef struct {int many_variables_and_pointers;} gui_struct;gui_c = #include gui.h\n#include gui_help.h\n#include engine.h\nvoid gui(){\n gui_struct gs;\ngs.many_variables_and_pointers = init_a_from_gui_help();\n \n//gs.other_variables_and_pointers = init_b_from_gui_help();\n//...foo, bar\n// engine callbacks are registered here.\n// GUI LOOPS here in engine event loop, other threads handle user interaction.\nengine_loop();\n}gui_help_h = init_a_from_gui_help();\n//init_b_from_gui_help();gui_help_c = int init_a_from_gui_help(){\n return 42;\n}engine_h = void engine_loop();\nvoid some_engine_callback_example_2();\nvoid some_engine_callback_example_1(void* data);engine_c = void engine_loop(){\n\tvolatile int a;\n\twhile(1){\n\t\ta = 1;\n\t}\n\tprintf(%d, a);\n}\nvoid some_engine_callback_example_1(void* data){\n\t// data->some_gui_element->manipulate();\n\t// would require initializing struct data with gui elements,\n\t// and passing pointer to this struct from engine to any other call,\n\t// possibly nesting several stack levels, limiting somewhat encapsulation\n\t// Possible synchronization issues as well?\n\t}\nvoid some_engine_callback_example_2(){\n\t// my_local_gui_element_pointer_copy = getter(label1);\n\t// my_local_gui_element_pointer_copy.manipulate();\n\t// would require #include gui_help.h, exposing api, \n\t// and keeping static global handles to labels, buttons, etc.\n\t}b = [main_c, gui_h, gui_c, gui_help_h, gui_help_c, engine_h, engine_c]for i, filename in enumerate(a): with open(filename, 'w') as file_: file_.write(b[i]) | GUI - engine data exchange, design with C, getters or struct pointers passing? | design;c;object oriented design;gui | null |
_ai.1632 | I'm aware this could be a complex topic, however I'm interested in existing research projects or studies where people are attempting or have succeeded in teaching an AI a foreign language just by training/teaching it from English books. By reading, analysing and understanding, so that it knows the foreign language's rules (such as grammar, spelling, etc.), the same way as a human would learn. The language doesn't have to be Chinese, which is difficult for even humans to learn. | What are the current approaches for AI to learn a foreign language just from English books? | research;machine learning;self learning;language processing | Current approaches for learning a language require having a large corpus of that language; it also doesn't seem reasonable to expect that it will ever be possible to learn about language A by extracting information from a corpus from an unrelated language B.Even if you want to learn about human languages in general (what sorts of things are true about grammar, vocabulary, and so on), that relies having many languages as training data, so that you can see the different ways of doing things instead of assuming that the way they're done in English is the way they're done in every language.(There is work in automatic translation that goes from a language to 'concept-space', then goes from that 'concept-space' to another language, so that you can build an English-Chinese translator by building two separate English-Concept and Chinese-Concept translators, instead of ever needing material that directly links English and Chinese. The obvious benefit of this is scalability; in order to make translators for a new language to any other language, you just need to learn that language and the models build themselves.) |
_codereview.141676 | Just a little exercise to make me more affluent with strings and error handling, any improvements welcome!#include <stdio.h>#include <string.h>#include <ctype.h>#include <stdbool.h>#include <math.h>#define MAXSIZE 1024void retreiveStringInput(char *str, size_t buffersize) { for (;;) { if (fgets(str, buffersize, stdin) != NULL) { str[strcspn(str, \n)] = 0; return; } else printf(Touble allocating memory, Please try again...\n); }}bool strHasAllDigits(char *str){ size_t strsize = strlen(str); if (str[0] != 0) { for (size_t strIndex = 0; strIndex < strsize; ++strIndex) { if (isdigit(str[strIndex])) continue; else return false; } return true; } else { printf(String is empty...\n); return false; }}int strToInt(char str[]){ size_t len = strlen(str); size_t power = len - 1; int convertedString = 0; for (size_t strIndex = 0; strIndex < len; ++strIndex, --power) { convertedString += ((int)(str[strIndex] - '0') * pow(10,power)); } return convertedString;}int main(){ char number[MAXSIZE]; int intNumber = 0; for (;;) { printf(ENTER A WHOLE NUMBER: ); retreiveStringInput(number, MAXSIZE); if (strHasAllDigits(number)) intNumber = strToInt(number); else { printf(Number must be a whole number containing no characters, please try again...\n\n); continue; } printf(Your number is: %d\n, intNumber); break; } printf(Press any key to continue...); getchar();} | Converts a user inputed string into a Integer | beginner;c;strings | Nitpicksvoid retreiveStringInput(char *str, size_t buffersize) Misspelled. void retrieveStringInput(char *str, size_t buffersize) Not a critical mistake, since you used it consistently. Don't forget to change other uses when you fix it. printf(Touble allocating memory, Please try again...\n);This suggests that there is trouble allocating memory, but this code doesn't allocate memory. It reads from input. It also has a typo in Trouble. Keeping it simple size_t strsize = strlen(str); if (str[0] != 0) { for (size_t strIndex = 0; strIndex < strsize; ++strIndex) { if (isdigit(str[strIndex])) continue; else return false; } return true; } else { printf(String is empty...\n); return false; }Consider if (*str == '\0') { printf(String is empty...\n); return false; } for (; *str != '\0'; ++str) { if (!isdigit(*str)) { return false; } } return true;I find it easier to use positive if conditions with else statements. So the if is the positive case and the else is the negative case. In this situation, we don't need an else then, as we return in the if. There is no point in a continue when there is no statement to skip. Just let it go. It will continue automatically. You don't need an else case. You only used the length as part of the condition check in the loop. But we don't need it. We can just check for the end of the string directly. We know that the end of string marker is '\0', so we can just check for that. It's true that '\0' is 0, but it is more readable to write it out in my opinion. I changed str[0] to *str because I knew that I was going to be saying *str in the for loop anyway. Rather than use two different things that return the same value, I picked the one that worked in both cases. It would look kind of odd to repeatedly do str[0] and act as if the values would be different. That's more understandable with *str. I don't like the single statement form of control structures. I always use the block form as being more robust against editing mistakes and a little easier to read. Avoid unnecessary floating point operations size_t power = len - 1; int convertedString = 0; for (size_t strIndex = 0; strIndex < len; ++strIndex, --power) { convertedString += ((int)(str[strIndex] - '0') * pow(10,power)); }Consider int convertedString = 0; for (size_t strIndex = 0; strIndex < len; ++strIndex) { convertedString *= 10; convertedString += (int)(str[strIndex] - '0'); }We don't need power anymore. We don't convert to and from a floating point type. No danger of precision losses. Everything is an integer type. We probably don't even need the explicit cast to int. I haven't run the code, so I left it. Simplify if (strHasAllDigits(number)) intNumber = strToInt(number); else { printf(Number must be a whole number containing no characters, please try again...\n\n); continue; } printf(Your number is: %d\n, intNumber); break;Consider if (strHasAllDigits(number)) { int intNumber = strToInt(number); printf(Your number is: %d\n, intNumber); break; } printf(Number must be a whole number containing no characters, please try again...\n\n);Now we don't have to declare intNumber outside the loop. And we don't have to continue to skip the break. |
_unix.248351 | I have this USB drive that doesn't seem to be detected neither on lsblk or fdisk.Here are some outputs:Dmesg:[93812.546850] usb 2-1.2: new high-speed USB device number 33 using ehci-pci[93812.631628] usb-storage 2-1.2:1.0: USB Mass Storage device detected[93812.632314] scsi host18: usb-storage 2-1.2:1.0udevadm:UDEV [93905.859931] add /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.0/host20/target20:0:0/20:0:0:0/block/sdb (block)UDEV [93905.878766] change /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.0/host20/target20:0:0/20:0:0:0/block/sdb (block)fdisk:$ sudo fdisk -l /dev/sdbfdisk: cannot open /dev/sdb: No medium foundmount:sudo mount /dev/sdb1 /mnt/usbmount: special device /dev/sdb1 does not existjournalctl:mtp-probe[28286]: bus: 2, device: 39 was not an MTP deviceAny ideas on what the issue might be and how should I fix it? | Usb drive not detected /arch | arch linux;usb drive | null |
_unix.199249 | I was wondering if its possible to execute commands from history that match a certain regex? I know you can do something likefc 232 248And it will go into your history and then do revisions 232-248 consecutively.However, if some of the commands in between are things I do not want to do, is there a way I can specify that? Right now I look up my history and pipe it out to a grephistory | grep checkoutSo this will look up all terminal actions I've done with checkout I have done. 232 git checkout master files/file1.txt234 git checkout master files/file2.txt248 git checkout master files/file3.txtIt filters out some of the numbers so I only want to execute the ones that have been piped out. rather than everything in between | Execute commands from history that match regex or grep | bash;grep;command history | null |
_webmaster.9262 | I have built a form input page in HTML thathas an action to post to an ASP handler/processor.asp file. The form handler/processor .asp filecontains only <% Insert VBScript Here %> and noHTML output whatsoever.The .asp file was never intended to be aweb viewable .asp file like an .asp home pagefile or html file would. It's supposed to befor my eyes only- not the public's howeverit does need to take info posted by the publicand do something with it on it's end.I have used VBScript/ASP3.0 to build the formhandler/processor file and would like to know howto keep someone from viewing the actual VBScriptin the handler/processor .asp file. I am aware ofobfuscation but I would like to know how to keepprying eyes from even being able to take a lookat the obfuscated code in the handler/processorfile.I realize that the server executes the .asp filefirst before outputting anything to the browser soI guess that my main concern is mostly that someonemay could download the form handler/processor .asp file,then view it's contents on their machine.Assuming the form handler .asp file is where it is,behind the root, and is on a windows server(no htaccess approach) how could one protect it so thatit could never be viewed or simply pulled down viaanonymous ftp or something like that?Is there something like script only permissions thatthe system administrator could set up for a particularfolder? Remember, with shared hosting I can't go abovethe root. If so, would the form still be able to post?How would any of you guys go about protecting theasp file in addition to obfuscation? Any help wouldbe greatly appreciated. | ASP 3.0 Folder/File Permissions Settings (ASP Classic) | asp.net | null |
_webapps.79501 | How do I print an entry with the company logo? When I print or view the entries the logo does not appear at the top of the page like it used to.June 9th I printed an entry and the logo and form name appeared on the printed copy, as of June 22 it no longer shows the logo or form name when viewing or printing entries. | Logo not appearing Cognito entries or printed form | cognito forms | null |
_unix.124938 | On my Dell latitude e6540, the WMI hotkeys Fn+Up and Fn+Down are not working. I have all necesary modules compiled in my kernel:CONFIG_DELL_LAPTOP=mCONFIG_DELL_WMI=mCONFIG_DELL_WMI_AIO=mOn the predecessor model (Latitude e6520), all worked fine, without any need for additional setup. I am using the same (custom build) kernel 3.16.6 on both laptops. On e6520 wmi works, on e6540 it doesn't.I can still change the brightness with echo:echo 35 > /sys/class/backlight/acpi_video0/brightnessbut only as root, obviously.Pressing Fn+Up and Fn+Down does not change the walue in /sys/class/backlight/acpi_video0/brightness. On the previous model, it does change the value.One thing I noticed, on the older model, the max value is 15. On the new model it is 95. Looks like something might have changed inside this mechanism.Thus my question: How can I make WMI hotkeys work on my new laptop?I am using Debian wheezy with custom kernel 3.16.6. I have also tried distribution kernel 3.16 (linux-image-3.16-0.bpo.2-amd64 from Wheezy-backports) and the wmi keys don't work either.UPDATE:I have just noticed that the WMI hotkeys work fine when I am in BIOS !!!That is quite surprising that they don't work when I boot into linux.following is output of dmesg. The mention of dell_wmi: Received unknown WMI event looks relevant to my problem, but I get the same messages on the old laptop, where wmi hotkeys are working. So this alone does not seeem the be the issue.dmesg | egrep -i '(dell|wmi)'[Tue Apr 15 22:04:30 2014] DMI: Dell Inc. Latitude E6540/05V0V4, BIOS A05 09/03/2013[Tue Apr 15 22:04:30 2014] ACPI: RSDP 00000000000eee60 00024 (v02 DELL )[Tue Apr 15 22:04:30 2014] ACPI: XSDT 00000000d8fe0080 0007C (v01 DELL CBX3 01072009 AMI 00010013)[Tue Apr 15 22:04:30 2014] ACPI: FACP 00000000d8fed7e8 0010C (v05 DELL CBX3 01072009 AMI 00010013)[Tue Apr 15 22:04:30 2014] ACPI: DSDT 00000000d8fe0188 0D659 (v02 DELL CBX3 00000014 INTL 20091112)[Tue Apr 15 22:04:30 2014] ACPI: APIC 00000000d8fed8f8 00072 (v03 DELL CBX3 01072009 AMI 00010013)[Tue Apr 15 22:04:30 2014] ACPI: FPDT 00000000d8fed970 00044 (v01 DELL CBX3 01072009 AMI 00010013)[Tue Apr 15 22:04:30 2014] ACPI: HPET 00000000d8feed38 00038 (v01 DELL CBX3 01072009 AMI. 00000005)[Tue Apr 15 22:04:30 2014] ACPI: MCFG 00000000d8fef148 0003C (v01 DELL CBX3 01072009 MSFT 00000097)[Tue Apr 15 22:04:38 2014] dcdbas dcdbas: Dell Systems Management Base Driver (version 5.6.0-3.2)[Tue Apr 15 22:04:39 2014] wmi: Mapper loaded[Tue Apr 15 22:04:39 2014] input: Dell WMI hotkeys as /devices/virtual/input/input10[Wed Apr 16 18:30:04 2014] dell_wmi: Received unknown WMI event (0x0)[Fri Apr 18 17:09:41 2014] dell_wmi: Received unknown WMI event (0x0)[Fri Apr 18 17:09:41 2014] dell_wmi: Received unknown WMI event (0x0)[Fri Apr 18 17:09:49 2014] dell_wmi: Received unknown WMI event (0x0)UPDATE2after patching the WMI module, I get following messages for Fn+Up and Fn+Down2014-04-18 19:00:49 kernel: [ 120.731480] dell_wmi: WMBU = 0002 0010 00482014-04-18 19:00:49 kernel: [ 120.731496] wmi: DEBUG Event GUID: 9DBB5994-A997-11DA-B012-B622A1EF54922014-04-18 19:00:53 kernel: [ 123.935400] dell_wmi: WMBU = 0002 0010 00502014-04-18 19:00:53 kernel: [ 123.935415] wmi: DEBUG Event GUID: 9DBB5994-A997-11DA-B012-B622A1EF5492UPDATE3Also interesting is, that the laptop came with pre-installed Ubuntu 12.04, and the wmi keys are working in Ubuntu. | WMI-based hotkeys on not working | laptop;key mapping;display | You could install xbacklight, a utility for managing your brightness using RandR. Then, to activate it, use a simple script along these lines—bound to your two keys:#!/usr/bin/env bashup() { xbacklight -inc 10}down() { xbacklight -dec 10}notify() { bright=$(</sys/class/backlight/acpi_video0/actual_brightness) if [[ $bright -eq 95 ]]; then score=100% else score=$(( $bright * 100 / 95 )) fi printf '%s\n' Backlight set to ${score}% | dzen2 -p 3}if [[ $1 = up ]]; then up && notifyelif [[ $1 = down ]]; then down && notifyfiSwap out your notification method for whatever you use as part of your normal setup, eg., notify-send. |
_unix.272318 | After I select an OS to boot to in rEFInd, it prints boot target and its options before booting.Is there a way to disable this behavior? | How do I hide the rEFInd boot text? | boot;boot loader;refind | null |
_webapps.51263 | I run two Chrome profiles on my laptop:Personal - Used for all my Stack Overflow accountsWork - Used for work Google accountBoth are signed into their respective Google accounts.How do I log into Stack Overflow using my personal account on my works Chrome user? | How do I log into Stack Overflow using a different google account than signed in with in Chrome | google chrome;stackoverflow | One option is adding your work login to your Stack Overflow account.Here's how:Login to Stack Overflow from your Personal Chrome User profile.Logout of your personal Gmail.Add more logins from your Stack Overflow profile pageNext, Login with Google and sign in with your work Gmail.This should work because you logged out of your personal Gmail in step 2Go to Gmail and Logout of your work profile and re-login with your personal profile.This to bring everything back to normal on your Personal Chrome User profile.From your Work Chrome User profile, visit Stack Overflow and login with your work Gmail. |
_codereview.69268 | The code snippet below, receives data from a form, formats and inserts into the database.This code snippet is located in a controller and the insertion is done in a 'repository' to manipulate data that entity laravel in my project.Wonder if there are improvements to be made in this code for a great process of receiving, formatting, and data persistence.- The method HelperRS :: date, gets a date in Brazil and format for timestamp formats.- The method HelperRS :: real, gets a value in Brazil and format to format float. // Formats data for inserting budget (orcamento)$data['idCliente'] = $cliente->id_cliente;$data['dataIni'] = ($data['dataIni']) ? HelperRS::data($data['dataIni'], 'ts') : NULL;$data['dataFim'] = ($data['dataFim']) ? HelperRS::data($data['dataFim'], 'ts') : NULL;$data['elaboradoPor'] = strtoupper(Auth::user()->nome);$data['loginUsuario'] = Auth::user()->usuario;$data['dataUltMudanca'] = ($data['dataUltMudanca']) ? HelperRS::data($data['dataUltMudanca'], 'ts') : NULL;$data['descontoRecibo'] = ($data['descontoRecibo']) ? HelperRS::real($data['descontoRecibo'], 'fl') : NULL;$data['total'] = ($data['total']) ? HelperRS::real($data['total'], 'fl') : NULL;$data['totalSemDesconto'] = ($data['totalSemDesconto']) ? HelperRS::real($data['totalSemDesconto'], 'fl') : NULL;$data['lembrar'] = ($data['lembrar']) ? HelperRS::data($data['lembrar'], 'ts') : NULL;;$id_orcamento = $this->orcamentos->insert($data); | Script that receives and formats data | php;repository;laravel | null |
_webapps.105346 | When doing a form or case export from CommCareHQ, what would be the most straight forward way to have the data export display with the Question IDs in the order in which they display in the form builder (as opposed to alphabetical order)?Would Excel Dashboards be the best solution? | CommCareHQ Exports to display in the Order they Appear in Form Builder | commcare | null |
_softwareengineering.229897 | I see a lot of talk in the OOP world about principles and laws such as Open/Close and Loose Coupling, I can understand how they are so high valued, However I seem to have ran into a problem with applying these principles and laws once I start to include relational databases.For example purposes, if I have a application which we are able to separate well into multiple components(Open/Close design) and allow them to work with each other when if needed, I start to run into problems when trying to enforce referential integrity.If I enforce a relational setup, and enforce integrity through foreign keys and so on, the tables become dependent on each other, gradually my OOP application logic starts to fall apart and become one big system.I can of course remove all references to tables, but then I risk making data redundant and start to repeat code/data, which then goes against the Don't Repeat Yourself principle.Have you came across such problems before? If so how did you handle it? Perhaps there is a way to achieve both referential integrity and OOP open/close components.Thanks | OOP and relational databases | object oriented;database;mysql | null |
_unix.274378 | #!/bin/bashARRAY=185.18.207.66 31.18.212.113result=for i in $ARRAYdo result=$(printf '%s %s' $result $i checked)donepaste <(printf %s\n $result)I am trying to print IP addresses but with appending checked phrase for each IP address.But I can not print a space between IP and checked phraseAbove code prints:185.18.207.66checked31.18.212.113checkedHow can I make it to print like below?185.18.207.66 checked31.18.212.113 checked | Printing Space Between Strings | bash;shell;printf | There are many things to improve with your script before making it done right:Missing double quoteSpawning unnecessary external commands.Just using an array instead:#!/bin/bashARRAY=(185.18.207.66 31.18.212.113)printf '%s checked\n' ${ARRAY[@]}or using $@ to make it POSIXly:#!/bin/shset -- 185.18.207.66 31.18.212.113printf '%s checked\n' $@ |
_unix.165676 | On my Ubuntu 14.04 virtual machine compiz freezes often. I usually swtich to tty1 and kill the process, then switch back to tty7 and, if I can see a terminal window, I run compiz --replace & in it.But there are times when I don't see any terminal window, and right clicking on the desktop doesn't give any menu so I can open one and I have to restart lightdm service. This is work blocking.My question is: how can I run compiz --replace & or any other command from a different tty on tty7?I read this thread, but I don't know how to make tmux connect to a different tty on my machine, and the second one involves using the homebrew program.I also read this, but it involves having a daemon run on tt7 expecting for my commands.Isn't there any easier way to do this? | Run an X11 command from a different console | x11;console | What matters is actually not what console you run the command from, but that you tell the program to connect to the still-existing X display. To do this, set the DISPLAY variable and restart Compiz from a standard terminal. Depending on your distribution and configuration, you may need to set XAUTHORITY as well. Switch to tty1 and type:$ export DISPLAY=:0$ compiz --replace &The display may be different on your machine. Use who to find yours:$ whoyou tty1 [time] < This is you from tty1.you :0 [time] (:0) < This is you from tty7. ^^ ^^ This is your display on tty7Note: you must be logged in as yourself on tty7 (graphically). Fortunately, when Compiz crashes, you are not disconnected from tty7 (even though you can't do much). |
_unix.156416 | Matlab MEX is compatible just with GCC version 4.7.X, however OpenSUSE 13.1 comes with GCC 4.8.1, when I compile a Matlab MEX file a warning comes out: Warning: You are using gcc version '4.8.1'. The version of gcc is not supported. The version currently supported with MEX is '4.7.x'., and MEX compilation fails.I saw this question in stackoverflow: Installing older version of gcc, but OpenSUSE does not provide a repository with GCC older versions. How can I install easily an older version of GCC just for Matlab? And, how can I setup Matlab to do it correctly?I'm using Matlab 8.3 R2014a. | How to install older version of GCC for Mex compatibility with Matlab on OpenSUSE? | opensuse;gcc | null |
_webapps.28479 | Possible Duplicate:Better way to search the Facebook activity log / timeline? I was just trying to look up something on my own timeline (specifically, the last time I had jury duty). Unfortunately, the native Facebook search feature seemed to be completely useless for this. I couldn't even get it to show me a post from 24 hours ago.The Facebook search feature seems to only works for public content, and doesn't seem to allow restricting results to just my own content. My privacy settings are generally set to friends-only, and I don't allow public searching of my timeline. I do, however, think I should be able to search my own content.Is there a way to search my own content with Facebook either natively with the standard Facebook web app or with a trustworthy/secure app or add-on? | How do I search for old items I posted in my own Facebook timeline? | search;facebook;facebook timeline | null |
_codereview.111019 | I am adding two custom metaboxes to the WordPress post page from a plugin. I am currently doing it with two separate instances of add_meta_boxes but this feels very bulky, especially as I go to add more.Since the plugin is fairly small I dont want to include a framework and was wondering if there was an easier to add more than one metabox. Preferably under one heading, unlike currently if you add this to your functions.php or look at the screenshot below, they are under separate headings.I was considering posting this on http://wordpress.stackexchange.com, but as it is working fully I posted it here.function wp_cat_map_add_meta_box() {$screens = array( 'post' );foreach ( $screens as $screen ) { add_meta_box( 'map_lat', __( 'Add Latitude', 'wp_cat_map' ), 'wp_cat_map_lat_callback', $screen ); add_meta_box( 'map_long', __( 'Add Longitude', 'wp_cat_map' ), 'wp_cat_map_long_callback', $screen );}}add_action( 'add_meta_boxes', 'wp_cat_map_add_meta_box' );function wp_cat_map_lat_callback( $post ) {wp_nonce_field( 'wp_cat_map_lat_data', 'wp_cat_map_lat_nonce' );$value = get_post_meta( $post->ID, '_wp_cat_map_lat', true );echo '<label for=wp_cat_map_lat>';_e( 'Latitude', 'wp_cat_map' );echo '</label> ';echo '<input type=text id=wp_cat_map_lat name=wp_cat_map_lat value=' . esc_attr( $value ) . '/>';}function wp_cat_map_lat_data( $post_id ) {if ( ! isset( $_POST['wp_cat_map_lat_nonce'] ) ) { return;}if ( ! wp_verify_nonce( $_POST['wp_cat_map_lat_nonce'], 'wp_cat_map_lat_data' ) ) { return;}if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return;}if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_id ) ) { return; }} else { if ( ! current_user_can( 'edit_post', $post_id ) ) { return; }}if ( ! isset( $_POST['wp_cat_map_lat'] ) ) { return;}$my_data = sanitize_text_field( $_POST['wp_cat_map_lat'] );update_post_meta( $post_id, '_wp_cat_map_lat', $my_data );}function wp_cat_map_long_callback( $post ) {wp_nonce_field( 'wp_cat_map_long_data', 'wp_cat_map_long_nonce' );$value = get_post_meta( $post->ID, '_wp_cat_map_long', true );echo '<label for=wp_cat_map_long>';_e( 'Longitude', 'wp_cat_map' );echo '</label> ';echo '<input type=text id=wp_cat_map_long name=wp_cat_map_long value=' . esc_attr( $value ) . '/>';}function wp_cat_map_long_data( $post_id ) {if ( ! isset( $_POST['wp_cat_map_long_nonce'] ) ) { return;}if ( ! wp_verify_nonce( $_POST['wp_cat_map_long_nonce'], 'wp_cat_map_long_data' ) ) { return;}if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return;}if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_id ) ) { return; }} else { if ( ! current_user_can( 'edit_post', $post_id ) ) { return; }}if ( ! isset( $_POST['wp_cat_map_long'] ) ) { return;}$my_data = sanitize_text_field( $_POST['wp_cat_map_long'] );update_post_meta( $post_id, '_wp_cat_map_long', $my_data );}add_action( 'save_post', 'wp_cat_map_lat_data' );add_action( 'save_post', 'wp_cat_map_long_data' ); | Adding Wordpress Meta boxes | php;wordpress | null |
_cs.20017 | Hello I am trying to solve the AlienTiles problem described at alientiles.com using the A* algorithm but I cannot find any good heuristic function so far.In AlienTiles you have a board with $N \times N$ tiles, all coloured red. By clicking on a tile, all tiles in the same row and column advance to the next color, with the colour order being red $\rightarrow$ green $\rightarrow$ blue $\rightarrow$ purple, resetting to red after purple. A goal state is a state where every tile has the same colour, as long as its not red.Is there any good point to start? I am completely frustrated about how I am supposed to handle the problem. An easy function that I came up with was the distance of the colour of the current tile with the target tile, but it is very slow. | Solving AlienTiles with an A* heuristic | algorithms;search algorithms;heuristics;board games | One candidate approach: for each color $c \in \{\text{green}, \text{blue}, \text{purple}\}$, try to define a distance heuristic $f_c(\cdot)$ that approximates the distance to the specific goal of getting all tiles to be the color $c$. For instance, if $s$ is a state, then $f_\text{green}(s)$ should be an estimate of the distance to the all-green state.Next, given these heuristics, define a distance heuristic$$f(s) = \min(f_\text{green}(s), f_\text{blue}(s), f_\text{purple}(s)).$$Then you could use $f$ as your distance heuristic with $A^*$.I leave it up to you to see if you can find a suitable definition of $f_c(s)$. One candidate would be the number of tiles in $s$ whose color is not $c$, but that's probably not going to work; you'll probably need something smarter.If you're willing to use something other than the $A^*$ algorithm, there is an elegant solution to this problem using linear algebra.Identify the colors red, green, blue, purple with the integers $0$, $1$, $2$, $3$, taken modulo 4 (so you are working in $\mathbb{Z}/4\mathbb{Z}$). Now you can solve the problem using linear algebra. In particular, the state $s$ is a $N^2$-vector over $\mathbb{Z}/4\mathbb{Z}$. Clicking on a tile at position $i,j$ corresponds to updating the state from $s$ to $s+v_{i,j}$, where $v_{i,j}$ is a fixed $N^2$-vector over $\mathbb{Z}/4\mathbb{Z}$. Thus, you can get from state $s$ to state $s'$ if and only if $s'-s$ is in the linear span of the $v_{i,j}$. If it is in the span, then find coefficients $c_{i,j} \in \mathbb{Z}/4\mathbb{Z}$ such that$$s' - s = \sum_{i,j} c_{i,j} v_{i,j},$$and this will give you a solution method: for each $i,j$, click on tile $i,j$ exactly $c_{i,j}$ times (order is irrelevant). You can use generalized Gaussian elimination to check whether $s'-s$ is in the span, and if so, to find the coefficients $c_{i,j}$. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.