id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_softwareengineering.342190
The code listed below is intended to calculate some rotation data which will later get used in my rendering code.renderer.cpp:rendered_image renderer::common_tasks(render_info const& info) { //info.radius is a float, info.min_image_size is an int calculated by taking the minimum //of info.image_width and info.image_height cl_float raw_delta = 2.f * info.radius / info.min_image_size; //cl_float4 is functionally a wrapper around float[4]. //info.rotation is a float value representing the rotation in degrees cl_float4 final_deltas{ cos(to_radians(info.rotation)) * raw_delta, sin(to_radians(info.rotation)) * raw_delta, -sin(to_radians(info.rotation)) * raw_delta, cos(to_radians(info.rotation)) * raw_delta }; //Other, irrelevant code /*...*/}But of course, I wanted to clean up the code a bit, so I rewrote it like this:renderer.cpp:cl_float4 get_deltas(render_info const& info) { //info.radius is a float, info.min_image_size is an int calculated by taking the minimum //of info.image_width and info.image_height cl_float raw_delta = 2.f * info.radius / info.min_image_size; //cl_float4 is functionally a wrapper around float[4]. //info.rotation is a float value representing the rotation in degrees cl_float4 final_deltas{ cos(to_radians(info.rotation)) * raw_delta, sin(to_radians(info.rotation)) * raw_delta, -sin(to_radians(info.rotation)) * raw_delta, cos(to_radians(info.rotation)) * raw_delta }; return final_deltas;}rendered_image renderer::common_tasks(render_info const& info) { cl_float4 final_deltas = get_deltas(info); //Other, irrelevant code /*...*/}Now, however, I have a globally declared function get_deltas that only exists in this .cpp file. As-is, this code compiles and runs normally, but are there any significant risks to me writing code like this? Should I be nesting the function in a namespace or declare it private in the renderer class? I know for a fact that I will never need to use get_deltas anywhere else in my code: does that change whether this is a good or bad use of this code style?
Is it safe to define a utility function for local use in my .cpp file?
c++
As a matter of principle private or local methods should always either be private members of the class or static local functions. Declaring a function as static it becomes file scope and the linker will throw an error if it is attempted to be used outside of the scope of the file that it is declared in.You can also use the anonymous namespace to achieve the same thing which is more verbose but some places prefer.One of the major reasons is that, while you may never intend to use get_deltas elsewhere someone else might at sometime in the life of the program, possibly as a typo, and then there is a reasonable chance that the program will compile and link without errors, (you should get a warning), but will have an obscure and hard to locate bug.
_webmaster.12108
I'm relocating my client's pages to a new server. Their old system was running Plesk and had some email groups and a few mail forwards defined. The new server has no Plesk and I'd really rather not install it just for the email groups either, so I'm looking for a new alternative for creating and managing the lists.Their main site is going to run on Drupal 6.x, so a module for that would be the preferred choice. I tried searching for one myself, but to no avail.Anything else that gets the job done will do as well, as long as the client who is not very tech-savvy can modify and add lists herself. The server is a Debian 5, root access is available.Any suggestions are highly appreciated.
Mail group managers similar to Plesk
drupal;email;linux;mailing list;plesk
What I finally ended up with was Sympa. It's a pain to set up the www interface, but I finally got it working with lighttpd. A Drupal module would have been nice but this solution is totally acceptable as well.
_codereview.101886
I'm designing a Factory in C++ with raw pointers, but I'd like to use smart pointers when possible as is recommended with the Factory pattern in newer C++. Unfortunately my compiler is a bit old (gcc 4.4.6) and not all of the features of C++11 (let alone C++0x) are available to me.I cannot use nullptr, which is the most troubling aspect to me. I'd love a standard review and any tips for adding smart pointers to my code.#ifndef SERVICE_FACTORY_H_#define SERVICE_FACTORY_H_#include <string>#include <map>#include <memory>class Service { public: virtual void free() = 0;};typedef Service* (*CreationFunction)(void);class Counter : public Service { public: static Service* create() { return new Counter(); } void free() { delete this; }};class ServiceFactory { public: ~ServiceFactory() { _registeredServices.clear(); } static ServiceFactory* getInstance() { static ServiceFactory instance; return &instance; } void registerService(const std::string &serviceName, CreationFunction fn) { _registeredServices[serviceName] = fn; } Service* createService(const std::string &serviceName) { auto it = _registeredServices.find(serviceName); if(it != _registeredServices.end()) return it->second(); return NULL; } private: ServiceFactory() { registerService(COUNTER, &Counter::create); } ServiceFactory(const ServiceFactory&) { /* Nothing implemented yet */ } ServiceFactory& operator=(const ServiceFactory&) { return *this; } std::map<std::string, CreationFunction> _registeredServices;};#endif // SERVICE_FACTORY_H_EDIT Here's a driver:#include ServiceFactory.h#include <iostream>int main() { Service* counter = ServiceFactory::getInstance()->createService(COUNTER); if(counter) { std::cout << Counter was made. << std::endl; counter->free(); } else { std::cout << Counter was not made. << std::endl; } return 0;}Here's the compilation process succeeding on ideone (with C++14).
Factory with raw pointers
c++;c++11
null
_unix.180769
Is there any way to change to the text console scrolling speed without rebooting? Currently using Fedora, but non-distribution-specific answers appreciated.https://www.kernel.org/doc/Documentation/fb/vesafb.txtI'd like to use 'ywrap' in the above documented kernel parameters for vesafb without having to reboot the kernel to try it.
change linux text console scrolling speed - without rebooting
linux;console;text;framebuffer
null
_unix.194366
I am using btrFS as a filesystem for my external harddrive.I'd like to use it under Android. Is there any painless way to do so?
Mount BTRFS on Android (usb OTG)
android;btrfs;usb otg
null
_webmaster.100852
I have a client with two products on one page.However, when I test my mark up, it is only recognising one. <script type=application/ld+json>{ @context: http://schema.org/, @type: Product, name: Example Product, image: https://www.example.co.uk/~/media/example/product%20images/g/gv15120_h328.png, description: Vitamins, brand: { @type: Thing, name: Client3 }, aggregateRating: { @type: AggregateRating, ratingValue: 4.2, reviewCount: 4842}, offers: { @type: Offer, priceCurrency: GBP, price: 11.95, sku: 120}, offers: { @type: Offer, priceCurrency: GBP, price: 19.95, sku: 240 }}</script>Does anyone have any advice?
How do I mark up multi product pages with Schema.org and JSON-LD?
schema.org;json ld
I assume you mean two Offer items for one Product (like your example suggests).Instead of repeating the offers property, you have to use one offers property with an array value (in [ and ]):offers: [ { @type: Offer }, { @type: Offer }]
_unix.106094
I read this from here:The most useful combination is the Alt+SysRq/Prnt Scrn + R-E-I-S-U-B.The above basically means that while you press and hold Alt+SysRq/Prnt Scrn and press R, E, I, S, U, B giving sufficient time between each of these keys to ensure they perform the required job.My question is: How long should I wait to ensure sufficient time between each of these keys?
How long should I wait between keystrokes when doing SysRq + REISUB?
linux;crash;magic sysrq
Forget about REISUB. I don't know who invented this, but it's overly complicated: half the steps are junk. If you're going to unmount and reboot, you only need two steps: U and B. At most three steps E, U, B.Alt+SysRq+R resets the keyboard mode to cooked mode (where typing a character inserts that character). That's useful if a program died and left the console in raw mode. If you're going to reboot immediately, it's pointles.Alt+SysRq+E and Alt+SysRq+I kills processes. E sends processes the SIGTERM signal, which causes some programs to save their state (but few do this). If you do E, there's no fixed delay: typically, after a few seconds, either the program has done what it was going to do or it won't do it. I sends processes the SIGKILL signal, which leaves the system unusable (only init is still running) and is pointles anyway if you're going to reboot immediately.Alt+SysRq+S synchronizes the file contents that are not yet written to disk. U does that first thing, so doing S before U is pointless.Alt+SysRq+U remounts filesystems read-only. If you can see the console, wait until the message Emergency Remount complete. Otherwise, wait until disk activity seems to have died down.Finally Alt+SysRq+B reboots the system without doing anything, not even flushing disk buffers (so you'd better have done it afterwards, preferably as part of Alt+SysRq+U which marks disks as cleanly unmounted).
_codereview.104102
I am looking to improve my code structure. In this code it is opening all the links with ?pid= in the url. However, the structure of the code can be improved.for a in self.soup.find_all(href=True): href = a['href'] if not href or len(href) <= 1: continue if href[0] == '/': href = (domain_link + href).strip() if href.lower().find(?pid=) != -1: href = href.strip() elif 'javascript:' in href.lower(): continue elif 'reviews' in href.lower(): continue elif href[:4] == 'http': if href.lower().find(?pid=) != -1: href = href.strip() elif href[0] != '/' and href[:4] != 'http': href = ( domain_link + '/' + href ).strip() if href.lower().find(?pid=) != -1: href = href.strip() if '#' in href: indx = href.index('#') href = href[:indx].strip() if href in links: continue links.append(self.re_encode(href))self.dict['a_href'] = links
Opening all the links
python;url;beautifulsoup
null
_unix.316492
How do I change the font size on a POS58 printer in Linuxmint 18? After altering the printer so that it is now seen as usb Unknown, it prints but the font is too small to read. How can I change the font size so that I can read it? It is a POS 58 thermal printer from china, and after installing the printer drivers from the manufacturer, it could be seen but it wouldn't print until I saw a post whereby you changed the URL from a socket to usb, then it at least printed.
changing printer POS58 font
usb;cups;printer
null
_codereview.150102
I've been working on Python for the past few weeks trying to get my head around it's syntax/naming conventions/style/etc. I decided to make a monty hall sim to see how it looks in python. For those who don't know what the Monty Hall problem is, check the second paragraph here.I've verified the code is fully functional and gives the right results. It IS indeed best to swap every time. After spending time getting rid of duplicated effort, overly wordy statements, and many logic errors, I'd like to know how to improve my code readability and efficiency (both here and in general).Specific to this code, here's what I'd like to know (mostly #1):If possible, how could I make this more efficient?Is having a function call in the first for loop a good idea? If not, where do I put it?I keep feeling like this is longer than needed. Are there still places I can cut out code?import randomdef setup(): # Basic greeting/explaining what to do. print(\n\nThere are 3 doors. One is a winner. The computer) print(will try guess the right one. After the first ) print(guess, one door is shown to be a loser. The computer ) print(can then change it's choice to the remaining door.\n) # Display choices and get input change_choice = input(Should the computer always change it's choice? y/n\n:> ) runs = int(input(How many times should this run?\n:> )) run(change_choice, runs)def run(change_choice, times_to_run): wins = 0 #Correct door choices # Loop through calling the function with switching enabled or not for i in range(times_to_run): if change_choice == 'y' or change_choice == 'Y': wins = wins + setupDoors(True) else: wins = wins + setupDoors(False) # Display amount of times won/percentage of games won statistics(wins, times_to_run)def setupDoors(always_change_choice): # Set up the winning door winning_door = random.randint(1,3) print(\nThe winning door is +str(winning_door)) # Get the computer's guessed door computer_guess = random.randint(1,3) print(the computer guessed door number +str(computer_guess)) return playGame(winning_door, computer_guess, always_change_choice)def playGame(winning_door, computer_guess, always_change_choice ): # Get the right door to open. # Can't be the computer's door OR the winning door opened_door = getAvailableDoor(computer_guess, winning_door) print(Door number +str(opened_door)+ was opened and shown not to be a winning door.) #Swap the computer's choice to last door if that was desired if always_change_choice: computer_guess = getAvailableDoor(computer_guess, opened_door) print(The computer changed it's guess to door number +str(computer_guess)) # Return a win or a loss. if computer_guess == winning_door: print(The computer won!) return 1 else: print(The computer lost!) return 0def getAvailableDoor(computer_guess, unavailable_door): # List of doors to choose from Doors = [1,2,3] for i in range(3): if Doors[i] == computer_guess or Doors[i] == unavailable_door: continue else: break return Doors[i]def statistics(wins, times_to_run): print(\nThe computer won +str(wins)+ times) print(This means the computer won +str((wins/times_to_run)*100)+% of the time)setup()
Monty Hall simulator in Python 3.x
python;performance;python 3.x;simulation
Readability:you should have 2 newlines after each function definitionyou should use augumented assignments where possible you should define each method in a logical order (e.g: if you're calling a function inside another function, the later should be defined first). That's rather a personal preference because you can't do this everytime. you should have a space around operators and delimitersyou should make your print() statements more compactvariable names should be snake_cased. The same goes for method names.at the beginning of each function you should define a docstringNow, let's dig into each function:in def statistics() you should use format() and join those two prints into a single one:def statistics(wins, times_to_run): Print the statistics print(The computer won {} times This means the computer won {} % of the time.format(wins, (wins / times_to_run) * 100))as mentioned above:def setup_doors(always_change_choice): Set up the winning door winning_door = random.randint(1, 3) computer_guess = random.randint(1, 3) print(The winning door is {}.\n The computer guessed door number {}.format(winning_door, computer_guess)) return play_game(winning_door, computer_guess, always_change_choice)in def run(change_choice, times_to_run) you should avoid that multiple condition by using the lower function. You can also use the enumerate() to get rid off that variable definition, and replace i by _ as you don't use it:def run(change_choice, times_to_run): Some description here for wins, _ in enumerate(range(times_to_run)): if change_choice.lower() == 'y': wins += setup_doors(True) else: wins += setup_doors(False) # Display amount of times won/percentage of games won statistics(wins, times_to_run)in def setup() I'd just join the print statements:def setup(): Basic greeting/explaining what to do. print(\n\n There are 3 doors. One is a winner. The computer \n will try guess the right one. After the first \n guess, one door is shown to be a loser. The computer \n can then change it's choice to the remaining door.\n) # Display choices and get input change_choice = input(Should the computer always change it's choice? y/n\n:> ) runs = int(input(How many times should this run?\n:> )) run(change_choice, runs)// To be continued. I have to leave the office.
_unix.313577
I have this setting:# Number windows and panes starting at 1 so that we can jump to# them easier.set -g base-index 1set -g pane-base-index 1But I'd also like to have the same for switching tmux sessions. When I open the tmux session list it still starts on 0. Is it possible to not start session counting from 0 but from 1 instead?
How to make tmux sessions count from 1 instead of 0?
tmux
You appear to be referring to the session group index, which is generated, and not used for telling tmux which session you would like to attach to.It's used in the template for list-sessions:#{?session_grouped, (group ,} \and generated in session.c (and always starts at zero):/* Find session group index. */u_intsession_group_index(struct session_group *sg){ struct session_group *sg2; u_int i; i = 0; TAILQ_FOREACH(sg2, &session_groups, entry) { if (sg == sg2) return (i); i++; } fatalx(session group not found);}but that value is used only in formatted output.
_unix.356246
I've gotten permission to use a Linux OS on my workplaces network, but I strongly suspect that IT has a product that they themselves don't realize is configured to block package managers. Over the last week I have tried Ubuntu and Fedora and spent close to 30 hours fiddling with proxy setting, and the only thing that doesn't work are apt and dnf. Everything else is fine. There are a number of centOS servers running running in the building, so out of frustration I installed centOS, and yum worked on the first try (with proxy settings). My guess is that the person who set up the servers long ago white listed yum or something. Is there some way I can prove one way or the other that our workplace proxy is or isn't interfering with apt or dnf?UPDATE:response when using wget instead of apt-install.wget http://ftp.riken.jp/Linux/ubuntu/dists/xenial-updates/InReleaseTcpdumping this request shows it does not contain the same Debian APT-HTTP header as it does when using APT. Everything appears to be normal. -----BEGIN PGP SIGNED MESSAGE-----Hash: SHA512Origin: UbuntuLabel: UbuntuSuite: xenialVersion: 16.04Codename: xenialDate: Thu, 21 Apr 2016 23:23:46 UTCArchitectures: amd64 arm64 armhf i386 powerpc ppc64el s390xComponents: main restricted universe multiverseDescription: Ubuntu Xenial 16.04MD5Sum: f52f354808b6658dcd8fc47c813cb087 501150562 Contents-amd64 605d6257d0144333d320d9aa750b19d2 32582143 Contents-arm64.gz... many many lines ommited... e201ab73d77c0208d5dcd4844b6215bc5e18b49d9f9b58d0fb627c47c0438ecd 9802268 universe/source/Sources.gz 06d5766fba7d0be3e2d0c801f26d10aa8b4e6e8618711445c1373b535777c84b 35812491 universe/source/Sources aefe5a7388a3e638df10ac8f0cd42e6c2947cc766c2f33a3944a5b4900369d1e 7727612 universe/source/Sources.xzAcquire-By-Hash: yes-----BEGIN PGP SIGNATURE-----Version: GnuPG v1.4.11 (GNU/Linux)iEYEAREKAAYFAlcZYVUACgkQQJdur0N9BbW9ewCfdMD63UFAr0wTIjaOnnQjI5oH/wIAnRYjUbR6/i6e6FPClWwNbI6uE15eiQIcBAEBCgAGBQJXGWFVAAoJEDtP5qzAsh8y3YwP/02/wiF9Q9UCkxJnP6Kr5osPaV9JkGV/bpLELGh6bHyJEnLPO+xfXBoDglXopP8YiSXhV26Xa2wWLKICKL476uHPOtLz4wn7bdGnUHkizPHfyxQZH58+QTn+Sy1PdtIPOSNbiU8dz7Q/hfjF5x7JBNC77D4b474hYdb8HZUn1dfTDPgDVW2k4nkU2w9ysGN8yfWMyG20L6emW4a1KRmyEHpynTMWGYKKzH58WEJKDGrRqbhlwxsjXW9KF/jkvQPSO7Rg3UB7gLBYKyVuNsCdVh4+Mn6jGf8wv6msJD6Dz1PrudKVBKkO181dMdO18GfBHhDiMaoIWzMD+XI/+JGV4TALy6zhVz9btH28u2aIgQ7j/K+shR8gk5yQpWbSF6GUEHQN44VhdNnA9NdWl9GyFKGWONBfuNMMcU5/HHhO4ZGv9CgvaKrgBWC2zck3R7SmeL9R3quj4hGP15105uGKKHjX0ee6VP7l3ovRl/d/f5ls7kDa09XGrWFyWTdU2gw8eutTWlfPPM6+MIjF0o5EWy1Dv03CrE4oNF3GKZaK+WbptKjpMxyGSeNg/K3TV11F3futZAoxpVbzAWS36BNxqqMotg3Cpegbxtn7s/SWWr0alzi2XqQfeLqCmLWHaGaIqAmyLXb8m18O5To3Z4zIA6neALhEHs7cfy4f4yQpnbkL=LkQz-----END PGP SIGNATURE-----
How to tell if package managers are being blocked by proxy
networking;apt;package management;yum
null
_unix.150048
I want to install CentOS 6.4 on HP DL380 G4 server. First of all I select install or upgrade an existing system, but it boot something like without graphic (like basic video card). My main problem is in partitioning type: it shows this and won't let me custom partitioning: |partitioning type|installation require partitioning of your hard drive. the default layout is suitable for most users. select what space to use and which drive to use as the install layout Use entire drive Replace existing Linux system Use free space [*] cciss/c0d0 .... MB (compaq amart arrey) OK BACK I want to manually make the partitioning myself, but selecting each one of them don't let me to do that. What to do?
Centos installation
centos;system installation
This is called Text mode installation Program. Anaconda also have a text-base installation apart of the graphical installation. If one of the following situation occurs the installation will use text-mode.The installation system fails to identify the display hardware on your computer.You choose the text mode installation from the boot menu.I didn't choose text mode myself, I think the installation has failed to identify the display hardware because I use a KVM to use the server. There is some differences between graphical installation and text-mode (I don't know why there should be difference between them ). Differences are:configuring advanced storage methods such as LVM, RAID, FCoE, zFCP, and iSCSI. customizing the partition layoutcustomizing the boot loader layout selecting packages during installation configuring the installed system with first bootfor this problem i selected the second one (Install system with basic video card ) and the problem solved and the graphical installation came up with all options. I think in HP DL380 G4 the video card is weak or the installation can not recognize it so it use text-mode installation. but with basic video card my problem solved.Some related information:We can configure options that are not available in text-mode with boot options. see this link.
_webapps.104986
Given:Two dates, the bounds of a date range;A list of dates (given in-extenso in a line or a column);Is there a way, in Google Spreadsheet, to get the number of dates (days) in the date range that are included in the list of dates ?Example:[2017-01-01;2017-01-31] intersected with {2017-01-01, 2017-03-01} would yield 1Because the range on the left hand side, seen as a set, contains the 31 days of January {2017-01-01, ..., 2017-01-31} and the set on the right hand side contains the date 2017-01-01, which is a day of January.
Formula to compute the cardinality of the intersection of two sets of dates
google spreadsheets;formulas;date
Assume that: A1: Holds the start dateA2: Holds the end dateColumn B holds the list of dates to count =QUERY( B:B, select COUNT(B) where B >= date '& TEXT(A1,yyyy-mm-dd)& ' AND B <= date '& TEXT(A2,yyyy-mm-dd)& ' label COUNT(B) '')
_unix.293528
I've been connected a few IRC nets for months and somehow one of them got a screwy server tag. I'd like to be able to rename it. Is this possible?
Is it possible to change a server tag in irssi? How?
irssi
null
_webmaster.42247
Can I monitor how long my server remains down on Godaddy shared hosting service? I have noticed myself once that for several minutes it was down, then back again. It will be helpful if I could see actually how long its getting down per week/month.
Monitor GoDaddy shared hosting server downtime
server;godaddy;downtime
Pingdom seems to be a popular tool for monitoring web site uptime. I haven't used it myself but they do provide SMS and email alerting.
_webapps.75980
Usually there's a green dot on each user to tell whether he's online or not, I am no longer seeing that dot.This happened a couple of weeks ago, just wondering if it's my browser or did Trello staff remove them?
Trello online status are gone
trello;trello organization
null
_softwareengineering.80846
I have recently been trying to learn about MVVM and all of the associated concepts such as repositories, mediators, data access. I made a decision that I would not use any frameworks for this so that I could gain a better understanding of how everything worked. Im beginning to wonder if that was the best idea because I have hit some problems which I am not able to solve, even with the help of Stack Overflow!Writing from scratchI still feel that you have a much better understanding of something when you have been in the guts of it than if you were at a higher level. The other side of that coin is that you are in the guts of something that you don't fully understand which will lead to bad design decisions. This then makes it hard to get help because you will create unusual scenarios which are less likely to occur when you working within the confines of a framework.I have found that there are plenty of tutorials on the basics of a concept but very few that take you all the way from novice to expert. Maybe I should be looking at a book for this?Using frameworksThe biggest motivation for me to use frameworks is that they are much more likely to be used in the workplace than a custom rolled solution. This can be quite a benefit when starting a new job if it's one less thing you have to learn.I feel that there is much better support for a framework than a custom solution which makes sense; many more people are using the framework than the solution that you created. The level of help is much wider as well, from basic questions to really specific, detailed questions.I would be interested to hear other people's views on this. When you are learning something new, should you/do you use frameworks or not? Why? If it's a combination of both, when do you stop one and move on to the other?
Learning a new concept - write from scratch or use frameworks?
learning;frameworks;self improvement
Use a framework.It's always good to be able to add a publicly used framework to your resumeYou actually get stuff done rather than focusing on plumbing implementationsYou gain insight into how others do it. More cases than not, they have more experience than you, so you may learn new things that you otherwise never would have thought ofIf you still want to learn the internals, step through library code with your debugger. Enhance it (if it's OS) and provide patches to the author(s) if you think what you've written is useful.In short, using a framework will always get you up to speed with a design pattern than rolling your own. Even if it's an academic exercise, the insight that you gain when using another framework (or a number of them) is invaluable.There's no sense in rebuilding the wheel when there are a number of them already built, with solid documentation to help you in learning the specific patterns.However, if you have specific requirements that aren't met by something that's already been written, then that's another story altogether.
_vi.11064
I search some words so that there are many highlight results in the current window.I use n to move cursor to a matching result, how to know its index of match results easilyI have tried SearchPosition, but it does not work in my Vim.
How to show the index of the current match?
search
I don't know if it's exactly what you want, but to get the number of matches and the index of the current match, I'm using a modified version of this:nno n n@=Search_and_index()<CR>nno N N@=Search_and_index()<CR>fu! Search_and_index() abort let winview = winsaveview() let [line, col] = [winview.lnum, winview.col] call cursor(1, 1) let [idx, total] = [1, 0] let [matchline, matchcol] = searchpos(@/, 'cW') while matchline && total <= 999 let total += 1 if matchline < line || (matchline == line && matchcol <= col) let idx += 1 endif let [matchline, matchcol] = searchpos(@/, 'W') endwhile call winrestview(winview) echo @/ . '(' . idx . '/' . total . ')' return ''endfuIt remaps n and N to call the function Search_and_index() which should echo a message such as pattern(3/4).The while loop is responsible for incrementing the variables total and idx. And at the end of the loop, their values should be respectively the total number of matches of your last search pattern, and the index of the current match (the one under the cursor).But the loop stops at 999 to avoid taking too much time. You could increase this number if you feel it's too low.
_cs.67832
I have been trying to find a solution both theoretical and practical to my problem but I just can't. The question is you have x players that should play some rounds y of games in groups of 4. Now if a player was in a game with somebody else, he is not allowed to be ever again with that player in the same group. Now the question is give n groups that satisfy this conditions. With n being maximal amount of possible groups.My first approach was to just take a player put him into a group, now for the next player check the array already_played_with_players of the first player for the second player if he's not in add him and add the players he played with to the already_played_with_players array. Proceed so too for the next two players. Then mark these 4 players as in a group and take the next player out of the pool and so on.This is not some educational question, but a real world problem. I would like to organize a game tournament, but so that people meet new people and don't play with the same people again. I already ask multiple people mathematicians, physicians, computer scientist, but the solution was not really evident to anybody. So I was wondering if the problem is NP-complete? I know I would need to find a reduction from another NP-complete problem to my problem to prove that, but I don't even know how to formalize my problem exactly.
Game tournament program, NP complete?
np complete
null
_softwareengineering.201979
From what I understand,HTML is a mark-up language, so is the content of XAML, XIB andwhatever Android uses and other native UI development frameworks.JavaScript is a programming language used along with it to handleclient side scripting which will include things like event handling,client side validations and anything else C#,Java,Objective-C or C++do in various such frameworks.There are MVC/MVVM patterns available in form frameworks like Sencha's, Angular etc.We have localStorage in form of both sqlite and key-value store as other frameworks have and you have API specification for almost everything that it missing.Whenever a native UI frameworks has to render UI , it has to parse a similar the markup and render the UI.Question break-downWhat stops from doing the same in HTML and JS itself ?Instead of having a web-control or browser as a layer in between why can't HTML(along with CSS) and JS be made to perform the same way ?Even if there is a layer,so does .net runtime and JVM are in other cases where C++,C are not being used. So Lets take the case of Android, like Dalvik, why Can't Chromium be another option(along with dalvik and NDK) where HTML does what android markup does and JavaScript is used to do what Java does ?So the Question is,Even if current implementations aren't as good, but theoretically is it possible to get HTML5 based applications to work as other native apps specially on mobile ?
What stops HTML5 and JS apps to perform as good as native apps?
javascript;mobile;html5;chrome
The poster boy for HTML5 apps, LinkedIn went native early 2013.In the interview in VentureBeat they explain why. I think this is the part most relevant to your question:Prasad said performance issues werent causing crashes or making the app run slowly. What he did say shows that HTML5 for the mobile web still has a bright future but only if developers are willing to build the tools to support it....There are a few things that are critically missing. One is tooling support having a debugger that actually works, performance tools that tell you where the memory is running out. If you look at Android and iOS, there are two very large corporations that are focused on building tools to give a lot of detailed information when things go wrong in production. On the mobile web side, getting those desktop tools to work for mobile devices is really difficult. The second big chunk we are struggling with is operability, runtime diagnostics information. Even now, when we build HTML5, we build it as a client-side app. Its more of a client-server architecture. The operability of that, giving us information when were distributed to a large volume of users, there arent as many great tools to support that, as well. [Prasad also noted that dev and ops tools for solving issues quickly don't exist.] Because those two things dont exist, people are falling back to native. Its not that HTML5 isnt ready; its that the ecosystem doesnt support it. There are tools, but theyre at the beginning. People are just figuring out the basics.
_softwareengineering.244786
CAN Driver means application program that interacts with CAN hardware and helps in initializing setup and communication.CANopen Stack provides various APIs to deal with CAN communication.Now this is confusing me so please let me know: Is CANopen Stack and CAN driver one and the same?
CANopen and CAN Driver
communication;protocol
Not necessarily.A 'stack' in this situation refers to a set of applications that are used for the overall product. See wikipedia solution stack and technology stack. The FOOstack would imply a set of software (the libraries necessary, maybe a specialized plugin or rework of the IDE (for example the SpringSource Tool Suite). For example, the MEAN Stack uses Mongo, expressjs, angularjs, and node for a solution and thus bundle of software is often referred to as a stack.You will sometimes see referred to the 'full stack developer' which someone who can work on any part of the system from client to database.The driver is a particular piece of software to communicate with a particular piece of hardware. Thats it. A video driver is used by the operating system to communicate with the video hardware.A driver may be included as part of the stack, but a driver is not the entirety of the solution stack.
_cstheory.12665
Could you point me a reference, an answer or it is an open question?
Is 3SAT problem APX-hard or not?
cc.complexity theory;np hardness;complexity classes;approximation hardness
null
_webapps.102574
I'm creating a Tumblr account, and wanted to include a Facebook link to my page, just the way there are beautiful buttons linking to big sites like YouTube, Instagram, Pinterest, Linkedin, etc.All these options appear as special links in the control panel of my Tumblr account. However, there's no Facebook option. I can create a Facebook link as other links, but then the style gets different, and I don't want that (this way I got only the word Facebook instead of the beautiful icon the other sites show).Considering that Facebook is probably in the Top 3 sites of the world, isn't it strange? I saw that I can edit the HTML, but got afraid of doing a mess there. Can anyone tell me if there's an easy way to include a Facebook link that has the same appearance of the other big social network sites (YouTube, Instagram, etc)?
In Tumblr, how to add Facebook icon just like other social network?
facebook;tumblr;links;social networks
null
_unix.138833
I have struggled with this problem for two days and have tried many things to fix it to no avail. I'm hoping you guys can help me out.I am trying to create an Upstart job that starts a new screen session on boot, in which I would like to automatically start a java executable. Here is the .conf file I am currently trying to get to work, although I have tried several others:description Run the bungeecord jarstart on (local-filesystems and net-device-up IFACE=eth0 and runlevel [2345])stop on runlevel [016]exec start-stop-daemon --start -c ridog --exec /usr/bin/screen -- -dmUS BungeeCord java -server -XX:UseSSE=4 -XX:+UseCMSCompactAtFullCollection -XX:MaxPermSize=356m -XX:ParallelGCThreads=6 -XX:+UseConcMarkSweepGC -XX:+DisableExplicitGC -XX:+CMSIncrementalMode -XX:+CMSIncrementalPacing -XX:+UseCompressedOops -XX:+AggressiveOpts -Xmx256M -jar BungeeCord.jarpre-stop script screen -S BungeeCord -X foo end^Mend scriptTo my knowledge, the script seems to work fine, I can run sudo start bungeecord and get the intended result, however, restarting the machine does not work. Instead, I get this error in the /var/log/upstart/bungeecord.log:Cannot make directory '/var/run/screen': Permission deniedI've looked up this error and the search results are obscure and inconclusive. I've tried running the command as root, this removes the error but still no screen session. I've tried different commands like this: su ridog -c screen -dmS BungeeCord java -jar /home/ridog/BungeeCord/BungeeCord.jarNothing seems to work and I'm out of ideas, any help would be appreciated.Thanks.
How do I start a screen session using an upstart job with a non privileged user?
gnu screen;startup;upstart
Problem solved, I switched from using upstart to using cron. It was much more simple and everything works great now.For anyone reading this that might be curious as to how I did it, I made a simple shell script:#!/bin/bashjava -Xms256M -Xmx256M -jar /home/ridog/BungeeCord/BungeeCord.jarAnd set it to run on startup with a new line in crontab -e:@reboot screen -dmS BungeeCord sh /home/ridog/BungeeCord/run.shThanks for your help!
_softwareengineering.157720
I have lots of ideas for products to be built. The problem is that I have less than a year of professional work experience and I am afraid of getting judged negatively in the future based on what I produce now. I have no clue if my code is any good.I am not familiar with any of the coding patterns. All I know is to build products that work. I want to have a public profile in github for my future projects and I will try hard to make sure that it is well commented, is optimized and clean.These are the things that I fear getting exposed publicly:My code may not be highly optimized.Wrong usage of certain libraries or functions which coincidentally get the job done.Not knowing or following any coding pattern.Lots of bugs/ not considering corner, edge casesFundamental lack of understanding and application of certain concepts such as thread safety, concurrency issues in multi-threaded programming, etc.Should I go ahead and get started or continue to stick to building stuff locally and privately till I get more experience. I don't want the mistakes made here to haunt my career prospects in the long run.
What are the disadvantages of starting an opensource project if one is not an experienced programmer?
open source;personal projects
After 30 years of professional software development, I still create bugs. I still find patterns I don't know. I still learn from my colleagues, and encounter stuff I don't know every day.Most experienced developers will judge you on how you respond to issues and criticism, whether you learn from your mistakes and improve your product to meet the users' or community's needs, whether you admit what you don't know and seek to improve.One of the best skills for a developer is willingness to ask the dumb questions and to look a bit foolish at times in order to find good answers as quickly as possible.Everyone who is experienced and very proficient was once where you are now. You will learn much faster if you put your work out there and work with other people.There is no reason to wait. Make your project open. Better yet, contribute to other open projects and learn from them.
_softwareengineering.20084
I know Git is great for open source projects. But I was wondering: for a company with 20 programmers working on a 1 year project, which source control system is desirable? From what I heard Git uses pulling; wouldn't it be less than desirable to need to go through someone else to get your changes in the main trunk? Especially when everyone is working at the same time?That's just of an example I was wondering about. I know how to use SVN but even at my last job we didn't use it on our projects, since everything was done in PHP and those were typically standalone 1 week projects. I just had SVN for my local code and didn't need to use it with others.So what are good source controls, and specifically why is it good for this?
What source control do I need for a large project in an average company?
version control
null
_cogsci.16625
Is there a difference in speed of impulses created by excitatory and inhibitory neurons?
Excitatory impulse speed vs inhibitory
neurobiology
There is a wide variety of inhibitory neuron classes. See here for a review of interneurons in the hippocampus: P. Somogyi, T. Klausberger, J. Physiol. 562, 926 (2005)..Different classes of interneurons have different spike durations (e.g. fast-spiking or FS cells, generally used as a marker of putative PV+ interneurons). Additionally, different classes of interneurons have different post-synaptic receptors with specific temporal and other characteristics. For example, GABA-A receptors have time constants of ~10ms, whereas GABA-B receptors have time constants of ~100ms (and yes, there are subtypes of those receptor classes). You can see a modeling paper I wrote for exploration of a use for different receptor classes, as well as more references for further research. H. Sanders, M. Berends, G. Major, M. S. Goldman, J. E. Lisman, J. Neurosci. 33, 424429 (2013)..
_unix.72215
When I fire up urxvt or xterm, by default the font is a sans-serif monospace unaliased font. I would like to make this my font in other applications, but I can't find it in my system font list (i.e. I can't find it in the font list in gnome-control-center). I tried looking in /etc/X11/Xresources and ~/.Xresources, but there are no fonts mentioned in either. Does anybody know how to determine what font this is?
RHEL6: system default font
rhel;xterm;urxvt
xterm/urxvt default to 'fixed` or whatever this has been aliased to. On my system (Arch):grep -r '^fixed' /usr/share/fonts/returns/usr/share/fonts/cyrillic/fonts.alias:fixed -misc-fixed-medium-r-semicondensed--13-120-75-75-c-60-koi8-r/usr/share/fonts/misc/fonts.alias:fixed -misc-fixed-medium-r-semicondensed--13-120-75-75-c-60-iso8859-1So the font used in xterm is Fixed Medium Semi-Condensed. Here is a screen-shot with the font in Font Viewer, xterm and gnome-terminal below (the latter configured to use the same font):
_codereview.20926
I was solving the Find the Min problem on Facebook Hacker Cup.The code below works fine for the sample inputs given there, but for input size as big as 109, this takes hours to return the solution.Problem statement:After sending smileys, John decided to play with arrays. Did you know that hackers enjoy playing with arrays? John has a zero-based index array, m, which contains n non-negative integers. However, only the first k values of the array are known to him, and he wants to figure out the rest.John knows the following: for each index i, where k <= i < n, m[i] is the minimum non-negative integer which is not contained in the previous *k* values of m.For example, if k = 3, n = 4 and the known values of m are [2, 3, 0], he can figure out that m[3] = 1.John is very busy making the world more open and connected, as such, he doesn't have time to figure out the rest of the array. It is your task to help him.Given the first k values of m, calculate the nth value of this array. (i.e. m[n - 1]).Because the values of n and k can be very large, we use a pseudo-random number generator to calculate the first k values of m. Given positive integers a, b, c and r, the known values of m can be calculated as follows:m[0] = am[i] = (b * m[i - 1] + c) % r, 0 < i < kInputThe first line contains an integer T (T <= 20), the number of test cases.This is followed by T test cases, consisting of 2 lines each.The first line of each test case contains 2 space separated integers, n, k (\$1 <= k \le 10^5, k < n \le 10^9\$).The second line of each test case contains 4 space separated integers a, b, c, r (\$0 \le a, b, c \le 10^9, 1 \le r <= 10^9\$).My solution:import syscases=sys.stdin.readlines()def func(line1,line2): n,k=map(int,line1.split()) a,b,c,r =map(int,line2.split()) m=[None]*n m[0]=a for i in xrange(1,k): m[i]= (b * m[i - 1] + c) % r #print m for j in range(0,n-k): temp=set(m[j:k+j]) i=-1 while True: i+=1 if i not in temp: m[k+j]=i break return m[-1]for ind,case in enumerate(xrange(1,len(cases),2)): ans=func(cases[case],cases[case+1]) print Case #{0}: {1}.format(ind+1,ans) Sample input:597 3934 37 656 97186 7568 16 539 186137 4948 17 461 13798 596 30 524 9846 187 11 9 46
Find the Min challenge on Facebook Hacker Cup
python;optimization;performance;programming challenge
1. Improving your codeIf you used if __name__ == '__main__': to guard the code that should be executed when your program is run as a script, then you'd be able to work on the code (for example, run timings) from the interactive interpreter.The name func is not very informative. And there's no docstring or doctests. What does this function do? What arguments does it take? What does it return?func has many different tasks: it reads input, it generates pseudo-random numbers, and it computes the sequence in the problem. The code would be easier to read, test and maintain if you split these tasks into separate functions.Reading all the lines of a file into memory by calling the readlines method is usually not the best way to read a file in Python. It's better to read the lines one at a time by iterating over the file or using next, if possible.When computing the result, you keep the whole sequence (all \$n\$ values) in memory. But this is not necessary: you only need to keep the last \$k\$ values (the ones that you use to compute the minimum excluded number, or mex). It will be convenient to use a collections.deque for this.Similarly, it's not necessary to build the set of the last \$k\$ values every time you want to compute the next minimum excluded number. If you kept this set around, then at each stage, all you'd have to do is to add one new value to the set and remove up to one old value. It will be convenient to use a collections.Counter for this.Applying all of these improvements results in the code shown below.import sysfrom itertools import count, islicefrom collections import Counter, dequedef pseudorandom(a, b, c, r): Generate pseudo-random numbers starting with a and proceeding according to the linear congruential recurrence a -> (b * a + c) % r. >>> list(islice(pseudorandom(34, 37, 656, 97), 10)) [34, 71, 82, 4, 28, 43, 16, 84, 78, 50] while True: yield a a = (b * a + c) % rdef mex(c): Return the mex (Minimum EXcluded) number in the Counter c. >>> mex(Counter(range(10))) 10 >>> mex(Counter([2, 3, 0])) 1 for i in count(): if c[i] == 0: return idef iter_mex(k, it): Generate the sequence whose first k values are given by the iterable `it`, and whose ith value (for i > k) is the mex (minimum excluded number) of the previous k values of the sequence. q = deque(islice(it, k)) for m in q: yield m c = Counter(q) while True: m = mex(c) yield m q.append(m) c[m] += 1 c[q.popleft()] -= 1def nth_iter_mex(n, k, a, b, c, r): Return the nth value of the sequence whose first k values are given by pseudorandom(a, b, c, r) and whose values thereafter are the mex of the previous k values of the sequence. seq = iter_mex(k, pseudorandom(a, b, c, r)) return next(islice(seq, n, None))def main(f): cases = int(next(f)) for i in xrange(cases): n, k = map(int, next(f).split()) a, b, c, r = map(int, next(f).split()) print('Case #{}: {}'.format(i, nth_iter_mex(n - 1, k, a, b, c, r)))if __name__ == '__main__': main(sys.stdin)2. TimingPython comes with the timeit module for timing code. Let's have a look at how long the program takes on some medium-sized test instances:>>> from timeit import timeit>>> timeit(lambda:nth_iter_mex(10**5, 10**2, 34, 37, 656, 97), number=1)1.6787691116333008>>> timeit(lambda:nth_iter_mex(10**5, 10**3, 34, 37, 656, 97), number=1)16.67353105545044>>> timeit(lambda:nth_iter_mex(10**5, 10**4, 34, 37, 656, 97), number=1)143.31502509117126The runtime of the program is approximately proportional to both \$n\$ and \$k\$, so extrapolating from the above timings, I expect that in the worst case, when \$n = 10^9\$ and \$k = 10^5\$, the computation will take about five months. So we've got quite a lot of improvement to make!3. Speeding up the mex-findingIn the implementation above it takes \$(k)\$ time to find the mex of the last \$k\$ numbers, which means that the whole runtime is \$(nk)\$. We can improve the mex finding to \$O(\log k)\$ as follows.First, note that the mex of the last \$k\$ numbers is always a number between \$0\$ and \$k\$ inclusive. So if we keep track of the set of excluded numbers in this range (that is, the numbers between \$0\$ and \$k\$ inclusive that do not appear in the last \$k\$ elements of the sequence), then the mex is the smallest number in this set. And if we keep this set of excluded numbers in a heap then we can find the smallest in \$O(\log k)\$.Like this:import heapqdef iter_mex(k, it): Generate the sequence whose first k values are given by the iterable `it`, and whose ith value (for i > k) is the mex (minimum excluded number) of the previous k values of the sequence. q = deque(islice(it, k)) for m in q: yield m excluded = list(set(xrange(k + 1)).difference(q)) heapq.heapify(excluded) c = Counter(q) while True: mex = heapq.heappop(excluded) yield mex q.append(mex) c[mex] += 1 old = q.popleft() c[old] -= 1 if c[old] == 0: heapq.heappush(excluded, old)Now the timings are much more satisfactory:>>> timeit(lambda:nth_iter_mex(10**5, 10**2, 34, 37, 656, 97), number=1)0.2606780529022217>>> timeit(lambda:nth_iter_mex(10**5, 10**3, 34, 37, 656, 97), number=1)0.2634279727935791>>> timeit(lambda:nth_iter_mex(10**5, 10**4, 34, 37, 656, 97), number=1)0.32929110527038574>>> timeit(lambda:nth_iter_mex(10**6, 10**5, 34, 37, 656, 97), number=1)3.5652129650115967However, we still expect that when \$n = 10^9\$ and \$k = 10^5\$, the computation will take around an hour, which is still far too long.4. A better algorithmLet's have a look at the actual numbers in the sequence generated by iter_mex and see if there's a clue as to a better way to calculate them. Here are the first hundred values from a sequence with \$k = 13\$ and \$r = 23\$:>>> list(islice(iter_mex(13, pseudorandom(34, 37, 656, 23)), 100))[34, 5, 13, 10, 14, 1, 3, 8, 9, 0, 12, 19, 2, 4, 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4, 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4, 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4, 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4, 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4, 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4, 6, 5]You should have noticed a pattern there, but let's lay it out in rows of length \$k + 1 = 14\$ to make it obvious:[34, 5, 13, 10, 14, 1, 3, 8, 9, 0, 12, 19, 2, 4, 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4, 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4, 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4, 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4, 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4, 6, 5, 7, 10, 11, 1, 3, 8, 9, 0, 12, 13, 2, 4, 6, 5]You can see that the first \$k + 1\$ values are different, but thereafter each group of \$k + 1\$ items from the sequence is identical (and moreover is a permutation of the numbers \$0, \ldots, k\$).Let's check that this happens for some bigger examples:>>> it = iter_mex(10**5, pseudorandom(34, 37, 656, 4294967291))>>> next(islice(it, 10**5, None))0>>> s, t = [list(islice(it, 10**5 + 1)) for _ in xrange(2)]>>> s == tTrue>>> sorted(s) == range(10**5 + 1)TrueLet's prove that this always happens. First, as noted above, the mex of \$k\$ numbers is always a number between \$0\$ and \$k\$ inclusive, so all numbers in the sequence after the first \$k\$ lie in this range. Each number in the sequence is different from the previous \$k\$, so each group of \$k + 1\$ numbers after the first \$k\$ must be a permutation of the numbers from \$0\$ to \$k\$ inclusive. So if the (\$k + 1\$)th last number is \$j\$, then the last \$k\$ numbers will be a permutation of the numbers from \$0\$ to \$k\$ inclusive, except for \$j\$. So \$j\$ is their mex, and that will be the next number. Hence the pattern repeats.So now it's clear how to solve the problem. If \$n > k\$, element number \$n\$ in the sequence is the same as element number \$k + 1 + n \bmod (k + 1)\$.The implementation is straightforward:def nth_iter_mex(n, k, a, b, c, r): Return the nth value of the sequence whose first k values are given by pseudorandom(a, b, c, r) and whose values thereafter are the mex of the previous k values of the sequence. seq = iter_mex(k, pseudorandom(a, b, c, r)) if n > k: n = k + 1 + n % (k + 1) return next(islice(seq, n, None))and now the timings are acceptable:>>> timeit(lambda:nth_iter_mex(10**9, 10**5, 34, 37, 656, 4294967291), number=1)1.6802959442138672
_codereview.101425
I am learning how to implement testing and try/catch statements into my code. I have a Laravel application with the following method. I am looking for advice on where I should add in try/catch statements and what phpunit unit-test(s) I would create to ensure this is functioning properly. Tips on comment blocks are also appreciated.// User sign uppublic function postSignup() { $validator = Validator::make(Input::all(), User::$rules); $confirmation_code = MyHelper::encrypt_decrypt('encrypt',Input::get('email')); if($validator->passes()) { $user = new User; $user->email = Input::get('email'); $user->password = Hash::make(Input::get('password')); $user->emailVerifiedToken = $confirmation_code; $user->firstName = null; $user->lastName = null; $user->shipAddressId = null; $user->billAddressId = null; $user->phone = null; $user->save(); $userdata = array( 'token' => $confirmation_code ); //Send the user an email requesting verification $toEmail = $user->email; $toName = $user->email; $subject = Email Verification - example.com; Mail::queue('emails.account.account-creation', $userdata, function($message) use ($toEmail,$toName,$subject) { $message->to($toEmail,$toName)->subject($subject); }); if(Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password')), false)) { return Redirect::to('/home/') ->with('login_message', 'Thank you for creating a new account, please sign in'); } } return Redirect::to('/account/sign-up') ->with('signup_message', 'Something went wrong') ->withErrors($validator) ->withInput();}
Basic sign-up method, testable and with try/catch
php;unit testing;authentication;laravel;integration testing
null
_webmaster.55410
I have modified my website www.vidyaniketan.in. It is a Joomla 2.5 site. When I search for it in Google by URL, there are several sub-links displayed (e.g., ABOUT US). this links to the old webpage. How do I link it to new webpage? I tried following code in my .htaccess file:Redirect 301 /about_us.html http://www.vidyaniketan.in/index.php?option=com_content&view=article&id=71&Itemid=468but unfortunately it's not working.
Redirect link of old webpage to new webpage in Joomla 2.5
htaccess;301 redirect;joomla
As mentioned you will need to wait for Google to re-index your website.In Joomla 2.5 though you don't need to hack the .htaccess file everytime you restructure your site or move an article. Simply add the desired redirect to the Redirect component (you may also need to enable the Redirect plugin).To use it navigate to Components>Redirect and you can add new redirects there. After a while you will also see other failed requests to your website, the large majority will be people trying to hack your site by looking for unsecured software installations.
_webmaster.26588
On my site, I have something like the following:<noscript> <p> <strong>JavaScript is currently disabled.</strong> Please enable it for a better experience on this site. </p></noscript>Will Google ignore this, or would this content be seen as part of my page's content, or even show up in the page description on a search results page?
How do search engines handle ?
seo;javascript;noscript
null
_reverseengineering.15256
I have the following situation. I am analyzing a crash of an application which gets an input file as argument. So, I open the crashing executable with the input file as argument.For further investigation, I need to know the memory location of the mapped input file. Can somebody tell me how to find it out ? Which command to type in windbg to achieve this ?Best regards,
Windbg - Memory Location of an input file
disassembly;windbg
null
_cs.71259
So I am in the process of learning about LL(1) grammar and converting an ambiguous one into LL(1). I know how to figure out if a grammar (G) is ambiguous, however, I am having trouble converting it to a LL(1) using left factoring.From my understanding, left factoring is basically factoring out prefixes which are common to two or more productions. So for example, A -> X | X Y ZBecomesA -> X BB -> Y Z | However, if we take an example such as the following grammar G, A -> acB | daB -> abB | daA | AfHow would I go about applying the left factoring to convert G to LL(1) since there is no common prefix based on what I can see. I am assuming I would have to use substitution (right corner substitution), correct?The following is my attempt at converting G to LL(1), did I do it correctly?A -> acB | daB -> abB | daA | AfA -> acabB | daA | Af | da //sub B into AA -> E | Af | da //left factorE -> acabB | daA | 1
Converting Ambiguous Grammar G to LL(1)
formal languages;formal grammars;compilers;parsers;factoring
null
_codereview.21042
I was interested in feedback on this architecture.Objective: serialize / deserialize a network application protocol stream.Approach: Create a class for each layer/object which exposes attributes as well as encapsulating the stream reader/writer.If instantiated for serialization the object is instantiated with the appropriate attributes, then a serialize method can be invoked with a BinaryWriter argument that results in the object, and sub-objects, serializing themselves to the stream.Conversely, when instantiated for deserialization the root object is instantiated with a BinaryReader in the constructor. The root object deserializes the stream by reading its attributes from the stream and instantiating instances of any child layer/object(s).Below is a working simple example of a single layer. It does not currently have the BinaryWriter method implemented, only the reader.Good idea? Typical? Bad idea? Are there other common architectures or better design patterns?... that of course is before we even get to code quality.namespace Sony.Protocol.Hdcp{ public class HdcpGammaData { private byte _fill1 = 0x00; private byte _fill2 = 0x00; private Table _table; private Color _color; private byte _fill3 = 0x00; private byte _offset; private byte _numberOfPoints = 0x10; private List<HdcpGammaPoint> HdcpGammaPoints; public HdcpGammaData(Table table, Color color, byte offset, List<HdcpGammaPoint> hdcpGammaPoints) { Table = table; Color = color; Offset = offset; if (hdcpGammaPoints.Count != _numberOfPoints) { throw new System.ArgumentException(hdcpGammaPoints must contain 0x10 points); } HdcpGammaPoints = hdcpGammaPoints; } public HdcpGammaData(BinaryReader reader) { HdcpGammaPoints = new List<HdcpGammaPoint>(); fill1 = reader.ReadByte(); fill2 = reader.ReadByte(); Table = (Table)reader.ReadByte(); Color = (Color)reader.ReadByte(); fill3 = reader.ReadByte(); Offset = reader.ReadByte(); NumberOfPoints = reader.ReadByte(); for (int i = 0; i < _numberOfPoints; i++) HdcpGammaPoints.Add(new HdcpGammaPoint(reader)); } public Table Table { get { return _table; } private set { if (!Enum.IsDefined(typeof(Table), value)) { throw new System.ArgumentOutOfRangeException(Table, value, Table must be between 1 and 3); } _table = value; } } public byte fill1 { get { return _fill1; } private set { _fill1 = value; } } public Color Color { get { return _color; } private set { if (!Enum.IsDefined(typeof(Color), value)) { throw new System.ArgumentOutOfRangeException(Color, value, Color must be between 0 and 2); } _color = value; } } public byte fill2 { get { return _fill2; } private set { _fill2 = value; } } public byte fill3 { get { return _fill3; } private set { _fill3 = value; } } public byte Offset { get { return _offset; } private set { if (_offset != 0x00 && _offset != 0x10) { throw new System.ArgumentOutOfRangeException(Offset, value, Offset must be 0x00 or 0x10); } _offset = value; } } public byte NumberOfPoints { get { return _numberOfPoints; } private set { if (_numberOfPoints != 0x10) { throw new System.ArgumentOutOfRangeException(NumberOfPoints, value, NumberOfPoints must be 0x10); } _numberOfPoints = value; } } } public enum Color : byte { Red = 0, Green, Blue } public enum Table : byte { Gamma1 = 0x01, Gamma2, Gamma3 }}
Layered network protocol serialize / deserialize
c#
I' not sure about having two constructors that would be used in different contexts i.e. one for serialization and one for serialization. It seems like to much of a constraint on the object before you even begin to use it.I think I would prefer to having a HdcpGammaDataReader and a HdcpGammaDataWriter (or something along these lines). These could perhaps both implement respectively a IDataReader and IDataWriter class. These classes would then do the serialization as you wish. Something like this perhaps:interface IDataSerializer<T>{ void Seralize(T obj);}interface IDataDeserializer<T>{ T DeSeralize();}public partial class HdcpGammaDataSerializer<HdcpGammaData> : IDataDeserializer{ public HdcpGammaData DeSeralize() { // Build my HdcpGameData object in here either }}public partial class HdcpGammaDataDeSerializer<HdcpGammaData> : IDataDeserializer{ public HdcpGammaData DeSeralize() { // deserialize here }}If you wanted to make the Gamma class immutable pass in all the arguments in the constructor. If you wanted to added an extra layer (packet header, CRC etc) around the data object then your serialize could inherit from a base class that first read the surrounding packet data and offloaded the actual payload serialization/serialization as required.As for the code itself. Just a few minor thingsI personally try not to make property names the same as their type names although this is just a personal preference. In your case as suggested by svick it is good to leave as is. Here's a good read on this conundrum I just found after a quick google if intereste. How to avoid using the same identifier for Class Names and Property Names? A couple of inconsistencies in your public property camel casing. I noticed you had a fill1. It should be Fill1 to be consistent.In line with 2. I'm not sure of your application domain but I tend to find properties like fill1, fill2 a bit obscure and don't tend to suggest what that property is. Perhaps a more meaningful name here to get away from the 1, 2 naming syntax would be appropiate.If you are going to have public properties with backing fields unless you need the private field just use auto-properties.i.e. public byte Fill3 { get; private set; }Alternatively you could do away with the private set altogether and make your field read-only and only expose a public methodi.e. private readonly byte _fill3; // initialise in constructorpublic byte fill3 { get { return _fill3; } }As you seem to be mixing and matching your assignment in your constructor being fields and properties I would probably just go with the auto-property concept.Just my 2cents...
_unix.298350
nlsadm list-timezoneiconv_open(wchar_t, UTF-8) failed for 'en_GB.ISO8859-15' localeInvalid argumentWhat is the cause for this error and is there a workaround?
Solaris 11 nlsadm list-timezone issue
solaris;locale;timezone
null
_softwareengineering.255971
I am creating a simple blackjack game backed by databaseIn my Card ispublic class Card{ private Face face; private Suit suit; //setters.. getters}where face and suit are enumsI have an entity Bet with the following@Entitypublic class Bet{ private Player player; private String cards; //...}Currently when I'm dealing cards I parse the suit and face to string and concatenate them in the cards field and then parse the cards if I want to calculate the score. I find this cumbersome so I want to change my field cards to List in the Bet Entity.Now, if that's the case I would have to make the Card class an entity as well. But my cardService, which is where I get my cards, does not rely on the database, it just creates random cards so it does not make sense to make card an entity - am I right?
Entity design for a blackjack game - should I make Card an entity?
domain model;hibernate;entity
A card is a value, not an entity. Cards do not have identity -- if the pack contains two cards with the same value it is of no interest to identify them separately. They only have value.Programming languages tend to provide values like integer, string and struct. You need to pick one of those to represent the value of a card. I would suggest using integer for the value, and write a class that can convert that integer to and from string or image representation, and to return the rank, suit and order (which may not be the same as the integer order).Then your generator simply generates integers within a specified range.The usual deck of cards contains 53 distinct cards, including a Joker. There are games (500) that have up to 63 distinct cards but the principle is the same, and an integer is a perfectly convenient way to encode the value. I would use that in the database too.For a hand or a deal you have multiple cards, up to 13 in Bridge or 52 if you want to keep a complete deal. You could encode that as a space-separated list of integers or some other way, depending on what you need. That's getting off the original point.For clarity, I do not suggest for a moment that one should use actual integers in the code to represent cards. In Java or JavaScript I would use a class, in C# or C++ a struct. The problem is that an object has identity but we want to deal with values. We want two different card objects that have the same value to compare equal. The simplest way (but not the only way) to do that is for the card object to contain an integer so that two cards with the same integer value are the same value. This is done by implementing a 'Compare Equal' operator in the class that compares the integer value.This is a subtle issue, the representation of value types, and not easily addressed with an audience of widely different skills.
_softwareengineering.129717
Recently I saw some possibilities of some IDEs (via plugins) to sort members of their classes/modules based on some criteria, sou you could have everything sorted automaticaly no matter where you would put the elements in time of writing it to editor.Do you think that this kind of sorting in class/module may have positive impacts on productivity, readability, comprehensibility etc?
Automatic sorting of class/module members and its possible impact on productivity and code quality
programming practices;code quality;source code
null
_unix.71690
I have a directory where some filenames have been wrongly named something .pdf rather than something.pdf. Is there a quick one liner I can use to delete the whitespace in the filenames.I have tried find -name * .pdf -type f | rename 's/ //g'but this did not work.
Delete whitespace in filenames in directory
linux;files;rename
In zsh, this is easily done with the zmv function. Put autoload -U zmv in your ~/.zshrc, or run this once in your shell, then:zmv '* .pdf' '${f// /}'This removes all spaces from the file name. If you only want to remove the one before the .pdf extension:zmv '* .pdf' '${f# .pdf}.pdf'or using parentheses to delimit groups that can be used as backreferences:zmv '(*) .pdf' '$1.pdf'If you want to act in subdirectories as well:zmv '**/* .pdf' '${f# .pdf}.pdf'or (note that you have to use (**/), not (**)/):zmv '(**/)(*) .pdf' '$1$2.pdf'Under Linux, with or without zsh, if there is only this one spurious space in the file names:rename \ .pdf .pdf *\ .pdfor, if there's only this one space in the original names:rename ' ' '' *\ .pdfIf you want to act in subdirectories as well, in ksh93 o+ or bash 4, you can use ** to match files in subdirectories. In bash, you need to run shopt -s globstar first (put this line in your ~/.bashrc) and set -o globstar in ksh93.rename \ .pdf .pdf **/*\ .pdfBeware that bash follows symlinks when recursing directories.Without the benefit of **, you can use find to recurse.find . -name '* .pdf' -exec rename ' .pdf' .pdf {} +Under Debian and derivatives (including Ubuntu) and most non-Linux systems that ship with perl, the rename command is a different one, which takes a Perl expression as an argument instead of a string to replace and a replacement string. Either use rename.ul in the commands above (under Debian and derivatives), or with the Perl rename:rename 's/ \.pdf$/.pdf/' -- *\ .pdf # strip the space before the extensionrename 's/ //g' -- *\ .pdf # strip all spaces
_unix.45899
I was just wondering why the Linux NFS server is implemented in the kernel as opposed to a userspace application?I know a userspace NFS daemon exists, but it's not the standard method for providing NFS server services.I would think that running NFS server as a userspace application would be the preferred approach as it can provide added security having a daemon run in userspace instead of the kernel. It also would fit with the common Linux principal of doing one thing and doing it well (and that daemons shouldn't be a job for the kernel).In fact the only benefit I can think of running in the kernel would a performance boost from context switching (and that is a debatable reason).So is there any documented reason why it is implemented the way it is? I tried googling around but couldn't find anything.There seems to be a lot of confusion, please note I am not asking about mounting filesystems, I am asking about providing the server side of a network filesystem. There is a very distinct difference. Mounting a filesystem locally requires support for the filesystem in the kernel, providing it does not (eg samba or unfs3).
Why is Linux NFS server implemented in the kernel as opposed to userspace?
linux;kernel;nfs
unfs3 is dead as far as I know; Ganesha is the most active userspace NFS server project right now, though it is not completely mature.Although it serves different protocols, Samba is an example of a successfulfile server that operates in userspace.I haven't seen a recent performance comparison.Some other issues:Ordinary applications look files up by pathname, but nfsd needs to be able tolook them up by filehandle. This is tricky and requires support from thefilesystem (and not all filesystems can support it). In the past it was notpossible to do this from userspace, but more recent kernels have addedname_to_handle_at(2) and open_by_handle_at(2) system calls.I seem to recall blocking file-locking calls being a problem; I'm not surehow userspace servers handle them these days. (Do you tie up a server threadwaiting on the lock, or do you poll?)Newer file system semantics (change attributes, delegations, share locks)may be implementedmore easily in kernel first (in theory--they mostly haven't been yet).You don't want to have to check permissions, quotas, etc., by hand--insteadyou want to change your uid and rely on the common kernel vfs code to dothat. And Linux has a system call (setfsuid(2)) that should do that. Forreasons I forget, I think that's proved more complicated to use in serversthan it should be.In general, a kernel server's strengths are closer integration with the vfs and the exported filesystem. We can make up for that by providing more kernel interfaces (such as the filehandle system calls), but that's not easy. On the other hand, some of the filesystems people want to export these days (like gluster) actually live mainly in userspace. Those can be exported by the kernel nfsd using FUSE--but again extensions to the FUSE interfaces may be required for newer features, and there may be performance issues.Short version: good question!
_unix.307361
I have recently got Core Linux, and am having trouble setting the resolution to 1920x1080 (my native resolution). I have not got a /etc/default/grub directory, nor have I got a UI. My question is, how can I make the console run in 1920x1080 resolution. This is what I get when I boot up:Currently I have no extensions loaded, and it can't seem to find xrandr.
Changing Console Resolution in Core (not Tiny Core) Linux
linux kernel;console;resolution
null
_softwareengineering.81072
A few do, but not any of the popular ones as far as I know. Is there something bad about nesting comments?I plan to have block comments nest in the (small) language I'm working on, but I would like to know if this is a bad idea.
Why do most programming languages not nest block comments?
language agnostic;syntax;comments
Because most of the implementations are using separate lexing and parsing stages, and for lexing they're using plain old regular expressions. Comments are treated as whitespaces - i.e., ignored tokens, and thus should be resolved entirely in a lexing pass. The only advantage of this approach is parsing speed. Numerous disadvantages include severe limitations on syntax (e.g., a need to maintain a fixed, context-independent set of keywords).
_softwareengineering.338202
One of the things I struggle with when unit testing is deciding what behaviors to actually test. I think part of my struggle stems from how most unit testing tutorials don't use good examples of things you would actually want to test in real life. For example, the tutorial I'm looking at now has a test basically like this: [Test]public void TestQuizIsInitializedCorrectly() { var question = QuizQuestion() { Question = What is your favorite color?, Answer = Blue, no yelloooowwww........ } var game = new Game(new List<QuizQuestion>(new[] { question })); Assert.AreEqual(1, game.Questions.Count);}What is the point of this test? To validate that when you put one object into a List in C#, that the List still has only 1 object? That's silly and I could spend a million years writing unit tests that validate simple things like putting an object into a list and validating the list count is 1. I would never finish my app. Are these just bad examples of what to test so we can focus on how to test in the tutorial?Or do people really write tests like this? Maybe tests like this are not really testing your own code, but they are formalizing an assumption about how we expect people to use the Game class? Perhaps the above example might be written not so much to test that the question was successfully initialized into the List, but rather to formalizing an assumption that that the Game class can only be passed in questions, it can't add default questions itself. I might know it's not doing that now, but putting it in a unit test makes it so we know right away if some future developer changes the Game class to invalidate that assumption. Is this a common use case in unit testing? Writing tests not so much to test code that's written but to formalize assumptions to protect against future changes?
Do people use unit testing to formalize assumptions in code?
unit testing
null
_unix.73669
When I press AltUp, A printed to terminal screen. Same thing happened when I pressed AltDown but B is printed instead. Other characters that I realized;AltLeft = D and AltRight = CWhat is the purpose of these commands?
What are the characters printed when Alt+Arrow keys are pressed?
command line;terminal;key mapping
Depending on how the terminal is configured, typing Alt+Key is like typing the Esc and Key keys in sequence, so it sends the ESC character (aka \e or ^[ or \033) followed by the character or sequence of characters sent upon pressing that Key.Upon pressing Up, most terminal emulators send either the three characters \033[A or \033OA depending on whether they're in application keypad mode or not.The first one does correspond to the escape sequence which when output to the terminal, move the cursor up. If you do:printf '\nfoo\033[Abar\n\n'You'll see bar written after foo one row up. If you do:stty -echoctl; tput rmkx; read fooYou'll see that the arrow keys do move the cursor around.When an application like zsh or vi reads that sequence of characters from the terminal, it interprets it as the Up action, because it knows from the terminfo database (kcuu1 capability) that it is the escape sequence sent upon pressing Up.Now, for Alt-Up, some terminals like rxvt and its derivatives like eterm send \033 followed by the escape sequence for Up (that is \033\033[A or \033\033OA), while some others like xterm or gnome-terminal have separate escape sequences for those types of keys when used with the combination keys like Alt, Shift, Ctrl.Those will typically send \033[1;3A upon Alt-Up.When sent to the terminal, that sequence will also move the cursor up (the second parameter (3) is ignored). There's no corresponding keypad key, so it's the same sequence sent upon Alt-Up in or out of application keypad mode.Now whether it's \033\033[A or \033[1;3A, many applications don't know what those sequences are for. The terminfo database won't help them, because there's no such capability that defines what characters those key combinations send.They will try their best to interpret that sequence. bash for instance will interpret \033[1;3 as an escape sequence, doesn't know anything about it, so does nothing, followed by A. zsh, will stop reading as soon as it finds out there's no known matching character sequence. There's no escape sequence that it knows that starts with \033[1 so it will skip that, and read the rest: ;3A and insert that in the line editor.Many applications like vi, zsh or readline based ones like gdb or bash (though beware bash uses a modified version of readline) allow you to add bindings for any sequence of characters.For instance, in zsh, you may want to bind Alt-Up, Alt-Down like:bindkey '\e[1;3A' history-beginning-search-backwardbindkey '\e[1;3B' history-beginning-search-forwardThose are to search the history backward and forward for command lines that start like the current one up to the current position of the cursor which is quite handy to recall previous commands.
_unix.90093
I have a problem with command editing in bash. If all of the following are true...My (single-line) prompt is particularly long.The terminal window is relatively narrow.I pressed Ctrl+C to exit the previous process, so that ^C is displayed at the left of the line.The command I'm editing wraps to the next line....then the editing is messed up. I end up replacing characters offset by 2 positions from the ones I thought I was editing.Similar things happen if, at step 4, I type in a command that spans multiple lines (rather than pressing Up). I can backspace onto the previous line, and then delete two characters of my prompt.Basically this:(Some output)^Cuser@host:~/path/to/somewhere $ some long commandthat wrapsIs broken by the ^C that appears at the start of the line.I've tried some other commands (e.g. sleep 30), and the ^C appears on a line by itself, and the prompt appears on the next line. This only seems to happen with node.js: node some_command_that_wraps.js.In case it's important, I have a brightly-coloured, git-integrated PROMPT_COMMAND. You can find it on github, in case I've done something stupid in that.UpdateMy PS1 is (for example) set to (I've wrapped it slightly):\[\e]0;\u@\h:\w\a\]\[\e[0;93m\]\u@\h\[\e[0;96m\]:\w \[\e[0;97m\]{\[\e[0;94m\]master\[\e[0;92m\]\[\e[0;91m\] ~1\[\e[0;97m\]}\[\e[0m\]\[\e[0;96m\]\$\[\e[0m\]...which displays (with more colour):roger@roger-p5q:~/Source/rlipscombe/bash_profile [master ~1] $ As far as I can tell, the escape characters are correctly non-countable (using \[ .. \]).How do I either:Get bash to detect the ^C and move to the next line?, orNot mess up the command editing?
^C characters at start of line break bash command editing
bash
null
_cs.54302
Consider we have $n$ disjoint segments and a point $P$ which is not on any segment. I want to find an $O(n \log n)$ algorithm to check which segments are visible from $P$. A segment is visible from $P$ if it has a point which is visible from $P$.My idea is to use a sweep half-line with one end-point on $P$, sort points clock-wise by degree and start from an end-point on the nearest visible segment (which I don't know how to find), rotate and detect one visible and some possible invisible segments at a time. All I can think of is $O(n^2)$ so far. Can anyone suggest an $O(n \log n)$ algorithm.
$O(n \log n)$ algorithm for disjoint segment visibility problem
algorithms;computational geometry
W.o.l.g. we could assume $P$ is the origin point $(0,0)$.List the endpoints of all segments, represent them in polar coordinate $(\theta,\rho) \in [0,2\pi) \times [0,\infty)$ and sort them by their degree. Imagine there is an ray from $P$ pointing to the right, we sweep it for one round (by gradually changing its direction $\alpha$ from 0 to $2\pi$). Let $R(\alpha)$ denotes the ray from $P$ to direction $\alpha$. We wonder what's the segments $R(\alpha)$ hits, and what's their order on $R(\alpha)$. Find out all segments hit $R(0)$, and sort them by their order on $R(0)$. Store them in a balanced binary search tree (e.g. red-black tree). Iterate over the points we found (and sorted) in step 1:Each point $(\theta,\rho)$ indicates a segment would start/stop hitting the ray $R(\alpha)$ when $\alpha$ increase to $\theta$. Update the binary search tree accordingly.The elements that once be the smallest one in the binary search tree are the segments visible from $P$.It's easy to check that the runtime of above algorithm is $O(n \log n)$.
_webmaster.21889
I run a WordPress blog, and have recently changed web hosts.When changing web hosts, I copied all files and exported/imported the database etc as explained by lots of tutorials found easily on Google. The blog home page works fine.What goes wrong:When I click on any link from the home page, the browser gets stuck in a redirect loop. Looking at the error log, I see:File does not exist: /usr/local/apache/htdocs/index.phpThe directory /usr doesn't even exist for my website - so perhaps this is looking for a file that was present using my old Web Host and is no longer present with my new web host?What is going on, and how might I resolve it?
After changing web host, I get a 'file does not exist' error
web hosting;php;wordpress;redirects;chmod
Weirdly, after changing the permissions on .htaccess from 744 to 644, everything works great. If someone wants to explain this, then go for it!
_datascience.9916
I'm dealing with a regression prediction challenge where the evaluation metric is (pearson) correlation.However, I have the impression that this metric is kind of arbitrary.While I can keep the RMSE stable the correlation can have great variety.Could someone please explain this metric and how to optimise for it?
Correlation as an evaluation metric for regression
machine learning;predictive modeling;correlation;evaluation
null
_datascience.22602
It is highly desirable that a NN/DNN must have smaller weights. For one thing, I am very sure why it is desirable i.e. if your model has smaller weights, then for a very small change in the input, there will be a very small change in the output. But what else? What are the other reasons for having smaller weights? A detailed explanation along with some resources will be very much appreciated. Thanks in advance.
Weights of a DNN model
machine learning;neural network;deep learning;convnet
null
_unix.17286
I have a monospace .ttf font I really like (UbuntuBeta Mono). Is there any way I can use it (or convert first and then use, if needed) for the console in freeBSD?I know there is usr/share/syscons/fonts, but it looks like they might be a different format? Once I install the font, how do I tell the console to use it?
Use or convert .ttf font for console use in FreeBSD
freebsd;fonts;ttf
null
_codereview.128707
I found this old piece of code that I wrote while I was learning C a while back:#include <stdio.h>#include <stdlib.h>#include <math.h>int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, Usage: %s <N>\n, argv[0]); return 1; } size_t limit = strtoul(argv[1], (char **) NULL, 10); size_t i, j, res = 0; size_t isqrt = (size_t) sqrt(limit); char* numbers = calloc(limit, 1); for (i = 2; i <= isqrt; i++) { if (numbers[i]) continue; for (j = i*i; j < limit; j += i) numbers[j] = 1; } for (i = 2; i < limit; i++) { if (!numbers[i]) ++res; } printf(%lu\n, res); free(numbers); return 0;}It's a sieve of Erathosthenes. Since now I started learning C++, I decided to rewrite it in C++11:#include <iostream>#include <memory>#include <vector>#include <string>#include <algorithm>#include <math.h>int main(int argc, char *argv[]) { if (argc < 2) { std::cerr << Usage: << argv[0] << <N> << std::endl; return 1; } size_t limit = std::stoul(argv[1]); size_t i, j, res = 0; size_t isqrt = size_t (sqrt(limit)); std::unique_ptr<std::vector<bool> > sieve(new std::vector<bool>(limit)); for (i = 2; i <= isqrt; ++i) { if (sieve->at(i)) continue; for (j = i*i; j < limit; j += i) sieve->at(j) = 1; } for_each(sieve->cbegin() + 2, sieve->cend(), [&res](bool i) { res += !i; }); std::cout << res << std::endl; return 0;}Is this the most idiomatic way to code in C++? I also tried to replace the first for loop with a for_each and a functor that accepts sieve, but in the end I decided it wasn't worth it and left it like that.In both versions I am allocating on the heap because the sieve array/vector gets too big for the stack.Interestingly, the C++ version is faster! I thought they were pretty much identical, but instead the C++ version wins by a large margin:$ gcc --std=c99 -O3 erat.c -lm -o erat$ time ./erat 100000000050847534./erat 1000000000 11.50s user 0.41s system 99% cpu 11.927 total$ g++ --std=c++14 -O2 erat.cpp -o erat2$ time ./erat2 100000000050847534./erat2 1000000000 8.52s user 0.02s system 99% cpu 8.554 totalFeedback on the C version is also welcomed!
Counting the number of primes in C and C++11
c++;c;c++11;primes;comparative review
Idiomatic C++ Review#include <math.h>C++ has its own version of math header.#include <cmath>Difference is all the functions are placed in the std namespace.Prefer not to use std::endl. std::cerr << Usage: << argv[0] << <N> << std::endl;Forcing a flush is not normally what you want to do. The streams will automatically flush when required and doing it manually will only make the code less efficient.Prefer to put one variable per line. Also for loop counters can be declared inside the for statement (see below). size_t i, j, res = 0;Don't dynamical allocate when a local variable will do: std::unique_ptr<std::vector<bool> > sieve(new std::vector<bool>(limit)); // Should be std::vector<bool> sieve(limit);Also std::vector<bool> is special. It is optimized for space not speed. It also has some other quirks that make it undesirable, so prefer std::vector<char> unless you really really need to save space. BUT because of the space saving you can get better caching which may improve time. In this case presumably because of the size of the vector keeping it as bool makes it much more efficient.see: Comparing std::vector to std::vectorDeclare loop variables inside the for: for (i = 2; i <= isqrt; ++i) { // Usually written like this: for(int i = 2; i <= isqrt; ++i) {The at() method is a checked access to the member. It validates your index is in range (you don't do this in the C code). if (sieve->at(i)) continue;Unless you are using unvalidated user input there is little need to use the at() method, prefer to use operator[].In C++14 the functions std::begin() and std::end() were introduced to get the iterators for containers. You should prefer to use these as they work with arrays as well as the standard containers. for_each(sieve->cbegin() + 2, sieve->cend(), [&res](bool i) { res += !i; }); // Can be written as: auto begin = std::begin(sieve); std::advance(begin, 2); for_each(begin, std::end(sieve), [&res](bool i) { res += !i; });Don't bother with a return at the end of main. return 0;
_codereview.97367
Input given is:Each test case contains two lines. The first line contains a single integer N (1N105), the number of persons playing the game. The second line contains N integers i(height) (1hi109) the height of the i-th person. They are numbered 1 to N starting from Druid.Output given is:For each test case print N lines, in the i-th line print 2 numbers, the index of the first person taller than the i-th person on his left, and the index of the first person taller than the i-th person on his right. If no one is taller than the i-th person print -1 -1.Input is:35172 170 168 171 1693172 169 172 1172The output obtained is:-1 -1 1 4 2 4 1 1 4 1-1 -1 1 3-1 -1-1 -1The code is:t = input()num = []def get_druid_index(arr,n): druid_max_index = arr.index(max(arr)) if n == 1: num.append(-1) num.append(-1) for j in range(n): if j == druid_max_index: num.append(-1) num.append(-1) else: cur = arr[j] l = j r = j for k in range(n): if arr[l] > cur: num.append(l + 1) break if l == 0: l = n l = l - 1 for k in range(n): if r == n: r = 0 if arr[r] > cur: num.append(r + 1) break r = r + 1for i in range(t): arr = [] n = input() arr = raw_input() arr = arr.split() get_druid_index(arr,n)count = 0for i in range(len(num)/2): print num[count],num[count + 1] count = count + 2I optimized the code as much as possible but I get TLE from the online judge. Please offer suggestions for improvements.
Finding the tallest and find the index number of the next taller guy in a circular queue
python;time limit exceeded;circular list
I think you can write a linear time solution borrowing ideas from this. The idea is to keep a stack of decreasing maxima (SDM). Let's consider first the problem without taking into account the circularity...Say your input was [7, 4, 5, 3]. When you are processing the third item (5), you want your SDM to be [(7, 1), (4, 2)], where he second item in the tuple is the 1-based index of that item in the original array, as per your problem's description. You search the SDM for the last entry larger than the item being processed, which in this case is (7, 1), so the index of the first item larger than 5 to its left is 1. You then discard all items in the SDM to the right of this one, and insert the current value in it's position, so the SDM now becomes [(7, 1), (5, 2)]. Rinse, repeat, and you have all your first items larger than to the left. For the symmetric item to the right, do the same scanning from right to left.At first this may seem as an \$O(n^2)\$ algorithm, since you have to search a list that could potentially be as large as the array (e.g. if the input is monotonically decreasing) for every item. Because the SDM is sorted, you could try to use binary search to make that bound \$O(n\log n)\$, but that would actually slow down the process!You have to keep in mind that, as the stack is being searched sequentially, entries that aren't larger than the one being processed are being removed from the stack! So the more work an item requires to find it's answer, the easier it makes it for the ones remaining. A careful analysis of this shows that, on average, each item takes constant time to process, so the resulting time complexity is \$O(n)\$, which is basically as good as it gets.You can factor in the circularity of the problem into the above approach, by first finding the maximum, and always starting your circular iteration, whether to the left or right, from it, so that you will always have the maximum in your SDM.But enough talking, here's an implementation:def taller_to_the_sides(list_): max_index = list_.index(max(list_)) sdm = [] left = [] for index in range(len(list_)): index += max_index index %= len(list_) item = list_[index] while sdm and sdm[-1][0] <= item: sdm.pop() if sdm: left.append(sdm[-1][1] + 1) else: left.append(-1) sdm.append((item, index)) if max_index > 0: left = left[-max_index:]+left[:-max_index] sdm = [] right = [] for index in range(len(list_)): index = max_index - index index %= len(list_) item = list_[index] while sdm and sdm[-1][0] <= item: sdm.pop() if sdm: right.append(sdm[-1][1] + 1) else: right.append(-1) sdm.append((item, index)) right = right[max_index::-1] + right[:max_index:-1] return zip(left, right)There are two almost identical blocks in that function that should probably be refactored into a common external function, but I felt it would better show what was going on to keep them separated.Anyway, when you run this you get the expected output:>>> list(taller_to_the_sides([172, 170, 168, 171, 169]))[(-1, -1), (1, 4), (2, 4), (1, 1), (4, 1)]>>> list(taller_to_the_sides([169, 172, 170, 168, 171]))[(5, 2), (-1, -1), (2, 5), (3, 5), (2, 2)]The second example is the first one shifted one item to the right, to show that maxima not in the first position also work. And since the algorithm is linear, it handles large inputs reasonably fast:a = [random.random() for _ in range(100)]>>> %timeit taller_to_the_sides(a)10000 loops, best of 3: 172 s per loopa = [random.random() for _ in range(1000)]>>> %timeit taller_to_the_sides(a)1000 loops, best of 3: 1.78 ms per loopa = [random.random() for _ in range(10000)]>>> %timeit taller_to_the_sides(a)100 loops, best of 3: 18.3 ms per loopTo be honest, I was expecting it to be faster, but do notice also how the time scaling is roughly linear, as expected.
_cogsci.13952
I've come across the Ebbinghaus Curve (forgetting curve) showing the retention of learned knowledge over time, but I wondered if there was the same kind of model for the retention of details from experiences over time, i.e., how much detail of an event does someone forget as time passes. One would guess the same kind of curve may have been produced for this but I'm unsure what to look for.
Ebbinghaus like model for retention of details from experience
learning;memory
null
_codereview.107495
I have a function that formats a number (even a float) to a German decimal format. I got this function from here https://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript and it works. But every time I want to format a number that I stored in a variable I have to add .format(2, 3, '.', ',').EX: I have an int :45122.9 and I want to format it I have this function:Number.prototype.format = function(n, x, s, c) { var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')', num = this.toFixed(Math.max(0, ~~n)); return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));};var netto=45122.9;document.write(netto.format(2, 3, '.', ',')+ ' ' +'');This will format my number as such 45.122,90 .Is there a way to name the function, lets say... formatNumber, add this part to it format(2, 3, '.', ',') and than just call it like this: document.write(formatNumber(netto)); ?
Number to german decimal format converter function
javascript;functional programming;formatting;integer
null
_unix.186718
I type mosquitto_sub -d -t +/# from the Ubuntu terminal to access the MQTT stream.Real output from the live MQTT stream is this:Sending PINGREQReceived PINGRESPSending PINGREQReceived PINGRESPReceived PUBLISH (d0, q0, r0, m0, 'm/gf/TMX6BP/075/d/SVlts', ... (28 bytes))86,1224830,27610 27869 17565Received PUBLISH (d0, q0, r0, m0, 'm/gf/TMX6BP/075/d/status', ... (39 bytes))86,1243000,164573,-33.836465,151.051189Sending PINGREQReceived PINGRESPReceived PUBLISH (d0, q0, r0, m0, 'm/NWRL/TMX/098/d/SVlts', ... (26 bytes))806,3040421,7549 7750 3904Received PUBLISH (d0, q0, r0, m0, 'm/NWRL/TMX/098/d/status', ... (39 bytes))806,3069000,59666,-33.836465,151.051189Sending PINGREQReceived PINGRESPSending PINGREQReceived PINGRESPSending PINGREQReceived PINGRESPSending PINGREQReceived PINGRESPReceived PUBLISH (d0, q0, r0, m0, 'm/NWRL/TMX/098/d/SVlts', ... (26 bytes))810,5440995,6143 7807 4076Sending PINGREQReceived PINGRESPReceived PUBLISH (d0, q0, r0, m0, 'm/NWRL/TMX/098/d/status', ... (39 bytes))810,5489000,59897,-33.836465,151.051189Sending PINGREQReceived PINGRESPThere is no way of predicting when the next PUBLISH will be seen as they are only seen in the stream when the vehicle has transmission/reception from the GSM/3G towersTo filter I add mosquitto_sub -d -t +/# 2> >(grep PUBLISH) this will only allow lines with PUBLISH in it, hence the ouput is:Received PUBLISH (d0, q0, r0, m0, 'm/gf/TMX6BP/075/d/status', ... (38 bytes))86,637999,164563,-33.836465,151.051189Received PUBLISH (d0, q0, r0, m0, 'm/NWRL/TMX/098/d/SVlts', ... (26 bytes))806,3040421,7549 7750 3904Received PUBLISH (d0, q0, r0, m0, 'm/NWRL/TMX/098/d/status', ... (39 bytes))806,3069000,59666,-33.836465,151.051189Received PUBLISH (d0, q0, r0, m0, 'm/gf/TMX6BP/075/d/SVlts', ... (28 bytes))86,1224830,27610 27869 17565Received PUBLISH (d0, q0, r0, m0, 'm/gf/TMX6BP/075/d/status', ... (39 bytes))86,1243000,164573,-33.836465,151.051189Received PUBLISH (d0, q0, r0, m0, 'm/NWRL/TMX/098/d/SVlts', ... (26 bytes))806,3640483,7463 7721 3933Received PUBLISH (d0, q0, r0, m0, 'm/NWRL/TMX/098/d/status', ... (39 bytes))806,3674000,59676,-33.836465,151.051189Received PUBLISH (d0, q0, r0, m0, 'm/NWRL/TMX/098/d/SVlts', ... (26 bytes))806,4240543,7291 7750 3933Received PUBLISH (d0, q0, r0, m0, 'm/NWRL/TMX/098/d/status', ... (39 bytes))806,4279000,59687,-33.836465,151.051189Received PUBLISH (d0, q0, r0, m0, 'm/gf/MXE/065/d/SVlts', ... (25 bytes))455,24715,28041 28041 967How would I be able to eliminate a few of the fields and also add a time stamp everytime I receive something; I 've tried using sed but had no luck. I entered $ mosquitto_sub -d -t +/# 2< <(grep PUBLISH) 2< <(sed s/^/ date/) , $ mosquitto_sub -d -t +/# 2< <(grep PUBLISH) 2< <(sed s/^/$date`/)Q: How can I change my input to the terminal so that the output from the above live feed would be:[timestamp],m,gf,TMX6BP,075,d,status,86,637999,164563,-33.836465,151.051189[timestamp],m,NWRL,TMX,098,d,SVlts,806,3040421,7549 7750 3904[timestamp],m,NWRL,TMX,098,d,status,806,3069000,59666,-33.836465,151.051189[timestamp],m,gf,TMX6BP,075,d,SVlts,86,1224830,27610 27869 17565[timestamp],m,gf,TMX6BP,075,d,status,86,1243000,164573,-33.836465,151.051189[timestamp],m,NWRL,TMX,098,d,SVlts,806,3640483,7463 7721 3933[timestamp],m,NWRL,TMX,098,d,status,806,3674000,59676,-33.836465,151.051189[timestamp],m,NWRL,TMX,098,d,SVlts,806,4240543,7291 7750 3933[timestamp],m,NWRL,TMX,098,d,status,806,4279000,59687,-33.836465,151.051189[timestamp],m,gf,MXE,065,d,SVlts,455,24715,28041 28041 967Possible solutions (future referencing):Using the mosquitto_sub -d -t +/# 2> >(sed -n s|.*\('.*',\).*|\1|p) | sed N;s/\n/ /;s/$/ $(date)/ The output is:0 810,5440995,6143 7807 4076 Wed Feb 25 23:23:51 UTC 2015 810,5489000,59897,-33.836465,151.051189 810,6041055,7606 7693 4076 Wed Feb 25 23:23:51 UTC 2015Using the mosquitto_sub -d -t +/# 2> >(grep PUBLISH) | sed N;s/\n/ /;s/$/ $(date)/ command from the terminal the output is 817,3069000,60045,-33.836465,151.051189 609,24570,27553 27553 955 Thu Feb 26 00:06:26 UTC 2015Using the mosquitto_sub -d -t +/# 2>&1 | sed -n /PUBLISH/{s|.*\('.*',\).*|\1|;N;s/\n/ /;s/$/ $(date)/;p} The output is 'm/gf/MX3/122/d/status', 610,33000,28162,-33.836465,151.051189 Thu Feb 26 01:18:17 UTC 2015
How can I remove a carriage return, add a time stamp and ignore some data from a live MQTT feed
text processing;streaming;data
Well, rather confusing but anyway... Judging by the output ofmosquitto_sub -d -t +/# 2> >(grep PUBLISH)your app seems to output to both stderr and stdout (otherwise you should only get lines matching PUBLISH in your output). It prints the debug messages (Sending... and Received...) to stderr and the actual data (810,5440995,6143...) to stdout. Apparently, you need comma separated values so you could try the following, if you need the timestamp from the line matching PUBLISH:mosquitto_sub -d -t +/# 2>&1 | xargs -d$'\n' -L1 sh -c 'date +%s,$0' | \sed -n /PUBLISH/{N;s|[ /]|,|g;s|^\([^,]*,\)[^']*'\([^']*\)',.*\n[^,]*,\(.*\)|\1\2,\3|;p}or, if you need the timestamp from the next line:mosquitto_sub -d -t +/# 2>&1 | xargs -d$'\n' -L1 sh -c 'date +%s,$0' | \sed -n /PUBLISH/{N;s|[ /]|,|g;s|^[^,]*,[^']*'\([^']*\)',.*\n\([^,]*,\)\(.*\)|\2\1,\3|;p}2>&1 redirects stderr to stdout, the output is then piped to xargs which passes each line as an argument to the next command sh -c 'date +%s,$0' so each line is prepended with a timestamp+comma, e.g.:[timestamp],Sending PINGREQ[timestamp],Received PINGRESP[timestamp],Received PUBLISH (d0, q0, r0, m0, 'm/NWRL/TMX/098/d/status', ... (39 bytes))[timestamp],871,40114,4536 4536 323This is then piped to sed suppressing the automatic printing (-n).For each line matching PUBLISH, append the Next line, replace each space and / with comma then via grouping, retain only the first or second timestamp, the values in between quotes and the values after the second timestamp and finally, print the result:[timestamp],m,NWRL,TMX,098,d,status,871,40114,4536,4536,323
_unix.273989
I've installed Raspian Jessie Lite and added on the minimum I can to get a browser running fullscreen. I started off with IceWeasel:sudo apt-get install -y x-window-system iceweaselAnd put this into my .xinitrc:iceweasel http://localhost/Now, when I run startx it loads IceWeasel. However, it only took up a small; portion of the screen. I was able to fix that by loading IceWeasel, closing it, then modifying the file that stored the window size and make it 1920x1080.That was all fine, until I discovered IceWeasel didn't support all th nice new ECAMScript goodness Chrome did. So, I'm trying to swap for Chromium. I've managed to get it all installed, and I've changed my .xinitrc to this:chromium-browser --start-maximized --kiosk http://localhost/However, when this launches it only uses about (possibly exactly) half of the screen! I've tried various options but can't get it working. --start-fullscreen is even weirder and renders correctly but gets chopped in half! :(Note: I'm trying to avoid installing any window manager/etc, as it seems like it shouldn't be required when IceWeasel is already all working correctly!?IceWeasel:Chromium (--start-maximized and --kiosk):Chromium (--start-fullscreen):
How can I make Chromium start full-screen under X?
xorg;raspbian;chrome
Ok, with help from this thread I got it working. Although that poster said it didn't work, I edited .config/chromium/Default/Preferences and explicitly set the window size:Beforewindow_placement:{ bottom:1060, docked:false, left:10, maximized:true, right:950, top:10 // ...Afterwindow_placement:{ bottom:1080, docked:false, left:0, maximized:true, right:1920, top:0 // ...I wondered if maybe this had been set badly by the first load of the app not being fullscreen, but I tried deleting ~/.config and then loading it again, but it just recreated it with the left half of the screen. I guess I'll have to script loading Chromium, killing it, then rewriting that part of the file in my setup script! ;(
_unix.41816
In unity, when I click on any application icon on the left vertical application launcher toolbar -that particular application bring to front. But If I click on the same icon again, why doesn't that application get minimized ?I am expecting to see the same behavior as that of Gnome's taskbar.
window minimize
gnome;unity
null
_cstheory.34398
Real computers have limited memory and only a finite number of states.So they are essentially finite automata.Why do theoretical computer scientists use the Turing machines (and other equivalent models) for studying computers?What is the point of studying these much stronger models with respect to real computers?Why is the finite automata model not enough?
Real computers have only a finite number of states, so what is the relevance of Turing machines to real computers?
soft question;fl.formal languages;automata theory;big picture;turing machines
There are two approaches when considering this question: historical that pertains to how concepts were discovered and technical which explains why certain concepts were adopted and others abandoned or even forgotten.Historically, the Turing Machine is perhaps the most intuitive model of several developed trying to answer the Entscheidungsproblem. This is intimately related to the great effort in the first decades of the 20th century to completely axiomatize mathematics. The hope was that once you have proven a small set of axioms to be correct (which would require substantial effort), you could then use a systematic method to derive a proof for the logical statement you were interested in. Even if someone considered finite automata in this context, they would be quickly dismissed since they fail to compute even simple functions.Technically, the statement that all computers are finite automata is false. A finite automaton has constant memory that cannot be altered depending on the size of the input. There is no limitation, either in mathematics or in reality, that prevented from providing additional tape, hard disks, RAM or other forms of memory, once the memory in the machine was being used. I believe this was often employed in the early days of computing, when even simple calculations could fill the memory, whereas now for most problems and with the modern infrastructure that allows for far more efficient memory management, this is most of the time not an issue.EDIT: I considered both points raised in the comments but elected not to include them both of brevity and time I had available to write down the answer. This is my reasoning as to why I believe these points do not diminish the effectiveness of Turing machines in simulating modern computers, especially when compared to finite automata:Let me first address the physical issue of a limit on memory by the universe. First of all, we don't really know if the universe is finite or not. Furthermore, the concept of the observable universe which is by definition finite, is also by definition irrelevant to a user that can travel to any point of the observable universe to use memory. The reason is that the observable universe refers to what we can observe from a specific point, namely Earth, and it would be different if the observer could travel to a different location in the universe. Thus, any argumentation about the observable universe devolves into the question of the universe's finiteness. But let's suppose that through some breakthrough we acquire knowledge that the universe is indeed finite. Although this would have a great impact on scientific matters, I doubt it would have any impact on the use of computers. Simply put, it might be that in principle the computers are indeed finite automata and not Turing machines. But for the sheer majority for computations and in all likelihood every computation humans are interested in, Turing machines and the associated theory offers us a better understanding. In a crude example, although we know that Newtonian physics are essentially wrong, I doubt mechanical engineers use primarily quantum physics to design cars or factory machinery; the corner cases where this is needed can be dealt at an individual level.Any technical restrictions such as buses and addressing are simply technical limitations of existing hardware and can be overcome physically. The reason this is not true for current computers is because the 64-bit addressing allowed us to move the upper bound on the address space to heights few if any applications can achieve. Furthermore, the implementation of an extendable addressing system could potentially have an impact on the sheer majority of computations that will not need it and thus is inefficient to have. Nothing stops you from organizing a hierarchical addressing system, e.g. for two levels the first address could refer to any of $2^{64}$ memory banks and then each bank has $2^{64}$ different addresses. Essentially networking is a great way of doing this, every machine only cares for its local memory but they can compute together.
_webmaster.31079
I own a site, and I want to know how many of my new visitors are being converted into returning visitors after visiting my site.Not how often users visit my site, recency or anything like that, but how many of new visitors come back, after stumbling upon my site.Do any of you out there know how to track this using Google Analytics?
How to track conversion from new visitor to returning visitor in Google Analytics?
google;analytics;visitors
null
_codereview.10545
Are these methods getNewId() & fetchIdsInReserve() thread safe ?public final class IdManager { private static final int NO_OF_USERIDS_TO_KEEP_IN_RESERVE = 200; private static final AtomicInteger regstrdUserIdsCount_Cached = new AtomicInteger(100); private static int noOfUserIdsInReserveCurrently = 0; public static int getNewId(){ synchronized(IdManager.class){ if (noOfUserIdsInReserveCurrently <= 20) fetchIdsInReserve(); noOfUserIdsInReserveCurrently--; } return regstrdUserIdsCount_Cached.incrementAndGet(); } private static synchronized void fetchIdsInReserve(){ int reservedInDBTill = DBCountersReader.readCounterFromDB(....); // read column from DB if (noOfUserIdsInReserveCurrently + regstrdUserIdsCount_Cached.get() != reservedInDBTill) throw new Exception(Unreserved ids alloted by app before reserving from DB); if (DBUpdater.incrementCounter(....)) //if write back to DB is successful noOfUserIdsInReserveCurrently += NO_OF_USERIDS_TO_KEEP_IN_RESERVE; }}
Is this method thread safe?
java;multithreading;thread safety
You may still have a logic problem. The first time getNewId() is called noOfUserIdsInReserveCurrently = 0 so fetchIdsInReserve() is called and noOfUserIdsInReserveCurrently = 199.Now imagine the thread gets parked before returning.Now imagine this happens to 179 more threads. So that we are now at noOfUserIdsInReserveCurrently = 20 and triggering fetchIdsInReserve() again. at this point there is no guarantee that return regstrdUserIdsCount_Cached.incrementAndGet() has ever been called so regstrdUserIdsCount_Cached.get() = 0. Given this, does the check if (noOfUserIdsInReserveCurrently + regstrdUserIdsCount_Cached.get() != reservedInDBTill) fail?This is not an issue if there are a fixed number of threads that can call this, like from a FixedThreadPool. But if it is unconstrained then there might be a failure mode.
_unix.117027
As stated in the title:How can I use Alt+<ASCII CODE> on Linux (Mint 16) on a netbook which doesn't have a num pad nor a Num lock button?I found lots of tutorials for Windows, but no one with Linux.I also tried using Alt+Fn key but I just get some strange behavior on terminal,like (while running gdb) :(arg: 23)
Insert a character that isn't present on my keyboard on Linux Mint
keyboard;keyboard layout
null
_cs.68458
Could you find an example of a complete $\mu$-recursive function that is not a primitive function?
Complete $\mu$-recursive function that is not primitive recursive
computability;recursion;primitive recursion
null
_datascience.4914
Recently in a Machine Learning class from professor Oriol Pujol at UPC/Barcelona he described the most common algorithms, principles and concepts to use for a wide range of machine learning related task. Here I share them with you and ask you: is there any comprehensive framework matching tasks with approaches or methods related to different types of machine learning related problems?How do I learn a simple Gaussian? Probability, random variables, distributions; estimation, convergence and asymptotics, confidence interval.How do I learn a mixture of Gaussians (MoG)? Likelihood, Expectation-Maximization (EM); generalization, model selection, cross-validation; k-means, hidden markov models (HMM)How do I learn any density? Parametric vs. non-Parametric estimation, Sobolev and other functional spaces; l 2 error; Kernel density estimation (KDE), optimal kernel, KDE theoryHow do I predict a continuous variable (regression)? Linear regression, regularization, ridge regression, and LASSO; local linear regression; conditional density estimation.How do I predict a discrete variable (classification)? Bayes classifier, naive Bayes, generative vs. discriminative; perceptron, weight decay, linear support vector machine; nearest neighbor classifier and theoryWhich loss function should I use? Maximum likelihood estimation theory; l -2 estimation; Bayessian estimation; minimax and decision theory, Bayesianism vs frequentismWhich model should I use? AIC and BIC; Vapnik-Chervonenskis theory; cross-validation theory; bootstrapping; Probably Approximately Correct (PAC) theory; Hoeffding-derived boundsHow can I learn fancier (combined) models? Ensemble learning theory; boosting; bagging; stackingHow can I learn fancier (nonlinear) models? Generalized linear models, logistic regression; Kolmogorov theorem, generalized additive models; kernelization, reproducing kernel Hilbert spaces, non-linear SVM, Gaussian process regressionHow can I learn fancier (compositional) models? Recursive models, decision trees, hierarchical clustering; neural networks, back propagation, deep belief networks; graphical models, mixtures of HMMs, conditional random fields, max-margin Markov networks; log-linear models; grammarsHow do I reduce or relate features? Feature selection vs dimensionality reduction, wrapper methods for feature selection; causality vs correlation, partial correlation, Bayes net structure learningHow do I create new features? principal component analysis (PCA), independent component analysis (ICA), multidimensional scaling, manifold learning, supervised dimensionality reduction, metric learningHow do I reduce or relate the data? Clustering, bi-clustering, constrained clustering; association rules and market basket analysis; ranking/ordinal regression; link analysis; relational dataHow do I treat time series? ARMA; Kalman filter and stat-space models, particle filter; functional data analysis; change-point detection; cross-validation for time seriesHow do I treat non-ideal data? covariate shift; class imbalance; missing data, irregularly sampled data, measurement errors; anomaly detection, robustnessHow do I optimize the parameters? Unconstrained vs constrained/Convex optimization, derivative-free methods, first- and second-order methods, backfitting; natural gradient; bound optimization and EMHow do I optimize linear functions? computational linear algebra, matrix inversion for regression, singular value decomposition (SVD) for dimensionality reductionHow do I optimize with constraints? Convexity, Lagrange multipliers, Karush-Kuhn-Tucker conditions, interior point methods, SMO algorithm for SVMHow do I evaluate deeply-nested sums? Exact graphical model inference, variational bounds on sums, approximate graphical model inference, expectation propagationHow do I evaluate large sums and searches? Generalized N-body problems (GNP), hierarchical data structures, nearest neighbor search, fast multiple method; Monte Carlo integration, Markov Chain Monte Carlo, Monte Carlo SVDHow do I treat even larger problems? Parallel/distributed EM, parallel/distributed GNP; stochastic subgradient methods, online learningHow do I apply all this in the real world? Overview of the parts of the ML, choosing between the methods to use for each task, prior knowledge and assumptions; exploratory data analysis and information visualization; evaluation and interpretation, using confidence intervals and hypothesis test, ROC curves; where the research problems in ML are
When to use what - Machine Learning
machine learning;algorithms
null
_webmaster.47430
I am thinking of signing up with cloud flare, but since i'm not very familiar with the technical side of things, I wanted to ask here first.How safe is it to sign up with services, like cloud flare?Do they ultimately own my domain? Are they able to take away control of my domain?The way I see it, I transfer ownership of my domain to them, and they will also appear as owners in whois. Is this how it works? I'm confused.Note, I am not asking how reputable cloud flare is, but rather how it works, and if they are technically able to snatch my domain.
Cloudflare is it safe?
domains;cdn;dns servers;whois;cloudflare
The short answer is that Cloudflare is safe. Cloudflare is essentially nothing more than a content delivery network (CDN). The theory behind it is that they will cache copies of your website to their servers, which are spread across different locations. When a visitor visits your site the server that is closest to them is chosen and the connection has less distance to travel, hence speeding up the load times. It will also attempt to serve a cached copy of your site if it ever goes down for some reason.
_unix.46892
One day the power just went off when was using my desktop computer running Ubuntu 11.04. When later the power came back, I couldn't access the internet.When I open any browser, it tells me I have no connection. Even my desktop network icon shows that I am offline. But when I check the wired connection behind my desktop computer, it shows that I connected with a green blinking LED.What is going on with my desktop? All the computers in our lab are fine. Only mine which I use to administer our computer lab has this problem.When I run the iconfig command this is what I get:eth0 Link encap:Ethernet HWaddr b8:ac:6f:37:0d:58 inet6 addr: fe80::baac:6fff:fe37:d58/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:2759 errors:0 dropped:0 overruns:0 frame:0 TX packets:27 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:479931 (479.9 KB) TX bytes:6608 (6.6 KB) Interrupt:16 lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:118 errors:0 dropped:0 overruns:0 frame:0 TX packets:118 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:13086 (13.0 KB) TX bytes:13086 (13.0 KB)And when I run the route -n command, this is what I get:Kernel IP routing tableDestination Gateway Genmask Flags Metric Ref Use Iface
Network icons showing not connected when my wired network cable shows that I am
ubuntu;networkmanager
null
_webapps.32093
I am not very familiar with Google Docs or Google Drive but started to look into it more and have two questions: Once a file is uploaded can others in my organization see the files and download them as they need to?Can I upload and download any file type with Google Drive?
Google Drive and Multiple Users
google;google drive
Once a file is uploaded can others in my organization see the files and download them as they need to?You will have to setup sharing options; also unless its set to Public I think others will need to have Google accounts to manage the access rights.Can I upload and download any file type with Google Drive?Not 'any' type, but it covers a lot of the common use cases: http://en.wikipedia.org/wiki/Google_Drive#Supported_file_formatsEdit: As @William Jackson points out in the comment below, this is the list of files that can be edited in docs, if you only care about storage then it should accept any file type.
_unix.292168
I've been struggling for days with this now and can't find what I'm doing wrong.I've got a website on a VPS server. Every night I make a backup of the database. It gets stored on my VPS server. I also want to send a copy to my NAS (Synology DS214play) at home. Both servers operate on Linux.So I've logged into my VPS server (as root) and generated a ssh-keygen.On my VPS it looks like this:[root@vps /]# cd ~[root@vps ~]# ls -alhdr-xr-x---. 7 root root 4.0K Jun 25 18:58 .dr-xr-xr-x. 24 root root 4.0K Jun 25 19:33 ..drwx------ 3 root root 4.0K Jun 25 20:29 .ssh[root@vps ~]# cd .ssh[root@vps .ssh]# ls -alhdrwx------ 3 root root 4.0K Jun 25 20:29 .dr-xr-x---. 7 root root 4.0K Jun 25 18:58 ..-rw------- 1 root root 1.7K Jun 26 07:27 id_rsa-rw-r--r-- 1 root root 403 Jun 26 07:27 id_rsa.pub-rw------- 1 root root 394 Jun 25 20:29 known_hostsThen I copied the file to the NAS by using ssh-copy-idadmin@NAS:/$ cd ~admin@NAS:~$ ls -alhdrwxrwxrwx 6 admin users 4.0K Jun 26 07:28 .drwxrwxrwx 13 root root 4.0K Jun 21 20:57 ..drwx------ 2 admin users 4.0K Jun 26 07:28 .sshadmin@NAS:~$ cd .sshadmin@NAS:~/.ssh$ ls -alhdrwx------ 2 admin users 4.0K Jun 26 07:28 .drwxrwxrwx 6 admin users 4.0K Jun 26 07:28 ..-rw------- 1 admin users 403 Jun 26 07:27 authorized_keysWhen looking into VPS/id_rsa.pub and NAS/authorized_keys I see that both keys are identical. Now I'm trying to copy a test file from the VPS to the NAS by using:[root@vps /]# scp -i ~/.ssh/id_rsa /test.txt admin@___.___.___.___:/volume1/SQL_backupThat however results in shell asking me for the password (every time).How come that I have to keep giving my pass?
SCP command keeps asking password
linux;ssh;scp;authorization
When troubleshooting problems with daemons, you should always check the system logs.In this particular case, if you check your system logs on the NAS host, you'll see something similar to:Authentication refused: bad ownership or modes for directory /home/adminThe problem is shown in this output:admin@NAS:~$ ls -alhdrwxrwxrwx 6 admin users 4.0K Jun 26 07:28 .For security, SSH will refuse to use the authorized_keys file if any ancestor of the ~/.ssh directory is writable by someone other than the user or root (ancestor meaning /home/user/.ssh, /home/user, /home, /). This is because another user could replace the ~/.ssh directory (or ~/.ssh/authorized_keys file) with their own, and then ssh into your user.To fix, change the permissions on the directory with something like:chmod 755 ~
_webapps.14978
Why is Yahoo Mail behind in security? They don't support HTTPS yet. Gmail and many others do. I'm shocked that Yahoo still doesn't have HTTPS. Why is this? What is the logic behind not supporting HTTPS in their mail client?
Yahoo Mail Does Not Have HTTPS
security;yahoo mail
null
_codereview.158664
I had a job interview one of the questions was the followingGiven an api - you submit a name of a person and it gives back a sorted list of all the free time slots this person has. the list might be very long.List<TimePeriod> GetTimesAvail(String person)you are given list of people and I need to implement a function which give you back a list of time periods where all the people are available at the same time.example for simplicity all the free time slots are on the same date 23/3/2017 - 00:59-1:30, 2:00-2:30, 3:00-3:30 //personA23/3/2017 - 1:00 -1:45, 3:00 -4:00 //personB23/3/2017 1:00am - 5:00pm //personCresult - 1:00-1:30 , 3:00 -3:30using System;using System.Collections.Generic;using System.Diagnostics;using System.Linq;using Microsoft.VisualStudio.TestTools.UnitTesting;namespace JobInterviewTests{ [TestClass] public class Question { [TestMethod] public void TestMethod1() { List<string> people = new List<string> { personA, personB, personC }; List<TimePeriod> result = GetTimeSlotForAll(people); Assert.AreEqual(1,result[0].Start.Hour); Assert.AreEqual(0,result[0].Start.Minute); Assert.AreEqual(1,result[0].End.Hour); Assert.AreEqual(30,result[0].End.Minute); Assert.AreEqual(3, result[1].Start.Hour); Assert.AreEqual(0, result[1].Start.Minute); Assert.AreEqual(3, result[1].End.Hour); Assert.AreEqual(30, result[1].End.Minute); } private List<TimePeriod> GetTimeSlotForAll(List<string> people) { if (people == null || people.Count == 0) { return new List<TimePeriod>(); } //future improvment -- suggested //List<List<TimePeriod>> tempTimeList = new List<List<TimePeriod>>(); //foreach (var person in people) //{ // var personList = Utiliies.GetTimesAvail(person); // tempTimeList.Add(personList); //} //List<Dictionary<string, List<TimePeriod>>> dictionaryList = new List<Dictionary<string, List<TimePeriod>>>(); //foreach (var list in tempTimeList) //{ // //key is the day/month/year // Dictionary<string, List<TimePeriod>> personDictionary = new Dictionary<string, List<TimePeriod>>(); // foreach (var time in list) // { // if (personDictionary.ContainsKey(time.ToDateTimeDay())) // { // personDictionary[time.ToDateTimeDay()].Add(time); // } // else // { // personDictionary[time.ToDateTimeDay()] = new List<TimePeriod>(); // personDictionary[time.ToDateTimeDay()].Add(time); // } // } // dictionaryList.Add(personDictionary); //} //place the first person meetings a the first result List<TimePeriod> firstPersonList = Utiliies.GetTimesAvail(people.FirstOrDefault()); List<TimePeriod> result = new List<TimePeriod>(); //intersect the meetings with the others for (int i = 1; i < people.Count; i++) { List<TimePeriod> secondPersonList = Utiliies.GetTimesAvail(people[i]); foreach (var secondSlot in secondPersonList) { foreach (var firstSlot in firstPersonList) { if (secondSlot.SameDay(firstSlot)) { CheckHourIntersections(firstSlot, secondSlot, result); } } } //copy the result into the first person firstPersonList.Clear(); foreach (var timeSlot in result) { firstPersonList.Add(new TimePeriod(timeSlot.Start, timeSlot.End)); } //clear result result.Clear(); } return firstPersonList; } private static void CheckHourIntersections(TimePeriod firstSlot, TimePeriod secondSlot, List<TimePeriod> result) { // check all the different interval intersections //one intersects with the start of anothesr //[-----] //firstSlot // [------] //secondSlot // 00:59 -> 1:30 --- 01:00 -> 01:45 //also cover //[-----] //firstSlot //[------] //secondSlot //also cover //[-------] //firstSlot // [------] //secondSlot if (((firstSlot.Start.Hour < secondSlot.Start.Hour) || (firstSlot.Start.Hour == secondSlot.Start.Hour && firstSlot.Start.Minute > secondSlot.Start.Minute)) && ((firstSlot.End.Hour < secondSlot.End.Hour) ||(firstSlot.End.Hour == secondSlot.End.Hour && firstSlot.End.Minute < secondSlot.End.Minute)) && ((secondSlot.Start.Hour < firstSlot.End.Hour) || (firstSlot.End.Hour == secondSlot.End.Hour && firstSlot.End.Minute < secondSlot.End.Minute)) ) { result.Add(new TimePeriod(secondSlot.Start, firstSlot.End)); return; } // [----] //firstSlot //02:00 -> 02:30 //[------] //secondSlot 01:00->01:45 if (((firstSlot.Start.Hour > secondSlot.Start.Hour) ||(firstSlot.Start.Hour == secondSlot.Start.Hour && firstSlot.Start.Minute >= secondSlot.Start.Minute)) && ((firstSlot.End.Hour < secondSlot.End.Hour)|| (firstSlot.End.Hour == secondSlot.End.Hour && firstSlot.End.Minute < secondSlot.End.Minute))) { result.Add(new TimePeriod(firstSlot.Start, firstSlot.End)); return; } // [----] //firstSlot //[------] //secondSlot if (((firstSlot.Start.Hour > secondSlot.Start.Hour && firstSlot.Start.Minute < secondSlot.Start.Minute) || (firstSlot.Start.Hour == secondSlot.Start.Hour && firstSlot.Start.Minute > secondSlot.Start.Minute)) && ((firstSlot.End.Hour > secondSlot.End.Hour && firstSlot.End.Minute < secondSlot.End.Minute) || (firstSlot.End.Hour == secondSlot.End.Hour && firstSlot.End.Minute > secondSlot.End.Minute))) { result.Add(new TimePeriod(firstSlot.Start, secondSlot.End)); } } } [DebuggerDisplay({Start.Hour}:{Start.Minute}->{End.Hour}:{End.Minute})] public class TimePeriod { public DateTime Start { get; set; } public DateTime End { get; set; } public TimePeriod(DateTime start, DateTime end) { Start = start; End = end; } public bool SameDay(TimePeriod other) { return this.Start.Year == other.Start.Year && this.Start.Month == other.Start.Month && this.Start.Day == other.Start.Day; } public string ToDateTimeDay() { return Start.ToShortDateString(); } } public static class Utiliies { public static List<TimePeriod> GetTimesAvail(String person) { var res = new List<TimePeriod>(); if (person == personA) { res.Add(new TimePeriod(new DateTime(2017, 3, 23, 0, 59, 00), new DateTime(2017, 3, 23, 1, 30, 00))); res.Add(new TimePeriod(new DateTime(2017, 3, 23, 2, 00, 00), new DateTime(2017, 3, 23, 2, 30, 00))); res.Add(new TimePeriod(new DateTime(2017, 3, 23, 3, 00, 00), new DateTime(2017, 3, 23, 3, 30, 00))); } if (person == personB) { res.Add(new TimePeriod(new DateTime(2017, 3, 23, 1, 00, 00), new DateTime(2017, 3, 23, 1, 45, 00))); res.Add(new TimePeriod(new DateTime(2017, 3, 23, 3, 00, 00), new DateTime(2017, 3, 23, 4, 00, 00))); } if (person == personC) { res.Add(new TimePeriod(new DateTime(2017, 3, 23, 00, 00, 00), new DateTime(2017, 3, 23, 14, 00, 00))); } return res; } }}I had about 20 mins to write the code and talk about complexity.one suggestion I made since the list of free TimePeriod could be very long is to store a List<Dictionary<day+month, TimePeriod>> personsso we would only call the API in the beginning for the list of all of the names and than later on use a dictionary to fetch the TimePeriods for a certain date.something like this:List<List<TimePeriod>> temptimeList = new List<List<TimePeriod>>(); foreach(var person in people) { var personList = getTimesAvail(person); tempTimelist.Add(personList); } List<Dictionary<DateTime, TimePeriod>> dictionaryList = new List<Dictionary<DateTime, TimePeriod>>(); foreach(var list in temptimeList) { Dictionary <DateTime, TimePeriod> personDictionary = new <DateTime, TimePeriod>(); foreach(var time in list) { personDictionary.Add(time.ToDateTimeDay(), time); } }My question is:Can you please point out where is my code not optimal? I am talking about algorithm and time complexity. please let me know if you need more information.
Time schedule intersection
c#;interview questions;interval
null
_webmaster.107126
I have setup an EC2 instance with the Amazon Linux image and installed LAMP and Wordpress as per the Amazon docs.It works fine, serves the default Wordpress page, but as soon as the instance is rebooted the web server no longer appears to work. The index page is no longer served. Curling localhost returns empty.I'm not sure what config is lost on reboot. Apache and MYSQL are running and are setup to run on boot.When I try and curl http://localhost and I look at the apache access log I see:::1 - - [17/Jun/2017:00:56:26 +0000] GET / HTTP/1.1 301 350 - curl/7.35.0::1 - - [17/Jun/2017:00:59:19 +0000] GET / HTTP/1.1 301 350 - curl/7.35.0::1 - - [17/Jun/2017:00:59:21 +0000] GET / HTTP/1.1 301 350 - curl/7.35.0Here is my httpd.confServerRoot /etc/httpdListen 80Include conf.modules.d/*.confUser apacheGroup apacheServerAdmin root@localhost<Directory /> AllowOverride none Require all denied</Directory>DocumentRoot /var/www/html<Directory /var/www> AllowOverride None # Allow open access: Require all granted</Directory># Further relax access to the default document root:<Directory /var/www/html> Options Indexes FollowSymLinks AllowOverride All Require all granted</Directory><IfModule dir_module> DirectoryIndex index.html</IfModule><Files .ht*> Require all denied</Files>ErrorLog logs/error_logLogLevel warn<IfModule log_config_module> LogFormat %h %l %u %t \%r\ %>s %b \%{Referer}i\ \%{User-Agent}i\ combined LogFormat %h %l %u %t \%r\ %>s %b common <IfModule logio_module> # You need to enable mod_logio.c to use %I and %O LogFormat %h %l %u %t \%r\ %>s %b \%{Referer}i\ \%{User-Agent}i\ %I %O combinedio </IfModule> CustomLog logs/access_log combined</IfModule><IfModule alias_module> ScriptAlias /cgi-bin/ /var/www/cgi-bin/</IfModule><Directory /var/www/cgi-bin> AllowOverride None Options None Require all granted</Directory><IfModule mime_module> TypesConfig /etc/mime.types AddType application/x-compress .Z AddType application/x-gzip .gz .tgz AddType text/html .shtml AddOutputFilter INCLUDES .shtml</IfModule>AddDefaultCharset UTF-8<IfModule mime_magic_module> MIMEMagicFile conf/magic</IfModule>EnableSendfile onIncludeOptional conf.d/*.confResponse Headers from curl -v[ec2-user@ip-x-x-x-x ~]$ curl -v localhost* Rebuilt URL to: localhost/* Trying 127.0.0.1...* TCP_NODELAY set* Connected to localhost (127.0.0.1) port 80 (#0)> GET / HTTP/1.1> Host: localhost> User-Agent: curl/7.51.0> Accept: */*> < HTTP/1.1 301 Moved Permanently< Date: Sat, 17 Jun 2017 23:46:00 GMT< Server: Apache/2.4.7 (Ubuntu)< X-Powered-By: PHP/5.5.9-1ubuntu4.21< X-Pingback: http://ec2-x-x-x-x.x-x-2.x.amazonaws.com/xmlrpc.php< Location: http://ec2-x-x-x-x.x-x-2.x.amazonaws.com< Content-Length: 0< Content-Type: text/html; charset=UTF-8< * Curl_http_done: called premature == 0* Connection #0 to host localhost left intact
Apache not working on AWS Linux after reboot - 301 Response code
wordpress;php;apache;linux;amazon aws
I figured out the issue. When an AWS instance is rebooted, the DNS address changes. As I am using Wordpress, I need to update the siteurl and home url in the MySQL Database for the wordpress site to the new DNS address.In the pictures below for example localhost should be replaced with the DNS address of the instance. When the instance reboots, this will need to be replaced again with the new DNS address and so on, every time the instance reboots. Really I should have used a static DNS address to save me the pain of this issue :)
_unix.272317
Consider this:$ cd /tmp$ echo echo YES >> prog/myprog$ chmod +x prog/myprog$ prog/myprogYES$ myprogmyprog: command not foundI can temporarily modify PATH to call myprog by name like this:$ PATH=$PATH:$(readlink -f prog) myprogYES... however I cannot chain commands with this approach:$ PATH=$PATH:$(readlink -f prog) myprog && myprogYESmyprog: command not found... apparently the modified PATH apparently didn't propagate to the second invocation.I'm aware I could do this:$ PATH=$PATH:$(readlink -f prog) bash -c myprog && myprogYESYES... but then I have to invoke an extra bash process - and even worse, I have to quote.Is there any way to append to PATH temporarily for chained commands in a one-liner, without having to invoke extra bash and quote? Tried backticks, they don't work:$ PATH=$PATH:$(readlink -f prog) `myprog && myprog`myprog: command not found
Bash one-liner to temporarily append path for chained commands without additional bash invocation?
bash;environment variables;path
How about using a subshell:$ (PATH=$PATH:$(readlink -f prog); myprog && myprog)YESYES
_unix.375460
With a server with Scientific Linux 6.4 and a client with Scientific Linux 7, the server has the following /etc/export definition/home/control/nfs02 *(rw,sync,no_root_squash,no_subtree_check)On the client we have this in /etc/fstabSERVER_IP:/home/control/nfs02 /home/control/nfs nfs defaults 0 0The folder gets mounted but with nobody:nobody user and group permissions recursively.What I tried:I tried working with different fstab options like this: rw,sync,nosuid,users and defaultsIn the client's /etc/idmap.conf, I tried setting static translation and added a mapping like this: control@IP = control.I enabled NFS ID mapping through /sys/module/nfs/parameters/nfs4_disable_idmapping (According to a Server Fault SE question I lost) and then cleared the ID mapping cache nfsidmap -c with restarting the rpcidmapd service.I eventually ended up modifying the Nobody group and user in /etc/idmap.conf on the client both to control which I don't think it is the ideal case. All clients will mount the same share having the same user name and group, an fstab entry should be sufficient for mounting with respect to the user. What could have gone wrong?
NFS shared folder is mounted with nobody permissions
permissions;mount;nfs
null
_softwareengineering.7038
I'm using VS 2010 since we're developing an app in .Net 4 and the performance is driving me crazy. It's mostly bad when I don't view the IDE for a while (such as when I get pulled away for a help desk call or come in in the morning). I realize it's probably built in WPF which unloads its resources when unused, but the few minute delay while it loads everything back up is really annoying. I've also noticed some significant delays when opening files or compiling.
Can I do anything to improve performance in VS 2010?
ide;performance;visual studio 2010
I had a similar problem after installing a couple of extensions. I ended up disabling them all and enabling them only when I actually use them. This really helped the experience.EDIT: There seems to be a problem with certain Video Cards and drivers. You can check all the info here: http://blogs.msdn.com/b/ddperf/archive/2010/09/16/vs2010-performance-and-bad-video-drivers-hardware-redux.aspx
_codereview.67080
I have implemented my code using Cython. It is the current bottleneck in my computations.There are two non-numpy functions involved:calculate_2D_dist_squared which calculates the distance squared between two pointscalculate_2D_dist_squared_matrix which generates the distances squared between every two distinct vertices. calculate_2D_dist_squared_matrix organizes results so that dist_squared_matrix[1, 2, 3, 4] = the distance between polygon 1, vertex 2 and polygon 3, vertex 4. All indexing starts from 0.cdef double calculate_2D_dist_squared(self, np.ndarray[np.float64_t, ndim=1] p1, np.ndarray[np.float64_t, ndim=1] p2): cdef np.ndarray[np.float64_t, ndim=1] relative_vector = p1 - p2 return relative_vector[0]**2 + relative_vector[1]**2cdef np.ndarray[np.float64_t, ndim=4] calculate_2D_dist_squared_matrix(self, np.ndarray[np.float64_t, ndim=3] polygons_vertex_coords, int num_polygons, int num_vertices): cdef: int pi_focus int vi_focus int pi int vi # at initialization, set all dist_squared values to be -1, # indicating that they have been initialized, but not set properly # since by definition a dist_squared value has to be >= 0 np.ndarray[np.float64_t, ndim=4] result = -1*np.ones((num_polygons, num_vertices, num_polygons, num_vertices), dtype=np.float64) for pi_focus in range(num_polygons): for vi_focus in range(num_vertices): for pi in range(num_polygons): for vi in range(num_vertices): # if a dist_squared < 0, then it means that it # it has not been changed since initialization, and # needs to be updated, this way I avoid repeating work if result[pi_focus, vi_focus, pi, vi] < 0: dist_squared = self.calculate_2D_dist_squared(polygons_vertex_coords[pi_focus, vi_focus], polygons_vertex_coords[pi, vi]) result[pi_focus, vi_focus, pi, vi] = dist_squared result[pi, vi, pi_focus, vi_focus] = dist_squared return resultWhat are some things I could think about in order to increase the performance of my code?For the time being, I got a significant improvement in performance by only re-calculating updates to the dist_squared_matrix, rather than always re-calculating the dist_squared_matrix entirely every step.
Calculating the distance squared between all vertex-pairs of a number of 2D polygons
python;performance;numpy;computational geometry;cython
null
_unix.370658
I have a web application that is accessible only through HTTPS with client certificate authentication. I need to run some analysis tools which don't cope well with client certificate authentication. A full blown proxy like ZAP or BurpSuite works but is too heavy-weight. I am seeking for a lean solution that can be launched from the command line without GUI etc.Specifically, how can I set up a proxy that is locally accessible through HTTP or HTTPS, where the proxy handles all the client certificate business with the actual remote application?
How to offload TLS client certificate authentication to a simple proxy
proxy;ssl;certificates;https;http proxy
null
_softwareengineering.295281
I've just used git-tfs to checkout a TFS repo into a Git repo. The .git directory comes to 2.33GiB, and the primary reason for this is a couple of large directories coming to about 650MiB each. Each directory is chock full of (roughly 1500) JPEG image files that range from 50KiB to 5MiB in size.This obviously makes the Git repo uncomfortably large, and yet the images do kind of logically fit into the solution as they are converted to smaller sized images and served out to the client. A few of them would be OK, but the sheer number of them takes the repo to being too large. Neither Github nor Bitbucket will even allow you to push a Git repository larger than 2GB (Github don't explicitly state this but I tried to push it and it failed). What would be the best way to handle this? This question on this same site has top answers suggesting that it's basically OK to check images into source control.
Git repo with lots of medium-sized images?
version control;git;github;image;bitbucket
null
_webapps.107206
I can't access the email or phone number on the account. It gives me the option to get help from friends but in order for them to help they must first logout and back in to do it and they don't know their log in information either. What else can I do? I have a lot of memories and pictures from my father which is now passed away three years ago. Please help.
Can't retrieve Facebook password
facebook;account recovery
null
_webmaster.132
I've read several blogs about turning KeepAlive off in apache. When I had it turned on, and a spike in traffic, people started timing out, or had to wait +10 seconds for a page load. However, when I turned it off, requests finished almost immediately.I know HOW KeepAlive functions, and what it does, I just want to know why I would ever need it. If i'm using CSS sprites and combining all my javascript into 1 file, with only 2-3 http requests to the server, is it safe to have it turned off?
Apache KeepAlive - why should I ever need it?
server;apache;keepalive
If you can provide your resources very quickly, then a very short KeepAlive timeout should be the way to go, or use no KeepAlive at all.KeepAlive is important when you are going to have many requests from the same client, but it gets to be a problem if you need to serve to many clients at the same time. KeepAlive with SSL is even more important as the cost to setup a new SSL connection is very high, especially if it is only for a small amount of data.If you can serve up what you need in only 2-3 request, I'd suggest keeping it short enough to get those requests handled. If that is still not working and other users are hanging for a long time, then you probably need to consider some load balancing and a proxy.
_webapps.2616
From a feedburner feed by clicking on the Google icon, it's 3 clicks.From Google Chrome with Google RSS browser extension I've managed 2 clicks (must click subscribe when in Google Reader).Anyone know how to do 1-click?
What's the quickest way to add a feed to Google Reader?
google reader
The Better GReader extension for Firefox offers an Auto Add to Reader option that skips the interim screen from Google that asks if you want to add to Reader or iGoogle. You still need to click to confirm, though.The Subscribe bookmarklet on the Official Google Reader blog does essentially the same thing.(I don't think you're going to get around that confirmation in Reader. Even the Add Subscription tool in Reader itself requires two clicks to paste and accept.)
_codereview.107988
Well, it really isn't a big pain: but I fear of security risks (if that is even possible).Background:I decided to (sort of) abandon my Sudoku project (because I accidentally deleted it from disk), and was given the idea of a JavaFX Helper Library. I started with the LoginPane, as I find I use login popups quite often.The code is here:import javafx.geometry.HPos;import javafx.geometry.Insets;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.Label;import javafx.scene.control.TextField;import javafx.scene.layout.ColumnConstraints;import javafx.scene.layout.GridPane;import javafx.scene.layout.HBox;import javafx.stage.Stage;public class LoginPane { public static final String DEFAULT_TITLE = Login; public static final String USERNAME_LABEL_DEFAULT_TEXT = Username: ; public static final String PASSWORD_LABEL_TEXT = Password: ; public static final String DEFAULT_LOGIN_TEXT = Login; public static final String CANCEL_TEXT = Cancel; public static final boolean DEFAULT_HAS_CANCEL = true; public static final boolean DEFAULT_CAN_CLOSE = true; private static final Insets MAIN_PANE_PADDING = new Insets(10); private static final int MAIN_PANE_GAP = 10; private static final int BUTTON_PREF_WIDTH = 60; private static final int BUTTON_PANE_SPACING = 10; private static final boolean IS_RESIZABLE = false; private static final ColumnConstraints COL_1_CONSTRAINS = new ColumnConstraints( 70); private static final ColumnConstraints COL_2_CONSTRAINS = new ColumnConstraints( 200); private static String username = null; private static char[] password = null; public static UserInfo showLoginPane() { return showLoginPane(DEFAULT_TITLE); } public static UserInfo showLoginPane(String title) { return showLoginPane(title, USERNAME_LABEL_DEFAULT_TEXT); } public static UserInfo showLoginPane(String title, String usernameLabelText) { return showLoginPane(title, usernameLabelText, DEFAULT_LOGIN_TEXT); } public static UserInfo showLoginPane(String title, String usernameLabelText, String loginText) { return showLoginPane(title, usernameLabelText, loginText, DEFAULT_HAS_CANCEL, DEFAULT_CAN_CLOSE); } public static UserInfo showLoginPane(String title, String usernameLabelText, String loginText, boolean hasCancel, boolean canClose) { Stage stage = new Stage(); GridPane mainPane = new GridPane(); mainPane.setPadding(MAIN_PANE_PADDING); mainPane.setHgap(MAIN_PANE_GAP); mainPane.setVgap(MAIN_PANE_GAP); mainPane.getColumnConstraints().addAll(COL_1_CONSTRAINS, COL_2_CONSTRAINS); Label userLabel = new Label(usernameLabelText); GridPane.setHalignment(userLabel, HPos.RIGHT); TextField usernameField = new TextField(); GridPane.setHalignment(usernameField, HPos.LEFT); mainPane.addRow(0, userLabel, usernameField); Label passwordLabel = new Label(PASSWORD_LABEL_TEXT); GridPane.setHalignment(passwordLabel, HPos.RIGHT); PasswordField passwordField = new PasswordField(); GridPane.setHalignment(passwordField, HPos.LEFT); mainPane.addRow(1, passwordLabel, passwordField); HBox buttonPane = new HBox(BUTTON_PANE_SPACING); Button login = new Button(loginText); login.setPrefWidth(BUTTON_PREF_WIDTH); buttonPane.getChildren().add(login); login.setOnAction(e -> { username = usernameField.getText(); password = passwordField.getText().toCharArray(); }); if (hasCancel) { Button cancel = new Button(CANCEL_TEXT); cancel.setPrefWidth(BUTTON_PREF_WIDTH); buttonPane.getChildren().add(cancel); cancel.setOnAction(e -> stage.close()); } buttonPane.setAlignment(Pos.CENTER_RIGHT); mainPane.add(buttonPane, 1, 2); GridPane.setHalignment(buttonPane, HPos.RIGHT); Scene scene = new Scene(mainPane); stage.setTitle(title); stage.setScene(scene); stage.setResizable(IS_RESIZABLE); stage.setOnCloseRequest(e -> { if (canClose) { stage.close(); } else { e.consume(); } }); stage.showAndWait(); return new UserInfo(username, password); }}and if you are wondering what UserInfo is, it's here:import java.util.Arrays;public class UserInfo { private final String username; private final char[] password; public UserInfo(String username, char[] password) { this.username = username; this.password = password; } public String getUsername() { return username; } public char[] getPassword() { return Arrays.copyOf(password, password.length); }}Snapshot (showLoginPane() with no arguments):Explanation:The showLoginPane() method is the basic method. It provide default values for all the possible editable values. The editable values are as follows:String title: the title of the popup.String usernameLabelText: the text that replaces the default Username: .String loginText: the text that replaces the default Login text on the button.boolean hasCancel: if true, the cancel button is added. If false, then the cancel button is not shown.boolean canClose: if true, the popup is closeable through the X button. Otherwise, it will not close.Questions:Is the static method, constants, and return values username and password good practice? I couldn't find a way around this.Which constants should be public, and which private?Naming?Anything else?
This LoginPane is a Pain
java;authentication;javafx
ConstantsAll the public statics should be private. If clients really care, you can document the default label, but then you can't change the label without it being an API spec change. I wouldn't expect most clients need to know the default. Either they care to specify or they don't.For the privates, my personal preference would be to inline all the ones that will only ever be used in one place, but I can see the argument for extracting them.DesignI would suggest making a LoginPane an instantiable class, rather than just a helper method. Conceptually, a LoginPane is a thing, and so representing instances as objects would seem to be reasonable. It would have a constructor and a public UserInfo show() method, which would make it reusable.You should also consider using the Builder pattern to avoid the telescoping static method problem that you have. It would allow clients to specify only the values they care about. Documentation can indicate defaults - a good idea for the booleans, at least, though per above the labels are debatable.NamingFor consistency, canCancel would be better than hasCancel. The documentation can indicate that the cancel option is only made available if canCancel is true. Non-abbreviated names are generally better - COLUMN_1_CONSTRAINTS > COL_1_CONSTRAINTS.CorrectnessThe passwordLabel and cancelButton don't use the non-default label values, even if they're provided as method arguments. I'm not sure how much making the password a char[] actually helps you, because it's already in memory as a String from getText(). I'm not a JavaFX expert, so I'm not sure if there's a more correct way to do it, but a quick search implies there is not.You have a bug at the intersection of canClose and hasCancel. If hasCancel is true and canClose is false, you render a cancel button which does nothing.You also don't differentiate at all between somebody hitting [Ok] without entering any values and somebody hitting [Cancel]. It's unclear if that's relevant to clients, but probably it is.Here's something I slapped together that addresses many of the issues I discussed. public final class LoginPane { private static final Insets MAIN_PANE_PADDING = new Insets(10); private static final int MAIN_PANE_GAP = 10; private static final int BUTTON_PREFERRED_WIDTH = 60; private static final int BUTTON_PANE_SPACING = 10; private static final boolean IS_RESIZABLE = false; private static final ColumnConstraints COLUMN_1_CONSTRAINS = new ColumnConstraints(70); private static final ColumnConstraints COLUMN_2_CONSTRAINS = new ColumnConstraints(200); private final String username = ; private final char[] password = new char[0]; private final Stage stage = new Stage(); private LoginPane(final Builder builder) { final GridPane mainPane = new GridPane(); mainPane.setPadding(MAIN_PANE_PADDING); mainPane.setHgap(MAIN_PANE_GAP); mainPane.setVgap(MAIN_PANE_GAP); mainPane.getColumnConstraints().addAll(COLUMN_1_CONSTRAINS, COLUMN_2_CONSTRAINS); final Label userLabel = new Label(builder.usernameLabel); GridPane.setHalignment(userLabel, HPos.RIGHT); final TextField usernameField = new TextField(); GridPane.setHalignment(usernameField, HPos.LEFT); mainPane.addRow(0, userLabel, usernameField); final Label passwordLabel = new Label(builder.passwordLabel); GridPane.setHalignment(passwordLabel, HPos.RIGHT); final PasswordField passwordField = new PasswordField(); GridPane.setHalignment(passwordField, HPos.LEFT); mainPane.addRow(1, passwordLabel, passwordField); final HBox buttonPane = new HBox(BUTTON_PANE_SPACING); final Button login = new Button(builder.loginText); login.setPrefWidth(BUTTON_PREFERRED_WIDTH); buttonPane.getChildren().add(login); login.setOnAction(e -> { username = usernameField.getText(); password = passwordField.getText().toCharArray(); }); if (builder.canCancel) { final Button cancel = new Button(builder.cancelText); cancel.setPrefWidth(BUTTON_PREFERRED_WIDTH); buttonPane.getChildren().add(cancel); cancel.setOnAction(e -> stage.close()); } buttonPane.setAlignment(Pos.CENTER_RIGHT); mainPane.add(buttonPane, 1, 2); GridPane.setHalignment(buttonPane, HPos.RIGHT); final Scene scene = new Scene(mainPane); this.stage.setTitle(builder.title); this.stage.setScene(scene); this.stage.setResizable(IS_RESIZABLE); this.stage.setOnCloseRequest(e -> { if (builder.canCancel || builder.canClose) { stage.close(); } else { e.consume(); } }); } public UserInfo showAndWait() { this.stage.showAndWait(); return new UserInfo(this.username, this.password); } public static final class Builder { private String title = Login; private String usernameLabel = Username: ; private String passwordLabel = Password: ; private String loginText = Login; private String cancelText = Cancel; private boolean canCancel = true; private boolean canClose = true; public Builder() { } public Builder title(final String title) { this.title = title; return this; } public Builder usernameLabel(final String usernameLabel) { this.usernameLabel = usernameLabel; return this; } public Builder passwordLabel(final String passwordLabel) { this.passwordLabel = passwordLabel; return this; } public Builder loginText(final String loginText) { this.loginText = loginText; return this; } public Builder cancelText(final String cancelText) { this.cancelText = cancelText; return this; } /** * Whether or not the user can cancel this login dialog without entering values. True by default. * @param canCancel if true, the user can cancel the login dialog without entering values. * @return the instance of this Builder for method chaining. Will never return null. */ public Builder canCancel(final boolean canCancel) { this.canCancel = canCancel; return this; } public Builder canClose(final boolean canClose) { this.canClose = canClose; return this; } public LoginPane build() { return new LoginPane(this); } }}Using it might look something like:final LoginPane loginPane = new LoginPane.Builder().title(New Title).canCancel(false).build();loginPane.showAndWait();If you wanted to be really fancy, you could add public static methods to the LoginPane class which create and return a Builder with that value set. Then the client call would look more like:final LoginPane loginPane = LoginPane.title(New Title).canCancel(false).build();loginPane.showAndWait();It makes the code a bit easier to read at the cost of a slightly messier API.
_webapps.9352
I've noticed that when I look at the news feeds in facebook, it doesn't show updates from all of my friends. Is there a way to get an rss feed that contains status updates (and possibly shared links) posted by ALL of my friends? Or do I need to create a separate feed for each friend (not feasible.)
How can I get an rss feed of the activity of all my friends on Facebook (updates, shares, etc.)?
facebook;rss
null
_cs.50704
m doing a practise quiz which my professor has posted online, one of the questions im very confused about was this one. Consider the clauses {x,y} , {~x,y} , {~y,z} , {~z,w} , {~w,~y}is this true or false?The implication graph contains the following bad loop:x -> y -> z -> w -> ~y -> xI said that this statement was false , however it came out that its true, can someone explain to me why this is the case?Because i thought a bad loop would be a transition between a letter to the negation of its own then back to the original for example x -> ~x -> x
How to check wether a 2SAT implication graph has a bad loop or not?
2 sat
null
_unix.113540
I am using Debian 7 on VirutalBox as my virtual web server. Now, my /var/www directory is almost full. I added 27 GB of space to my VM as a new partition, formatted the partition with ext4 but my /var/www directory still doesn't have enough space.How can I resize /var/www?The output of df -h:
My /var/www directory is full
debian;webserver;www
Since the biggest partition appears to be /home, here is one solution (assuming there is no /home/webpages directory):cd /varcp -a www /home/webpages/rm -fr wwwln -s /home/webpages/ wwwWhat this does is:Enter the /var/ direcotoryMake an (as much as possible) exact copy of /var/www in the directory /home/webpagesComplete destroy the contents of the www directory (to save disk space). rm -fr is a very dangerous command Always use rm -fr with the utmost of careMake a symbolic link (symlink) so that /var/www now uses the files in /home/webpagesNow, sometimes web servers have issues with symlinks (I know Apache, in some configurations, refuses to follow a symlink), but, as I recall, this is not an issue if the document root (the directory the web server uses to publish files on the web) points to a symlink or if the symlink is below the document root. But, if it is an issue, it may be necessary to set up Apache to allow symlinks.
_webmaster.57333
This has happened to links we put on web pages and in emails.We might put www.oursite.org/work/ but when I view source it shows up as webmail.ourhosting.ca/hwebmail/services/go.php?url=https%3A%2F%2Fwww.oursite.org%2F%2work%2FThis ends up at the webmail login page for our web host. But only some of the people who click the link get the login page; others go directly to the original page we intended. We don't want it to go to the webmail login page, nobody needs to log in to our web site.This occurs for links to pages on our site, but also to links to other sites that we put in emails or in posts. It seems to be browser independent as well as e-mail client independent as we variously have used Firefox and Chrome as well as MS Outlook and Thunderbird. I've tried to resolve the issue with our webhost but they keep telling me they don't support our browser, or our email client (i.e., they don't understand the issue).At the moment, our only option is to try another web host just to get rid of their login. Any ideas about what's going on?
Good links somehow being converted to ones with a PHP redirect (not a virus)
php;redirects
null
_cs.6519
It's well-known that this 'naive' algorithm for shuffling an array by swapping each item with another randomly-chosen one doesn't work correctly:for (i=0..n-1) swap(A[i], A[random(n)]);Specifically, since at each of $n$ iterations, one of $n$ choices is made (with uniform probability), there are $n^n$ possible 'paths' through the computation; because the number of possible permutations $n!$ doesn't divide evenly into the number of paths $n^n$, it's impossible for this algorithm to produce each of the $n!$ permutations with equal probability. (Instead, one should use the so-called Fischer-Yates shuffle, which essentially changes out the call to choose a random number from [0..n) with a call to choose a random number from [i..n); that's moot to my question, though.)What I'm wondering is, how 'bad' can the naive shuffle be? More specifically, letting $P(n)$ be the set of all permutations and $C(\rho)$ be the number of paths through the naive algorithm that produce the resulting permutation $\rho\in P(n)$, what is the asymptotic behavior of the functions $\qquad \displaystyle M(n) = \frac{n!}{n^n}\max_{\rho\in P(n)} C(\rho)$ and $\qquad \displaystyle m(n) = \frac{n!}{n^n}\min_{\rho\in P(n)} C(\rho)$? The leading factor is to 'normalize' these values: if the naive shuffle is 'asymptotically good' then $\qquad \displaystyle \lim_{n\to\infty}M(n) = \lim_{n\to\infty}m(n) = 1$. I suspect (based on some computer simulations I've seen) that the actual values are bounded away from 1, but is it even known if $\lim M(n)$ is finite, or if $\lim m(n)$ is bounded away from 0? What's known about the behavior of these quantities?
How asymptotically bad is naive shuffling?
algorithms;algorithm analysis;asymptotics;probability theory;randomness
We will show by induction that the permutation $\rho_n = (2,3,4,\ldots, n,1)$ is an example with $C(\rho_n) = 2^{n-1}$. If this is the worst case, as it is for the first few $n$ (see the notes for OEIS sequence A192053), then $m(n) \approx (2/e)^{n}$. So the normalized min, like the normalized max, is 'exponentially bad'. The base case is easy. For the induction step, we need a lemma: Lemma: In any path from $(2,3,4, \ldots, n, 1)$ to $(1,2,3, \ldots, n)$, either the first move swaps positions $1$ and $n$, or the last move swaps positions $1$ and $n$. Proof Sketch: Suppose not. Consider the first move that involves the $n$'th position. Assume that it is the $i$'th move, $i\neq 1$ and $i \neq n$. This move must place the item $1$ in the $i$'th place. Now consider the next move that touches the item $1$. Assume this move is the $j$'th move. This move must swap $i$ and $j$, moving the item $1$ into the $j$'th place, with $i < j$. A similar argument says that the item $1$ can only subsequently be moved to the right. But the item $1$ needs to end up in the first place, a contradiction. $\square$Now, if the first move swaps the positions $1$ and $n$, the remaining moves must take the permutation $(1, 3,4,5, \ldots, n,2)$ to $(1,2,3,4, \ldots, n)$. If the remaining moves don't touch the first position, then this is the permutation $\rho_{n-1}$ in positions $2 \ldots n$, and we know by induction that there are $C(\rho_{n-1})=2^{n-2}$ paths that do this. An argument similar to the proof of the Lemma says that there is no path that touches the first position, as the item $1$ must then end up in the incorrect position.If the last move swaps the positions $1$ and $n$, the first $n-1$ moves must take the permutation $(2,3,4,\ldots, n,1)$ to the permutation $(n,2, 3,4, \ldots, n-1, 1)$. Again, if these moves don't touch the last position, then this is the permutation $\rho_{n-1}$, and by induction there are $C(\rho_{n-1})=2^{n-2}$ paths that do it. And again, if one of the first $n-1$ moves here touches the last position, the item $1$ can never end up in the correct place.Thus, $C(\rho_n) = 2C(\rho_{n-1}) = 2^{n-1}$.
_webapps.54692
I have a Google Apps Free with 2 domain:A is primary domain (3 users with many many mail, docs, calendars, etc...) B another domain (0 users)A company made me a very attractive confirmed offer to sell my A domain.Can i remove this domain (A) and use only B domain without losing free account?Or i need to upgrade to Business?Please let me know - it's very important and urgent.I need take a decision!
Google Apps Free to Business and Change primary domain
google;google apps;google apps email
null
_codereview.147660
My code shares some values with its neighbor. The names Instructions, Registers can be ignored in the comments; just see them as names. What's important is how they are shared, which can be seen in the calculations.What I want is to improve this code, because it looks awful and one can barely understand what's going on.hexShared = {80,3E,14}; //lwz r31, -0x0018(r20) //Merge Hex Values that are shared (Basically every other is shared with the next one except the Address) private static string mergeHex(string[] hexShared) { //[ ][ ][ ][ ] //[0 1][2 3] string s1 = hexShared[0]; //Instruction string s2 = hexShared[1]; //Register 1 string s3 = hexShared[2]; //Register 2 char c1 = s1[1]; //Instruction Shared with Register 1 char c2 = s2[0]; //Register 1 Shared with Instruction char c3 = s2[1]; //Register 1 Shared with Register 2 char c4 = s3[0]; //Register 2 Shared with Register 1 char c5 = s3[1]; //Register 2 string hex = AddHex(c1, c2); string hex2 = AddHex(c3, c4); hex = s1[0] + hex + hex2 + c5; return hex; }I will try explain with an example (though I barely get it myself).We have a Hexdecimal of 8 characters (that's the structure always).83340247Now we can split it up, the last 4 are the Address and it can be taken out.So what remains are Hexdecimals that share values.8334Now for example the code:lwz r0, 0x0000(r0)will translate to: 80000000So lwz == 8 here.lwz r1, 0x0000(r0) == 80200000So the first r1 equals 2 right?lwz r1, 0x0000(r1) == 80210000It all looks fine, everything is separated, the other r1 is simply 1.Now here is the dilemma, when they reach values higher than one Hexdecimal can represent.lwz r1, 0x0000(r31) == 803F0000lwz r31, 0x0000(r31) == 83FF0000So as you can see, when they increase size, they will Add into the place Left of their starting point.So r1 (which is 2) will become 3 when the second r31 becomes large enough so it needs to use that space.I suck at explaining but i hope this Examples helps a bit at least:) //Convert Hex in String to Integer public static int HexToInt(string Hex) { return int.Parse(Hex, NumberStyles.AllowHexSpecifier); }//Sum Two Hex Chars and return it as Hex String (1 character) public static string AddHex(char hex1, char hex2) { int i1 = HexToInt(hex1.ToString()); int i2 = HexToInt(hex2.ToString()); int sum = i1 + i2; return sum.ToString(X1); }
Composing CPU instructions by merging four short hex strings
c#
Assembly opcodes are not constructed with string manipulations. They are very carefully designed with bit positioning, so a simple add operation between two integers might not be the best way to describe it. So your mergeHex method that god-knows-what does with strings should become a method that might do some bit shifting, masks, ...I sampled the behavior of your mergeHex with two calls (which is not enough to know what it does for all your possible scenarios), but anyway I reached the following conclusion:The output is a 16bits (word) hex string.The first 8 bits are given by hexShared[0] | ((hexshared[1] & 0xF0) >> 4)The last 8 bits are given by ((hexshared[1] & 0x0F) << 4) | values[2]Turning this into an algorithm becomes now trivial, let me suggest an implementation with some simplifications:private static string ToWord(string[] hexTokens){ var values = hexTokens .Select(t => HexToInt(t)) .ToArray(); var result = values[0] << 8 | values[1] << 4 | values[2]; return result.ToString(X1);}
_webapps.76034
On Google Sheets, I enter my sales for the month in Column F. How can I get column F to Auto Sum so that the total always appears below the bottom entry?
Autosum entire column
google spreadsheets
null
_softwareengineering.106804
I just started using git, and because I tend to live in emacs, I want to use one of the emacs integration packages. Looking at this list, I see that there are a lot of packages available, but the blurbs for each of them don't explain very much about their capabilities, especially since I don't know git very well.Which git modes for emacs have you used, and what are the advantages and disadvantages of each?
What are the advantages and disadvantages of the various git modes available for emacs?
version control;git;comparison;emacs
I've tried to describe these changes in my article about Emacs/Git integration. There are following major modes: git-emacs is basic mode, that provides access to most of commands, but sometime not so handy in use. Egg - good mode, but not actively developed (imho). Magit - is most advanced comparing to other modes, and has modular architecture to extend it, so it possible to add different extensions, such as git-svn, etc. And it developed very actively with good community, documentation, etc. All other modes are mostly add-ons to existing modes, or implement only limited functionality, that often available in other modes (for example, gitsum's functionality is available in magit)
_webmaster.84709
I have an online application which has an internal feature that returns blocks of text. You can think of this page almost like a search-results page. Depending on the input variables, different combinations of text will be returned.In other words, this 'results' page is not necessarily unique text. Multiple different input variables, may return very similar text output, or repeated text output.Is it best just to tell Google to ignore this page entirely? How does one tell Google that this is a dynamic page that may or may not have loads of repeated content (of very similar content) on it?Loads of sites have internal Search. How do SEO's handle the pages for returned search results?
What are best practices for SEO on an internal results page
seo;search
It's against Google's guidelines to index automatically generated content, which they count search results as.Google Guidelines on Automatically generated contentDepending on on your set up, one the easiest ways to block Google from crawling your search results is blocking the URLs in robots.txt. Learn About Robots.txt with Interactive Examples
_datascience.12626
What is the difference between the test and training data sets.As per blogs and papers I studied what I understood is we will have 100 % data set then that is divided into 2 sets(test data set is 30% & reaming 70% is training data set).I want to know more points and use of differentiating the 100% data set to test and training data sets.
what is the difference between the training and testdata set?
machine learning;beginner
null
_cogsci.13333
Setting: Bathroom, you've just brushed your teeth, turned the water on to let the remainder drift into the drain. After a moment you know there is something that needs to happen(obviously turning off the sink) but instead you flick the light switch off, for no apparent reason. I realize it's an odd situation but it can be compared to other events where there are multiple options for action and 'accidentally' choose the one you don't mean to.Question Would this be regarded as cognitive dissonance or is there a better name for this type of action? Thank you.
Looking for a name of a theory or reason behind a seeming cognitive mistake or error
cognitive psychology
null
_codereview.58483
I have the following Ruby code that's designed to update item, price and stock data for items in a MSSQL database. It's running on a Ruby 1.8.6/Rails 1.2.3 installation, in its own controller (for now)What I'm looking for is ways to optimize performance. Right now each item takes about 0,2 seconds (200ms) to process. Edit: There may be 10,000+ items in the XML file, and 10,000,000+ items in the Items and Price SQL tables.I've been told thatcomposing my own SQL queries directly instead of using the models will be faster, since I'm doing quite a few lookups, how much performance would that lend me? and selecting many rows at once, doing processing, and inserting at once should be faster, instead of doing it one by one. (How would this be done in practice?) # counters for statistics count = 0 skips = 0 # load + parse XML file = File.read(XML_PATH) doc = REXML::Document.new file # loop through products in XML file doc.elements.each('products') { |product| itemid = product.attributes['id'].to_i itemprice = product.elements['price'].text.to_i item = Item.find_by_id(itemid) if item.nil? skips += 1 next end # update prices price = Price.find(:first, :conditions => { :item_id => itemid }) # create new price if price not found if price.nil? price = Price.new price.item_id = itemid end price.price = product.elements['price'].text.to_i price.save # find + update item stock data product.elements.each('stocks/location') { |location| item_stock_location_id = location.attributes['location_code'] item_stock_location = ItemStockLocationCount.find(:first, :conditions => { :item_stock_location_id => item_stock_location_id, :item_id => itemid.to_s }) if item_stock_location.nil? item_stock_location = ItemStockLocationCount.new item_stock_location.item_stock_location_id = item_stock_location_id item_stock_location.item_id = itemid end item_stock_location.stock_qty = location.elements['stock'].text.to_i item_stock_location.save } # update onsite_stock + offsite_stock item_stock_count_on_site = 0 item_stock_count_off_site = 0 item_stock_loc_qtys = ItemStockLocationQuantity.find_all({ :item_id => itemid.to_s }) item_stock_loc_qtys.each { |stock_loc_qty| item_stock_count_on_site += stock_loc_qty.stock_qty item_stock_count_off_site += stock_loc_qty.stock_qty unless stock_loc_qty.item_stock_location_id == 1 } item.onsite_stock = item_stock_count_on_site item.offsite_stock = item_stock_count_off_site # update price lock item.price_lock = product.elements['price_locked'] if item.price_lock == 1 item.vat_price = product.elements['price'] item.price = (itemprice - ((itemprice * 25)/ (100 + 25))) end item.save count += 1 # progress bar if count%100 == 0 printf '.' end } puts 'Item Count: ' + count.to_s puts 'Items skipped: ' + skips.to_s
Optimize mass import of XML to SQLServer in Ruby
ruby;sql server
null
_unix.346770
How can I safely access my web services and accounts in a computer in which I do have sudo rights but the administrator(s) have, naturally, remote root access as well?DetailsI use a dekstop which is connected to a (large) closed/restricted LAN. Even log-in to the system is only successful if connected to the LAN.The administrator has, of course, remote root access (which I will suggest to change and opt for a password-less ssh-key based authentication). As well, my userid is assigned to the sudoers group, ie, in the /etc/sudoers file, there is:userid ALL=(ALL) NOPASSWD: ALLI am hesitant to use my passwords for accessing my webmail client and my firefox account. And more.QuestionsWhat can I do to ensure that my passwords, to access external web services, are protected from anyone else than me?For example, since I do have sudo rights, how can I ensure that no key loggers are running?I access password-less-ly based on SSH key(s) various services. How can I protect my passphrase from being logged?Would 2FA be safe to access external services in such a use-case?Is there a collection of Safe practices using a Linux-based computer which others can access remotely as root?
How can I protect my user passwords and passphrase from root
security;root;privacy
You can't.The root user has full access to the machine. This includes the possibility of running keyloggers, reading any file, causing the programs you run to do things without showing them in the user interface... Whether this is likely to happen depends on your environment so we can't tell you that. Even 2FA isn't safe because of the possibility of session hijacking.In general, if you suspect a machine isn't safe, you shouldn't use it to access your services.
_cogsci.13071
I'm trying to find research on the role of interactions between caregiver and infant via shared gaze/joint attention for the development of executive abilities, including attention and inhibition. My assumption is that joint attention serves as an externally guided precursors of later self-generated executive abilities as might be postulated based on Vygotsky. References or comments would be most welcome
Role of shared gaze/joint attention in infants for the development of executive function
cognitive psychology;developmental psychology;cognitive development
null
_cstheory.9999
We are so used to von neumann architecture and say a register machine like the x86. (Also with programming languages built for those machines x86 assembly, C, etc) Is that approach to computing completely separate from a language and system like haskell?What would a machine look like that was based functional programming paradigms look like? and one not running on a register or stack machine.This article is relevant to my question:http://www.stanford.edu/class/cs242/readings/backus.pdf
Are register based machines on von neumann architecture diametrically opposed to functional programming style?
pl.programming languages;big picture
Many hardware designs for executing functional programs have been proposed:The Lisp MachineSteele and Sussman's Scheme chip designThe Reduceron, by Naylor and Runcimanand more (lots are cited in the Reduceron papers).
_unix.272442
I'm trying to connect a to guest machine (protostar) through ssh from my host PC (Linux Mint). I'm using VirtualBox.I tried:setting up hostonlyadapters. setting up NAT Networking. portforwarding(from confing)arp-scanme@pc ~ $ ifconfigeth0 Link encap:ethernet hardware-address YY:YY:YY:YY:YY:YY UP BROADCAST MULTICAST MTU:1500 metric:1 RX-packet:0 error:0 loss:0 overrun:0 frame:0 TX-packet:0 errro:0 loss:0 overrun:0 carrier:0 Collisions:0 :1000 RX-byte:0 (0.0 B) tx-byte:0 (0.0 B) interrupt:20 memory:f7300000-f7320000lo Link encap:local loopback inet-address:127.0.0.1 mask:255.0.0.0 UP LOOPBACK RUNNING MTU:65536 metric:1tun0 for VPNwlan0 Link encap:Ethernet Hardware-address XX:XX:XX:XX:XX:XX inet-address:192.168.11.X broadcast:192.168.11.255 masc:255.255.255.0 UP BROADCAST RUNNING MULTICAST MTU:1500 metric:1 RX-packet:764076 error:0 loss:0 overrun:0 frame:0 TX-packet:729687 error:0 loss:0 overrun:0 carrier:0 (Collisions):0 TX:1000 RX:895582674 (895.5 MB) TX-byte:4283r48742 (428.3 MB)anyone help?
I cannnot connect to guest os(protostar) through ssh from host-pc (linux mint)
ssh;networking;virtualbox
null
_unix.88345
i Follow tutorial from https://wiki.archlinux.org/index.php/Courier_MTAbased on systemctl status command, the server is working fine# systemctl status couriercourier.service - Courier Daemon Loaded: loaded (/usr/lib/systemd/system/courier.service; disabled) Active: active (running) since Tue 2013-08-27 15:40:16 WIT; 35s ago Process: 509 ExecStop=/usr/sbin/courier stop (code=exited, status=0/SUCCESS) Process: 511 ExecStart=/usr/sbin/courier start (code=exited, status=0/SUCCESS) Main PID: 516 (courierd) CGroup: name=systemd:/system/courier.service 516 /usr/lib/courier/courierd 517 /usr/lib/courier/courierd 518 ./courieruucp 519 ./courierlocal 520 ./courierfax 521 ./courieresmtp 522 ./courierdsnAug 27 15:40:16 gravity courierd[517]: Started ./courieruucp, pid=518, maxdels=4, maxhost=4, maxrcpt=16Aug 27 15:40:16 gravity courierd[517]: Started ./courierlocal, pid=519, maxdels=10, maxhost=4, maxrcpt=1Aug 27 15:40:16 gravity courierd[517]: Started ./courierfax, pid=520, maxdels=1, maxhost=1, maxrcpt=1Aug 27 15:40:16 gravity courierd[517]: Started ./courieresmtp, pid=521, maxdels=40, maxhost=4, maxrcpt=100Aug 27 15:40:16 gravity courierd[517]: Started ./courierdsn, pid=522, maxdels=4, maxhost=1, maxrcpt=1Aug 27 15:40:16 gravity courierd[517]: queuelo=200, queuehi=400Aug 27 15:40:16 gravity courierd[517]: Purging /var/spool/courier/msgqAug 27 15:40:16 gravity courierd[517]: Purging /var/spool/courier/msgsAug 27 15:40:16 gravity courierd[517]: Waiting. shutdown time=Tue Aug 27 16:40:16 2013, wakeup time=Tue Aug 27 15:50:44 2013, queuedeliverin...rogress=0Aug 27 15:40:16 gravity courieruucp[518]: ERROR: no uucp user found, outbound UUCP is DISABLED!but the server was not listening at all$ sudo netstat -ant | grep :25$ sudo netstat -ant | grep :143the start configuration# grep START= /etc/courier/*/etc/courier/esmtpd:ESMTPDSTART=YES/etc/courier/esmtpd-msa:ESMTPDSTART=YES/etc/courier/esmtpd-ssl:ESMTPDSSLSTART=NO/etc/courier/imapd:IMAPDSTART=YES/etc/courier/imapd-ssl:IMAPDSSLSTART=NO/etc/courier/pop3d:POP3DSTART=YES/etc/courier/pop3d-ssl:POP3DSSLSTART=NOthe log:Aug 27 15:40:16 gravity courierd: Loading STATIC transport module libraries.Aug 27 15:40:16 gravity courierd: Courier 0.71 Copyright 1999-2012 Double Precision, Inc.Aug 27 15:40:16 gravity courierd: Installing [0/0]Aug 27 15:40:16 gravity courierd: Installing uucpAug 27 15:40:16 gravity courierd: Installed: module.uucp - Courier 0.71 Copyright 1999-2012 Double Precision, Inc.Aug 27 15:40:16 gravity courierd: Installing localAug 27 15:40:16 gravity courierd: Installed: module.local - Courier 0.71 Copyright 1999-2012 Double Precision, Inc.Aug 27 15:40:16 gravity courierd: Installing faxAug 27 15:40:16 gravity courierd: Installed: module.fax - Courier 0.71 Copyright 1999-2012 Double Precision, Inc.Aug 27 15:40:16 gravity courierd: Installing esmtpAug 27 15:40:16 gravity courierd: Installed: module.esmtp - Courier 0.71 Copyright 1999-2012 Double Precision, Inc.Aug 27 15:40:16 gravity courierd: Installing dsnAug 27 15:40:16 gravity courierd: Installed: module.dsn - Courier 0.71 Copyright 1999-2012 Double Precision, Inc.Aug 27 15:40:16 gravity courierd: Initializing uucpAug 27 15:40:16 gravity courierd: Initializing localAug 27 15:40:16 gravity courierd: Initializing faxAug 27 15:40:16 gravity courierd: Initializing esmtpAug 27 15:40:16 gravity courierd: Initializing dsnAug 27 15:40:16 gravity courierd: Started ./courieruucp, pid=518, maxdels=4, maxhost=4, maxrcpt=16Aug 27 15:40:16 gravity courierd: Started ./courierlocal, pid=519, maxdels=10, maxhost=4, maxrcpt=1Aug 27 15:40:16 gravity courierd: Started ./courierfax, pid=520, maxdels=1, maxhost=1, maxrcpt=1Aug 27 15:40:16 gravity courierd: Started ./courieresmtp, pid=521, maxdels=40, maxhost=4, maxrcpt=100Aug 27 15:40:16 gravity courierd: Started ./courierdsn, pid=522, maxdels=4, maxhost=1, maxrcpt=1Aug 27 15:40:16 gravity courierd: queuelo=200, queuehi=400Aug 27 15:40:16 gravity courierd: Purging /var/spool/courier/msgqAug 27 15:40:16 gravity courierd: Purging /var/spool/courier/msgsAug 27 15:40:16 gravity courierd: Waiting. shutdown time=Tue Aug 27 16:40:16 2013, wakeup time=Tue Aug 27 15:50:44 2013, queuedelivering=1, inprogress=0Aug 27 15:40:16 gravity courieruucp: ERROR: no uucp user found, outbound UUCP is DISABLED!how to increase debugging information?
Courier-MTA not listening, how to increase debugging information?
networking;arch linux;email;courier
null
_codereview.94677
I was looking for questions that might be asked in a technical interview and I found this one:Write a function that determines if two integers are equal without using any comparative operators.I'm using Java and my solution was to wrap the ints in an Integer object, convert that Integer to a string and return:(firstInt.toString()).equals(secondInt.toString()).I have 2 questions:Is there a better Java answer to this question? Does this response fulfill the requirements and if so, is it a good one?public class Main{ public static void main(String[] args){ log(equal(1,2)); //prints out false log(equal(67,67)); //print out true log(equal(-5,-5)); //prints out true log(equal(-9,-4)); //prints out false; } public static boolean equal(int a, int b){ Integer first = a; Integer sec = b; return (first.toString()).equals(sec.toString()); } public static void log(Object o){ System.out.println(o); } }
Comparing 2 ints without using comparative operators
java;interview questions
I find it highly unlikely that the interview question is designed to be answered in Java. It is more than likely referring to languages that can evaluate non-boolean value types as boolean expressions. A possible solution in JavaScript could be:function equal(a, b) { return !(a - b); // returns true only if (a - b) === 0}Is there a better Java answer to this question?You can simplify your method by calling toString on the Integer class and passing in the integer you wish to convert.public static boolean equal(int a, int b){ return Integer.toString(a).equals(Integer.toString(b));}Not that this is a better solution: a == b would be favored in any scenario.Does this response fulfill the requirements and if so, is it a good one?String.equals is doing a series of comparisons to verify the sequence of characters in your converted integers match; arguably this does not fulfill the requirements, but simply obfuscates it through an internal method call.