id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_unix.212085 | I use openjdk for my work, but sometimes I need oracle's JRE. I thought that I could use 'env' command for this, but can't figure out why it's not working.I have openjdk in /usr/lib/jvm/java-1.8.0-openjdk-amd64 and oracle's jdk in /usr/lib/jvm/jdk-8-oracle-x64when I'm running: env JAVA_HOME=/usr/lib/jvm/jdk-8-oracle-x64 java -versioni get:java version 1.7.0_75OpenJDK Runtime Environment (IcedTea 2.5.4) (7u75-2.5.4-3)OpenJDK 64-Bit Server VM (build 24.75-b04, mixed mode)but if i try: env JAVA_HOME=/usr/lib/jvm/jdk-8-oracle-x64 env|grep JAVAI see:JAVA_HOME=/usr/lib/jvm/jdk-8-oracle-x64I have 'feeling' that this is somehow related to process forking and inheritance. I know that i can simply use export name=variable command and etc. But would appreciate get explanation is it possible with 'env' command and how. Thank you! (I am using debian linux, unstable repo) | How to change JAVA_HOME temprorary with env command | linux;debian;environment variables;java | It is possible to do that using the env command, however you have to use a little work around and call sh, see the following code snippets:# env var=bla echo $var># env var=bla sh -c 'echo $var'> bla# echo $var>You can find more information using on info coreutils 'env invocation'Unfortunatelly I can't give you any further explanations why it only works using sh -c ''.It seems env has a rather non-intuitive behavior...# env PATH= echo $PATH> env: echo: No such file or directory# env PATH= /bin/echo $PATH> /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin |
_cogsci.15467 | Does anyone know papers indicating that too much information is bad for the memory or even more precise - that too much learning matter is bad for the success of a student? I know a bit of the mechanism of how memory works (Papez circle, Hippocampus etc.) but not too much. So if there is any mechanism that also would indicate my hypothesis, could you help me with that?Thanks a lot! | Are there any papers showing that too much learning matters is bad for memory? | learning;memory;mental exhaustion | null |
_unix.117323 | TL;DR; version - How do I undo text that was pasted in from my OS copy buffer without undoing other text that was typed in since I went into insert mode?Longer description:Put something in your OS copy buffer (e.g. highlight some text and do Command-c on Mac)Go into insert mode in vim ( i )Type something ( e.g. asdf)Without exiting insert mode, paste from your copy buffer into vim ( Command-v on Mac)Hit escape Try to undo the paste ( u )It undoes everything from the last time you went into insert mode. In otherwords, it clears out asdf plus all the text I pasted in. How do I just undo the text that pasted in? Do I have to always go out of insert mode and back in before I paste text just to have the option to undo the pasted text? | How do I only undo pasted text in vim? | vim;osx | One way is explicitly dropping out and back into insert mode before the paste. If you extend the paste commands, you can also automatically set an undo point before the paste: Any text fragment pasted in insert mode should be undone separately, without destroying what was typed before.inoremap <C-R> <C-G>u<C-R>The above is for the built-in i_CTRL-R command. I don't know how Command-v is implemented in MacVim, but prepending <C-G>u to the :imap command should achieve the same effect. |
_codereview.74166 | I based this implementation on CountedPtr in The C++ Standard Library book by Nicolai Josuttis (page 222) and also available online here.I know that I can use the C++11 smart pointers but this is a learning exercise and also for some projects an earlier compiler must be used.I didn't understand the need for the actual reference counter to be a pointer so I just used a standard integer. Maybe that introduces a bug, not sure. My main concern is about the object lifecycle. Does the reference counter as a straight integer cause a bug? Any feedback will be much appreciated.Here is the smart pointer class:#ifndef SMARTPOINTER_HPP__#define SMARTPOINTER_HPP__#include <iostream>template<typename T>class sp {public: sp(T* ptr) : ptr_(ptr), ref_cnt_(1) { std::cout << sp ctor: << ptr_ << , ref_cnt_: << ref_cnt_ << std::endl; } T& operator*() { return *ptr_; } T* operator->() { return ptr_; } sp(const sp<T>& rhs) : ptr_(rhs.ptr_), ref_cnt_(rhs.ref_cnt_) { ++ref_cnt_; std::cout << sp copy ctor: << ptr_ << , ref_cnt_: << ref_cnt_ << std::endl; } sp& operator=(const sp& rhs) { if(this != &rhs) { *this = rhs; ++ref_cnt_; std::cout << sp assignment: << ptr_ << , ref_cnt_: << ref_cnt_ << std::endl; } return *this; } ~sp() { if(ptr_) std::cout << ~sp: << ptr_ << , ref count: << ref_cnt_ << std::endl; --ref_cnt_; if(ref_cnt_ == 0) delete ptr_; } bool operator==(const T& that) const { return ptr_ == that.ptr_; } bool operator==(T* that) const { return ptr_ == that; } bool operator!=(const sp& that) const { return ptr_ != that.ptr_; } bool operator!=(sp* that) const { return ptr_ != that; }private: T* ptr_; unsigned ref_cnt_;};#endif //SMARTPOINTER_HPP__Here is my code to exercise:#include <iostream>#include <string.h>#include smart_pointer.hppclass name {public: name(const char* label) : label_(label) {} const char* get_name() const { return label_; } unsigned length() const { return strlen(label_); }private: const char* label_;};int main() { { std::cout << Test with ints\n; sp<int> myptr1 = new int(3); *myptr1 = 4; std::cout << number: << *myptr1 << std::endl; sp<int> myp2(myptr1); sp<int> myp3(myptr1); sp<int> myp4 = myptr1; } { std::cout << Test with name object\n; sp<name> myname = new name(Andrew); std::cout << myname->get_name() << has length: << myname->length() << std::endl; sp<name> myname2(myname); } return 0;}I get this output:Test with intssp ctor: 004C7A80, ref_cnt_: 1number: 4sp copy ctor: 004C7A80, ref_cnt_: 2sp copy ctor: 004C7A80, ref_cnt_: 2sp copy ctor: 004C7A80, ref_cnt_: 2~sp: 004C7A80, ref count: 2~sp: 004C7A80, ref count: 2~sp: 004C7A80, ref count: 2~sp: 004C7A80, ref count: 1Test with name objectsp ctor: 004C7A80, ref_cnt_: 1Andrew has length: 6sp copy ctor: 004C7A80, ref_cnt_: 2~sp: 004C7A80, ref count: 2~sp: 004C7A80, ref count: 1 | Yet another smart pointer implementation for learning | c++;reinventing the wheel;pointers | Main problem with the reference counter:As it stands right now, your code will eventually leak or try to delete the same pointer more than once. You are keeping a diferent reference count inside each smart pointer, which is not synchronised, so smart pointers sharing the same object can have different counts for the same memory. Take this simple example, similar to your second one:sp<MyObject> ptr1 = new MyObject(); // ptr1.ref_cnt = 1sp<MyObject> ptr2 = ptr1; // ptr1.ref_cnt = 1, ptr2.ref_cnt = 2// Now we have two different counts for the same object!Once you pass the copy constructor or assignment operator, the reference count of the original pointer is left unaltered. This cannot possibly end well. That's why in the original example you've linked the author used a pointer for the reference counter as well, so that any smart pointer sharing ownership of an object can also point to the same counter. Once the owned object is to be freed, the last pointer also frees the counter.One cleaver trick to avoid allocating the counter in a separate new call is to allocate both the object and the counter as the same block of raw bytes, then adjust the pointers and construct the object on the remaining memory. This is how some implementations of std::make_shared() work. Once you fix the counter issue, you might want to try this optimization.Other issues with the code:This destructor seems broken: ~sp() { if(ptr_) std::cout << ~sp: << ptr_ << , ref count: << ref_cnt_ << std::endl; --ref_cnt_; if(ref_cnt_ == 0) delete ptr_; }Didn't you forget to wrap the first if with curly braces? This seems like a case where the indenting of the code tries to tell the reader one thing, while the code does a different thing. The first if only applied to the cout call. To avoid this confusion, it is a good idea to always provide { } even for single line control statements. So this is how I believe you intended to write, since it wouldn't make sense decrementing the counter if the pointer is null:~sp() { if(ptr_) { std::cout << ~sp: << ptr_ << , ref count: << ref_cnt_ << std::endl; --ref_cnt_; if(ref_cnt_ == 0) { delete ptr_; } }}The comparison operators that take a raw pointer should take that pointer by const T*, to make clear that they do not attempt to modify the pointed object.You'll probably also want to provide overloads of operator * and -> that are const and return const pointer and reference. Otherwise you aren't able to call those on a const sp<T>.Your class still requires a lot of tuning and polishing to be anywhere near usable. If you plan on taking it a step further, I recommend reading Modern C++ Design. The book has a dedicated chapter on Smart Pointers. It is very detailed and well written and I think it is still one of the best references out there on SPs, even though it was released before C++11. |
_unix.81977 | There is an OpenBSD 5.3 server. It only listens on port 443 with an apache (on higher port an sshd listens, but port knocking is used).How can I hide the servers operating system/webserver to be recognized as something else thatn OpenBSD. ex.: some Linux distribution, etc. | How to hide an OpenBSD 5.3 server as it would be a windows server or something else? | security | If you want to get a server to look like something else, you should have an awareness of passive OS fingerprinting. Michal Zalewski's p0f v3 could be used to unmask your server based on TCP handshake's initial SYN packet, or on TCP connection take down.When acting as a NAT router, OpenBSD can scrub routed packets to make OS identification harder, but it's not clear to me if OpenBSD can mark up its own TCP packets to avoid such passive identification. |
_unix.354150 | I don't seem to be able to use umask to make sure my default file permission is 755. I need it because every time I check out a script file on CentOS from my version control, it doesn't have the x permission and I have to manually chmod +x script.sh. How to umask to get default file permission of 755? Why is the umask calculation for files based off of 666 as the maximum permission for files and not 777? | How to umask to get default file permission of 755? | permissions;umask | null |
_webmaster.89978 | So, we have a functionality on example.com/folder that we decided to make as separate site and we're in need of moving it to a new domain (brand it)...This is what I'm going to make SEO wise (unordered list):make a 301 redirect map to redirect on a page levelmake sitemaps both for old site's folder and new domain (to make indexing faster)migrate all content to new domainregister new domain in GSC (to submit sitemap...)What other steps do I need to take to keep SE traffic and ranking positions that we currently have and have our new domain indexed as fast as possible?We can't use change of address in GSC because we don't completely change domains. We are only moving a subdirectory from one domain to a new domain, we aren't completely moving everything from one domain to another. | Moving folder's content to a new domain, what SEO steps to take? | seo;google search console;301 redirect;sitemap;indexing | You have all the steps correct, but it won't prevent a temporary (up to 8 month) drop in SEO traffic.Google does not support migrating an entire folder to its own new domain. When you do so, your new domain name will enter the sandbox for a new domain and Google won't trust it as much as the content in the folder on your main domain for some months.For entire sites that are changing domain names, Google has a change of address tool in Google Search Console that will bypass the sandbox period. Google does not allow this tool to be used for a single folder, only for an entire domain. |
_webmaster.34785 | refer to this URL: http://imagemechanics.com.au/Every page seems to have its own unique URL, but the /#!/ leads me to believe it's all one giant page with anchor tags defining the sections. Is each section truly its own .html page or is it just one page? | How is this website's architecture structured? | javascript;jquery;architecture | It's not a single page. (This should be obvious just from viewing source.)There are separate documents, like this one, being loaded via Ajax. In Firefox, open Firebug and enable the Net tab. When you click the navigation links, you'll be able to see the GET requests for them. |
_webmaster.95708 | I've built a website that's been slowly increasing its users/day and now gets about 3k each day. The site uses a database to fill in some fields on the page and is optimized to do well in searches (which it does).A week ago I noticed that I had a big drop in users and see that it's because the site isn't showing up in searches as much as before. I'm including a screen capture of WebMasters Tools to show what I'm seeing.I've looked all over WebMaster Tools and Analytics to figure out why this is happening. I don't have any messages from Google. I do see a handful of errors (e.g. a few pages have problems on mobile) that I'll address, but I don't think that's the reason.Can anyone suggest any reasons why I'm seeing such a big drop in traffic? What should I look at to try to figure this put? | Huge drop in search traffic - I don't see any reasons for this | google;google analytics;google search console;search | null |
_softwareengineering.186242 | I'd like to read the documentation of Azure Active Directory on my kindle (or similar device), but don't want to use Print to Kindle for each and every page.Is the Microsoft documentation for this technology available in other formats? (.chm, PDF, etc).If an alternative format is available, then I can adapt that to my needs.http://msdn.microsoft.com/en-us/library/jj673460.aspx | Is MSDN / Azure Active Directory information available in different formats? | documentation;microsoft;azure;msdn;active directory | There is some information in e-book format (English and other languages) located here:E-Book Gallery for Microsoft TechnologiesDownload content for ASP.NET, Office, SQL Server, Windows Azure, SharePoint Server and other Microsoft technologies in e-book formats. Reference, guide, and step-by-step information are all available. All the e-books are free. New books will be posted as they become available.Not sure the all information you were looking for is here. It also appears that it's necessary to create a profile to download books. I am a Microsoft employee and write developer documentation for the MSDN site, we don't republish all our online documentation in e-book formats. MSDN is trying to use a continuous publishing model for online content and encourages users to go online to get the latest content. To my knowledge very little of the content for developers is being published in e-book format. |
_softwareengineering.35293 | A few months ago my company found itself with its hands around a white-hot emergency of a project, and my entire team of six pulled basically a five week crunch week. In the 48 hours before go-live, I worked 41 of them, two back to back all-nighters. Deep in the middle of that, I posted what has been my most successful question to date.During all that time there was never any talk of failure. It was always get it done, regardless of the pain. Now that the thing is over and we as an organization have had some time to sit back and take stock of what we learned, one question has occurred to me. I can't say I've ever taken part in a project that I'd say had failed. Plenty that were late or over budget, some disastrously so, but I've always ended up delivering SOMETHING.Yet I hear about failed IT projects all the time. I'm wondering about people's experience with that. What were the parameters that defined failure? What was the context? In our case, we are a software shop with external clients. Does a project that's internal to a large corporation have more space to fail? When do you make that call? What happens when you do?I'm not at all convinced that doing what we did is a smart business move. It wasn't my call (I'm just a code monkey) but I'm wondering if it might have been better to cut our losses, say we're not delivering, and move on. I don't just say that due to the sting of the long hours--the company royally lost its shirt on the project, plus the intangible costs to the company in terms of employee morale and loyalty were large. Factor that against the PR hit of failing to deliver a high profile project like this one was... and I don't know what the right answer is. | Failed Project: When to call it? | project management;failure | The concept of failure is really a business related call. If a commercial project costs more than the money it brings in, that project would be considered a failure. If an open source project cannot build a community around the code to help maintain it and care for it, that open source project failed.I've been involved in projects were we delivered everything on time and within budget, but the business development team failed to get follow on work. From a business perspective the project failed, although what we delivered was well received and liked.In situations like yours, the company has to make some hard decisions. If they want the project to succeed, then they need to learn some lessons:Failure to plan appropriately will cause undue stress on your team, and ultimately lead to a failed projectA stressed team will retaliate with high turnover--and eventually you won't be able to get good people to join the company.Emergencies happen, but find what caused the emergency and change your practices to avoid that emergency in the future.Any company that doesn't learn from its mistakes will repeat history quite often. I would take that as a sign that it is time to find another company. |
_cstheory.37681 | The complexity of my algorithm is in $O(\frac{p^p}{p!}(\frac{n}{p})^k)$ for any $p=o(n)$ and $k>1$.How can I simplify this complexity while removing this $p$?For instance, for $p=2$ the complexity is in $O((\frac{n}{2})^k)$, but for $p=3$ it is in $O((\frac{n}{3})^k)$ which is better.Can I have a formula without fixing $p$ and that would be always the best? | Simplifying a parametrized complexity given that a parameter is in $o(n)$ | parameterized complexity | I've discussed with an ``FPT and XP guy'', we found that I shouldn't have written the problem in such a way. Let me rewrite it.This is related to graph algorithms. Chiba and Nishizeki showed that it is possible to list $(k+2)$-cliques (cliques on $k+2$ nodes) in time $O(m \cdot a^k)$ where a is the arboricity of the graph and $m$ the number of edges in the graph.http://www.ecei.tohoku.ac.jp/alg/nishizeki/sub/j/DVD/PDF_J/J053.pdfWe have designed an algorithm that can do it in time $O(m \cdot \frac{(2a)^k}{k!})$.In practice, on real-world graphs (which have a small arboricity), our algorithm performs much better than the one of Chiba and Nishizeki. We now want to show through theory that it is better.So the question is, how can we show that $O(m \cdot \frac{(2a)^k}{k!})$ is better than $O(m \cdot a^k)$?For instance, does it make sense to write: $m \cdot \frac{(2a)^k}{k!}\leq m \cdot \frac{4^4}{4!}\cdot (\frac{a}{2})^k$ and thus the running time of our algorithm is in $O(m \cdot (\frac{a}{2})^k)$ and is thus better than the one of Chiba and Nishizeki?If what is above is ok, then as I've done this with $p=4$, why can't I do it with $p=1000$? |
_cs.53750 | I am dealing a bioinformatics problem and need help in approaching it in the right direction.I have a set of variables that represent different kinds of genomic data and are real valued. I am trying to compare all these different variables among two species (though in the future I might be interested in generalizations to more than 2 species). What I need to do is to develop a graph theoretical method to calculate an entropy measure (or a better evolutionary distance measure) among all different genomic interval and cluster the pairs according to a high/low entropy measure.So in genomics in the case of multiple species/two species there would be genomic regions which have a similar DNA sequence (known as orthologus regions). These regions would have a epigenetic/epigenomic mark associated with them. Such marks generally affect the gene expression/the overall chromatin make up of the genome or chromosome. What I want to do is identify regions of orthologus DNA which have high evolutionary conservation and high epigenomic conservation. I also want to identify regions of DNA between 2 or multiple species which have high evolutionary and epigenomic conservation or low evolutionary conservation and high epigenomic conservation and vice versa. What I want to do at the end is to develop a method that would help ,make multi-species /pairwise comparison at the end. Since I am not a formally trained Computer Scientist I don't know what would be a good approach/algorithm to use.PS: epigenomic data would generally be in the form of counts (normalized to RPKM (https://wiki.nci.nih.gov/pages/viewpage.action;jsessionid=5265E39473A073390CF868D3E56E619A?pageId=71439191). While RPKM of epigenomic signals is available for a span of regions (say 200 base pairs) the evolutionary conservation data is available for every base of DNA (the evolutionary conservation value of a base lies between 0 and 1) | Graph theoretical approach to compare n pair of variables along a set of interval | graph theory;bioinformatics | null |
_unix.146478 | I am trying to generate a preseed file for automating the Ubuntu installation process.I want full disk encryption with the help of preseed having the pass-phrase included in the preseed.I wrote this:d-i partman-auto/method string cryptod-i partman-crypto/passphrase password helloworldd-i partman-crypto/passphrase-again password helloworldit is giving me error:unable to generate key file.I have tried many links but none helped:https://askubuntu.com/questions/24079/full-disk-encryption-with-preseedhttps://askubuntu.com/questions/305176/preseed-with-lvm-and-crypto-fails-with-an-error-occured-while-creating-the-keyf?rq=1but every time I got the same error.The thing is when I do it without the help of any preseed everything works fine.I want to know how to write a preseed for full disk encryption.I also referred to Ubuntu documentation, but that also did not help. And this guide is not having much information for writing a preseed for encryption | unable to create key file. ubuntu installation error | ubuntu;preseed | null |
_codereview.24829 | I have a collection of PlaylistItem objects. They are linked together such that each item knows the ID of its next/previous item. I am iterating over this collection of objects, starting at a known position and working with each object once. I'm not a big fan of how I do this, but I am not seeing an obvious way of rewriting it.var firstItemId = activePlaylist.get('firstItemId');var currentItem = activePlaylist.get('items').get(firstItemId);// Build up the ul of li's representing each playlistItem.do { var listItem = $('<li/>', { 'data-itemid': currentItem.get('id'), contextmenu: function (e) { var clickedItemId = $(this).data('itemid'); var clickedItem = activePlaylist.get('items').get(clickedItemId); contextMenu.initialize(clickedItem); // +1 offset because if contextmenu appears directly under mouse, hover css will be removed from element. contextMenu.show(e.pageY, e.pageX + 1); // Prevent default context menu display. return false; } }).appendTo(playlistItemList); $('<img>', { 'class': 'playlistItemVideoImage', src: 'http://img.youtube.com/vi/' + currentItem.get('video').get('id') + '/default.jpg', }).appendTo(listItem); $('<a/>', { text: currentItem.get('title') }).appendTo(listItem); currentItem = activePlaylist.get('items').get(currentItem.get('nextItemId'));} while (currentItem && currentItem.get('id') !== firstItemId)How would you write this?Note that it is a do-while because I want to ensure I always render that firstItem. If there's only one item in the list, the loop will immediately terminate. Thus the need for the do-while. | Iterating through a linked-list in a cleaner manner | javascript;linked list | Here's a bit of light refactoring. I've basically moved the element constructing into its own function to keep the while-block less crowded.I'm also using some closure magic for the contextmenu, so it doesn't have to re-get the clicked item.Lastly, I'm going more by the current ID rather than the current object when looping. This was to avoid the get the id to get the object to get its id again code that I see a few places in your version.function buildListItem(item) { var listItem = $('<li/>', { contextmenu: function (event) { contextMenu.initialize(item); // available via closure contextMenu.show(e.pageY, e.pageX + 1); return false; } }); listItem.append($('<img>', { 'class': 'playlistItemVideoImage', 'src': 'http://img.youtube.com/vi/' + item.get('video').get('id') + '/default.jpg' })); listItem.append($('<a/>', { text: item.get('title') })); return listItem;}var firstItemId = activePlaylist.get('firstItemId'), allItems = activePlaylist.get('items'), currentItemId = firstItemId, currentItem;do { currentItem = allItems.get(currentItemId); // get the obj if(!currentItem) { break; // stop if it ain't there } playlistItemList.append(buildListItem(currentItem)); // build the list item element currentItemId = currentItem.get('nextItemId'); // get the next ID} while(currentItemId && currentItemId !== firstItemId); // I'm assuming that valid IDs are thruth'yAnother thing to consider would be to use rawer HTML because it can be faster. |
_unix.319365 | I have a directory with files coming for every day. Now I want to zip those files group by dates. Is there anyway to group/list the files which landed in same date.Suppose there are below files in a directory-rw-r--r--. 1 anirban anirban 1598 Oct 14 07:19 hello.txt-rw-r--r--. 1 anirban anirban 1248 Oct 14 07:21 world.txt-rw-rw-r--. 1 anirban anirban 659758 Oct 14 11:55 a-rw-rw-r--. 1 anirban anirban 9121 Oct 18 07:37 b.csv-rw-r--r--. 1 anirban anirban 196 Oct 20 08:46 go.xls-rw-r--r--. 1 anirban anirban 1698 Oct 20 08:52 purge.sh-rw-r--r--. 1 anirban anirban 47838 Oct 21 08:05 code.java-rw-rw-r--. 1 anirban anirban 9446406 Oct 24 05:51 cron-rw-rw-r--. 1 anirban anirban 532570 Oct 24 05:57 my.txtdrwxrwsr-x. 2 anirban anirban 67 Oct 25 05:05 look_around.py-rw-rw-r--. 1 anirban anirban 44525 Oct 26 17:23 failed.logSo there are no way to group the files with any suffix/prefix, since all are unique. Now when I will run the command I am seeking I will get a set of lines like below based on group by dates.[ [hello.txt world.txt a] [b.csv] [go.xls purge.sh] [code.java] ... ] and so on.With that list I will loop through and make archive tar -zvcf Oct_14.tar.gz hello.txt world.txt a | Get list of files group by Date | files;ls | null |
_unix.55782 | Is it possible to make an Apache server like thisApache/1.3.41 Server at user.it.uu.se Port 80display hidden files (i.e., those who start with a dot) in a specific directory? I have some configuration there that's accessible (no problem), only those files don't show when I navigate to that directory. (Of course, you could set up an HTML interface with links, etc., even automatize update, but I'd rather just view the files like any others.)It's my school's server, so I can't configure it apart from putting a file in that directory, telling the server to override the habit of not showing hidden files. Is this something you normally do, and, if so, how?The system, if it matters (with uname -a):SunOS yxan.it.uu.se 5.10 Generic_147440-25 sun4u sparc SUNW,Sun-Fire-V240 | Make Apache view hidden files (Solaris) | solaris;apache httpd;dot files | null |
_webmaster.108836 | If two people buy a particular domain at the same time from different providers, what will happen? | What happens if two people try to buy a domain at the same time? | domains | null |
_unix.36621 | I need to read input from a file given in following format. $ ./process_data.sh arg1 < input_data.txtHow do I read input_data in my shell script process_data.sh? | Shell script how to read input from a file | bash;io redirection;input | null |
_unix.126773 | I often need to selectively archive a long list of files using cp -iar, or similar, and to speed up the process I would like to press just one key instead of y or n followed by ENTER on every file. In other words I want to avoid having to press ENTER as well as y or n. Of course I would happily use different keys instead of y or n.Is there a way to do this? | Can I avoid enter key in cp -i? | command line;cp | I think that what you need is a file manager, like midnight commander. In mc you can select several files with insert or + and realize operations on them, like deleting, moving or copying. A full set of instructions and tips can be found in the Tutorial.If you give it a try to pure shell commands (no gui), suppose you have file0 to file10 but wants to copy only file1 and file3:cp file1 file3 directory/Of course, you can use the shell to help yourself:cp file{1,3} directory/but what about consecutive ones? file5 through file10?cp file{5..10} directory/You can also use find to help, if you want something more advanced, for example:find Downloads -name *.cfg -exec cp {} directory \;will do this:copy Downloads/file(6).cfg to directorycopy Downloads/file(7).cfg to directorycopy Downloads/file(1).cfg to directorycopy Downloads/file.cfg to directorycopy Downloads/file(2).cfg to directorycopy Downloads/file(4).cfg to directorycopy Downloads/file(3).cfg to directorycopy Downloads/file(5).cfg to directoryyou can verify the files to be copied removing the -exec ... part. You can also use -exec echo cp ... in case you want to know what find will do. |
_unix.71181 | In Debian Squeeze I have installed a packageX from debian-backports. Q1: When I apt-get dist-upgrade or aptitude full-upgrade, what release is checked for updates for packageX? debian-backports or debian-stable?Q2: Can I use a command to update a single package from a specific release? For example is aptitude -t full-upgrade packageX a valid command? I tried aptitude -st full-upgrade packageX but the output was not helpful.Q3: For completeness purposes, what are the equivalent answers for RPM based distros? | Upgrade a single package from a target release | debian;apt;upgrade;aptitude | Q1: This depends on your current priorities. You can view the priorities with the apt-cache policy command. Here is an example of a couple of lines from the output: 500 http://security.debian.org/ stable/updates/main amd64 Packages release v=6.0,o=Debian,a=stable,n=squeeze,l=Debian-Security,c=main origin security.debian.org 100 http://backports.debian.org/debian-backports/ squeeze-backports/main amd64 Packages release o=Debian Backports,a=squeeze-backports,n=squeeze-backports,l=Debian Backports,c=main origin backports.debian.orgYou can also use apt-cache policy on a single package:$ apt-cache policy linux-image-2.6-amd64 linux-image-2.6-amd64: Installed: (none) Candidate: 2.6.32+29 Version table: 3.2+46~bpo60+1 0 100 http://backports.debian.org/debian-backports/ squeeze-backports/main amd64 Packages 2.6.32+29 0 500 http://apt.magazines.com/debian/ stable/main amd64 PackagesThe priorities are explained in apt_preferences(5): P > 1000 causes a version to be installed even if this constitutes a downgrade of the package 990 < P <=1000 causes a version to be installed even if it does not come from the target release, unless the installed version is more recent 500 < P <=990 causes a version to be installed unless there is a version available belonging to the target release or the installed version is more recent 100 < P <=500 causes a version to be installed unless there is a version available belonging to some other distribution or the installed version is more recent 0 < P <=100 causes a version to be installed only if there is no installed version of the package P < 0 prevents the version from being installedIn our example, this means that if the given package is already installed from backports, it will be upgraded from backports. If it is not installed from backports, the backports repository will not be used.Q2: The install command is used for upgrading single packages. If the package is already installed when install is given, it will be upgraded if an upgrade is available.apt-get install packageXaptitude install packageXQ3: For an RPM-based distro, it would depend on the distro. Things like yum are not tied to rpm in the same way that apt is tied to dpkg. The tool used for upgrades and remote management varies depending on distro. The yum (RHEL) and zypper (SLES) commands are the most common. |
_codereview.41113 | I wrote this code to clean up some of the space on our file server. We've got 15 years of legacy data that nobody accesses or changes or cares about that we have to keep regardless. I'd rather have it not sitting on our main file server so that I don't have to add an additional TB to it annually. This script goes through the file structure, finds files that haven't been touched in 4 years and copies them to slower storage, then replaces the source file with a symlink. I'm new to PowerShell, so any pointers regarding style or a better way to do things would be nice. I know that my way of bracing things is wrong and that closing curly braces should be indented one less level, but I don't care and find this easier to deal with.param( [string]$Dir = , [string]$ArchiveDrive = )if ($ArchiveDrive -eq ){ $hostname = hostname $ArchiveDrive = \\Archives\+$hostname+\+$Dir[0]+\ }import-module PSCXimport-module new-symlink$FileList = @()$SourceDrive = $dir[0] + :\$date = Get-Date -Format yyyy-MM-dd$ErrLog = C:\ErrorLog $date.txt$DelLog = C:\DelLog $date.txt$PathWarning = C:\_PROBLEMS DETECTED.txt function BuildLists($dir){ $FileList = @() $DirList = (dir $dir -recurse) foreach ($item in $DirList){ if ( ((get-date).Subtract($item.LastWriteTime).Days-gt 1460) -eq $True) { $FileList += $item } #else {write-host $item is modified recently} } return $FileList }function CheckPathLength($file){ if ($File.FullName.Length -ge 220){ copy $PathWarning $File.DirectoryName} }function ArchiveFile($SourceFile){ $DestFile = ($SourceFile.fullname.replace($SourceDrive, $ArchiveDrive)) $DestDir = ($SourceFile.DirectoryName.replace($SourceDrive, $ArchiveDrive)) mkdir -Path $DestDir 2>$ErrLog copy $SourceFile.FullName $DestFile }function HashCheckFile($SourceFile){ $DestFile = $SourceFile.FullName.replace($SourceDrive, $ArchiveDrive) $SourceHash = get-hash($SourceFile.fullname) $DestHash = get-hash($DestFile) return $SourceHash.HashString -eq $DestHash.HashString }function DeleteFIle($File){ del $file.fullname }function LinkFile($Sourcefile){ $SourceFilePath = $Sourcefile.fullname $DestFile = ($sourcefilepath.replace($SourceDrive, $ArchiveDrive)) New-Symlink -path $DestFile $SourceFile.fullname -file 1>$errlog }function CheckPathLength($file){ if ($File.FullName.Length -ge 220){ copy $PathWarning $File.DirectoryName} }function ReplicateFile($file){ if ($file.Attributes -eq Directory){continue} ArchiveFile($File) if (HashCheckFile($File)){ DeleteFile($File) LinkFile($File) } }function Archive($FileList){ foreach ($File in $FileList){ CheckPathLength($file) ReplicateFile($File) } }function RunArchiving($dir){ $FileList = BuildLists($dir) Archive($FileList) }function UnArchive(){}RunArchiving($dir) | Script which migrates files to secondary storage and symlinks them | beginner;windows;powershell | null |
_webmaster.54899 | On this official Google page about canonical links it says:Can rel=canonical be a redirect?Yes, you can specify a URL that redirects as a canonical URL. Google will then process the redirect as usual and try to index it.There is no mention that this might dilute the impact of the canonical link. However, Google has made clear elsewhere that 301 redirects do dilute PageRank - roughly as much as a link dilutes PageRank. Is that relevant here? I'm assuming the answer is no but I wanted to confirm.Relevant but not duplicate: Does Rel=Canonical Pass PR from Links or Just Fix Dup Content. | Will a rel=canonical link pointing to a 301 redirect pass less pagerank than one without a 301? | google;redirects;301 redirect;pagerank;canonical url | null |
_unix.216534 | How to access CD's content in GRUB, when booted from HDD?This is what I would like to do:title Boot from CD with modified parameters root (cd) kernel /live/vmlinuz <my parameters> initrd /live/initrd.imgortitle Boot from CD with my parameters kernel (cd)/live/vmlinuz <my parameters> initrd (cd)/live/initrd.imgExcept, when the GRUB is loaded from HDD, there is no (cd) device.I would like to boot from Live CD, but using different kernel boot parameters than those specified in ISOLINUX config file present on the CD. I don't want to rewrite it each time I boot. I thought I would just boot using HDD/UFD, then let GRUB load the kernel and initrd from the CD.Is this somehow possible? | Mount CD/DVD in GRUB | grub2 | null |
_unix.38874 | I am a big fan of linux and like trying out new distros now and then. I usually have my home folders and roots in a lvm atop an encrypted partition, but this tends to become cumbersome with every initramfs creation process being more alien than the last one. I value privacy, but most of my valuable information or personal is stored in the home folders. Moreover, I partitioned using GPT, so multiple partitions are not that hard to setup even outside a lvm. So the question is: Is root crypting and lvm-ing of / worth it, especially with all the early userspace hassle I have to deal with? | Any reason for encrypted /? | lvm;encryption;root filesystem | First of all the hassle with encrypted root and early userspace is typically already handled by your distribution (as far as i know Fedora, Debian, Ubuntu and OpenSUSE support encrypted root out of the box). That means you don't have to care for the setup itself.One reason for encrypting / is just to be sure you don't leak any information at all. Think about programs writing temporary data into /tmp, log files containing sensitive information like username/passwords in /var/log or configuration files containing credentials like a password in /etc/fstab or some commands in the shell history of the root user.Using LVM instead of partitions has one great benefit, you can easily resize/rename/remove logical volumes without the need to re-partition your disk itself, it is just more convenient than using partitions (GPT or MBR) |
_webmaster.39664 | I use bluhost web hosting.I already have mysite1.com. I want to copy this website to different domains within the same hosting, eg. mysite2.com, mysite3.com, and so on. All sites will have the same content as mysite1.com.How can I do it in fastest possible way ? | How to copy Wordpress website within same hosting? | domains;web hosting;wordpress | null |
_vi.6160 | Consider this string:1 1 1When I mark the first two 1s in visual mode and then :'<,'>s/1/2/g, all 1s on the line are replaced by 2s, not just those in the selected region. Why is this the case and how can I restrict the operation to the selected text? | Why is substitution applied outside the selected region? | visual mode;substitute | The :s[ubstitue] command operates on whole lines and the [range] prefix is a range of lines.To restrict the operation to just the visually-selected region, you can use the \%V atom in your search pattern. That is, visually-select the first two 1s in your example, then use this command to replace just those 1s:'<,'>s/\%V1/2/gSee also:help /\%VThe :help entry says to put \%V at the start and end of the pattern, but I didn't read that before trying it and it worked in the example here with \%V at just the start of the pattern. |
_codereview.143567 | This is my attempted solution to cracking the coding interview exercise 3.5. Looking for any feedback on coding style or the algorithm anywhere I can improve really.The problem specification is as follows.Write a program to sort a stack such that the smallest items are on the top. You can use an additional temp stack, but you may not copy the elements into any other data structure (such as an array). The stack supports push, pop, peek and isEmpty.MyStack.javapackage problem_2_8;import java.util.ArrayList;import java.util.EmptyStackException;public class MyStack<T extends Comparable<T>> { private static class StackNode<T extends Comparable<T>> { T data; StackNode<T> next; StackNode(T data){ this.data = data; } } private StackNode<T> top = null; private int size; public MyStack(){} public int size(){ return size; } T pop(){ if(top == null) throw new EmptyStackException(); T item = top.data; top = top.next; size--; return item; } void push(T data){ StackNode<T> node = new StackNode<T>(data); if(top != null){ node.next = top; } top = node; size++; } T peek(){ if(top == null) throw new EmptyStackException(); return top.data; } boolean isEmpty(){ return size == 0; } void sortStack(){ MyStack<T> tempStack = new MyStack<T>(); while(!isEmpty()){ tempStack.insertToSortedStack(this, pop()); } while(!tempStack.isEmpty()){ push(tempStack.pop()); } } void insertToSortedStack(MyStack<T> auxStack, T item){ int countPops = 0; while(!isEmpty() && item.compareTo(peek()) < 0){ auxStack.push(pop()); countPops++; } push(item); for(int i = 0; i < countPops; i++){ push(auxStack.pop()); } } void printStack(){ StackNode<T> current = top; ArrayList<String> stackAsString = new ArrayList<String>(); while(current != null){ stackAsString.add(current.data.toString()); current = current.next; } System.out.println(Top -> + String.join(, , stackAsString)); }}I ran the code as follows to test that the sorting works as expected.Main.javapackage problem_2_8;public class Main { public static void main(String[] args) { MyStack<Integer> myStack = new MyStack<Integer>(); myStack.push(5); myStack.push(7); myStack.push(11); myStack.push(5); System.out.println(Stack before sorting: ); myStack.printStack(); myStack.sortStack(); System.out.println(Stack after sorting: ); myStack.printStack(); MyStack<String> myStackOfStrings = new MyStack<String>(); myStackOfStrings.push(x); myStackOfStrings.push(c); myStackOfStrings.push(y); myStackOfStrings.printStack(); myStackOfStrings.sortStack(); myStackOfStrings.printStack(); }} | Sort a stack using Java | java;beginner;sorting;stack | The first thing you should do is assess the visibility of your methods. Some should be public, and others private. I don't see any that should stay package-protected as you have them now.Next, instead of having a printStack() method, you should consider overriding the toString() method. Just a Java standard.Now, I don't know if you're as far as multi-threading in your modules, but I can see some cases where your Stack is not thread-safe (particularly around the sorting). I'll leave the problem of how to solve this as an exercise to the questioner. |
_codereview.6224 | The exercise was to take a file such as this:You say yesI say noYou say stopAnd I say go go goCHORUS:Oh noYou say GoodbyeAnd I say helloHello helloI don't know whyYou say GoodbyeI say hello#repeat 9 12Why#repeat 11 13I say highYou say lowYou say whyAnd I say I don't know#repeat 5 19And parse the repeats so they actually repeat the lines. Nested repeats have to work and I had to use my own stack class.main.cpp#include Stack.h#include <fstream>#include <iostream>#include <string>#include <vector>void parseLines(const std::vector<std::string> text, const int begin, const int end);void parseRepeat(const std::string repeatLine, int &begin, int &end);int main() { int fileLines = 0; std::string in; std::string fileName = lyrics; std::ifstream inFile(fileName.c_str()); std::vector<std::string> text; while(!inFile.eof()) { getline(inFile, in); text.push_back(in); fileLines++; } parseLines(text, 0, fileLines);}void parseLines(const std::vector<std::string> text, const int begin, const int end) { Stack<int> lyricStack; int fromLine = begin; int toLine = end; while(fromLine <= toLine && (unsigned int)fromLine < text.size()) { if(text.at(fromLine).substr(0, 7) == #repeat) { lyricStack.push(fromLine); lyricStack.push(toLine); parseRepeat(text.at(fromLine), fromLine, toLine); } else { std::cout << text.at(fromLine) << std::endl; fromLine++; } } while(!lyricStack.isEmpty()) { toLine = lyricStack.pop(); fromLine = lyricStack.pop(); fromLine++; parseLines(text, fromLine, toLine); }}void parseRepeat(const std::string repeatLine, int &begin, int &end) { std::string numbers = repeatLine.substr(repeatLine.find( ) + 1); begin = atoi((numbers.substr(0, numbers.find( ))).c_str()) - 1; end = atoi((numbers.substr(numbers.find( ))).c_str()) - 1;}Stack.h#ifndef STACK_H_#define STACK_H_#include <string>template <class A>struct NODE { A data; NODE* next;};template <class B>class Stack {private: NODE<B>* head;public: Stack(); virtual ~Stack(); void push(const B item); B pop(); bool isEmpty();};#endif /* STACK_H_ */Stack.cpp#include Stack.h#include <string>template <class B>Stack<B>::Stack() { head = NULL;}template <class B>Stack<B>::~Stack() { NODE<B>* current = head; NODE<B>* previous; while(current) { previous = current; current = current->next; delete previous; }}template <class B>void Stack<B>::push(const B item) { NODE<B>* newNode = new NODE<B>; newNode->data = item; if(!head) { newNode->next = NULL; head = newNode; } else { newNode->next = head; head = newNode; }}template <class B>B Stack<B>::pop() { NODE<B>* next = head->next; B data = head->data; delete head; head = next; return data;}template <class B>bool Stack<B>::isEmpty() { if(!head) { return true; } return false;} | Song repetition manager with Stack | c++;parsing;stack | First main problem is the code does not compile:When you implement template classes. The compiler instantiates the templates on use. This means the compilation unit that is instantiating the class must have already seen the source for the template (if it has not then it marks it as unresolved) and then tries to resolve them at link time. In your case this does not happen.main.cpp: Uses Stack<int> thus needs the constructor and destructor. But does not have them at this point. So waits for the linker to find one.Stack.cpp: Contains only template definition and thus does **NOT** generate any code. Templates only become real code when there is an instantiation (implicit as done by the compiler in main.cpp or explicit when you do it). Since there is no instantiation there is no code.This all means that main fill fail to link.The easiest way to solve this:Rename Stack.cpp to Stack.tpp#include Stack.tpp from inside Stack.hThe reason to rename to Stack.tpp is that some build systems will try to build all source and since this is included by a header this can cause problems with some build systems. So it is best to change the name just to avoid any future problems. tpp is often used to hold template definitions.Never do this:while(!inFile.eof()) { getline(inFile, in); text.push_back(in); fileLines++;}Several problems:If getline() fails with a real error (not EOF) you end up with an infinite loop.The last line read reads up to (but not past the EOF).So you have read the last line but EOF is not set. You then re-enter the loop try to get another line, this fails and sets EOF but nothing is done with in yet you still push in onto text. So you end up pushing the last line twice.The correct way to read from a file is:while(getline(inFile, in)){ // The loop is only entered if getline() successfully reads a line. // Thus it solves the two problems above. text.push_back(in); fileLines++;}This works because getline() returns a reference to a stream. When a stream is used in a boolean context it is converted to a type that can be used as a boolean (type unspecified in C++03 but bool in C++11). It is converted by checking the fail() flag. If this is true the conversion returns an object equivalent to false otherwise an object equivalent to true.When passing big objects as parameters consider passing them by reference. If they are never modified pass by const reference. If you don't the compiler is going to generate a copy.void parseLines(const std::vector<std::string> text, const int begin, const int end) {Here you should probably pass text by const reference.void parseLines(const std::vector<std::string> const& text, const int begin, const int end) {// ^^^^^^^^Same thing here:void parseRepeat(const std::string repeatLine, int &begin, int &end) {// Should probably bevoid parseRepeat(const std::string& repeatLine, int &begin, int &end) {// ^^^Casting is nearly always a sign that something is wrong with your design:(unsigned int)fromLineThis should be a hint that fromLine is the wrong type. Since it is measuring a size and will never by less than 0 this is an indication that the correct type for the type is unsigned int (or probably size_t).void parseLines(const std::vector<std::string> text, std::size_t const begin, std::size_t const end) { Stack<int> lyricStack; std::size_t fromLine = begin; std::size_t toLine = end; while(fromLine <= toLine && fromLine < text.size()) {atoi() is fast but non standard and not always available. An easier way is to just use the stream operators. This will always work and 99% of the time will be sufficiently fast. Only optimize out when you know it makes a difference.Also this code is so dense it is nearly unreadable. White space is your friend.void parseRepeat(const std::string repeatLine, int &begin, int &end){ std::string numbers = repeatLine.substr(repeatLine.find( ) + 1); begin = atoi((numbers.substr(0, numbers.find( ))).c_str()) - 1; end = atoi((numbers.substr(numbers.find( ))).c_str()) - 1;}Much easier to write with streams:void parseRepeat(const std::string repeatLine, int &begin, int &end){ // This line always has the form // #repeat <number> <number> std::stringstream linestream(repeatLine); std::string repeat; linestream >> repeat >> begin >> end;}Both NODE and Stack contain RAW pointers. Yet they do not obey the rule of three. This is very dangerous. The simple rule is your classes should never contain RAW pointers (all pointers should be wrapped in smart pointers) unless you are writing a smart pointer or container.In this situation NODE would be easy to implement using smart pointer. Also you do a work handling node inside stack. It simplifies the design if you move this work to the constructor of NODE. This makes the code in Stack much easier to read as it just handles the stack and the NODE can handle itself.The Stack is arguably a container so it can have a pointer but you must implement the rule of three. This means you need to implement the Copy Constructor/Assignment operator/Destructor or make these methods private. The reason is that if you do not then the compiler will automatically generate these methods. And the compiler generated version does not plat well with OWNED RAW pointers.{ Stack<int> a; a.push(4); Stack<int> b(a); // Copy made of a DO STUFF} // Here B is destroyed. // But because you did not define a copy constructor b is a shallow copy of a // This means they both contain the same pointer. So b deletes it first. // Now A is destroyed. // This also deletes its pointer (the same as b) but it has already been deleted. // Your program is now free to produce nasal daemons (undefined behavior).The simplest solution is to disable copy construction and the assignment operator.You have over complicated push:if(!head) { newNode->next = NULL; head = newNode;} else { newNode->next = head; head = newNode;}Would this not be easier to write as:newNode->next = head;head = newNode;Also isEmpty() is over complicated:if(!head) { return true;}return false;Could be written as:return head == NULL; |
_unix.145084 | for some reason, my filename completion in gvim is not working.In vim, its working properly. Commands and such are, however, completed correctly.I have set wildmode=full.An example:Assume i want to open the file main.cI type :op<Tab> and gvim gives me a list with all possible completions (open and options). I choose open and continue to :open m<Tab>. I would expect gvim to now complete my file, what happens however, is this: :open m^I, no completion.As mentioned, in vim it works perfectly fine. | Filename completion in gvim | vim;autocomplete | Did you mean:edit index<tab>Which completes to index.php etcfrom Vim Help:help openVim does not support open mode, since it's not really useful. For thosesituations where :open would start open mode Vim will leave Ex mode, whichallows executing the same commands, but updates the whole screen instead ofonly one line. |
_reverseengineering.14951 | We have an embedded product, which we are carrying for several hardware iterations since more than 5 years ago. We have all the source code, most of it nicely documented. As the product is actively sold and needs an upgrade, I have been tasked to design next generation improved version.While we have all the source code, and most of it is well documented, the security part is not, especially its slowest part, a 128-bit hash function with 72 rounds. I can step trough it in our debugger, execute it, and the code works fine except its slowness. If I would know which cryptography standard it is, I could attempt to upgrade it to be executed in hardware, which would drastically speed it up. (The original consultant who wrote this function is not with our company and I cannot find her).Is there any logical way to find out which encryption are we executing?I do not need a help to do my work, I am asking for an advice if there is any strategy how to look at code ('unoptimized mess'); learning the principle of it (like this one has 72 rounds and hashes 128 bits); then finding candidate standards doing the same thing.I would think that after finding a documented standard, I should be able to hash various numbers by using both our hash and the standard hash, and simply see if the results match?I looked on the web for information about known functions using 72 rounds, like the Skein algorithm, but could not find anything similar.Are there any known hash values for known standards, for example results of hashing 0? This hash converts 0 to these 16 hexadecimal bytes:ae c5 40 44 df 2d 91 1c 87 ab 1a ff 59 09 aa b7Function beginning and end is below, as some of you requested, the full function is at: full_function_codeIt looks like the previous programmer let the old C compiler to convert it, and then used it in 'assembly' style. Maybe it was due to avoid compiler optimizing, just my guess.There are 72 rounds, each of which ends with a call to function TricoreDextr(); which is the C equivalent of Infineon TriCore DEXTR instruction. Think of DEXTR as splitting a 64-bit number into two parts (at the selected bit location) and swapping them.Any concept explanations is a great help, thank you!/* * @param in_arr 16 byte long array, input data (128 bits) * @param out_arr 16 byte long array, output data (128 bits) */void Hash16bytes(unsigned char *in_arr, unsigned char *out_arr) { long d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d15; long IN[16]; d4 = 0xB12E8FB5; int i; for (i = 0; i < 16; i++) { IN[i] = (long) (*(in_arr + i)); } d11 = (IN[3] << 24) | (IN[2] << 16) | (IN[1] << 8) | IN[0]; d10 = (IN[7] << 24) | (IN[6] << 16) | (IN[5] << 8) | IN[4]; d12 = (IN[0xB] << 24) | (IN[0xA] << 16) | (IN[9] << 8) | IN[8]; d13 = (IN[0xF] << 24) | (IN[0xE] << 16) | (IN[0xD] << 8) | IN[0xC]; /* block like this below repeats 72 times... */ d3 = 0x7025BD47; d8 = 0xCCEE4EFE; d8 += d13; d8 += d3; d8 = TricoreDextr(d8, 6); /* etc., TricoreDextr is called total of 72 times */ d0 += d15; d0 += 0x5C4E0000; d0 -= 0x2EDC; d0 = TricoreDextr(d0, 5); *(out_arr + 3) = (unsigned char) ((d5 >> 24) & 0xFF); *(out_arr + 2) = (unsigned char) ((d5 >> 16) & 0xFF); *(out_arr + 1) = (unsigned char) ((d5 >> 8) & 0xFF); *(out_arr + 0) = (unsigned char) ((d5) & 0xFF); *(out_arr + 7) = (unsigned char) ((d6 >> 24) & 0xFF); *(out_arr + 6) = (unsigned char) ((d6 >> 16) & 0xFF); *(out_arr + 5) = (unsigned char) ((d6 >> 8) & 0xFF); *(out_arr + 4) = (unsigned char) ((d6) & 0xFF); d8 += d0; d8 += 0x10320000; d8 += 0x5476; *(out_arr + 0xB) = (unsigned char) ((d8 >> 24) & 0xFF); *(out_arr + 0xA) = (unsigned char) ((d8 >> 16) & 0xFF); *(out_arr + 9) = (unsigned char) ((d8 >> 8) & 0xFF); *(out_arr + 8) = (unsigned char) ((d8) & 0xFF); *(out_arr + 0xF) = (unsigned char) ((d7 >> 24) & 0xFF); *(out_arr + 0xE) = (unsigned char) ((d7 >> 16) & 0xFF); *(out_arr + 0xD) = (unsigned char) ((d7 >> 8) & 0xFF); *(out_arr + 0xC) = (unsigned char) ((d7) & 0xFF);} | Is there a way to find out which hash standard by studying the source code? | c;static analysis;encryption;cryptography;hash functions | null |
_scicomp.20929 | I have a $80\times200$ matrix, and I want to plot its contents with the contourf command in MATLAB, as follows:\begin{align}&\text{[C,h] = contourf(mat,100);}\\&\text{set(h,'LineColor','none');}\end{align}The resulting image, as you can see, has some step-like discontinuities where the white part meets the coloured part. Is there any way to smooth this region with curve-fitting tool or other methods? | Having smoother contour plots in MATLAB | matlab;plotting;smoothing | null |
_unix.156707 | I have been working on my laptop a lot lately, and I am accidentally clicking while typing. I know I could remove set mouse=a in my .vimrc, but sometimes I like using the mouse.What can I do to create a toggle function to toggle mouse support? | How to toggle mouse support in vim? | vim | You can retrieve the value of an option by using its name with a & prepended. So a simple toggle function for the mouse option would be:function! ToggleMouse() check if mouse is enabled if &mouse == 'a' disable mouse set mouse= else enable mouse everywhere set mouse=a endifendfuncThis toggles between no mouse and mouse in all modes. You can use it via :call ToggleMouse()PS: don't use something like this for options that are boolean, for these :set option! can be used to invert them. |
_webmaster.42643 | I am working on a PHP laravel project. I am currently facing issues with .htaccess file. I have following .htaccess:<IfModule mod_rewrite.c>Options -MultiViewsRewriteEngine OnRewriteBase /RewriteCond %{REQUEST_FILENAME} !-fRewriteRule ^ index.php [L]</IfModule>When I reload my page the it gave me following error:404 Not FoundThe requested URL /contacts was not found on this server.Then I opened /etc/apache2/users/username.conf file which had following line of code:<Directory /Users/username/Sites/>Options Indexes MultiViewsAllowOverride NoneOrder allow,denyAllow from all</Directory>In above code I changed AllowOverride None to AllowOverride All. Then I reload page and got following error:403 ForbiddenYou don't have permission to access /contacts on this server.When I add FollowSymLinks to .htaccess file Options such as like this Options -MultiViews FollowSymLinks. Then sometimes I get this 500 Internal Server Error error and sometime this *Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data*. Each time I reload my page one of these errors with FollowSymLinks option.I also uncomment following lines in /etc/apache2/httpd.conf:LoadModule rewrite_module libexec/apache2/mod_rewrite.soLoadModule php5_module libexec/apache2/libphp5.soand still I am getting same permission denied error.Please help me I am trying to solve this problem for past 3 days but it is till unresolved. | Clean URLs issue using .htaccess in PHP project | apache;htaccess;webserver;http code 500;configuration | null |
_cs.63839 | In order for the BIOS code to matter, it must be evaluated by the processor. However, the processor itself needs to do work to actually get access to the BIOS code, since the CPU only performs instructions that are given, something must give the instructions to the CPU (since I can't imagine a way for instructions to just flow from BIOS to the CPU without anything in between).Where are the instructions for loading BIOS and passing control to it stored, and who passes these instructions to CPU so that CPU can preform them? | Where does the CPU get its first instructions from? | computer architecture;cpu | null |
_unix.156837 | I need to use it to so the program asks the user for the text file and then the string located in that file. Then the program will tell the user whether the string exists in the file. | Using grep to locate string from a text file | grep | null |
_datascience.2284 | I want to identifies different queries in sentences. Like - Who is Bill Gates and where he was born? or Who is Bill Gates, where he was born? contains two queries Who is Bill Gates?Where Bill Gates was bornI worked on Coreference resolution, so I can identify that he points to Bill Gates so resolved sentence is Who is Bill Gates, where Bill Gates was bornLike wiseMGandhi is good guys, Where he was born?single querywho is MGandhi and where was he born?2 querieswho is MGandhi, where he was born and died?3 quriesIndia won world cup against Australia, when?1 query (when India won WC against Auz)I can perform Coreference resolution (Identifying and converting he to Gandhi) but not getting how can I distinguish queries in it. How to do this? I checked various sentence parser, but as this is pure nlp stuff, sentence parser does not identify it. I tried to find Sentence disambiguation like word sense disambiguation, but nothing exist like that.Any help or suggestion would be much appreciable. | Is it possible to identify different queries/questions in sentence? | machine learning;data mining;nlp;social network analysis | null |
_unix.116539 | I am writing a bash script that needs to know which desktop environment (XFCE, Unity, KDE, LXDE, Mate, Cinnamon, GNOME2, GNOME3,... ) is running.How can I obtain that information? | How to detect the desktop environment in a bash script? | bash;desktop environment;bash script | The main problem with checking the DESKTOP_SESSION is that it is set by the display manager rather than the desktop session and is subject to inconsistencies. For lightdm on Debian, the values come from the names of files under /usr/share/xsessions/. DESKTOP_SESSION reflects the desktop environment if a specific selection is made at log in, however the lightdm-xsession is always used the default session.GDMSESSION is another option, but seems to have a similar predicament (it is the same value as DESKTOP_SESSION for me).XDG_CURRENT_DESKTOP looks like a good choice, however it is currently not in the XDG standard and thus not always implemented. See here for a discussion of this. This answer shows its values for different distros/desktops, I can also confirm it is currently not available for me on XFCE.The reasonable fallback for XDG_CURRENT_DESKTOP not existing would be to try XDG_DATA_DIRS. Provided the data files for the desktop environment are installed in a directory bearing its name, this approach should work. This will hopefully be the case for all distros/desktops!The following (with GNU grep) tests for XFCE, KDE and Gnome:echo $XDG_DATA_DIRS | grep -Eo 'xfce|kde|gnome'POSIX compatible:echo $XDG_DATA_DIRS | sed 's/.*\(xfce\|kde\|gnome\).*/\1/'To combine with checking XDG_CURRENT_DESKTOP:if [ $XDG_CURRENT_DESKTOP = ]then desktop=$(echo $XDG_DATA_DIRS | sed 's/.*\(xfce\|kde\|gnome\).*/\1/')else desktop=$XDG_CURRENT_DESKTOPfidesktop=${desktop,,} # convert to lower caseecho $desktop |
_codereview.141143 | I'm still learning C++ and also algorithms. So I'm expecting to do a lot of refactoring. Here's my code#include <iostream>#include <vector>#include <iterator>std::vector<int> mergesort(std::vector<int> &);std::vector<int> merge(std::vector<int> &, std::vector<int> &);std::vector<int>::iterator get_midpoint(std::vector<int> &);int main(){ std::vector<int> vect; int num = 0; while(std::cin >> num) { vect.push_back(num); } std::vector<int> temp_vect = mergesort(vect); for(int num: temp_vect) { std::cout << num << std::endl; }}std::vector<int> mergesort(std::vector<int> &unsorted_vector){ std::vector<int>::iterator middle = unsorted_vector.begin(); std::vector<int> sorted_vect, first_half, second_half, first_temp, second_temp; if(unsorted_vector.size() == 1) { return unsorted_vector; } else { middle = get_midpoint(unsorted_vector); first_temp.insert(first_temp.begin(), unsorted_vector.begin(), middle); second_temp.insert(second_temp.begin(), middle, unsorted_vector.end()); first_half = mergesort(first_temp); second_half = mergesort(second_temp); sorted_vect = merge(first_half, second_half); return sorted_vect; }}std::vector<int> merge(std::vector<int> & first_vect, std::vector<int> & second_vect){ std::vector<int> sorted_vect; auto first_it = first_vect.begin(), second_it = second_vect.begin(); while(first_it != first_vect.end() && second_it != second_vect.end()) { if(*first_it < *second_it) { sorted_vect.push_back(*first_it); first_it++; } else { sorted_vect.push_back(*second_it); second_it++; } } sorted_vect.insert(sorted_vect.end(), first_it, first_vect.end()); sorted_vect.insert(sorted_vect.end(), second_it, second_vect.end()); return sorted_vect;}std::vector<int>::iterator get_midpoint(std::vector<int> &vect){ std::vector<int>::iterator it = vect.begin(); int middle = 0; if(vect.size() % 2 == 0) { middle = vect.size() / 2; } else { middle = (vect.size() - 1) / 2; } std::advance(it, middle); return it;} | Merge sort using c++ vectors | c++;c++11;mergesort;vectors | null |
_unix.119644 | First a bit of context for those who don't know gradle. It's basically like make except that you don't have to have gradle installed on your computer. It ships with projects as a file called gradlew. So for instance a gradle project could look like:. gradlew src main java com foo bar Bar.java Baz.java Foo.java Qux.javaAnd from the root directory I can run commands like ./gradlew build or ./gradlew test to build/test my code.Now vim. First I :set autochdir in my .vimrc. Second, my current buffer is Foo.java.I want to run :make which would trigger ../../../../../../gradlew. How can I set makeprg such that no matter what's my :pwd it'll call gradlew (I guess that could be achieved using dirname in a loop but I'm not sure if that's the most efficient/cleanest way to do that).Thanks. | Set makeprg to gradlew | vim;compiling | For those looking to do the same thing (or similar things), it's doable by creating a new compiler that use findfile, and reuse errorformat from some other compiler + slight modifications. The end result looks like:let s:gradlew = escape(findfile('gradlew', '.;') . -b . findfile('build.gradle', '.;'), ' \')if exists(current_compiler) finishendifif exists(:CompilerSet) != 2 older Vim always used :setlocal command -nargs=* CompilerSet setlocal <args>endiflet current_compiler = s:gradlewexecute CompilerSet makeprg= . s:gradlew copied from javac.vim + added the :compileJava bitsCompilerSet errorformat=%E:compileJava%f:%l:\ %m,%E%f:%l:\ %m,%-Z%p^,%-C%.%#,%-G%.%# |
_codereview.26484 | I made a class to perform tasks concurrently and have implemented it. From appearances and testing, everything seems to work. How can I improve this? I understand this is somewhat a broad question, so please let me know how I should narrow it down.Here is the pseudocode:The general idea is a single Starter spawns multiple TaskWorker to do the work. I want to start the loading process fairly early on and then block EDT until the completion of all TaskWorker.class ImproveMe { private AtomicInteger incompleteTasksCount = new AtomicInteger( -1 ); /* SwingWorker has a limitation of 10 */ private static final int MAX_CONCURRENT_THREAD = 20; private static ExecutorService threadPool = Executors.newFixedThreadPool( MAX_CONCURRENT_THREAD ); /* This just starts multiple TaskWorker */ class Starter extends SwingWorker { Object doInBackground() { incompleteTasksCount.getAndSet( -1 ); Tasks[] taskList = getTasks(); for ( Task task : taskList ) { /* Track incomplete tasks */ if ( incompleteTasksCount.compareAndSet( -1, 1 ) { incompleteTasksCount.incrementAndget(); } threadPool.submit( new TaskWorker( task ) ); } threadPool.shutdown(); } } /* Performs the actual work -- I don't care about the results since it will be cached elsewhere */ class TaskWorker implements Runnable { Task t; TaskWorker( Task t ) { this.t = t; } void run() { if ( t != null ) { do stuff with 't' } synchronized( incompleteTasksCount ) { if ( incompleteTasksCount.decrementAndGet() == 0 ) { /* everything is done! */ incompleteTasksCount.notifyAll(); } } } } /* User will call this to start the loading */ public void startLoading() { if ( !threadPool.isShutdown() ) { Starter s = new Starter(); s.execute(); } } /* User will call this to ensure that everything has complete before continuing */ public void blockUntilDone() { boolean cont = true; if ( incompleteTasksCount.get() == 0 || threadPool.isTerminated() ) { return; } else if ( incompleteTasksCount.get() == -1 ) { /* not loaded/started */ return; } while ( cont ) { synchronized( incompleteTasksCount ) { try { incompleteTasksCount.wait(); } catch ( InterruptedException e ) { e.printStackTrace(); cont = false; } finally { if ( incompleteTasksCount.get() == 0 ) { cont = false; } } } } }}In reality, TaskWorker calls PrintService.getSupportedAttributeValues(..) because of the numerous printers and Java caches that so any future calls will return fairly quickly as compared to the first time (some of the network printers took 40+ seconds). I call ImproveMe.startLoading() somewhere fairly early in my program then before the actual program starts (e.g. GUI is shown), I use ImproveMe.blockUntilDone() to ensure everything is loaded.I was suggested to post here from StackOverflow. | Improve my threading in Java | java | null |
_unix.241309 | I am running a laravel application on a Ubuntu 14.04 digital ocean vps and I am using New Relic to monitor the server.I got an email alert that my CPU usage was above 80%. I logged in to New Relic and now it's showing my CPU usage at 99% for 18 hours now. But when I log into my shell and run 'top' the CPU usage of the processes don't even sum up to 10%. What could be wrong? Which are other commands I could run to check the real usage and what is using it so much? (Perhaps an infinite loop on the application?)This is my htop result:And this is htop after shift+K Any links or help would be greatly appreciated. | CPU > 80% - how can I debug? | performance;cpu | null |
_unix.192361 | Is it possible to do backup without closing programs that are opening files for editing?I would like to do backup without closing programs that are opening files that I am reading or writing. I usually open many text files in emacs in different terminal tabs, and pdf files in pdf editors, for a long period of editing, so I don't want to close the programs for keeping what files and where in them I am working on.Most of the time I save changes immediately after I make some. But I might miss to save them sometimes.Should I check that manually, or is there some program to do that? | backup without closing programs that are opening files for editing, and detect unsaved open files? | files;backup | null |
_softwareengineering.117530 | I am very new to Visual Studio and C# and am wondering how best to create a repository of sorts for utility methods.For instance, we need a method that returns the current fiscal year and other company specific values.Would it be best to create utility class file that is imported into every project? Or, create a new project with the these methods and add it to the current solution?In python, for instance, I created an egg that has all the utility methods that I then install into the site-packages. | Where should I put my utility methods? | c#;class design | Create a new project and import it into needed solutions. This way you can let it have its own solution and add an additional project for unit tests. |
_unix.236509 | Is there a way in XFCE to ensure that every time a certain type of window opens, it goes to a specified workspace? For instance, every time a ffplay window opens, I would like it to open on workspace 4, no matter what the active workspace is. | XFCE Always Open Certain Types of Windows on the Same Workspace | xfce;workspaces | null |
_softwareengineering.50168 | What roles do people take after scrum master/technical lead?EDIT: My current role is a mix of a technical lead and scrum master role, but that's how we do it in my company :) ) | What roles do people take after scrum master/technical lead? | agile;scrum | null |
_webmaster.91642 | I got the problem with my domain with 1&1. They canceled my account without any notice. Then I checked status of my domain on whois.WHOIS Server: whois.1und1.deReferral URL: http://1und1.deUpdated Date: 2016-03-18T00:05:09.0ZCreation Date: 2016-03-02T17:33:21.0ZRegistry Expiry Date: 2017-03-02T23:59:59.0ZSponsoring Registrar: 1&1 Internet SE (TLDs)Sponsoring Registrar IANA ID: 83Domain Status: pendingDelete https//icann.org/epp#pendingDeleteDomain Status: clientTransferProhibited https//icann.org/epp#clientTransferProhibitedDomain Status: redemptionPeriod https//icann.org/epp#redemptionPeriodSo do you know when I can re-register my domain in other Provider? 1&1 support told me 5,6 days but now is 7 days. | How long before I can re-register my domain at another registrar after my registrar cancelled my account and deleted my domain? | domain registration;whois | null |
_softwareengineering.253868 | We've been in the process of changing how our AS3 application talks to our back end and we're in the process of implementing a REST system to replace our old one.Sadly the developer who started the work is now on long term sick leave and it's been handed over to me. I've been working with it for the past week or so now and I understand the system, but there's one thing that's been worrying me. There seems to be a lot of passing of functions into functions. For example our class that makes the call to our servers takes in a function that it will then call and pass an object to when the process is complete and errors have been handled etc.It's giving me that bad feeling where I feel like it's horrible practice and I can think of some reasons why but I want some confirmation before I propose a re-work to system. I was wondering if anyone had any experience with this possible problem? | Passing functions into other functions as parameters, bad practice? | object oriented;object oriented design;rest | It isn't a problem. It is a known technique. These are higher order functions (functions that take functions as parameters).This kind of function is also a basic building block in functional programming and is used extensively in functional languages such as Haskell.Such functions are not bad or good - if you have never encountered the notion and technique they can be difficult to grasp at first, but they can be very powerful and are a good tool to have in your toolbelt. |
_datascience.13919 | Reading the ResNet paper, paragraph 3.3:The convolutional layers mostly have 33 filters and follow two simple design rules: (i) for the same output feature map size, the layers have the same number of filters; and (ii) if the feature map size is halved, the number of filters is doubled so as to preserve the time complexity per layer.The network uses convolutional layers with stride 2 to halve the feature map size, but this divides both the width and the height of the feature maps, so the total area is divided by 4, not by 2.So I am guessing the time complexity per layer is halved every time the feature maps are halved. Did I miss something? | Do all layers have the same computational complexity in a ResNet? | convnet | null |
_unix.59874 | I know that this question has already got asked before, but it's pretty old and things have changed (probably).Already in 2009 the news rumbled, that Debian was going to switch to Upstart. You were able to install it, but had to remove sysvinit:$ aptitude show upstart$ > Conflicts: startup-tasks, system-services, sysvinit, upstart-compat-sysv, upstart-jobIt appears like you can still install Upstart, as it is in the Debian packages.So my question is, what's the status quo? Was there any development on this? Does Debian still use sysvinit; did they switch to another system comparable to Upstart? | What's the status of Upstart on Debian? | debian;systemd;upstart;sysvinit | They use insserv by default, which still requires the sysvinit package as of Debian 6.0 (Squeeze). It was originally developed and used in OpenSUSE. Links to discussions and reasons for the change to insserv can be found on the Debian Wiki. There has been much debate over the future of init systems in Debian. The main reason that Debian has not moved on to a new init system such as Upstart or Systemd is that they both use Linux specific features. Debian offers ports for non-Linux kernels such as KFreeBSD. Even though they are not the default and not fully supported by all services, they can still be used.Here is an archive link for some of their recent discussions: http://lists.debian.org/debian-devel/2012/03/msg00452.html. As a warning, it is 100 emails long and even spawned into sub-threads. |
_unix.179125 | For most vim colorschemes, they appear different than advertised when I open vim in xterm. I've been using xterm-256color and set t_Co=256.A similar thing happens when I use xfce-terminal, but the colors in the colorschemes will vary depending on which colors I set in the terminal's preferences menu. I've read that some colorschemes will rely on terminal colors, and that appears to be what's happening here.Is there a way to prevent the vim colorscheme from conflicting with the terminal one? | Vim colors conflicting with terminal ones | terminal;vim;xterm | Unless you use the mostly experimental support for full RBG-colors in some terminals, you're limited to the indexed 256 color palette provided by the terminal. You're right that terminals may slightly deviate in the exact colors used, and that will be noticeable. If you completely reassign colors (turn red into blue etc.), there's nothing that corrects this in Vim, as Vim will ignorantly request color at index #42.If the differences are only in the basic 16 colors and the rest of the palette is correct and you use a colorscheme with both GUI and cterm definitions, you can work around this via plugins like CSApprox, which take the GUI color definitions and convert them to a closely matching 256-color cterm color palette for high-color terminals.Another approach is taken by csexact, which modifies the (supported) terminal's palette to exactly match Vim's GUI colors. If your terminal is supported, that may be worth a try. |
_webmaster.71876 | I realized my site was SEO optimized but only using the <title> tag and not the <meta name=title content=My Website title> tag.Can I have both, the <title> tag and the <meta name=title content=My Website title> tag displaying the same phrase? Would this impact the SEO? | Does a meta title tag help rankings when used in addition to a title tag? | seo;meta tags;title | Google maintains a list of all the meta tags that it uses. It lists the <title> tag (although it notes that it is technically not a meta tag). It does not list <meta name=title> tags.Most websites rank very well without meta tags named title. I've never used such a tag myself before. Your use of a meta title tag would be ignored by search engines and have no impact on your rankings.You already know that it is very important to use a <title> tag on each page for SEO. The <title> tag is the place on the page where Google gives the most weight to the keywords you use. |
_codereview.47587 | Is this repository code written according to best practices? The Last Section I included it in the repository as well.class HR_Repository<T> : IRepository<T> where T : class{ private readonly LoginDataContext dataContext; public HR_Repository(LoginDataContext dataContext) { this.dataContext = dataContext; } public void Commit() { dataContext.SubmitChanges(); } public IList<T> FindAll() { var table = this.LookupTableFor(typeof(T)); return table.Cast<T>().ToList(); } public IQueryable<T> Find() { var table = this.LookupTableFor(typeof(T)); return table.Cast<T>(); } public void Add(T item) { var table = this.LookupTableFor(typeof(T)); table.InsertOnSubmit(item); } public void Delete(T item) { var table = this.LookupTableFor(typeof(T)); table.DeleteOnSubmit(item); } private ITable LookupTableFor(Type entityType) { return dataContext.GetTable(entityType); }}public static class UserQueries{ public static Employee ByUserName(this IQueryable<Employee> employees, string username) { return employees.Where(u => u.User_Name == username).FirstOrDefault(); }} | Is the following repository pattern properly applied? | c#;design patterns | null |
_cstheory.29309 | Goldbach's conjecture states that every even number greater than 2 can be expressed as the sum of 2 primes.I'm interested in this function problem:Given an even natural number n greater than 2, find a natural number p such that p and n - p are both prime. (Inputs that are not even natural numbers may be mapped to 0.)If we assume that Goldbach's conjecture is true, this function f(n) = p is a member of TFNP. The reason for this is that we are guaranteed by our assumption that Goldbach's conjecture is true that there exists an answer to the problem, and we can easily guess this answer (it is no greater in size than n), and then verify its accuracy in linear time.Can we do any better than TFNP here? Could there be some algorithm in PPAD that computes this, or could there even be an FP algorithm? | Is there a PPAD algorithm for computing primes that sum to even numbers? | complexity classes;nt.number theory | null |
_webmaster.92237 | I want to make sure visitors to my website have the best experience possible so I want them to be able to use LastPass and other Password Managers.Is there any way of identifying whether or not my visitors are using one of these plugins? | How can I tell if my website visitors are using LastPass or other password managers? | security;forms;ux | Yes.Users can install LastPass as a browser plugin. Thus you can rely on client side scripting languages to check if LastPass is installed. For instance, using NavigatorPlugins.plugins allows you to get the a PluginArray object, listing the plugins installed in the application:function getLastPassVersion() { var lastpass = navigator.plugins['LastPass']; if (lastpass === undefined) { // LastPass is not present return undefined; } return lastpass.version;}Note also that what you are asking for is commonly implemented and used by browser fingerprinting technologies. |
_codereview.35784 | I have this jQuery function I wrote up to set the size of an input based off of its data. In this case I have already figured out the widths for each character based off of a 12px font size for Helvetica.It's not super flexible or anything, but I would like to know if there is any good way to take what I have and maybe make it more elegant (or fewer lines of code).HTML:<input value=Some really long string about nothing important />CSS: body { font-family:Helvetica; font-size:12px;}span { padding:0; margin:0;}input { border:0;}JavaScript / jQuery:// Helvetica, 12px or 1.2em at 62.5%var str = $('input').val();var length = str.length;var charWidth = 0;for ( var i = 0; i < length; i++ ){ console.log(str[i]); if ( str[i] == f || str[i] == i || str[i] == I || str[i] == j || str[i] == l || str[i] == t ) { charWidth += 3; } if ( str[i] == r ) { charWidth += 4; } if ( str[i] == v || str[i] == x || str[i] == y || str[i] == z ) { charWidth += 5; } if ( str[i] == c || str[i] == k || str[i] == ) { charWidth += 6; } if ( str[i] == a || str[i] == A || str[i] == b || str[i] == d || str[i] == e || str[i] == F || str[i] == g || str[i] == h || str[i] == J || str[i] == L || str[i] == n || str[i] == o || str[i] == p || str[i] == q || str[i] == s || str[i] == T || str[i] == u || str[i] == V || str[i] == X || str[i] == Y || str[i] == Z || str[i] == 0 || str[i] == 1 || str[i] == 2 || str[i] == 3 || str[i] == 4 || str[i] == 5 || str[i] == 6 || str[i] == 7 || str[i] == 8 || str[i] == 9 ) { charWidth += 7; } if ( str[i] == B || str[i] == E || str[i] == K || str[i] == P || str[i] == S ) { charWidth += 8; } if ( str[i] == C || str[i] == D || str[i] == G || str[i] == H || str[i] == M || str[i] == N || str[i] == O || str[i] == Q || str[i] == R || str[i] == U || str[i] == w ) { charWidth += 9; } if ( str[i] == m || str == W) { charWidth += 11; }}$('input').css({'width': charWidth});jsFiddle | Input text sizing function | javascript;jquery | Here's how you could use a table array for the widths. I didn't fill in all the character widths (I just did lowercase) because it's tedious to build, but you can extend it to contain all the typeable characters that you want to support. I also made it a jQuery method that you can call like this: $(input).autoSize();Here's the code (also in a jsFiddle):(function() { var widths = [ // a, b, c, d, e, f, g 7, 7, 6, 7, 7, 3, 7, // h, i, j, k, l, m, n 7, 3, 3, 6, 3, 11, 7, // o, p, q, r, s, t, u 7, 7, 7, 4, 7, 3, 7, // v, w, x, y, z 5, 9, 5, 5, 5 ]; // character code our table starts with var lowWidth = 97; $.fn.autoSize = function() { return this.each(function() { var val = this.value; var totalWidth = 0, charIndex, ch; for (var i = 0, len = val.length; i < len; i++) { // get char code and see if it's in our width table charIndex = val.charCodeAt(i) - lowWidth; ch = val.charAt(i); if (charIndex >= 0 && charIndex < widths.length) { totalWidth += widths[charIndex]; } else if (ch == ' ') { // special case for space char // until the table contains all codes we need totalWidth += 6; } } $(this).css(width, totalWidth + px); }); }})();FYI, jQuery will also measure the natural width of any DOM element for you so you could also have a span that is styled with the right font that you insert this text into and then ask jQuery what it's width is. jQuery will temporarily make it position absolute (so it will layout to it's natural width) and then let the browser tell you how wide it is. This would be much, much more accurate than what you are doing.Letting jQuery measure it for you would look like this:$.fn.autoSize = function() { var testItem = $(#testWidth); return this.each(function() { // put the text into our test span testItem.text(this.value); $(this).width(testItem.width()); });}And, you'd have appropriate CSS for a testItem span (see the jsFiddle demo for details):jsFiddle demo: http://jsfiddle.net/jfriend00/jQ93f/ |
_webmaster.98335 | First off, sorry for my english. I am currently developing a new website that may be deployed in early 2017. This site may contain user login but that may be shipped later in that year. Now, I googled about https and I hear mixed opinions, google wants the web in https and may punish those who don't use https in the future. Mozilla will also favor https over http for its Firefox. Let's Encrypt make it for free. So far so good.What is worrying me is I read that many sites that switched to https suffered much lower revenues of adsense (I read also some terrible things about seo and ranking suffering after switching) and many returned again to http.How much truth is in the suffering of revenues due to switching to https? My website is still in development so I have actually no links needed to be reindexed. My site isn't a blog type. It mainly provides profiles on local artists in my country.The problem is I need every penny to cover the server and cdn hosting costs. I can't be sure how much using https will hurt the revenues. | Effect of choosing https over http in a new website for AdSense & SEO | seo;https;google adsense;advertising | For existing sites, switching from HTTP to HTTPS is in effect, starting over. All the ranking factors and metrics have to be rebuilt from scratch including links, trust metrics, etc. This is why all the negative hype.Switching from HTTP to HTTPS is disruptive and why people complain. It did not occur to them that there would be an additional cost to switching from HTTP to HTTPS. Conceptually, anytime there can be different content served, it is a new site. However, going beyond that, each domain name, no matter how it appears, for example, www.example.com versus example.com are stored in the index as separate sites. This includes HTTP versus HTTPS. There is a good reason for this despite the tradition where these sites wold normally be the same. Each of these sites within the index has to build trust and domain metrics all on their own. The largest factors would be trust and links.If you do not have a HTTP site and start with HTTPS, then there is no downside. You are not starting over but rather building metrics for a single site. For the record, Google may be a 900 pound gorilla, however, it does not make the rules. Each time it tries, it gets shutdown. Yes. Google wants the world to be HTTPS, however, it is fully your right to use HTTP and they will just have to deal with it. HTTP does make sense most of the time.Here is some of the backlash:http://searchengineland.com/seo-industry-tweets-reactions-googles-ssl-ranking-boost-199510Here is where HTTPS helps.Other than the obvious security argument which is a powerful one for both the user and web site owner, HTTPS is a trust metric that positively effects a sites Trust score. Today, there are many factors that can outweigh the effect of HTTPS, however, Google is making noises that HTTPS will have more than a the slight score increase it is today. And that makes sense.Considering the quality of the certificate, some companies do vet who they are giving certificates to, the value of the certificate can ensure to any search engine that the site ownership is actually verifiable. Google does use registration details in evaluating site trust, however, having an additional layer of vetting helps with trusting a site.As far as earnings with Adsense HTTP versus HTTPS, there is no difference. Any complaint is a result of the disruption in switching from HTTP to HTTPS. |
_unix.181857 | The LANGUAGE variable is supposed to set the default language and can be used to specify a set of languages, where the next language will be used if a message is not available in the first (previous) one.For example (as from gettext example) with 'sv:de' variable's value programs will show messages in Swedish and if such text is not found then in German.I want to use English language as my primary language and some other (let's say Russian language) as secondary:export LANGUAGE=en:ru; blablablabla: ^^^^^^^^^^^^^^^^^^**Russian error message used**Ok. Let's try another order:export LANGUAGE=ru:en; blablablabla: ^^^^^^^^^^^^^^^^^^**Russian error message used again**In the other words, it doesn't matter on which position English language was specified, it always has the lowest priority and a message will be shown at any other specified language if the message is defined for that language.The question: how can I specify English language as primary and any other language as secondary? And what's going on with the LANGUAGE variable?P.S. 'LC_MESSAGES' is set up to the English locale of course. | The 'LANGUAGE' locale variable - how to set English as primary language? A bug in gettext? | environment variables;locale | null |
_softwareengineering.51531 | I'm working on a web application where there will be many different users from all over the world making updates. I'm wondering what the best way to handle timezones would be? Ideally, as an event happens, all users view it using their local times.Should the server OS time be set to GMT, physical location time, or my development location time?Should the application logic (PHP) and database (MySQL) be set to store data as GMT or local time (local to users)?Is there an industry standard or even a simple/obvious solution that I'm just not seeing? | What is the best way to handle different TimeZones? | php;mysql | Save your events in MySQL's TIMESTAMP format - it is stored internally as UTC regardless of the server / user timezone. This way the data is portable regardless of your server's specific configuration. If you store it in any specific timezone, you will have much more work converting it into different timezones. Fetch it from the database into a numeric timestamp (using the UNIX_TIMESTAMP() function) for use with PHP's various date/time functions (such as date() ).You then need to set for each user the PHP timezone using date_default_timezone_set() - you can get that information either via user configurable settings or from the browser headers (less accurate). You can then use PHP date/time functions as you would normally, and the output will be in the user's timezone.Another alternative is to show relative time (for example: 5 hours and 2 minutes ago). |
_unix.158539 | With Fedora20 and built from sources qemu-2.1.1, I'm experiencing issues to run qemu with non-root privileges:% qemu-system-x86_64 -hda vdisk.img -m 512M -netdev tap,helper=/usr/libexec/qemu-bridge-helper,id=net0 -device e1000,netdev=net0failed to create tun device: Operation not permittedfailed to launch bridge helperqemu-system-x86_64: -netdev tap,helper=/usr/libexec/qemu-bridge-helper,id=net0: Device 'tap' could not be initializedTun device has proper permissions:% ls -la /dev/net/tuncrw-rw-rw- 1 root root 10, 200 Sep 30 09:22 /dev/net/tunqemu-bridge-helper has suid bit enabled, SELinux is disabled ('getenforce' returns Disabled). Whatever else am I missing? | running qemu on Fedora20 | fedora;virtualization;qemu | null |
_webmaster.79118 | When I tested my website in the past with powermapper tools, It suggested I should add a skip to content link hidden off-screen to help people with screen readers use the website.I can completely relate and so can this website: http://accessibility.oit.ncsu.edu/training/accessibility-handbook/skip-to-main-content.htmlThen I go look at Google's webmaster quality guidelines at:https://support.google.com/webmasters/answer/66353and it mentions that hidden text can be seen as deceptive.The only text I deliberately made hidden on my website is a Skip to content link which when clicked takes users to just past the common menu header (a.k.a. straight to where the content starts). I placed the hyperlink tag directly below the body tag, and used CSS to set the link as a block and positioned it to -xxxxpx (some location off screen) so that users with sufficient technologies won't see the skip to content link, but instead see the site as it is meant to be displayed.I'm curious of the best course of action to take. I could either:remove the skip to content link all together and make Google happy and possibly several other advertisers unhappyOrMake the skip to content link visible at the minimum font size acceptable by Google (whatever percent that is) and pray that no user complains.OrFigure out who runs Google and rant (which I will likely be unsuccessful at). | Would Google think a hidden skip to content link is deceptive? | links;anchor;hidden text;named anchor;colors | For what it's worth, I'll offer my own take on this. Hidden text alone is not deceptive. What you do with it is what determines whether it's deceptive.There are many scenarios in which hidden text is a good thing, both in terms of accessibility, functionality and just pure awesomeness. But there are also some setbacks, and times where hidden text may prevent certain users from being able to use the website as it was intended to be used.You must always take the common-sense approach. Do what is right for your users, and always follow the standards; if you can do that, nobody has the right to penalise you or your website, and if they do try, fight back.This page says that skip to main content links are good. Also, Google does not say that hidden text is bad, and it does not say that you will - or may - be penalised for using hidden text on your website.What Google does say, is:Hiding text or links in your content to manipulate Googles search rankings can be seen as deceptive and is a violation of Googles Webmaster Guidelines. Text (such as excessive keywords) can be hidden in several ways...And a little further down, they say:However, not all hidden text is considered deceptive.So basically, Google is saying this:'Hidden text is only considered bad if you are doing something bad with it (E.g. trying to manipulate the search rankings or trying to deceive your visitors/potential visitors).' |
_cogsci.16521 | I'm wondering if there exists a validated questionnaire designed to assess the duration/intensity/type of physical activity someone has taken part in over the past 1-3 days?I've seen many questionnaires (e.g. IPAQ, link to full questionnaire here) where the target time scale is 1 week, but I'm looking for something that captures exercise amount on a much shorter/recent time scaleIdeally it would also be short and quick to administer (for reference, I would consider both versions of the IPAQ too long)I ask because I'm interested in people's recent levels of exercise and I've tried administering a short questionnaire where I ask things like how many minutes of aerobic exercise did you do yesterday? but when I looked at the the data it turns out that >70% of people report 0, so I end up with a zero-inflated variable.This could be due to a poorly worded question, poor response format, or any number of reasons. Ideally, I would conduct a full survey design study and use factor analysis to create/validate a short form questionnaire, but at this point it might be easier to just use one that currently exists, if there is oneDoes anything like this already exist?ReferencesCraig, C. L., Marshall, A. L., Sandstrom, M., Bauman, A. E., Booth, M. L., Ainsworth, B. E., Oja, P. (2003). International Physical Activity Questionnaire: 12-Country Reliability and Validity. Medicine & Science in Sports & Exercise, 35(8), 13811395. https://doi.org/10.1249/01.MSS.0000078924.61453.FB | Exercise and physical activity questionnaire | cognitive psychology;measurement;experimental psychology;survey;exercise | null |
_cogsci.17041 | I'd appreciate some help from you guys. I'm currently analyzing an experiment where I've entrained participants to these frequencies: Condition 1: 4.16Hz-8.33HzCondition 2: 2.77Hz-8.33HzCondition 3: 2.4HzFor each condition I passed 8 trials of 26 seconds at Fs = 500Hz. I'm analysing the data using FieldTrip and some toolboxes in Matlab. I calculated the Power and PSD using pwelch function after processing the data in Fieldtrip. I want my data in dB units and get rid of the $1/f^\gamma$ trend where $0< \gamma<2$ (Demanuele et al., 2007)I have 2 problems:1) I don't know how to remove the 1/f trend correctly since I don't understand how the article that I mention does it (see below) in the frequency domain (I have tried fitting $1/f^\gamma$ with best $\gamma$, using the lsqcurvefit function. Using the medfilt1 with order 15 gives me the best results. Though I think there should be a better way, also that can be defended on an article). the spectrogram of one EEG channel was calculated. The median across all time windows was then found for every frequency point. Thus, a graph of the median PSD value for every frequency was obtained. The same procedure was repeated for all the EEG channels. Then, the overall median of the median PSD curves of all the channels was calculated. The same was done for each of the 'task' and 'rest' condition. The average was then calculated across all conditions and this was used as our normalisation curve.EDIT I thought it might be helpful to provide the code I made. Sorry for the inefficiencies you may find since I am no developer: % Choose subjectload matfiles/Subject05% loading subject5 where (channel,samples,trial,condition) is a 4D matrixsamples = numel(subject5(1,:,1,1)); % number of samples% Number of samples per window, the less windows the better frequency resolution and worst time resolution. I tried different windows. nsc = floor(samples/4.5);nov = floor(nsc*0.75); % overlap of 75% fr = 0.5:0.05:15; % foifs = 500; % sampling freq%initialize variablemedps = zeros(291,28,21,3);% loop conditionsfor cond = 1 : length(subject5(1,1,1,:)) %loop trials for trial = 1 : length(subject5(1,1,:,cond)) % loop channels for chan = 1 : length(subject5(:,1,trial,cond)) % calculate spectrogram for each channel, trial and condition %gives t(time) and ps (PSD estimate for each freq and time in Amplitude^2/Hz units) [~,~,t,ps] = spectrogram(subject5(chan,:,trial,cond),hamming(nsc),nov,fr,fs); % calculate median over time points per channel, trial and condition medps(:,chan,trial,cond) = median(ps,2); end endend%Calculate median over channels per trial and conditionmedchan = median(medps,2); %this produces matrix freqx1channelxtrialsxcondmedchan = permute(medchan,[1 3 4 2]); %get 4D into 3D %Calculate median over trials per conditionmedtrial = median(medchan,2); medtrial = permute(medtrial,[1 3 2]); %Get a 2D matrix freqxcond%Mean over conditions is our Normalization CurvenormalizationCurve = mean(medtrial,2);2) Once I transform the data to dB units (i.e. $10*log10$) it gets really noisy, making the peaks at the foi (frequencies of interest) as big as the background or almost. I've looked into SNR but really don't know how to apply it here. The only thing I've done and still doesn't remove all the noise is the medfilt1 mentioned in 1). I hope any of you with experience in this can help me solve this issue! | How to denoise and get rid of 1/f trend of a PSD in an EEG synchronization experiment | cognitive neuroscience;eeg;synchronization;analysis | null |
_unix.296122 | The machine I'm working from has many active X displays (one standard X server and many VNC displays). It is also running a handful of GUI applications, which appear on an X display.Assuming I have the PID (using ps) is there a method to determine which X screen the process is using, or even the value the DISPLAY variable held when launched?Even better if there's a method to show the value of DISPLAY for the process and all of its children process, in case some processes spawn their GUI as a child process. | Check which display an application is using | process;display;x server | If you have root access (or sudo ps) then you can display the environment of a process with the e option. Inside here you should be able to see the DISPLAY variable (if it's set). You probably need ww to ensure the output doesn't get truncated.e.g.% ps wwep $$ | tr ' ' '\012' | grep DISPLAYDISPLAY=:0So my current shell is talking to :0.Many OS's protect the environment from other users (because it may leak sensitive information), so a normal user can only see their own process environments. root can see every user's. |
_webmaster.104158 | Imagine I'm proprietor of two domains that are alias, i.e., they point exactly to the same server and folder: exemple.com and exemplo.comHowever, in that server I detect the country of the user, so that, for example:in UK it points to /index_en.html in Spain it points to /index_es.htmlQuestion: Which option is the best internationial SEO practise?allow the crawling of the four combinations, restricting only to exemple.com/index_en.html and exemplo.com/index_es.html and block exemple.com/index_es.html and exemplo.com/index_en.html avoiding thus crawling duplication, ordo not crawl alias and focusing only on one domain, for example example.com and simply make a permanent 301 forwarding from exemplo.com to example.com | Internationial SEO with different alias domains | seo;multiple domains;internationalization | Edit based on Joao's comment*The domains in question are cctld, i.e .es, .it, .pt. Geotargeted subfolders on country specific domains don't work well, if the top level domain is generic (i.e. .com) this solution works. Otherwise, from a pure best for ranking perspective, keeping cctlds that only serve one country is best, but, like every solution, each has it's drawbacks such as additional technical overhead and having to market/optimize each cctld independently rather than consolidating signals to one domain (subfolder approach).Edit endGreat question, I don't fully understand your setup but I think this should describe it and how to deal with it:Where...exemple.com/index_en.html === exemplo.com/index_en.html &&exemple.com/index_es.html === exemplo.com/index_es.htmlSetup:Your 3rd option is best, use 301 redirects to redirect all pages from exemplo.com to exemple.com on a 1:1 basis, i.e. redirect each page to its equivalent. You should determine which domain is the preferred domain by checking which one ranks better/gains more traffic (the preferred domain should also have higher external link count and links from decent websites)The preferred domain in this hypothetical scenario will be exemple.com. When a request originating from a UK IP to exemple.com, you will 302 redirect them to exemple.com/index_en.html. A request originating from Spain with a Spanish IP to exemple.com should 302 to exemple.com/index_es.html.That would be it - don't redirect any other requests on the domain, use hreflang to annotate the spanish and english versions accordingly.I did the Redbull.com setup and a friend of mine did theguardian.com. We followed Google engineer's advice despite doubting the 302 redirect. The hreflang lead, Christopher Semturs confirmed in a comment on a post I wrote here.I would highly advise you take precaution when consolidating your domains (vigoriously check google search console, run crawls, etc..) and test the international configuration (be ready to roll back immediately) as well. |
_reverseengineering.12125 | I have a vmlinux ELF file to run under QEMU.My arguments to qemu-system-arm.exe are:The correct -cpu argument.The versatilepb -machine which I'm not sure if it's the right choose, but can't see the other options with -cpu help.The -kernel flag to pass the vmlinux file.The -serial stdio -nographic flags with console=ttyAMA0 console=tty1 console=ttyS0 kernel arguments.Why I don't see any output? I also tried the -D flag to get a log file. | Running vmlinux ELF under QEMU | firmware;arm;qemu | null |
_scicomp.21234 | I would like to code for a quadtree type meshing but don't know how to do. If anyone can help or can share any starting code? | Quadtree type Grid | mesh generation;multigrid;grid | null |
_unix.195743 | I need to run a Java JAR Swing GUI executable in a Raspbian Wheezy Debian distribution inside an ARM device during boot time.I am following this as reference with myapp,myapp-start.sh and myapp-stop.sh, and this with possible solutions (and others more quite similar). But here is not reference to the DISPLAY variable.Ive checked a lot of alternatives, with Tried and not applicable Options:/usr/bin/java -jar -Djava.awt.headless=true $myapp.jarunset DISPLAY (inside myapp-start.sh, above the java -jar sentence)Errors: java.awt.HeadlessException: No X11 DISPLAY variable was set, but this program performed an operation which requires it.Tried Options (inside myapp-start.sh, above the java -jar sentence):export DISPLAY=:0export DISPLAY=:0.0export DISPLAY=localhost:0.0Errors:Can't connect to X11 window server using ':0.0' as the value of the DISPLAY variable...Client is not authorized to connect to ServerException in thread stack...Untried Optionsssh - X localhost: How should i do an ssh to the X11 server? Where should i execute that under an init.d process?. Is that the standard solution for running a Java program with GUI?.USER=root inside myapp-start.sh: The init.d stops, and request password. So smart, the process don`t start. Should any of the options above to be included in another place than the myapp-start.sh code? Where?Should not be simpler to run a single piece of code at startup?.Any other option, will be appreciated.EDIT 2015-04-12New OptionsIn the following options, i am adding a code inside this location /etc/xdg/lxsession/LXDE-pi/autostart for execution after the default user pi logs and X11 starts (see jlliagre suggestion):usr/bin/java -jar /home/pi/Embedded/bin/PowerBar.jar (no ampersand)export DISPLAY=:0.0usr/bin/java -jar /home/pi/Embedded/bin/PowerBar.jar (no ampersand)/bin/bash /home/pi/Embedded/bin/powerbarstart.sh (no ampersand)All them start the application in the background, that is, the background music is played, and the graphics are available only through a VNC at :0 (using TightVNC). As side effect, the screensaver activates, and the application freezes, each 60 seconds approx. Please note this same location is also used to disable the screensaver.Is there a missing option, or symbol, I am not including?.SolutionThe device was configured as :1.0 instead of :0.0. Changing this on the myapp-start.sh solved the issue. | How to setup DISPLAY to run a Java JAR Swing Executable from Init.d | debian;java;display;init.d | If your application is not interactive, you might launch a virtual X11 server and set the DISPLAY variable for your application to use it.Possible X11 servers that can be used that way are:XvfbXdummyXvncThe latter allows you to connect later to see and interact with the screen with a VNC client (vncviewer).If you Raspberry pi (or similar) is configured to autologin the pi user under a graphical environment, you can start your application as the pi user and use the :0 display. Beware that you have to make sure X11 has completed its startup before doing it.Edit: It looks like your configuration is launching a Xvnc server first as the pi user then is launching the frame buffer main X server as the root user. In that case, as you figured out, your application has to be started as root and using :1 as its display.Alternatively, if what you really want is not to start your application once at boot time but whenever a user (typically pi) logs in under a graphic environment, add it to the rc file applicable to this graphic environment. For example /etc/xdg/lxsession/LXDE-pi/autostart. |
_cs.55598 | Consider the alphabet E = ${[abc] : a, b, c \in 0,1,...,9)} $ Example [234], [567],[897] are symbols of the alphabet. For a string $w \in $ let n(w) denote the number represented by $ w $: Example for symbol [345], n([345]) = 345.1) Describe a DFA for the language of strings of the form $[x_0y_0z_0][x_1y_1z_1] [x_ny_nz_n]$ such that$n(x_n... x_1x_0) + n(y_n... y_1y_0) = n(z_n... z_1z_0)$This language corresponds of reading the numbers from right to left and positionby position; this is how we add numbers by hand.Example $[819][606][213]$ is in the language because 268 + 101 =369. How can we describe something like this? $M = (Q, E, d, q_0, F)$ where Q : ? E = ${[abc] : a, b, c \in 0,1,...,9)} $d: ?$q_0 = $F: ? | How do I describe a DFA? | automata;finite automata | null |
_unix.115415 | Is there an easy way to boot a Debian-based Linux system from a read-only medium (say a Live Linux read-only DVD) and then use Debian's .deb checksums / signatures (?) to verify that the files installed do indeed come from properly signed Debian packages?In other words: is it possible to boot a system from a known clean Live CD and then use Debian's package format as a poor man's intrusion detection system?If so, how should I go about it? | Verifying Debian/Ubuntu packages integrity when booting from a read-only DVD? | debian;package management;checksum;signature;chkrootkit | null |
_hardwarecs.68 | These four are the main I/O that you see. What are the pros/cons for each?As far as I know HDMI 2.0 supports higher fps than earlier HDMI as well as that Display Port supports high fps. Besides that I'm not positive on why I would connect my monitor with a certain cable. | What are the differences between monitors inputs (HDMI, Display Port, DVI, VGA)? | hdmi;display port;dvi;vga | I'll start with VGA, which is, in my opinion, a standard.VGA is an analog signal. This basically means that the quality will not be as great as cables that make use of digital signals, especially at high resolutions. The problem with analog is that noise often distorts the signal and the quality ends up not being as good. So in terms of quality, go for the other three.Digital signals do not have this problem because they are noise tolerant.DVI is a digital signal that has a few different connecter types and two link modes: DVI-A has an analog signal.DVI-D has only a digital signal.DVI-I has both, making it especially useful as it can be used with VGA-DVI adaptorsMost adaptors are single link and support a resolution up to 1920x1200 whereas dual link supports up to 2560x1600.HDMI is the standard for HDTVs. It is also a digital signal and is therefore fully compatible with DVI-D and DVI-I. The benifit of HDMI over DVI is that is has the ability to carry audio as well as the video signal although it does require that your monitor has built in speakers. Recently, HDMI 2.0 was released and gives HDMI the ability to better deal with 4K (Ultra HD) displays at a higher frequency and FPS. If your display or TV has HDMI 1.4, youll be limited to 3,8202160, 4K, at 30 Hz. However, if youve got a video card and 4K display with HDMI 2.0, youll be able to get 4K at 60 Hz.There's not much difference between between HDMI 1.4 and DVI besides the audio in the HDMI, which can be a real benefit depending on your setup and that colour ranges for HDMI go beyond the RGB spectrum which DVI is limited to. The only benefit of the DVI is the physical screws that support the DVI cable and help prevent port damage.DisplayPort is the newest of the lot and is aimed towards higher end monitors - newer and high-end monitors tend to have DisplayPort. Its designed to deal with 4K at higher FPS and Hz. DisplayPort is capable of 38402160, 8K at 60Hz or 4k at 120Hz!DisplayPort looks like it's the way of the future, especially if you want 4K.Generally it depends on your setup (monitor and graphics card), what you can and can't use but for the future of gaming DisplayPort looks the way to go.References and more info:http://www.makeuseof.com/tag/video-cables-explained-difference-vga-dvi-hdmi-ports/https://superuser.com/questions/15884/hdmi-vs-component-vs-vga-vs-dvi-vs-displayport http://www.avadirect.com/blog/displayport-vs-hdmi-vs-dvi-vs-vga/ |
_scicomp.7148 | Given a vector-valued Dolfin function u from the function space V*V with V=FunctionSpace(mesh, 'CG', 2), how do I extract$$\max_{x\in\Omega} \|u(x)\|$$? An approximation works, too. | compute max(||u||) for vector field | python;fenics | null |
_codereview.61576 | I have some JavaScript that was put together for functionality but I wanted to know if there was a better way to write it. As it stands it's a little hard to read and follow.$(document).ready(function(){var loop = null;$(li).click(function(){ $(li).css(box-shadow, none); $(.selector).css(visibility,hidden); var offSet = 7; if($(this).hasClass('Selected')){ $(this).removeClass('Selected'); $(this).children(div).css(visibility,hidden); $(this).css(box-shadow, none); } else{ $(li).removeClass('Selected'); $(this).addClass('Selected'); $(this).children(div).css(visibility,visible); $(this).css(box-shadow, inset 0 0 + offSet + px #333); }});$(#sideNav > ul > li).click(function(){ var element = $(#content); var offsetElement = $(#subSideNav); var width = 0; var offSet = parseInt(offsetElement.css(width)) + 2; if($(this).attr('id') === Selected && !element.hasClass('large')){ $(this).attr('id', ''); width = parseInt(element.css(width)) + 2; slider(element, offSet, 'hidden'); $(element).addClass('large'); } else if($(this).attr('id') !== 'Selected' && element.hasClass('large')){ $(#subSideNav).css('display', 'block'); $(this).attr('id', 'Selected'); width = parseInt(element.css(width)) - 2; slider(element, offSet, 'visible'); $(element).removeClass('large'); }else if($(this).attr('id') !== 'Selected' && !element.hasClass('large')){ $(#sideNav > ul > li).attr('id', ''); $(this).attr('id', 'Selected'); }});function slider(element, offSet, visibility){ var width = parseInt(element.css(width)); if('visible' === visibility){ width -= 1; } else{ width += 1; } offSet -= 1; if(0 < offSet){ element.css(width, width + px); loop = setTimeout(function(){slider(element, offSet, visibility)}, 5); } else{ clearTimeout(loop); }}})The functions are basically supposed to create a slider to adjust the width and two click events. One event make a cover selector div visible to let you know it has been clicked, and the other does the same plus triggering the slider function. The reason there are two different clicks is because there are two separate menus, and only one needs the slider function. | Creating a slider to adjust the width and two click events | javascript;jquery | null |
_unix.20000 | When I run sudo apt-get update I have the following output:Hit http://mirror.transact.net.au stable Release.gpgIgn http://mirror.transact.net.au/debian/ stable/contrib Translation-enIgn http://mirror.transact.net.au/debian/ stable/contrib Translation-en_AUIgn http://mirror.transact.net.au/debian/ stable/main Translation-enIgn http://mirror.transact.net.au/debian/ stable/main Translation-en_AUIgn http://mirror.transact.net.au/debian/ stable/non-free Translation-enIgn http://mirror.transact.net.au/debian/ stable/non-free Translation-en_AUHit http://mirror.transact.net.au stable Release Hit http://mirror.transact.net.au stable/main amd64 PackagesHit http://mirror.transact.net.au stable/contrib amd64 PackagesHit http://mirror.transact.net.au stable/non-free amd64 PackagesGet:1 http://www.debian-multimedia.org squeeze Release.gpg [198 B]Ign http://www.debian-multimedia.org/ squeeze/main Translation-enIgn http://www.debian-multimedia.org/ squeeze/main Translation-en_AUIgn http://www.debian-multimedia.org/ squeeze/non-free Translation-enIgn http://www.debian-multimedia.org/ squeeze/non-free Translation-en_AUGet:2 http://www.debian-multimedia.org squeeze Release [22.0 kB]Ign http://www.debian-multimedia.org squeeze ReleaseGet:3 http://www.debian-multimedia.org squeeze/main amd64 Packages [72.8 kB]Get:4 http://www.debian-multimedia.org squeeze/non-free amd64 Packages [3,902 B]Fetched 98.9 kB in 3s (32.6 kB/s) Reading package lists... DoneW: GPG error: http://www.debian-multimedia.org squeeze Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 07DC563D1F41B907I've scoured the web but can only find esoteric solutions I cannot understand. Is there a way to bypass the security feature blocking it without engaging in esoteric commandline? | Security hurdles to enabling sources in repo | repository | As you can find on the Debian Multimedia home pageThe first package to install is debian-multimedia-keyring.Since Squeeze you can install this package with apt-get but you need to press Y when the package ask what to do and do not press return. So, summing up, don't care about apt-get update warning, install the named package and answer Y when asked. |
_webmaster.54579 | My company uses CloudFlare for its DNS, but as our site is HTTPS-secured and we're on the free plan, we can't utilize CloudFlare's CDN services.Our host has fairly rare but not insignificant downtime. We can't migrate servers just yet, and I'd like to be able to either have the main domain redirect to the status domain, or simply resolve to the alternative status host in the event of downtime so users will stop bugging me asking if the site is down.Is this possible to do automatically using the free CloudFlare plan, or will I have to manually edit my DNS every time the site goes down? | CloudFlare DNS: Downtime failover host | dns;downtime;cloudflare | I've had a similar problem before and have solved it using CloudFlare's API. I had a Dedicated server and a large VPS for backup. Mirrored the data on the two servers, and used CloudFlare to switch between them (DNS Failover) if the Dedicated went down. Initially did reboots via SSH/IPMI to verify and it worked as configured.Here's the link to the article: http://blog.booru.org/?p=12 |
_cs.28624 | I have a directed acyclical graph. Each node represents an event with start and end dates and each edge represents a constraint between to events with 2 properties:max interval between previous event end and next event startmin interval between previous event end and next event startWhen an event's date is updated, all edge constraints should be respected and every other event's date should be recalculated if those constraints are violated. Problem is that there might be multiple conflicting constraints and I'm struggling to find best way to traverse the graph updating events without breaking previously satisfied constraints.I have no formal CS education and my knowledge in this area is quite limited. Is there an existing algorithm to solve my problem? | Satisfy edges' constraints when updating node in directed acyclical graph | graph traversal | null |
_datascience.2632 | I'm running a test on MapReduce algorithm in different environments, like Hadoop and MongoDB, and using different types of data. What are the different methods or techniques to find out the execution time of a query.If I'm inserting a huge amount of data, consider it to be 2-3GB, what are the methods to find out the time for the process to be completed. | Timing sequence in MapReduce | efficiency;map reduce;performance;experiments | null |
_unix.67861 | Once I've created a new tab in gnome-terminal with Ctrl+Shift+t, how can I switch back and forth between the tabs using the keyboard? For example, in Google Chrome the keyboard shortcut is Ctrl+Tab (forward) and Ctrl+Shift+Tab (backward).I'm using Linux Mint 14 Cinnamon. | Switch between tabs in gnome-terminal with keyboard? | terminal;keyboard shortcuts;tabs | Ctrl+Page Down (forward) and Ctrl+Page Up (backward). |
_unix.186935 | Using previous posts, I used the following command in fedora21 terminal to remove the external drive safely:# umount full_path_to_external_driveWhen I checked with the command df -k, the external looked removed, but its icon was seen in the desktop. If I clicked that icon, the external drive again got mounted. How can I remove the external drive safely in fedora21? | Removing external drive safely in Fedora21 | fedora | null |
_cs.26441 | I am confronted with task to find polynomial time complexity solution for weighted hitting set problem. I have found that usual hitting set problem is NP-complete and therefore the task seems to be contradictory.But there are several other reformulations of this problem. E.g. d-Hitting set problem can be solved in polynomial time (when each class or set contains no more than d elements).Maybe the weighted case has completely different algorithms and complexity estimation? Apparently the non-weighted problem is the special case of weighted one and therefore there should not be different complexity estimation, isn't so? | Can weighted problem have polynomial complexity if non-weighted problem is NP-complete: hitting set | complexity theory;time complexity;np complete;optimization | null |
_webapps.14639 | Gmail recently switched from links that would allow you to select multiple threads (read, unread, starred, none, etc.) to a drop down to do same: I would like my links back (one less click). Is there a way to switch back to the old view? | Can I get my links back in Gmail for selecting threads instead of the new drop down? | gmail;user interface | null |
_unix.52544 | I have two monitors, both 1600 x 900, running as a single x-screen.When I try to run a full screen application (a game for example), the application full screens as though my two monitors were one monitor at 3200 x 900.The center is then of course the crack between my two real monitors.How can I run such applications so that they only use one monitor, 1600x900, centered on one of the real monitors? | Two monitors and a single X-Screen: How to change full screen center and resolution | xorg;x11;dual monitor | null |
_cstheory.25529 | Aaronson recently wrote a blog refuting the idea that there could be some glitch in the formulation of the P vs NP conjecture[1] which reminds me of this following question.the Blum speedup theorem has been characterized by Goldreich [3] (p149)A conceptually related phenomenon is of problems that have no optimal algorithm (not even in a very mild sense); that is, every algorithm for these pathological problems can be drastically sped-up. It follows that the complexity of these problems can not be defined (i.e., as the complexity of the best algorithm solving this problem).in math, it is not unprecedented that major conjectures have been shown to have glitches eg discovery that they are independent of axiomatic systems, etc.also Goldreich reference to pathological languages is reminscent of historical consternations in math eg the counterintuitive discovery of functions that are continuous but nowhere differentiable eg the Weierstrauss function.another angle is that at least one complexity theorist expert Lipton speculates that program size is underanalyzed in TCS and may have surprising aspects,[2] and the Blum speedup theorem seems to fit in with this line of thinking, because the proof construction basically relies on improving the language recognition time based on increasing the size of the TM program (ie like a tradeoff).so:how does one show/ prove that no such pathological languages are/can be involved in open complexity class separation questions eg P=?NP etc?am interested in more technical/ mathematical perspectives that avoid handwaving. (eg something more detailed/ substantial than an assertion that the Blum speedup construction is contrived etc.)[1] Is the P vs. NP problem ill-posed? (Answer: no.) Aaronson blog[2] Does program size matter? RJLipton blog[3] Computational complexity: a conceptual perspective / Goldreich | proving speedup phenomenon does not apply to any open complexity class separations | cc.complexity theory;reference request;complexity classes;time complexity;big picture | null |
_unix.140221 | When working on certain projects, I routinely open a number of terminals, navigate each of them to various directories and resize and position them on my desktop. Is there any way to save this configuration, so that I can come back to this state easily?Ideally I would like to save the number of terminals and for each terminal:The position on the monitorThe window sizeThe current working directoryI'm using gnome shell, but I am very open to trying other desktop environments. | Is it possible to save the state of open terminals? | terminal;desktop environment | null |
_unix.298917 | We just updated our server from CentOS 6 to RHEL 7 and after setting up our HP LaserJet 600 from ppd, I'm noticing that all print jobs now have about a 2 margin at the top of the page. Is it possible to define margins in a configuration file? This reply suggests that margins can be set with some arguments to lpr, but I'd rather store them in a conf file. using lp: -o page-bottom=N-o page-left=N-o page-right=N-o page-top=NSets the page margins when printing text files. The values are in points - there are 72 points to the inch. | Set default margins in cups? | rhel;configuration;cups | Standard options can be set with the lpoptions command.If run as a normal user the file $HOME/.cups/lpoptions is set.If run as the root user then the system defaults /etc/cups/lpoptions is set.This can be used to change various settings (eg double sided printing) and page-top. |
_cs.47092 | Graphs are usually defined as a set of vertices $V$ together with a set of edges $E$ consisting of elements $V \times V$. I'm interested in a slight generalization of this, where instead one has two sets $V$, $W$ and the edges are taken from $V \times W$. The adjacency matrix of such an object would be rectangular, as opposed to the adjacency matrix of a regular old graph, which is square. Is there a name for this?I'm interested in this because I'm writing a data structure to represent a graph in terms of its partitioning into sub-graphs for the purposes of parallel computation. For example, given a graph $G$ on a vertex set $V$, we can partition $V$ into disjoint subsets $V_1$ and $V_2$; $G$ is then naturally divided into two subgraphs $G_1$ and $G_2$ describing connections among $V_1$ and $V_2$ respectively, and a rectangular graph $H$ describing connections between $V_1$ and $V_2$. I'd like to give the class a name that makes sense. | graph theory analogue of rectangular matrix | graph theory;graphs | Such a graph is known as a bipartite graph. There is a whole theory about bipartite graphs, including a number of algorithms that are specialized for bipartite graphs. |
_codereview.167521 | I have started to learn C and decided to recreate my bakery task in C.As I am new to the language, I am unsure if I have approached the task in the right way using structs. Feedback on the style of the code would also be appreciated.#include <stdio.h>double cup_ingredients[4] = {4.0,0.1,12.0,14.0}; // Amount of each ingredient for 1 cupcake = {Butter, eggs, flour, sugar}double lemon_ingredients[4] = {80.0,4.5,240.0,300.0}; // Amount of each ingredient for 1 lemon cake = {Butter, eggs, flour, sugar}double total[4];double cup_req;double lemon_req;struct Bags { int big_bag; int med_bag; int small_bag;};void calc_bag(double total_ingredient, struct Bags* bag_sizes, struct Bags* type);int main() { printf(How many cupcakes would you like? ); scanf(%lf, &cup_req); for (int x = 0; x<cup_req; x++){ // For the number of cupcakes required: for (int y = 0; y<4; y++){ // For each ingredient total[y] += cup_ingredients[y]; // Add the amount of each ingredient to the total amount of that ingredient } } printf(How many lemon cakes would you like? ); scanf(%lf, &lemon_req); for (int x = 0; x<lemon_req; x++){ // For the number of lemon cakes: for (int y = 0; y<4; y++){ // For each ingredient total[y] += lemon_ingredients[y]; // Add the amount of each ingredient to the total amount of that ingredient } } //Structs for the amount of each ingredient a bag can hold struct Bags Butter_size = {.big_bag = 500, .med_bag = 250, .small_bag = 125}; struct Bags Egg_size = {.big_bag = 12, .med_bag = 10, .small_bag = 6}; struct Bags Flour_size = {.big_bag = 750, .med_bag = 500, .small_bag = 250}; struct Bags Sugar_size = {.big_bag = 600, .med_bag = 400, .small_bag = 200}; //Set the bags required to 0 struct Bags Butter_req = {0,0,0}; struct Bags Egg_req = {0,0,0}; struct Bags Flour_req = {0,0,0}; struct Bags Sugar_req = {0,0,0}; //Calculate the amount of each ingredient bag required calc_bag(total[0], &Butter_size, &Butter_req); calc_bag(total[1], &Egg_size, &Egg_req); calc_bag(total[2], &Flour_size, &Flour_req); calc_bag(total[3], &Sugar_size, &Sugar_req); printf(\nButter: %d large bags, %d medium bags, %d small bags., Butter_req.big_bag, Butter_req.med_bag, Butter_req.small_bag); printf(\nEgg: %d large bags, %d medium bags, %d small bags., Egg_req.big_bag, Egg_req.med_bag, Egg_req.small_bag); printf(\nFlour: %d large bags, %d medium bags, %d small bags., Flour_req.big_bag, Flour_req.med_bag, Flour_req.small_bag); printf(\nSugar: %d large bags, %d medium bags, %d small bags., Sugar_req.big_bag, Sugar_req.med_bag, Sugar_req.small_bag);}void calc_bag(double total_ingredient, struct Bags* bag_sizes, struct Bags* type){ while (total_ingredient > 0){ if (total_ingredient > bag_sizes->big_bag) { type->big_bag++; total_ingredient -= bag_sizes->big_bag; } else if (total_ingredient > bag_sizes->med_bag) { type->med_bag++; total_ingredient -= bag_sizes->med_bag; } else if (total_ingredient > bag_sizes->small_bag) { type->small_bag++; total_ingredient -= bag_sizes->small_bag; } else { type->small_bag++; total_ingredient = 0; } }} | Calculate amount of necessary ingredients | beginner;c | I see some things that may help you improve your code.Eliminate function prototypes by orderingIf you put the calc_bag implementations above main in the source code, you don't need the function prototype. Avoid the use of global variablesI see that cup_ingredients and lemon_ingredients, etc. are declared as global variables rather than as local variables. It's generally better to explicitly pass variables your function will need rather than using the vague implicit linkage of a global variable. In this case, these should all be in main rather than global.Initialize variablesGlobal variables are initialized for you (to 0 for numeric variables), but local variables are not. For that reason, you should also get into the habit of initializing variables, ideally when they're declared. For example:double total[4] = {0.0, 0.0, 0.0, 0.0};double cup_req = 0.0;double lemon_req = 0.0;Use const where practicalThe ingredients lists cup_ingredients and lemon_ingredients, as well as the bag capacities Butter_size, etc. should all be constant. For that reason, they should all be declared static const as in:static const struct Bags Butter_size = {.big_bag = 500, .med_bag = 250, .small_bag = 125};Then the calc_bag function should be this:void calc_bag(double total_ingredient, const struct Bags* bag_sizes, struct Bags* type);Simplify by using a typedefThe code you have isn't wrong, but it's often convenient to use a typedef for structures that are used frequently. In this case, I'd suggest that your Bags structure could be this:typedef struct bags_s { int big_bag; int med_bag; int small_bag;} Bags;Then instead of writing struct Bags everywhere, you can simply write Bags.Prefer multiplication to iterationEspecially when using floating point numbers, it's most often better to multiply than to use iteration. For example, the code currently has this:printf(How many cupcakes would you like? );scanf(%lf, &cup_req);for (int x = 0; x<cup_req; x++){ for (int y = 0; y<4; y++){ total[y] += cup_ingredients[y]; }}That could be replaced by this:for (int i = 0; i < 4; ++i) { total[i] += cup_req * cup_ingredients[i];}Similarly, your calc_bag function could use division rather than iteration.Break up the code into smaller functionsThe main function is quite long and does a series of identifiable steps. Rather than having everything in one long function, it would be easier to read and maintain if each discrete step were its own function. I'd be inclined to divide it into separate input, calculation, and output stages, each with the appropriate function.Eliminate magic valuesThe value 4 is sprinkled through the code, but it really ought to be a named constant instead. I'd give it a meaningful name like this:#define INGREDIENT_COUNT 4Rethink your data structuresThe only difference between the cup_ingredients and lemon_ingredients is the name. They're parallel structures. This relationship could be made more clear by defining another structure which includes the name. One might write it like this:typedef struct recipe_s { char *name; double ingredients[INGREDIENT_COUNT];} Recipe;With that structure in place, one might rewrite main like this:int main() { static const char *ingredient_name[INGREDIENT_COUNT] = { butter, eggs, flour, sugar, }; static const Recipe recipes[] = { { cupcakes, {4.0,0.1,12.0,14.0} }, { lemon cakes, {80.0,4.5,240.0,300.0} }, }; static const int recipe_count = sizeof(recipes) / sizeof(recipes[0]); Recipe total = { total, {0.0, 0.0, 0.0, 0.0} }; for (int i = 0; i < recipe_count; ++i) { double qty; printf(How many %s would you like? , recipes[0].name); scanf(%lf, &qty); for (int j = 0; j < INGREDIENT_COUNT; ++j) { total.ingredients[j] += qty * recipes[i].ingredients[j]; } } //Structs for the amount of each ingredient a bag can hold static const Bags capacity[INGREDIENT_COUNT] = { { 500, 250, 125}, // butter { 12, 10, 6}, // eggs { 750, 500, 250}, // flour { 600, 400, 200}, // sugar }; // make a shopping list Bags shopping_list[INGREDIENT_COUNT] = { {0, 0, 0}, // butter {0, 0, 0}, // eggs {0, 0, 0}, // flour {0, 0, 0}, // sugar }; //Calculate the amount of each ingredient bag required for (int i = 0; i < INGREDIENT_COUNT; ++i) { calc_bag(total.ingredients[i], &capacity[i], &shopping_list[i]); printf(%s: %d large bags, %d medium bags, %d small bags.\n, ingredient_name[i], shopping_list[i].big_bag, shopping_list[i].med_bag, shopping_list[i].small_bag ); }}I'll leave it to you to divide that into smaller functions, but it should help you get an idea of how to write better C. Other enhancementsI would be very disappointed if my grocer actually handed me a bag of eggs. Instead, the common quantities for different things have different units of measure such as a dozen or a kilogram or a pound. Using a similar idea of associating a name with constants (as with the recipes shown above), you might want to associate units of measure with each kind of ingredient.Also, our lemon cake does not appear to have lemon as an ingredient, which makes it a somewhat less appealing confection. Consider adding the ability to create arbitrary lists of named ingredients, consolidating them into a shopping list as above. |
_unix.355839 | When I attempt to autocomplete ssh in zsh, I am presented with two types of lists.$ ssh a<TAB> -- remote host name --aur -- login name --avahiHowever, the latter is not useful to me. Is it possible to suppress everything under -- login name --, leaving only entries under -- remote host name --?I also get multiple entries when using rsync, although the headings differ.$ rsync a<TAB> -- user --avahi -- host --aurI'd like to suppress entries under -- user -- here.Possibly pertinent informationI use zim. Also, the following is in ~/.zshrc.h=()if [[ -r ~/.ssh/config ]]; then h=($h ${${${(@M)${(f)$(cat ~/.ssh/config)}:#Host *}#Host }:#*[*?]*})fiif [[ $#h -gt 0 ]]; then zstyle ':completion:*:ssh:*' hosts $h zstyle ':completion:*:slogin:*' hosts $h zstyle ':completion:*:rsync:*' hosts $hfiThis a workaround for a bug in zim where tab completion works with hostnames instead of hosts. | Can I suppress autocomplete of a certain category in zsh? | zsh;autocomplete | You can use the users style:zstyle ':completion:*' usersSetting an empty list like this disables completion on user names. You can narrow it down to individual commands, if you like:zstyle ':completion:*:rsync:*' usersfor example, would disable it for rsync but leave it on elsewhere.The zsh completion system is very sophisticated, and its configuration complex. The zshcompsys man page covers the new style of completion, as demonstrated here, and the zstyle command is documented in the zshmodules man page. |
_cs.56590 | Is there a name for graphs which contain oriented and non-oriented edges?I couldn't find on the internet if there exist a specific name for such graphs. | Is there a name for graphs which contain oriented and non-oriented edges? | graph theory;graphs;terminology | They are called mixed graphs. |
_softwareengineering.146140 | After reading this interesting question, I felt like I had a good idea of which insecure hashing algorithm I'd use if I needed one, but no idea why I might use a secure algorithm instead.So what is the distinction? Isn't the output just a random number representing the hashed thing? What makes some hashing algorithms secure? | What makes a hashing algorithm secure? | security;hashing | There are three properties one wants from every cryptographic hash function H:preimage resistance: Given h, it should be hard to find any value x with h = H(x).second preimage resistance: Given x1, it should be hard to find x2 != x1 with H(x1) = H(x2).collision resistance: It should be hard to find two values x1 != x2 with H(x1) = H(x2).With hash functions as used in common programming languages for hash tables (of strings), usually none of these is given, they only provide for:weak collision resistance: For randomly (or typically) selected values of the domain, the chance of collision is small. This says nothing about an attacker intentionally trying to create collisions, or trying to find preimages.The three properties above are (among) the design goals for every cryptographic hash function. For some functions (like MD4, SHA-0, MD5) it is known that this failed (at least partially). The current generation (SHA-2) is assumed to be secure, and the next one (Secure Hash Algorithm 3) is currently in the process of being standardized, after a competition.For some uses (like password hashing and key derivation from passwords), the domain of actually used values x is so small that brute-forcing this space becomes feasible with normal (fast) secure hash functions, and this is when we also want:slow execution: Given x, it takes some minimum (preferably configurable) amount of resources to calculate the value H(x).But for most other uses, this is not wanted, one wants instead:fast execution: Given x, calculating the value of H(x) is as fast as possible (while still secure).There are some constructions (like PBKDF2 and scrypt) to create a slow hash function from a fast one by iterating it often.For some more details, have a look at the hash tag on our sister site Cryptography Stack Exchange. |
_webapps.35864 | Some time ago I created an account on Trello. Now I see that you can log in with a Google account. How can change my current Trello account to log in with my Google account? | How can I change account type on Trello? | trello;google account | null |
_unix.152124 | in this example it is a full ipip is: 1.1.1.1-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -s 1.1.1.1 -j ACCEPTbut suppose i want to allow any ip that simply starts with:1.1.because for example my internet ip always starts with 1.1. but rest changes time to time.i want to be able to do something like this:-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -s 1.1.* -j ACCEPTi do not think this will work because i think in world of computers they use ranges and etc rather than the wild card symbols. Range stuff looks very complex to me. is there something like this with a wild card style concept ? | How to use partial IP address in /etc/sysconfig/iptables for the -s flag? | linux;centos;security;iptables;ip | To specify the ip address 1.1.*, you would use 1.1.0.0/16. This notation is used for CIDR (classless inter-domain routing) and is the standard method used to specify blocks of addresses. The /16 indicates the network includes all of the lower 16 bits of the address, so it matches in this case the address block from 1.1.0.0 to 1.1.255.255. |
_unix.280406 | In AIX we can view raw data of hdisk by issuing following comamandlquerypv -h /dev/hdisk0This displays data in hexa decimal format. More of like hex editor.What is the equivalent command in Linux based system | AIX lquerypv equivalent in Linux (RHEL/Cent OS) | linux;centos;rhel | This is what i was looking for. Finally i got it with the help of cfdisk command.cfdisk -P r /dev/sdaWhere sda is your disk, P is for printing partition table to screen and r is for print raw output.Here is the sample output. |
_unix.306468 | I just wanted to upgrade my ubuntu server from 14.04 to 16.04 LTS. During the installation of the packages my screen went off, showing 'no signal'. Normally this happens in screen energy saving mode. So i pressed arrow keys and tab keys on my keyboard but the screen is not coming back.I still have access to the server via ssh. How can i tell now when the upgrade process is complete? | No video signal during release upgrade | upgrade;video | I just got back into the session via SSH.While the upgrading process all stuff is running in a screen started by root. So first check, which screen root is using:chris@server15:~$ sudo screen -listThere is a screen on: 6208.ubuntu-release-upgrade-screen-window (19/08/2016 05:20:12 PM) (Detached)1 Socket in /var/run/screen/S-root.So you can easily connect to this screen that contains the upgrade process:chris@server15:~$ sudo screen -x -rNow i was able to answer configuration file questions and complete the whole upgrade up to the reboot process. Puh! :) |
_codereview.160905 | I am just new to programming I just have a 2 month experience in programming and a 2 week experience with python.This is my chess game written in python with pygame.Can some one help me how can I improve this program ?p.s. this is not a AI chess game it is a multiplayer game; also the checkmate condition is not yet implemented, I'd like to clean up what I have (which works as intented) before I go and implement it.import pygameimport timepygame.init()# defines the width and height of the displaydisplay_width = 600display_height = 680# defines block width and heightblock_height = 50 * 1.5block_width = 50 * 1.5factor = 25 * 1.5# defines colourswhite = (255, 255, 255)d_white = (250, 250, 250)black = (0, 0, 0)teal = (0, 128, 128)blue_black = (50, 50, 50)game_display = pygame.display.set_mode((display_width, display_height))pygame.display.update()clock = pygame.time.Clock()selected_family = blackclass piece: x = 0 # x coordinate y = 0 # y coordinate rank = # rank of the piece life = True # is the piece dead or alive family = # colour of the piece (black or white) pic = # photo of the piece def __init__(self, x_position, y_position, p_rank, p_family): self.x = x_position self.y = y_position self.rank = p_rank self.family = p_familyselected_piece = pieceend_piece = piecepie = [piece(3, 7, q, black), piece(0, 6, p, black), piece(1, 6, p, black), piece(2, 6, p, black), piece(2, 0, b, white), piece(5, 0, b, white), piece(0, 0, r, white), piece(7, 0, r, white), piece(3, 6, p, black), piece(4, 6, p, black), piece(5, 6, p, black), piece(6, 6, p, black), piece(7, 6, p, black), piece(1, 0, k, white), piece(6, 0, k, white), piece(4, 0, king, white), piece(0, 1, p, white), piece(1, 1, p, white), piece(2, 1, p, white), piece(3, 1, p, white), piece(4, 1, p, white), piece(5, 1, p, white), piece(6, 1, p, white), piece(7, 1, p, white), piece(3, 0, q, white), piece(2, 7, b, black), piece(5, 7, b, black), piece(0, 7, r, black), piece(7, 7, r, black), piece(1, 7, k, black), piece(6, 7, k, black), piece(4, 7, king, black) ]print(pie[0].x, pie[0].y)def initialize_piece(): i = 0 while i < len(pie): if pie[i].rank == p and pie[i].life: if pie[i].family == white: img = pygame.image.load(pawn_white.png) else: img = pygame.image.load(pawn_black.png) game_display.blit(img, ((2 * pie[i].x) * factor, ((2 * pie[i].y) * factor))) elif pie[i].rank == q and pie[i].life: if pie[i].family == white: img = pygame.image.load(queen_white.png) else: img = pygame.image.load(queen_black.png) game_display.blit(img, ((2 * pie[i].x) * factor, ((2 * pie[i].y) * factor))) elif pie[i].rank == b and pie[i].life: if pie[i].family == white: img = pygame.image.load(bishop_white.png) else: img = pygame.image.load(bishop_black.png) game_display.blit(img, ((2 * pie[i].x) * factor, ((2 * pie[i].y) * factor))) elif pie[i].rank == r and pie[i].life: if pie[i].family == white: img = pygame.image.load(rook_white.png) else: img = pygame.image.load(rook_black.png) game_display.blit(img, ((2 * pie[i].x) * factor, ((2 * pie[i].y) * factor))) elif pie[i].rank == k and pie[i].life: if pie[i].family == white: img = pygame.image.load(knight_white.png) else: img = pygame.image.load(knight_black.png) game_display.blit(img, ((2 * pie[i].x) * factor, ((2 * pie[i].y) * factor))) elif pie[i].rank == king and pie[i].life: if pie[i].family == white: img = pygame.image.load(king_white.png) else: img = pygame.image.load(king_black.png) game_display.blit(img, ((2 * pie[i].x) * factor, ((2 * pie[i].y) * factor))) i += 1def clear(): i = 0 while i < len(pie): if (pie[i].x + pie[i].y) % 2 == 0: pygame.draw.rect(game_display, d_white, ((2 * pie[i].x + 1) * 25, ((2 * pie[i].y + 1) * 25), 12, 12)) else: pygame.draw.rect(game_display, blue_black, ((2 * pie[i].x + 1) * 25, ((2 * pie[i].y + 1) * 25), 12, 12)) i += 1def move(orignal_x, orignal_y, final_x, final_y): val = False t = 9 final_pie = piece # print(final_x, +, final_y) global selected_family fam = selected_family for i in range(len(pie)): final_pie = None if pie[i].x == orignal_x and pie[i].y == orignal_y and pie[i].life and pie[i].family == fam: for k in range(len(pie)): if pie[k].x == final_x and pie[k].y == final_y and pie[k].life: final_pie = pie[k] t = k break # If the pieces are not of same family then if pie[i].rank == 'p' and final_pie != None: if final_pie.family != pie[i].family and orignal_x != final_x: if orignal_x + 1 == final_x or orignal_x - 1 == final_x: if pie[i].family == black: direction = -1 else: direction = 1 if orignal_y + direction == final_y: pie[t].life = False pie[i].x = final_x pie[i].y = final_y if pie[i].family == white: selected_family = black else: selected_family = white clear() print(pie[t].x, final_pie.y, <--) else: val = True if pie[i].rank == 'q' and final_pie != None: if pie[t].family != pie[i].family: if check_queen(orignal_x, orignal_y, final_x, final_y): pie[t].life = False pie[i].x = final_x pie[i].y = final_y if pie[i].family == white: selected_family = black else: selected_family = white clear() # print(pie[t].x, final_pie.y, <--) clear() else: val = True if pie[i].rank == 'b' and final_pie != None: if pie[t].family != pie[i].family: if diagonalcheck(orignal_x, orignal_y, final_x, final_y): print(yaah) pie[t].life = False pie[i].x = final_x pie[i].y = final_y if pie[i].family == white: selected_family = black else: selected_family = white clear() # print(pie[t].x, final_pie.y, <--) clear() else: val = True if pie[i].rank == 'r' and final_pie != None: if pie[t].family != pie[i].family: if check_rook(orignal_x, orignal_y, final_x, final_y): print(yaah) pie[t].life = False pie[i].x = final_x pie[i].y = final_y if pie[i].family == white: selected_family = black else: selected_family = white clear() clear() else: val = True if pie[i].rank == 'k' and final_pie != None: if pie[t].family != pie[i].family: if knight_check(orignal_x, orignal_y, final_x, final_y): print(yaah) pie[t].life = False pie[i].x = final_x pie[i].y = final_y if pie[i].family == white: selected_family = black else: selected_family = white clear() clear() else: val = True if pie[i].rank == 'king' and final_pie != None: if pie[t].family != pie[i].family: if king_check(orignal_x, orignal_y, final_x, final_y): pie[t].life = False pie[i].x = final_x pie[i].y = final_y if pie[i].family == white: selected_family = black else: selected_family = white clear() clear() else: val = True if val is False: for i in range(len(pie)): if pie[i].x == orignal_x and pie[i].y == orignal_y and pie[i].family == selected_family: clear() if pie[i].rank == p: if pie[i].family == black: direction = -1 else: direction = 1 if orignal_y == 6 or orignal_y == 1: if final_y == orignal_y + (2 * direction) and final_x == orignal_x: rigt_upfront = False for k in range(len(pie)): if pie[k].y == orignal_y + direction and pie[k].x == orignal_x: rigt_upfront = True if not rigt_upfront: pie[i].x = final_x pie[i].y = final_y if pie[i].family == white: selected_family = black else: selected_family = white if final_y == orignal_y + direction and final_x == orignal_x: pie[i].x = final_x pie[i].y = final_y if pie[i].family == white: selected_family = black else: selected_family = white if pie[i].rank == q: if check_queen(orignal_x, orignal_y, final_x, final_y): pie[i].x = final_x pie[i].y = final_y if pie[i].family == white: selected_family = black else: selected_family = white if pie[i].rank == b: if diagonalcheck(orignal_x, orignal_y, final_x, final_y): if diagonal(orignal_x, orignal_y, final_x, final_y): pie[i].x = final_x pie[i].y = final_y if pie[i].family == white: selected_family = black else: selected_family = white if pie[i].rank == r: if check_rook(orignal_x, orignal_y, final_x, final_y): pie[i].x = final_x pie[i].y = final_y if pie[i].family == white: selected_family = black else: selected_family = white if pie[i].rank == k: if knight_check(orignal_x, orignal_y, final_x, final_y): pie[i].x = final_x pie[i].y = final_y if pie[i].family == white: selected_family = black else: selected_family = white if pie[i].rank == king: if king_check(orignal_x, orignal_y, final_x, final_y): pie[i].x = final_x pie[i].y = final_y if pie[i].family == white: selected_family = black else: selected_family = whitedef check_queen(x_i, y_i, x_f, y_f): col = True if x_i == x_f and y_i != y_f: a = 0 b = 0 if y_i > y_f: a = y_i b = y_f else: a = y_f b = y_i for i in range(b, a): if i == b: col = True else: for k in range(len(pie)): if pie[k].x == x_f and pie[k].y == i and pie[k].life: col = False elif x_i != x_f and y_i == y_f: a = 0 b = 0 if x_i > x_f: a = x_i b = x_f else: a = x_f b = x_i for i in range(b, a): if i == b: col = True else: for k in range(len(pie)): if pie[k].y == y_f and pie[k].x == i and pie[k].life: col = False elif diagonalcheck(x_i, y_i, x_f, y_f): if diagonal(x_i, y_i, x_f, y_f): col = True else: col = False return coldef king_check(x_i, y_i, x_f, y_f): col = False if x_i+1 == x_f and y_i == y_f: col = True elif x_i + 1 == x_f and y_i +1 == y_f: col = True elif x_i + 1 == x_f and y_i -1 == y_f: col = True elif x_i-1 == x_f and y_i == y_f: col = True elif x_i - 1 == x_f and y_i +1 == y_f: col = True elif x_i - 1 == x_f and y_i -1 == y_f: col = True elif x_i == x_f and y_i -1 == y_f: col = True elif x_i == x_f and y_i -1 == y_f: col = True elif x_i == x_f and y_i -1 == y_f: col = True return coldef check_rook(x_i, y_i, x_f, y_f): col = True if x_i == x_f and y_i != y_f: a = 0 b = 0 if y_i > y_f: a = y_i b = y_f else: a = y_f b = y_i for i in range(b, a): if i == b: col = True else: for k in range(len(pie)): if pie[k].x == x_f and pie[k].y == i and pie[k].life: col = False elif x_i != x_f and y_i == y_f: a = 0 b = 0 if x_i > x_f: a = x_i b = x_f else: a = x_f b = x_i for i in range(b, a): if i == b: col = True else: for k in range(len(pie)): if pie[k].y == y_f and pie[k].x == i and pie[k].life: col = False else: col = False return coldef knight_check(i_x, i_y, f_x, f_y): t = False if i_x+1 == f_x and i_y+2 == f_y: t = True elif i_x+1 == f_x and i_y-2 == f_y: t = True elif i_x-1 == f_x and i_y+2 == f_y: t = True elif i_x-1 == f_x and i_y-2 == f_y: t = True elif i_x+2 == f_x and i_y+1 == f_y: t = True elif i_x+2 == f_x and i_y-1 == f_y: t = True elif i_x-2 == f_x and i_y+1 == f_y: t = True elif i_x-2 == f_x and i_y-1 == f_y: t = True return tdef diagonalcheck(i_x, i_y, f_x, f_y): dir_x = 0 dir_y = 0 th = False a = i_x b = i_y if i_x < f_x: dir_x = +1 elif i_x > f_x: dir_x = -1 if i_y < f_y: dir_y = 1 elif i_y > f_y: dir_y = -1 while a < 8 and a >= 0 and b < 8 and b >= 0 and dir_x != 0 and dir_y != 0: if a == f_x and b == f_y: print(yes) th = True a += dir_x b += dir_y return thdef diagonal(i_x, i_y, f_x, f_y): dir_x = 0 dir_y = 0 th = True a = i_x b = i_y if i_x < f_x: dir_x = +1 elif i_x > f_x: dir_x = -1 if i_y < f_y: dir_y = 1 elif i_y > f_y: dir_y = -1 print(a =, a, ,b =, b, ,dir x =, dir_x, ,dir y =, dir_y, ,final x =, f_x, final y =, f_y) while a != f_x and b != f_y: for i in range(len(pie)): print(a =, a, ,b =, b) if pie[i].x == a + dir_x and pie[i].y == b + dir_y: th = False a = a + dir_x b = b + dir_y if i_x == f_x or i_y == f_y: th = False return thdef board_draw(): x = 0 y = 0 game_display.fill(black) selected_family = black for i in range(8): if i % 2 == 0: j = 0 else: j = 1 while j < 8: pygame.draw.rect(game_display, d_white, (i * 50 * 1.5, j * 50 *1.5, block_width, block_height)) j += 2def select_block(x_cursor, y_cursor): selected_piece = None for i in range(len(pie)): if pie[i].x == x_cursor and pie[i].y == y_cursor: return pie[i]def game(): selec = False global selected_family while True: for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONUP: pos = pygame.mouse.get_pos() a = pos[0] // 75 b = pos[1] // 75 pygame.draw.rect(game_display, teal, (a * 50 * 1.5, b * 50 * 1.5, block_width, block_height)) pygame.display.update() time.sleep(0.03) if not selec: selected_piece = select_block(a, b) selec = True if selected_piece is not None: print(selected_piece.x, , selected_piece.y) else: selec = False else: if selected_piece is not None: move(selected_piece.x, selected_piece.y, a, b) selec = False if event.type == pygame.QUIT: pygame.quit() quit() board_draw() initialize_piece() myfont = pygame.font.Font(sans.ttf, 30) string = selected_family +'s turn label = myfont.render(string, 1, white) game_display.blit(label, (20, 620)) pygame.display.update() clock.tick(20)game() | First chess game | python;pygame;chess | Your function initialize_piece could be way simpler if you used a dictionary to map from the piece rank to the file name and used str.format to supply the family into the string:file_names = {p: pawn_{}.png, ...} def initialize_piece(): for piece in pie: if piece.life: img = pygame.image.load(file_names[piece.rank].format(piece.family) game_display.blit(img, ((2 * piece.x) * factor, ((2 * piece.y) * factor)))This could be simplified even further if every piece had for example pawn as rank, so that you could add a file_name property (and a position property):class piece: x = 0 # x coordinate y = 0 # y coordinate rank = # rank of the piece, e.g. pawn life = True # is the piece dead or alive family = # colour of the piece (black or white) pic = # photo of the piece def __init__(self, x_position, y_position, p_rank, p_family): self.x = x_position self.y = y_position self.rank = p_rank self.family = p_family @property def file_name(self): return {self.rank}_{self.family}.png.format(self=self) @property def position(self): return ((2 * self.x) * factor, ((2 * self.y) * factor))With this it would become:def initialize_piece(): for piece in pie: if piece.life: img = pygame.image.load(piece.file_name) game_display.blit(img, piece.position)In addition to this, you should work on your style. Python has an official style-guide, PEP8. It recommends using CAPITAL_LETTERS for constants, lower_case for variables and functions and PascalCase for classes.In addition, you should get rid of your global variables as much as possible, they make it very hard to follow the program flow. Instead, pass the variables as arguments where necessary:def initialize_piece(pieces): for piece in pieces: if piece.life: img = pygame.image.load(piece.file_name) game_display.blit(img, piece.position)What would make it even better is if the image was only loaded once per piece:class Piece: def __init__(self, x, y, rank, family): self.x, self.y = x, y # rank of the piece, e.g. pawn self.rank = rank # colour of the piece (black or white) self.family = family self.file_name = {}_{}.png.format(rank, family) self.img = pygame.image.load(self.file_name) @property def position(self): return ((2 * self.x) * factor, ((2 * self.y) * factor))def initialize_piece(pieces): for piece in pieces: if piece.life: game_display.blit(piece.img, piece.position)Here I also removed the unnecessary initializations in the class, you don't need to initialize variables in Python. The comments could be moved to a docstring, for documentation purposes.Finally, something I have already done above, you should learn how to iterate properly. In Python iterating over the indices of a list (and even worse, using a while loop where a for loop would be a lot easier) is frowned upon.Instead of any of these:l = [1, 2, 3, 4, 5]i = 0while i < len(l): do_something(l[i]) i += 1for i in range(len(l)): do_something(l[i])you should just use:for x in l: do_something(x)If you really need the index, use enumerate:for i, x in enumerate(l): do_something(i, x)I will leave the rest for somebody else... |
_softwareengineering.119795 | We are trying to have our own startup, with a middleware application to glue small applications with enterprise legacy systems.for such middle-ware to function properly, we will need some sort of messaging system to make different components talk to each other in a reliable way. the alternatives are:use an existing messaging system, such as 0MQ, jBOSS, WebSphere MQ, etc.build our own messaging system the way we see the problemI am more biased towards the later option for the following reasons:to have more control over our final productto avoid any licensing problems later onto learn about messaging while writing the codeto invent something new, that might cost us lots of $$$ if reused an existing systemWhat would you do if in my shoes? | Write own messaging system vs. utilize existing ones | design;message queue;messaging | Since you are a startup I would say it depends on two things.Do you have any time constraints on this?Will building your own messaging system give you an advantage?I don't know what kind of business your startup is in but in general its best to focus on great user experience in the beginning. The code running in the back may be awful but the user will never know that, he'll just notice if the user interface is easy to use.So given that you have some time constraints, if the messaging system doesn't give you anything that makes a great difference for your application, I would use an existing one.It's tested, it's used and there is a knowledge base. |
_unix.322401 | I have the following scenario.I have a Perl script that takes an ID and looks up some arguments from a DB.lets say look_up_args.pl 234 prints the following abc 123 something with spacesI have another shell script script.sh that does the followingsome_command --param1 $1 --param2 $2 --par3 $3 ...what I am trying to do is to call the script with the argumentsI have tried the following 2 methods ./script.sh `./look_up_args.pl 234`./script.sh $(./look_up_args.pl 234)still whenever I run the script.sh, $3 seems to contain only something causing my script to fail. I am looking for away to pass the quoted string with out any form of shell expansion/etc... The third parameter may contain other special bash characters, but will always be quoted. | How to pass arguments to a script that were generated by another script | shell script;perl;arguments;output | I wouldn't recommend this, but try:eval ./script.sh $(./look_up_args.pl 234)This should work, but keep in mind that eval will evaluate whatever look_up_args.pl happens to output, meaning you leave yourself vulnerable to code injection.A better option would be what @thrig suggested in the comments: use a standardized data format to pass data between tools. Even a newline-delimited string would be a fine format for a shell-style processing pipeline. |
_unix.268765 | My goal is to make,for testing purposea multipath lvm iscsiI have setup two debianiscsi server,workingsI have setup the multipath ona debian client and i cancreate dirs,etc on ext4 fs.But if server1 goes downthe fs is stucked(hang)Why?This is my multipath.confdefaults { udev_dir /dev polling_interval 5 path_grouping_policy multibus path_checker directio prio const rr_min_io 100 rr_weight priorities failback immediate no_path_retry fail}blacklist { devnode ^(ram|sda|raw|loop|fd|md|dm-|sr|scd|st)[0-9]* devnode ^hd[a-z][[0-9]*] devnode ^vd[a-z] devnode ^cciss!c[0-9]d[0-9]*[p[0-9]*]}multipaths { multipath { wwid 149455400000000009d1b03a0217052c8b19b0fa6e5bfe7bd alias iscsi_storage }} | Linux and iscsi multipath | multipath storage | The answer is: not possibleDual-primary DRBD, iSCSI, and multipath: Dont Do That!Dual-primary iSCSI targets for multipath: does not work. iSCSI is a stateful protocol, there is more to it that than just reads and writes. To run multipath (or multi-connections per session) against distinct targets on separate nodes youd need to have cluster aware iSCSI targets which coordinate with each other in some fashion. To my knowledge, this does not exist (not for Linux, anyways). |
_webmaster.99007 | I have Google Adsense several years ago and I have gotten purchased from Google several times too. One of my websites has been stopped showing ads (I manage to upgrade it and it is an welcome page only).From long time I have not login to my Adsense account, but today I have login in and I found the total balance is -$86.53 USD as shown in the screen shot:What's happening there? Do I have lost my balance? What I have to do? | Google Adsense records current balance as negative value | google adsense | The below attachment is from Official Adsense Team.It is a glitch in their system nothing to be worried about.It will be fixed very soon!Latest News,Trending Topics on Info BuzzMusic Streaming Website - PCILY |
_codereview.9 | I have a method that has a lot of loops:private void update(double depth) { Console.WriteLine(update with level + depth); this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate() { List<Grid> grids = new List<Grid>(); Dependencies.Children.Clear(); Grid g = new Grid(); //Canvas.SetZIndex(g, 100); g.Width = 50; g.Height = 50; g.Tag = focus; Ellipse e = new Ellipse(); e.Width = 50; e.Height = 50; e.Fill = Brushes.Red; if (depth == 1) { Canvas.SetTop(g, 163); } else if (depth == 2) { Canvas.SetTop(g, 108); } else if (depth == 3) { Canvas.SetTop(g, 81); } else if (depth == 4) { Canvas.SetTop(g, 65); } else if (depth == 5) { Canvas.SetTop(g, 54); } else if (depth == 6) { Canvas.SetTop(g, 46); } Canvas.SetLeft(g, 500); g.Children.Add(e); Viewbox box = new Viewbox(); box.Width = e.Width; box.Height = e.Height; TextBox txt = new TextBox(); txt.Text = focus.getName(); box.Child = txt; txt.Background = Brushes.Transparent; txt.BorderBrush = Brushes.Transparent; g.Children.Add(box); grids.Add(g); List<SourceFile> list = new List<SourceFile>(); list = focus.getInvocations(); int counter = 1; foreach (SourceFile sf in list) { Grid g1 = new Grid(); //Canvas.SetZIndex(g, 101); g1.Width = 50; g1.Height = 50; g1.Tag = sf; Ellipse e1 = new Ellipse(); //Dependencies.Children.Add(e1); sf.setGrid(g1); e1.Width = 50; e1.Height = 50; e1.Fill = Brushes.Red; g1.Children.Add(e1); if (depth == 1) { Canvas.SetTop(g1, 488); } else if (depth == 2) { Canvas.SetTop(g1, 324); } else if (depth == 3) { Canvas.SetTop(g1, 244); } else if (depth == 4) { Canvas.SetTop(g1, 195); } else if (depth == 5) { Canvas.SetTop(g1, 163); } else if (depth == 6) { Canvas.SetTop(g1, 139); } Canvas.SetLeft(g1, counter * (1000 / (list.Count + 1) )); Viewbox box1 = new Viewbox(); box1.Width = g1.Width; box1.Height = g1.Height; TextBox txt1 = new TextBox(); txt1.Text = sf.getName(); txt1.Background = Brushes.Transparent; txt1.BorderBrush = Brushes.Transparent; box1.Child = txt1; g1.Children.Add(box1); Line l = new Line(); //Canvas.SetZIndex(l, 1); l.Stroke = Brushes.Green; l.StrokeThickness = 10; Binding x1 = new Binding(); x1.Path = new PropertyPath(Canvas.LeftProperty); x1.Converter = new MyConverter(); x1.ConverterParameter = g; Binding y1 = new Binding(); y1.Path = new PropertyPath(Canvas.TopProperty); y1.Converter = new MyConverter(); y1.ConverterParameter = g; Binding x2 = new Binding(); x2.Path = new PropertyPath(Canvas.LeftProperty); x2.Converter = new MyConverter(); x2.ConverterParameter = g1; Binding y2 = new Binding(); y2.Path = new PropertyPath(Canvas.TopProperty); y2.Converter = new MyConverter(); y2.ConverterParameter = g1; x1.Source = y1.Source = g; x2.Source = y2.Source = g1; l.SetBinding(Line.X1Property, x1); l.SetBinding(Line.Y1Property, y1); l.SetBinding(Line.X2Property, x2); l.SetBinding(Line.Y2Property, y2); Dependencies.Children.Add(l); l.Tag = new Call(focus, sf); Contacts.AddPreviewContactDownHandler(l, OnLineDown); counter++; grids.Add(g1); SizeChangedEventHandler act = (Object s, SizeChangedEventArgs args) => { BindingOperations.GetBindingExpressionBase(l, Line.X1Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.Y1Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.X2Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.Y2Property).UpdateTarget(); }; g.SizeChanged += act; g1.SizeChanged += act; } int counter2 = 1; if (depth >= 2) { int invocCount = 0; foreach (SourceFile s in list) { foreach (SourceFile source in s.getInvocations()) { invocCount = invocCount + s.getInvocations().Count; } } Console.WriteLine(invocCount); foreach (SourceFile s in list) { foreach (SourceFile source in s.getInvocations()) { Console.WriteLine(`Found invocation of + s.getName() + : + source.getName()); Grid g1 = new Grid(); g1.Width = 50; g1.Height = 50; Ellipse e1 = new Ellipse(); // Canvas.SetZIndex(g1, 102); grids.Add(g1); e1.Width = 50; e1.Height = 50; e1.Fill = Brushes.Red; source.setGrid(g1); g1.Tag = source; g1.Children.Add(e1); if (depth == 2) { Canvas.SetTop(g1, 540); } else if (depth == 3) { Canvas.SetTop(g1, 406); } else if (depth == 4) { Canvas.SetTop(g1, 325); } else if (depth == 5) { Canvas.SetTop(g1, 271); } else if (depth == 6) { Canvas.SetTop(g1, 232); } Canvas.SetLeft(g1, counter2 * (1000 / (invocCount + 1))); Viewbox box1 = new Viewbox(); box1.Width = g1.Width; box1.Height = g1.Height; TextBox txt1 = new TextBox(); txt1.Text = source.getName(); txt1.Background = Brushes.Transparent; txt1.BorderBrush = Brushes.Transparent; box1.Child = txt1; g1.Children.Add(box1); Line l = new Line(); //Canvas.SetZIndex(l, 2); l.Stroke = Brushes.Green; l.StrokeThickness = 10; Binding x1 = new Binding(); x1.Path = new PropertyPath(Canvas.LeftProperty); x1.Converter = new MyConverter(); x1.ConverterParameter = s.getGrid(); Binding y1 = new Binding(); y1.Path = new PropertyPath(Canvas.TopProperty); y1.Converter = new MyConverter(); y1.ConverterParameter = s.getGrid(); Binding x2 = new Binding(); x2.Path = new PropertyPath(Canvas.LeftProperty); x2.Converter = new MyConverter(); x2.ConverterParameter = g1; Binding y2 = new Binding(); y2.Path = new PropertyPath(Canvas.TopProperty); y2.Converter = new MyConverter(); y2.ConverterParameter = g1; x1.Source = y1.Source = findGrid(grids, s, source); x2.Source = y2.Source = g1; l.SetBinding(Line.X1Property, x1); l.SetBinding(Line.Y1Property, y1); l.SetBinding(Line.X2Property, x2); l.SetBinding(Line.Y2Property, y2); Dependencies.Children.Add(l); l.Tag = new Call(s, source); Contacts.AddPreviewContactDownHandler(l, OnLineDown); counter2++; SizeChangedEventHandler act = (Object o, SizeChangedEventArgs args) => { BindingOperations.GetBindingExpressionBase(l, Line.X1Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.Y1Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.X2Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.Y2Property).UpdateTarget(); }; source.getGrid().SizeChanged += act; g1.SizeChanged += act; } } } int counter3 = 1; if (depth >= 3) { int invocCount = 0; foreach (SourceFile s in list) { foreach (SourceFile source in s.getInvocations()) { foreach (SourceFile s1 in source.getInvocations()) { invocCount = invocCount + source.getInvocations().Count; } } } foreach (SourceFile s in list) { foreach (SourceFile source in s.getInvocations()) { foreach (SourceFile s1 in source.getInvocations()) { Grid g1 = new Grid(); grids.Add(g1); g1.Width = 50; g1.Height = 50; g1.Tag = s1; Ellipse e1 = new Ellipse(); e1.Width = 50; e1.Height = 50; e1.Fill = Brushes.Red; s1.setGrid(g1); g1.Children.Add(e1); if (depth == 3) { Canvas.SetTop(g1, 569); } else if (depth == 4) { Canvas.SetTop(g1, 455); } else if (depth == 5) { Canvas.SetTop(g1, 379); } else if (depth == 6) { Canvas.SetTop(g1, 325); } Canvas.SetLeft(g1, counter3 * (1000 / (invocCount + 1))); Viewbox box1 = new Viewbox(); box1.Width = g1.Width; box1.Height = g1.Height; TextBox txt1 = new TextBox(); txt1.Background = Brushes.Transparent; txt1.BorderBrush = Brushes.Transparent; txt1.Text = s1.getName(); box1.Child = txt1; g1.Children.Add(box1); Line l = new Line(); //Canvas.SetZIndex(l, 2); l.Stroke = Brushes.Green; l.StrokeThickness = 10; Binding x1 = new Binding(); x1.Path = new PropertyPath(Canvas.LeftProperty); x1.Converter = new MyConverter(); x1.ConverterParameter = source.getGrid(); Binding y1 = new Binding(); y1.Path = new PropertyPath(Canvas.TopProperty); y1.Converter = new MyConverter(); y1.ConverterParameter = source.getGrid(); Binding x2 = new Binding(); x2.Path = new PropertyPath(Canvas.LeftProperty); x2.Converter = new MyConverter(); x2.ConverterParameter = g1; Binding y2 = new Binding(); y2.Path = new PropertyPath(Canvas.TopProperty); y2.Converter = new MyConverter(); y2.ConverterParameter = g1; x1.Source = y1.Source = findGrid(grids, source, s1); x2.Source = y2.Source = g1; l.SetBinding(Line.X1Property, x1); l.SetBinding(Line.Y1Property, y1); l.SetBinding(Line.X2Property, x2); l.SetBinding(Line.Y2Property, y2); Dependencies.Children.Add(l); l.Tag = new Call(source, s1); Contacts.AddPreviewContactDownHandler(l, OnLineDown); counter3++; SizeChangedEventHandler act = (Object o, SizeChangedEventArgs args) => { BindingOperations.GetBindingExpressionBase(l, Line.X1Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.Y1Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.X2Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.Y2Property).UpdateTarget(); }; s1.getGrid().SizeChanged += act; g1.SizeChanged += act; } } } } int counter4 = 1; if (depth >= 4) { int invoCount = 0; foreach (SourceFile s in list) { foreach (SourceFile source in s.getInvocations()) { foreach (SourceFile s1 in source.getInvocations()) { foreach (SourceFile s2 in s1.getInvocations()) { invoCount = invoCount + s1.getInvocations().Count; } } } } foreach (SourceFile s in list) { foreach (SourceFile source in s.getInvocations()) { foreach (SourceFile s1 in source.getInvocations()) { foreach (SourceFile s2 in s1.getInvocations()) { Grid g1 = new Grid(); grids.Add(g1); g1.Width = 50; g1.Height = 50; g1.Tag = s2; Ellipse e1 = new Ellipse(); e1.Width = 50; e1.Height = 50; e1.Fill = Brushes.Red; s2.setGrid(g1); g1.Children.Add(e1); if (depth == 4) { Canvas.SetTop(g1, 585); } else if (depth == 5) { Canvas.SetTop(g1, 488); } else if (depth == 6) { Canvas.SetTop(g1, 418); } Canvas.SetLeft(g1, counter4 * (1000 / (invoCount + 1))); Viewbox box1 = new Viewbox(); box1.Width = g1.Width; box1.Height = g1.Height; TextBox txt1 = new TextBox(); txt1.Background = Brushes.Transparent; txt1.BorderBrush = Brushes.Transparent; txt1.Text = s2.getName(); box1.Child = txt1; g1.Children.Add(box1); Line l = new Line(); //Canvas.SetZIndex(l, 2); l.Stroke = Brushes.Green; l.StrokeThickness = 10; Binding x1 = new Binding(); x1.Path = new PropertyPath(Canvas.LeftProperty); x1.Converter = new MyConverter(); x1.ConverterParameter = s1.getGrid(); Binding y1 = new Binding(); y1.Path = new PropertyPath(Canvas.TopProperty); y1.Converter = new MyConverter(); y1.ConverterParameter = s1.getGrid(); Binding x2 = new Binding(); x2.Path = new PropertyPath(Canvas.LeftProperty); x2.Converter = new MyConverter(); x2.ConverterParameter = g1; Binding y2 = new Binding(); y2.Path = new PropertyPath(Canvas.TopProperty); y2.Converter = new MyConverter(); y2.ConverterParameter = g1; x1.Source = y1.Source = findGrid(grids, s1, s2); x2.Source = y2.Source = g1; l.SetBinding(Line.X1Property, x1); l.SetBinding(Line.Y1Property, y1); l.SetBinding(Line.X2Property, x2); l.SetBinding(Line.Y2Property, y2); Dependencies.Children.Add(l); l.Tag = new Call(s1, s2); Contacts.AddPreviewContactDownHandler(l, OnLineDown); counter4++; SizeChangedEventHandler act = (Object o, SizeChangedEventArgs args) => { BindingOperations.GetBindingExpressionBase(l, Line.X1Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.Y1Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.X2Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.Y2Property).UpdateTarget(); }; s2.getGrid().SizeChanged += act; g1.SizeChanged += act; } } } } } int counter5 = 1; if (depth >= 5) { int invoCount = 0; foreach (SourceFile s in list) { foreach (SourceFile source in s.getInvocations()) { foreach (SourceFile s1 in source.getInvocations()) { foreach (SourceFile s2 in s1.getInvocations()) { foreach (SourceFile s3 in s2.getInvocations()) { invoCount = invoCount + s2.getInvocations().Count; } } } } } foreach (SourceFile s in list) { foreach (SourceFile source in s.getInvocations()) { foreach (SourceFile s1 in source.getInvocations()) { foreach (SourceFile s2 in s1.getInvocations()) { foreach (SourceFile s3 in s2.getInvocations()) { Grid g1 = new Grid(); g1.Width = 50; g1.Height = 50; grids.Add(g1); g1.Tag = s3; Ellipse e1 = new Ellipse(); //Dependencies.Children.Add(e1); e1.Width = 50; e1.Height = 50; e1.Fill = Brushes.Red; s3.setGrid(g1); g1.Children.Add(e1); if (depth == 5) { Canvas.SetTop(g1, 596); } else if (depth == 6) { Canvas.SetTop(g1, 511); } Canvas.SetLeft(g1, counter5 * (1000 / (invoCount + 1))); Viewbox box1 = new Viewbox(); box1.Width = g1.Width; box1.Height = g1.Height; TextBox txt1 = new TextBox(); txt1.Background = Brushes.Transparent; txt1.BorderBrush = Brushes.Transparent; txt1.Text = s3.getName(); box1.Child = txt1; g1.Children.Add(box1); Line l = new Line(); //Canvas.SetZIndex(l, 2); l.Stroke = Brushes.Green; l.StrokeThickness = 10; Binding x1 = new Binding(); x1.Path = new PropertyPath(Canvas.LeftProperty); x1.Converter = new MyConverter(); x1.ConverterParameter = s2.getGrid(); Binding y1 = new Binding(); y1.Path = new PropertyPath(Canvas.TopProperty); y1.Converter = new MyConverter(); y1.ConverterParameter = s2.getGrid(); Binding x2 = new Binding(); x2.Path = new PropertyPath(Canvas.LeftProperty); x2.Converter = new MyConverter(); x2.ConverterParameter = g1; Binding y2 = new Binding(); y2.Path = new PropertyPath(Canvas.TopProperty); y2.Converter = new MyConverter(); y2.ConverterParameter = g1; x1.Source = y1.Source = findGrid(grids, s2, s3); x2.Source = y2.Source = g1; l.SetBinding(Line.X1Property, x1); l.SetBinding(Line.Y1Property, y1); l.SetBinding(Line.X2Property, x2); l.SetBinding(Line.Y2Property, y2); l.Tag = new Call(s2, s3); Contacts.AddPreviewContactDownHandler(l, OnLineDown); Dependencies.Children.Add(l); counter5++; SizeChangedEventHandler act = (Object o, SizeChangedEventArgs args) => { BindingOperations.GetBindingExpressionBase(l, Line.X1Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.Y1Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.X2Property).UpdateTarget(); BindingOperations.GetBindingExpressionBase(l, Line.Y2Property).UpdateTarget(); }; s3.getGrid().SizeChanged += act; g1.SizeChanged += act; } } } } } } foreach (Grid grid in grids) { Dependencies.Children.Add(grid); Contacts.AddPreviewContactDownHandler(grid, DownOnSourceFile); } } )); }Is there any easy way to improve that? And to make it working not only for 6 steps but also for n steps? | Too many loops in Drawing App | c#;performance;algorithm | Break this down into several methods - it's very long, meaning it's not easy to read. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.