id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_webmaster.85564
I don't quite understand why some Schema.org examples use <meta> instead of say <span>. For example:<meta itemprop=startDate content=2016-04-21T20:00> Thu, 04/21/16 8:00 p.m.Source: https://schema.org/EventIf my current markup is:<li>Jan 13-15, 2016</li>Do I need to use meta or can I just add the Schema itemprop and content stuff inside the <li>? And what's the reason so I know when I will need to use the <meta>?
Why use meta for some Schema markup?
html;meta tags;schema.org
For Microdata, meta and link elements should be used if you dont want to display the value of the property on your page.This is typically the case for properties that expect a value that is not human-readable, for example URIs that represent accepted payment/delivery methods (= good case for link), or ISO 4217 codes that represent currencies (= good case for meta).The example with the startDate property would ideally use the time element instead, as this is what should be used for dates/times, and it allows to specify the machine-readable format in the datetime attribute:<time itemprop=startDate datetime=2016-04-21T20:00> Thu, 04/21/16 8:00 p.m.</time>For your own example, you could also use time elements, but because of your chosen format, it might not be very elegant:<li> Jan <time itemprop=startDate datetime=2016-01-13>13</time>-<time itemprop=endDate datetime=2016-01-15>15</time>, 2016</li>The alternative with meta elements could look like:<li> Jan 13-15, 2016 <meta itemprop=startDate content=2016-01-13 /> <meta itemprop=endDate content=2016-01-15 /></li>Which one of those to use is a semantic markup question; it doesnt affect the extracted Microdata/Schema.org.
_softwareengineering.150145
We have an intranet site which was done in .net with plenty of functionality but management wants it to look more visually attractive and get the graphic designer involved. The graphic designer is NOT a programmer nor has any desire to learn how to code. She would be updating the main page only. I was trying to figure out how to make it easy for her to update the site. I was looking into Joomla but it requires PHP, MySQL, and Apache. Our box is .net/iis/sql. Does anyone have experience with this? Just a bit concerned about compatibility issues. or maybe there is an easier way. I'm more of a back end guy than a graphics guy.
What is the best way to allow a non-coding designer to design intranet web pages?
web design;gui design
null
_webmaster.98978
How to do this with regular expression?Old -> Newhttp://www.example.com/cat1/cat2/cat3/tool-model-10 -> http://www.example.com/tool/tool-model-10http://www.example.com/cat1/cat2/cat4/tool-model-11 -> http://www.example.com/tool/tool-model-11http://www.example.com/cat1/cat2/tool-model-12 -> http://www.example.com/tool/tool-model-12http://www.example.com/cat5/cat6/tool-model-13 -> http://www.example.com/tool/tool-model-13http://www.example.com/cat7/tool-model-14 -> http://www.example.com/tool/tool-model-14I've tried this:Redirect 301 /cat1/cat2/cat3/tool-model-10 http://www.example.com/tool/tool-model-10Redirect 301 /cat1/cat2/cat4/tool-model-11 http://www.example.com/tool/tool-model-11 Redirect 301 /cat1/cat2/tool-model-12 http://www.example.com/tool/tool-model-12 Redirect 301 /cat5/cat6/tool-model-13 http://www.example.com/tool/tool-model-13Redirect 301 /cat7/tool-model-14 http://www.example.com/tool/tool-model-14I understand that logi should be:divide URL string on 2 strings: 1 and 2If first URL string 1 contains tool-model- at the end AND does not contain tool catalog at the beginning then make redirect to http://www.example.com/tool/tool-model- PLUS two digits (string 2).
.htaccess 301 redirect dynamic URL with regex?
htaccess;301 redirect;regular expression
If first url string 1 contain tool-model- at the end AND does not contain tool catalog at the beginning make redirect to http://www.example.com/tool/tool-model- PLUS two digits (string 2)To simplify/combine your redirects into a single ruleset I would use mod_rewrite, rather than mod_alias (Redirect or RedirectMatch) since you want a condition that says does not contain tool (which is tricky with RedirectMatch). Try something like the following in your root .htaccess file:RewriteEngine OnRewriteCond %{REQUEST_URI} !^/tool/RewriteRule /(tool-model-\d\d)$ /tool/$1 [R=302,L]This states for any URL that ends /tool-model-NN and does not start /tool/ then redirect to /tool/tool-model-NN. $1 in the substitution is a backreference to the captured group (ie. (tool-model-\d\d)) in the RewriteRule pattern (a regex).NB: I've used a 302 (temporary) redirect above. Change this to 301 (permanent) when you are sure it's working OK. 301 redirects are cached by the browser, so can make testing awkward. (So, you will need to clear your browser cache before testing the above directives.)Also, if you are currently using mod_alias Redirect (or RedirectMatch) for other redirects then it would be advisable to also convert these to mod_rewrite RewriteRule directives. The reason being that different modules run at different times, regardless of the order in the .htaccess file. So, you can get some unexpected conflicts by combining redirects from both modules.
_webmaster.99875
I have been using non-www redirect in .htaccess for a couple of years now for my Wordpress site. I want to switch to redirecting to www because, among other reasons, a naked URL does not work with Cloudflare CDN. Will it hurt my SEO score?
SEO and www to non-www (and vice versa) AFTER having settled for some time in one of them
seo;redirects;wordpress;no www
As you'll be using a redirect from non www to www all the previous incoming links and URL's will still be working and pointing to the correct content, so your SEO scores should not be affected.The key here is that when ever changing URL's you have to have redirects (301) in place, so you wouldn't lose any SEO :)I'll just in case mention that you do use the redirect, as all your site's pages should only either be www or non www, otherwise it could be classified as duplicate content.
_softwareengineering.200041
When forming opinions, it is a good practice to follow scholastic tradition - think as hard as you can against the opinion you hold and try to find counter-arguments.However, no matter how hard I try, I just cannot find reasonable arguments in favor of antivirus (and related security measures) on development machines.Arguments against antivirus(AV) in development are plentiful:It is not uncommon for 1 minute build to take 10 times longer with AV onIn a conference talk, IntelliJ developers claim AV software is #1 suspect when their IDE is sluggishUnzipping comes with roughly 100 kb/s speed with AV onAV renders Cygwin completely unusable (vim takes 1 minute to open a simple file) AV blocks me from downloading useful files (JARs, DLLs) from colleagues' e-mailsI can't use multiple computers for development, since AV / security measures prevent me from unblocking portsAV kills performance of programs with high file turnover, such as Maven or AntLast, but not least - what does AV actually protect me from? I am not aware of my AV program ever stopping any security thread.If the reason is fear of disclosing NDA stuff - no AV can possibly prevent me from doing it if I set my mind to it.If the reason is fear of losing source code and/or documentation - there are distributed revision systems for this (there are at least 20 copies of our repo and we sync on daily basis).If the reason if fear of disclosing customer data - developers rarely work connected to real production databases, instead they are playing around in toy environments.Even if there are meaningful arguments in favor of having AV on development machines, they fall apart when faced with the ability to run a Virtual Machine in your paranoidly protected environment.Since I want to keep an open mind of the issue, could anyone present meaningful, strong argument in favor of Anti-virus software for developers?
Looking for meaningful, strong argument in favor of antivirus software on development machines
security;hardware;development environment
The one reason to use anti-virus software on development machines that trumps all your arguments is:To comply with security audits.Banks, government agencies, large regulated firms with sensitive data don't have a choice on this matter.
_unix.302620
I need to show the ethernet interfaces on a Centos 7 server. On centos 6.5, I was using this command (from another post)and it works fine on 6.5.ifconfig -a | sed -n 's/^\([^ ]\+\).*/\1/p' | grep -Fvx -e lo on Centos 7 the interface output now has a trailing : so my output look like this ifconfig -a | sed -n 's/^\([^ ]\+\).*/\1/p' | grep -Fvx -e loens32:lo:to remove the lo: I modified to this. which results in ens32:ifconfig -a | sed -n 's/^\([^ ]\+\).*/\1/p' | grep -Fvx -e lo:ens32:How can I remove the trailing : ? can this sed be modified? or other ideas
How can i modify this sed command to remove the trailing colon on the output
centos;sed;string;ifconfig
null
_datascience.21986
Why it's so that in convolutional neural networks we generally take the image dimensions of input image to be generally a square? We even do padding to make it happen. Why not different dimensions?What I understood is that computer computes multiplication and division (by 2) much faster than the rest.Can someone shed some light on this? Any link or reference will be appreciated. I already have CS231n notes and lecture slides.
Why CNN input images are often square shaped?
neural network;deep learning;convolution
null
_unix.259502
I'm migrating a machine to another boot drive with more space. I've done the following:sudo partclone.vfat -c -R -o partclone.sda1.vfat.img -s /dev/sdg1and then I created my partitions on the new device in parted, and then restored:sudo partclone.vfat -r -s partclone.sda1.vfat.img -o /dev/sdg1The new partition is larger than the one I cloned from.$ sudo parted /dev/sdg print 1Minor: 1Flags: File System: fat32Size: 1074MB (0.11%)Minimum size: 210MB (0.02%)Maximum size: 1000GB (100%)However, when I view the filesystem with df, it shows me something else:$sudo df -h extefi/Filesystem Size Used Avail Use% Mounted on/dev/sdg1 197M 42M 156M 22% /mnt/extefiIs there a command I can run to properly resize the filesystem to fill its partition?
Resize VFAT partition?
parted;vfat;partclone
null
_webapps.34056
Specifically, I'd like to see the amount of visits that it gets and the geographic region. Is that possible at all? Searching in Google it looks like it was possible at some point but for the life of me I can't find it in the interface.
How can I see statistics for a Google Slides presentation
analytics;google presentations
null
_softwareengineering.24464
My question here is relative to jobs for programmers.Why does employer still contract programmers if today we have a lot of good commercial system avaliable on the market?I want to be very clear at this point, this question is relative only to a system, more specially to ERP systems. Maybe this question looks a little bit useless, but right now I'm working and this doubt arose to me and my boss.I have a few answers to my own question, but I really would like to speculate this subject a bit more.Also I know, every good company needs a customized system, but ... the question is here. :-)Any answer will make me feel better. Thanks.
Programmer VS Commercial Systems (ERP)
erp
Do you realize how expensive some of those higher-end commercial systems can cost to buy in the first place? If companies are spending hundreds of thousands if not millions of dollars, don't you think they would want someone to help them get the most out of this big purchase?Paying for the customization is why the contractors come in and don't forget that the big guys like SAP and Oracle may well have other companies that work as System Integrators that help companies implement the system correctly at a rather high cost. Think of this as the difference between having a personal chef cook your meals and getting them in bulk from McDonald's. That personal chef can put in so many touches that while yes it is expensive, some people tend to believe you pay for what you get and want lots of little things that they do pay but they may be happy in the end.
_softwareengineering.344051
I'm new to DDD + CQRS, and I'm working in a project that has this implemented, but I wonder why the guy duplicates the models.I understand, that one is for writing (commands) and one is for reading, but both implement the same fields, except that ReadModel only has getters.Is there any advice against having the fields (id, name, socialnumber, etc) of a relational database AND getters in a model then inherit them in WriteModel and ReadModel?For example:Abstract UserModelUserReadModel inherits UserModelUserWriteModel inherits UserModel
Can readmodel and writemodel inherit from Model for fields in DDD + CQRS?
domain driven design;domain model;cqrs
null
_codereview.156120
I ran the following code through a Leetcode.com challenge and it says the runtime for the test cases is 119ms, which puts it at the back of the pack performance wise.The goal is to remove duplicates from a sorted array of Ints and return the count of the array without dups.func removeDuplicates(_ nums: inout [Int]) -> Int { nums = Array(Set(nums)).sorted() return nums.count}I thought my solution was pretty simple, but 119ms isn't so hot compared with the average of ~60-70ms. Is there a better way to do this?
Remove Duplicates from Array in Swift 3.0
performance;programming challenge;array;swift;set
Your code works correctly, as far as I can see. A small simplificationwould be func removeDuplicates(_ nums: inout [Int]) -> Int { nums = Set(nums).sorted() return nums.count}because sorted() can directly be applied to any collection of comparable elements and returns an array.However, your code does not take advantage of the fact that thegiven array is already sorted. Two intermediate collections (a setand an array) are created, and the new array is sorted.That can be improved.Since the array elements are sorted, you can traverse through allelements and only keep those which are different to the previousone. This leads to the following implementation:func removeDuplicates(_ nums: inout [Int]) -> Int { guard let first = nums.first else { return 0 // Empty array } var current = first var uniqueNums = [current] // Keep first element for elem in nums.dropFirst() { if elem != current { uniqueNums.append(current) // Found a different element current = elem } } nums = uniqueNums return uniqueNums.count}In addition, you can save memory by overwriting the elementsin the given array directly. If a different element is found then itis copied directly to its new position. At the end of the loop,surplus elements are removed:func removeDuplicates(_ nums: inout [Int]) -> Int { guard let first = nums.first else { return 0 // Empty array } var current = first var count = 1 for elem in nums.dropFirst() { if elem != current { nums[count] = elem current = elem count += 1 } } nums.removeLast(nums.count - count) return count}In my tests, the last two methods were about a factor 10 fasterthan yours.
_cs.47633
. Imagine two disks on the xy plane. Each disk is represented bythree numbers (the radius, the x coordinate of the center and the y coordinate of the center). All valuesfor this problem are real numbers. Your task is to determine if the two disks intersect.
How can can I find out if the two disks intersect in the plane?
algorithms
null
_unix.49895
I'm using rsync in my own C++ program by issueing the command system(rsync -rauzvq root@host:/folder);I use this for keeping multiple systems in sync. Now I have the problem that when a remote host shuts off and there it was still rsync-ing with my program, my program hangs for the period of the TCP timeout. So I thought, I would adjust the TCP timeout parameter for the rsync socket, but I can't figure out how (--sockopts isn't working).Another way of fixing this would involve making a forked system call and check whether the rsync pID still exists after a certain timeout, otherwise kill it. Only downside on this is that I can't check whether the process is genuinely syncing or just hanging on a TCP timeout?So, what would you guys try?
Adjusting rsync TCP timeout
rsync;tcp;socket
In your command line, rsync is not talking TCP directly, it's relying on ssh for the transmission.You can use:RSYNC_RSH='ssh -o ConnectTimeout=2 -o ServerAliveInterval=2 -o ServerAliveCountMax=2' rsync ...
_unix.274572
I have a huge file which contains BGP updates in the following fashion :BGP4MP|1043481872|A|64.200.199.3|7911|217.72.176.0/20|7911 8272 16102 16102 16102|IGP|64.200.199.3|0|0|7911:999 7911:7211|NAG||Basically, it is derived from using the route_btoa function.I want to plot a graph based on the 2nd and 3rd fields of this line (you can ignore everything else). The 2nd field indicates time and the third field indicates if it is an Announcement (A) or Withdrawal (W) - these are the only two cases. The graph is supposed to have as X-axis the time and Y-axis will be the number of BGP (A) - we ignore W- updates at that time. If anyone could help me plot this, that would be a great help! Thanks.
Using bash to plot a graph
bash;gnuplot
null
_codereview.150957
I am trying to keep the progression of the Review Queue Notifier moving forward. My next big move is to turn it into an extension for Chrome and FireFox and eventually Edge.I would like the Javascript for the code reviewed again to get me back into the groove of coding this extension/script.Here are the guts:$( document ).ready(function() { //Public Key var publicKey = '?key=hyEwZ8*W*OF7tQ3KYgNjzg(('; var sites; var ACTIVESITES;// = chrome.storage.sync.get(activeSites); GetSelectedSites(); getAllTehSitez(); function getAllTehSitez() { console.log(getAllTehSitez has been called); $.getJSON('http://api.stackexchange.com/2.2/sites' + publicKey + '&pagesize=100', function(data) { sites = data.items; isActiveSite(); }); } function isActiveSite() { console.log(isActiveSite has been called); chrome.runtime.sendMessage(getUrl, function(response) { var tabUrl = response.url; for (var site in sites) { if ((tabUrl == sites[site].site_url + '/review') && (ACTIVESITES.indexOf(sites[site].name.toLowerCase()) > -1)) { runRQN(); return; } } }); } function GetSelectedSites () { console.log(GetSelectedSites has been called); chrome.storage.sync.get({ activeSites: Code Review }, function(item) { ACTIVESITES = item.activeSites; }); } function runRQN () { console.log(runRQN has been called) Notification.requestPermission(); var DELAY = 300 * 1000; //120,000 milliseconds = 2 Minutes function getDelayAmount() { chrome.storage.sync.get({ refreshRate: 300000 }, function(item){ DELAY = item.refreshRate; }); } getDelayAmount(); setTimeout(function(){ window.location.reload(); }, DELAY); console.log(DELAY); var notificationTitle = (document.title.split(' - ')[1] + ' Review Queue').replace(' Stack Exchange', '.SE'); var reviewCount = 0; var reviewItems = document.getElementsByClassName('dashboard-num'); for (var i = 0; i < reviewItems.length; i++){ if (reviewItems[i].parentNode.className != 'dashboard-count dashboard-faded'){ reviewCount += parseInt((reviewItems[i].getAttribute(title)).replace(',', ''), 10); console.log(reviewItems[i]); } } console.log(reviewCount); var image = chrome.extension.getURL('Icon2.jpg'); if (reviewCount > 0) { var details = { body: reviewCount + ' Review Items', icon: image } var n = new Notification(notificationTitle, details ); setTimeout(n.close.bind(n), 100000); // Magic number is time to notification disappear } }}); Stack Apps QuestionGitHub RepositoryThis is a follow-up to the following questions, kind of...First QuestionSecond Question
Queue Notifier Extension Script
javascript;google chrome;firefox
null
_codereview.79262
I implemented the Simple Factory Pattern with some unit tests, but I'm with a feeling that I did something wrong and that I can improve it.Tell me what you think about the code (source and tests).PizzaFactoryTest.php:<?php namespace Pattern\SimpleFactory;use PHPUnit_Framework_TestCase;class PizzaFactoryTest extends PHPUnit_Framework_TestCase { private $pizzaFactory; public function setUp() { $this->pizzaFactory = new PizzaFactory(); } public function testPizzaFactoryShouldMakeAPizza() { $pizza = $this->pizzaFactory->make('greek'); $this->assertInstanceOf('Pattern\SimpleFactory\Pizza', $pizza); } public function testPizzaFactoryShouldReturnNullWhenMakingANonexistentPizza() { $pizza = $this->pizzaFactory->make('nonexistent pizza'); $this->assertNull($pizza); }}PizzaFactory.php:<?php namespace Pattern\SimpleFactory;/** * @package Pattern\SimpleFactory */class PizzaFactory { /** * @var array */ private $pizzas = [ 'greek' => 'Pattern\SimpleFactory\Pizza\Greek', 'pepperoni' => 'Pattern\SimpleFactory\Pizza\Pepperoni', ]; /** * @param string $name * @return null|Pizza */ public function make($name) { if (isset($this->pizzas[$name])) { return new $this->pizzas[$name]; } return null; }}PizzaStoreTest.php:<?php namespace Pattern\SimpleFactory;use PHPUnit_Framework_TestCase;class PizzaStoreTest extends PHPUnit_Framework_TestCase { private $pizzaFactory; private $pizzaStore; public function setUp() { $this->pizzaFactory = $this->getMock(PizzaFactory::class); $this->pizzaStore = new PizzaStore($this->pizzaFactory); } public function testPizzaStoreShouldReturnTheRequestedPizzaWhenOrdered() { $this->pizzaFactory->expects($this->once())->method('make')->with('greek'); $this->pizzaStore->order('greek'); }}PizzaStore.php:<?php namespace Pattern\SimpleFactory;/** * @package Pattern\SimpleFactory */class PizzaStore { /** * @var PizzaFactory */ private $factory; /** * @param PizzaFactory $factory */ function __construct(PizzaFactory $factory) { $this->factory = $factory; } /** * @param string $name * @return null|Pizza */ public function order($name) { return $this->factory->make($name); }}PizzaTest.php:<?php namespace Pattern\SimpleFactory;use PHPUnit_Framework_TestCase;class PizzaTest extends PHPUnit_Framework_TestCase { private $pizza; public function setUp() { $this->pizza = $this->getMockForAbstractClass('Pattern\SimpleFactory\Pizza'); } public function testPizzaShouldSetAndReturnTheExpectedName() { $pizzaName = 'Greek Pizza'; $this->pizza->setName($pizzaName); $this->assertEquals($pizzaName, $this->pizza->getName()); } public function testPizzaShouldSetAndReturnTheExpectedDescription() { $pizzaDescription = 'A Pepperoni-style pizza with dough, tomato, and cheese'; $this->pizza->setDescription($pizzaDescription); $this->assertEquals($pizzaDescription, $this->pizza->getDescription()); }}Pizza.php:<?php namespace Pattern\SimpleFactory;/** * @package Pattern\SimpleFactory */abstract class Pizza { /** * @var string */ private $name; /** * @var string */ private $description; /** * @return string */ public function getName() { return $this->name; } /** * @param string $name */ public function setName($name) { $this->name = $name; } /** * @return string */ public function getDescription() { return $this->description; } /** * @param string $description */ public function setDescription($description) { $this->description = $description; }}Pizza/Greek.php<?php namespace Pattern\SimpleFactory\Pizza;use Pattern\SimpleFactory\Pizza;/** * @package Pattern\SimpleFactory\Pizza */class Greek extends Pizza { function __construct() { parent::setName('Pizza Greek'); parent::setDescription('A Greek-style pizza with feta cheese, onion, olive and tomato'); }}Pizza/Pepperoni.php<?php namespace Pattern\SimpleFactory\Pizza;use Pattern\SimpleFactory\Pizza;/** * @package Pattern\SimpleFactory\Pizza */class Pepperoni extends Pizza { function __construct() { parent::setName('Pizza Pepperoni'); parent::setDescription('A Pepperoni-style pizza with dough, tomato, and cheese'); }}
Simple Pizza Factory with tests
php;tdd;phpunit
To me, this looks pretty much like a by-the-book example of the factory pattern. There are, however, a few areas that could be improved.Missing Test PathsI noticed that you have no test in PizzaFactoryTests which ensures that the produced Pizza is of the right type. As your tests states, you might be returning a Pizza, but not necessarily the one you would expect.public function testPizzaFactoryShouldMakeAGreekPizza(){ $pizza = $this->pizzaFactory->make('greek'); $this->assertInstanceOf('Pattern\SimpleFactory\Pizza\Greek', $pizza);}EncapsulationI noticed that you use setters on the parent class to initialize your specialized classes. This works but breaks encapsulation. Instead, I would keep the setters private to the base class and expose a constructor that can take care of setting the properties. This also has the upside of enforcing that all pizzas are created equal. After all, in your system, is a pizza really a pizza when it has no name or description?class Pepperoni extends Pizza { function __construct() { parent::__construct( 'Pizza Pepperoni', 'A Pepperoni-style pizza with dough, tomato, and cheese' ); }}MockingYou might want your factory to be able to return mocked objects when testing. This is useful to ensure that you are testing the factory in isolation, specially if the classes it instantiate are heavy to initialize. In that case, dependency injection is the way to go. There are many ways that you could accomplish this. In your case, you could inject the class path so that it points to a mocking pizza object.class PizzaFactory { private $pizzas = []; function __construct($pizzas) { $this->$pizzas = $pizzas; } //...}// Usage$properFactory = new PizzaFactory([ 'greek' => 'Pattern\SimpleFactory\Pizza\Greek', 'pepperoni' => 'Pattern\SimpleFactory\Pizza\Pepperoni',]);$mockedFactory = new PizzaFactory([ 'greek' => 'Pattern\SimpleFactory\Pizza\Mock', 'pepperoni' => 'Pattern\SimpleFactory\Pizza\Mock',]);This is a simple solution that will let you mock any path to the one you want, but it also leaks part of the internal logic. An alternative solution is to mock the instantiation operation entirely using an anonymous function.class PizzaFactory { private $pizzas = [ 'greek' => 'Pattern\SimpleFactory\Pizza\Greek', 'pepperoni' => 'Pattern\SimpleFactory\Pizza\Pepperoni', ]; private $maker = null; function __construct($maker) { $this->$maker = $maker; } public function make($name) { if (isset($this->pizzas[$name])) { return $maker($this->pizzas[$name]); } return null; }}// Usage$properFactory = new PizzaFactory(function($className) { return new $className;});$mockedFactory = new PizzaFactory(function($className) { return new 'Pattern\SimpleFactory\Pizza\Mock';});There are probably other ways to mock the dependency on new but I am no aware of them. In the end, it all boils down to your requirement and how the PizzaFactory will evolve over time.
_codereview.125283
This is my new version of my Tic Tac Toe game written in C++. I tried to follow community advice by separating I/O from the game logic and view (MCV). The code works great, and I am looking to see if I followed the model control view design pattern correctly.TicTacToe.h#ifndef TICTACTOE#define TICTACTOE#include<string>class TicTacToe{ std::string boardInfo; char player1; char player2;public: TicTacToe(); ~TicTacToe(); void markBoard(const size_t &, const char&); void setPlayerMark(const char &); char getMark(const int &); char checkWin(const int&); char positionValue(const size_t&);};#endif TicTacToe.cpp#include TicTacToe.hTicTacToe::TicTacToe(){ boardInfo = 123456789; player1 = 'X'; player2 = 'O';}TicTacToe::~TicTacToe(){}void TicTacToe::markBoard(const size_t & boardIndex, const char &playerMark) { boardInfo[boardIndex - 1] = playerMark;}// 'X' or 'O' = game win, 'C' = catsgame, and 'N' = no winchar TicTacToe::checkWin(const int &turnCount) { //winning solutions involving middle square for (size_t i = 0, k = 8; i <= 3 && k >= 5; i++, k--) { if (boardInfo[4] == boardInfo[i] && boardInfo[i] == boardInfo[k]) { return boardInfo[4]; } } //remaining winning solutions if (boardInfo[2] == boardInfo[1] && boardInfo[1] == boardInfo[0]) { return boardInfo[2]; } if (boardInfo[2] == boardInfo[5] && boardInfo[5] == boardInfo[8]) { return boardInfo[2]; } if (boardInfo[6] == boardInfo[3] && boardInfo[3] == boardInfo[1]) { return boardInfo[6]; } if (boardInfo[6] == boardInfo[7] && boardInfo[7] == boardInfo[8]) { return boardInfo[6]; } //catsgame int totalTurns = 9; //total possible turns if (turnCount > totalTurns) { return 'C'; } return 'N';}void TicTacToe::setPlayerMark(const char &mark) { player1 = mark; //the other player will always receives opposite mark switch (mark) { case 'X': player2 = 'O'; break; case 'x': player2 = 'o'; break; case 'O': player2 = 'X'; break; case 'o': player2 = 'x'; break; }}char TicTacToe::positionValue(const size_t &index) { return boardInfo[index];}char TicTacToe::getMark(const int &player) { if (player == 1) { return player1; } if (player == 2) { return player2; } return 'N';}Game.h#ifndef GAME#define GAME#include <iostream>#include <limits>#include TicTacToe.hclass Game{ TicTacToe board1;public: Game(); ~Game(); void drawBoard(); void turn(int &, TicTacToe &); void setMarks(); void run();};#endifGame.cpp#include Game.hGame::Game(){}Game::~Game(){}void Game::drawBoard() { std::cout << << board1.positionValue(0) << | << << board1.positionValue(1) << | << << board1.positionValue(2) << \n; std::cout << ___|___|___ \n; std::cout << << board1.positionValue(3) << | << << board1.positionValue(4) << | << << board1.positionValue(5) << \n; std::cout << ___|___|___ \n; std::cout << << board1.positionValue(6) << | << << board1.positionValue(7) << | << << board1.positionValue(8) << \n; std::cout << | | ;}void Game::turn(int &turnCount, TicTacToe &board1) { char mark; size_t spaceChoice; if (turnCount % 2) { mark = board1.getMark(1); //player 1's mark turnCount++; std::cout << \nPlayer 1's turn\nChoose space to mark: ; } else { mark = board1.getMark(2); //player 2's mark turnCount++; std::cout << \nPlayer 2's turn\nChoose space to mark: ; } bool inputpass = false; //used to check if the input is passed, failed, or not marked while (!inputpass) { //tests input type if (std::cin >> spaceChoice) { //checks domain if (spaceChoice > 0 && spaceChoice < 10) { char check = board1.positionValue(spaceChoice-1); //used to check if space has been marked if (check != 'X' && check != 'x' && check != 'O' && check != 'o') { board1.markBoard(spaceChoice, mark); inputpass = true; } else { std::cout << \nSPACE ALREADY MARKED\nTry again: ; } } else { std::cout << \nINNCORRECT SPACE\nTry agian: ; } } //if the input type fails else { std::cout << \nINCORRECT INPUT TYPE\nTry agian:; std::cin.clear(); //clears input fail state std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } }}void Game::setMarks() { char tempMark; bool inputPass = false; while (!inputPass) { if (std::cin >> tempMark) { if (tempMark == 'X' || tempMark == 'x' || tempMark == 'O' || tempMark == 'o') { board1.setPlayerMark(tempMark); inputPass = true; } else { std::cout << MARK MUST BE X OR O\nTry again: ; } } else { std::cout << INCCORECT INPUT TYPE\nTry again: ; } } }void Game::run() { std::cout << Enter wether player 1 is 'X' or 'O': ; setMarks(); char gameWin = 'N'; int turnCount = 1; drawBoard(); while (gameWin != 'X' && gameWin != 'x' && gameWin != 'O' && gameWin != 'o' && gameWin != 'C') { turn(turnCount, board1); gameWin = board1.checkWin(turnCount); drawBoard(); } if (gameWin != 'C') { std::cout << ((board1.getMark(1) == gameWin) ? \nThe winner is: Player 1! : \nThe winner is: Player 2!); } else std::cout << \nCATS GAME!;}main.cpp#include <iostream>#include Game.hvoid pause();int main() { Game game1; game1.run(); pause();} void pause() { char end; std::cout << \nPress any key followed by ENTER to continue...; std::cin >> end;}
Tic Tac Toe C++ MVC design
c++;object oriented;mvc;tic tac toe
Good that you got around the #pragma once problem.My IDE generates #ifndef TICTACTOE_H_#define TICTACTOE_H_#endif /* TICTACTOE_H_ */I thing that's a little more unique, possibly better.MAGIC NUMBERS:You still have a lot of magic numbers in your code: for (size_t i = 0, k = 8; i <= 3 && k >= 5; i++, k--) { if (boardInfo[4] == boardInfo[i] && boardInfo[i] == boardInfo[k]) { return boardInfo[4]; } } //remaining winning solutions if (boardInfo[2] == boardInfo[1] && boardInfo[1] == boardInfo[0]) { return boardInfo[2]; } if (boardInfo[2] == boardInfo[5] && boardInfo[5] == boardInfo[8]) { return boardInfo[2]; } if (boardInfo[6] == boardInfo[3] && boardInfo[3] == boardInfo[1]) { return boardInfo[6]; } if (boardInfo[6] == boardInfo[7] && boardInfo[7] == boardInfo[8]) { return boardInfo[6]; } //catsgame int totalTurns = 9; //total possible turns if (turnCount > totalTurns) { return 'C'; }In the public section of TicTacToe.h you should defineconst int MAX_TURNS = 9;There are coding standards that apply to symbolic constant names, this link is one, but there are others. It doesn't do as much good where it is defined in checkWin().Code which may lead to possible problems:Your switch statement doesn't have a default case, generally switch statements should contain a default case which handles all cases not specified and can be used to provide error messages. switch (mark) { case 'X': player2 = 'O'; break; case 'x': player2 = 'o'; break; case 'O': player2 = 'X'; break; case 'o': player2 = 'x'; break; default: std::cerr << Please provide the correct input << std::endl; break; }Variable Names:What are i and k in the following code? for (size_t i = 0, k = 8; i <= 3 && k >= 5; i++, k--) { if (boardInfo[4] == boardInfo[i] && boardInfo[i] == boardInfo[k]) { return boardInfo[4]; } }Fix the Typos:Game.cpp: wether => whether, agian => again.Model View Controller:Generally a MVC design pattern has a set of classes for the Model, a set of classes for the view and a set of classes for the control. The classes in this implement contain elements of all 3.What you really need to do is separate the logic of the game from the display mechanism. An example, Game contains both game control and display. The reason for this is that it allows your model classes to be reused on different operating systems using different display mechanisms (console text as you are now or graphics).Amoung other things your controller should contain the code whether or not to play another game (remove pause() from Main.cpp, add playAnotherGame() to a controller class.The controller class should call both the model and view classes. The view classes should only handle formatting the output, the model should have all the internal game functionality.Let the Compiler do more work for you:In Game.h you have Game(); and ~Game(); and in Game.cpp you haveGame::Game(){}Game::~Game(){}Since you are not doing anything special in either the constructor or distructoryou can use the default constructor and distructor if you are using C++11 or C++14.This allows you to declare/define your constructors only in your header file, and let the C++ compiler generate the proper constructors and destructors. The less code you have to write, the less error prone it is.In C++11 or C++14 class Game{ TicTacToe board1;public: Game() = default; ~Game() = default;};Functions in Main.cpp:If you reverse the order of pause() and main() in Main.cpp you don't need the function prototype of void pause(); prior to main(). Having main() as the last function in the file is fairly common for this reason.In the past on certain operating systems, pause(); has been a system call. I would avoid it's use, although the system call did return int so the signature is different. It also isn't the most descriptive name you could give this function.
_unix.48729
ProblemI'm creating a bootable iso from a YUMI USB drive to burn on DVD's for friends. More info here.I took the grldr and menu.lst from a bootable XBoot iso, but now I'm trying to figure out a way to get from the menu.lst to the syslinux.cfg menu? Is this completely nonsensical? Am I on the right lines / how might I be able to do this?As a little test I have the following in my menu.lst:### MENU STARTlabel Syslinux Menukernel vesamenu.c32append /multiboot/syslinux.cfg MENU SEPARATOR ### MENU ENDBut I end up at a grub4dos command prompt rather than my syslinux.cfg menu! No real idea what I'm doing in all honesty, just trial and error and would love a bit of guidance!
How can I get from menu.lst to syslinux.cfg?
grub;syslinux
null
_unix.44426
I have about 10 php.ini files on my system, located all over the place, and I wanted to quickly browse through them. I tried this command:locate php.ini | xargs viBut vi warns me Input is not from a terminal and then the console starts getting really weird - after which I need to press :q! to quit vi and then disconnect from the ssh session and reconnect to have the console behave normally again.I think that I sort of understand what's happening here - basically the command hasn't finished when vi started so the command maybe hasn't finished and vi doesn't think that the terminal is in normal mode.I have no idea how to fix it. I have searched Google and also unix.stackexchange.com with poor luck.
xargs and vi - Input is not from a terminal
command line;terminal;vi;xargs
I hate xargs, I really wish it'd just die :-)vi $(locate php.ini)Note: this will have issues if your file paths have spaces, but it is functionally equivalent to your command.This next version will properly handle spaces but is a bit more complicated (newlines in file names will still break it though)(IFS=$'\n'; vi $(locate php.ini))Explanation:What's happening is that programs inherit their file descriptors from the process that spawned them. xargs has its STDIN connected to the STDOUT of locate, so vi has no clue what the original STDIN really in.
_cs.69296
I am working on an NP-Hard problem. The state-of-the-art algorithm for my problem runs in O(3^n) time using dynamic programming approach. I changed the way the dynamic program works for my problem and it reduces the time complexity to O(n2^n). But, the main problem with my approach is the optimal result. More than 95% of the time my approach is giving the optimal output. Is there any way to publish my work by showing the results for the different data set. I am unable to prove the approximation ratio. Please give me any suggestion regarding this. Note: The Input size is 2^n
Ways to publish new result for NP-complete problem
algorithms;np complete
null
_softwareengineering.197313
I am test-driving a method that is to generate a collection of data objects. I want to verify that the properties of the objects are being set correctly. Some of the properties will be set to the same thing; others will be set to a value which is dependent on their position in the collection. The natural way to do this seems to be with a loop. However, Roy Osherove strongly recommends against using logic in unit tests (Art of Unit Testing, 178). He says:A test that contains logic is usually testing more than one thing at a time, whicfh isn't recommended, because the test is less readable and more fragile. But test logic also adds complexity that may contain a hidden bug.Tests should, as a general rule, be a series of method calls with no control flows, not even try-catch, and with assert calls.However, I can't see anything wrong with my design (how else do you generate a list of data objects, some of whose values are depended on where in the sequence they are?—can't exactly generate and test them separately). Is there something non-test-friendly with my design? Or am being too rigidly devoted to Osherove's teaching? Or is there some secret unit test magic I don't know about that circumvents this problem? (I'm writing in C#/VS2010/NUnit, but looking for language-agnostic answers if possible.)
How to unit test method that returns a collection while avoiding logic in the test
unit testing;loops;logic;collections
TL;DR:Write the testIf the test does too much, the code may do too much too.It may not be a unit test (but not a bad test).The first thing for testing is about dogma being unhelpful. I enjoy reading The Way of Testivus which points out some issues with dogma in a lighthearted way.Write the test that needs to be written.If the the test needs to be written some way, write it that way. Attempting to force the test into some idealized test layout or not have it at all is not a good thing. Having a test today that tests it is better than having a perfect test some later day.I will also point to the bit on the ugly test:When the code is ugly, the tests may be ugly.You dont like to write ugly tests, but ugly code needs testing the most.Dont let ugly code stop you from writing tests, but let ugly code stop you from writing more of it.These can be considered truisms to those who have been following for a long time... and they just become ingrained in the way of thinking and writing tests. For people that haven't been and are trying to get to that point, reminders can be helpful (I even find re-reading them helps me avoid getting locked into some dogma).Do consider that when writing an ugly test, if the code it may be an indication that the code is trying to do too much too. If the code that you are testing is too complex to be properly exercised by writing a simple test, you might want to consider breaking the code into smaller parts that can be tested with the simpler tests. One should not write a unit test that does everything (it might not be a unit test then). Just as 'god objects' are bad, 'god unit tests' are bad too and should be indications to go back and look at the code again.You should be able to exercise all the code with reasonable coverage through such simple tests. Tests that do more end to end testing that deal with larger questions (I have this object, marshalled into xml, sent to the web service, through the rules, back out, and unmarshalled) is an excellent test - but it certainly isn't a unit test (and falls into the integration testing realm - even if it has mocked services that it calls and custom in memory databases to do the testing). It may still use the XUnit framework for testing, but the testing framework doesn't make it a unit test.
_softwareengineering.211635
For my simple MUD client I'm using Apache Telnet (no, not ssh). A mud client is a strange beast:Generally, a MUD client is a very basic telnet client that lacks VT100 terminal emulation and the capability to perform telnet negotiations. ... Standard features seen in most MUD clients include ANSI color support, aliases, triggers and scripting. - WikipediaI would like for a not-yet-written Controller to have a reference to TelnetConnection and just use it for a higher level of abstraction for I/O, but all attempts to prise this class apart fail for me. TelnetConnection seems to take on responsibility for everything, and then some, and just keep growing.package telnet;import java.io.IOException;import java.io.OutputStream;import java.net.InetAddress;import java.net.SocketException;import java.util.Deque;import java.util.Observable;import java.util.Observer;import java.util.logging.Logger;import org.apache.commons.net.telnet.TelnetClient;import player.GameAction;import player.DataFromRegex;import player.Regex;public class TelnetConnection implements Observer { private static Logger log = Logger.getLogger(TelnetConnection.class.getName()); private TelnetClient telnetClient = new TelnetClient(); private InputOutput inputOutput = new InputOutput(); private Regex regexParser = new Regex(); private DataFromRegex data = null; private Logic logic = new Logic(); public TelnetConnection() { init(); } private void init() { try { int port = 3000; InetAddress host = InetAddress.getByName(rainmaker.wunderground.com); telnetClient.connect(host, port); inputOutput.readWriteParse(telnetClient.getInputStream(), telnetClient.getOutputStream()); } catch (SocketException ex) { } catch (IOException ex) { } inputOutput.addObserver(this); } private void sendAction(GameAction action) throws IOException { log.info(action.toString()); byte[] actionBytes = action.getAction().getBytes(); OutputStream outputStream = telnetClient.getOutputStream(); outputStream.write(actionBytes); outputStream.write(13); outputStream.write(10); outputStream.flush(); } private void sendActions(Deque<GameAction> gameActions) { while (!gameActions.isEmpty()) { GameAction action = gameActions.remove(); try { sendAction(action); } catch (IOException ex) { } } } @Override public void update(Observable o, Object arg) { String line = null; if (o instanceof InputOutput) { line = inputOutput.getLine(); log.fine(line); data = regexParser.parse(line); Deque<GameAction> gameActions = logic.getActions(data); sendActions(gameActions); } } public static void main(String[] args) { new TelnetConnection(); }}Part of the difficulty lies within the InputOutput class, which is adapted from IOUtil from Apache. (For some reason, I cannot include the link to to the Apache source code.)Once I send the InputStream to InputOutput there needs to be callback using Observable to then send the String data for matching and searching? And then get back what after matching and searching the text?The trick being, in terms of I/O:capture console inputprint remote output from the MUD server to the console like regular telnetsome regex/etc on the remote output, concurrent with open, unterminated streams. This last requirement seems to make an odd beast for which I cannot envision the flow of control and data.
how to model a connection to a resource, with rudimentary event processing
java;design patterns;object oriented;mvc;observer pattern
If you wanted to simplify the nitty gritty implementation details into a class called TelnetConnection, I definitely think that would be a wise idea, however it may be that you cannot do it with simply one class. You may need to have a secondary class which deals with the asynchronous aspect of this. Lets call this class TelnetObserver which implements Observer.Now in this way, it is still asynchronous, which makes your life difficult, so lets make it synchronous. Make TelnetObserver implement Future<String>. The idea is that you call get() whenever you're ready for the next line of input (waiting until input is available if necessary).Of course this doesn't happen on its own, we must make it synchronous by using an instance of CountDownLatch. The purpose of CountDownLatch is to make a thread wait for an asynchronous job to finish within a certain timeframe. I found an excellent example of this implementation here.Once you have this, TelnetConnection will handle the connection logic. From there, TelnetConnection could also handle the parsing of the individual lines, but I wouldn't recommend it. I would create another class TelnetParser which does that for you, given the input from TelnetObserver. The resulting Object would then be returned to any listeners for input. Alternatively on output, you use the same TelnetParser to convert from an Object to a String which TelnetObserver could send. The basic interface for TelnetParser would likely look something like this:public class TelnetParser { public Object parseFromString(String) { ... } public String parseToString(Object) { ... }}The end result is that you have a model object which you can call upon to receive input or to send output. This returns control back to the caller, or in this case your class Controller! I hope that helps. Good luck in your endeavor!
_unix.81355
I'm on windows 7 using Cygwin.My script and text file are located in the same directory.#!/bin/bashwhile read name; doecho Name read from file - $namedone < /home/Matt/servers.txtI get this error and I don't know why because this is correct while loop syntax..?u0146121@U0146121-TPD-A ~/Matt$ ./script.sh./script.sh: line 4: syntax error near unexpected token `done'./script.sh: line 4: `done < /home/Matt/servers.txt'Can anybody tell me what I'm doing wrong? I think its because I'm on windows and using Cygwin.
Trouble with read line script in Cygwin
bash;shell script;cygwin
As pointed out by ott--, your script has CR LF line endings. This is more visible with od.$ od -c script0000000 # ! / b i n / b a s h \r \n w h i0000020 l e r e a d n a m e ; d o0000040 \r \n e c h o N a m e r e a0000060 d f r o m f i l e - $ n0000100 a m e \r \n d o n e < / h o0000120 m e / M a t t / s e r v e r s .0000140 t x t \r \n0000145As you can see, you have \r (carriage return) and \n (line feed) characters at the end of each line where you should only have \n characters. This is a result of a compatibility issue between Windows and *nix systems. Bash has difficulty dealing with the \r characters. You can fix your script by using a utility like dos2unix or by running the following line.sed -i 's/\r$//' script
_codereview.49892
I wrote a small program that aims to take some data from the MongoDB database and put them in the RabbitMQ queue.I tried to use only promise style but I am a beginner in JavaScript. Could you please help me to improve my first draft?var mongo = require('mongod');var amqp = require('amqplib');var _ = require('underscore');var TaskBroker = function () { this.queueName = 'task_queue'; this.rabbit = {}; this.mongo = {};};TaskBroker.prototype.connectRabbit = function() { return amqp.connect('amqp://localhost') .then(function (connection) { this.rabbit.connection = connection; return connection.createChannel() }.bind(this)) .then(function(channel) { this.rabbit.channel = channel; return channel.assertQueue(this.queueName, {durable: true}); }.bind(this))};TaskBroker.prototype.connectMongo = function(){ return function() { this.mongo.db = mongo('mongodb://127.0.0.1:27017/test', ['test']); return this.mongo.db; }.bind(this);};TaskBroker.prototype.connect = function () { return this.connectRabbit() .then(this.connectMongo());};TaskBroker.prototype.disconnect = function() { this.mongo.db.close(); this.rabbit.channel.close(); this.rabbit.connection.close();};TaskBroker.prototype.get_url_array = function(_data) { return _.chain(_data).pluck('probes').flatten().pluck('url').uniq().value();};TaskBroker.prototype.getTask = function() { return function () { return this.mongo.db.test.find({ 'status': 'ONGOING' }, { 'probes.url':1, '_id':0}) .then(function(results) { var url_array = []; if (results != null && results.length > 0) { url_array = this.get_url_array(results); } return this.mongo.db.test.find({ 'probes.url' : { $nin: url_array } }); }.bind(this)) .then(function(results) { if (results.length > 0) return results[0]; return null; }); }.bind(this);};TaskBroker.prototype.produceTask = function() { return function(_message) { if(_message != null) { _message.status = 'ONGOING'; this.rabbit.channel.sendToQueue(this.queueName, new Buffer(JSON.stringify(_message)), { deliveryMode: true }); return this.mongo.db.test.update({_id: _message._id}, { $set: { 'status': _message.status }}).then(function() { return _message; }); } return null; }.bind(this);};var taskBroker = new TaskBroker();taskBroker.connect() .then(function() { setInterval( function () { taskBroker.getTask()() .then(taskBroker.produceTask()) .then(function(result) { if(result == null) { console.log('No job to produce'); } else { console.log('Produce', result); } //console.log('Disconnected'); //taskBroker.disconnect(); } , function(error) { console.log('ERROR', error.stack); } ); } , 10000 ); });
NodeJS broker between MongoDB and RabbitMQ
javascript;node.js;promise;mongodb;rabbitmq
Interesting question, it was hard to find things I would do different.To Malachi's point, there are a few strings you could put in a config object, I would definitely add also 10000 to that config object as config.delay and your statuses like 'ONGOING'.Also, I would write this:.then(function(results) { if (results.length > 0) return results[0]; return null;});As.then(function(results) { return results[0] || null;});In the bottom part, you have very stylized code, very functional except for the 2 blocks. I would create 2 named functions called logResults and logError and use those.In produceTask, you are stretching quite a bit your horizontally, part of that is your atypical use of then on the same line ( different from the rest of your code ). I would counter-propose cutting the code a bit up:TaskBroker.prototype.produceTask = function() { var sendOptions = { deliveryMode: true }; var statusUpdate = { $set: { 'status': 'ONGOING' }}; return function(message) { if(!message) { return; } message.status = 'ONGOING'; var content = new Buffer(JSON.stringify(message)); this.rabbit.channel.sendToQueue(this.queueName, content , sendOptions); return this.mongo.db.test.update({_id: message._id}, statusUpdate) .then(function() { return message; }); }.bind(this);};I also declared sendOptions and statusUpdate outside of the returned function, there is no sense in re-creating these all the time.I also return early if there is no message to reduce arrow pattern codeI renamed _message to message, more on that laterAnonymous functions; you are using a number of anonymous functions. This becomes a problem if you have to analyze stack traces, simply add well named function names, and your code becomes that much easier to support:TaskBroker.prototype.connectRabbit = function() { return amqp.connect('amqp://localhost') .then(function onConnect(connection) { this.rabbit.connection = connection; return connection.createChannel() }.bind(this)) .then(function onChannelCreated(channel) { this.rabbit.channel = channel; return channel.assertQueue(this.queueName, {durable: true}); }.bind(this))};JsHint.com -> Use it, you have missing semi colons and bad line breaksCommented out code -> Dont do that in production codeConsole.log -> I would wrap this in a function where I can control whether I really want to log and where I can optionally also log into a file for later analysisI am not sure why you prefix some variables and parameters with underscore, I would advise against it. I know that mongo does this, to distinguish between mongo properties and data properties on an object, which is okay. But I see no good reason in your code for you to prefix variables/parameters with _Connection to Mongo db; your approach is okay for development, for quality and production I would get the details from the environment:this.mongo.db = mongo('mongodb://'+ process.env.MY_APP_MONGODB_HOST + '/myapp' , ['myapp']);You can writeif (results != null && results.length > 0) { url_array = this.get_url_array(results);}as if (results instanceof Array) { url_array = this.get_url_array(results);}I dont like url_array, I tend to take whatever is in the array and an 's' in JavaScript, but urls does not read much better in my mind. All I can say is that you should have some deep thoughts about that variable name.The usage of null; the usage of null is not idiomatic JavaScript. Consider converting your code to check for undefined instead. Since functions return undefined if you dont return something yourself, you can then avoid statements like return nullAll in all, I wish could write code like that when I am a beginner in a new language ;) Sometimes the code feels a bit forced into the promise style, but all in all this is pretty good.
_codereview.80203
I wrote this script a while back to generate press releases. It consumes a csv of data where each row contains the data for a country and fills in values in pre-written text based on the data. In its current state, it's basically a mad libs implementation with some hard coded conditionals. I'd like to refactor it to make it a bit smarter. I had the following ideas:create separate methods for static text paragraphs, paragraphs with conditionals and paragraphs with complex conditionals. How would I do this without constructing methods that take too many complicated arguments?use the NLTK for parsing plurals and verb tenses.Put this entire script into a Django app so that I don't have to do the tweaks myself every time they want new press releases.An abbreviated version of the script is below. I also welcome any changes to make it more Pythonic. #!/usr/bin/env python# -*- coding: utf-8 -*-import datetimeimport osimport sysimport csvfrom docx import Documentdef generate_documents(): with open(sys.argv[1], 'rb') as csvdata: reader = csv.DictReader(csvdata) timestamp = output/ + datetime.datetime.now().strftime('%d-%m-%Y_%H-%M-%S') os.makedirs(timestamp) os.chdir(timestamp) for row in reader: document = Document() name = row['country'].decode('cp1252') + .docx embargo = uEMBARGOED FOR RELEASE UNTIL {0}, DECEMBER {1} at {2} ({3}).format(row['weekday'], row['day'], row['time'], row['capital'].decode('cp1252').upper()) headline = Colored Walls Gain International Popularity subheadline = u {0} walls become common in {1}, citiznes think this development is {2}.format(row['color'], row['country'].decode('cp1252'), row['adjective']) if row['country'].decode('cp1252') == Andorra or row['country'].decode('cp1252') == Canada or row['country'].decode('cp1252') == Zimbabwe or row['country'].decode('cp1252') == Qatar or row['country'].decode('cp1252') == Gabon: cond_para_1 = u{0} Today, fewer people are painting walls {1} in {2}, according to a new, comprehensive analysis of trend from 188 countries..format(row['capital'].decode('cp1252').upper(), row['color1'], row['country'].decode('cp1252')) else: cond_para_1 = u{0} Today, fewer people are painting walls {1} and {2} in {3}, according to a new, comprehensive analysis of trend from 188 countries. .format(row['capital'].decode('cp1252').upper(), row['color1'], row['color2'], row['country'].decode('cp1252')) static = Everyone thinks this is very exciting if row['bestColor'] == yellow: cond_para_2 = Shockingly, residents of {0} prefer yellow walls..format(row['country'].decode('cp1252')) else: cond_para_2 = Most of the world likes white walls. # add the content to the document document.add_paragraph(embargo) document.add_paragraph().add_run(headline).bold = True document.add_paragraph().add_run(subheadline).italic = True document.add_paragraph(cond_para_1) document.add_paragraph(static) document.add_paragraph(cond_para_2) document.save(name)generate_documents()
Script to generate documents based on conditionals and CSV data
python;csv;natural language processing;ms word
Instead of decoding each field within the CSV as CP1252, you should open the entire file that way.I think that you should approach this more as a templating problem than a document-generation problem. Templating is a challenge that has been solved many times before though mainly generating HTML rather than OOXML. Authoring OOXML directly looks like it would be a pain though. Perhaps you would be better off using a templating solution (Django has one built in) to produce semantically correct HTML as an intermediate format. Then, you can convert the HTML into DOCX using one of many such tools available, involving Python or not.Basically, that strategy would decompose one programming headache into two solved problems.
_codereview.6383
I tried creating a quick tooltip plugin using the jquery and jquery ui position. Is the way I have used the enclosure are right and is the use of position right since in ff it seem to have some memory problem..it remembers the previous position when I refresh the page after the first time. below is the code This need the latest jquery & jquery ui $.fn.tooltip = function(options) { var defaults = { my : left center, at : right top, collision : none, offset : 0 0 } var options = $.extend(defaults, options); return this.each(function() { var $this = $(this); var tip = $(<span class='tooltip'> + $this.attr('tooltip') + </span>); tip.css({ width : options.width }); $this.after(tip); tip.position({ my : options.my, at : options.at, of : $this, collision : options.collision, offset : options.offset }); $this.add(tip).hover(function() { var timeoutId = $this.data('timeoutId'); if(timeoutId) { clearTimeout(timeoutId); } tip.fadeIn(slow); }, function() { var timeoutId = setTimeout(function() { tip.fadeOut(slow); }, 650); $this.data('timeoutId', timeoutId); }); }); }; $(function() { $('#input1').tooltip(); $('#input2').tooltip(); });css style .tooltip { display: none; position: absolute; background-color: #ffaa5e;/* #F5F5B5; */ border: 1px solid #DECA7E; color: #303030; font-family: sans-serif; font-size: 12px; line-height: 18px; padding: 10px 13px; position: absolute; text-align: center; top: 0; left: 0; z-index: 3; }html code to test thishttp://jsfiddle.net/HE8QN/thanks
can we use of $this in closure for jquery plugin
javascript;jquery;jquery ui
null
_unix.110008
I need to upload a directory with a rather complicated tree (lots of subdirectories, etc.) by FTP. I am unable to compress this directory, since I do not have any access to the destination apart from FTP - e.g. no tar. Since this is over a very long distance (USA => Australia), latency is quite high.Following the advice in How to FTP multiple folders to another server using mput in Unix?, I am currently using ncftp to perform the transfer with mput -r. Unfortunately, this seems to transfer a single file at a time, wasting a lot of the available bandwidth on communication overhead.Is there any way I can parallelise this process, i.e. upload multiple files from this directory at the same time? Of course, I could manually split it and execute mput -r on each chunk, but that's a tedious process.A CLI method is heavily preferred, as the client machine is actually a headless server accessed via SSH.
How can I parallelise the upload of a directory by FTP?
command line;ftp;parallel;file transfer
lftp would do this with the command mirror -R -P 20 localpath - mirror syncs between locations, and -R uses the remote server as the destination , with P doing 20 parallel transfers at once. As explained in man lftp: mirror [OPTS] [source [target]] Mirror specified source directory to local target directory. If target directory ends with a slash, the source base name is appended to target directory name. Source and/or target can be URLs pointing to directo ries. -R, --reverse reverse mirror (put files) -P, --parallel[=N] download N files in parallel
_codereview.113154
I'm a junior who wants to refactor a big method in my code, which has been tested and works: def self.authorized_status plugin_id, store_id, application_id, version, locale=nil if plugin_id.match /^(\w|-)+$/ I18n.locale = locale || :en # I think I can move it to a concern # for this I thought about an external method how return two values, or a hash. Any idea? found_by = :iid plugin = Plugin.find_by_iid(plugin_id) if !plugin plugin = Plugin.find_by_aid(plugin_id) found_by = :aid end application_id_and_version = { application_id: application_id, version: version, status: Application::PUBLISHED_STATUS } update_by_application_id = ApplicationUpdate.where(application_id: application_id).joins(application: :store).where(application: {store_id: store_id} ) is_store = update_by_application_id.first.application.is_store? if !update_by_application_id.first.nil? # for the rest of the code I don't know what to do expect put validations into separate methods. if plugin.nil? || plugin.user.nil? { status: UNREGISTERED_PLUGIN, message: I18n.t('....') } elsif ApplicationUpdate.where(application_id_and_version).count == 0 && !is_store { status: UNKNOWN_APPLICATION, message: I18n.t('....') } else if !is_store groups = Group.joins(users: :plugins).where(users: {plugins: {found_by => plugin_id}}) .joins(:application_updates) .where(application_updates: application_id_and_version) end if !is_store && groups.empty? { status: NOT_AUTHORIZED, message: I18n.t('....') } else store = Store.find store_id authorized = (!store.preauthorized?) || is_store || plugin.authorized_for_store?(store) if !authorized || BlacklistedPlugin.find_by_organisation_id_and_plugin_id(store.organisation_id, plugin.id) { status: NOT_AUTHORIZED, message: I18n.t('....') } else { status: AUTHORIZED, message: I18n.t('....') } end end end else { status: PLUGIN_ID_FORMAT_ERROR, message: I18n.t('....') } end endI saw recently to get some help a talk from Andy Pike (slide) with some nice principle like OCP or SOLID. I don't think the way he refactors the code is something I should do but maybe I'm wrong. To be honest, the method sometimes looks so weird, especially with all the ifs, that I don't know where to start.
Managing many availability status
ruby;ruby on rails
null
_webmaster.60032
Even though I have thousands of impressions and a few dozen clicks, there is no detail in the AdWords interface about the keywords.In other words, I would like to know which clicks and impressions came from which keywords. This way I can make better decisions as to which keywords I should use!
In Google Adwords the impressions and clicks are not broken out according to keyword
google;analytics;google adwords
null
_codereview.155628
I'm writing a command-line utility and I need to find commands (and parameters) by name. The name can either be a full name like save or a shortcut s.I thought I use a dictionary with an ISet key and a custom comparer. At first I had a list and searched for the name with LINQ but I'd like to have something more convenient. The performance doesn't matter - this time convenience goes first. There will be at most a few dozens of commands. I know I could use a string and map each name to the command but this isn't cool :-)First, there is a NameSet that is the base class for concrete sets.class NameSet : HashSet<string>{ protected NameSet(IEnumerable<string> keys, IEqualityComparer<string> keyComparer) : base(keys ?? throw new ArgumentNullException(nameof(keys)), keyComparer) { }}one with the suffix CI which stands for Case Insensitive (like the collation in Sql Server)class NameSetCI : NameSet { private NameSetCI(IEnumerable<string> keys, IEqualityComparer<string> keyComparer) : base(keys, keyComparer) {} public static NameSetCI Create(params string[] keys) => new NameSetCI(keys, StringComparer.OrdinalIgnoreCase);}the other with the suffix CS which obviously stands for Case Sensitive.class NameSetCS : NameSet{ private NameSetCS(IEnumerable<string> keys, IEqualityComparer<string> keyComparer) : base(keys, keyComparer) { } public static NameSetCS Create(params string[] keys) => new NameSetCS(keys, StringComparer.Ordinal);}The comparer for this is very simple. It just looks if there is any overlapping set.internal class SetComparer : IEqualityComparer<ISet<string>>{ public bool Equals(ISet<string> x, ISet<string> y) => x.Overlaps(y); public int GetHashCode(ISet<string> obj) => 0; // Force Equals.}With the hash code 0 it doesn't seem to be O(1) anymore but all the keys are in one place an the logic is just a single Overlaps method. LINQ wouldn't be faster anyway and it would mean a lot more work.Example:var dic = new Dictionary<NameSetCI, string>(new SetComparer());dic.Add(NameSetCI.Create(foo, bar), fb);dic.Add(NameSetCI.Create(qux), q);dic[NameSetCI.Create(baz)] = b;dic[NameSetCI.Create(bar)].Dump(); // fbdic.Add(NameSetCI.Create(foo), f); // bam!
Dictionary with ISet key as a collection of names
c#;dictionary;set
You can just use a single class with a generic Create method which has constraints for IEqualityComparer<string>:internal class NameSetGeneric : HashSet<string>{ private NameSetGeneric(IEnumerable<string> keys, IEqualityComparer<string> keyComparer) : base(keys ?? throw new ArgumentNullException(nameof(keys)), keyComparer) { } public static NameSetGeneric Create<T>(T comparer, params string[] keys) where T : IEqualityComparer<string> => new NameSetGeneric(keys, comparer);}You can even go further and make the whole class generic, but that's only if you want to work with different data types.Example usage:var dic = new Dictionary<NameSetGeneric, string>(new SetComparer());dic.Add(NameSetGeneric.Create(StringComparer.OrdinalIgnoreCase, foo, bar), fb);dic.Add(NameSetGeneric.Create(StringComparer.OrdinalIgnoreCase, qux), q);dic[NameSetGeneric.Create(StringComparer.OrdinalIgnoreCase, baz)] = b;dic[NameSetGeneric.Create(StringComparer.OrdinalIgnoreCase, bar)].Dump(); //fbdic.Add(NameSetGeneric.Create(StringComparer.OrdinalIgnoreCase, foo), f); // bam!
_webapps.86192
Since last weekend, I encounter problems retrieving data from exchanges such as SGX and SHA. =GOOGLEFINANCE(SGX:ES3,changepct)=GOOGLEFINANCE(SHA:000001,changepct)The error message is; When evaluating GOOGLEFINANCE, Google Spreadsheets is not authorized to access data for exchange: 'SHA'Anyone encountered the same problem and found a solution?
Cannot retrieve data for some exchanges from Google Finance
google spreadsheets
null
_unix.53647
After several attempts, I have managed to compile GNURadio on the Raspberry Pi. However, I am just not able to meet the prerequisites for the gnuradio build script on the Pandaboard (Linaro 12.04) or the BeagleBoard (Ubuntu 12.04)This is what I see -Failed to find package 'libqwtplot3d-qt4-dev' in known package repositoriesPerhaps you need to add the Ubuntu universe or multiverse PPA?see https://help.ubuntu.com/community/Repositories/Ubuntuexiting buildI have tried adding all kinds of repositories to get this to work. What repository do I get libqwtplot3d-qt4-dev from for the armhf architecture? Can I mix armfh and armel packages?
GNU Radio prerequisite libraries on armhf
ubuntu;repository;arm
That package isn't int the Ubuntu repositories for armel or armhf (at least according to packages.ubuntu.com -- you can probably compile the source package (qwtplot3d). It looks like that package is in universe, so you'll need that enabled.You should be able to runapt-get build-dep qwtplot3dapt-get source qwtplot3dcd qwtplot3d-*/dpkg-buildpackageand get .debs for what you need.(If the last step fails, then the package needs some porting to work/compile on ARM -- either go nuts, or abandon all hope, depending on how much C++-fu you've got at the moment).
_cs.65531
So I'm working on a project and I'm totally stuck right now on how to generate an nxn matrix in Matlab (where n is defined by user input). I need to make a matrix that has ones diagonally, zeroes below it, and values of negative one above. As a 2x2 example shown right here:[1 -10 1] I would show the code that I have, but I'm blank on how to make it actually do that. I know how to get it to accept user input. I also figure that nested for loops may be able to work here, because if I could generate an nxn matrix with values I can set, I can have two variables, like r and c (rows and columns). For the diagonal, where r=c the values can equal 1, -1 where r is less than c, and 0 where r is greater than c. Problem is I'm not sure how to generate a matrix where you can set values in it like that. I know you can generate an identity matrix with the 'eye' command, but that just has the diagonal values equal to 1. I can give more information, but if there's some command for that I'm missing, I could really use to know. Thank you.
How to make a certain matrix in Matlab
matrices
null
_unix.149937
With GNU screen (version 4), why is it that the following runs perfectly fine:$ screen -S some-nameBut if I try having a slash (/) in the session name, it gives me an error about multiuser support.$ screen -S some/nameMust run suid root for multiuser support.If I try setting the session name from within the screen:$ screenC-a :sessionname some/nameI get the following error:: bad session name 'some/name'So apparently a / is invalid character for a session name. Looking at the man page for screen, I see nothing about invalid or reserved characters for sessionname:-S sessionnameSet the name of the new session to sessionname. This option can be used to specify a meaningful name for the session in place of the default tty.host suffix. This name identifies the session for the screen -list and screen -r commands. This option is equivalent to the sessionname command (see Session Name). 8.5 Session Name Command: sessionname [name](none) Rename the current session. Note that for screen -list the name shows up with the process-id prepended. If the argument name is omitted, the name of this session is displayed. Caution: The $STY environment variable still reflects the old name. This may result in confusion. The default is constructed from the tty and host names.Also, unmatched ' and in the session name complain about unmatched quotes which seems to be about syntax. E.g., :sessionname 'test' gives test as the name. And ^A, ^B, etc. yield control characters.What is the valid syntax or characters for a session name?
Valid screen session names
gnu screen
The purpose of assigning a name to a screen session with -S is so you can operate on that session (for example with screen -r ...) by specifying its name.Looking at the man page under the -r option:-r [pid.tty.host]-r sessionowner/[pid.tty.host] resumes a detached screen session. No other options (except com binations with -d/-D) may be specified, though an optional prefix of [pid.]tty.host may be needed to distinguish between multiple detached screen sessions. The second form is used to connect to another user's screen session which runs in multiuser mode. This indicates that screen should look for sessions in another user's directory. This requires setuid-root.So a session name with a / character is interpreted as owner/name. (This could be documented better under the -S option.)You can doscreen -S $USER/namewhich is equivalent to:screen -S nameIn some quick experiments with screen version 4.01.00, I haven't found any other special characters that are prohibited in session names. All the following:screen -S 'foo bar'screen -S 'foobar'screen -S foo'barscreen -S 'foo\bar'screen -S foo'bar^Xbazworked correctly for me.In the last one, the ^X was actually a literal Ctrl-X character. screen -ls shows it literally; I had to do screen -ls | cat -A to see it. I was able to resume all these sessions by specifying their names:screen -dr 'foo bar'etc., and the value of $STY within each session was correct.(I don't recommend using control characters, for what I hope are obvious reasons.)
_codereview.11289
I am relatively new to jQuery and this is one of the first attempts to use it. Tell me if I am using it wrong:This is the main code that toggles everything:$(function(){ $(#tree li).hide();//collapse everything by default $(#tree span).click(function(){ $(this).toggleClass(uncollapsed);//toggle V and > $(this).parent().find(>li).toggle(fast);//display and hide });});I am only interested to get reviews on the JS above, however, I will post the the HTML and CSS to give some background.HTML:<ul id=tree> <span>(click to toggle)</span> <li>1</li> <li>2</li> <li> <ul> <span>(click to toggle)</span> <li>3</li> </ul> </li></ul>CSS:#tree ul,#tree li,#tree span{ list-style:none; padding:0; margin:0;}#tree li,#tree span{ padding:5px 0 5px 20px;}#tree span{ cursor:pointer; background:url('collapsed.png') no-repeat 0 50%;}#tree span.uncollapsed{ background-image:url('uncollapsed.png');}
Collapsable Tree
javascript;jquery
That is not valid html.The only thing you can put inside a <ul> tag is <li> tags.With that in mind, this would be much better (change the selector as necessary):$(#tree span).click(function () { $(this).toggleClass(uncollapsed).next().toggle(fast);});Otherwise, you should change the click method to:$(#tree span).click(function () { $(this).toggleClass(uncollapsed).parent().children(li).toggle(fast);});Reasons:you don't need to use $() over again to recreate $(this).find(>li) is a less efficient version of .children(li)Better yet, if you can change the html to:<span class='hasChildren'> (click to toggle) <ul id=tree> <li>1</li> <li>2</li> <li class='hasChildren'> (click to toggle) <ul> <li>3</li> </ul> </li> </ul></span>Then the click event to:$(.hasChildren).click(function (e) { $(this).toggleClass(collapsed); return false;});And in css, style accordingly (you could even animate the class if you wished). Note however that this would be a change in the way the list worked (play around with <a> tags in the list and clicking in different parts to see the difference).
_webapps.90749
Is there a way to set up 2 factor auth for Gmail but not for my Google Calendar?I'm using YouCanBook.me and enabling 2fa seems to have broken it.
Set up 2 factor authentication for Gmail but NOT Google Calendar?
gmail;google calendar;two factor authentication
null
_reverseengineering.9388
I am trying to debug a linux application using remote debugging feature in ida pro. I use the remote linux debugger on windows after running the ida server on linux. My problem is that the file run normally in the linux environment since environment variables are accessible to the file. However, on using ida in windows the environment variables seems to be inaccessible and give error that I should define environment variables.
adding environment variable to ida pro
ida
1) Run the linux program normally, then attach to the running process from IDA. Of course this won't work if you have to debug the application startup.2) Define (and export) the environment variables on Linux before you start linux_server. When you attach IDA to the running server, and start your program, the environment variables should get passed through to your program.Of course, defining any environment variables in windows won't alter the environent of your linux program.
_codereview.113853
I would love a code review of this LSD radix sort implementation. I've rolled my own, and have implemented counting sort as well. I feel like some of the data structures I've chosen could be improved. My List<List<char[]>>, for instance, is a little gross and makes fiddling with its innards more complex than I think needs to be.public class LSDSorting {private static final int DIGIT_RANGE = 5;public static void main(String[] args) { char[][] toSort = new char[][]{0123.toCharArray(), 1233.toCharArray(), 1212.toCharArray(), 1111.toCharArray(), 4444.toCharArray()}; int LSD_INDEX = toSort[0].length - 1; char[][] sorted = lsdSort(toSort, LSD_INDEX); for (char[] str: sorted) { System.out.println(String.valueOf(str)); }}private static char[][] lsdSort(char[][] toSort, int d) { if (d < 0) { return toSort; } char[][] sortedOnD = runCountingSort(d, toSort, DIGIT_RANGE); return lsdSort(sortedOnD, d-1);}private static char[][] runCountingSort(int d, char[][] toSort, int range) { List<List<char[]>> idx = new ArrayList<>(); for (int i = 0; i < range; i++) { idx.add(i, new ArrayList<char[]>()); } for (int i = 0; i < toSort.length; i++) { int currVal = Character.getNumericValue(toSort[i][d]); List<char[]> currList = idx.get(currVal); if (currList == null) { currList = new ArrayList<>(); idx.add(currVal, currList); } currList.add(toSort[i]); } char[][] result = new char[toSort.length][toSort[0].length]; int currIdx = 0; for (int i = 0; i < idx.size(); i++) { for (char[] str : idx.get(i)) { result[currIdx] = str; currIdx++; } } return result;}}
Implementing LSD radix sort
java;algorithm;reinventing the wheel;radix sort
null
_webmaster.57971
I have a dynamically generated PHP web page where I change randomly the page <title> and <h1> by synonyms.Will search engines index the page for all or just for one synonym? Is it good option in terms of SEO?
Synonyms and SEO
seo;change frequency
It's going to index whatever it sees when it crawls the page. So one day it may be one word and the next day another. So this really isn't going to do anything for you. If you want to improve your rankings for the synonyms you should find a way to work them into your copy. That way they are all there, all the time.
_webmaster.27662
A client just got a notice from Google saying that their Adwords campaign has been put on hold because the site is:Improperly rendering orUnder construction orNeeds a special program to runNow the site is improperly rendering on IE6. On everything else, including IE7+ it's fine. If this is the issue, would putting up a Looks like you're using an older browser message instead of the site for IE6 be a solution? Or must the site look good in IE6 for the Adwords campaign to continue?
Can Adwords be cancelled by Google because of improper IE6 site rendering
google adwords;internet explorer 6
Improperly rendering orEnsure no cloaking is in place;Under construction orAll links are OK;Needs a special program to runhttp://damionbrown.com/2011/01/google-apparently-penalising-adwords-advertisers-with-flash-landing-pages/
_computergraphics.4479
How do you use textures with direct state access in OpenGL?I have the following in my code, which seems to work:GLuint textureHandle;glGenTextures(1, &textureHandle);glActiveTexture(GL_TEXTURE0);glBindTexture(GL_TEXTURE_2D, textureHandle);glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, imageW, imageH, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);However, when I replace it with the following everything just becomes black:GLuint textureHandle;glActiveTexture(GL_TEXTURE0);glCreateTextures(GL_TEXTURE_2D, 1, &textureHandle);glTextureImage2DEXT(textureHandle, GL_TEXTURE_2D, 0, GL_RGBA8, imageW, imageH, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);glTextureParameteri(textureHandle, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
How to do texturing with OpenGL direct state access?
opengl;texture
You still have to bind the desired texture to the texture unit to use it for rendering. In your current code, you're not specifying which texture to use for rendering, so the GL driver doesn't know which one you want to use and is defaulting to no texture.There are a few ways to bind a texture. You can keep using glActiveTexture+glBindTexture as in your non-DSA code, or you can use either glBindTextures or glBindTextureUnit.For example, with glBindTextureUnit, do this:glBindTextureUnit(0, textureHandle);The first parameter is the texture unit to bind to.By the way, instead of using glTextureImage2DEXT (which is from the old and deprecated EXT_direct_state_access extension), it's probably better to stick with core OpenGL calls. You can initialize the texture by using glTextureStorage2D to allocate the memory and set the format, then glTextureSubImage2D to upload the data.(Here's an article with more on the differences between EXT_direct_state_access and the newer core version of the functionality, if you're interested.)
_unix.242383
I want to mount an ntfs partition on two different mount-points on my Debian. I have already done this with other file systems like vfat or ext4, but I am not able to do it with ntfs: mkdir -p /tmp/mp_0 /tmp/mp_1mount -t ntfs -umask=000 /dev/sda1 /tmp/mp_o --> everything is till now okmount -t ntfs -umask=000 /dev/sda1 /tmp/mp_1 --> ERRORMount is denied because the NTFS volume is already exclusively opened.The volume may be already mounted, or another software may use it whichcould be identified for example by the help of the 'fuser' command.Why can't I mount ntfs twice?*********** Update **********as far as i understood, ntfs does not provide such a feature, whereby it is not even needed since i can acheive the same effect withmount --bind Thanks
Mount an ntfs partition two times
mount;ntfs
null
_unix.56327
Is there a naming convention in Linux when it comes to application icon filenames? What I'm referring to is the practice of including the icon size in the filename if the application uses multiple icon files (PNGs, for example) for different views (desktop, lists, menus, etc.). OS X has the icon_16x16, icon_32x32, etc. convention, so I'm wondering if there's a similar practice in Linux.
Linux Icon Naming Conventions
linux;files;filenames;icons;conventions
Yes, but Linux separates different sizes of icons into different directories instead of giving them different names. You'll want to read the Icon Theme Specification, which explains the directory layout, and the Icon Naming Specification, which explains how the filenames should be chosen.To summarize, Linux application icons would be something like:/usr/share/icons/<theme-name>/<icon-size>/apps/<program-name>.png
_softwareengineering.317415
I am looking for a system for building state machines with timed/scheduled transitions, and with events that happen periodically during a given state. I can implement it myself, though I feel like this is a common enough requirement that there would be a category of software for it.I don't need a library recommendation, vendor, etc. I just don't know what to call this thing, and thus what to google, because it isn't a cron and it isn't a message queue. I don't know if such a server-side layer even exists currently, but I'm hoping to find an indication one way or the other. If this type of question is a reason for down votes and close votes, definitely indicate that, and maybe point me to another SE, or suggest improvements.The application I have in mind is a timed video game event system, like those you might see in an MMORPG (periodic monster spawns, timed escalating waves, failure timer, scheduled event starts), or in a trivia bot (per-question timer, time between questions, round timer), etc. It won't be used for simulations, physics, etc, so I won't be throwing real-time (sub-second) granularity events at it.The system I have in mind would be some sort of hybrid pub/sub and scheduling system, operating entirely server-side. It would be somewhat like a Javascript setTimeout, except with a more reliable mechanism, probably with a 1 second resolution, and with the ability to pass parameters explicitly when you schedule the timeout. It probably would also have some sort of global monitoring for ops purposes, and maybe would have some sort of support for scaling to multiple systems.I don't know if I will need to roll my own, or if there are more generic systems that already do what I want them to do. I would prefer to use an existing system if possible. There is some common server tech that is similar, but I don't think it quite does the job.The system I want operates sort of like Cron, with these exceptions:It should be function callback/micro-process oriented rather than shell oriented.Tasks should probably be executed in a delegate sub-process pool, or in-process of the daemon, rather than spawning a new process per task.It should have a resolution of 1 second (or smaller)The system I want also operates sort of like a message or task queue, with these exceptions:It should allow for periodic tasks (already possible in some queues, I think)It should support parallel execution for tasks that are scheduled for a given tick, rather than sequentially running them off a queueIt shouldn't expect tasks to be long-running, and shouldn't build its interface for long-running tasksIt should be just as easy to make recurring tasks as one-off tasks, without having to build task-chaining glueI should be able to cancel scheduled tasks easily and quicklyRobustness of preserving and guaranteeing task execution is not a priority over per-task overhead. Vertical and horizontal scalability is way more important than carefully preserving data (at this layer)Tasks should probably be able to share state at some level (so that IPC and task execution latency/overhead is minimized)If the system supports horizontal scaling, I should be able to give grouped tasks an affinity so that they are executed off the same shared state, rather than sent to an arbitrary worker in a poolMy preferred programming platform is python, but I would be fine with a stand-alone system in any language that allows for low-latency server side IPC over a standard protocol, so I can use my server-side language of choice. I'd also be fine with a system that specifically integrates with popular server-side languages, as my task implementations are likely to be a pretty small portion of my larger system.Having a built-in ability to optionally send events to clients in a push style would also be cool, but definitely does not have to be part of this library or layer.
System for scheduling parallel tasks/callbacks
design;architecture;libraries
null
_unix.375120
I can create multiple numbered folders at once like so:mkdir Season\ {1,2,3,4,5}Is there a way I can run the following commands in a oneliner (without a for loop):mv 01.* Season\ 1mv 02.* Season\ 2mv 03.* Season\ 3mv 04.* Season\ 4mv 05.* Season\ 5Bonus points if there's a ZSH way to do it.
Bash - move files into numbered folders oneliner
bash;zsh
With zsh:autoload zmv # best in ~/.zshrczmv -n '(<1-5>).*' 'Season $(($1))'(remove the -n when happy)Note that it calls one mv per file so it would be less efficient than the 5 mv commands of your question (unless you do a zmodload zsh/files beforehand to get a builtin mv).A perl's rename alternative:rename -n '$_=Season $1/$_ if /0*(\d+)/' 0[1-5].*(remove -n when happy)Note that rename calls the rename() system call, so that only works to move files within the same file system (while mv will resort to copy+unlink when moving files across file system boundaries).With mmv (moving across FS boundary is supported, but then note that not all attributes will be preserved and for symlinks a copy of the target file is created):mmv -n '0[0-9].*' 'Season #1/'(remove -n when happy)
_unix.38639
Every so often, some application runs wild and fills a directory with a huge amount of files. Once we fix the bug and clean up the files, the directory stays big (>50MB) even though there's only 20-30 files in it.Is there some command that compacts a directory without having to recreate it?Bonus points: does a huge empty directory affect access performance of that directory? I'm assuming it does, but maybe it's not worth bothering. It seems slower to do ls on such a directory.
How to compact a directory
filesystems;ext3
null
_webmaster.71988
I have been struggling fixing the CDATA comment problem every time I inserted Google remarketing tag on our Wordpress e-commerce site. IGoogle tag assistant says it can't find the CDATA comment. For further info, I inserted the remarketing tag in the header.php after the <body> tag.
Google remarketing tag on Wordpress site: can't find the CDATA comment
google;wordpress;google tag manager;remarketing
null
_cs.23661
I am curious as to what steps one would reasonably need to take to perform an extraction-based text summarizer.I've taken a look at some papers I've found on Google such as this one, which explains that UPGMA is the best clustering algorithm (out of the tested set). I've also found this one to be interesting, regarding single and multi-document summarization.I'm unclear as to whether I'd need to combine these techniques for summarization or whether it would suffice to use a tool like Gensim to model a corpus of documents and just extract the sentences with the highest vector values.
Document clustering for summarization
machine learning;data mining;natural language processing;cluster
null
_webmaster.22613
Possible Duplicate:I cannot see my website in google I have a strange problem with my website. I have a website, let's say Abcdefg.com.Website is live for 2 months and google still doesn't know it. While searching for my domain name 'abcdefg', google displays results for similar phrase (abcdef) but not fot mine. How to make google get to know my domain name? Website and sitemaps have been submitted via Google Webmaster Tools.
How to make google get to know my domain name
seo
null
_scicomp.5211
I am new user of OpenFOAM, I have to generate a grid of a human body to calculate the convective heat transfer between the body and the environment.Can someone guide me please?Thanks in advanceMoorzMore information:My work is to apply CFD tools for the calculation of the heat transfer between the human body and the environment. The convection and the heat transfer from the body are calculated directly without any empiric information.These are the Questions that need to be answered:Is the slender body model sufficient for calculation of the heat exchange on the human body surface?What is the sensibility of calculations to the grid used?What is the sensibility of calculations to the turbulence model used?What is the difference between RANS and URANS computations?And i need to find the solution of the Reynolds (or LES) equations, while the temperature transport equation is to be found using the OpenFoam CFD code under the following boundary conditions:Inlet of the computational domain: The velocity profile is fixed. The pressure is fixed at patm value. The temperature is fixed at the value Tatm.Outlet of the computational domain: The velocity, temperature and the pressure satisfy the zero gradient condition.Sides of the computational domain: The velocity, temperature and the pressuresatisfy the zero gradient condition.No slip condition on the human body. The temperature fulls the condition T = Tb on the human body. The temperature distribution Tb is given.As of now i just need to finish the task of generating a grid for human body and use RANS for calculations. If i do that, i will be given more time to finish other tasks.
OpenFOAM-CFD, human body grid
openfoam
null
_codereview.132630
This method removes n elements starting from a given index, from an array of a given type. If n is positive it removes elements forwards, if it is negative it removes them backwards (e.g. for an array {1,2,3,4,5} Remove(2,2) results in {1,2,5}; Remove (2,-2) results in {1,4,5})It there a better way to do it?public static class ArrayExtensions{ public static T[] RemoveAt<T>(this T[] array, int idx, int len) { T[] newArray; if (len > 0) { if (idx + len > array.Length) len = array.Length - idx; newArray = new T[array.Length - len]; if (idx > 0) Array.Copy(array, 0, newArray, 0, idx); if (idx < array.Length - 1) Array.Copy(array, idx + len, newArray, idx, array.Length - idx - len); } else { newArray = new T[array.Length + len]; if (idx > 0) Array.Copy(array, 0, newArray, 0, idx + len); if (idx < array.Length - 1) Array.Copy(array, idx, newArray, idx + len, array.Length - idx); } return newArray; }}
Removing n elements from array starting from index
c#;array
I believe that if the len < 0, it's better to adjust idx and len values. This will eliminate two branches of code.Another suggestion is to use more readable variable names.For instance, method arguments could be named startIndex and length respectively.public static T[] RemoveAt<T>(this T[] array, int startIndex, int length){ if (array == null) throw new ArgumentNullException(array); if (length < 0) { startIndex += 1 + length; length = -length; } if (startIndex < 0) throw new ArgumentOutOfRangeException(startIndex); if (startIndex + length > array.Length) throw new ArgumentOutOfRangeException(length); T[] newArray = new T[array.Length - length]; Array.Copy(array, 0, newArray, 0, startIndex); Array.Copy(array, startIndex + length, newArray, startIndex, array.Length - startIndex - length); return newArray;}
_scicomp.3206
I want to make my python program fast by using cython, but my inner loop is still making slow python calls to the random number generator! Several years ago this same issue was raised by someone on sage-support and there seemed to be no good solution at that time. It is not convenient for me to pre-generate a long list of random samples because I am actually sampling from various distributions in a way that is conditional on previous samples.Here's a blog post explaining how this was kludged by connecting from cython to gsl:http://pyinsci.blogspot.com/2010/12/efficient-mcmc-in-python-errata-and.htmlAnd a stackoverflow post by someone trying to implement the gsl kludge:https://stackoverflow.com/questions/8177446/random-number-generators-to-work-on-x86-64
random number generation from cython
python;random number generation;sage
null
_webmaster.2347
I am tracking the pageviews that each of my authors' articles generates on a Wordpress site with Google Analytics Event Tracking:var pageTracker = _gat._getTracker(UA-xxxxxxx-x);pageTracker._trackPageview();} catch(err) {}<?php if ( is_singular()) { ?> pageTracker._trackEvent('Authors','viewed','<?php the_author_meta('ID'); ?>'); <?php } ?>I have an event category Authors and there's an event label for each of their IDs. How can I give each author access to the data for their respective label without giving them access to other author's stats and the sites stats as a whole?
Reporting on Specific Event Label in Google Analytics
google analytics
null
_webapps.60686
I have a video on YouTube (a cinema tutorial), but when I visit the site anonymously it says that I have 188 views.When I log in with my account that I used to upload the video it says it was viewed only 31 times. Why is this?
Why does my YouTube video show more visits when I check it anonymously?
youtube;account management;statistics
null
_webmaster.71156
I am attempting to redirect the IP address of my domain to the domain name and am running into trouble. The IP address does not redirect to the domain name listed in the redirect statement below.The IP Address is 123.123.123.123My .htaccess looks like belowRewriteCond %{HTTP_HOST} ^123\.123\.123\.123$ [NC]RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
redirect the site IP address to the domain name
htaccess
Ordinarily your code should work OK. Although the NC (NOCASE) flag on a numeric value is unnecessary and should be removed.Also note that if you are checking for an exact match (such as a complete IP address) it is usually easier to simply use the = (equals) operator, for example:RewriteCond %{HTTP_HOST} =123.123.123.123This now matches against the plain string 123.123.123.123 (exact match), not a regular expression, so there is no need to escape the dots.Your site also appears to be example.com, not www.example.com so you should change the substitution in the RewriteRule to reflect this, otherwise this will result in a second redirection.However, the main problem in your case seems to be that you are on a shared host - multiple websites hosted on the same IP address (in fact, a rough estimate shows that there are over 500 websites on that IP address). Requesting your server's IP address does not return your website, so attempting to do this kind of redirection is not going to work.
_unix.19778
I'm using mutt with mutt-patched to manage 5 different Gmail accounts. For each of this accounts, I have INBOX as a mailbox with the mailboxes +INBOX configuration statement for each one. Then, I have 5 different uglies INBOX options to choose in my left column.Is there a way to rename that mailboxes screen names to get visually information about, for example, wich account belongs each one?
Rename mailboxes in mutt
mutt
null
_unix.24351
Possible Duplicate:Open a window on a remote X display (why “Cannot open display”)? I have a computer running debian, connected to my TV, running an xorg session. What I want to do is ssh into that machine and start an application that will also display on that machine. For example, I want to be able to ssh to it from my laptop and start mplayer on the host, playing a file on the host and showing it on the TV. Is this possible? I have a feeling it should be (relatively) trivial, but I just can't seem to figure it out.Just to clarify, simply running $ ssh -X host$ mplayer movie.avi &won't cut it, because it will start displaying on my laptop's display.
Remotely control an xorg session
ssh;xorg;x11;remote
If you know what $DISPLAY your ssh host's X server is using, e.g. :0.0, the following works for me:ssh hostexport DISPLAY=:0.0Now you can run any graphical app of your choice on your host. You won't be able to see or control the graphical aspects on/from your laptop, of course.
_unix.43430
I'm on debian testing, and after rebooting (after an uptime of 3 weeks or so, that included a bunch of package updates, I believe including the kernel) the other day, the fine-adjustment - what a golfer would call putting - of the mouse pointer position gets really hard, it feels like the pointer is still moving, although the the trackpoint is already back at its center position. Using the trackpoint is no fun anymore, it takes seconds just to select a bunch of words.I don't think it's just a trackpoint performance configuration setting. It might be some threshold or the deactivation of some clever algorithm (or the activation of a wannabe clever algorithm) to enhance the usability of the trackpoint.This is an IBM/Lenovo external USB keyboard (it is not a ThinkPad laptop, even though I tagged this question 'thinkpad', as there is no 'trackpoint' tag yet and my current reputation doesn't permit tag creation).My xinput version:$ xinput --versionxinput version 1.6.0XI version on server: 2.2And here the props of the device:$ xinput list-props 10Device 'Synaptics Inc. Composite TouchPad / TrackPoint': Device Enabled (125): 0 Coordinate Transformation Matrix (127): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000 Device Accel Profile (247): 1 Device Accel Constant Deceleration (248): 2.500000 Device Accel Adaptive Deceleration (249): 1.000000 Device Accel Velocity Scaling (250): 12.500000 Synaptics Edges (251): 1632, 5312, 1572, 4284 Synaptics Finger (252): 25, 30, 256 Synaptics Tap Time (253): 180 Synaptics Tap Move (254): 221 Synaptics Tap Durations (255): 180, 180, 100 Synaptics ClickPad (256): 0 Synaptics Tap FastTap (257): 0 Synaptics Middle Button Timeout (258): 75 Synaptics Two-Finger Pressure (259): 282 Synaptics Two-Finger Width (260): 7 Synaptics Scrolling Distance (261): 100, 100 Synaptics Edge Scrolling (262): 1, 0, 0 Synaptics Two-Finger Scrolling (263): 0, 0 Synaptics Move Speed (264): 1.000000, 1.750000, 0.039809, 40.000000 Synaptics Edge Motion Pressure (265): 30, 160 Synaptics Edge Motion Speed (266): 1, 401 Synaptics Edge Motion Always (267): 0 Synaptics Off (268): 0 Synaptics Locked Drags (269): 0 Synaptics Locked Drags Timeout (270): 5000 Synaptics Tap Action (271): 0, 0, 0, 0, 0, 0, 0 Synaptics Click Action (272): 1, 1, 1 Synaptics Circular Scrolling (273): 0 Synaptics Circular Scrolling Distance (274): 0.100000 Synaptics Circular Scrolling Trigger (275): 0 Synaptics Circular Pad (276): 0 Synaptics Palm Detection (277): 0 Synaptics Palm Dimensions (278): 10, 200 Synaptics Coasting Speed (279): 20.000000, 50.000000 Synaptics Pressure Motion (280): 30, 160 Synaptics Pressure Motion Factor (281): 1.000000, 1.000000 Synaptics Grab Event Device (282): 1 Synaptics Gestures (283): 1 Synaptics Capabilities (284): 1, 1, 1, 1, 1, 1, 1 Synaptics Pad Resolution (285): 1, 1 Synaptics Area (286): 0, 0, 0, 0 Synaptics Noise Cancellation (287): 25, 25 Device Product ID (242): 1739, 9 Device Node (243): /dev/input/event6Update I forgot there are 2 devices that might be relevant, this one actually looks more relevant than the synaptics device:$ xinput list-props 11Device 'TPPS/2 IBM TrackPoint': Device Enabled (135): 1 Coordinate Transformation Matrix (137): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000 Device Accel Profile (260): 0 Device Accel Constant Deceleration (261): 1.000000 Device Accel Adaptive Deceleration (262): 1.000000 Device Accel Velocity Scaling (263): 10.000000 Device Product ID (255): 2, 10 Device Node (256): /dev/input/event9 Evdev Axis Inversion (302): 0, 0 Evdev Axes Swap (304): 0 Axis Labels (305): Rel X (145), Rel Y (146) Button Labels (306): Button Left (138), Button Middle (139), Button Right (140), Button Wheel Up (141), Button Wheel Down (142) Evdev Middle Button Emulation (307): 0 Evdev Middle Button Timeout (308): 50 Evdev Third Button Emulation (309): 0 Evdev Third Button Emulation Timeout (310): 1000 Evdev Third Button Emulation Button (311): 3 Evdev Third Button Emulation Threshold (312): 20 Evdev Wheel Emulation (313): 0 Evdev Wheel Emulation Axes (314): 0, 0, 4, 5 Evdev Wheel Emulation Inertia (315): 10 Evdev Wheel Emulation Timeout (316): 200 Evdev Wheel Emulation Button (317): 4 Evdev Drag Lock Buttons (318): 0Any idea what knob to turn?Update I diffed the above properties against those of another machine (a Lenovo laptop where the TrackPoint works fine) also running debian testing, and they are exactly identical. The version of xinput is the same, too. So I guess we can exclude the xinput version as well as the xinput settings for those devices from our considerations. I'll try to get my hand on another IBM USB keyboard and check if it isn't - after all - a hardware issue...[The following is an edit to this question made by Barry Grumbine (thanks, man), that got rejected by https://unix.stackexchange.com/users/2180/shawn-j-goff (no thanks, man). Because I find it very useful and Shawn's rejection hid this bit of information from me (until now) and others, I'll paste it in here:]Additional InformationThere is an open Debian bug report that I believe describes this problem #682413 The problem seems to be related to the synaptics_usb kernel module. According to synaptics_usb.c, line 30:[...] touchstick support has not been tested much yet[...]
TrackPoint hard to control after Debian update
debian;thinkpad;xinput
null
_unix.244473
Hosting multiple sites with the same Nginx, and a lot of them share common configurations. Such as protection against POODLE and even entire sets of redirects.I tried using the include directive but that didn't seem to do the trick (it acts as if the configuration isn't even there. But Nginx -t reported no problems including the conf file and nginx reloads/restarts just fine) Is there any good way to reuse configurations amongst multiple server blocks?
How to share common configurations amongst Nginx server blocks?
ubuntu;nginx
null
_unix.196455
I'm reading an old book on linkers and loaders and it has images of object code. But I can't figure out what tools is used to display the contents of these files. I'd appreciate if someone could point out the tool.Here is the C code and corresponding display of the object files.Source file m.c:extern void a(char *);int main(int argc, char **argv){ static char string[] = Hello, world!\n; a(string);}Source file a.c:#include <unistd.h>#include <string.h>void a(char *s){ write(1, s, strlen(s));}Object code for m.o:Sections:Idx Name Size VMA LMA File off Algn0 .text 00000010 00000000 00000000 00000020 2**31 .data 00000010 00000010 00000010 00000030 2**3Disassembly of section .text: 00000000 <_main>:0: 55 pushl %ebp1: 89 e5 movl %esp,%ebp3: 68 10 00 00 00 pushl $0x104: 32 .data8: e8 f3 ff ff ff call 09: DISP32 _ad: c9 leavee: c3 ret...Object code for a.o:Sections:Idx Name Size VMA LMA File off Algn0 .text 0000001c 00000000 00000000 00000020 2**2CONTENTS, ALLOC, LOAD, RELOC, CODE1 .data 00000000 0000001c 0000001c 0000003c 2**2CONTENTS, ALLOC, LOAD, DATADisassembly of section .text: 00000000 <_a>:0: 55 pushl %ebp1: 89 e5 movl %esp,%ebp3: 53 pushl %ebx4: 8b 5d 08 movl 0x8(%ebp),%ebx7: 53 pushl %ebx8: e8 f3 ff ff ff call 09: DISP32 _strlend: 50 pushl %eaxe: 53 pushl %ebxf: 6a 01 pushl $0x111: e8 ea ff ff ff call 012: DISP32 _write16: 8d 65 fc leal -4(%ebp),%esp19: 5b popl %ebx1a: c9 leave1b: c3 ret
What tool to use to view an object file?
utilities
You can use objdump. See man objdump. For example -d option for disassemble (there are a lot of options):objdump -d a.oAnother useful programs are included in binutils.
_unix.89023
My system is Gentoo amd64, up to date.[I] dev-libs/boost Available versions: 1.49.0-r2 (~)1.52.0-r6(0/1.52) (~)1.53.0(0/1.53) [M](~)1.54.0(0/1.54) {debug doc icu mpi +nls python static-libs +threads tools PYTHON_TARGETS=python2_5 python2_6 python2_7 python3_1 python3_2 python3_3} Installed versions: 1.53.0(10:17:32 PM 08/19/2013)(icu nls python threads -debug -doc -mpi -static-libs -tools PYTHON_TARGETS=python2_7 python3_2 -python2_5 -python2_6 -python3_1 -python3_3) Homepage: http://www.boost.org/ Description: Boost Libraries for C++My boost is already compiled with threads USE flag.But I still got this error when compiling Hugin.../hugin_base/libhuginbase.so.0.0: undefined reference to `boost::thread::join()'../hugin_base/libhuginbase.so.0.0: undefined reference to boost::thread::start_thread()'collect2: error: ld returned 1 exit statusSome people suggests downgrade boost to 1.47...but it is no longer in the portage.
Hugin 2012 build fail on Gentoo
gentoo
It is caused by a problem in boost-1.5, the include directory is not remove, and causing the Hugin compiling script to use the wrong header file.Manually remove the orphaned directory solve the problem.
_unix.268531
I'm looking for a way I can add files to linux live iso that I've built and somehow load them to memory after or before initrd loads and then mount them as tmpfs, Anyone know how to do that?Thanks.
How to add squashfs file to linux live iso with initrd and mount it
linux;init script;tmpfs;squashfs
null
_codereview.146609
The setPixelColor function below changes the color of pixels.I need some suggestions to optimize this function.Example:public static void main(String[] args) throws IOException { BufferedImage pic1 = ImageIO.read(new File(Images/Input-1.bmp)); setPixelColor(pic1, 34, 177, 76, 127, 127, 127);}This changes the left image into the right image. private static void setPixelColor(BufferedImage imgBuf, int red, int green, int blue, int newRed, int newGreen, int newBlue) throws IOException { int[] RGBarray; int w; int h; //Declare color arrays int[][] alphaPixels; int[][] redPixels; int[][] greenPixels; int[][] bluePixels; w = imgBuf.getWidth(); h = imgBuf.getHeight(); alphaPixels = new int[h][w]; redPixels = new int[h][w]; greenPixels = new int[h][w]; bluePixels = new int[h][w]; RGBarray = imgBuf.getRGB(0, 0, w, h, null, 0, w); //Bit shift values into arrays int i = 0; for (int row = 0; row < h; row++) { for (int col = 0; col < w; col++) { alphaPixels[row][col] = ((RGBarray[i] >> 24) & 0xff); redPixels[row][col] = ((RGBarray[i] >> 16) & 0xff); greenPixels[row][col] = ((RGBarray[i] >> 8) & 0xff); bluePixels[row][col] = (RGBarray[i] & 0xff); i++; } } //Set the values back to integers using re-bit shifting for (int row = 0; row < h; row++) { for (int col = 0; col < w; col++) { if (redPixels[row][col] == red && greenPixels[row][col] == green && bluePixels[row][col] == blue) { int rgb = (alphaPixels[row][col] & 0xff) << 24 | (redPixels[row][col] & newRed) << 16 | (greenPixels[row][col] & newGreen) << 8 | (bluePixels[row][col] & newBlue); imgBuf.setRGB(col, row, rgb); } } } //Write back image ImageIO.write(imgBuf, bmp, new File(Images/Output2.bmp));}
Color substitution in a BufferedImage
java;performance;image
I think that changeColor or substColor would be a more appropriate name for this function.I don't see why the function should write out its result to a file. That's a violation of the Single Responsibility Principle. What if I want to perform multiple color substitutions before writing out the result? What if I want a different output filename, or a format other than BMP?Avoid empty declarations, when you can declare and initialize values at the same time. It's more readable and less error-prone.You don't care about the x-y coordinates of each pixel only the color matters. So, there is no need to construct the 2-D arrays representing the red, green, and blue channels./** * Changes all pixels of an old color into a new color, preserving the * alpha channel. */private static void changeColor( BufferedImage imgBuf, int oldRed, int oldGreen, int oldBlue, int newRed, int newGreen, int newBlue) { int RGB_MASK = 0x00ffffff; int ALPHA_MASK = 0xff000000; int oldRGB = oldRed << 16 | oldGreen << 8 | oldBlue; int toggleRGB = oldRGB ^ (newRed << 16 | newGreen << 8 | newBlue); int w = imgBuf.getWidth(); int h = imgBuf.getHeight(); int[] rgb = imgBuf.getRGB(0, 0, w, h, null, 0, w); for (int i = 0; i < rgb.length; i++) { if ((rgb[i] & RGB_MASK) == oldRGB) { rgb[i] ^= toggleRGB; } } imgBuf.setRGB(0, 0, w, h, rgb, 0, w);}public static void main(String[] args) throws IOException { BufferedImage pic1 = ImageIO.read(new File()); changeColor(pic1, 34, 177, 76, 127, 127, 127); ImageIO.write(pic1, bmp, new File());}
_unix.296241
I've been trying to install a GBU521 Bluetooth adapter on Debian. I've been following several guides, one for Raspbian (http://www.ioncannon.net/linux/1570/bluetooth-4-0-le-on-raspberry-pi-with-bluez-5-x/), and one for Linux Mint (https://community.linuxmint.com/hardware/view/14340) (which should work on Debian), but still get the error No adapters found with Blueman and it doesn't show up on hciconfig.So how do I get the IOGear GBU521 Bluetooth adapter working on Debian? If you need any more information, just ask in the comments.
IOGear GBU521 Bluetooth adapter on Debian
debian;bluetooth;bluez
I was able to get it working by compiling a new kernel with the option CONFIG_BT_HCIBTUSB=y.
_unix.187425
I need to setup a static IP for eth0, my server has multiple network interfaces and I don't want to bring any of them, except for eth0 down.I found lot of guides like https://www.howtoforge.com/linux-basics-set-a-static-ip-on-centos but all of them ends with now restart networking or now rebootI can't reboot this server, nor I can bring down eth1 even if it was for a microsecond. How would I change eth0 config without touching other interfaces?
How to change configuration of eth0 without restarting other interface (CentOS, Redhat)
networking
null
_codereview.85507
I have a binary file with alternating uint8 and uint64 data stamps.I read those in by using the following line:clicks = np.fromfile(filename, dtype=[('time','u8'),('channel','u2')])This works well and fast enough. Now i want to go though the array and set the time values to the time difference with respect to the last 'click' seen on channel 7 (the so called gate clicks). The array is sorted by time. In C I would do this with a simple for loop going over the array (and this works extremly fast). When I implement this in python i get a data rate of only 2 mb/s. The best solution i came up with looks like this: ''' create an array with the indices of the channel-7 clicks ''' gate_clicks = clicks['channel']==7 gate_ind = np.array(range(len(gate_clicks))) gate_ind = gate_ind[gate_clicks] gate_ind_shift = np.delete(gate_ind,0,0) ''' slice out the clicks between to gate clicks and set the time stamps ''' for start,end in zip(gate_ind,gate_ind_shift): start_time = data[start]['time'] slice = data[start:end] slice['time'] = slice['time']-start_time data[start:end] = sliceThis gives a data rate of about 4.
Reading binary data from a file
python;performance
null
_softwareengineering.226092
Suppose in a manufacturing environment, there are certain stock materials available for use in a product. For example, there are only a few different sizes of copper tube, each having a specific thickness and diameter combination. For the purposes of clean and minimal code as well as the ability to control the available options, is an enum a good fit for this combination of data? I was thinking I could make an enum with a member for each valid stock item (representing metal, physical measurements, etc.), and then provide extension methods on the enum to return the mentioned details.The stocks available for use may change over time, so maybe an enum is not the best answer. Is there a better way to express the valid combination of related values? I am using c#.
Allowing enum to express a valid combination of values
c#;validation;enum
I would probably just make a class TubeParameterCombination with read-only properties Thickness and Diameter, and provide an array or list like List<TubeParameterCombination> validCombinations;somewhere in the code. If you want to be absolutely sure no one changes that list afterwards once it got initialized, encapsulate it behind some kind of ValidCombinationProviderclass which allows only read-only access. What you have to decide is where and when you initialize that list. You can either hardcode the initialization in your program (which means you have to change your program whenever the valid combinations change), read the combinations from a text file (which could be changed by a user ot an administrator), maybe just once when your program starts. Or you read the valid combinations from a database (which makes sense when your program is already using a database for such kind of data, and you want to provide a possibility for controlled changes to that list). Pick whatever suits your needs best.
_unix.188659
I have gone through plenty of documents and spent a lot of time trying to configure it, but so far unsuccessfully. I have keyboard with the 3rd level keys (probably ISO_LEVEL3_shift ?)So when I press Caps Lock and at the same time A, I get a acute ().Is it possible to map level 3 shift key to Space instead of Caps Lock?I imagine it as when it is pressed with the key, then it acts as level 3 shift, otherwise it is just space.I am not against experimenting but show me, please, at least direction (if it is possible).
3rd level with space XKB
xkb
null
_webmaster.99476
I see the number 50,000 referenced by Google and Schema.org as the limit for the number of URLs that a sitemap can contain, however, it is unclear to me if that means <loc> elements specifically, or if that also includes other types of URLs, such as<xhtml:link rel=alternate hreflang=de href=http://www.example.com/deutsch/ />Any one of my pages may have 25 of the above alternate URLs, so I want to understand if those count towards the total.
Are alternate links included in the 50,000 URL limit for sitemaps?
google;sitemap;schema.org;xml sitemap;standards
null
_softwareengineering.331647
I have a top10 table (like top 10 restaurants say). Each top 10 row can have up to 10 top10items associated.Modelspublic class Top10{ public Guid Id { get; set; } [Required(ErrorMessage=Title Required)] public string Title { get; set; }}public class Top10Item{ public Guid Id { get; set; } public Guid Top10Id { get; set; } public Guid PlaceId { get; set; } public Int16 Position { get; set; } public Place place { get; set; }}View Modelpublic class Top10ItemsPlaceDropdown{ public Top10 top10 { get; set; } [Display(Name = Place)] public Guid SelectedPlaceId { get; set; } public IEnumerable<Place> Places { get; set; } public IEnumerable<SelectListItem> PlaceItems { get { return new SelectList(Places, Id, PlaceName); } } public IEnumerable<Top10Item> items { get; set; }}I bind the ViewModel to a View. I use it to populate a dropdown on the page, and populate a grid of items for the top 10. The user can then select an item from the dropdown - which is then posted by the [httpPost] method when the user submits the form.The problem - if it is a problem - is that when the view loads [httpGet] - all properties - and those of all sub-objects are valid. However when the view posts back to the controller [httpPost], many are empty (invalid) because on the view they aren't in form fields and don't get posted back (they don't need to be).This means Model.IsValid == false. If I had a validation summary on the page - this would invoke it.This doesn't seem like good practice - but what should i do about this? The model serves my purposes when the page loads - but all I need when the page is posted is top10Id and SelectedPlaceId.
asp.net MVC 5 - Does it matter if my ModelState is not valid & I don't need it to be?
asp.net mvc;asp.net mvc5
The first GET returns a View built from a valid ViewModel.The POST then returns a View built from an invalid ViewModel, giving validation warnings.If the second View is the same as the first, the ViewModel must be valid, or the display won't be correct, because of the missing properties.If the second View is different from the first, you should use another ViewModel, which contains only the properties needed for the second View, without validation warnings
_webmaster.26236
Hi how to redirect the user into mobile site when the user accessing from mobile. Say example i have site called www.mysite.com. Now, a person accessing a website from mobile it should redirect to www.mysite.com/mobile or www.m.mysite.com.I put some research in google that we can redirect using javascript to get the user agent(browser)if(mobile browser) { //redirect to www.mysite.com/mobile} else if(normal browser) { //redirect to www.mysite.com}or using screen resolutionif(screen resolution < 800 ) { //redirect to www.mysite.com/mobile} else if(screen resolution > 800) { //redirect to www.mysite.com}I think It will not work If it is the case of javascript disable.Can we do this using .htaccess or php stuff?Is there any standard mechanism to do this?
How to redirect user into mobile website?
php;htaccess;javascript
use media queries for css in you css put@media all and (max-device-width: 1024px) {... css here}the max-device-width should be the width of the mobile device you want to detect.on the other hand u can use useragentin javascriptvar isMobile = navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/);if(isMobile) { // User-Agent is IPhone, IPod, IPad, Android or BlackBerry}to check the specific user-agent string if(navigator.userAgent.match(/iPhone/)) { // The User-Agent is iPhone}in php this is hwo you do thisif(isset($_SERVER['HTTP_USER_AGENT'])){$agent = $_SERVER['HTTP_USER_AGENT'];}check first the useragent of the device the give the condition if(preg_match('/^Mozilla\/.*?Gecko/i',$agent)){print Firefox user.;// process here for firefox browser}in the pregmatch.. you can put into condition 'iPhone','Andriod' etc
_hardwarecs.7923
I am searching for a keyboard similar to the Cherry MX-BOARD 3.0. I used this keyboard for quite a time and really liked it but it does not satisfy all my requirements:Low price (<=100 EUR) since this will my secondary keyboardBlue (or green) switches (Cherry)en-gb keyboard layoutMedia keys
Low priced mechanical keyboard with en-gb layout and blue switches (cherry)
keyboards
null
_unix.33331
Does anybody know a small and simple Linux distribution that contains not much more than the VirtualBox program? I'd like to set up a machine that actually needs some kind of graphical display plus VirtualBox, which should automatically boot the productive OS as a virtual system.
small Linux host for virtual box
distribution choice;virtualbox;small distribution
null
_datascience.5519
I have a new data point and want to classify it into the existing classes.I can calculate pairwise distance for the new point to all existing points(in the existing classes). I know using KNN would be a straightforward to classify this point. Is there a way I could randomly sampling existing classes and then correlated the new point to a potential classes without calculating all pairwise distances?
about predict the class for a new datapoint
data mining;classification;clustering
I think you need to take a step back and figure out what you're trying to do at a higher level.How were the existing classes built? If they were built by clustering unlabeled data, then with this new data point you're continuing with the clustering process.If the existing classes are labeled data, then k-NN is one possible classification method, and there are plenty more (decision trees, naive bayes, neural networks, etc.). If you're doing clustering, then there are several ways of assigning a point to a cluster, among measuring the distances from the point to cluster centroids is one. There's also single-linkage (distance is min of distances from point to points of cluster), complete-linkage (max of distances). These different methods will give clusters with different shapes and there's no universally best approach. You could test them with points that are already in clusters... but then if you're certain of what classes they re in, then you have a classification problem.So... if it's classification, then you can use k-NN, that's similar to the idea of assigning a point to a cluster according to distance. But it's not defined as finding the nearest cluster, it's defined as finding the classes of the k nearest points, then applying a vote or something. 1-NN is basically like single-linkage clustering. kNN does require finding the most similar (training) data points to your new data point. Sampling is definitely sub-optimal, but it may be good enough if you classes are well separated. If the cost of calculating distances is high, then one way of reducing the cost of calculation is the idea of skyline clustering: use a cheap distance metric to determine a subset of points that are likely to be among the k nearest neighbours, then compute these neighbours using the more expensive distance metric.Finally, if you will be classifying many points and not updating your model, it may be worth training a model (e.g. a decision tree) on the existing classes.
_unix.228446
I have a file that come from map reduce output for the format below that needs conversion to CSV using shell script . The dynamic values are five values and they are the transaction IDs and the four fields(2000,ABC corp,.., BE900000075000027) after that and they keep changing for the next Transaction ID , only the other 17 values(25-MAY-15,04:20 ...til standard life) is constant. 25-MAY-1504:20Client0000000010127.0.0.1PAYISO20022PAIN0001001CUSTAPIABF07ABC03_LIFE.xmlAFF07/LIFE100000Standard Life ================================================================================================AFF07-B000001 2000ABC Corp..BE900000075000027AFF07-B000002 2000XYZ corp..BE900000075000027AFF07-B000003 20003MM corp..BE900000075000027Need output in below format 25-MAY-15,04:20,Client,0000000010,127.0.0.1,PAY,ISO2002,PAIN000,100,1,CUST,API,ABF07,ABC03_LIFE.xml,AFF07/LIFE,100000,Standard Life, 25-MAY-15,04:20,Client,0000000010,127.0.0.1,PAY,ISO2002,PAIN000,100,1,CUST,API,AFF07-B000001, 2000,ABC Corp,..,BE90000007500002725-MAY-15,04:20,Client,0000000010,127.0.0.1,PAY,ISO2002,PAIN000,100,1,CUST,API,ABF07,ABC03_LIFE.xml,AFF07/LIFE,100000,Standard Life, 25-MAY-15,04:20,Client,0000000010,127.0.0.1,PAY,ISO2002,PAIN000,100,1,CUST,API,AFF07-B000002,2000,XYZ Corp,..,BE900000075000027I need values to be repeating just before the two dashed lines along with the rest of the output for the Transaction ID AFF07-B000001,AFF07-B000002,AFF07-B000003There is no dash lines in the real file , I have added it to ensure a better understanding of the input file
Convert a Column oriented file to CSV output using shell script
linux;shell script
null
_unix.156428
I would like for example to remove php and all it's components and extensions as seen in this picture, but instead of removing every software one by one, is there anyway safe I can remove them all using a single command?
How to remove a (group) of softwares that depend on one another?
yum
Since you are in CentOS, you could use the yum as suggested here.yum remove $(yum list installed | grep php | cut -d' ' -f1 | tr \n )
_webmaster.56787
My web site is posted in English. I do not have the Google Translate plugin installed, nor do I have any plans to install it. However, I'm inferring from some of my analytics data that people visiting my web site are using Google Translate to translate my pages. I presume they're visiting my site and seeing Google's This page is in English. Would you like to translate it to [their language]? and clicking Translate.Is there any hook in Google's automatic translation, e.g. some event fired, that I can use to detect these automatic translations and fire a Google Analytics event tracking the translation and hopefully capturing the language they're translating to? Note: I've seen this post, but the answer refers to the plugin, which I'm not using. I want to track when Google volunteers to translate automatically.
How do I track automatic translation of web page?
google analytics;google translate;translation;event tracking
null
_codereview.169690
I used some web resources to find how to make a web page with javascript validator for fractional numbers. What do you think about it? How it can be improved and still look like a web page? Your help will be highly apreciated. Thank you very much!!<html><head><title>JavaScript fractional numbers validator</title><script type=text/javascript> function checkDecimal() { var res=true; var orgValue=document.getElementById(Text1).value; var digit=parseFloat(document.getElementById(Text1).value); if(isNaN(digit)) { alert(not decimal number); res=false; return; } else if(orgValue.charAt(orgValue.length-1)=='.') { alert(not decimal number); res=false; return; } else { var i=0,count=0; for(i=0;i,i<orgvalue.length;i++)> { var posvalue=parseInt(orgValue.charAt(i)); if(!isNaN(posvalue)) { } else { posvalue=orgValue.charAt(i); if(posvalue=='.') { count++; } else{ res=false; break; } } } if(count==0||count>=2)/*if you use If(count>1) the it is work when you enter 12345 then display decimal number.*/ { res=false; } } if(res==true) alert(decimal number); else alert(not decimal number); }</script></head><body><form name=form1><div> Enter Decimal Number: <input id=Text1 type=text /> <br /><input id=Button1 type=button value=Check onclick=checkDecimal(); /></div></form></body></html>It will be great if the code is shorter and eventually possible to have maximum symbols length for the whole part that is different (let's say double) from the fraction part.
Validator for fractional numbers
javascript
How about this one? Representing numbers as object to be able to use the logic for both whole and fraction operations. Also using regexp to check input symbols and length:function checkNumber() { var stringsFromInput = document.getElementById(inputNumber).value.split(/[,\n.]/), numbers = [ { name: whole, regexp: /^[0-9]{1,10}$/, errorMsg: number expected to be 10 symbols maximum }, { name: fraction, regexp: /^[0-9]{0,5}$/, errorMsg: number expected to be 5 symbols maximum } ]; for (var n in numbers) { var name = numbers[n].name, value = stringsFromInput[n], regexp = numbers[n].regexp, msg = numbers[n].errorMsg, div = document.getElementById(name + Div); regexp.test(value) ? div.innerHTML = name + number is OK : div.innerHTML = name + msg; }}<form> <div class=form-group> <label for=inputNumber>Enter a number</label> <input type=string class=form-control id=inputNumber placeholder=123456789.54321> <button type=button onclick=checkNumber()>Check</button> </div> <div id=wholeDiv>Status will</div> <div id=fractionDiv>appear here</div></form>
_webmaster.9748
I want to change some legacy URL's like this:/modules.php?name=News&file=article&sid=600to this:/news/story/600/This is what I have tried:RewriteEngine onRewriteCond %{QUERY_STRING} ^name=News&file=([a-z_]+)&sid=([0-9]+)RewriteRule ^modules\.php /news/story/%2/ [R=301,L]However I still get 404's on the old URLs.I do have some other rewrite rules working, so I am pretty sure mod_rewrite is enabled and functioning. These rules are in a httpd.conf file in a VirtualHost container.I should also mention this is for a Python application (using Django) running with mod_wsgi. Should the rewrites happen before the URLs are passed to the wsgi application?Any ideas? Thanks.
Help with Apache mod_rewrite rules
apache;mod rewrite
I got it to work. It seems I had a couple of problems.I needed a forward slash on the pattern in RewriteRule; i.e.^/modules.php instead of^modules.php.I needed to prevent the query string from being appended to the new URL. This could cause recursion in some cases, or other strange things (400 bad request). A trailing ? did the trick.I ended up with this:RewriteEngine onRewriteCond %{QUERY_STRING} sid=([0-9]+)RewriteRule ^/modules\.php /news/story/%1/? [R=301,L]
_webmaster.19391
There is a website and the layout looks something like below: home->approved-> education entertainment business | | | kid, teenager, adult kid, teenager, adult kid, teenager, adult | | | and so on.. and so on.. and so on..home->not approved-> education entertainment business | | | kid, teenager, adult kid, teenager, adult kid, teenager, adult | | | and so on.. and so on.. and so on..On homepage, one would see two links - approved and not-approved. Once you click on any of the links, relevant entries will come up and then both pages also have filters on top for further drilling, see above. Urls are organized like below:Home/Approved will pull up all entries. Home/Approved/Education will pull up education only (and so on). Home/Approved/Education/Kid will pull up educational kid only (and so on). I am planning to organize my sitemap to have two static parent nodes - approved and not approved, and then add all entries dynamically to the sitemap to these two parent nodes and not include sublevels in sitemap at all.Do you see any problem/pitfall with this approach - in terms of seo or anything else?
Sitemap and url are laid out differently from each other
seo;sitemap;url rewriting
null
_datascience.17630
Say you have a binary classification problem, and a dataset with 20,000 observations and 20 columns. The target variable is very imbalanced, there are are missing values, skewed distributions, outliers, etc.My question is, in a general sense, what order should these data preprocessing steps be performed?Fill in missing values,Normalize/standardize data,Deal with skewness,Deal with outliers,Balance target variable classes
Correct sequence of data prep steps?
machine learning;data cleaning
null
_codereview.151362
I'm working with some math-heavy code in JavaScript. I just realized that there's a render that currently takes about 30 minutes. 95% of that time is spent in a single ~40 line function that I've pasted below. I am not extremely well-versed in JavaScript math optimization, so my first attempts to optimize this code haven't gone wonderfully.I would love any pointers as to what in here is slowing things down. I have good reason to believe that things are non-optimal because the same code in Python runs about 30x faster and JS is not a slow language.// return cost and gradient, given an arrangementcostGrad: function(Y) { var N = this.N; // About 5000 long var dim = this.dim; // About 300 long var P = this.P; // About 5000^2 long var pmul = this.iter < 100 ? 4 : 1; // trick that helps with local optima // compute current Q distribution, unnormalized first var Qu = zeros(N * N); var qsum = 0.0; for(var i=0;i<N;i++) { for(var j=i+1;j<N;j++) { var dsum = 0.0; for(var d=0;d<dim;d++) { var dhere = Y[i][d] - Y[j][d]; dsum += dhere * dhere; } var qu = 1.0 / (1.0 + dsum); // Student t-distribution Qu[i*N+j] = qu; Qu[j*N+i] = qu; qsum += 2 * qu; } } // normalize Q distribution to sum to 1 var NN = N*N; var Q = zeros(NN); for(var q=0;q<NN;q++) { Q[q] = Math.max(Qu[q] / qsum, 1e-100); } var cost = 0.0; var grad = []; for(var i=0;i<N;i++) { var gsum = new Array(dim); // init grad for point i for(var d=0;d<dim;d++) { gsum[d] = 0.0; } for(var j=0;j<N;j++) { cost += - P[i*N+j] * Math.log(Q[i*N+j]); // accumulate cost (the non-constant portion at least...) var premult = 4 * (pmul * P[i*N+j] - Q[i*N+j]) * Qu[i*N+j]; for(var d=0;d<dim;d++) { gsum[d] += premult * (Y[i][d] - Y[j][d]); } } grad.push(gsum); } return {cost: cost, grad: grad};}For those that are curious to see more, this is from the wonderful tsnejs library from Andrej Karpathy.
Gradient computation in JavaScript
javascript;performance;mathematics
null
_unix.368634
I need your help in understanding why I'm facing this strange problem.So I'll get to the set up:Windows 10 laptop as a host let's call this host win10.Vmware installed on win10two Linux VMs on VMware:fedora desktop let's call this vm1fedora server let's call this vm2both vm's are configured with static IP, somehow they both are automatically using the VMware application as a dns server which, as mentioned somewhere in vmware documentation, uses the win10 to resolve names.win10 has it's hosts files appended with the ip mappings of both vm'sNow here comes the twist:Another device is my android phone which is running wifi for win10 to connect to. Both vm's use NAT to access the internet through my phone.Symptoms:When win10 is connected to android wifi. All works well!!!When disconnected however both vm's can nslookup each other and vm1 can ping both itself, vm2 and win10. Vm2, however, can't ping anything it seems not even itself.Please provide any advice to solve this issue. I have no idea why everything works fine when connected to the internet but not when disconnected. None of my devices should depend on the internet for name resolution of local resources!!!I did some research and I found out that maybe I have this avahi software on vm1. But I'm not sure whether this can be the difference. Still doesn't explain why I can't ping with my vm2.Thank you.
Fedora VMs: nslookup works, ping does not when disconnected from Internet
fedora;dns;ping;nslookup
null
_codereview.83146
This is my second program in Python. I am aware that globals are a bad idea, but that is what I have learned so far in my course.Right now the program is doing what it's supposed to do, my only concern is that it might be too long for nothing. I'm asking you to help me figure out where I could make it simpler.import simpleguiimport randomimport math#Globals, random guess and player's remaining guessesnum_range = 100remaining_guesses = 7# New game, range from 0 - 100 by default# after the according button is pressed# Reset the remaining guesses to 7def range100(): global num_range global remaining_guesses remaining_guesses = 7 print New game. Range is from 0 to 100 print Number of remaining guesses is %i %(remaining_guesses) print num_range = random.randrange(0, 101) return num_range# Set game to a range of 0 - 1000 # after the according button is pressed# Reset the remaining guesses to 10def range1000(): global num_range global remaining_guesses remaining_guesses = 10 print New game. Range is from 0 to 1000 print Number of remaining guesses is %i %(remaining_guesses) print num_range = random.randrange(0, 1001) return num_range# Compare guess to random range# Remove 1 to remaining guesses# Display hint on the random range# Restart the game if player is correct or out of guessesdef input_guess(guess): guess = float(guess) global remaining_guesses global num_range remaining_guesses -= 1 print Your guess was: %i %(guess) print Number of remaining guesses is %i %(remaining_guesses) if (remaining_guesses == 0 and guess != num_range): print The correct answer was %i %(num_range) print Let's try again! print print range100() elif (remaining_guesses == 0 and guess == num_range): print Correct! print print range100() elif guess > num_range: print Try a lower number! elif guess < num_range: print Try a higher number! else: print Correct! print print range100() print return guess, remaining_guesses# Create & start framef = simplegui.create_frame(Guess the number, 200, 200)f.add_button(Range is [0, 100], range100, 200)f.add_button(Range is [0, 1000], range1000, 200)f.add_input('My label', input_guess, 50)f.start()# Start a new gamerange100()
Number-guessing game with simple GUI
python;beginner;gui;number guessing game
You have a function called input_guess(). That function inputs the guess, compares the guess, and plays the entire game. It should only input the guess. I would create a function to run the program, one to input the number, and one to do the comparison and output prompts about being too large or small. This way, only the function that plays the game needs to know the number of moves left. Once the number is correctly guessed, that function just returns to its caller, who can call it again if the user wants to play again. Also, try not to write functions this long.As for your range100() and range1000() functions, I would combine those into one function like this:def get_num(min, max): print New game. Range is from + min + to + max num = random.randrange(min, max + 1) return numYou can tell the user how many guesses they have left in the function that controls the game.Finally, you should have the part of the program that always runs in an if __name__ == __main__: block. This is for re-usability of your program, and you can read more about it here: What does if __name__ == __main__: do?.
_codereview.158068
I need to set date and time (12 hours 0 minutes) via Angular UI DatePicker Popup.plunkerI had two issues:1. When page was loaded:Input had value 17-March-2017 12:00:00.000. It's right.But Selected date was: 2017-03-17T14:57:51.080Z. It's not true, not 12:00.2. When I changed date via button:Input view was 24-March-2017 12:00:00.000Selected date was: 2017-03-24T09:00:00.000ZI solved both issues this way:I added defTime directive with formatters and parsers for input element;I added time service to set 12 hours. If I use ng-model-options={timezone: 'utc'} attribute in input, I don't need to subtract TimezoneOffset from Date differently for view (formatter) and model (parser) (Compare plunker ver.1 and ver.2).In ver.1 (without ng-model-options attribute):subtracting TimezoneOffset hours for $parsers;subtracting 0 hours for $formatters.Could you offer a better solution? Thanks.var app = angular.module('ui.bootstrap.demo', ['ui.bootstrap']);app.controller('DatepickerPopupDemoCtrl', function ($scope, time) { $scope.dt = time.getDefault(new Date());});app.directive('defTime', function (time) { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attrs, ngModel) { ngModel.$parsers.push(time.getDefault); ngModel.$formatters.push(time.getDefault); } }});app.service('time', function () { return { getDefault: getDefault } function getDefault(dateObj){ var tzOffset = new Date().getTimezoneOffset() / 60; var hoursTZ = 12 - tzOffset; return new Date(new Date(dateObj).setHours(hoursTZ, 0, 0, 0));}});<link href=//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css rel=stylesheet/><script src=//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js></script><script src=//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js></script><div ng-app=ui.bootstrap.demo> <div ng-controller=DatepickerPopupDemoCtrl> <pre>Selected date is: <em>{{dt}}</em></pre> <h4>Popup</h4> <div class=row> <div class=col-md-6> <p class=input-group> <input def-time type=text class=form-control uib-datepicker-popup=dd-MMMM-yyyy HH:mm:ss.sss ng-model-options={timezone: 'utc'} ng-model=dt is-open=opened/> <span class=input-group-btn> <button type=button class=btn btn-default ng-click=opened = !opened> <i class=glyphicon glyphicon-calendar></i> </button> </span> </p> </div> </div> </div></div>
Angular UI Datepicker Popup with Default Time
javascript;angular.js;angular bootstrap
null
_codereview.123923
I implemented a fixed-length stack in Java for use in my fractal generator program, an RPN calculator and my esolang interpreter. This is a generic stack, and goes over and above the call of duty in places to supply my esolang interpreter with some essential methods (the initStack(),dumpStack() and ...N() methods, as well duplication and reversal.This works fine when I use it for the fractal generator (I haven't tested the interpreter with the stack very much).Here's the code. Please suggest any improvements, lexical/syntactic or algorithmic, and especially about any bugs, if they arise.Note:I purposely throw a custom StackOverflowException subclassing java.lang.IndexOutOfBoundsException rather than a java.lang.StackOverflowError as the latter indicates an overflow of the JVM internal stack specifically.package in.tamchow.fractal.math;import java.io.Serializable;import java.util.EmptyStackException;/** * A generic fixed-length stack */public class FixedStack<E> implements Serializable { /**Array of elements*/ E[] elements; /**Stack top pointer*/ int top; /** * Parameterized constructor. No default constructor. * @param capacity The maximum size (capacity) of the stack * @see FixedStack#setSize(int) * @see FixedStack#resetTop(boolean) */ @SuppressWarnings(unchecked) public FixedStack(int capacity) { setSize(capacity); resetTop(false); } /** * Resets the stack top pointer depending on whether the stack is empty or full * @param notEmpty Whether or not the stack is empty */ public void resetTop(boolean notEmpty) { top = notEmpty ? 0 : elements.length; } /** * Note: Setting the size <b>WILL CLEAR THE STACK</b>. * @param size The size of the newly-initialized stack * @see FixedStack#resetTop(boolean) */ @SuppressWarnings(unchecked) public void setSize(int size){ this.elements = (E[]) new Object[size]; resetTop(false); } /** * Has the same effect as {@link FixedStack#setSize(int)}, * but does not reinitialize the elements array * @see FixedStack#setSize(int) * @see FixedStack#resetTop(boolean) */ public void erase() { for (int i = 0; i < elements.length; ++i) { elements[i] = null; } resetTop(false); } /** * Pushes a set of values onto the stack * @param values The values to push */ public void pushN(E[] values) { for (E value : values) { push(value); } } /** * Pushes a value onto the stack * @param value The value to push */ public void push(E value) { if (isFull()) throw new IndexOutOfBoundsException(Overflow Exception); elements[--top] = value; } /** * Checks whether the stack is full * @return Whether the stack is full or not */ public boolean isFull() { return (top == 0); } /** * Pops a set of values from the stack * @return The popped values */ @SuppressWarnings(unchecked) public E[] popN(int n) { E[] values = (E[]) new Object[n]; for (int i = 0; i < n; i++) { values[i] = pop(); } return values; } /** * Pops a value from the stack * @return The popped value */ public E pop() { if (isEmpty()) throw new EmptyStackException(); E value = elements[top]; elements[top++] = null; return value; } /** * Checks whether the stack is empty * @return Whether the stack is empty or not */ public boolean isEmpty() { return (top == elements.length); } /** * Peeks at a set of values on the stack * @param n The number of values to peek at * @return The peeked-at values */ @SuppressWarnings(unchecked) public E[] peekN(int n) { E[] values = (E[]) new Object[n]; for (int i = 0; i < n; i++) { values[i] = peek(i); } return values; } /** * Peeks at a value on the stack at a particular index * @param n The relative index of the value to peek at * @return The peeked-at value */ private E peek(int n) { if (isEmpty()) throw new EmptyStackException(); return elements[top - n]; } /** * Duplicates the n topmost elements of the stack, top-down. * @param n The number of elements to duplicate */ public void duplicateN(int n) { for (int i = 0; i < n; i++) { duplicate(); } } /** * Duplicates the topmost element of the stack */ public void duplicate() { push(peek()); } /** * Peeks at a value on the stack * @return The peeked-at value */ public E peek() { if (isEmpty()) throw new EmptyStackException(); return elements[top]; } /** * Reverses the stack * @see FixedStack#initStack(Object[]) */ @SuppressWarnings(unchecked) public void reverse() { E[] reversed = (E[]) new Object[elements.length]; for (int i = 0, j = reversed.length - 1; i < elements.length && j >= 0; i++, j--) { reversed[j] = elements[i]; } initStack(reversed); } /** * Initializes the stack with the supplied set of values * @param elements The set of initial values * @see FixedStack#pushN(Object[]) * @see FixedStack#setSize(int) */ @SuppressWarnings(unchecked) public void initStack(E[] elements) { setSize(elements.length); pushN(elements); } /** * Dumps the stack elements to the caller * @return The set of elements currently on the stack */ public E[] dumpStack() { return elements; } /** * Provides the current number of elements on the stack * @return The size of the stack */ public int size() { return elements.length - top; } /** * More conventional stack size calculation. * Use not recommended. * @return The size of the stack * @see FixedStack#size() */ public int sizeN() { int size = 0; for (E i : elements) { if (i != null) size++; } return size; } /** * Alias for {@link FixedStack#erase()} * @see FixedStack#erase() */ @SuppressWarnings(unchecked) public void clear() { erase(); }} /** * Custom Stack Overflow Exception class */ public class StackOverflowException extends IndexOutOfBoundsException{ /** * Constructs the exception with a default message */ public StackOverflowException(){ this(Stack Overflow); } /** * Constructs the exception with a custom message * @param message The custom message */ public StackOverflowException(String message){ super(message); } }
Fixed-length Stack in Java
java;array;generics;stack
1You should declare the fields elements and top as private. Also, since you do not expand the storage array (elements), you can declare it final as well.2It's kind of funny that your stack grows from larger indices towards smaller ones. I suggest you rename top to size, and make your stack grow towards larger indices. That way, the value of size will be the storage array index at which the next pushed element would be placed.3In the constructor, you call erase that sets all the storage array components to null. Don't do this, JVM initializes all object array components to null by default.
_cogsci.8976
As far as I can tell, both megalomania and narcissism are found in [delusions of] grandiosity. Perhaps megalomania has more focus on power, rather than just being well liked?What is the primary difference between the two?Are all megalomaniacs narcissists? Or all narcissists megalomaniacs? Or are they completely separate?
What is the difference between Megalomania and Narcissism?
abnormal psychology
The DSM (Diagnostic and Statistical Manual of Mental Disorders) doesn't distinguish between megalomania and narcissism. The most recent edition of the DSM (DSM-5) classifies both as a form of narcissistic personality disorder.
_softwareengineering.225263
About a year ago I had an idea in mind which was using my friends computers to help me process my data, so I programmed a socket server application with boost::asio, and gave the client part of it to my friends.When they connect they send the server (my machine) a message containing their computer specs (available cores, memory), based on that the server application decides how much data they can handle at a time and whenever they finish processing a batch they send a ready for more messages to my server, and the client applications keep sending data about the state of the process, and there is a lot of handling going in the background, whatever happens on the client machines its up to the server to take the right decision, if the connection with a client machine is lost and it has not been back in 5 minutes, the server keeps track of the data that has been sent to that machine and asks about it whenever that client reconnects.I started this project and I only had some basic knowledge in network programming and I didn't read about any patterns that could be used and I just used my guts but I found it really useful, I would like to expand it but I want to know if there is a known pattern for doing the same thing using TCP sockets, if yes what's the name of that pattern?I think of it as a super computer with its components spread around the world.So I would appreciate some resources about this kind of thing.
A Server sending data to be processed to clients
c++;c;server;sockets;client
The general concept you're referring to is distributed computing. More specifically, you seem to be doing some sort of volunteer computing. I'd suggest researching volunteer computing (on the magic googlebox) and looking into an existing project like BOINC.
_cogsci.8614
What is the name of a cognitive bias where a person takes all of their knowledge of a particular subject (at a point in time) and arranges it in a hypothesis or world model that makes sense to that individual?In particular I'm thinking of Sigmund Freud and his work on the interpretation of dreams. It seems to me that he took what he knew at the time and arranged it in a hypothesis, selectively including or excluding facts to the point where he deemed just about everything in dreams, from hats to stairs to buildings and mountains in dreams as referring to sexual content. I believe that Freud himself, in his book mentions that before him people were evaluating dreams as various influences of spirits or divines. A modern researcher might interpret dreams as a product of interaction of brain regions and neurotransmitter systems. Is this a cognitive bias or a general way in which a certain kind of brain (rational temperament) works?
What is the name of a cognitive bias by which existing facts are tailored to fit a personal hypothesis?
cognitive psychology;bias
null
_softwareengineering.215350
I have a hierarchy of classes that represents GUI controls. Something like this:Control->ContainerControl->FormI have to implement a series of algoritms that work with objects doing various stuff and I'm thinking that Visitor pattern would be the cleanest solution. Let take for example an algorithm which creates a Xml representaion of a hierarchy of objects. Using 'classic' approach I would do this:public abstract class Control{ public virtual XmlElement ToXML(XmlDocument document) { XmlElement xml = document.CreateElement(this.GetType().Name); // Create element, fill it with attributes declared with control return xml; }}public abstract class ContainerControl : Control{ public override XmlElement ToXML(XmlDocument document) { XmlElement xml = base.ToXML(document); // Use forech to fill XmlElement with child XmlElements return xml; }}public class Form : ContainerControl{ public override XmlElement ToXML(XmlDocument document) { XmlElement xml = base.ToXML(document); // Fill remaining elements declared in Form class return xml; }}But I'm not sure how to do this with visitor pattern. This is the basic implementation:public class ToXmlVisitor : IVisitor{ public void Visit(Form form) { }}Since even the abstract classes help with implementation I'm not sure how to do that properly in ToXmlVisitor?The reason that I'm considering Visitor pattern is that some algorithms will need references not available in project where the classes are implemented and there is a number of different algorithms so I'm avoiding large classes.
Understanding Visitor Pattern
c#;design patterns;object oriented design
The visitor pattern is a mechanism to simulate dual binding in programming languages that only support single binding. Unfortunately, that statement might not clarify things a lot, so let me explain with a simple example.In .NET and C#, the platform you are using, objects can be converted to strings using the ToString() function. What that funtion does, i.e. the code being executed, depends on the type of object you're applying it to (it's a virtual method). What code is executed depends on one thing, the one type of the object, hence the mechanism used is called single binding.But what if I want to have more than one way to convert an object to a string, for each different kind of object? What if I wanted to have two ways to convert objects to strings, so that the code being executed depends on two things: not only the object to be converted, but also the way in which we want it to be converted?That could be solved nicely if we had dual binding. But most OO languages, including C#, only support single binding. The visitor pattern solves the problem, by turning dual binding into two succesive single bindings.In our example above, it would use a virtual method in the object to convert, that calls a second virtual method in the object implementing the conversion algorithm.But that implies that the object upon which you want to apply the algorithm needs to collaborate with this: it needs to have support for the visitor pattern baked in.You seem to be using .NET's Windows Forms classes, which do not have support for the visitor pattern. More specifically, they would need to have a public virtual void Accept(IVisitor) method, which obviously they don't have.So, what's the alternative? Well, .NET does not only support single binding, it also supports dynamic binding, which is even more peowerful than dual binding.For more information on how to apply that technique, which will allow you to solve your problem (if I understand it well), take a look at Farewell Visitor.UPDATE:To apply the technique to your specific problem, first define your extension method:public static XmlDocument ToXml(this Control control){ XmlDocument xml = new XmlDocument(); XmlElement root = xml.CreateElement(control.GetType().Name); xml.AppendChild(root); Visit(control, xml, root); return xml;}Create the dynamic dispatcher:private static void Visit(Control control, XmlDocument xml, XmlElement root){ dynamic dynamicControl = control; //notice the 'dynamic' type. //this is the key to dynamic dispatch VisitCore(dynamicControl, xml, root);}Then fill in the specific methods:private static void VisitCore(Control control, XmlDocument xml, XmlElement root){ // TODO: specific Control handling}private static void VisitCore(ContainerControl control, XmlDocument xml, XmlElement root){ // call the base method VisitCore(control as Control, xml, root); // TODO: specific ContainerControl handling // for example: foreach (Control child in control.Controls) { XmlElement element = xml.CreateElement(child.GetType().Name); root.AppendChild(element); // call the dynamic dispatcher method Visit(child, xml, element); }}private static void VisitCore(Form control, XmlDocument xml, XmlElement root){ // call the base method VisitCore(control as ContainerControl, xml, root); // TODO: specific Form handling}
_webapps.101594
Using Google Translate, I managed to translate a webpage containing approximately 150000 characters, excluding spaces and HTML tags, from Korean to English. However, for a larger webpage, I got an error saying that the page is too big. So the limit is greater than 150000 characters, but my question is, what is the exact character limit for translating webpages?
What is the character limit of Google Translate's website translation service?
google translate
null
_cogsci.13097
Can two given neurons in the human brain can be directly connected more than once, either mutually or in the same or direction? Also, can the same neuron have transitive connections to itself (in order to amplify itself for example)?
Can two neurons in the brain be connected more than once?
neurobiology;neuroanatomy;neurophysiology
The commenter below alerted me to the existence of autapses, which apparently are chemical synapses between a neuron and itself. So those clearly exist. At the same time, it does seem that there is a mechanism that would suppress self-synapses: a protein called Dscam that acts during neuronal development. Dscam is a membrane protein that can form a high number of isoforms through alternative splicing and thereby provides an identity to the developing neuron to prevent forming connections to itself. I suspect that what is more common is for a neuron to be connected to itself indirectly. That is, neuron 1 stimulates neuron 2, which stimulates neuron 3, which stimulates neuron 1.EDIT: Just heard about this article, which shows that two neurons can be connected via two different synapses!
_softwareengineering.284650
I hope it is the right place to ask this. I wasn't sure if it belongs to Stack Overflow or Computer Science.Eventually this seemed more suitable. Anyway, some background first:A closed curve, is a curve with no endpoints and which completely encloses an area.A simple curve, is a curve that does not cross itself. Example: Now, given n ordered (x,y) coordinates that represents mouse movement, it is easy to determine if they form a closed curve (given an upper bound on the allowed distance between two points, of-course), but is there an algorithm that will determine whether or not the coordinates form a simple curve? I tried to look online for an answer, but couldn't find relevant solutions.
How to determine if set of ordered coordinates form a simple curve?
algorithms;geometry
You could argue that a curve is simple if there are no two line segments between points such that the lines intersect, meaning you could check if a curve is simple by verifying the absence of this condition.The algorithm would look something like:for each p1, p2 in pointlist for each p3, p4 in pointlist if line_segment(p1, p2) intersects line_segment(p3, p4) return falsereturn true Note that p2 would be the successive point after p1 and similarly, p4 would be the successive point after p3. In order to avoid redundancy, points p3 and p4 could start after points p1 and p2. This should be easily done in O(n^2) time. Be careful in your check for intersection since at least once the lines will be the same (no dividing by zero).If you have many such points, you could skip every other point and this algorithm will run 4 times faster at the small risk that a truly intersecting line may not be detected should the curve approach a tangent.
_unix.253161
Say I want to remove all digits from a text file using gedit 3.10.4advanced_find 3.6.0I have selected the Advanced Find/Replace plugin to support regular expressions out of an internet search. It seemed to stand out for simplicity, accessibility and users' endorsements. The version is claimed to be suitable for gedit 3.8 and later.The plugin has been successfully installed and activated in the Edit>Preferences>Plugin list.However, if I launch a regex substitution query for the object [:digit:], I get the message[:digit:] not found while there are digits aplenty. The same occurs for little variations like [:digit:]* or ([:digit:]*)Strangely, if I do precisely the same on the same document with LibreOffice Writer, the commands are executed flawlessly.What is the problem with gedit here? Is there a compatibility issue between host application and plugin? Need regular expression be typed in gedit according to specific rules? Did I miss anything obvious?Help to get the same capabilities with gedit as with LibreOffice Writer much appreciated.
Substitution with Regular Expressions in gedit
regular expression;gedit;plugin
I am not fully aware of LibreOffice's internal syntax, but if you are talking about regex, as in regular expressions, you will have to use the digit symbol \d.
_unix.243728
my_username@my_username-laptop MINGW64 ~ (master)$ ssh-keygen -t dsaGenerating public/private dsa key pair.Enter file in which to save the key (/c/Users/my_username/.ssh/id_dsa):EnterEnter passphrase (empty for no passphrase):EnterEnter same passphrase again: EnterYour identification has been saved in /c/Users/my_username/.ssh/id_dsa.Your public key has been saved in /c/Users/my_username/.ssh/id_dsa.pub.The key fingerprint is: EnterSHA256:KMLyesG1eWkXq1iI4y7i+4bmVKgZBdCnReukvJgrtP0 my_username@my_username-laptopThe key's randomart image is: Enter+---[DSA 1024]----+|+. .. || .. o. || .+o || +o+. .. ||oo=+o+..So ||.O*o+.= o ||*o*o = o ||=*oo. . ||OB=..E |+----[SHA256]-----+my_username@my_username-laptop MINGW64 ~ (master)$ cd .sshmy_username@my_username-laptop MINGW64 ~/.ssh (master)$ cd ~/.sshmy_username@my_username-laptop MINGW64 ~/.ssh (master)$ lsgithub_rsa id_dsa known_hosts rsa_key_pair.pubgithub_rsa.pub id_dsa.pub rsa_key_pairmy_username@my_username-laptop MINGW64 ~/.ssh (master)$ ls -latotal 45drwxr-xr-x 1 my_username 197121 0 Nov 17 23:43 ./drwxr-xr-x 1 my_username 197121 0 Nov 17 23:08 ../-rw-r--r-- 1 my_username 197121 668 Nov 17 23:43 id_dsa-rw-r--r-- 1 my_username 197121 614 Nov 17 23:43 id_dsa.pubmy_username@my_username-laptop MINGW64 ~/.ssh (master)$ cat id_dsa.pubssh-dss AAAAB3NzaC1kc3MAAACBAOrkqv9wt7WcngRfKSaMrCSXn8BfJZN7wEJWvpuqpTYWBzCAylqUSVA+GpMuXGhaDdwHJFftmoxi81PnASpIoZZrIRgqRHRnQph9DnQikB1Bkf4B+EpzD3EwKYWRUOFrHwnjPU1ByRgFOTADXn/O9SIj+9APKer9xFNHaBvv9AvDAAAAFQCYK15hX9llcyIPsHedNTpE0BhgaQAAAIAZ3xOjbu1Vs0yposrwfHdc1+WoUdt89Y8a2YEvmeToR7/M7SM6IPPgbxLTz6l32pbmFFUDknMpX0rL/VaP/ygLifKJDxtWlE2doQR+2FwsvQKnk1wyXlYGXPCaI6flxqJRVV8/VJapQBRAC/cC6g6MNPbTs9GyV/z/SYBE/f4EhgAAAIEAlVinwInGC2gfWL5y7iPmv4gHWuJx0bmGq8Dc5UGdB99uxGRkdOlPFQ8BP6dZ1T8+DlikwPE2CH7RNIb+08KEvtdRJCy++6x0wnvL6ApPM1szNL+gUdL8X2/Mt9r2bj3LvjIrz21u4lXgOa+OsCanu4yUfHhPcj5YgQrrrn3P0Gs= my_username@my_username-laptopmy_username@my_username-laptop MINGW64 ~/.ssh (master)my_username@my_username-laptop MINGW64 ~ (master)$ ssh -vT [email protected]_7.1p1, OpenSSL 1.0.2d 9 Jul 2015debug1: Reading configuration data /etc/ssh/ssh_configdebug1: Connecting to github.com [192.30.252.129] port 22.debug1: Connection established.debug1: key_load_public: No such file or directorydebug1: identity file /c/Users/my_username/.ssh/id_rsa type -1debug1: key_load_public: No such file or directorydebug1: identity file /c/Users/my_username/.ssh/id_rsa-cert type -1debug1: key_load_public: No such file or directorydebug1: identity file /c/Users/my_username/.ssh/id_dsa type -1debug1: key_load_public: No such file or directorydebug1: identity file /c/Users/my_username/.ssh/id_dsa-cert type -1debug1: key_load_public: No such file or directorydebug1: identity file /c/Users/my_username/.ssh/id_ecdsa type -1debug1: key_load_public: No such file or directorydebug1: identity file /c/Users/my_username/.ssh/id_ecdsa-cert type -1debug1: key_load_public: No such file or directorydebug1: identity file /c/Users/my_username/.ssh/id_ed25519 type -1debug1: key_load_public: No such file or directorydebug1: identity file /c/Users/my_username/.ssh/id_ed25519-cert type -1debug1: Enabling compatibility mode for protocol 2.0debug1: Local version string SSH-2.0-OpenSSH_7.1debug1: Remote protocol version 2.0, remote software version libssh-0.7.0debug1: no match: libssh-0.7.0debug1: Authenticating to github.com:22 as 'git'debug1: SSH2_MSG_KEXINIT sentdebug1: SSH2_MSG_KEXINIT receiveddebug1: kex: server->client [email protected] <implicit> nonedebug1: kex: client->server [email protected] <implicit> nonedebug1: expecting SSH2_MSG_KEX_ECDH_REPLYdebug1: Server host key: ssh-rsa SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8debug1: Host 'github.com' is known and matches the RSA host key.debug1: Found key in /c/Users/my_username/.ssh/known_hosts:1Warning: Permanently added the RSA host key for IP address '192.30.252.129' to the list of known hosts.debug1: SSH2_MSG_NEWKEYS sentdebug1: expecting SSH2_MSG_NEWKEYSdebug1: SSH2_MSG_NEWKEYS receiveddebug1: Roaming not allowed by serverdebug1: SSH2_MSG_SERVICE_REQUEST sentdebug1: SSH2_MSG_SERVICE_ACCEPT receiveddebug1: Authentications that can continue: publickeydebug1: Next authentication method: publickeydebug1: Trying private key: /c/Users/my_username/.ssh/id_rsadebug1: Trying private key: /c/Users/my_username/.ssh/id_dsadebug1: Trying private key: /c/Users/my_username/.ssh/id_ecdsadebug1: Trying private key: /c/Users/my_username/.ssh/id_ed25519debug1: No more authentication methods to try.Permission denied (publickey).my_username@my_username-laptop MINGW64 ~ (master)$ ssh-agent -sSSH_AUTH_SOCK=/tmp/ssh-8kgSDhweA5gl/agent.11684; export SSH_AUTH_SOCK;SSH_AGENT_PID=13892; export SSH_AGENT_PID;echo Agent pid 13892;my_username@my_username-laptop MINGW64 ~ (master)$ ssh-add -lCould not open a connection to your authentication agent.my_username@my_username-laptop MINGW64 ~ (master)$
Why can't I authenticate to GitHub?
ssh;ssh agent;github
null
_cs.28811
I'm more or less familiar with the landau symbols, most specifically in computer science for complexity, however I was wondering if someone could clarify a bit for me. I'll just mention that I know that technically the correct notation is to say $f(n)$ is an element of $O(f(n))$, not $f(n) = O(f(n))$.Loosely, my understanding is this, given$ f(n) = n^2 + 2n +log(n)$ Big O represents the upper magnitude, so it would be correct (according to a past CS tutor), but not very accurate, to say $O(f(n)) = n^3$, but incorrect to say $O(n) = log(n)$, whereas the $(f(n)) $represents the lower bound, so it would be correct, but inaccurate to say $(f(n)) = log(n)$ or (not sure about this one), $(f(n)) = 1$.I know that $(f(n))$ is defined as the intersection of $O(f(n))$ and $(f(n))$, but is it valid to drop off lower orders of magnitude in the case of $(f(n))$? ie. is $(f(n)) = n^2$ correct? If not, what is the correct equality?What I am entirely unsure about is $o(f(n))$ and $(f(n))$. I've seen the mathematical definitions and I know that the only difference between them and $O(f(n))$ and $(f(n)) $respectively is that rather than there exists C, it is for all C, but my understanding of mathematical symbols is (at this stage) embarrassing. If anyone could shed some light on all of the above it'd be appreciated, thanks.
Can someone clarify landau symbols definition please?
asymptotics;landau notation
null
_softwareengineering.229055
I have two libraries that implement a protocol: one provides tools for establishing a channel between two parts, and the other provides classes and tools for building and parsing the binary protocol messages.These two libraries can be used independently, they don't depend on each other, and each has its own build setup. However, they do share a common set of examples (using both libraries) and documentation (tutorials).I have two alternatives in mind for organizing this in Git repositories:Alternative 1Make each library be in its own repository. A central repository would keep the common documentation, examples and tools for cloning both repositories and bootstraping them. Users would use this main repository, and developers would work on the dedicated repositories.I don't want to use Git submodules since they are hard to manage this way (versioning becomes much harder to do when the libraries constantly change).Alternative 2Place it all together: both libraries, documentation and examples. Versioning would be applied to both libraries, since they would be treated as a single (though separated) entity.This is how we are doing it now. It makes things simpler but I feel it could be improved.So... what are the best practices for organizing it all using Git? I'm open to other alternatives too.Even though we're not using it right now, it's possible that we will be using continuous integration tools, automated testing and builds, etc.
How to organize repositories for a split library?
git;libraries;organization;repository
null
_webmaster.78794
We have a number of sites on this dedicated server. Pages from one site are showing up on another site. Example:clientsite1.com (right site, no SSL installed)clientsite2.com (forwards to SSL, shows right site)clientsite1.com (no SSL installed, WRONG site, shows clientsite2 after untrusted connection message)Now I'm in WHM and this is what I see: The one that says Is primary website on IP address? is the one that's showing up improperly across all non-SSL domains. I am assuming this is because the OTHER domain on our IP address has Web SNI enabled, which apparently allows you to use multiple certificates on one IP?To fix this problem, would someone confirm these steps please? Get each site on own dedicated IP.Delete the SSL host for each site in WHM.Re-add the SSL host for each site in WHM, with new dedicated IP address.Or I can somehow also enable Web SNI for the domain that is currently showing improperly? Not sure how to do that, but I'll look it up if someone can confirm it will fix the problem.I found another question on here with this comment but I'm not sure if it applies to my situation: ... at least on Apache a properly setup name-based virtualhost should display the correct content, even with SSL (I've used this myself). You'll get the this is a bogus cert warning, but if the client accepts the cert, the client will still send the Host header to the server, which Apache should use to select a VirtualHost block and show the correct content, not someone else's site. Is that the case here? If this is the case, what can I say to my webhost that will make them understand (and fix!) the problem?
Dedicated server issues with SSL and IPs, content showing on wrong site
web hosting;https
null
_softwareengineering.329221
The page is loaded as a normal MVC page. The ajax is so the user can add items to their model without having to reload the page.Right now there is no Web API in the project. I don't want to add it unless it makes sense but I'm worried that using AJAX on an MVC controller is bad.All the books I've read and at work we only do AJAX to Web API. Is that a convention or am I allowed to POST an AJAX to an MVC Controller?
Can I do a POST AJAX to an MVC Controller or should I use Web API?
asp.net mvc
null