id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_cs.66116
Is there an efficient algorithm which computes the (possibly approximately) shortest $n$-edge path between two points $A$ and $B$ in a weighted complete graph? Dijkstra won't work because it will just give the trivial answer of $A\to B$. I'd like to find an $n$-edge path (e.g. for $n=4$, find $C$, $D$ and $E$ which minimize total path length of $A\to C\to D\to E\to B$).
Shortest path between two points with n hops
graphs;shortest path;traveling salesman
If vertices can be visited more than once, then yes: you can create $n+1$copies of the graph, with each vertex $v$ in the original graph becoming the $n+1$ vertices $v_1, \dots, v_{n+1}$ and each edge $uv$ in the original graph becoming the set of edges $u_iv_{i+1}$ for all $1 \le i \le n$; now run Dijkstra on the resulting graph with start vertex $A_1$ and end vertex $B_{n+1}$. Intuitively, each edge traversed in any path necessarily takes you to the next level of the graph.If vertices cannot be visited more than once, then there's no known poly-time algorithm, since setting setting $n$ to one less than the number of vertices would solve the NP-hard Hamiltonian Path problem. (Although the HP problem technically asks for any path that visits all vertices exactly once, a poly-time algorithm for the simple-paths version of your problem would nevertheless give you a poly-time algorithm for HP: just run it $O(n^2)$ times, one for each possible pair of start and end vertices.)
_softwareengineering.220209
My project involves validating and normalising email addresses in this format[userpart]@[domainpart].[tld]After syntactic validation of the address, [tld] is checked to exist, otherwise the validation fails.After validation, [userpart] and [domainpart] are normalised into a 32-bit numeric ID called [partid] (one for each part), partid and the part string are permanently stored on disk when new strings are discovered. 4 bytes seems the most sensible for each as 3 bytes is not enough (there are around 200 million registered domain names just now).To process lists of new emails quickly, I've been using Judy arrays (JudySL to be exact, http://judy.sourceforge.net/doc/index.html) , where the part string is mapped to the part id. I've used Judy Arrays as I know how to use them and they generally perform well, although they are not thread safe which is a slight drawback (I use mutexes to get round that). There's no collisions that I'd get with a hash table... which reduces complexity somewhat.However they seem to be taking up a much larger proportion of memory than I'd like, so my question is what would you suggest as a better storage method?Example case:64-bit system (Debian based)150,000,000 parts, averaging around 8 bytes each, 12 bytes total when including the partid~1.67GB for that data in itself~5.1GB used by JudyPerhaps worth noting that the emails are evaluated after being converted to punycode format.Input would come in lists varying between 10K and 1M rowsInserts on-demand, when a new [part] is found, ++partid is assigned as its partid and partid,part are written to diskNo deletes required, only inserts and lookups.So I need around 3x more memory than disk space in order to convert [~8-byte-string] to an int.Is there any better(*) data structures that I should be considering?(* by better, I'd hope for reasonably fast, with a smaller memory footprint and preferably something pre-written like a library...)UpdateThe TL;DR of my original question... converting a variable length string to a 32 bit INT.Strictly speaking the userpart is case sensitive but from what I understand the standard implementation is to ignore case. In that case (no pun), there are 56 valid characters in either punycoded domain part, or 6 bits worth.I'm thinking I can sacrifice 1-bit to indicate direct conversion of string->int without a lookup table, which will allow conversion back too. The bit would be switched on when this can occur and would prevent collisions with lookups, leaving 31 bits for data, and 2^31 IDs for all other domain parts that don't fit.I was messing around with fixed length 4-5-6 bit length codes based on the least frequent character, but huffman encoding would seem to (obviously?) win out in the long run and avoids a 2nd pass of the input string. Here's some data based on the char distribution across those 150m parts.http://pastebin.com/DTrUWSnaHuffman manages to have yahoo, gmail and even hotmail squeezed into 31 bits which is excellent. 6.1% of all parts can be mapped this way.With the same huffman encoding, a further 70.5% can be mapped to 63 bits which'd allow a fixed length int key->value list. This should save on memory (I'll try report back)That leaves less than 25% of all parts to be mapped still. This new layout should help a lot for saving on memory, thanks for the suggestions so far.
Most suitable data structure for in-memory string -> int conversion for variable length strings
data structures
null
_softwareengineering.277852
Option 1:At first I would make a call to my service layer, which served as an API for my core domain, to get a domain object or a list of domain objects and then pass them into the assembler which would construct the DTOs I needed for my view. The problem I have with this approach are cases where the domain object is large and I don't want to load in the whole object just to copy a few fields needed for the DTO (ie showing a list of summaries entities). Option 2:The next approach I used was to wire in a repository (for read-only purposes) into my assembler so that I could only query the database for the fields I need in the DTO. I can also use this repository when I get a DTO and need to use it to update and entity. For example, a DTO filled will values I need to update on my entity comes into my assembler, the assembler looks up the entity from a repository and then overlays the information from the DTO on the entity and then returns the entity. The controller then calls the service layer to save the entity that the assembler returned.Option 3:I could wire in the repositories directly into the controllers but something about exposing the repository in the controller seems wrong to me because the service layer should be handling transactions and security, but then again, if I put a repository in the assembler I am basically doing the same thing.Any thoughts are welcome. I just want to understand pros and cons and what has worked well for others.
What is the best way to create DTOs from entities and update entities from DTOs in a layered architecture?
design patterns;entity;domain driven design;dto
null
_webmaster.92855
In an automated email from Google's Search Console...1 Add all your website versionsMake sure you add separate Search Console properties for all URL variations that your site supports, including https, http, www, and non-www.What does ... site supports ... mean?I'm trying to do what Google suggests in this knowledge base article about using canonical URLs, but it isn't totally clicking in my head just yet. My end goal is that I want Google to understand my site is available at https://www.example.com/ and every other permutation is incorrect. Should I add http://www.example.com/, http://example.com/, and https://example.com/ as properties to my Google Search Console?I think I have (correctly) set up my .htaccess file so that all naked and/or http requests will be 301'd to www. prefixed and https requests.public_html/.htaccess<IfModule mod_rewrite.c>RewriteEngine OnRewriteCond %{HTTP_HOST} !^www\.RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]RewriteCond %{HTTPS} !=onRewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]</IfModule>
Google Search Console - Which Properties Should I Add?
google search console
As Google clearly says, you should add all versions of your site as followshttp://example.comhttp://www.example.comand the 2 https versions. What does ... site supports ... mean?Well, it means whatever URLs are supported by your site i.e. are served by your site. Google will treat each of them differently and you have to keep checking all the four to ensure that most of your traffic is moving to your canonical property i.e. https://www version in your case.I would suggest you add all four, and periodically keep checking - Doing by practice is sometimes the best way to clear your head.
_unix.166263
I am trying to measure the cpu usage of my ubuntu machine and if the cpu usage is more than 60%, then I need to find out the process who has the highest cpu usage and then send out an email saying CPU usage is more than 60% and with the process name which has the highest cpu usage.When I do top this is what I see. Cpu0 : 20.0%us, 0.0%sy, 0.0%ni,100.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%stCpu1 : 34.0%us, 0.0%sy, 0.0%ni,100.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%stCpu2 : 17.0%us, 0.0%sy, 0.0%ni,100.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%stCpu3 : 20.0%us, 0.0%sy, 0.0%ni,100.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%stI came up with the below script which only finds out the cpu load but not the cpu usage. How do I achieve above thing?#!/bin/bashtop -bn1 | grep load | awk '{printf CPU Load: %.2f\n, $(NF-2)}' To send an email, I use below command and it works for me - echo Body | mailx -r [email protected] -s SUBJECT [email protected]
Find the process which is taking maximum CPU usage if CPU usage is more than 60%?
shell script;performance;top
using awk:ps aux --sort=-%cpu | awk 'NR==1{print $2,$3,$11}NR>1{if($3!=0.0) print $2,$3,$11}' > some_file.txtthe above code will give all program with non-zero cpu usage. will give you pid,%cpu, command_nameif you want cpu usage greater than equal to 60 replace $3!=0.0 to $3>=60I have saved the output in file some_file.txt. you can cat the file and pipe it to mail command.try like this: to send mailcat some_file.txt | mailx -r [email protected] -s SUBJECT [email protected]
_webapps.91799
I want to automatically, once a day, retrieve all (or all new) messages from a Facebook Page where I have admin rights.I have investigated using Graph API, but in order to use this, I need to create an app. Moreover, in order to read messages, I need the 'read_page_mailboxes' permission. As far as I can understand, I need to demonstrate a proper app by screencast to the facebook team to get this permission granted, as explained here:https://support.ladesk.com/704852-How-to-submit-Facebook-application-for-reviewI don't have any such app, as I just plan to retrieve the messages by a web service interface.I have also investigated digi.me, which is a third-party tool that can take backups of the messages to a PC. The sync with facebook can by automated. The problem is that it is only possible to manually export the content out of the internal application storage, it can't be scheduled.Do anyone know any way to periodically and automatically retrieve messages from Facebook Pages? Any method would be fine: commercial third-party tools, automatic forwarding to email, whatever works.
How can I retreive messages from Facebook Pages?
facebook;facebook pages;facebook chat
null
_cs.47769
I know this might sound like a newbie question, but bear with me.I have read a paper where researchers use a random forest to predict species distribution, but in their study, they only predict a new set of points given an old set and a map of environmental variables. https://www.uam.es/proyectosinv/Mclim/pdf/MBenito_EcoMod.pdfI would like to replicate these results, only using a random forest to predict a new set of vectors given a set of vectors (the seal migrations) and some environmental variables in map form (a scalar field).My plan would be to prepare the training data as each vector paired with the environmental variables (ocean surface temperature, ocean currents, etc.) at the head and tail of that vector. Would a random forest be able to, given this type of data, predict a new set of vectors if I feed it a new map of environmental variables? Is this even the right way to go about this? Thanks so much, I really appreciate anyone's feedback and or criticism.
Using the random forest algorithm to predict vectors
machine learning;trees;randomized algorithms;neural networks;statistics
null
_softwareengineering.251756
We have been building custom software for one of our customer for a few years now. Everything is going well so far.However the customer always has an attitude that when they find a bug in the software, then they are getting really pathetic and complain that they are now really disappointed with the quality of the software: Because if they found this one bug then there surely must be other bugs, so they assume that the quality of the software is getting worse. It's almost like a proof by induction: If there is one then there must be many.To me, there can always be bugs (the software is part of their CRM solution, so nothing like software used to run airplanes, nuclear reactors, etc.) Obviously, we have various means of testing, but we (or the customers) are not testing everything, so bugs can slip through. Which is OK in my opinion.But how would you react to such a pathetic and emotional response? I am always totally speechless when they start this way.
Customer is deeply disappointed in our software because of one bug. How to reply?
code quality;bug;customer relations
It sounds like for the most part, you have a good relationship with this customer. (Everything is going well so far.)Presumably you want to keep that relationship.But it sounds like this scenario has occurred more than once.Perhaps you have somehow (unintentionally, perhaps) let the customer believe that you aren't bothered by these occasional bugs as much as they are. If so, the customer may feel they should increase their own expressed level of concern over the problem in order to get more attention from you.In such cases, the more you appear to brush off the problem, the more they will complain.Outside of (possibly) some very expensive development processes, it is perhaps inevitable that a bug will sometimes be found after release. But it never needs to be acceptable (or OK) for bugs to slip through. You can reconcile these two beliefs by making it clear that you don't want to deliver buggy software and that you take the discovery of even one bug as something to be addressed.The next step is to figure out how to address it.If you make the customer understand that you are on top of the situation and doing everything within reason to fix the problem, they may complain less. If they somehow inform you of the existence of the bug (such as in an email saying, Hey, is this supposed to happen?) before the meeting where they tell you how disappointed they are, you might even be able pre-emptively to make them understand (even before the meeting) how seriously you take this situation and in that way possibly deflect some of the criticism.
_vi.5929
I'm using r a lot (e.g. for replacing with ' when refactoring code). Is there an easy way to do something like this:For text: values = [a, b, c].Place cursor on first , press r' to change to values = ['a, b, c].Now we want to repeat that five times.For example by pressing 5<Ctrl>r.To repeat previous r command five times for next occurences of '.Would this be possible? And if so, how?I know I can do <Shift>v:s//'/<Enter>. But this seems inefficient.Please help making my life easier. ;)
Repeat replace one character (r) for next occurence
replace;repeated commands
Well, <Shift>v:s//'/<Enter> is certainly less efficient than :s//'<CR>.Here are various ways to perform the same task:f jump to next r' replace it with a ';. repeat jump then repeat replace;. repeat jump then repeat replace;. repeat jump then repeat replace;. repeat jump then repeat replace;. repeat jump then repeat replace/<CR> search for next cgn'<Esc> change it to ' (Note: the gn command was introduced in Vim 7.3.610)..... repeat change 5 timesqq start recording in register qf jump to next r' replace it with 'q stop recording5@q replay recording 5 timesNone of which being as efficient as :s//'<CR> which can be made even better with a small mapping:nnoremap <key> :s/nnoremap <otherkey> :%s/
_unix.308718
I use Smb4K for mounting my shares across my machines. However, something's happened, and when I mount my NAS share on my laptop I can't write to the share unless I sudo to root.According to top, Smb4K runs under my user account. Smb4k's settings for user and group are 1000 and the file and dir masks are 0755, and write access is set to read-write. However, when it mounts the device to /media/nasbox/fileshare, the nasbox folder is created under the user account, but the fileshare folder was created under the root account.When I unmount, both nasbox and fileshare are removed from the filesystem.Whilst mounted, if I try to chown the fileshare to the user account, it says success, but doesn't actually change.Does anyone know how I can fix the permissions to write normally?
Permissions in smb4k mounts
kde;samba
null
_unix.111073
I need to install Debian with an image less than 1GB, with a desktop environment and reasonable functionality. The Wheezy image is around 1.2 GB and my USB stick is 1GB. I can't understand the net-install either, and Debian does not auto-detect my wireless card on install.What else can I try?
Debian install less than 1 GB.
debian
null
_unix.28188
I can do tcpdumps with this command: tcpdump -w `date +%F-%Hh-%Mm-%Ss-%N`.pcap src 10.10.10.10 or dst 10.10.10.10Q: I have an FTP server with username: FTPUSER and password FTPPASSWORD. How can I upload the tcpdump in real time I mean I don't have a too big storage to store the dumps, so I need to upload it to a place what I can only reach via FTP. Can I pipe somehow the output of the tcpdump to an ftp client that uploads it? [I need to preserve the filenames too: date +%F-%Hh-%Mm-%Ss-%N.pcap]so I'm searching for a solution that doesn't store any tcpdumps locally, rather it uploads the dumps in real-time.The OS is OpenWrt 10.03 - the router where the tcpdump runs. [4MB flash on the router, that's why I can't store them locally.]UPDATE2: there is no SSH connection to the FTP server, just FTP [and FTPES, but that doesn't matter now I think]
How to upload tcpdumps in realtime to FTP?
ftp;openwrt
install curlftpfsopkg update; opkg install curlftpfsthen create a script that will run after every boot of the routervi /etc/rc.d/S99tcpdumpthe content of S99tcpdump#!/bin/ashmkdir -p /dev/shm/somethingcurlftpfs FTPUSERNAMEHERE:[email protected] /dev/shm/something/tcpdump -i wlan0 -s 0 dst 192.168.1.200 or src 192.168.1.200 -w /dev/shm/something/tcpdump-`date +%F-%Hh-%Mm-%Ss`.pcap &make it executablechmod +x /etc/rc.d/S99tcpdumpreboot router, enjoy.p.s.: looks like -s 0 is needed because there could be messages like: packet size limited when capturing, etc. - when loading the .pcap files in wiresharkp.s.2: make sure the time is correct because if not, the output filename could be wrong..
_softwareengineering.235393
In the source code I'm evaluating (jarjar), there exists java code that can be used like this:JarJarTask fixture = new JarJarTask();fixture.addConfiguredRule(new Rule());fixture.execute();Which will throw an exception like:java.lang.IllegalArgumentException:The <rule> element requires both pattern and result attributes.Now, to me it is clear that the API is less than optimal here - if the rule element requires these attributes, it should ask for them in the constructor (or provide a Builder or similar that would require them). But I was unable to find coding conventions or java programming recommendations to agree with me.Is there some specific name for this that I can use to look this up in research, programming literature, style guides? Which terms could I use to find some discussion on this?Surely it's been discussed somewhere using some terms, but I seem to be unable to find anything.I did find discussion around constructor injection as presented by Kent Beck in Smalltalk Best Practice Patterns and supported by Martin Fowler, which, according to this, makes it immediately clear what a class requires when it is instantiated, and furthermore it is impossible to instantiate the class without passing in the fields objects. So that's a starting point at least to find some discussion.
Is there a named antipattern for unclear API not exposing the requirements?
coding style;anti patterns
The best you're going to do here is to state what the API isn't, or what it fails to provide. Constructor vs. Setter Injection is a bit of a side journey, but the principle is sound: write your classes so that it is clear from the constructor arguments exactly what is required to create a fully-formed, functional object. If you follow best practices in your organization, simply state that the class fails to follow the practice of describing its instantiation requirements in the constructor.RelatedDesign by Contract
_cs.62790
I am working on a transformation from k Vertex Cover to SAT and I have some issues regarding the last clause in the boolean formula.Here is my approach: $$\forall \text{ nodes } n_i \in V, \text{ invent variables } v_i$$ $$\forall \text{ edges } (n_i, n_j) \in E, \text{ invent the terms } (v_i \lor v_j) \Rightarrow C_{edges}$$Is this approach correct or am I missing something?
Reducing k Vertex Cover to SAT (last clause problem)
complexity theory;reductions;satisfiability
null
_unix.244704
I tried to check who is connecting to my server and got this line I could not recognized. I used sudo lsof -i -n | egrep '\<ssh\>'. And these lines looks odd to me:sshd 5921 sshd 3u IPv4 66008 0t0 TCP 192.168.1.165:ssh->43.229.53.76:59605 (ESTABLISHED)sshd 5922 root 3u IPv4 66056 0t0 TCP 192.168.1.165:ssh->43.229.53.76:60008 (ESTABLISHED)sshd 5923 sshd 3u IPv4 66056 0t0 TCP 192.168.1.165:ssh->43.229.53.76:60008 (ESTABLISHED)sshd 5924 root 3u IPv4 66082 0t0 TCP 192.168.1.165:ssh->43.229.53.76:60407 (ESTABLISHED)The address is from HongKong and I am not aware of why that could happen.
What does this mean :sshd 5927 root 3u IPv4 66110 0t0 TCP 192.168.1.165:ssh->43.229.53.76:60 673 (ESTABLISHED)
sshd
null
_cogsci.1732
A while back, I watched the movie The Terminal and the main character played by Tom Hanks learns to speak fluent English while he is stranded in the airport for more than a year. Which seems somewhat superfluous as I was of the opinion that picking up a new language when you grow older is not easy. But Tom Hanks' character manages to speak English quite fluently given his background. Dr Martha Young-Scholten of University of Newcastle mentions that the movie accurately describes how someone would acquire a second language under naturalistic exposure:Misrepresentations of complex issues such as adult second language (L2) acquisition are rife in the news media; one does not expect Hollywood to differ. Yet the 2004 film The Terminal (2004) gets it right. Stranded in a NY airport for a year, Tom Hanks character accurately depicts the early stages of acquisition and demonstrates how ample naturalistic exposure leads to advanced L2 proficiency. Hollywood also manages cultural nuances; initial communication fails because the authorities assume Hanks is attempting to immigrate when his purpose is one of pilgrimage.If an individual is forced to use a language he is almost unfamiliar with, would it help him make significant progress in acquiring that language, regardless of his age?
Does the effect of naturalistic exposure on second language acquisition vary with age?
learning;language;aging
null
_unix.119525
CentOS 5.xI'd like to understand what is specifically happening to incoming packets that don't explicitly match rules in my iptables chains. Is the default action to reject them? Or drop them? How/where can I set this? Here's an example output of my firewall setup (some ports have been modified to protect the innocent :-) ) :Chain INPUT (policy ACCEPT)target prot opt source destinationRH-Firewall-1-INPUT all -- anywhere anywhereChain FORWARD (policy ACCEPT)target prot opt source destinationRH-Firewall-1-INPUT all -- anywhere anywhereChain OUTPUT (policy ACCEPT)target prot opt source destinationChain RH-Firewall-1-INPUT (2 references)target prot opt source destinationACCEPT all -- anywhere anywhereACCEPT all -- anywhere anywhereACCEPT icmp -- anywhere anywhere icmp anyACCEPT esp -- anywhere anywhereACCEPT ah -- anywhere anywhereACCEPT all -- anywhere anywhere state RELATED,ESTABLISHEDACCEPT tcp -- anywhere anywhere state NEW tcp dpt:456REJECT all -- anywhere anywhere reject-with icmp-host-prohibitedThe key point though is that I have a different chain called RH-Firewall-1-INPUT that doesn't have an explicit (policy ACCEPT) or (policy REJECT) statement. What would be the default behavior for that (assuming of course that I'm NOT matching any of the prior rules). Is the last line just a catch all?
What is the default action for incoming packets that don't match explicit iptables rules?
networking;security;iptables
null
_unix.299503
There are many posts here on U&L on the topic; Using arch + xfce + no display manager but the bug (obviously) keeps saving my sessions although Automatically save session on logout is unchecked.What would be the best workaround? Right now I am thinking of rm the contents of .cache/sessions and .xfce4-sessions in .xinitrc.UpdateA simple one-liner solves the problem (the ugly way). The .xinitrcrm -R ~/.cache/sessions
xfce session always saved
arch linux;xfce;desktop environment
null
_unix.335051
Is there any way to automatically click a link in an email from a specific recipient in Evolution, as the emails come in? Perhaps there is an extension that can be added, or possibly a macro? If not, is there any other way of doing this?
Can hyperlink clicks be automated in Evolution and how
email;evolution
I don't think that you can directly click links, but Evolution have filters that can invoke different actions. One of the action is Pipe to Program.Create filter by going to: Edit -> Message filters -> Add and set it to filter emails from the address that you want. In Then section select Pipe to Program and select script to process your mail.I would reccomend simple Python script to process the mails - it has to allow input to be piped into it. Example below (based on this and this) should give you some idea how to achieve it. Obviously instead of logging urls to file you would have to open browser or just open it using urllib or similar.#!/usr/bin/python import fileinputimport ref = open('a.out', 'a')for line in fileinput.input(): urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', line) for url in urls: f.write(url+\n)f.close()
_cs.54047
Assuming its one step closer to realism as compared to ANN, DNNs and other Neural Network models, what are the primary differences between a real neuron system and SNN?
How different is the working of SNN (Spiking Neural Network) as compared to a real Neuron System in biological systems?
machine learning;artificial intelligence;neural networks;bioinformatics
There are different types of spiking neural network models:Hodgkin-Huxley: models the processes within a neuron with electrical parts. This results in differential equations with 4 variables (capacity of the membrane, resistance of the ion channels, balance potentials, openings of the ion channels).Leaky integrate and Fire (LIF): Probably the simplest SNN; it is only an ordinary first order differential equation Spike Response Model: models refraction time. It tries only to model the phenomena. Although it is simple, it is still more accurate than LIF.I don't have a biology background, but I would say the Hodgkin-Huxley model is probably the closest to real neurons. However, as far as I know (which is very little), there is no (effective, plausible) training algorithm. So this is probably the key difference to the brain. Also the topology will certainly be different.And, of course, we can model much less spiking neurons than we have natural neurons in a human. So the number of neurons is a key difference, too. I've heard SNNs have a few dozend neurons, probably up to several hundred neurons. The biggest MLP (CNN) models I've seen so far have about 150 000 neurons (see Deep Residual Learning for Image Recognition). The human brain has about 86,000,000,000 neurons (see Wikipedia).
_cs.52729
I'm watching a video, demonstrating merge sort, https://www.youtube.com/watch?v=EeQ8pwjQxTMAt 5:42, happens something I do not understand. We are merging last 2 big arrays, [4,15,50,108] and [8,16,23,42].My understanding is - we pick each pair, since they are already in sorted arrays, and swap them if one is larger than the other.So it goes well, until 23 is smaller than 50, and next element is 42 which is smaller than 108 and we end up with [4,8,15,16,23,50,42,108].Obviously, my understanding is faulty. But I heard no indication we go we compare each element in first array with all the elements of second one. Did I miss it? If so, how's the n log n complexity achieved, since we do n^2 operations?
merge sort merge phase
algorithms;algorithm analysis;sorting
How does the merging work?Imagine two pointers, starting at the first element of each array. In this example I will use the #-Symbol to indicate the pointers.This is your start configuration:[#4,15,50,108][#8,16,23,42][ ]Now you always compare the elements, that the pointers are pointing at and move the smaller element to the merged list. Then you move the winning pointer to the next element. The loser pointer does not move. If a pointer reaches the end of the list, the other pointer always wins.This is your result after the first comparison:[4,#15,50,108][#8,16,23,42][4]4 won the comparison and therefore is added to the merged list. The pointer is moved to the next position. Now we start over and compare 15 and 8 resulting in this configuration:[4,#15,50,108][8,#16,23,42][4, 8]This process continues until each element is in the merged list.After comparing 15 and 16:[4,15,#50,108][8,#16,23,42][4, 8, 15]After comparing 50 and 16:[4,15,#50,108][8,16,#23,42][4, 8, 15, 16]After comparing 23 and 50:[4,15,#50,108][8,16,23,#42][4, 8, 15, 16, 23]And so on...In code these pointers could be realised by using indexes for the lists (increasing them when the pointer has to move) or using queues (always taking the first element).How is it $O(n*log(n))$ if we do $O(n^2)$ Operations?Because we dont. During the merge process, every element is still only visited once (you never decrease a pointer). If your merge algorithm has two lists of length $n$ for arguments, then it needs $O(2*n)$-Time but $O(2*n) = O(n)$. And with merging in $O(n)$, merge sort is in $O(n * log(n))$.
_unix.278564
[NOTE: The intent of this question is to help people evaluate whether systemd timers would be a good choice for their job timing needs. Many (most?) people are probably using cron, but maybe some are open to alternatives/improvements.]It was recently pointed out to me that an alternative to cron exists, namely systemd timers.However, I know nothing about systemd or systemd timers. I have only used cron.There is a little discussion in the Arch Wiki. However, I'm looking for a detailed comparison between cron and systemd timers, focusing on pros and cons. I use Debian, but I would like a general comparison for all systems for which these two alternatives are available. This set may include only Linux distributions.Here is what I know.Cron is very old, going back to the late 1970s. The original author of cron is Ken Thompson, the creator of Unix. Vixie cron, of which the crons in modern Linux distributions are direct descendants, dates from 1987.Systemd is much newer, and somewhat controversial. Wikipedia tells me its initial release was 30 March 2010.So, my current list of advantages of cron over systemd timers is:Cron is guaranteed to be in any Unix-like system, in the sense of being an installable supported piece of software. That is not goingto change. In contrast, systemd may or may not remain in Linuxdistributions in the future. It is mainly an init system, and may bereplaced by a different init system.Cron is simple to use. Definitely simpler than systemd timers.The corresponding list of advantages of systemd timers over cron is:Systemd timers may be more flexible and capable. But I'd likeexamples of that.So, to summarise, here are some things it would be good to see in an answer:A detailed comparison of cron vs systemd timers, including pros andcons of using each.Examples of things one can do that the other cannot.At least one side-by-side comparison of a cron script vs a systemdtimers script.
Cron vs systemd timers
cron;systemd timer
null
_webapps.67760
I am working on a document that involves two languages simultaneously.In Open Office I have created a 2-column table, with the left-hand column set to English and the right-hand column set to the other language (for spell checking, grammar, hyphenation, ...).Now I'd like to invite others to collaboratively edit this document, and a Google document almost seems like a good solution.How do I do the same thing in Google Docs? I can only find a language setting for the entire document.
How do I use two languages simultaneously in Google Docs?
google documents
null
_unix.325846
I got gulp installed via npm. When I execute gulp in any folder it works as expected. But when I'm in a folder which contains a folder named gulp, it changes the directory (cd) into this folder instead of executing the command.How can I fix this?
ohmyzsh opens folder instead of command (autocd)
zsh;oh my zsh
null
_unix.39624
Centos- 6, LVM2after a system hang and hard reboot.lvdisplay and lvscan return no volumes. It had volumes earlier...how to recover?there is data on LV (logical volume) - shared as NFS export..VG is listed under /etc/lvm/backup/datastore1. any ideas to restore the LV?vgdisplay -- Volume group -- VG Name datastore1 System ID Format lvm2 Metadata Areas 1 Metadata Sequence No 1 VG Access read/write VG Status resizable MAX LV 0 Cur LV 0 Open LV 0 Max PV 0 Cur PV 1 Act PV 1 VG Size 10.92 TiB PE Size 4.00 MiB Total PE 2861467 Alloc PE / Size 0 / 0 Free PE / Size 2861467 / 10.92 TiB VG UUID 7uq001-dUxd-I1WS-PPu2-ljT3-FybY-D9ddx2cat /etc/lvm/backup/datastore1datastore1 { id = 7uq001-dUxd-I1WS-PPu2-ljT3-FybY-D9ddx2 seqno = 2 status = [RESIZEABLE, READ, WRITE] flags = [] extent_size = 8192 # 4 Megabytes max_lv = 0 max_pv = 0 metadata_copies = 0 physical_volumes { pv0 { id = kRGDrz-YFyf-EIKk-0om6-9H78-jgle-9z0B27 device = /dev/cciss/c0d1p1 # Hint only status = [ALLOCATABLE] flags = [] dev_size = 23441142637 # 10.9156 Terabytes pe_start = 2048 pe_count = 2861467 # 10.9156 Terabytes } }}
Logical volume missing after reboot
linux;lvm;nfs
If you're about to restore the LVM partiton scheme from backup file , you could try:vgcfgrestore datarestore1If everything is ok , try activate all LVs by:vgchange -ayAnd do a fsck on all volums with fsck , e.g fsck /dev/datarestore1/XXIf no errors occured , try mount them by mount -a
_codereview.32769
Does this code create sufficiently hard-to-guess session tokens, assuming the server and client are communicating over HTTPS?Take 2 (thanks to this crypto.SE answer):(ql:quickload (list :ironclad :cl-base64))(let ((prng (ironclad:make-prng :fortuna))) (defun new-session-token () (cl-base64:usb8-array-to-base64-string (ironclad:random-data 32 prng) :uri t)))As an additional note, the previous version was using the incorrect encryption mode (ecb, instead of ctr which is preferable for this task), and using an insecure method of generating random keys ((sha256 rand)).If not, what else is required for that goal, and why?Are there attacks I should be worried about other than guessing and sniffing session tokens?
Generating hard to guess session tokens
security;common lisp
Your question doesn't give enough information about exactly what you want to do to know if this might work in your case. The most important answer is simple though: don't do that; use a web framework instead. Session management should almost always be done in the standard way of your framework; then you won't have to do anything other than check if your framework thinks your user is authenticated. Let's now look at the specifics of the code. You have used a cryptographic PRNG. That should be fine. You used 32 bytes = 256 bits of random data. This should be no problem (128 bits is normally enough against brute force attack; 256 is overkill, which is likely good in this case) your main fears should probably be seeding and leaking bits.Seeding: the PRNG documentation says that if you don't give a random seed the PRNG will be unseeded. In real life it seems that it actually does get seeded from /dev/random. I deeply don't like this and would probably seed it explicitly. Better would be discuss with the author and send a patch to the documentation for the library so that it promises to do what it actually does. I don't have an OS without /dev/random to test on, but I think your function simply won't work there (which is good because it's safe).Leaking bits1: If the attacker can find a situation where response time depends on the contents there might be a problem (e.g. force regeneration of the session). Looking up about timing attacks on Ironclad I don't think it's resistant (see e.g. https://www.mail-archive.com/[email protected]/msg00977.html). You need to check or protect against this. If the contents of the message are true then you should probably switch to a better library such as LibreSSL when it comes out (possibly GNU TLS?). If someone attempts to use the function on e.g. Windows I would simply exit with a warning. Leaking bits2: your output is constant size but includes some special characters. If the attacker can find a situation where your message length depends on the authentication token then you have a problem. Using Base64 encoding (a second time) should be fine. Using maximal HTML encoding for your tokens will not be (n.b. normal HTML would be fine; but some encoders go too far). Leaking bits3: Going further, there are standard attacks against SSL/TLS which I think you should consider; BEAST, CRIME and BREACH which leak bits https://en.wikipedia.org/wiki/Transport_Layer_Security#CRIME_and_BREACH_attacks. Increasing the size of your random token beyond 256 bits might marginally protect against such things. However In the current form, the exploit uses JavaScript and needs 6 requests to extract one byte of data (https://community.qualys.com/blogs/securitylabs/2012/09/14/crime-information-leakage-attack-against-ssltls) so I think you may find that effort would be better invested in turning off compression on all sites and user web browsers. Personally I would go for 384 bytes just to be more conservative than the rest ;-) Summary: probably your function is basically the same one used in many frameworks. Because of the risk of timing attacks and bit leakage I wouldn't personally want to release it for public use until I understood the whole surrounding situation of usage much better than I currently do. (edited lots since I misread bytes as bits in the first response)
_webmaster.93877
I made a photo collage editor system on my site and I tried to made the page with a lot of text so that users know what is going on. This is the URL if anyone is wondering: http://new.clubcatcher.com/collageAnyways, what happens to new users is that a sticky box appears over content at the bottom right reminding guests where they can go if they need extensive help on making a collage. They can click the no thanks button in the box to remove it completely.Now I'm starting to think my income went down again because of this box. Maybe google is thinking that I'm just playing games with people by blocking content, yet I'm only doing it to try to help people. This is the only section of the site where that box would exist. The only other times a box like that exists is if the user decides to go through the tutorial.As for box implementation, the box is hidden by default via CSS then javascript checks for a special cookie and if it is unset, the box appears, otherwise it stays hidden.I still want to point out to users that such tutorial exists, but somehow I feel the way I'm doing it is frustrating google.What would be another way I can advertise the existence of the tutorial from within the same page where even the dumbest person on the planet can still find it without frustrating google, any user, or any other search engine?
alternative to adding a box initially covering content that actually helps users
content
null
_softwareengineering.146255
We are in a small company with around 10 developers. I am the team leader and responsible for the development process.Supervisors and salesmen are close to us since we are a small team, but have no clue on how software is developed.When they ask me how much time I want for a change (bugfixes/features) in a product, my response is 'let me calculate it'. After giving them the schedule, they start by saying OK you can do it in XX time which differs a lot from my plan. We are using a model close to Agile basic principles and have circles per week or per three days.Of course I argue and say that this cannot be done. They seem to have no idea on the effort we are doing. They do not want to see WHY my schedule is for that amount of time. I know this behavior is stupid, but how can I make them see the problem?
Completion time on a company where the supervisors don't know programming
development process;time estimation;leadership
If the salesmen are also the ones who are in charge, you can say, Ok, I can go with your schedule. Which features or responsibilities would you like me to sacrifice in order to make your deadline? That way you're not saying no to the people in charge but you're not committing to impossible things. The decision is in their hands how to run the business. If they want to axe other things to make time for the changes, let them.EDIT:We need to respect and submit to those who are in authority, while still doing our jobs with excellence. The only way to do this is with humility. I'll work on whatever my boss wants me to work on, but I can only do so much. When you tell him like it is with an attitude of submission, he is in a better position to make better decisions and he'll want more employees like you.Make sure these things are documented too in order to explain why the commitments are unreasonable and how the situation was resolved. It can help coworkers deal with similar situations in the future.
_hardwarecs.4391
I want to build a PC as small as possible, so I'm considering a mini-ITX build which support dedicated graphic card. In fact I don't need a graphic card right now, but just in case I will need one in the future, so mini-ITX seems to be a good choice.I want a small and solid chassis at reasonable price, any recommends?
What are the smallest mini-ITX cases available?
case
null
_unix.351295
I'm not sure exactly when this started but it's been only a few days max, when I try to run the android tool I'm getting a:Exception in thread main java.lang.UnsatisfiedLinkError: no swt-gtk-3550 or swt-gtk in swt.library.path, java.library.path or the jar file at org.eclipse.swt.internal.Library.loadLibrary(Unknown Source) at org.eclipse.swt.internal.Library.loadLibrary(Unknown Source) at org.eclipse.swt.internal.C.(Unknown Source) at org.eclipse.swt.internal.Converter.wcsToMbcs(Unknown Source) at org.eclipse.swt.internal.Converter.wcsToMbcs(Unknown Source) at org.eclipse.swt.widgets.Display.(Unknown Source) at com.android.sdkmanager.Main.showSdkManagerWindow(Main.java:403) at com.android.sdkmanager.Main.doAction(Main.java:391) at com.android.sdkmanager.Main.run(Main.java:151) at com.android.sdkmanager.Main.main(Main.java:117)Googling about the exception shows somewhat old results, which I've tried all except one, basically I need to remount my /tmp as noexec, but because I'm running an Arch system and it is somewhat advanced for my experience and I don't want to mess it up. One of the suggested fixes and the one that I just implemented (so I'm not sure if it will continue working) is to specify a temporary dir on the script via the -Djava.io.tmpdir argument. I thought that would do it but since this error is still showing up, another thing I want to do is increase its size.When I went to read fstab documentation, I noticed that Arch's systemctl manages partition mounting automatically and manually editing /etc/fstab is required for specific configuration and I'm still confused of why fstab only shows one entry: # /etc/fstab: static file system information. # <file system> <mount point> <type> <options> <dump> <pass> UUID=someId / ext4 defaults,noatime,discard 0 1 UUID=someOtherId swap swap defaults,noatime,discard 0 0 tmpfs /tmp tmpfs defaults,noatime,mode=1777 0 0and there are 4 tmpfs filesystems on my system: mount | grep tmp dev on /dev type devtmpfs (rw,nosuid,relatime,size=4035472k,nr_inodes=1008868,mode=755) run on /run type tmpfs (rw,nosuid,nodev,relatime,mode=755) tmpfs on /dev/shm type tmpfs (rw,nosuid,nodev) tmpfs on /sys/fs/cgroup type tmpfs (ro,nosuid,nodev,noexec,mode=755) tmpfs on /tmp type tmpfs (rw,noatime) tmpfs on /run/user/1000 type tmpfs (rw,nosuid,nodev,relatime,size=807996k,mode=700,uid=1000,gid=1005)and for what I can see it's not the one my user is assigned to. I tried reading the .conf files suggested on systemd's documentation but I just can't get a deal of how they work.So I guess the question is how do I modify my user-assigned /tmp partition without screwing it up? Or if I need to configure one of the existing three globally so Android Studio and the android tool don't complain about silly, non-existing issues? ThanksEDITI guess increasing the size is not useful since I just noticed it's configured to fully use the 8GB I have. So my intuition tells me that somehow, they are trying to use a different partition than mine, isn't it?
Error no swt-gtk-3550 or swt-gtk in swt.library.path when launching `android`
arch linux;java;android;tmpfs
null
_datascience.16162
Why Gaussian Discriminant Analysis model use joint probability to get maximum likelihood ? But why in some models like linear model, we use posterior probability to get maximum likelihood ? I don't know how to choose the appropriate kind of probability.
Why Gaussian Discriminant Analysis model use joint probability to get maximum likelihood?
machine learning;discriminant analysis
null
_softwareengineering.270868
I'm working on the implementation of a few related algorithms in CUDA, all of which require a primitive that we'll call f(). The related algorithms can't simply call f though, as they require f to have slightly different behavior for each algorithm.f is highly optimized feature though, so I don't want to overload f for each case because if I end up making changes to f then I need to change each overload.f looks something like the following:__device__ void f(const int *R, const int *C, const int n, int *d, int *Q, int *Q2){ for(int i=blockIdx.x; i<n; i+=gridDim.x) { //Cooperatively inspect R and C and place results into d }}It's actually way more complicated as it uses lots of __shfl instructions and whatnot, but that shouldn't be relevant here. The problem is that the related algorithms all need slightly different variations of f but since f is complicated I only want it's code in one location.Here are the requirements of the related algorithms:A: An additional global device variable to keep track of the maximum of a set of dataB: An additional O(n) or O(n^2) array for recording integer data at various stages of fC: Similar to B but recording binary dataD: Requires a stack and an array for recording data at various stages of f (the array is the same as needed in B). Has other requirements too but those are better handled separately.How can I avoid duplicating f and make it flexible for these use cases?
Maximizing reuse out of a function primitive in CUDA
design;c++;code reuse
null
_reverseengineering.16154
I'm trying to understand how ARM add with shift is implemented e.g. sym.imp.__libc_start_main : .plt:0x000082bc 00c68fe2 add ip, pc, 0, 12; after execution ip=0x82c4.plt:0x000082c0 08ca8ce2 add ip, ip, 8, 20; after execution ip=0x102c4.plt:0x000082c4 48fdbce5 ldr pc, [ip, 0xd48]!I wonder about the line.plt:0x000082c0 08ca8ce2 add ip, ip, 8, 20;it will add #0x8000 to the ip register. My question is why #0x8000 ?I'd assume it will be:ip = ip + (8<<20)so 0x800000 but it's more likeip = ip + (8<<(20-8))Why is that? do I always have to substract 8 from the shift ?
ARM add instruction with shift
disassembly;assembly;arm
It's a Circular Shift on a 32-bit system.Circular ShiftIn computer programming, a circular shift (or bitwise rotation) is a shift operator that shifts all bits of its operand. Unlike an arithmetic shift, a circular shift does not preserve a number's sign bit or distinguish a number's exponent from its significand (sometimes referred to as the mantissa). Unlike a logical shift, the vacant bit positions are not filled in with zeros but are filled in with the bits that are shifted out of the sequence.Understanding the codeFirst Line:This is simply translated into add ip, pc because rotate operations on #0 is still 0.So it's actually IP = PC + (0 << 12) = PC + 0Second Line:Let's take apart the opcodes and understand the problematic line:The opcodes should be read like this because of endianness: e28cca08e - always execute this instruction28 - add immediatec - Rd is the ipc - Rn is the ipa 08 - 8 right rotated by 20The things is, that it's not 8<<20 but instead it is 8<<(32-12) because we are on a 32-bit system and it is a Circular Shift.Here's a C code that showing the Circular Shift based on the example from Wikipedia:#include <stdint.h> // for uint32_t, to get 32bit-wide rotates, regardless of the size of int.#include <limits.h> // for CHAR_BITuint32_t rotl32 (uint32_t value, unsigned int count) { const unsigned int mask = (CHAR_BIT*sizeof(value)-1); count &= mask; return (value<<count) | (value>>( (-count) & mask ));}uint32_t rotr32 (uint32_t value, unsigned int count) { const unsigned int mask = (CHAR_BIT*sizeof(value)-1); count &= mask; return (value>>count) | (value<<( (-count) & mask ));}int main(){ printf(Result: 0x%x\n,rotr32(8,20)); return 0;}The code will output: Result: 0x8000
_codereview.87533
I'm building a game with Pygame, a simple turn-based strategy game where on each turn a character can move and/or perform an action. I have a somewhat good structure for the game on the background, and pygame provides the gui for that. Below is the code of the main file. I think the structure of main.py is quite terrible at the moment. The question is then, how do I alter that (including the main loop) to a better one. Also, what can I do to improve the performance?Here's everything else if you need to take a look at the background logic.def map_to_screen(x,y, offset_x=0, offset_y=0): screen_x = (x - y) * (tile_w / 2) + offset_x screen_y = (x + y) * (tile_h / 2) + offset_y return screen_x, screen_ydef screen_to_map(x,y, offset_x=0, offset_y=0): x -= ( offset_x + tile_w / 2 ) y -= offset_y x = x / 2 map_x = (y + x)/(tile_h) map_y = (y - x)/(tile_h) if map_x < 0: map_x -= 1 if map_y < 0: map_y -= 1 return int(map_x), int(map_y)def square_clicked(screen_x, screen_y): x = screen_x y = screen_y map_x = ( x / (tile_w / 2) + y / (tile_h / 2) ) / 2 map_y = ( y / (tile_h / 2) - (y / (tile_w / 2)) ) / 2 return (map_x, map_y)def load_sprites(): sprites = {} # For each squaretype, load sprites that are not loaded for squaretype in m.squaretypes: if m.squaretypes[squaretype].sprite not in sprites: sprites[m.squaretypes[squaretype].sprite] = pygame.image.load(m.squaretypes[squaretype].sprite).convert_alpha() print(Successfully loaded sprite '{:}'.format(m.squaretypes[squaretype].sprite)) # For each object type, load sprites that are not loaded for object_type in m.object_types: if m.object_types[object_type].sprite not in sprites: sprites[m.object_types[object_type].sprite] = pygame.image.load(m.object_types[object_type].sprite).convert_alpha() print(Successfully loaded sprite '{:}'.format(m.object_types[object_type].sprite)) # For each character, load all sprites that are not already loaded for character in m.characters: for sprite in character.stand_sprites: if character.stand_sprites[sprite] not in sprites: sprites[character.stand_sprites[sprite]] = pygame.image.load(character.stand_sprites[sprite]).convert_alpha() print(Successfully loaded sprite '{:}'.format(character.stand_sprites[sprite])) for sprite_list in character.walk_sprites: for sprite in character.walk_sprites[sprite_list]: if sprite not in sprites: sprites[sprite] = pygame.image.load(sprite).convert_alpha() print(Successfully loaded sprite '{:}'.format(sprite)) return spritesdef render_squares(surface): surface.fill((0,0,0)) for x in range(m.width): for y in range(m.height): square = m.get_square_at(Coordinates(x,y)) screen_x, screen_y = map_to_screen(x,y) surface.blit(sprites[square.squaretype.sprite], (screen_x + map_offset_x, screen_y))def render_range(surface): for sq in within_range: sq_mx, sq_my = sq.location.x, sq.location.y sq_sx, sq_sy = map_to_screen(sq_mx, sq_my, map_offset_x, map_offset_y) if selected_action: if selected_action.type == Action.HEAL: surface.blit( heal_target_img, (sq_sx, sq_sy) ) else: surface.blit( action_target_img, (sq_sx, sq_sy) ) else: surface.blit( selected_img, (sq_sx, sq_sy) )def render_characters_and_objects(surface, walking=None, scr_loc=None, sprite_counter=None): # collect dirty rects dirty = [] # For each square on the map, check if there's a character and if yes, draw it. Do this in the order of squares to maintain proper drawing order. for x in range(m.width): for y in range(m.height): square = m.get_square_at(Coordinates(x,y)) character = square.character # Translate coordinates screen_x, screen_y = map_to_screen(x,y, map_offset_x, map_offset_y) if square.character and not square.character.dead: if character.facing == direction.UP: facing = up elif character.facing == direction.DOWN: facing = down elif character.facing == direction.LEFT: facing = left elif character.facing == direction.RIGHT: facing = right if character == walking: # Draw sprite based on the direction facing if character.walk_sprites: dirty.append(surface.blit(sprites[character.walk_sprites[facing][sprite_counter]], (scr_loc[0] + character_offset_x, scr_loc[1] + character_offset_y))) else: dirty.append(surface.blit(sprites[character.stand_sprites[facing]], (scr_loc[0] + character_offset_x, scr_loc[1] + character_offset_y))) else: dirty.append( surface.blit(sprites[character.stand_sprites[facing]], (screen_x + character_offset_x, screen_y + character_offset_y)) ) #dirty.append(pygame.Rect(48,48, screen_x+character_offset_x,screen_y+character_offset_y)) elif square.object: dirty.append( surface.blit(sprites[square.object.type.sprite], (screen_x + square.object.type.offset_x, screen_y + square.object.type.offset_y)) ) return dirtydef render_info_text(surface, text_to_display): text = font.render(text_to_display, 1, (10, 10, 10)) textpos = text.get_rect() textpos.move_ip(0,screen_h - 16) textpos.centerx = screen.get_rect().centerx bgpos = pygame.Rect(0,0,(screen_w - 128*2 - 14), 28) bgpos.centerx = textpos.centerx surface.blit(bottom_bar.subsurface(bgpos), (bgpos.x, screen_h-28)) surface.blit(text, textpos) return textposdef render_char_info(surface, wanted=None): if wanted: if not isinstance(wanted, list): wanted = [wanted] else: wanted = m.characters count = 0 ai_count = 1 dirty = [] for character in m.characters: if character in wanted: if character.has_turn(): char_info_surface = char_info_turn.copy() elif character.dead: char_info_surface = char_info_dead.copy() else: char_info_surface = char_info.copy() head_image = pygame.image.load(character.stand_sprites[right]).convert_alpha() head_image.set_clip(pygame.Rect(0,0, 20,20)) char_info_surface.blit(head_image, (5,5), (8,5,24,24)) text_line_1 = str(character.health) + / text_line_2 = str(character.max_health) t1 = font.render(text_line_1, 1, (10,10,10)) t2 = font.render(text_line_2, 1, (10,10,10)) t1_pos = t1.get_rect() t1_pos.move_ip(0,36) t1_pos.centerx = char_info_surface.get_rect().centerx char_info_surface.blit(t1, t1_pos) t2_pos = t2.get_rect() t2_pos.move_ip(0,46) t2_pos.centerx = char_info_surface.get_rect().centerx char_info_surface.blit(t2, t2_pos) if character.ai: surface.blit(char_info_surface, (screen_w - ai_count * 34 - 5, 7)) dirty.append(pygame.Rect(32,58, screen_w - ai_count * 34 - 5,7)) else: surface.blit(char_info_surface, (7 + count* 34, 7)) dirty.append(pygame.Rect(32,58, 7+count*34,7)) if character.ai: ai_count += 1 else: count += 1 return dirtydef render_bottom_bar(surface): #blit background bar bar = pygame.image.load(graphics/bottom_bar.gif).convert() for i in range(surface.get_width() // 4): surface.blit(bar, (i*4, 0))def render_end_turn_button(surface): if end_turn_button.rect.collidepoint(pygame.mouse.get_pos()): if pygame.mouse.get_pressed()[0]: end_turn_button.pushed = True else: end_turn_button.hovered = True else: end_turn_button.hovered = False end_turn_button.pushed = False end_turn_button.render_to(surface) #return the button for dirty rects and mouse recognition return end_turn_button.rectdef render_action_menu(surface): # blit menu bg actions_menu = pygame.image.load(graphics/actions_menu.gif).convert_alpha() surface.blit(actions_menu, (7, screen_h - 103)) if selected_character: use_buttons = [] count = 0 for action in selected_character.actions: use_button = ui.Button(ui.action_bg, ui.action_bg_hover, ui.action_bg_push, (20, screen_h - 94 + count * 26)) use_buttons.append(use_button) if use_button.rect.collidepoint(pygame.mouse.get_pos()): if pygame.mouse.get_pressed()[0]: use_button.pushed = True else: use_button.hovered = True else: use_button.hovered = False use_button.pushed = False use_button.render_to(surface) text = action.description + ( + str(action.strength) + ) text = font.render(text, False, (10,10,10)) text_pos = text.get_rect() text_pos.move_ip(65, screen_h - 84 + count * 26) surface.blit(text, text_pos) count += 1 return use_buttons return []def render_effect_text(surface, count, text_surface): if text_surface: scr_loc = map_to_screen(effect_text_loc.x, effect_text_loc.y) x = scr_loc[0] + 32 - text_surface.get_width()/2 + map_offset_x y = scr_loc[1] - 40 - count*1 + map_offset_y location = (x, y) if count > 10: opacity = 255 - 12 * count else: opacity = 255 #surface.blit(map_surface, (map_offset_x + map_fix_x, map_offset_y)) blit_alpha(surface, text_surface, location, opacity) count += 1 if count > 20: count = 0 return count, None return count, text_surfacedef get_effect_text(action): if action.type == Action.HEAL: text = + + str(action.strength) color = (10, 200, 10) else: text = - + str(action.strength) color = (200, 10, 10) text_surface = med_font.render(text, False, color) return text_surfacedef blit_alpha(target, source, location, opacity): '''Blits opaque element while keeping per pixel alpha in other parts of the surface.''' x = location[0] y = location[1] temp = pygame.Surface((source.get_width(), source.get_height())).convert_alpha() temp.blit(target, (-x, -y)) temp.blit(source, (0, 0)) temp.set_alpha(opacity) target.blit(temp, location)def blit_map(surface): return surface.blit(map_surface, (map_offset_x + map_fix_x, map_offset_y))#Game startspygame.init()clock = pygame.time.Clock()fps = 40#read config from filesr = ConfigReader()f = open('map_config', 'r')map_config = r.read_config(f)f.close()f = open('character_config', 'r')character_config = r.read_config(f)f.close()m = r.build_from_config(map_config, character_config)ai = Ai(m)#set window sizescreen_w = 1280screen_h = 768screen = pygame.display.set_mode((screen_w, screen_h))#initiate fontsfont = pygame.font.Font(fonts/coders_crux.ttf, 14)med_font = pygame.font.Font(fonts/coders_crux.ttf, 16)#load spritesselected_img = pygame.image.load('graphics/selected.gif').convert_alpha()action_target_img = pygame.image.load('graphics/action_selected.gif').convert_alpha()heal_target_img = pygame.image.load('graphics/heal_selected.gif').convert_alpha()char_info = pygame.image.load(graphics/char_info.gif).convert_alpha()char_info_turn = pygame.image.load(graphics/char_info_has_turn.gif).convert_alpha()char_info_dead = pygame.image.load(graphics/char_info_dead.gif).convert_alpha()sprites = load_sprites()#prepare the map and rendering offsetstile_w = 64tile_h = 32map_w = (m.width + m.height) * tile_w / 2map_h = (m.width + m.height) * tile_h / 2 + 8map_offset_x = map_w / 2 - tile_w / 2map_offset_y = 0character_offset_x = 13character_offset_y = -30#create a separate surface for the map and render squares on itmap_surface = pygame.Surface((map_w, map_h))render_squares(map_surface)bottom_menu_rect = pygame.Rect(0, screen_h-128, screen_w, 128)bottom_bar = pygame.Surface((screen_w, 28))render_bottom_bar(bottom_bar)end_turn_button = ui.Button(ui.end_turn_bg, ui.end_turn_bg_hover, ui.end_turn_bg_push, (screen_w - 135, screen_h - 71))#prepare pause menuoptions = [ ui.MenuOption(NEW GAME), ui.MenuOption(QUIT) ][ option.set_rect(screen, options) for option in options ]#prepare the game loop control variablesdone = Falseselected_character = m.turn_controller.current_characterselected_action = Nonemouse_pos = Nonewithin_range = selected_character.within_range(selected_character.range) text_to_display = Nonesaved_text = Nonedid_update_already = Falsedid_move_already = Falseeffect_fade_count = 0effect_text = Nonedirty_rects = []refresh_map = Falsewalk = Falseaction = Falsepath_to_move = Falsesquare_clicked = None#Initial renderscreen.fill((0,0,0))#map, the map_fix_x fixes horizontal positioning, and the offsets center the map on the screenmap_fix_x = tile_w / 2 - map_surface.get_rect().w/2map_offset_x += screen_w / 2 - map_w / 2map_offset_y += screen_h / 2 - map_h / 2in_menu = Truepaused = Falseplr_won = False ai_won = False#milliseconds from last framenew_time, old_time = None, None #set a wait timer to leave time between AI actionsai_delay = 1000wait_ms = False#start main loopwhile not done: clock.tick(fps) dirty_rects = [] did_update_already = False #recognize winner plr_characters_alive = 0 ai_characters_alive = 0 for c in m.characters: if not c.ai and not c.dead: plr_characters_alive += 1 elif c.ai and not c.dead: ai_characters_alive += 1 if plr_characters_alive == 0: ai_won = True in_menu = True elif ai_characters_alive == 0: plr_won = True in_menu = True #--------------- # Menu loop while in_menu: #draw menu and options screen.fill((0, 0, 0)) if plr_won or ai_won: if plr_won: winner = ui.super_large_font.render(You won!, True, (255,255,255)) else: winner = ui.super_large_font.render(You lost!, True, (255,255,255)) winner_rect = winner.get_rect() winner_rect.centerx = screen.get_rect().centerx winner_rect.y = 20 screen.blit(winner, winner_rect) #prevent action effect text from showing after pressing new game effect_text = None if paused: resume = ui.large_font.render(Press Esc to resume game., True, (255,255,255)) resume_rect = resume.get_rect() resume_rect.centerx = screen.get_rect().centerx resume_rect.y = 20 screen.blit(resume, resume_rect) for option in options: if option.rect.collidepoint(pygame.mouse.get_pos()): option.hover = True else: option.hover = False option.draw() for event in pygame.event.get(): if event.type == pygame.QUIT: in_menu = False done = True if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE and paused and not (plr_won or ai_won): paused = False in_menu = False refresh_map = True if event.type == pygame.MOUSEBUTTONUP: for option in options: if option.text == QUIT and option.rect.collidepoint(pygame.mouse.get_pos()): in_menu = False done = True if option.text == NEW GAME and option.rect.collidepoint(pygame.mouse.get_pos()): #read config from files r = ConfigReader() f = open('map_config', 'r') map_config = r.read_config(f) f.close() f = open('character_config', 'r') character_config = r.read_config(f) f.close() m = r.build_from_config(map_config, character_config) ai.m = m m.turn_controller.reset() selected_character = m.turn_controller.current_character selected_action = None within_range = selected_character.within_range(selected_character.range) text_to_display = None mouse_pos = None in_menu = False refresh_map = True if new_time: old_time = new_time new_time = pygame.time.get_ticks() if new_time and old_time: pygame.display.set_caption(fps: + str(int(clock.get_fps())) + ms: + str(new_time-old_time)) pygame.display.update() #------------------ # The actual game if refresh_map: screen.fill((0,0,0)) # map, range and characters dirty_rects.append(blit_map(screen).inflate(20,20)) render_range(screen) render_characters_and_objects(screen) # menu elements screen.blit(bottom_bar, (0, screen_h-28)) if saved_text: text_to_display = saved_text render_end_turn_button(screen) use_buttons = render_action_menu(screen) render_char_info(screen) refresh_map = False # move the map with arrow keys keys = pygame.key.get_pressed() if not (map_offset_x + map_fix_x) < (-map_w + tile_w / 2 - (screen_w - map_w)): if keys[pygame.K_LEFT]: map_offset_x -= 10 refresh_map = True if not (map_offset_x + map_fix_x) > (map_w - tile_w / 2 + (screen_w - map_w)): if keys[pygame.K_RIGHT]: map_offset_x += 10 refresh_map = True if not (map_offset_y) < (-map_h + tile_h / 2): if keys[pygame.K_UP]: map_offset_y -= 10 refresh_map = True if not (map_offset_y) > (map_h - tile_h / 2 + (screen_h - map_h)): if keys[pygame.K_DOWN]: map_offset_y += 10 refresh_map = True #Handle mouse and keyboard events for event in pygame.event.get(): # Quit if window is closed if event.type == pygame.QUIT: done = True # Use Esc to go into pause menu if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: in_menu = True paused = True continue # If not in menu else: # get mouse position and convert to cartesian coordinates mouse_pos = pygame.mouse.get_pos() mx = mouse_pos[0] my = mouse_pos[1] # Update buttons if mouse moves in or out # End button if ( (end_turn_button.hovered and not end_turn_button.rect.collidepoint((mx,my))) or (not end_turn_button.hovered and end_turn_button.rect.collidepoint((mx,my))) ): dirty_rects.append(render_end_turn_button(screen)) else: # Action buttons for button in use_buttons: if (button.hovered and not button.rect.collidepoint((mx,my))) or (not button.hovered and button.rect.collidepoint((mx,my))): use_buttons = render_action_menu(screen) for button in use_buttons: dirty_rects.append(button.rect) # Handle mouse clicks if event.type == pygame.MOUSEBUTTONUP: # Reset button states end_turn_button.pushed = False for use_btn in use_buttons: use_btn.pushed = False # Recognize end turn button if end_turn_button.rect.collidepoint((mx,my)): # get current and next character old_character = selected_character text_to_display = m.turn_controller.current_character.end_turn() selected_character = m.turn_controller.current_character # update range with new character if not selected_character.ai: within_range = selected_character.within_range(selected_character.range) else: within_range = [] selected_action = None refresh_map = True wait_ms = ai_delay continue # recognize action use buttons else: for use_btn in use_buttons: if use_btn.rect.collidepoint((mx,my)): selected_action = selected_character.actions[use_buttons.index(use_btn)] within_range = selected_character.within_range(selected_action.range, for_action = True) selected_character.has_moved = True refresh_map = True break # Convert clicked coordinates to game map coordinates # map mouse x = mmx, map mouse y = mmy, i.e. which square on the map was clicked mouse_pos_map = screen_to_map(mx,my, map_offset_x, map_offset_y) mmx = mouse_pos_map[0] mmy = mouse_pos_map[1] # Handle game events resulting from clicks: set movement or action target square # if there is a square at the selected coordinates, i.e. if the click was inside the map if m.get_square_at(Coordinates(mmx, mmy)): square_clicked = m.get_square_at(Coordinates(mmx, mmy)) # if a square outside range was clicked if not square_clicked in within_range: text_to_display = Not within range. continue # if square inside range and the character has not moved, set walk target elif selected_character.has_turn() and not selected_character.has_moved: target_map_loc = Coordinates(mmx, mmy) walk = True # if an action was selected and the square clicked is in the action range elif selected_action and square_clicked in within_range: target_map_loc = Coordinates(mmx, mmy) action = True #if AI's turn, get AI movement or action # get movement if the AI character has not moved if selected_character.ai and not selected_character.has_moved and not wait_ms: target_map_loc = ai.get_next_move() # If gets a target, move, otherwise proceed to action if target_map_loc: print(str(selected_character) + moving to + str(target_map_loc)) walk = True else: selected_character.has_moved = True # get action if the AI character has moved elif selected_character.ai and selected_character.has_moved and not wait_ms: selected_action, target_map_loc = ai.get_action() # If gets a target, perform the action, else end turn if target_map_loc: action = True print(str(selected_character) + chose action + str(selected_action) + to use on location + str(target_map_loc)) else: #update character infos for current character, action target character, and the next turn character old_character = selected_character selected_character.end_turn() selected_character = m.turn_controller.current_character dirty_rects += render_char_info(screen, [selected_character, old_character]) #clear range within_range = selected_character.within_range(selected_character.range) refresh_map = True continue #Walk, if a walk target was set if walk: # remove range blit_map(screen) # set target map coordinates and get the shortest path there path = selected_character.get_shortest_path(target_map_loc) # walk the shortest path for step in path: # get the current map and screen locations current_map_loc = selected_character.location current_scr_loc = map_to_screen(selected_character.location.x, selected_character.location.y, map_offset_x, map_offset_y) # set the target screen location for the current step step_scr_target = map_to_screen(step.x, step.y, map_offset_x, map_offset_y) # determine if the character has walk sprites and prepare the animation walk_animation = False if len(selected_character.walk_sprites) > 0: nr_of_sprites = len(selected_character.walk_sprites) half_speed = True frame_counter = 0 sprite_counter = 0 walk_animation = True # move the character according to the shortest path step if step.x == current_map_loc.x and step.y < current_map_loc.y: selected_character.facing = direction.UP facing = up elif step.x == current_map_loc.x and step.y > current_map_loc.y: selected_character.facing = direction.DOWN facing = down elif step.x < current_map_loc.x and step.y == current_map_loc.y: selected_character.facing = direction.LEFT facing = left elif step.x > current_map_loc.x and step.y == current_map_loc.y: selected_character.facing = direction.RIGHT facing = right dirty_rects_moving = [] #---------------- # Walk loop # while the character has not reached the target while not current_scr_loc == step_scr_target: clock.tick(0) map_rect = blit_map(screen) pygame.event.pump() # if walk sprites available if walk_animation: # if animation is set to half speed, may look too fast if full speed if half_speed and frame_counter % 2 == 0: if sprite_counter < nr_of_sprites - 1: sprite_counter += 1 else: sprite_counter = 0 frame_counter += 1 dirty_rects_moving += render_characters_and_objects(screen, selected_character, current_scr_loc, sprite_counter) # if no walk sprites or if in target else: dirty_rects_moving += render_characters_and_objects(screen, selected_character, current_scr_loc) # move the character on screen according to the shortest path step if facing == up: current_scr_loc = (current_scr_loc[0] + 2, current_scr_loc[1] - 1) elif facing == down: current_scr_loc = (current_scr_loc[0] - 2, current_scr_loc[1] + 1) elif facing == left: current_scr_loc = (current_scr_loc[0] - 2, current_scr_loc[1] - 1) elif facing == right: current_scr_loc = (current_scr_loc[0] + 2, current_scr_loc[1] + 1) # if map goes under the menus if map_rect.colliderect(bottom_menu_rect): screen.blit(bottom_bar, (0, screen_h-28)) render_end_turn_button(screen) use_buttons = render_action_menu(screen) #display fps and milliseconds between frames if new_time: old_time = new_time new_time = pygame.time.get_ticks() if old_time and new_time: pygame.display.set_caption(fps: + str(int(clock.get_fps())) + ms: + str(new_time-old_time)) #print([str(r) for r in dirty_rects_moving]) pygame.display.update(dirty_rects_moving) #did_update_already = True dirty_rects_moving = [] # walk loop end #---------------- #move in the background logic selected_character.move_to_coordinates(step) # if all steps were successful else: blit_map(screen) dirty_rects += render_characters_and_objects(screen) pygame.display.update(dirty_rects) text_to_display = Choose action. refresh_map = True path_to_move = False walk = False if selected_character.ai: wait_ms = ai_delay #did_update_already = True # don't display range after the character has moved if selected_character.has_moved and not selected_action: within_range = [] #If an action target was set if action: square = m.get_square_at(target_map_loc) # set the correct facing direction for the attacking character if target_map_loc.x == selected_character.location.x and target_map_loc.y < selected_character.location.y: selected_character.facing = direction.UP elif target_map_loc.x == selected_character.location.x and target_map_loc.y > selected_character.location.y: selected_character.facing = direction.DOWN elif target_map_loc.x < selected_character.location.x and target_map_loc.y == selected_character.location.y: selected_character.facing = direction.LEFT elif target_map_loc.x > selected_character.location.x and target_map_loc.y == selected_character.location.y: selected_character.facing = direction.RIGHT # perform action text_to_display = selected_action.perform(target_map_loc) # display red or green text with action strength above the action target effect_text_loc = target_map_loc if square.has_character(): effect_text = get_effect_text(selected_action) # reset selected action selected_action = None action = False #update character infos for current character, action target character, and the next turn character old_character = selected_character selected_character.end_turn() selected_character = m.turn_controller.current_character dirty_rects += render_char_info(screen,[square.character, selected_character, old_character]) #clear range within_range = selected_character.within_range(selected_character.range) refresh_map = True if old_character.ai: wait_ms = ai_delay #continue if effect_text: effect_fade_count, effect_text = render_effect_text(screen, effect_fade_count, effect_text) # if was not reset if effect_text: dirty_rects.append(effect_text.get_rect().inflate(0,2)) refresh_map = True # skip render if the screen was already updated in an inner loop if did_update_already: continue # if buttons need to be refreshed if end_turn_button.dirty: dirty_rects.append(render_end_turn_button(screen)) end_turn_button.dirty = False for button in use_buttons: if button.dirty: render_action_menu(screen) dirty_rects.append(button.rect) button.dirty = False break if text_to_display: text_rect = render_info_text(screen, text_to_display) dirty_rects.append(text_rect) saved_text = text_to_display text_to_display = None # show fps and milliseconds if new_time: old_time = new_time new_time = pygame.time.get_ticks() if new_time and old_time: pygame.display.set_caption(fps: + str(int(clock.get_fps())) + ms: + str(new_time-old_time)) #print([str(r) for r in dirty_rects]) pygame.display.update(dirty_rects) if wait_ms > 0: wait_ms -= (new_time - old_time) elif wait_ms <= 0: wait_ms = Falsepygame.quit()sys.exit()
Discoknights game structure
python;performance;pygame;adventure game
null
_softwareengineering.129505
Going by the general principle of data abstraction, I normally abstract data in a serialized format(JSON) and pass it as a parameter to the Business Logic(BL) modules such that the BL module always see a consistent format of the data irrespective of the underlying data storage layer. Even if I use a ORM, I use the serialized format of that ORM. I feel I have the following advantages.By serializing data, there would be better control over data and parametersAny developer can write BL without thinking too much about the underlying data storageWrappers can be written for new databases (There are a lot of ready-made wrappers to convert data into JSON)Testing could be done ruthlessly and without a database (since the data format is serialized)Functionally easier to understand and better OLAP, OLTP integrationI also notice the following drawbacksA new layer to be added between the database and the BL module (most ORM's nowadays come with a predetermined JSON format)Extra function calls slow down the application (but I think this trade-off is OK when compared to better testing and easy maintenance)Increased level of abstractions may confuse the developerI make the above observations mostly in the context of business applicationsTo follow this discussion, lets have an example so that things could be discussed in its context.Assume a product database having the columns: Product,Rate,Taxes and we need to create a invoiceCode without database abstractionGET rate,taxes for product X from databasemultiply qty with rate and add taxesdisplay invoiceCode with database abstraction GET rate,taxes for product X from database Convert it into JSON call create_invoice function //This does all the calculations display invoiceIn the second example, I would pass arguments in the form (Product=X, Qty=5, Rate=5, Taxes=0.05). If taxes are to be split into more that one category (State Tax=0.03, Central Tax=0.02) or a discount factor to be added I would just increase the number of parameters in the BL functions such that the database fields, the JSON keys and the function parameters match (this is done automatically during serialization and most ORM's do it). This makes it easy, in my approach, to extend functions and also make modules independent of data since the modules always know the data they can receive and even if they receive a new parameter, they can adapt it provide the underlying code is intelligent.My general questions areIs this a good pattern and what's it called (Data abstraction comes to my mind)?Pros/Cons of this pattern(apart from those mentioned above) in the context of business application, apps for embedded devices, big dataIs there a difference between this pattern and ORM (I believe so since ORM is mostly a class wrapper to get data from a database while this pattern is more oriented towards data structure)If this is good, can this be easily understood by a new developer?
Data Serialization to process business logic
design patterns;data structures;abstraction
A lot depends on your intention. Data serialization in this manner just to pass on to the business logic of a single application, seems wasteful, when you should be passing a native object from the ORM to the object encapsulating BL which will modify state and return the object to the ORM for persistence.On the other hand, if you have multiple, distributed applications that handle different aspects of of the domain, then wrapping your DB in an API to provide serialized (JSON or XML) data is a good idea. For instance: I have to deal with a rather insane vendor-supplied legacy database in which a major constraint is inability to modify the DB schema other than adding the occasional view. I have this DB (as well as a couple of our other 'enterprise' data stores) wrapped in a REST API. Most of our user-facing applications, as well as daemons that monitor the DB for certain events, communicate with the API. In this way I can have the following workflow:OR/M classes each wrap a single table in the DB. One object == one record.Decorator classes handle presentation, including composition of more complex objects from simple model objects.Controller classes respond to requests with a JSON representation of the object appropriate to the client application.Clent processes data, POSTs or PUTs JSON object back to the APIController requests to save object, which is decomposed back to model objects and persisted by the O/RM.This adds significant complexity.If you have to deal with heterogeneous data stores, distributed applications, etc., this is an excellent solution. But unless you have those requirements, the rule of thumb is You Ain't Gonna Need It.
_codereview.117976
Can this query be improved? Is there a way to eliminate the duplicate function call?-- a Special Group has many Items which have many Bookingscreate function f_BookingsForSpecialGroup(@specialGroupId varchar(99))returns table as return select * from v_Booking where ITEM_CODE in (select ITEM_CODE from v_Item i where i.SPECIAL_GROUP_ID = @specialGroupId);gocreate view v_SpecialGroup asselect (NON_BAD_BOOKINGS - PAID_BOOKINGS) as PENDING_BOOKINGS, * from(select (select count(*) from f_BookingsForSpecialGroup(g.SPECIAL_GROUP_ID) where IS_BAD=0) as NON_BAD_BOOKINGS, (select count(*) from f_BookingsForSpecialGroup(g.SPECIAL_GROUP_ID) where IS_PAID=1) as PAID_BOOKINGS, *from SPECIAL_GROUP g) ggoThe view v_SpecialGroup is never queried directly by the application; it is used to build other views which select individual columns as needed. (You can think of v_SpecialGroup as a base view which exists solely to augment the SPECIAL_GROUP table. I have profiled this strategy and it seems that if you don't select the more expensive columns you don't pay for them, but I could be wrong of course...)
Counting pending bookings using a subselect
sql;sql server
It looks to me like the view returns all of the columns from a SPECIAL_GROUP table, along with an additional column counting bookings that are neither is_bad nor is_paid.If so, you could use a common table expression* to simplify the logic a bit:create view v_SpecialGroup aswith bookings_by_group as ( select i.SPECIAL_GROUP_ID, count(case when is_bad = 0 then 1 end) as NON_BAD_BOOKINGS, count(case when is_paid = 1 then 1 end) as PAID_BOOKINGS from v_booking b join v_item i on b.ITEM_CODE = i.ITEM_CODE group by i.SPECIAL_GROUP_ID)select NON_BAD_BOOKINGS - PAID_BOOKINGS as PENDING_BOOKINGS, g.*from bookings_by_group b join SPECIAL_GROUP g on b.SPECIAL_GROUP_ID = g.SPECIAL_GROUP_IDps. It might also be possible to condense the logic further:count(case when is_bad = 0 and is_paid != 1 then 1 end) as PENDING_BOOKINGSit would depend on whether you had any bookings that were both is_bad and is_paid*SQL Server must be >= 2008R2
_softwareengineering.123342
When should you prefer inheritance patterns over mixins in dynamic languages?By mixins, I mean actual proper mixing in, as in inserting functions and data members into an object in runtime.When would you use, for example, prototypal inheritance instead of mixins? To illustrate more clearly what I mean by mixin, some pseudocode:asCircle(obj) { obj.radius = 0 obj.area = function() { return this.radius * this.radius * 3.14 }myObject = {}asCircle(myObject)myObject.area() // -> 0
Inheritance vs mixins in dynamic languages?
javascript;inheritance;mixins
Prototypical inheritance is simple. It has a single advantage over mixins.That is that it's a live link. if you change the prototype everything that inherits it is changed.Example using pdvar Circle = { constructor: function _constructor() { this.radius = 0; return this; }, area: function _area() { return this.radius * this.radius * Circle.PI }, PI: 3.14};var mixedIn = pd.extend({}, Circle).constructor();var inherited = pd.make(Circle, {}).constructor();Circle.perimeter = perimeter;inherited.perimeter(); // winsmixedIn.perimeter(); // failsfunction perimeter() { return 2 * this.radius;}So basically, if you want changes to the interface Circle to reflect at run-time to all objects that use it's functionality, then inherit from it.If you do not want changes to reflect then mix it in.Note that mixins have more purpose than that as well. Mixins are your mechanism for multiple inheritance.If you want an object to implement multiple interfaces then you will have to mix some in. The one you use for prototypical inheritance is the one you want changes to reflect for at run-time, the others will be mixed in.
_cs.33990
I found the following problem that I am trying to answer:Consider the three color problem where V, vertex set of a bipartite graph. can be partitioned into three subsets such that there is no edge between verticies of the same subset. Show that this problem is in NP by describing:A polynomial time algorithm for verifying a given graph coloring. [Hint:Use graph traversal].A nondeterministic polynomial time algorithm for graph coloring.For 1) I attempted to solve this problem using search algorithm like depth-first search/breadth first search. At each vertex, I would check to see if any of adjacent vertices have different color from the current vertex. If not, then graph is not colored correctly. This is worst case O(|e|), linear time. Is this correct ? How can I answer this question ? And how would I do part 2)?
Algorithms for verifying and solving three-coloring
algorithms;complexity theory;graphs;np
null
_unix.213781
I'm trying to configure devilspie so that on detection of opening a certain directory it runs a script to mount that directory over a network.I don't think the script itself is too important but just in case I'll display its code here:#!/bin/bashldir=/home/LinPC/Desktop/Picturesrdir=//WinPC/My Picturesif [ !$(ls -A $ldir) ] ; then sudo mount.cifs $rdir $ldir -o user=someguyfiThe script works when ran from a shell.I configure devilspie using gdevilspie interface (which may be a part of the problem?). I know the conditions are being met as I see a window flash briefly but the shell instantly closes. I use the following line for the 'spawn_sync' action:lxterminal -e sudo bash ~/mount_music.shTyping the above into a shell also spawns the shell and runs the script successfully (prompting me for input). Triggered by devilspie it does not prompt me, it opens and closes before I get to see the output.(On a side note, entering into gdevilspie spawn_sync action:lxterminal -command=sudo bash ~/mount_music.shthen closing the dialog and reopening it, causes everything after the equals symbol to have been wiped out; a bug in gdevilspie?)
-devilspie doesn't play nice with spawning new terminals
bash;scripting;terminal;devilspie;lxterminal
null
_unix.50684
Reading from /proc/PID/stat a lot of information can be processed. I would like to see how many percentages has been used of CPU power by this process. There are a lot of variable around here (utime, stime, cutime, cstime, gtime, cgtime) but they are in jiffies. The problem with this that jiffy depends on speed of the current CPU. However IPS (Instructions Per Second) depends on inctructions set, and which program do we run but maybe this is more accurete.I would like to use this information in embedded systems where I could pick a CPU that just satisfies the features. In this way I don't have to spend a lot for a largly oversized system.Here is the contents of the stat file (as of 2.6.30-rc7): Field Content pid process id tcomm filename of the executable state state (R is running, S is sleeping, D is sleeping in an uninterruptible wait, Z is zombie, T is traced or stopped) ppid process id of the parent process pgrp pgrp of the process sid session id tty_nr tty the process uses tty_pgrp pgrp of the tty flags task flags min_flt number of minor faults cmin_flt number of minor faults with child's maj_flt number of major faults cmaj_flt number of major faults with child's utime user mode jiffies stime kernel mode jiffies cutime user mode jiffies with child's cstime kernel mode jiffies with child's priority priority level nice nice level num_threads number of threads it_real_value (obsolete, always 0) start_time time the process started after system boot vsize virtual memory size rss resident set memory size rsslim current limit in bytes on the rss start_code address above which program text can run end_code address below which program text can run start_stack address of the start of the stack esp current value of ESP eip current value of EIP pending bitmap of pending signals blocked bitmap of blocked signals sigign bitmap of ignored signals sigcatch bitmap of catched signals wchan address where process went to sleep 0 (place holder) 0 (place holder) exit_signal signal to send to parent thread on exit task_cpu which CPU the task is scheduled on rt_priority realtime priority policy scheduling policy (man sched_setscheduler) blkio_ticks time spent waiting for block IO gtime guest time of the task in jiffies cgtime guest time of the task children in jiffies
What is the connection between jiffies and IPS? How to convert jiffies to IPS?
linux;embedded;proc;mips
The jiffy does not depend on the CPU speed directly. It is a time period that is used to count different time intervals in the kernel. The length of the jiffy is selected at kernel compile time. More about this: man 7 timeOne of fundamental uses of jiffies is a process scheduling. One jiffy is a period of time the scheduler will allow a process to run without an attempt to reschedule and swap the process out to let another process to run.For slow processors it is fine to have 100 jiffies per second. But kernels for modern processors usually configured for much more jiffies per second.
_codereview.70153
I think there is more that is needed here. Can someone please comment on it?What I need is to add some common functions to check if an element exists.// Common functions$(document).ready(function() { /* Function for creating different styling checkbox, radio input, and select */ // Create pretty checkboxes and inputs if ($('.iCheck').length){ $('.iCheck').iCheck({ checkboxClass: 'icheckbox_minimal-blue', radioClass: 'iradio_minimal-blue', increaseArea: '20%' // optional }); } // Create pretty selects and multiselect if(!$(html).hasClass(ie8)){ if ($('select').length){ $('select').attr('data-width', '100%').selectpicker(); } }; /* Preloader */ var targetPreloader = $('[data-overlay-text]'); targetPreloader.click(function() { var text = $(this).attr(data-overlay-text); $('.preloader-text').text(text); $('.preloader-window').show().fadeIn(); }); /* Fix for showing SVG */ svgeezy.init('nothing', 'png'); /* Form validation using Jquery validate */ $('form').validate({ highlight: function(element) { $(element).closest('.form-group').addClass('has-error'); }, unhighlight: function(element) { $(element).closest('.form-group').removeClass('has-error'); }, errorElement: 'span', errorClass: 'help-block', errorPlacement: function(error, element) { if(element.parent('.input-group').length) { error.insertAfter(element.parent()); } else { error.insertAfter(element); } } });});
Common function to check if an element exists
javascript;jquery
null
_vi.2677
Is there a way to copy the error message that YCM shows at the bottom of vim? For example in the above image, it says: unused parameter 'sortFunction'I had an idea of using howdoi [paste] in another terminal and get a solution easily :)
How do I copy the error message I get from YCM
cut copy paste;plugin you complete me
null
_softwareengineering.27091
I've been working as a developer for about 3 years now (straight from uni), I'm wondering, if I take a year or two out would it be impossible to get back into the industry?I didn't get the gap year thing out of my system after uni, and I'm thinking that I should probably do it before I hit 30 (24 now), my main concern is that if I leave the industry now, I might not get back into it at all and end up working some dead end job.The way I see things is, that general concepts / design patterns etc remain similar over the years, and it is mostly coding syntax / actual implementation that evolves, so it shouldn't move on dramatically.Also, women developers (yes there are some out there!) take years out to have kids and still carry on with their career afterwards, so it can't be impossible.Ultimatum : Would taking a year or two out destroy the (small) career I've built up so far?
If you take a year or two out from being a developer, is it really that hard to get back into it?
employment
null
_datascience.16538
Some time ago I read article about method of checking hypothesis in case of impossibility to conduct A/B testing. The key point of this method is to balance groups with help of machine learning technique to prevent bias. E.g. we have records about users and if they used our product or not, then we use classifier to predict if user tends to use product or not based on his known features and build unbiased test groups for products.This explanation may be unclear but unfortunately I forgot how is this method called. I am sure that I have read about it somewhere on wikipedia, if you have any guess on what it may be or you know any similar methods, please let me know its name.Thanks!
Hypothesis check on historical data
ab test
null
_webmaster.83960
We have hired a company to do our SEO. They've done their onpage work and starting to do link building. They are now asking for access to Search Console and Analytics.BackgroundThe SEO company actually also handles SEO work for a few of our competition (we don't know the exact number, but supposedly not enough to create a conflict of interest). One of the ways they got us to sign up with them is by them telling us that a competition of ours signed up with them the previous month and have already made it to first page.After signing up with them, we found out that they used that fact as a selling point when they approached another one of our competitions. We have a good working relation with this particular competing company and they informed us about what the SEO company told them.We've went back to the SEO company and asked them not to tell anyone that we're using them; we don't want our competition finding out what we're doing to outdo them. The SEO company said they were happy to oblige.ProblemWe really don't want any of our metrics to be divulged to our competition. Or even to give the SEO additional insights on how they could improve the competition's ranking (e.g. they might find out that we are ranking high for certain keywords that's not even registering for the competition; that information could be used to suggest new keywords for the competition to optimize for). We've become paranoid.QuestionCan the SEO company do their jobs effectively if we do not give them access to Search Console and Analytics?
Is it necessary to share access to Google Search Console and Google Analytics with an SEO agency?
seo;google analytics;google search console
They can do SEO without these tools but for doing it perfectly they need the access to Google Search Console and Google Analytics. For example,Using Google Search ConsoleThey can get notified about your sites issues/penaltiesThe Search Analytics (search queries) report details a list ofkeywords a website ranks for and the number of impressions andclicks they received along with click through rate (CTR) and averageranking position.They can identify & monitor broken pages on your site (Crawl Errors)They can monitor your sites Link Profile They can check Mobile Usability which is more important.Disavow Tool Structured Data, Google Index, Crawl Stats, Sitemaps, Security IssuesetcThese are all very important. With out access to Google Search Console they can't check all these points.So better give those access to your SEO company. If you don't trust them change to another one.
_unix.8342
Suppose I haveexport MY_VAR=0in ~/.bashrc.I have an opened gnome terminal, and in this terminal, I change $MY_VAR value to 200. So, if I doecho $MY_VARin this terminal, 200 is shown.Now, I opened another tab in my gnome terminal, and do echo $MY_VAR...and instead of 200, I have 0.What should I do to persist the 200 value when a terminal modifies an environment variable, making this modification (setting to 200) available to all subsequent sub shells and such? Is this possible?
Export an env variable to be available at all sub shells, and possible to be modified?
bash;shell;environment variables
A copy of the environment propagates to sub-shells, so this works:$ export MY_VAR=200$ bash$ echo $MY_VAR200but since it's a copy, you can't get that value up to the parent shell not by changing the environment, at least.It sounds like you actually want to go a step further, which is to make something which acts like a global variable, shared by sibling shells initiated separately from the parent like your new tab in Gnome Terminal.Mostly, the answer is you can't, because environment variables don't work that way. However, there's another answer, which is, well, you can always hack something up. One approach would be to write the value of the variable to a file, like ~/.myvar, and then include that in ~/.bashrc. Then, each new shell will start with the value read from that file.You could go a step further make ~/.myvar be in the format MYVAR=200, and then set PROMPT_COMMAND=source ~/.myvar, which would cause the value to be re-read every time you get a new prompt. It's still not quite a shared global variable, but it's starting to act like it. It won't activate until a prompt comes back, though, which depending on what you're trying to do could be a serious limitation.And then, of course, the next thing is to automatically write changes to ~/.myvar. That gets a little more complicated, and I'm going to stop at this point, because really, environment variables were not meant to be an inter-shell communication mechanism, and it's better to just find another way to do it.
_webmaster.36388
Webmaster Newbie QuestionI have a low end vps (128MB RAM)running on Debian.I used a bash script by ilevkov to setup the site. After some trial and error, I managed to set up a WordPress on it. Just now I found out that my VPS can't send any email. I tested using the WordPress reset password email, and it showsThe e-mail could not be sent. Possible reason: your host may have disabled the mail() function...After some Google session I noticed that I can send email from ssh. So I triedmail [email protected]: Halo dionsome message.and the result saidEOT/usr/lib/sendmail: No such file or directory/root/dead.letter 9/243. . . message not sent.The questionHow can I fix my VPS mail setting?
My VPS cannot send email
email;vps
null
_unix.363802
I've created an access point using nmcli however it isn't showing up when I scan for it on my phone.Here's how I created to access pointuser@user:~# sudo nmcli connection add type wifi ifname wlan0 ssid 'wifi-wlan0'user@user:~# sudo nmcli con edit wifi-wlan0 set ipv4.method shared set ipv6.method ignore set connection.autoconnect no set 802-11-wireless.mode adhoc save quitHere are my connectionsuser@user:~# sudo nmcli connectionNAME UUID TYPE DEVICE (green) Wired connection 1 00000000-000-0000-0000-000000000000 802-3-ethernet eth0 (green) wifi-wlan0 11111111-111-1111-1111-111111111111 802-11-wireless wlan0 (white) wlan0 22222222-222-2222-2222-222222222222 802-11-wireless -- wifi-wlan0 is configured as the access point however it doesn't show up on as a wifi network. root@orangepizero:~# nmcli connection show wifi-wlan0 connection.id: wifi-wlan0 connection.uuid: 11111111-111-1111-1111-111111111111 connection.interface-name: wlan0 connection.type: 802-11-wireless connection.autoconnect: no connection.autoconnect-priority: 0 connection.timestamp: 1494274782 connection.read-only: no connection.permissions: connection.zone: -- connection.master: -- connection.slave-type: -- connection.autoconnect-slaves: -1 (default) connection.secondaries: connection.gateway-ping-timeout: 0 connection.metered: unknown connection.lldp: -1 (default) 802-11-wireless.ssid: iot 802-11-wireless.mode: adhoc 802-11-wireless.band: -- 802-11-wireless.channel: 0 802-11-wireless.bssid: -- 802-11-wireless.rate: 0 802-11-wireless.tx-power: 0 802-11-wireless.mac-address: -- 802-11-wireless.cloned-mac-address: -- 802-11-wireless.mac-address-blacklist: 802-11-wireless.mac-address-randomization:default 802-11-wireless.mtu: auto 802-11-wireless.seen-bssids: 802-11-wireless.hidden: no 802-11-wireless.powersave: default (0) ipv4.method: shared ipv4.dns: ipv4.dns-search: ipv4.dns-options: (default)ipv4.dns-priority: 0ipv4.addresses: ipv4.gateway: --ipv4.routes: ipv4.route-metric: -1ipv4.ignore-auto-routes: noipv4.ignore-auto-dns: noipv4.dhcp-client-id: --ipv4.dhcp-timeout: 0ipv4.dhcp-send-hostname: yesipv4.dhcp-hostname: --ipv4.dhcp-fqdn: --ipv4.never-default: noipv4.may-fail: yesipv4.dad-timeout: -1 (default)ipv6.method: ignoreipv6.dns: ipv6.dns-search: ipv6.dns-options: (default)ipv6.dns-priority: 0ipv6.addresses: ipv6.gateway: --ipv6.routes: ipv6.route-metric: -1ipv6.ignore-auto-routes: noipv6.ignore-auto-dns: noipv6.never-default: noipv6.may-fail: yesipv6.ip6-privacy: -1 (unknown)ipv6.addr-gen-mode: stable-privacyipv6.dhcp-send-hostname: yesipv6.dhcp-hostname: --GENERAL.NAME: wifi-wlan0GENERAL.UUID: a629217a-36a8-44ce-a91f-dfaa042d4a37GENERAL.DEVICES: wlan0GENERAL.STATE: activatedGENERAL.DEFAULT: noGENERAL.DEFAULT6: noGENERAL.VPN: noGENERAL.ZONE: --GENERAL.DBUS-PATH: /org/freedesktop/NetworkManager/ActiveConnection/1GENERAL.CON-PATH: /org/freedesktop/NetworkManager/Settings/0GENERAL.SPEC-OBJECT: /org/freedesktop/NetworkManager/AccessPoint/23GENERAL.MASTER-PATH: --IP4.ADDRESS[1]: 10.42.0.1/24IP4.GATEWAY: IP6.ADDRESS[1]: fe80::de44:6dff:fe30:4d5d/64IP6.GATEWAY:
nmcli wifi access point isn't showing up
ubuntu;networking;access point
null
_codereview.166614
I am implementing a litte generic math library. What I have done is to write my generic matrix and vector class. I'm curious if I have it done right so far (implementation wise not totally mathematical correctness wise). Reason: I'm relatively new to template programming and I am not sure what is right, what could be done better and what should I try to avoid at all costs if I use templates in C++.So far I managed to multiply different matrices of (obviously) different sizes while maintaining static allocation by using only std::array, so no dynamic memory allocation.One thing is needed to be mentioned: my Vectors and Matrices start count their elements with #1 not #0 like it is usually done in C++ with arrays. The reason for this is to be near as possible to 'proper' math, but I am open to get convinced otherwise.First of all, my generic Vector class is quite boring but needed for my matrix class, so I put it inside this post.#include <array>#include <cmath>namespace jslmath{ template<size_t Dimension,typename NumberType = double> class Vector { public: using Value = NumberType; using Storage = std::array<NumberType, Dimension>; private: Storage mField; public: Vector(const Vector&) = default; Vector(Vector&&) = default; virtual ~Vector() = default; template<typename ...Targs> Vector(Targs... args): mField({args...}){} Vector(const Storage& args) : mField(args){} Vector& operator=(const Vector&) = default; Vector& operator=(Vector&&) = default; Value operator[](size_t index)const { return at(index); } Value at(size_t index)const { if (index <= Dimension && index != 0) return mField[index - 1]; throw;//need improvment } Vector operator+(Vector vec) const{ return add(vec); } Vector operator-(Vector vec) const{ return sub(vec); }; Vector operator/(Vector vec) const{ return div(vec); }; Vector operator*(Vector vec) const{ return mul(vec); }; Vector operator+(Value scalar) const{ return add(scalar); }; Vector operator-(Value scalar) const{ return sub(scalar); }; Vector operator/(Value scalar) const{ return div(scalar); }; Vector operator*(Value scalar) const{ return mul(scalar); }; Vector add(Vector vec)const { Storage temp; for (auto i = 0; i < Dimension; i++) temp[i] = mField[i] + vec[i + 1]; return {temp}; } Vector sub(Vector vec)const { Storage temp; for (auto i = 0; i < Dimension; i++) temp[i] = mField[i] - vec[i + 1]; return { temp }; } Vector div(Vector vec)const { Storage temp; for (auto i = 0; i < Dimension; i++) temp[i] = mField[i] / vec[i + 1]; return { temp }; } Vector mul(Vector vec)const { Storage temp; for (auto i = 0; i < Dimension; i++) temp[i] = mField[i] * vec[i + 1]; return { temp }; } Value dot(Vector vec) const { Value tmp = 0; for (auto i = 1; i <= Dimension; i++) tmp = vec[i] + at(i); return tmp; } Value magnitude() const { return std::sqrt(dot(*this)); } Value magnitudeSq() const { return (dot(*this)); } Value distance(Vector vec) const { auto tmp = vec - *this; return tmp.magnitude(); } void normalize() { *this = *this * (1.0 / magnitude()); } double Angle(Vector vec) { return std::acos(dot(vec)/ std::sqrt(magnitudeSq()*vec.magnitudeSq())); } Vector add(Value scalar)const { Storage temp; for (auto i = 0; i < Dimension; i++) temp[i] = mField[i] + scalar; return { temp }; } Vector sub(Value scalar)const { Storage temp; for (auto i = 0; i < Dimension; i++) temp[i] = mField[i] - scalar; return { temp }; } Vector div(Value scalar)const { Storage temp; for (auto i = 0; i < Dimension; i++) temp[i] = mField[i] / scalar; return { temp }; } Vector mul(Value scalar)const { Storage temp; for (auto i = 0; i < Dimension; i++) temp[i] = mField[i] * scalar; return { temp }; } };So from here on now the interesting part starts: template<size_t N,size_t M,typename NumberType = double> class Matrix { public: using Value = NumberType; using Storage = std::array<NumberType, N*M>; using RowVec = Vector<M, NumberType>; using ColVec = RowVec;The first part of my class is just some lifetime saver and also makes the code more readable:private: Storage mGrid; public: Matrix(const Matrix&) = default; Matrix(Matrix&&) = default; template<typename ...Targs> Matrix(Targs... args) : mGrid({ args... }) { } Matrix(const Storage& args) : mGrid(args) { } RowVec operator[](size_t index) const { return Row(index); } Value operator()(size_t Row, size_t Col) const { if(Row != 0 && Col != 0) return mGrid[(Col-1) + M*(Row-1)]; throw; } constexpr size_t Height() { return N; }; constexpr size_t Width() { return M; } Storage& data() { return mGrid; } RowVec Row(size_t index)const { if (index <= N && index != 0) { typename RowVec::Storage temp; for (auto i = 1; i <= M; i++) temp[i - 1] = (*this)(index, i); return RowVec(temp); } throw; } RowVec Col(size_t index)const { if (index <= N && index != 0) { typename RowVec::Storage temp; for (auto i = 1; i <= N; i++) temp[i - 1] = (*this)(i, index); return RowVec(temp); } throw; } void transpose(){ Storage tmp; for (auto i = 0; i < N * M; i++) { int row = i / N; int col = i % M; tmp[i] = mGrid[M * col + row]; } mGrid = tmp; } template< template<size_t, size_t, typename>class B, size_t I, size_t J, typename Type> auto operator*(B<I, J, Type>& b) { return mul(b); } auto operator*(Value val) { return mul(val); }The most complicated part of my code so far. I have to calculate the size of my new matrix at compile time so that I am able to keep my goal to avoid dynamic allocation. The syntax of template templates is quite odd to me but it does work. template< template<size_t,size_t,typename>class B, size_t I, size_t J, typename Type> auto mul(B<I,J,Type>& b) -> decltype(Matrix<N, J, Value>{}) { Matrix<N, J, Value> result; for (auto i = 0; i < N; ++i) for (auto j = 0; j < J; ++j) { for (int k = 0; k < I; ++k) { int _a = M * i + k; int _b = J * k + j; result.data()[J * i + j] += this->mGrid[_a] * b.data()[_b]; } } return result; } Matrix mul(Value b) { Storage result; for (auto i = 0; i < N; ++i) for (auto j = 0; j < M; ++j) { result[M*i + j] = mGrid[M*i + j] * b; } return { result }; }};}And a small test application:int main(int argc, char* argv[]){ jslmath::Matrix<3, 3> Test3( 1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0 ); jslmath::Matrix<3, 1> Test4( 1.0, 2.0, 3.0 ); auto T = Test3 * Test4; return T(1,1);}With the help of an online compiler I already found out that VS is not particularly great at compiling this code example compared to gcc and clang. What totally surprised me was that clang was so good at optimizing my code that in the and all that was left were a single return statement with value 14!Clang did all the computation of multiplying two different sized matrices at compile time. I am flabbergasted about that. It is also the reason why I posted this code here. I want to know from you what I did well and what could be improved. I'm not really sure how I did that on the first try without even thinking of active optimization from my side.
Generic matrices implementation
c++;performance;matrix;template;c++17
Some PointsSo far I managed to multiply different matrices of (obviously) different sizes while maintaining static allocation by using only std::array, so no dynamic memory allocation.Sure. If this is something you really want.One thing is needed to be mentioned: my Vectors and Matrices start count their elements with #1 not #0 like it is usually done in C++ with arrays. The reason for this is to be near as possible to 'proper' math, but I am open to get convinced otherwise.That depends entirely on the user base who will be using this class. If they are mathematicians who are used to 1 based array then fine. But think that most people who use C like languages are already used to using 0 based arrays so have this may confuse people.Some ThoughtsA lot of Matrix libraries actually delay the multiplication (and other operations) until the value inside the matrix is required. That way you don't pay for operations that you don't need.Also by deferring operations you can potentially eliminate null operations or simplify operations that are cumulative.Example: { Matrix<4,5> x(init); Matrix<4,5> y(init); Matrix<4,5> z = x + y; // Here the + operator // Can loop over all the elements // and do the operation for each element. std::cout << z[1][1] << \n; // Here we use only one value } // Then z goes out of scope and is destroyed. // So we just did a bunch of operations // that are not needed.// If at the point where we did the operation + we returned an// object that knows about x and y but did not immediately do the operation// Then we accesses element [1][1] we see the work has not been done// and just do the operation for that location. We don't work out all// the elements just the one we want and only when we need it.// That is a deferred operation.Example 2: Matrix<4,5> a(init); Matrix<5,3> b(init); Matrix<4,3> c = a * b; Matrix<4,3> d = c; Matrix<4,3> e = c - d;In this example we can see that all elements of e will be zero. So calculating the value of c first is a waste of time. By deferring calculations of the elements we can sometimes determine the result without having to do all the expensive operations.So at run-time you can perform operations that cancel out other operations and thus you do not need to perform expensive operations if there results do not generate a value that effects the result.Code ReviewIf your Value (or NumberType) is always a simple POD then this is fine. template<typename ...Targs> Vector(Targs... args): mField({args...}){}But maybe you want arrays/matrices of complex types then it may be useful to forward the values. template<typename ...Targs> Vector(Targs&&... args): mField({std::forward<Targs>(args)...}){}In C++ normally the operator[] is unchecked to allow for optimal speed (you don't need to check the ranges in the function if you have already checked it outside the function) while the method at() does do a range check (because you have not done the check externally).Your access access operators change this behavior. Value operator[](size_t index)const { // Changes an unchecked operation into a checked operation. return at(index); } Value at(size_t index)const { // Uses the unchecked access operator[] // But does manually checking the mField.at() will check. if (index <= Dimension && index != 0) return mField[index - 1]; throw; }The second thing to think about is returning by value. Usually when you have a container you return accesses to the element by reference. Thus allowing you to modify the value intuitively. This also makes writting operator+= simpler (then operator+ can be written in terms of operator+=.The third thing is that throw; (without an expression is wrong). This is used to re-throw a currently propogating exception from within a catch clause. There is no catch here so this results in a call to std::terminate // Const and non const version return by reference // Use correct underlying method for checking and non checking. Value const& operator[](size_t index) const { return mField[internalIndex(index)]; } Value& operator[](size_t index) { return mField[internalIndex(index)]; } Value const& at(size_t index) const { return mField.at(internalIndex(index)); } Value& at(size_t index) { return mField.at(internalIndex(index)); }Creating Operators.Normally you implement operator+ in terms of operator+=. Vector operator+(Vector vec) const{ return add(vec); }But you should also pass the parameter by const reference to avoid a copy. Vector& operator+=(Vector const& vec) { for (auto i = 1; i <= Dimension; ++i) (*this)[i] += vec[i]; return *this; } Vector operator+(Vector const& vec) const { Vector temp(*this); return temp += vec; }Same applies to all the operators.Matrix definitions using RowVec = Vector<M, NumberType>; using ColVec = RowVec;Should ColVec not have a size N? using ColVec = Vector<N, NumberType>;
_scicomp.4701
I have some C++ code that links to matlab2008b. Are matlab 2012a and 2012b backwards compatible with 2008b?If it's not trivially compatible, are there some simple steps to make it compatible?
Are matlab C library versions backwards compatible?
matlab;c++;c
In each version some functions are added, changed and removed.As such newer versions are never fully backwards compatible.That being said, not that much has changed from 2008 to 2012, so there is a good chance that you can get your code to work with no or few adjustments.
_cstheory.19241
Residual finite state automata (RFSAs, defined in [DLT02]) are NFAs that have some nice features in common with DFAs. In particular, there is always a canonical minimum sized RFSA for every regular language, and the language recognized by each state in the RFSA is a residual, just like in a DFA. However, whereas a minimum DFAs states form a bijection with all residuals, the canonical RFSAs states are in bijection with the prime residuals; there can be exponentially fewer of these, so RFSAs can be much more compact than DFAs for representing regular languages. However, I can't tell if there is an efficient algorithm for minimizing RFSAs or if there is a hardness result. What is the complexity of minimizing RFSAs?From browsing [BBCF10], it doesn't seem like this is common knowledge. On the one hand, I expect this to be difficult because a lot of simple questions about RFSAs like is this NFA an RFSA? are very hard, PSPACE-complete in this case. On the other hand, [BHKL09] shows that canonical RFSAs are efficiently learnable in Angluin's minimally-adequate teacher model [A87], and efficiently learning a minimum RFSA and minimizing RFSAs seems like it should be of equal difficulty. However, as far as I can tell [BHKL09]'s algorithm does not imply a minimization algorithm, since the size of counter-examples is not bounded and it is not clear how to efficiently test RFSAs for equality to simulate the counter-example oracle. Testing two NFAs for equality is PSPACE-complete, for example.References[A87] Angluin, D. (1987). Learning regular sets from queries and counterexamples. Information and Computation, 75: 87-106[BBCF10] Berstel, J., Boasson, L., Carton, O., & Fagnot, I. (2010). Minimization of automata. arXiv:1010.5318.[BHKL09] Bollig, B., Habermehl, P., Kern, C., & Leucker, M. (2009). Angluin-Style Learning of NFA. In IJCAI, 9: 1004-1009.[DLT02] Denis, F., Lemay, A., & Terlutte, A. (2002). Residual finite state automata. Fundemnta Informaticae, 51(4): 339-368.
Minimizing residual finite state automata
cc.complexity theory;ds.algorithms;automata theory;lg.learning;minimization
null
_softwareengineering.39122
I've been evaluating a number of code review tools (mostly free ones), but they all seem to be aimed at reviewing patches before they are committed. This wouldn't really fit within our workflow with Subversion, so I've been looking for alternatives that better support reviewing committed revisions instead of just diffs. Any recommendations? I would prefer free or inexpensive tools.
What tools can be used to facilitate code reviews after commits?
tools;code reviews
null
_codereview.113486
We are always told to call GPIO.cleanup() before we exit our Pi programs. I've seen people using try ... catch ... finally to achieve this. But hey, we are doing python here, an elegant programming language. Do you guys think this is a more elegant solution?# SafeGPIO.pyfrom RPi import GPIOclass SafeGPIO(object): def __enter__(self): return GPIO def __exit__(self, *args, **kwargs): GPIO.cleanup()Use like this:from SafeGPIO import SafeGPIOimport timewith SafeGPIO() as GPIO: GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT) GPIO.output(7, True) GPIO.setup(8, GPIO.OUT) GPIO.output(8, True) val = 0 for i in xrange(10): val = (val + 1) % 2 active_pin = 7 + val inactive_pin = 7 + (val + 1) % 2 GPIO.output(active_pin,True) GPIO.output(inactive_pin,False) time.sleep(2)
Raspberry Pi GPIO safe clean up
python;python 2.7;raspberry pi
null
_unix.346439
How does rsync --fuzzy work? I do not get the results I expect.From the manual:This option tells rsync that it should look for a basis file for any destination file that is missing. The current algorithm looks in the same directory as the destination file for either a file that has an identical size and modified-time, or a similarly-named file. If found, rsync uses the fuzzy basis file to try to speed up the transfer.If the option is repeated, the fuzzy scan will also be done in any matching alternate destination directories that are specified via --compare-dest, --copy-dest, or --link-dest.Note that the use of the --delete option might get rid of any potential fuzzy-match files, so either use --delete-after or specify some filename exclusions if you need to prevent this.Thus I expect the following shell script to rename the file destination/a1 to destination/a2 on the second rsync run. However as I interpret the output this is not what is happening (Matched data: 0 bytes).#! /usr/bin/env bashset -ecd $(mktemp -d)mkdir source destinationcat /dev/urandom | head --bytes=1M > source/a1rsync --recursive --times $(pwd)/source/ $(pwd)/destination/treemv source/a1 source/a2rsync \ --verbose \ --recursive \ --times \ --delete \ --delete-after \ --fuzzy \ --human-readable \ --itemize-changes \ --stats \ $(pwd)/source/ \ $(pwd)/destination/treerm -r source destinationOutput: destination a1 source a12 directories, 2 filesbuilding file list ... done>f+++++++++ a2*deleting a1Number of files: 2 (reg: 1, dir: 1)Number of created files: 1 (reg: 1)Number of deleted files: 1 (reg: 1)Number of regular files transferred: 1Total file size: 1.05M bytesTotal transferred file size: 1.05M bytesLiteral data: 1.05M bytesMatched data: 0 bytesFile list size: 0File list generation time: 0.001 secondsFile list transfer time: 0.000 secondsTotal bytes sent: 1.05MTotal bytes received: 34sent 1.05M bytes received 34 bytes 2.10M bytes/sectotal size is 1.05M speedup is 1.00. destination a2 source a22 directories, 2 filesOutput of rsync --version:rsync version 3.1.2 protocol version 31Copyright (C) 1996-2015 by Andrew Tridgell, Wayne Davison, and others.Web site: http://rsync.samba.org/Capabilities: 64-bit files, 64-bit inums, 64-bit timestamps, 64-bit long ints, socketpairs, hardlinks, symlinks, IPv6, batchfiles, inplace, append, ACLs, xattrs, iconv, symtimes, preallocrsync comes with ABSOLUTELY NO WARRANTY. This is free software, and youare welcome to redistribute it under certain conditions. See the GNUGeneral Public Licence for details.How does rsync --fuzzy work?Why do I not get the results I expect?
How does the --fuzzy option for rsync work?
rsync
You're using rsync to copy files between two local file trees. The incremental algorithm, and all its associated optimisations such as --fuzzy, are ignored in this mode.Repeat your test with a local file being copied to a remote server (or remote to local; it doesn't matter) and you'll find it works as expected.As an example, modify your script in both places such as $(pwd)/destination is changed to localhost:$(pwd)/destination. It's not elegant but it will suffice.# Set up PKI for localhostssh-keygen -t rsacat ~/.ssh/id_rsa.pub >>~/.ssh/authorized_keysssh localhost idScript results from the second rsync:building file list ... done<f+++++++++ a2*deleting a1Number of files: 2 (reg: 1, dir: 1)Number of created files: 1 (reg: 1)Number of deleted files: 1 (reg: 1)Number of regular files transferred: 1Total file size: 1.05M bytesTotal transferred file size: 1.05M bytesLiteral data: 0 bytesMatched data: 1.05M bytesFile list size: 0File list generation time: 0.001 secondsFile list transfer time: 0.000 secondsTotal bytes sent: 4.20KTotal bytes received: 6.18Ksent 4.20K bytes received 6.18K bytes 20.75K bytes/sectotal size is 1.05M speedup is 101.09
_unix.134918
I've installed maven3 on CentOS from the JPackage repository. Problem is my installs also seem to have pulled in maven2 which is the default. Is there any way to switch /usr/bin/mvn to be maven3? perhaps using the alternatives application? (note: I can modify the path, or symlink I know, just trying to find out if there's a more correct way)
Switch Maven version after installing from jpackage?
centos;software installation;configuration
null
_webapps.88362
I am using Apps Script in Google Sheets to import JSON from Google Analytics. I have previously used the ImportJSON function to easily get the JSON from an open API just using =ImportJSON(url) within a cell. Because I am using Apps Script to authorise the Analytics API stuff (this all works fine), I am also using it to insert the JSON data into my sheet. ImportJSON returns a two-dimensional array containing the data, with the first row containing headers. However, I am having difficulty getting the range of the data so that I can add the values to the sheet.This is what I have:function makeRequest() { var analyticsService = getAnalyticsService(); var apiUrl = 'https://www.googleapis.com/analytics/v3/data/ga?ids=removed&start-date=30daysAgo&end-date=yesterday&metrics=ga%3AuniquePageviews&dimensions=ga%3ApagePath&sort=-ga%3AuniquePageviews&filters=ga%3ApagePath%3D%40%2FKnowledgeBank%2FFactsheetForFarmers.aspx&max-results=10&access_token=' + analyticsService.getAccessToken() var sheet = SpreadsheetApp.getActiveSheet(); var jsonData = ImportJSON(apiUrl); var cell = sheet.getRange(jsonData.length,jsonData[0].length); cell.setValues(jsonData);}The error I get is Incorrect range height, was 3 but should be 1
Import JSON to Google Sheet using Google Apps Script
google spreadsheets;google apps script;import
As JPV pointed out, the line var jsonData = ImportJSON(apiUrl);is not valid in Apps Script (unless you have defined ImportJSON function somewhere). To fetch something from an external URL in Apps Script, one uses UrlFetchApp. So the line could bevar jsonData = JSON.parse(UrlFetchApp.fetch(apiUrl).getContentText());After this, jsonData is a JavaScript object parsed from the JSON string returned by the server. To import it in a spreadsheet, one has to create a double array suitable for passing to setValues. How to do this depends on the structure of the object.The pullJSON gist that you referenced gives a simple model of this process, which works when jsonData is already an array. But different APIs work differently: for example, Stack Exchange API returns an object with several wrapper properties, one of which is items that holds an array of objects of interest. So in this case one would loop over the elements of jsonData.items, extracting the properties of each object in the array and pushing them into a double array.
_unix.30909
I think what I want to do is long and convoluted; then again, it might be somewhat easy, and I'm just overthinking it.Here's the setup I want to achieve:The internal drive (sda) is one giant WinXP partition (sda2), a tiny one for a boot partition (sda1), and the MBR.On an external drive (sdb), I will create multiple partitions for several distros. This drive will be either an HDD in an enclosure or something like a WD passport. This will be attached via USB 2.0.I know it is possible to install grub to the MBR of sda and boot an sdb partition from there. I also know I'll need to edit grub to chainload Windows and list all the distros. However, I have the following questions:If I disconnect sdb and want to select + boot into Windows, is grub going to get upset? In other words, does the grub menu just display what you tell it to, or does it go hunting for those other options immediately and will have problems because some have disappeared? If I disconnect sdb, I'd love for it to still be bootable on another computer. If I have a boot partition on sdb as well as sda, but have my BIOS set to use the internal MBR first, can this be achieved? What if I want to use something pretty like burg or plymouth? How will this change things?I'm sure the answers are out there somewhere, but I'm finding it hard to Google for!
GRUB on MBR of Windows-only internal drive, with distros on external drive
dual boot;grub2;usb drive
Keep in mind that GRUB also needs a configuration file and additional files, so you need it in the MBR and it has to access files in some partition just to run. This will ruin 1.You can either spare some megabytes (if it's even that much) just to have the grub files in sda, or install another bootloader that sits in the MBR (I think lilo does that).Now for 2., your best choice is probably:Set up sdb with a GRUB itself, so that booting through sdb gives you a menu of what is in that disk, and you can use that menu on any computer;Set up another GRUB on sda (or another bootloader, if you can't have the files in sda). This one should be independent from sdb and have two entries: chainload into Windows and chainload into sdb (run the other GRUB).So yes, that setup is achievable, the only thing you may need to spend some time with is finding out what to install on sda if you can't make a tiny partition for GRUB.(I'm just not sure if GRUB will be able to chainload into an USB drive, I guess that depends partly on GRUB, partly on the BIOS.)
_codereview.169499
I am using following code to download a csv file using Web API. Maximum file size will be less than 500mb. How can I improve this code?[HttpPost, Route(api/files/getfile)]public HttpResponseMessage GetDataFileResponse(string filePath) { try { FileStream fileStream = File.OpenRead(filePath); long fileLength = new FileInfo(filePath).Length; var response = new HttpResponseMessage(); response.Content = new StreamContent(fileStream); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue(attachment); response.Content.Headers.ContentDisposition.FileName = mydata.csv; response.Content.Headers.ContentType = new MediaTypeHeaderValue(application/octet-stream); response.Content.Headers.ContentLength = fileLength; return response; } catch (Exception e) { Console.WriteLine(e); throw; }}
Download file uisng ASP.Net WebApi
c#;asp.net web api
null
_unix.327935
I'm a gentoo user and I've become I a bit tired of copying my kernel config file when a new kernel comes out. I wonder if it's possible to pipe the configuration file to genkernel directly. Something like this:sudo genkernel --install --clean --kernel-config=$(gunzip/proc/config.gz) --menuconfig allor this:zcat /proc/config.gz | sudo genkernel --install --clean --kernel-config=- --menuconfig allBut I can't get it to work since I'm not really that good at piping/shell scripting. Any ideas?EDIT: with $(gunzip /proc/config.gz) it says gzip: /proc/config: No such file or directory. But it's untrue since zcat /proc/config.gz prints all my settings
Piping config file to genkernel
kernel;pipe;gentoo
null
_cs.19065
In the pre-history of dependent type theory, Per Martin Lfintroduced a calculus that is in some sense the simplest dependenttype theory and the most general form of impredicative polymorphism.It is often referred to as Type:Type because the kind Type isitself of type Type. Unfortunately, it is inconsistent as alogic. This was discovered by Girard in his famous dissertation [1],who managed to express the Burali-Forti paradox in Type:Type.Various people have analysed, generalised and simplified Girard'sanalysis, see e.g. [2, 3]. This analysis seems to involve showing thatnon-terminating terms can be typed.I have a question about non-termination: do we get non-normalisation atthe level of types? By that I mean, is there a type $T$ such that thereduction relation $\rightarrow$ used, explicitly or implicitly, todefine equality of types, gives rise to an infinite reduction sequence$$ T \rightarrow T' \rightarrow T'' \rightarrow \cdots?$$[1] J.-Y.. Girard, Une extension de l'interpretation fonctionelle deGdel a l'analyse.[2] T. Coquand, A New Paradox in Type Theory.[3] A. J. C. Hurkens, A Simplification of Girard's Paradox.
Non-termination of types in Martin-Lf's Type:Type?
type theory;functional programming;dependent types;curry howard
Short answer: yes.Long answer: For $\mathrm{Type}:\mathrm{Type}$, non-termination at the type level is trivial. You can take a constant $X:\mathrm{False}\rightarrow \mathrm{Type}$. Then if you take the inconsistent term $\bot : \mathrm{False}$ you have$$ X\ \bot : \mathrm{Type}$$Which is non-terminating at the type level. You might complain that this has a head normal form, which isn't what usually leads to inconsistency in type theory. In this case you can remember that $$ \mathrm{False}\equiv \forall X.\ X$$and so$$ \bot\ \mathrm{Type}:\mathrm{Type}$$Which has no head-normal form. In general, in this system the types and terms are so intertwined that the non-termination always seeps at the type level.However, there is another system, called $U^-$, also described by Girard in his thesis, which was discovered to be inconsistent by Coquand (A New Paradox in Type Theory). This system is terminating at the type level, as it only has $\mathrm{system}\ F$ types at the kind level, and we know that terms are normalizing in that system (also a result of Girard!).This means that non-termination at the type level is not necessary for having an inconsistent pure type system (a fact that I found out somewhat painfully after having proven an open question while depending on this fact).
_webmaster.92842
So I know that positions change and are also tailored to the user personally, but when I am looking at positions in my Webmaster tools dashboard some keywords have positions like 5, 6 or 7 (first page), but when I am actually trying the same keywords in Google search I don't see my website anywhere at all, and I also checked image search.Does anyone know why this happens?
Google search console reports rankings, but my site doesn't show up for me when searching for those keywords
seo;google search console;google search
null
_unix.252171
I have a file named, for example, ascdrgi.txt, with the following contents:tigerlioncatI want to duplicate this file a (variable) number of times by changing the last character of the filename (ignoring the extension). For example, in this case if I made 3 copies, they would be named:ascdrgj.txtascdrgk.txtascdrgl.txtIf the filename ends with a number, that number should increase instead, so copies of ascdrg1.txt would be:ascdrg2.txtascdrg3.txtascdrg4.txtIf the file already exists, the script should skip that name and move onto the next one. If we reach the last character (z, Z, or 9), it should loop around to the beginning (the next would be a, A, or 1, respectively).In addition to duplicating the original file, I need to modify the first line of each file to say which file it is (numerically), as well as the total number of files. Using the first ascdrgi.txt example, that file would now contain:tiger number(1,4)lioncatThe next file, ascdrgj.txt, would contain:tiger number(2,4)lioncatand so on.
How to duplicate a file a number of times while embedding an index in each file
shell script;text processing;awk;file copy
null
_codereview.145833
I have the following code but I am not too happy about the way I replace e-mails with mailto links. Additionally, I am thinking how to conbine the logic of the URLs and E-mails into one Loop. Finally, Will be there any ill effects if I take the Pattern and compile it as a public static final outside of the method? I don't think it will but I want to be safe. private static String wrapURLsInStrings(String s) { String [] parts = s.split(\\s+); StringBuilder returnedString = new StringBuilder(); // Attempt to convert each item into an URL. for( String item : parts ) { try { URL url = new URL(item); // If possible then replace with anchor... returnedString.append(<a href=\ + url + \ title=\ + url + \ target=\_blank\> + url + </a> ); } catch (MalformedURLException e) { // If there was an URL that was not it!... returnedString.append(item).append( ); } } String urlString = returnedString.toString(); Pattern patternEmail = Pattern.compile([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+); // why i need to compile; //E-mails Matcher matcher = patternEmail.matcher(urlString); String eMaill; while (matcher.find()) { eMaill = matcher.group(); urlString = urlString.replaceAll(eMaill, <a href=\mailto: + eMaill + \ title=\ + eMaill + \ target=\_blank\> + eMaill + </a> ); } return urlString; }
Link Detection and Addition of Anchor
java;performance;regex
null
_cs.33455
I'm struggling to understand a question I've been given. The question asks:Let $\psi$ be a boolean formula in $n$ variables. There are $2^n$ different combinations of assigningvalues to the variables. Consider the problem of deciding whether (strictly) more than $2^{n1}$of these assignments satisfy the formula $\psi$. We will call the language that corresponds to thisdecision problem, $L$.From this I can tell that if $x_1, x_2, ..., x_n$ are the $n$ variables which can be either true or false. I understand why there would be $2^n$ different assignings for the formula, as each variable can be assigned 1 of 2 values. But then what is $\psi$ exactly, is it an assignment such as $\psi$=($x_1 \lor x_2 \lor ... x_n$). But then the later part of the question doesn't make any sense. Can someone please explain in more detail what it means by deciding whether (strictly) more than $2^{n1}$ of these assignments satisfy the formula $\psi$?The question is then to show that there exists a turing machine $M$ and polynomials $T$ and $p$, with the following properties: For every input $x$, $M$ terminates after at most $T(|x|)$ steps. If $x\in L$, then $Pr_{t\small\{0,1\small\}^{p(|x|)}}$[$M$ accepts $<x, t>$] $>$ 1/2. If $x\notin L$, then $Pr_{t\small\{0,1\small\}^{p(|x|)}}$[$M$ rejects $<x, t>$] $$ 1/2Where $Pr_{t\{0,1\}^{p(|x|)}}$[$M$ accepts $<x, t>$] means the probability, for a give $t$ from the set $\{0,1\}^{P(|x|)}$, that M accepts the input $<x,t>$ is greater than 1/2. This is similar to the definition of bounded error probabilistic polynomial time(BPP), except that the definition for BPP have both equalities as $$, so I'm guessing I need to show that the language L is in BPP. But how would I even start the proof to show that he language is indeed in BPP. Also the definition of a language in BPP is not identical to what is mentioned in the question, so maybe there's a different approach to answering the question. Also, I don't need to explicitly find the polynomials $p$ and $T$, but instead argue that they exist.Any help to assist me with the question would be much appreciated
Show there exists a turing machine with the following properties
complexity theory;turing machines
null
_unix.84273
Please comment on the following sentence:On the standard Linux kernel without the rt patch, interrupts can't interrupt ongoing system calls. The reason why our machine doesn't stop working when data is fetched from the hard disk is because the system call we used for that operation is blocking. Blocking means that once it issues the request to the hard disc it changes the process state to blocked, and willingly gives up the processor time. There are no means to interrupt an ongoing system call on a non real time kernel.This is my understanding of the topic, I am however, not sure if it is correct.
Can system calls be interrupted?
linux;linux kernel;scheduling;interrupt
System calls can be interrupted through the use of signals, such as SIGINT (generated by CTRL+C), SIGHUP, etc. You can only interrupt them by interacting with the system calls through a PID, however when using Unix signals and the kill command.rt_patch & system calls@Alan asked the following follow-up question:Is the possibility to interrupt system calls directly related with the acceptance of the rt_patch in the mainline Linux kernel?My response:I would think so. In researching this I couldn't find a smoking gun that says you could/couldn't do this which leads me to believe that you can. The other data point which makes me think this, is that the underlying signals mechanism built into Unix is necessary for being able to interact with processes. I don't see how a system with these patches in place would be able to function without the ability to use signals. Incidentally the signals operate at the process level. There isn't any method/API which I'm aware of for injecting interrupts to system calls directly.ReferencesWhen and how are system calls interrupted?
_unix.230087
I'm trying to create an array of file names, based on two variable and using brace expansion, like this:#!/bin/bashaltdir=/usrarg=abctries=({.,$altdir}/{$arg,$arg/main}.{tex,ltx,drv,dtx})for i in ${tries[@]}; do echo $i; doneThe last statement list the files I want correctly:./abc.tex./abc.ltx./abc.drv./abc.dtx./abc/main.tex./abc/main.ltx./abc/main.drv./abc/main.dtx/usr/abc.tex/usr/abc.ltx/usr/abc.drv/usr/abc.dtx/usr/abc/main.tex/usr/abc/main.ltx/usr/abc/main.drv/usr/abc/main.dtxBut shellcheck tells me that the two variables, altdir and arg, appear to be unused:$ shellcheck testscriptIn testscript line 3: altdir=/usr ^-- SC2034: altdir appears unused. Verify it or export it.In testscript line 4: arg=abc ^-- SC2034: arg appears unused. Verify it or export it.Is there a better way to do this?
bash shellcheck issue with variables in brace expansion
bash;shell;brace expansion;shellcheck
A workaround can be:#!/bin/bashunset altdirunset arg: ${altdir:=/usr}: ${arg:=abc}tries=({.,$altdir}/{$arg,$arg/main}.{tex,ltx,drv,dtx})for i in ${tries[@]}; do echo $i; doneor make shellcheck ignore SC2034 code:shellcheck -e SC2034 testscript(And remember to always quote your variables if you don't want list context)
_webapps.101378
I'm in the process of setting up G Suite for a small business. I have a domain that I own (newDomain.ca), a single G Suite account for an email ([email protected], which manages [email protected]), and can log into the admin console. However, when I go to some sites associated with the account I am unable to perform certain actions as Google thinks I am not an administrator -- despite the fact that I'm the only user. For instance, if I go to Google Plus to edit my information and attempt to update anything under the Organization Info heading, the following appears:Because Google doesn't think I'm an administrator, I also can't contact their support services for help despite being a paying customer. This, as you might imagine, is very frustrating -- especially as Google's advice is to contact my administrator. Any idea what I might be doing wrong? Do I fundamentally misunderstand how G Suite works?
New G Suite Setup: Only user is not an administrator?
google plus;google account;account management;alias;g suite
null
_softwareengineering.189052
I recently finished this book called The Elements of Computing Systems where you build a working computer system from the ground up, starting from basic logic gates, to creating your own machine code and Assembly language, to intermediate code, and finally a simple object-oriented programming language that compiles down to VM code. I enjoyed it a lot and I'd like to create something similar in JavaScript, but with more features. I've already written an emulator for the Hack machine in JS: // Creates a new CPU object that is responsible for processing instructions var CPU = function() {var D = 0; // D Register var A = 0; // A Registervar PC = 0; // Program counter// Returns whether an instruction is valid or notvar isValidInstruction = function(instruction) { if (instruction.length != 32) return false; instruction = instruction.split(); for (var c = 0; c < instruction.length; c++) { if (instruction[c] != 0 && instruction[c] != 1) return false; } return true;}; // Given an X and Y input and 6 control bits, returns the ALU outputvar computeALU = function(x, y, c) { if (c.length != 6) throw new Error(There may only be 6 ALU control bits); switch (c.join()) { case 000000: return 0; case 000001: return 1; case 000010: return -1; case 000011: return x; case 000100: return y; case 000101: return ~x; case 000110: return ~y; case 000111: return -x; case 001000: return -y; case 001001: return x+1; case 001010: return y+1; case 001011: return x-1; case 001100: return y-1; case 001101: return x+y; case 001110: return x-y; case 001111: return y-x; case 010000: return x*y; case 010001: return x/y; case 010010: return y/x; case 010011: return x%y; case 010100: return y%x; case 010101: return x&y; case 010110: return x|y; case 010111: return x^y; case 011000: return x>>y; case 011001: return y>>x; case 011010: return x<<y; case 011011: return y<<x; default: throw new Error(ALU command + c.join() + not recognized); }}; // Given an instruction and value of Memory[A], return the resultvar processInstruction = function(instruction, M) { if (!isValidInstruction(instruction)) throw new Error(Instruction + instruction + is not valid); // If this is an A instruction, set value of A register to last 31 bits if (instruction[0] == 0) { A = parseInt(instruction.substring(1, instruction.length), 2); PC++; return { outM: null, addressM: A, writeM: false, pc: PC }; } // Otherwise, this could be a variety of instructions else { var instructionType = instruction.substr(0, 3); var instructionBody = instruction.substr(3); var outputWrite = false; // C Instruction - 100 c1, c2, c3, c4, c5, c6 d1, d2, d3 j1, j2, j3 (000..000 x16) if (instructionType == 100) { var parts = [ a, c1, c2, c3, c4, c5, c6, d1, d2, d3, j1, j2, j3 ]; var flags = {}; for (var c = 0; c < parts.length; c++) flags[parts[c]] = instructionBody[c]; // Compute the ALU output var x = D; var y = (flags[a] == 1) ? M : A; var output = computeALU(x, y, [flags[c1], flags[c2], flags[c3], flags[c4], flags[c5], flags[c6]]); // Store the result if (flags[d1] == 1) A = output; if (flags[d2] == 1) D = output; if (flags[d3] == 1) outputWrite = true; // Jump if necessary if ((flags[j1] == 1 && output < 0) || (flags[j2] == 1 && output == 0) || (flags[j3] == 1 && output > 0)) PC = A; else PC++; // Return output return { outM: output, addressM: A, writeM: outputWrite, pc: PC }; } else throw new Error(Instruction type signature + instructionType + not recognized); }}; // Reset the CPU by setting all registers back to zerothis.reset = function() { D = 0; A = 0; PC = 0;}; // Set the D register to a specified valuethis.setD = function(value) { D = value;}; // Set the A register to a specified valuethis.setA = function(value) { A = value;}; // Set PC to a specified valuethis.setPC = function(value) { PC = value;};// Processes an instruction and returns the resultthis.process = function(instruction, M) { return processInstruction(instruction, M); }; }; I was thinking about adding things like a filesystem, sound, Internet connectivity, and an RGBA screen output (currently it's only black and white). But how feasible would this be, really? Because what I'm thinking about doing is starting completely from scratch. And what I mean by that is create my own machine code, then work all the way up towards a C-like language and actually create working programs and stuff.
Building a computer system with JS?
javascript
You could certainly do it. You'd need to implement certain components of your operating system, such as the boot loader, and interrupts in a lower level language.Have a look at the approach taken by the Singularity Operating System by Microsoft on how to develop an operating system that runs on Managed Code.Of course, there is no requirement that you have to bolt on memory management to JavaScript, you could add an API for memory management to JavaScript. You could choose to write a compiler for JavaScript or write a virtual machine.Singularity has source code available so you could gain valuable insight from looking at the design decisions that Microsoft made.
_unix.386332
Just after upgrade my system start to fail when I try to login as normal user both via gdm and tty. However it's not possible to login as root too. When try to login via tty it outputs 'Login Incorrect'. Via the gdm the same but another words used. I've changed passwords with live cd but it's not helped. I tried to check logs, but last log changed before upgrade.It's Debian system.How to reslolve this? Thanks!PS. chrooting from live cd to purpose system successfully done however.
Debian not logged in with proper password after upgrade
debian;ubuntu;security;login;pam
null
_webmaster.102850
I am in the process of updating the structured data on my site and added the siteNavigationElement schema to top category navigation on my page.I was wondering if it is beneficial or if it is incorrect to add this schema to the faceted navigation and the navigation in the footer.
Should I use the navigation schema on faceted navigation and footer navigation?
schema.org;structured data
null
_unix.156719
Is the ext2 filesystem good for /boot partition? I set ext4 for / root partition, but wasn't sure which filesystem to select for the /boot partition, and I just set ext2. Does it matter in this case?
Ext2 filesystem for /boot partition
filesystems;boot;boot loader;ext2
It only matters if you're going to use the ancient GRUB, ext4 is only supported by GRUB2.ext2 is simple, robust and well-supported, which makes it a good choice for /boot.
_unix.361085
I've been asked to determine the absolute minimum attributes for Samba accounts on AIX. For instance, setting the local account shell to /bin/false in order to prevent shell access. That's feasible. I can even set the /home directory to something other than /home/service/$USER or /home/$USER because, from what I gather, it is impossible to actually create a local account without a /home directory on AIX.But, what about Samba? Is it possible to create a Samba user without creating its home directory?
Disable samba home directories
samba;aix;home;accounts
null
_webmaster.101992
I am guessing Google structured data testing tool behaves strange.I wrote a code to create JSON-LD for multiple locations for one of my websites. But Google testing tool returns an error: Missing '}' or object member name.The error is related to missing }, or ], but that's not all right. Because the syntax is correct. Below is the code I used, maybe others are also in the same condition these days:<script type=application/ld+json>{@context: http://schema.org,@type: LocalBusiness,name: Company,url: http://www.example.com,[{address: { addressLocality: United Arab Emirates, addressRegion: Dubai, streetAddress: Building 213, telephone : 04 444 5555 openingHours: [Su, Mo,Tu,We,Th, 09:00-18:00], },{address: { addressLocality: Jordan, addressRegion: Amman, postalCode:XXXXXXX, streetAddress: Building 213 openingHours: [Su, Mo,Tu,We,Th, 09:00-18:00], },{address: { addressLocality: Lebanon, addressRegion: Beirut, streetAddress: Building 213, telephone : +961 444 5555 openingHours: [Su, Mo,Tu,We,Th, 09:00-18:00], },{address: { addressLocality: Qatar, addressRegion: Doha, streetAddress: Building 213, telephone : +1(503) 444 5555 openingHours: [Su, Mo,Tu,We,Th, 09:00-18:00], },{address: { addressLocality: Saudi Arabia, addressRegion: Riyadh, streetAddress: Building 213, telephone : +966 1 4444 5555 openingHours: [Su, Mo,Tu,We,Th, 09:00-18:00], },{address: { addressLocality: Egypt, addressRegion: New Cairo, streetAddress: Building 213, telephone : +20 2 44445555 openingHours: [Su, Mo,Tu,We,Th, 09:00-18:00], }],description: Company description,email:[email protected],logo: http://www.example.com/w-logo.png,sameAs : [ https://www.facebook.com/Example,https://twitter.com/Example,https://plus.google.com/+Example,https://www.youtube.com/user/Example,http://www.slideshare.net/Example,https://www.linkedin.com/company/Example]}</script>
Google SDTT gives error Missing '}' or object member name. for my JSON-LD
google rich snippets tool;json ld
null
_softwareengineering.76591
I've spent too much time on setup & maintain a development server, which contains following tools:Common services like SSH, BIND, rsync, etc.Subversion, Git.Apache server, which runs CGit, Trac, Webmin, phpmyadmin, phppgadmin, etc.Jetty, which runs Archiva and Hudson.Bugzilla.PostgresSQL server, MySQL server.I've created a lot of Debian packages, like my-trac-utils, my-bugzilla-utils, my-bind9-utils, my-mysql-utils, etc. to make my life more convenient. However, I still feel I need a lot more utils. And I've spent a lot of time to maintain these packages, too.I think there maybe many developers doing the same things. As tools like subversion, git, trac are so common today. It's not to hard to install and configure each of them, but it took a long time to install them all. And it's time consuming to maintain them. Like backup the data, plot the usage graph and generate web reports. (gitstat for example)So, I'd like to hear if there exist any pre-configured distro for Development Server purpose, i.e., something like BackTrack for hackers?
Linux distro for software development support?
linux
I think you'll have to make one yourself, since I don't think there's a one-size-fits-all solution, every developer needs a unique set of tools.However, you can create your own distribution using something like SuSE studioOr search for linux unattended install on Google, I found some good hits.
_unix.377339
I am a sysadmin by trade, and I do what I do at work at home as well for fun. I have a Gentoo Linux laptop, Raspberry Pis running Raspian, a Gentoo server, ARM devices running Debian and have various Android devices. I'm always wrestling and worrying about backing up and synchronizing my own home directory among disperate devices, while keeping it reasonably safe from prying eyes.I had experience with Andrew in the '80s at CMU, and it was like magic. I would consider NFS if it had some mechanism to handle disconnected access and didn't presume a constant network connection.Would OpenAFS be something that admins out there might consider to handle synchronizing the data of lightly connected hosts of the modern user? I've also considered things like Lustre. I am looking for something that requires moderate maintenance after initial setup. It seems like OpenAFS might also be interesting in that I could divide my home directory into administratively different subdirectories, which might be distributed to different devices in different measure. (E.g. a ~/mobile for files which must reside on my phone and tablets, ~/pi for Raspberry Pi files, etc.)Is OpenAFS a dead end, or am I on a good track? :)
Is it crazy to consider keeping my home directory on OpenAFS?
linux;home;synchronization;distributed filesystem;afs
null
_unix.347926
Gnome desktop seems configurable in various ways: in Gnome settings, with gnome-extensions, gnome-tweak-tool, gsettings or dconf-editor.However, apart from this procedure to change the login screen background, which involves a little bit of glib compiling, I have found no way to customize the appearance of:the login screen (font, position, color and size of the login boxes)shield screen aka lock screen aka curtain (font, position, color, format and size of the clock, displayed messages, etc.)I understand that Gnome philosophy is not to allocate much resource in tweaky-tweak-tweaking-tweakable stuffs. But I am suprised that such basic and harmless properties of these screens seem so difficult to access.Is there a way I can access and tweak login / shield screen organization properties?Are they hardcoded or is it just a matter of sneaking into a small curtain.xml or loginscreen.json?Do I need to get into the sources and compile gnome myself?
How do I customize Gnome screen shield / curtain / login screen appearance?
gnome;gnome shell;screen lock;dconf;appearance
null
_cs.74756
How to compute the run-time of distributed algorithms in message passing systems? I was reading across and found it very weird that any computation done in each node is considered to take $\mathcal{O}(1)$ time due to the unreliability in the time it takes to pass messages. Since this approach is not practical at all, I am assuming that I have not understood it properly. Could someone please explain?By impractical, I mean that I can simply solve any NP-Hard problem in distributed computing trivially in $\mathcal{O}(n^2)$ time by passing information throughout the network and then brute-forcing for the solution in $\mathcal{O}(1)$ time and this obviously seems stupid since in real life message passing shouldn't take more time than a brute-force solution over the search space.
How do you compute the time complexity of distributed algorithms?
algorithm analysis;runtime analysis;distributed systems
You understood it right. The standard models of distributed computing typically assume that local computation is free. It follows that in the LOCAL model of distributed computing, you can solve any graph problem in time $O(n)$, and in the CONGEST model of distributed computing, you can solve any graph problem in time $O(m)$ by brute force; here $n$ is the number of nodes and $m$ is the number of edges.However, we are not interested in such running times in these models. For example, for the LOCAL model, the key question is what can be solved e.g. in polylogarithmic time time, or $O(\log n)$ time, or $O(\log^* n)$ time, or even $O(1)$ time. Now these are highly non-trivial questions even if you assume that local computation is free.LOCAL and CONGEST are usually the wrong models if you are interested in studying e.g. NP-hard problems. However, if you consider easy problems (e.g. something that you can trivially solve in linear time with a centralised algorithm), then these models become much more interesting. Yes, of course you can find a maximal matching or a maximal independent set in linear time, but can you find it in sublinear time?Here are the key definitions for reference:LOCAL model: running time = number of synchronous rounds until all nodes stop and announce their local outputs; in each round each node can send a message to each of its neighbours; the message size is unbounded; local computation is free.CONGEST model: as above, but messages are bounded to $O(\log n)$ bits.
_cs.53967
I am trying to understand deeply how memories work in computers, and I faced the next difficulty.Let's say we have a device with two memory chips but only one address space (for example, 0x00000000 to 0x10000000 will be memory1 and 0x10000000 to 0x20000000 will be memory2). In case an assembly code does a load/store instruction to memory2 to the address 0x10000004, who's responsible it is to change the address so it will be absolute to the memory chip?I assume that the memory chip doesn't know it's relative address space, and in our example memory2 expects a load/store from/to 0x00000004.
Mapping several memories to one address space
memory management;memory hardware;memory access
Each RAM chip (e.g., DIMM module) has its own range of physical addresses. The memory controller connects the CPU to the RAM chips via a memory bus.In its simplest form, each read or write operation sent on the memory bus contains some bits that select which RAM chip it applies to, and some bits that indicate the address to be selected within that RAM chip. So, physical memory is partitioned among the RAM chips. The memory controller is responsible for managing this partition and determining, based on the physical address, which RAM chip to select (what to write on the chip select bits of the memory bus). The specific architectural details have evolved over time and may differ from platform to platform.Physical addresses are normally not visible to user-level applications. Instead, a virtual memory subsystem (page tables) are used to translate from virtual addresses to physical addresses. The user-level application seems virtual addresses. There need not be any simple way that ranges of virtual memory addresses correspond to RAM chips.
_softwareengineering.165264
I have a domain model, persisted in a database, which represents a graph. A graph consists of nodes (e.g. NodeTypeA, NodeTypeB) which are connected via branches. The two generic elements (nodes and branches will have properties). A graph will be sent to a computation engine. To perform computations the engine has to be initialised like so (simplified pseudo code):Engine Engine = new Engine() ;Object ID1 = Engine.AddNodeTypeA(TypeA.Property1, TypeA.Property2, , TypeA.Propertyn);Object ID2 = Engine.AddNodeTypeB(TypeB.Property1, TypeB.Property2, , TypeB.Propertyn);Engine.AddBranch(ID1,ID2);Finally the computation is performed like this:Engine.DoSomeComputation();I am just wondering, if there are any relevant design patterns out there, which help to achieve the above using good design principles. I hope this makes sense. Any feedback would be very much appreciated.
design pattern advice: graph -> computation
design;design patterns;object oriented design;domain driven design
I think the Visitor Pattern is appropriate to your problem, as it allows you to separate the tasks:apply a computation to every node on the graph; andthe computation that is applied.Your DoSomeComputation() method would take a parameter that is a (closure/lambda/implementation of some Visitor interface[*]) and apply that to the nodes on the graph.[*] delete as appropriate for the programming language you're using.
_datascience.22056
I have come across many job openings where knowledge of ML, NLP and Deep learning are required to work in elasticsearch. I am actually not sure how ML, NLP etc are related with elasticsearch which is purely a search and indexing tool. At best it can be used for information retrieval tasks. I am not able to get a clear picture. Can anyone shed some light on this please?I am posting some of the job descriptions below after changig some of the wordings.Job description 1Working with a group (Data Science & Machine Learning Group) of ML engineers, Data Scientists and Product AnalystsDefine API oriented solutions for data and machine learning servicesGood to have :Elastic Search, NLP background and Machine Learning Platforms from a product engineering background.Job description 2This role emphasizes a need for to conceptualize, design, and develop reusable NLP and AI models as well as very strong technical knowledge.Work on technologies that people can't live without in the future: AI, NLP, Data Science + Bots.Advanced and Semantic Search (experience with indexing and retrieval technologies such as Elasticsearch or Lucene)Can anyone guide me? I am unable to get a clear picture and connect the dots.
Does elasticsearch job requires knowledge of Machine learning and Deep Learning?
beginner;tools;career;reference request
null
_webapps.35592
As far as I understand, at Amazon music cloud for 30 dollars a year you can upload all your mp3 music that you have.Even if you never payed for some of the mp3s, after those uploads, they are treated as leagally owned.What will happen, if you cancel that 30 dollars per year?Do you still legally own the songs, you once uploaded to the drive?
Is Amazon music cloud the salvation? Do I own the music afterwards?
amazon;music;online storage;cloud
null
_unix.371027
I have had the following error for the last month or so when trying to do a standard:apt-get upgradeor update-managerOutput from terminal is as follows:Reading package lists...Building dependency tree...Reading state information...Calculating upgrade...The following packages will be upgraded: linux-firmware1 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.11 not fully installed or removed.Need to get 0 B/38.7 MB of archives.After this operation, 5,624 kB of additional disk space will be used.(Reading database ... 408213 files and directories currently installed.)Preparing to unpack .../linux-firmware_1.157.10_all.deb ...Unpacking linux-firmware (1.157.10) over (1.157.8) ...dpkg: error processing archive /var/cache/apt/archives/linux-firmware_1.157.10_all.deb (--unpack):unable to create '/lib/firmware/brcm/brcmfmac4330-sdio.bin.dpkg-new' (while processing './lib/firmware/brcm/brcmfmac4330-sdio.bin'): Permission denieddpkg-deb: error: subprocess paste was killed by signal (Broken pipe)update-initramfs: Generating /boot/initrd.img-4.4.0-79-genericupdate-initramfs: Generating /boot/initrd.img-4.4.0-78-genericupdate-initramfs: Generating /boot/initrd.img-3.13.0-106-genericErrors were encountered while processing: /var/cache/apt/archives/linux-firmware_1.157.10_all.debE: Sub-process /usr/bin/dpkg returned an error code (1)I have tried deleting the file at:'./lib/firmware/brcm/brcmfmac4330-sdio.bin'and then reinstalling but no luck.I have also looked at:https://bugs.launchpad.net/ubuntu/+source/linux-firmware/+bug/1688602 but my issue does not seem to be with *.ucode drivers.Was wondering if it was my graphics card but my system at home is 16.04 too and it has a much older graphics card and there seems to be no problem there. Still a noob so any help appreciated.Cheers.Edit: Added:total 75224drwxr-xr-x 74 root root 32768 Jun 14 08:27 .drwxr-xr-x 26 root root 4096 Jun 7 10:00 ..drwxr-xr-x 11 root root 4096 Jan 3 08:53 3.13.0-106-genericdrwxr-xr-x 2 root root 4096 Feb 12 13:29 3comdrwxr-xr-x 11 root root 4096 May 17 15:10 4.4.0-78-genericdrwxr-xr-x 11 root root 4096 Jun 7 10:04 4.4.0-79-genericdrwxr-xr-x 2 root root 4096 Feb 12 13:29 acenicdrwxr-xr-x 2 root root 4096 Jun 14 08:27 adaptecdrwxr-xr-x 2 root root 4096 Jun 14 08:27 advansys-rw-r--r-- 1 root root 50698 Apr 25 2016 agere_ap_fw.bin-rw-r--r-- 1 root root 65046 Apr 25 2016 agere_sta_fw.bindrwxr-xr-x 2 root root 12288 Jun 14 08:27 amdgpudrwxr-xr-x 3 root root 4096 Jun 14 08:27 ar3k-rw-r--r-- 1 root root 153416 Dec 1 2016 ar5523.bin-rw-r--r-- 1 root root 95500 Dec 1 2016 as102_data1_st.hex-rw-r--r-- 1 root root 81820 Dec 1 2016 as102_data2_st.hexdrwxr-xr-x 2 root root 4096 Feb 12 13:29 asihpidrwxr-xr-x 10 root root 4096 Jan 3 09:25 ath10k-rw-r--r-- 1 root root 246804 Jan 6 17:56 ath3k-1.fwdrwxr-xr-x 4 root root 4096 Apr 17 2014 ath6kdrwxr-xr-x 2 root root 4096 Jun 14 08:27 ath9k_htcdrwxr-xr-x 2 root root 4096 Feb 12 13:29 atmel-rw-r--r-- 1 root root 35180 Jan 6 17:56 atmel_at76c504_2958.bin-rw-r--r-- 1 root root 39928 Jan 6 17:56 atmel_at76c504a_2958.bin-rw-r--r-- 1 root root 9726 Apr 25 2016 atmsar11.fwdrwxr-xr-x 2 root root 4096 Jun 14 08:27 atusbdrwxr-xr-x 2 root root 4096 Jun 14 08:27 av7110drwxr-xr-x 2 root root 4096 Jun 14 08:27 bnx2xdrwxr-xr-x 2 root root 4096 Feb 13 14:54 brcm-rw-r--r-- 1 root root 13388 Dec 1 2016 carl9170-1.fwdrwxr-xr-x 9 root root 4096 Jun 14 08:27 carl9170fw-rw-r--r-- 1 root root 412528 Apr 25 2016 cbfw-3.2.1.1.bin-rw-r--r-- 1 root root 414016 Apr 25 2016 cbfw-3.2.3.0.bin-rw-r--r-- 1 root root 414480 Dec 1 2016 cbfw-3.2.5.1.bindrwxr-xr-x 3 root root 4096 Jun 14 08:27 cis-rw-r--r-- 1 root root 107 Dec 1 2016 configuredrwxr-xr-x 2 root root 4096 Jun 14 08:27 cpia2-rw-r--r-- 1 root root 582440 Apr 25 2016 ct2fw-3.2.1.1.bin-rw-r--r-- 1 root root 583688 Apr 25 2016 ct2fw-3.2.3.0.bin-rw-r--r-- 1 root root 584216 Dec 1 2016 ct2fw-3.2.5.1.bin-rw-r--r-- 1 root root 655436 Dec 1 2016 ctefx.bin-rw-r--r-- 1 root root 537160 Apr 25 2016 ctfw-3.2.1.1.bin-rw-r--r-- 1 root root 538712 Apr 25 2016 ctfw-3.2.3.0.bin-rw-r--r-- 1 root root 539144 Dec 1 2016 ctfw-3.2.5.1.bin-rw-r--r-- 1 root root 4120 Dec 1 2016 ctspeq.bindrwxr-xr-x 2 root root 4096 Jun 14 08:27 cxgb3drwxr-xr-x 2 root root 4096 Jun 14 08:27 cxgb4drwxr-xr-x 2 root root 4096 Jun 14 08:27 dsp56k-rw-r--r-- 1 root root 18643 Dec 1 2016 dvb-fe-xc4000-1.4.1.fw-rw-r--r-- 1 root root 12401 Apr 25 2016 dvb-fe-xc5000-1.6.114.fw-rw-r--r-- 1 root root 16497 Dec 1 2016 dvb-fe-xc5000c-4.1.30.7.fw-rw-r--r-- 1 root root 33768 Apr 25 2016 dvb-usb-dib0700-1.20.fw-rw-r--r-- 1 root root 8128 Dec 1 2016 dvb-usb-it9135-01.fw-rw-r--r-- 1 root root 5834 Dec 1 2016 dvb-usb-it9135-02.fw-rw-r--r-- 1 root root 50222 Apr 25 2016 dvb-usb-terratec-h5-drxk.fwdrwxr-xr-x 2 root root 4096 Jun 14 08:27 eadrwxr-xr-x 2 root root 4096 Jun 14 08:27 edgeportdrwxr-xr-x 2 root root 4096 Feb 12 13:29 emi26drwxr-xr-x 2 root root 4096 Jun 14 08:27 emi62drwxr-xr-x 2 root root 4096 Feb 12 13:29 ene-ub6250drwxr-xr-x 2 root root 4096 Feb 12 13:29 ess-rw-r--r-- 1 root root 180776 Apr 25 2016 f2255usb.bindrwxr-xr-x 2 root root 4096 Feb 12 13:29 go7007-rw-r--r-- 1 root root 35068 Apr 25 2016 GPL-3-rw-r--r-- 1 root root 31828 Jan 6 17:56 hfi1_dc8051.fw-rw-r--r-- 1 root root 16848 Dec 1 2016 hfi1_fabric.fw-rw-r--r-- 1 root root 33168 Dec 1 2016 hfi1_pcie.fw-rw-r--r-- 1 root root 5360 Dec 1 2016 hfi1_sbus.fwdrwxr-xr-x 2 root root 4096 Feb 18 2014 hp-rw-r--r-- 1 root root 72684 Dec 9 2016 htc_7010.fw-rw-r--r-- 1 root root 50980 Dec 9 2016 htc_9271.fw-rw-r--r-- 1 root root 1251036 Apr 25 2016 i2400m-fw-usb-1.4.sbcf-rw-r--r-- 1 root root 1334532 Apr 25 2016 i2400m-fw-usb-1.5.sbcf-rw-r--r-- 1 root root 1531932 Apr 25 2016 i6050-fw-usb-1.5.sbcfdrwxr-xr-x 2 root root 4096 Jun 14 08:27 i915drwxr-xr-x 2 root root 4096 Jun 14 08:27 intel-rw-r--r-- 1 root root 209190 Jan 6 17:56 ipw2100-1.3.fw-rw-r--r-- 1 root root 201138 Jan 6 17:56 ipw2100-1.3-i.fw-rw-r--r-- 1 root root 196458 Jan 6 17:56 ipw2100-1.3-p.fw-rw-r--r-- 1 root root 191154 Jan 6 17:56 ipw2200-bss.fw-rw-r--r-- 1 root root 185428 Jan 6 17:56 ipw2200-ibss.fw-rw-r--r-- 1 root root 187836 Jan 6 17:56 ipw2200-sniffer.fwdrwxr-xr-x 2 root root 4096 Feb 12 13:29 isci-rw-r--r-- 1 root root 337520 Apr 25 2016 iwlwifi-1000-5.ucode-rw-r--r-- 1 root root 337572 Apr 25 2016 iwlwifi-100-5.ucode-rw-r--r-- 1 root root 689680 Apr 25 2016 iwlwifi-105-6.ucode-rw-r--r-- 1 root root 701228 Apr 25 2016 iwlwifi-135-6.ucode-rw-r--r-- 1 root root 695876 Apr 25 2016 iwlwifi-2000-6.ucode-rw-r--r-- 1 root root 707392 Apr 25 2016 iwlwifi-2030-6.ucode-rw-r--r-- 1 root root 609892 Dec 1 2016 iwlwifi-3160-10.ucode-rw-r--r-- 1 root root 683996 Dec 1 2016 iwlwifi-3160-12.ucode-rw-r--r-- 1 root root 688616 Dec 1 2016 iwlwifi-3160-13.ucode-rw-r--r-- 1 root root 918212 Dec 1 2016 iwlwifi-3160-16.ucode-rw-r--r-- 1 root root 918268 Dec 9 2016 iwlwifi-3160-17.ucode-rw-r--r-- 1 root root 670484 Apr 25 2016 iwlwifi-3160-7.ucode-rw-r--r-- 1 root root 667284 Apr 25 2016 iwlwifi-3160-8.ucode-rw-r--r-- 1 root root 669872 Dec 1 2016 iwlwifi-3160-9.ucode-rw-r--r-- 1 root root 1384856 Dec 9 2016 iwlwifi-3168-21.ucode-rw-r--r-- 1 root root 1028032 Dec 9 2016 iwlwifi-3168-22.ucode-rw-r--r-- 1 root root 150100 Apr 25 2016 iwlwifi-3945-2.ucode-rw-r--r-- 1 root root 187972 Apr 25 2016 iwlwifi-4965-2.ucode-rw-r--r-- 1 root root 340696 Nov 30 2016 iwlwifi-5000-5.ucode-rw-r--r-- 1 root root 337400 Apr 25 2016 iwlwifi-5150-2.ucode-rw-r--r-- 1 root root 454608 Apr 25 2016 iwlwifi-6000-4.ucode-rw-r--r-- 1 root root 444128 Apr 25 2016 iwlwifi-6000g2a-5.ucode-rw-r--r-- 1 root root 677296 Apr 25 2016 iwlwifi-6000g2a-6.ucode-rw-r--r-- 1 root root 679436 Apr 25 2016 iwlwifi-6000g2b-6.ucode-rw-r--r-- 1 root root 469780 Apr 25 2016 iwlwifi-6050-5.ucode-rw-r--r-- 1 root root 672352 Dec 1 2016 iwlwifi-7260-10.ucode-rw-r--r-- 1 root root 782300 Dec 1 2016 iwlwifi-7260-12.ucode-rw-r--r-- 1 root root 786920 Dec 1 2016 iwlwifi-7260-13.ucode-rw-r--r-- 1 root root 1049284 Dec 1 2016 iwlwifi-7260-16.ucode-rw-r--r-- 1 root root 1049340 Dec 9 2016 iwlwifi-7260-17.ucode-rw-r--r-- 1 root root 683236 Apr 25 2016 iwlwifi-7260-7.ucode-rw-r--r-- 1 root root 679780 Dec 1 2016 iwlwifi-7260-8.ucode-rw-r--r-- 1 root root 680508 Dec 1 2016 iwlwifi-7260-9.ucode-rw-r--r-- 1 root root 736844 Dec 1 2016 iwlwifi-7265-10.ucode-rw-r--r-- 1 root root 880604 Dec 1 2016 iwlwifi-7265-12.ucode-rw-r--r-- 1 root root 885224 Dec 1 2016 iwlwifi-7265-13.ucode-rw-r--r-- 1 root root 1180356 Dec 1 2016 iwlwifi-7265-16.ucode-rw-r--r-- 1 root root 1180412 Dec 9 2016 iwlwifi-7265-17.ucode-rw-r--r-- 1 root root 690452 Apr 25 2016 iwlwifi-7265-8.ucode-rw-r--r-- 1 root root 697828 Dec 1 2016 iwlwifi-7265-9.ucodelrwxrwxrwx 1 root root 21 Dec 9 2016 iwlwifi-7265D-10.ucode -> iwlwifi-7265-10.ucode-rw-r--r-- 1 root root 1002800 Dec 1 2016 iwlwifi-7265D-12.ucode-rw-r--r-- 1 root root 1008692 Dec 1 2016 iwlwifi-7265D-13.ucode-rw-r--r-- 1 root root 1384500 Dec 1 2016 iwlwifi-7265D-16.ucode-rw-r--r-- 1 root root 1383604 Dec 9 2016 iwlwifi-7265D-17.ucode-rw-r--r-- 1 root root 1385368 Dec 9 2016 iwlwifi-7265D-21.ucode-rw-r--r-- 1 root root 1028316 Dec 9 2016 iwlwifi-7265D-22.ucode-rw-r--r-- 1 root root 1745176 Dec 1 2016 iwlwifi-8000C-13.ucode-rw-r--r-- 1 root root 2351636 Dec 1 2016 iwlwifi-8000C-16.ucode-rw-r--r-- 1 root root 2394060 Dec 9 2016 iwlwifi-8000C-21.ucode-rw-rw-r-- 1 michael michael 2120860 Jun 7 11:44 iwlwifi-8000C-23.ucode-rw-r--r-- 1 root root 2389968 Dec 9 2016 iwlwifi-8265-21.ucode-rw-r--r-- 1 root root 1811984 Dec 9 2016 iwlwifi-8265-22.ucodedrwxr-xr-x 2 root root 4096 Jun 14 08:27 kawethdrwxr-xr-x 2 root root 4096 Feb 12 13:29 keyspandrwxr-xr-x 2 root root 4096 Jun 14 08:27 keyspan_pdadrwxr-xr-x 2 root root 4096 Feb 12 13:29 korg-rw-r--r-- 1 root root 118888 Apr 25 2016 lbtf_usb.bin-rw-r--r-- 1 root root 262 Apr 25 2016 lgs8g75.fwdrwxr-xr-x 2 root root 4096 Jun 14 08:27 libertasdrwxr-xr-x 2 root root 4096 Jun 14 08:27 liquidio-rw-r--r-- 1 root root 370 Jan 6 17:56 Makefiledrwxr-xr-x 2 root root 4096 Jun 14 08:27 matroxdrwxr-xr-x 2 root root 4096 Feb 12 13:29 moxadrwxr-xr-x 2 root root 4096 Jun 14 08:27 mrvl-rw-r--r-- 1 root root 45412 Dec 1 2016 mt7601u.bin-rw-r--r-- 1 root root 368220 Dec 1 2016 mt7650.bin-rw-r--r-- 1 root root 13847 Apr 25 2016 mts_cdma.fw-rw-r--r-- 1 root root 14067 Apr 25 2016 mts_edge.fw-rw-r--r-- 1 root root 13847 Apr 25 2016 mts_gsm.fw-rw-r--r-- 1 root root 13769 Apr 25 2016 mts_mt9234mu.fw-rw-r--r-- 1 root root 13769 Apr 25 2016 mts_mt9234zba.fwdrwxr-xr-x 2 root root 4096 Feb 12 13:29 mwl8kdrwxr-xr-x 2 root root 4096 Feb 12 13:29 mwlwifi-rw-r--r-- 1 root root 378832 Dec 1 2016 myri10ge_eth_big_z8e.dat-rw-r--r-- 1 root root 389144 Dec 1 2016 myri10ge_ethp_big_z8e.dat-rw-r--r-- 1 root root 389056 Dec 1 2016 myri10ge_ethp_z8e.dat-rw-r--r-- 1 root root 378736 Dec 1 2016 myri10ge_eth_z8e.dat-rw-r--r-- 1 root root 536192 Dec 1 2016 myri10ge_rss_eth_big_z8e.dat-rw-r--r-- 1 root root 545936 Dec 1 2016 myri10ge_rss_ethp_big_z8e.dat-rw-r--r-- 1 root root 545920 Dec 1 2016 myri10ge_rss_ethp_z8e.dat-rw-r--r-- 1 root root 536176 Dec 1 2016 myri10ge_rss_eth_z8e.dat-rw-r--r-- 1 root root 15664 Jan 6 17:56 NPE-B-rw-r--r-- 1 root root 15664 Jan 6 17:56 NPE-Cdrwxr-xr-x 10 root root 4096 Jan 3 09:25 nvidiadrwxr-xr-x 2 root root 4096 Jun 14 08:27 ositech-rw-r--r-- 1 root root 1845305 Dec 1 2016 phanfw.bin-rw-r--r-- 1 root root 463612 Dec 1 2016 qat_895xcc.bin-rw-r--r-- 1 root root 114176 Dec 1 2016 qat_895xcc_mmp.bin-rw-r--r-- 1 root root 265444 Dec 1 2016 qat_c3xxx.bin-rw-r--r-- 1 root root 114820 Dec 1 2016 qat_c3xxx_mmp.bin-rw-r--r-- 1 root root 398144 Dec 1 2016 qat_c62x.bin-rw-r--r-- 1 root root 114820 Dec 1 2016 qat_c62x_mmp.binlrwxrwxrwx 1 root root 18 Dec 1 2016 qat_mmp.bin -> qat_895xcc_mmp.bindrwxr-xr-x 2 root root 4096 Feb 12 13:29 qcadrwxr-xr-x 2 root root 4096 Jun 14 08:27 qed-rw-r--r-- 1 root root 76802 Apr 25 2016 ql2100_fw.bin-rw-r--r-- 1 root root 84566 Apr 25 2016 ql2200_fw.bin-rw-r--r-- 1 root root 125252 Dec 1 2016 ql2300_fw.bin-rw-r--r-- 1 root root 136038 Dec 1 2016 ql2322_fw.bin-rw-r--r-- 1 root root 264520 Dec 9 2016 ql2400_fw.bin-rw-r--r-- 1 root root 275160 Dec 9 2016 ql2500_fw.bindrwxr-xr-x 2 root root 4096 Jun 14 08:27 r128-rw-r--r-- 1 root root 9452 Dec 1 2016 r8a779x_usb3_v1.dlmem-rw-r--r-- 1 root root 9472 Jan 6 17:56 r8a779x_usb3_v2.dlmemdrwxr-xr-x 2 root root 36864 Jun 14 08:27 radeon-rw-r--r-- 1 root root 1562 Jan 6 17:56 README-rw-r--r-- 1 root root 63 Dec 1 2016 rp2.fw-rw-r--r-- 1 root root 94100 Dec 1 2016 rsi_91x.fw-rw-r--r-- 1 root root 8192 Apr 25 2016 rt2561.bin-rw-r--r-- 1 root root 8192 Apr 25 2016 rt2561s.bin-rw-r--r-- 1 root root 8192 Apr 25 2016 rt2661.bin-rw-r--r-- 1 root root 8192 Jan 6 17:56 rt2860.bin-rw-r--r-- 1 root root 8192 Jan 6 17:56 rt2870.binlrwxrwxrwx 1 root root 10 Apr 25 2016 rt3070.bin -> rt2870.binlrwxrwxrwx 1 root root 10 Apr 25 2016 rt3090.bin -> rt2860.bin-rw-r--r-- 1 root root 4096 Nov 30 2016 rt3290.bin-rw-r--r-- 1 root root 2048 Apr 25 2016 rt73.bindrwxr-xr-x 2 root root 4096 Jun 14 08:27 RTL8192Edrwxr-xr-x 2 root root 4096 Feb 12 13:29 rtl_btdrwxr-xr-x 2 root root 4096 Feb 12 13:29 rtl_nicdrwxr-xr-x 2 root root 4096 Feb 12 13:29 rtlwifilrwxrwxrwx 1 root root 17 Dec 1 2016 s2250.fw -> go7007/s2250-2.fwlrwxrwxrwx 1 root root 17 Dec 1 2016 s2250_loader.fw -> go7007/s2250-1.fw-rw-r--r-- 1 root root 352652 Dec 9 2016 s5p-mfc.fw-rw-r--r-- 1 root root 306312 Dec 9 2016 s5p-mfc-v6.fw-rw-r--r-- 1 root root 343756 Dec 9 2016 s5p-mfc-v6-v2.fw-rw-r--r-- 1 root root 382724 Dec 9 2016 s5p-mfc-v7.fw-rw-r--r-- 1 root root 360576 Dec 9 2016 s5p-mfc-v8.fwdrwxr-xr-x 2 root root 4096 Feb 12 13:29 sb16drwxr-xr-x 2 root root 4096 Jun 14 08:27 scripts-rw-r--r-- 1 root root 816 Dec 1 2016 sdd_sagrad_1091_1098.bindrwxr-xr-x 2 root root 4096 Feb 12 13:29 slicossdrwxr-xr-x 2 root root 4096 Jun 14 08:27 sundrwxr-xr-x 2 root root 4096 Jun 14 08:27 tehuti-rw-r--r-- 1 root root 13765 Apr 25 2016 ti_3410.fw-rw-r--r-- 1 root root 13764 Apr 25 2016 ti_5052.fwdrwxr-xr-x 2 root root 4096 Jun 14 08:27 ti-connectivitydrwxr-xr-x 2 root root 4096 Jun 14 08:27 tigondrwxr-xr-x 2 root root 4096 Jun 14 08:27 ti-keystone-rw-r--r-- 1 root root 51972 Apr 25 2016 tlg2300_firmware.bindrwxr-xr-x 2 root root 4096 Jun 14 08:27 ttusb-budgetdrwxr-xr-x 2 root root 4096 Jun 14 08:27 ueagle-atmdrwxr-xr-x 2 root root 4096 Jun 14 08:27 usbdux-rw-r--r-- 1 root root 999 Apr 25 2016 usbduxfast_firmware.bin-rw-r--r-- 1 root root 1770 Apr 25 2016 usbdux_firmware.bin-rw-r--r-- 1 root root 8192 Jan 6 17:57 usbduxsigma_firmware.bin-rw-r--r-- 1 root root 16382 Apr 25 2016 v4l-cx231xx-avcore-01.fw-rw-r--r-- 1 root root 141200 Apr 25 2016 v4l-cx23418-apu.fw-rw-r--r-- 1 root root 158332 Apr 25 2016 v4l-cx23418-cpu.fw-rw-r--r-- 1 root root 16382 Apr 25 2016 v4l-cx23418-dig.fw-rw-r--r-- 1 root root 262144 Jan 6 17:56 v4l-cx2341x-dec.fw-rw-r--r-- 1 root root 376836 Jan 6 17:56 v4l-cx2341x-enc.fw-rw-r--r-- 1 root root 155648 Jan 6 17:56 v4l-cx2341x-init.mpg-rw-r--r-- 1 root root 16382 Apr 25 2016 v4l-cx23885-avcore-01.fw-rw-r--r-- 1 root root 16382 Apr 25 2016 v4l-cx25840.fw-rw-r--r-- 1 root root 8192 Jan 6 17:56 v4l-pvrusb2-24xxx-01.fw-rw-r--r-- 1 root root 8192 Jan 6 17:56 v4l-pvrusb2-29xxx-01.fwdrwxr-xr-x 2 root root 4096 Jun 14 08:27 vicam-rw-r--r-- 1 root root 11341 Apr 25 2016 vntwusb.fw-rw-r--r-- 1 root root 4082928 Jan 6 17:56 vpu_d.bin-rw-r--r-- 1 root root 131160 Jan 6 17:56 vpu_p.bindrwxr-xr-x 2 root root 4096 Feb 12 13:29 vxge-rw-r--r-- 1 root root 4685 Jan 6 17:56 WHENCE.ubuntu-rw-r--r-- 1 root root 23554 Apr 25 2016 whiteheat.fw-rw-r--r-- 1 root root 5626 Apr 25 2016 whiteheat_loader.fw-rw-r--r-- 1 root root 97824 Dec 1 2016 wsm_22.bindrwxr-xr-x 2 root root 4096 Jun 14 08:27 yamdrwxr-xr-x 2 root root 4096 Jun 14 08:27 yamaha-rw-r--r-- 1 root root 62484 Jan 6 17:56 zd1201-ap.fw-rw-r--r-- 1 root root 70612 Jan 6 17:56 zd1201.fwdrwxr-xr-x 2 root root 4096 Jun 14 08:27 zd1211 </blockquote>Ok, so I have found out that some files have Linux attributes as well as permissions. These attributes can limit file deletion see man chattr. So I did lsattr on the brcm folder contents (I could not delete this folder using rm -rf) and found that all the files had the -e flag. From the manpage I found that you cannot change the -e attribute using chattr. So now my question is:How do you remove files with the -e attribute? I did not receive an answer to the above. I am not sure it can be done. In the end my solution was to reinstall Ubuntu 16.04. I am not sure what caused this error or how to solve it.
linux-firmware_1.157.10 installation error: cannot remove '/lib/firmware/brcm/brcmfmac43362-sdio.bin': Permission denied.
ubuntu;kernel;linux kernel;ext4;firmware
null
_cogsci.44
Elephants and whales have brains that are much larger than those of humans. It is presumed that much of their brain is used up for their larger bodies (after all, there is a allometric scaling between brain weight and body weight in mammals). Do elephants and whales really need super-large somatosensory cortices to map to their larger bodies? Have we mapped out the parts of the brains of a whale or elephant to see which parts of the brain are mapped to which parts of the body?With whales in particular, they don't even have arms or legs, so I wouldn't expect them to have large regions of the brain devoted to, say, fine-motor skills.Yet, it is apparent (to many people) that whales and elephants don't have drastically higher intelligence than humans. So their extra brain regions have to go somewhere. Where do they go to?I asked the same question here, though I'm not convinced by any of the answers provided.
What do the super-large brains of whales and elephants map to?
neurobiology;animal cognition
null
_webmaster.6093
I am very new in this field and I wanted to do SEO for my blog .How many keywords should I select?After selecting the keywords,shouldI always focus on those keywordsonly?I mean whatever the post is Imust add those keywords?or should itdepend upon the posts?
How many keywords should be selected for SEO?
seo
There is no number of keywords for a blog or a website. It's a number per page as it's the pages that are ranked, not entire sites or blogs. Each page should be about a very specific topic so the number of keywords it targets, intentionally or not, shouldn't be very large. If you find a page covers a large number of keywords that may be a sign it needs to be split up into multiple pages or posts. I'm not going to give you a specific number of keywords to target per page as not only isn't there a set number, but you should be writing your content for your users and not focusing on how you can fit keywords into the content. If you write your content properly you'll find that approximately a handful of popular/semi-popular keywords will be targeted naturally for you with a bunch of long tail keywords sprinkled in, too.
_cogsci.5167
It's fairly well documented that childhood trauma (such as chronic illness) can lay the neurochemical groundwork for conditions like depression later in life. A paper, The link between childhood trauma and depression: insights from HPA axis studies in humans, states:We here summarize results from a series of clinical studies suggesting that childhood trauma in humans is associated with sensitization of the neuroendocrine stress response, glucocorticoid resistance, increased central corticotropin-releasing factor (CRF) activity, immune activation, and reduced hippocampal volume, closely paralleling several of the neuroendocrine features of depression. Neuroendocrine changes secondary to early-life stress likely reflect risk to develop depression in response to stress, potentially due to failure of a connected neural circuitry implicated in emotional, neuroendocrine and autonomic control to compensate in response to challenge.Late Consequences of Pediatric Chronic Illness has some related findings too.I'm interested in what psychological groundwork might be also laid by early life stress such as childhood illness, also contributing to the development of mental health conditions. For example, I've read of cases where chronic childhood pain may cause the patient to have an unhealthily high acceptance (not tolerance) of stress as an adult, meaning they persist in stressful situations where others would not. They've learned that pain is to be accepted and worked through to an extent beyond which many would think reasonable, and this may lead to stress related illness.Are there any other maladaptive behaviours, cognitive distortions or similar that commonly occur in adults who experienced chronic childhood illness?(Also interested in evidence related to my anecdotal example.)EDIT (31st Dec 2013): Thanks to caseyr547 for his answer. To clarify, I'm particularly interested in answers using the behavioural, cognitive and psychodynamic models, as opposed to the biological or stress-vulnerability models.
What maladaptive behaviours or cognitive distortions develop as a result of chronic childhood illness?
developmental psychology;depression
null
_unix.242748
I am having trouble figuring out how to determine the linux kernel version by analyzing a memory snapshot from a linux VM. I have used hexdump to examine the binary but can't find anything that would explicitly tell me what the version is. Any help would be appreciated.
How to determine kernel version from linux vm snapshot
linux;virtualbox;forensics
null
_cs.7894
I need help figuring the potential function for a max heap so that extract max is completed in $O(1)$ amortised time. I should add that I do not have a good understanding of the potential method. I know that the insert function should pay more in order to reduce the cost of the extraction, and this has to be in regards to the height of the heap (if $ \lfloor \log(n) \rfloor $ gives the height of the heap should the insert be $2\log(n)$ or $ \sum_{k=1}^n 2\log(k) $)
Potential function binary heap extract max O(1)
data structures;runtime analysis;heaps;amortized analysis
Try the following:The weight $w_i$ of an element $i$ in the heap $H$ is its depth in the corresponding binary tree. So the element in the root has weight zero, its two children have weight 1 and so on. The you define as potential function$$\Phi(H)=\sum_{i\in H}2 w_i.$$Let us now analyze the heap operations. For insert you add a new element add depth $d$ at most $\log(n)$. This increases the potential by $2d$, and can be done in $O(1)$ time. Then you bubble up the new heap element to assure the heap-property. This takes $O(\log n)$ time and leaves $\Phi(H)$ unchanged. Thus the costs for insert are $O(\log(n)+\Delta(\Phi(H)))=O(\log n)$.Now consider the extractMin. You take out the root and replace it by the last element in the heap. This decreases the potential by $2\log(n)$, thus you can afford to repair the heap property, and therefore the amortized costs are now $O(1)$.If you have a general question for the potential function you should pose this as a different question.
_unix.336670
I've been fiddling with neovim color schemes for a while now, and cannot make them look same as on previews.I'm using terminal.app on osx, and thought it was 256 color cap problem, so I moved to iterm2 which has true color support - while it improved some things, color schemes are nowhere near to screenshots I see!this is how solarized theme looks in iterm2 + neovimthis is nothing close to https://github.com/altercation/vim-colors-solarized screenshots!I've used google foo but without success, surely there is a way to get colors right. Any ideas? ***************************************************************************** Plug install packages***************************************************************************** Specify a directory for pluginscall plug#begin('~/.config/nvim/plugged')Plug 'tomasr/molokai'Plug 'dracula/vim'Plug 'justb3a/vim-smarties'Plug 'tyrannicaltoucan/vim-quantum' let g:quantum_black = 1Plug 'mhartington/oceanic-next'Plug 'altercation/vim-colors-solarized' Plug 'vim-scripts/CSApprox'Plug 'ctrlpvim/ctrlp.vim'Plug 'scrooloose/nerdtree'Plug 'airblade/vim-gitgutter'Plug 'bronson/vim-trailing-whitespace'Plug 'editorconfig/editorconfig-vim'Plug 'Raimondi/delimitMate'Plug 'scrooloose/syntastic'Plug 'Yggdroot/indentLine'Plug 'tpope/vim-commentary'Plug 'sheerun/vim-polyglot'Plug 'valloric/matchtagalways' Initialize plugin systemcall plug#end()***************************************************************************** Visual Settings*****************************************************************************set numberset rulerset nowraplet $NVIM_TUI_ENABLE_TRUE_COLOR=1 set termguicolors unfortunately doesn't work in terminal.app - needs true color support, like iterm2 but it lags and diff in visuals is not that much so sticking to terminal.app for nowset background=darkcolorscheme solarized***************************************************************************** NERDTree config***************************************************************************** open NERDTree automatically when vim starts up on opening a directoryautocmd StdinReadPre * let s:std_in=1autocmd VimEnter * if argc() == 1 && isdirectory(argv()[0]) && !exists(s:std_in) | exe 'NERDTree' argv()[0] | wincmd p | ene | endif keep focus on NERDTree when opening a directoryautocmd VimEnter * wincmd p close vim if the only window left open is a NERDTreeautocmd bufenter * if (winnr($) == 1 && exists(b:NERDTree) && b:NERDTree.isTabTree()) | q | endif***************************************************************************** Optimizations*****************************************************************************set lazyredrawlet g:python_host_skip_check = 1let g:python3_host_skip_check = 1***************************************************************************** syntastic*****************************************************************************let g:syntastic_always_populate_loc_list = 1let g:syntastic_auto_loc_list = 1let g:syntastic_check_on_open = 1let g:syntastic_check_on_wq = 0***************************************************************************** yank and cut to osx clipboard*****************************************************************************noremap YY +y<CR>noremap XX +x<CR>***************************************************************************** indent***************************************************************************** tabsset listchars=tab:\ ,eol:set list spaceslet g:indentLine_enabled = 1let g:indentLine_concealcursor = 0let g:indentLine_char = ''let g:indentLine_faster = 1set tabstop=2***************************************************************************** matchtagalways*****************************************************************************let g:mta_filetypes = { 'html' : 1, 'xhtml' : 1, 'xml' : 1, 'jinja' : 1, 'php': 1 }***************************************************************************** ctrlp*****************************************************************************set wildignore+=*.o,*.obj,.git,*.rbc,*.pyc,__pycache__let g:ctrlp_custom_ignore = '\v[\/](node_modules|target|dist)|(\.(swp|tox|ico|git|hg|svn))$'
cannot get color schemes to display correctly in neovim
vim
null
_softwareengineering.173186
What are the best ways of gathering information on events (any type) from the internet ?Keeping in mind that different websites will present information in different ways.I was thinking 'smart' web crawlers, but that can turn out to be extremely challenging, simply because of the hugely varied ways that different sites present their information.Then I was thinking of sifting through the official twitter feeds of organisations, people with knowledge of events .. etc and look for the event hash tag, grab the tweet and dissect it to grab the relevant information about the event.Information I am interested in gathering is: Date and Time of Event, Address where Event is being held, and any Celebrities (or any famous people) attending the event (if any).The reason to ask here is my hope that experienced folk will open my eyes to things I've missed, which I am sure I have.
Ways of Gathering Event Information From the Internet
artificial intelligence;social networks;web crawler
null
_webmaster.8093
I uploaded a tif image into SharePoint Designer but it will not display on the web page. Does it have to be jpeg? I have uploaded jpeg images and they work fine but I erased a background on an image and saved it as a tif.Thanks
Does SharePoint Designer only use jpeg images and not tif images?
website design
null
_cseducators.2730
I have a class undergraduate students (2nd and 3rd year) who have had at least two terms of college/university level programming courses using a procedural programming language (typically C++), and often a term or two in other languages, also procedural. They have usually, though not a requirement, taken programming in high school, which was also based on one or another of the procedural languages. In the other computer classes they might have taken, or be taking concurrently, they have a procedural language as a secondary exposure. For example, the web design classes use JavaScript and PHP extensively. Bottom line is that these students are well versed (indoctrinated) in the imperative paradigm.Now I have to teach them functional programming, and help them to adjust to a new way of thinking about the problems and solutions. In other words, I want them to be able to write a Scheme program, not a C++ program translated into Scheme.So then, the question here is this: in the switch from procedural to functional programming, what are the critical habits to change in the students' minds so that they are able to grasp the functional paradigm enough to get them programming in the new language rather than writing old programs in the new style?
What 'procedural' habits to break when teaching 'functional' programming?
functional programming;programming paradigms;imperative programming;scheme
I undertook this study myself about a year ago. I started working through the Programming Languages MOOCs on Coursera (Part A Part B Part C), which are based on a UW course of the same name.I didn't really know what I was getting into, but it sounded interesting. Before I knew it, I was learning a radically different approach to programming first with SML and now with Racket (Ruby is up next). Here are some of the key ideas that were a major departure from my having programmed in C and Python:Avoid mutation. Over and over again the professor emphasizes why mutation is a bad thing (or at least potentially problematic). From the world of C where I learned about declaring and updating variables almost immediately, this forced me to think differently about the information my programs contained and processed.Don't call them variables. As a continuation of the above, they aren't variables (because after all they shouldn't vary because they don't mutate); rather, call them value bindings. Moreover, these value bindings exist in an environment. This latter idea is essential (and has only recently sunk in) for understanding function closures.Think recursively. Of the 3+ assignments I've completed for Part A and Part B, thinking recursively has been an essential component for creating elegant, efficient solutions. Indeed, in some cases it's been the only way to solve a problem thanks to the goal of avoiding mutation. This is not to say that recursion doesn't exist in other languages (because it obviously does), but it's been a more fundamental element to the design of solutions using functional programming languages.Those are my big three; I'm sure there are more. Obviously understanding anonymous functions, higher-order functions, first-class functions, and all that comes with them (e.g. currying) is what functional programming entails. However, this content wasn't a rewiring of old habits in the same way that the above points were.For what it's worth, I appreciate what C has taught me about what happens on a lower level, but I think studying a functional language qua an approach to programming has made me an overall better programmer.
_datascience.12811
Can not find any example in Python for training XOR function using SHOGUN library.By otherwise, is there any other easy example for feedforward neuralnetwork training with Shogun for Python?
How to train ANN with Python using SHOGUN Libs?
python;neural network;training
null
_unix.2126
I notice a weird (well, according to me) thing about passwords. For example, if I type an incorrect password during login, there will be a few seconds' delay before the system tells me so. When I try to sudo with a wrong password I would also have to wait before the shell says Sorry, try again.I wonder why it takes so long to recognize an incorrect password? This has been seen on several distributions I use (and even OSX), so I think it's not a distribution specific thing.
Why is there a big delay after entering a wrong password?
security;password;authentication;pam
This is a security thing, it's not actually taking long to realize it. 2 vulnerabilities this solves:this throttles login attempts, meaning someone can't pound the system as fast as it can go trying to crack it (1M attempts a sec? I don't know).If it did it as soon as it verified your credentials were incorrect, you could use the amount of time it took for it to invalidate your credentials to help guess if part of your credentials were correct, dramatically reducing the guessing time.to prevent these 2 things the system just takes a certain amount of time to do it, I think you can configure the wait time with PAM ( See Michaels answer ).Security Engineering ( 2ed, amazon | 1ed, free ) gives a much better explanation of these problems.
_unix.360424
I have a user that is used to run my server. Ideally, it would only have write access to the server's log files, and only have read access to the document-root. How would I do this on FreeBSD 11?
How to Only Allow Users Access to Specific Files?
permissions;freebsd;webserver
null
_cs.56469
From the Cormen book I was studying the chapter focused on the red black tree. I was particularly interested in why the procedures for insert/delete fixup works (namely a formal proof).I report both the algorithms, taken from the book:The book gives a generic explanation of why they works, but doesn't give any formal proof. Could you suggest me how to prove the result, or could where I find the proof? For example if I focus on the insert, I would look at the node $z$ and I would assume by induction that one subtree has black height $h-1$ while the other has black height $h$, then I would show that after an iteration both subtree have black height $h$. I would try something similar for the delete procedure.I'm not entirely sure that this is the best way to prove the correctness, and I can't actually find a formal proof of the result.(The main reason is actually that every time I read the book and specifically such chapter I just try to memorize the procedures. Since this kind of tree implementation is quite common I think is time I understand why it works.
Red black tree - Insert/Delete proof of correctness
binary trees;search trees
null
_unix.361216
I have to units that I want to run one after the other with the help of systemd:A mount unit mnt-data.mount[Unit]Description=nfs mount scriptAfter=network-online.target[Mount]What=some_ip:/media/dataWhere=/mnt/dataOptions=hard,async,intr,fscType=nfs[Install]WantedBy=multi-user.targetAnd some code to execute after the mount is done with my-unit.service:[Unit]Description=Do some Cool stuffDocumentation=Read the code !Requires=mnt-data.mountAfter=mnt-data.mount[Service]Type=oneshotExecStart=/usr/local/sbin/some_script[Install]WantedBy=default.targetThe code is executed, but I get the following error in syslog:systemd[1]: [/etc/systemd/system/my-unit.service:5] Failed to add dependency on mnt-data.mount, ignoring: Invalid argumentI am worry that my-unit.service could be executed before mt-data.mount is finished. What is wrong with those two!I also get the following logs from journalctl and systemctl:$ systemctl status my-unit.service my-unit.service - Do some Cool stuffLoaded: loaded (/etc/systemd/system/my-unit.service; enabled; vendor preset: enabled)Active: inactive (dead) since Wed 2017-04-26 10:56:16 EDT; 1 day 11h agoProcess: 831 ExecStart=/usr/local/sbin/some_script (code=exited, status=0/SUCCESS)Main PID: 831 (code=exited, status=0/SUCCESS)Apr 26 10:56:16 sapin systemd[1]: Starting Do some Cool stuff...Apr 26 10:56:16 sapin some_script[831]: dataApr 26 10:56:16 sapin some_script[831]: testingApr 26 10:56:16 sapin systemd[1]: Started Do some Cool stuff.and$ journalctl -u my-unit.service -- Logs begin at Wed 2017-04-26 10:56:15 EDT, end at Thu 2017-04-27 22:17:01 EDT. --Apr 26 10:56:16 sapin systemd[1]: Starting Do some Cool stuff...Apr 26 10:56:16 sapin some_script[831]: dataApr 26 10:56:16 sapin some_script[831]: testing Apr 26 10:56:16 sapin systemd[1]: Started Do some Cool stuff
systemd Failed to add dependency on my-point.mount
systemd;systemd mount
null
_unix.217595
In sys-v-init, to query a service's status you can use the service command and do a service $NAME_OF_SERVICE status. In systemd, how do you query a service's status?
systemd: How do you query a service's status?
systemd;services
To query the status of a service in systemd you can do:systemctl status $NAME_OF_SERVICE
_codereview.40230
I have two functions to count the number of set '1' bits in the first offset bits of either a 64 bit number, or a bitmap struct.After some profiling, particularly the latter is quite a bottleneck in our system.What can we do to make it faster?#define POPCOUNT16(x) __builtin_popcount(x)#define POPCOUNT64(x) __builtin_popcountl(x)static __always_inline __constant int32 count64(int64 const bitmap, int32 const offset) { return offset == 0 ? 0 : POPCOUNT64(bitmap & (0xffffffffffffffffUL << (64 - offset)));}typedef struct { int64 hi; int16 lo;} __packed int80;static __always_inline __constant int32 countBitmap(int80 const bitmap, int32 const offset) { int32 count = 0; if (offset > 0) { count += POPCOUNT64(bitmap.hi & (0xffffffffffffffffUL << (sizeof (bitmap.hi)*8 - MIN(offset, sizeof (bitmap.hi)*8)))); if (offset > sizeof (bitmap.hi)*8) count += POPCOUNT16(bitmap.lo & ((int16)0xffff << (sizeof (bitmap.hi)*8+sizeof (bitmap.lo)*8 - offset))); } return count;}
Efficiently counting '1' bits in the first n bits
optimization;c;performance;bitwise
null
_webmaster.88635
I know there are similar questions. But they either was not what I was looking for OR I did not understand them fully, therefore I am asking here.My situationAt the moment I am using rel prev and rel next as pagination.<link rel=prev href=http://www.example.com/category/blablabla/page/2 /><link rel=next href=http://www.example.com/category/blablabla/page/4 />I currently also add a canonical link which refers to the first page, i.e:<link href=http://www.example.com/category/blablabla rel=canonical>The problemThe thing is that the first page only has 20 items (as all other pages).With this canonical link only to the first page get indexed by Google.I would like all the pages to get indexed, because important content get lost in those pages.Should I just change the canonical link to the current URL? i.e the current page, in this case:<link href=http://www.example.com/category/blablabla/page/3 rel=canonical>Or should I do something else, if yes then what?
Should I use a canonical link which refers to the current URL in a pagination?
seo;indexing;google index;canonical url;pagination
you shouldn't set your canonical to the first, but to the current page, like big G said.
_cstheory.3230
Counting the number of perfect matchings in a bipartite graph is immediately reducible to computing the permanent. Since finding a perfect matching in a non-bipartite graph is in NP, there exists some reduction from non-bipartite graphs to the permanent, but it may involve a nasty polynomial blowup by using Cook's reduction to SAT and then Valiant's theorem to reduce to the permanent.An efficient and natural reduction $f$ from a non-bipartite graph $G$ to a matrix $A = f(G)$ where $\operatorname{perm}(A) = \Phi(G)$ would be useful for an actual implementation to count perfect matchings by using existing, heavily-optimized libraries that compute the permanent. Updated: I added a bounty for an answer including an efficiently-computable function to take an arbitrary graph $G$ to a bipartite graph $H$ with the same number of perfect matchings and no more than $O(n^2)$ vertices.
Is there a direct/natural reduction to count non-bipartite perfect matchings using the permanent?
graph theory;counting complexity;reductions;permanent
I would say that a simple reduction to bipartite matching is highly unlikely. Firstly, it would give an algorithm for finding a perfect matching in a general graph using the Hungarian method. Hence, the reduction should contain all the complexity of the Edmond's blossom algorithm. Secondly, it will give a compact LP for perfect matching polytope and hence the reduction should not be symmetric (which are ruled out by a result of Yannakakis) and inherently very complicated.