id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_unix.144346
The problem is that when watch is executed it runs sh and I get this error:sh: 1: func1: not foundhere is the code:#!/bin/bashfunc1(){ echo $1}export -f func1watch func1
How to force watch to run under bash
bash;shell;shell script;function;watch
Ok, so there are a few issues with your approach.You are exporting a function, which is not portable between shells. watch executes its commands with /bin/sh, which on your system is not bash. And whatever shell it is, it doesn't respect function exports, so you get the error.Secondly, you can change your command to something like watch bash -c 'func1', but this may not work well either.The reason here being that any variables set by the script won't be available to the function. You might be able to export the ones it needs, but that starts getting messy.The safest solution is to put func1 in a script by itself and call that script. In short, try:watch bash -c func1
_unix.322486
I usually connect my mouse to a USB 2 port, but after hibernation I can only use the mouse from the USB 3 port.xface list and lsusb don't show the mouse as present when connecting to any of the USB 2 ports, but do if it's the USB 3 port. The USB 2 ports seem to work fine for other stuff like flash drives.Is there a way to reset the USB controller (without restarting the computer) or any other solution for this?
Mouse only working over usb 3 port?
usb;mouse
null
_unix.251457
Im trying to rsync all the .PHP and .HTML files from any directory inside of /home/ . However in /home/site2/public_html/cache_old/ there are .html files that i do not want to include in the sync (thus i want to exclude that directory and any of its sub-directories)Here is the best rsync command i can come up with (after lots of testing and failures):rsync -avv /home/ /ssd/rsyncPHPsFORmtree/ --include '*/' --include '*.html' --include '*.php' --exclude /site2/public_html/cache_old/* --exclude '*'Im convinced that my rsync command is not formatted properly based upon this output from when rsync is running:[sender] showing file site2/public_html/cache_old/total_pages/s/e/a/r/c/page99.html because of pattern *.html[sender] showing file site2/public_html/cache_old/total_pages/s/e/a/r/c/Page4.html because of pattern *.html[sender] showing file site2/public_html/cache_old/total_pages/s/e/a/r/c/searchHe107.html because of pattern *.html[sender] showing file site2/public_html/cache_old/total_pages/s/e/a/r/c/page18.html because of pattern *.htmlThanks
rsync exclude directory not working, when also scanning for only *.php files
linux;centos;rsync;synchronization
rsync -avv /home/ /ssd/rsyncPHPsFORmtree/ --exclude '/site2/public_html/cache_old/' --include '*.html' --include '*.php' --include '*/' --exclude '*' This should do it.The order of the filers is important. The 1st matching rule applies. So you exclude the folder 1st, then include the files you want, then include directories that weren't previously excluded, then exclude everything else.
_unix.44741
I just got a .iso of the linux distro Backtrack 5 R2. I set it up, using virtual box, and set it up to run using the .iso, and hard drive as a .vdi. Here's the setup:System: Base Memory: 1500 MB Boot Order: CD/DVD-ROM, Hard Disk Acceleration: VT-x/AMD-V, Nested PagingStorage: IDE Controller IDE Primary Master (CD/DVD): BT5R2-KDE-64.iso (2.62 GB)SATA Controller SATA Port 0: Backtrack 5 R2.vdi (Normal, 8.00 GB)Why would I be getting this error? Everything looks fine to me. And also, I'm running virtual box in a Windows 7 64bit OS.
FATAL : No Bootable medium found! System halted
virtualbox;iso;backtrack
null
_codereview.160722
So, I have decided to make a little guessing game where the user tries to decode what the encoded piece of text prompted. I'm sure it works. However, I know that there are places where I can improve. I am open to any constructive criticism about this. This program was done in HTML + JavaScript.<!DOCTYPE HTML><HTML><HEAD> <META CHARSET=UTF-8 /> <TITLE>Decryption Guessing Game</TITLE></HEAD><BODY> <p id=para>Text:</p> <form name=game action=# onsubmit=return validateForm()> Decrypt: <input type=text name=text> <input type=submit value=Check!> </form> <SCRIPT LANGUAGE=Javascript> function randomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } // defines the function that gets a random number, will be useful later var text = ['smell', 'cat', 'jump']; // pieces of text to decrypt var encryptedText = []; // the decrypted pieces of text. for (var i = 0; i < text.length; i++) { encryptedText.push(window.btoa(text[i])); } var pieceOfText = encryptedText[randomInt(0, 2)]; console.log(pieceOfText); document.getElementById('para').innerHTML += + pieceOfText; function validateForm() { var form = document.forms['game']['text']; var input = form.value; if (input == ) { alert(Enter your answer within the input.); return false; } else if (!(/^[a-zA-Z0-9-]*$/.test(input))) { alert(Your input contains illegal characters.); return false; } else if (input != window.atob(pieceOfText)) { alert(Incorrect; try again.); location.reload(); } else { alert(Correct!); location.reload(); } } </SCRIPT></BODY></HTML>
A decoding guessing game
javascript;html
Use lowercase tag names and attributesQuoting Quentin from Is it bad to use uppercase letters for html tags?:The only relevant parts of specifications say:HTML tag and attribute names are case insensitive. XHTML tag and attribute names are case sensitive and must be lower caseStuff that isn't mentioned in any standard:Lower case is generally considered easier to readLower case is most common (and what people are used to working with)Holding down the shift key or toggling CAPS LOCK all the time is a painDon't use onsubmit attributeIt's a rather bad code style to still use attributes like this one, these days. For example, that way the submit event would not be raised by form.submit() function, which you may want to use later. Use addEventListener() instead, it's supported even by IE9+.Don't use deprecated language attribute of script tagNot only it is deprecated and it's not used anymore, but also a standard regarding this attribute's values never existed. You should use type=text/javascript instead or no attribute at all, since in HTML5 in case of lack of specification of language used by script tag, it is assumed to be JavaScript, anyway.Randomness source and distributionYour function randomInt() uses Math.random() to obtain random values in a manner that will give you non-uniform distribution of returned values. It should also be noted, that it provides non-cryptographically secure randomness, although this is not a problem in this case.CommentsNot all comments are useful, especially this invalid one:var encryptedText = []; // the decrypted pieces of text.Global scopeYou shouldn't declare variables in the global scope, like you did between the two functions you made. Break that code into another function or combine with already existing ones, if appropriate.Use map()Thisvar encryptedText = []; // the decrypted pieces of text.for (var i = 0; i < text.length; i++) { encryptedText.push(window.btoa(text[i]));}could be shortened to one, very straight-forward line:var encodedText = text.map(window.btoa);Use .textContent instead of .innerHTMLSince you don't want nor need to have your string parsed, you should use .textContent property instead of .innerHTML.Inconsistent quotation marksYou mix single ('') and double () quotation marks. Use single ones, except where it would force you to escape what's between them.Dot notationThisvar form = document.forms['game']['text'];would look better and be written by most as:var form = document.forms.game.text;Use strict equality operatorYou should use strict equality operator in your code, as it doesn't performs type conversion and is generally considered a good practice.Don't location.reload()You don't need to location.reload(), just reset() the form.Don't encode before necessaryCurrently you are encoding all strings before they are even randomly chosen. There is no need to do that. What if there were thousands of strings? Reverse the order of operations, first choose random string and just then encode it. That way, you won't even need to store results of encoding, by the way.NamingWhat you do is encoding and decoding with Base64, but one variable is named encryptedText. Comment on the same line have exactly the same naming issue. There is no encryption involved in your code, at all.Replace two location.reload()s with oneYou could remove two instances of location.reload() that you have in your code and add just one below the chain of conditional checks.Edit: Although remember that even this one location.reload() should be replaced with form resetting, as mentioned before.Empty string submission checkInstead of checking if (input === '') you could add required= attribute to your input tag.
_unix.246181
I am writing a program printing the file and directory of a specify directory. But I have to ignore certain kind of file. We store them in .ignorefile.So, to get just the file that I want, I use find function. But, I have the same error every time: No such file or directory.And, when I try on my terminal it works perfectly with the same arguments.An example : In my ignore file I have: *.txt, *.cppWhen I execute my .sh file I put two arguments: the ignore file and a directory.Then, when I scan all text in my file to construct the argument files then I call my store() function.Here you can see my code: function store(){ dir=$1 find_arg=$2 # Dir ! -name '*.txt' ! -name '*.cpp' -print echo $find_arg cmd=`find $find_arg` echo $cmd }Here the function which build find_args : function backup(){ if [ $1=-i ] && [ -f $2 ] then backignore=$2 if [ $3=-d ] && [ -d $4 ] then directory=$4 find_arg= $directory while IFS='' read -r line || [[ -n $line ]]; do find_arg+= ! -name find_arg+=' find_arg+=$line find_arg+=' done < $backignore find_arg+= -print store $directory $find_arg else echo please entrer a right directory fi else echo Please enter a right ignore file fi}backup $1 $2 $3 $4I call sh file./file.sh -i ignorefile -d Sourceoutput:Source ! -name '\*.cpp' ! -name '\*.txt' -printSource/unix_backup/example_files/backignore Source/unix_backup/example_files/Documents/rep1/file3.txtSource/unix_backup/example_files/Documents/rep1/file4.cpp Source/unix_backup/example_files/Documents/rep3 Source/unix_backup/example_files/Documents/rep3/rep4 Source/unix_backup/example_files/Documents/rep3/rep4/file7.txt Source/unix_backup/example_files/Documents/rep3/rep4/file8.cpp
find problem in bash script
shell script
null
_cs.12620
I have the following formal grammar: $$G= (\{S,A,B\},\{a,b\},R,S)$$ $$R=\{S \rightarrow A\ |B, A \rightarrow \varepsilon\ | aA\ |bA, B \rightarrow \varepsilon\ |Bb\ | b\}$$Now, we see, the production rules $A \rightarrow \varepsilon$ and $B \rightarrow \varepsilon$ implies that this grammar is not context-sensitiv ($CSG$). But on the other hand, we see this grammar satisfies the conditions for a context-free ($CFG$) grammar, because every production rule has just one NON-terminal on the left side.We know, according to the Chomsky hierarchy, a contest-free grammar imples a contest-sensitive grammar: $CFG \implies CSG$Now i am confused, is my grammar context-free or it is not, even if it satisfies the conditions? Can it be $CFG$ without being $CSG$?
Is this formal grammar context-free (CFG) but not context-sensitive (CSG)?
formal languages;formal grammars
Context-free languages are context-sensitive languages; therefore, if there's a valid CFG for a language, then there is a valid CSG for the same language. Depending on how you define CFGs and CSGs, it's possible that a CFG may not count as a CSG. It's quite often the case that CSGs aren't CFGs, even if the CSG generates a context-free language. Basically, even if CFG does not imply CSG, it is still true that CFL implies CSL. That's the confusion: the Chomsky hierarchy implies things about languages.If your definition of a CSG says No transitions, you're right. If it says The only transition can be S , then you are right. If it doesn't say something specifically excluding , then you're wrong. It's a matter of how you define what consistutes a valid CSG, which sounds obvious, and in fact is.
_datascience.18562
I am currently doing pattern recognition on spectograms of audio files using convolutional neural networks. The spectograms are made using matplotlib cm.jet colormaps. Problem with this color map is that it auto ranges its colors based on the min and max value of the input it is given. so an example:Spectrograms of two different version of audio file. One with static filter output, and the other with delta filter outputs. RGB values show no difference in ranges for both delta and normal, but the db, scale shows a big difference. My input consist of one column of the static and one column of delta, or a matrix (40,2,3), but since these ranges are very different kinda make me suspect that this would not work very well. Am I right or wrong?
Does the input data representation matter while training CNN for speech recognition?
visualization;data;image recognition;audio recognition
Data representation does matter because this is all the information that you pass to a learning algorithm. It is normal for static and delta (delta-delta) to have different range (I have worked with mfccs). They represent different information.Static features can be small but they may change rapidly making delta large or vice-versa. The blue regions in the first spectrogram (low magnitude) becomes red in second( high magnitude). As long as all the input are processed in the same manner (static followed by delta followed by delta-delta or any order), it won't be a problem.
_unix.317475
I have linux mint mate 17 and am trying to install my amd drivers.I downloaded my drivers from linux amd which gives me a .zip file, after extracting I get a .run file. If i run the .run file as is it seems to go fine till it reaches a point that it wants Superuser and reverts back, if I run it as admin I get: xed has not been able to detect the character encoding. Please check that you are not trying to open a binary file. Select a character encoding from the menu and try again.I have tried both x32 and x64 for Ubuntu and linux OS and I always get the same result.Is this a binary file? How do I get these drivers to install?This is my video card: VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] RS880M [Mobility Radeon HD 4225/4250] (prog-if 00 [VGA controller])
trying to install amd drivers
amd graphics
null
_unix.332589
I bought a desktop machine with Windows on it a couple of years ago, and then just last year or so installed Fedora on it from a disk I had (got it from a Linux magazine). Fedora works great, but I was never able to access Windows since then ever again. I'm interested in trying to get it to work now, so I'm taking another crack at it. I'm trying to follow this guide right now, but I'm not sure which partition to use (or if Windows still even works). The guide uses sda1 but I have a Windows recovery environment on there, not sure which one to use instead. This is the result of my sudo fdisk -l: Disk /dev/sda: 931.5 GiB, 1000204886016 bytes, 1953525168 sectorsUnits: sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 4096 bytesI/O size (minimum/optimal): 4096 bytes / 4096 bytesDisklabel type: gptDisk identifier: D8E185CC-1266-4DC6-AEF5-459091253354Device Start End Size Type/dev/sda1 2048 1640447 800M Windows recovery environment/dev/sda2 1640448 2172927 260M EFI System/dev/sda3 2172928 2435071 128M Microsoft reserved/dev/sda4 2435072 317007871 150G Microsoft basic data/dev/sda5 317007872 391127039 35.4G Microsoft basic data/dev/sda6 1919969280 1953523711 16G Windows recovery environment/dev/sda7 391127040 391129087 1M BIOS boot partition/dev/sda8 391129088 392153087 500M Microsoft basic data/dev/sda9 392153088 425199615 15.8G Linux swap/dev/sda10 425199616 530057215 50G Microsoft basic data/dev/sda11 530057216 1919969279 662.8G Microsoft basic dataCould someone please steer me in the right direction in getting Windows to boot up, or check if it's still even working?
Accessing Windows from Fedora after install?
fedora;boot;windows
null
_unix.342621
I have a problem with creating some reference from backup (main source dir).My wish is to create shadow of a backup for another user with the selected features:files of the backup folder can be updated,user have all rights to the shadow of the backup catalog,all files and subdir's are reference,user can't remove source backup files or modify via shadow copy.
Reference to main source (directory) as a shadow
mount;ln;shadow;reference
null
_unix.58671
With zsh multios set (setopt multios) it's possible to do things like:< in1 < in2 > outand:< in > out1 > out2which is very convenient.I want to combine this feature with brace expand (setopt braceexpand), so when I say:<in{1,2}^I(^I is a literal tab and invokes the completion system), I want it to expand to:<in1 <in2 but instead I get:<in1 in2Is there an easy way to modify this behavior?
Expand less-than sign when using multios and brace expand
zsh;autocomplete;brace expansion
This is the completer setting I'm using: zstyle ':completion:*' completer _complete _list _expand _oldlist _ignored _match _correct _approximate _prefixThe substitute setting is the default, i.e. 1.Seeing Chris's answer and pointers in the right direction, made me realize that this must have something to do with my configuration.I started poking around with the completer order and the substitute setting, none of which changed the behavior. Comparing the settings, using the minimal configuration file provided by Chris, with my own, I narrowed the problem down to my bindkey file, and from there down to bindkey -v. This has the side-effect of setting ^I to expand-or-complete which for some reason botches desired expansion.As I want to continue using the viins and vicmd keymaps the solution for me was to change tabs behavior to complete-word: bindkey -M viins \CI complete-wordbindkey -M vicmd \CI complete-wordtl;drIf you're using viins or viicmd as keymap remember to change ^I to complete-word:bindkey -M viins \CI complete-wordbindkey -M vicmd \CI complete-word
_softwareengineering.329096
I have a hard time understanding when the Single Responsibility Principle is correctly used. Consider the following code:// --------------------------------------------------------------------------------------------------void CTCPClient::Try_Send_Data(const char *Outgoing_Message)// --------------------------------------------------------------------------------------------------{ Reset_Return_Value(); Copy_Data_Into_Buffer(Outgoing_Message); try { if((strcmp(Outgoing_Message, ) != 0)) { Send_Data(); Keep_Alive_Counter = 0; // reset as a button has been pressed } if(Return_Value < 0) { throw SEND_DATA_TCP_ERROR; } } catch(EError_ID) { Error_Message = strerror(errno); LOG_WARNING(__SOURCE__ << Error_Message); }}If I would read this method for the first time, I would, as the name sugest, expect a try and catch statement. But before that Im calling two additional methods (Reset_Return_Value(), Copy_Data_Into_Buffer()). Is the SRP already violated here?Further in the method I'm setting Keep_Alive_Counter = 0;. In my opinion, at least at this point the SRP has been violated in addition to the fact, that if I were to be someone who didn't write the code, would simply not expect this line to be there. The problem I have here is: If I do this in an explicit method, it will be a one line method, something I encounter more often, as I try to consinder the SRP. These methods still look weird to me and I haven't found an answer to when they are considered good pratice. Always? In some cases? Never?This is my own code so feel free to criticize, as long as it is constructive.EDIT: Keep_Alive_Counter and Return_Value are class attributes, which are changed/used by other methods.
Problem with understanding SRP
design;design patterns;c++;single responsibility
When considering whether or not a function or a method violates the SRP, you should look not at the implementation of the method but at what it's supposed/promises to do. Consider the following two functions:void printTime() { print(getTime()); invade(POLAND);}void printTimeAndInvadePoland() { print(getTime()); invade(POLAND);}Only the second function violates the SRP. printTimeAndInvadePoland has two responsibilities - to print the time and to invade Poland. printTime does not violate the SRP, as it has only one responsibility - to print the time. It has a different problem - unwanted side-effects. You just want to print the time and suddenly you started a world war. printTimeAndInvadePoland does not have unwanted side-effects because it's supposed to invade Poland - that side-effect is part of it's responsibility.Let's look at your Try_Send_Data. It has one responsibility - to send the data. You are worried about the calls to Reset_Return_Value and Copy_Data_Into_Buffer and about resetting Keep_Alive_Counter. Does any of them violate the SRP? No - because they don't change the fact that Try_Send_Data's only responsibility is to send the data. So the question is - do they make the method deviate from it's responsibility?Reset_Return_Value(); - it looks like it refers to the return value of some lower level data transmission function that you call from Send_Data, and Send_Data is setting. This is not a violation of the SRP, but it's still a bad practice: Send_Data should either return that value or throw an exception if it indicates an error. Even if you keep Send_Data as is, if it guarantees to always set Return_Value you can move the if(Return_Value < 0) check to only happen when Send_Data is called, and then you won't have to reset it.Copy_Data_Into_Buffer(Outgoing_Message); - I see no problem here. While I don't know if it copies the data to or from Outgoing_Message, this copy seems like a necessary task for sending the data, which supports Try_Send_Data one responsibility.Keep_Alive_Counter = 0; - updating the keep-alive information is part of the data sending process, so there are no weird side-effects here, but I don't think this line belongs here. If you update the keep-alive info every time you send data(makes sense), it should be done inside Send_Data. If, like the comment indicates, you only update it when a button is pressed(WTF?), it should be done in the button press event handler.Of course, if Send_Data is not yours, and Try_Send_Data is a convenience wrapper around Send_Data's awkward API, this may be acceptable - though you might want to rename Try_Send_Data, because right now it's name indicates it's just a variation of Send_Data that does not throw, when it clearly does more. If you can change Send_Data, consider moving some of Try_Send_Data's functionality(like copying the data to the buffer, resetting the keep alive counter, and throwing in case of bad return value) to Send_Data.
_unix.16107
I have a variable containing a leading zeroes number, and I want to grep this variable and that same variable plus one. I made several attempts but ran into errors. Here's what I want to do:read varnewvar=$(($var +1))grep '$var' /some/dirgrep '$newvar' /some/dirI really think there's something wrong with my code. I also tried some test like this:#!/bin/bashecho enter numberread numbernewnumber=$(($number + 1))echo $newnumberThat gives me an error: value too great for base (error token is. If i do it like this: #!/bin/bashecho enter numberread numbernumber=newnumber=$(($number + 1))echo $newnumberThis will output 1 all the time.What's wrong with my attempts, and how can I do what I want?
grepping a variable and adding 1 to it
shell;grep;arithmetic
null
_unix.106631
How do I use the bitwise logical-or operator, |, in tcsh?I enter@ y = 1001; @ z = 0110;@ x = $y|$z110: Command not found.
TCSH bitwise | operator
tcsh;arithmetic
Do you really want to do this in tcsh only? Csh and its derivative tcsh have many such quirks. You are better off with another shell like bash etc.In this particular case, it appears that throwing in a pair of parenthesis keeps tcsh happy. This is also documented in the tcsh manual:expr may contain the operators *, +, etc., as in C. If expr contains <, >, & or | then at least that part of expr must be placed within ().mint13:~> echo $versiontcsh 6.17.06 (Astron) 2011-04-15 (x86_64-unknown-linux) options wide,nls,dl,al,kan,rh,nd,color,filecmint13:~> @ y = 1001; @ z = 0110;mint13:~> @ x = $y|$z110: Command not found.mint13:~> @ x = ($y|$z)mint13:~> echo $x1007You might already be aware of this tcsh is reading 1001 and 0110 as decimal numbers. I don't know how to make it understand binary numbers.
_unix.137990
If I terminate the Xorg server with a SIGINT signal (eg. when I press Ctrl+C), what signal does it send to its clients?
What signal does X send to its clients when it receives SIGINT?
xorg;x11;signals;exit
The X server doesn't send a signal to its clients. This wouldn't be possible in general since the client and the server might not even be running on the same machine.Communication between the server and the client goes through a socket. When the server dies, its end of the socket is closed. It's up to the client application to decide how to react to that; most print an error message and terminate.If the client is a terminal emulator, then when it terminates, it sends SIGHUP to its controlling process, which is usually a shell. The shell in turn sends SIGHUP to the main process of each foreground or background job.
_unix.363770
I have configured one of the web-instance configuration files with the below snippet to allow redirects to work through another file without the need to restart the server. RewriteMap redirects txt:/mnt/var/www/html/abc/content/abc/na/ac/config_en_us/redirects/redirects.txtRewriteCond %{REQUEST_URI} ^(.*)$RewriteCond ${redirects:%1} >RewriteRule ^(.*)$ ${redirects:%1} [R=301,NC,L]When trying to restart the httpd after putting the code snippet i am not able to start the apache. The same code is working on other servers. Also the file was created and i have validated the permission. below is the error statement Syntax error on line 69 of /etc/httpd/conf.d/abc.conf: RewriteMap: file for map redirects not found:/mnt/var/www/html/abc/content/abc/na/ac/config_en_us/redirects/redirects.txtI was finally able to bring the server up but the fix was not correct. Here is what i did. I created the same file with the same name in a the path /etc/httpd/conf.d and then moved it to the required path, after which apache was able to find the file and did come up. Can anyone help me understand what happened.
Apache restart failing as it is not able to find a file which is present
permissions;apache httpd
null
_codereview.19919
I have a data structure, containing time span nodes, with the following properties:Nodes are sorted ascendingTime spans will not overlap, but may have gaps between themEach node will have a start datetime and a finish datetimeThe last node's finish may also be null (not finished yet)I want to be able to find the node that intersects a given datetime, or return false if no match is found basically resembling the following sql query for a sql table with similar properties as my data structure:SELECT t.*FROM table tWHERE t.start <= @probeDate AND ( t.finish >= @probeDate OR t.finish IS NULL )I've concluded that a (variation of a) binary search is probably the most efficient search algorithm. So, this is what I have come up with so far:<?phpclass Node{ protected $start; protected $finish; public function __construct( DateTime $start, DateTime $finish = null ) { $this->start = $start; $this->finish = $finish; } public function getStart() { return $this->start; } public function getFinish() { return $this->finish; } public function __toString() { /* for easy displaying of the timespan */ return $this->start->format( 'H:i:s' ) . ' - ' . ( null !== $this->finish ? $this->finish->format( 'H:i:s' ) : '' ); }}class NodeList{ protected $nodes; public function __construct( array $nodes = array() ) { $this->nodes = $nodes; } public function find( DateTime $date ) { $min = 0; $max = count( $this->nodes ) - 1; return $this->binarySearch( $date, $min, $max ); } protected function binarySearch( $date, $min, $max ) { if( $max < $min ) { return false; } else { $mid = floor( $min + ( ( $max - $min ) / 2 ) ); $node = $this->nodes[ $mid ]; $start = $node->getStart(); $finish = $node->getFinish(); if( $date < $start ) { return $this->binarySearch( $date, $min, $mid - 1 ); } else if( $date > $finish ) { if( $finish == null ) { return $node; } else { return $this->binarySearch( $date, $mid + 1, $max ); } } else { return $node; } } }}I am testing it with the following:$nodes = array( new Node( new DateTime( '01:01:00' ), new DateTime( '01:05:00' ) ), new Node( new DateTime( '01:06:00' ), new DateTime( '01:10:00' ) ), new Node( new DateTime( '01:11:00' ), new DateTime( '01:15:00' ) ), new Node( new DateTime( '01:16:00' ), new DateTime( '01:20:00' ) ), new Node( new DateTime( '01:21:00' ), new DateTime( '01:25:00' ) ), new Node( new DateTime( '01:26:00' ), new DateTime( '01:30:00' ) ), new Node( new DateTime( '01:31:00' ), new DateTime( '01:35:00' ) ), new Node( new DateTime( '01:36:00' ), new DateTime( '01:40:00' ) ), new Node( new DateTime( '01:41:00' ) ));$list = new NodeList( $nodes );$date = new DateTime( '01:00:00' );for( $i = 0; $i < 100; $i++, $date->modify( '+30 seconds' ) ){ $node = $list->find( $date ); echo 'find: ' . $date->format( 'H:i:s' ) . PHP_EOL; echo ( $node !== false ? (string) $node : 'false' ) . PHP_EOL . PHP_EOL;}Do you see any inherent flaws and/or ways to improve this algorithm? Perhaps you even know of a more time efficient algorithm to accomplish the same?PS.: Don't worry about the internal integrity of NodeList and Node (checking for invalid nodes, invalid min and max datetimes, checking overlaps, etc.) this is just a quick and dirty concept. I'm primarily interested in the search algorithm in NodeList::find() and consequently NodeList::binarySearch().
Binary search algorithm for non-overlapping time spans and possible gaps
php;optimization;algorithm;binary search
null
_codereview.90809
I have some code here that I am very unhappy with. The task I am trying to accomplish is this.Given a 2d vec like this:[[0 2 0] [1 3 5] [3 3 0]]which can contain positive ints including zero I want to remove all lines that are greater zero.Where the definition of line is the following:A line is represented by the position n in every vec inside the 2d vec.So my example above has three lines: [0 1 3], [2 3 3] and [0 5 0].The line that I want to remove from it according to my algortihm is [2 3 3] because every element is greater than zero.So my 2d vec would now look like this:[[0 0] [1 5] [3 0]]And finally I want to pad the vecs to their original size filling them with zero for every removed line, so that it looks finally like this:[[0 0 0] [0 1 5] [0 3 0]]This is what I came up with:(defn in? true if seq contains elm [seq elm] (some #(= elm %) seq))(defn not-in? true if seq does not contain elm [seq elm] (not (in? seq elm)))(defn all-greater-zero-at Given a 2-d vec [[0 1] [0 2]] return true if all elements at 'at' are greater than zero [v at] (not-in? (map #(if (> (nth % at) 0) true false) v) false))(defn to-be-removed Returns a seq of positions to be removed (0 3 4) [v width] (reduce (fn [a b] (if (all-greater-zero-at v b) (conj a b) a)) [] (range width)))(defn remove-at Removes an element from a 1d vec [v at] (into [] (concat (subvec v 0 at) (subvec v (+ at 1) (count v)))))(defn insert-at inserts an element into a 1d vec [v elm at] (into [] (concat (subvec v 0 at) elm (subvec v at (count v)))))(defn remove-and-replace-all-at [v at] (map #(insert-at (remove-at % at) [0] at) v))(defn replace-full-by-zero [v width] (reduce (fn [a b] (remove-and-replace-all-at a b)) v (to-be-removed v width)))(defn remove-zeros [v at] (reduce (fn [a b] (conj a (remove-at b at))) [] v))(defn fill-with-zeros Takes a 2d vec and pads ith with zeros up to width [v width] (map #(into [] (concat (take (- width (count (first v))) (repeat 0)) %)) v))(defn clean-grid removes all full lines [fbz tbr] (loop [acc fbz tbr tbr i 0] (if (empty? tbr) acc (recur (remove-zeros acc (- (first tbr) i)) (rest tbr) (inc i)))))(defn remove-full-lines [v width] (let [fbz (replace-full-by-zero v width) tbr (to-be-removed v width) cleaned-grid (clean-grid fbz tbr)] (into [] (fill-with-zeros cleaned-grid width))))This seems like a lot of code for such a simple algorithm and I assume there are a lot of better ways to do that, but just did not come up with a better one, so, please, go ahead and fix it, if you want to.
Remove lines from a 2D vec
clojure;computational geometry
A transpose function would be useful here. This is the code I came up with:(defn transpose [m] Transposes a matrix, returning a new matrix. For 2D matrices, rows and columns are swapped. (vec (apply map vector m)))(defn any-zero? [r] ((complement not-any?) #(= 0 %) r))(defn empty-matrix [x y] (vec (repeat y (vec (repeat x 0)))))(defn filter-matrix [m] (let [row-size (-> m first count) fm (filterv any-zero? m) padding-size (- (count m) (count fm))] (into (empty-matrix row-size padding-size) fm)))(defn transform-matrix [m] (-> m transpose filter-matrix transpose))Let's try it out:=> (transform-matrix [[0 2 0] [1 3 5] [3 3 0]])[[0 0 0] [0 1 5] [0 3 0]]If you want to do more advanced operations on matrices I recommend looking into the core.matrix library.Hope this helps!
_unix.97390
The POSIX description of the -b flag for the sort command isIgnore leading characters when determining the starting and ending positions of a restricted sort key.I can understand the use for the starting position of the key, but what about the ending positions? Can anybody give an example?For instance, with the locale set to POSIX, the file with contentx zx awould be sorted differently under sort -k 2 and sort -k 2b, but I haven't been able to come up with a case where, say, sort -k 2,3b and sort -k 2,3 would make a difference.
When do `sort -k 2,3b` and `sort -k 2,3` differ?
sort;utilities
It has an effect when you add reverse to the comparison. Order of precedence are changed as in the -r only apply to last-resort comparison.No reverse:$ sort -k 1,2 sampleA 34A 33$ sort -k 1,2b sampleA 34A 33Reverse:$ sort -rk 1,2 sampleA 33A 34$ sort -rk 1,2b sampleA 34A 33
_unix.77588
Is it possible to use curl and post binary data without passing in a file name? For example, you can post a form using binary via --data-binary:curl -X POST --data-binary @myfile.bin http://foo.comHowever, this requires that a file exists. I was hoping to be able to log HTTP calls (such as to rest services) as the text of the curl command to reproduce the request. (this greatly assists debugging these services, for example) However, logging curl commands that reference a file would not be useful, so I was hoping I could actually log the raw binary data, presumably base64 encoded, and yet still allow you to copy and paste the logged curl command and execute it.So, is it possible to use curl and post binary data without referencing a file? If so, how would that work? What would an example look like?
Passing binary data to curl without using a @file
curl;binary
You can pass data into curl via STDIN like so:echo -e '...data...\n' | curl -X POST --data-binary @- http://foo.comThe @- tells curl to pull in from STDIN.To pipe binary data to curl (for example):echo -e '\x03\xF1' | curl -X POST --data-binary @- http://foo.com
_unix.276060
In Bash, I want to rename a file so that the prefix up to - is removed, but why does it not work with brace expansion?$ lsThomas Anderson, Michael Dahlin-Operating Systems$ mv {Thomas\ Anderson,\ Michael\ Dahlin-,}Operating\ Systemsmv: target Operating Systems is not a directory
Brace expansion does not work
bash
Your file contain , which is special to brace expansion, so your brace expansion expanded to 3 strings, instead of two as you intend.You can try:$ printf '%s\n' {Thomas\ Anderson,\ Michael\ Dahlin-,}Operating\ SystemsThomas AndersonOperating Systems Michael Dahlin-Operating SystemsOperating Systemsto see how brace expansion was expanded.The quick fix is escaping the ,:$ printf '%s\n' {Thomas\ Anderson\,\ Michael\ Dahlin-,}Operating\ SystemsThomas Anderson, Michael Dahlin-Operating SystemsOperating Systems
_unix.304034
I have a file like this:1;1471375551;joe;WO12344;2;1471378551;frank;WO12345;14713802113;1471383211;frank;WO12345;14713852114;1471385311;frank;WO12345;5;1471385311;joe;WO12346;1471388211I'd like to use a bash script to find the line that contains a specified name (like frank) as well as a specified WO number (like WO12345) and also ends with a ;, then add a string to the end of the line. I want to edit the file directly, not output to stdout. I know how to use read to get the name and WO number. I'm guessing sed with -i is the right tool. How can I do that?
How can I add text to the end of a line that contains multiple strings?
text processing;sed;awk
If the name and WO are always consecutive, it's quite straightforward:sed '/frank;WO12345;/s/;$/;sometext/' -i fileIf they can appear either way around, or not necessarily next to each other, use blocks of commands to combine the two tests:sed '/;frank;/{/;WO12345;/s/;$/;sometext/}' -i file
_cs.50261
I am trying to teach myself how to write Context-free Grammar for different languages. I have an example language I am trying to work out and this is the answer I came up with, does it make sense?the language is (i used an image because i don't know how to write out the powers on a mac):This is my answer:S --> rSjZr | Z Z --> ooI've been trying to learn it by reading other people's CFG's, however I am still unsure of how it works, my thinking is that, if j and k are 0 then r becomes 0 as well because 2*0 would return 0 and I therefore end up with oo. However, I am unsure about the first part it seems like it could make sense and at the same time it doesn't could somebody please explain to me how they would write a context-free grammar for the language and if my answer makes sense?Thanks
How to write Context-free Grammar for this language?
formal languages;context free;formal grammars
A couple of things:Sometimes it helps to simplify the description of your grammar. Instead of $\{r^{2j+k}j^ko^2r^j \mid j,k \geq 0 \}$, you can write this: $\{r^{2j}r^kj^koor^j \mid j,k \geq 0\}$. It is still the same grammar, but you can easier see what you're doing. For example, something here stands out: $\{r^{2j}\mathbf{r^k}\mathbf{j^k}oo\mathbf{r^k} \mid j,k \geq 0\}$ Next: Sanity-checking. See if what you're trying to achieve conflicts with any known rules. Can this language be produced by a context-free grammar? Or is this language not context-free? Consider that $\{ a^kb^kc^k \mid k \geq 0\}$ is a classical example for non-context-free grammars (It is context sensitive).If the language is not context-free, we can stop trying to find a context-free grammar for it. Attempts will be (hopefully) futile.Unfortunately, I can't provide you with a simple way of constructing grammars for context-free languages. Maybe (probably) some other (far more experienced and knowledgeable) members here might be able to do so. What worked for my (short) stint in TCS, practice helped. I started with simple examples, and increased their complexity. Then you learn to recognize some patterns in languages and solve them for example by splitting the language into multiple, smaller and simpler languages which you already know how to solve.Lets try to apply that to this case: $\{r^{2j}r^kz^koor^j \mid j,k\geq0\}$We can see that that is essentially $\{r^{2j}$ [something else] $r^j \mid j\geq0\}$. That is easy to produce:$S \rightarrow rr X r | X$, where $X$ will produce the [something else]. That something else is of course $r^kz^koo \mid k\geq0$, which is also easy to produce:$X \rightarrow Y oo | oo$ and$Y \rightarrow rYz$Ultimately, the key behind this construction was simplifying the language, and then recognize that the language is a nested variation of $\{a^k\ b\ a^k\}$ and $\{a^k\ b^k\ a\}$, which both are trivial languages to produce.
_unix.245864
I can browse my server site using ip:8080which is inside my home network.But I am not able to browse using hostname:8080I do not have dns server. I have edited /etc/hosts file to include hostname and ip. I can ping using hostname.127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4::1 localhost localhost.localdomain localhost6 localhost6.localdomain610.16.2.12 apple.myserver.com10.16.2.22 ball.myserver.com10.16.2.20 cat.myserver.com10.16.2.19 dog.myserver.com10.16.2.18 elep.myserver.comSimilar Issue Here.
Browse by hostname from internet browser
centos;hostname;hosts
null
_unix.8807
What could the problem be? How do I find out what's going on?EDIT: Hitting f2 when the progress bar is going across the screen shows that booting stops at Starting atd: [OK]. After it reaches that point, the screen flickers a little bit and it just hangs.
Fedora won't boot. The startup progress bar goes all the way to the right and then everything just freezes
fedora
Sounds very much like there is a problem starting X, especially if you were messing around with xorg.conf.Deleting xorg.conf should solve the problem, also you should check /var/log/Xorg.0.log for errors.
_unix.320167
I am trying to get hardware keyboard support to work in my QT 4.8.6 application for the Beaglebone Green that is running Debain. The file system does not have any desktop so linux boots into a console that shows tty1 at the top. I created a systemd service in /lib/systemd/system/ to have my app start on bootup. The application starts but I don't get any hardware keyboard input. Here are some things I tried:Manually start the application from the tty1 console:Result: Hardware keyboard works in my appManually start the application from a serial console ttyS1:Result: No Hardware keyboardMy systemd service file looks like:[Unit]Description=MyApp Startup script ServiceAfter=syslog.target network.target[Service]Type=simpleWorkingDirectory=/usr/local/bin/myAppdirExecStart= /bin/sh myAppStartupScriptSyslogIdentifier=MyApp[Install]WantedBy=multi-user.targetI tried using the above service to start nano, but I can't tell if nano ever starts. After the system boots up, I don't see nano running. I also don't see it in the process list when I run ps command. The above service does start my qt app. I was trying to find out if I can get hardware keyboard support in nano by using the above service.It seems like I am not using systemd properly. Does anyone know what I am maybe doing wrong?
Enable Keyboard in QT application that is started with systemd
linux;debian;systemd;qt
null
_codereview.87268
I am working on a new MVC web application, so the project is in early stages. I have created 4 projects.Let me explain what they do:Common --> contains all my DTOs, enums helpers, ViewModels etc.Web --> simple MVC applicationBusiness --> This contains providers which have an interface and implementation for dependency injection:DAL --> Contains edmx file and DB EntitiesDAL is similar to Business project. It has an IUsersDAL and then UsersDAL implementation.Do I really need the DAL classes to access the database, or can I just access them from the Business class?Just for an example I am adding a sample code from UsersProvider.cs:This what my BusinessProvider is doing: private readonly IXPTSecurity _security; private readonly IUsersDAL _usersDAL; public UsersProvider(IXPTSecurity xptSecurity, IUsersDAL usersDAL) { _security = xptSecurity; _usersDAL = usersDAL; } public UserSessionModel AuthenticateUser(string userName, string password, ValidationContainer validationContainer) { var userInfo = _usersDAL.GetUserByUserNamePassword(userName, _security.Encrypt(password)); if (userInfo == null) { validationContainer.AddMessage(MessageType.Error, Login Failed. User name or password is incorrect.); return null; }}And then this is what is happening in the _usersDal.GetUserByUserNamePassword():// So this is this is what UsersDAL is doing public User GetUserByUserNamePassword(string userName, string password) { return _managerEntities.Users.FirstOrDefault(s => s.sUserName == userName && s.sPassword == password); }As you can see, all I am doing in my DAL classes is a simple LINQ type read from the database. If I do this in the Providers it saves me an extra layer.It would be nice to get someone else opinion on this before I start coding.By the way I need a separate Common and Business because this project requires another web application and another 3,4 Windows services, which will be later added using the same Business and Common. But I am not sure on the DAL.
MVC N-Tier Architecture
c#;asp.net mvc;n tier
null
_unix.143865
I've been searching for this issue for days now and tried various solutions suggested, without any success.Basically, I have a laptop with built-in audio (the output goes either to the headphone jack or to the built-in speaker) and HDMI. I'm running Debian 7.5 with KDE.Previously, I was running ALSA only and I was able to configure Skype to ring on the HDMI, but use the headphones for the calls themselves. I'd like to achieve something similar using Pulse.I'm not sure if Skype still separates ringing and call audio when it sends them to PulseAudio, but as the Linux version of Skype can run arbitrary scripts on events, I would be happy if I could use e.g. aplay to play something on the HDMI port. However, whatever I do, I always see (and can use) a single output device only.aplay -l:**** List of PLAYBACK Hardware Devices ****card 0: PCH [HDA Intel PCH], device 0: ALC269VB Analog [ALC269VB Analog] Subdevices: 1/1 Subdevice #0: subdevice #0card 0: PCH [HDA Intel PCH], device 3: HDMI 0 [HDMI 0] Subdevices: 1/1 Subdevice #0: subdevice #0aplay -L:default Playback/recording through the PulseAudio sound serversysdefault:CARD=PCH HDA Intel PCH, ALC269VB Analog Default Audio Devicefront:CARD=PCH,DEV=0 HDA Intel PCH, ALC269VB Analog Front speakerssurround40:CARD=PCH,DEV=0 HDA Intel PCH, ALC269VB Analog 4.0 Surround output to Front and Rear speakerssurround41:CARD=PCH,DEV=0 HDA Intel PCH, ALC269VB Analog 4.1 Surround output to Front, Rear and Subwoofer speakerssurround50:CARD=PCH,DEV=0 HDA Intel PCH, ALC269VB Analog 5.0 Surround output to Front, Center and Rear speakerssurround51:CARD=PCH,DEV=0 HDA Intel PCH, ALC269VB Analog 5.1 Surround output to Front, Center, Rear and Subwoofer speakerssurround71:CARD=PCH,DEV=0 HDA Intel PCH, ALC269VB Analog 7.1 Surround output to Front, Center, Side, Rear and Woofer speakershdmi:CARD=PCH,DEV=0 HDA Intel PCH, HDMI 0 HDMI Audio OutputWhen I try to use the hdmi device directly, I get the following error:$ aplay -D hdmi alert.wavPlaying WAVE 'alert.wav' : Signed 16 bit Little Endian, Rate 22050 Hz, Monoaplay: set_params:1087: Channels count non availableIn pavucontrol, under the Configuration tab, I see a Profile drop-down with the following options:Analog Stereo DuplexAnalog Stereo OutputAnalog Stereo (HDMI) Output + Analog Stereo InputAnalog Stereo (HDMI) OutputAnalog Stereo InputOffAs far as I can tell, all of these work as (probably) expected: the ones that say HDMI will direct audio output to the HDMI port; the others to the built-in audio card. No matter which one I select, I always see a single output device only under the Output Devices tab.I've tried adding either the built-in or the HDMI device to /etc/pulse/default.pa using load-module module-alsa-sink device=hw:0,0 and load-module module-alsa-sink device=hw:0,3 - these either seemed to have no effect, or made pulseaudio not display any profiles at all.
How to enable both built-in audio output and HDMI audio output with PulseAudio?
debian;audio;pulseaudio;hdmi
null
_unix.66505
I was wanting to run a find and then execute a script on each match; however, I was wanting to print the name of the matched file above the output from each exec. How can I produce the following output:$ find . -name 'something' -exec sh script.sh {} \;./something_1output from script.sh something_1./something_2output fromscript.sh something_2I am currently only getting the output from script.sh. I tried -exec echo {} && sh script.sh {} \; with no success.I would prefer a solution using -exec or xargs -print0, i.e., not prone to problems with white space.
How to print find match as well as run an -exec
bash;find
null
_unix.326608
I am not able to boot my HP Pavilion 15 which has EFI with the Arch Linux ISO for installation. The error message is: Selected boot image did not authenticateI have tried booting with a DVD as well as a USB flash drive. The image is: archlinux-2016.11.01-dual.isoHow do I get past this?
Arch Linux ISO issues with EFI (could not authenticate image)
arch linux;uefi
null
_unix.178857
I am trying to run grep against a list of a few hundred files:$ head -n 3 <(cat files.txt)admin.phpajax/accept.phpajax/add_note.phpHowever, even though I am grepping for a string that I know is found in the files, the following does not search the files:$ grep -i 'foo' <(cat files.txt)$ grep -i 'foo' admin.phpThe foo was foundI am familiar with the -f flag which will read the patterns from a file. But how to read the input files?I had considered the horrible workaround of copying the files to a temporary directory as cp seems to support the <(cat files.txt) format, and from there grepping the files. Shirley there is a better way.
grep files from list
bash;grep;command substitution;process substitution
You seem to be grepping the list of filenames, not the files themselves. <(cat files.txt) just lists the files. Try <(cat $(cat files.txt)) to actually concatenate them and search them as a single stream, orgrep -i 'foo' $(cat files.txt)to give grep all the files.However, if there are too many files on the list, you may have problems with number of arguments. In that case I'd just writewhile read filename; do grep -Hi 'foo' $filename; done < files.txt
_unix.207564
I have Fedora 21, which is a fedup from Fedora 20. My problem is that whenever I am using ps commaand, I am getting /usr/bin/dpkgd/ps: error while loading shared libraries: libprocps.so.1: cannot open shared object file: No such file or directory.This code was working perfectly when I had Fedora 20 installed. While doing Fedup, I got a bunch ofldconfig: /usr/lib/libOpenCL.so.1 is not a symbolic linkmessage, but the fedup went fine.Here are the output of the commands which might be relevant:$ which ps/bin/ps$ type psps is /bin/ps$ ldd /bin/psnot a dynamic executable$ ldd /usr/bin/dpkgd/ps inux-gate.so.1 => (0xb77f7000) libprocps.so.1 => not found libsystemd-login.so.0 => /lib/libsystemd-login.so.0 (0xb77ae000) libdl.so.2 => /lib/libdl.so.2 (0x467c7000) libc.so.6 => /lib/libc.so.6 (0x465f9000) librt.so.1 => /lib/librt.so.1 (0x46a72000) libdw.so.1 => /lib/libdw.so.1 (0x47816000) libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x46854000) libpthread.so.0 => /lib/libpthread.so.0 (0x467ce000) /lib/ld-linux.so.2 (0x465ce000) libelf.so.1 => /lib/libelf.so.1 (0x47695000) liblzma.so.5 => /lib/liblzma.so.5 (0x46edd000) libbz2.so.1 => /lib/libbz2.so.1 (0x46a7d000) libz.so.1 => /lib/libz.so.1 (0x467eb000)If I do a sudo yum reinstall procps, the problem goes away, even if the output of ldd does not change. But after restarting the computer, the problem returns. What could be the permanent solution of this problem?
Fedora 21: Getting libprocps.so.1: cannot open shared object file: No such file or directory on ps
fedora;ps
null
_webmaster.62983
I am trying to automatically place login data through a URL query for my university services. (https://login.gatech.edu/cas/login)two problems arise when I try to pass a URL query (Ex: https://login.gatech.edu/cas/login?username=testingone)1) The query does not show unless I already press the submit button2) the Query adds an extra 'comma' to the username field... I have no idea why.I have googled for hours to no avail...Any help will be appreciatedIf you copy and paste the URL (see example link posted above) and hit the LOGIN button you will understand my problemI am sort of a beginner and would love any feedback as I am trying to develop an app to make logging in an easier/automatic task.
URL query is adding an unecessary comma
html;url;authentication
null
_softwareengineering.187609
-I'm trying to figure out how to identify Application Services in my application. I think I can identify a Domain service by 2 things:It acts as a facade to the repository.It holds business logic that can't be encapsulated in a single entity.So I thought about this simple use case that I'm currently working on:An admin should be able to ban a certain user. The operation must be logged and an email must be sent to the banned user.I have a UserRepository which has a function getUserById(). I have a User entity which has a ban() function.I'll create a UserService like this:class UserService{ static void banUser(int userId){ User user= UserRepository.getUserById(userId); user.ban(); UserRepository.update(user); }}The userId is a POST variable that I'll be receiving in my Controller from a web form.Now where does the logging go? I need to log the ban process twice before and after the operation ex:Logger.log(Attempting to ban user with id:+userId);//user gets banned Logger.log(user banned successfully.);Second, I need to send a mail to the user. where should the call go?I thought about putting the logging and email is the UserService class itself, but I think there are better solutions.Third, where do Application Services fit in all of this?
Identifying Domain Services & Application Services when doing DDD
design;object oriented;architecture;domain driven design;services
null
_unix.49864
I'm using sh (dash) on Ubuntu (lucid) and the manpage has this to say about -e: -e errexit If not interactive, exit immediately if any untested command fails. The exit status of a command is considered to be explicitly tested if the command is used to control an if, elif, while, or until; or if the command is the left hand operand of an && or || opera tor.What happens when a background command fails? And does bash behave differently in this respect?
How does sh -e interact with &?
bash;shell;background process;exit
It's quite simple to test this. With -e:% bash -e -c 'false & echo waiting; if wait $!; then echo success; else echo failure; fi'waitingfailureSo if a backgrounded command fails, the shell will not exit automatically (-e is not enough).If you wait outside an explicit test, wait will return the return code of the failed backgrounded process. In this case, if -e is specified, the shell will exit:% bash -e -c 'false & echo waiting; wait $!; echo returned' waitingSame results with bash or sh or zsh.
_unix.17812
I have a bunch of random folders, some of them are hidden (beginning with a period). I want to list all of them, sorted by their sizes. I have something on the lines of this in mind:ls -d -1 -a */ | xargs du -s | sortBut the ls ... part of it doesn't show hidden files. I know some questions have been asked before on the same topic, but the answers never include a way to include hidden files. Or if it does, it uses the long format, hence making the output incompatible with the rest of the command.
How to list ALL directories according to their size? [without including the parent directory]
shell;command line;find;ls;disk usage
Parsing the output of ls is always problematic. You should always use a different tool if you mean to process the output automatically.In your particular case, your command was failing -- not because of some missing or incompatible argument to ls -- but because of the glob you were sending it. You were asking ls to list all results including hidden ones with -a, but then you were promptly asking it to only list things that matched the */ glob pattern which does not match things beginning with. and anything ls might have done was restricted to things that matched the glob. You could have used .*/ as a second glob to match hidden directories as well, or you could have left the glob off entirely and just let ls do the work. However, you don't even need ls for this if you have a glob to match.One solution would be to skip the ls entirely and just use shell globing:*$ du -s */ .*/ | sort -nAnother way which might be overkill for this example but is very powerful in more complex situations would be to use find:*$ find ./ -type d -maxdepth 1 -exec du -s {} + | sort -nExplanation:find ./ starts a find operation on the current directory. You could use another path if you like.-type d finds only things that are directories-maxdepth 1 tells it only to find directories in the current directory, not to recurse down to sub-directories.-exec [command] [arguments] {} + works much like xargs, but find gets to do all the heavy lifting when it comes to quoting and escaping names. The {} bit gets replaced with the results from the find.du -s you know* Note that I used the -n operator for sort to get a numeric sorting which is more useful in than alphabetic in this case.
_webmaster.69757
On most posts on my website the date is displayed. There are however some posts where I would not like to show the date.Would it be better to use display:none; via css or actually remove the code for the date altogether.Here is an example of the code I use (generated by a php function)<span class=posted-on>Posted on <time class=entry-date published datetime=2014-07-21T18:15:52+00:00>July 21, 2014</time><time class=updated datetime=2014-07-21T18:17:35+00:00>July 21, 2014</time></span>The reason I ask is that I was under the impression, even if I don't want to display the date, that the timestamp would be useful to search engines.Currently I use display:none; when I don't want to show the date.
How not to display the date on certain WordPress pages?
seo;wordpress;search engines;dates
null
_unix.49268
Is there any way to overload or wrap the ls command so that it will highlight / underline / otherwise make obvious the last three modified files?I know that I can simply ls -rtl to order by reverse modification time, but I usually do need an alphabetical list of files despite the fact that I would like to quickly identify the last file that myself or another dev modified.
Highlight the three last updated files in ls output
linux;bash;command line;ls
The following seems to work for me grep --color -E -- $(ls -rtl | tail -n3)|$ <(ls -l)It uses grep with highlight on input ls -l and uses a regular expression to search for either of the inputs for the three oldest command. It also search for the end-of-line $ in order to print the whole file.You can also put it in a function, such that you can use lll * with multiple arguments, just as you would use lsfunction lll (){ command grep --color -E -- $(ls -rtl $@ | tail -n3)|$ <(ls -l $@)}
_softwareengineering.89506
I currently use a Mac Pro for Xcode development, but am considering buying a MacBook Air when the newer models are released. How should I collaborate with myself when using both machines on the same project? Should I use Git, or should I just acess the Mac Pro as a networked drive from the MacBook, or something else?
One Developer, Two Machines
version control;ios;osx;xcode
You should definitely use a SCM system, even when only working on one machine. Which one you use is not that important. I would also recommend keeping the working directories on the two machines separate rather than using a directory shared across the network. Less chance for cluttering your environment, and allows you to work when the network is unavailable or down.
_codereview.11925
When we select the 'info' list in the combobox, the article with type 'info' characteristic automatically showed up, and when we select 'Berita' list in the combobox, the article with type 'Berita' charateristic automatically showed up.This is a long script that uses a post method. Can you help me make it simpler, perhaps using functions?<form method=post name=form2> <select name=type id=type> <option value=Semua>Semua</option> <option value=Berita>Berita</option> <option value=Info>Info</option> </select> <input type=submit id=type /></form><table width=200 border=1 class=tbl_art_content id=results><tbody> <tr> </tr> <?php $i=0; $no=0; if($_POST['type'] == 'Semua') { $query_art = mysql_query(SELECT * FROM artikel_tbl ORDER BY id) or die(mysql_error()); } else if ($_POST['type'] == 'Berita') { $query_art = mysql_query(SELECT * FROM artikel_tbl WHERE type = 'Berita' ORDER BY id) or die(mysql_error()); } else if ($_POST['type'] == 'Info') { $query_art = mysql_query(SELECT * FROM artikel_tbl WHERE type = 'Info' ORDER BY id) or die(mysql_error()); } else { $query_art = mysql_query(SELECT * FROM artikel_tbl ORDER BY id) or die(mysql_error()); } while($show=mysql_fetch_array($query_art)) { $no++; if(($no%2)==0) $color = '#f2f2f2'; else $color = '#f9f9f9'; ?> <tr bgcolor=<?php echo $color; ?> class=rows> <td class=chk_content><input type=checkbox name=checked<?php echo $i; ?> value=<?php echo $show['id']; ?>/></td> <td class=no_content><?php echo $no; ?></td> <td class=middle_content><?php echo $show['judul']; ?></td> <td class=middle_content><?php echo $show['penulis']; ?></td> <td class=middle_content><?php echo $show['type']; ?></td> <td class=middle_content><img src=.././upload/artikel/<?php echo $show['foto']; ?> width=144 height=88/></td> <td class=middle_content><?php echo $show['tanggal']; ?></td> <td class=aksi_content><div id=aksi_table> <ul> <li><a href=table_artikel.php?edit=<?php echo $show['id']; ?>><img src=images/Apps-text-editor-icon.png width=20 height=20 /></a></li> <li><a href=table_artikel.php?delete=<?php echo $show['id']; ?> onclick=return confirm('Hapus artikel?');><img src=images/Remove-icon.png width=20 height=20/></a></li> </ul> </div><!-- end of aksi_table --></td> </tr> <?php $i++; } ?> <input type=hidden name=n value=<?php echo $i; ?> /> </tbody></table>
Sorting with combobox
javascript;php;mysql
null
_datascience.6027
I have few points in $S^n$, i.e., the $n$-dimensional unit sphere embedded in $\mathbb{R}^{n+1}$, and I would like to project them down to $S^2$, i.e., the 2-dimensional unit sphere (embedded in $\mathbb{R}^3$) to visualize it with the constraint that neighboring points should be close by. I spent some time playing with t-sne but of course, the points no longer lie on $S^2$. I normalized the projections but that introduces weird distortions, for instance, if the variance of one dataset is very small in $S^n$ as compared to other, I expect the same to hold in their $S^2$ projections; that is not the case upon normalizing t-sne. Any ideas? I would really like something that makes the previous statement hold.
Projecting data from $S^n$ to $S^2$
machine learning;dimensionality reduction;visualization
null
_unix.386713
I know, my wireless does not support monitor mode (in kali linux)so, is there any other way for wireless attack?I want to hack the wireless and for this operation, I've done the following steps...i disconnect from all wireless networks and wrote in the terminal airmon-ng and give me this outputairmon-ng start wlan0 Found 3 processes that could cause trouble.If airodump-ng, aireplay-ng or airtun-ng stops working aftera short period of time, you may want to run 'airmon-ng check kill'PID Name 604 NetworkManager 714 wpa_supplicant 1568 dhclientPHY Interface Driver Chipsetphy0 wlan0 wl Broadcom Limited BCM4352 802.11ac Wireless Network Adapter (rev 03)(experimental wl monitor mode vif enabled for [phy0]wlan0 on [phy0]prism0)and then i typedairmon-ng stop wlan0 && airmon-ng check killPHY Interface Driver Chipsetphy0 wlan0 wl Broadcom Limited BCM4352 802.11ac Wireless Network Adapter (rev 03)(experimental wl monitor mode vif disabled for [phy0]wlan0)Killing these processes:PID Name714 wpa_supplicant9405 dhclientairodump-ng wlan0ioctl(SIOCSIWMODE) failed: Operation not supportedioctl(SIOCSIWMODE) failed: Operation not supportedError setting monitor mode on wlan0In my problem appearance, the wireless did not support the monitor mode.so, is there any other way for monitoring in the terminal?
wireless monitor mode error
kali linux
null
_webmaster.55307
We have recently consolidated one site into another one. We set up all of our 301s and those all work famously. The bulk of the 301s (including the old site's homepage) land on an interior page of the new site.We want to display an image to users that hit the interior page from the 301 and not show the image to other users. Obviously, though, there's no reliable way to know that someone came over from a 301. We do know, given our architecture, if a page is the redirect point for a 301, so on the request, we check three things - page is a 301 target, referrer is null and, because it's an interior page, if the session is new.While this sounded great in theory, it's not awesome. Two primary sources of traffic are now configured to hit that interior page directly and, of course, the image is showing when we don't want it to.How bad would it be for SEO purposes, to change my existing 301s like this:orig: http://example.com 301 to http://foo.com/interiorpagenew: http://example.com 301 to http://foo.com/interiorpage?showimageGiven that the original 301s have already been crawled, am I damaging my juice by adding that querystring now? The parameterless url is canonical. The only difference in content is the visibility of an image that exists on both versions of the page.
301 redirects, query strings and SEO
seo;url;301 redirect;url rewriting
we check three things - page is a 301 target, referrer is null and, ...The referrer is not necessarily empty for a 301 redirect. Is this something unique to your architecture? If so, how do you enforce this?Assuming you have the appropriate rel=canonical set then the query string option is the one I'd go for. However, if the original 301s have already been crawled then it might not have an effect for very long, unless users are accessing these URLs in other ways. But I can't see this causing any problems in terms of search engine ranking.
_codereview.138989
I am practicing my coding at HackerRank. The exact problem statement can be found here, but to summarize, it is finding the distances of the shortest path from a starting node to every other node in a non-directional graph where every edge is weighted 6. If a node is unreachable, the distance is -1. The nodes are named 1 to n. If you want an example, please see the provided one in the link.To solve this, I googled an explanation of Dijkstra's Algorithm and tried my best to implement it (I am new to graph problems). My program passes 6/7 of the test cases, but it times out on the 7th. I improved some small inefficiencies, but it wasn't enough. Please advise me on how I may make the following faster:def shortest (start, nodes, adj): unique = [] #this part is pretty standard for this Algorithm I think distance = [float('inf')]*nodes for i in range(1, nodes+1): if (len(adj[i-1])>0): unique.append(i) distance [start-1] = 0 while (len(unique)>0): minDist = float('inf') for i in unique: if (distance[i-1] <= minDist): minDist = distance[i-1] distIndex = i current = distIndex #sets the current node as the closest unvisited node unique.remove(current) for i in adj[current-1]: #updates the distance of each neighbour of the current node neigh = i temp = 6 + distance[current-1] #edges are 6 if temp < distance[neigh-1]: distance[neigh-1] = temp return distance q = int(input()) #each test case contains multiple problems, so just consider one iterationfor i in range(q): a = [] #for input purposes b = [] #for output purposes node = 0 edge = 0 #start of input node, edge = list(map(int, input().strip().split())) #the input begins with the number of nodes and edges in the graph for j in range(edge): a.append(list(map(int, input().strip().split()))) #reading the edges, which are all inputted next starting = int(input()) #reading the starting node #end of input adj = [[] for x in range(node)] #the adjacency matrix for j in a: #making the adjacency matrix from the inputted edges adj[j[0]-1].append(j[1]) adj[j[1]-1].append(j[0]) for j in adj: j = list(set(j)) #someone warned that the problematic test case gives the same edge many times, so this is to remove duplicates b = shortest(starting, node, adj) #formatting the output to what the question required b.remove(0) for i in range(len(b)): if b[i] == float('inf'): b[i] = -1 print ( .join(str(e) for e in b))If it helps, I 'purchased' the test case which is timing out.
My attempt at Dijkstra's Algorithm in Python 3
python;python 3.x;graph;time limit exceeded
Those comments are very difficult to read.j = list(set(j)) #someone warned that the problematic test case gives the same edge many times, so this is to remove duplicatesFormat this properly:# The problematic test case gives the same edge many times,# so this is to remove duplicatesj = list(set(j))Then remove fluff:# Remove duplicates. Helps some test cases.j = list(set(j))In this case just remove the first comment, because list(set(...)) is already known to mean deduplicate. And remove the second since it's implied by the fact you've written the code.j = list(set(j))Another pair isa = [] # for input purposesb = [] # for output purposesDon't do this. Just call themdescriptive_name_1 = []descriptive_name_2 = []so you don't need the comment in the first place.Then there's q = .... So I wrack my brain thinking about what word contains q. But it turns out you just meant to write num_test_cases. What does that have to do with the letter q?Worse than that is when you outright lie. What would you expect the variable node to contain? A node, right? Nope - it contains the total number of nodes.And you writenode = 0so we expect the total number of nodes to be 0 at that point, right? Nope, you immediately change your mind and writenode, edge = list(map(int, input().strip().split()))But OK, fine. At least we know what nodes contains, then: multiple nodes, so a list (or other collection) of lengths of nodes.Nope, it actually means exactly the same thing as node.A similar comment goes for edge, which should be num_edges.Then there's adj, which you label adjacency matrix. Why not just call it adjacency_matrix then? But it's not even a dense matrix like that would imply, it's actually a list of per-node adjacencies, so call it adjacencies.Then there's starting and start, which are the same thing named differently. Call them start_node or at least be consistent.Going back to b, you haveb = []but again this is a lie, because actuallyb = shortest(start_node, num_nodes, adjacencies)So just write that.distances = shortest(start_node, num_nodes, adjacencies)For a, initialize it as close to usage as possible and call it edges.If you writefor j in range(num_edges):you're misleading me into thinking you're going to use the index. When you're not going to, writefor _ in range(num_edges):And what's up with that, followed byfor j in edges:followed byfor j in adjacencies:Is j just your general this is a thing variable? Most people use x, elem and item for that. Instead, writefor _ in range(num_edges):for edge in edges:for adjacent in adjacencies:The middle can befor start, end in edges:The comment#edges are 6Isn't coherent. Try# Edges are length 6Instead, though, don't put this information in shortest - use 1 and multiply out when using the results.Don't call variables temp. It's a poor name.You've double-indented the part where you update the neighbours.Note thatnum_nodes, num_edges = list(map(int, input().strip().split()))is justnum_nodes, num_edges = map(int, input().strip().split())Why do you do this?for i in adjacencies[current-1]: neigh = iJust writefor neighbour in adjacencies[current-1]:And the content can befor neighbour in adjacencies[current-1]: distance[neighbour-1] = min(distance[neighbour-1], distance[current-1] + 1)Do you not think this whole -1 thing is getting a bit silly? When reading, just decrement the edge values and starting edge correctly:edges = []for _ in range(num_edges): start, end = map(int, input().strip().split()) edges.append((start - 1, end - 1))start_node = int(input()) - 1while loops and if statements don't need their condition parenthesized, and operators should be spaced properly:while (len(unique)>0): # beforewhile len(unique) > 0: # afterThen this is better as just while unique.Don't put spaces before the parentheses in function calls or indexing.minDist should be min_dist. You can also start with it set to num_nodes, and the same for distance's initialization.unique is a horrible name, and has nothing to do with the variable's purpose. Try unvisited instead. It can be initialized asunvisited = [i for i, adj in enumerate(adjacencies) if adj]distance, unsurprisingly, does not mean distance but instead distances. Fix that.This code:min_dist = num_nodesfor i in unvisited: if distances[i] <= min_dist: min_dist = distances[i] distIndex = icurrent = distIndexis justmin_dist = num_nodesfor i in unvisited: if distances[i] <= min_dist: min_dist = distances[i] current = iand current should be called closest. It is simplifiable toclosest = min(unvisited, key=lambda x: distances[x])This is faster if you writeclosest = min(unvisited, key=distances.__getitem__)but the difference isn't vital.One last thing with shortest - rename it to shortest_distances.Put the rest of the code in a main function.If you writedef read_pair(decrement): x, _, y = input().partition( ) return int(x) - decrement, int(y) - decrementthen you can initialize num_nodes, num_edges and edges withnum_nodes, num_edges = read_pair(0)edges = [read_pair(1) for i in range(num_edges)]Note my use of partition instead of split as IMO it's a better description of the operation here.Thenfor adjacent in adjacencies: adjacent = list(set(adjacent))doesn't actually work! adjacent = only affects the local scope! Instead, you wantadjacencies = [list(set(adj)) for adj in adjacencies]which is even better asadjacencies = [set() for _ in range(num_nodes)]for start, end in edges: adjacencies[start].add(end) adjacencies[end].add(start)as you never have the large intermediates then, and there's no real point converting back from a set.This stuff:distances.remove(0)for i in range(len(distances)): if distances[i] == num_nodes: distances[i] = -1 else: distances[i] *= 6print( .join(str(e) for e in distances))is justprint(*(-1 if i == num_nodes else i * 6 for i in distances if i))Nice, that seems to have made it fast enough, but more important the code is more readable.We can improve speed further by avoiding input, using sys.stdin directly to get buffering.def main(lines): def read_pair(decrement): x, _, y = next(lines).partition( ) return int(x) - decrement, int(y) - decrement ...main(sys.stdin)Note that this change is sufficient on its own to beat the time limit: you can apply it to your original code to pass the test. Note also that you shouldn't mix input with next; at least on Python 2 this throws an error sayingValueError: Mixing iteration and read methods would lose dataThough this error is gone in Python 3, that doesn't leave me feeling good about it.I'd finish off withfrom __future__ import print_functionto make it Python 2 compatible.from __future__ import print_functionimport sysdef shortest_distances(start_node, num_nodes, adjacencies): distances = [num_nodes] * num_nodes unvisited = [i for i, adj in enumerate(adjacencies) if adj] distances[start_node] = 0 while unvisited: closest = min(unvisited, key=distances.__getitem__) unvisited.remove(closest) # Update the distances of each neighbour for neighbour in adjacencies[closest]: distances[neighbour] = min(distances[neighbour], distances[closest] + 1) return distancesdef main(lines): def read_pair(decrement): x, _, y = next(lines).partition( ) return int(x) - decrement, int(y) - decrement num_test_cases = int(next(lines)) for i in range(num_test_cases): num_nodes, num_edges = read_pair(0) edges = [read_pair(1) for i in range(num_edges)] start_node = int(next(lines)) - 1 adjacencies = [set() for _ in range(num_nodes)] for start, end in edges: adjacencies[start].add(end) adjacencies[end].add(start) distances = shortest_distances(start_node, num_nodes, adjacencies) print(*(-1 if i == num_nodes else i * 6 for i in distances if i))main(sys.stdin)
_webapps.69906
I recently started trying out the new Inbox app from Google. While it generally works side by side with Gmail, there is one thing I can't find a parallel for in Gmail.When a mail (or reminder) is snoozed in Inbox, it is removed from the inbox but can be found in Inbox by opening the Snoozed label, thus listing the snoozed items. However, looking at Gmail the snoozed items seem only visible in the All Mail view, where they are mixed in with other mail that's archived or still in the inbox but there doesn't seem to be a Snoozed label that would let me view only the snoozed items. Is this simply a missing feature still to come, or is there some way I've missed that would let me view just the snoozed items within traditional Gmail?
How to find an email in Gmail that was snoozed in Google Inbox?
gmail;email;inbox by gmail
Searching for label:snoozed lists Inbox snoozed emails in Gmail. But snoozed does not seem to behave like any normal label in gmail as you can not apply it other emails.
_softwareengineering.78625
Let's say I want to initiate publication of some source code under an open-source license like Apache or MIT, but I know that I'm only the Creator of the source code in its initial form, and I'm unlikely to be the one who maintains it long term. I just want to get it out there and make sure it's free for others to use per one of these licenses.What do I need to do as far as copyright statement? Do I need to put my name or company down in order for the open-source license to apply? Is there a way that source code can be published anonymously, or without a designated owner?Alternatively, if I put my name or company down, can this ownership be reassigned later?
does correctly applying an open-source license require designating a copyright holder?
open source;licensing
null
_hardwarecs.1717
It's the second time I read a praise or speculation about how Lightning-connected headphones will improve audiophile experience, this time in English:Apple's Lightning connector standard across modern iPods, iPhones, and iPads could be the catalyst for a dramatic change. There are already Lightning headphones from Philips and Audeze, whose advantage over conventional wired cans is in sending a digital signal to an integrated amp and converter inside the headphones.The Verge: What to expect CES 2016Is a mobile audiophile experience possible and practical?Does Lightning play a key role?
Headphones: 3.5mm, Bluetooth or Lightning-connected?
audio;headphones
null
_softwareengineering.166212
I am trying to come up with a decent Adjacency List graph implementation so I can start tooling around with all kinds of graph problems and algorithms like traveling salesman and other problems... But I can't seem to come up with a decent implementation. This is probably because I am trying to dust the cobwebs off my data structures class. But what I have so far... and this is implemented in Java... is basically an edgeNode class that has a generic type and a weight-in the event the graph is indeed weighted.public class edgeNode<E> { private E y; private int weight; //... getters and setters as well as constructors...}I have a graph class that has a list of edges a value for the number of Vertices and and an int value for edges as well as a boolean value for whether or not it is directed. The brings up my first question, if the graph is indeed directed, shouldn't I have a value in my edgeNode class? Or would I just need to add another vertices to my LinkedList? That would imply that a directed graph is 2X as big as an undirected graph wouldn't it? public class graph { private List<edgeNode<?>> edges; private int nVertices; private int nEdges; private boolean directed; //... getters and setters as well as constructors...}Finally does anybody have a standard way of initializing there graph? I was thinking of reading in a pipe-delimited file but that is so 1997.public graph GenereateGraph(boolean directed, String file){ List<edgeNode<?>> edges; graph g; try{ int count = 0; String line; FileReader input = new FileReader(C:\\Users\\derekww\\Documents\\JavaEE Projects\\graphFile); BufferedReader bufRead = new BufferedReader(input); line = bufRead.readLine(); count++; edges = new ArrayList<edgeNode<?>>(); while(line != null){ line = bufRead.readLine(); Object edgeInfo = line.split(|)[0]; int weight = Integer.parseInt(line.split(|)[1]); edgeNode<String> e = new edgeNode<String>((String) edges.add(e); } return g; } catch(Exception e){ return null; } }I guess when I am adding edges if boolean is true I would be adding a second edge. So far, this all depends on the file I write. So if I wrote a file with the following Vertices and weights...Buffalo | 18 br Pittsburgh | 20 br New York | 15 br D.C | 45 brI would obviously load them into my list of edges, but how can I represent one vertices connected to the other... so on... I would need the opposite vertices? Say I was representing Highways connected to each city weighted and un-directed (each edge is bi-directional with weights in some fictional distance unit)... Would my implementation be the best way to do that?I found this tutorial online Graph Tutorial that has a connector object. This appears to me be a collection of vertices pointing to each other. So you would have A and B each with there weights and so on, and you would add this to a list and this list of connectors to your graph... That strikes me as somewhat cumbersome and a little dismissive of the adjacency list concept? Am I wrong and that is a novel solution?This is all inspired by steve skiena's Algorithm Design Manual. Which I have to say is pretty good so far. Thanks for any help you can provide.
Generic Adjacency List Graph implementation
algorithms;data structures
null
_cogsci.6107
I'm talking about Henry Molaison (HM), the famous memory research patient. I hear that he could converse normally with a researcher until he got distracted, at which point he no longer remembered ever meeting the researcher.Molaison was able to remember information over short intervals of time. This was tested in a working memory experiment involving the recall of previously presented numbers; in fact, his performance was no worse than that of control subjects (Smith & Kosslyn, 2007).If distractions were avoided, how long could HM focus and remember the present or task at hand? How long could he talk to researcher before forgetting ever meeting him? I hear that he was tested for hours. During those tests, did he had to be reminded at some time interval about the test procedure?
How long could Henry Molaison keep his memory of the present?
memory;long term memory;working memory
null
_webapps.105189
Is there no way to create a single horizontal rule without creating a Content section and putting a horizontal rule within it? The Content sections are too high ... they seem to be a minimum of 3 lines of text and always have a blank line at the end, so they add a lot of wasted space on a form when I only want a single horizontal rule across the form like this:Some text.Some more text.
Create a single horizontal rule without creating a Content section
cognito forms
null
_webapps.73385
I am receiving posts of a person I do not know. I believe it may have been a mistake and I messaged her to tell her to stop posting to me. I have no idea who this person is. The posts are annoying and cluttering up my page. Please help me.
unknown people posting on my facebook page
facebook
null
_cs.53632
it is well-known that propositional logic problems such as $$ (p\leftrightarrow q) \lor r \quad\overset{?}{\vdash}\quad (((p\lor q)\to(p\land q)) \land \lnot r)\lor r$$can be simply solved by evaluating the corresponding boolean functions for the $2^n$ possible values of the $n$ boolean variables (here $p,q,r$).my question is then : instead of hand-writing such a propositional logic solver, couldn't we search for a program capable of generating such a solver ? what would be then the minimal core / set of concepts and rules needed for a program being capable of ''discovering'' and ''solving'' the propositional calculus ?is it a unsolvable artificial intelligence problem, or would it have some nice solutions, helpful for solving the more interesting higher order logics ?
a program discovering himself how to solve propositional calculus
artificial intelligence;first order logic;propositional logic
null
_unix.351593
Most answers here [1] [2] [3] use a single angle bracket to redirect to /dev/null, like this : command > /dev/nullBut appending to /dev/null works too :command >> /dev/nullExcept for the extra character, is there any reason not to do this ? Is either of these nicer to the underlying implementation of /dev/null ?Edit:The open(2) manpage says lseek is called before each write to a file in append mode:O_APPEND The file is opened in append mode. Before each write(2), the file offset is positioned at the end of the file, as if with lseek(2). The modification of the file offset and the write operation are performed as a single atomic step.which makes me think there might be a tiny performance penalty for using >>. But on the other hand truncating /dev/null seems like an undefined operation according to that document:O_TRUNC If the file already exists and is a regular file and the access mode allows writing (i.e., is O_RDWR or O_WRONLY) it will be truncated to length 0. If the file is a FIFO or terminal device file, the O_TRUNC flag is ignored. Otherwise, the effect of O_TRUNC is unspecified.and the POSIX spec says > shall truncate an existing file, but O_TRUNC is implementation-defined for device files and there's no word on how /dev/null should respond to being truncated.So, is truncating /dev/null actually unspecified ? And do the lseek calls have any impact on write performance ?
Should I use single or double angle brackets to redirect to /dev/null?
io redirection;devices
By definition /dev/null sinks anything written to it, so it doesn't matter if you write in append mode or not, it's all discarded. Since it doesn't store the data, there's nothing to append to, really.So in the end, it's just shorter to write > /dev/null with one > sign.As for the edited addition:The open(2) manpage says lseek is called before each write to a file in append mode.If you read closely, you'll see it says (emphasis mine):the file offset is positioned at the end of the file, as if with lseek(2)Meaning, it doesn't (need to) actually call the lseek system call, and the effect is not strictly the same either: calling lseek(fd, SEEK_END, 0); write(fd, buf, size); without O_APPEND isn't the same as a write in append mode, since with separate calls another process could write to the file in between the system calls, trashing the appended data. In append mode, this doesn't happen (except over NFS, which doesn't support real append mode).The text in the standard doesn't mention lseek at that point, only that writes shall go the end of the file.So, is truncating /dev/null actually unspecified?Judging by the scripture you refer to, apparently it's implementation-defined. Meaning that any sane implementation will do the same as with pipes and TTY's, namely, nothing. An insane implementation might do something else, and perhaps truncation might mean something sensible in the case of some other device file.And do the lseek calls have any impact on write performance?Test it. It's the only way to know for sure on a given system. Or read the source to see where the append mode changes the behaviour, if anywhere.
_unix.370719
I want to delete all the text after the second underscore (including the underscore itself), but not on every line. Every of the target lines begin with a pattern (>gi_). EXAMPLE.Input>gi_12_pork_catACGT>gi_34_pink_blueCGTAOutput>gi_12ACGT>gi_34CGTA
Delete everything after second underscore
text processing;command line;bioinformatics
$ awk -F_ 'BEGIN {OFS=_} /^>gi/ {print $1,$2} ! /^>gi/ {print}' input>gi_12ACGT>gi_34CGTA
_webmaster.87058
I want my wordpress blog's subdomain to be hosted on Blogger. My current host is bluehost and I bought domain from Godaddy. Will it work? Why would I like to do this?Because I having something that will work better on Blogger. And I just don't want to buy a new domain for it.Please present your thoughts.
Can I have my Wordpress blog's subdomain hosted on Blogger.com?
web hosting;wordpress;subdomain;godaddy;blogger
null
_webmaster.26248
I found turn.js as a very simple and nice effect to create page flip effect. The problem is that I'm looking for that effect but vertical not horizontal.Does anybody knows any Javascript or what should I modify in that one to get the result I'm looking for?
Vertical page flip effect
looking for a script;javascript;html5;jquery;plugin
null
_unix.335612
I recently upgraded from Fedora 23 to 25, which seems to have broken my display manager configuration.I was using lightdm and was able to switch between 3 GUIs running lightdm by just hitting ctrl+alt+Fn, n being the number of the tty. This started lightdm automatically on each tty I had configured.After the upgrade, lightdm was completely broken. I managed to get it running again by modifying the configuration and changing, I think it was [DefaultSeats] to [Seat:*]. Now it is running, but only on the tty that has exactly the minimum-vt number. So if I set minimum-vt=7, for example it will only run on tty7; the others don't autostart anymore.On tty8-12, I just get a blinking underscore and lightdm doesn't react to the switching according to the logs when running lightdm -d. tty1-6 are normal console ttys.Output of lightdm --show-config (which composes all configurations and shows the one that is ultimately used to start lightdm):[LightDM] minimum-vt=7 user-authority-in-system-dir=true seats=seat0, seat1, seat2 minimum-display-number=0[Seat:*] session-wrapper=/etc/X11/xinit/Xsession xserver-command=X -background none greeter-session=lightdm-gtk-greeter[Seat:seat0]vt=7[Seat:seat1]vt=8[Seat:seat2]vt=8Unfortunately I couldn't find any documentation on the vt= option but it was working on Fedora 23. I read something about a use-vt= option here. But it seems to be something planned and not yet implemented. Here is another post that about the vt option. I tried this configuration, but maybe I'm missing something.Apparently lightdm is ignoring both the vt= and use-vt= options. lightdm -d said that it loaded the configuration for seat0 and it didn't matter to which value I set it, the actual vt remained the minimum-vt= value.I also tried adding -sharevts to the standard xserver-command which left me stuck in the vt that lightdm took me to first. So it may be working like that but I can't switch vt. This may be because of the hard-coded -no-vtswitch option that is automatically passed to the X server, but I'm not sure as I found many configurations in older forum posts that even manually passed that option to X and it was working for them.I'd like to be able to autostart and switch between the GUIs again. I'm also ok with another display manager. I already tried ssdm, but there doesn't seem to be an option for multiple seats at all.
Display manager on multiple tty
fedora;display manager;lightdm
null
_codereview.91644
I am new to C# and develop a configurable PasswordService class. As the code works the next step is to improve the code.Right now there are the following options:Set alpha characters and the number of alpha characters that has to be in the password.Set numeric and the number of numeric characters that has to be in the password.Set non alphanumeric and the number of non alphanumeric characters that has to be in the password.My questions:Is the structure fine as it is?Are the thrown Exceptions and it's message well chosen?What do you think about the generate function yet?Would you add or adjust the options?Are the comments c#/xml valid?How can I improve the password algorithm?Did I miss something else?using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace PasswordGenerator{namespace Utility{namespace Service{ /// <summary> /// This is a configurable password generator. /// </summary> class PasswordService { string sAlphaCharacters; string sNumericCharacters; string sNonAlphanumericCharacters; uint uiNumberOfAlphaCharacters; uint uiNumberOfNumericCharacters; uint uiNumberOfNonAlphanumericCharacters; /// <summary> /// Initializes class with common configuration. /// </summary> public PasswordService() { this.SAlphaCharacters = abcdefghijklmnopqrstuwvxyABCDEFGHIJKLMNOPQRSTUWVXYYZ; this.SNumericCharacters = 0123456789; this.SNonAlphanumericCharacters = !$%&()[]{}=?#; this.UiNumberOfAlphaCharacters = 6; this.UiNumberOfNumericCharacters = 6; this.UiNumberOfNonAlphanumericCharacters = 3; } // Accessor & modifier public string SAlphaCharacters { get { return sAlphaCharacters; } set { System.Text.RegularExpressions.Regex oRegex = new System.Text.RegularExpressions.Regex([^a-zA-Z]{1,}); if (oRegex.IsMatch(value)) { throw new ArgumentException(Value must not contain anything but alpha characters., SAlphaCharacters.set); } sAlphaCharacters = value; } } public string SNumericCharacters { get { return sNumericCharacters; } set { System.Text.RegularExpressions.Regex oRegex = new System.Text.RegularExpressions.Regex([^0-9]{1,}); if (oRegex.IsMatch(value)) { throw new ArgumentException(Value must not contain anything but numeric characters., SNumericCharacters.set); } sNumericCharacters = value; } } public string SNonAlphanumericCharacters { get { return sNonAlphanumericCharacters; } set { System.Text.RegularExpressions.Regex oRegex = new System.Text.RegularExpressions.Regex([a-zA-Z0-9]{1,}); if (oRegex.IsMatch(value)) { throw new ArgumentException(Value must not contain alphanumeric characters., SNonAlphanumericCharacters.set); } sNonAlphanumericCharacters = value; } } public uint UiNumberOfAlphaCharacters { get { return uiNumberOfAlphaCharacters; } set { uiNumberOfAlphaCharacters = value; } } public uint UiNumberOfNumericCharacters { get { return uiNumberOfNumericCharacters; } set { uiNumberOfNumericCharacters = value; } } public uint UiNumberOfNonAlphanumericCharacters { get { return uiNumberOfNonAlphanumericCharacters; } set { uiNumberOfNonAlphanumericCharacters = value; } } /// <summary> /// Chooses randomly characters of given group and returns them. /// </summary> /// <param name=sCharacterGroup>From this character group the chararacters will be choosen.</param> /// <param name=uiNumberOfThisGroup>The amount of characters to choose randomly.</param> /// <returns>One random character of the character group</returns> public string getRandomSubstrOfCharacterGroup(string sCharacterGroup, uint uiNumberOfThisGroup) { Random rnd = new Random(); int iPosition = 0; string sCharacters = ; for (uint ui = 0; ui < uiNumberOfThisGroup; ui++) { iPosition = iPosition = rnd.Next(0, sCharacterGroup.Length); sCharacters += sCharacterGroup.ToCharArray()[iPosition].ToString(); } return sCharacters; } /// <summary> /// Based upon the config a password will be generated and returned. /// </summary> /// <exception cref=InvalidOperationException> /// Thrown when the number of each character group is 0. /// </exception> /// <returns> /// Returns generated password. /// </returns> public string generate() { if (this.UiNumberOfAlphaCharacters == 0 && this.UiNumberOfNumericCharacters == 0 && this.UiNumberOfNonAlphanumericCharacters == 0) { throw new InvalidOperationException(The number of each character group is 0.); } Random oRand = new Random(); string sPassword = ; sPassword += this.getRandomSubstrOfCharacterGroup(this.SAlphaCharacters, this.uiNumberOfAlphaCharacters); sPassword += this.getRandomSubstrOfCharacterGroup(this.SNumericCharacters, this.UiNumberOfNumericCharacters); sPassword += this.getRandomSubstrOfCharacterGroup(this.SNonAlphanumericCharacters, this.UiNumberOfNonAlphanumericCharacters); sPassword = new string(sPassword.ToCharArray().OrderBy(s => (oRand.Next(2) % 2) == 0).ToArray()); return sPassword; } }}}}
C# PasswordService class
c#;error handling;exception
I covered the security problem in another answer; in this answer let's look at more subtle problems.Someone already mentioned that the nested namespaces are unnecessarily verbose, but even with the more compact syntax, things are still not great. We have a class PasswordGenerator.Utility.Service.PasswordService. What is the function of each portion of the namespace? Namespaces are used primarily to organize large bodies of code, and secondarily to mitigate the danger of collisions between your password service and another. So, first, when I see your namespace there with its three levels I assume that there must be hundreds or thousands of classes that you are organizing, that there is a PasswordGenerator.Utility.Foo and PasswordGenerator.Utility.Bar and PasswordGenerator.Blah.Whatever as well -- in short, that three levels are necessary to organize the mass of code you have in there.The standard way to structure a namespace is Organization.FunctionalArea.SubArea -- so, Microsoft.CodeAnalysis.CSharp, for example. The namespace you've come up with seems there only to hold a single class which does exactly what the namespace name says it does. I would be inclined to have a single namespace PasswordUtilities and be done with it.The name PasswordService is vague. What kind of service? Generation? Verification? Entropy measuring? The class relies upon its namespace to make it clear that it is a generator. That's completely backwards. The namespace should be PasswordUtilities and the class should be Generator.Others have already commented on your use of System Hungarian, which Joel and I both noted in 2003 is the bad Hungarian. Neither form of Hungarian should be used in C#.Do not use unsigned integers in C# even for quantities that are logically non-negative. String.Length is signed. Follow its example.Your test for whether a character is alpha is deeply prejudiced towards American usage. If a Greek person wishes their password to be shouldn't they be allowed to do so? If you want to check for alpha-ness, use the methods on char that do so.Follow C# naming conventions public string getRandomSubstrOfCharacterGroupOthers have noted that methods begin with a capital letter in C#.Worse: mthds shd nt cntn abbrvs, u r totes nt a 13yo grl wrtng nts n clss.Why is this method public? It seems to be an implementation detail.The methods name is incorrect. It does not return a random substring. CAB is not a substring of ABCDEFG. CAB is a substring of TAXICAB and CABERNET. sCharacters += sCharacterGroup.ToCharArray()[iPosition].ToString();The ToString is unnecessary. C# automatically calls ToString on your behalf when appending to a string.Others have suggested that StringBuilder would be the better choice here. If the string were likely to be hundreds or thousands of characters, then yes, always use a builder. But for this little thing that is only six or ten characters, no need to worry about it. sPassword = new string(sPassword.ToCharArray().OrderBy(s => (oRand.Next(2) % 2) == 0).ToArray());I cannot for the life of me figure out what this thing is trying to do. It looks like you're trying to shuffle the string, but why are you shuffling it by flipping a coin (Next(2)) then making sure it was either heads or tails (the remainder), then turning the 0 or 1 into true or false, and then sorting the string by heads first? This is a bizarre way to shuffle a string. Can you explain what your logic was here? Maybe there is some good reason for this, and if there is, it should be very clearly explained in the comments.If I wanted to shuffle a string like this then I'd say password = new string(password.ToCharArray().OrderBy(s => random.NextDouble()).ToArray());That is generate a random number between 0 and 1 as the sort key. System.Text.RegularExpressions.Regex oRegex = new System.Text.RegularExpressions.Regex([a-zA-Z0-9]{1,});Notice how completely uninteresting information dominates this statement. Use a using System.Text.RegularExpressions; directive to bring Regex into scope, and then use var to simplify the declaration: var regex = new Regex([a-zA-Z0-9]{1,});
_softwareengineering.209371
I've become a project manager in my company and here is what I've experienced till now:At first, I was trying to keep in shape technically with other developers of the team (about 15 developers) and read as much as I could so that I would know almost everything going on in the project, from architecture, up to syntax consistency.However, soon I realized that it's almost impossible for you to know everything. Therefore it's natural that you fall back in the technical race. Imagine how much work it requires for you to learn Ext JS, Angular JS, BRE, WCF, Enterprise Library for logging, Asterisk, etc. etc. all at the same time. Thus it seems to me that this is not the correct path.I think the formula is: The more people you have to manage, the less technical knowledge you can possess.However, there are problems in not knowing what's going on inside your team technically:You might not understand and detect bottlenecks just the way you would do when you were developingYou might not decide which technology is better at performance and productivityIn case of a technical dispute in team, you might not be able to helpThe more distance you get from code, the less you might understand developer's stress, pressures, and feelings (this is a big concern for me)You might not be able to forecast and predict the time necessary to get a task doneYou loose your passion when a developer talks with enthusiasm about a problem that has been solved, because you don't understand like 40 percent of what he talks about, and the less you know about something, the more boring it might become for youDevelopers would find it harder to explain something to you and they need to speak less technicallyBad developers (rare but existing) might misuse your lesser technical knowledge and cause all sort of problems...This phenomenon probably occurs in any career and profession. However, since the world of development and computer in general is moving forward with more speed (comparing to say, car industry), thus in a short period of time like 6 months you feel that you've fallen back. Version after version, feature after feature, library after library, you got the idea.I saw these questions, and they contain good suggestions.How can I maintain my technical skills after becoming a project manager?How much should my project manager know?How much should my project manager know?Should a manager (or CEO) in an IT company have an IT background to perform in the organization?How can I convince management to deal with technical debt?However, they're based more on personal experience and advises, which is of course good, but might not help that much.Do we have a book, or a well-thought and researched essay on this subject, on how to manage a team of software developers, with lesser technical knowledge than team members? What points should I take into account to lead effectively and make the whole team achieve success?
How to manage with less technical knowledge?
project management;self improvement;technology
null
_datascience.4942
Due to various curses of dimensionality, the accuracy and speed of many of the common predictive techniques degrade on high dimensional data. What are some of the most useful techniques/tricks/heuristics that help deal with high-dimensional data effectively? For example,Do certain statistical/modeling methods perform well on high-dimensional datasets?Can we improve the performance of our predictive models on high-dimensional data by using certain (that define alternative notions of distance) or kernels (that define alternative notions of dot product)?What are the most useful techniques of dimensionality reduction for high-dimensional data?
High-dimensional data: What are useful techniques to know?
machine learning;statistics;dimensionality reduction
null
_softwareengineering.238364
This is probably a damn fool question, for which I apologise, but I can't seem to get the google syntax right to find an answer.Imagine a Property, like this:private int _typepublic int Type{ get { return _type; } set { _type = value; //raise an event in your chosen language or tech CallAFunction(); }}Now, imagine that CallAFunction does some sort of fairly serious heavy lifting in your application, interacting with the database via a repository.It doesn't seem unreasonable to want a unit test for this, to make absolutely sure that Type gets set to whatever you put in and to check that doing so raises the expected event.However, setting the property with a test will call CallAFunction() which means that you're no longer really testing a unit of code as such, and perhaps more importantly that a very simple test for this very simple property might well require more elaborate preparation, including repository mocking, which seems huge overkill. In some cases you could split these apart by having CallAFunction raised via the event. But that's not always the case (I'm using WPF, and the events bubble up to non-testable XAML). What's the best way to split these two interdependent things apart?
Unit-based architecture
design;architecture;unit testing
There are two issues intermingled here.Is it OK to have hidden logic in a setter? This is asked from time to time, and there is no accepted universal answer. It depends on whether the additional thing you do is really an intrinsic part of that property or not.How do I test a method with an expensive external dependency? Here the general opinion is that if your method does stuff via a collaborator, you should either mock that collaborator out, or use it normally while making sure that this does not make your unit test unacceptably slow.
_unix.16754
An ordinally network topology in picture: In words: - server (e.g.: an Ubuntu 10.04 LTS) is connected to the internet through pppoe connection- server is using it's wireless card in AP mode, so it could share the internet connection through wireless to the clients (WPA2/AES/63 char pass)- The server has two ethernet ports: 1-is for the internet(using pppoe); 2-is connected to a gbit switch, were the clients also are connected- The server (10.0.0.1) has a dhcp server (10.0.0.0/8), so the clients automagically got IP addresses, DNS server addresses and gateway addresses- The server has a dns server (10.0.0.1), so the dns queries are cached, (better network speed feeling)- Extra: on the server, there is an OpenVPN server, so the clients can OpenVPN to the server (even if not in the subnet, e.g.: from a netcafe)- ExtraExtra: the server can be configured in two modes: 1-no internet forwarding to any client, just only after it's connects through OpenVPN; 2-internet forwarding to any client and optionally they could use OpenVPN to have a secure/authenticated tunnelQuestion: How I need to configure the server to make this work (permanently, I mean no manual interaction is required after the server reboots, e.g.: the dhcp server starts automatically, internet forwarding is ok, openvpn is started, wifi is working, pppoe connection to the ISP is up, DNS server is working)?Or does anyone has any exact howtos regarding this setup? Or at least part of them?
How to share the internet connection?
linux;networking;iptables
Gentoo Linux has a very nice Home Router Guide in it's Gentoo Linux Documentation: http://www.gentoo.org/doc/en/home-router-howto.xmlMany of the steps can be adapted to use with Ubuntu.
_unix.24045
I am a Linux noob, but I am willing to learn. My immediate objective is to compile a small kernel for my laptop without sacrificing usability. I am familiar with the kernel compilation steps (don't necessarily understand the process). What are the options I can get rid of in menuconfig for a faster, slimmer kernel? I have been using the trial and error method, i.e uncheck unused filesystems and drivers, but this is a painfully slow process. Can somebody point me towards things I should not touch or a better way of going about this process? This little project is for recreation only.System Specs and OS:i7 580M, Radeon HD5850, 8Gb DDR3, MSI Motherboardx86_64 Ubuntu 11.10.
Stripped down Kernel for a Laptop
linux;ubuntu;kernel;compiling
Unchecking filesystems and drivers isn't going to reduce the size of the kernel at all, because they are compiled as modules and only the modules that correspond to hardware that you have are loaded.There are a few features of the kernel that can't be compiled as modules and that you might not be using. Start with Ubuntu's .config, then look through the ones that are compiled in the kernel (y, not m). If you don't understand what a feature is for, leave it alone.Most of the kernel's optional features are optional because you might not want them on an embedded system. Embedded systems have two characteristics: they're small, so not wasting memory on unused code is important, and they have a dedicated purpose, so there are many features that you know you aren't going to need. A PC is a general-purpose device, where you tend to connect lots of third-party hardware and run lots of third-party software. You can't really tell in advance that you're never going to need this or that feature. Mostly, what you'll be able to do without is support for CPU types other than yours and workarounds for bugs in chipsets that you don't have (what few aren't compiled as modules). If you compile a 64-bit kernel, there won't be a lot of those, not nearly as many as a 32-bit x86 kernel where there's quite a bit of historical baggage.In any case, you are not going to gain anything significant. With 8GB of memory, the memory used by the kernel is negligible.If you really want to play around with kernels and other stuff, I suggest getting a hobbyist or utility embedded board (BeagleBoard, Gumstix, SheevaPlug, ).
_cogsci.4163
In Dr. Martin Seligman's book, Learned Optimism: How to Change Your Mind and Your Life, there was mention of a study involving teaching cancer patients to fight learned helplessness.I believe this study commenced around 1990, but could not find any information on the study online. I would like to know if now, more than 20 years later, if the group showed improvements in battling the cancer.
Where to find published results of positive psychology cancer treatment study mentioned in Martin Seligman's book?
neurobiology;reference request;positive psychology;health psychology
null
_hardwarecs.7922
I was all set to buy the One Plus 5 but realised that it doesn't support SD cards or have an FM radio. I looked at the Xiaomi Mi6 as well but that's similarly hobbled.Can anyone recommend a decent spec Android Nougat smartphone, 5 display or bigger with SD card support and an active FM chip please?Budget, as it's been asked below, is up to what those two phones would cost in the EU (450-550)
Android smartphone with SD and FM
android;smartphones
Seeing as your budget supports it, I would recommend the Motorola Moto G5 or the G5 Plus. If you are looking even better that that, the the Motorola Moto Z is pretty good.The reason why I suggest Motorola is because they have NO bloatware and they are fast, very fast. Most of them come standard with multiple gbs of RAM, top end processors etc.They are also very good value for money. For buying, just Google the make and model, and put sim free at the end, unless you intend to buy from the high street.If these options don't suit you, I would suggest using www.gsmarena.com and specify what you want in their advanced search.
_codereview.9377
I have this code: lengths = [] lengths.append(len(self.download_links)) lengths.append(len(self.case_names)) lengths.append(len(self.case_dates)) lengths.append(len(self.docket_numbers)) lengths.append(len(self.neutral_citations)) lengths.append(len(self.precedential_statuses))Unfortunately, any of those object properties can be None, so I need to check each with either an if not None block or a try/except block. Checking each individually will blow up the size and conciseness of the code. I assume there must be a better way for this kind of pattern, right?
Better way to do multiple try/except in Python
python
Firstly, consider whether these shouldn't be None, but instead should be empty lists. Most of the time None is better replaced by something else like an empty list.If that's not an option, you can use a list:for item in [self.download_links, self.case_name...]: if item is not None: length.append( len(item) )or a functiondef add_length(obj): if obj is not None: lengths.append(len(obj))add_length(self.download_links)add_length(self.case_name)...
_unix.38780
I am porting C/pro*c code from UNIX to Linux. The code is: #define __NFDBIT (8 * sizeof(unsigned long))#define __FD_SETSIZ 1024#define __FDSET_LONG (__FD_SETSIZ/__NFDBIT)typedef struct { unsigned long fds_bits [__FDSET_LONG];} __ernel_fd_set;typedef __ernel_fd_set fd_set_1;int main(){ fd_set_1 listen_set; int listen_sd; int socket_id; FD_ZERO(&listen_set); socket_id = t_open(/dev/tcp, O_RDWR|O_NONBLOCK, (struct t_info *) 0); if ( socket_id <0 ) { exit(FAILURE); } return 0;}In UNIX the value of socket_id is > 0 in Linux it is -1. Reason is in UNIX, there is a /dev/tcp. This is not present on Linux. Also in UNIX this tcp file is character special file which is different from normal file. Is there any way to create same character special file in Linux as in UNIX or how to proceed this further?
/dev/tcp not present in Linux
linux;c;tcp
t_open() and its associated /dev/tcp and such are part of the TLI/XTI interface, which lost the battle for TCP/IP APIs to BSD sockets.On Linux, there is a /dev/tcp of sorts. It isn't a real file or kernel device. It's something specially provided by Bash, and it exists only for redirections. This means that even if one were to create an in-kernel /dev/tcp facility, it would be masked in interactive use 99%[*] of the time by the shell.The best solution really is to switch to BSD sockets. Sorry.You might be able to get the strxnet XTI emulation layer to work, but you're better off putting your time into getting off XTI. It's a dead API, unsupported not just on Linux, but also on the BSDs, including OS X. (By the way, the strxnet library won't even build on the BSDs, because it depends on LiS, a component of the Linux kernel. It won't even configure on a stock BSD or OS X system, apparently because it also depends on GNU sed.)[*] I base this wild guess on the fact that Bash is the default shell for non-root users in all Linux distros I've used. You therefore have to go out of your way on Linux, as a rule, to get something other than Bash.
_webapps.22212
When trying log into Facebook, the message comes up: Your computer appears to be infected with a malwareI've tried different browsers, same result with all. Apparently the session thinks my computer is infected. How can the browser know that my computer is infected? I really did not know that it was infected. It's aMac. If that's the case it's only this user. Might be something else the browser is complaining about. I'm on OS X 10.6 with Firefox 8.Update: It turned out that Facebook has shut my accout down without notice, NOT telling me, right. The least they could do is sending me an email telling me but I guess they don't bother. The error message is pointless.
Facebook. Why do I get the Your computer appears to be infected with a malware message?
facebook
Firefox uses Phishing and Malware Protection, which is a Google service. Basically, it checks the sites that you visit against lists of reported phishing and malware sites. This link explains the technical details of the Safe Browsing protocol.Google has an support article on this notice as well.Why does Google think my computer is infected?Some forms of malicious software will alter your computer settings to redirect some or all of your traffic through a proxy controlled by the attacker. When you use Google, the proxy forwards your query to the real Google servers to fetch the search results. If our system detects that a search came through one of these proxies, we display the warning.
_scicomp.26233
I have 4 coupled equations as below and I want to find the evolution of the system in time for parameters Y(x,t), R(x,t), T(x,t) and W(x,t) which are scalars, scalar, vector and tensor in order.the system is 2d( i and j could be 1 or 2.)equations are as below:equationsK, d, a, v and b are constants. Any solution is highly appreciated.could anyone help me? Boundary condition: normal derivatives of R,W,Y and T on the boundary of a square with length L is zero. At t=0, R=r, Y=y and W=T=0.(y and r are some constants)
Discretization and simulation of coupled equations (pde)
nonlinear equations;discretization;nonlinear programming;coupling
null
_softwareengineering.238156
I've been interested in uniqueness types as an alternative to monads in pure functional languages for some time; unfortunately, this is kind of an esoteric area of CS research and online resources about programming with uniqueness types are few and far between.It's obvious how uniqueness types may be used to implement stateful data structures like references (boxes) and arrays, though it escapes me how you might implement other common stateful data structures with them.Is it possible to implement, for example, locking with unique types? Can uniqueness types be used to share mutable data across threads? Is it possible to use unique types to build synchronization primitives (like mutexes), or is message passing necessary?
Using uniqueness types to implement safe parallelism
programming languages;functional programming;type systems;parallelism
null
_unix.284756
I decided to create a vm image of one of the windows desktops using the following commands in ubuntu live cd. /dev/sda is the windows drive to backup. /dev/sdb is the extra drive to store the image.On /dev/sda1$ dd if=/dev/zero of=tempzero.tmp bs=32k$ rm tempzero.tmpUnmounted /dev/sda1 and on /dev/sdb1$ dd conv=sparse if=/dev/sda bs=32k | gzip > backup.img.gzThen restored the image in vmware player. The provisioned hard disk size was set to 510G (actualy physical disk was 500G (actually 468.5G))Restored the image to the hard disk using(i know we could have piped but I encountered out of disk error when using pipe)$ gunzip backup.img.gz$ dd if=backup.img of=/dev/sda bs=32k$ sync$ ntfsfix /dev/sda1Upon booting in the vm I get the following chkdisk error. What mistake did I make?Checking file system on C:The type of the file system is NTFS.One of your disks needs to be checked for consistency. Youmay cancel the disk check, but it is strongly recommendedthat you continue.Windows will now check the disk. Cleaning up minor inconsistencies on the drive.Cleaning up 797 unused index entries from index $SII of file 0x9.Cleaning up 797 unused index entries from index $SDH of file 0x9.Cleaning up 797 unused security descriptors.CHKDSK is verifying Usn Journal...Usn Journal verification completed.CHKDSK discovered free space marked as allocated in themaster file table (MFT) bitmap.Windows has made corrections to the file system. 488375968 KB total disk space. 101373272 KB in 700645 files. 281608 KB in 41598 indexes. 0 KB in bad sectors. 1242632 KB in use by the system. 65536 KB occupied by the log file. 385478456 KB available on disk. 4096 bytes in each allocation unit. 122093992 total allocation units on disk. 96369614 allocation units available on disk.
why does does windows run checkdisk after I clone into a vm disk it using dd?
dd
null
_unix.223229
My piece of code looks like::let ClassZ = {'author': Juchen.Zeng}:function ClassZ.Print_author_name(): echo self.author:endfunction:function ClassZ.Change_author_name(arg1): let self.author = a:arg1:endfunction:call ClassZ.Print_author_name()Juchen.Zeng:call ClassZ.Change_author_name('MarioLuisGarcia'):call ClassZ.Print_author_name()MarioLuisGarciaAnd in vim's official doc, it says: :function uk2nl.translate(line) dict : return join(map(split(a:line), 'get(self, v:val, ???)')) :endfunctionLet's first try it out: :echo uk2nl.translate('three two five one') drie twee ??? eenThe first special thing you notice is the dict at the end of the :functionline. This marks the function as being used from a Dictionary. The selflocal variable will then refer to that Dictionary.Why in my examples, without extra dict argument, the self reference seems work well? Is this dict arg indispensable?
Why my dict methods works well without defining with extra `dict` argument ? [vim]
vim
The dict attribute is dispensable in this case, because defining and assigning function directly to dictionary implied dict attribute for function, using dict attribute is not necessary anymore.That type of functions are called anonymous-function or numbered-function.In your example, you have defined two ClassZ keys, Change_author_name and Print_author_name which have values are Funcref.You can verify it, using function()::function ClassZ.Print_author_name function 394() dict1 echo self.author endfunctionYou can see, a numbered-function - 394 had been created, with dict attribute.
_unix.293624
I attach to a docker image where user has already been created with this command:RUN useradd -r -u 200 -m -c nexus role account -d /nexus-data -s /bin/false nexusI wanted to run a command as this user, but nothing happened. Trying to solve this, I discovered I can't run anything with a user having /bin/false as login:# useradd xxx# su xxx -c 'ls >>/t/t1'# ls /tt1# useradd -s /bin/false# su xxx1 -c 'ls >>/t/t2'# ls /tt1I was expecting that login shell would not matter when calling su without -. I googled and I found out that I can run the command if I add -s /bin/bash, but why is that so? The - option is su means 'use login shell', why is the login shell relevant without -?
Why can't I run a command as a user having /bin/false as login shell?
shell;login;su
null
_cseducators.342
In my experience, people who have programmed before, whether they're professional or not, almost always consider imperative programming to be obvious. They're usually skeptical that a concept such as variable assignment could be difficult to learn.On the other hand, in my limited experience (teaching Programming 101, and with people learning to write simple scripts), students who are beginning to learn about programming do find the concept difficult. Given a program likex := 2;print(x);if some_condition() then x := 3;many students struggle with the concept that print(x) will not print 3 even if some_condition() is true. Writing assignment using = may make the difficulty more widespread.Is difficulty with imperative programming correlated with certain backgrounds? For example, do students with a strong mathematical background struggle more because they have some prior concept of equality? Do students with more computer time struggle less because they're more used to the concept of a state change (even if they can't formulate it in these terms of course)?
What makes imperative programming easier or harder to learn?
imperative programming;programming paradigms
This is a topic very close to my heart. I think that the skeptical attitude you've alluded to simply comes from the fact that most people were taught imperative programming first (and some were never exposed to any other paradigms at all). Turing's Machine was easier to conceive of as a physical, mechanical device than Church's $\lambda$, and it is presumably by this historical accident that mutability rules the day almost everywhere. I am not even remotely convinced that imperative programming is more obvious or intuitive than functional programming. In my experience, setting values is a consistent cognitive trap for students, and one that I have to treat with great care. My very first unit for AP is modeled rather loosely after Tom Rogers' phenomenal opening AP unit, Java Ain't Algebra, which takes exactly this issue head on. In my (by now heavily modified) version of Roger's mini-unit, I make explicit that values can change, spend time tracing them, show why x = 4 + 7 is not the same as x - 4 = 7, and spend a lot of time making clear that the programmer's= is only barely related to the mathematical$=$. We also begin to explore the runtime stack.Teachers often miss that this even needs to be covered because, once they are thoroughly inculcated in imperative programming, it can become hard to even see why this is hard in the first place. The variable x was 4, but now it is 5. What could be simpler? But of course, students exposure to variables prior to CS comes from algebra. And in algebra, when we say that $x + 3 = 7$, we mean that $x = 4$, and it cannot suddenly become $5$. We can solve for values, but we cannot alter them. Here's the takeaway: if we, as teachers, don't make explicit how very different it is to be able to change values, a certain percentage of students don't ever fully pick up this idea. They'll get hazy bits and pieces of the idea, but have trouble operating, and ultimately fall behind.In my experience, they don't appear to get noticeably lost until far later in the year, but by then, it is very hard to get them back on track. (When I take on a new tutee in the months leading up to the AP test, this is one of the first areas I check if they seem generally lost.) I have also come to believe that this is one of the key ideas that most CS teachers miss, and is responsible for a substantial portion of computer science's very bimodal results with students.There is a real cognitive load to considering not the value of x, but the value of x right now, and having to both track that value and figure out when to change it.In spite of what this all sounds like, I'm not suggesting that functional programming is necessarily easier; it has its own cognitive load, since suddenly we are contemplating many, many simultaneous x's taking place during recursive calls. It's almost as if learning to talk to something as alien as a computer is always going to be a bit tricky :)
_cs.56822
If the strings of a language L can be effectively enumerated in lexicographic order then is the statement L is recursive but not necessarily context free is true?
If the strings of a language can be enumerated in lexicographic order, is it recursive?
formal languages;computability;context free;enumeration
null
_webapps.102793
I am using Hotmail (which is now outlook.com) so I am using the web client.Is there any way to get better junk filtering? Like a plugin or a way to make a plugin where I can really manually analyse the mail and filter it myself?The current junk filtering and sweep options are insufficient to filter the torrent of junk I'm getting.
Better Junk filtering for outlook.com
spam prevention;outlook.com
null
_codereview.118795
I'm working on some code right now where the goal is to take in a byte stream and grab the data from the body of a message. The data is 10 bytes long and is meant to be translated into hex. Specifically, the 10 bytes coming in look like 01000200030004000500 or 01010201030104010501 (with implied 0x in front of each).The code does this, but in my opinion it's not very pretty, so I was hoping to get help in improving both my own code and learning about a more effective way of grabbing an uneven amount of bytes (i.e. not the size of a data type for an easy memcpy). I've seen suggestions for using an array, but I wasn't sure if memcopying or endianness changes would complicate its use.case MyMessage:{ std::string s; unsigned int i,j; // bytes are of type unsigned char* // each hex value is 4 bits memcpy(&i, bytes, sizeof(i)); // Bytes 0, 1, 2, 3 i = ntohl(i); // 01000200 or 01010201 memcpy(&j, bytes + 4, sizeof(j)); // Bytes 4, 5, 6, 7 j = ntohl(j); // 03000400 or 03010401 unsigned short k; memcpy(&k, bytes + 8, sizeof(k)); // Bytes 8, 9 k = ntohs(k); // 0500 or 0501 std::ostringstream iS, jS, kS; iS << std::hex << (i); s += 0 + iS.str(); // Have to shove 0 at front when dropped jS << std::hex << (j); s += 0 + jS.str(); kS << std::hex << (k); s += 0 + kS.str(); // In my actual code, these strings are constants if (s == 01000200030004000500) { s = Off; } else if (s == 01010201030104010501) { s = On; } else { s = ERROR; } return s;}
Grabs 10 bytes and converts it into a hex formatted string
c++;performance;converting
null
_softwareengineering.311842
I worked with Ruby on Rails and RESTful api before and now with Django Rest framework. For this question let's say we only consider the case of JSON but not XML. It seems that when we expect an array as a result, if the result is 1 or above, we can happily get back an array with the proper content, but if the result is 0, we don't get back an empty array -- it actually will return a 404 HTTP status code with empty response content? Is this always the case with RESTful resources, and is it true that if we don't define our API as REST or resource, then we can do whatever we want (and return an empty array)?In a way, I think if it is math or functional programming, I would think that if a function returns a set or an array when the number of items is 1 or above, but give you back a null or raise an exception, instead of returning an empty set or empty array, I think it is a little strange behavior. And in the case of recursion, such behavior usually doesn't work, so I wonder if a behavior that is more mathematically correct may be a better behavior. But this question is about RESTful... whether its definition is that it should be 404 with empty response content but cannot be otherwise.
Does RESTful response always return a 404 and empty content when an array is expected but the result is empty?
rest;ruby on rails;django;resources
null
_vi.2003
I have a problem in Vim, and I think it may be in my vimrc file (or have been told it could be my vimrc file).How do I verify this? And if it is my vimrc file, how do I know what exactly it is?
How do I debug my vimrc file?
vimrc
The first thing you want to do is to start Vim with the default settings:vim -u NONE -U NONE -NThe -u NONE prevents Vim from loading your vimrc, -U NONE prevents Vim fromloading your gvimrc, and -N tells Vim to use no-compatible mode (this isn'trequired, but most Vim users are not used to compatible mode).Note that the NONE is required to be in all-caps.In Windows you can add these flags by creating a new shortcut1.If the problem stays, then you know it's not something in your vimrc.If the problem disappears, you now it's caused by something in your vimrcfile.It's not my vimrc!Hurray! Go and ask your question. Be sure to mention that you tried starting Vimwithout a vimrc file!So it's my vimrc, now what?If you haven't already, you probably want to save a backup copy of your vimrcfile first.Check the pluginsThe next thing you probably want to do is disable all plugins first; plugins canalter quite a bit in Vim. If this fixes the problem, then try to find outwhich plugin by re-enabling them one-by-one. After you've found out whichplugin exactly causes the problem, you can try & fix it by reading this plugin'sdocumentation, and/or by asking a question tagged with plugin-<name>.If it's not a plugin, and you don't have any idea what's causing yourproblem, then it's a trial-and-error procedure. Comment out one or more lines inyour vimrc, start Vim, check if the problem occurs, and repeat this procedureuntil the problem stops occurring. The fastest way of doing this is:Comment out (or remove) about half your vimrc file.Restart Vim, or open a new Vim (reloading the vimrc is not good enough, assettings aren't unset).Is the problem now gone? Put back the part you removed out (keeping Vimopen and using undo is useful here) and repeat step 1 on the part you addedback.Does the problem still occur? Go to step 1.In the end you should have a single option or a combination of a few optionsthat causes your problem. You can find out more about any option in Vim byusing::help 'option_name'The quotes are important here, it usually works without them, but sometimesyou end up on the wrong page if you omit them.If you're still confused after reading the help page, you know where to ask aquestion ;-)Footnotes1 For example: on 64 bit Windows, the shortcut would look something like this: C:\Program Files (x86)\Vim\vim74\vim.exe -u NONE -U NONE -N. To create it, right click in File Explorer where you want the shortcut, then select New -> Shortcut and paste the shortcut text. You may need to change the Vim path if your Vim is installed in another location.
_unix.283497
I have a function that is setup to send status updates to anybar.function e --description 'Run command' \ --argument-names command anybar yellow; eval $command; anybar green;endI am trying to find a way wrap all of my commands that I give through cli to fish in this function.Does anyone know if this is possible?
Fish Wrap all commands in a function
fish
Instead of this method, try adding the following to your config.fish:function my_preexec --on-event fish_preexec anybar yellowendfunction my_postexec --on-event fish_postexec anybar greenendThis will run these functions before and after every command, without requiring the potentially-explosive eval.
_webmaster.39947
I have an ASP.net application which I've been playing around with on my Windows 2008 server. I have WordPress installed so that when I visit the server by it's IP address I can visit my hosted website.The WordPress website works fine when I request the site by it's IP, but when I try to debug the ASP.net application in visual studio it opens http://localhost:49219/, where I can see my asp.net website, but even after opening this port and trying to access my application over the net by my server's IP I get the following error: What is strange is that even on my server, I cannot visit the site by typing in http://127.0.0.1:49219/. I'd like to try to get this application on the net but I really have no clue why I can refer to it using localhost but not by IP. Any suggestions?
Localhost vs 127.0.0.1 - Error when referring to own IP address for an application running on IIS
wordpress;asp.net;ip address;localhost;windows server 2008
After playing around for some time, I think I figured it out. The service I was running was on visual studio's debug server, so it was probably redirecting the request for localhost on that port to itself, however 127.0.0.1 probably can't be remapped in the same way. Everything worked correctly after the site was published.
_datascience.18667
I have found the following example online:from keras.datasets import mnistfrom keras.models import Sequential from keras.layers.core import Dense, Activationfrom keras.utils import np_utils(X_train, Y_train), (X_test, Y_test) = mnist.load_data()X_train = X_train.reshape(60000, 784) X_test = X_test.reshape(10000, 784)Y_train = np_utils.to_categorical(Y_train, classes) Y_test = np_utils.to_categorical(Y_test, classes)batch_size = 100 epochs = 15model = Sequential() model.add(Dense(100, input_dim=784)) model.add(Activation('sigmoid')) model.add(Dense(10)) model.add(Activation('softmax'))model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='sgd')model.fit(X_train, Y_train, batch_size=batch_size, epochs=epochs, verbose=1)score = model.evaluate(X_test, Y_test, verbose=1)print('Test accuracy:', score[1])This gives about 95% accuracy, but if I change the sigmoid with the ReLU, I get less than 50% accuracy. Why is that?
ReLU vs sigmoid in mnist example
python;neural network;keras;image classification
null
_cseducators.3196
Bit of history: The Darmouth Basic Manual (1964) follows a common order of exposition: expressions, variables, constants, assignment, tests/loops; calling subprograms being considered an advanced topic (well, the last thing, after using tables).This reminds me of the first version of Fortran, (see preliminary report of 1954) which had no user-defined subroutines/functions at all.So teaching the importance of decomposing code into smaller (reusable) units was not considered a major priority. And as a consequence we had generations of students who wrote functions/subprograms only under coercion.There's a recent paper (2016) about a procedure-oriented approach to teaching programming in C ; the question is, were there similar approaches in the sixties ot seventies?Question: Was this order of topics standard in the 1960s for imperative programming? Bonus points if you can directly link to textbooks that demonstrate your answer.Remark: Counter-examples will certainly by found in the presentation of functional and LOGO programming. In Teaching Children Thinking, by S. Papers, 1971, page 5-2 it is shown that after demonstration of FORWARD 100 and ROTATELEFT 90, the student can write the first (endless recursive) procedureTO CIRCLE FORWARD 100 ROTATELEFT 90 CIRCLEENDHere the procedural aspect comes even before variables, expressions etc.In the famous SICP book (not for innocent children) using Scheme, definition of functions come after expressions and before IF etc. But it comes much later (1985).Partial answer: the ACM Curricula Recommendations for Computer Science, vol 1 (1983) contains the 1968's course contents and outlines. In course B1 (page 21) Introduction to Computing :This outline reflects an order in which the material might be presented [...]2. Basic Programming. Constants identifiers, variables, subscripts, operations, functions, and expressions. Declarations, substitution statements, input-output statements, conditional statements, and complete programs3. Program structure. Procedures, functions, subroutine calling, and formal-actual parameter association. Statement grouping, nested structure of expressions and statements, local versus global variables [....]The book A Fortran Primer (1963) by E.I. Organick starts explaining subroutines and functions at page 89. Last section before 12. Preparation of Punch Card Program Decks. Can be considered as a good textbook for beginners, not a Fortran reference manual. Read it if you miss good old time flowcharts.
Historical standard order of topics in imperative programming textbooks
resource request;resource information;programming paradigms
null
_cstheory.4826
Given a directed acyclic graph with $2n$ nodes how can one determine if there is a path between any of following n pairs of nodes $(1 \rightarrow n+1), \ldots, (n \rightarrow n+n)$? There is a simple algorithm in $O(n \cdot (n + m))$ (where m is the number of edges) by doing a search from each node $1 \ldots n$, but can it be done better?EDIT: I'm looking for existence, not complete paths.
Route existence between n pairs of nodes
ds.algorithms;graph algorithms;directed acyclic graph
null
_unix.108122
Following are the details of my system: Fedora Core-18, i686.I am trying to install ubuntu in the qemu. Following are the commands I executed: qemu-img create ubuntu.img 8Gqemu-system-i386 -hda ubuntu.img -boot d -cdrom ./ubuntu-13.10-desktop-i386.iso -m 512After executing the second command the window pops up and it shows UBUNTU getting started but after that the window just becomes black with no activity. Not sure how to proceed on the same. Any tips/hints where I am going wrong.
Installing Ubuntu-13.0 Desktop in Qemu
ubuntu;virtualization;qemu
null
_codereview.136026
I need to know (for monitoring purposes) the PID of a program immediately before I start it. There could be multiple of the same program launched at the same time, so monitoring ps or top isn't really an option. It dawned on me as I was exploring various bash-related options that I could make use of C's exec functions to try and pull this off. With that in mind, I whipped up this little piece of code:#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <unistd.h>int main(int argc, char **argv){ char **argv_copy; int i; if (argc >= 2) { argv_copy = malloc(argc * sizeof *argv_copy); for (i = 1; i < argc; i++) { argv_copy[i-1] = argv[i]; } argv_copy[argc] = (char *) NULL; printf(%lu\n, (long unsigned) getpid()); execvp(argv[1], argv_copy); } return 0;}It works as expected - it immediately prints out the PID of the process and then loads the actual process I want to run. What I'm not convinced of is the security or robustness of this little hack. I don't need it to be 100% bullet-proof security-wise, but if you can drive an SUV through it I'd like to know.Could I get some advice on these two areas specifically?
Printing the PID of a program immediately before it runs
c;child process
BugThis line: argv_copy[argc] = (char *) NULL;should be: argv_copy[argc-1] = NULL;You are removing one argument so you need to terminate the array at the right place.Copy unneededInstead of: execvp(argv[1], argv_copy);you could do: execvp(argv[1], &argv[1]);and avoid making a copy.
_webapps.78935
I have a sheet in a document with details of hundreds of signups for an event. As part of this event, there are roughly sixty 'centres'. People have signed up through one form, and now I want to allocate them to centres. I've created a new column in the big Master Sheet (where the form submissions are dumped) called Allocated Centres, and a new sheet in the document for each centre - let's use Centre A as an example.I would like to copy the whole row of information from Master Sheet, where the value in the column Allocated Centre is Centre A, to the new sheet created for that centre.
Copying rows to another sheet based on column value
google spreadsheets
This can be done in a couple of ways, depending on how the spreadsheet will evolve later. Copy once, so that after copying the second sheet exists independently of the master (changes in one will not affect the other). For this, select the column with Centre information, choose Data > Filter in the menu, then click the filter dropdown in the first row and select only Centre A in the filter.After this, only the rows with Centre A will be shown. You can copy-paste into the new sheet; only visible cells will be copied. Reference: filtering your data.Put a formula in the second sheet that will update its contents based on whatever changes are made to the master. This can be done with FILTER command: for example, =FILTER('Master Sheet'!A:D, 'Master Sheet'!D:D=Centre A)With this approach, any future edits to the master will propagate to Centre A sheet. You will not be able to edit this data in Centre A sheet.
_vi.6765
I use vim for writing code and often accidentally type this:funciton() {}instead offunction() {}It's irritating and I know vim supports iabbrev for this purpose. But it doesn't work in this case since there is not a space after the word function. Blame our coding standards I guess. But is there a way either out-of-the-box or through a plugin to automatically correct such a thing?
Can vim automatically correct a spelling mistake if the word doesn't end in a space?
abbreviations
As mentioned in the comments, the simple abbreviation iabbr funciton function works on my setup and in vanilla vim, without any need of type space -- it is triggered by the (.Your problem is being caused by some specific configuration/plugin; thus you should follow the procedure described on Vim-FAQ 2.5:2.5. I have a xyz (some) problem with Vim. How do I determine it is a problem with my setup or with Vim? / Have I found a bug in Vim?First, you need to find out, whether the error is in the actual runtime files or any plugin that is distributed with Vim or whether it is a simple side effect of any configuration option from your .vimrc or .gvimrc. So first, start vim like this: vim -u NONE -U NONE -N -i NONEthis starts Vim in nocompatible mode (-N), without reading your viminfo file (-i NONE), without reading any configuration file (-u NONE for not reading .vimrc file and -U NONE for not reading a .gvimrc file) or even plugin.If the error does not occur when starting Vim this way, then the problem is either related to some plugin of yours or some setting in one of your local setup files. You need to find out, what triggers the error, you try starting Vim this way: vim -u NONE -U NONE -NIf the error occurs, the problem is your .viminfo file. Simply delete the viminfo file then. If the error does not occur, try: vim -u ~/.vimrc --noplugin -N -i NONEThis will simply use your .vimrc as configuration file, but not load any plugins. If the error occurs this time, the error is possibly caused by some configuration option inside your .vimrc file. Depending on the length of your vimrc file, it can be quite hard to trace the origin within that file.The best way is to add :finish command in the middle of your .vimrc. Then restart again using the same command line. If the error still occurs, the bug must be caused because of a setting in the first half of your .vimrc. If it doesn't happen, the problematic setting must be in the second half of your .vimrc. So move the :finish command to the middle of that half, of which you know that triggers the error and move your way along, until you find the problematic option. If your .vimrc is 350 lines long, you need at a maximum 9 tries to find the offending line (in practise, this can often be further reduced, since often lines depend on each other).If the problem does not occur, when only loading your .vimrc file, the error must be caused by a plugin or another runtime file (indent autoload or syntax script). Check the output of the :scriptnames command to see what files have been loaded and for each one try to disable each one by one and see which one triggers the bug. Often files that are loaded by vim, have a simple configuration variable to disable them, but you need to check inside each file separately.
_softwareengineering.58824
I am interested in doing some projects that involve heavy use of JavaScript. Namely HTML5 based canvas games, potentially using node.js as well. I am interested in learning modern best practices, tools and resources for JavaScript. JavaScript is tough to research because you end up wading through a lot of really outdated material, hailing from the times that JavaScript was a four letter word. If you are heavily involved in JavaScript programming... What text editor or IDE do you use?What unit testing framework do you use?Do you use Selenium, or something else?What other tools do you use?What communities exist that discuss recent advents in JavaScript?What books do you read/refer to?What blogs do you read?
Good resources and tools for modern, heavy JavaScript development?
tools;javascript;developer tools
null
_unix.20446
Does anyone know of a simple way to produce the PostScript corresponding to a syntax-highlighted version of a source file that can be piped directly to a PostScript printer?As the wording of the question above probably suggests, I'm looking for something that I can run from the command line. I'm thinking of an interaction like:% syntax_highlight <SOURCE_FILE> | lp...with command-line switches as needed, etc.The best I've found so far is a Unix utility called highlight, but it has problems. The most serious of it is that it doesn't have an option to output PostScript directly. (Since highlight does support LaTeX output, I tried to patch together a script that would automate the process of generating the PostScript file via *.tex => *.dvi => *.ps, but the visual appearance of the final result is awful, much worse than it is for the HTML file that highlight generates for the same source code input.)Thanks!
syntax_highlight | lpr
command line;printing;highlighting;postscript
You can use vim.vim -c hardcopy -c quit /path/to/fileThis will print the file and quit immediately. By default, vim prints with syntax highlighting.If you need to print from stdout of some command, you can do this:cat some_file.c | vim -c hardcopy -c 'quit!' -If you want to save the .ps for later, you can do that by adding redirection to the hardcopy command, like so:vim -c 'hardcopy > /path/to/saved.ps' -c 'quit' /path/to/fileVim lets you set lots of printing-related options, so you might want to see the documentation if you want to tweak it. Of course, there are lots of syntax highlighting options as well.
_cs.10228
Lets say I have a global dataset and I run queries over those data set.For example my dataset would be#id, #Name, #Employee, #Birthdate, #number_of_children1, Nick, Nasa, 1982, 12, Jack, Exon, 1985, 53, Tom, ABCD, 1978, 0And I can run queryies on those dataset.sample queries would be* #Query => #Result_ids * (Name starts with A) => [1]* (Birthdate before 1983 and have children ) => [1]I want to store those queries on a data structure and I want to be able to do set operations on those queries like intersection and union. So an example union operation would be.(Birthdate before 1983) intersection (have children) => (Birthdate before 1983 and have children)I also want to be able to findout if one query is subset or superset of another one. For example.(Birthdate before 1983) is superset of (Birthdate before 1980)(Have 3 children) is subset of (Have more than 1 children)(Name = Jack and born in 1980) is subset of (Born before 1990)I will have a program that will have thousands of queries. And it will combine those queries to make more variety of queries. When I have a new query, I will compare it with existing queries to see if I have an exact query in store or have a superset.Can anybody suggest me a data structure that is fast enough to store and operate on those data?
Algorithm for query comparison
databases;data sets
null
_unix.16852
I just downloaded a Ubuntu v10.10 vmware image for Windows. I'm trying to install a web application that can only run on Linux MySQL, Apache and PHP. How do I open a terminal in Ubuntu?
Ubuntu x86 10.10 terminal
ubuntu;command line;terminal
Try: Accessories > Terminal ;-)
_codereview.127917
Please provide constructive criticism for this TinyMCE plugin which allows the user to save the content, or cancel and go back to the original.JS Bin<!DOCTYPE html><html> <head> <meta http-equiv=Content-Type content=text/html; charset=utf-8> <title>Testing</title> <link href=//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/ui-lightness/jquery-ui.css type=text/css rel=stylesheet /> <script src=//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js type=text/javascript></script> <script src=//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js type=text/javascript></script> <script src=//cdn.tinymce.com/4/tinymce.min.js></script> <script type=text/javascript> tinymce._addHTML=function(id,html){ //Is there a better way to do this? var e=this.get(id); document.getElementById(id).innerHTML=html; e.startContent = html; e.setContent(html); //e.save(); //Remove?? } tinymce.PluginManager.add('mysave', function(editor) { function save() { var formObj; formObj = tinymce.DOM.getParent(editor.id, 'form'); if (editor.getParam('mysave_enablewhendirty', true) && !editor.isDirty()) { return; } editor.startContent = editor.getContent(); editor.hide(); //tinymce.triggerSave(); editor.save(); if (editor.getParam('mysave_onsavecallback')) { editor.execCallback('mysave_onsavecallback', editor); editor.nodeChanged(); return; } if (formObj) { editor.setDirty(false); if (!formObj.onsubmit || formObj.onsubmit()) { if (typeof formObj.submit == 'function') { formObj.submit(); } else { displayErrorMessage(editor.translate('Error: Form submit field collision.')); } } editor.nodeChanged(); } else { displayErrorMessage(editor.translate('Error: No form element found.')); } } function displayErrorMessage(message) { editor.notificationManager.open({ text: message, type: 'error' }); } function cancel() { if (editor.getParam('mysave_oncancelconfirmcallback') && editor.isDirty()) { editor.execCallback('mysave_oncancelconfirmcallback', editor, cancelChanges); } else { cancelChanges(); } function cancelChanges() { var h = tinymce.trim(editor.startContent); if (editor.getParam('mysave_oncancelcallback')) { editor.execCallback('mysave_oncancelcallback', editor); } editor.setContent(h); editor.undoManager.clear(); editor.nodeChanged(); //tinymce.triggerSave(); editor.save(); editor.setDirty(false); editor.hide(); } stateToggle.call(mySaveButton); mySaveButton.disabled(true); } function stateToggle() { var self = this; editor.on('nodeChange dirty', function() { self.disabled(editor.getParam('mysave_enablewhendirty', true) && !editor.isDirty()); }); } editor.addCommand('mceMySave', save); editor.addCommand('mceMyCancel', cancel); var mySaveButton; editor.addButton('mysave', { icon: 'save', text: 'Save', title: 'Save changes and close editor', cmd: 'mceMySave', disabled: true, onPostRender: function() { mySaveButton = this; stateToggle.call(this); } }); editor.addButton('mycancel', { icon: 'remove', text: 'Cancel', title: 'Cancel changes and close editor', cmd: 'mceMyCancel', disabled: false }); editor.addShortcut('Meta+S', '', 'mceMySave'); }); </script> <style type=text/css> #box { border: 1px solid; } .section { padding:10px; height:200px;width:800px; } </style> <script type=text/javascript> tinymce.init({ selector: '.content', width : 800, height: 100, toolbar: 'undo redo | bold italic underline strikethrough fontsizeselect | bullist numlist | link | mysave mycancel', plugins: 'spellchecker link paste mysave', //external_plugins: {mysave: /path/to/tinymce/plugin.js}, browser_spellcheck: true, save_enablewhendirty: true, // Enabled by default mysave_oncancelconfirmcallback: function(editor, confirmedCallback) { if (confirm('You have unsaved work. Are you sure you want to cancel?')) { console.log('cancelled'); confirmedCallback(); } else { console.log('cancel cancelled'); } }, mysave_oncancelcallback : function(editor) { console.log('cancel callback'); }, mysave_onsavecallback: function (editor) { console.log('saved'); }, menubar: false, statusbar: false, setup: function(ed) { ed.on('init', function(e) { e.target.hide(); }); } }); $(function() { $(#open).click(function(){$(#dialog).dialog(open);}); $(#dialog).dialog({ autoOpen : false, resizable : false, height : 800, width : 800, modal : true, open : function() { tinymce._addHTML('content1','New text 1 from DB.'); tinymce._addHTML('content2','New text 2 from DB.'); tinymce._addHTML('content3','New text 3 from DB.'); //$('#content1').html('New text 1 from DB.'); //tinymce.get('content1').startContent = 'New text 1 from DB.'; //tinymce.get('content1').setContent(Newer text 1 from DB.); //tinymce.get('content1').save(); //tinyMCE.activeEditor.setContent('Newest text 1 from DB.'); } }); $('a.edit').click(function() { tinymce.get($(this).closest('div.section').find('div.content').attr('id')).show(); }); }); </script> </head> <body> <button id='open'>Open</button> <div id=dialog title=dialog title> <div id=box> <div class=section> <p>Content 1 <a href=# class=edit id=edit1>edit</a></p> <div id=content1 class=content>Original text 1.</div> </div> <div class=section> <p>Content 2 <a href=# class=edit id=edit2>edit</a></p> <div id=content2 class=content>Original text 2.</div> </div> <div class=section> <p>Content 3 <a href=# class=edit id=edit3>edit</a></p> <div id=content3 class=content>Original text 3.</div> </div> </div> </div> </body> </html>
TinyMCE plugin to save with cancel button
javascript;plugin;callback;text editor
null
_codereview.152757
I'm trying to incorporate the advice found in https://docs.python.org/3.5/library/heapq.html in order to make a priority queue implementation (see corresponding section) in a class priorityQ. Not going to reinvent the wheel so i use the the python's heapq implementationclass priorityQ(): import heapq import itertools def __init__(self,mylist): self._entry_finder = {} # mapping of tasks to entries self._counter = itertools.count() # unique sequence count self.REMOVED = '<removed-task>' # placeholder for a removed task if mylist: self.data = [] for element in mylist: priority, count, task = element[0], next(self._counter), element[1] entry = [priority,count,task] self._entry_finder[task] = entry heapq.heappush(self.data,entry) else: self.data = [] def add_task(self,task,priority): if task in self._entry_finder: self.remove_task(task) count = next(self._counter) entry = [priority,count,task] self._entry_finder[task] = entry heapq.heappush(self.data, entry) def remove_task(self,task): 'Mark an existing task as REMOVED. Raise KeyError if not found.' entry = self._entry_finder.pop(task) entry[-1] = self.REMOVED def pop_task(self): while self.data: priority, count, task = heapq.heappop(self.data) if task is not self.REMOVED: del self._entry_finder[task] return task raise KeyError('pop from an empty priority queue')The code as it is seems to solve the implementation challenges listed in 8.5.2 in the link I gave. I just wonder if this is a clean implementation of such a candidate class. Is it better to just implement with the procedural style suggested in the manual and incorporate it in whatever project i'm working on or is it a better practice to make use of a class like the above (or a more refined version of that).PS: I know it's slightly off-topic for this stack exchange site, but i wonder if there is a way around the side effect of having a bunch of deleted-entries residing in the queue after doing a set of priority updates in existing tasks. (Something different than copying/cleaning the entire queue every fixed period of time)
Python priority queue class wrapper
python;object oriented;python 3.x;priority queue
1. ReviewThe code in the post does not work:>>> q = PriorityQueue(())Traceback (most recent call last): File <stdin>, line 1, in <module> File cr152757.py, line 8, in __init__ self._counter = itertools.count() # unique sequence countNameError: name 'itertools' is not definedThe problem is that itertools was imported in class scope (not at top level) so you need self.itertools (or to move the imports to the top level).The class has no docstring. How am I supposed to use this class?The __init__, add_task and pop_task methods have no docstrings. What arguments do I pass? What do they return?The objects in the queue are described as tasks but priority queues can be used for all sorts of different things for example, the A* search algorithm uses a priority queue containing unexpanded search nodes. I would use a more generic name like item or element, and change add_task to add, remove_task to remove and pop_task to pop.The Python style guide (PEP8) recommends thatClass names should normally use the CapWords convention.So I would call the class PriorityQueue. You're not obliged to follow this guide, but it will make it easier for you to collaborate with other Python programmers if you do.If a class has no superclasses, then you can omit the parentheses from the class declaration.The constructor has a required argument mylist. It would be better if this argument was optional, and if omitted then the constructed queue is empty. This would match the behaviour of other class constructors like queue.PriorityQueue() and collections.deque() which construct empty queues if given no argument.There is a test if mylist: but this is unnecessary because if mylist is an empty list, then both branches have the same behaviour (setting self.data to the empty list). So you might as well omit the test.Once you omitted the test on mylist, it doesn't have to be a list any more any iterable would do. So I would name this argument iterable.It is perverse that the argument to __init__ must be a list of pairs (priority, task) but when calling add_task you have to supply the arguments (task, priority). This seems likely to be the cause of errors.The need for _counter is slightly tricky (it's necessary to break ties in case the items cannot be compared for order), so a comment would be a good idea.self.REMOVED is always the same, so it could be a member of the class. Also, it is only needed for use internally by the class so PEP8 recommends using a name starting with an underscore.Similarly, self.data ought to have a name starting with an underscore.Instead of using element[0] and element[1] here:for element in mylist: priority, count, task = element[0], next(self._counter), element[1] entry = [priority,count,task]use tuple unpacking:for priority, item in iterable: entry = [priority, next(self._counter), item](But see the next item.)The code in __init__ duplicates the code in add_task. So it would be simpler if the former called the latter:for priority, item in iterable: self.add(item, priority)The docstring for remove_task is written from the implementer's point of view: it says, Mark an existing item as REMOVED. But the user does not need to know how removal is implemented: that's an internal detail of the class which the documented API should hide.In pop_task you unpack all the elements of the popped entry:priority, count, item = heapq.heappop(self._data)but priority and count are not used. It is conventional to use the variable name _ for values that go unused.2. Revised codeimport heapqimport itertoolsclass PriorityQueue: Collection of items with priorities, such that items can be efficiently retrieved in order of their priority, and removed. The items must be hashable. _REMOVED = object() # placeholder for a removed entry def __init__(self, iterable=()): Construct a priority queue from the iterable, whose elements are pairs (item, priority) where the items are hashable and the priorities are orderable. self._entry_finder = {} # mapping of items to entries # Iterable generating unique sequence numbers that are used to # break ties in case the items are not orderable. self._counter = itertools.count() self._data = [] for item, priority in iterable: self.add(item, priority) def add(self, item, priority): Add item to the queue with the given priority. If item is already present in the queue then its priority is updated. if item in self._entry_finder: self.remove(item) entry = [priority, next(self._counter), item] self._entry_finder[item] = entry heapq.heappush(self._data, entry) def remove(self, item): Remove item from the queue. Raise KeyError if not found. entry = self._entry_finder.pop(item) entry[-1] = self._REMOVED def pop(self): Remove the item with the lowest priority from the queue and return it. Raise KeyError if the queue is empty. while self._data: _, _, item = heapq.heappop(self._data) if item is not self._REMOVED: del self._entry_finder[item] return item raise KeyError('pop from an empty priority queue')
_codereview.86526
I'm looking for some feedback on my first program. It's a small game you play with matches.It's a two-player game, where the players take turns picking matches (1, 2 or 3) and cannot pick the same number of matches as the other player: if player one picks 2 matches, player two will have to pick either 1 or 3 matches. The player who cannot pick anymore matches loses the game, which means there are two end scenarios : when there are no more matches, or there is 1 but the other player picked 1 during the previous round.Is there a more efficient way to do something (performance-wise or with less code to write)? Can I improve the overall presentation/organization of the code? (am I unaware of a convention?) Any advice or criticism is very welcome.import java.util.Scanner ;public class JeuDeNim2 {public static void main(String[] args) { Scanner sc = new Scanner(System.in) ; int totalMatches ; do { System.out.println(How many matches do you want to play with? + (from 6 to 60)) ; totalMatches = sc.nextInt() ; } while (totalMatches < 6 || totalMatches > 60) ; int matchesThisTurn ; int matchesPreviousTurn = 0 ; int round = 0 ; int player = 0 ; int previousPlayer ; while (true) { round++ ; previousPlayer = player ; player = round % 2 ; if (player == 0) { player = 2 ; } while (true) { if (totalMatches == 1) { System.out.println(There is only one match left on + the table) ; } else { System.out.println(There are + totalMatches + matches on the table) ; } if (round == 1 || round == 2) { System.out.println(Player + player + : How many + matches do you want to pick? (1, 2 or 3)) ; } else { System.out.println(Player + player + : How many + matches do you want to pick this turn?) ; } matchesThisTurn = sc.nextInt() ; if (matchesThisTurn < 1 || matchesThisTurn > 3) { System.out.println(Wrong entry: you have to pick 1, 2 + or 3 matches) ; continue ; } if (matchesThisTurn == matchesPreviousTurn) { System.out.println(You cannot pick the same number of + matches as Player + previousPlayer) ; continue ; } if (totalMatches == 1 && matchesThisTurn > totalMatches) { System.out.println(You cannot pick + matchesThisTurn + matches: there is only one match left) ; continue ; } if (matchesThisTurn > totalMatches) { System.out.println(You cannot pick + matchesThisTurn + matches: there are only + totalMatches + matches left) ; continue ; } break ; } totalMatches -= matchesThisTurn ; matchesPreviousTurn = matchesThisTurn ; if (totalMatches == 0) { System.out.println(*** There are no more matches! ***) ; break ; } if (totalMatches == 1 && matchesThisTurn == 1) { System.out.println(*** There is only one match left, but + Player + player + already took one! ***) ; break ; } } System.out.println(*** The game is over! Player + player + Wins! ***) ;}}
Two-player match-picking game
java;game
Java is an Object Oriented language... and I recognize that objects are not always the right solution to a problem.... The generally accepted opposites of object-orientation, though, are procedural, and functional. It is common (for example, in C) to write code as a collection of procedures, or (in haskell) to write it as functions.In almost no languages, though, is it common to have no procedures, no objects, and no functions... well, except shell scripts, I guess. Your program has no methods, no objects, no functions, except the main method.You need to break your code down in to parts that do logically isolated things, and then call those reusable chunks when needed.Function 1The first function I would extract, is a start-of-game match-count:private static int getStartCount(Scanner sc) { while(true) { System.out.println(How many matches do you want to play with? + (from 6 to 60)) ; int totalMatches = sc.nextInt() ; if (totalMatches >= 6 && totalMatches <= 60) { return totalMatches; } }}Note, in that function I converted it from a do-while loop, to an infinite while-loop, with an early-return if the input is valid. I have nothing against do-while loops, but I find this early-return system simpler in terms of variable management. Note that the int totalMatches has a smaller scope than your code. You can call the code with:int totalMatches = getStartCount(sc);Function 2 (and 3)Right, here's your input issue.... you have a big while loop, that plays each round, and inside that it has a user-input loop. The conditions on that loop are... confusing. What you have, is a prompt, some validation, and if everything is OK, you break. If there's a problem, you loop again. Again, extracting a function with an early return value, would be useful.As an aside, when it comes to user input, it is almost always better to inform the user what input would be valid before requesting the input. Telling them they made a mistake afterwards is great, but telling them what their options are before, is better. Consider these two functions, the first function computes what would be a valid input, the second function uses that information to prompt the user:private static int[] computeAllow(int totalMatches, int previous) { if (totalMatches == 1) { return new int[]{1}; } if (totalMatches == 2 && previous < 3 && previous > 0) { return previous == 1 ? new int[]{2} : new int[]{1}; } switch (previous) { case 0: return new int[]{1,2,3}; case 1: return new int[]{2,3}; case 2: return new int[]{1,3}; case 3: return new int[]{1,2}; } throw new IllegalStateException(Unexpected previous count + previous);}Then, use this function like:private static int getPlayerPick(Scanner sc, int totalMatches, int player, int previous) { if (totalMatches == 1) { System.out.println(There is only one match left on + the table) ; } else { System.out.println(There are + totalMatches + matches on the table) ; } final int[] allow = computeAllow(totalMatches, previous); while (true) { System.out.printf(Player %d: How many matches do you want to pick? %s, player, Arrays.toString(allow)); final int matchesThisTurn = sc.nextInt(); for (int a : allow) { if (a == matchesThisTurn) { // Valid input. return matchesThisTurn; } } System.out.printf(Wrong entry: there are %d matches, + the last player selected %d, + which means you can only select one of %s\n, totalMatches, previous, Arrays.toString(allow)); }}MainPuting this all together, the main method becomes much simpler:public static void main(String[] args) { try (Scanner sc = new Scanner(System.in) ;) { int totalMatches = getStartCount(sc); int matchesPreviousTurn = 0 ; int round = 0 ; int player = 0 ; do { //previousPlayer = player ; player = 1 + (round % 2); round++ ; int matchesThisTurn = getPlayerPick(sc, totalMatches, player, matchesPreviousTurn); totalMatches -= matchesThisTurn ; matchesPreviousTurn = matchesThisTurn ; } while (totalMatches > 1 || totalMatches == 1 && matchesPreviousTurn != 1); System.out.println(*** The game is over! Player + player + Wins! ***) ; }}It is still probably too busy, but you can at least see what's going on now.Note how the user is prompted with valid values before they are entered now:How many matches do you want to play with? (from 6 to 60)10There are 10 matches on the tablePlayer 1: How many matches do you want to pick? [1, 2, 3]4Wrong entry: there are 10 matches, the last player selected 0, which means you can only select one of [1, 2, 3]Player 1: How many matches do you want to pick? [1, 2, 3]2There are 8 matches on the tablePlayer 2: How many matches do you want to pick? [1, 3]2Wrong entry: there are 8 matches, the last player selected 2, which means you can only select one of [1, 3]Player 2: How many matches do you want to pick? [1, 3]3There are 5 matches on the tablePlayer 1: How many matches do you want to pick? [1, 2]3Wrong entry: there are 5 matches, the last player selected 3, which means you can only select one of [1, 2]Player 1: How many matches do you want to pick? [1, 2]2There are 3 matches on the tablePlayer 2: How many matches do you want to pick? [1, 3]1There are 2 matches on the tablePlayer 1: How many matches do you want to pick? [2]2*** The game is over! Player 1 Wins! ***
_cstheory.9706
What is the complexity of precisely finding the square root of a perfect square?
Complexity of finding the square root of a perfect square
cc.complexity theory;ds.algorithms
null
_unix.94429
When digging around in the advanced settings in Dropbox I lost a folder. I only discovered this about a month later. I managed to get this folder back from Dropbox however the file structure of the subfolders have changed dramatically. The current folder now contains two versions of each original subfolder. Currently it looks like this:folder /folder1 /folder11 /folder111 /Folder111 /file1111 /file1112 /file1113 /Folder11 /file111 /file112 /folder12 /Folder12 /folder2 /folder3 So I have lowercase subfolders and I have BumpyCase subfolders. The lowercase subfolders contain subsubfolders and the BumpyCase subfolders contain files. The subsubfolders again contain a lowercase and a BumpyCase version of their respective subfolders. And this story goes on for several levels deep.Fortunately there is no duplication in files, only in folders (same letters but different casing). So on each level I need to merge folders which differ only in the casing of names. And to do this correctly I need to start at the deepest level and work myself up to the top level folder.I want everything to go into the CamelCase directories.The partition where the data is is an Ext4 partition. I have access to several NTFS partitions.Is there a handy Linux command/tool or someone with an idea for a script which could accomplish this? I'm already very happy that I got my stuff back, but the current structure is a big inconvenience.
Merging folders with practically the same name but different casing
command line;shell script;rename;filenames;recursive
null
_unix.327571
There is a file named partner like:abcdefghiThere is another conf file like:part=abcvar=xvar=yid=123part=defvar=zid=345and so on...I am making a shellscript which reads line from 'partner' using while loop, then searches the block containing that partner name in conf file using sed. After that, and finally replacing id value (eg: from 123 to 123_1 )using sed and storing the new block in another file.while read -r var || [[ -n $var ]]do sed -n '/part=$var/,/^$/p' conf.cfg | xargs sed 's/id=123/id=123_1/g' >> new.txtdoneWhat am I doing wrong? As it only gives me empty lines of text as output.
Using sed to find and change information in configuration file
shell script;sed
When using variables in arguments of a command, you can't enclose it in simple quotes.Troubleshooting shell scripts, try running your commands one after the other, ... this would help you narrow down your problem.sed -n /part=$var/,/^$/p conf.cfg
_datascience.14777
I want to do a text classification problem for which I want to train use Adaboost Classifier from sklearn using a Keras estimator. I do know how to use the Keras wrappers for using sklearn functions. So that is not the problem. I have a 3D input data (number_sentences, number_words, features) and when I checked the source code of Adaboost, it shows that X can be only 1D or 2D. Why is that so? Is there any other way for me to use Adaboost for 3D input data?
Adaboost for 3D Input data
machine learning;scikit learn;optimization
null