id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_cstheory.4732 | This CodeGolf answer suggests that quick sorting an array whose elements can take only two values is linear. Can this assumption be proved? | Is qsort linear when sorting only two values? | ds.algorithms;time complexity;sorting | There is a large body of research on Quicksort for sorting multisets.The talk Quicksort is optimal by Sedgewick gives a nice overview of this.Basically with 3-way partitioning you get within a constant of the information theoretic minimum. The information theoretic minimum is: Suppose we are to sort $n$ keys, where there is only $m$ distinct keys, and the $i$th key occurs $n_i$ times. Then we need $n \lg(n) - \sum_{i=1}^m n_i\lg n_i -n \lg e +O(\lg n)$ three way comparisons on the average. (See Sorting multisets and vectors in-place, by Munro and Raman). |
_vi.454 | It's pretty common when programming or opening text files to encounter files with trailing whitespace at the end of a line. vim has a way to show this by setting the trail option in the listchars option and then turning list on.However, what's the easiest way to eliminate that trailing whitespace globally across the whole of a file (ideally without a plugin)? | What's the simplest way to strip trailing whitespace from all lines in a file? | whitespace;line breaks | Use a keybinding to strip all trailing whitespaceSince some pages that I edit actually need trailing whitespaces (e.g. markdown) and others don't, I set up a keybinding to F5 so that it's trivial to do without being automatic. To do so, add the code below (from vim.wikia) or some variation of it to your .vimrc:Remove all trailing whitespace by pressing F5nnoremap <F5> :let _s=@/<Bar>:%s/\s\+$//e<Bar>:let @/=_s<Bar><CR>nnoremap <F5> does a nonrecursive mapping to the key F5 in normal mode :let _s=@/ stores the last search term (from the macro @/) in the variable _s<Bar> Functions as a pipe symbol | to separate commands, however | would end a command in this context, so <Bar> must be used instead.:%s/\s\+$//e searches for trailing whitespace and deletes it everywhere in the buffer (see CarpetSmoker's answer for a detailed breakdown of this expression)let @/=_s restores your last search term to the macro @/, so that it will be available the next time you hit n.<CR> ends the mapping... or be more selectiveIf you have cases in which you don't want to strip all of the trailing whitespace, you can use a pattern to be more selective. For example, the following code shows how I strip trailing whitespace only if it comes after a semicolon (here it's tied to F8).nnoremap <F8> :let _s=@/<Bar>:%s/;\s\+$/;/e<Bar>:let @/=_s<Bar><CR>This is useful if, like me, you have some files with markdown-like heredocs interspersed among semicolon-terminated programming statements. |
_unix.68700 | I am getting an error when I run Python programs that imports peewee:ImportError: No module named peeweeThe same program works fine under Ubuntu 12.04. I used pip to install peewee, and it confirms that it is installed:$ pip install --upgrade peeweeRequirement already up-to-date: peewee in /usr/local/lib/python2.7/site-packagesCleaning up...Any ideas? | Can't use peewee on Mac OS X Mountain Lion | osx;python;pip | The peewee module appears to be installed under /usr/local, but the OS X system default python lives in /usr/bin. Check the shebang line of the program that's failing, and make sure it's using the correct python. |
_webapps.24816 | There must be an easier way to do this than re-upping hundreds of photos all over again? I have tried everything I can find in Facebook apps and an iOS app called Facebook Photo Importer which looks the part but crashes every 2 mins! | How to export or share Google+ photos with Facebook? | facebook;google plus | null |
_softwareengineering.193647 | In an Agile development process usually the main focus is on User stories, but sometimes a single requirement may span several user stories.For example, the client may request a search page for all users in a forum, and there are several actions that can occur on each user such as ban user, delete user, reset Password, etc.We may divide this feature into at least 4 user stories: Search for usersBan userDelete userReset passwordHow would the user interface designer implement such a user interface? Should he/she work on the first user story and then start incrementing more features to the UI? However, I think the final UI will be messed up!If he decides to work on the whole feature (search + actions), what if the actions where of low priority and would be implemented several iterations after the search functionality was done? | How to deal with user interface design and respective feature support in Agile development? | web development;agile;user interface;user story;user experience | Take it iteratively. You're working directly with the users, right? So it should never really be a mess.First do the search page. You and the users should keep in mind that they'll want to be able to do actions on the results. Do the users like it? OK, you've got your search.Now add the Change Password (or whatever is next in priority). Oops, we need to change the search page a little--well, change is often part of the game. Do the users like it like the results? Good.Now add the next item, and the next...The agile approach says you always have feedback right away, so you should be good.That said, there's no real reason why you might not be able to attack 2 of these stories in the same iteration (adding delete user AND ban user). The key is to always be working with the customer to make sure it's right. You're often (always?) going to end up with users thinking of something else they want to do from that search screen after your original design is done and implemented. So, you'll end up modifying it at some point anyway. Just approach the whole thing with that expectation and you should be good. |
_unix.101711 | I'm trying to run pyopencl with the open source radeon drivers on gentoo. The package compiles fine, but every time I try to import the pyopencl module, I get an error telling me that the clGetExtensionFunctionAddress symbol cannot be found in _cl.so (and the libraries this is linked to). This function is indeed defined in the header files installed by mesa (cl.h), yet it seems to be missing from the actual library.OpenCL itself seens to be working, it's just pyopencl that refuses to load. Since I need pyopencl for my current project, for the moment I'm using fglrx, but I'd really prefer to use pyopencl with the open source driver which imho performs much better for everyday work.I was trying to use mesa 9.2.2 and pyopencl 2013.2. To sum it up: How can I get pyopencl running with the open source radeon drivers? | PyOpenCL and Mesa Radeon driver | gentoo;radeon | null |
_softwareengineering.182159 | I am stuck with a very old large website which I need to do some modifications. I can't use or integrate a new MVC framework due to current site is outdated with some custom coding done long time ago. I am writing custom reflection class for the user table in the database, but I find it easy to work on the model creating when the parameter passed or primary key and populated the member variables , then use them in the code. for example $user= new User($user_id);and then if I need the age I can use if($user->age > 18)To do this you might say it's easy just create a constructor method and do a select and assign them to the member variables .. however tricky part is I want to Even the database table design is changed I want them to be reflected in the coding without altering the code, ie. if we add a new field to the database table I want it to be called using $user->new_field; without touching the code. (I know Yii can do this but I can't use Yii as I have to write all functionality of the website if I have to move to a framework)if possible assign them to the member variables with the data type i.e Strings, Int etc reading them from the database How to build a model base on above (actually constructor method)? | php - auto populate the model member variable from database table | design;php | null |
_vi.2116 | In scripts it is customary to do something like:let s:save_cpo = &cposet cpo&vim... script ...let &cpo = s:save_cpoTo ensure nocompatible mode for the script.Is:set cpo&vimsome sort of special syntax, as in foo & bar? Or is it more like a command, trigger line or something else? | Is cpo&vim a special syntax? | vimscript | Yes, it's a special syntax to reset options to the Vim defaults. From :help :set-&vim::se[t] {option}& Reset option to its default value. May depend on the current value of 'compatible'. {not in Vi}:se[t] {option}&vi Reset option to its Vi default value. {not in Vi}:se[t] {option}&vim Reset option to its Vim default value. {not in Vi}:se[t] all& Set all options, except terminal options, to their default value. The values of 'term', 'lines' and 'columns' are not changed. {not in Vi}I found it by just typing :help &vim (which also goes to :help :set-&vim) :-) |
_cstheory.7992 | Branch and bound is an effective heuristic for search problems, and Wikipedia lists a number of hard problems where branch-and-bound has been used. However, I haven't been able to find references to suggest that it's more than just one method for solving these problems. Anecdotally, I've heard that some of the best heuristics for SAT and integer programming come from branch and bound, so my question is:Can someone point me to any references detailing effective uses of branch and bound for NP-hard problems ? | Successful application of branch-and-bound methods for NP-hard problems | ds.algorithms;reference request;optimization;heuristics | For TSP, checkout this book...http://www.tsp.gatech.edu/book/index.htmlMy understanding is that there is no one tool to kill them all. Arguably any recursive solution deploying backtracking and some scoring function is using branch and bound. As such, a large fraction of solvers to NP hard problems use some form of branch and bound. |
_webmaster.52583 | I have some PDF documents that I offer users once they have subscribed to my newsletter. Well, Google found them, and other people are posting them on various sites.I'd like to take advantage of Google ranking my PDF documents and redirect users that click on those links to an html or php page.How do you automatically redirect hotlinked PDF clicks (on Google search and other sites) to a relevant page (i.e. domain.com/PDFdoc1.pdf redirects to domain.com/PDFdoc1.html or domain.com/PDFdoc1/)?I want to keep the PDFs ranked where they are on Google, and keep the PDF documents exactly where they are on my site, but just redirect hotlinked clickers to a page instead of the PDF.How can this be done? | How do you stop PDF hotlinking and automatically redirect hotlink clickers? | redirects | null |
_softwareengineering.147445 | Google is well known for the ridiculous amount of C++ they've coded over the years. Correct me if I'm wrong, but a large part of Google's core search engine is written in C++, isn't it? How does one take a program written in C++ and interface it with a website?Note: I'm not looking for how Google in particular does this, just how it might be done in general. | How does one interface C++ with the web (at Google, for example)? | web development;c++;web applications | Any web software will only send and receive messages through sockets, that's all. You could use any language to do this, it's not specific to languages.However, you'd better not reinvent the wheel for this kind of work so most languages that are used to do web applications have their set of framework that does the basic communication for you, to allow you to concentrate on the specificities of your project. Ruby have ROR, Python have Django and others, Java as ...etc.C++ historically didn't have any similar framework until recently: a modern-C++ way of doing it is to use something like CPPCMS;there is also an effort to setup a standard library for web dev. in C++, one of them being cpp-netlib;Recently there have been a release of a cross-platform REST API library for C++11 from Microsoft called Casablanca which also helps;Now, the ridiculous amount of C++ that Google is built over is necessary because you need to have very-high-performance modules to solve the kind of problems Google solves. Good luck trying to do the same without any module written in a language focused on performance. I recommend reading the CPPCMS wiki about this subject to understand better. For historic facts, Amazon, Google, Facebook (see Hip Hop and recent Alexandrescu interviews) and some other really big web services do have cores in C++, for obvious computational reasons that are more important than the time lost on programmer productivity.CPPCMS and cpp-netlib being open source, you can study them if you want to know how to make an application work as a web service using C++. That said, any application that can listen to ports and send data to port can potentially do this, it's all about protocoles (TCP/IP, HTTP, etc.), not code. |
_unix.228634 | I want to do a line count and get the number into a variable in a shell script.For eg. wc -l filename.datgives 221 filename.datI want to grep '221' into a variable, which I could use later.Can this be done in a single statement ? I don't want to copy the output of wc -l into another file and then grep. | line(records) Count and grep together in a one command on a dat file | shell;wc | You can pass the filename to the STDIN of wc to get only the number of lines :wc -l <filename.datTo save it as a variable :var=$(wc -l <filename.dat)Example :$ wc -l foo.txt 12 foo.txt$ wc -l <foo.txt 12$ var=$(wc -l <foo.txt)$ echo $var12Note that as Stphane Chazelas has pointed out, some wc variants might add spaces before and after the number of lines to get desired alignment. |
_webmaster.105217 | I've moved my WordPress site from HTTP to HTTPS almost a month ago. Here are the steps that I've taken:Replace all the internal links over the site like navigation etc. (HTTP links still there in content)Changed the protocol in Google Analytics.Add new property in Web Master Tools with the HTTPS protocol.Force HTTPS everywhere via .htaccess fileChange the site address in WordPress admin panelAfter all these, Google still keeps HTTP links in SERPs and whenever I Google https://example.com it goes:Did you mean http://example.comMoreover, when I Google site:example.com inurl:http it returns like 1450 results, and for site:example.com inurl:http://example.com it returns 130 results.In my opinion, something makes my site stuck in HTTP and does not let it be HTTPS.Is there anyone here with any suggestions? | HTTP links still in Google's SERPs after moving to HTTPS | google;https;serps;search results | null |
_softwareengineering.236630 | I have started building a charting library on top of d3js using javascript's inheritance. My goal is to develop reusable and fully customizable chart components. I read the article: Towards Reusable Charts. Then, I went through the source code of nvd3. NVD3 uses boiler plate code in each chart like: copying and pasting definitions for width, height, margin etc. BUT I would rather use inheritance to avoid such boiler plate code. I would like properties like: dimensions, axes and functions like zooming and event listeners to be reusable among all charts and customizable through any instance (object) of the chart.Here is what my current library looks like. (It only supports bubble chart for now.)var BaseChart = function(){ this.width = 200; this.height = 200;//and others like: margin/ chart title}//XYChart inherits from BaseChartvar XYChart = function(){ //It contains members for axes, axis groups, labels, ticks, domains and ranges //Example: One of the members it contains is this.yAxis this.yAxis = d3.svg.axis().scale(this.scaleY) .orient(left) .ticks(this.yTickCnt) .tickSize(-this.width);}//Extends XYChart and adds zoomingvar ZoomableXYChart = function(){ this.zoom = function(){ this.svg.selectAll(this.dataShape) .attr(transform, function(d, i) { var translate = that.calculateTranslation(d); return translate( + translate.x + , + translate.y + ); }); }}//Extends zoomable XY chart and adds support for drawing shapes on data pointsvar BubbleChart = function(){ this.dataShape = path; this.drawChart = function() { this.prepareChart();//Attaches zooming, draws axes etc. var that = this; this.svg.selectAll(that.dataShape) .data(that.data) .enter() .append(that.dataShape) .attr(transform, function(d) { return that.transformXYData(d); }) .attr(d, symbolGenerator().size(100).type(function(d) { return that.generateShape(d); })) .attr(fill, function(d) { return that.generateColor(d); }) .on(click, function(d) { that.onClickListener(this, d); }) }}I can create a chart in this way:var chart = new BubbleChart();chart.data = someData;chart.width = 900;chart.elementId = #myChart;chart.onClickListener = function(this,d){}chart.drawChart();This solution allows me to use common properties and functions across all charts. In addition to that, it allows any instance of any chart to override default properties and functions (like: onClickListener).Do you see any limitations with such a solution? I haven't really seen javascript's inheritance used for d3.js and I wonder why? Is chaining that important? Using Mike Bostock's suggestions, how can we share functions like zooming across all XY charts? Isn't inheritance absolutely necessary to share functions and properties? | Reusable and customizable charting library on top of d3js | javascript;libraries;inheritance;code reuse | null |
_codereview.142148 | I'm writing a simple database class so I could use it in my future projects. It is based on some Codeigniter database methods, but my implementation, so if you could review this, that would be cool. It is not finished yet, but I want to remove all bad code early on.<?phpclass Database { private static $instance = null; private $pdo; private $query; private $results; private $count = 0; private $error = false; private $query_string = ; private $bindValues = array(); private $lastId; private function __construct() { try { // Put your database information $this->pdo = new PDO(mysql:host=127.0.0.1;dbname=login,root,); } catch (PDOException $e) { die($e->getMessage()); } } public static function getInstance() { if (is_null(self::$instance)) { self::$instance = new Database(); } return self::$instance; } public function query($sql, $parameters = array()) { $this->error = false; if ($this->query = $this->pdo->prepare($sql)) { $i = 1; foreach ($parameters as $param) { $this->query->bindValue($i, $param); $i++; } if ($this->query->execute()) { // You can PDO::FETCH_OBJ instad of assoc, or whatever you like $this->results = $this->query->fetchAll(PDO::FETCH_ASSOC); $this->count = $this->query->rowCount(); $this->lastId = $this->query->lastInsertId(); } else { $this->error = true; } } return $this; } public function select($fields = *) { $action = ; $this->query_string = ; if (is_array($fields)) { $action = SELECT ; for ($i = 0; $i < count($fields); $i++) { $action .= $fields[$i]; if ($i != count($fields) - 1) $action .= ', '; } } else { $action = SELECT * ; } $this->query_string .= $action; return $this; } public function from($table) { $this->query_string .= FROM {$table} ; return $this; } public function where($where = array()) { $keys = array_keys($where); $action = WHERE ; for ($i = 0; $i < count($keys); $i++) { $action .= $keys[$i] . ' = ?'; if ($i < count($keys) - 1) $action .= ' AND '; $this->bindValues[] = $where[$keys[$i]]; } $this->query_string .= $action; return $this; } public function execute() { if (!empty($this->query_string)) $this->query($this->query_string, $this->bindValues); $this->bindValues = array(); } public function getQueryString() { return $this->query_string; } public function results() { return $this->results; } public function first() { return $this->results[0]; } public function last() { return $this->results[$this->count-1]; } public function row($id) { return $this->results[$id]; } public function error() { return $this->error(); } public function count() { return $this->count; } public function lastId() { return $this->lastId; }} | Simple PDO database class in PHP | php;object oriented;database;pdo | null |
_softwareengineering.117064 | I was wondering what is the reason behind pagination? Is it used because it lessens the burden on the servers since we would technically limit the amount of rows returned per page?I wanted to do something without pagination but given that I am new to this (I am an amateur) started wondering if its OK technically or not. | Does having pagination lessens server load? (theory) | php;pagination | null |
_unix.277444 | I'm trying to perform the same process on all subdirectories. This should exclude the current directory, but I'm still matching on that and I don't know why.# Make a dummy file tree to test withmkdir d d/d{1..3}find ./d -type d -exec bash -c echo '{}' \;d/d/d1d/d2d/d3 | How to ignore passed directory in find command directory search? | find | Well it is a directory and (-type d) so it gets printed. You can try to set the minimum depthfind ./d -mindepth 1 -type d |
_unix.304275 | I'm using ubuntu 14.04 and did a apt-get install phpmyadmin I went through the install process and forgot to check off an option to install it for apache2. The install didn't finish, but it must have edited something on my system and I can't seem to start mysqld anymore. root@drupalpro:/var/log/mysql# service mysql start * Starting MariaDB database server mysqld [fail] root@drupalpro:/var/log/mysql# service mysql status * MariaDB is stopped.root@drupalpro:/var/log/mysql# When starting mysqld it just says starting and then hits me back to the prompt. And mysql isn't started at all. How would one fix something like this? This is crazy that just because I forgot to check off a checkbox it just screwed up my entire system. | Screwed up installing phpmyadmin and now mysql / mariadb won't start | mysql;phpmyadmin | null |
_webmaster.28824 | I want to make a 301 redirect to a different page on a different domain. The page is on the same topic, but is different content.Also, the traffic to the original page comes from the alt text on an image. I'm sure that the alt text is different on the same image from the other page.Is this wise to do and will it last? Or, should 301 redirects only be done when it's the exact same content? Thank you. | 301 redirect to different page on different domain? | redirects;indexing;301 redirect | I didn't understand your second sentence.It's perfectly fine to use 301 redirect even if the content of the page is different, redirecting to another domain is called domain redirection or domain forwarding.What you want to avoid is using 302 redirect which means moved temporarily.You might be interested in reading more about 301 redirect, I recommend going over this and this. |
_webmaster.106230 | There are a lot of schemas out there. Which should I use for my website SEO? Which are useless or may even be harmful? I will explain my question by the description tag:Schema.org: This is Google's first choice when it comes to SEO so I guess I SHOULD use it (either as JSON-LD or with Microdata).<meta itemprop=description content=fdsa />Open Graph: Also mandatory as the number one choice by social media websites.<meta property=og:description content=fdsa />Dublin Core: May be useful? Is also used e.g. by geolocation services.<meta name=DC.Description content=fdsa>Standard Meta: <meta name=description lang=de-DE content=fdsa />Lets assume that the user may enter a different og:description, however the other descriptions would be usually the same. Anyway I may add useful additional information through each schema so my first guess it would be o.k. to use each of those?However I read somewhere that duplicate metadata is considered harmful for SEO. So my question is: Is it o.k. or is it better to stick with one or two? | Website metadata SEO: Schema.org, Open Graph, Dublin Core and standard meta vs. duplicate meta? | seo;duplicate content;schema.org;meta tags | I read somewhere that duplicate metadata is considered harmful for SEOThis is nonsense. I don't suppose the article you read referenced an authoritative source for this? I recommend treating with caution any pronouncements of absolute SEO knowledge that aren't either from a search engine or supported by high quality research.Anyway, you've largely answered your own question. Schema.org is a collaboration between major search engines, including Google, Bing and Yandex. From an SEO point of view, this is the important one.Likewise, Open Graph (and Twitter Cards) have demonstrable benefits for social. Standard, valid HTML metadata are supported to varying degrees by different search engines. No harm using any that serve a clear purpose, even if some search engines will ignore them.Dublin Core, to the best of my knowledge, was never widely supported and so offers little advantage. That said, there's no harm using it if you want to. |
_unix.226772 | I tried to upgrade(in-place) CentOS 6.7 to CentOS 7.0 on the various environments.I installed CentOS-6.7-x86_64-bin-DVD1.iso on VWware 11.0.And I followed the https://wiki.centos.org/TipsAndTricks/CentOSUpgradeTool.When I run the preupg, I got the following results.We found some potential in-place upgrade risks.And then I continued to work the upgrading.But after completeing the upgrade I can't start due to kernel panic or login to system.Please tell me the reason.I expected that the minimal system of CentOS 6.7 will be upgrading successfully and I installed CentOS-6.7-x86_64-minimal.iso and tried to upgrade, but I failed.My questions:The command preupg and redhat-upgrade-tool are not yet completed?The upgrading on CentOS is not recommended? If so, Why?The upgrading on RHEL 6.7 is woring well?(I have no RHEL 6.7) | Upgrading CentOS 6.7 to CentOS 7 on VMWare 11.0 | centos;upgrade;x86 | null |
_webapps.31807 | There is a Git repository that I want to be notified about. Any notificatioin would be fine: RSS would be the best, but Twitter or similar notifications are acceptable too. Unfortunately, the page is not understood by Twitterfeed:Your feed might be empty or missing publish dates or GUIDsIs there another service that understands Git history and pushes a notification when a new commit is made?Actually this open source project has most of the code that would be needed to create such a service. | Watch a Git repository on Google Code? (RSS/Twitter/...) | google code | To answer to the question the feed is here.As a bonus note: Firefox removed the RSS button over a year ago because allegedly only 3% of users used it. You can still check if a page has an RSS by going Bookmarks Subscribe to this page or by right clicking on the tool bar, selecting Customise and dragging the icon back to its rightful place. |
_unix.190238 | I have divided my ssd into two partitions, one for the root and one for the home directories. Unfortunately I have provided too few space for the root directory and I would like to expand it, by shrinking the home directory.I have found the resize2fs that it can expand the partition while been in use but I don't have the expertise to complete all the steps without a guide. Can you provide me with some steps of what to do to shrink the Home partition and expand the root partition without having to format the complete disk? | Resizing home and root partions at opensuse | partition;opensuse;resize2fs | null |
_webmaster.9100 | I have a 16x16 PNG that I want to use for my favicon. It works fine in modern browsers, but I need a favicon.ico file for older ones. The problem is that either the ICO format doesn't support semi-transaprency, which my favicon uses, or the converters I've found online don't support it.Which is it? If the format supports it, how can I convert a PNG to an ICO with semi-transparency? | How can I make a good favicon? | favicon | Here's a website I found using photoshop and a website to do it.Here's another website I found that deals with the Windows ICO plugin for Photoshop - located here.Warning: I have NOT tested that file download for exclusion of viruses - download at your own risk. |
_cogsci.1448 | In their classic study, Ekman and Friesen (1971) identified seven facial expressions recognised by people universally across all cultures as depicting certain emotions: happiness, sadness, surprise, fear, anger, disgust and contempt. This is quite solid paradigm, but recent studies showed some cross cultural differences. For example Western Caucasian observers tend to look fairly evenly across all areas of the face, whereas Eastern Asian observers focus their attention toward the eye region (Jack et al., 2009). Ekman, P., & Friesen, W. V. (1971). Constants across cultures in the face and emotion. Journal of Personality and Social Psychology, 17(2), 124-129.Jack, R. E., Blais, C., Scheepers, C., Schyns, P. G., & Caldara, R. (2009). Cultural confusions show that facial expressions are not universal. Current biology, 19(18), 1543-8.While facial expression literature on the topic is vast, there is very limited research into cross cultural differences in perception of emotions from dynamic body expression. There have been some attempts to look at the static body posture (Kleinsmith et al., 2006), but virtually nothing on the dynamic body expressions. Ok, there is one study by Sneddon et al. (2011) but their stimuli contain facial expression together with movement, and I am specifically interested in the research where participants only view body movement/expression.Kleinsmith, A., De Silva, P. R., & Bianchi-Berthouze, N. (2006). Cross-cultural differences in recognizing affect from body posture. Interact. Comput., 18(6), 1371-1389.Elfenbein, H. (2003). Universals and Cultural Differences in Recognizing Emotions. Current Directions in Psychological, 159-164.Sneddon, I., McKeown, G., McRorie, M., & Vukicevic, T. (2011). Cross-cultural patterns in dynamic ratings of positive and negative natural emotional behaviour. PloS one, 6(2).Is there any (published) research that has been done on comparing cross cultural differences in the perception of emotions from body movement? | Do cultures differ in the perception of emotions from body expression? | cognitive psychology;emotion;cross cultural psychology | null |
_unix.202840 | I've opened a terminal session and started some processes with &. When I tried closing the terminal window, it warned me that there were still jobs running in the background.I can see the processes running with ps, but how can I know which ones were started through this session? | processes started in this session | bash;process | jobs -l Lists process IDs of the active jobs |
_softwareengineering.140125 | There are multiple ways of tracking code ownership (i.e., collective, team or individual).In case of team or individual ownership, how do you:track ownership?deal with situations when dev leaves or team splits/re-organizes for new projects? | Code ownership: What should I do when a dev leaves or team splits? | project management;team;knowledge transfer;code ownership | As a team leader, you should always plan for someone leaving / getting hit by a bus. People implement this in many ways: Pair programming / buddy testing and so on. Sole proprietorship in a corporate environment is detrimental to both the company and the developer. The developer can never be promoted because he is too important to move away from this, or worse, could be promoted too high, just to keep him around and will be the first one to be laid off in lean times. Its a lose lose scenario.Having said that, whenever teams split, I have seen serious knowledge transfer sessions / recorded presentations / documentation touch ups happen. |
_unix.367825 | I'm planning to set-up a server, running centos 7, that is connected to three networks with three eth ports. Those three networks belong to 10.0.0.0/8. I configured 10.0.0.0/8 into two eth ports (static route). The other one port is for the default route. I know that there would be a routing conflict between the two eth ports. Is there a possible solution to resolve this routing issue in such a way that I'm not going to breakdown the 10.0.0.0/8? | Same static route configuration on two different interface (Centos7) | routing | null |
_unix.113423 | I am attempting to connect a Huawei E3131B 3g modem using Linux. I use usb-modeswitch and pppd.First I mode-switch the modem using the command:usb_modeswitch -c /etc/usb_modeswitch.d/12d1:14fe -v 12d1 -p 14fe(12d1:14fe) is the address of the modem. This creates the /dev/ttyUSB0, 1 and 2 ports that can be used to communicate serially with the modem. Next, I run pppd with the following options:debugmodem/dev/ttyUSB0460800crtsctslock-detachnoipdefaultdefaultroutedumpnoauthconnect '/usr/sbin/chat -v -t 60 -f /etc/ppp/chat-isp':The connection script, chat-isp, looks as follows:ABORT 'BUSY'ABORT 'NO CARRIER''' ATIOK AT+CRSM=176,65507,0,0,17OK AT+CGDCONT=1,IP,internetOK ATQ0 V1 E1OK AT+CPIN=0000OK AT+COPS=0,2OK AT+FCLASS=0OK AT+S0=0OK AT&D2&C1OK ATD*99#CONNECT ogin:sword:I'm going to be honest and say some of those AT commands are there plainly to try to get this thing to work! Can someone please help by telling me what is wrong with the connection script and what order / what AT functions need to be used to set up the modem? | Connect Huawei E3131B 3g Modem | usb;angstrom;3g | null |
_vi.11236 | Is there a standard way to compare two strings in vim so that I can quickly determine which string is sorted before the other.Something likestrcmp(str1, str2) to return 0 if str1 == str2, 1 if str1 > str2 and -1 if str1 < str2 | How do I alphabetically compare two strings | vimscript;string manipulation | null |
_webapps.75084 | I'm lucky enough to live far away from literately everything, middle of freaking nowhere, and my land line doesn't work at the moment. So all I had for communication was my e-mail, in this case Gmail. Now Google have deactivated my account and I need a phone verification to reactivate it. Any chance of bypassing this? I don't have a phone for miles. | Can I verify my deactivated Google account without having a phone? | google account | null |
_softwareengineering.336988 | Polyglot Programs strikes me as pretty confusing and error prone. Right away I don't see any use to it besides showing-off. Wouldn't that be a bad programming pattern, since it's not modular?Is there something that can be implemented with it that's cleaner than designing software applications as suites of independently deployable modules/libraries/services? | When is a polyglot program something worth using/deploying? | design patterns | null |
_unix.211186 | If i do:ssh 192.168.1.8 //my wlan0 connectioni get:ssh: connect to host 192.168.1.8 port 22: Connection refusedHowever, if i plug the LAN, i can ssh to 192.168.1.7 (wired ip). And after that, i can ssh to 192.168.1.8 (wlan0 port) with no issues even after unplugging lan.What can it be?Drawing: | SSH: connection refused to wlan, works when i plug wired lan and unplug | ssh;wifi | null |
_datascience.6848 | (I've posted this question on CV, but I feel it would also be great to hear from experts in DS community.)As a PhD student starting to think about dissertation topics, I am particularly interested in high-dimensional statistical learning. I wish to find some research review/survey/papers (or webpages, blogs, whatever...) about the state-of-the-art research in this research area, but there seems limited resources I can obtain. My first question is then,Could you describe some current interesting research topics inhigh-dimensional statistics? If you can list any relevant resources(papers, webpages, etc.), that would be really helpful.In addition, I've noticed that high-dimensional statistical learning is closed related with machine learning research. For example, the idea of penalized regularization in high-dimensional statistics was used in machine learning domain, like support vector machine, boosting tree, (sparse) additive models, etc. My question is,what are good research papers about the interplay ofhigh-dimensional statistics and machine learning?Last, since high-dimensional statistics was really motivated by genetic research (like gene-expression analysis, or genome-wide association studies), most of applications in high-dimensional research are devoted in that area.Are there any successful applications of high-dimensional statisticsin areas other than genetics, particularly say, image/text mining,recommendation, etc, areas where machine learning techniques havelong been used?A new question to machine learning researchers/practitioners: I might be wrong, but as I understand, most machine learning algorithms are designed for low-dimensional problems (or at least the number of features is smaller that number of observations). Are there any successful applications of machine learning techniques for modeling high-dimensional data? Any resources/comments are highly appreciated. Thanks. | Research in high-dimensional statistics vs. machine learning? | machine learning;statistics | null |
_cs.74320 | How do I change the Bellman-Ford algorithm so replaces v.d to -inf for all vertices v for which there is a negative-weight cycle on some path from the source to v?I've been thinking about it, and don't think for each edge (u, v) in G.E if v.d > u.d + w(u, v) v.d = -infcuts it. Since we are in a cycle, do I simply recurse through it and change the other distances / parents? Help -- how do I do this? | Question about Bellman Ford modification algorithm | algorithms;graphs;weighted graphs | null |
_unix.13091 | I have a flash drive, let's name it FLASH.I want, when on my mac, when FLASH is plugged (and automatically mounted), execute a specific script and make ~/Documents to be automatically copied to /Volumes/FLASH/Documents (mac mounts drives at /Volumes).This same drive, FLASH, (with this new Documents folder added before with the mac situation), when plugged in an Ubuntu machine, I want it to automatically copy FLASH/Documents to ~/Documents (or automatically execute an script, after mounting).How should I do this in these different scenarios? I don't want to use third party applications for this, I prefer using core/builtin tools available in both platforms. | Sync files from a mac to a flash drive - automatically? | ubuntu;backup;rsync;macintosh | Use a launchd item using the StartOnMount key!# example launchd plist file using StartOnMount keyopen -e /System/Library/LaunchDaemons/com.apple.backupd-attach.plistFurther information: The macosxhints Forums: launchD StartOnMount helpMacEnterprise: Snow Leopard, launchd, and Lunch (Recipe 7: Run a script when a volume is mounted) |
_webmaster.61132 | I am using Magento for one of my site. In Magento there is a file mage (no extension file name is mage only) to block this file I write robots.txt as# FilesUser-agent: * Disallow: /mageBut this also block URLs start with mage like magenta-color-item.html.How I write in robot to block mage only not URL start with mage? | robots.txt blocking specific files also block unnecessary URLs | url;web crawlers;robots.txt;magento | You can add a dollar sign to the end of the string which means it will only match exactly that entry:# FilesUser-agent: * Disallow: /mage$This will only block the mage file if it come straight after the root domain:www.example.com/mageIf there are any other preceding directories, you must add these o the entry. So to block the file located below:www.example.com/somedirectory/mageYou would need to use:# Files User-agent: * Disallow: /somedirectory/mage$ |
_unix.311977 | As some may know, Firefox 49 now includes the Google Widevine CDM for Linux!!! This works perfectly for viewing some encrypted streams such as the ones here: http://demo.castlabs.com/, however when trying to watch the streams on Netflix or Amazon Video I run into trouble.With Netflix I am told to install the Silverlight plugin and with Amazon I just get an error which send me to the help page advising me to update Google Chrome.I assume I need to switch my user agent for this which I do know how to do, though I cannot find one which works. Has anyone found a user agent which will allow Netflix and/or Amazon Video to work? | How to Watch Netflix/Amazon Video on Firefox 49? | firefox | This one worked for me for Netflix:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36But it doesn't work for Amazon. On Amazon the window expands but no video player ever launches.(Mint 18, Firefox 49 from MintUpdate. I had to enable DRM content, of course.) |
_unix.384173 | I am using Linux Mint and tethering Internet through my phone.Every time I enable tethering, my DNS on computer is being set to 127.0.0.1 which results in being unable to resolve any name. I have to manually open network settings panel and change DNS to 8.8.8.8 (google's DNS). It works till next time I enable tethering (that is, multiple times per day).I have tried saving them in network connection panel for this particular connection, but it seems to be completely ignored.I have also tried to edit /etc/resolv.conf and even remove write permissions, but sooner or later it gets overwritten anyway.What is changing my DNS settings and how to make it stop? | Stop changing my DNS! | linux mint;dns | null |
_unix.290370 | For the past few days, my Debian install keeps randomly hanging every 5-30 minutes. The screen freezes. Sometimes GDM kicks me back to the login screen after a little while. Other times it just completely freezes. It started after I did a dist-upgrade for the first time in a few weeks, inc upgrading to Gnome 3.20.Here's what I found in the syslog, a similar set of messages appear each time:Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) [mi] EQ overflowing. Additional events will be discarded until existing events are processed.Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE)Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) Backtrace:Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 0: /usr/lib/xorg/Xorg (xorg_backtrace+0x4e) [0x55fd88968f6e]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 1: /usr/lib/xorg/Xorg (mieqEnqueue+0x253) [0x55fd8894aa33]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 2: /usr/lib/xorg/Xorg (QueuePointerEvents+0x52) [0x55fd88823632]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 3: /usr/lib/xorg/Xorg (xf86PostMotionEvent+0xd6) [0x55fd8885a956]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 4: /usr/lib/xorg/modules/input/synaptics_drv.so (0x7f0fbb634000+0x5f89) [0x7f0fbb639f$Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 5: /usr/lib/xorg/modules/input/synaptics_drv.so (0x7f0fbb634000+0x7532) [0x7f0fbb63b5$Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 6: /usr/lib/xorg/Xorg (0x55fd887b7000+0x940f8) [0x55fd8884b0f8]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 7: /usr/lib/xorg/Xorg (0x55fd887b7000+0xb9392) [0x55fd88870392]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 8: /lib/x86_64-linux-gnu/libc.so.6 (0x7f0fc3a6d000+0x334e0) [0x7f0fc3aa04e0]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 9: /lib/x86_64-linux-gnu/libc.so.6 (ioctl+0x5) [0x7f0fc3b4e4f5]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 10: /usr/lib/xorg/modules/drivers/intel_drv.so (0x7f0fbf3ef000+0x24f5d) [0x7f0fbf413f$Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 11: /usr/lib/xorg/modules/drivers/intel_drv.so (0x7f0fbf3ef000+0x28904) [0x7f0fbf4179$Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 12: /usr/lib/xorg/modules/drivers/intel_drv.so (0x7f0fbf3ef000+0x5c3ee) [0x7f0fbf44b3$Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 13: /usr/lib/xorg/Xorg (BlockHandler+0x4a) [0x55fd8880f5ba]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 14: /usr/lib/xorg/Xorg (WaitForSomething+0x163) [0x55fd88965c33]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 15: /usr/lib/xorg/Xorg (0x55fd887b7000+0x53a1e) [0x55fd8880aa1e]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 16: /usr/lib/xorg/Xorg (0x55fd887b7000+0x57c03) [0x55fd8880ec03]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 17: /lib/x86_64-linux-gnu/libc.so.6 (__libc_start_main+0xf0) [0x7f0fc3a8d5f0]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) 18: /usr/lib/xorg/Xorg (_start+0x29) [0x55fd887f8f99]Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE)Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) [mi] These backtraces from mieqEnqueue may point to a culprit higher up the stack.Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) [mi] mieq is *NOT* the cause. It is a victim.Jun 17 11:18:10 piglet kernel: [ 1087.627729] [drm] stuck on render ringJun 17 11:18:10 piglet kernel: [ 1087.634979] [drm] GPU HANG: ecode 8:0:0xfffffffe, in Xorg [1162], reason: Ring hung, action: resetJun 17 11:18:10 piglet kernel: [ 1087.634995] [drm] GPU hangs can indicate a bug anywhere in the entire gfx stack, including userspace.Jun 17 11:18:10 piglet kernel: [ 1087.635004] [drm] Please file a _new_ bug report on bugs.freedesktop.org against DRI -> DRM/IntelJun 17 11:18:10 piglet kernel: [ 1087.635012] [drm] drm/i915 developers can then reassign to the right component if it's not a kernel issue.Jun 17 11:18:10 piglet kernel: [ 1087.635019] [drm] The gpu crash dump is required to analyze gpu hangs, so please always attach it.Jun 17 11:18:10 piglet kernel: [ 1087.635029] [drm] GPU crash dump saved to /sys/class/drm/card0/errorJun 17 11:18:10 piglet kernel: [ 1087.641887] drm/i915: Resetting chip after gpu hangJun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: [mi] Increasing EQ size to 1024 to prevent dropped events.Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: [mi] EQ processing has resumed after 37 dropped events.Jun 17 11:18:10 piglet /usr/lib/gdm3/gdm-x-session[1160]: [mi] This may be caused by a misbehaving driver monopolizing the server's resources.Jun 17 11:18:13 piglet pulseaudio[916]: [pulseaudio] sink-input.c: Failed to create sink input: sink is suspended.Jun 17 11:18:18 piglet kernel: [ 1095.635999] [drm] stuck on render ringJun 17 11:18:18 piglet kernel: [ 1095.642984] [drm] GPU HANG: ecode 8:0:0xfffffffe, in Xorg [1162], reason: Ring hung, action: resetJun 17 11:18:18 piglet kernel: [ 1095.643414] [drm:i915_set_reset_status [i915]] *ERROR* gpu hanging too fast, banning!Jun 17 11:18:18 piglet kernel: [ 1095.646268] drm/i915: Resetting chip after gpu hangJun 17 11:18:18 piglet /usr/lib/gdm3/gdm-x-session[1160]: (EE) intel(0): Failed to submit rendering commands (Input/output error), disabling acceleration.My system is completely up to date, on Debian stretch.How can I try to stop this? Could I switch drivers from the Intel i915 driver? Or disable the DRM or some other element in the grub config? | Debian keeps hanging, may be graphics driver issue | debian;xorg;crash;i915 | null |
_unix.73459 | I have a virtual machine set up with a directory created with virtualenv (env2). I am inside this directory and have it activated and want to instal django 1.4. This is my command:$ pip install django==1.4But it returns saying that the hashes don't match. The thing is, they do match though. Anyone know my problem? | Django not installing with pip because of mismatched hash | python;django;pip | null |
_hardwarecs.2419 | Is there any WiFi USB adapter that works without any errors with the 802.11ac WiFi standard in the 2.4GHz and the 5GHz bands with USB 3.0?I have a WiFi adapter (TP-Link Archer T4U), but it gives me a lot of problems (One being that TP-Link does not provide a driver for Linux...). There are problems when I try to change/read the power transmission, when I try to get the bit rate, etc. So, I was wondering if there was a WiFi adapter that works with the 802.11ac standard and USB 3.0 that does not have so many problems and will work well. | Are there any 802.11ac usb 3.0 adapters working well in Ubuntu? | usb;wifi;wireless;network adapter | null |
_webapps.6513 | We would like to start accepting user contributed photos for our website and events in our area. Ideally we'd like to be able to say email [email protected] as well as a web interface where users can upload their photos, or perhaps share via facebook etc...We don't want the photos to be published right away of course, as we'll need to vet and choose the best ones. but we would like them to go directly into our photo account so we can easily publish them. we have both a smugmug account and a flickr account but haven't been able to determine if this can be done and where.If you have done this in the past please let us know what worked for you, thanks! | Site for accepting user photos (crowdsourcing) | webapp rec;photo sharing | null |
_webmaster.22511 | I am looking for theoretical resources (books, tutorials, etc.) to learn about making sound statistical inferences given (plenty of) multivariate website conversion data.I'm after the math involved, and cannot find any good non-marketing stuff on the web. The sort of questions I want to answer: how much impact does a single variable (e.g. color of text) have? what is the correlation between variables? what type of distribution is used for modelling (Gaussian, Binomial, etc.)? When using statistics to analyze results - what should be considered as a random variable - the web-page element that gets different variations or the binary conversion-or-no-conversion outcome of an impression?There's plenty of information about different website optimization testing methods and their benefits\pitfalls, plenty of information about multivariate statistics in general, do you guys know of resources that discuss statistics in this specific context of website optimization? | Math behind multivariate testing for website optimization | statistics;recommendations;books | null |
_codereview.151949 | Square free no: It is an integer which is divisible by no other perfect square than 1. For example, 10 is square-free but 18 is not, as 18 is divisible by 9 = 3^2.The smallest positive square-free numbers are 1, 2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29, 30, 31, 33, 34, 35, 37, 38, 39Is it possible to reduce the time execution for this code, without importing any Python module?What should I use in place of a for loop body containing an if condition? Will using a lambda function be helpful?def squarefree(n): for i in range (2, round(n**0.5)): if n % (i**2) == 0: return False return n | Square free number | python;python 3.x | ReviewPython has an official style-guide, PEP8. It recommends using white-space only where necessary (so the blank line after def squarefree(n): could go, as could the trailing space) and using four spaces as indentation.Normally I would consider it best practice for a function like this to return actually True or False. Your function returns False or a truthy value, which also works, but is not as clean. Consider changing it from return n to return True.Alternate implementationAs @Dair mentioned in the comments, depending on your use-case for this, it would be faster to write a sieve that gets all square-free numbers up to some limit.Starting with the Sieve of Eratosthenes, taken from another of my answers, this could be implemented like this:def squarefree(n): Check if n is a square-free number, i.e. is divisible by no other perfect square than 1. Args: n positive integer to check Returns: n if n is a square-free number False else for i in range(2, round(n**0.5)): if n % (i**2) == 0: return False return ndef square_free_sieve(limit): Generator that yields all square free numbers less than limit a = [True] * limit # Needed so we don't mark off multiples of 1^2 yield 1 a[0] = a[1] = False for i, is_square_free in enumerate(a): if is_square_free: yield i i2 = i * i # Start at 2 * i**2 to allow first square free number, like 9 for n in range(2 * i2, limit, i2): a[n] = Falsetest1 = [n for n in range(100) if squarefree(n)]test2 = list(square_free_sieve(100))assert test1 == test2When generating all square free numbers up to 100,000, your code needs about 3.5s, while the sieve only takes 0.05s, which is about 70 times faster. |
_webapps.70892 | I open the Facebook app on my phone and go to chat and it tells me one person was last active ten minutes ago and then all of a sudden it says last active one minute ago but I never see a green dot to say they were online. Why is this? It shows green dots for others but not this one person. It was happening throughout the night but then stopped at a certain time.I only ask this because I have an anxiety along with other things and it plays on me at times. I just wondered is it a flaw with Facebook or something I should be concerned about. Any help would be greatly appreciated. | Why on Facebook can I not see someone online but only last active? | facebook chat | null |
_codereview.139702 | I've been thinking of using this:template <typename T>inline T from_string(const std::string& s){ std::istringstream iss; iss.str(s); T result; iss >> result; return result;}in my code. Then I thought I shouldn't construct istringstreams all the time, and made it into this:inline std::istringstream& get_istringstream(){ static thread_local std::istringstream stream; stream.str(); return stream;}template <typename T>inline T from_string(const std::string& s){ auto& iss(get_istringstream()); iss.str(s); T result; iss >> result; return result;}... and this builds and works (although I haven't tested it very extensively, nor ran performance tests). Would you say that good enough for general-purpose utility code, that is not intended to run in some tight loop? Are there other considerations I've overlooked, performance-wise (*) or usability-wise?Perhaps I should mention my motivation here is partly how I found it strange that there's no std::from_string().Edit: If you're concerned about the dependence on a default constructor, we can also throw in this:template< typename T >struct istream_traits { inline static T read(std::istream& is) { T x; is >> x; return x; }};template<> struct istream_traits<bool> { inline static bool read(std::istream& is) { is >> std::boolalpha; bool x; is >> x; return x; }};template<typename T>inline T read(std::istream& is){ T x = istream_traits<T>::read(is); return x;}... and then replace T result; iss >> result; with return read<T>(iss);.(*) - Yes, I know anything with iostreams is probably not fast to begin with. | A from_string() function (inverse of std::to_string) | c++;c++11;parsing;serialization | null |
_softwareengineering.288292 | Can I take a GPL program and relicense my changes under the AGPL?Say I clone a GPL project, make some changes, can I only allow people to use my changes under the AGPL license? | Can I take a GPL program and relicense my changes under the AGPL? | licensing;gpl;agpl | null |
_unix.190690 | I'm getting this kind of error when i'm deleting file on my AIX machine. Getting same error for rmdir. venky-19:[/hm/dev/application/backup/ear/] # rm -rf resourcesrm: Directory resources is not empty.I tried to find out the hidden files using ls -lart under resources and ear directory. But there are no hidden files. | rm: Directory resources is not empty | directory;rm;aix | null |
_unix.337862 | Is there still any possibility to install PHP7 on Debian Wheezy (7.11) ?/etc/apt/sources.listdeb http://packages.dotdeb.org wheezy alldeb-src http://packages.dotdeb.org wheezy allCommands# apt-get install php7.0Reading package lists... DoneBuilding dependency treeReading state information... DoneE: Unable to locate package php7.0E: Couldn't find any package by regex 'php7.0'Only PHP5 packages are available. | Obtain PHP7.0 on Debian 7 | debian;php | Eventually I haven't found any feasible solution for me (I was too lazy to compile from source) and I upgraded to Debian Jessie with the help of this articlehttps://www.debian.org/releases/jessie/i386/release-notes/ch-upgrading.en.html |
_scicomp.11284 | I am a novice at PETSC, and I have been trying to write an FVM code for steady heat conduction in 2D using PETSC (square, regular grid, Dirichlet boundaries)Since the large matrix , say A, will be sparse I declare 5 non-zeros per row and use MatCreateSeqAIJ()My question is about assembling the entries of the matrix. In each CV, I call MatSetValues()and add the 5 coefficients into A using local arrays II, JJ and Values_IJ1) Is this the right or usual way to do this? I ask because, it seems to me, am assembling by implicitly using a COO type representation of sparsity in my loop while the matrix representation in PETSC is CSR.2) If not, is there a way to create the local arrays II, JJ and Values_IJ to fit the CSR format of the matrix and then call MatSetValues()? | Assembling sparse matrix in PETSC for Poisson equation | finite difference;petsc;sparse;finite volume;poisson | null |
_unix.275639 | I would like to be able to switch between my default US English keyboard to an Arabic one, as I would like to learn some Arabic. I know that going to System Settings → Regional Settings → Translations and choosing as my default language will cause everything that can be translated to be translated to Arabic when I next log into KDE Plasma 5. I also know that this causes the Plasma panel to be reversed (so that its Left→Right orientation to be switched to a Right→Left one). What I want is for nothing to be translated or reversed just for my keyboard to be temporarily switched to an Arabic one (but easily switchable back to my default US English one), so that I can type in Arabic. If relevant (like if your answer involves installing extra software) I am using Arch Linux. | How do I temporarily switch between keyboards on KDE Plasma 5? | keyboard layout;plasma5 | I have found an answer, namely running:sudo setxkbmap -layout arachanges my keyboard to an Arabic one. Likewise running:sudo setxkbmap -layout usswitches it back to a US English keyboard. Further layouts can be found in /usr/share/X11/xkb/symbols/. |
_cstheory.16254 | Given a data matrix $D$, is there any effective algorithm to solve the optimization problem$\min_Q || D - Q ||_F$such that$Qe=e$,$e^TQ=e^T$, and$Q_{i,j} \geq 0 $ $\forall i,j$,where $||\cdot||_F$ is the Frobenius norm of matrix.p.s. I also posted this question on the Mathematicss exchange. | Effective algorithm of searching the nearest doubly stochastic matrix | optimization;matrices | This is a special case of the following problem: given a polytope $P$ specified by linear constraints and a point $x$ find $y \in P$ that minimizes $\|x - y\|_2^2$. If you are ok with a small additive approximation to $\|x - y\|_2^2$, you can try using the Frank-Wolfe algorithm. This is a sort of gradient descent algorithm. You start from a point $y_0 \in P$ (in your case this could be say the $n \times n$ matrix with $1/n$ in every coordinate) and in each steps you compute $y_{i+1}$ from $y_i$ as follows:Let $w = x - y_i$.Let $v$ be the vertex of $P$ that maximizes $w^Tz$ for $z \in P$ (can be found by LP).Find the point on the line through $y_i$ and $v$ that is closest to $x$ (this is quadratic optimization in a single variable). This point is $y_{i+1}$.Ken Clarkson has analyzed this simple algorithm. In $t$ steps, the additive approximation is bounded by $d(P)^2/t$, where $d(P)$ is the diameter of $P$. In your case, I believe $d(P) \leq \sqrt{n}$, as the vertices of $P$ are permutation matrices and they all have Frobenius norm $\sqrt{n}$. So in $O(n/\epsilon)$ iterations of the above algorithm you can get $Q$ such that $\|D - Q\|_F^2 \leq \|D - Q^*\|_F^2 + \epsilon$, where $Q^*$ is the optimal solution. |
_webapps.19977 | Yahoo! Mail is not letting me attach files to send. This problem started suddenly and inexplicably on 18 October 2011. I have tried multiple browsers. I have tried re-installing browsers. I have tried to attach both .docx and .doc files (files that are clearly well below the maximum allowed size). Sometimes the system just hangs and sometimes I get an error message in red type (sorry, can't recall the specific text of the message). Has anyone else experienced this? More importantly, does anyone have a solution? | Yahoo! Mail is not letting me attach files to send... | email;yahoo mail;attachment | null |
_unix.106243 | file is:BASH.NIRSH.ABII want the awk will show:User is NIR, SHELL is BASHUser is ABI, SHELL is SHI dont know how to split a parameter by char.The Idea is:cat file.txt | awk '{print User is afterDot($1) , SHELL is beforeDot($1)}' | awk split parameter by char | awk | You can use the string functions in awk.$ (echo BASH.NIR; echo SH.ABI FOOBAR) | awk '{p=index($1,.);print User is, substr($1,p+1) , SHELL IS, substr($1,0,p-1)}'User is NIR, SHELL IS BASHUser is ABI, SHELL IS SHThe index function returns the position of the character to be found (in this case a dot). And strstr will return a substring. We use p+1 and p-1 to not include the dot.For more information look in the String Functions section of the awk manpage. |
_unix.285328 | This question is about best practices. I know logging in over secure shell or switching users su, and su -l have different effects. Also, in the event you make a typo in the configuration, you still want to be able to log in. Where is/are the/some ideal place/s to store color definitions? At the moment I have them in .bash_profile. Is it ok to store them in .bashrc?Configuration Locations:According to the ArchWiki/etc/profile Sources application settings in /etc/profile.d/*.sh and /etc/bash.bashrc. ~/.bash_profile Per-user, after /etc/profile. ~/.bash_login (if .bash_profile not found)~/.profile (if .bash_profile not found)/etc/skel/.bash_profile also sources ~/.bashrc.~/.bash_logout /etc/bash.bashrc Depends on the -DSYS_BASHRC=/etc/bash.bashrc compilation flag. Sources /usr/share/bash-completion/bash_completion~/.bashrc Per-user, after /etc/bash.bashrc.Let's save I have two color definitions, one for the command prompt and one for the ls command.set_prompt () { Last_Command=$? # Must come first! Blue='\[\e[01;34m\]' White='\[\e[01;37m\]' Redbold='\[\e[01;31m\]' Greenbold='\[\e[01;32m\]' Greenlight='\[\e[00;32m\]' Blueintense='\[\033[00;96m\]' Purplelight='\[\e[00;35m\]' Yellowbold='\[\e[01;33m\]' Graydark='\[\e[01;90m\]' Reset='\[\e[00m\]' FancyX='\342\234\227' Checkmark='\342\234\223' PS1=${Graydark}\t if [[ $Last_Command == 0 ]]; then PS1+=$Greenlight$Checkmark else PS1+=$Redbold$FancyX fi if [[ $EUID == 0 ]]; then PS1+=\\u@$Redbold\\h else PS1+=$Greenlight\\u$White@$Redbold\\h fi PS1+=$Graydark\\W $Redbold\\\$$Reset }PROMPT_COMMAND='set_prompt'set_ls () { Default='0;0' White='97' Yellowbold='01;33' Greenlight='00;32' Purplelight='00;35' Purplebold='01;35' Whitelight='00;37' Yellowlight='00;33' Graydark='00;90' # Highlight Highlightpurpledark='45' Highlightgraydark='100' LS_COLORS=fi=$Greenlight:di=$White;$Highlightgraydark:*.tex=$Purplebold export LS_COLORS}set_ls | Where should I save color codes for the PS1 command line / terminal? | shell;command line;configuration;colors | null |
_softwareengineering.90161 | I just started working at a company and we're currently in a fairly intensive (full-days most work days) training program to bring us up to speed on the way the company does things, and train us in VB.NET, along with some C#.They're beginning to migrate towards a modified Model-View-Presenter architecture, with server remoting playing a fairly large role. An example .NET program might look like this:SomeSolution|+-+- ServerProject| || +- ServerEmployee.vb| || +- Server.vb|+-+- Presenter| || +- PresenterEmployee.vb| || +- Presenter.vb| || +- IView.vb|+-+- ViewProject | +- ViewEmployee.vb | +- View.vbThe classes in question would be the employee classes. The example that I was given was that the ServerEmployee would have the most information - being retrieved from a database, it would likely have the most attributes, such as .FirstName, .LastName, .MiddleInitial, .PreferredName, .HireDate, and whatever other attributes were present on the database. The PresenterEmployee would have the other attributes, as well as a .FullName attribute that perhaps was generated this way:If employee.PreferredName <> String.Empty Then employee.FullName = employee.PreferredName & & employee.LastNameElse employee.FullName = employee.FirstName & & Employee.MiddleInitial & & Employee.LastNameEnd IfAnd finally, the ViewEmployee would only have the .FullName and .HireDate attributes. We were informed that the rationale behind this design was that if we have say, a DataStructures class that's referenced by the other classes then each time the DataStruture class has to be rebuilt, the entire project must be re-deployed (which I understand is a somewhat tedious process because of some infrastructure decisions). I understand that that would not be A Good Thing, but it seems that if you have some code that probably won't change much (a fairly generic superclass with some straightforward properties), it would make sense to avoid the code duplication.Am I correct in thinking that this is a violation of the DRY principle? The first thing I thought of when they taught this was ewww, that kinda smells...Other than (potentially) not having to redeploy the entire application every time the superclass is changed, is there any benefit to doing things this way? And if it is broken, and I want to take the onus to try and fix it, what are some good arguments to defend my choice? | Does this pattern disregard the DRY principle, and can I modify the pattern to fit? | design;code smell | Once you get into the world of n-tier architecture, it becomes a question of how much separation you want between layersA typical 3-tier architecture would be Data Layer <-> Business Layer <-> UI Layer.The data layer would contain the database entities, the business layer would contain a view of the database entities with business logic applied and the UI layer would contain a view of the business layer with presentation logic applied.Depending on the scope of the project, it is perfectly acceptable to re-use entities between layers if you want to avoid a lot of repetitive mapping.It really comes down to separation of concerns versus DRY. If you need to reuse the business layer, you obviously don't want the UI layer using the business entities directly since any refactoring would have to be applied in multiple places (is having to refactor the same thing in multiple places considering a violation of DRY? :)? The only concern I would have with the above approach is that I'm not sure how you are handling aggregated entities. My own preference is to use DDD to design the business layer so that each component is intended for a specific use case rather than just a collection of separate entities with some business logic inside themI would recommend a tool like AutoMapper to do the mapping between layers via convention if you want the flexibility of the above approach whilst avoiding some of your DRY concerns.Ultimately, there is no right answer tho. :( |
_softwareengineering.339981 | I find it difficult allying CQRS/ES with the Out of tar pit paper architecture.This architecture implies 4 layers:State (state of the application) Business Domain (purely functional)I/OControl ( all the dirty stuff for making the layers work together)In my case, the state depends heavily on a database.With the CQRS/ES in mind, I have a decision engine.The decision engine for producing an event from a command, is the Business Domain, which has to be purely functional.When a command asks for an Item to be created, the decision engine chooses to accept or not to create an event CreateItem only if the Item is not already existing (simplified for the example).In theory, I should pass the state of the application as a argument to the Business Domain, so as to decide accordingly.But in the case of a database, I cannot pass the database as a side-effect free parameter. I feel like I have to perform the query checking the existence of the item beforehand inside the Control layer, and then pass the result of the query on the database to the Business Domain, which will then return an event or not.The consequence is that I have some business code (the one related to the query and the business logic to perform the checkings) that will be inside the Control layer.That feels wrong for me as far as I understood the Out of the tar pit paper and also CQRS/ES.The main issue seems for me that the state is huge: it's the whole database.What is wrong in my reasoning ? | CQRS/ES in haskell, using Out of the tar pit paper architecture | haskell;cqrs;event sourcing | With the CQRS/ES in mind, I have a decision engine. The decision engine for producing an event from a command, is the Business Domain, which has to be purely functional.Good.When a command asks for an Item to be created, the decision engine chooses to accept or not to create an event CreateItem only if the Item is not already existing (simplified for the example).Also good.In theory, I should pass the state of the application as a argument to the Business Domain, so as to decide accordingly.Yes, perfect. (Note: more state of the domain than state of the application. Also, ddd taught us that we don't need the state of the entire domain, just state local to the change we are considering.)But in the case of a database, I cannot pass the database as a side-effect free parameter.That's right -- all of the interaction with the database should happen outside of the business domain (which only cares about state).I feel like I have to perform the query checking the existence of the item beforehand inside the Control layer, and then pass the result of the query on the database to the Business Domain, which will then return an event or not.Ah. Not quite -- you don't need to check the existence of the item, you need to check its state, which is not quite the same thing.Fortunately, you are using ES; which does make things simpler to explain: this history of an entity that doesn't exist is empty.So in this case: you receive a command from IO. Control fetches the appropriate history from the state of the application. The model is invoked, passing in that history and the command as arguments. The model returns event(s) that are consequences of the command being run at this point in the history. Control updates the copy of the history in the state of the application.So happy path: the commmand CreateItem(x) arrives. Command fetches History(x), which in this case is an empty sequence of events. The model invoked, it sees from the history that the item doesn't exist yet, and that the business invariant is otherwise satisfied, to it returns a representation of the ItemCreated(x) event.Alternative path: the commmand CreateItem(x) arrives. Command fetches History(x), which in this case is a sequence of events including CreatedItem(x). The model invoked, it sees from the history that the item has previously been created, and rejects the command (throws an exception, returns an Error, returns an empty collection of events). |
_unix.218573 | When I update my google chrome or chromium to a version that is higher than 38 The window of the browser gets black functional square. It's all black even the top bar. I basically can't see anything just black. When I downgrade to version 38 or previous version, It runs correctly. The machine has centos 6.6 3.10.56-11.el6.centos.alt.x86_64. | Google chrome and chromium black window | centos;chrome | null |
_codereview.59744 | I have a lot of code that looks like this:value = TopicLinkClick.create_from(new_params)return value unless value.nil?# do something elseI find this code is not so good because creating a temporary variable is troublesome and disruptive of my workflow, and it takes time to read and understand a large block of code that is meaningless.Is there a better way for me to do this? | Early return, unless return value is nil | ruby | null |
_softwareengineering.161119 | How is programming a quantum algorithm different? What would a C like language look like if it was designed for qubits? Would types change? | How will quantum computing change programming? | programming languages;algorithms | null |
_softwareengineering.267044 | Consider the following program:Many people when they want to use a struct, they create a new variable as:struct structureName variableNameWhile it works when you just define it as: structureName variableNameMy teacher always uses the first method. My question is how do they differ? Do I ever need to specify struct before defining my variableName. Here is an example to explain my question:struct example { int n; char c;};int main() { example o; o.c = 'c'; o.n = 5; printf(%c, o.c); printf(%d\n, o.n); //this works struct example ex; // this versus example o without using struct keyword ex.c = 'e'; ex.n = 7; printf(%c, ex.c); printf(%d, ex.n); //this works return 0;} | Why define struct in variable? | c++;c;data structures | This is one of the differences between C and C++.In C, structure names are completely separate from other names and you must use the struct keyword to tell the compiler to look for the name of a structure.Another way to put it is that the struct keyword is actually part of the name of the structure.When designing C++, this was changed and the use of the struct (or class) keyword was made optional when referring to a structure or class. |
_datascience.17487 | I read on this post that the best way to train a model to convert an audio input to an audio output is using regression:Is it possible using tensorflow to create a neural network that maps a certain input to a certain output?What if the dataset I am training with has audio input & outputs of different length? I would like my model to be able to convert any sized input to the corresponding sized output. | Neural Network Regression Model Allowing Audio Input of Any Length? | neural network;regression;tensorflow | null |
_softwareengineering.84598 | In database programming there's a technique called normalization that you do to data you want to store.Has anyone tried to apply this concept to object design? How did you? How did it work out?Edit: To expand/clarify, database normalization is more than a set of principles to reduce redundancy. There's actually steps and stages you go through and at least moderately objective measures that tell you which stage you are in. Object design has its own principles, and there's the concept of smell, but is there any way to do something similar that would tell you that you're in XX-form0,1,2...etc...and methods to move to the next most normalized level? | Object Oriented normalization | design | null |
_webmaster.55682 | I have updated the .htaccess file so that when someone types in example.com, they are redirected to www.example.com. This works great on my computer, but when I try it on my cell phone is does not redirect. Instead I get the Webpage not available message. Does anyone know why? I've designed many websites and have never run into this problem. | Website won't work without www on mobile phone | htaccess;redirects;mobile | null |
_reverseengineering.109 | We all know that Ubuntu is the most popular Linux distro today with plenty of application currently being developed for it. But then I use Fedora and some use other distros but still liked to have the same program from Ubuntu in their systems.So how can I convert .deb files back to .tar so it can be recompiled for other distros? | How can I turn .deb files back to .tar for reuse with other Linux distros? | decompilation;linux;development | null |
_softwareengineering.49749 | In simple steps how can one make the transition from a Use Case diagram to a Class diagram? | UML: Going from Use Case to Class Diagram | uml | Last year I gave a talk at ICSOFT 2010 that addressed that particular issue. The answer is not simple and I cannot describe it here in full, but you can download my presentation here. Scroll down to slide 23 Moving from functional to structural models for this topic.The OPEN/Metis white paper contains additional information to complement the presentation.The basic steps to obtain a class model from use cases are:Create a service model for each use case.Define operations for each service and busy state in your service models.Determine the responsible class for each operation, adding new classes when necessary.I will be happy to extend this answer with additional details if you have further questions. |
_webmaster.58725 | I was looking at this question and others similar, but I'm a bit unsure if the same applies for my case: I recently made a site which cuts for browser support at IE9. However the old site, which mine replaces, does have support all the way back to IE6. Users on < IE8 will be redirected using JavaScript to ie.mydomain.com rather allowed trough to www.mydomain.com. As the content is fairly similar on both sides I'm a bit worried about getting punished for duplicated content. For now I've disallowed the IE site for indexing altogether. But if there is something to gain of allowing indexing of both sites, that would of course be best. | Browser specific sub-domain? | seo;subdomain | This isn't a terrible thing to do if you want to support legacy browsers. As long as you have it blocked from search engines crawlers you won't have to worry about duplicate content issues. And it isn't serving up special content just for the search engines because they are getting the same content as everyone else (nor is it done for the benefit of search engines) so it isn't black hat. So SEO-wise, this is fine. |
_codereview.102559 | I designed a simple drop-out stack a while back. Basically, I just want to get a few opinions on whether or not this is a good implementation and whether I am understanding the concept of a drop-out stack correctly. I know there are other / better ways to implement a stack, but I'm interested specifically in doing it with an array.Basically, my idea is to allow elements to be pushed in until limit of array is reached, then an int representing the top of the stack is reset to 0, so the bottom elements are replaced by new ones pushed in. This is as opposed to making a copy of the array in a new array...but then it wouldn't be a drop-out stack.The pop method does something similar, only in reverse. If the marker for the top reaches 0, it is set to size of array-1 so elements can still be popped in correct order.The output I'm getting looks fine to me. No null references or objects in the wrong place, etc. I've tested it pushing in Character and Integer objects.package CAStack;import java.util.Arrays;//********************************************************************// CircularArrayStack.java //// Represents an array implementation of a dropout stack. The bottom of// the stack drops out each time a new element is pushed in, after// size limit is reached. //// Based on ArrayStack.java//////******************************************************************** public class CircularArrayStack<T> implements StackADT<T> { private static final int DEFAULT_CAPACITY = 100; private int top; private int bottomElem = 0; private T[] stack; //----------------------------------------------------------------- // Creates an empty stack using the default capacity. // //----------------------------------------------------------------- public CircularArrayStack() { this(DEFAULT_CAPACITY); } //----------------------------------------------------------------- // Creates an empty stack using the specified capacity. // Note top is now initialized at -1 so that when first // element is added an top is decremented, top will equal 0 // corresponding to the array index of the first element. // //----------------------------------------------------------------- public CircularArrayStack(int initialCapacity) { top = -1; stack = (T[])(new Object[initialCapacity]); } //----------------------------------------------------------------- // Adds the specified element to the top of this stack, expanding // the capacity of the stack array if necessary. // Top is now incremented BEFORE element is added, so that element // is still successfully added to top of array; makes sure // element at value of top before increment is not overwritten. // // If new element is pushed in after size = CUTOFF, bottom element // or lowest stack element remaining is removed. // // Instead of expanding capacity, elements are added to bottom of // stack if it becomes full. //----------------------------------------------------------------- public void push (T element) { if (top == size()-1) top = -1; top++; stack[top] = element; } //----------------------------------------------------------------- // Removes the element at the top of this stack and returns a reference to it. // Top is now decremented AFTER element is popped and value is changed // to null, as top now represents position of element, not position // above element. //----------------------------------------------------------------- public T pop () throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException(stack); T result = stack[top]; stack[top] = null; if (top == 0) top = size(); top--; return result; } //----------------------------------------------------------------- // Returns a reference to the element at the top of this stack. // Returns element at top rather than top -1 since top now // corresponds to position of element. //----------------------------------------------------------------- public T peek () throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException(stack); return stack[top]; } //----------------------------------------------------------------- // Returns a string representation of this stack. //----------------------------------------------------------------- public String toString() { String result = <top of stack>\n; for (int index = top; index >= 0; index--) result += stack[index] + \n; return result + <bottom of stack>; } //----------------------------------------------------------------- // Returns true if the stack is empty. // Changed so that method returns true if top < 0 rather // than top < 1 since top < 0 now represents empty condition. //----------------------------------------------------------------- public boolean isEmpty() { return top < 0; } //----------------------------------------------------------------- // Returns the number of elements on the stack. //----------------------------------------------------------------- public int size() { return stack.length; } }Interface Used: package CAStack; /** * Defines the interface to a stack collection. * * @author Java Foundations * @version 4.0 */ public interface StackADT<T> { /** * Adds the specified element to the top of this stack. * @param element element to be pushed onto the stack */ public void push(T element); /** * Removes and returns the top element from this stack. * @return the element removed from the stack */ public T pop(); /** * Returns without removing the top element of this stack. * @return the element on top of the stack */ public T peek(); /** * Returns true if this stack contains no elements. * @return true if the stack is empty */ public boolean isEmpty(); /** * Returns the number of elements in this stack. * @return the number of elements in the stack */ public int size(); /** * Returns a string representation of this stack. * @return a string representation of the stack */ public String toString(); } | Stack using an array | java;array;stack;circular list | null |
_unix.206376 | I like the website www.globalresearch.ca and I have made copies of it. This command works for me wget -r -l14 -t2 -T60 -E -k --no-check-certificate --restrict-file-names=windows,nocontrol --user-agent=Mozilla/4.0 (compatible; MSIE 6.0; Microsoft Windows NT 5.1) http://www.globalresearch.ca/but it takes something over 30 hours! to make a complete copy of the site. And It's over 6 Gigabytes in size.Is there a better or faster way , to copy a website in gnu/linux?Can I copy the website one time with wget and then use wgetto update the files on the hard drive and add only the new material?I would like to have it convert the links so that they point to the fileson the hard drive ( -k ). What would the command for something like that look like. Or is there a better way, a faster way to make a copy of the site? I really don't want to have to wait 30+ hours just to make a copyof one web site.Thank You. | Whats the best way to copy a website onto your harddrive? | wget | null |
_codereview.146468 | This problem is from INOI 2014 , where I have find out the maximum cost of traveling through the cities but taking the minimum possible route cost , here is an excerpt from it,Indian National Olympiad in Informatics 2014Nikhils slogan has won the contest conducted by Drongo Airlines and he is entitled to a free ticket between any two destinations served by the airline. All cities served by Drongo Airlines can be reached from each other by some sequence of connecting flights. Nikhil is allowed to take as many connecting flights as needed, but he must take the cheapest route between his chosen destinations.Each direct flight between two cities has a fixed price. All pairs of cities connected by direct flights have flights in both directions and the price is the same in either direction. The price for a sequence of connecting flights is the sum of the prices of the direct flights along the route.Nikhil has information about the cost of each direct flight. He would like to maximize the value of his prize, so he would like to choose a pair of cities on the network for which the cost of the cheapest route is as high as possible.For instance, suppose the network consists of four cities {1, 2, 3, 4}, connected as shown on the diagram.In this case, Nikhil should choose to travel between 1 and 4, where the cheapest route has cost 19. You can check that for all other pairs of cities, the cheapest route has a smaller cost. For instance, notice that though the direct flight from 1 to 3 costs 24, there is a cheaper route of cost 12 from 1 to 2 to 3.The solution was pretty obvious to do dijkstra's in every vertex and find the maximum cost from the incurred map, but while maximum of the tutorials use a map+heap structure which is unavailable in c++ , hence I have to use a sorted vector for the same purpose.The problem is the code , out of 20 testcases , shows TLE on 2 , so anyone have any better idea on how to tackle that heap + map approach , so that my code passes without a TLE?Here is my code,#include <iostream>#include <deque>#include <map>#include <vector>#include <utility>#include <algorithm>#include <climits>#define NIL -1typedef struct distances{ int index; int dist;}distances;bool compareheap(distances a,distances b){ return a.dist < b.dist;}int findIndex(std::deque<distances>heap,int vertex){ int size = heap.size(); int index = NIL; for(int i=0;i<size;i++){ if(heap[i].index == vertex){ index = i; } } return index;}bool comparePt(std::pair<int,int> a,std::pair<int,int>b){ return a.second > b.second;}int dijkstra(std::vector<std::vector<int> >graph,int vertex,int size){ std::map<int,int>map; map.insert(std::pair<int,int>(vertex,0)); std::deque<distances>heap; for(int i=0;i<size;i++){ if(i == vertex){ continue; } if(graph[vertex][i] != NIL){ distances a; a.index = i; a.dist = graph[vertex][i]; heap.push_back(a); }else{ distances a; a.index = i; a.dist = INT_MAX; heap.push_back(a); } } //std::cout << got here << std::endl; while(!heap.empty()){ sort(heap.begin(),heap.end(),compareheap); distances top = heap.front(); heap.pop_front(); int ind = top.index; int distance = top.dist; //std::cout << ind << ' ' << distance << std::endl; map.insert(std::pair<int,int>(ind,distance)); //std::cout << got here << std::endl; for(int i=0;i<size;i++){ //std::cout << i << std::endl; //std::cout << ind << ' ' << i << std::endl; if(graph[ind][i] != NIL){ //std::cout << got here << std::endl; int index = findIndex(heap,i); if(index == NIL){ continue; } //std::cout << got here << std::endl; int d = graph[ind][i]+distance; if(d < heap[index].dist){ heap[index].dist = d; } } } //std::cout << got here << std::endl; } std::vector<std::pair<int,int> >v; std::copy(map.begin(),map.end(),back_inserter(v)); sort(v.begin(),v.end(),comparePt); return v[0].second;}int main(){ int city,connections; std::cin >> city >> connections; std::vector<std::vector<int> >graph(city,std::vector<int>(city,NIL));//Adjacency matrix for storing the graph for(int i=0;i<connections;i++){ int a , b; std::cin >> a >> b; a--;b--; std::cin >> graph[a][b]; graph[b][a] = graph[a][b]; } int max = 0; for(int i=0;i<city;i++){ int highest = dijkstra(graph,i,city);//do dijkstra for each and every vertex if(highest > max){ max = highest; } } std::cout << max << std::endl; return 0;} | Finding the max cost from the minimum cost incurred on travelling | c++;algorithm;programming challenge;time limit exceeded;graph | null |
_scicomp.26185 | I'm going through the article in the following link lately and one point confuses me a lot. https://arxiv.org/pdf/1509.05001.pdfSo, the goal of this paper is to solve the following constrained binary quadratic programming. Here the parameters $A$, $Q$ and $b$ are all of integer values.max $x^{T}Qx$$s.t.,$ $Ax\leq b$ $\text{and}$ $x\in \{0,1\}^{n}$.The authors consider the lagrangian relaxation of this problem in the following.So, we have the following optimization problem $L_{\lambda}$.$d(\lambda) = \text{min}_{x} x^{T}Qx+\lambda^{T}(Ax-b) $$s.t., $ $x\in \{0,1\}^{n}$.And the further optimization problem $L$ in the following.$L:\text{max}_{\lambda \in R_{+}^{m}}$ $d(\lambda)$Then, a branch-and-bound tree is created (which I do not quite understand why to create the tree). In each node $u$ of the branch-and-bound tree, a lower bound is computed by solving the problem $L$ and the primal-dual pair $(x^{u},\lambda^{u})$ is obtained. we define the slack of constraint $i$ at a point $x$ to be $s_{i}$ = $b_{i} a_{i}^{T}x$, where $a_{i}$ is the $i$-th row of $A$. Then the set of violated constraints at $x$ is the set $V = {i : si < 0}$. If $x^{u}$ is infeasible for the original problem, it must violate one or more constraints. Additionally, we define the change in slack for constraint $i$ resulting from flipping variable $j$ in $x^{u}$ to be $$\delta_{ij}=a_{ij}(2x_{j}^{u}-1).$$I do not understand why $\delta_{ij}$ is defined in this way. For my understanding, $x^{u}\in \{0,1\}^{n}$, so when you flip the variable $j$ of $x^{u}$, you change it either from 0 to 1 or from 1 to 0. So, in either case, the change in slack for constraint $i$ can be calculated. Did I miss something here ? Could anyone shed some light on what shall I do here? Many thanks for your time and attention. | constraint satisfaction via an LD solution | optimization;convex optimization;constrained optimization | $2x_{j}^{u}-1$ is either $+1$ if $x_{j}^{u}$ is 1 or $-1$ if $x_{j}^{u}$ is 0. Flipping $x_{j}^{u}$ from 0 to 1 or 1 to 0 will always change the contribution of $a_{ij}x_{j}$ to the left hand side of constraint $i$ (either by $+a_{ij}$ or $-a_{ij}$ This formula makes explicit that change in the slack for each constraint $i$. |
_webapps.7182 | By default, Facebook exports Attending, (Maybe) Attending and also events that I haven't replied (RSVPed) to yet. This results in an event spam in my Google Calendar.Is there a way to get a ical feed of only the events that I have marked to Attend or (Maybe) Attend? | Export (.ical) only Attending or Maybe Attending events from Facebook | facebook;export;facebook events;ical | null |
_codereview.140777 | I'm trying to design an application that binds a phrase or word to some item, for example image, and saves phrase-item pair in the database. Then it receives a text, and if it contains binded substring, corresponding item should be returned. It should return only one item (first match), and longest substrings should take precedence.I wrote a function, that returns expected values:from operator import itemgetterdef get_item(text, bindings): text = text.lower() matches = [] for phrase, item in bindings: phrase = phrase.lower() index = text.find(phrase) if index != -1: matches.append((phrase, item, index)) if matches: matches.sort(key=lambda x: len(x[0]), reverse=True) matches.sort(key=itemgetter(2)) item_id = matches[0][1] else: item_id = None return item_idExample:bindings = [('i', 'item1'), ('like', 'item2'), ('i like', 'item3'), ('turtles', 'item4'),]text = 'I like turtles!'print(get_item(text, bindings)) # should return item3Is there cleaner ways to complete such task, or faster, perhaps? | Check if strings from a list in a text and return first longest match | python;performance | null |
_softwareengineering.404 | Joel Spolsky wrote a famous blog post Human Task Switches considered harmful.While I agree with the premise and it seems like common sense, I'm wondering if there are any studies or white papers on this to calculate the overhead on task switches, or is the evidence merely anecdotal? | Is there any hard data to back up Human task switches considered harmful? | project management;performance | The abstract of a study that says 'maybe'Another study [PDF] that says interruptions make things seem like they took longer.A study[PDF] that says interruptions increase resumption lag time, but that cues seen in the task before the interruption can speed recovery time.Task switching[PDF] takes a significant portion of our work week.More reading on the psychology of interruptions than you can shake a stick at. |
_codereview.82272 | I made a panel of buttons which run commands when pushed. In order to not have the command run on every loop if the button is held down, I am comparing the button to a previous state and only run if it is not, like so:buttonStateR1 = digitalRead(redButton1);if (buttonStateR1 != lastButtonStateR1) { if (buttonStateR1 == LOW) { startFlash(); Serial.println('R1'); }}lastButtonStateR1 = buttonStateR1;This works quite well for only a couple of buttons. Is there a more effective method to use when there are 20 or so buttons? Having 20 or so of these statements does work but it get unwieldy and hard to maintain. Luckily each button acts the same (only needs to know that it has been pressed, not that it is held down or held down for a certain period of time, etc).This is the full code and setup with 4 buttons and a toggle to turn it all on or off:// LED output mappingsint greenLED = 0;int redLED = 1;// Pin input mappingsconst int redButton1 = 5;const int redButton2 = 3;const int blackButton1 = 4;const int blackButton2 = 6;const int safetyToggle = 2;// Button statesint buttonStateR1 = HIGH;int lastButtonStateR1 = HIGH;int buttonStateR2 = HIGH;int lastButtonStateR2 = HIGH;int buttonStateB1 = HIGH;int lastButtonStateB1 = HIGH;int buttonStateB2 = HIGH;int lastButtonStateB2 = HIGH;// Serial readingString inputString = ;boolean stringComplete = false;// Helper functionsvoid turnOn(int pin) { digitalWrite(pin, HIGH);}void turnOff(int pin) { digitalWrite(pin, LOW);}void cycleLED(int led, int time){ turnOn(led); delay(time); turnOff(led); delay(time);}void startFlash() { cycleLED(greenLED, 50); cycleLED(redLED, 50); cycleLED(greenLED, 50); cycleLED(redLED, 50);}void successFlash() { cycleLED(greenLED, 50); cycleLED(greenLED, 50);}void failureFlash() { cycleLED(redLED, 50); cycleLED(redLED, 50);}void setup() { pinMode(greenLED, OUTPUT); pinMode(redLED, OUTPUT); digitalWrite(greenLED, LOW); digitalWrite(redLED, LOW); // INPUT_PULLUP sets input buttons when unconnected to high // this means that the 'pressed' state outputs low pinMode(redButton1, INPUT_PULLUP); pinMode(redButton2, INPUT_PULLUP); pinMode(blackButton1, INPUT_PULLUP); pinMode(blackButton2, INPUT_PULLUP); pinMode(safetyToggle, INPUT_PULLUP); Serial.begin(9600); startFlash();}void loop() { if (digitalRead(safetyToggle) == LOW) { // 'safety' toggle // Button Red 1 buttonStateR1 = digitalRead(redButton1); if (buttonStateR1 != lastButtonStateR1) { if (buttonStateR1 == LOW) { startFlash(); Serial.println('R1'); } } lastButtonStateR1 = buttonStateR1; // Button Red 2 buttonStateR2 = digitalRead(redButton2); if (buttonStateR2 != lastButtonStateR2) { if (buttonStateR2 == LOW) { startFlash(); Serial.println('R2'); } } lastButtonStateR2 = buttonStateR2; // Button Black 1 buttonStateB1 = digitalRead(blackButton1); if (buttonStateB1 != lastButtonStateB1) { if (buttonStateB1 == LOW) { startFlash(); Serial.println('B1'); } } lastButtonStateB1 = buttonStateB1; //Button Black 2 buttonStateB2 = digitalRead(blackButton2); if (buttonStateB2 != lastButtonStateB2) { if (buttonStateB2 == LOW) { startFlash(); Serial.println('B2'); } } lastButtonStateB2 = buttonStateB2; } if (stringComplete) { if (inputString.equals(OK)) { successFlash(); } else { failureFlash(); }; inputString = ; stringComplete = false; }}void serialEvent() { while (Serial.available()) { char inChar = (char)Serial.read(); inputString += inChar; if (inChar == '\n') { stringComplete = true; } }} | Checking that buttons are being pushed | c++;arduino | null |
_unix.314502 | I recently noticed that emerging world does not upgrade packages obtained with layman. I have been syncing with layman, and in fact many of the overlay packages currently installed are no longer in the tree. I suppose I could emerge each package individually to upgrade it, but there has got to be a better way. Here's the relevant part of my current upgrade process:layman --sync-allemerge --update --deep --with-bdeps=y --newuse --keep-going --complete-graph --verbose-conflicts @worldI would think that running emerge like that would at least raise a warning that atoms are in my world file yet not in the portage tree, but I've never seen one. | How to emerge world, including overlays, in gentoo | gentoo;portage | The problem is that the overlay packages are never stabilized (the ~ is never removed from the arch KEYWORDS in the ebuilds). I'm not sure why this isn't being done -- at least in any of the overlay packages I use.The solution, found in this gentoo-user mailing list thread, is to allow unstable packages from each overlay in package.accept_keywords:*/*::overlay-name ~amd64 |
_webmaster.86483 | I have a web application in ASP.NET MVC that we want SEO optimized. I wanted to test whether the pages are appearing as search results in Google. However, I didn't want it to appear to the general public until I am ready to go live. Is there a way to do a sandbox testing of an SEO website on Google where I can continue developing and testing without it being pop up for search results for everyone else? | Testing SEO website | seo;testing | null |
_unix.14478 | Where can I find a technical description of the kernel parameters listed in /proc/sys (ob Linux)? | Documentation of kernel parameters | linux;kernel;documentation;parameter | The directory /proc/sys gives easy access to sysctl settings through the shell. You can read and write these settings either by reading and writing these files, or by calling the sysctl utility or the underlying sysctl system call.The various settings are described in the kernel documentation, in Documentation/sysctl/*. Start with README.This is fairly low-level stuff, so sometimes the documentation isn't completely precise and you'll need to turn to the source. Each sysctl setting usually corresponds to a variable with a resembling name inside the kernel (but this is a convention, not a rule). Many settings are declared in kernel/sysctl.c, but additional kernel components and modules can define their own. In the source (on a local copy or online at LXR), search for the name of the sysctl setting between quotes (e.g. xfrm_larval_drop) to find its declaration. |
_codereview.154783 | This is a follow-up for here.ProblemYour friend John uses a lot of emoticons when you talk to him on Messenger. In addition to being a person who likes to express himself through emoticons, he hates unbalanced parenthesis so much that it makes him go :(Sometimes he puts emoticons within parentheses, and you find it hard to tell if a parenthesis really is a parenthesis or part of an emoticon.A message has balanced parentheses if it consists of one of the following:An empty string One or more of the following characters: 'a' to 'z', ' ' (a space) or ':' (a colon)An open parenthesis '(', followed by a message with balanced parentheses, followed by a close parenthesis ')'.A message with balanced parentheses followed by another message with balanced parentheses.A smiley face :) or a frowny face :(Write a program that determines if there is a way to interpret his message while leaving the parentheses balanced.I'm working on this balanced smileys checking algorithm, and my current solution is very naive, with just two rules:At any point, the number of ) (close) should be less than the number of ( (open) + number of :( (frown)At the end, the number of ( (open) should be less than the number of ) (close) and :) (smile)I'm wondering if any bugs in my checking logic. Any advice on algorithm time complexity improvement or code style advice is highly appreciated as well.def check_balance(source): left = 0 right = 0 frown = 0 smile = 0 for i,c in enumerate(source): if c == '(': left += 1 if i > 0 and source[i-1] == ':': # :( left -= 1 frown += 1 elif c == ')': right += 1 if i > 0 and source[i-1] == ':': # :) right -= 1 smile += 1 if left + frown < right: return False if left > right + smile: return False return Trueif __name__ == __main__: raw_smile_string = 'abc(b:)cdef(:()' print check_balance(raw_smile_string) | Balanced smileys check algorithm (part 2) | python;algorithm;python 2.7;balanced delimiters | In the verbal description of the algorithm, should be less than implies not equal, which would not be correct. A wording such as must be at most would be totally clear.Your code has a bug because you are not quite following rule 1. The rule says at any point..., but you only check the rule after a smiley. You miss the case when a lone ) breaks the rule.Instead of canceling += 1 with -= 1 here...left += 1if i > 0 and source[i-1] == ':': # :( left -= 1 frown += 1... it would be clearer to use else:if i > 0 and source[i-1] == ':': # :( frown += 1else: left += 1Instead of if i > 0 and source[i-1] == ':' it would be simpler to remember the previous character in a variable: previous_char = None for char in source: if char == 'c': if previous_char == ':': ... previous_char = char |
_unix.114074 | One noob question from a new zsh user:In bash, I can use tab-completion to move one directory up and descend down again another path. For example, suppose I'm in $HOME/folder1, and I want to cd to $HOME/folder2. $HOME only has the two child directories folder1 and folder2. In bash, I could just typecd ..[TAB]f[TAB]2and would end up in $HOME/folder2. In my fresh zsh installation, pressing cd ..[TAB] produces a list of those child directories of $HOME/folder1 which have two . in their name.Is there a simple way to get the behaviour I'm used to? Or is there something even easier to achieve what I want in zsh? | Tab completion of ../ in zsh | zsh;directory;autocomplete;oh my zsh | Add this to your .zshrc and ..[TAB] will complete to ../ as per bash.zstyle ':completion:*' special-dirs true |
_unix.252267 | I just installed MariaDB on Kubuntu 15.10. I am able to log in with the root user via the plugin that authenticates the user from the operating system. (This is new to me, so I am learning about it rather than removing the plugin authentication as most tutorials seem to recommend.) Now I want to create a non-root user and grant all privileges to that user and allow the user to log into mysql (on localhost) without a password (using just the plugin). How would I do this? Do I need to give the user a password too? | MariaDB: Create and grant a new user using unix sockets plugin (passwordless) | mysql;authentication;mariadb;unix sockets | Found the answer. The part I needed was IDENTIFIED VIA unix_socket as shown below:MariaDB [(none)]> CREATE USER serg IDENTIFIED VIA unix_socket;MariaDB [(none)]> GRANT ALL PRIVILEGES on mydatabase.* to 'serg'@'localhost';MariaDB [(none)]> select user, host, password, plugin from mysql.user;+--------------+-----------+----------+-------------+| user | host | password | plugin |+--------------+-----------+----------+-------------+| root | localhost | | unix_socket || root | mitra | | unix_socket || root | 127.0.0.1 | | unix_socket || root | ::1 | | unix_socket || serg | localhost | | unix_socket |+--------------+-----------+----------+-------------+5 rows in set (0.00 sec)MariaDB [(none)]> FLUSH PRIVILEGES;Then in the shell: sudo service mysql restartTo log in using user 'serg' do not use sudo. Just use mysql -u serg. |
_webapps.35922 | I've just been suggested to use Trello, but I have one problem. I get the message to verify my email address... but I don't receive the email to verify the address. What to do? | I don't receive my email verifications in Trello | trello;email | null |
_unix.348912 | Guys i have mistakenly deleted some useful data from my backup file but the problem is I have so far analyzed huge amount of backup file and now i cannot take a another backup and start analyzing from first so can linux community help me on this.This is file formatORDER ALPHAFacility: 201 ZZZ COUNTRYWrong Trace: Kotak: NA Soak: NA NOUN: XP O O O O O O O O O O O O O O O O O O O O O O O O O O O O LAMAMO ORDER # P/P R O L H S C N D K M D D C N LAM uii ii oo--- -------- --- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --- --- -- -- BZ90rty K/K AA AA AA NA XP AP NA NA NA NA NA NA AP AP OOL XP IP Na ZX A/A WD WD WD NA WD WD NA NA NA NA NA NA WD WD OOL WD IP YORDER BURYFacility: 201 ZZZ COUNTRYWrong Trace: Kotak: NA Soak: NA NOUN: XP O O O O O O O O O O O O O O O O O O O O O O O O O O O O LAMAMO ORDER # P/P R O L H S C N D K M D D C N LAM uii ii oo--- -------- --- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --- --- -- -- BZ903901 A/A AA AA AA NA XP AP NA NA NA NA NA NA AP AP OOL XP IP Na ZX D/A WD WD WD NA WD WD NA NA NA NA NA NA WD WD OOL WD IP YORDER ALUIOI have deleted ORDER ALPHAFacility: 201 ZZZ COUNTRYWrong Trace: Kotak: NA Soak: NA NOUN: XP O O O O O O O O O O O O O O O O O O O O O O O O O O O O LAMAMO ORDER # P/P R O L H S C N D K M D D C N LAM uii ii oo--- -------- --- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --- --- -- -- BZ90rty D/D AA AA AA NA XP AP NA NA NA NA NA NA AP AP OOL XP IP Na ZX D/D WD WD WD NA WD WD NA NA NA NA NA NA WD WD OOL WD IP Ylike this only ORDER XXXXX number changes but condition remains sameCase 1: (IF NOUN :XP && D/D above D/D) add these data from original file to Backup file.NOTE:Original file has these Case 1:deleted data ,add these data back to Backupfile(where backup files states mistakenly deleted case 1 data).Simple flow---->either rsync or cp or sed or awk and append case 1 data from original file to backup file again. | Rsync , cp or any utility add specific filtered data back from original file to analyzed file | awk;sed;rsync;cp | null |
_webmaster.19455 | down vote favoriteshare [fb] share [tw] share [in]My site is built in PHP.I need to upload a file to the root directory, to verify ownership of the domain.I put the file in the first window I see when I log in over ftp, but the file doesn't show up at the relevant url.Where do I place a file so that it's in the root directory? | Root directory -- verifying ownership -- did I put the file in the right place? | ftp | This will vary since webservers can be setup in different ways. But it should be a directory named one of the following:wwwhtdocspublic_htmlwwwroot |
_unix.278501 | I have a line which looks like this: </File2>. I want to remove it using sed, but nothing I tried worked, I triedsed '/^<\/File2>$/d'so I thought maybe theres special characters at the end, but:sed '/^<\/File2>/d'didn't work either. I cannot remove the ^ in the beginning, because's there's lines I want to keep that includes </File2>. | Removing entire line with sed not working? | text processing;sed | Running tr -d '\r' on the file before removing the lines work.No idea why, but when I ran this command it revealed another tag as well as a space before <\/File2>. |
_unix.157404 | Here is what i get:[zehu@danville ~]$ groupsapl vboxusers[zehu@danville ~]$ [zehu@danville ~]$ grep zehu /etc/passwd [zehu@danville ~]$ [zehu@danville ~]$ grep apl /etc/group[zehu@danville ~]$ [zehu@danville ~]$ grep vboxusers /etc/groupvboxusers:x:1540:zehu[zehu@danville ~]$ Could anyone tell me if that's normal or not? and why is that? Thanks for help! [zehu@danville ~]$ sudo grep zehu /etc/shadow [zehu@danville ~]$ [zehu@danville ~]$ id uid=1580(zehu) gid=1100(apl) groups=1100(apl),1540(vboxusers) [zehu@danville ~]$ getent group apl apl:x:1100: [zehu@danville ~]$ ypcat passwd | grep zehuzehu:beL3WqT.4rb5Y:1580:1100:Zeyu Hu:/home/zehu:/bin/tcsh | can't find my user name in /etc/passwd nor name of my initial group in /etc/group | users;account restrictions;nsswitch | null |
_unix.188829 | I need to convert a bunch of .wv files to .flac but I can't seem to find a program to do it. Does anybody know how I can do this?P.S.: I was wondering why Audacity does not support the importing .wv format if it is open source and lossless. Does anybody know?Update: Somewhere I read about converting .ape to .flac using ffmpeg, so I decided to try replacing the .ape with .wv and at first it seems to work but then I get this at the end:[wv @ 0x8e7c200] Invalid block header.te= 836.1kbits/s audiofile.wv: Invalid data found when processing inputSo my question is: what is wrong here?By the way, the command used was ffmpeg -i audiofile.wv audiofile.flac. Thanks for the help. | How to convert WavPack to FLAC? | audio;conversion;flac | null |
_codereview.115503 | My Application looks something like this (Screenshot). To Control the URL Routing i am using a Angular Js Router. On Click of Store of the Side Panel the StoreList Appears. And on Click of the Edit, the portion template gets fetched from Spring MVC and displayed along with the details. I have written the Code for app.js provided in the below part. Because data could not be shared between the controllers i have written a StoreService and then the listStore array and its getters and setters so that same can be accessed via the controllers. This works fine but :-can there be a better code to this or any Angular functionalities i can use which can really simplify the code ? ORif i am not violating the rules of this forumn, can i directly ask is that the right way to code ? Was there anyway to use one single Controller for a logical module (like Store CRUD) ?app.js :- var storezillaadminapp = angular.module('storezilla-admin',['ngRoute']); storezillaadminapp.config(['$routeProvider', function($routeProvider) { $routeProvider.when(/liststores,{ templateUrl:_contextPath+/stores/getallstores, controller : StoreZillaAdminListController }); $routeProvider.when(/editstore/:id,{ templateUrl:_contextPath+/stores/geteditstore, controller : StoreZillaAdminEditController }); }]); storezillaadminapp.service('StoreService',function($http){ var listStores = []; this.getAllStores = function() { console.log('Called....'); return $http.get(_contextPath+'/stores'); }; this.getListStores = function() { return listStores; }; this.setListStores = function(data) { listStores = data; }; }); storezillaadminapp.controller('StoreZillaAdminListController',function($scope,StoreService){ StoreService.getAllStores().success(function(response){ $scope.listStores = response; StoreService.setListStores(response); }); }); storezillaadminapp.controller('StoreZillaAdminEditController',function($scope,$routeParams,StoreService){ $scope.store = StoreService.getListStores()[$routeParams.id];}); | Angular.js - Using Service to share data between controllers | javascript;angular.js | null |
_unix.285889 | I'm trying to create a script that will bring up my vagrant VM (a Ubuntu box hosted on OSX) navigate to the correct directory and start up my virtual env. I've read that this command should work for me:vagrant ssh -- -t 'some commands'The commands execute correctly, I see their output, but then the connection closes as soon as the script or statement is done executing. Here is the exact statement I'm trying to run:vagrant ssh -- -t 'source ~/env/bin/activate; cd /vagrant/refunite-web-touchpoint; pwd'I get this output:/vagrant/refunite-web-touchpointConnection to 127.0.0.1 closed.Here is the script for now:#!/bin/bashvagrant upvagrant ssh -- -t 'source ~/env/bin/activate; cd /vagrant/refunite-web-touchpoint; pwd' | Vagrant ssh closes connection after executing -t option | bash;ssh;vagrant | null |
_codereview.86725 | I require hundreds of equal, small sized buffers in my current project. The bulk of the computation in the program operates on data stored directly in those containers, so high performance is imperative. As the number of the buffers stays constant at runtime, my current approach is to use a std::vector<std::deque<MyObj>> as the buffer, but I do not like the low cache locality (since the actual storage of each deque is spread on the heap) and possibility for memory fragmentation that this approach entails.Thus I would like to replace my current container with something like a std::vector<somecontainer<MyObj>>, where somecontainer has at least a part of the contained objects stored locally, within the container object itself, and thus in contigous storage in the vector.My attempt to implement such a class is presented below. The container Ring is implemented as a circular buffer, permitting fast insertion and deletion at either end, and supports indexed access to the contents. The size is fixed at compile time, and is restricted to powers of two in order to effectively utilize binary modular integer arithmetic. It is still incomplete, lacking mainly iterators and an assignment operator capable of handling Ring objects to others with different capacities. I do not plan to add exception support to the class or bounds checking to the access functions.Are there any serious pitfalls in the design, or any significant improvements to be made? Will the memory alignment of the elements be correct, and will move constructors be used when inserting elements if possible? Could the container even be adapted to work as a thread safe, single producer - single consumer queue by substituting the current indexes of type uintN_t with indexes of type std::atomic_uintN_t along with other small modifications?Usage example:Ring<int, 8> buf(4, 0);buf.popFront();buf.pushBack(1);buf.pushFront(-1);while(!buf.isFull()) buf.pushBack(2);auto buf2(buf);buf.clear();for(size_t n = 0; n < buf2.getSize(); n++) std::cout << buf2[n] << , ;//-1, 0, 0, 0, 1, 2, 2, 2,Implementation:#include <cstdint>template<int N> struct UintByBits{ };template<> struct UintByBits<8> { using type = uint8_t; };template<> struct UintByBits<16> { using type = uint16_t; };template<> struct UintByBits<32> { using type = uint32_t; };template<> struct UintByBits<64> { using type = uint64_t; };constexpr getReqdBitCount(uint64_t val){ return (val <= 0xFF) ? 8 : ( (val <= 0xFFFF) ? 16 : ( (val <= 0xFFFFFFFF) ? 32 : 64));}//MinUint is an alias for the smallest unsigned integer type where MaxVal fitstemplate<uint64_t MaxVal>using MinUint = typename UintByBits<getReqdBitCount(MaxVal)>::type;constexpr bool isPowerOfTwo(uint64_t val){ return val != 0 && (val & (val - 1)) == 0;}//A constant-sized dual-ended queue implemented as a ring buffer. The size of//..the container may only be a power of two (this is a requirement of the//..modular arithmetic performed internally)template<typename T, size_t BufSize>class Ring{ static_assert(isPowerOfTwo(BufSize), 'Ring' buffer size (template param 'BufSize') is not a power of two); //Aligned raw memory array for constructing objects of type T into using ElemT = typename std::aligned_storage<sizeof(T), alignof(T)>::type; ElemT ring_[BufSize]; //Indexes to the raw memory pointig to the head and tail end of the ring. //..The indexes are each guaranteed to have one extra parity bit of storage, //..which is used for distinguishing between an empty ring and a full ring. MinUint<BufSize> ringFront_; MinUint<BufSize> ringBack_; //Bit masks used in bitwise operations: INDEX_MASK is used to remove all bits //..from an index that do not express the actual element position, PARITY_BIT //..is used for masking and comparing to the parity bit. static constexpr MinUint<BufSize> INDEX_MASK = BufSize - 1; static constexpr MinUint<BufSize> PARITY_BIT = BufSize;public: //When the Ring object is first constructed, ringFront_ points to the first //..element and ringBack_ to the last element in the container. Pushing one //..element to either end causes the index of the affected end to roll around, //..resulting in both indexes pointing to the same element, at which point the //..element can also be popped from either end. Ring() : ringFront_(0), ringBack_(BufSize - 1) { } //Fill constructor: copy construct n elements Ring(size_t n, const T &val) : ringFront_(0), ringBack_(BufSize - 1) { while(n-- > 0) pushBack(val); } //Fill constructor: construct n elements using default constructor explicit Ring(size_t n) : ringFront_(0), ringBack_(BufSize - 1) { while(n-- > 0) pushBack(); } //The assignment operator destroys all elements copy constructs new ones. //..Perhaps a templated version with a bounds check could accept a different //..sized Ring of the same value type? Ring& operator=(const Ring &other) { if(this != &other) { clear(); size_t n = other.getSize(); while(n-- > 0) pushFront(other[n]); } return *this; } //Copy constructor Ring(const Ring &other) : ringFront_(0), ringBack_(BufSize - 1) { size_t n = other.getSize(); while(n-- > 0) pushFront(other[n]); } ~Ring() { clear(); } //Get the element at the position 'position' relative to the front of the //..ring (that is, the element returned by getFront()). Pushing/popping at //..the front will thus change which element a given index points to, while //..pushing/popping at the back will not. Accessing at indexes equal getSize() //..NOT BOUNDS CHECKED T &operator[] (size_t position) { return *static_cast<T*>(static_cast<void*>( ring_ + ((ringFront_ + position) & INDEX_MASK)) ); } const T &operator[] (size_t position) const { return *static_cast<const T*>(static_cast<const void*>( ring_ + ((ringFront_ + position) & INDEX_MASK)) ); } //Construct an element to the front. NOT BOUNDS CHECKED template<typename ... Args> void pushFront(Args&& ... args) { --ringFront_; new(ring_ + (ringFront_ & INDEX_MASK)) T(std::forward<Args>(args)...); } //Destroy the element at the front. NOT BOUNDS CHECKED void popFront() { getFront().~T(); ++ringFront_; } //Get a reference to the front element. If size == 1 returns the same element //..as getBack(). Undefined for an empty container. T &getFront() { return *static_cast<T*>(static_cast<void*>( ring_ + (ringFront_ & INDEX_MASK)) ); } const T &getFront() const { return *static_cast<const T*>(static_cast<const void*>( ring_ + (ringFront_ & INDEX_MASK)) ); } //Construct an element to the back. NOT BOUNDS CHECKED template<typename ... Args> void pushBack(Args&& ... args) { ++ringBack_; new(ring_ + (ringBack_ & INDEX_MASK)) T(std::forward<Args>(args)...); } //Destroy the element at the front. NOT BOUNDS CHECKED void popBack() { getBack().~T(); --ringBack_; } //Get a reference to the back element. If size == 1 returns the same element //..as getFront(). Undefined for an empty container. T &getBack() { return *static_cast<T*>(static_cast<void*>( ring_ + (ringBack_ & INDEX_MASK)) ); } const T &getBack() const { return *static_cast<const T*>(static_cast<const void*>( ring_ + (ringBack_ & INDEX_MASK)) ); } //Destroy all elements in the container. void clear() { while(!isEmpty()) popFront(); } bool isEmpty() const { //if the indexes are otherwise equal but the parity bits differ, the ring is empty return (((ringBack_ + 1) ^ ringFront_) & (PARITY_BIT | INDEX_MASK)) == PARITY_BIT; } bool isFull() const { //if the indexes are equal including the parity bits, the ring is empty return (((ringBack_ + 1) ^ ringFront_) & (PARITY_BIT | INDEX_MASK)) == 0; } size_t getSize() const { //distinguish between a full and an empty ring, otherwise it would never return 0 return isEmpty() ? 0 : ((ringBack_ - ringFront_) & INDEX_MASK) + 1; } constexpr size_t getCapacity() const { return BufSize; }}; | Fixed size double-ended queue | c++;performance;c++11;queue;collections | Here are some observations that may help you improve your program.Add type to getReqdBitCountThe C++ standard does not allow definition of functions without type, so this program is technically malformed. I suspect that getReqdBitCount should return unsigned.Use std::size_tSince this is C++11, you should use the standard std::size_t and #include <cstdlib> rather than using the plain C version which may or may not be defined in <cstdint>.Use appropriate #includesIn addition to <cstdlib> mentioned above, the code is using std::aligned_storage but does not #include <type_traits> where that is defined and is using std::forward but does not #include <utility>.Consider simplifying some of the templatesThere are a series of templates and constexpr functions near the top that are ulimately all about finding the smallest size for MinUint<BufSize> but there are two changes I would like to suggest. The first is simplification. You can do all of that with just two templates:#include <limits>template <bool C, typename T, typename F>using Conditional = typename std::conditional<C, T, F>::type;template<uint64_t MaxVal> using MinUint = Conditional<std::numeric_limits<uint8_t>::max()>=MaxVal, uint_fast8_t, Conditional<std::numeric_limits<uint16_t>::max()>=MaxVal, uint_fast16_t, Conditional<std::numeric_limits<uint32_t>::max()>=MaxVal, uint_fast32_t, uint_fast64_t > > >;The second change is to use types such as uint_fast8_t instead of uint8_t for the resulting type. There may be no difference, but the intent is to designate the fastest uint type with at least 8 bits. Also note the use of std::numeric_limits means that we don't have to manually type a bunch of potentially error-prone constant values. The difference is that if you type one too few Fs in a long constant, the compiler will happily generate the wrong code anyway, but if you make an error typing std::numeric_limits... the compiler will halt with an error.Think of the data cacheEach of your data structures has three data items -- ringFront_, ringBack_ and the actual buffer. Because the cache line size in a typical machine these days is 64 bytes, you'll want to put the hottest (that is, the most frequently accessed) data toward the front of any object. For that reason, you should probably make the ring_ element the last of the three data items instead of the first to improve cacheing performance. Naturally, you should actually test the performance change (if any) rather than simply making assumptions.A somewhat more radical possibility is to put all of the cache pointers in one object and all of the cache buffer area in another. Consider keeping explicit countAt the moment, the isEmpty, isFull and getSize are relatively complex because of the storage mechanism used. Instead, consider instead if a separate count_ variable were used. Then, those functions would be trivial:bool isEmpty() const { return count_==0; }bool isFull() const { return count_==BufSize; }bool getSize() const { return count_; }Increment and decrement would be done in each dequeue operation instead, but it may be worthwhile to check for a performance difference. This would also allow for the front and back to be pointers (*T) rather than indices, which would also likely speed access. |
_webmaster.105041 | A lot of city domains are now available. Is it worth (or even good practice) to target markets in various cities in this way?<link rel=alternate href=https://mydomain.com.au hreflang=en-au/><link rel=alternate href=https://mydomain.sydney hreflang=en-au/><link rel=alternate href=https://mydomain.melbourne hreflang=en-au/>Is having multiple hreflang tags with the same language a good idea? | Using hreflang tags to target cities rather than countries | seo;html;language;hreflang | null |
_webapps.69774 | I am using Yet Another Mail Merge with Google Spreadsheet and Gmail and it works just as expected. But I am also trying to add a google drawing into the email body, so I would have more flexibility to have text areas (I have not found a way to enter a text area in gmail).The email merge works out of email draft. So I am trying to have a text area (where I can add the spreadsheet fields) on top of a image then export to email. Once I copy to web clipboard and try to paste onto email body, the text box slides down the picture. And it looses some details. Any suggestion? In summary: have a text box on top of image inside the body of email. Text box to have Spreadsheet details. Everything works OK in the google drawing, but it does not seem to be able to export to gmail.Thank you for any suggestion. | Insert Google Drawing into Gmail body | gmail;google drawing;mail merge | It's possible using a table inside the google drawing. Everything will stay more or less in the position you want, with certain limitations. Drawing is not very versatile, but you can get your job doneCopy it into a draft message and from there you can do the mail merge that will seem to be part of the drawing. Seems simple, but it took some time... |
_unix.220207 | I have a script that I'm trying to use to make handing applications easier. Right now it gets the window id of an application name (the first parameter) and checks if the window_id exists or not. If it doesn't exist, it runs the command to open that applications (second parameter. If it does exist, it uses wmctrl to get the window by window_id and move it to the front. My plan is to add this script to shortcuts for each application I use often. However, I want to add the ability to cycle through all the windows open for an application, instead of just being able to raise the last one open. Any recommendations on how to do this in bash? Would I need to set a global system variable? Though it's obvious, I'm fairly new to bash. Here's the script for windowctl, the place I want to extend is the get_window_id function.#!/bin/bash#command [app_name] [app_command]function get_window_id() { #this is the part I want to extend window_id=$(wmctrl -l | grep -i $1 | tail -1 | cut -f1 -d )}function open_app() { exec $2 }get_window_id $1if [ -z $window_id ] then open_app $1 $2 else wmctrl -i -a $window_id fiAn example would be adding the command windowctl sublime subl3 to Alt+S. | Cycle between open windows with wmctrl | shell script;x11;window management | null |
_scicomp.10402 | I have a question about matrix diagonalization. I don't know if this is the right forum... Is there a way to compute the smallest real eigenvalue (and eigenvector if possible) of a general real nxn matrix? (with n small say n=5). Is there a routine in fortran 90 that does this? And, more generally, what is the situation on numerical computing all existing eigenvalues (even for non diagonalizable matrices)? Edit: after Gerry's comment, I believe it's better to consider n as an odd number. In this case a real eigenvalue always exists because a polynomial of odd order with realcoefficients, the characteristic polynomial, has always a zero and so the smallest real eigenvalue is well defined. | Real eigenvalues finding | matrix;eigenvalues | null |
_unix.38050 | For linux machines I can use: # vi ~/.bashrc # red/green terminal colors regarding exit codeexport PROMPT_COMMAND='PS1=`if [[ \$? = 0 ]];then echo \\[\\033[0;32m\\];else echo \\[\\033[0;31m\\];fi`[\u@\h \w]\[\e[m\] 'export PS1to get green terminal when exit code is 0, and get red prompt when exit code is not 0. How can I do this under OpenBSD? (the default ksh)(I was trying to do it, but with no luck - using ssh to connect to the OpenBSD machine from my notebook - ubuntu/gnome-terminal. ) | How to get green/red terminals under OpenBSD? | prompt;openbsd;ksh | The problem is only bash has PROMPT_COMMAND. Try this instead:PS1='\[$(if (($?)); then tput setaf 1; else tput setaf 2; fi)\]'\'[\u@\h \w]\['$(tput sgr0)'\]' Caveat: I haven't tested this on ksh, but it avoids PROMPT_COMMAND and works in bash. tput uses your system's terminfo databases. This is generally more portable and maintainable than hard-coding escape sequences, provided terminfo is installed correctly. |
_unix.106846 | We want to publish an electronic magazine about to free software applications such as Gimp, Inkscape, GNU/Linux and so on. We need a magazine or book design application similar to InDesign of the Windows world. We found Scribus, but our language is written right-to-left and Scribus doesn't support RTL. What can we use? | Magazine publishing software with RTL support | software rec;right to left | null |
_cstheory.11481 | I have read a stream computation paper in STOC07(Paul Beame, T. S. Jayram, and Atri Rudra. Lower bounds for randomized read/write stream algorithms.) and FOCS08Paul Beame and Trinh Huynh. On the value of multiple read/write streams for approximating frequency moments).I am interested in this topic with design of algorithms and analysis of limitations.I want a list of natural counting functions, which stream algorithm theorists often consider like NPcomplete problems list by Garey and Johnson .Is there such a list ? | Functions and Counting Problems in Streaming Computation | ds.algorithms;lower bounds;survey;data streams;streaming | I don't know if there's a list of canonical hard problems, but there is a list of open problems in streaming as maintained by Andrew McGregor. This is not limited to the specific models you're referring to though. |
_codereview.147937 | I have a table with over 1,000,000 records. I need to replace any names in the text fields with aliases to help de-identify the data. For this example, let's assume the table is TemporaryTest and has two fields: Id (the key field) and IndexedXML (the text field).I have a second table, AppellationSubstitution, that has the following columns: TextEntry (a name needing replacement), Length (length of TextEntry), Replacement (the replacement name, which may be of a different length). That table has about 110,000 rows.The first step I use is (the regex matches words in the text field -- it looks a bit odd because of some odd characters that show up in this database):SELECT id, matchindex, matchlength, replacement FROM TemporaryTest CROSS APPLYmaster.dbo.Regexmatches('([Xx]-)?[\w-[0-9_]]{2,}(-[\w-[0-9_]]{2,})?(''[\w-[0-9_]])?', [IndexedXML], master.dbo.Regexoptionenumeration(0, 0, 1, 1, 0, 0, 0, 0, 0)) INNER JOIN dbo.appellationsubstitution ON match = textentry ORDER BY Id, MatchIndex DESC;--if replace in forward order, insertion point gets moved This produces a table with over 100,000 rows, which the following shows a few lines:Id matchindex matchlength replacement99309 122 5 Demarcus108639 106 5 Demarcus109809 84 6 Rehbein110373 89 7 Reginald111156 105 5 Demarcus112452 129 6 Thie112896 113 6 Diberardino112896 92 6 Diberardino113503 119 3 RubinThe full procedure I'm currently trying out is:SET NOCOUNT ON;SET XACT_ABORT ON;BEGIN TRANSACTION;DECLARE ReplaceCursor CURSOR LOCAL FORSELECT id, matchindex, matchlength, replacementFROM TemporaryTest CROSS APPLYmaster.dbo.Regexmatches('([Xx]-)?[\w-[0-9_]]{2,}(-[\w-[0-9_]]{2,})?(''[\w-[0-9_]])?', [IndexedXML], master.dbo.Regexoptionenumeration(0, 0, 1, 1, 0, 0, 0, 0, 0)) INNER JOIN dbo.appellationsubstitution ON match = textentry ORDER BY Id, MatchIndex DESC;--if replace in forward order, insertion point gets moved DECLARE @Rid int, @Rmi AS int, @Rml AS int, @Rrep AS nvarchar(255);OPEN ReplaceCursor;FETCH NEXT FROM ReplaceCursor INTO @Rid, @Rmi, @Rml, @Rrep;WHILE @@FETCH_STATUS = 0BEGIN UPDATE TemporaryTest Set IndexedXML = STUFF([IndexedXML],@Rmi+1,@Rml,@Rrep) WHERE Id = @Rid; FETCH NEXT FROM ReplaceCursor INTO @Rid, @Rmi, @Rml, @Rrep;END;CLOSE ReplaceCursor;DEALLOCATE ReplaceCursor;COMMIT TRANSACTIONThis works, but takes a very long time to run (over an hour and not yet completed), and IndexedXML is one of the smallest text fields I have in the production database.I resorted to using a cursor as I didn't know any other way to manage sequential STUFF calls on the same cell, where subsequent STUFF calls use the result of the previous ones.Am I taking the right course with this, or is there a faster/cleaner way of achieving this? | Replacing names in text fields with aliases to help de-identify data | sql;sql server;t sql | null |
_webmaster.18110 | Possible Duplicate:How to choose between web hosting and cloud hosting? What the difference between a shared host and a cloud server.I have a url http://domain.com and with a shared host, easly I have FTP details where I can upload everything on the server. Is is the same with cloud server or is it the same as amazon Cloudfront where you haven't got FTP details etc? What are the differences in terms of speed?Thanks alot | Shared Host VS Cloud server | cloud hosting | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.