id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_unix.366157
I have Centos 6.7 running java application via a wrapper programme. So first I ran this.lsof -p 15200 | wc -l and I got the results immediately as 200next I ran this lsof -p 15232 | wc -l I keep taking too long and never generated any results. What other method can I use to get the total open files? I need to know cause my system keep hanging after certain time. I will maybe need to increase the open file size.
lsof command taking too long for a particular process id
centos;lsof
You can get the number files opened by a process identified by a PID, for instance 15232, doing:ls -l /proc/15232/fd | wc -lfrom the Debian lists:I am trying to figure out the meaning of:/proc/$PID/fd/*files.These are links that point to the open files of the process whose pid is $PID. Fd stands for file descriptors, which is an integer that identifies any program input or output in UNIX-like systems.This is also actually where the lsof command drinks the information to give you the files of a process.This is a feature of the linux kernel, and is distribution agnostic.
_webapps.47152
I came across a YouTube whose title was made of use letters that were not part of its logo. Here is the link:http://www.youtube.com/watch?v=oZkgIjJlsxAThese letters are considered part of the text and provide a huge advantage over other videos in terms of visibility.My question is, how did the makers of this video create these giant letters? Is it a special font, or perhaps a hack using some foreign writing system?
How to write in super large letters in an ordinary textfield
youtube;font;text;hack
It is done using block element characters that look like they spell another word: It is actually an ASCII art with the following characters: It can't be used to spell all letters of the alphabet, but you can try. Other characters can help as well.Here I just wrote the first part of your username: I gave up because the R is hard to draw, but I am sure there are some online generators out there.I am not sure YouTube approves of using such tricks, though.
_unix.167852
I have a simple default website configuration located in my sites-available folder in nginx that looks like the one below.When I try browse to /hello I'd expect it to serve the index.html file located in the root folder I specified. Instead, it is trying to get /hello/index.html within the root location I specified.Is there a way to tell nginx to serve the files without prefixing the context path?root /var/...;location / { ...}location /hello/ { root /home/vagrant/public_html/project/dist;}
Why does nginx prefixes the location context path to the root location?
nginx
null
_unix.164229
I'm connected to Internet with a simple ADSL router with NAT. I have a smartphone and a laptop running linux.I need to connect to a IPsec server using OpenSwan. First I tested that it is possible to connect to. I entered connection info into the smartphone and connection was established through the router. Now I see that router is not a problem. And I start to connect my linux laptop:# ipsec auto --up witopia104 witopia #1: STATE_MAIN_I1: initiate010 witopia #1: STATE_MAIN_I1: retransmission; will wait 20s for response010 witopia #1: STATE_MAIN_I1: retransmission; will wait 40s for response010 witopia #1: STATE_MAIN_I1: retransmission; will wait 40s for response...My configuration file /etc/ipsec.d/witopia.conf:conn witopia left=%defaultroute leftid=@witopia leftmodecfgclient=yes leftxauthclient=yes leftxauthusername=W\[email protected] right=ipsec.sanfrancisco.witopia.net rightxauthserver=yes rightmodecfgserver=yes authby=secret auto=addWhat could be wrong here?
Connect to IPsec VPN using OpenSwan
networking;vpn;nat;ipsec;openswan
null
_unix.190653
Sample Input:id,Product1,Product2,Product3,Product41,0.1,0.3,0.8,0.72,0.6,0.7,0.5,0.9I need output as :id,productname,product_val1,Product1,0.11,Product2,0.31,Product3,0.81,Product4,0.72,Product1,0.62.Product2,0.73,Product3,0.5I had tried awk -F, 'NR==1 { for (i=1; i<=NF; i++) sn[i]=$i } NR>1 { for (i=1; i<=NF; i++) print sn[i] , $i;}' filename.csv
Transform .csv into 3 columns and a row
shell;text processing;scripting;csv simple
except for the new headings, which you can easily add, this does it:awk -F, 'NR==1 { for (i=2; i<=NF; i++) sn[i]=$i } NR>1 { for (i=2; i<=NF; i++) print $1 , sn[i] , $i }' filename.csv
_unix.40406
Stardict uses a tray icon , also allows multiple instance of itself , but sadly , i don't use a panel , so no notification area available.But when I hit on close , it minimized to tray , is there a way to find its Window ? if the WId was found , activate this window by sending some X message ? I'm not sure if it's possible. (for hidden windows)Thanks , and please provide a simple bash script
Shell script: find iconized programs , if found , activate it
bash;xorg;window
With wmctrl:wmctrl -a StardictWith xdotool:xdotool windowactivate $(xdotool search --class Stardict)I used Stardict for the window class, check that this is right with xprop (run xprop in a terminal then click on a non-iconified Stardict window and check the WM_CLASS line).
_cstheory.14162
Is there any way to get $n$ primes efficiently? That is, is there any polynomial algorithm for doing this? ($n$ is the cardinality.)Re-phrasing the question:1) Suppose that at the input level, we insert $n$. This is the number of primes we want to obtain. (any set) (So, for example, getting five number of prime. The example output would be 2,3,5,7,11)2) Is there any algorithm that does this efficiently? What would be its complexity (based on $n$)?
An algorithm for getting $n$ primes
cc.complexity theory
null
_unix.218906
I would like to move all the folders contained in the folder /example named e.g. *_jony to a new directory call /jony. I have try several way without success! It would be great to have some helps. Thanks!
Find and move directory to a new directory based on name
find;directory;move
null
_unix.294972
I need to extract more than 2k files from 1000 folders..the problem is, each folder has a zipped folder inside and inside this folder, there is another folder called fileholder which contains some temp.processed filetype that I need to get. Is there any way to search for all these files and copy them to another location? or do I have to extract all of the zip files? I have ran: find -type f -iname \*.PROCESSEDbut that does not search inside the zipped files. Can someone point me to the right direction?
Search for files inside multiple subdirectories and zip directories
shell script;files;find;search;zip
null
_unix.56589
I am quite new to Ubuntu, so I am running into some problems.I was following this tutorial to install Ruby Tests for Sublime Text 2: https://github.com/maltize/sublime-text-2-ruby-testsThere is one point: Make a copy of RubyTest.sublime-settings file to ~/Library/Application Support/Sublime Text 2/Packages/User/ and make your changes.But when I try to copy, I get error that there is no such folder.Can anyone help me?
How to install Ruby Test to Sublime Text 2
ubuntu;software installation;path;ruby
null
_cogsci.15797
Why do we need to break down long sentences that won't immediately scan? Is it an attention thing? Working memory, executive function?For example:Studies show that if there are many stimuli present (especially if they are task-related).... is a straightforward sentence. The only ambiguous term is they. Does it mean studies or stimuli? In this case it is, obviously, stimuli, but the issue seems to be that i need to read the they slower, and am not primed to. What part of cognition is being tested?
Why do we need to break down long sentences to understand them?
linguistics;reading
First off, the difficulty in the specific example given in the question is more a matter of proper writing habits than anything else. The use of parentheses is often discouraged because it disrupts sentence structure and therefore interferes with the flow of information. Secondly, the use of referring words (pronouns) to earlier parts of the sentence are generally encouraged, barred that the pronoun is unambiguous. In the example the pronoun is ambiguous, as both 'stimuli' and 'studies' can be 'task-related'. The cited sentence is therefore a prime example of how not to write a decent English sentence and could be a textbook example for Scientific-English writing courses.In terms of cognition, it is indeed related to working memory, as you need to remember the words in the earlier part of the sentence. Of course attention (vigilance) is needed to extract the information in the sentence. Executive function therefore is involved, as it includes all aforementioned processes.
_codereview.124637
I'm making a photo marker application and need to make a factory pattern for marker. I think it is not very flexible and overall not good.Would you check my code and suggest what could be improved?import Foundationenum MarkerType: String { case Shape, Image}enum MarkerError: ErrorType { case ImageNoExist case ShapeNoExist}struct ImageMarker { static func make(type: String) -> UIImageView { var imageStr: String = switch type { case X: imageStr = close.png break default: break } let image = UIImage(named: imageStr) let tintedImage = image?.imageWithRenderingMode(.AlwaysTemplate) let imageView = UIImageView(image: tintedImage) imageView.tintColor = UIColor.redColor() return imageView }}struct ShapeMarker { static func make(type: String) -> UIView { var shape: UIView = UIView() switch type { case CIRCLE: //shape = CircleView() break default: break } return shape }}typealias Factory = (String) -> AnyObjectclass MarkerHelper { class func factoryFor(type: MarkerType) -> Factory { switch type { case .Shape: return ShapeMarker.make case .Image: return ImageMarker.make } }}
Factory pattern for image or shape marker
ios;swift;abstract factory;uikit
In looking at your code, what I see are a series of effectively global functions that make things based on a string.The object that calls factoryFor must know what the string is in order to know which type of maker to return (after all, if the string is going to be X, then the object that calls factoryFor has to know not to pass Shape.) Also, the caller of the factory function must know what the factory is making in order to correctly cast the AnyObject that is returned.This leads me to wonder what the MakerHelper.factoryFor function's responsibility is? I mean, it's job just seems to be to return the make global function that the caller already knows it wants, so why not just have the caller use the make function directly?It seems to me that you could have written:import UIKitfunc tintedImageViewNamed(name: String) -> UIImageView { let image = UIImage(named: name) let tintedImage = image?.imageWithRenderingMode(.AlwaysTemplate) let imageView = UIImageView(image: tintedImage) imageView.tintColor = UIColor.redColor() return imageView}func make(type: String) -> UIView? /* thanks nhgrif */ { switch type { case CIRCLE: //return CircleView() return UIView() case X: return tintedImageViewNamed(close.png) default: return nil }}The above accomplishes the same thing your code does, is no less safe and no more testable than what you have and it's a lot less complex (which means less chance of bugs.)I'd love to suggest a better solution, but to do that, I would have to better understand what problem you are trying to solve...
_unix.379209
I need to post data like this to an open telnet{ context : 50EF2767, data : { user_status : invisible }, command : setStatus}The data is multiline. I cannot copy-paste it, as telnet treats new lines as Enter. I tried http://telnet-online.net/ and it works fine But I need this for localhost.Is there any telnet client or any way to allow to post multiline data?
Linux telnet client with multiline support
telnet
Try netcat (nc). See http://www.thegeekstuff.com/2012/04/nc-command-examples/?utm_source=feedburner for examples on how to use it.
_softwareengineering.256397
Consider having a project which you would want to release as open-source.There are parts which you have removed, but still remain in version control history. License of those parts is not compatible with the license you intend to use to release the project.How to solve this?Just release source tree as is. Possibly illegal option.Strip changes/modify history to remove unwanted parts. Breaks compatibility with existing copies of repos. Old versions no longer compile, because important part is missing.Create new repo without unwanted parts. Same problems as above.I have a Mercurial in mind, but I think this applies to any DVCS.
Having unwanted bits in version control history
open source;version control
Create a new repo, probably with no old revision history in it.No old versions fail to compile because there are no old versions (and old versions make no sense as you're deleted half of their source code!)This doesn't preclude you from using the old repo yourself, though migrating changes from OSS devs into your copy will require you to manually make a new branch, populate with a copy of their code, and merge rather than simply merge.You could keep the old repo for the historical versions, while they're still needed, and close it to new development.The last idea is still to create a new repo, and populate it with all but the copyright parts. Put those into a different repo that only you have access to.
_unix.116355
I have Red Hat Enterprise Linux 6.5 and I just mounted an SSHFS directory. When I try to browse the mount as my regular user I can't browse it, but as root I can. Believing it was a problem with the UID under which the directory is mounted I listed the mount directory's permissions... and this is what I get.[root@oc2222167007 sshfs]# lldrwxr-xr-x. 1 nekomikoreimu daemon 4096 Jan 14 10:52 cogfvt1[root@oc2222167007 sshfs]# exit[nekomikoreimu@oc2222167007 sshfs]$ llls: cannot access cogfvt1: Permission deniedd?????????? ? ? ? ? ? cogfvt1Why can't I read the directory as user nekomikoreimu when listing it as root clearly says this user is the owner?
Directory mounted under regular user is inaccessible from said user
rhel;sshfs
So after perusing the manpages looking for how to change the remote port to connect to a virtual machine... I found the answer.All I had to do was adding -o allow_other and bam, it worked. Apparently, sshfs assumes you will read the mounted directory under the same user used to mount it, without considering that usually only ROOT is allowed to mount filesystems .-.
_codereview.60250
I'm trying to follow the path of Sandi Metz and others who state that aiming for small and simple is good for writing understandable code. I've written a method that takes care of writing content to a file without overwriting any existing file of the same name. I wrote it TDD style and, once the tests passed, I refactored the rather large methods into smaller methods, hoping that it would improve readability.I hope you can tell me whether I succeeded, or how I could further improve on my code. I've considered adding modules (such as a Appender module) to my class in order to improve the code according to the single responsibility principle, but can't figure out whether it would actually clarify things more, or whether the added lines would make the intended clarification void. class CautiousWriter def self.write(filename, content) if File.exists?(filename) rename_existing_file_beginning_with(filename) end create_file(filename, content) end private def self.rename_existing_file_beginning_with(filename) if File.exists? append_old_to(filename) rename_with_old_and_number_appended(filename) else rename_with_old_appended(filename) end end def self.rename_with_old_and_number_appended(filename) old_and_num_appended = find_available_filename(filename) rename(filename, old_and_num_appended) end def self.find_available_filename(filename) number = 0 until File.exists?(append_old_to(filename) + number.to_s) == false number += 1 end append_old_to(filename) + number.to_s end def self.rename_with_old_appended(filename) rename(filename, append_old_to(filename)) end def self.rename(filename, new_filename) File.rename(filename, new_filename) end def self.create_file(filename, content) File.open(filename, 'w') { |file| file.write(content) } end def self.append_old_to(filename) filename + '_old' endend
Cautious File Writer
beginner;ruby;file;tdd
null
_unix.118891
I've been using VirtualBox (and sometimes VMWare) for years and I've never had any problem with the virtual network adapters, no matter if the physical ones were wired or not.I also played some time ago with KVM in a wired set-up and, although I had to edit some configuration files to get it working, I could also create a bridged adapter without any major problems.Today I decided (wrongly, it seems) to try to use KVM in a laptop running Ubuntu 13.10 and tried to create a virtual machine with bridged networking over a wireless interface. It was extremely painful to set this up.After following all the tutorials I found (for example) and having to reboot my laptop several times to get the connection back I just gave up and went back to my old well-known VirtualBox.And, actually, the first thing I noticed when I looked into the official KVM documentation was that they discourage from trying to bridge a wireless adapter since, according to them: The here shown method, will not work with most(all?) wireless drivers, as these do not support bridging. So, my question is: How come they say that most wireless adapters do not support bridging if it works in VirtualBox and VMWare just out-of-the-box?And what's the difference between these hypervisors that makes it so complicated in KVM, if it works at all?
Wireless bridged networking in KVM. Why is it so complicated?
networking;virtualbox;vmware;kvm;virtualization
Background on KVMI think this is partly due to expectations with KVM. KVM is first and foremost a server product and not a desktop product for virtualization. It can be used in either application but it's definitely suited more for being used on a server. I use it on 3+ hosts at work each hosting 5-10 VMs apiece and it has run flawlessly and is easy to manage, and basically just works.Question #1How come they say that most wireless adapters do not support bridging if it works in VirtualBox and VMWare just out-of-the-box?I believe you're drawing this conclusion from this blurb on the KVM website.WARNING: The here shown method, will not work with most(all?) wireless drivers, as these do not support bridging.This statement is here because it is typically the case. I believe this is often why when you install VirtualBox or VMWare there are typically kernel modules that are getting installed and these products provide their own wrapping around doing this to facilitate making it easier. These products are essentially working around these issues.I believe this issue is also a driver issue. The drivers for WiFi under Linux still pales in comparison to the support that's provided by the Windows drivers for the same hardware. That's just a fact of life.NOTE: I've had wireless NICs in the past that I was not able to put into bridge mode in the past as well. I've typically worked around the issue by either using VirtualBox or getting a different NIC for my laptop.I'll also highlight that neither VirtualBox nor VMware could do this either, at least not until more recent versions. See this as evidence from VMware's KB:If your host has a wireless network adapter, you cannot use bridged networking on Linux hosts in VMware Workstation 5 or lower, VMware Server 1.x, any version of GSX Server, any hosts in VMware Workstation 3 or lower, or in VMware GSX Server 2 or lower. Under these products, if you want to run virtual machines on a host that uses wireless Ethernet adapters, you must configure your virtual machines to use NAT or host-only networking.Source: Using bridged networking with a wireless NIC (760)Question #2And what's the difference between these hypervisors that makes it so complicated in KVM, if it works at all?I can't really shed any light on this particular question, other than to say that if it was easy I imagine this feature would be enabled. I think the crux of the issue has to do with this feature requiring 3 or more groups to coordinate their efforts (hardware manuf., driver devs., Linux kernel, & KVM). These situations are often what results when you need multiple groups to work together in the open source world (IMO)!So can I set it up or what?You can set this up following the directions from either of these 2 articles. The setup requires using a TUN/TAP device which can be put into bridge mode.Bridging a Wireless Card in KVM/QEMUBridge wireless cards
_unix.164872
Let's say I'm trying to lookup the IPs mail.yahoo.com, gmail.com and mail.google.comIf I execute:dig @8.8.8.8 +nocomments +noquestion \ +noauthority +noadditional +nostats +nocmd \ gmail.com mail.yahoo.com mail.google.comI get:gmail.com. 299 IN A 173.194.123.21gmail.com. 299 IN A 173.194.123.22mail.yahoo.com. 0 IN CNAME login.yahoo.com.login.yahoo.com. 0 IN CNAME ats.login.lgg1.b.yahoo.com.ats.login.lgg1.b.yahoo.com. 0 IN CNAME ats.member.g02.yahoodns.net.ats.member.g02.yahoodns.net. 0 IN CNAME any-ats.member.a02.yahoodns.net.any-ats.member.a02.yahoodns.net. 17 IN A 98.139.21.169mail.google.com. 0 IN CNAME googlemail.l.google.com.googlemail.l.google.com. 243 IN A 173.194.123.21googlemail.l.google.com. 243 IN A 173.194.123.22Can I ensure that if I see a CNAME record, the A record corresponding to it won't appear before a CNAME corresponding to another machine or an A record for other hostname?For instance, let me focus on mail.yahoo.com (I just want the IP or IPs mail.yahoo.com resolves to):This is the output:mail.yahoo.com. 0 IN CNAME login.yahoo.com.login.yahoo.com. 0 IN CNAME ats.login.lgg1.b.yahoo.com.ats.login.lgg1.b.yahoo.com. 0 IN CNAME ats.member.g02.yahoodns.net.ats.member.g02.yahoodns.net. 0 IN CNAME any-ats.member.a02.yahoodns.net.any-ats.member.a02.yahoodns.net. 17 IN A 98.139.21.169The hostname I'm looking for ( mail.yahoo.com) is the first column of the first entry. Then there's a bunch of CNAMES I really don't care about, and then an A record with the actual IP (which I do care about).Is there a possibility of getting the CNAMES or A records out of order? Something like:ats.login.lgg1.b.yahoo.com. 0 IN CNAME ats.member.g02.yahoodns.net. #(!)BADats.member.g02.yahoodns.net. 0 IN CNAME any-ats.member.a02.yahoodns.net. #(!)BADmail.yahoo.com. 0 IN CNAME login.yahoo.com.login.yahoo.com. 0 IN CNAME ats.login.lgg1.b.yahoo.com.any-ats.member.a02.yahoodns.net. 17 IN A 98.139.21.169Or even worse (the actual A record on top):any-ats.member.a02.yahoodns.net. 17 IN A 98.139.21.169mail.yahoo.com. 0 IN CNAME login.yahoo.com.login.yahoo.com. 0 IN CNAME ats.login.lgg1.b.yahoo.com.ats.login.lgg1.b.yahoo.com. 0 IN CNAME ats.member.g02.yahoodns.net.ats.member.g02.yahoodns.net. 0 IN CNAME any-ats.member.a02.yahoodns.net.Or the worse of the worse (in a multi-resolution dig execution, as the one shown on top of the post):ats.member.g02.yahoodns.net. 0 IN CNAME any-ats.member.a02.yahoodns.net.any-ats.member.a02.yahoodns.net. 17 IN A 98.139.21.169mail.google.com. 0 IN CNAME googlemail.l.google.com. # This one I wantgmail.com. 299 IN A 173.194.123.21 # This one I wantgmail.com. 299 IN A 173.194.123.22 # This one I wantmail.yahoo.com. 0 IN CNAME login.yahoo.com. # This one I wantlogin.yahoo.com. 0 IN CNAME ats.login.lgg1.b.yahoo.com.ats.login.lgg1.b.yahoo.com. 0 IN CNAME ats.member.g02.yahoodns.net.googlemail.l.google.com. 243 IN A 173.194.123.21googlemail.l.google.com. 243 IN A 173.194.123.22
Dig command: Is the output guaranteed to be sorted?
dns;dig
dig does not reorder the results, it shows them in the order that the nameserver returns them. Nameservers normally shuffle the results (either randomly or round-robin) each time they're queried for a particular record (to implement a simple form of load balancing), although there may be server configuration options that override this. In the case of BIND, the relevant options are rrset-order and sortlist.As far as I can tell, if you perform multiple queries with a single dig invocation, it's as if you had executed dig separately for each name, in that order. I can't imagine why the code wouldn't just loop through them in the order they're on the command line.If the server has to follow CNAME records to get the final answer, the DNS specification says that each alias will be added to the response in the order they're processed. So you're guaranteed that the original name you gave will be first, and the final results will be last.
_reverseengineering.12363
I am using Intel Pin in order trace memory activity of an executable on Windows. What I have found, that most of the memory operands (Read or Write) operates with 2 or 4 bytes. So I decided to modify original Pin's pinatrace example, in order to see which Assembly opcodes produces which memory activity.VOID Instruction(INS ins, VOID *v){ UINT32 memOperands = INS_MemoryOperandCount(ins); fprintf(trace,\n[%s]\n,(INS_Disassemble(ins)).c_str()); for (UINT32 memOp = 0; memOp < memOperands; memOp++) { .....What it basically does (I hope), is just writes disassembled opcode BEFORE the memory operands it produces. But then I looked in the file (W is for write, R is for read):[test edx, 0x800000][jnz 0x77708557][mov dword ptr [ebp-0x4], edi][test dl, 0x1][jnz 0x77703136] RWWRWW [lea edi, ptr [ebx+0xcc]][push dword ptr [edi]][call 0x77702520] RWW [mov edi, edi][push ebp][mov ebp, esp][mov eax, dword ptr [ebp+0x8]][mov ecx, dword ptr fs:[0x18]][lea edx, ptr [eax+0x4]][lock btr dword ptr [edx], 0x0][jnb 0x777041dc][mov ecx, dword ptr [ecx+0x24]][mov dword ptr [eax+0xc], ecx][mov dword ptr [eax+0x8], 0x1][mov eax, 0x1][pop ebp][ret 0x4] WRRRWRWWRRAs we can see, opcodes that are supposed to work with memory (e.g. mov) do not produce memory operands. While memory traces are connected as blocks after ret/call/jnz etc.Question: What kind of memory operands does Intel Pin trace? Is it about calls to virtual memory/RAM/CPU registers? Could it be possible, that memory activity goes in blocks due to CPU's pipeline?
Intel Pin memory operations tracking
disassembly;binary analysis;memory;pintool
So, finally I came up with the solution that works how I want and results seem to be valid according to enter link description herefprintf(trace,\n[%s]\n,(INS_Disassemble(ins)).c_str()); //(INS_Disassemble(ins)).c_str() fflush(trace); for (UINT32 memOp = 0; memOp < memOperands; memOp++) { if (INS_MemoryOperandIsRead(ins, memOp)) { fprintf(trace,R); icount++; } if (INS_MemoryOperandIsWritten(ins, memOp)) { fprintf(trace,W); icount++; } }And it produces the following output:[mov eax, dword ptr [ebp+0x10]]R[mov byte ptr [ebx+0x2], 0x0]W[mov byte ptr [ebx+0x7], 0x0]WI cannot be sure that it is the true sequence of executable under analysis because I do output in the instrumentation phase, but the code can probably be modified it the way to write opcode inside another INS_InsertPredicatedCall, so it will be recorded when it will be executed.
_softwareengineering.273983
I have a modular application written in Java based on NetBeans Modules (those details probably aren't so important :-) ) and I'd like to add another module written in Clojure language. Clojure programs need to have the clojure library accessible.Is it generally a good practice to put such a dependency library to another, separate module so it could be shared by multiple modules? Or do you prefer to pack that library into the module?
Modular application - dependency as separate module?
clojure;modules;netbeans
null
_unix.83687
I have found a website that hosts a few files that I'm after, there's too many to download them all individually. The filenames take a fairly standard and reproduceable form i.e. 1_a, 1_b, 1_c etcIs there a way, using the Linux command line, to use wget to automate downloading them all? I can easily put the filenames in a 1 entry per line text file and direct the command line to look up from there, but it wouldn't be the whole URL, just the bit that changes so the command would need to look something like:wget url.com/files/(bit from file).doc sourcefile.txtAnd basically be able to substitute in an entry from the sourcefile to the bit in the brackets.Also, at one stage a large chunk (a few hundred) of the files are simply sequentially numbered, so could I use a for loop for that bit? If so, how would I do this syntactically in the command line?
Using wget to get file names from a text file
bash;wget
null
_unix.104056
I was running an Ubuntu desktop. The OS was installed on a SSD. I had two additional drives formatted ext4 and mounted on /storage (1TB) and /storage-bak (1.5TB). I installed Centos over Ubuntu on the SSD and the install put a 2.3GB Logical volume on my two storage drives. I didn't want this. I guess I missed something during the Centos install. Centos used the LV to mount /home on it. I booted once and logged in. Not much was written to it.Is there any way to remove the LV and get my drives back to the state they were in.... data intact? I just want a /dev/sdb1 and a /dev/sdc1 so I can mount them as generic EXT4 drives.
How do I recover an ext4 volume overwritten by an LVM logical volume?
partition;lvm;data recovery
null
_webapps.37252
I am locked out of Facebook due to Facebook saying my computer has been infected with malware. I upgraded my Internet Explorer browser to version 9 and ran a security check. Report came back clean and protected. When trying to get back onto my Facebook account, the continue button for removal of malicious extensions does not work. Any other options?
Facebook malicious extension remover
facebook;login
null
_unix.35874
Lately I've been trying to brush up on the math I should have learned in high school. (I didn't pay much attention.) Regarding this, college entrance exams and Octave make a great pair.This morning I got to fractional powers. And Octave had something surprising in store:octave:41> (9 ^ 1/2)ans = 4.5000octave:42> (9 ^ .5)ans = 3octave:43> (9 ^ 0.5)ans = 3Maybe I dozed off when we covered this in high school, but no... According to this website, By the way, some decimal powers can be written as fractional exponents, too. If you are given something like 35.5, recall that 5.5 = 11/2, so:3 ^ 5.5 = 3 ^ 11/2So evidently there's some reason why octave evaluates these two expressions differently...Why does Octave evaluate fractional powers differently? Is this a non-feature, or is there a good reason why it should?
Why does octave give different results for 9 ^ 1/2 and 9 ^ 0.5?
math;octave
I'm no Octave expert, but it look like Octave parses 9 ^ 1/2 as (9^1)/2. That is, the exponentiation operator has a higher priority (binds tighter) than division. Try parenthesizing like this: (9 ^ (1/2)).
_softwareengineering.332252
Rust needs external linkers (e.g. GCC) to generate final output. Why doesn't it provide a bundled one? Are there any languages that does the similar?
Why does Rust require external linkers? Any other similar languages?
compilation;rust
Rust requires a linker to generate final output. It's only external insofar as it is a separate program from the compiler that generates object files.The same is true for most C and C++ compilers, and probably a bunch of other compiled languages, like Swift, Ada and Fortran.Using the system linker instead of bundling your own is useful to ensure compatibility. Sure, Rust could bundle LLD, but what would be the advantage over using the system linker on Linux, or bundling MinGW (which is needed anyway) on Windows and using the LD inside? (Or if you go for the MSVC ABI, you will want a Visual Studio installed anyway, so link.exe is available.)Also, relying on an external compiler driver for the linker invocation simplifies the rustc compiler, since linker invocations tend to be complicated and full of platform-specific black magic. Reimplementing this logic would be a waste of time.
_codereview.144280
I'm working on my first jQuery plugin for a lightweight dropdown. This dropdown behaves just like a ordinary <select>. Before implementing new features I'd like to know if my current approach is clean and efficient (I care about readability and performance)./** * Dropdown plugin. * * @license MIT (https://opensource.org/licenses/MIT) */;(function($, window, document) { 'use strict'; var plugin = 'dropdown', methods = ['open', 'close', 'toggle'], defaults = { onOpen : function() {}, onClose : function() {}, classNames : { dropdown : 'dropdown', menu : 'dropdown__menu', item : 'dropdown__item', open : 'dropdown--open', empty : 'dropdown--empty' } }; // Constructor function Dropdown(element, options) { this.element = element; this.settings = $.extend({}, defaults, options); this.init(); } // Instance $.extend(Dropdown.prototype, { init: function() { var instance = this, $element = $(instance.element), $items = $element.find('.' + instance.settings.classNames.item); // Check if there already is a selection if ($items.filter('.selected').length === 0) { $element.addClass(instance.settings.classNames.empty); } // Bind listeners $element .mousedown(function() { instance.toggle(); }) .keydown(function(e) { switch (e.which) { case 13 : // enter key instance.toggle(); break; case 38 : // arrow up instance.select('prev'); e.preventDefault(); // prevent scroll break; case 40 : // arrow down instance.select('next'); e.preventDefault(); // prevent scroll break; } }) .focusout(function() { instance.close(); }); $items .mousedown(function(e) { instance.select(e.target); }); }, /** * Check the state of the dropdown. * * @param state * @returns {*} */ is: function(state) { var instance = this, $element = $(this.element); return { open: function() { return $element.hasClass(instance.settings.classNames.open); }, empty: function() { return $element.hasClass(instance.settings.classNames.empty); } }[state].apply(); }, /** * Select a dropdown item. * * @param item */ select: function(item) { var instance = this, $element = $(this.element), $items = $element.find('.' + instance.settings.classNames.item), $selected = $items.filter('.selected'), $target; // Check if an element is passed if (typeof item === 'object') { $target = $(item); } else { // Check if we have a selection if ($selected && $selected.length > 0) { if (item === 'next') { $target = $selected.next(); } else if (item === 'prev') { $target = $selected.prev(); } } else { $target = $items.first(); } } // Ensure the target is set and a different element the selected item if ( ! $target || $target.length === 0 || $target[0].isEqualNode($selected[0])) { return false; } // Set classes $element.removeClass(instance.settings.classNames.empty); $selected.removeClass('selected'); $target.addClass('selected'); // Set values $element.find('input, select').val( $target.data('value') ); $element.find('span').first().text( $target.text() ); }, /** * Toggles the dropdown. */ toggle: function() { if (this.is('open')) this.close(); else this.open(); }, /** * Open the dropdown. */ open: function() { var instance = this, $element = $(instance.element); if (instance.is('open')) { return; } $element.addClass(instance.settings.classNames.open); instance.settings.onOpen.call($element[0]); }, /** * Close the dropdown. */ close: function() { var instance = this, $element = $(this.element); if ( ! instance.is('open')) { return; } $element.removeClass(instance.settings.classNames.open); instance.settings.onClose.call($element[0]); } }); // Plugin definition $.fn.dropdown = function(options, args) { return this.each(function() { var $el = this, data = $.data($el, plugin); // Prevent multiple instantiations if ( ! data) { $.data($el, plugin, new Dropdown($el, options)); } else if (typeof options === 'string') { // Attempting to call public method if (data[options] && options.indexOf(methods) === -1) { data[options].apply(data, $.isArray(args) ? args : new Array(args)); } else { console.error(plugin + ': Trying to call a undefined or inaccessible method') } } }); };})(jQuery, window, document);See it in action: Navigational control with the arrows keys seem to not work in the fiddle for some reason. This should work tho./** * Dropdown plugin. * * @package Fundament * @license MIT (https://opensource.org/licenses/MIT) */;(function($, window, document) { 'use strict'; var plugin = 'dropdown', methods = ['open', 'close', 'toggle'], defaults = { onOpen : function() {}, onClose : function() {}, classNames : { dropdown : 'dropdown', menu : 'dropdown__menu', item : 'dropdown__item', open : 'dropdown--open', empty : 'dropdown--empty' } }; // Constructor function Dropdown(element, options) { this.element = element; this.settings = $.extend({}, defaults, options); this.init(); } // Instance $.extend(Dropdown.prototype, { init: function() { var instance = this, $element = $(instance.element), $items = $element.find('.' + instance.settings.classNames.item); // Check if there already is a selection if ($items.filter('.selected').length === 0) { $element.addClass(instance.settings.classNames.empty); } // Bind listeners $element .mousedown(function() { instance.toggle(); }) .keydown(function(e) { switch (e.which) { case 13 : // enter key instance.toggle(); break; case 38 : // arrow up instance.select('prev'); e.preventDefault(); // prevent scroll break; case 40 : // arrow down instance.select('next'); e.preventDefault(); // prevent scroll break; } }) .focusout(function() { instance.close(); }); $items .mousedown(function(e) { instance.select(e.target); }); }, /** * Check the state of the dropdown. * * @param state * @returns {*} */ is: function(state) { var instance = this, $element = $(this.element); return { open: function() { return $element.hasClass(instance.settings.classNames.open); }, empty: function() { return $element.hasClass(instance.settings.classNames.empty); } }[state].apply(); }, /** * Select a dropdown item. * * @param item */ select: function(item) { var instance = this, $element = $(this.element), $items = $element.find('.' + instance.settings.classNames.item), $selected = $items.filter('.selected'), $target; // Check if an element is passed if (typeof item === 'object') { $target = $(item); } else { // Check if we have a selection if ($selected && $selected.length > 0) { if (item === 'next') { $target = $selected.next(); } else if (item === 'prev') { $target = $selected.prev(); } } else { $target = $items.first(); } } // Ensure the target is set and a different element the selected item if ( ! $target || $target.length === 0 || $target[0].isEqualNode($selected[0])) { return false; } // Set classes $element.removeClass(instance.settings.classNames.empty); $selected.removeClass('selected'); $target.addClass('selected'); // Set values $element.find('input, select').val( $target.data('value') ); $element.find('span').first().text( $target.text() ); }, /** * Toggles the dropdown. */ toggle: function() { if (this.is('open')) this.close(); else this.open(); }, /** * Open the dropdown. */ open: function() { var instance = this, $element = $(instance.element); if (instance.is('open')) { return; } $element.addClass(instance.settings.classNames.open); instance.settings.onOpen.call($element[0]); }, /** * Close the dropdown. */ close: function() { var instance = this, $element = $(this.element); if ( ! instance.is('open')) { return; } $element.removeClass(instance.settings.classNames.open); instance.settings.onClose.call($element[0]); } }); // Plugin definition $.fn.dropdown = function(options, args) { return this.each(function() { var $el = this, data = $.data($el, plugin); // Prevent multiple instantiations if ( ! data) { $.data($el, plugin, new Dropdown($el, options)); } else if (typeof options === 'string') { // Attempting to call public method if (data[options] && options.indexOf(methods) === -1) { data[options].apply(data, $.isArray(args) ? args : new Array(args)); } else { console.error(plugin + ': Trying to call a undefined or inaccessible method') } } }); };})(jQuery, window, document);$('.dropdown').dropdown();.dropdown{position:relative;display:block;padding:.625rem .8125rem;padding-right:2rem;font-family:Source Sans Pro,sans-serif;font-size:16px;color:#333;line-height:1.125;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;outline:0;cursor:pointer;border:1px solid #d9d9d9;border-radius:.25rem;background-color:#fff;-webkit-transition:all .25s ease-out;transition:all .25s ease-out}.dropdown>span{pointer-events:none}.dropdown>select{display:none!important}.dropdown:focus{border-color:#49a2bd}.dropdown:after{content: ;position:absolute;top:50%;right:1rem;margin-top:-2.5px;width:0;height:0;border-color:#d9d9d9;border-left:4px solid transparent;border-right:4px solid transparent;border-top:5px solid}.dropdown.dropdown--empty{color:#b3b3b3}.dropdown.dropdown--open{border-color:#49a2bd;border-bottom-left-radius:0;border-bottom-right-radius:0}.dropdown.dropdown--open:after{-webkit-transform:rotate(-180deg);transform:rotate(-180deg)}.dropdown.dropdown--open .dropdown__menu{display:block;border-color:#49a2bd}.dropdown__menu{display:none;position:absolute;top:100%;left:-1px;right:-1px;z-index:1;margin:0;padding:0;max-height:300px;overflow-y:auto;outline:0;list-style:none;border:1px solid #d9d9d9;border-top:0;border-radius:0 0 .25rem .25rem;background-color:#fff;box-shadow:0 3px 4px rgba(0,0,0,.15)}.dropdown__item{display:block;padding:.625rem .8125rem;color:#333;vertical-align:middle;line-height:1.125;border-top:1px solid rgba(0,0,0,.04)}.dropdown__item>.icon{margin-right:.5rem}.dropdown__item.selected{font-weight:700;background-color:rgba(0,0,0,.01)}.dropdown__item:hover{background-color:rgba(0,0,0,.03)}<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script><div class=dropdown> <input type=hidden name=foo> <span>Placeholder</span> <ul class=dropdown__menu> <li class=dropdown__item data-value=1>First option</li> <li class=dropdown__item data-value=2>Second option</li> <li class=dropdown__item data-value=3>Third option</li> <li class=dropdown__item data-value=4>Fourth option</li> <li class=dropdown__item data-value=5>Fifth option</li> </ul></div>
jQuery plugin for a lightweight dropdown
javascript;beginner;jquery;form;plugin
null
_cs.23011
I was solving a problem on topcoder http://community.topcoder.com/stat?c=problem_statement&pm=2402&rd=5009 .There is one example :{ 1, 2, 3, 4, 5, 1, 2, 3, 4, 5 }Returns: 16So my question how its answer is 16 ?
Explain BadNeighbors problem statement
dynamic programming
null
_softwareengineering.236751
I'm in charge of defining an XML schema for some data; the plan is to have various systems (all under our control) upload XML files that match this schema to a central server for processing. I don't have much knowledge of the design of these other systems, so I'm working collaboratively with those system experts to make this XML schema reasonable to both consume (on our side) and produce (on their side).The schema is not entirely clear-cut, and I'm defining the data we want to collect at the same time as defining the schema. There are a million ways to do it so there's a definite do something, think about it, talk to so-and-so, refactor, repeat process in place.All of that said, we have an unfortunate situation where myself and a few others are defining things and a few other developers are implementing it. I'd like to write some code but haven't found the time. This leads to the frustrating cycle whereby the design changes in the ivory tower and then the guys writing the code have to go and change it again and again. Avoiding details for various reasons, the developers writing the implementation aren't in a position to effectively define the requirements of the schema and the data we must collect.Should I be the one writing and playing with this stuff as I figure out how it should be done? This would be ideal to me, but we're under pressure to get things done and it's quicker to have a few people working on it rather than just me.Do we have too many cooks in the kitchen with the XML file providers influencing the schema? Ease of XML file creation should be a consideration of the schema, right?Is there a better way to solve this problem, or is churn a necessary evil when you're trying to fly the plane as you build it?What is the correct development process to apply here which will minimize wasted time?
How to avoid churn when you are defining a schema while others are trying to program against it
development process;requirements management
I am not sure if it is a way to definitively reduce churn and how applicable it would be to your current situation, but these are some things I would try to do - Minimum Viable ProductI am not sure if this is fully relevant to your current situation since it looks like you are already in the middle of things but I am going to put it in anyway since it provides a context to some of the other points.I would push to identify the bare minimum of data needed and try to build the smallest end to end integration possible first. Once that is done it becomes a lot easier to handle further changes as a lot of the initial questions around approach and risk have been addressed. Tight communication loopSince you have mentioned that you are not in a position to work on coding the modification to the systems or building a prototype yourself the next best thing is to work closely with the people who have to do this.While building up the schema specification I would try to keep the communication loop as tight and small as possible. Identify a small team that can handle the project end to end and work closely with them (preferably in the same room).If you have multiple teams for different systems I would identify certain folks from each team and work with them. If the teams are too small for this I would try to get a specific block of time to focus on the schema integration and build it in focussed sprints. Build for easy modification/extensionSince you know this is a rapidly changing and sometimes ambiguous schema it is important to design the schema and the code to generate it such that they can be easily modified.If this is done well, after the initial minimum viable product built out, it would be much easier for the developers to extend the system and reduce the churn time.
_unix.327290
Is there a way to save pid while starting a process? The script should not return to a command line, until started process finishes. And the possibility to end process by Ctrl+C should be kept.
How to start process at foreground saving it's pid to a file?
bash;process
command &echo $! > filefg > /dev/nullIf there's no job control, first turn on monitor mode withset -mMore about monitor mode here: Turning off the monitor mode in Bash.
_cs.54548
I'm surprised that people keep adding new types in type theories but no one seems to mention a minimal theory (or I can't find it). I thought mathaticians love minimal stuff, don't they?If I understand correctly, in a type theory with a impredicative Prop, -abstraction and -types suffice. By saying suffice I mean it could be used as intuitionistic logic. Other types can be defined as following:$$\bot \stackrel{def}{=} \Pi \alpha: Prop. \alpha \\\neg A \stackrel{def}{=} A \to \bot \\A \land B \stackrel{def}{=} \Pi C: Prop. (A \to B \to C) \to C \\A \lor B \stackrel{def}{=} \Pi C: Prop. (A \to C) \to (B \to C) \to C \\\exists_{x: S}(P(x)) \stackrel{def}{=} \Pi \alpha: Prop. (\Pi x: S. P x \to \alpha) \to \alpha \\$$My first question is, do they (, ) really suffice?My second question is, what do we need minimally if we don't have an impredicative Prop, such as in MLTT? In MLTT, Church/Scott/whatever encoding doesn't work.Edit: related
Minimal intuitionistic type theory?
type theory;dependent types
To elaborate on gallais' clarifications, a type theory with impredicative Prop, and dependent types, can be seen as some subsystem of the calculus of constructions, typically close to Church's type theory. The relationship between Church's type theory and the CoC is not that simple, but has been explored, notably by Geuvers excellent article.For most purposes, though, the systems can be seen as equivalent. Then indeed, you can get by with very little, in particular if you're not interested in classical logic, then the only thing you really need is an axiom of infinity: it's not provable in CoC that any types have more than 1 element! But with just an axiom expressing that some type is infinite, say a natural numbers type with the induction principle and the axiom $0\neq 1$, you can get pretty far: most of undergraduate mathematics can be formalized in this system (sort of, it's tough to do some things without the excluded middle).Without impredicative Prop, you need a bit more work. As noted in the comments, an extensional system (a system with functional extensionality in the equality relation) can get by with just $\Sigma$ and $\Pi$-types, $\mathrm{Bool}$, the empty and unit types $\bot$ and $\top$, and W-types. In the intensional setting that's not possible: you need many more inductives. Note that to build useful W-types, you need to be able to build types by elimination over $\mathrm{Bool}$ like so:$$ \mathrm{if}\ b\ \mathrm{then}\ \top\ \mathrm{else}\ \bot $$To do meta-mathematics you'll probably need at least one universe (say, to build a model of Heyting Arithmetic).All this seems like a lot, and it's tempting to look for a simpler system which doesn't have the crazy impredicativity of CoC, but is still relatively easy to write down in a few rules. One recent attempt to do so is the $\Pi\Sigma$ system described by Altenkirch et al. It's not entirely satisfying, since the positivity checking required for consistency isn't a part of the system as is. The meta-theory still needs to be fleshed out as well.A useful overview is the article Is ZF a hack? by Freek Wiedijk, which actually compares the hard numbers on all these systems (number of rules and axioms).
_codereview.162176
The below code works because of the do operator on line 24. Is there a more functional way to get the test to pass, or would you consider this an appropriate use of do?import RxSwiftstruct Token: Equatable { let rawValue: String static func ==(lhs: Token, rhs: Token) -> Bool { return lhs.rawValue == rhs.rawValue }}protocol Login { func getCredentials() -> Observable<(email: String, password: String)> func presentAuthFailure(_ error: Observable<Error>)}protocol Network { func getAuthToken(credentials: (email: String, password: String)) -> Observable<Token>}// MARK: - function Under Testfunc checkCredentials(login: Login, network: Network) -> Observable<Token> { let credentials = login.getCredentials() let token = credentials.flatMap { network.getAuthToken(credentials: $0) } .do(onError: { login.presentAuthFailure(Observable.just($0)) }) // can this be done in some other way? return token.retry()}// MARK: - Test harnessclass MockLogin: Login { func getCredentials() -> Observable<(email: String, password: String)> { assert(_credentials == nil) _credentials = PublishSubject() return _credentials! } func presentAuthFailure(_ error: Observable<Error>) { _ = error.subscribe(onNext: { [unowned self] error in assert(self._error == nil) self._error = error }) } var _credentials: PublishSubject<(email: String, password: String)>? var _error: Error?}class MockNetwork: Network { func getAuthToken(credentials: (email: String, password: String)) -> Observable<Token> { assert(_token == nil) _token = PublishSubject() return _token! } var _token: PublishSubject<Token>?}func testTwoBadAttempts(login: MockLogin, network: MockNetwork) { checkCredentials(login: login, network: network).subscribe() assert(login._credentials != nil) let credentials = (email: foo, password: bar) login._credentials?.onNext(credentials) assert(network._token != nil) let error = NSError(domain: testing, code: -1, userInfo: nil) network._token?.onError(error) assert(login._error != nil) network._token = nil login._error = nil login._credentials?.onNext(credentials) network._token?.onError(error) assert(login._error != nil)}let login = MockLogin()let network = MockNetwork()testTwoBadAttempts(login: login, network: network)
Notify user of credential failure and make another attempt
error handling;swift;authentication;reactive programming;rx swift
null
_webmaster.75968
First, I don't know if it's the right site to post this so sorry if not.I want to create a website which permits users to create events.In a legal and webmaster way, am I responsible if users create illegal events (like racist gathering)?
Allow some illegal gathering without knowing it
administration
To some extend, yes. Your site, your domain, your responsibility.But; I assume you have ToS which tells people not to do hatefull/offensive on your site, with some kind of penalty ((temp)ban, removal, ...). If you check events which are flagged as bad, and delete/cancel those when encounter you shouldn't get in much trouble. I find that You will be held responsible for your own content works well too.If someone reports something bad, and you decide they're correct and delete it, you should be safe.I'm no legal expert, but this has worked for me so far. When someone complains, I review it and send a polite message (whatever their tone might've been!) regarding my actions.
_unix.366642
So today when I attached my wireless keyboard I discovered that other Bluetooth USB adapter (which I used to connect with my headphones, receive files from phone) is not working anymore.When I type lsusb in Terminal I get only one busy spot.Bus 004 Device 004: ID 046d:c534 Logitech, Inc. Unifying Receiver which is the receiver for keyboard and mouse.All others are like this Bus 001 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hubIs there a way to get them both working or make the old one to accept keyboard and mouse also, because I think the receiver doesn't have functionality for all this (file transfer, headphones etc.)?P.S. - I am using Ubuntu 16.04 LTS 32-bit
Two Bluetooth adapters working simultaneously
bluetooth;ubuntu mate
null
_unix.84525
Sometimes when I update my software with yum update, the summary of packages to be updated displays two lists: Updating and Updating for dependencies. The packages in the Updating for dependencies lists were previously installed. Why is there a separate list of packages like this? What does this mean for these packages?
What does yum's Updating for dependencies mean?
fedora;yum
These are run-time dependencies in the packages you're actually trying to update (meaning the software you asked for either uses them directly or uses them indirectly through a secondary package that does use the given dependency). The newer versions of the packages you're trying to go to will sometimes link against specific versions of the software they depend on or be designed with a particular software version in mind so Updating for Dependencies means that in order to have the software you requested be installed/updated it needs to upgrade these other packages otherwise the software you did request may behave erratically (if at all).The analogous concept in the Windows world are software products or patches thereof that require particular service packs already be installed. In other words, the software has a run-time dependency on that service pack.As a more direct example, many applications list glibc as a dependency. If you currently have one version of glibc but try to install a version that was compiled against an updated version, yum will automatically figure out (via metadata) that it needs to update glibc then install the package you asked for.As for why it's itemized separately, it's purely for clarity. If yum just suddenly showed you a huge list of software it was about to install, you might say No, no no, that's not what I asked you to do at all! and think something went wrong (like a bug or something). Itemizing them separately as dependencies let's you know No, everything's fine, we just need to update these packages to get to the one you asked for.IIRC there's also a Install for dependency category which lists new software differently so you can see when it gets introduced through a system update versus just when it forced an update of an already installed package.
_codereview.172398
My code style is capped 128 characters, not 80 characters. This abstract base class constructor initializes some resources which are injected in the implementations. However, I cannot assume that will be always the case, so I used some try catching to and Apache Commons Lang3 Validate to validate my inputs and throw applicable errors. The base class is normally implemented as a stateless ejb, because of the database rollback features. The BusinessConfigurationException extends Exception and is annotated with @ApplicationException(rollback = true), so that these checked exceptions will be thrown without being wrapped in an EJBException and will do a rollback of all database actions correctly./** * BaseController constructor with injectable parameters. * * @param configBundle Configuration parameters for the application. * @param errorsBundle Error messages thrown by the application. * @param em Needs to be injected from implementation. * @param clazz The class that implements the BaseEntity. * @throws BusinessConfigurationException When the property value returns an error somehow. */public BaseController(final ResourceBundle configBundle, final ResourceBundle errorsBundle, final EntityManager em, final Class<T> clazz) throws BusinessConfigurationException { try { Validate.notNull(configBundle); this.baseURI = configBundle.getString(HOST_NAME) + configBundle.getString(APPLICATION_NAME) + configBundle.getString(BASE_PATH); } catch (NullPointerException | MissingResourceException | ClassCastException ex) { log.error(Cannot initialize baseURI in BaseController constructor., ex); throw new BusinessConfigurationException(ex.getMessage()); } try { Validate.notNull(errorsBundle); this.errorsBundle = errorsBundle; } catch (NullPointerException ex) { log.error(Cannot initialize errorsBundle in BaseController constructor., ex); throw new BusinessConfigurationException(ex.getMessage()); } try { Validate.notNull(em); this.em = em; } catch (NullPointerException ex) { log.error(Cannot initialize em in BaseController constructor., ex); throw new BusinessConfigurationException(findErrMsg(EM_NOT_AVAILABLE)); } // No business exceptions thrown for valdidations below. This is a programmer fault. Validate.notNull(clazz); Validate.isAssignableFrom(clazz, BaseEntity.class); this.clazz = clazz; this.resourceName = clazz.getSimpleName().toLowerCase();}
Initializing some resources
java
null
_unix.78063
The scenario: I log on a server using ssh, and search for keywords in a log file using vi.The problem: at the moment, the results of a search is only highlighted by a cursor _ below the searched word, which is not very easy to find on a screen of log messages.The question: how can I change the highlighting of the search results to something more noticeable? e.g. different background and foreground colors on the whole word.
How to change search result highlight in vi?
ssh;vim;vi
Switch to vim, and use :set hlsearchYou can then use :highlight Search ctermfg=yellow to customize; where:cterm is for formatingctermfg is for foreground colorctermbg is for background colorsee :help highlight linkYou can then use :noh to temporarily hide the last search highlight.
_webapps.8754
I have a Google Apps Account which has recently been changed to a full Google Account which has the email address [email protected] . I also have a gmail account with [email protected] . The Gmail account has stuff stored in Google Calendar, and is linked to a YouTube account. The Google Apps account has Google Analytics in use, and Google Docs. Both accounts have Google Reader in use.Is it possible to fully merge these two accounts? At the moment, the Gmail account just forwards all email to Google Apps account, but I would like to have the Calendar and YouTube accounts also under the one account. If not, is there a way to migrate my calendar data to the Google Apps account?
Merge Google Accounts?
google apps;google calendar;google account
According to Google's support docs, it's not possible to merge accounts.They do offer a comprehensive list of how to move and share data between Google accounts. For the specific products you mention:Google Reader can export feeds from one account and import to anotherCalendars can be shared; if you have meeting invites being forwarded via email you should be able to accept them on the new account.It is possible to unlink a YouTube account (by visiting this webpage) from one Google account and re-link it to another (by visiting this other webpage).
_unix.344057
If I make a .tar.gz viatar czvf - ./myfiles/ | pigz -9 -p 16 > ./mybackup.tar.gz,Can I safely unzip an already gzip'd file ./myfiles/an_old_backup.tar.gz within the ./myfiles directory viagzip -d mybackup.tar.gztar -xvf mybackup.tarcd myfilesgzip -d an_old_backup.tar.gztar -xvf an_old_backup.tar? And can one do this recursive compression safely ad infinitum?
Is it safe to do recursive compression with tar, gzip and pigz?
backup;tar;recursive;compression;gzip
If your question can be rephrased as is it OK to have compressedarchives within compressed archives?, then the answer is yes.This may not be the most convenient (as you note, you will have to runtar several files to get everything unpacked), and applyingcompression to data that has already been compressed may not yield anadditional reduction in size, but it will all work.
_unix.218456
Here's what I did:copied some files from server to my local computerscp root@remotemachine:/var/log/nginx/* /home/me/logsdeleted the files on the serverThe next moment I realized, that I forgot to create the target directory on the local machine (/home/me/logs). Now instead of copied files inside 'logs' I see a file called 'logs' that looks like gzip archive, but file-roller doesn't recognize it as a valid gzip archive.
What happens to my files if I scp-ed to non existing directory
directory;scp;gzip
In this case scp will copy each source file to /home/me/logs, overwriting /home/me/logs with the contents of each new file.The result is that /home/me/logs will be a copy of the last source file in the list. All the other source files are lost.Oops! Regular cp warns and aborts in this case, at least!
_ai.2826
Short version of this question: where in the OpenAI Gym docs can you find more information about an environment, like what each of the variables in an observation means, and so on.As per their docs (https://gym.openai.com/docs), you can get the state space as follows:env.observation_spaceThe problem is, these just look like random numbers in an array.Using CartPole-v0 as an example, the bounds are given as:env.observation_space.high # array([ 4.80000000e+00, 3.40282347e+38, 4.18879020e-01, 3.40282347e+38])env.observation_space.low# array([ -4.80000000e+00, -3.40282347e+38, -4.18879020e-01, -3.40282347e+38])It seems intuitive after reading some papers about the inverted pendulum, that the state is typically represented by a 4-tuple of (angle, angular speed, horizontal displacement, horizontal speed).This also suggests that the observation space bounds are actually meant to represent:Low: (-pi, -inf, x_min, -inf)High: (+pi, +inf, x_max, +inf)The magnitude of the 2nd and 4th lows/highs seem to suggest that they do indeed represent angular speed and horizontal speed.But why does the 1st low/high not correspond to -/+pi?Where can more information be found about what these numbers actually represent?
Where do I find documentation about specific OpenAI Gym environments?
reinforcement learning
null
_unix.177014
I used mount to show mounted drives, I don't want to see the not so interesting ones (i.e. non-physical). So I used to have a script mnt that did:mount | grep -Ev 'type (proc|sysfs|tmpfs|devpts) 'under Ubuntu 8.04 and showed me ext3 and reiserfs mount points only. That line is actually commented out and now I use (for Ubuntu 12.04):mount | grep -Ev 'type (proc|sysfs|tmpfs|devpts|debugfs|rpc_pipefs|nfsd|securityfs|fusectl|devtmpfs) 'to only show my ext4 and zfs partitions (I dropped using reiserfs).Now I am preparing for Ubuntu 14.04 and the script has to be extended again (cgroup,pstore). Is there a better way to do this without having to extend the script? I am only interested in physical discs that are mounted and mounted network drives (nfs,cifs).
Showing only interesting mount points / filtering non interesting types
linux;filesystems;mount
The -t option for mount also works when displaying mount points and takes a comma separated list of filesystem types:mount -t ext3,ext4,cifs,nfs,nfs4,zfsI am not sure if that is a better solution. If you start using (e.g. btrfs) and forget to add that to the list you will not see it and maybe not miss it. I'd rather actively filter out any new uninteresting filesystem when they pop up, even though that list is getting long.You can actively try to only grep the interesting mount points similar to what @Graeme proposed, but since you are interested in NFS/CIFS mounts as well (which don't start with /), you should do:mount | grep -E --color=never '^(/|[[:alnum:]\.-]*:/)'( the --color is necessary to suppress coloring of the initial / on the lines found). As Graeme pointed out name based mounting of NFS shares should be allowed as well. The pattern either selects lines starting with a / or any combination of a-zA-Z0-9. followed by :/ (for NFS mounts).
_unix.33236
I have a utility that takes a load of different arguments. For now, I want to autocomplete the first argument, but leave all the others to fall through to normal autocompletion. How do I do that?function _my_autocomplete_(){ case $COMP_CWORD in 1) COMPREPLY=($(compgen -W $(get_args_somehow) -- ${COMP_WORDS[COMP_CWORD]}));; *) # What goes here? esac}complete -F _my_autocomplete_ mycommand
Configure autocomplete for the first argument, leave the others alone
bash;autocomplete
Apparently I completely missed your question. The answer is that there's no well-defined normal autocompletion. However, if you know what sort of thing you'd like it to complete (files, aliases, pids, variable names, etc.), you can give one or more flags to compgen. See this compgen manual page, specifically the -A options under complete (they're the same). E.g. if you want to complete file names, you would use this:compgen -f -- ${COMP_WORDS[COMP_CWORD]}If you want to complete commands (incl. aliases, functions, etc.), you can use this:compgen -back -A functions -- ${COMP_WORDS[COMP_CWORD]}Use $COMP_CWORD to get the index of the word being completed. If the index isn't 1, set $COMPREPLY to () and return.COMP_CWORD An index into ${COMP_WORDS} of the word containing the current cursor position. This variable is available only in shell functions invoked by the programmable completion facilities
_unix.28771
Possible Duplicate:How to delete part of a path in an interactive shell? Is there a short-cut in bash that lets you delete the last part of a path?Example: /usr/local/bin should become /usr/local/ (or /usr/local)I know of <ctrl>-w but it deletes the complete last word and I'd like to retain that functionality, too.
How to remove last part of a path in bash?
bash;readline
null
_webmaster.108336
I have a few articles that are in the top 3 of Google search results. They are currently accessed by the URL http://example.com/myarticle1. Now, I want to move that article to the other URL http://example.org/different-name-myarticle1. The old URL is referenced in many places on the internet. I don't want to break the links so I setup a 301 redirect returned from the server with the new location. A browser works perfectly but I'm wondering if the indexing bot will follow the redirects and keep the ranking of my page? Are there any risks?
Changing domain through 301 redirects - will I lose ranking position?
redirects;indexing;ranking
While you indeed seem to have done things perfectly with the 301 redirect, you might (temporarily) lose your rankings. This is due to the fact that Google is hesitant to immediately transfer all link metrics to new URLs after they redirect.Also, if the article indeed has a different name (as your example shows) then this might also impact your rankings.Furthermore, with each redirect you could lose some link juice, as referenced, for instance, in http://www.seoblog.com/2014/06/link-juice-lost-301-redirect/.
_unix.155520
I have a problem with my new installation of ArchLinux with an encrypted partition. I guess I have done the same steps as before and it works on my other machine. The error message I get is:ERROR: device 'UUID=[....]' not found. SKipping fsck.ERROR: Unable to find root device 'UUID=[...]'.You are being drpped to recovery shell I have not typed in the UUID, it is the same in both lines.To fix this I have searched the internet. The first thing I have done was to change the HOOKS line in /etc/mkinitcpio.conf to:HOOKS=base udev block autodetect modconf keyboard keymap encrypt filesystems fsckAnd the second thing I have done is to arch-chroot into it, install linux with pacman and doing:grub-mkconfig -o /boot/grub/grub.cfgI have also checked the /etc/fstab file and this looks also correct and the grub UUID in the grub.cfg file looks also correct I have checked this with blkid. It is the UUID of /dev/mapper/vgarch-lvroot. The same counts for the machine on which it works.And the third thing I have done was to reinstall grub and redoing the steps but none of this has worked.Resources: first, secondI am looking forward to hear from you.
Encrypted ArchLinux: unable to find root device
boot;grub;uuid;cryptsetup
I have solved my question, I have simply forget to add lvm2 in the HOOKS line of /etc/mkinitcpio.conf. Now it looks like:HOOKS = base udev autodetect modconf block keyboard keymap encrypt lvm2 filesystems fsck shutdown
_codereview.92106
This code adds and takes away background GIF images on scroll. I will be using this for 12 images on the same page but the code looks like it will get incredibly repetitive.My main concern is to get eventsGif() and teamsGif() to be the same function (since all 12 will be using the same sort of code).**edit to new code further down **I was thinking I could just call a manageGif() function and pass in the team or event object but then I'm not sure how to concatenate the variable name (ie eventGif). I then thought that instead of trying to concatenate the variable name, I could use two for loops and add all properties to objects in one function and then in the manageGif function I could loop through the objects and apply it to each. But now I'm just confused and starting over again.var gifAnimations = gifAnimations || {};gifAnimations = { featurePageBool: x$('#set-feature-panel'), teamGif: document.getElementById('witkit-teams'), eventGif: document.getElementById('witkit-events'), teams: null, events: null, getElementPositions: function(){ var de = document.documentElement; var windowHight = window.innerHeight; gifAnimations.teams = gifAnimations.getTopBottom(gifAnimations.teamGif, de, windowHight); gifAnimations.events = gifAnimations.getTopBottom(gifAnimations.eventGif, de, windowHight); gifAnimations.startGifAnimations(); }, getTopBottom: function(el, de, windowHight) { var result = {}; var box = el.getBoundingClientRect(); result.top = box.top + window.pageYOffset - de.clientTop; result.bottom = box.bottom + window.pageYOffset - de.clientTop; result.diff = result.bottom - result.top; result.padding = windowHight - result.diff; return result; }, startGifAnimations: function(){ var scrollPosition = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop; gifAnimations.teamsGif(scrollPosition); gifAnimations.eventsGif(scrollPosition); }, teamsGif: function(scrollPosition){ var bg = gifAnimations.teamGif.getAttribute('style'); // these thresh are where the image is out of view var topThreshold = (gifAnimations.teams.top+ gifAnimations.teams.diff) - scrollPosition - 55; var bottomThreshold = ( gifAnimations.teams.bottom - gifAnimations.teams.diff - window.innerHeight )- scrollPosition; if ( !(topThreshold > 0 && bottomThreshold < 0) ){ gifAnimations.teamGif.removeAttribute('style');//style.backgroundImage='url(../i/frame-one.gif)'; } //these thresh is where animation should happen var topTrigger = gifAnimations.teams.top - scrollPosition - 55; var bottomTrigger = ( gifAnimations.teams.top + gifAnimations.teams.diff -window.innerHeight )- scrollPosition; if (topTrigger > 0 && bottomTrigger < 0 && bg === null){//background-image: url(http://regan.dev.witkit.com/i/frame-one.gif); || bg === background-image: url(\../i/frame-one.gif\);)){ gifAnimations.teamGif.style.backgroundImage='url(../i/test.gif?'+Math.random()+')'; console.log(called) } }, eventsGif: function(scrollPosition){ var bg = gifAnimations.eventGif.getAttribute('style'); var topThreshold = (gifAnimations.events.top+ gifAnimations.events.diff) - scrollPosition - 55; var bottomThreshold = ( gifAnimations.events.bottom - gifAnimations.events.diff - window.innerHeight )- scrollPosition; if ( !(topThreshold > 0 && bottomThreshold < 0) ){ gifAnimations.eventGif.removeAttribute('style'); } var topTrigger = gifAnimations.events.top - scrollPosition - 55; var bottomTrigger = ( gifAnimations.events.top + gifAnimations.events.diff -window.innerHeight )- scrollPosition; if (topTrigger > 0 && bottomTrigger < 0 && bg === null){ gifAnimations.eventGif.style.backgroundImage='url(../i/test2.gif?'+Math.random()+')'; console.log(called) } },}if(gifAnimations.featurePageBool){ window.addEventListener('resize', gifAnimations.getElementPositions); document.addEventListener('scroll', gifAnimations.getElementPositions);}EDITI have managed to get it down to the following but I need the gif, gifElements and gifElementSizes to always be in the same order. Does anyone know how I can do this? For some reason Im really having a hard time making and using just simple team, event objects instead of the gif, gifElements and gifElementSizesvar gifAnimations = gifAnimations || {};gifAnimations = { featurePageBool: x$('#set-feature-panel'), gifElements: [ document.getElementById('witkit-events'), document.getElementById('witkit-teams') ], gifs: [ ../i/test.gif, ../i/test2.gif ], gifElementSizes:[], getElementPositions: function(){ gifAnimations.getElementPositions = []; var de = document.documentElement; var windowHight = window.innerHeight; for(var i=0;i<gifAnimations.gifElements.length;i++){ gifAnimations.getTopBottom(gifAnimations.gifElements[i], de, windowHight); } gifAnimations.manageGif(); }, getTopBottom: function(el, de, windowHight) { var result = {}; var box = el.getBoundingClientRect(); result.top = box.top + window.pageYOffset - de.clientTop; result.bottom = box.bottom + window.pageYOffset - de.clientTop; result.diff = result.bottom - result.top; result.padding = windowHight - result.diff; gifAnimations.gifElementSizes.push(result); }, manageGif: function() { var scrollPosition = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop; for(var i=0;i<gifAnimations.gifElements.length;i++){ var elGif = gifAnimations.gifElements[i]; var el = gifAnimations.gifElementSizes[i]; var gif = gifAnimations.gifs; var bg = elGif.getAttribute('style'); // these thresh are where the image is out of view var topThreshold = (el.top+ el.diff) - scrollPosition - 55; var bottomThreshold = ( el.bottom - el.diff - window.innerHeight )- scrollPosition; if ( !(topThreshold > 0 && bottomThreshold < 0) ){ elGif.removeAttribute('style');//style.backgroundImage='url(../i/frame-one.gif)'; } //these thresh is where animation should happen var topTrigger = el.top - scrollPosition - 55; var bottomTrigger = ( el.top + el.diff -window.innerHeight )- scrollPosition; if (topTrigger > 0 && bottomTrigger < 0 && bg === null){//background-image: url(http://regan.dev.witkit.com/i/frame-one.gif); || bg === background-image: url(\../i/frame-one.gif\);)){ elGif.style.backgroundImage='url('+gif[i]+'?'+Math.random()+')'; // console.log(called) } } },}if(gifAnimations.featurePageBool){ window.addEventListener('resize', gifAnimations.getElementPositions); document.addEventListener('scroll', gifAnimations.getElementPositions);}
Adding/removing background GIF images on scroll
javascript
null
_softwareengineering.277278
I'm reviewing best practices articles for WCF versioning. A lot of the recommendations revolve around one decision: Are you using strict versioning? If so, treat every contract as immutable. If not, .. [list of additional recommendations..]The problem is that none of these articles really explain scenarios where you would assume strict versioning. That is, with two exceptions: 1) having no clue whatsoever as to what the client deploy base looks like (could be explicitly strict, could be Java, could be anything), and 2) not using WCF to begin with. But in a scenario where clients are carefully distributed within an enterprise, and only WCF is used, are there any other scenarios where one would choose to establish strict validation?
In WCF, why would one deliberately use strict schema validation?
wcf;versioning
null
_codereview.9790
I tried to solve one SPOJ problem. I wrote one program in Python, however, it got accepted by the SPOJ judges, but its total execution time is 2.88s. The same algorithm used in C language having execution time 0.15s.Please offer suggestions on improving this approach.def tempPalindrome(inputString): Code for finding out temporary palindrome. used by nextPalindrome function inputList = list(inputString) length = len(inputList) halfL = inputList[:length/2] halfL.reverse() if (length % 2) == 0: inputList = inputList[:length>>1] + halfL else: inputList = inputList[:(length>>1)+1] + halfL #if new palindrome is greater than given number then return otherwise increment it if ''.join(inputList) > inputString.zfill(length): return inputList else: position = length >> 1 if length %2 == 0: position-=1 for i in range(position, -1, -1): if inputList[i] == '9': inputList[i] = '0' else: inputList[i] = chr(ord(inputList[i]) + 1) break if (i == 0) and (inputList[i] == '0'): inputList = ['1'] + inputList length += 1 halfL = inputList[:length/2] halfL.reverse() if (length % 2) == 0: inputList = inputList[:length>>1] + halfL else: inputList = inputList[:(length>>1)+1] + halfL return inputList return Nonedef nextPalindrome(): Take an input from user and find next palindrome inputs = list() noOfCases = int(raw_input()) for i in range(noOfCases): inputs.append(raw_input()) for inputString in inputs: inputList = tempPalindrome(inputString) print ''.join(inputList) return Noneif __name__ == '__main__': nextPalindrome()By profiling this code using cProfile profiler, I get the following output: >>> 199101 119 function calls in 3.111 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 3.111 3.111 <string>:1(<module>) 2 0.000 0.000 0.000 0.000 AsyncFile.py:107(flush) 4 0.000 0.000 0.000 0.000 AsyncFile.py:121(fileno) 4 0.000 0.000 0.000 0.000 AsyncFile.py:16(AsyncPendingWrite) 2 0.000 0.000 0.000 0.000 AsyncFile.py:160(readline_p) 4 0.000 0.000 0.000 0.000 AsyncFile.py:261(write) 6 0.000 0.000 0.000 0.000 AsyncFile.py:55(__checkMode) 6 0.000 0.000 0.000 0.000 AsyncFile.py:67(__nWrite) 8 0.000 0.000 0.000 0.000 AsyncFile.py:88(pendingWrite) 2 0.000 0.000 0.000 0.000 AsyncIO.py:44(readReady) 2 0.000 0.000 3.111 1.555 DebugClientBase.py:318(raw_input) 2 0.000 0.000 3.111 1.555 DebugClientBase.py:34(DebugClientRawInput) 2 0.000 0.000 0.000 0.000 DebugClientBase.py:374(handleLine) 2 0.000 0.000 0.000 0.000 DebugClientBase.py:965(write) 2 0.000 0.000 3.110 1.555 DebugClientBase.py:987(eventLoop) 1 0.000 0.000 0.000 0.000 nextPalindrome.py:24(tempPalindrome) 1 0.000 0.000 3.111 3.111 nextPalindrome.py:65(nextPalindrome) 7 0.000 0.000 0.000 0.000 socket.py:223(meth) 2 0.000 0.000 0.000 0.000 utf_8.py:15(decode) 2 0.000 0.000 0.000 0.000 {_codecs.utf_8_decode} 7 0.000 0.000 0.000 0.000 {getattr} 7 0.000 0.000 0.000 0.000 {len} 1 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects} 2 0.000 0.000 0.000 0.000 {method 'decode' of 'str' objects} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 1 0.000 0.000 0.000 0.000 {method 'encode' of 'str' objects} 2 0.000 0.000 0.000 0.000 {method 'encode' of 'unicode' objects} 4 0.000 0.000 0.000 0.000 {method 'fileno' of '_socket.socket' objects} 2 0.000 0.000 0.000 0.000 {method 'find' of 'str' objects} 6 0.000 0.000 0.000 0.000 {method 'find' of 'unicode' objects} 2 0.000 0.000 0.000 0.000 {method 'join' of 'str' objects} 4 0.000 0.000 0.000 0.000 {method 'recv' of '_socket.socket' objects} 2 0.000 0.000 0.000 0.000 {method 'reverse' of 'list' objects} 2 0.000 0.000 0.000 0.000 {method 'rfind' of 'str' objects} 6 0.000 0.000 0.000 0.000 {method 'rfind' of 'unicode' objects} 3 0.000 0.000 0.000 0.000 {method 'sendall' of '_socket.socket' objects} 1 0.000 0.000 0.000 0.000 {method 'zfill' of 'unicode' objects} 2 0.000 0.000 0.000 0.000 {range} 2 3.110 1.555 3.110 1.555 {select.select}
The Next Palindrome - reducing total execution time
python;performance;beginner;programming challenge;palindrome
Here are a few thoughts:Don't bother to store the inputs in a list, just convert and print as you go. (This saves memory, but not processing time)Converting strings to lists and back again is costing you a lot of time.Looping over all characters is slow, better to use a built-in function if possible. Your main loop seems to be discarding lots of '9' characters so in this case you can use rstrip to do this much faster.I suspect a string functions will be faster than list functions (e.g. I would expect reversing a string to be faster than reversing a list of characters)In this case, the main optimisation is therefore to keep the processing based on strings rather than lists of characters. Testing with a million character strings containing all 9s in Python 2.7, the code below is 28 times faster:def tempPalindrome(inputString): inputList = inputString length = len(inputList) halfL = inputList[:length/2][::-1] inputList = inputList[:(length+1)>>1] + halfL if inputList > inputString.zfill(length): return inputList position = (length-1) >> 1 i = len(inputList[:position+1].rstrip('9'))-1 num9s = position-i if i>=0: inputList = inputList[:i]+chr(ord(inputList[i]) + 1)+'0'*num9s+inputList[position+1:] else: inputList = '1' + '0'*num9s+inputList[position+1:] length += 1 halfL = inputList[:length/2][::-1] return inputList[:(length+1)>>1] + halfLdef nextPalindrome(): noOfCases = int(raw_input()) for i in xrange(noOfCases): print tempPalindrome(raw_input())
_unix.243151
I am trying to run a packaged Electron application at startup to create a kiosk system.When i use it in a fresh install of Lubuntu all seems to work fine. When i install openbox and slim on Ubuntu server with the following packages mednafen mame git hsetroot python-software-properties software-properties-common xserver-xorg xserver-xorg-core xorg slim libsdl2-dev openbox libgtk2.0-0 libgconf-2-4 libnss3 i get the following error from this application.A JavaScript error occurred in the main processUncaught Exception:Error: Failed to set path at Error (native) at Object.<anonymous> (/home/arcadia/arcadia/resources/atom.asar/browser/lib/init.js:115:7) at Object.<anonymous> (/home/arcadia/arcadia/resources/atom.asar/browser/lib/init.js:127:4) at Module._compile (module.js:434:26) at Object.Module._extensions..js (module.js:452:10) at Module.load (module.js:355:32) at Function.Module._load (module.js:310:12) at Function.Module.runMain (module.js:475:10) at startup (node.js:129:18) at node.js:981:3Is there a fundamental difference between these two methods that i don't see? What could be the cause of being unable to run this application in this light environment? Would there be an alternative that i can install and try?
Difference lubuntu openbox-session: Asked because of aplication error
ubuntu;desktop environment;openbox;application
null
_unix.329590
When writing a command with a - option and pressing tab, a list of possible completions with short explanations of what the options do is displayed. Is there a way to make this list also contain the currently typed option? E.g., writing grep -r and hitting tab displays-rA (Print NUM lines of trailing context)-ra (Process binary file as text)-rB (Print NUM lines of leading context)-rb (Print byte offset of matches)and 32 more rowsbut I would like it to display-r (Read files under each directory, recursively)-rA (Print NUM lines of trailing context)-ra (Process binary file as text)-rB (Print NUM lines of leading context)-rb (Print byte offset of matches)and 32 more rowsCheers,Hassanbot
Printing autocomplete info on current option in fish shell
shell;autocomplete;options;fish
null
_unix.40332
I am writing a bash script to automatically generate some other files, and I have to format some strings a certain way. Specifically, the last problem I'm having is formatting a string that has individual capital letters and a word that starts with a capital letter. For example:O S D Settings needs to become OSD SettingsI have a sed command that strips the first space, but it also deletes the D (i.e. O S D Settings -> OS Settings). This command is: O S D Settings | sed 's/ \([A-Z]\)* \(A-Za-z]*\)/\1/g'Does anyone know how to delete the spaces in between individual capital letters without losing any letters?
Strip spaces after single capital letters with sed
bash;text processing;sed
I ended up just using sed with pipes to get a statement that is easy for me to understand:echo O S D Settings | sed 's/\([A-Z][^ ]\)/_\1/g' | sed 's/ //g' | sed 's/_/ /g'All this does is replaces the spaces I don't want with the underscore and then deletes them. Thanks for all the answers!
_unix.50215
The only calculator I know is bc. I want to add 1 to a variable, and output to another variable.I got the nextnum variable from counting string in a file:nextnum=`grep -o stringtocount file.tpl.php | wc -w`Lets say the nextnum value is 1. When added with 1, it will become 2. To calculate, I run:rownum=`$nextnum+1 | bc`but got error:1+1: command not foundI just failed in calculation part. I've tried changing the backtick but still not works. I have no idea how to calculate variables and output it to another variable.
Calculate variable, and output it to another variable
shell;arithmetic;bc;calculator
The substring inside the ` ` must be a valid command itself:rownum=`echo $nextnum+1 | bc`But is preferable to use $( ) instead of ` `:rownum=$(echo $nextnum+1 | bc)But there is no need for bc, the shell is able to do integer arithmetic:rownum=$((nextnum+1))Or even simpler in bash and ksh:((rownum=nextnum+1))
_softwareengineering.187201
I am thinking of managing a product source I am doing using Codeigniter + HMVC.Right now my folder structure is something like this:application |-modules |-module1 | |--controllers | |--models | |--views |-module2 | |--controllers | |--models | |--viewsassets |-themes |-default |-module1 | |-- module1 theme files |-module2 | |-- module2 theme filesI am thinking of cleaning this up and making the modules self contained at development time, like thisapplication |-- this will only contain the core files () |--modules (an empty directory OR core modules)modules |-module1 | |-controllers | |-models | |-themes | | |-default | | | |-module1 default theme files | |-assets | | |-css (css files for just this module) | | |-js (js files just for this module) |-module2 |--//same as aboveAnd then use Phing to build the project during which, the modules will be copied to respective folders, css files and js files will be minified (SCSS compiled) and images copied to respective folders.This looks great for deploying changes, but I think it will just increase development time, as every time I make any changes, I will have to build even to see it in development. Have any one used this approach to development using CI? or even better?I want to keep my core core more trackable and separate the modules for better version controlling, as I will be able to add those modules to the project as sub projects.
Codeigniter modular separation with Phing
php;continuous integration;codeigniter
null
_reverseengineering.14308
I'm trying to edit a Japanese Configuration executable using Resource Hacker and I just want to translate the UI stuff to English. There are also a few English text that I was able to find and successfully edit. My problem is that before the hex editor can properly display Kanji, I need a table for it (.tbl). Google only leads me to translating Japanese NES games which doesn't apply to what I'm trying to do.Also, the Japanese characters on the UI of the .exe file I'm trying to edit even if I have already installed the Japanese Language Pack -- I still need to set the Region > Format to Japan before the characters are properly displayed.I really hope someone can help me with this. :-/
How can I create an appropriate Japanese .tbl file for Hex Editing?
hex;patching;binary editing
null
_webmaster.103935
We have a domain and a hosted website attached to it.For one of our product, we bought a second domain, which forward to our main website.Is there anyway to have search engine index or find that domain?
How to search index a domain forward?
domains;search engines
null
_codereview.123117
Note: this is from a COMPLETED course. This is not a ploy to get help with homework, as I have already received a 100% on this assignment (last year). I just want to become a neater programmer. Can you please provide me with some stylistic feedback? Note, the assignment did not allow for the use of objects at the time and the dat files contained X's and .'s. X's = life, .'s = absence of life. It was an exercise to provide us practice with multi-dimensional arrays.package java_labs.GameOfLife;import java.util.Scanner;import java.io.*;public class GameOfLife { final static int M = 25; final static int N = 75; public static void main(String[] args) { char[][] oldBoard = new char[M + 2][N + 2]; char[][] newBoard = new char[M + 2][N + 2]; char[][] tempBoard = new char[M + 2][N + 2]; buildBoardFromFile(oldBoard, newBoard, tempBoard); int generationCount = 0; printBoard(oldBoard, generationCount); /* prints Generation #0 every time*/ boolean continueGame = true; while (continueGame) { if (isEmpty(oldBoard)) { continueGame = false; } else { newBoard = getNextGeneration(oldBoard, newBoard); if (isGenerationChanged(oldBoard, newBoard)) { tempBoard = copyArray(newBoard, tempBoard); Scanner input = new Scanner(System.in); String inputValue = ; while ((!(inputValue.equalsIgnoreCase(Y))) && (!(inputValue.equalsIgnoreCase(Q)))) { System.out.print(\nWould you like to see the next generation?\n + Enter 'Y' for yes or 'Q' to quit: ); inputValue = input.next(); if (inputValue.equalsIgnoreCase(Q)) { continueGame = false; System.out.println(\nYou opted to quit. + Game Over!\n); } else if (inputValue.equalsIgnoreCase(Y)) { generationCount++; printBoard(newBoard, generationCount); oldBoard = tempBoard; } else { System.out.println(\nInvalid option. Try again.); } } } else { continueGame = false; generationCount++; System.out.println(\n\nGAME OVER! Generation # + (generationCount) + is the same as Generation # + (generationCount - 1) + .\nBelow is proof that Generation # + (generationCount) + is the same as Generation # + (generationCount - 1) + \nfor your reference:\n); printBoard(newBoard, generationCount); System.out.println(\n\n\nYou will now exit the program!\n\n\n); } } } } static void buildBoardFromFile(char[][] oldBoard, char[][] newBoard, char[][] tempBoard) { boolean inputInvalid = true; Scanner fileReader = null; File file = null; String line = ; boolean invalidNumberOfRowCol = false; while (inputInvalid) { Scanner consoleReader = new Scanner(System.in); System.out.print(\nWhich file do you want to open?); String filename = consoleReader.next(); file = new File(filename); try { fileReader = new Scanner(file); inputInvalid = false; } catch (Exception e) { System.out.println(\nError: File + file + does not exist! Try again:); } } for (int row = 0; row < M; row++) { try { line = fileReader.nextLine(); }/* Accounts for files with too few rows */ catch (java.util.NoSuchElementException err) { System.out.println(\nError: + file + is not compatible with + this program! Try adding + (M - (row)) + rows to\n + file + to fix this issue.); buildBoardFromFile(oldBoard, newBoard, tempBoard); break; } for (int col = 0; col < N; col++) { /* Added this code to account for files with too few columns */ try { oldBoard[row + 1][col + 1] = line.charAt(col); } catch (StringIndexOutOfBoundsException err) { System.out.println(\nError: + file + is not compatible with this program! + Try adding + (N - line.length()) + characters to\nrow # + (row + 1) + in + file + to fix this issue.); invalidNumberOfRowCol = true; break; } } }/* * Note this program will ignore data in file greater outside the * maximum column size and row size. For example, if a row in the .dat * file contains 76 characters and the maximum board size is 75, the * 76th character in that row is ignored by the program's for loop. This * assignment did not ask the user to address this issue. I did create * additional error checking functionality outside the scope of the * assignment for practice. See above. */ if (invalidNumberOfRowCol) buildBoardFromFile(oldBoard, newBoard, tempBoard); setBoarder(oldBoard, newBoard, tempBoard); } /* Note boarder will always be . and will not change */ static void setBoarder(char[][] oldBoard, char[][] newBoard, char[][] tempBoard) { for (int row = 0; row <= M + 1; row++) { for (int col = 0; col <= N + 1; col++) { if (row == 0 || col == 0 || row == M + 1 || col == N + 1) { oldBoard[row][col] = '.'; newBoard[row][col] = '.'; tempBoard[row][col] = '.'; } } } } /* Checks for life on game board */ static boolean isEmpty(char[][] oldBoard) { boolean noLife = true; for (int row = 1; row <= M; row++) { for (int col = 1; col <= N; col++) { if (oldBoard[row][col] == 'X') noLife = false; } } return noLife; } /* Identifies if a generation is different from its successor */ static boolean isGenerationChanged(char[][] oldBoard, char[][] newBoard) { boolean continueGame = false; for (int row = 1; row <= M; row++) { for (int col = 1; col <= N; col++) { if (oldBoard[row][col] != newBoard[row][col]) continueGame = true; } } return continueGame; } static void printBoard(char[][] board, int generationCount) { if (isEmpty(board)) System.out.println(\nEveryone is dead! Game over!\n); System.out.println(\nGeneration # + generationCount + :); for (int row = 1; row <= M; row++) { for (int col = 1; col <= N; col++) { System.out.print(board[row][col]); } System.out.print(\n); } } static char[][] getNextGeneration(char[][] oldBoard, char[][] newBoard) { for (int row = 1; row <= M; row++) { for (int col = 1; col <= N; col++) { if ((oldBoard[row][col] == 'X' && (countNeighbors(oldBoard, row, col) == 2 || countNeighbors(oldBoard, row, col) == 3)) || (oldBoard[row][col] == '.' && countNeighbors( oldBoard, row, col) == 3)) { newBoard[row][col] = 'X'; } else { newBoard[row][col] = '.'; } } } return newBoard; } static char[][] copyArray(char[][] newBoard, char[][] tempBoard) { for (int row = 0; row <= M + 1; row++) { for (int col = 0; col <= N + 1; col++) { tempBoard[row][col] = newBoard[row][col]; } } return tempBoard; } static int countNeighbors(char[][] board, int row, int col) { int count = 0; int tempRow = row; int tempCol = col; for (col = tempCol - 1; col <= tempCol + 1; col++) { if (board[row - 1][col] == 'X') count++; if (board[row + 1][col] == 'X') count++; } for (col = tempCol - 1; col <= tempCol + 1; col += 2) { if (board[row][col] == 'X') count++; } return count; }}
The Game of Life that scored 100%
java;game of life
It's great that you strive to improve your skills, even though you already got a good score. OOPAn OOP language like Java makes it easy to encapsulate closely related data and operations in ADTs (abstract data types). An exercise like this screams for an ADT called Board. Methods with the word board in the name will naturally fit into the ADT, and instead of passing the char[][] parameters around everywhere, it could be hidden neatly inside the board, applying the good principles of encapsulation and information hiding. (Recommended reading: Code Complete chapter 6)Single responsibility principleA method should have one responsibility, one thing to do and do it well. Most of your method do multiple things. They can be split up to smaller methods. The result will be multiple shorter methods that are easier to understand and easier to understand.Reading from standard inputThe program reads from standard input in two places, and each time it creates a new Scanner instance. It would be better to create one scanner instance in the main method, and pass that to the methods that need it.Avoid pointless flag variablesThe flag variable continueGane here is unnecessary (like flag variables often are): boolean continueGame = true; while (continueGame) { if (isEmpty(oldBoard)) { continueGame = false; } // ...Instead of setting this variable to false, it would be simpler to just break out of the loop. Not doing so makes the program harder to read. Here, for example, if I want to verify what else will happen until the end of this cycle, I have to read the entire loop body. By breaking out right here right now, I will know that we're definitely out of the loop, the mental burden is greatly reduced.Another good example is in the other branch in this loop that sets the flag variable: } else { continueGame = false; // ... many many lines of code System.out.println(\n\n\nYou will now exit the program!\n\n\n); }So the print statement tells me that we're exciting the loop. But on that line, far away from the statement where you set the flag, and far away from the statement of the loop, it's not obvious that we really will exit. That's an unnecessary mental burden. And making it obvious is easy: System.out.println(\n\n\nYou will now exit the program!\n\n\n); break;And as we never change the flag variable anymore, the loop condition can be simplified to true.Flag variables also often lead to overlooking performance issues, for example here:static boolean isGenerationChanged(char[][] oldBoard, char[][] newBoard) { boolean continueGame = false; for (int row = 1; row <= M; row++) { for (int col = 1; col <= N; col++) { if (oldBoard[row][col] != newBoard[row][col]) continueGame = true; } } return continueGame;}Once the flag is set to true, it will never change, but the code continues to explore the entire board, instead of returning immediately.Magic valuesSome literal values appear at multiple places here and there, for example '.' and 'X'. It would be better to put these in constants with descriptive names.
_codereview.111772
I have some JS code that when the user clicks the add button, some text is displayed to a textarea.The code seems to be working OK. However, I realize I must refactor the code so that I am using only the one on click function instead of the six that I have for each of the 6 add buttons.$('#row_split_id_cover_letter_details_first_paragraph').prepend('<div id=id_standard_suggestion_01 class=cover_letter_suggestion_content margin-bottom-15><span id=id_1a1 class=margin-bottom-15>Standard Sentence Number 1.1. </span><span class=cover_letter_suggestion_add_button><button id=id_add_standard_suggestion_paragragh01_01 class=btn btn-xs rounded btn-primary type=button>{% trans Add %}</button></span></div><div id=id_standard_suggestion_02 class=cover_letter_suggestion_content margin-bottom-15><span id=id_1a2 class=margin-bottom-15>Standard Sentence Number 1.2. </span><span class=cover_letter_suggestion_add_button><button id=id_add_standard_suggestion_paragragh01_02 class=btn btn-xs rounded btn-primary type=button>{% trans Add %}</button></span></div><div id=id_standard_suggestion_03 class=cover_letter_suggestion_content margin-bottom-15><span id=id_1a3 class=margin-bottom-15>Standard Sentence Number 1.3. </span><span class=cover_letter_suggestion_add_button><button id=id_add_standard_suggestion_paragragh01_03 class=btn btn-xs rounded btn-primary type=button>{% trans Add %}</button></span></div><div id=id_standard_suggestion_04 class=cover_letter_suggestion_content margin-bottom-15><span id=id_1a4 class=margin-bottom-15>Standard Sentence Number 1.4. </span><span class=cover_letter_suggestion_add_button><button id=id_add_standard_suggestion_paragragh01_04 class=btn btn-xs rounded btn-primary type=button>{% trans Add %}</button></span></div><div id=id_standard_suggestion_05 class=cover_letter_suggestion_content margin-bottom-15><span id=id_1a5 class=margin-bottom-15>Standard Sentence Number 1.5. </span><span class=cover_letter_suggestion_add_button><button id=id_add_standard_suggestion_paragragh01_05 class=btn btn-xs rounded btn-primary type=button>{% trans Add %}</button></span></div><div id=id_standard_suggestion_06 class=cover_letter_suggestion_content margin-bottom-15><span id=id_1a6 class=margin-bottom-15>Standard Sentence Number 1.6. </span><span class=cover_letter_suggestion_add_button><button id=id_add_standard_suggestion_paragragh01_06 class=btn btn-xs rounded btn-primary type=button>{% trans Add %}</button></span></div>');$(function () { $('#id_add_standard_suggestion_paragragh01_01').on('click', function () { var divTA1 = document.getElementById('id_cover_letter_details_first_paragraph'); var divGS1 = document.getElementById('id_1a1'); divTA1.innerHTML = divTA1.innerHTML + divGS1.innerHTML; }); $('#id_add_standard_suggestion_paragragh01_02').on('click', function () { var divTA1 = document.getElementById('id_cover_letter_details_first_paragraph'); var divGS1 = document.getElementById('id_1a2'); divTA1.innerHTML = divTA1.innerHTML + divGS1.innerHTML; }); $('#id_add_standard_suggestion_paragragh01_03').on('click', function () { var divTA1 = document.getElementById('id_cover_letter_details_first_paragraph'); var divGS1 = document.getElementById('id_1a3'); divTA1.innerHTML = divTA1.innerHTML + divGS1.innerHTML; }); $('#id_add_standard_suggestion_paragragh01_04').on('click', function () { var divTA1 = document.getElementById('id_cover_letter_details_first_paragraph'); var divGS1 = document.getElementById('id_1a4'); divTA1.innerHTML = divTA1.innerHTML + divGS1.innerHTML; }); $('#id_add_standard_suggestion_paragragh01_05').on('click', function () { var divTA1 = document.getElementById('id_cover_letter_details_first_paragraph'); var divGS1 = document.getElementById('id_1a5'); divTA1.innerHTML = divTA1.innerHTML + divGS1.innerHTML; }); $('#id_add_standard_suggestion_paragragh01_06').on('click', function () { var divTA1 = document.getElementById('id_cover_letter_details_first_paragraph'); var divGS1 = document.getElementById('id_1a6'); divTA1.innerHTML = divTA1.innerHTML + divGS1.innerHTML; });});Here is a working fiddle.
Displaying text on button click
javascript;jquery
Don't add HTML in DOM from jQuery, add it from server side.Changes in HTMLRemoved all ids as it is not usedRemoved redundant attribute type=button from buttons.Use HTML structure as follow:<div class=cover_letter_suggestion_content margin-bottom-15> <span class=margin-bottom-15>Standard Sentence Number 1.1. </span> <span class=cover_letter_suggestion_add_button> <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button> </span></div><div class=cover_letter_suggestion_content margin-bottom-15> <span class=margin-bottom-15>Standard Sentence Number 1.2. </span> <span class=cover_letter_suggestion_add_button> <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button> </span></div><div class=cover_letter_suggestion_content margin-bottom-15> <span class=margin-bottom-15>Standard Sentence Number 1.3. </span> <span class=cover_letter_suggestion_add_button> <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button> </span></div><div class=cover_letter_suggestion_content margin-bottom-15> <span class=margin-bottom-15>Standard Sentence Number 1.4. </span> <span class=cover_letter_suggestion_add_button> <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button> </span></div><div class=cover_letter_suggestion_content margin-bottom-15> <span class=margin-bottom-15>Standard Sentence Number 1.5. </span> <span class=cover_letter_suggestion_add_button> <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button> </span></div><div class=cover_letter_suggestion_content margin-bottom-15> <span class=margin-bottom-15>Standard Sentence Number 1.6. </span> <span class=cover_letter_suggestion_add_button> <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button> </span></div>JavascriptUse common class to bind event on all elements, cover_letter_suggestion_add_button in this caseUse the DOM traversal methods to get the elements corresponding to the clicked element, using $(this) to reference to clicked element and prev to get the previous sibling.Code:$(document).ready(function () { $('.cover_letter_suggestion_add_button button').on('click', function () { // Get text of the previous span element var text = $(this).closest('.cover_letter_suggestion_add_button').prev().text(); $('#id_cover_letter_details_first_paragraph').val(function (i, oldVal) { return oldVal + text; // Append the value of the prev. span to the textarea }); });});Demo$(document).ready(function() { $('.cover_letter_suggestion_add_button button').on('click', function() { var text = $(this).closest('.cover_letter_suggestion_add_button') .prev().text(); $('#id_cover_letter_details_first_paragraph').val(function(i, oldVal) { return oldVal + text; }); });});.cover_letter_suggestion_content { background-color: #ededed; border: 1px solid #a8a8a8; padding: 10px;}.cover_letter_suggestion_add_button { display: block; text-align: right;}.textAreaSplit { height: 200px; max-height: 600px; max-width: 50%; min-height: 100px; min-width: 50%; resize: vertical;}.textAreaSplitContainer { background-color: #f6f6f6; border: 1px solid #d9d9d9; display: inline-block; height: 200px; max-height: 600px; max-width: 45%; min-height: 100px; min-width: 45%; overflow: scroll; overflow-x: hidden; padding: 10px; resize: none; /* container is resized by resizing the textarea */ vertical-align: top;}<script src=https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js></script><div id=row_id_cover_letter_details_first_paragraph class=form-group > <label for=id_cover_letter_details_first_paragraph class=control-label >Paragraph 1:</label> <div class=controls > <span id=row_id_cover_letter_details_first_paragraph> <textarea cols=40 data-parsley-maxlength=2000 id=id_cover_letter_details_first_paragraph maxlength=2000 name=cover_letter_details_first_paragraph rows=10 class=textAreaSplit kmw-disabled keymanweb-font data-parsley-id=8695 data-parsley-required=false></textarea> <span class=parsley-errors-list id=parsley-id-8695></span> </span> <p class=help-block>2,000 character limit</p> </div> <div class=cover_letter_suggestion_content margin-bottom-15> <span class=margin-bottom-15>Standard Sentence Number 1.1. </span> <span class=cover_letter_suggestion_add_button> <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button> </span> </div> <div class=cover_letter_suggestion_content margin-bottom-15> <span class=margin-bottom-15>Standard Sentence Number 1.2. </span> <span class=cover_letter_suggestion_add_button> <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button> </span> </div> <div class=cover_letter_suggestion_content margin-bottom-15> <span class=margin-bottom-15>Standard Sentence Number 1.3. </span> <span class=cover_letter_suggestion_add_button> <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button> </span> </div> <div class=cover_letter_suggestion_content margin-bottom-15> <span class=margin-bottom-15>Standard Sentence Number 1.4. </span> <span class=cover_letter_suggestion_add_button> <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button> </span> </div> <div class=cover_letter_suggestion_content margin-bottom-15> <span class=margin-bottom-15>Standard Sentence Number 1.5. </span> <span class=cover_letter_suggestion_add_button> <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button> </span> </div> <div class=cover_letter_suggestion_content margin-bottom-15> <span class=margin-bottom-15>Standard Sentence Number 1.6. </span> <span class=cover_letter_suggestion_add_button> <button class=btn btn-xs rounded btn-primary>{% trans Add %}</button> </span> </div></div>
_unix.251960
I've been using curl -XPOST to post some links to a Telegram channel via a bot api/key, the urls are in form of https://site/x/pre_encoded_string, where pre_encoded_string is in form (real samples) XOsmY90GWWA, 4QHTV_K_WwQ, and they're generated from perl's MIME::Base64 encode_base64url function.This fails when the generated string contains the underscore char _ (as in second sample above), which gets stripped, and curl seems to post 4QHTVKWwQEven if I get rid of --data-* (binary,raw,urlencode) and pass the string in the url, it gets stripped also.ais@rex ~ # curl -vv -s -XPOST 'https://api.telegram.org/bot1[...]4:AAE[...]Ggd3g/sendMessage?parse_mode=Markdown&chat_id=@xt2RM' --data-urlencode 'text=https://xt2/x/4QHTV_K_WwQ'* Trying 149.154.167.198...* Connected to api.telegram.org (149.154.167.198) port 443 (#0)* Initializing NSS with certpath: none* CAfile: /etc/ssl/certs/ca-certificates.crt CApath: none* NPN, server accepted to use http/1.1* SSL connection using TLS_RSA_WITH_AES_128_GCM_SHA256* Server certificate:* subject: CN=api.telegram.org,OU=Domain Control Validated* start date: May 23 16:17:38 2015 GMT* expire date: May 23 16:17:38 2018 GMT* common name: api.telegram.org* issuer: CN=Go Daddy Secure Certificate Authority - G2,OU=http://certs.godaddy.com/repository/,O=GoDaddy.com, Inc.,L=Scottsdale,ST=Arizona,C=US> POST /bot1[...]4:A[...]ApJyf9Pg0/sendMessage?parse_mode=Markdown&chat_id=@xt2RM HTTP/1.1> Host: api.telegram.org> User-Agent: curl/7.43.0> Accept: */*> Content-Length: 55> Content-Type: application/x-www-form-urlencoded> * upload completely sent off: 55 out of 55 bytes< HTTP/1.1 200 OK< Server: nginx/1.9.1< Date: Mon, 28 Dec 2015 18:55:30 GMT< Content-Type: application/json< Content-Length: 193< Connection: keep-alive< Strict-Transport-Security: max-age=31536000; includeSubdomains< * Connection #0 to host api.telegram.org left intact{ok:true,result:{message_id:1506,chat:{id:-1[........]8,title:tty2RM,username:tty2RM,type:channel},date:1451328930,text:https:\/\/xt2\/x\/4QHTVKWwQ}}ais@rex ~ #Any clue as where my problem is?
curl --data-urlencode and underscores
curl;character encoding;base64
null
_codereview.101232
I'm reinventing std::future from scratch (for an upcoming talk). I'd like to incorporate as many of the latest and most likely-to-succeed proposals as possible, and then also at least one additional feature that I haven't seen in any proposal yet: cancellation of tasks.The idea is that if I spawn a chain of tasks via async(x).then(y).then(z), and then (maybe after a while) drop the resulting future on the floor, I am indicating that I no longer care about the result of the chain of computations, and therefore the executor should not execute any of them that aren't already in progress. (For example, if it's still in the middle of executing x, it should finish x but not start y or z).I'd like feedback on the particular way I've chosen to implement this feature. Namely, I've added a new member to Future<T>: a shared_ptr named cancellable_task_state_. The caller can set this pointer via Future<T>::attach_cancellable_task_state(). When you create a PackagedTask from a function object, we make_shared a copy of your function object so that its lifetime is now controlled by the PackagedTask's stored Future; and then the thing that we enqueue with the scheduler is simply a wrapper around a weak_ptr.This way, the scheduler itself doesn't have to worry about descheduling tasks from the middle of the queue; but we still get deterministic destruction of the function objects controlled by a future.One downside (in my current way of thinking) is that destroying a Future can now cause a lot of code execution, because it might destroy a whole chain of user-defined function objects. These objects' destructors might even throw exceptions! This feels too much like spooky action at a distance for my taste. How does std::async currently deal with the fact that the user might supply a function object with a destructor that throws? Where would that exception show up?(FYI, all this code is also available on GitHub, although it may eventually bit-rot since I rewrite my git history frequently.)The tricky bits of cancellation are all in PackagedTask:template<class F>struct PackagedTask;template<class R, class... A>struct PackagedTask<R(A...)> { UniqueFunction<void(A...)> task_; Future<R> future_; bool promise_already_satisfied_ = false; PackagedTask() = default; template<class F> PackagedTask(F&& f) { Promise<R> p; future_ = p.get_future(); auto f_holder = [f = std::forward<F>(f)]() mutable { return std::move(f); }; auto sptr = std::make_shared<decltype(f_holder)>(std::move(f_holder)); std::weak_ptr<decltype(f_holder)> wptr = sptr; future_.attach_cancellable_task_state(sptr); task_ = [p = std::move(p), wptr = std::move(wptr)](A... args) mutable { if (auto sptr = wptr.lock()) { auto f = (*sptr)(); try { p.set_value(f(std::forward<A>(args)...)); } catch (...) { p.set_exception(std::current_exception()); } } }; } bool valid() const { return task_; } Future<R> get_future() { if (!task_) throw no_state; if (!future_.valid()) throw future_already_retrieved; return std::move(future_); } void operator()(A... args) { if (!task_) throw no_state; if (promise_already_satisfied_) throw promise_already_satisfied; promise_already_satisfied_ = true; task_(std::forward<A>(args)...); }};Future<T> is derived from SharedFuture<T>, which looks like this. Note that SharedState<T> is defined below; and that both the Promise and the Future (or the Promise and the several SharedFutures) hold shared_ptrs to the SharedState. This is for simplicity; I'm not interested in micro-optimizing the non-shared variant of Future unless it also reduces the absolute amount of source code.template<class R>struct SharedFuture { std::shared_ptr<SharedState<R>> state_; std::shared_ptr<void> cancellable_task_state_; SharedFuture() {} SharedFuture(std::shared_ptr<SharedState<R>> s) : state_(s) {} R& get() const { ... } bool valid() const { return (state_ != nullptr); } bool ready() const { ... } void wait() const { ... } void attach_cancellable_task_state(std::shared_ptr<void> sptr) { cancellable_task_state_ = std::move(sptr); } template<class F> auto then(F func) { if (this->state_ == nullptr) throw no_state; auto sp = this->state_; using R2 = decltype(func(*this)); PackagedTask<R2()> task([func = std::move(func), fut = *this]() mutable { return func(std::move(fut)); }); Future<R2> result = task.get_future(); std::lock_guard<std::mutex> lock(sp->mtx_); if (sp->ready_) { SystemScheduler().schedule(std::move(task)); } else { sp->continuations_.emplace_back(std::move(task)); } return result; }};template<class R>struct Future : private SharedFuture<R> { // differs only in minor details, such as the signature of get()};And here's Promise<T>:template<class R>struct SharedState { R value_; std::exception_ptr exception_; bool ready_ = false; std::mutex mtx_; std::condition_variable cv_; std::list<UniqueFunction<void()>> continuations_;};template<class R>struct Promise { std::shared_ptr<SharedState<R>> state_; bool future_already_retrieved_ = false; Promise() : state_(new SharedState<R>) {} Promise(const Promise&) = delete; Promise& operator=(const Promise&) = delete; Promise(Promise&&) = default; Promise& operator=(Promise&& rhs) { if (this != &rhs) abandon_state(); state_ = std::move(rhs.state_); return *this; } ~Promise() { abandon_state(); } Future<R> get_future() { if (state_ == nullptr) throw no_state; if (future_already_retrieved_) throw future_already_retrieved; future_already_retrieved_ = true; return Future<R>(state_); } void set_value(R r) { if (state_ == nullptr) throw no_state; if (state_->ready_) throw promise_already_satisfied; state_->value_ = std::move(r); set_ready(); } void set_exception(std::exception_ptr p) { if (state_ == nullptr) throw no_state; if (state_->ready_) throw promise_already_satisfied; state_->exception_ = std::move(p); set_ready(); } bool has_extant_future() const { if (state_ == nullptr) return false; return future_already_retrieved_ && !state_.unique(); } private: void set_ready() { std::lock_guard<std::mutex> lock(state_->mtx_); state_->ready_ = true; for (auto& task : state_->continuations_) { SystemScheduler().schedule(std::move(task)); } state_->continuations_.clear(); state_->cv_.notify_all(); } void abandon_state() { if (state_ != nullptr && !state_->ready_) { set_exception(std::make_exception_ptr(broken_promise)); } }};
Cancellable futures, interaction with throwing destructors
c++;reinventing the wheel;asynchronous;pointers;exception
null
_computergraphics.69
If rendering an image in 2D, adding depth of field effects (blurring objects further from the focal distance) adds realism and draws the eye to the object of the image. With a 3D (i.e. stereo) image, looking at an object in the image at a given depth will makes objects at all other depths defocused (not blurred, but incorrectly aligned by the eyes, giving a double image). This means that if depth of field effects are used, there will be conflicting results: looking at an object that is at a different depth will cause that depth to be the only depth not having a double image, but it is also a depth that is blurred. This gives the object a property of being focused upon, and a property of not being focused upon. In a 3d still image, are depth of field effects detrimental to the acceptance of the image by the eye, or are there ways around this?
Is depth of field incongruous in a 3D still image?
depth of field;3d;stereo rendering
In traditional stereo 3D, I don't believe that there is a way to make a fixed focal plane feel natural to the viewer. When looking at an out-of-focus object in stereo 3D, the object remains out-of-focus, causing conflicting cues. The lens in the eye tries to adjust to bring the object into focus, but of course it won't succeed, causing eye strain and headaches.However, there is hope outside stereo 3D: Lightfield displays, such as this nvidia prototype, go a different route. In stereo 3D, the light in the scene is already captured by two virtual (or physical) cameras, baking in the focal plane. Head-mounted displays like Oculus Rift then attempt to tape two displays in front of your eyes in such a way that the retina receives the exact same image that was captured by the camera. Lightfield displays go a different route: Instead of capturing two images ahead of time, they reproduce the entire 4D light field in front of your eyes, allowing your eyes to capture the image as if they were sitting directly inside the virtual scene. This has a number of benefits, including much smaller and lighter hardware as well as giving your eyes the ability to refocus.If there is a way to make lightfield displays technically and commercially viable, then I believe they can remove the need for depth of field and fixed focal planes entirely and make VR feel a whole lot more comfortable for the viewer. However, it is likely not possible to construct lightfield screens, so televisions and cinemas won't be able to use this technology.
_cseducators.235
I have student who is attempting an independent study next year in audio processing. Her goals involve detecting the meter of a song. Thus could be done through machine learning, or through other forms of AI.While she will eventually be creating a science fair project, she has asked for advice on what to study over the summer in order to make the most of next year. I have no experience in this realm. I know that she had not yet taken AP Statistics, but I also don't know how much statistical knowledge is really necessary.As some context, she is a rising high school junior who has already taken AP Computer Science, and a course on C and Assembly Programming.Can anyone advise on how I can guide her?
Self guided learning about audio processing
curriculum design;artificial intelligence;self learning;sound processing
null
_unix.386950
Please correct me if I am wrong: When a bash shell runs an external executable program, the bash shell will create a child process to run the program in foreground. If there is any key-generated signal, the signal will be sent to the child process and handled by program.When a bash shell runs a builtin command, the bash shell will run the builtin command in the shell process directly in foreground. If there is any key-generated signal, will the signal be sent to the shell process? Which will handle the signal, the builtin command's program or bash? Can a builtin command have its own signal handler, or does it have to rely on the signal handlers of bash?For example, when a bash shell is running wait in foreground and I press Ctrl-C, will the signal SIGINT be received by the shell process and handled by wait or by bash? Does wait have its own signal handler or rely on the signal handler of bash?Thanks.
When a shell runs a builtin, and a signal is generated by keyboard, what will handle the signal?
bash;signals;shell builtin
null
_codereview.160360
I found myself in need of a fixed size queue and decided to implement one using a ring (cyclic) buffer. I have tried my best to match the API of std::queue with the addition of full() to test if the queue is full and unable to accept another element.The code compiles cleanly with: -Wall -Wextra -pedantic --std=c++14 -lgtest -lgtest_main, it runs and all tests pass on clang 3.9.1. Unfortunately at least GCC 4.9.4 and below cannot compile the header file due to a bug where a noexcept specification can't refer to a member. All comments welcome.File: xtd/fixed_queue.hpp#ifndef GUARD_INCLUDE_XTD_FIXED_QUEUE_HPP#define GUARD_INCLUDE_XTD_FIXED_QUEUE_HPP#include <array>#include <cstdint>#include <stdexcept>namespace xtd { template <typename T, std::size_t N> class fixed_queue { public: using value_type = T; using reference = value_type&; using const_reference = const value_type&; using size_type = std::size_t; fixed_queue() = default; fixed_queue(const fixed_queue& other) { *this = other; } fixed_queue(fixed_queue&& other) { *this = std::move(other); } ~fixed_queue() { clear(); } fixed_queue& operator=(const fixed_queue& other) { clear(); auto i = other.m_read_idx; while (i != other.m_write_idx) { emplace(*other.get(i)); i = other.increment_index(i); } return *this; } fixed_queue& operator=(fixed_queue&& other) { clear(); while (!other.empty()) { emplace(std::move(other.front())); other.pop(); } return *this; } size_type capacity() const { return N; } size_type size() const { if (empty()) { return 0; } else if (m_write_idx > m_read_idx) { return m_write_idx - m_read_idx; } else { return N - m_read_idx + m_write_idx + 1; } } void clear() { while (!empty()) { pop(); } } bool full() const { return size() == capacity(); } bool empty() const { return m_write_idx == m_read_idx; } reference front() { return const_cast<reference>(cthis()->front()); } const_reference front() const { assert_not_empty(Cannot peek an empty queue!); return *get(m_read_idx); } void pop() { assert_not_empty(Cannot pop an empty queue!); auto old_idx = m_read_idx; m_read_idx = increment_index(m_read_idx); get(old_idx)->~value_type(); } void swap(fixed_queue<T, N>& other) noexcept(noexcept(swap(this->m_data, other.m_data))) { using std::swap; swap(m_data, other.m_data); swap(m_write_idx, other.m_write_idx); swap(m_read_idx, other.m_read_idx); } template <typename... Args> void emplace(Args&&... args) { assert_not_full(Cannot push to a full queue!); new (get(m_write_idx)) value_type(std::forward<Args>(args)...); m_write_idx = increment_index(m_write_idx); } private: // We add one to the capacity, this avoids the problem that: // read_idx == write_idx on both an empty and a full queue. // We will never get truly full as there will always be one // extra space. alignas(value_type) std::array<uint8_t, sizeof(value_type) * (N + 1)> m_data; size_type m_write_idx = 0; size_type m_read_idx = 0; auto cthis() const { return const_cast<const fixed_queue<T, N>*>(this); } auto assert_not_empty(const char* message) const { if (empty()) { throw std::runtime_error(message); } } auto assert_not_full(const char* message) const { if (full()) { throw std::runtime_error(message); } } auto increment_index(size_type i) const { return (i + 1) % (N + 1); } auto get(size_type i) { return const_cast<value_type*>(cthis()->get(i)); } auto get(size_type i) const { return reinterpret_cast<const value_type*>(m_data.data()) + i; } }; template <typename T, std::size_t N> void swap(fixed_queue<T, N>& a, fixed_queue<T, N>& b) noexcept(noexcept(a.swap(b))) { a.swap(b); }}#endifFile: test/fixed_queue.cpp#include xtd/fixed_queue.hpp#include <gtest/gtest.h>#include <ostream>std::ostream& operator<<(std::ostream& os, const std::vector<std::string>& v) { os << [; auto first = true; for (auto& x : v) { if (!first) { os << , ; } first = false; os << x; } os << ]; return os;}namespace xtd { std::vector<std::string> destructorCalls; std::vector<std::string> constructorCalls; std::vector<std::string> copyConstructorCalls; std::vector<std::string> moveConstructorCalls; class TestClass { public: TestClass(const std::string& name) : m_name(name) { constructorCalls.emplace_back(m_name); } TestClass(TestClass&& other) : m_name(std::move(other.m_name)) { other.m_name = --MOVED--; moveConstructorCalls.emplace_back(m_name); } TestClass(const TestClass& other) : m_name(other.m_name) { copyConstructorCalls.emplace_back(m_name); } ~TestClass() { destructorCalls.emplace_back(m_name); } bool operator==(const TestClass& other) const { return m_name == other.m_name; } const std::string& name() const { return m_name; } private: std::string m_name; }; class fixed_queue_test : public ::testing::Test { protected: virtual void SetUp() { constructorCalls.clear(); copyConstructorCalls.clear(); moveConstructorCalls.clear(); destructorCalls.clear(); } virtual void TearDown() {} }; TEST_F(fixed_queue_test, CopyAssignmentWithComplexObject) { auto cut = fixed_queue<TestClass, 3>(); // Create a test case that is partially wrapped around. cut.emplace(foo); // index 0 cut.pop(); cut.emplace(bar); // 1 cut.pop(); cut.emplace(baz); // 2 cut.emplace(boz); // index 0 auto copy = fixed_queue<TestClass, 3>(); copy.emplace(beef); // make sure old data is cleared copy = cut; ASSERT_EQ(cut.size(), copy.size()); ASSERT_EQ(cut.front().name(), copy.front().name()); ASSERT_EQ(0, moveConstructorCalls.size()); ASSERT_EQ(5, constructorCalls.size()); ASSERT_EQ(2, copyConstructorCalls.size()); ASSERT_EQ(3, destructorCalls.size()); ASSERT_EQ(baz, copyConstructorCalls[0]); ASSERT_EQ(boz, copyConstructorCalls[1]); } TEST_F(fixed_queue_test, MoveAssignmentWithComplexObject) { auto cut = fixed_queue<TestClass, 32>(); cut.emplace(foo); cut.emplace(bar); cut.emplace(baz); cut.pop(); auto copy = fixed_queue<TestClass, 32>(); copy.emplace(beef); copy = std::move(cut); ASSERT_EQ(2, copy.size()); ASSERT_EQ(bar, copy.front().name()); // std::cout<<moveConstructorCalls<<std::endl; ASSERT_EQ(2, moveConstructorCalls.size()); ASSERT_EQ(4, constructorCalls.size()); ASSERT_EQ(4, destructorCalls.size()); ASSERT_EQ(bar, moveConstructorCalls[0]); ASSERT_EQ(baz, moveConstructorCalls[1]); ASSERT_EQ(foo, constructorCalls[0]); ASSERT_EQ(bar, constructorCalls[1]); ASSERT_EQ(baz, constructorCalls[2]); ASSERT_EQ(beef, constructorCalls[3]); ASSERT_EQ(foo, destructorCalls[0]); ASSERT_EQ(beef, destructorCalls[1]); ASSERT_EQ(--MOVED--, destructorCalls[2]); ASSERT_EQ(--MOVED--, destructorCalls[3]); } TEST_F(fixed_queue_test, EmplacePopWithComplexObject) { auto cut = fixed_queue<TestClass, 32>(); ASSERT_TRUE(constructorCalls.empty()); ASSERT_TRUE(destructorCalls.empty()); cut.emplace(foo); ASSERT_EQ(1, constructorCalls.size()); ASSERT_EQ(foo, constructorCalls[0]); ASSERT_TRUE(destructorCalls.empty()); cut.emplace(bar); cut.emplace(baz); cut.pop(); ASSERT_EQ(3, constructorCalls.size()); ASSERT_EQ(bar, constructorCalls[1]); ASSERT_EQ(baz, constructorCalls[2]); ASSERT_EQ(1, destructorCalls.size()); ASSERT_EQ(foo, destructorCalls[0]); } TEST_F(fixed_queue_test, ClearWithComplexObject) { constructorCalls.clear(); destructorCalls.clear(); auto cut = fixed_queue<TestClass, 32>(); cut.emplace(foo); cut.emplace(bar); cut.emplace(baz); cut.clear(); ASSERT_TRUE(cut.empty()); ASSERT_EQ(0, cut.size()); ASSERT_EQ(3, constructorCalls.size()); ASSERT_EQ(foo, constructorCalls[0]); ASSERT_EQ(bar, constructorCalls[1]); ASSERT_EQ(baz, constructorCalls[2]); ASSERT_EQ(constructorCalls, destructorCalls); } TEST_F(fixed_queue_test, DestructorWithComplexObject) { constructorCalls.clear(); destructorCalls.clear(); { auto cut = fixed_queue<TestClass, 32>(); cut.emplace(foo); cut.emplace(bar); cut.emplace(baz); } ASSERT_EQ(3, constructorCalls.size()); ASSERT_EQ(foo, constructorCalls[0]); ASSERT_EQ(bar, constructorCalls[1]); ASSERT_EQ(baz, constructorCalls[2]); ASSERT_EQ(constructorCalls, destructorCalls); } TEST_F(fixed_queue_test, DefaultConstructor) { auto cut = fixed_queue<int, 32>(); ASSERT_EQ(32, cut.capacity()); ASSERT_TRUE(cut.empty()); ASSERT_FALSE(cut.full()); ASSERT_EQ(0, cut.size()); } TEST_F(fixed_queue_test, SimpleUsage) { auto cut = fixed_queue<int, 4>(); cut.emplace(1); ASSERT_FALSE(cut.empty()); cut.emplace(2); cut.emplace(3); cut.emplace(4); ASSERT_EQ(1, cut.front()); ASSERT_EQ(4, cut.size()); ASSERT_FALSE(cut.empty()); ASSERT_TRUE(cut.full()); ASSERT_EQ(4, cut.capacity()); cut.pop(); ASSERT_EQ(2, cut.front()); ASSERT_EQ(3, cut.size()); ASSERT_FALSE(cut.full()); cut.pop(); ASSERT_EQ(3, cut.front()); ASSERT_EQ(2, cut.size()); cut.pop(); ASSERT_EQ(4, cut.front()); ASSERT_EQ(1, cut.size()); cut.pop(); ASSERT_EQ(0, cut.size()); ASSERT_TRUE(cut.empty()); } TEST_F(fixed_queue_test, LoopingUsage) { const int capacity = 10; const int laps = 3; for (int window = 1; window <= capacity; ++window) { int counter = 0; auto cut = fixed_queue<int, capacity>(); for (int i = 0; i < window; ++i) { cut.emplace(counter++); } try { for (int i = 0; i < capacity * laps; ++i) { std::string msg = Window: + std::to_string(window) + i= + std::to_string(i); ASSERT_EQ(counter - window, cut.front()) << msg; cut.pop(); cut.emplace(counter++); ASSERT_EQ(window, cut.size()) << msg; } } catch (...) { std::cout << Window: << window << std::endl; throw; } } }}
Implementation of fixed size queue using a ring (cyclic) buffer
c++;c++14;collections;circular list
Non Standard Copy SemanticsInterested in why you chose to implement the copy constructor in terms of the copy assignment operator and not the other way around. Noting that the standard way to implement this is the copy and swap idiom (other way around).I can see this is probably slightly more efficient. But is the decrease in readability worth it. Only you can answer that.fixed_queue(const fixed_queue& other) { *this = other; }fixed_queue& operator=(const fixed_queue& other) { clear(); auto i = other.m_read_idx; while (i != other.m_write_idx) { emplace(*other.get(i)); i = other.increment_index(i); } return *this;}The one issue I have with this is that it does not provide the strong exception guarantee and you can't fall back to the original state if something goes wrong.Though this is correct. I don't like the copy constructor not explicitly initializing the members. Have to go check the rest of the code to make sure the members are initialized reeks of doing things in multiple places.Move SemanticsThe source of the move can be left in an undefined state (as long as it is valid).I don't see the need to pop() values from the source object. just move them. Poping them adds extra work that is not required. The destructor when called when do all the cleanup required.fixed_queue& operator=(fixed_queue&& other) { clear(); while (!other.empty()) { emplace(std::move(other.front())); // Don't need this. // Though if you do remove this you need to change the above line // to get a reference to an internal member. other.pop(); } return *this;}AlignmentNot 100% convinced this works.alignas(value_type) std::array<uint8_t, sizeof(value_type) * (N + 1)> m_data;You want the internals of the array (ie. the array members) to be aligned to value_type. This is technically aligning the array (not its members). I have not read up on the requirements of the array (so this may work) but this seems a bit doggy.Just point this works because std::array is a special case (guaranteed to only have one element that aligns with the specified data type). In general aligning containers on their content data type may not work.Initializationsize_type m_write_idx = 0;size_type m_read_idx = 0;I prefer the constructor to initialize members. It's easier to spot when things are missed. If you are going to initialize the members in the code then I prefer them near the construcors so that it is easy to spot.Personally I lay my code out like this:Class private Variables public Constructors/Assignment/Destructors public methods protected methods private methodsThis way I can quickly see if the members have all been initialized.
_softwareengineering.329117
I want to ask for any suggestions for an architecture I can implement for a Java app I need to create (initial thoughts below).It is supposed to be a local Swing application for tracking financial aspects of multiple construction sites. Excel-like but with a few additional features like mailing data etc.After some thinking, I came up with an idea of using a Derby database with a separate table for clients, another one for categories of products used and multiple ConstructionX tables, each containing records for a different construction site, created dynamically via JDBC.That last part is what I'm most concerned about as it doesn't really feel like a good solution programatically but it does so pragmatically.I don't really have much experience building applications like this so here comes my question: Is there any better way I could design this database? I'm open for suggestions (please don't post it on TheDailyWTF).(I originally asked this question on StackOverflow and was redirected here)As a side note (as someone on SO suggested something like this too): I originally planned to create just one Construction table which would hold records for all construction sites where each record would be tagged with a construction site number it refers to (possibly forming a relation to a table holding all sites). However, I was worried about times of running SELECT statements (when displaying all records just for one specific site). Can anyone confirm it'd be a better solution here?
Performance: One table vs multiple tables (generated programatically) for the same logical entity?
java;database design
Creating separated tables for the same entity based on a domain value is generally a bad idea.Talking about CONNSTRUCTION and CONSTRUCTION_SITE:Make sure the tables are apropiatelly indexedCONSTRUCTION has a PKCONSTRUCTION_SITE has a PKCONSTRUCTION has a FK pointing to CONSTRUCTION_SITEThere will be an index for every PK and every FK.The database engine will take care of, as fast as it can, filter out the rows you want. That's what database engines are for.As they say: Premature optimization, etc.
_webapps.100195
We use Cognito for a long, complex application process with application windows every 6 months. I have a large number of users that started the form and I would like to be able to email them their resume URL rather than have them call/email to have it manually resent. I have exported the data to excel, but I can't find a field/column that would be the resume URL. Does this exist, or alternatively can I get to t thru an API or Zapier?
How can I export the cognito forms resume URL for all incomplete submissions
cognito forms
null
_unix.296697
I want to encrypt a file with a private key and decrypt it with a public key. A public key will be embedded in my app. So I want to have a guarantee that the file was created by me. How can I use gpg or openssl to implement it.
How to encrypt a file with private key
openssl;gpg;signature
It makes no sense to encrypt a file with a private key.Using a private key to attach a tag to a file that guarantees that the file was provided by the holder of the private key is called signing, and the tag is called a signature.There is one popular cryptosystem (textbook RSA) where a simplified (insecure) algorithm uses has public and private keys of the same type, and decryption is identical to signature and encryption is identical to verification. This is not the case in general: even RSA uses different mechanisms for decryption and signature (resp. encryption and verification) with proper, secure padding modes; and many other algorithms have private and public keys that aren't even the same kind of mathematical objects.So you want to sign the file. The de facto standard tool for this is GnuPG.To sign a file with your secret key:gpg -s /path/to/fileUse the --local-user option to select a secret key if you have several (e.g. your app key vs your personal key).Transfer file.gpg to the place where you want to use the file. Transfer the public key as well (presumably inside the application bundle). To extract the original text and verify the signature, rungpg file.gpgIf it's more convenient, you can transfer file itself, and produce a separate signature file which is called a detached signature. To produce the detached signature:gpg -b /path/to/fileTo verify:gpg file.gpg fileYou can additionally encrypt the file with the -e option. Of course this means that you need a separate key pair, where the recipient (specified with the -r option) has the private key and the producer has the public key.
_webmaster.22305
Is there a way to find if the site is using shared hosting hosting or not?
Is there a way to find if the site is using shared hosting
web hosting;shared hosting
You can try using a reverse IP lookup and see how many other websites run on the same IP:Something like: http://www.yougetsignal.com/tools/web-sites-on-web-server/
_webmaster.24614
I'm about to re-launch a uk based community interest company website which has the same link structure for each of 10 different top level domains.There are presently no international websites, but there may be in the future.For simplicity's sake I intend to nominate a single primary domain (.org.uk) and then use htaccess to redirect incoming traffic from alternative TLD's back to the primary domain.Is this best practice in terms of efficiency and SEO?Would there be any benefit to using .com or .co.uk as the primary domain.
Best practice for URL direction in a multi TLD site
seo;domains;top level domains
There is no SEO bias towards any major tld, such as the ones you mentioned. The only thing you need to take into consideration here is which tld is best suited by definition - .co.uk for a site that is for a UK audience, .org.uk for an organization in the uk or .com for an international website. I would personally go with .com as it allows you to expand internationally in the future (you mentioned you might), it's arguably the easiest to remember/one most people are familiar with.You're absolutely correct in redirecting each extension back to your chosen one (a 301 redirect in your .htaccess would be the way to go).Also, add each site to your bing/google webmaster tools and configure accordingly. :-)Hope this helps.
_unix.344928
I have a Scientific Linus 6.7 box that serves some applications on our network. The person who set it up is no longer around. This morning machine stopped booting. There are two HDD's and they both show up in BIOS. If I put another HDD in, it boots fine.I ran Ubuntu from another drive and Gparted shows the original drives are LVM2. I installed LVM and can see that they were configured to be used as one logical drive of combined capacity.My hunch is that one of the drives failed. Can I rescue any data?
Can I rescue any data if one of two drives in LVM failed?
lvm;data recovery;raid;scientific linux
null
_unix.350132
I have been partially successful with this, but I am stuck. Here is my script:I want to prompt the user, wait for input from a USB gamepad, and then execute a command based on which button is pressed.if lsusb | grep -q '0583:2060'then echo press the A button # if jstest --event /dev/input/js0 | grep -q number 0, value 1 then echo you pressed the A button else echo you pressed the NOT A button fifiIt checks for the gamepad being connected just fine. It also checks the jstest and echos you pressed the A button when I press the A button. I can't get it to execute the else part in this situation though, as grep filters only button 0, value 1 from jstest (the A button), which means if I am not pressing the A button jstest is piping NOTHING to grep, it always waits for the A button.I was thinking maybe there was some way to do:grep -q number ., value 1 which will return ANY button being pressed, and then have different commands executed based on what what grep shows. I thought I could use a case statement for this, but I can't get jstest to work with case. I feel like jstest isn't meant for this kind of stuff, only to test, but extensive googling has shown me no other options for interacting with a game pad through a script.How can I make a shell script that prompts the user, waits for a button press, then executes different commands based on which button was pressed?
Using a shell script with jstest, how can I get a gamepad to interact with my script?
shell script
null
_softwareengineering.227651
My organization was flat two years ago, and people felt that the general manager had disproportionate almost dictatorial powers. Also the general manager didn't have time to coach employees, so some employees were dysfunctional and nothing was done about them. However on the plus side everyone was involved in the decision making, thus motivation was very high.So what do you think about flat vs hierarchical organizational structures in software development?
Flat organizations vs hierarchical for software development
organization
null
_webmaster.99867
The use case is a document which has multiple versions which are all simultaneously available. For example, documentation on a product for each version of that software:/v1/install-guide/v2/install-guide/v3/install-guideThese are not the same content in the sense that it would be incorrect to specify in the v1 and v2 pages that the canonical URL is v3. If I searched in Google for 'product install guide v2' I'd expect to be able to find v2. Each version of the document would be slightly different but they'd have a lot in common with each other.So the question is: can I mark up these pages in some way to signal to Google and friends that the latest version (v3) is preferred, so a simple search for 'product install guide' is more likely to show the v3 page instead of the v1 or v2 page?
How to correctly mark up different versions of the same document which are non-canonical
seo;duplicate content;canonical url
null
_unix.261268
I have a set of hosts that I can only access via openVPN (one VPN per host or group of hosts). ssh is only available after connected to the VPN.Is there any way to automatically bring up the VPN connection for the individual hosts / host groups inside the inventory using default ansible methods?
using ansible via vpn
vpn;ansible
null
_webmaster.84708
I was wondering the about the effect a duplicate/similar codebase of products would have on a sites SEO across 190 domains.We have a dealer group with 190 for a certain class of products e.g. hardware & building supplies in the same country. As part of thier membership to the dealer group our members recieve printed catalogues of 2500 - 7000 products, they also get a web solution with all the catalogue products listed which allows b2b ordering, searching and quote requests on these items. We are looking into making these sites more SEO friendly (readable url's, responsive, keywords etc) nothing serious, pretty much just make sure we check all the basics. All the websites point to the same codebase, which then fetches the members template and product/category visibility and displays the site.My questions are as follows...Would there be any negative ranking effect based on the repeated listings of products from different domains served from the same ip? Thousands of products have identical short and long descriptions,keywords,codes and images.What would be the best way to implement and xml sitemap for each different domain? I have considered generating a sitemap for each domain in a directory i.e /allsitemaps with a disallow bots file and then adding a route to the site that points to the correct sitemap depending on the url so www.sample.com/sitemap.xml actually returns www.sample.com/allsitemaps/sample.com/sitemap.xml. Do you think this approach would work?Sorry if the questions seem basic. I have just enough SEO knowledge to get a unique site indexed reasonably well, but I have no idea how search engines react to a situation like this and am struggling to find any information on the topic.Thanks in advance.
SEO multiple ecommerce website running off the same codebase
seo;sitemap;duplicate content;googlebot;ecommerce
In short, yes. One of the biggest issues in SEO is duplication of content (both externally and internally). If 190 domains all have the exact same products listed that will create lots of duplicate content, and it will be difficult for the sites to rank. However there are ways around this, after all amazon is full of content found elsewheree on the web. Such as adding other unique content to the site, using iframes to 'hide' the duplicated content.Some good tips on this here:Handling User-Generated & Manufacturer-Required Duplicate Content Across Large Numbers of URLsYou can list sitemap.xml files for different domains on a single domain, you just need to verify all domains in the same Search Console acccount.More info here: Manage sitemaps for multiple sites
_unix.87160
In the KDE menu in Knoppix live CD I saw there is a submenu somewhere with the title 'shells' and another with the title 'xshells'.So seemed to me they are two seperate family of shells.What is the difference between them?
What's the difference between shells and xshells?
kde
A shell is a command line application that prompts the user for commands and then executes those commands.X Shell is another word for terminal emulator. It's a graphical application that allows you to run a command line application inside it and thus allows you to execute command line applications in a graphical environment.When you select an entry in the Shells menu, the selected shell will be started in your default terminal emulator/xshell. When you select an entry in the XShells menu, your default shell will be started in the selected terminal emulator.
_codereview.124782
I have a query in MSSQL, where I get a summary by days from a range in a table, and this is in union with other queries. This query is used to generate days in a specific range, then add the registry per day, and exclude the registry that are equal to others (in this case, count the rows that tipo is 1, and tipo = 0, and if both are equal, exclude this), and then do a union with a single query.Is there any way to improve this query?USE [C:\PROGRAMDATA\REGISFING\REGISFING.MDF];/* Borre las tablas temporales si existen. */IF OBJECT_ID('tempdb..#Period') IS NOT NULL DROP TABLE #Period;IF OBJECT_ID('tempdb..#Registro') IS NOT NULL DROP TABLE #Registro;DECLARE @FInicio date = '29/02/2016';DECLARE @FFinaliza date = '04/04/2016';/* Los siguientes son para utilizar los listados en los filtros */DECLARE @Cedula table(Ced int);INSERT @Cedula(Ced) VALUES (1073237901), (1032456940), (1070622582), (45504769);DECLARE @Puntos table(Punto int);INSERT @Puntos(Punto) VALUES (0), (43), (99);/* Importante al pasar al .Net se debe modificar y adjuntar segn las elecciones en los controles */WITH CTE AS (SELECT DISTINCT CONVERT(date,Inicio,101) AS StartTime, DATEDIFF(dd, Inicio, Finaliza) AS diff, cedula FROM Asignaciones /* Aqu colocar el codigo para las cedulas especficas */ WHERE cedula IN (SELECT Ced FROM @Cedula)UNION ALL SELECT StartTime, diff - 1 AS diff, cedula FROM CTE WHERE diff <> 0) SELECT DISTINCT DATEADD(dd, diff, StartTime) AS Dias, C.cedula INTO #Period FROM CTE C, Asignaciones A WHERE C.cedula = A.cedula /* Filtra entre las fechas especificadas */ AND (DATEADD(dd, diff, StartTime) BETWEEN @FInicio AND @FFinaliza) GROUP BY StartTime, C.cedula, diff--, R.Fecha ORDER BY C.Cedula, DiasSELECT R.cedula, (CAST(Fecha AS date)) AS Dia, Tipo_Reg, COUNT(CAST(R.Fecha AS date)) AS Cantidad INTO #Registro FROM Registro R /* Filtra entre las fechas especificadas */ WHERE R.Fecha BETWEEN @FInicio AND @FFinaliza /* Filtra entre las cedulas especificadas */ AND cedula IN (SELECT Ced FROM @Cedula) /* Filtra entre las ubicaciones especificadas */ AND (R.IdUbicacion IN (SELECT Punto FROM @Puntos))GROUP BY R.cedula, (CAST(R.Fecha AS date)), R.Tipo_Reg/* Se unen las dos consultas temporales */SELECT 'XX No timbrados' AS column1, CONCAT(p.cedula, ' ', U.Nombre, ' ', U.Apellido) AS column2, 'Diferencias' AS column3, CAST(p.Dias AS datetime) AS column4, CONCAT('Entradas: ', CASE WHEN SUM(CASE WHEN R.Tipo_Reg = 0 THEN Cantidad END) IS NULL THEN 'No timbr' ELSE CAST(SUM(CASE WHEN R.Tipo_Reg = 0 THEN Cantidad END) AS varchar) END, ' - Salidas: ', CASE WHEN SUM(CASE WHEN R.Tipo_Reg = 1 THEN Cantidad END) IS NULL THEN 'No timbr' ELSE CAST(SUM(CASE WHEN R.Tipo_Reg = 1 THEN Cantidad END) AS varchar) END) AS column5 FROM Usuario U, #Period p LEFT JOIN #Registro r on r.cedula = p.cedula AND r.Dia = p.Dias WHERE U.cedula = P.cedula GROUP BY P.cedula, U.Nombre, U.Apellido, CAST(p.Dias AS datetime) HAVING SUM(CASE WHEN R.Tipo_Reg = 0 THEN Cantidad END) IS NULL OR SUM(CASE WHEN R.Tipo_Reg = 1 THEN Cantidad END) IS NULL OR SUM(CASE WHEN R.Tipo_Reg = 0 THEN Cantidad END) <> SUM(CASE WHEN R.Tipo_Reg = 1 THEN Cantidad END) UNION ALLSELECT CONCAT(P.IdUbicacion, ' ', P.nombre) AS column1, CONCAT(U.cedula, ' ', U.Nombre, ' ', U.Apellido) AS column2, (CASE WHEN R.Tipo_Reg = 1 THEN 'Entrada' ELSE 'Salida' END) AS column3, N.Fecha AS column4, N.Observacion AS column5 FROM Novedades N, Usuario U, Registro R, Ubicacion P WHERE (U.cedula = N.cedula AND R.cedula = N.cedula AND R.Fecha = N.Fecha AND R.IdUbicacion = P.IdUbicacion) AND R.Fecha BETWEEN @FInicio AND @FFinalizaORDER BY column1, column2, column4
Generating days in a specific range
sql;datetime;sql server
null
_unix.371434
I am trying to use find to find files matching a certain pattern, and then symlink their parent directorys to another directory, this is my current script (I'm doing this on mac so -printf won't work here):#!/usr/bin/env bashPROCESS_DIR=/Users/me/Google Drive/MeOUTPUT_DIR=/Users/me/OfflineFolder# Copy directory structure and then make symlinksrm -R $OUTPUT_DIR;mkdir $OUTPUT_DIR;cd $PROCESS_DIR;find . -name *.md -exec ln -vs $(dirname {}) $OUTPUT_DIR \;But it doesn't seem to be working. This script however does work (makes symlinks to all the md files on my computer:# Copy directory structure and then make symlinksrm -R $OUTPUT_DIR;mkdir $OUTPUT_DIR;cd $PROCESS_DIR;find . -type d -exec mkdir -vp $OUTPUT_DIR/{} \;find . -name *.md -exec ln -vs $(pwd)/{} $OUTPUT_DIR/{} \;find $OUTPUT_DIR -type d -empty -deleteAny idea why this is not working? I've tried several different approaches (including using find $PROCESS_DIRECTORY instead of cd $PROCESS_DIRECTORY). Thanks
Find a file and make a symlink to parent using find and -exec
shell script;find;quoting;command substitution
You have two problems, both related to the order in which things happen.find . -name *.md -exec ln -vs $(dirname {}) $OUTPUT_DIR \; is a single command. The shell parses it before executing it. Amongst the step in parsing:$() is a command substitution, so dirname {} is executed, yielding . (there's no directory part in {}).$OUTPUT_DIR is a variable substitution, so it's replaced by its value.*.md is a glob pattern, so it's replaced by the list of matching files. If there are no matches, the pattern remains in place.This completes the work required to determine what command to execute.If there are no files matching *.md in the current directory then the following command is executed with the given arguments: find, ., -name, *.md, -exec, ln, -vs, ., /Users/me/OfflineFolder, ;.If *.md matches bar.md and foo.md then the command is find, ., -name, foo.md, -exec, (and find will miss any file called something-other-than-foo.md in subdirectories).If *.md matches bar.md and foo.md then the command is find, ., -name, bar.md, foo.md, -exec, (and find will complain of a syntax error).You want to execute dirname on the find results. This means that you need to instruct find to run dirname. You can do that, but find doesn't have any mechanism to gather the output from dirname and pass it as an argument to ln. For this you need a tool such as a shell, where it's a command substitution.So here's the strategy: tell find to invoke a shell, and tell that shell to run the command involving ln and dirname. You need to take care of quoting. Put the shell command in single quotes to avoid having its special characters interpreted by the outer shell. Also put the pattern for -name in quotes so that it's passed to find and not expanded by the outer shell.find . -name '*.md' -exec sh -c 'ln -vs ' \;The next step is to complete the . Do not use {} inside the shell command: that would just place the file name as a snippet of shell code, and any special characters would be parsed by the inner shell. Instead, pass the file name given by find as an argument to the shell script. The first argument after sh -c CODE is the name of the shell instance ($0), but you can use it for whatever purpose you like; subsequent argument are the positional parameters ($1, $2, ).find . -name '*.md' -exec sh -c 'ln -vs $(dirname $0) $1' {} $OUTPUT_DIR \;I've passed $OUTPUT_DIR as an argument to the script. It doesn't matter here because the value doesn't contain any shell special characters, but it's a good habit to get into, you never know when someone might change the path to e.g. include spaces. Another possibility would be to pass it through the environment:export OUTPUT_DIRfind . -name '*.md' -exec sh -c 'ln -vs $(dirname $0) $OUTPUT_DIR' {} \;Instead of dirname, you can use a textual substitution: remove everything after the last slash. You don't have to worry about the special case where there's no directory part as this doesn't happen for a file name passed by find.export OUTPUT_DIRfind . -name '*.md' -exec sh -c 'ln -vs ${0%/*} $OUTPUT_DIR' {} \;You can use the + form of -exec to speed things up a little. I pass _ as $0 and the subsequent arguments are the file names which the for loop iterates over.export OUTPUT_DIRfind . -name '*.md' -exec sh -c 'for x; do ln -vs ${x%/*} $OUTPUT_DIR; done' _ {} +
_codereview.173105
I've written a script in python to scrape e-mail addresses from different pizza shops located in los-angeles available in yellowpage traversing multiple pages. It is able to go one-layer deep and dig out email addresses. I believe, this crawler has got the ability to parse all the emails from any link no matter how many pages it has spread across. Just needed to adjust the last page number in the crawler.Here is what I've written:import requestsfrom lxml import htmllink = https://www.yellowpages.comfor page_num in range(1,10): for item in html.fromstring(requests.get(https://www.yellowpages.com/search?search_terms=pizza&geo_location_terms=Los%20Angeles%2C%20CA&page={0}.format(page_num)).text).cssselect('div.info h2.n a:not([itemprop=name]).business-name'): for data in html.fromstring(requests.get(link + item.attrib['href']).text).cssselect('a.email-business'): print(data.attrib['href'].replace(mailto:,))
E-mail crawler for yellowpages
python;python 3.x;web scraping;lxml
Knowing that you had a ton of scrappers questions, this doesn't look nice at all. It looks like you were in a hurry and didn't much care about how the code looks.StylingUse 4 spaces per indentation levelConstants should be LOWERCASEDYou should have a space after ,Your lines are way too long. Stick to 72 characters or 120 (at most)CodeFirst, you don't have to hardcode your search items. Instead, you might as well define a function which returns the data you need (the entire URL):def build_url(item, location, page): params = urllib.parse.urlencode({ 'search_terms': item, 'geo_location_terms': location, 'page': page }) return '{}/search?{}'.format(URL, params)With that in mind, your code might be restructured nicer, like this:import requestsimport urllibfrom lxml import htmlURL = https://www.yellowpages.comLOWER_LIMIT = 1UPPER_LIMIT = 10def build_url(item, location, page): params = urllib.parse.urlencode({ 'search_terms': item, 'geo_location_terms': location, 'page': page }) return '{}/search?{}'.format(URL, params)def scrape(): for page in range(LOWER_LIMIT, UPPER_LIMIT): url = build_url('pizza', 'Los Angeles CA', page) html_ = requests.get(url).text for item in html.fromstring(html_).cssselect('div.info h2.n a:not([itemprop=name]).business-name'): for data in html.fromstring(requests.get(URL + item.attrib['href']).text).cssselect('a.email-business'): print(data.attrib['href'].replace(mailto:, ))if __name__ == '__main__': scrape()Other changes that I did above:Move the logic into separate functionsMake the range arguments constants so that they can be easily modifiedAdd the guard check if __name__ == '__main__'As is, your scrapper is pretty slow because it has to search in each page the entire html for that specific a info. You might consider using Scrapy.
_opensource.1844
With, say, a commercial game (Kerbal Space Program in this instance) with user mods, that are themselves GPL3 licenced and have an effect on the visuals of a screenshot (e.g. art assets, images, custom displays), does a screenshot that includes these custom visuals have to automatically be licenced under the GPL?My specific query is regarding the RasterPropMonitor plugin, which manages and renders real-time HUD screens. In this case, the whole project lists itself as GPL3, so I assume that automatically covers any attached images/textures, which would then undergo transformation/arrangement by the code - and then be visible on a screenshot.I can reason how the project can be allowed to be GPL3, as it is Downstream from the (closed source) base game that it links with (I assume that Unity classes as a 'System Library'), but am troubled by whether everything that touches or relates to the base mod also ends up being GPL3 - e.g. someone who provides a custom screen, is using the GPL3 mod, so that work would also have to be GPL3?
Is a screenshot with GPL3 resources, GPL3?
gpl 3
Screenshots might be a derivative work and might need to comply with GPL (or any other open source license).The factors to determine this are extremely complicated and must be judged individually depending on the screenshot and how the screenshot is being used. They also vary greatly depending what country's laws are being applied.If in doubt, this is a case where you need to contact a lawyer in your local jurisdiction.In the United States most screenshots are fair use because because they are some kind of commentary or education or archival of the original work and also because when you distribute copies of a screenshot you are not causing any financial harm to the copyright holder.In some situations, a screenshot can also be a de minimis copy, for example if a multi billion dollar movie has a scene where for 6 seconds an actor is using Linux... that would not be fair use but it would be such an insignificant use in the scheme of things that the movie cannot be considered a derivative of the GPL'd work. If, however, the movie was about linux then it would not be de minimis and GPL might apply (although if it was about linux then the copy could be fair use...).If fair use or de minimis do not apply, then a screenshot is a derivative work and you must comply with the license. Typically the best option is simply to ask for permission to distribute screenshots, but for GPL that is difficult - depending how the project is run you might need permission from every contributor going back hundreds of years.Fair use and de minimis copying are part of US copyright law however most other countries have something similar. The specific details vary greatly from country to country.You are usually only required to comply with copyright law in your own country. Again, ask a lawyer.
_codereview.143381
ProblemSolve correct flips to sort given input with pancake sort.Exampleinput (input size and values):86 7 2 5 1 4 3 8solution (number of flips and how many elements to flip per operation):62 7 4 5 3 4 2 -> 7 6 2 5 1 4 3 8 7 -> 3 4 1 5 2 6 7 8 4 -> 5 1 4 3 2 6 7 8 5 -> 2 3 4 1 5 6 7 8 3 -> 4 3 2 1 5 6 7 8 4 -> 1 2 3 4 5 6 7 8 alternative solution:63 6 2 5 7 3Program doesn't need to actually sort anything, just give one possible solution.What would be faster way to calculate needed flips without resorting to sorting input with ineffective pancake sort?#include <iostream>#include <algorithm>#include <vector>int main() { using namespace std; ios::sync_with_stdio(false); int N; cin >> N; vector<int> v(N); vector<int> flips; for (int i=0; i<N; ++i) cin >> v[i]; auto first = v.begin(); auto last = v.end(); for (; first != last; --last) { auto mid = max_element(first, last); if (mid == last - 1) { continue; } if (first != mid) { flips.push_back(distance(first, mid+1)); reverse(first, mid + 1); } flips.push_back(distance(first, last)); reverse(first, last); } cout << flips.size() << endl; for (auto flip : flips) cout << flip << ; cout << endl;}
Finding solution for pancake sort efficiently without actually flipping each time
c++;sorting
null
_unix.249485
Just moved from windows and installed Debian 8, got chrome running When i visited google.co.in the various languages are showing as boxes.Tried dkpg-locale reconfigure noting worked ,PS: I am new to linux & debian :)
Fonts Not showing Up - Debian 8
linux;debian;locale
To display non-ASCII characters you need to have the appropriate font packages installed; glyphs that can't be displayed will be shown as a box outline.I generally have the following font packages installed in Debian and see most languages in their own font:fonts-dejavu-extrafonts-freefont-ttffonts-liberationttf-mscorefonts-installerttf-unifontPerhaps you only need one or two, but these give a reasonably complete coverage in my experience.
_unix.274213
(On OS X 10.11.3)I'm having a problem starting a java process that needs to listen on port 8040. Getting a BindException. So seems like somebody else is already listening on it. A quick check confirms that:lsof -i TCP| fgrep LISTEN | grep 8040jspawnhel 13566 alon 255u IPv6 0x2a5edc8fe0a093d7 0t0 TCP *:8040 (LISTEN)jspawnhel 14482 alon 255u IPv6 0x2a5edc8fe0a093d7 0t0 TCP *:8040 (LISTEN)jspawnhel 81770 alon 255u IPv6 0x2a5edc8fe0a093d7 0t0 TCP *:8040 (LISTEN)So, I'm trying to figure out what these processes are, but I don't understand what ps is showing me:ps ax | grep 13566\|14482\|8177013566 ?? U 0:00.00 313:31614482 ?? U 0:00.00 324:32781770 ?? U 0:00.00 301:304what does the ?? mean? what is 313:316 in this context?I can't kill it either, even with -9:kill -9 13566ps ax | grep 1356613566 ?? U 0:00.00 313:316Tried many times...Any help is appreciated.
What are these processes and why can't I kill them?
process;osx;kill;ps
If you run ps ax without the grep, you'll see the column headers:PID TT STAT TIME COMMAND?? is in the TT column -- that's the controlling terminal for the process. The ?? indicates that the process isn't associated with a terminal.The U in the STAT column indicates that the process is in the uninterruptible sleep state. That explains why you cannot kill it -- is blocked in an uninterruptible sleep in the kernel and cannot be awoken to be terminated. When the process eventually exits the uninterruptible state, it will notice the signal and die.The numbers in the right are in the COMMAND column -- that's the name of the process. As for what those processes are, I don't know.
_softwareengineering.323706
I am learning API. I now want to write a program to send an email once some twitter users tweet.I have found there is an API call (user_timeline) which can get the tweets from an user.So my idea is to store the latest tweet, and keep calling user_timeline to detect whether the latest tweet changes. It would require my program to send requests like every single minute.Is this a common way to implement this functionality? Any suggestions would be appreciated!
How to detect someone tweets using twitter API?
algorithms;api;web services;web;twitter
null
_cstheory.20693
I'm looking for a set of permutations over $n$ elements $\mathcal{P}=\{P_1,P_2,...,P_r\}$ of minimal size such that for every ordered subset of size $k$, $S=<x_1,x_2,...,x_k>, (x_i \in [n])$, there exists a permutation $P \in\mathcal{P}, $ such that $P(x_1)<P(x_2)<...<P(x_k)$.A simple probabilistic argument can show that such family of size $r=k!\cdot k\cdot log(n)+1$ exists:Suppose we draw $r$ random permutations.The chance that some specific $<x_1,...,x_k>$ is not ordered by non of the permutations is $(1-\frac{1}{k!})^r$.Using the union bound, the chance that any ordered k tuple will not be ordered is bounded by:$(1-\frac{1}{k!})^r\cdot$$ n\choose k$$\cdot k!<(1-\frac{1}{k!})^r\cdot n^k < n^k\cdot e^{-r/k!}$If we demand that the probability will be less than 1 (which ensures such family exists), we get the desired size, $r>k!\cdot k\cdot log(n)$.The question is:Is there an explicit build for such family? is it computable in $O(k!\cdot poly(n))$ time?This question might have been referred to somewhere in a different name, so if anyone is familiar with it, a reference will be great.Edit: Andreas gave a nice build for parametric $k$.What about the case that $k$ is a small, fixed number?If $k=2$, then it's easy: take $\mathcal{P}=\{<1,2,...,n>,<n,n-1,...,1>\}$.Can we build $O(1)$ sized 3-perfect permutation family? higher fixed $k$?
Constructing a k-perfect permutations family
ds.algorithms;co.combinatorics;extremal combinatorics
Here is a sketch on how to do almost what you want, but not quite. It only proves a $k^{k+\operatorname{polylog}(k)}\log n$ bound.Consider a set of size $m=n\log_2 k$ which we think of as $n$ groups on $\log_2 k$ elements each.Next construct an $(m,k\log_2 k)$-universal set family $F$ of size $2^{k\log k+\operatorname{polylog}(k)}\log m$ using the method of Naor, Schulman, and Srinivasan. We interprete each set in $F$ as a string on $n$ symbols from $[k]$ with one symbol for each group.Now we turn each string into a permutation of $[n]$ in the following way:We first think of the $n$ first positive integers divided in $k$ stacks $T_0$ throgh $T_{k-1}$ where $T_0$ contains the elements $1,...,n/k$ from top to bottom, $T_1$ contains $n/k+1,...,2n/k$, and so on.We parse each string $s_1s_2...s_n\in F$ into a permutation by considering the symbols one at a time for increasing $j$, and on encountering symbol $s_j$ we pop the stack$T_{s_j}$ from the top and put that number in place $j$ of the permutation.Since the family $F$ was $(m,k\log_2 k)$-universal, we know that for every ordered set of $k$ of the $n$ groups, there is one string that maps the symbols $0$,$1$,...,$k-1$ to that ordered set. By the construction of the stacks, the elements fetched to the permutations preserve the order required.
_datascience.20179
While training models in machine learning, why is it sometimes advantageous to keep the batch size to a power of 2? I thought it would be best to use a size that is the largest fit in your GPU memory / RAM.This answer claims that for some packages, a power of 2 is better as a batch size. Can someone provide a detailed explanation / link to a detailed explanation for this? Is this true for all optimisation algorithms (gradient descent, backpropagation, etc) or only some of them?
What is the advantage of keeping batch size a power of 2?
machine learning;training
null
_webmaster.105019
I was wondering if the following is good for SEO. I have a webshop with categories and products. Products can contain - themselves.For example, one of the URLs would be:http://SITE/products/CATEGORY/this+is+something+1-layerWhere the product name is This is something 1-layerNow, I understand it's better to use - as space replacement, but since my product names can contain a - I was wondering if just using + would be good.If not, what would be a better way to display it?
Are plusses a good second character to use for spaces in URLs for SEO when dashes are already in use?
seo;url
null
_codereview.97424
I am a Java programmer trying to learn the ways of Swift. I coded a Hangman game in Xcode. I was wondering what I could improve, specifically whether I used delegation correctly and if there is anything I can do more elegantly in Swift.Title View Controllerimport UIKit@IBDesignableclass TitleViewController: UIViewController {//Mark - Properties@IBOutlet weak var hangmanTitleLabel: UILabel! { didSet { let hangmanTitle: NSString = Hangman let attributes = [NSFontAttributeName: UIFont(name: MarkerFelt-Thin, size: 48.0)!, NSForegroundColorAttributeName: UIColor.redColor()] let titleString = NSAttributedString(string: hangmanTitle as String, attributes: attributes) hangmanTitleLabel.attributedText = titleString }}//MARK - Lifecycle functionsoverride func shouldAutorotate() -> Bool { return false}override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.Portrait}override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let destination = segue.destinationViewController as? GameViewController { if let identifier = segue.identifier { switch identifier { case Easy: destination.brain.level = Easy case Medium: destination.brain.level = Medium case Hard: destination.brain.level = Hard default: break } } }}}TitleViewimport UIKit//MARK - Global Functionsfunc connectPoints(bottomLeftPoint: CGPoint, bottomRightPoint: CGPoint, topLeftPoint: CGPoint, topRightPoint: CGPoint, color: UIColor) {color.set()let path = UIBezierPath()path.moveToPoint(bottomLeftPoint)path.addLineToPoint(topLeftPoint)path.addLineToPoint(topRightPoint)path.addLineToPoint(bottomRightPoint)path.closePath()path.fill()path.stroke()}func calculateMidPoint(point1: CGPoint, point2: CGPoint) -> CGPoint {return CGPoint(x: (point1.x + point2.x) / 2, y: (point1.y + point2.y) / 2)}class TitleView: UIView {//MARK - Drawing Scales and Constantsstruct DrawingConstants { static let gallowBaseStartScale: CGFloat = 0.15 static let gallowBaseEndScale: CGFloat = 0.85 static let gallowBaseHeight: CGFloat = 10 static let gallowHeight: CGFloat = 0.15 static let gallowHeightStart: CGFloat = 0.175 static let gallowHeightWidth: CGFloat = 10 static let gallowAcrossScale: CGFloat = 0.5 static let gallowTipHeight: CGFloat = 17.5 static let headRadius: CGFloat = 16 static let bodyLength: CGFloat = 25 static let bodyHeight: CGFloat = 25 static let legLength: CGFloat = 50 static let grassHeightScale: CGFloat = 0.68 static let armBack: CGFloat = 5}//MARK - Drawing Functionsoverride func drawRect(rect: CGRect) { drawGrass() drawSky() drawGallow() drawDude()}func drawGrass() { let topStartPoint = CGPoint(x: CGFloat(0), y: CGFloat(bounds.size.height * DrawingConstants.grassHeightScale)) let topRightPoint = CGPoint(x: CGFloat(bounds.size.width), y: topStartPoint.y) let bottomRightPoint = CGPoint(x: topRightPoint.x, y: CGFloat(bounds.size.height)) let bottomLeftPoint = CGPoint(x: CGFloat(0), y: bottomRightPoint.y) connectPoints(bottomLeftPoint, bottomRightPoint: bottomRightPoint, topLeftPoint: topStartPoint, topRightPoint: topRightPoint, color: UIColor.greenColor())}func drawSky() { let bottomLeftPoint = CGPoint(x: CGFloat(0), y: CGFloat(bounds.size.height * DrawingConstants.grassHeightScale)) let topLeftPoint = CGPoint(x: CGFloat(0), y: CGFloat(0)) let topRightPoint = CGPoint(x: CGFloat(bounds.size.width), y: CGFloat(0)) let bottomRightPoint = CGPoint(x: CGFloat(bounds.size.width), y: CGFloat(bounds.size.height * DrawingConstants.grassHeightScale)) connectPoints(bottomLeftPoint, bottomRightPoint: bottomRightPoint, topLeftPoint: topLeftPoint, topRightPoint: topRightPoint, color: UIColor.cyanColor())}func drawGallow() { drawGallowBase() drawGallowHeight() drawGallowAcross() drawGallowTip()}func drawGallowBase() { let bottomLeftPoint = CGPoint(x: CGFloat(bounds.size.width * DrawingConstants.gallowBaseStartScale), y: CGFloat(bounds.size.height * DrawingConstants.grassHeightScale)) let topLeftPoint = CGPoint(x: bottomLeftPoint.x, y: bottomLeftPoint.y - DrawingConstants.gallowBaseHeight) let topRightPoint = CGPoint(x: CGFloat(bounds.size.width * DrawingConstants.gallowBaseEndScale), y: topLeftPoint.y) let bottomRightPoint = CGPoint(x: topRightPoint.x, y: bottomLeftPoint.y) connectPoints(bottomLeftPoint, bottomRightPoint: bottomRightPoint, topLeftPoint: topLeftPoint, topRightPoint: topRightPoint, color: UIColor.brownColor())}func drawGallowHeight() { let bottomLeftPoint = CGPoint(x: CGFloat(bounds.size.width * DrawingConstants.gallowHeightStart), y: CGFloat(bounds.size.height * DrawingConstants.grassHeightScale - DrawingConstants.gallowBaseHeight)) let bottomRightPoint = CGPoint(x: bottomLeftPoint.x + DrawingConstants.gallowHeightWidth, y: bottomLeftPoint.y) let topLeftPoint = CGPoint(x: bottomLeftPoint.x, y: bounds.size.height * DrawingConstants.gallowHeight) let topRightPoint = CGPoint(x: bottomRightPoint.x, y: topLeftPoint.y) connectPoints(bottomLeftPoint, bottomRightPoint: bottomRightPoint, topLeftPoint: topLeftPoint, topRightPoint: topRightPoint, color: UIColor.brownColor())}func drawGallowAcross() { let bottomLeftPoint = CGPoint(x: CGFloat(bounds.size.width * DrawingConstants.gallowHeightStart) + DrawingConstants.gallowHeightWidth, y: CGFloat(bounds.size.height * DrawingConstants.gallowHeight + DrawingConstants.gallowBaseHeight)) let bottomRightPoint = CGPoint(x: CGFloat(bounds.size.width * DrawingConstants.gallowAcrossScale), y: bottomLeftPoint.y) let topLeftPoint = CGPoint(x: bottomLeftPoint.x, y: CGFloat(bounds.size.height * DrawingConstants.gallowHeight)) let topRightPoint = CGPoint(x: CGFloat(bottomRightPoint.x), y: topLeftPoint.y) connectPoints(bottomLeftPoint, bottomRightPoint: bottomRightPoint, topLeftPoint: topLeftPoint, topRightPoint: topRightPoint, color: UIColor.brownColor())}func drawGallowTip() { let topLeftPoint = CGPoint(x: CGFloat(bounds.size.width * DrawingConstants.gallowAcrossScale - DrawingConstants.gallowHeightWidth), y: CGFloat(bounds.size.height * DrawingConstants.gallowHeight + DrawingConstants.gallowBaseHeight)) let topRightPoint = CGPoint(x: CGFloat(bounds.size.width * DrawingConstants.gallowAcrossScale), y: topLeftPoint.y) let bottomLeftPoint = CGPoint(x: topLeftPoint.x, y: topLeftPoint.y + DrawingConstants.gallowTipHeight) let bottomRightPoint = CGPoint(x: topRightPoint.x, y: bottomLeftPoint.y) connectPoints(bottomLeftPoint, bottomRightPoint: bottomRightPoint, topLeftPoint: topLeftPoint, topRightPoint: topRightPoint, color: UIColor.brownColor())}private func drawDude() { drawHead() drawBody()}func drawHead() { let centerX = CGFloat(bounds.size.width * DrawingConstants.gallowAcrossScale - (DrawingConstants.gallowHeightWidth / 2)) let centerY = CGFloat(bounds.size.height * DrawingConstants.gallowHeight + DrawingConstants.gallowBaseHeight + DrawingConstants.gallowTipHeight + DrawingConstants.headRadius) let center = CGPoint(x: centerX, y: centerY) UIColor.blackColor().set() let path = UIBezierPath(arcCenter: center, radius: DrawingConstants.headRadius, startAngle: CGFloat(0), endAngle: CGFloat(2 * M_PI), clockwise: true) path.lineWidth = CGFloat(2) path.stroke()}private func drawBody() { let add = CGFloat(DrawingConstants.gallowBaseHeight + DrawingConstants.gallowTipHeight + 2 * DrawingConstants.headRadius) let startPointY = CGFloat(bounds.size.height * DrawingConstants.gallowHeight + add) let startPointX = CGFloat(bounds.size.width * DrawingConstants.gallowAcrossScale - (DrawingConstants.gallowHeightWidth / 2)) let startPoint = CGPoint(x: startPointX, y: startPointY) let midPoint = CGPoint(x: startPoint.x + DrawingConstants.bodyLength, y: startPoint.y + DrawingConstants.bodyHeight) let endPoint = CGPoint(x: midPoint.x + DrawingConstants.legLength, y: midPoint.y) let bodyMid = calculateMidPoint(startPoint, point2: midPoint) let armStartX = CGFloat(bodyMid.x - DrawingConstants.armBack) let armStartY = CGFloat(bodyMid.y - DrawingConstants.armBack) let armStart = CGPoint(x: armStartX, y: armStartY) let armMid = CGPoint(x: armStart.x, y: midPoint.y) let armEnd = CGPoint(x: bodyMid.x + DrawingConstants.armBack, y: armMid.y) let legStart = calculateMidPoint(midPoint, point2: endPoint) let legEndX = calculateMidPoint(legStart, point2: endPoint).x let legEndY = endPoint.y let legMidX = legStart.x let legMidY = armStartY let legMid = CGPoint(x: legMidX, y: legMidY) let legEnd = CGPoint(x: legEndX, y: legEndY) UIColor.blackColor().set() let path = UIBezierPath() path.lineWidth = CGFloat(2) path.moveToPoint(startPoint) path.addLineToPoint(midPoint) path.addLineToPoint(endPoint) path.stroke() path.moveToPoint(armStart) path.addLineToPoint(armMid) path.addLineToPoint(armEnd) path.moveToPoint(midPoint) path.addLineToPoint(legMid) path.addLineToPoint(legEnd) path.stroke()}}GameView Controllerimport UIKitclass GameViewController: UIViewController, gameViewDataSource {//MARK - Properties@IBOutlet weak var gameView: GameView! { didSet { gameView.dataSource = self }}@IBOutlet weak var youLose: UILabel! { didSet { youLose.textColor = UIColor.cyanColor() youLose.font = UIFont(name: MarkerFelt-Thin, size: CGFloat(48.0)) }}@IBOutlet weak var youWin: UILabel! { didSet { youWin.textColor = UIColor.cyanColor() youWin.font = UIFont(name: MarkerFelt-Thin, size: CGFloat(48.0)) }}@IBOutlet weak var numberOfGuessesLabel: UILabel! { didSet { if let guesses = brain.guesses { numberOfGuessesLabel.text = \(guesses) } }}@IBOutlet weak var gameWordLabel: UILabel! { didSet { let gameWord = brain.gameWord gameWordLabel.text = gameWord }}@IBAction func guess(sender: UIButton) { if running { let guessedAlready = sender.currentTitleColor if guessedAlready == UIColor.redColor() { return } else { sender.setTitleColor(UIColor.redColor(), forState: .Normal) let guess = sender.currentTitle! brain.checkGuessAndUpdateGameWordAndGuesses(character: guess) numberOfGuessesLabel.text = \(brain.guesses!) gameWordLabel.text = brain.gameWord gameView.setNeedsDisplay() checkYouWin() checkYouLose() } }}var running = truevar brain = HangmanBrain()//MARK - Lifecycle Functionsoverride func shouldAutorotate() -> Bool { return false}override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.Portrait}//MARK - Gameplay Methodsfunc numberOfGuessesLeft() -> Int { return brain.guesses!}func gameLevel() -> String { return brain.level}func checkYouLose() { if brain.theUserLost() { running = false youLose.textColor = UIColor.redColor() brain.buildCorrectWord() gameWordLabel.text = brain.gameWord }}func checkYouWin() { if brain.theUserWon() { running = false youWin.textColor = UIColor.redColor() }}}GameViewimport UIKit//MARK - GameView protocolprotocol gameViewDataSource: class {func numberOfGuessesLeft() -> Intfunc gameLevel() -> String}//MARK - Global Functionfunc drawLine(startPoint: CGPoint, endPoint: CGPoint) {let path = UIBezierPath()path.lineWidth = CGFloat(2)path.moveToPoint(startPoint)path.addLineToPoint(endPoint)path.stroke()}class GameView: TitleView {//MARK - Drawing Scales and Constantsstruct ScaleConstants { static let bodyLength: CGFloat = 50 static let limbLength: CGFloat = 25 static let handHeightScale: CGFloat = 0.4 static let headRadius: CGFloat = 20 static let eyeRadius = CGFloat(0.15 * ScaleConstants.headRadius) static let eyeOffset = CGFloat(0.3 * ScaleConstants.headRadius) static let mouthOffSet = CGFloat(0.3 * ScaleConstants.headRadius) static let mouthRadius = CGFloat(0.25 * ScaleConstants.headRadius)}//MARK - Propertiesweak var dataSource = gameViewDataSource?()private var bodyStart: CGPoint = CGPointZeroprivate var bodyEnd: CGPoint = CGPointZeroprivate var headMiddle: CGPoint = CGPointZero//MARK - Drawing functionsoverride func drawRect(rect: CGRect) { drawSky() drawGrass() drawGallow() let level = dataSource?.gameLevel() let guesses = dataSource?.numberOfGuessesLeft() var wrongGuessesSoFar = 0 var maxGeusses = 0 switch level! { case Hard: maxGeusses = 6 case Medium: maxGeusses = 8 case Easy: maxGeusses = 10 default: break } wrongGuessesSoFar = maxGeusses - guesses! startDrawChain(wrongGuessesSoFar)}func startDrawChain(numberOfGuesses: Int) { drawHead(numberOfGuesses)}func drawHead(numberOfGuesses: Int) { if numberOfGuesses == 0 { return } else { let centerX = CGFloat(bounds.size.width * DrawingConstants.gallowAcrossScale - (DrawingConstants.gallowHeightWidth / 2)) let centerY = CGFloat(bounds.size.height * DrawingConstants.gallowHeight + DrawingConstants.gallowBaseHeight + DrawingConstants.gallowTipHeight + ScaleConstants.headRadius) let center = CGPoint(x: centerX, y: centerY) headMiddle = center UIColor.blackColor().set() let path = UIBezierPath(arcCenter: center, radius: ScaleConstants.headRadius, startAngle: CGFloat(0), endAngle: CGFloat(2 * M_PI), clockwise: true) path.lineWidth = CGFloat(2) path.stroke() drawBody(numberOfGuesses - 1) }}func drawBody(numberOfGuesses: Int) { if numberOfGuesses == 0 { return } else { UIColor.blackColor().set() let add = CGFloat(DrawingConstants.gallowBaseHeight + DrawingConstants.gallowTipHeight + 2 * ScaleConstants.headRadius) let startPointY = CGFloat(bounds.size.height * DrawingConstants.gallowHeight + add) let startPointX = CGFloat(bounds.size.width * DrawingConstants.gallowAcrossScale - (DrawingConstants.gallowHeightWidth / 2)) let startPoint = CGPoint(x: startPointX, y: startPointY) let endPoint = CGPoint(x: startPoint.x, y: startPoint.y + ScaleConstants.bodyLength) bodyStart = startPoint bodyEnd = endPoint drawLine(startPoint, endPoint: endPoint) drawLeftLeg(numberOfGuesses - 1) }}func drawLeftLeg(numberOfGuesses: Int) { if numberOfGuesses == 0 { return } else { let startPoint = CGPoint(x: bodyEnd.x, y: bodyEnd.y) let endPoint = CGPoint(x: startPoint.x - ScaleConstants.limbLength, y: startPoint.y + ScaleConstants.limbLength) drawLine(startPoint, endPoint: endPoint) drawRightLeg(numberOfGuesses - 1) }}func drawRightLeg(numberOfGuesses: Int) { if numberOfGuesses == 0 { return } else { let startPoint = CGPoint(x: bodyEnd.x, y: bodyEnd.y) let endPoint = CGPoint(x: startPoint.x + ScaleConstants.limbLength, y: startPoint.y + ScaleConstants.limbLength) drawLine(startPoint, endPoint: endPoint) drawLeftArm(numberOfGuesses - 1) }}func drawLeftArm(numberOfGuesses: Int) { if numberOfGuesses == 0 { return } else { let startPoint = CGPoint(x: bodyStart.x, y: bodyStart.y + ScaleConstants.handHeightScale * ScaleConstants.bodyLength) let endPoint = CGPoint(x: startPoint.x - ScaleConstants.limbLength, y: startPoint.y - ScaleConstants.limbLength * ScaleConstants.handHeightScale) drawLine(startPoint, endPoint: endPoint) drawRightArm(numberOfGuesses - 1) }}func drawRightArm(numberOfGuesses: Int) { if numberOfGuesses == 0 { return } else { let startPoint = CGPoint(x: bodyStart.x, y: bodyStart.y + ScaleConstants.handHeightScale * ScaleConstants.bodyLength) let endPoint = CGPoint(x: startPoint.x + ScaleConstants.limbLength, y: startPoint.y - ScaleConstants.limbLength * ScaleConstants.handHeightScale) drawLine(startPoint, endPoint: endPoint) drawLeftEye(numberOfGuesses - 1) }}func drawLeftEye(numberOfGuesses: Int) { if numberOfGuesses == 0 { return } else { UIColor.blackColor().set() let eyeMiddle = CGPoint(x: headMiddle.x - ScaleConstants.eyeOffset, y: headMiddle.y - ScaleConstants.eyeOffset) let path = UIBezierPath(arcCenter: eyeMiddle, radius: ScaleConstants.eyeRadius, startAngle: 0, endAngle: CGFloat(2 * M_PI), clockwise: true) path.lineWidth = CGFloat(1) path.stroke() drawRightEye(numberOfGuesses - 1) }}func drawRightEye(numberOfGuesses: Int) { if numberOfGuesses == 0 { return } else { UIColor.blackColor().set() let eyeMiddle = CGPoint(x: headMiddle.x + ScaleConstants.eyeOffset, y: headMiddle.y - ScaleConstants.eyeOffset) let path = UIBezierPath(arcCenter: eyeMiddle, radius: ScaleConstants.eyeRadius, startAngle: 0, endAngle: CGFloat(2 * M_PI), clockwise: true) path.lineWidth = CGFloat(1) path.stroke() drawMouth(numberOfGuesses - 1) }}func drawMouth(numberOfGuesses: Int) { if numberOfGuesses == 0 { return } else { UIColor.blackColor().set() let mouthMiddle = CGPoint(x: headMiddle.x, y: headMiddle.y + ScaleConstants.mouthOffSet) let path = UIBezierPath(arcCenter: mouthMiddle, radius: ScaleConstants.mouthRadius, startAngle: 0, endAngle: CGFloat(2 * M_PI), clockwise: true) path.lineWidth = CGFloat(1) path.stroke() }}}Hangman Brainimport Foundationimport Darwinclass HangmanBrain {//MARK - Database of Wordsprivate struct Words { static let Easy: [String] = [fireplace,apple,january,tooth,cookies,mysterious,essential,magenta,darling,pterodactyl] static let Medium: [String] = [palace,thumb,eleven,monkey,hunter,wounds,wright,egypt,slaves,zipper] static let Hard: [String] = [jazz,puff,jiff,sphinx,vex,pox,hajj,jinx,vine,mom] static let numberOfWordsPerLevel = 10}//MARK - Propertiesvar level: String = { didSet { chooseWord(wordLevel: level) setNumberOfGuesses(level: level) }}var guesses: Int? = nilvar word: String? = nilvar gameWord = private let wordsByLevel : [String: [String]] = [Easy: Words.Easy, Medium: Words.Medium, Hard: Words.Hard]//MARK - Gameplay Functionsprivate func chooseWord(wordLevel wordLevel: String) { let UInt = UInt32(Words.numberOfWordsPerLevel - 1) let wordNumber = Int(arc4random_uniform(UInt)) let wordChosen = wordsByLevel[wordLevel]![wordNumber] word = wordChosen gameWord = for _ in wordChosen.characters { createGameWord(character: _) }}private func setNumberOfGuesses(level level: String) { switch level { case Easy: guesses = 10 case Medium: guesses = 8 case Hard: guesses = 6 default: break }}func checkGuessAndUpdateGameWordAndGuesses(character character: String) { var guessIsCorrect = false let answer = word! let currentWord = gameWord as String gameWord = let currentWordTrimmed = currentWord.stringByReplacingOccurrencesOfString( , withString: ) let numberOfLetters = answer.characters.count as Int for i in 0...numberOfLetters-1 { let start = advance(currentWordTrimmed.startIndex, i) let end = advance(currentWordTrimmed.startIndex, i+1) let subCurrentWord = currentWordTrimmed.substringWithRange(Range<String.Index>(start: start, end: end)) if subCurrentWord != _ { createGameWord(character: subCurrentWord) } else { let subAnswer = answer.substringWithRange(Range<String.Index>(start: start, end: end)) if subAnswer == character.lowercaseString { guessIsCorrect = true createGameWord(character: subAnswer) } else { createGameWord(character: _) } } } if(!guessIsCorrect) { guesses = guesses! - 1 }}func buildCorrectWord() { gameWord = for c in word!.characters { createGameWord(character: \(c)) }}func createGameWord(character character: String) { gameWord += \(character) }func theUserWon() -> Bool { for ch in gameWord.characters { if \(ch) == _ { return false } } return true}func theUserLost() -> Bool{ return guesses == 0}}
Hangman in Swift
game;ios;swift;hangman
There's a ton of code here. For the purposes of this review, I'll be focusing on the HangmanBrain class (I've ignored everything else for this answer). This class seems to be the core, so it's a good place to start.private struct Words { static let Easy: [String] = [fireplace,apple,january,tooth,cookies,mysterious,essential,magenta,darling,pterodactyl] static let Medium: [String] = [palace,thumb,eleven,monkey,hunter,wounds,wright,egypt,slaves,zipper] static let Hard: [String] = [jazz,puff,jiff,sphinx,vex,pox,hajj,jinx,vine,mom] static let numberOfWordsPerLevel = 10}I am a fan of declaring constants within structs like this. However, I don't like what's being done here.We've severely limited the expandability of our game.Instead of this struct, our HangmanBrain class should be reworked to read in JSON to construct its word list. For example:EasyWords.json{ wordList : { difficulty : easy, list : [ fireplace, apple, january, tooth, cookies, mysterious, essential, magenta, darling, pterodactyl ] }} Importantly here, we've defined a JSON structure. Our app can come preloaded with EasyWords.json, MediumWords.json, and HardWords.json, but we can then easily add word lists in future updates just by adding JSON files. As well, we can allow our app to download word lists from online. We either simply point our app toward some API endpoint we develop, or we can come up with a way for the user to point toward an endpoint of their choosing to download custom word lists. Of course, none of this is necessary yet... but if we ever want it to be an available option, we need to start with a more flexible way of loading our word lists in the first place.In addition to stripping the hard-coded word list from our source code and adding it as a resource, we should rethink how we're getting words.The HangmanBrain class has too much responsibility. It should only be in charge of playing the game. It shouldn't be in charge of generating the word to be played. It should be told what word wants to be played. So, let's use a property of type Generator<String> and just call next() on it to get the word to play.Now we can give our HangmanBrain game a generator to use. One generator might load our objects from a JSON file and serve them up in random order. Another might load the strings from a web server and serve them up in a predetermined order. We can think of a million different ways to generate lists of words for the game to use. Maybe one generator is based off user-inputted words for a multiplayer hangman? When we decouple the list from the brain, we allow a lot more flexibility in our code.So, for example...class HangmanBrain { // set this in init var wordGenerator: Generator<String> /* stuff */ // now, any time we need a word, we just call: self.wordGenerator.next() // when this call returns nil, the generator is out of words // but generators don't have to ever return nil}Lastly (for this review), I think it's very important that we not use strings for setting the difficulty level.Instead, let's provide a difficulty enum:class HangmanBrain { enum Difficulty: String { case Easy = easy case Medium = medium case Hard = hard } // other stuff}The enum is still backed by a string, so when we need that string value for parsing JSON, we can access it (HangmanBrain.Difficulty.Easy.rawValue), but importantly, we've made it very explicit what sort of values to accept when we're looking for a difficulty.
_scicomp.3470
To compute the eigenvector corresponding to a dominant eigenvalue of a matrix $A\in\mathbb{R}^{n\times n}$, one could apply the Power Iteration: $$v_1=\frac{Av_1}{\|Av_1\|}.$$1) in case $A$ is symmetric, eigenvectors are orthonormal. However, suppose that there are, e.g, two occurrences of the dominant eigenvalue $\lambda_1$ corresponding to different eigenvectors. Does that mean that the method would yield inconsistent results on different invocation? The inconsistency means that the method could (assuming random initialization on each invocation) change direction of convergence (since the eigenvalues are the same)In case one needs the following dominant eigenvector, one usually performs Gram Schmidt orthonormalization, ie, removes component of the first eigenvector from the initialization to the second. Would this second vector converge to the eigenvector corresponding to the other occurence of dominanant eigenvalue $\lambda_1$?2) in case of a general $A$, eigenvectors are not orthonormal. So, what would be the way to extract subsequent eigenvectors. In other words, would GS orthonormalization now make sense? It removes component from the first eigenvector, but, since the eigenvectors are not orthogonal, I'm not sure it the following matrix-vector multiplication adds the component back.
Power Iteration on general matrices (with higher multiplicity of dominant eigenvalue)
linear algebra;matrices;eigensystem
1) In case of a multiple dominant eigenvalue (and no other of the same absolute value), the power itieration converges to the vector obtained by projecting the starting vector to the dominant eigenspace (if this vector is nonzero). These projections are orthogonal if the matrix is symmetric. Of course, if you start with different starting vectors you'll typically get different such projections.2) If the matrix is nondefective, the starting vector can be written in a unique way as a linear combination of eigenvectors to distinct eigenvalues. In this decomposition, it is easy to see what happens when you iterate. If the matrix is nondefective, the result is the same but the proof needs an additional limiting step. [Edit1] Note that in the nonsymmetric, nondefective case, the left and right eigenvectors form a biorthogonal system, and one must orthogonalize with a left eigenvector to get a particular right eigenvector.[Edit2]3) If the matrix has precisely two dominant eigenvalues, each of algebraic multiplicity 1, one has convergence if and only the starting vector isorthogonal to exactly one of the corresponding left eigenvectors, and then converges to the other. I leave it as an exercise to figure out what happens in the other degenerate cases possible.But why are you so concerned about the power iteration? it is generally a poor method, and it fails to converge if there are two different eigenvalues with (equal) maximal absolute value. Lanczos (in the symmetric case) or Arnoldi (in the nonsymmetric case) are far better.
_cs.47775
I have a field in my data store which must take exactly 180 bits of information. Some users will choose to make this data encrypted, some won't, so some of those 180 bit fields will be ciphertext some will be plaintext. A boolean will indicate which one the user is using. The important thing here is that I need this field to be exactly 180 bits long.However, a 128-bit cipher will mean I have to put in 256 bits in as plaintext, which is fine, just use a buffer string, but this means that the output is 256 bits when what is stored must be exactly 180 bits. And I can't simply cut off the ciphertext or that would mess up the decryption.
Encrypting a 180-bit plaintext into a 180 bit ciphertext with a 128-bit block cipher
cryptography
If you have a unique, unchanging identifier for each entry in your data store, you can use counter mode.A nice thing about counter mode turns a block cipher into a stream cipher. No matter what the block size is, CTR mode encrypts an $n$-bit plaintext into an $n$-bit ciphertext.In order to achieve that, CTR requires a unique counter value per block. Note: not just a unique counter value per message, but a unique counter value per block. The counter size is the same as the block size. In your case, you have messages that fit on two blocks, thus each message requires two counter values. If you have a unique identifier $k$ for each message, you can use $k$ and $k+1$ as the counter values for the two blocks (the second of which is partial) of the message.Thus you need a 127-bit unique identifier for each message (128-bit block, minus one bit to distinguish the two blocks inside each message). The only security requirement for these 127 bits is that they are never reused for a given key. The initial counter value to encrypt a message is often chosen randomly, but this is not a requirement, just a convenience to ensure uniqueness. Of course, to decrypt the data, you need to be able to recover the unique identifier associated with each entry.If your entries have some kind of unique identifier, which is often the case in databases, then you're set. Just remember that if you move data around or normalize it in a way that changes the identifiers, you will need to decrypt and reencrypt the data.Some crypto libraries may present CTR mode through a function that randomly generates the initial counter value and prepends it to the message (so you'd input a 160-bit plaintext and get back a 288-bit ciphertext). Use a library that lets you specify the initial counter value (almost all implementations will increment the counter by 1 for each successive block, so pick initial counter values that are even, but you'll need to be aware of the endianness used by your library).Keep in mind that encryption only gives you confidentiality, not integrity. In other words, someone who obtains the ciphertexts but not the key will not be able to find any information about the data; but if someone can inject fake ciphertexts or modify existing ciphertexts, the tampering cannot be detected. It is intrinsically impossible to detect tampering by cryptographic means in your scenario since there is no room for any redundancy.
_unix.53275
I have bash script which was written for OS X and now ported to Linux. I don't have access to the Linux box. The bash script would read values from plist files using the defaults read and PlistBuddy command available on OS X. Since the Linux machine doesn't have these commands, I'm looking for workarounds. Is there library/script (Perl preferably) that helps user fetch values from plist files for a given key on a Linux machine? I tried using sed/awk, but the output isn't reliable. I've come across scripts like plutil.pl that convert a plist file to other formats.I have installed a Virtual machine running Ubuntu on my Mac so that I can test my changes before deploying to the actual Linux box.
Fetch values from plist file on Linux
linux;bash;scripting;osx;perl
Since .plist files are already XML (or can be easily converted) you just need something to decode the XML.For that use xml2:$ cat com.apple.systemsound.plist<?xml version=1.0 encoding=UTF-8?><!DOCTYPE plist PUBLIC -//Apple//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd><plist version=1.0><dict> <key>com.apple.sound.beep.volume</key> <real>1</real></dict></plist>$ xml2 < com.apple.systemsound.plist/plist/@version=1.0/plist/dict/key=com.apple.sound.beep.volume/plist/dict/real=1$ You should be able to figure out the rest.Or for Perl, use XML::Simple; (see perldoc for more) to put the XML data structure into a hash.
_unix.328449
How can I do parallel processing in bash?My approach, in my bash script, added so many background jobs with &, and then I am adding each process id using an array, then I am fetching that array using a loop and inside that I am using wait command, but somehow wait command is not working. my code is like thisfor i in some path do ls -d $i | xargs du -kh --max-depth=0 |sed 's/\t/,/g' >> $TEMP/Outfile/disk_usage_Session_wise.csv & pid=$! ls -d $i/session | xargs du -kh --max-depth=1 | sed 's/\t/,/g' >> $TEMP/Outfile/disk_usage_Session_wise.csv & pid_1=$! process_list=($pid $pid_1) done for job in echo ${process_list[@]} do echo $job is running wait $job # this command is not working done
how to wait for many background jobs in bash
bash
null
_unix.139036
I'm trying to set up a screenrc file that opens a few windows, and in one of them I'd like to start a shell and start vim within it (rather than starting vim directly). I've tried things along the lines ofscreen -t vim -ln 1 bash -c vimbut that seems to open vim directly (if I quit vim, the window is killed, whereas I'd like to simply return to the shell in that window). How can I set this up correctly?
GNU Screen: how to start a bash process and execute a command within it?
bash;gnu screen
null
_unix.271726
I am a bit new to Linux and I know this is late but I recently read about how Linux Mint 17.3 was hacked on February 20th and I want to make sure my version isn't hacked. I originally installed Linux Mint 17.2 back in August and I upgraded to 17.3 via the Update Manager. While I am unsure of the exact date I did this, I believe it was sometime around the date in question. In order to make sure I don't have an infected system I would like to know the answers to a few questions that would greatly help me.1) First, if I already had Linux Mint installed on my computer and I simply upgraded from Rosa to Cinnamon via the Update Manager, am I ok?2) If not, is there a way I can simply view when I upgraded my OS in the terminal?3) If not, I have read the Linux Mint blog post about how to check if my ISO is compromised using the md5sum command, but in order to do that, I need to find the ISO file. Where would that be located on my computer?
How to check if I downloaded a hacked version of Linux Mint 17.3
linux mint
null
_cstheory.38808
I have text snippets (resources) that I collect from all over the internet which I then upload to a cloud database, include a reference, give it a resource ID, and TAG the text for later retrieval. What complicates things a bit, is that the TAGS can appear in one of three different places (tiers) for each resource based on its significance or relevance to that specific text. I am looking to write a machine learning program that can sort the tagged text in an appropriate order (so that I do not have to search through the whole database for specific content) that I can then export into a document that I can work of.The content looks pretty much like a Wordpress blog post with tags, it's just that the tags are in three different tiers that I want the ML program to search for.Does ML software like this exist, or is it better to just design it myself from scratch? (Not sure if this makes sense...
Machine learning for tagged text
machine learning;software
null
_codereview.95008
I'm working on a script to backup S3 to GC everyday. I'm not sure if my script has any potential bug or error that might have destroyed anything from both sides? The data is quite sensitive and I don't want to mess it up. Anything is welcomed. #!/bin/shif hash aws 2>/dev/null; then echo 'awscli is installed.'else echo 'Please install awscli by running sudo pip install awscli' exitfiif hash gsutil 2>/dev/null; then echo 'gsutil is installed.'else echo 'Please install gsutil by running sudo pip install gsutil'fiif env | grep -q ^BACKUP_TO_EMAIL=then echo After backup is done email will be send to $BACKUP_TO_EMAILelse echo BACKUP_TO_EMAIL is not set please set it exitfiif env | grep -q ^S3_BUCKET=then echo Checking if $S3_BUCKET exists if aws s3 ls s3://$S3_BUCKET 2>&1 | grep -q 'AllAccessDisabled' then echo bucket $S3_BUCKET doesn't exist please check again. exit fielse echo 'S3_BUCKET is not set please set it' exitfiif env | grep -q ^GC_BUCKET=then echo Checking if $GC_BUCKET exists if gsutil ls gs://$GC_BUCKET 2>&1 | grep -q 'AccessDeniedException' then echo bucket $GC_BUCKET doesn't exist please check again. exit fielse echo 'GC_BUCKET is not set please set it' exitfiecho Backing up now...#`gsutil -m rsync -r s3://$S3_BUCKET gs://$GC_BUCKET`echo Creating new backup folderdatestamp=$(date +%m%d%y)mkdir $datestampecho Downloading backupaws s3 sync s3://$S3_BUCKET $datestampecho Compressing site backuptar -zcvf $datestamp.tar.gz $datestampfile=$datestamp.tar.gzrm -rf $datestampecho Uploading to GCgsutil cp $file gs://$GC_BUCKETecho Deleting temporary filesrm $fileecho Sending emailbody=Backup is complete and the file is in gs://$GC_BUCKET/$fileecho $body | mail $BACKUP_TO_EMAIL -s S3 to GS backup
Bash script to backup from S3 to GC
bash;amazon s3
Looks mostly pretty good.When exiting with error, it's a good practice to specify a non-zero exit code, for example exit 1.This looks odd:if env | grep -q ^S3_BUCKET=then echo Checking if $S3_BUCKET exists if aws s3 ls s3://$S3_BUCKET 2>&1 | grep -q 'AllAccessDisabled'It's odd to check environment variables using env | grep.And in this example, it looks error-prone too,because S3_BUCKET might be defined empty, with no values.I don't know aws, but I have a strong feeling that in case of S3_BUCKET= (empty) you would rather raise an error than run execute aws s3 ls s3://.I suggest to replace with a simple variable check:if test $S3_BUCKET; thenIn this code:tar -zcvf $datestamp.tar.gz $datestampfile=$datestamp.tar.gzIt would be better to set file first, and then use it in the tarI like to avoid nested if statements when possible. For example here:if env | grep -q ^S3_BUCKET=then echo Checking if $S3_BUCKET exists if aws s3 ls s3://$S3_BUCKET 2>&1 | grep -q 'AllAccessDisabled' then echo bucket $S3_BUCKET doesn't exist please check again. exit fielse echo 'S3_BUCKET is not set please set it' exitfiI would flatten by inverting the outer if:if test ! $S3_BUCKETthen echo 'S3_BUCKET is not set please set it' exit 1fiecho Checking if $S3_BUCKET existsif aws s3 ls s3://$S3_BUCKET 2>&1 | grep -q 'AllAccessDisabled' then echo bucket $S3_BUCKET doesn't exist please check again. exit 1fi
_cs.70712
So I am trying to work on a problem and honestly... I am so lost with this one. I will try to ask it the best I can.Exact text of the problem: Prove the following directly from the definition of Big Theta; 100,000,000 is a member of the set of functions defined by Big Theta of g(n), where g(n) = 1Additionally, the definition in question is [Click here to see definition]Basically, I don't understand the definition and I don't understand the question. I understand that this chapter is talking about asymptotic behavior, and how given 2 different functions these 1 number could grow faster than the other up to a certain point and then it would switch. Example, Using 1 and 100,000,000 as n. In the following 2 functions 1 is larger number using 1... and then the other one is larger when you 100,000,000.1,000,000n and n^2Perhaps someone can help put the definition and question into words I can understand a little better.
Prove 100,000,000 is a member of the set of functions defined by Big Theta of g(n), where g(n) = 1
algorithms
null
_webapps.102433
I would like to transpose an array and divide the transposed output by a number for every single cell of the array. Example (not functional):=TRANSPOSE('1/3/2017'!O2:S2)/COUNTA('1/3/2017'!A2:A108)
How to transpose and divide by a number?
google spreadsheets
null
_codereview.79118
How can I improve it?#include <iostream>#include <deque>#include <string>#include <stdexcept>#include <Windows.h>namespace ms{ typedef signed char Int8; typedef unsigned char Uint8; typedef signed short Int16; typedef unsigned short Uint16; typedef signed int Int32; typedef unsigned int Uint32; typedef signed __int64 Int64; typedef unsigned __int64 Uint64; struct NonCopyable { NonCopyable() = default; virtual ~NonCopyable() = default; NonCopyable(const NonCopyable &) = delete; NonCopyable(const NonCopyable &&) = delete; NonCopyable& operator = (const NonCopyable&) = delete; }; template <typename T> struct Vector2 { Vector2(); Vector2(T X, T Y); T x; T y; }; template <typename T> bool operator !=(const Vector2<T>& V1, const Vector2<T>& V2); template <typename T> Vector2<T>::Vector2() : x(), y(){ } template <typename T> Vector2<T>::Vector2(T X, T Y) : x(X), y(Y){ } template <typename T> Vector2<T> operator -(const Vector2<T>& V) { return Vector2<T>(-V.x, -V.y); } template <typename T> Vector2<T>& operator +=(Vector2<T>& V1, const Vector2<T>& V2) { V1.x += V2.x; V1.y += V2.y; return V1; } template <typename T> Vector2<T>& operator -=(Vector2<T>& V1, const Vector2<T>& V2) { V1.x -= V2.x; V1.y -= V2.y; return V1; } template <typename T> Vector2<T> operator +(const Vector2<T>& V1, const Vector2<T>& V2) { return Vector2<T>(V1.x + V2.x, V1.y + V2.y); } template <typename T> Vector2<T> operator -(const Vector2<T>& V1, const Vector2<T>& V2) { return Vector2<T>(V1.x - V2.x, V1.y - V2.y); } template <typename T> Vector2<T> operator *(const Vector2<T>& V, T X) { return Vector2<T>(V.x * X, V.y * X); } template <typename T> Vector2<T> operator *(T X, const Vector2<T>& V) { return Vector2<T>(V.x * X, V.y * X); } template <typename T> Vector2<T>& operator *=(Vector2<T>& V, T X) { V.x *= X; V.y *= X; return V; } template <typename T> Vector2<T> operator /(const Vector2<T>& V, T X) { return Vector2<T>(V.x / X, V.y / X); } template <typename T> Vector2<T>& operator /=(Vector2<T>& V, T X) { V.x /= X; V.y /= X; return V; } template <typename T> bool operator ==(const Vector2<T>& V1, const Vector2<T>& V2) { return (V1.x == V2.x) && (V1.y == V2.y); } template <typename T> bool operator !=(const Vector2<T>& V1, const Vector2<T>& V2) { return (V1.x != V2.x) || (V1.y != V2.y); } typedef Vector2<int> Vector2i; typedef Vector2<float> Vector2f; typedef Vector2<Uint32> Vector2u; struct Mouse { enum Button { Left, Right, Middle, XButton1, XButton2, ButtonCount }; static bool isButtonPressed(Button button); static Vector2i getPosition(); static void setPosition(const Vector2i& position); }; struct Keyboard { enum Key { Unknown = -1, A = 0, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Num0, Num1, Num2, Num3, Num4, Num5, Num6, Num7, Num8, Num9, Escape, LControl, LShift, LAlt, LSystem, RControl, RShift, RAlt, RSystem, Menu, LBracket, RBracket, SemiColon, Comma, Period, Quote, Slash, BackSlash, Tilde, Equal, Dash, Space, Return, BackSpace, Tab, PageUp, PageDown, End, Home, Insert, Delete, Add, Subtract, Multiply, Divide, Left, Right, Up, Down, Numpad0, Numpad1, Numpad2, Numpad3, Numpad4, Numpad5, Numpad6, Numpad7, Numpad8, Numpad9, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, Pause, KeyCount }; static bool isKeyPressed(Key key); }; namespace priv { struct InputImpl : NonCopyable { static bool isKeyPressed(Keyboard::Key key); static bool isMouseButtonPressed(Mouse::Button button); static Vector2i getMousePosition(); static void setMousePosition(const Vector2i& position); }; bool InputImpl::isKeyPressed(Keyboard::Key key) { int vkey = 0; switch (key) { default: vkey = 0; break; case Keyboard::A: vkey = 'A'; break; case Keyboard::B: vkey = 'B'; break; case Keyboard::C: vkey = 'C'; break; case Keyboard::D: vkey = 'D'; break; case Keyboard::E: vkey = 'E'; break; case Keyboard::F: vkey = 'F'; break; case Keyboard::G: vkey = 'G'; break; case Keyboard::H: vkey = 'H'; break; case Keyboard::I: vkey = 'I'; break; case Keyboard::J: vkey = 'J'; break; case Keyboard::K: vkey = 'K'; break; case Keyboard::L: vkey = 'L'; break; case Keyboard::M: vkey = 'M'; break; case Keyboard::N: vkey = 'N'; break; case Keyboard::O: vkey = 'O'; break; case Keyboard::P: vkey = 'P'; break; case Keyboard::Q: vkey = 'Q'; break; case Keyboard::R: vkey = 'R'; break; case Keyboard::S: vkey = 'S'; break; case Keyboard::T: vkey = 'T'; break; case Keyboard::U: vkey = 'U'; break; case Keyboard::V: vkey = 'V'; break; case Keyboard::W: vkey = 'W'; break; case Keyboard::X: vkey = 'X'; break; case Keyboard::Y: vkey = 'Y'; break; case Keyboard::Z: vkey = 'Z'; break; case Keyboard::Num0: vkey = '0'; break; case Keyboard::Num1: vkey = '1'; break; case Keyboard::Num2: vkey = '2'; break; case Keyboard::Num3: vkey = '3'; break; case Keyboard::Num4: vkey = '4'; break; case Keyboard::Num5: vkey = '5'; break; case Keyboard::Num6: vkey = '6'; break; case Keyboard::Num7: vkey = '7'; break; case Keyboard::Num8: vkey = '8'; break; case Keyboard::Num9: vkey = '9'; break; case Keyboard::Escape: vkey = VK_ESCAPE; break; case Keyboard::LControl: vkey = VK_LCONTROL; break; case Keyboard::LShift: vkey = VK_LSHIFT; break; case Keyboard::LAlt: vkey = VK_LMENU; break; case Keyboard::LSystem: vkey = VK_LWIN; break; case Keyboard::RControl: vkey = VK_RCONTROL; break; case Keyboard::RShift: vkey = VK_RSHIFT; break; case Keyboard::RAlt: vkey = VK_RMENU; break; case Keyboard::RSystem: vkey = VK_RWIN; break; case Keyboard::Menu: vkey = VK_APPS; break; case Keyboard::LBracket: vkey = VK_OEM_4; break; case Keyboard::RBracket: vkey = VK_OEM_6; break; case Keyboard::SemiColon: vkey = VK_OEM_1; break; case Keyboard::Comma: vkey = VK_OEM_COMMA; break; case Keyboard::Period: vkey = VK_OEM_PERIOD; break; case Keyboard::Quote: vkey = VK_OEM_7; break; case Keyboard::Slash: vkey = VK_OEM_2; break; case Keyboard::BackSlash: vkey = VK_OEM_5; break; case Keyboard::Tilde: vkey = VK_OEM_3; break; case Keyboard::Equal: vkey = VK_OEM_PLUS; break; case Keyboard::Dash: vkey = VK_OEM_MINUS; break; case Keyboard::Space: vkey = VK_SPACE; break; case Keyboard::Return: vkey = VK_RETURN; break; case Keyboard::BackSpace: vkey = VK_BACK; break; case Keyboard::Tab: vkey = VK_TAB; break; case Keyboard::PageUp: vkey = VK_PRIOR; break; case Keyboard::PageDown: vkey = VK_NEXT; break; case Keyboard::End: vkey = VK_END; break; case Keyboard::Home: vkey = VK_HOME; break; case Keyboard::Insert: vkey = VK_INSERT; break; case Keyboard::Delete: vkey = VK_DELETE; break; case Keyboard::Add: vkey = VK_ADD; break; case Keyboard::Subtract: vkey = VK_SUBTRACT; break; case Keyboard::Multiply: vkey = VK_MULTIPLY; break; case Keyboard::Divide: vkey = VK_DIVIDE; break; case Keyboard::Left: vkey = VK_LEFT; break; case Keyboard::Right: vkey = VK_RIGHT; break; case Keyboard::Up: vkey = VK_UP; break; case Keyboard::Down: vkey = VK_DOWN; break; case Keyboard::Numpad0: vkey = VK_NUMPAD0; break; case Keyboard::Numpad1: vkey = VK_NUMPAD1; break; case Keyboard::Numpad2: vkey = VK_NUMPAD2; break; case Keyboard::Numpad3: vkey = VK_NUMPAD3; break; case Keyboard::Numpad4: vkey = VK_NUMPAD4; break; case Keyboard::Numpad5: vkey = VK_NUMPAD5; break; case Keyboard::Numpad6: vkey = VK_NUMPAD6; break; case Keyboard::Numpad7: vkey = VK_NUMPAD7; break; case Keyboard::Numpad8: vkey = VK_NUMPAD8; break; case Keyboard::Numpad9: vkey = VK_NUMPAD9; break; case Keyboard::F1: vkey = VK_F1; break; case Keyboard::F2: vkey = VK_F2; break; case Keyboard::F3: vkey = VK_F3; break; case Keyboard::F4: vkey = VK_F4; break; case Keyboard::F5: vkey = VK_F5; break; case Keyboard::F6: vkey = VK_F6; break; case Keyboard::F7: vkey = VK_F7; break; case Keyboard::F8: vkey = VK_F8; break; case Keyboard::F9: vkey = VK_F9; break; case Keyboard::F10: vkey = VK_F10; break; case Keyboard::F11: vkey = VK_F11; break; case Keyboard::F12: vkey = VK_F12; break; case Keyboard::F13: vkey = VK_F13; break; case Keyboard::F14: vkey = VK_F14; break; case Keyboard::F15: vkey = VK_F15; break; case Keyboard::Pause: vkey = VK_PAUSE; break; } return (GetAsyncKeyState(vkey) & 0x8000) != 0; } bool InputImpl::isMouseButtonPressed(Mouse::Button button) { int vkey = 0; switch (button) { case Mouse::Left: vkey = GetSystemMetrics(SM_SWAPBUTTON) ? VK_RBUTTON : VK_LBUTTON; break; case Mouse::Right: vkey = GetSystemMetrics(SM_SWAPBUTTON) ? VK_LBUTTON : VK_RBUTTON; break; case Mouse::Middle: vkey = VK_MBUTTON; break; case Mouse::XButton1: vkey = VK_XBUTTON1; break; case Mouse::XButton2: vkey = VK_XBUTTON2; break; default: vkey = 0; break; } return (GetAsyncKeyState(vkey) & 0x8000) != 0; } //////////////////////////////////////////////////////////// Vector2i InputImpl::getMousePosition() { HWND handle = GetConsoleWindow(); if (handle) { COORD tempfontsize = { 0, 0 }; CONSOLE_FONT_INFOEX cfix = { 0 }; cfix.cbSize = sizeof(CONSOLE_FONT_INFOEX); if (GetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfix)) { tempfontsize = GetConsoleFontSize(GetStdHandle(STD_OUTPUT_HANDLE), cfix.nFont); } POINT pos = { 0, 0 }; if (!GetCursorPos(&pos) && ScreenToClient(GetConsoleWindow(), &pos)) { throw failed to GetCursorPos(&pos); } Vector2i delta = { 0, 0 }; ScreenToClient(GetConsoleWindow(), &pos); delta.x = pos.x / tempfontsize.X; delta.y = pos.y / tempfontsize.Y; return delta; } else { return Vector2i(); } } void InputImpl::setMousePosition(const Vector2i& position) { HWND handle = GetConsoleWindow(); if (handle) { POINT point = { position.x, position.y }; ClientToScreen(handle, &point); SetCursorPos(point.x, point.y); } } } // namespace priv bool Keyboard::isKeyPressed(Key key) { return priv::InputImpl::isKeyPressed(key); } bool Mouse::isButtonPressed(Button button) { return priv::InputImpl::isMouseButtonPressed(button); } Vector2i Mouse::getPosition() { return priv::InputImpl::getMousePosition(); } void Mouse::setPosition(const Vector2i& position) { priv::InputImpl::setMousePosition(position); } struct Event : NonCopyable { struct SizeEvent { unsigned int width; unsigned int height; }; struct KeyEvent { Keyboard::Key code; bool alt; bool control; bool shift; bool system; }; struct TextEvent { Uint32 unicode; }; struct MouseMoveEvent { int x; int y; }; struct MouseButtonEvent { Mouse::Button button; int x; int y; }; struct MouseWheelEvent { int delta; int x; int y; }; enum EventType { Closed, Resized, TextEntered, KeyPressed, KeyReleased, MouseWheelMoved, MouseButtonPressed, MouseButtonReleased, MouseMoved, MouseEntered, MouseLeft, Count }; EventType type; union { SizeEvent size; KeyEvent key; TextEvent text; MouseMoveEvent mouseMove; MouseButtonEvent mouseButton; MouseWheelEvent mouseWheel; }; }; namespace priv { Keyboard::Key KeyConvert(const WORD Key) { if ((Key >= 'A' && Key <= 'Z') || (Key >= '1' && Key <= '9') || Key == '0') { return Keyboard::Key(Key); } if (Key == VK_RETURN) return Keyboard::Return; if (Key == VK_ESCAPE) return Keyboard::Escape; if (Key == VK_TAB) return Keyboard::Tab; return Keyboard::Unknown; } } struct Console : NonCopyable { Console(short left, short top, short width, short height, const std::string& rStrTitle, short rWidth = 8, short rHeight = 12); void setFontSize(short& rWidth, short& rHeight); void title(const std::string& rStrTitle); void resize(const short width, const short height); bool pollEvent(Event& ev); POINT getMousePosition() const; private: COORD getFontSize() const; void setPosition(short left, short top); std::deque<POINT> mMouseMoveQueue; }; Console::Console(short left, short top, short width, short height, const std::string& rStrTitle, short rWidth, short rHeight) { if (!SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT)) { throw failed to SetConsoleMode(); } setPosition(left, top); title(rStrTitle); resize(width, height); setFontSize(rWidth, rHeight); } void Console::setFontSize(short& rWidth, short& rHeight) { CONSOLE_FONT_INFOEX cfix = { 0 }; COORD cfs1 = { 0, 0 }, cfs2 = { 0, 0 }; short w = rWidth, h = rHeight; cfix.cbSize = sizeof(CONSOLE_FONT_INFOEX); rWidth = 0; rHeight = 0; if (GetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfix)) { cfs1 = GetConsoleFontSize(GetStdHandle(STD_OUTPUT_HANDLE), cfix.nFont); if (cfs1.X && cfs1.Y) { cfix.dwFontSize.X = w; cfix.dwFontSize.Y = h; if (SetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfix) && GetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfix)) { cfs2 = GetConsoleFontSize(GetStdHandle(STD_OUTPUT_HANDLE), cfix.nFont); if (cfs2.X && cfs2.Y) { rWidth = cfs2.X; rHeight = cfs2.Y; } } } } } void Console::setPosition(short left, short top) { SetWindowPos(GetConsoleWindow(), NULL, left, top, 0, 0, SWP_NOZORDER | SWP_NOSIZE); } COORD Console::getFontSize() const { COORD tempfontsize = { 0, 0 }; CONSOLE_FONT_INFOEX cfix = { 0 }; cfix.cbSize = sizeof(CONSOLE_FONT_INFOEX); if (GetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfix)) { tempfontsize = GetConsoleFontSize(GetStdHandle(STD_OUTPUT_HANDLE), cfix.nFont); } return tempfontsize; } void Console::title(const std::string& rStrTitle) { SetConsoleTitleA(rStrTitle.c_str()); } void Console::resize(const short width, const short height) { long lHeight = 0, lWidth = 0; HMONITOR hMonitor = NULL; MONITORINFO mi = { 0 }; CONSOLE_FONT_INFO cfi = { 0 }; COORD crdfontsize = { 0, 0 }; COORD coord = { 0, 0 }; COORD crdbuf = { width, height }; hMonitor = MonitorFromWindow(GetConsoleWindow(), MONITOR_DEFAULTTONEAREST); mi.cbSize = sizeof(MONITORINFO); if (!GetMonitorInfo(hMonitor, &mi) || !GetCurrentConsoleFont(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfi)) { return; } crdfontsize = GetConsoleFontSize(GetStdHandle(STD_OUTPUT_HANDLE), cfi.nFont); lWidth = width * crdfontsize.X + 2 * (GetSystemMetrics(SM_CXFRAME) + GetSystemMetrics(SM_CXBORDER)); lHeight = height * crdfontsize.Y + 2 * (GetSystemMetrics(SM_CYFRAME) + GetSystemMetrics(SM_CYBORDER)) + GetSystemMetrics(SM_CYCAPTION); if (crdfontsize.X == 0 || crdfontsize.Y == 0 || lWidth > (mi.rcWork.right - mi.rcWork.left) || lHeight > (mi.rcWork.bottom - mi.rcWork.top) || lWidth < GetSystemMetrics(SM_CXMIN) || lHeight < GetSystemMetrics(SM_CYMIN)) { return; } coord.X = static_cast<short>((mi.rcWork.right - mi.rcWork.left) / crdfontsize.X); coord.Y = static_cast<short>((mi.rcWork.bottom - mi.rcWork.top) / crdfontsize.Y); if (SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coord) && SetWindowPos(GetConsoleWindow(), NULL, 0, 0, lWidth, lHeight, SWP_NOZORDER | SWP_NOMOVE) && SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), crdbuf)) { SetWindowPos(GetConsoleWindow(), NULL, 0, 0, lWidth + 50, lHeight + 50, SWP_NOZORDER | SWP_NOMOVE); } } POINT Console::getMousePosition() const { POINT pos = { 0, 0 }; if (!GetCursorPos(&pos) && ScreenToClient(GetConsoleWindow(), &pos)) { throw failed to GetCursorPos(&pos); } POINT delta = { 0, 0 }; ScreenToClient(GetConsoleWindow(), &pos); delta.x = pos.x / getFontSize().X; delta.y = pos.y / getFontSize().Y; return delta; } bool Console::pollEvent(Event& ev) { if (!mMouseMoveQueue.empty()) { ev.type = ms::Event::MouseMoved; ev.mouseMove.x = mMouseMoveQueue.front().x; ev.mouseMove.y = mMouseMoveQueue.front().y; mMouseMoveQueue.pop_front(); return true; } INPUT_RECORD record; DWORD numEvents; if (!GetNumberOfConsoleInputEvents(GetStdHandle(STD_INPUT_HANDLE), &numEvents)) { return false; } while (numEvents > 0) { DWORD numRead; if (!ReadConsoleInput(GetStdHandle(STD_INPUT_HANDLE), &record, 1, &numRead)) { return false; } if (numRead == 0) { return false; } switch (record.EventType) { case KEY_EVENT: { Keyboard::Key code = priv::KeyConvert(record.Event.KeyEvent.wVirtualKeyCode); if (code == ms::Keyboard::Unknown) { break; } ev.key.code = code; ev.type = (record.Event.KeyEvent.bKeyDown) ? ms::Event::KeyPressed : ms::Event::KeyReleased; return true; } case MOUSE_EVENT: { if (record.Event.MouseEvent.dwEventFlags == 0 || record.Event.MouseEvent.dwEventFlags == DOUBLE_CLICK) { DWORD change = record.Event.MouseEvent.dwButtonState; if (change == FROM_LEFT_1ST_BUTTON_PRESSED) { ev.mouseButton.button = ms::Mouse::Left; } else if (change == RIGHTMOST_BUTTON_PRESSED) { ev.mouseButton.button = ms::Mouse::Right; } else if (change == FROM_LEFT_2ND_BUTTON_PRESSED) { ev.mouseButton.button = ms::Mouse::Middle; } else if (change == FROM_LEFT_3RD_BUTTON_PRESSED) { ev.mouseButton.button = ms::Mouse::XButton1; } else if (change == FROM_LEFT_4TH_BUTTON_PRESSED) { ev.mouseButton.button = ms::Mouse::XButton2; } else { break; //invalid key } ev.type = (change & 0x8000) ? ms::Event::MouseButtonPressed : ms::Event::MouseButtonReleased; return true; } if (record.Event.MouseEvent.dwEventFlags == MOUSE_WHEELED) { ev.type = ms::Event::MouseWheelMoved; ev.mouseWheel.delta = record.Event.MouseEvent.dwButtonState; return true; } if (record.Event.MouseEvent.dwEventFlags == MOUSE_MOVED) { mMouseMoveQueue.push_back(getMousePosition()); return true; } } case WINDOW_BUFFER_SIZE_EVENT: { ev.type = ms::Event::Resized; ev.size.width = record.Event.WindowBufferSizeEvent.dwSize.X; ev.size.height = record.Event.WindowBufferSizeEvent.dwSize.Y; return true; } case FOCUS_EVENT: { //should be ignored break; } default: { //ignored break; } } //switch // event was ignored - let's see how many are left. if (!GetNumberOfConsoleInputEvents(GetStdHandle(STD_INPUT_HANDLE), &numEvents)) { return false; } } return false; }}int main(){ ms::Console window(350, 50, 80, 50, test console library 0.01, 8, 8); bool isRunning = true; while (isRunning) { ms::Event event; while (window.pollEvent(event)) { // Window closed or escape key pressed: exit if ((event.type == ms::Event::Closed) || ((event.type == ms::Event::KeyPressed) && (event.key.code == ms::Keyboard::Escape))) { isRunning = false; } else if (event.type == ms::Event::Resized) { std::cout << Resized to << event.size.width << , << event.size.height << std::endl; } else if (event.type == ms::Event::MouseButtonPressed) { std::cout << Mouse button << event.mouseButton.button << pressed << std::endl; } else if (event.type == ms::Event::MouseButtonReleased) { std::cout << Mouse button << event.mouseButton.button << released << std::endl; } else if (event.type == ms::Event::MouseWheelMoved) { std::cout << Mouse wheel moved by << event.mouseWheel.delta << std::endl; } else if (event.type == ms::Event::KeyPressed) { std::cout << Key << char(event.key.code) << pressed << std::endl; } else if (event.type == ms::Event::KeyReleased) { std::cout << Key << char(event.key.code) << released << std::endl; } else if (event.type == ms::Event::MouseMoved) { std::cout << Mouse moved by << event.mouseMove.x << , << event.mouseMove.y << std::endl; } } if (ms::Keyboard::isKeyPressed(ms::Keyboard::A)) { std::cout << 'A'; } if (ms::Keyboard::isKeyPressed(ms::Keyboard::Left)) { std::cout << move left ; } else if (ms::Keyboard::isKeyPressed(ms::Keyboard::Right)) { std::cout << move right ; } }}
Simple Win32 console library (mimicking almighty SFML)
c++;c++11;console;library;sfml
null
_cs.51034
How can a 4-bit two's complement operation be implemented using only boolean logic gates (AND, OR, NOR, NOT, NAND, XOR, and XNOR)?(This question was redirected to CS from Stack Overflow)
Two's complement Using ONLY Logic Gates
logic;boolean algebra
A two's complement operation is simply a one's complement operation followed by the addition of 1 to the result. One's complement is easy: simply invert all of the input bits.The addition of 1 must be done with a 4-bit adder. A 4-bit adder is constructed using four stages of a 1-bit full adder. The 1-bit full adder accepts two bits, plus a Carry input, and generates the sum of the two bits, plus a Carry output. The following diagram is a 1-bit full adder:We can cascade four of the 1-bit full adder stages together, feeding the Carry output of each stage to the Carry input of the next stage. The inverted (one's complement) inputs are applied to the B inputs of the four stages. To perform an addition of 1, we apply the 4-bit binary value 0001 to the A inputs. The complete boolean circuit is shown below:The above circuit can be reduced by noting that each XOR operation on the input of each adder stage can be replaced either with an inverter if the A input is a 0, or a NOP (no operation) if the A input is a 1. On further analysis, further reductions may be made to the circuit, as well.
_softwareengineering.114394
My team and I are very keen on doing Scrum manual-style (with paper and scissors). Though, we are struggling to find a tool to manage our backlog. The main requirements are:To be able to print the backlog in cards to stick to the whiteboardTo be able to assign backlog items to the releases manuallySo far we have not found anything that matches these criteria. Suggestions?
Scrum tool for Product Backlog management
scrum;product backlog
We're using Rally. Once the sprint is defined, cards get printed, put up on the board, and we have a feedback loop between the board & the online record. Everyone in the office can see the board, so anyone can know the sprint status.