id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_softwareengineering.121831
I want my scribbles of a program's design and behaviour to become more streamlined and have a common language with other developers.I looked at UML and in principle it seems to be what I'm looking for, but it seems to be overkill. The information I found online also seems very bloated and academic.How can I understand UML in plain-English way, enough to be able to explain it to my colleagues? What are the canonical resources for understanding UML at a ground level?
What are the essential things one needs to know about UML?
design;uml
Liked the questions - same ones as I've asked myself:How can I understand UML in plain-English way, enough to be able to explain it to my colleagues? What are the canonical resources for understanding UML at a ground level?Here is what I have found:For a kick-start: my choice would be Fowlers UML Distilled.It really is a distillation of the basics, as has been mentioned: definitions, examples, advice on when a certain type of diagram should or should not be used. It is also a good reference, if you want to focus on a certain part of UML without reading the book cover-to-cover.For a more detailed, yet plain-English introduction: UML 2 for Dummies has done for my colleagues and me.It not only introduces UML, its syntax and uses at length, but has a lot of advice on good programming and design practices.There are occasional differences between the two books on what syntax belongs to which version of the UML standard. These however are minute and definitely not essential for using UML diagrams to communicate design ideas.(For example: whether UML 2 allows discrete multiplicities, i.e. showing that a certain property may have exactly X, Y or Z objects, rather than just zero, one, many or more than X, say; when participants names should be underlined...)For a totally non-academic and less wordy introduction: this blog has articles on various bits of UML:http://blog.diadraw.com/category/uml/It's not a textbook, so is far from exhaustive, but also uses non-textbook stories and examples, which are relatable to. The few available posts are focused on introducing UML concepts visually, so you can skip the reading of the text altogether.
_cogsci.12219
Just out of curiosity, regardingly highly unlikely situations of ever needing to disarm someone - using neuroscience to make informed self defence decisions:How fast can the brain recieve a visual or reflexive (seeing me beginning to move my hand, or feeling my hand hit the wrist -- I suspect the two impulses might have differing response times) signals from the body, to the moment of signaling the finger muscles?
How fast can the brain react in order for someone to pull a trigger?
reaction time
Short answerThe motor response latency to a visual stimulus is approximately 210 ms.BackgroundYou are basically asking for the visually induced reaction time of a motor response. Reaction times have been assessed many times in various studies. In a very recent study with an impressive subject population of more than 1400 (aged 18 - 65), the motor response latency to a visual stimulus was estimated at an average of 213 ms. Reaction times increased with age, but were unaffected by sex or educational level. Old age mainly affected the motor latency, and not so much the visual processing speed.Reference- Woods et al., Frontiers Human Neurosci (2015); 9:131-12p
_webmaster.15526
I am preparing to have my web application in a private beta. The application when fully live will have a lot more content than in beta. Currently our plan is to release it to limited users with limited content to ensure that all the business functions are working fine.We plan to use Google to power the search within the application. My question is will there be any negative impact in future (in terms of page rank or reputation) if we let Google crawl it in its present state? Or should we wait till it is fully functional to let Google crawl it.
Google crawl on uncompleted site
search engines;google search
That's perfectly fine. All you're doing is adding content to your site which is what most sites do every day. A perfect example of that is this page right here. By asking this question and by me answering it we're creating new content for this site. So letting Google find your site with less content then you plan on ultimately having is common and normal. Google will keep coming back to find new content so it can index it and hopefully rank it well.
_unix.31634
I am running OS X 10.7 and I am learning unix commands. I would like to set up a very basic cron job that sends me an email with a certain message.How would I go about this. From what I have read, I should receive an email automatically unless I specify otherwise.I don't seem to have the crontab file in the /etc directory.Any help is more than appreciated.
I want to set up a basic cron job that sends an email
cron;email
null
_unix.140620
I'm using egrep with the -o option in order to just get the matching part of the line, e.g.cat /usr/share/dict/words | egrep -o '(aa|ii)'Now I'd like to see some context of the match, i.e. a few characters on the left and on the right. One way to achieve this is bycat /usr/share/dict/words | egrep -o '.{3}(aa|ii).{2}'Is there a better (more efficient and elegant) way? (I've gone through the egrep commandline options but didn't find one for this purpose.)
Context of the matching regular expression
grep;regular expression
You could do something like:$ echo 'aabiicaa' | perl -lne ' while (/aa|ii/g) {print substr($`,-3).[$&].substr($'\'',0,2)}'[aa]biaab[ii]caiic[aa]
_webmaster.44647
I am building a web application for a client. I never set up a server using IIS. He needs me to configure the server to work with mySQL, php, and phpmyadmin. The server, is completely empty/unconfigured version of IIS 6. I need to set it up so the web application I built is completely accessible on the www. Not sure how long this will take me. It may take anywhere from 10-50 hours, I am not sure. I worked on set up servers using IIS, I never configured one from scratch. I am afraid that troubleshooting, and getting everything working as it should may take me days...What would be a reasonable charge for this service?I appreciate any advice,Many thanks in advance!
Client asking for estimate to set up/ configure his server
web development;website design;server;freelancer
null
_codereview.64401
This code is similar to Underscore. I've added in some functions to fill in different use cases.For example, one can use someKey to iterate through localStorage and sessionStorage.Underscore does not have a good way to loop through localStorage / sessionStorage as it is incorrectly detected as an array like object, i.e. it has a length property but does not have indices./***************************************************************************************************UTILITYThis is a small and efficient utility library. There is additional coverage,consistent ordering, consistent naming conventions, increased input validation, increased structure,and fewer function branches compared to underscore.*//*jslint browser: true, forin: true, plusplus: true, eqeq: true, ass: true*/(function (global, undef) { use strict; // holds (Pub)lic properties for the package var Pub = {}, // holds (Priv)ate properties for the package Priv = {}, // native prototype methods nativeSlice = Array.prototype.slice, nativeSome = Array.prototype.some, nativeToString = Object.prototype.toString; // handles global variable management Pub.noWar = (function () { // Priv.g holds the single user-defined global variable Priv.g = '$A'; Priv.previous = global[Priv.g]; Pub.pack = { utility: true }; return function () { var temp = global[Priv.g]; global[Priv.g] = Priv.previous; return temp; }; }()); // returns type in a capitalized string form // typeof is only accurate for function, string, number, boolean, and // undefined. null and array are both reported as objects // also typeof does not detect boxed values such as `new Number(1)` Pub.getType = function (obj) { return nativeToString.call(obj).slice(8, -1); }; Pub.isType = function (type, obj) { return Pub.getType(obj) === type; }; Pub.isGone = function (obj) { return obj == null; }; // detects null, undefined, NaN, '', , 0, -0, false Pub.isFalsy = function (obj) { return !obj; }; Pub.hasLength = function (obj) { if (obj == null) { return false; } return obj.length === +obj.length; }; // *underscore calls this, isObject Pub.isObjectWritable = function (obj) { return Object(obj) === obj; }; // *breaks naming convention for compatibility with underscore Pub.isObjectLiteral = function (obj) { return nativeToString.call(obj) === '[object Object]'; }; //compare to underscore // - on a func truthy match returns true and on no match returns false // - on func/obj validation fail returns false // - does not insert identity function on func validation fail Pub.someKey = function (obj, func, con) { var key; if (typeof func !== 'function') { return false; } for (key in obj) { if (obj.hasOwnProperty(key)) { if (func.call(con, obj[key], key, obj)) { return true; } } } return false; }; Pub.someIndex = function (arr, func, con) { var ind, len; // validation - prevent type errors if ((arr == null) || (arr.length !== +arr.length) || (typeof func !== 'function')) { return false; } // delegate to native some() if (nativeSome && arr.some === nativeSome) { return arr.some(func, con); } for (ind = 0, len = arr.length; ind < len; ind++) { if (func.call(con, arr[ind], ind, arr)) { return true; } } return false; }; Pub.someString = function (str, func, con) { if (typeof str !== 'string') { return false; } return Pub.someIndex(str.split(/\s+/), func, con); }; Pub.morph = function (obj, func) { if (typeof func !== 'function') { return false; } Pub.someKey(obj, function (val, key) { obj[key] = func(val); }); return obj; }; // near direct copy from underscore Pub.lacks = function (obj) { Pub.someIndex(nativeSlice.call(arguments, 1), function (val) { var lacks; if (val) { for (lacks in val) { if (obj[lacks] === undef) { obj[lacks] = val[lacks]; } } } }); return obj; }; // shallow clone Pub.cloneFlat = function (obj) { if (!Pub.isObjectWritable(obj)) { return obj; } return Pub.isType('Array', obj) ? obj.slice() : Pub.extendFlat({}, obj); }; // extends non-prototype properties from obj2 on to obj1 // with out any over writing. does not extend up the prototype chain. Pub.extendSafe = function (obj1, obj2) { var key; for (key in obj2) { if (obj2.hasOwnProperty(key)) { if (obj1.hasOwnProperty(key)) { throw new Error(naming collision: + key); } obj1[key] = obj2[key]; } } return obj1; }; // does not extend up the prototype chain like underscore Pub.extendFlat = function (obj) { Pub.someIndex(nativeSlice.call(arguments, 1), function (object) { var key; if (object) { for (key in object) { if (object.hasOwnProperty(key)) { obj[key] = object[key]; } } } }); return obj; }; // for adding underscore and a suffix Pub.addU = function (str, suf) { if (typeof str !== 'string' || typeof suf !== 'string') { return false; } return str + '_' + suf; }; // for removing the last underscore and suffix Pub.removeU = function (str) { var res; if (typeof str !== 'string') { return false; } res = str.lastIndexOf(_); if (res !== -1) { return str.slice(0, res); } return false; }; // first key that for / in will iterate through Pub.firstKey = function (obj) { var prop; for (prop in obj) { if (obj.hasOwnProperty(prop)) { return prop; } } return false; }; Pub.testKeys = function (keys, pattern, func) { var test = '', key; for (key in keys) { test += key; } if (test === pattern) { func(); } }; // runtTest(test_foo, [input1, input2], function(arr){//write test here}); Pub.runTest = (function () { var tests = {}; return function (name, arr, func) { tests[name] = func.apply(this, arr); }; }()); Pub.prettyTime = function (post_time) { var NORMALIZE = 1000, // 1000 milliseconds in a second MINUTE = 60, // 60 seconds in a minute HOUR = 3600, // 3600 seconds in an hour DAY = 43200, // 43,200 seconds in a day // server time is in seconds while browser time is in milliseconds current_time = Math.round(Date.now() / NORMALIZE), rounded_time, elapsed_time, string = ''; // synch factor actually exeeds transit time in some cases // post_time originates on the server as a unix time stamp // and current_time we calculate above if (current_time < post_time) { current_time = post_time; } elapsed_time = (current_time - post_time); if (elapsed_time === 0) { string = ' just a second ago'; // 0 to 1 minute ago } else if ((elapsed_time > 0) && (elapsed_time < MINUTE)) { string = (elapsed_time === 1) ? 'one second ago' : (elapsed_time + ' seconds ago'); // 1 minute to 1 hour ago } else if ((elapsed_time >= MINUTE) && (elapsed_time < HOUR)) { rounded_time = Math.floor(elapsed_time / MINUTE); string = (rounded_time === 1) ? 'one minute ago' : (rounded_time + ' minutes ago'); // 1 hour to to 1 day ago } else if ((elapsed_time >= HOUR) && (elapsed_time < DAY)) { rounded_time = Math.floor(elapsed_time / HOUR); string = (rounded_time === 1) ? 'one hour ago' : (rounded_time + ' hours ago'); // more than 1 day ago } else if ((elapsed_time >= DAY)) { rounded_time = new Date(post_time * NORMALIZE); string = 'on ' + rounded_time.toLocaleDateString(); } return string; }; // Used for primitives saved to localStorage and sessionStorage Pub.unStringify = function (string) { // Booleans first if (string === true) { return true; } if (string === false) { return false; } }; // for the arc library global[Priv.g] = Pub.extendSafe(global[Priv.g] || {}, Pub); // for underscore mixins global.ArcUtility = Pub;}(this));
Utility library and Underscore mixin - 1
javascript;underscore.js;mixins
Quick review, in no particular order. I haven't gone line by line, I just scrolled around and noted what I saw.Firstly, the good stuff:Consistent style (almost, see #8 below)use strict;jslint-checkedThen, the not-so-good stuffNaming convention may be internally consistent (not that I can really tell), but your library is not, in my opinion, quite large enough to get away with it. The first function I come across is called noWar. This seems to be (the documentation is lacking) your library's implementation of the common noConflict function - so why not call it that? Right now it's just a cutesy name for a function that should aim for external consistency.It's almost ironic that a function that exists to play nice with other code goes out of its way to do things differently.isGone and isFalsy should be defined as negations of calling isHere and isTruthy respectively. Or vice-versa. The whole point is that those functions report the opposite of their counterparts; don't write separate logic for either one, even when that logic is pretty straightforward.Similar to the above, hasLength should also use isGone in its internal check. Don't repeat logic. And someIndex should be calling hasLength and isType in its checks. If your library doesn't trust its own functions, why should anyone?These two comments confuse me:// *underscore calls this, isObject...// *breaks naming convention for compatibility with underscoreSo... in one case, you use your own name for something, underscore be damned, but in the very next function, you break naming convention (though I don't see how) specifically to match underscore. Huh?Naming in general: I just don't get many of these names, and with spotty documentation, I'm often left wondering. For instance testKeys. I can read the code, but I have no idea what I'd ever use it for.Speaking of testKeys: Why does it take a callback when it's not asynchronous? It can just return a boolean. How can I be sure it'll do what I expect? Objects are unordered, so if the keys object contains the keys foo and bar, and my pattern string is foobar, the string that's being tested might still be barfoo. And it doesn't use hasOwnProperty like everything else.runTest doesn't appear to let anyone access its internal tests object, nor does it return the result of the test being run. So you run a test, and... what? You always get undefined back, and tests is forever a private closure.prettyTime. Nice - unless you want another language than English, of course. The entire function just doesn't seem germane to whatever else the library is doing.Furthermore it looks like a copy-paste job, since all the variables are snake_cased, while the rest of you code is camelCased. My bad, the style is consistent with the other functions (see comments). I would add, though, that distinguishing between functions and variables is sort of pointless in JS. Functions are variables. So I'm not sure the distinction makes sense.addU and removeU. These functions are just overly specific (and complex). Besides, removeU will fail if the original suffix contains an underscore already: removeU(addU(test, my_suffix)) will return test_my. So it'll only work for some kinds of strings, meaning it's probably built to work for your strings in your project. In another context, you or anyone else might have to do their own utility methods anyway, so as a utility library function there's not much value here, I'm afraid.firstKey. Again: Objects do not guarantee any ordering of their keys, so the function doesn't really do anything useful. At worst it misinforms the caller. It's entirely dependent on the vagaries of the runtime. To quote the spec: The mechanics and order of enumerating the properties [...] is not specified. (emphasis added)In all, this doesn't seem like a generic library (like underscore). It does have some generally applicable functions, sure, but it's also got some pretty context-specific and sometimes mystifying functions.
_softwareengineering.270216
My current company has a Jenkins/DotCi setup. Our current process for CI is when dev pushes to github, jenkins runs unit tests on all branches and reports back to us via email if the unit tests failed. If on master, we then run a deploy to a UAT environment and we will soon be activating our integration tests after a deploy occurs successfully.We want to run our integration tests against our Staging environment on a daily basis. With the Build Periodically feature under Config i know we can specify when we trigger it to occur, however is there a way to have it trigger the integration test only rather than having to deploy?
Scheduling a Jenkins job to only run integration test
unit testing;testing;continuous integration;integration tests;jenkins
You can create a new job that only runs your integration tests. I always split up jobs like this:build + unit testdeploy into UATrun smoke testsrun integration tests / UATTake a look at the plugins Build Result Trigger, and the new Build Flow Plugin.You can also just trigger another job with plain Jenkins without any plugin. In your job, add a Post build step and make it Run anther job.edit If you need to copy artifacts from one build to another (to create a build+deploy pipeline), you can use the Copy Artifact Plugin.
_codereview.161089
Just completed a piece of code - a credit card validation program in python - as a little side project. Having no experience with classes in the past, I decided to employ classes in this project.I am wondering if you could review my code, both appraising the actual code, but also evaluate my use of OOP/classes.The requirements for the program are:The user enters their name, postcode, the card code, and the card date.The eighth digit of the card code is removed and acts as a check digitThe code is then reversedThe 1st, 3rd, 5th, and 7th digits are multiplied by 2If the result of the multiplication is > 9, subtract 9 from it.If the sum of the 7 digits, and the check digit are divisable by 10, the code is validThe card date must also be in the future.Finally, output their name, postcode, card number, and whether it is valid or not.The code:Program used to check if a credit card is authentic.# !/usr/bin/env python# -*- coding: utf-8 -*-# Check it outimport datetimeclass Customer: Class representing the customer and their credit card details # Constructor def __init__(self): self.name = input(Name: ) self.postcode = input(Postcode: ) self.card_date = input(Card date: ) self.card_code = input(Card code: ).strip() def check_date(self): Checks current date against the credit card's date. If it is valid, returns True; else False. card = datetime.datetime.strptime(self.card_date, %d/%m/%Y).date() if datetime.date.today() < card: return True else: return False def check_code(self): Contains the algorithm to check if the card code is authentic code_list = list(str(self.card_code)) check_digit = int(code_list[7]) code_list.pop() # The last digit is assigned to be a check digit and is removed from the list. code_list.reverse() for item in code_list: temp_location = code_list.index(item) if is_even(temp_location): code_list[temp_location] = int(item) * 2 # Loops over each digit, if it is even, multiplies the digit by 2. for item in code_list: temp_location = code_list.index(item) if int(item) > 9: code_list[temp_location] = int(item) - 9 # For each digit, if it is greater than 9; 9 is subtracted from it. sum_list = 0 for item in code_list: sum_list += int(item) # Calculates the sum of the digits code_total = sum_list + int(check_digit) if code_total % 10 == 0: return True else: return False # If the code is divisible by 10, returns True, else, it returns False. def check_auth(self): Checks the card's authenticity. if self.check_code() and self.check_date(): print(----------------------) print(Valid) print(self.name) print(self.postcode) print(self.card_date) print(self.card_code) else: print(----------------------) print(Invalid) print(self.name) print(self.postcode)def is_even(number): Function used to test if a number is even. if number % 2 == 0: return True else: return Falseif __name__ == __main__: customer().check_auth()
Credit card validation - Python 3.4
python;python 3.x;validation;checksum
I think there is this code organization issue - you have a class named Customer, but it, aside from the .name attribute, consists of credit-card related logic only. I would also pass the obtained attributes to the class constructor instead of asking for them inside it:def __init__(self, name, post_code, card_date, card_code): self.name = name self.post_code = post_code self.card_date = card_date self.card_code = card_codeIt is a little bit cleaner to do this way since now our class is more generic, it is agnostic of where the attributes are coming from.Some other code-style related notes:consistent naming: rename postcode to post_code revise the quality and necessity of comments: there is probably not much sense in having a comment # Constructor you can simplify the way you return a boolean result from your methods. For instance, you can replace:if datetime.date.today() < card: return Trueelse: return Falsewith:return datetime.date.today() < cardAnd, it's worth mentioning that, generally speaking, if you doing this for production, you should not be reinventing the wheel and switch to a more mature, well-used and tested package like pycard.
_unix.29181
Nautilus is taking up 450 MiB according to System Monitor (Ubuntu 10.04).$pmap <PID of Nautilus>...total 1578276KIs pmap reporting 1.5 GiB of memory here? I'm trying to find out what's taking up the 450 MiB so I can deduce what I'm doing wrong, or where the problem lies.
Impossible pmap results
ubuntu;memory;nautilus
There's no simple notion of how much memory is used by a program.The output of pmap describes all the virtual memory that's mapped by a process. Mapped means that the process can access that data through a pointer, without issuing any further command to load data or request access. Mapped virtual memory isn't always in RAM: it can be swapped out, and it can be in a file. For example, all the shared libraries that are used by a program are mapped in each process that uses them, but (for the most part) only one copy is kept in RAM for the whole system, and that copy need not be fully loaded in memory (parts that are required will be loaded from the disk file on when needed). The 1.5GB figure includes all of the process's code, static data, shared memory and own data. It's not a very meaningful figure.pmap is a simple reformatting of /proc/$pid/maps. Understanding Linux /proc/id/maps explains what the columns mean.The 450MB figure is (I think) the process's resident set, that is, the non-shared memory that is currently in RAM. This includes both data that belongs only to the process (and which may get swapped out), and files that the process has opened for writing (disk buffers, which may be evicted to be reloaded later from the file).You won't easily be able to break down the 450MB memory further. This is a job for the program's author, with debugging tools.
_hardwarecs.7984
I need to buy or build a machine for my research in Deep Learning and Computer Vision. I read in some tutorial about building a machine for Deep Learning, it suggested using a CPU with minimum 8 Cores, where Cache Doesn't Matter even some people suggest that CPU power doesn't matter as much as GPU. They also suggested a minimum of 8GB RAM and a GPU with at least 2GB Memory. Suggested GPU GTX 680, GTX 980 and GTX 1080. First two are not available here.The reason why I'm not following already available suggestions is that I have low budget and I'm considering only those options which are available as used or at low cost in Pakistan.So far I have visited local stores and I have been offered following packages. But none of the store owner has ever encountered a person working in machine learning or vision so neither they know anything about requirements nor I. That's why I don't even know if all these components offered in packages below will work optimally together or not. So Please have a look at them and let me know if they is something wrong with using one kind of processor on a kind of motherboard or GPU compatibility with board or processor.I also open for mixed suggestions e.g. using GPU offered in one package and CPU from other but I want to keep my budget as low as $1000 with a little margin. Prices of some components are provided separately.Option 1 ($991 or PKR 104500)Asus X99 Board (Supports 40 Lane PCIe 3.0) - USED ($237)Intel Core i7-5820K (6 Core, 3.3 GHz, 15M Cache) - USED ($332)16 GB DDR4 RAM - NEW with Full Warranty ($142)500 GB Mechanical Hard Drive - USED ($19)128 GB SSD - USED ($28)GTX 1050Ti - NEW with Full Warranty ($185)650W Power Supply ($42)Option 2 ($835 or PKR 88000)Dell T3610 Desktop Workstation - USED Intel Xeon E5 Series Processor with 1 Core, 30M Cache - USED 16 GB DDR3 RAM ($33)500 GB Mechanical Hard Drive - USED ($19)128 GB SSD - USED ($28)GTX 1050Ti - NEW with Full Warranty ($185)Option 3 ($1803 or PKR 190000)MSI X99 SLI PLUS (Supports 40 Lane PCIe 3.0) - USEDIntel Xeon E5-2620 v4 (8 Core, 2.1 GHz, 20M Cache) - USED16 GB DDR4 RAM - NEW with FULL Warranty ($142)500 GB Mechanical Hard Drive - USED ($19)128 GB SSD - USED ($28)GTX 1080 - New with Full Warranty ($711)Option 4 ($1090 or PKR 115000)HP Tower z820Intel Xeon E5-2687W (8 Core, 3.1 GHz, 20M Cache)16 GB DDR3 RAM ($33)1 TB Hard Drive ($28)128 GB SSD ($28)NVidia Quadro 5000 (2.5 GB, 384 bit)Option 5 ($512 or PKR 54000 without Graphic Card)HP z620 TowerIntel Xeon e5-2650 (8 Core, 2 GHz, 20M Smart Cache)16 GB DDR3 RAM ($33)500 GB Hard Drive ($19)128 GB SSD ($28)Graphics Card is not included
Workstation for Deep Learning in Pakistan
graphics cards;motherboard;power supply;case;cpu
null
_softwareengineering.249891
I'd like to add a couple of command-line arguments to my Django's ./manage.py dbshell command, and I can't figure out how.In specific I'd like to add -A to prevent MySQL from scanning every table and every column, and --prompt=LOCAL: since I frequently keep multiple shells open.I can't figure out how to do this! I'm only idea is to create my own mysql command in /usr/local/bin and have it be a wrapper for mysql with my own flags. But I'd really like to avoid doing that.
Add arguments to mysql in Django's dbshell
mysql;django;command line
null
_unix.37370
Is there any way to restart ONE web application in mono without having to restart Apache?Currently I'm doing a sudo service apache2 restart everytime I deploy my .NET web application to mono, but it restarts all my other applications, requiring them ALL to get reloaded into memory at next web request.
How to restart mono web application without restarting apache?
apache httpd;mono
Enable the mod_mono control panel.In httpd.conf, add<Location /mono> SetHandler mono-ctrl Order deny,allow Deny from all Allow from 127.0.0.1</Location>You will need to modify the addresses that can access it in the Allow from line.Reload httpd and now you can go to http://some.website.domain/mono. You can, among other things, reload all or individual mono applications.
_cogsci.13316
I have noticed that when I look at a cropped picture of someone's face, I fill in the remaining image of his/her body in a manner that is consistent with the face (wider face, larger body, skinnier face, frail body, large jaw, more muscular body, etc). Does the human brain immediately and accurately fill in such information and guess what a persons's body looks like from just images of the face?
Are people able to accurately judge body shape and size from images of the face?
cognitive psychology;perception
null
_codereview.26631
Code reviews and suggestions to improve coding style are welcome.using ExpressionEvaluatorLibrary;namespace ExpressionEvaluator{ class Program { static void Main(string[] args) { ConsoleKeyInfo cki = new ConsoleKeyInfo(); Console.WriteLine( Mathematical Expression Evaluation); Console.WriteLine(Maximum length : 250 characters); Console.WriteLine(Allowed Operators : +, -, *, /); do { string strUserInput = ; if (args.Length == 0) { Console.Write(\n\nEnter an Expression: ); strUserInput = Console.ReadLine(); } else { // TO be able to run from command prompt. strUserInput = args[0]; } IExpressionModel expressionModel = new ExpressionModel(); string strValidate = expressionModel.ExpressionValidate(strUserInput); if (strValidate == Valid) { try { string strPostFixExpression = expressionModel.ConvertToPostfix(strUserInput); // Console.WriteLine(strPostFixExpression); string strResult = expressionModel.EvaluateExpression(strPostFixExpression); Console.WriteLine(\n The result is: + strResult); } catch (Exception e) { Console.WriteLine(e); } } else { Console.WriteLine(strValidate); } Console.WriteLine(\nPress any key to continue; press the 'Esc' key to quit.); cki = Console.ReadKey(false); } while (cki.Key != ConsoleKey.Escape); } }}namespace ExpressionEvaluatorLibrary{ public interface IExpressionModel { string ExpressionValidate(string strUserEntry); string ConvertToPostfix(string strValidExpression); string EvaluateExpression(string strPostFixExpression); }}namespace ExpressionEvaluatorLibrary{ public class ExpressionModel : IExpressionModel { public string ExpressionValidate(string strUserEntry) { strUserEntry = strUserEntry.Trim(); if (string.IsNullOrEmpty(strUserEntry)) return There was no entry.; if (strUserEntry.Length > 250) //250 seemed better than 254 return More than 250 characters entered.; string[] fixes = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; bool boolStartsWith = fixes.Any(prefix => strUserEntry.StartsWith(prefix)); if (!boolStartsWith) return The expression needs to start with a number.; bool boolEndsWith = fixes.Any(postfix => strUserEntry.EndsWith(postfix)); if (!boolEndsWith) return The expression needs to end with a number.; if (!Regex.IsMatch(strUserEntry, ^[-0-9+*/ ]+$)) return There were characters other than Numbers, +, -, * and /.; if (!Regex.IsMatch(strUserEntry, [-+*/])) return Not a mathematical expression; string[] strOperator = Regex.Split(strUserEntry, @\d+); for (int i = 1; i < strOperator.Length - 1; i++) //the first and last elements of the array are empty { if (strOperator[i].Trim().Length > 1) return Expression cannot have operators together ' + strOperator[i] + '.; } return Valid; } public string ConvertToPostfix(string strValidExpression) { StringBuilder sbPostFix = new StringBuilder(); Stack<Char> stkTemp = new Stack<char>(); for (int i = 0; i < strValidExpression.Length; i++) { char chExp = strValidExpression[i]; if (chExp == '+' || chExp == '-' || chExp == '*' || chExp == '/') { sbPostFix.Append( ); if (stkTemp.Count <= 0) stkTemp.Push(chExp); else if (stkTemp.Peek() == '*' || stkTemp.Peek() == '/') { sbPostFix.Append(stkTemp.Pop()).Append( ); i--; } else if (chExp == '+' || chExp == '-') { sbPostFix.Append(stkTemp.Pop()).Append( ); stkTemp.Push(chExp); } else { stkTemp.Push(chExp); } } else { sbPostFix.Append(chExp); } } for (int j = 0; j <= stkTemp.Count; j++) { sbPostFix.Append( ).Append(stkTemp.Pop()); } string strPostFix = sbPostFix.ToString(); strPostFix = Regex.Replace(strPostFix, @[ ]{2,}, @ ); return strPostFix; } public string EvaluateExpression(string strPostFixExpression) { Stack<string> stkTemp = new Stack<string>(); string strOpr = ; string strNumLeft = ; string strNumRight = ; List<String> lstPostFix = strPostFixExpression.Split(' ').ToList(); for (int i = 0; i < lstPostFix.Count; i++) { stkTemp.Push(lstPostFix[i]); if (stkTemp.Count >= 3) { Func<string, bool> myFunc = (c => c == + || c == - || c == * || c == /); bool isOperator = myFunc(stkTemp.Peek()); if (isOperator) { strOpr = stkTemp.Pop(); strNumRight = stkTemp.Pop(); strNumLeft = stkTemp.Pop(); double dblNumLeft, dblNumRight; bool isNumLeft = double.TryParse(strNumLeft, out dblNumLeft); bool isNumRight = double.TryParse(strNumRight, out dblNumRight); if (isNumLeft && isNumRight) { double dblTempResult; switch (strOpr) { case (+): dblTempResult = dblNumLeft + dblNumRight; stkTemp.Push(dblTempResult.ToString()); break; case (-): dblTempResult = dblNumLeft - dblNumRight; stkTemp.Push(dblTempResult.ToString()); break; case (*): dblTempResult = dblNumLeft * dblNumRight; stkTemp.Push(dblTempResult.ToString()); break; case (/): dblTempResult = dblNumLeft / dblNumRight; stkTemp.Push(dblTempResult.ToString()); break; } } } } } return stkTemp.Pop(); } }}
Mathematical expression evaluator.
c#;regex;console
If I'm not mistaken your acceptable input expressions are in infix notation and look like this:number [+-*/] number [+-*/] number ....In that case you can greatly simplify you validation check with a single regular expression:^\d+(\s*[+-*/]\s*\d+)+$It checks for strings starting with a number composed out of 1 or more digits followed by 1 or more groups of [+-*/] number. The \s* allows any number of white spaces between operators and numbers.When you validate you should not return a string representing the validation result. Two alternative options:Return a ValidationResult object like this:class ValidationResult{ bool readonly IsValid; string readonly FailureReason; private ValidationResult() { } public static ValidationResult Valid() { return new ValidationResult { IsValid = true; } } public static ValidationResult Invalid(string reason) { return new ValidationResult { IsValid = false; FailureReason = reason; } }}Use: return ValidationResult.Invalid(some error)Throw a ValidationException with the message as the failure reason and catch it when calling the validation method and log/display the message to the user.You are doing a lot of parsing and re-parsing by passing everything around as strings. This is not really a good way of doing it and also very inefficient as you are constantly throwing away information and having to reconstruct it via parsing it out of the string.Here is how I would split it up:Write a tokenizer which splits the input string into tokens (numbers and operators) and provides the next token to the parserThe parser should build the expression tree. The operators should be the nodes and the leaves are the numbers. This way you can traverse it anyway you like infix, postfix, prefix and you retain the information about the parsed input. Evaluating just means to traverse the tree and evaluate the nodes and the operands.Some skeleton code:The nodes of the tree:interface INode{ double Evaluate();}abstract class Operator : INode{ protected readonly INode Left; protected readonly INode Right; protected Operator(INode left, INode right) { Left = left; Right = right; } public abstract double Evaluate(); public static Operator FromString(string op, INode left, INode right) { switch (op) { case +: return new Add(left, right); case -: return new Sub(left, right); case *: return new Mul(left, right); case /: return new Div(left, right); default: throw new ArgumentException(Invalid operator, op); } }}class Add : Operator{ public Add(INode left, INode right) : base(left, right) {} public override double Evaluate() { return Left.Evaluate() + Right.Evaluate(); }}// ...// similar classes for Sub, Mul And Div // ...class Constant : INode{ private readonly double _Number; public Constant(double number) { _Number = number; } public double Evaluate() { return _Number; }}Parsing (will only deal with valid input):public IEnumerable<string> Tokenize(string input){ // assuming only spaces or tabs are allowed in the expression return string.Split(new [] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);}public INode ParseTokens(IEnumerable<string> tokens){ INode left = new Constant(Double.Parse(tokens.First())); tokens = tokens.Skip(1); // last token of expression is always a number if (!tokens.Any()) return left; var op = tokens.First(); // recursive descending INode right = ParseTokens(tokens.Skip(1)); return Operator.FromString(op, left, right);}Actually evaluating the input becomes:double EvaluateInput(string input){ var tokens = Tokenize(input); var root ParseToken(tokens); return root.Evaluate();}Ideally you actually create a Tokenizer class which gets instantiated with the input string and where you can call Next() on which will return the next token. The tokenizer should be passed to the parse method. I just used simple IEnumerable because it was quicker to show the basic concept.
_unix.80045
If I try to execute read -a fooArr -d '\n' < barthe exit code is 1 -- even though it accomplishes what I want it to; put each line of bar in an element of the array fooArr (using bash 4.2.37).Can someone explain why this is happeningI've found other ways to solve this, like the ones below, so that's not what I'm asking for.for ((i=1;; i++)); do read fooArr$i || break;done < barormapfile -t fooArr < bar
read -a array -d '\n' < foo, exit code 1
bash;newlines;read
What needs to be explained is that the command appeared to work, not its exit code'\n' is two characters: a backslash \ and a letter n. What you thought you needed was $'\n', which is a linefeed (but that wouldn't be right either, see below).The -d option does this: -d delim continue until the first character of DELIM is read, rather than newlineSo without that option, read would read up to a newline, split the line into words using the characters in $IFS as separators, and put the words into the array. If you specified -d $'\n', setting the line delimiter to a newline, it would do exactly the same thing. Setting -d '\n' means that it will read up to the first backslash (but, once again, see below), which is the first character in delim. Since there is no backslash in your file, the read will terminate at the end of file, and:Exit Status:The return code is zero, unless end-of-file is encountered, read times out,or an invalid file descriptor is supplied as the argument to -u.So that's why the exit code is 1.From the fact that you believe that the command worked, we can conclude that there are no spaces in the file, so that read, after reading the entire file in the futile hope of finding a backslash, will split it by whitespace (the default value of $IFS), including newlines. So each line (or each word, if a line contains more than one word) gets stashed into the array.The mysterious case of the purloined backslashNow, how did I know the file didn't contain any backslashes? Because you didn't supply the -r flag to read: -r do not allow backslashes to escape any charactersSo if you had any backslashes in the file, they would have been stripped, unless you had two of them in a row. And, of course, there is the evidence that read had an exit code of 1, which demonstrates that it didn't find a backslash, so there weren't two of them in a row either.TakeawaysBash wouldn't be bash if there weren't gotchas hiding behind just about every command, and read is no exception. Here are a couple:Unless you specify -r, read will interpret backslash escape sequences. Unless that's actually what you want (which it occasionally is, but only occasionally), you should remember to specify -r to avoid having characters disappear in the rare case that there are backslashes in the input.The fact that read returns an exit code of 1 does not mean that it failed. It may well have succeeded, except for finding the line terminator. So be careful with a loop like this: while read -r LINE; do something with LINE; done because it will fail to do something with the last line in the rare case that the last line doesn't have a newline at the end.read -r LINE preserves backslashes, but it doesn't preserve leading or trailing whitespace.
_webmaster.8502
Sometimes videos appear in google's web search results (and not only in Google Videos). For a video to appear in the web search results, does it have to appear in Google Videos first? Does each and every video that appears in Google Videos has a chance to appear in google's web search results (given that the video is very relevant to the query, more relevant than all the other videos)?Please note: I'm not asking about video sitemaps or mRSS. I'm just asking when do videos appear in google's web search results compared to when do videos appear in Google Videos.
When do videos appear in google's web search results?
seo;google;video
Use microformats to tell them it's a video ans what it's about.UPDATE:The results you see at the top of Google search results are from google video. They do the same thing for images. These results are separate from google search results. Basically you have to be a top search result in google video to be shown there. I would assume that achieving high rankings in Google Video Search would be similar to regular Google Search. The context of the page (page title, headings, content) the video is on as well as link popularity etc, help them determine which videos are most relevant for a video search.
_computerscience.169
Different screens can have different pixel geometry, so that the red, green and blue components are arranged in different patterns. Using sub-pixel rendering to give a higher apparent resolution is only possible if the pixel geometry is known (what will give an improvement in clarity on one type of monitor will make things worse on another).This is particularly relevant if an application needs to run on both a desktop/laptop and a mobile screen, as different pixel geometry is quite common in mobile screens.Is there a way to determine which geometry the screen uses at runtime, without having to ask the user? I'm interested in whether this is possible in general, but ideally I'd like to know whether this is possible when using JavaScript with WebGL.
Can I determine the pixel geometry programmatically?
webgl;javascript
It appears that Microsoft has punted on this in Windows 7:This is the method available in the control panel for selecting what layout ClearType uses.Additionally, it seems that iOS and the Windows modern UI style de-emphasize subpixel antialiasing heavily, due to the prevalence of animations and screen rotations. As a result I expect the OS vendors to not spend a lot of effort trying to figure out the subpixel layout of every screen.
_unix.96846
There are various directories in linux. Example /root,/var,/etc,/proc,/usr. In embedded system, during boot up, it will copy image from flash to RAM.Questions: How can i know, which directory goes to RAM and which resides on FLASH?
RAM and Flash directories in embedded system based on linux
linux;boot
null
_unix.217475
My son and I are playing around with LOGO programming on a Raspberry Pi (in Raspbian). We ran into a problem with the current package (v 5.5) not properly interpreting arrow key input: https://raspberrypi.stackexchange.com/questions/33677/arrow-keys-output-scancodes-in-ucblogoThe current version of UCBLogo, according to https://www.cs.berkeley.edu/~bh/logo.html, is 6.0 (released in late 2008).Is there a reason that http://archive.raspbian.org/raspbian/pool/main/u/ucblogo/ only has the 5.5 version? Can the package be updated to 6.0 from the source on https://www.cs.berkeley.edu/~bh/logo.html?
State of ucblogo package in debian / raspbian
debian;apt;raspberry pi;raspbian
Check the Debian package tracker: https://tracker.debian.org/pkg/ucblogo.The maintainer has stopped his work on this package (orphaned in July 2015). There won't be no update unless someone takes over the maintenance. For now you should probably build it for yourself.
_softwareengineering.318766
I would like to ask about a problem I have designing a security flow.The contextI have a webapp designed in two modules web and serverWeb: it's a single page client, built with Angular 1.5.5 (among other modules). It's a wizard with 6 possible states (screens). Its data provider is going to be the server side module.Server: It's a Rest API. Which I want it to be stateless. It's built with Spring MVC and Spring Security.So far so good.Client side app (client from now on) can not be requested without previous authorization. Only trusted sources are allowed. These sources will set a hash into headers or string query.The API in charge of the security is Spring. So far, with a simple PreauthFilter I have been able to take the hash from the request, validate it and in case of OK, set it as Authenticated (PreAuthenticationAuthenticatedToken). However my spring security context is stateless, and Spring security context will not persist it into any session/holder. Due to client is single page, I don't need it after the validation.Once client is working (PreAuth finished successfully), now is time to get rid of the security of the API Rest.), which I want to it to be also stateless and I would like to implement a JWT.Here is what I'm struggling with. I would like to send 3 values to client after the Preauth process, in order to inform to client the values required to start all the JWT protocol.Usually it starts with user/password from a login page. But I have to start from a PreAuth...The only way I have found to inform these 3 values has been through a SucessfulAuthenticationHandler from which I have set 3 cookies. Question is:Is there any other way to inform these 3 values, after PreAuth, instead of cookies?(I have tried to add headers to the response, but I don't know If I will have access to the response headers from Angular. Overall because it's not a ajax request).These cookies have a maxAge of 0, so after the request are no longer available (I don't want to have to deal with expired cookies). Anyways I don't feel totally comfortable with them.Should I try any other approach? What would you suggest?
From PreAuthentication to JWTAuthorization
security;authentication;spring;web api;authorization
null
_webapps.13172
A website I need to access is currently down (port 80 connection hangs). Is there a free online no-registration-required service that monitors websites that are down and then emails me when the site's back up?I realize I could write this myself or use Nagios/etc, but it'd benice to have a quick-and-dirty website for this.I also don't want to set up constant or repeating monitoring. I justwant to know when the site is up, and never hear from the app again(unless I revisit it and ask it to monitor another site).
Online free no-registration app that monitors websites?
monitoring
There are a lot of uptime checkers. I use uptime.openacs.org because I like the clean interface. :)It sends a request every 15 minutes. You get an email when your site is down and another one when the site is back again. On some sites I use the service as a poor mans cron job.
_softwareengineering.250422
I have a Route that activates a Controller which returns to me a page through a View. Let's call it master page.route -> controller -> view [master page]The master page is divided into header, sidebar, body and footer. And as the sidebar can be loaded to other pages, and not only the master page, it has its own View file.However, the sidebar should receive the data from user, which would be obtained through a Model. And in theory, the Model could only be called by a Controller, who call the View, however, this View is the master page, not the sidebar.[...] -> view [master page] -> view [sidebar]So I thought the possibilities were as follows, and the idea is to know whether it is right or wrong, or perhaps it is another way that I could not imagine.The Controller will load the data from the Model and apply the sidebar which, in turn, be applied to the master page. The problem here is, in a deeper case, it would be extremely laborious and difficult to understand.The Controller run the Model, but send to the master page, which would be responsible for loading the View sidebar and pass the information of the Model to it. In this case, the work would be passing on information between the layers, so far as was necessary to take the information.The Controller will only load the View master page, which will load the sidebar, which will be responsible for executing the Model (inside View). The problem here is that a View theoretically should not run a Model, just print your information already processed in the Controller.What would be the most appropriate way to make this process run correctly?
MVC: view/sidebar.php can load model?
mvc
null
_softwareengineering.342558
I am writing a collection that accepts a time parameter, the purpose is that after that specified amount of time have passed the element won't be present in the collection.I want the user of this collection to be able to act when an item is removed from the collection under this circumstance. I have two different ways of achieving this, but I am unsure which I should take. Both approaches feels different, but the end result is pretty much the same.I am asking this question since I may not notice a small (or large) difference between the two and I was hoping to get guidance.Approach A: Have an event such as OnRemovalDueToTimeout which expects some function that receive an element (e.g void foo(T removedElement)). upon removal I would raise the eventApproach B: Receive a delegate with the same signature as above and call that delegate when an element times out.
What is 'better' - An event that tells you that something happened or accepting a delegate to be called when the event triggers internally?
c#;design;delegates;event
null
_webmaster.7876
I want to start and host my own blog. I have ideas for creating the website theme myself.However, I would prefer to not create the actual engine behind the blog -- comments, creating posts, caching everything, creating and managing the post database, spam protection or CAPTCHA of some sort... basic blog features.Honestly, I'm just hoping for something barebones that I can just do something like, <?php include('comment_list.php'); ?> where I want comments to show up on a post. Similar functions to that. (This is a little oversimplified, but hopefully it's understood what I'm getting at)This may be a little far-fetched. I'm not looking for the ability to have plugins, themes or user sessions and things of that nature. Just post creation, comment creation and caching are the big things I'm hoping for.I don't know if I can explain this any better. I'm just looking for the bare minimum.
Simple blogging platform
php;blog
null
_unix.311316
Is it possible to take a backup of /proc ?Almost all the backup utility suggests to avoid the /proc, /sys, /tmp directories. Former two are dynamic directories but I guess, having backup of these two directories will help to track down the issue without looking at problematic machine.Problematic machine can take the backup of these two directories and send to someone who can dig for problems from system point of view.
Backup: /proc /sys
backup;proc
null
_unix.187085
I have a RAID5 array consisting of 3 identical 2TB drives. Suddenly GRUB wouldn't boot anymore and gave the error out of disk.Eventually booted a livecd and ran some mdadm commands:mdadm --examine /dev/sda1 gives no md superblock detected on /dev/sda1.But when examining /dev/sdb1 and /dev/sdc1/ gives the output in the attached photo's.Any help in solving or diagnosing this problem would be greatly appreciated. Thanks!
How to restore RAID5 Array
linux;grub2;data recovery;mdadm;raid5
null
_datascience.5013
Our main use case is object detection in 3d lidar point clouds i.e. data is not in RGB-D format. We are planning to use CNN for this purpose using theano. Hardware limitations are CPU: 32 GB RAM Intel 47XX 4th Gen core i7 and GPU: Nvidia quadro k1100M 2GB. Kindly help me with recommendation for architecture. I am thinking in the lines of 27000 input neurons on basis of 30x30x30 voxel grid but can't tell in advance if this is a good option.Additional Note: Dataset has 4500 points on average per view per point cloud
Machine learning for Point Clouds Lidar data
machine learning;dataset
First, CNNs are great for image recognition, where you usually take sub sampled windows of about 80 by 80 pixels, 27,000 input neurons is too large and it will take you forever to train a CNN on that.Furthermore, why did you choose CNN? Why don't you try some more down to earth algorithms fisrst? Like SVMs, or Logistic regressions.4500 Data points and 27000 features seems unrealistic to me, and very prone to over fitting.Check this first.http://scikit-learn.org/stable/tutorial/machine_learning_map/
_webmaster.95557
For quite a few years the University library where I work has used Google Analytics to track usage of our web pages. Recently I noticed it wasn't working. The code had some how disappeared from the page - possibly in a WordPress upgrade. It is working now.Here is the oddity. Google Analytics never stopped reporting usage statistics. The University has its own tracking code so my assumption is they came from there. Is Google's system clever enough to know how to associate numbers for our account with the University one? Can the numbers I have be trusted? Update:After doing some further investigation, I can confirm our tracking code has not been properly implemented since October 2013. It was then when the University switched over WordPress which seems to have treated the code as Character Data. Then in mid-August 2015 the code vanished entirely. I now have it in an external file which seems to work fine. However while there has been a noticeable drop in web traffic from July 1, 2013 to the present, it does not entirely coincide with either the WordPress migration or the GA code's disappearance last summer. I'm not entirely sure this answers the question, however. Google Analytics was giving a tracking code mismatch error until I re-inserted the code. However it still reported results. Exactly how accurate they were remains to be seen.
Is it possible for Google Analytics to keep tracking even when the tracking code was removed if there is a parent tracking code present?
google analytics
To answer the first part of your question, no Google Analytics does not add additional tracking codes to your site if it has a parent tracking code. EG: If you have a university wide tracking code as well as your own tracking code and then your tracking code is removed and the university code stays it will report only on the university tracking code and not your removed one. The only reason why I can think that you would still see traffic from it with the tracking code removed is if there where users who where accessing a cached version of your site on a business network or through an ISP who cached the website as the cached copy would still have your own tracking code within the HTML. If this occurred you would see less traffic that what actually hit your site due to the fact that not all users would have accessed a cached copy of it.
_unix.164458
I have a file1 which contains comma separated values (timein/timeout in military time format eg 0800, 0900, 1300). For each line of File 1 contains timein/timeout for each day. Sample File 1:Name, Position Level 30800, 18000900, 1200, 1230, 20000901, 2100File 2 contains (hourly rate):Position Level 1, 100Position Level 2, 200Position Level 3, 300Position Level 4, 400Position Level 5, 500I need to create a File 3 with lines with the 1st time in and last timeout and number of hours rendered for each day displayed in each line of File3. And last line will display the monthly salary which will calculate the number of hours rendered for the month (sum of hours from each day) * the hourly rate. File 3:Name, Position Level 30800, 1800, 100900, 2000, 10.50901, 2100, 10.9839444.9
Process Files to create a new file
shell script;text processing
null
_unix.8550
rm -rf will fail if something tries to delete the same file tree (I think because rm enumerates the files first, then deletes).A simple test:# Terminal 1for i in `seq 1 1000`; do mkdir -p /tmp/dirtest/$i; done# Now at the same time in terminal 1 and 2rm -rf /tmp/dirtestThere will be some output into stderr, e.g.:...rm: cannot remove directory `/tmp/dirtest/294': No such file or directoryrm: cannot remove directory `/tmp/dirtest/297': No such file or directoryrm: cannot remove directory `/tmp/dirtest/304': No such file or directoryI can ignore all the stderr output by redirecting it to /dev/null, but removing of /tmp/dirtest actually fails! After both commands are finished, /tmp/dirtest is still there.How can I make rm delete the directory tree properly and really ignore all the errors?
rm -rf failing if deleting in parallel
files;rm;concurrency
null
_unix.250415
Is it possible to restrict the number of possible simultaneous connections to a certain directory on my server?I have a public directory which I want to share many download-able files, yet its popularity is straining my server to the max - causing it to crash, so I want to restrict the connections to that certain directory.When I use Deny from all directive - then my server doesn't get swamped.
Apache - restrict simultaneous connections per directory?
apache httpd
null
_webmaster.63025
Previously there was a page on our partner's site that had a link to our site. Now, this page and the whole partner's website is gone (404).But this page still exists in our website backlink profile. Do we need to disavow or take any other action regarding this partner's website (page)?
What to do when we had a backlink (from a gone site) to one of our a 404 page?
backlinks;404
null
_codereview.162466
I have a problem with my printing program, in which it uses up too much resources while printing (to paper or to .pdf). I try to manually dispose as much as I can, but for example, when I tried printing 300 pages, the program itself used up around 500mb of memory, and I would like to avoid that. When the program finishes printing, it goes back down to 37mb of usage. I use Visual Studio to check performance. Below you can find the code, and any help to manage resources and lower ram usage while printing would be appreciated. I apologize in advance for mixing German and English. And for clarity, this draws n number of each element (one is a string, second an arrow, up or down, third a barcode).private void DocumentDrucker_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e){ Graphics graphic = e.Graphics; SolidBrush brush = new SolidBrush(Color.Black); Font font = new Font(Courier New, 27, FontStyle.Bold); float pageWidth = e.PageSettings.PrintableArea.Width; float pageHeight = e.PageSettings.PrintableArea.Height; float fontHeight = font.GetHeight(); int startX = 40; int startY = 40; int offsetY = 40; for (; elemente < ZumDrucken.Items.Count; elemente++) { graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; graphic.DrawString(ZumDrucken.Items[elemente].Text, font, brush, startX, startY + offsetY); if (ZumDrucken.Items[elemente].Checked == true) { if (ZumDrucken.Items[elemente].Text.Substring(ZumDrucken.Items[elemente].Text.Length - 1) != 1) graphic.DrawImage(Properties.Resources.pfeilU, new Point(Convert.ToInt32(pageWidth * 0.35), offsetY + 37)); else graphic.DrawImage(Properties.Resources.pfeilO, new Point(Convert.ToInt32(pageWidth * 0.35), offsetY + 37)); } else { if (ZumDrucken.Items[elemente].Text.Substring(ZumDrucken.Items[elemente].Text.Length - 1) != 1) graphic.DrawImage(Properties.Resources.pfeilO, new Point(Convert.ToInt32(pageWidth * 0.35), offsetY + 37)); else graphic.DrawImage(Properties.Resources.pfeilU, new Point(Convert.ToInt32(pageWidth * 0.35), offsetY + 37)); } b.Encode(TYPE.CODE128A,ZumDrucken.Items[elemente].Text, Color.Black, Color.Transparent,600,100); graphic.DrawImage(b.EncodedImage, new Point(Convert.ToInt32(pageWidth*0.6),offsetY)); offsetY = offsetY + 175; if (offsetY >= pageWidth-100) { e.HasMorePages = true; offsetY = 0; elemente++; graphic.Dispose(); b.Dispose(); brush.Dispose(); font.Dispose(); return; } else { e.HasMorePages = false; } } graphic.Dispose(); b.Dispose(); brush.Dispose(); font.Dispose();}
Printing 300 pages
c#;performance;memory optimization
don't mix german and english words for names. Best is to stick to english because most/all developers knows the language.don't repeat yourself. You have some duplicated code which should be removed. e.g:You create the same Point for printing at 4 different location (new Point(Convert.ToInt32(pageWidth * 0.35), offsetY + 37)) don't omit braces {} although they might be optional. Omitting them can lead to hidden and therfore hard to track bugs. Let's take a look at the if..else construct and how we could refactor it if (ZumDrucken.Items[elemente].Checked == true){ if ZumDrucken.Items[elemente].Text.Substring(ZumDrucken.Items[elemente].Text.Length - 1) != 1) graphic.DrawImage(Properties.Resources.pfeilU, new Point(Convert.ToInt32(pageWidth * 0.35), offsetY + 37)); else graphic.DrawImage(Properties.Resources.pfeilO, new Point(Convert.ToInt32(pageWidth * 0.35), offsetY + 37));}else{ if (ZumDrucken.Items[elemente].Text.Substring(ZumDrucken.Items[elemente].Text.Length - 1) != 1) graphic.DrawImage(Properties.Resources.pfeilO, new Point(Convert.ToInt32(pageWidth * 0.35), offsetY + 37)); else graphic.DrawImage(Properties.Resources.pfeilU, new Point(Convert.ToInt32(pageWidth * 0.35), offsetY + 37));} First we can remove the == true because comparing a non nullable bool to true is senseless. Either it is true or false. Now let us create a var imagePoint = new Point(Convert.ToInt32(pageWidth * 0.35), offsetY); just before the loop and increase the Y before the if..else we are talking about so the whole thing becomes imagePoint.Y += 37;if (ZumDrucken.Items[elemente].Checked){ if (ZumDrucken.Items[elemente].Text.Substring(ZumDrucken.Items[elemente].Text.Length - 1) != 1) { graphic.DrawImage(Properties.Resources.pfeilU, imagePoint); } else { graphic.DrawImage(Properties.Resources.pfeilO, imagePoint); }}else{ if (ZumDrucken.Items[elemente].Text.Substring(ZumDrucken.Items[elemente].Text.Length - 1) != 1) { graphic.DrawImage(Properties.Resources.pfeilO, imagePoint); } else { graphic.DrawImage(Properties.Resources.pfeilU, imagePoint); }}If we extract the checking of the last character from the text outside of the if..else like so bool lastCharIsAOne = ZumDrucken.Items[elemente].Text[ZumDrucken.Items[elemente].Text.Length - 1] == '1'; we don't create a new string because we just access the char array directly. But for readability I would introduce a var currentItem = ZumDrucken.Items[elemente]; then the if..else will become var currentItem = ZumDrucken.Items[elemente]; ... some more codebool lastCharIsAOne = currentItem.Text[currentItem.Text.Length - 1] == '1'; imagePoint.Y += 37;if (currentItem.Checked){ if (lastCharIsAOne) { graphic.DrawImage(Properties.Resources.pfeilU, imagePoint); } else { graphic.DrawImage(Properties.Resources.pfeilO, imagePoint); }}else{ if (lastCharIsAOne) { graphic.DrawImage(Properties.Resources.pfeilO, imagePoint); } else { graphic.DrawImage(Properties.Resources.pfeilU, imagePoint); }} Now we need to do something about the image which should be printed. We see that pfeilU should be printed if:(currentItem.Checked && lastCharIsAOne) || (!currentItem.Checked && !lastCharIsAOne) which is the same as (currentItem.Checked == lastCharIsAOne)like @DDrmmr stated in the comments, hence we only need one if and one else which we could reduce to a simple if like so var currentImage = Properties.Resources.pfeilO;if (currentItem.Checked == lastCharIsAOne) { currentImage = Properties.Resources.pfeilU; } graphic.DrawImage(currentImage, imagePoint);If we now extract the setting of the graphic.InterpolationMode outside of the loop we will get this graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;var imagePoint = new Point(Convert.ToInt32(pageWidth * 0.35), offsetY); var barcodePoint = new Point(Convert.ToInt32(pageWidth * 0.6), 0); for (; elemente < ZumDrucken.Items.Count; elemente++){ var currentItem = ZumDrucken.Items[elemente]; graphic.DrawString(currentItem.Text, font, brush, startX, startY + offsetY); var currentImage = Properties.Resources.pfeilO; bool lastCharIsAOne = currentItem.Text[currentItem.Text.Length - 1] == '1'; if (currentItem.Checked == lastCharIsAOne) { currentImage = Properties.Resources.pfeilU; } imagePoint.Y += 37; graphic.DrawImage(currentImage, imagePoint); b.Encode(TYPE.CODE128A, currentItem.Text, Color.Black, Color.Transparent, 600, 100); barcodePoint.Y = offsetY; graphic.DrawImage(b.EncodedImage, barcodePoint); offsetY = offsetY + 175; ... the other `if..else`
_codereview.95800
In JavaScript, I wrote a class that can be optionally instantiated with the new keyword, but can also be called statically as well. What is the best way to demonstrate this behavior in comment syntax? I was thinking something like this:// localize constantvar PI = Math.PI;/** * Complex constructor * optionally instantiate with `new` * * @class Complex * @constructor * @static * @param r {Number} real part * @param i {Number} imaginary part * @param m {Number} optional, magnitude * @param t {Number} optional, argument * @return {Object} complex number */function Complex(r, i, m, t) { if (!(this instanceof Complex)) { return new Complex(r, i, m, t); } if (typeof m === 'number') { this.m = Math.abs(m); } else { this.m = Math.sqrt(r * r + i * i); } if (typeof t === 'number') { this.t = (m >= 0 ? t : t + PI); } else { this.t = Math.atan2(i, r); } // limit argument between (-pi,pi] this.t = PI - (PI * 3 - (PI - (PI * 3 - this.t) % (PI * 2))) % (PI * 2); this.r = r; this.i = i;}
YUIDoc syntax for optionally static constructor
javascript;object oriented;formatting;constructor;static
null
_webmaster.15765
I'm big Drupal fan, and some very high profile sites use Drupal which also suggests that its a good system. Can the same be said for Ubercart? I've used it for some small eCommerce sites purely because I know Drupal. It seems to lack some basic features and also relies on JavaScript. I don't know of any high profile eCommerce sites using it. My productivity would take a big hit if I had to learn a new eCommerce platform and also if I couldn't use my favorite CMS with it, but do I have a choice? If not I guess I can hope that Drupal 7's Commerce module will be an improvement.
Ubercart for 'serious' eCommerce?
ecommerce;drupal
High profile is quite a subjective thing. These sites are using it: http://www.ubercart.org/site32,000 sites are reported as using it http://drupal.org/project/usage/ubercart but I appreciate this is not the same thing as a few well known sites using it.
_unix.125376
I have downloaded a Linux Live CD which I am required to do pentesting using VirtualBox . Live CD is configured for router with Pool Starting Address 192.168.2.2 . Now problem is that my router is't configurable to that setting nor I am allowed to change anything in Live CD. How can i create a virtual network that can be configured as per this requirement ?
How to create Virtual Network for VM's
linux;networking
null
_unix.11661
I'm dropped the 32-bit GRML ISO onto a 1GB thumb drive with the usual command:dd if=grml_2010.12.iso of=/dev/USB_STICK(of course, with the correct device). But, when I try to boot from it, it produces this error:0AAD Loading ...bad magic error...bad magicAnd then proceeds to restart. What would cause that?
Error While Booting GRML
linux;live usb;grml
I'm posing this answer because this is the first Google hit when you search for the error.In my case, what caused the error was wrong architecture - I tried to boot a 64bit system on a 32bit computer.
_unix.127755
I have a bash script that executes rsync transfers to a remote location, and every time I execute the script I get asked for a password. Is there a way to avoid this? This is the command I use: rsync -av /source usr@ip:/destination
No password prompt when using rsync remotely?
linux;bash;rsync
Use rsync over SSH and use an SSH key without a passphrase.man rsync:-e, --rsh=COMMAND specify the remote shell to usersync -e ssh ...
_codereview.106712
I'm a beginner to web programming and just started a MVC project from scratch. Because this will become a large project eventually, I would like to make sure that I'm doing things kind of right from the beginning. The architecture is the following: ASP.NET 4.6, MVC 5, EF 6, Identity 2.0. I'm using EF Database First approach and Bootstrap 3.3.5. The solution is divided into 3 projects: Data (where I keep my .edmx and model classes), Resources (where I keep strings for localization purposes -and eventually images-), and Web (with my controllers, views, etc).I'm going to point out a couple of examples in my code where I'm not sure about my approach. I have a navigation bar with an Administration link and two submenu links, Users and Roles. UsersWhen a user clicks on Users, I'd like to show a table with four columns:UsernameRoles (string with the names of all roles assigned)Assign Role (button that will take you to another form)Remove Role (button that will take you to another form)This is what the UserIndex.cshtml view looks like:@model List<MySolution.Data.DAL.ApplicationUser>@{ ViewBag.Title = Resources.Users;}<h2>@Resources.Users</h2><hr /><table class=table table-striped table-hover > <thead> <tr> <th>@Resources.User</th> <th>@Resources.Roles</th> <th></th> <th></th> </tr> </thead> <tbody> @foreach (var user in Model) { <tr> <td> @user.UserName </td> <td> @user.DisplayRoles() </td> <td> @using (Html.BeginForm(UserAssignRole, Admin, new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Get, new { @class = form-horizontal, role = form })) { @Html.AntiForgeryToken() @Html.HiddenFor(m => m.Where(u => u.Id.Equals(user.Id)).FirstOrDefault().UserName) <input type=submit [email protected] class=btn btn-default btn-sm /> } </td> <td> @using (Html.BeginForm(UserRemoveRole, Admin, new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Get, new { @class = form-horizontal, role = form })) { @Html.AntiForgeryToken() @Html.HiddenFor(m => m.Where(u => u.Id.Equals(user.Id)).FirstOrDefault().UserName) <input type=submit [email protected] class=btn btn-default btn-sm /> } </td> </tr> } </tbody></table> I added a DisplayRoles() method to my ApplicationUser class that returns a string with the list of assigned roles separated by commas, so that I can plug it directly into the user table in my view. I'm not sure at all about this approach; it does work, but putting logic like that in my model just seems kind of weird. I just haven't figured a better way to do this.Then, on my controller, I have the following: // // GET: /Admin/UserIndex [Authorize(Roles = Admin)] public ActionResult UserIndex() { var users = context.Users.ToList(); return View(users); } // // GET: /Admin/UserAssignRole [HttpGet] //[ValidateAntiForgeryToken] public ActionResult UserAssignRole(UserAssignRoleViewModel vm) { ViewBag.Username = vm.Username; ViewBag.Roles = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList(); return View(UserAssignRole); } // // POST: /Admin/UserAssignRole [HttpPost] //[ValidateAntiForgeryToken] [ActionName(UserAssignRole)] public ActionResult UserAssignRolePost(UserAssignRoleViewModel vm) { ApplicationUser user = context.Users.Where(u => u.UserName.Equals(vm.Username, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault(); this.UserManager.AddToRole(user.Id, vm.Role); return RedirectToAction(UserIndex); }With my UserAssignRoleViewModel looking like this:/// <summary>/// Views\Admin\UserAssignRole.cshtml/// </summary>public class UserAssignRoleViewModel{ [Display(Name = Username, ResourceType = typeof(Resources))] public string Username { get; set; } [Display(Name = Role, ResourceType = typeof(Resources))] public string Role { get; set; }}And the UserAssignRole view being this:@model UserAssignRoleViewModel@{ ViewBag.Title = Resources.AssignRole;}<h2>@Resources.AssignRole</h2><hr /><div class=row> <div class=col-md-8> <section id=assignRoleForm> @using (Html.BeginForm(UserAssignRole, Admin, new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = form-horizontal, role = form })) { @Html.AntiForgeryToken() @Html.ValidationSummary(true, , new { @class = text-danger }) <div class=form-group> @Html.LabelFor(m => m.Username, new { @class = col-md-2 control-label }) <div class=col-md-10> @Html.TextBoxFor(m => m.Username, new { @class = form-control , @readonly = readonly }) @Html.ValidationMessageFor(m => m.Username, , new { @class = text-danger }) </div> </div> <div class=form-group> @Html.LabelFor(m => m.Role, new { @class = col-md-2 control-label }) <div class=col-md-10> @Html.DropDownListFor(m => m.Role, (IEnumerable<SelectListItem>)ViewBag.Roles, Resources.DropdownSelect, new { @class = form-control }) </div> </div> <div class=form-group> <div class=col-md-offset-2 col-md-10> <input type=submit [email protected] class=btn btn-default /> </div> </div> } </section> </div></div>I especially am not sure about the way that I use my controller actions, and how I'm calling them from my forms. And does it make sense to have a Get and Post method for the same action, or should I be doing something else?RolesThe Roles section is very similar, with a table with three columns:NameEdit (button that will take you to another form to rename the role)Delete button (button that will show a modal asking for verification)On top of the table, there's a separate button allowing the user to add a new role.Here's my RoleIndex.cshtml view.@model IEnumerable<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>@{ ViewBag.Title = Resources.Roles;}<h2>@Resources.Roles</h2><hr />@using (Html.BeginForm(RoleCreate, Admin, new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Get, new { @class = form-horizontal, role = form })){ <input type=submit [email protected] class=btn btn-default btn-sm />}<hr /><table class=table table-striped table-hover > <thead> <tr> <th>@Resources.Role</th> <th></th> <th></th> </tr> </thead> <tbody> @foreach (var role in Model) { <tr> <td> @role.Name </td> <td> @using (Html.BeginForm(RoleEdit, Admin, new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Get, new { @class = form-horizontal, role = form })) { @Html.AntiForgeryToken() @Html.HiddenFor(m => m.Where(r => r.Id.Equals(role.Id)).FirstOrDefault().Name) <input type=submit [email protected] class=btn btn-default btn-sm /> } </td> <td> <input type=submit [email protected] class=btn btn-default btn-sm data-toggle=modal data-target=#confirm-delete/> <div class=modal fade id=confirm-delete tabindex=-1 role=dialog aria-labelledby=myModalLabel aria-hidden=true> <div class=modal-dialog> <div class=modal-content> <div class=modal-header> @Resources.DeleteRole </div> <div class=modal-body> @Resources.AreYouSureYouWantToDelete </div> <div class=modal-footer> @using (Html.BeginForm(RoleDelete, Admin, new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = form-horizontal, role = form })) { @Html.AntiForgeryToken() @Html.HiddenFor(m => m.Where(r => r.Id.Equals(role.Id)).FirstOrDefault().Name) <button type=button class=btn btn-default data-dismiss=modal>@Resources.Cancel</button> <input type=submit [email protected] class=btn btn-danger btn-ok /> } </div> </div> </div> </div> </td> </tr> } </tbody></table>Here's my RoleCreateViewModel/// <summary>/// Views\Admin\RoleCreate.cshtml/// </summary>public class RoleCreateViewModel{ [Required] [Display(Name = Name, ResourceType = typeof(Resources))] public string Name { get; set; }}and RoleCreate actions // // GET: /Admin/RoleCreate [HttpGet] [Authorize(Roles = Admin)] public ActionResult RoleCreate() { return View(); } // // POST: /Admin/RoleCreate [HttpPost] [Authorize(Roles = Admin)] public ActionResult RoleCreate(RoleCreateViewModel vm) { context.Roles.Add(new IdentityRole() { Name = vm.Name }); context.SaveChanges(); ViewBag.ResultMessage = Resources.RoleCreatedSuccessfully; return RedirectToAction(RoleIndex); }and RoleCreate.cshtml view@model RoleCreateViewModel@{ ViewBag.Title = Resources.CreateRole;}<h2>@Resources.CreateRole</h2><hr /> <div class=row> <div class=col-md-8> <section id=createRoleForm> @using (Html.BeginForm(RoleCreate, Admin, new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = form-horizontal, role = form })) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <div class=form-group> @Html.LabelFor(m => m.Name, new { @class = col-md-2 control-label }) <div class=col-md-10> @Html.TextBoxFor(m => m.Name, new { @class = form-control }) @Html.ValidationMessageFor(m => m.Name, , new { @class = text-danger }) </div> </div> <div class=form-group> <div class=col-md-offset-2 col-md-10> <input type=submit [email protected] class=btn btn-default /> </div> </div> } </section> </div></div>Please do critique.
MVC app to associate users with roles
c#;html;mvc;asp.net;authorization
Well, there's a lot there. I'll give some feedback on the Users bit.I wouldn't call DisplayRoles in cshtml either. I would use a view model for that page. It would have an int, UserId, and 2 strings, UserName and UserRoles, and the page would use a list or ienumerable of that view model. Then in your Get for the Index, create the view model from each user and build up the collection. Pretty straightforward using LINQ. For the 2 buttons in your table, can't you just use ActionLink? Yes it makes sense to have Get and Post for same action. But your Get for assigning roles would just take the user Id. Your Post would accept your view model, then you don't have to change the name in order to make it unique.
_codereview.62637
I saw this codegolf challenge and I set out to try and write a solution for it. I'm nowhere near an expert codegolfer (or programmer), but it was an interesting exercise.Now I'm wondering how to improve my code, as it feels really bulky (especially compared to some of the answers to the challenge). Note that I'm not looking for ways to golf this code, I'm merely looking for general improvements and optimizations, hints and tips.I hope the title is clear as to what the program does, it was pretty hard to describe!Anyway, what my program does is pretty simple:It accepts a string as inputIt then fetches the index of each char in the string from the arrayIt checks if that char is within a certain rangeEach range corresponds with a classic mobile phone button (0,1,2 = A,B,C)The current button is compared to the previously used buttonIf the buttons match, the string does not pass and it returns falseMy code:int previousButton = -1;char[] letters ={ 'a', 'b', 'c', // 2 'd', 'e', 'f', // 3 'g', 'h', 'i', // 4 'j', 'k', 'l', // 5 'm', 'n', 'o', // 6 'p', 'q', 'r', 's', // 7 't', 'u', 'v', // 8 'w', 'x', 'y', 'z', // 9 ' ' // 0};for (int i = 0; i < line.Length; i++) { char currentLetter = line[i]; int index = Array.IndexOf(letters, currentLetter); int currentButton = 1; if (index >= 0 && index <= 2) { currentButton = 2; } else if (index >= 3 && index <= 5) { currentButton = 3; } else if (index >= 6 && index <= 8) { currentButton = 4; } else if (index >= 9 && index <= 11) { currentButton = 5; } else if (index >= 12 && index <= 14) { currentButton = 6; } else if (index >= 15 && index <= 18) { currentButton = 7; } else if (index >= 19 && index <= 21) { currentButton = 8; } else if (index >= 22 && index <= 25) { currentButton = 9; } else if (index == 26) { currentButton = 0; } if (previousButton == currentButton) { return false; } previousButton = currentButton;}return true;
Compare the index of each char in a string in an alphabet array to a range of numbers
c#;strings;array
There are two alternatives I can recommend, one alternative avoids all the if/else/if cascading, and replaces it with a single 'switch' statement. Switch statements are optimized at compile time so that, effectively, each char/operation takes as long as any other. it makes sense to extract that to a function too.The second alternative is to trade code space, for memory space.First though, improving your current solution...Current versionYour current version has a lot of unnecessary conditions in the cascading if/else system.If you check for 'low' values first, then you can assume the next value's lower range is already handled. It is easier to explain this by example.... you have:if (index >= 0 && index <= 2) { currentButton = 2;} else if (index >= 3 && index <= 5) { currentButton = 3;} else if (index >= 6 && index <= 8) {But this will produce the same results, with half the comparisons:if (index < 0){ currentButton = 1; //invalid index, char not found?}else if (index <= 2){ currentButton = 2;}else if (index <= 5){ currentButton = 3;}else if (index <= 8){Note how I have also used the conventional C# style there for the braces....1. Switch:A switch statement can work on chars:switch (currentLetter){ case 'a': case 'b': case 'c': return 2; case 'd': case 'e': case 'f': return 3; ..... default: return 1; // whatever you need for an invalid char}The above code (included in a function) will encode each char to a key, and unmapped chars will return 1.2. In memory lookupA second common way to do this is to prepopulate an array with the indexes for each char:int[] keys = new int[]{2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,9};Then use that array as a simple lookup:if (currentChar < 'a' || currentChar > 'z'){ return 1;}return keys[currentChar - 'a'];That converts the char to an offset in the keys array. I have taken the liberty of coding this up in Ideone to ensure it works (which it does, except for the handling of space characters)
_webmaster.15115
A friend of mine is an architect starting her own business, and needs to build a basic brochure site to promote herself. The site will simply include a few articles and pictures of projects she worked on.There are so many CMS that it's hard to choose on, but the following are basic requirements:- Open-source- Mature, and with good support- In PHP, since just about any hoster supports PHP- DB-free, to make deployment really basic. If the SCM really does need a database for indexing, SQLite is OK- Good UI so she can easily add articles and photos to her site without having to know any HTML/CSS- Nice templates to choose fromThank you.
Open-source, PHP, DB-free SCM for brochure site?
php;cms
Use WordPress. It's written in PHP, offers CMS features, and has a large ecosystem of themes and plugins. See the list of recommended WordPress hosts.For SCM, most good hosts will support Subversion, Git, or both.
_webmaster.83791
I had a separate mobile site uploaded so as to make Google happy. My big problem is that I had a desktop page that was once showing in the top 3 results on Google, and now it and its mobile alternative are showing up on the 3rd page or worse.My structure is as follows. The desktop file is www.myserver.com/pellet-calculator.php. The mobile file is www.myserver.com/pelletcalculator.php. I have a PHP redirection working beautifully on the desktop file, placed at the very top of the page, in the following format:<?php $url = 'http://m.myserver.com/pelletcalculator.php'; // only check if the desktop cookie isn't present if(!isset($_COOKIE['mobile'])) { $useragent=$_SERVER['HTTP_USER_AGENT']; if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4))) { header('Location: '.$url.''); } }?>In my bid to resolve this issue, I did some reading. I didn't have any of the links as suggested by Google on their Separate URL's page (https://developers.google.com/webmasters/mobile-sites/mobile-seo/configurations/separate-urls?hl=en). I have therefore now added the following links to each file, directly under the <title> tags:// following link on the desktop page<link rel=alternate media=only screen and (max-width: 640px) href=http://m.myserver.com/pelletcalculator.php >// following link on the mobile page<link rel=canonical href=http://www.myserver.com/pellet-calculator.php >However I'm now worried about 2 things?1) I'm now worried about my redirect. Google mentioned that Googlebot support javascript redirection, and I'm using PHP redirection. Should I get rid of the above redirect code and replace it with an equivalent javascript code? And if so, where should I place this javascript? Should it be placed above or below the <link> code above?2) The alternative link above mentions media=only screen and (max-width: 640px), but what if I want to specify all mobile browsers? How should I then rewrite this.Many thanks for all and any advice.
Strategy for mobile redirection and using alternative and canonical links
seo;googlebot
null
_unix.218182
Several weeks ago I installed Kali Linux on my laptop (Asus X53BR). I installed it successfully but the when system started, I only had a command line and no login manager (gdm3) running. I have tried everything to fix it; I updated and upgraded system and gdm3 several times. Nothing worked and I gave up. Yesterday, I tried installation one more time. Same problem but this time I tried every method to fix this on first five pages on Google but nothing worked. And suddenly Gnome started and graphical desktop appeared. I have no idea how. But after restart the same problem: only command window. Please help me solve this problem.Details:When gdm accidentally started, I was trying to connect to the internet using the command prompt. After this accident, I reviewed my command history and there were gnome3 typed in the command window. I don't remember if I typed it or what. But any other time when I was trying run gdm3, I got this error: failed acquire org.gnome.DisplayManager and something like this on second line. As I searched there could be permission issue at /etc/dbus-1/system.d/gdm.conf as I remember. But I was logged in as root and also changed permission to allow any user access to it but nothing changed. I also examined that conf file and there were html-like scripts mentioning gdm3 running permissions. But I don't know exactly what those scripts mean.
Gnome 3 doesn't run on Kali Linux
kali linux;gdm3
null
_unix.385994
Last NVidia update in the Debian unstable branche (375.82) broke the symlinks of the openGL libs.LIBGL_DEBUG=verbose glxinfo|greplibGL: screen 0 does not appear to be DRI2 capablelibGL: OpenDriver: trying /usr/lib/x86_64-linux-gnu/dri/tls/swrast_dri.solibGL: OpenDriver: trying /usr/lib/x86_64-linux-gnu/dri/swrast_dri.solibGL: dlopen /usr/lib/x86_64-linux-gnu/dri/swrast_dri.so failed (/usr/lib/x86_64-linux-gnu/dri/swrast_dri.so: cannot open shared object file: No such file or directory)libGL: OpenDriver: trying ${ORIGIN}/dri/tls/swrast_dri.solibGL: OpenDriver: trying ${ORIGIN}/dri/swrast_dri.solibGL: dlopen ${ORIGIN}/dri/swrast_dri.so failed (${ORIGIN}/dri/swrast_dri.so: cannot open shared object file: No such file or directory)libGL: OpenDriver: trying /usr/lib/dri/tls/swrast_dri.solibGL: OpenDriver: trying /usr/lib/dri/swrast_dri.solibGL: dlopen /usr/lib/dri/swrast_dri.so failed (/usr/lib/dri/swrast_dri.so: cannot open shared object file: No such file or directory)libGL error: unable to load driver: swrast_dri.solibGL error: failed to load driver: swrastX Error of failed request: GLXBadContext Major opcode of failed request: 154 (GLX) Minor opcode of failed request: 6 (X_GLXIsDirect) Serial number of failed request: 48 Current serial number in output stream: 47sudo ldconfig -p | grep -i gl.so libwayland-egl.so.1 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libwayland-egl.so.1libcogl.so.20 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libcogl.so.20libGL.so.1 (libc6,x86-64) => /usr/local/lib/libGL.so.1I have no experience with symlinks and I can't find this problem online solved without using docker or installing the bin version. The latter would break my CUDA/Tensorflow setup due to libs not being compatible with the .bin version.
Nvidia Opengl symlinks
debian;symlink;nvidia;opengl
null
_codereview.74221
I've been prototyping a Match 3 game (Bejeweled clone) because I have an interesting concept for one, and because it is good practice. One key aspect of my version is that the matches must contain one of the swapped orbs. Therefore matches elsewhere on the board do not get destroyed (and for now there are no combos).To solve this, I devised a special algorithm that searches for matches starting with the positions of the swapped orbs.Since this is a naive implementation of Match 3, I am sure that there are lots of problems with the code and especially with the algorithm.Here is the initial evaluation that happens when a player tries to swap two orbs:-(BOOL) swapOrb:(DMOrb *)firstOrb withOrb:(DMOrb *)secondOrb { //if its the same orb, fail if ([firstOrb isEqual:secondOrb]) { return NO; } //check and make sure that the orbs are next to each other if (![self orbAdjacent:firstOrb toOrb:secondOrb]) { return NO; } //potentially check and make sure they are not the same color here //makes a copy of the board inside the eval class _boardEval.board = self.board; //actually moves the pieces, but will only save the new board if there is a match if ([_boardEval swapHasMatchesForOrb:firstOrb withOrb:secondOrb]) { [_boardEval resolveSwapBetweenPosition:firstOrb.boardPosition position:secondOrb.boardPosition]; self.board = _boardEval.board; return YES; } return NO;}And here is the board evaluator class. It is possible that all of this class should simply be in the GameBoard class, but I am unsure. Right now the Game class has both the GameBoard and the BoardEvaluator, and processes the moves of the game sent by the UI.DMBoardEval.h#import <Foundation/Foundation.h>#import DMGameBoard.h@interface DMBoardEval : NSObject@property (nonatomic) DMGameBoard *board;-(BOOL) swapHasMatchesForOrb:(DMOrb *)firstOrb withOrb:(DMOrb *)secondOrb;-(void) resolveSwapBetweenPosition:(CGPoint)firstPosition position:(CGPoint)secondPosition;@endDMBoardEval.m#import DMBoardEval.h#import DMRow.h#import DMColumn.hstatic const int kNumOrbsPerRow = 9;@implementation DMBoardEval#pragma mark - Copy Board-(void) setBoard:(DMGameBoard *)board { _board = [DMGameBoard boardWithBoard:board];}#pragma mark - Swap Orbs-(BOOL) swapHasMatchesForOrb:(DMOrb *)firstOrb withOrb:(DMOrb *)secondOrb { [_board swapOrb:firstOrb withOrb:secondOrb]; //dont need to switch them back because the board will be kept if there are matches and discarded if not //[_board swapOrb:secondOrb withOrb:firstOrb]; return [self findMatchesInBoardForPosition:firstOrb.boardPosition secondPosition:secondOrb.boardPosition];}#pragma mark - Quick Search for Matches-(BOOL) findMatchesInBoardForPosition:(CGPoint)firstPos secondPosition:(CGPoint)secondPos { DMRow *firstRow = _board.rows[(int)firstPos.y]; DMOrb *firstOrb = firstRow.orbs[(int)firstPos.x]; DMRow *secondRow = _board.rows[(int)secondPos.y]; DMOrb *secondOrb = secondRow.orbs[(int)secondPos.x]; if ([self findMatchesForOrb:firstOrb] || [self findMatchesForOrb:secondOrb]) { return YES; } return NO;}-(BOOL) findMatchesForOrb:(DMOrb *)orb { if ([self searchRowForMatchesWithOrb:orb]) { return YES; } if ([self searchColumnForMatchesWithOrb:orb]) { return YES; } return NO;}-(BOOL) searchRowForMatchesWithOrb:(DMOrb *)orb { DMRow *row = _board.rows[(int)orb.boardPosition.y]; //search right in row BOOL otherColorFound = NO; int numberOfOrbs = 0; for (int i = orb.boardPosition.x; i < kNumOrbsPerRow; i++) { if (!otherColorFound) { if (orb.type == ((DMOrb *)row.orbs[i]).type) { numberOfOrbs++; } else { otherColorFound = YES; } } } if (numberOfOrbs >= 3) { return YES; } //search left in row otherColorFound = NO; numberOfOrbs = numberOfOrbs - 1; //because it is going to count self again for (int i = orb.boardPosition.x; i >= 0; i--) { if (!otherColorFound) { if (orb.type == ((DMOrb *)row.orbs[i]).type) { numberOfOrbs++; } else { otherColorFound = YES; } } } if (numberOfOrbs >= 3) { return YES; } return NO;}-(BOOL) searchColumnForMatchesWithOrb:(DMOrb *)orb { //create columns NSMutableArray *columns = [[NSMutableArray alloc]init]; for (int i = 0; i < kNumOrbsPerRow; i++) { [columns addObject:[[DMColumn alloc]initWithRows:_board.rows number:i]]; } DMColumn *column = columns[(int)orb.boardPosition.x]; //search up in column BOOL otherColorFound = NO; int numberOfOrbs = 0; for (int i = orb.boardPosition.y; i < kNumOrbsPerRow; i++) { if (!otherColorFound) { if (orb.type == ((DMOrb *)column.orbs[i]).type) { numberOfOrbs++; } else { otherColorFound = YES; } } } if (numberOfOrbs >= 3) { return YES; } //search down in column otherColorFound = NO; numberOfOrbs = numberOfOrbs - 1; //because it is going to count self again for (int i = orb.boardPosition.y; i >= 0; i--) { if (!otherColorFound) { if (orb.type == ((DMOrb *)column.orbs[i]).type) { numberOfOrbs++; } else { otherColorFound = YES; } } } if (numberOfOrbs >= 3) { return YES; } return NO;}#pragma mark - Resolve Move-(void) resolveSwapBetweenPosition:(CGPoint)firstPos position:(CGPoint)secondPos { DMRow *firstRow = _board.rows[(int)firstPos.y]; DMOrb *firstOrb = firstRow.orbs[(int)firstPos.x]; [self markMatchesForOrb:firstOrb]; DMRow *secondRow = _board.rows[(int)secondPos.y]; DMOrb *secondOrb = secondRow.orbs[(int)secondPos.x]; [self markMatchesForOrb:secondOrb]; [self destroyMarkedOrbs];}-(void) destroyMarkedOrbs { for (DMRow *row in _board.rows) { for (DMOrb *orb in row.orbs) { if (orb.markedForDestruction) { //placeholder until block settling is in place orb.type = DMOrbTypeNumTypes; } } }}#pragma mark - Mark Complete Matches-(void) markMatchesForOrb:(DMOrb *)orb { [self markRowForMatchesWithOrb:orb]; [self markColumnForMatchesWithOrb:orb];}-(void) markRowForMatchesWithOrb:(DMOrb *)orb { DMRow *row = _board.rows[(int)orb.boardPosition.y]; //search right in row BOOL otherColorFound = NO; NSMutableSet *orbsToMark = [[NSMutableSet alloc]init]; for (int i = orb.boardPosition.x; i < kNumOrbsPerRow; i++) { if (!otherColorFound) { DMOrb *nextOrb = row.orbs[i]; if (orb.type == nextOrb.type) { [orbsToMark addObject:nextOrb]; } else { otherColorFound = YES; } } } //search left in row otherColorFound = NO; for (int i = orb.boardPosition.x; i >= 0; i--) { if (!otherColorFound) { DMOrb *nextOrb = row.orbs[i]; if (orb.type == nextOrb.type) { [orbsToMark addObject:nextOrb]; } else { otherColorFound = YES; } } } //mark the appropriate orbs if (orbsToMark.count >= 3) { for (DMOrb *orb in orbsToMark) { orb.markedForDestruction = YES; } }}-(void) markColumnForMatchesWithOrb:(DMOrb *)orb { //create columns NSMutableArray *columns = [[NSMutableArray alloc]init]; for (int i = 0; i < kNumOrbsPerRow; i++) { [columns addObject:[[DMColumn alloc]initWithRows:_board.rows number:i]]; } DMColumn *column = columns[(int)orb.boardPosition.x]; //search up in column BOOL otherColorFound = NO; NSMutableSet *orbsToMark = [[NSMutableSet alloc]init]; for (int i = orb.boardPosition.y; i < kNumOrbsPerRow; i++) { if (!otherColorFound) { DMOrb *nextOrb = column.orbs[i]; if (orb.type == nextOrb.type) { [orbsToMark addObject:nextOrb]; } else { otherColorFound = YES; } } } //search down in column otherColorFound = NO; for (int i = orb.boardPosition.y; i >= 0; i--) { if (!otherColorFound) { DMOrb *nextOrb = column.orbs[i]; if (orb.type == nextOrb.type) { [orbsToMark addObject:nextOrb]; } else { otherColorFound = YES; } } } //mark the appropriate orbs if (orbsToMark.count >= 3) { for (DMOrb *orb in orbsToMark) { orb.markedForDestruction = YES; } }}@endThere is a bit of code duplication inside the BoardEval class in the methods that search for a match and the methods that mark the orbs that will be destroyed due to a match. I could not figure out a good solution for this. I wanted the search for any match to return as soon as it found one, because any match will cause a swap to be valid. It is only after the swap is valid that it needs to calculate all of the orbs that will be destroyed. Part of the reason for this setup is that the UI will animate an attempted swap when a swap is invalid, and will otherwise animate the completed swap. However, my approach may not be the best way to approach the problem.
Board Evaluator for Bejeweled Clone
game;objective c
This can be 100% eliminated:-(void) setBoard:(DMGameBoard *)board { _board = [DMGameBoard boardWithBoard:board];}And instead, change the property declaration to look like this:@property (copy) DMGameBoard *board;I'd rewrite this method:-(BOOL) findMatchesForOrb:(DMOrb *)orb { if ([self searchRowForMatchesWithOrb:orb]) { return YES; } if ([self searchColumnForMatchesWithOrb:orb]) { return YES; } return NO;}As this (notice I'm also renaming... find matches implies we'll return matches):- (BOOL)hasMatchesForOrb:(DMOrb *)orb { return [self searchRowForMatchesWithOrb:orb] || [self searchColumnForMatchesWithOrb:orb];}for (int i = orb.boardPosition.x; i < kNumOrbsPerRow; i++) { if (!otherColorFound) { if (orb.type == ((DMOrb *)row.orbs[i]).type) { numberOfOrbs++; } else { otherColorFound = YES; } }}if (numberOfOrbs >= 3) { return YES;}This is just a subsection of one of your methods, but it's a little confusing. Let' see if we can clear it up and make it a little more efficient.for (int i = orb.boardPosition.x; i < kNumOrbsPerRow; ++i) { if (orb.type == ((DMOrb *)row.orbs[i]).type) { if (++numOrbs >= 3) { return YES; } } else { break; }}This pattern can be applied in 3 other places. This pattern eliminates the otherColorFound variable and saves us a lot of iterations. Consider if your row is say 20 orbs wide, and I move an orb into the 20th spot. Your original implementation will iterate 20 times no matter what. With this implementation, we stop as soon as we find a different .type or as soon as we find 3 in a row.
_unix.163601
I'm just starting with my own Virtual Server (and Linux). I've an apache2 and a few WordPress sites. I need to send mails via PHP (contact forms). I managed to install ssmtp with the help of a few tutorials. It sends mail with an gmail account. I'm not sure about the right permissions of the ssmtp.conf: When I chmod 600 /etc/ssmtp/ssmtp.conf I cant't send mails from the commandline, php-contact forms are also not working.When I chmod 640 /etc/ssmtp/ssmtp.conf I can send mails from the commandline, but php-contact forms are not working.When I chmod 666 /etc/ssmtp/ssmtp.conf I can't send mails from the commandline and php-contact forms are working fine.Obviously I would like to stay with 666, but I'm not sure if this could be a security problem.
Permissions for /etc/ssmtp/ssmtp.conf
permissions;ssmtp
It appears that you have your Gmail password in the configuration file so you would want the the third number to be 0 (No permissions to Others). Ideal is 640. You can change the ownership of the configuration file (using the command chown) e.g. chown root:mail /etc/ssmtp/ssmtp.conf. You can send from the command line using sudo or as root. Your web server user also need to be a member of group mail. Or you can change that to root:www-data if the user group of the web server is www-data.
_cs.1113
I am trying to implement bidirectional search in a graph. I am using two breadth first searches from the start node and the goal node. The states that have been checked are stored in two hash tables (closed lists).How can I get the solution (path from the start to the goal), when I find that a state that is checked by one of the searches is in the closed list of the other?EDIT Here are the explanations from the book:Bidirectional search is implemented by having one or both of the searches check eachnode before it is expanded to see if it is in the fringe of the other search tree; if so, a solution has been found... Checking a node for membership in the other search tree can be done in constant time with a hash table...Some pages before: A node is a boolkkeeping data structure used to represent the search tree. A state corresponds to a configuration of the world... two different nodes can contain the same world state, if that state is generated via two different search paths. So from that I conclude that if nodes are kept in the hash tables than a node from the BFS started from the start node would not match a node constructed from the other BFS started from the goal node.And later in general Graph search algorithm the states are stored in the closed list, not the nodes, but it seems to me that even that the states are saved in the hash tables after that the nodes are retrieved from there.
How to construct the found path in bidirectional search
algorithms;graphs;shortest path
Let me give this question a try. I am not sure I do fully understand it so I was considering to post a comment but in the end, I preferred to try an explanation. Hope it helps!Raphael already suggested a solution (so I voted up his comment) which works even if you only store states instead of nodes. To make it clear: states: those in the original problem. These are uniquenodes: those enumerated by your search algorithm (bidirectional breadth-first search in your case). As stated in your book two different nodes can contain the same world state, if that state is generated via two different search paths so that it is very likely to have more nodes than states (since the former distinguish states by the different paths ---which can be exponentially large--- that lead to the same state).Obviously, the path from the start state $s$ to the target $t$ is computed by concatenating the paths from $s$ to $n$ and from $n$ to $t$ where $n$ is the node that was found in the hash table of the opposite search.Now, assuming you are using a consistent-heuristic function (a heuristic function $h (n)$ is said to be consistent if and only if it satisfies the triangular inequality $h(n) \leq c(n,m) + h(m)$ where $c(n,m)$ is the cost of the operator from node $n$ to one of its offsprings $m$) or no heuristic function at all (so that your BFS is a blind search) let me suggest the following procedure: Let me assume wlg that $n$ was generated by the forward search (i.e., from the start state $s$) and that it was found in the hash table of the backward search (i.e., the one issued from the goal node). In this case it suffices to expand the node $n$ and to select any descendant that appears also in the hash table of the backward search. You can do this since you are storing all states (instead of nodes) in both hash tables. No matter of the difference between nodes and states, if you generated $n$ in the backward search (which results from the fact that it is stored in the hash table) it had to be done via one of its parents which can be recovered now as one of its descendants (assuming you are traversing undirected graphs, otherwise just apply the inverse operators to recover the parents). Acting like this you will eventually get to the target node.The same mechanism applies to the forward search ---i.e., no need to store with each node its path to the start node, just use the closed list implemented as a hash table. Reverse the path obtained in the previous paragraph, concatenate them and there you are a solution path.If you are not using a consistent heuristic function, then you should store along each node in the hash table its value $g(n)$ ---i.e., the cost of the path from its corresponding root node, either $s$ or $t$. Doing so, the previous procedure is just slightly modified by selecting the parent (now generated as a successor) whose $g$ value is $g(n)-1$. However, this is not even necessary in case you are seeking (as it seems) any path from $s$ to $t$.Bidirectional search is one of the most intriguing paradigms in heuristic search. Noone has already found a simple way that makes it as efficient as in the case of blind search (where it is clearly a winner).Hope this helps,
_softwareengineering.250833
A friend has written a programming language. It has a syntax reminiscent of SGML. He has written an interpreter for it, and an IDE. He and his colleagues use it in-house as a server-side language. It can also be used to write command-line tools. He wants to make it available to the public, in the expectation that people will purchase a license to use it. He wants to keep the code expressing the language implementation to himself, as there's a fair bit of intellectual property tied up in it. I keep telling him that the day of closed-source programming languages is gone. I say, Look at all the major languages: the vast majority are open-source. You're going to have to go open-source too if you want anyone outside the company to pay any attention to what you've built.Am I giving him good advice or is there still room for proprietary languages that you pay for?LATERDen asked, ... could you please also explain how a language can be closed-source?I said, @Den you make a good point. What my friend wants to avoid, I suppose, is the situation where Microsoft cooks up a Java-alike language, calls it J++ and then gets into litigation with Sun about its Java-ness. How do you protect a syntax and a programming methodology from being hijacked by a company whose implementation could put you out of business?
Can a closed-source programming language survive?
programming languages;open source;closed source
The answer is yes, and no. It depends on the commercial motivations of potential customers and the attributes of the language and the problems it solves.No, the world does not need another general purpose computing language created by an individual or a small team. When Perl, Python, Ruby, Java and Javascript and were created there was a vacuum to fill, proprietary languages were expensive and the barrier to entry was low. Rebol is one that started off paid and is now free. Look at C# and Go to see how much harder it is now and how much bigger the teams are, even for languages that are more or less free.But yes, the world badly needs niche languages to fill a whole range of specific roles and will pay well for them. I can't quote you examples because neither you nor I have ever heard of most of them, but they are being used routinely in highly specialised situations and they make money for their creators. Solve a problem and you will get paid.So for your friend to make money he needs one or more of three things.An identifiable technical niche for which his language is the best available solution, preferably with a reasonably high barrier to entry to slow down competitors.An identifiable customer segment with a problem his language can solve as well as the capacity to pay for it to be solved.A body of pre-written code, documentation, tutorials and skills that will allow customers to put it to work immediately and start solving problems immediately.Problems mentioned in relying on small companies are not unique to programming languages, and are easily resolved by commercial means.Disclosure: I am the author of a commercial programming language system (Powerflex) that helped a lot of people build software businesses. That window closed as the Internet window opened.
_webmaster.107524
I'm using Joomla as CMS. It allows appending the website name before or after the actual site name. So I do it after the site name. If I put the main keyword in the website name, it will be appended to every page title after the site name.Is it better to remove the appending of the same phrase (website name/product name and so on) to every page? I'm afraid the main keyword which if indexed quite good will lose ranking if I use it only in a few pages.
For SEO, should I append the site's main keyword to the title tag of every page?
seo;title
Your website title shouldn't contain the same set of keywords on every page.Appending the business name at the end is OK.Try to create a unique title for every page based on what the page is all about. In some pages, you may have covered more keywords in that case you may not have space to append the business name at the end so you don't need to.Do not append set of keywords at the end in every page meta title.
_unix.280438
My Bluetooth adapter is not working.I tried to connect to my device using graphical interface, but the button connects not working.So, I had to use command line, but this time I get the error:root # /etc/init.d/bluetooth start[....] Starting bluetooth (via systemctl): bluetooth.serviceJob for bluetooth.service failed. See 'systemctl status bluetooth.service' and 'journalctl -xn' for details.and when I tried to get more details :root # systemctl -l status bluetooth.service bluetooth.service - Bluetooth service Loaded: loaded (/lib/systemd/system/bluetooth.service; enabled) Active: failed (Result: exit-code) since Sun 2016-05-01 21:04:08 EDT; 23s ago Docs: man:bluetoothd(8) Process: 9950 ExecStart=/usr/lib/bluetooth/bluetoothd (code=exited, status=1/FAILURE) Main PID: 9950 (code=exited, status=1/FAILURE) Status: Starting upMay 01 21:04:08 user bluetoothd[9950]: Bluetooth daemon 5.23May 01 21:04:08 user bluetoothd[9950]: D-Bus setup failed: Name already in useMay 01 21:04:08 user systemd[1]: bluetooth.service: main process exited, code=exited, status=1/FAILUREMay 01 21:04:08 user systemd[1]: Failed to start Bluetooth service.May 01 21:04:08 user systemd[1]: Unit bluetooth.service entered failed state.root #lsusbBus 002 Device 002: ID 8087:8000 Intel Corp. Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 001 Device 004: ID 0930:0220 Toshiba Corp. Bus 001 Device 002: ID 8087:8008 Intel Corp. Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hubBus 003 Device 002: ID 058f:6366 Alcor Micro Corp. Multi Flash ReaderBus 003 Device 008: ID 1bcf:0005 Sunplus Innovation Technology Inc. Optical MouseBus 003 Device 003: ID 04f2:b3b1 Chicony Electronics Co., Ltd Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubroot # lspci00:00.0 Host bridge: Intel Corporation Xeon E3-1200 v3/4th Gen Core Processor DRAM Controller (rev 06)00:02.0 VGA compatible controller: Intel Corporation 4th Gen Core Processor Integrated Graphics Controller (rev 06)00:03.0 Audio device: Intel Corporation Xeon E3-1200 v3/4th Gen Core Processor HD Audio Controller (rev 06)00:14.0 USB controller: Intel Corporation 8 Series/C220 Series Chipset Family USB xHCI (rev 04)00:16.0 Communication controller: Intel Corporation 8 Series/C220 Series Chipset Family MEI Controller #1 (rev 04)00:1a.0 USB controller: Intel Corporation 8 Series/C220 Series Chipset Family USB EHCI #2 (rev 04)00:1b.0 Audio device: Intel Corporation 8 Series/C220 Series Chipset High Definition Audio Controller (rev 04)00:1c.0 PCI bridge: Intel Corporation 8 Series/C220 Series Chipset Family PCI Express Root Port #1 (rev d4)00:1c.2 PCI bridge: Intel Corporation 8 Series/C220 Series Chipset Family PCI Express Root Port #3 (rev d4)00:1c.3 PCI bridge: Intel Corporation 8 Series/C220 Series Chipset Family PCI Express Root Port #4 (rev d4)00:1d.0 USB controller: Intel Corporation 8 Series/C220 Series Chipset Family USB EHCI #1 (rev 04)00:1f.0 ISA bridge: Intel Corporation HM86 Express LPC Controller (rev 04)00:1f.2 SATA controller: Intel Corporation 8 Series/C220 Series Chipset Family 6-port SATA Controller 1 [AHCI mode] (rev 04)00:1f.3 SMBus: Intel Corporation 8 Series/C220 Series Chipset Family SMBus Controller (rev 04)02:00.0 Network controller: Qualcomm Atheros QCA9565 / AR9565 Wireless Network Adapter (rev 01)03:00.0 Ethernet controller: Qualcomm Atheros QCA8172 Fast Ethernet (rev 10)kali version:4.0.0-kali1-amd64 #1 SMP Debian 4.0.4-1+kali2 (2015-06-03) x86_64 GNU/Linux
Kali: Bluetooth adapter is not working
debian;drivers;kali linux;bluetooth
null
_webmaster.3354
How often should one submit a site map to Google for a site similar to this?
How often should one submit a site map to Google for a site similar to this?
seo
null
_webapps.18059
I have found the article I was looking for on Wikipedia with the message This article is an orphan. at the top. I have also found another page with the topic of this article highlighted in red, as if the link should exist but has no target page. The complication is that the term used in the attempted link is not identical to the page title on the article but both are valid and should corefer. How can I make a redirect page whose title is the dead link to solve this problem?(I hope I explained this clearly enough.)
How do you make a redirect page on Wikipedia?
links;wikipedia
Check out this wiki page on redirecting wiki pages: Help:Redirect. A redirect is a page created so that navigation to a given title will take the reader directly to a different page. A redirect is created using the syntax:#REDIRECT [[target]] where Target is the name of the target page. It is also possible to add a section anchor to make a redirect to a specific section of the target page.A page will be treated as a redirect page if its wikitext begins with #REDIRECT followed by a valid wikilink or interwikilink.
_unix.17263
Possible Duplicate:How can I close a terminal without killing the command running in it? How to launch a GUI application (e.g. gedit) from terminal and detach it from there in one step?
Launching application from terminal
bash;terminal
The & operator enables the application to run in the background. Usenohup geditornohup gedit &(the latter lets you use the terminal after launching gedit, just press return to send it to the background). Nohup dispatches the application completely from the terminal and session.
_cstheory.36418
When I said a succinct representation of a graph of n nodes, I meant a Boolean circuit C of 2*b input gates (where b = |n| and |n| is the binary string length of n), such that for every b-bits integers i and j, then C accepts the input i and j if and only if (i, j) is an edge of the graph and the size of C is O(b^{k}), that is polylogarithmic in relation to n.
Is it possible to find always a succinct representation of an arbitrary graph?
cc.complexity theory
With n vertices, there are $O(2^{n \choose 2})$ possible labelled graphs (based on which edges are present). So you need ${n\choose 2}$ bits to store.
_webapps.58053
See this photo , it appears like mobile when I am using it from PC How can I restore it to default ?
My Facebook appears like mobile when I am using it from PC
facebook
That's how it's supposed to look on the desktop. As of today (March 9, 2014), Facebook changed the design so it has less clutter and bigger photos.
_reverseengineering.10736
I have got a custom.dll which is utilized in a larger application. The application executable imports this dll to use its functionality. But this functionality is not used through out the life cycle of the application but only when a specific event occurs. for instance when I input something in the application console a new thread would be created and some of the functionality of the given dll would be used. Now the problem is I am unable to find out what is exactly going on in the dll without having that application executable. I only have the dll file. I want to reverse it. Just like debugging an exe file and go through the registers step by step to find out what is what and why something happens, simply perform a dynamic analysis on the dll instead of the static one.To be more specific, the dll file creates a specific string, I want to know how that string is created and where it is stored for console usage.
How to reverse a dll and call its functions?
disassembly;debuggers;dll;patch reversing
null
_webmaster.78314
I have recently redone my website in wordpress and moved it to a different server.I need www.example.com/releases to point to another IP.I have set releases.example.com to point to this IP.So I'd now like when someone browses to www.example.com/releases for the user to be redirected to releases.example.com/releases.The reason we need this to happen is our software automatically checks that folder for new releases (and we don't want to have to update that part of the code).
Wordpress redirect folder to subdomain
wordpress
null
_datascience.6649
I am trying to see if my data is multimodal (in fact, I am more interested in bimodality of the data). I performed dip test and it does evidence against unmodal data. However, I want to see, in particular, if it is bimodal. I believe silver man's test can be used. However, I couldn't find the implementation of it in either r or in python. (The one in R is old and not working with the current version of R). Also, assuming that I have a bimodal data and that I am able to get the two components (using mixtools in R), how do I figure out how to find the point of intersection of the two components. For example, here is the histogram (overlaid with its density estimation) of the entire data. Here are the two components: I want to get the the x value where the curves intersected. I could have uploaded the data, but the length of the vector is rather long. Any general thought and idea is welcome including the R and/or Python packages are welcome.Thanks
Testing bimodality of data
machine learning;r;python;statistics
null
_scicomp.1469
How is (generalized) geometric programming different from general convex programming?A geometric program can be transformed into a convex program, and is typically solved by an interior point method. But what is the advantage over directly formulating the problem as a convex program and solving it by an interior point method?Does the class of geometric programs only constitutes a subset of the class of convex programs that can be solved especially efficient by interior point methods? Or is the advantage simply that a general geometric program can easily be specified in computer readable form.On the other hand, are there convex programs that cannot be approximated reasonably well by geometric programs?
How is geometric programming different from convex programming?
optimization;convex optimization
I'd actually never heard of geometric programming until this question. Here is a review paper by Stephen Boyd, et al (Vandenberghe is a co-author too) that is a tutorial on geometric programming.Geometric programs as originally expressed are not convex. For instance, $x^{1/2}$ is a posynomial, and it is not convex, so geometric programs aren't a strict subset of convex programming. The advantage of transforming a geometric program into a convex program is that the original geometric program is not necessarily convex. If you solved the geometric program as a nonlinear program (NLP), you would need to use methods from non-convex optimization in order to guarantee a global optimal solution. These methods are more expensive than convex optimization methods, require more algorithmic tuning, and require initial guesses.Moreover, if you use an algorithm from non-convex NLP, you would need to specify your feasible set as a compact set in $\mathbb{R}^{n}$; in geometric programs, $x > 0$ is a valid constraint.It's not clear if the set of geometric programs maps (through the log-exponential transformation) to a set of convex programs that solves particularly efficiently. I don't see any advantages to geometric programming beyond the transformation to convex programs.As for your last question, I don't think the set of geometric programs is isomorphic to the set of convex programs, so I suspect that there are convex programs that cannot be expressed as geometric programs, and of these programs, I suspect that there are some that can't be approximated reasonably well by geometric programs. However, I don't have a proof or a counterexample.
_softwareengineering.313514
I'm getting a list of items from an external API and each item has a number of ratings and an average rating out of 5.What is the best way to rank them? Is it statistically sound to just convert an item with 1000 ratings and a 4/5 average to an item with 800 upvotes and 200 downvotes and use Wilson Score? If not, are there any alternatives?
Alternative to Wilson Score when I only have the number of ratings and the average rating?
statistics
null
_unix.366132
This question is very basic and I ask it not only for myself but for more newcomers who see the term Variable substitution and having the following thoughts:As far as I understand, the term variable substitution deals with substituting a value of a given variable in another.Why is this action need a special term, why can't we just say changing a variable's value with editing it manually in Vim or Nano or sed?The above question isn't what I'm asking, it's but example to what I asked myself. This is my actual question:Why is there a Variable substitution concept in Bash? And if you answer, can you please give a practical example for what types of actions it uses you in your work.
Why is there a Variable substitution concept in Bash?
shell;variable substitution
substituting a value of a given variable in another.That description is wrong on several counts. Variable substitution replaces the name of a variable (plus some syntactic fluff) by its value. Furthermore, it does not operate in a variable, but in a command. The command could be one that sets the value of a variable, but that's just one case among many.For example, the command echo $foo displays the value of the variable. The source code contains $foo, and the corresponding output contains the value of the variable foo.The reason this is called variable substitution is that the shell operates by a series of transformations of strings (and lists of strings). For example (simplified), consider the command ls -l $dir/*.$ext. To evaluate it, several things happen in sequence:The shell starts to parse the command and splits it into three words: ls, -l and $dir/*.$ext.In the third word, the shell sees two variable substitutions to perform (that's what the dollar signs mean in this context). Say that the value of dir is /some/path and the value of ext is txt, then the shell rewrites $dir/*.$ext to /some/path/*.txt. This is a substitution because the value of each variable is substituted for the dollar-name syntax.The shell expands the wildcard pattern /some/path/*.txt to the list of matching file names.The shell executes ls with the arguments that it's computed.(The syntax $foo does more than substitute the value of a variable but that's another story.)In most programming languages, to take the value of a variable, you just write the variable's name. The shell is designed for interactive use; if you write a name it's interpreted as a literal string. That's why the syntax to take the value of a variable has an extra marker to say I want to take a variable's value.Why is this action need a special term, why can't we just say a Bash programmer changes a variable's value with editing it manually in Vim or Nano or sed?Variable substitution has nothing to do with changing the value of a variable. Changing the value of a variable is an assignment.Of course an assignment can contain variable substitutions, like any other command. But variable substitutions are not designed specifically for assignments.Furthermore you can't change the value of a variable with an editor. A variable has a value in each process, it isn't a system configuration. You can have configuration files that set the initial value of a variable, but after that the value can change.
_scicomp.25480
Suppose that we have to find an optimal solution $x^*$ to an optimization problem involving some function $f$, such that $0\in\partial f(x^*)$ where $\partial$ denotes the subdifferential.Let $(x_n)_{n\ge 0}$ be a sequence generated by some algorithm, satisfying $\lim\limits_{n \to \infty} (x_{n+1} -x_{n}) = 0$, and that $(x_n)_{n\ge 0}$ has an accumulation point $\bar{x}$ (e.g. when the sequence is bounded).Suppose further that this sequence has the following property:$$x_{n+1} -x_{n} \in \partial f(x_n).$$My question is: Under which conditions can we conclude that $0\in \partial f(\bar{x})$?Thanks in advance for your discussions!
Question concerning accumulation point
optimization;convex optimization
This holds if $f$ is convex, proper and lower semi-continuous (in which case the subdifferential is weakly-strongly closed) and$x_n\to \bar x$ strongly (in particular, if $\{x_n\}\subset \mathbb{R}^N$).(If $\bar x$ is just an accumulation point, you can apply this argument to the subsequence converging to it.)
_unix.226456
I have a TL-WN821N wifi adapter that is supposed to work using purely free software.It used to work when I used the Trisquel Linux distribution but now when I have switched to Debian it does not work.I know that the device is connected because it shows up in the output from the lsusb command.$ lsusbBus 008 Device 002: ID 0cf3:7015 Atheros Communications, Inc. TP-Link TL-WN821N v3 802.11n [Atheros AR7010+AR9287]Bus 008 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubBus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub...You can also see in the output that this device is identical to the one listed here on h-node which is supposed to work using the ath9k_htc driver.The ath9k_htc driver is installed as it shows up in the listing of the lsmod command:$ lsmod | grep athath9k_htc 51019 0 ath9k_common 21530 1 ath9k_htcath9k_hw 380024 2 ath9k_common,ath9k_htcath 21707 3 ath9k_common,ath9k_htc,ath9k_hwmac80211 421481 1 ath9k_htccfg80211 350041 5 ath,iwlwifi,ath9k_common,mac80211,ath9k_htcusbcore 170994 5 uhci_hcd,ehci_hcd,ehci_pci,usbhid,ath9k_htcThe problem is that the adapter does not light up and I get no connection. It is as if the adapter does not start up.I do not know what could be causing this problem. Do you know what could be wrong and how I can fix it?Update: I just noticed that I get this error message printed during the boot:[12423.2421] usb8-1: firmware: failed to load htc_7010.fw (-2)I do not remember the exact number between the square brackets ([ and ]). I hope this information is useful.I also get error messages about the firmware for the integrated WiFi card but that is because the firmware for it is missing. I want to run 100 % free software (except for BIOS) so I installed Debian without the proprietary firmware for the integrated WiFi card.
USB WiFi adapter using ath9k_htc not working on Linux
wifi;drivers;usb;kernel modules
null
_cs.6732
In the theory of distributed algorithms, there are problems with lower bounds, as $\Omega(n^2)$, that are big (I mean, bigger than $\Omega(n\log n)$), and nontrivial.I wonder if are there problems with similar bound in the theory of serial algorithm, I mean of order much greater than $\Omega(n\log n)$.With trivial, I mean obtained just considering that we must read the whole input and similarly.
Is there any nontrivial problem in the theory of serial algorithms with a nontrivial polynomial lower bound of $\Omega(n^2)$?
algorithms;complexity theory;lower bounds
null
_unix.198326
I'm trying to download this published journal article using cURL. It's the main page of an open access, so there should be not problems for anyone to see/download the article. I then extract the pdfurl, which keeps changing.Then I try to download the pdf:curl -L -o test.pdf http://www.sciencedirect.com/science/article/pii/S0378426612000817/pdfft?md5=6a85f34def09dd5cfb1d1b8feded0d51&pid=1-s2.0-S0378426612000817-main.pdfbut all the time it redirects me to the main page, which is then downloaded as a html page called test.pdf.
Download an article with cURL given a dynamic download link
pdf;curl;download
curl seems to handle redirects differently from wget by default. The direct download URL will involve some redirects and it also requires the HTTP referer header to be set correctly after the first redirect (otherwise, you will get a HTML page).First, you need to enable location redirects in curl with -L, and then enable curl's automatic handling of the referer header with --referer ;auto, that is,curl -L --referer ;auto -o test.pdf URL-for-direct-download
_scicomp.14549
Consider the Darcy equation,$$\mathbf{v} + \dfrac{k}{\mu_0}\nabla p = \mathbf{f} \\ \mathrm{div}\; \mathbf{v} = 0$$ If the coefficient $k$ is piecewise constant across an interface $\Gamma$ in the domain, we have that(1) $$\mathrm{jump}(k \cdot p\mathbf{n}) = 0 \rightarrow \mathrm{jump}(k\cdot p) =0 $$ over the interface $\Gamma$ On the other hand, the system can also be written as $$ \mathrm{div}(k \nabla p) = \mu_0f_1 = \mathrm{div}\mathbf{f} $$ in which case the jump condition now is(2) $$\mathrm{jump}(k \nabla p\cdot\mathbf{n}) = 0$$ over $\Gamma$I am confused as to how to reconcile the two. Secondly, does this dictate the choice of finite element spaces used in the solution ? For example, using a piecewise continuous polynomial for $p$ in 1) would be wrong ?
jump conditions for Poisson/Darcy equation in primal form versus mixed form
finite element;fluid dynamics;boundary conditions;poisson;elliptic pde
Your jump condition is wrong. To see this, let's assume for a moment that $\mu=1$ because it plays no real role in your formulation. Then, if you want to integrate the $\nabla p$ term and still want to get a symmetric formulation, you need to start with the first equation in the form$$ k^{-1} \mathbf v + \nabla p = k^{-1} \mathbf f,$$which ultimately leads to the jump condition $[p]=0$ -- in other words, the pressure must be continuous.How do you see that this is the right jump condition? Multiply the equation with a test function $\phi$ and integrate over a (arbitrary) part of the domain $\Omega_1$, for example one of the subdomains where $k$ is constant. After integrating by parts, you have$$ (\phi,k^{-1} \mathbf v)_{\Omega_1} - (\nabla\cdot\phi, p)_{\Omega_1} + (\phi,p\mathbf n)_{\partial\Omega_1}= (\phi,k^{-1} \mathbf f)_{\Omega_1}.$$Now do the same on $\Omega_2=\Omega\backslash\Omega_1$ and you get$$ (\phi,k^{-1} \mathbf v)_{\Omega_2} - (\nabla\cdot\phi, p)_{\Omega_2} + (\phi,p\mathbf n)_{\partial\Omega_2}= (\phi,k^{-1} \mathbf f)_{\Omega_2}.$$In the last equation, the sign of the normal vector is of course outward from $\Omega_2$, whereas in the first equation it is outward from $\Omega_1$. Now add these two equations together and you get$$ (\phi,k^{-1} \mathbf v)_{\Omega} - (\nabla\cdot\phi, p)_{\Omega} + (\phi,p\mathbf n)_{\partial\Omega} + (\phi,[p]\mathbf n)_{\Gamma} = (\phi,k^{-1} \mathbf f)_{\Omega},$$where $\Gamma$ is the interface between $\Omega_1$ and $\Omega_2$ and $[p]$ is the jump of $p$ on the interface. $\mathbf n$ is the normal from $\Omega_1$ info $\Omega_2$.We could, on the other hand, also have multiplied the original equation by $\phi$ and instead integrated over the entire domain right away. This would have shown that $\mathbf v$ must satisfy the equation$$ (\phi,k^{-1} \mathbf v)_{\Omega} - (\nabla\cdot\phi, p)_{\Omega} + (\phi,p\mathbf n)_{\partial\Omega} = (\phi,k^{-1} \mathbf f)_{\Omega}.$$Comparing with the equation immediately above, it is clear that we have the condition$$ (\phi \cdot \mathbf n,[p])_{\Gamma} = 0.$$Because the normal traces $\phi \cdot \mathbf n$ of functions in $H(div)$ are in $L^2(\Gamma)$, this implies that $[p]=0$ in $L^2(\Gamma)$.
_unix.325545
I have two Windows environments on different subnets (192.168.1.80/30 & 172.16.21.0/25), both statically assigned with addresses connecting to a single Debian router with two NICs. I've assigned 172.16.21.1 to eth1 and 192.168.1.81 to eth2. Each Windows environment is using their respective gateway IP.How do I allow the Windows environments to ping one other using the routing tables? I have already enabled net.ipv4.ip_forward=1 in the /etc/sysctl.conf file. I tried to use separate routing tables but my configuration didn't seem to work. Right now I've only done IP configuration on each machine, everything else is at default.ifconfig output:eth1 Link encap:Ethernet HWaddr 00:0c:29:08:05:01 inet addr:172.16.21.1 Bcast:172.16.21.127 Mask:255.255.255.128 inet6 addr: fe80::20c:29ff:fe08:501/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:526 errors:0 dropped:0 overruns:0 frame:0 TX packets:562 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:44822 (43.7 KiB) TX bytes:40642 (39.6 KiB) Interrupt:17 Base address:0x20a4 eth2 Link encap:Ethernet HWaddr 00:0c:29:08:05:0b inet addr:192.168.1.81 Bcast:192.168.1.83 Mask:255.255.255.252 inet6 addr: fe80::20c:29ff:fe08:50b/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:856 errors:0 dropped:0 overruns:0 frame:0 TX packets:909 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:71421 (69.7 KiB) TX bytes:85064 (83.0 KiB) Interrupt:17 Base address:0x2424 lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:65536 Metric:1 RX packets:47 errors:0 dropped:0 overruns:0 frame:0 TX packets:47 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:4733 (4.6 KiB) TX bytes:4733 (4.6 KiB)Routing table (using route -n):Kernel IP routing tableDestination Gateway Genmask Flags Metric Ref Use Iface0.0.0.0 172.16.21.1 0.0.0.0 UG 0 0 0 eth1169.254.0.0 0.0.0.0 255.255.0.0 U 1000 0 0 eth1172.16.21.0 172.16.21.1 255.255.255.128 UG 0 0 0 eth1192.168.1.80 192.168.1.81 255.255.255.252 UG 0 0 0 eth2tcpdump on eth1:tcpdump: verbose output suppressed, use -v or -vv for full protocol decodelistening on eth1, link-type EN10MB (Ethernet), capture size 262144 bytes14:35:38.591460 IP 172.16.21.2 > 192.168.1.82: ICMP echo request, id 1, seq 71, length 4014:35:43.126147 ARP, Request who-has router (00:0c:29:08:05:01 (oui Unknown)) tell 172.16.21.2, length 4614:35:43.126189 ARP, Reply router is-at 00:0c:29:08:05:01 (oui Unknown), length 2814:35:43.141954 IP 172.16.21.2 > 192.168.1.82: ICMP echo request, id 1, seq 72, length 4014:36:08.894329 IP router.mdns > 224.0.0.251.mdns: 0 [2q] PTR (QM)? _ipps._tcp.local. PTR (QM)? _ipp._tcp.local. (45)14:36:09.658277 ARP, Request who-has 199.7.91.13 tell router, length 2814:36:10.656763 ARP, Request who-has 199.7.91.13 tell router, length 2814:36:10.707265 IP6 fe80::20c:29ff:fe08:501.mdns > ff02::fb.mdns: 0 [2q] PTR (QM)? _ipps._tcp.local. PTR (QM)? _ipp._tcp.local. (45)
Connecting two Windows clients on seperate subnets through a Debian router
linux;debian;networking;routing;router
To make a Linux machine to act as a router, you need to tell it how to route the traffic going from both subnets.You need to use route command to add the routes for each subnet, somenthing like this should work:route add -net 192.168.1.80/30 gw 192.168.1.81 dev eth2route add -net 172.16.21.0/25 gw 172.16.21.1 dev eth1If you have already activated net.ipv4.ip_forward=1 like you said, it should work. If you have a firewall enabled on the debian machine, you need to make the appropiate configuration on it.
_webmaster.69447
I'm running an Ubuntu 12.04 server with Plesk 12, Apache 2.2.22 and PHP 5.3.10.I want to enable reCaptcha for my phpBB board, but every time I get this error: Could not open socketI've enabled allow_url_fopen for this domain and temporarily allowed outgoing traffic on port 80 and 443 for all IPs.According to phpinfo() allow_url_fopen is enabled.
fsockopen() not working
php;linux
null
_codereview.9374
I've re-written my old pagination class into something a little cleaner, and also added PDO support (The prev version was mysqli only). I'd like to clean it up even more if it's possible, does anyone have any pointers?Here's the class:<?class paginate{ /** * Array of options for the class * * @access public * @var array */ public $options = array( 'results_per_page' => 10, 'url' => '', 'url_page_number_var' => '*VAR*', 'text_prev' => '&laquo; Prev', 'text_next' => 'Next &raquo;', 'text_first' => '&laquo; First', 'text_last' => 'Last &raquo;', 'text_ellipses' => '...', 'class_ellipses' => 'ellipses', 'class_dead_links' => 'dead-link', 'class_live_links' => 'live-link', 'class_current_page' => 'current-link', 'class_ul' => 'pagination', 'show_links_first_last' => true, 'show_links_prev_next' => true, 'show_links_first_last_if_dead' => true, 'show_links_prev_next_if_dead' => true, 'max_links_between_ellipses' => 7, 'max_links_outside_ellipses' => 2, 'db_conn_type' => 'mysqli', /* Can be either: 'mysqli' or 'pdo' */ 'db_handle' => null ); /** * An array of any errors * * @access public * @var array */ public $debug_log; /** * The current page * * @access public * @var int */ public $current_page; /** * The query to run on the database * * @access public * @var string */ public $query; /** * The resultset of the query * * @access public * @var resultset */ public $resultset; /** * The total results of the query * * @access public * @var int */ public $total_results; /** * The total pages returned * * @access public * @var int */ public $total_pages; /** * The total total number of links to render before showing the ellipses * * @access public * @var int */ public $number_of_links_before_showing_ellipses; /** * The pagination links (Presented as an UL) * * @access public * @var string */ public $links_html; /** * __construct(int $surrent_page, string $query, array $options) * * Class constructor * * @access public * @param int $current_page The number of the current page (Starts at 1) * @param string $query The query to run on the database * @param array $options An array of options * @return void */ public function __construct($current_page = 1, $query = '', $options = null) { /* * Set the current page */ $this->current_page = $current_page; /* * Set the query to run */ $this->query = $query; /* * Populate the options array */ if(!empty($options)) { foreach($options as $key => $value) { if(array_key_exists($key, $this->options)) { $this->options[$key] = $value; } else { $this->debug_log[] = 'Attempted to add setting \''.$key.'\' with the value \''.$value.'\' - option does not exist'; } } } /* * Check to make sure 'max_links_between_ellipses' is an odd number */ if(!($this->options['max_links_between_ellipses'] & 1)) { $this->debug_log[] = 'Setting \'max_links_between_ellipses\' has been set with the value \''.$this->options['max_links_between_ellipses'].'\' - This number must be an odd number'; echo 'Setting \'max_links_between_ellipses\' has been set with the value \''.$this->options['max_links_between_ellipses'].'\' - This number must be an odd number'; } $this->prepare_query(); $this->run_query(); $this->calculate_number_of_pages(); $this->calculate_max_pages_before_ellipses(); $this->build_links(); } /** * prepare_query(void) * * Prepares the query to be run with the found rows and start/end limits * * @access public * @return void */ public function prepare_query() { /* * Add SQL_CALC_FOUND_ROWS for finding out total amount of results later on */ $this->query = substr_replace($this->query, 'SELECT SQL_CALC_FOUND_ROWS', 0, 6); /* * Add our start/end limit */ if($this->current_page == 1) { $this->query .= ' LIMIT 0, '.$this->options['results_per_page']; } else { $this->query .= ' LIMIT '.(($this->current_page - 1) * $this->options['results_per_page']).', '.$this->options['results_per_page']; } } /** * run_query(void) * * Run's the query against the database * * @access public * @return void */ public function run_query() { if($this->options['db_conn_type'] == 'mysqli') { /* * Execute using MySQLi */ $this->resultset = $this->options['db_handle']->query($this->query); /* * Get the total results with FOUND_ROWS() */ $count_rows = $this->options['db_handle']->query('SELECT FOUND_ROWS();'); $found_rows = $count_rows->fetch_assoc(); $this->total_results = $found_rows['FOUND_ROWS()']; } elseif($this->options['db_conn_type'] == 'pdo') { /* * Execute using PDO */ $pdos = $this->options['db_handle']->prepare($this->query); $pdos->execute(); $this->resultset = $pdos; /* * Get the total results with FOUND_ROWS() */ $pdos_fr = $this->options['db_handle']->prepare(SELECT FOUND_ROWS();); $pdos_fr->execute(); $pdos_fr_result = $pdos_fr->fetch(PDO::FETCH_ASSOC); $this->total_results = $pdos_fr_result['FOUND_ROWS()']; } else { /* * An unknown DB connection type has been set */ $this->debug_log[] = 'You have selected a \'db_conn_type\' of \''.$this->options['db_conn_type'].'\' - this method is not supported'; } } /** * calculate_number_of_pages(void) * * Calculates how many pages there will be * * @access public * @return void */ public function calculate_number_of_pages() { $this->total_pages = ceil($this->total_results / $this->options['results_per_page']); } /** * calculate_max_pages_before_ellipses(void) * * Calculates the number of links to show before showing an ellipses * * @access public * @return void */ public function calculate_max_pages_before_ellipses() { $this->number_of_links_before_showing_ellipses = $this->options['max_links_between_ellipses'] + ($this->options['max_links_outside_ellipses'] * 2); } /** * build_link_url(int $page_number) * * Builds the URL to insert in links * * @access public * @param int $page_number The page number to insert into the link * @return string The built URL */ public function build_link_url($page_number) { return str_replace($this->options['url_page_number_var'], $page_number, $this->options['url']); } /** * get_current_or_normal_class(int $page_number) * * Returns the live link class, or link link and current page class * * @access public * @param int $page_number The page number to insert into the link * @return string The class to use */ public function get_current_or_normal_class($page_number) { if($page_number == $this->current_page) { return $this->options['class_live_links'].' '.$this->options['class_current_page']; } else { return $this->options['class_live_links']; } } /** * build_links(void) * * Build the HTML links * * @access public * @return void */ public function build_links() { /* * Start the UL */ $this->links_html = '<ul class='.$this->options['class_ul'].'>'.PHP_EOL; /* * The 'First' link */ if($this->options['show_links_first_last'] == true) { if($this->current_page == 1 && $this->options['show_links_first_last_if_dead'] == true) { $this->links_html .= '<li><span class='.$this->options['class_dead_links'].'>'.$this->options['text_first'].'</span></li>'.PHP_EOL; } elseif($this->current_page != 1) { $this->links_html .= '<li><a class='.$this->options['class_live_links'].' href='.$this->build_link_url(1).'>'.$this->options['text_first'].'</a></li>'.PHP_EOL; } } /* * The 'Previous' link */ if($this->options['show_links_prev_next'] == true) { if($this->current_page == 1 && $this->options['show_links_prev_next_if_dead'] == true) { $this->links_html .= '<li><span class='.$this->options['class_dead_links'].'>'.$this->options['text_prev'].'</span></li>'.PHP_EOL; } elseif($this->current_page != 1) { $this->links_html .= '<li><a class='.$this->options['class_live_links'].' href='.$this->build_link_url($this->current_page - 1).'>'.$this->options['text_prev'].'</a></li>'.PHP_EOL; } } /* * Build our main links */ if($this->total_pages <= $this->number_of_links_before_showing_ellipses) { /* * If there's not enough links to have an ellipses in the set, just run through them all */ $counter = 1; while($counter <= $this->total_pages) { $this->links_html .= '<li><a href='.$this->build_link_url($counter).' class='.$this->get_current_or_normal_class($counter).'>'.$counter.'</a></li>'.PHP_EOL; $counter++; } } else { /* * We have enough links to show the ellipses, so run through other method */ if($this->current_page <= ($this->options['max_links_between_ellipses'] + $this->options['max_links_outside_ellipses'])) { /* * Type 1 - skipping the first ellipses due to being low in the current page number */ $counter = 1; while($counter <= ($this->options['max_links_between_ellipses'] + $this->options['max_links_outside_ellipses'])) { $this->links_html .= '<li><a href='.$this->build_link_url($counter).' class='.$this->get_current_or_normal_class($counter).'>'.$counter.'</a></li>'.PHP_EOL; $counter++; } $this->links_html .= '<li><span class='.$this->options['class_ellipses'].'>'.$this->options['text_ellipses'].'</span></li>'.PHP_EOL; $counter = ($this->total_pages - $this->options['max_links_outside_ellipses']) + 1; while($counter <= $this->total_pages) { $this->links_html .= '<li><a href='.$this->build_link_url($counter).' class='.$this->get_current_or_normal_class($counter).'>'.$counter.'</a></li>'.PHP_EOL; $counter++; } } elseif($this->current_page > ($this->options['max_links_between_ellipses'] + $this->options['max_links_outside_ellipses']) && $this->current_page < ($this->total_pages - ($this->options['max_links_between_ellipses'] + $this->options['max_links_outside_ellipses']) + 1)) { /* * Type 2 - Current page is between both sets of ellipses */ $counter = 1; while($counter <= $this->options['max_links_outside_ellipses']) { $this->links_html .= '<li><a href='.$this->build_link_url($counter).' class='.$this->get_current_or_normal_class($counter).'>'.$counter.'</a></li>'.PHP_EOL; $counter++; } /* * Pop in an ellipses */ $this->links_html .= '<li><span class='.$this->options['class_ellipses'].'>'.$this->options['text_ellipses'].'</span></li>'.PHP_EOL; $before_after = (($this->options['max_links_between_ellipses'] - 1) / 2); $counter = $this->current_page - $before_after; while($counter <= $this->current_page + $before_after) { $this->links_html .= '<li><a href='.$this->build_link_url($counter).' class='.$this->get_current_or_normal_class($counter).'>'.$counter.'</a></li>'.PHP_EOL; $counter++; } /* * Pop in an ellipses */ $this->links_html .= '<li><span class='.$this->options['class_ellipses'].'>'.$this->options['text_ellipses'].'</span></li>'.PHP_EOL; $counter = ($this->total_pages - $this->options['max_links_outside_ellipses']) + 1; while($counter <= $this->total_pages) { $this->links_html .= '<li><a href='.$this->build_link_url($counter).' class='.$this->get_current_or_normal_class($counter).'>'.$counter.'</a></li>'.PHP_EOL; $counter++; } } else { /* * Type 1 - skipping the last ellipses due to being high in the current page number */ $counter = 1; while($counter <= $this->options['max_links_outside_ellipses']) { $this->links_html .= '<li><a href='.$this->build_link_url($counter).' class='.$this->get_current_or_normal_class($counter).'>'.$counter.'</a></li>'.PHP_EOL; $counter++; } $this->links_html .= '<li><span class='.$this->options['class_ellipses'].'>'.$this->options['text_ellipses'].'</span></li>'.PHP_EOL; $counter = ($this->total_pages - ($this->options['max_links_between_ellipses'] + $this->options['max_links_outside_ellipses'])) + 1; while($counter <= $this->total_pages) { $this->links_html .= '<li><a href='.$this->build_link_url($counter).' class='.$this->get_current_or_normal_class($counter).'>'.$counter.'</a></li>'.PHP_EOL; $counter++; } } } /* * The 'Next' link */ if($this->options['show_links_prev_next'] == true) { if($this->current_page == $this->total_pages && $this->options['show_links_prev_next_if_dead'] == true) { $this->links_html .= '<li><span class='.$this->options['class_dead_links'].'>'.$this->options['text_next'].'</span></li>'.PHP_EOL; } elseif($this->current_page != $this->total_pages) { $this->links_html .= '<li><a class='.$this->options['class_live_links'].' href='.$this->build_link_url($this->current_page + 1).'>'.$this->options['text_next'].'</a></li>'.PHP_EOL; } } /* * The 'Last' link */ if($this->options['show_links_first_last'] == true) { if($this->current_page == $this->total_pages && $this->options['show_links_first_last_if_dead'] == true) { $this->links_html .= '<li><span class='.$this->options['class_dead_links'].'>'.$this->options['text_last'].'</span></li>'.PHP_EOL; } elseif($this->current_page != $this->total_pages) { $this->links_html .= '<li><a class='.$this->options['class_live_links'].' href='.$this->build_link_url($this->total_pages).'>'.$this->options['text_last'].'</a></li>'.PHP_EOL; } } /* * Close the UL */ $this->links_html .= '</ul>'.PHP_EOL; } /** * debug(void) * * Show the debug log * * @access public * @return void */ public function debug() { print_r($debug_log); }}?>And here's an example of how it's called:<?$options = array( 'results_per_page' => 10, 'url' => 'http://www.domain.com/somepage.php?page=*VAR*', 'db_conn_type' => 'pdo', 'db_handle' => $dbh);$paginate = new paginate($page, 'SELECT cols FROM table', $options);$result = $paginate->resultset->fetchAll();?>ta!
PHP/MySQL Pagination Class - How can it be improved?
php;pagination
I'm not going to do a full code review, but there are a couple of issues that I think need to be addressed. Everything's public in your class, this is very bad because it means that external agents can scribble all over the class internal state. You should definitely make all your properties (variables) protected or private and provide a set of public setters and getters instead, as this will give you more control over what external state consumers of your class can change and how. I've already given a few answers that cover the benefits of getters and setters, so you might want to look those up ;)When designing a class you should be thinking about what the class embodies, what it's meant to accomplish and what services it's providing to consumers of the class. What is the consumer going to ask the class to do and what output can the consumer expect in return? For these services you need to provide a public interface (public methods/functions) so consumers can ask the class to perform some service for them and collect the results. Anything else that the class does internally to achieve the goal of providing the service it implements should not be publicly available to consumers because consumers don't need to know about how a class does what it does, only that the class provides that service. The more of the internals of your class you expose to outside agents, the harder it becomes to make changes without breaking something that depends on the class. Your constructor is too big. Constructors should do nothing more than initialize the class to a usable state, they shouldn't do any actual work, because if you want to subclass a class to give it different behaviour and a lot of behaviour is defined in the constructor then you will need to either inherit a lot of behaviour you don't want, or rewrite the constructor to completely override what the superclass constructor does, possibly resulting in a lot of duplication of effort as you rewrite the bits of the superclass constructor that you do want. It also means that you have less opportunity to configure an instance of a class before asking it do provide its service for you. Your build_links method is also too big. This means it's inflexible and difficult to modify without causing other issues elsewhere. If you split the method down into smaller chunks, then you can more easily swap those chunks out for different ones should you choose to subclass your class, thus making it easier to adapt your class to work in different ways. For example, all the code between each of the function's first level of if statements (the ones with the least indentation) could be split out into their own (protected) methods. This will make the main method shorter, and the methods in question can be easily overridden in any subclasses you choose to make. Also, if you notice you have several methods doing similar work then you have an opportunity to come up with a way to generalize the operation being done and removing some code from your class.Long methods/functions have other issues too when it comes to understandability and maintainability. A shorter method is easier to understand and therefore maintain, so long methods should be considered a code smell and refactored out. A good rule of thumb is, if you need to scroll to fit the method's body into your editor screen then you probably need to split it into smaller chunks of functionality. Programming is all about divide and conquer (splitting a big problem into smaller problems and solving each small problem until you have a solution to the big problem they're a part of). Additionally, good code isn't code where there's nothing left to add, but when there's nothing left to take away.
_unix.328254
So my real question is, how do i access the game file in progam files (x86) in script editor to create the shortcut ? when i enter the cmd in terminal cd ~/.wine/drive_c/Program\ Files\ \(x86\)/ubisoft/prince\ of\ persia/prince\ of\ persia.exe/but in script editor this doesn't work, for some reason typing the (x86) doesn't allow it to, and the spaces are wrong too, is there anyone that knows how to write the cmd i wrote in script editor?. Thank you in advance. p.s. i'm a beginner at all this coding so i have no idea about it and really need help. Thank you again.
How to create a short cut for the app to my desktop, instead of using terminal?
shell script;shell;command line;scripting;osx
null
_unix.241601
For a guest machine how can I know where the files created in vm (not the VM config files but actual files which I create while using VM) are stored on my host machine? To which directory of my host the root directory of VM is mapped?
Where does KVM hypervisor store VM files?
files;kvm;virsh
null
_unix.317014
I was looking at the header of some elf files and noticed something odd:ELF Header: Magic: 7f 45 4c 46 01 02 01 00 00 00 00 00 00 00 00 00 Class: ELF32 Data: 2's complement, big endian Version: 1 (current) OS/ABI: UNIX - System V ABI Version: 0 Type: EXEC (Executable file) Machine: MIPS R3000 Version: 0x1 ... Flags: 0x80000027, noreorder, pic, cpic, abi2, mips64r2 ...Why is it labeled as ELF32 but have a mips64r2 flag? What does that indicate? Does it mean that the file was compiled as a 32 bit program intended to be run on a 64 bit processor? Also, if it is running on mips64r2, why is the machine labeled as MIPS r3000?If I wanted to run this with qemu, what type of environment would I need? mips64 r2? mips r3000?
Meaning of MIPS flags in elf header
qemu;elf;mips
null
_softwareengineering.216274
Hello fellow Programmers,I am still a relatively new programmer and have recently gotten my first on-campus programming position. I am the sole dev responsible for 8 domains as well as 3 small sized PHP web apps. The campus has its web environment divided into staging and live servers -- we develop on the staging via SFTP and then push the updates to the live server through a web GUI.I use Sublime Text 2 and the Sublime SFTP plugin currently for all my dev work (its my preferred editor). If I am just making an edit to a page I'll open that individual file via the ftp browser. If I am working on the PHP web app projects, I have the app directory mapped to a local folder so that when I save locally the file is auto-uploaded through Sublime SFTP.I feel like this workflow is slow and sub-optimal. How can I improve my workflow for working with remote content? I'd love to set up a local environment on my machine as that would eliminate the constant SFTP upload/download, but as I said there are many sites and the space required for a local copy of the entire domain would be quite large and complex; not to mention keeping it updated with whatever the latest on the staging server is would be a nightmare.Anyone know how I can improve my general web dev workflow from what I've described? I'd really like to cut out constantly editing over FTP but I'm not sure where to start other than ripping the entire directory and dumping it into XAMP.
What are some efficient ways to set up my environment when working on a remote site?
php;optimization;workflows;development environment;sublime text
keeping it updated with whatever the latest on the staging server is would be a nightmare.It's shouldn't be a nightmare, it should be trivial. At a minimum you should be using version control to automate much of this. These days I would start with either git or mercurial. Any professional programmer should run away screaming in horror from a job that does not use version control in some fashion. It's something you need in your toolbox RIGHT NOW. Distributed version control makes it very easy to just set up on your own and even if you can't get buy in from the group at least you can keep yourself sane. Mercurial (hg) is easier to get started with IMHO than git, but git is probably the defacto standard. Create a github account for yourself and play around with some simple boring stuff to get a feel for it. Or try hg at bitbucket.com. You don't need either site to use these programs effectively, but they do make it easier to get started. Once you have version control in your toolbox, the next thing is to have a portable development environment. If you have anything like a reasonably powered laptop or workstation you should be able to completely duplicate the production environment of most web applications. Using a tool like Vagrant can make this a simple as a single command to get a complete test environment up and running. It does take a fair amount of work, but this is the world many people are working in these days. The more you can learn about these tools, the more employable you'll be in the future.
_webmaster.102589
I am trying to download report data using API for adgroup_performance_report. I get all the campaigns etc in the report except download campaigns. How do I get about that? What am I missing?Details:AWQL query:SELECT Date,HourOfDay, AdGroupId, AdGroupName,AdNetworkType1, CampaignId, CampaignName, Impressions, Clicks, Cost FROM ADGROUP_PERFORMANCE_REPORT DURING YESTERDAYAPI: v201609Language: PythonMore:Download campaigns: Not sure if they are download campaigns but they have a down arrow button where normally it's search and video
How to get download campaigns data from Adwords API
google api;google adwords
The campaign type you are referring to are the Universal App Campaigns (UAC). For reporting, UAC statistics can be found in the following reports mentioned here. Currently, however, the AdvertisingChannelType and AdvertisingChannelSubType fields are not available in the Adgroup Performance Report.Source: https://groups.google.com/forum/#!topic/adwords-api/l2H5E3bvv-g
_unix.283471
I'm trying to print only the <N>th line before a search pattern. grep -B<N> prints all the <N> lines before the search pattern. I saw the awk code here that can print only the <N>th line after the search pattern.awk 'c&&!--c;/pattern/{c=N}' fileHow to modify this to print only the <N>th line before each line that matches pattern ? For example, here is my input file...... 0.50007496 0.42473932 0.01527831 0.99997456 0.97033575 0.44364198Direct configuration= 1 0.16929051 0.16544726 0.16608723 0.16984300 0.16855274 0.50171112...... 0.50089841 0.42608090 0.01499159 0.99982054 0.97154975 0.44403547Direct configuration= 2 0.16931296 0.16553376 0.16600890 0.16999941 0.16847055 0.50170694 ...I need a command that can give me back the 2nd line before the search string Direct configuration.I'm trying to run this in SUSE-Linux
Print only the Nth line before each line that matches a pattern
text processing;awk;search
A buffer of lines needs to be used.Give a try to this:awk -v N=4 -v pattern=example.*pattern '{i=(1+(i%N));if (buffer[i]&& $0 ~ pattern) print buffer[i]; buffer[i]=$0;}' fileSet N value to the Nth line before the pattern to print.Set patternvalue to the regex to search.buffer is an array of N elements. It is used to store the lines. Each time the pattern is found, the Nth line before the pattern is printed.
_unix.114523
I have set up a cron job on my local Ubuntu 12.04 server to log on a remote server through a passwordless ssh connection and run mysqldump on a database on that server once a day. My problem is that, in addition to running mysqldump at 00:00 every day, it is for some reason also run at HH:17 at every hour, thereby filling up the disk fairly rapidly. The job in my crontab is set up as:@daily /bin/bash /home/backup/scripts/db_backupThe most important parts of the script db_backup looks like this:#!/bin/bash# Sets the properties and folders to be backed uphost_name=admin@the_host.comdb_name=the_db_namedb_backup_folder_at_host=~/db_backup# Dumps the mysql database{ # Try ssh ${host_name} mysqldump ${db_name} > ${db_backup_folder_at_host}/backup$(date +%F_%R).sql && echo $(date) SUCCESS! mysqldump of database} || { # Catch echo $(date) FAILURE! mysqldump of database}At the remote server I have specified a .my.cnf file for the database (in the home folder) like this:[mysqldump]user=USERNAMEpassword=PASSWORDhost=MYSQLSERVERand this works fine.The crontab is successfully installed for the super user of my local Ubuntu 12.04 server. I have tried rebooting the server, but that does not fix the problem. Running sudo ps -A | grep cron at the Ubuntu server produces 1166 ? 00:00:00 cron as output, so only one process is running. Running sudo crontab -l shows the daily cron job above, while running crontab -l shows that no jobs are installed for the regular user. There are no cron jobs running on the remote server.Can anyone give me a hint on how this can be happening? Where can I search for clues?Note that I have also tried the following for the crontab, but mysqldump is still run every HH:17:0 0 * * * /bin/bash /home/backup/scripts/db_backup
cron runs job at unexpected times
ssh;cron
Although I'm running a different version of ubuntu, my /etc/crontab runs the hourly script 17mins past the hour.SHELL=/bin/shPATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin# m h dom mon dow user command17 * * * * root cd / && run-parts --report /etc/cron.hourly25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )#Have a look in /etc/cron.hourly
_softwareengineering.266752
I am a freshman college student currently learning C++ programming. I am good at math and physics, so I am looking to specialize in 2D/3D graphics with OpenGL. My question is about the differences between OpenGL and OpenCV, and the amount of overlap these areas have. From what I have read, one creates graphics while the other processes them. I have many books on 3D graphics and the mathematics associated with it. What I am wondering is if the same concepts I am learning in OpenGL could be applied to OpenCV. Is it possible to become a C++ software engineer that could specialize in both OpenGL AND OpenCV, or is this an unrealistic goal?I ask these questions because I understand that 2D/3D graphics programming requires a tremendous amount of knowledge in math and physics, but I don't know too much about OpenCV and the prerequisite skills necessary to get my foot in the door.
OpenGL vs OpenCV for beginner
c++;graphics;opengl
OpenGL is a 3D graphics API. It provides APIs describe a 3D scene and render it to a framebuffer and ultimately display it on a screen. The primitives it has are vertex lists, triangle lists, normal vector lists, etc. n.b. 2D is a special case of 3D; IIRC OpenGL doesn't have explicit 2D support (i.e. sprites and bit blit)OpenCV is a computer vision (CV) API, and has implementations of various CV algorithms, blob detection, template matching, etc.OpenCV generally operates on real image data, and wouldn't operate on graphics generated by OpenGL. (unless one was trying to make an AI bot that only sees the framebuffer output of a game, but that in another tangent altogether.)Is it possible to become a C++ software engineer that could specialize in both OpenGL AND OpenCV, or is this an unrealistic goal? Sure, they are different types of systems, and you could specialize in more than one thing. As for OpenGL and 3D graphics, if you learn one you can probably use any of them.For computer vision learing one system will certianly help with another, but probably not to the same extent as computer graphics.n.b This question probably belongs an another board.
_unix.249434
How to partitioning hard disk for two different linux system on the GPT/UEFI.Size of disk 500gb.I ask because of the fact the disk is limited to 4 primary partition.I want to have 2 partitions on each system and one common.1 section will be EFI
How to partition my hard disk
filesystems;partition
GPT can have as many partitions as you want*. Therefore, you can have them all. Most of the time when I partition my disc, I set up /home on separate partition for my data(music, images, etc). This has a benefit of being able to reinstall my system without losing data.So we already have 3 partitions: swap(double the ram), /(I give it 1/2 of disc space I have), and /home (another 1/2). You can also make separate /var for programs, or /boot, but they aren't really needed - you'll do just fine with these 3.As for filesystems, here's what I go with:swap: swap/, /home : ext4/boot : ext2I basically take these 3(+ I have /boot), set up swap and boot, then divide rest in half, approximately. Should work for you too.* Given you don't want insanely many partitions.
_softwareengineering.73532
There are lots of great books and resources out there about managing new software developments, but very little that I've seen about managing ongoing maintenance of software systems. I'm not talking about big enhancements, I'm talking about the little 1 or 2 day bug fixes and updates that quickly accumulate once a system goes into production.Any recommended books or other resources on this subject?
How to manage maintenance
maintenance
null
_unix.344348
terminal, run web browser: web_browser & disownweb browser opens fine.it seems to be disowned by the terminal.but as I use the web browser... to surf the web..I begin to see the web browser reporting datato that terminal.terminal prints data about the web browser.so I suppose disown is not sufficient tocompletely disown the web browser ?
web_browser & disown : still see-ing data
bash;terminal;disown
The web browser is still run with its output and input connected to your terminal.Disown will only stop your shell from sending signals to it when it sends signals to its children.To get rid of the output you need to redirect the outputbrowser > /dev/null 2>&1 &orbrowser > /dev/null 2> /dev/nullIf you are running this in an ssh session you will also want to disconnect the input just in case so that it does not hang:browser < /dev/null > /dev/null 2>&1 &and then you can also disown itbrowser < /dev/null > /dev/null 2>&1 &disown
_unix.292189
I am running Fedora 24 with Gnome Shell. I try to pair my new Bose QuietComfort 35 over Bluetooth. I started using the Gnome interface. Unfortunately, the connection seems not to hold. It appears as constantly connecting/disconnecting:https://youtu.be/eUZ9D9rGUZYMy next step was to perform some checks using the command-line. First, I checked that the bluetooth service is running:$ sudo systemctl status bluetooth bluetooth.service - Bluetooth service Loaded: loaded (/usr/lib/systemd/system/bluetooth.service; enabled; vendor preset: enabled) Active: active (running) since dim. 2016-06-26 11:19:24 CEST; 14min ago Docs: man:bluetoothd(8) Main PID: 932 (bluetoothd) Status: Running Tasks: 1 (limit: 512) Memory: 2.1M CPU: 222ms CGroup: /system.slice/bluetooth.service 932 /usr/libexec/bluetooth/bluetoothdjuin 26 11:19:24 leonard systemd[1]: Starting Bluetooth service...juin 26 11:19:24 leonard bluetoothd[932]: Bluetooth daemon 5.40juin 26 11:19:24 leonard bluetoothd[932]: Starting SDP serverjuin 26 11:19:24 leonard bluetoothd[932]: Bluetooth management interface 1.11 initializedjuin 26 11:19:24 leonard bluetoothd[932]: Failed to obtain handles for Service Changed characteristicjuin 26 11:19:24 leonard systemd[1]: Started Bluetooth service.juin 26 11:19:37 leonard bluetoothd[932]: Endpoint registered: sender=:1.68 path=/MediaEndpoint/A2DPSourcejuin 26 11:19:37 leonard bluetoothd[932]: Endpoint registered: sender=:1.68 path=/MediaEndpoint/A2DPSinkjuin 26 11:20:26 leonard bluetoothd[932]: No cache for 08:DF:1F:DB:A7:8AThen, I have tried to follow some explanations from Archlinux wiki with no success. The pairing is failing Failed to pair: org.bluez.Error.AuthenticationFailed:$ sudo bluetoothctl [NEW] Controller 00:1A:7D:DA:71:05 leonard [default][NEW] Device 08:DF:1F:DB:A7:8A Bose QuietComfort 35[NEW] Device 40:EF:4C:8A:AF:C6 EDIFIER Luna Eclipse[bluetooth]# agent onAgent registered[bluetooth]# scan onDiscovery started[CHG] Controller 00:1A:7D:DA:71:05 Discovering: yes[CHG] Device 08:DF:1F:DB:A7:8A RSSI: -77[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 0000febe-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A RSSI: -69[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 0000febe-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 0000110d-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 0000110b-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 0000110e-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 0000110f-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 00001130-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 0000112e-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 0000111e-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 00001108-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 00001131-0000-1000-8000-00805f9b34fb[CHG] Device 08:DF:1F:DB:A7:8A UUIDs: 00000000-deca-fade-deca-deafdecacaff[bluetooth]# devicesDevice 08:DF:1F:DB:A7:8A Bose QuietComfort 35Device 40:EF:4C:8A:AF:C6 EDIFIER Luna Eclipse[CHG] Device 08:DF:1F:DB:A7:8A RSSI: -82[CHG] Device 08:DF:1F:DB:A7:8A RSSI: -68[CHG] Device 08:DF:1F:DB:A7:8A RSSI: -79[bluetooth]# trust 08:DF:1F:DB:A7:8AChanging 08:DF:1F:DB:A7:8A trust succeeded[bluetooth]# pair 08:DF:1F:DB:A7:8AAttempting to pair with 08:DF:1F:DB:A7:8A[CHG] Device 08:DF:1F:DB:A7:8A Connected: yesFailed to pair: org.bluez.Error.AuthenticationFailed[CHG] Device 08:DF:1F:DB:A7:8A Connected: noI tried to disable SSPMode but it seems to have no effect:$ sudo hciconfig hci0 sspmode 0When I use bluetoothctl, journalctl logs the following:juin 26 11:37:21 leonard sudo[4348]: lpellegr : TTY=pts/2 ; PWD=/home/lpellegr ; USER=root ; COMMAND=/bin/bluetoothctljuin 26 11:37:21 leonard audit[4348]: USER_CMD pid=4348 uid=1000 auid=4294967295 ses=4294967295 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 msg='cwd=/home/lpellegr cmd=bluetoothctl terminal=ptjuin 26 11:37:21 leonard audit[4348]: CRED_REFR pid=4348 uid=0 auid=4294967295 ses=4294967295 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 msg='op=PAM:setcred grantors=pam_env,pam_fprintd acct=roojuin 26 11:37:21 leonard sudo[4348]: pam_systemd(sudo:session): Cannot create session: Already occupied by a sessionjuin 26 11:37:21 leonard audit[4348]: USER_START pid=4348 uid=0 auid=4294967295 ses=4294967295 subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 msg='op=PAM:session_open grantors=pam_keyinit,pam_limits,juin 26 11:37:21 leonard sudo[4348]: pam_unix(sudo:session): session opened for user root by (uid=0)juin 26 11:38:06 leonard bluetoothd[932]: No cache for 08:DF:1F:DB:A7:8AUnfortunately, I don't understand the output. Any idea or help is welcome. I am pretty lost.The bluetooth receiver I use is a USB dongle from CSL-Computer. Bluetoothctl version is 5.40. I am running kernel 4.5.7-300.fc24.x86_64.Below are the features supported by my bluetooth adapter:hciconfig -a hci0 featureshci0: Type: BR/EDR Bus: USB BD Address: 00:1A:7D:DA:71:05 ACL MTU: 310:10 SCO MTU: 64:8 Features page 0: 0xff 0xff 0x8f 0xfe 0xdb 0xff 0x5b 0x87 <3-slot packets> <5-slot packets> <encryption> <slot offset> <timing accuracy> <role switch> <hold mode> <sniff mode> <park state> <RSSI> <channel quality> <SCO link> <HV2 packets> <HV3 packets> <u-law log> <A-law log> <CVSD> <paging scheme> <power control> <transparent SCO> <broadcast encrypt> <EDR ACL 2 Mbps> <EDR ACL 3 Mbps> <enhanced iscan> <interlaced iscan> <interlaced pscan> <inquiry with RSSI> <extended SCO> <EV4 packets> <EV5 packets> <AFH cap. slave> <AFH class. slave> <LE support> <3-slot EDR ACL> <5-slot EDR ACL> <sniff subrating> <pause encryption> <AFH cap. master> <AFH class. master> <EDR eSCO 2 Mbps> <EDR eSCO 3 Mbps> <3-slot EDR eSCO> <extended inquiry> <LE and BR/EDR> <simple pairing> <encapsulated PDU> <non-flush flag> <LSTO> <inquiry TX power> <EPC> <extended features> Features page 1: 0x03 0x00 0x00 0x00 0x00 0x00 0x00 0x00The pairing works well with EDIFIER Luna Eclipse speakers. I suspect the issue is really related to the headset I am trying to configure.
Pairing Bose QC 35 over Bluetooth on Fedora
fedora;pulseaudio;bluetooth;bluez
I have these headphones as well, along with a handy laptop running Fedora 24. After chatting with one of the Bluez developers on IRC, I have things working. Below is what I've found. (Note that I know very little about Bluetooth so I may be using incorrect terminology for some of this.)The headphones support (or at least say they support) bluetooth LE but don't support LE for pairing. Bluez does not yet support this and has no way to set the supported BT mode except statically in the configuration file. You can use the headphones over regular bluetooth just fine, though. This happens to be the reason Bluez 4 works; it doesn't really support LE.So, create /etc/bluetooth/main.conf. Fedora 24 doesn't come with this file so either fetch a copy from Upstream, find the line containing#ControllerMode = dualand change it to:ControllerMode = bredror create a new file containing just:[General]ControllerMode = bredrThen restart bluetooth and pair. (I did this manually via bluetoothctl, but just using the bluetooth manager should work.)Now, this got things working for me, though if you don't force pulseaudio to use the A2DP-Sink protocol, the headphones will announce that you have an incoming call for some reason. However, my mouse requires Bluetooth LE, so I went in and removed the ControllerMode line. And... the headphones still work, as well as the mouse. I guess that once they are paired everything is OK.
_cs.43472
consider integers represented as base 2 (strings). define a relation called n-msb matching that is true when the 1st n msbs (MSB is most significant bits) match (of two integers). what is a pragmatic way of searching/ computing the following?given n2, find x, n such that n3x is many msb matching (with n2).note am not necessarily looking for efficient. a nice/ ideal answer would also analyze the complexity (ie # of possible solutions, hardness of finding etc)background: naturally arises in Collatz conjecture study.
pragmatic way to compute/ search/ match MSBs operation
algorithms;time complexity;arithmetic
null
_cs.65535
I am trying to solve the following:Given a set $S_0$, find min $|S|$ where $S_0 \subseteq S$ subject to:$\forall s \in S$ $\exists$ $s_a, s_b \in S $ $|$ $ ( s_a \neq s, s_b\neq s ) \land ( s = s_a + s_b \lor s = 1 \lor s=2 ) $Or in english, forall s in S there exists sa, sb in S such that sa != s, sb != s AND ( s = sa + sb OR s = 1 OR s = 2 )For example if $S_0 = \{ 7, 9, 13, 22 \}$then the solution is $S = \{ 1, 2, 3, 4, 7, 9, 13, 22 \}$ as1 -> is 1 so allowed2 -> is 2 so allowed3 = 1 + 24 = 1 + 37 = 3 + 49 = 7 + 213 = 9 + 422 = 9 + 13|S| = 8$|S_0|$ is not particularly large but the numbers in $S_0$ can be very very large such that expressing all numbers possible is infeasible.I have tried an ILP and ran out of memory expressing the binary variables for each number in the set.My current approach ( which gives a pretty bad solution ) is pick the lowest number that is violated, heuristically pick two numbers and put them in the set. Repeat until all numbers meet constraints.An approximate solution is fine. Anyone have any ideas?
Growing a set given constraints
optimization;discrete mathematics;set cover
I suggest you formulate this as an instance of integer linear programming (ILP). Let $m$ be the largest number in $S_0$. For each $i$ such that $1 \le i \le m$, introduce the zero-or-one variable $x_i$, with the intended meaning that $x_i=1$ means that $i \in S$ and $x_i=0$ means that $i \notin S$.Now your constraints can be readily converted into linear inequalities: e.g., for each $s$ such that $2<s \le m$, we obtain that $x_s=1$ implies $\lor_{s_a,s_b} (x_{s_a}=1 \land x_{s_b}=1)$, where the disjunction is taken over all $s_a,s_b$ such that $1 \le s_a < s$ and $1 \le s_b < s$. This can be converted into a linear inequality; see Express boolean logic operations in zero-one integer linear programming (ILP). Also, for each $i \in S_0$, we add the requirement $x_i=1$. Finally, we minimize $\sum_i x_i$. Feeding this to an off-the-shelf ILP solver should yield a solution.This should find the exact optimal solution, as long as the largest number in $S_0$ is not too large. However, the running time is potentially exponential in $m$, the largest number in $S_0$. I don't know if there is a polynomial-time solution.(You could also formulate it as an instance of SAT instead of ILP. This will require applying the Tseitin transform to convert the implication/disjunction into CNF, and it will require constructing an adder-circuit to add the requirement that the size of $S$ is at most $k$ and then doing binary search over $k$. Then, you could feed it to an off-the-shelf SAT solver. I have no idea whether this will work better than the ILP approach.)
_cogsci.10933
I'm looking for the name of the cognitive bias that describes the following phenomenon: Person A asks person B to evaluate and give feedback on a certain topic (a student, a manuscript etc), casually warning person B that the student/manuscript is not very good and so the task will not be particularly pleasant. Person B then tries to objectively do the evaluation, however inadvertently and unavoidably gravitates towards person A's premise, and subsequently has a hard time deciding whether the fact that he too now thinks the student/manuscript is poor is in fact his own opinion or just a regurgitation/confirmation of what person A told him.First it seemed to me that this is an instance of the hindsight (knew it all along) bias, but I don't think it is, as there the extra (bias inducing) information comes after person A's appraisal, rather than before as is the case in the scenario I describe.Any other cognitive biases this could be an instance of?
What cognitive bias is it when an (ideally objective) evaluation is influenced by the prior opinion of another person?
terminology;bias
It's an example of the confirmation bias:Confirmation bias (...) is the tendency to search for, interpret, favor, and recall information in a way that confirms one's beliefs or hypotheses.Research has shown that people have a strong tendency to engage in a positive test strategy when investigating a hypothesis (see e.g., Klayman & Ha, 1978). That is, when testing an expectation (such as in your example) they tend to search for confirming, rather than disconfirming evidence. This tendency then results in the kind of confirmation bias you are describing in your example.ReferencesKlayman, J., & Ha, Y. (1987). Confirmation, disconfirmation, and information in hypothesis testing. Psychological Review, 94, 211228. doi:10.1037/0033-295X.94.2.211
_webapps.69263
I've been using Trello for quite a while and love the project-/board-based approach to task management. However, my lifestyle has made it necessary to make use of context-based task filtering so that when I find time at home after work to do some things I can quickly see what I have that needs to be done at home, for example.I thought I could use labels for this purpose, which seemed to work okay searching across multiple boards, but since some of my boards are used by teams that actually make use of labels themselves, that didn't seem like a good solution; there was label pollution, if you will. I was thinking I could also just come up with my own keywords to put in the description, like context--home, context--work. Whatever the solution is, it needs to work at least as well on Android as it does on a desktop browser. I guess that rules out a search-based solution though as Android search isn't really implemented yet.Any other ideas? Maybe integration with another Android app?
How can I use Trello with contexts, as with GTD?
trello
null
_datascience.3742
I've been working in SAS for a few years but as my time as a student with a no-cost-to-me license comes to an end, I want to learn R.Is it possible to transpose a data set so that all the observations for a single ID are on the same line? (I have 2-8 observations per unique individual but they are currently arranged vertically rather than horizontally.) In SAS, I had been using PROC SQL and PROC TRANSPOSE depending on my analysis aims.Example:ID date timeframe fruit_amt veg_amt <br/> 4352 05/23/2013 before 0.25 0.75 <br/> 5002 05/24/2014 after 0.06 0.25 <br/> 4352 04/16/2014 after 0 0 <br/> 4352 05/23/2013 after 0.06 0.25 <br/> 5002 05/24/2014 before 0.75 0.25 <br/>Desired:ID B_fr05/23/2013 B_veg05/23/2013 A_fr05/23/2013 A_veg05/23/2013 B_fr05/24/2014 B_veg05/24/2014 (etc) <br/>4352 0.25 0.75 0.06 0.25 . . <br/>5002 . . . . 0.75 0.25 <br/>
Data transposition code in R
data mining;r;dataset;beginner
You can use the reshape2 package for this task.First, transform the data to the long format with melt:library(reshape2)dat_m <- melt(dat, measure.vars = c(fruit_amt, veg_amt))where dat is the name of your data frame.Second, cast to the wide format:dcast(dat_m, ID ~ timeframe + variable + date)The result: ID after_fruit_amt_04/16/2014 after_fruit_amt_05/23/2013 after_fruit_amt_05/24/2014 after_veg_amt_04/16/20141 4352 0 0.06 NA 02 5002 NA NA 0.06 NA after_veg_amt_05/23/2013 after_veg_amt_05/24/2014 before_fruit_amt_05/23/2013 before_fruit_amt_05/24/20141 0.25 NA 0.25 NA2 NA 0.25 NA 0.75 before_veg_amt_05/23/2013 before_veg_amt_05/24/20141 0.75 NA2 NA 0.25>
_softwareengineering.337018
So at a high level my use case is as follows - I periodically (every 24 hours) get a very large file (size can vary from MBs to 10s of GBs) which I need to process within 24 hours. The processing involves reading a record, apply some Business Logic and updating a database with the record.Current solution is a single threaded version which initially reads the entire file in memory, that is, it reads each line and constructs a POJO. So essentially it creates a big ListIt then iterates on the List and applies business logic on each Pojo and saves them in databaseThis works for small files with less than 10 million records. But as the systems are scaling we are getting more load, i.e. larger files (with >100 million records occasionally). In this scenario we see timeouts, that is we are unable to process the entire file within 24 hoursSo I am planning to add some concurrency here.A simple solution would be-Read entire file in memory (create POJOs for each record, as we are doing currently) or read each record one by one and create POJOSpawn threads to concurrently process these POJOs.This solution seems simple, the only downside I see is that the file parsing might take time since it is single threaded (RAM is not a concern, I use a quite big EC2 instance).Another solution would be to - Somehow break the file into multiple sub-filesProcess each file in parallelThis seems slightly complicated since I would have to break the file up into multiple smaller files.Any inputs on suggestions here on the approaches would be welcomed.
Java - Processing a large file concurrently
java;concurrency;file handling
The most likely efficient way to do this is:Have a single thread that reads the input file. Harddisks are at their fastest when reading sequentially.Do not read it into memory all at once! That is a huge waste of memory which could be used much better to speed the processing!Instead, have this single thread read a bundle of entries (maybe 100, maybe 1000, this is a tuning parameter) at once and submit them to a thread to process. If each line represents a record, the reading thread can defer all the parsing (other than looking for newlines) to the processing threads. But even if not, it is very unlikely that the parsing of records is your bottleneck. Do the thread handling through a fixed size thread pool, choose the size to be the number of CPU cores on the machine, or maybe a bit more.If your database is an SQL database, make sure the individual threads access the database through a connection pool and do all their DB updates for one bundle of entries in a single transaction and using batch inserts.You might want to use Spring Batch for this, as it will guide you towards doing the right thing. But it is somewhat overengineered and hard to use.Keep in mind that all of this might still be futile if the DB becomes your bottleneck, which it very easily can be - SQL databases are notoriously bad at dealing with concurrent updates, and it might require quite a but of finetuning to avoid lock contention and deadlocks.
_unix.158504
When reading answers to this post, I wonder if we can make the programs we often used on our computers portable (in the Windows sense), so that we can make a copy of them on our flash drive, so that we don't have to worry if we don't have access to the programs we like on other computers? Is it possible to make such portable installations?
Installing programs on a flash drive so that they can be executed in place
software installation
null
_webmaster.72084
There are a few things that come into this question that's based around Google+ reviews (formerly Google places).I have always been advised to get as many reviews as possible on my Google+ business page in order to improve rankings. The idea is that the more positive reviews you have, the higher you will be shown in the results. How important does Google consider these reviews when ranking local businesses?The next part of this question is based on the likelihood of Google using these in the future. I have already noticed the change from places to Google+ and recently I have noticed that when I search the exact business name, the details on the right hand side (small map, photos, opening hours etc.) have seem to had been removed. Does this suggest a possible change?The last part of this question is based around reviews as a bigger picture. Should I look to gain reviews with just Google, or would I be better off using several review sites (directory listings etc. all see to have reviews now).I have always been faced with a difficult question. I have the opportunity to send my clients somewhere to leave a review, so where should I send them? There are so many sites now that offer reviews.
How important are Google+ reviews when ranking a website?
google;google search;ranking
null
_cs.62647
Before I ask my doubt I would like to state that problem which led me to my doubt. It can also serve as a good example scenario.A $20\ Kbps$ satellite link has a propagation delay of $400\ ms$. The transmitter employs the Sliding Window protocol scheme with Window Size set to $10$. Assuming that each frame is $100$ bytes long. What is the link utilization of transmission medium.From the question we can make out that Window Size $(WS)$ is $10$, transmission time $(T_t)$ of a frame is $40\ ms$ , and propogation time $(T_p)$ is $400\ ms$.Now, the solution that book proposes simply states that Link Utilization $(LU)$ for sliding window protocol can be calculated as$$LU = \frac{WS*T_t}{T_t + 2*T_p}$$That's where I'm facing the problem. From what I have learned about Link utilizationIt is the fraction of total time the host was busy in transmission of data. In other words, it is the ratio of total transmission time over Total Time involved in transmission.Now if I try to fit the formula proposed in book with what I have learned, the total time involved in transmission is $T_t+2*T_p$. But that is only the total transmission time of one single packet over the medium. Why isn't it is $WS*T_t + 2*T_p$, since we are sending $WS$ packets without wating for acknowledgement.The only thing I could figure out after thinking a lot about my doubt is that I am probably going wrong because of my incomplete understanding of what Link Utilization means.I will appriciate any kind of help.
Link utilization of sliding window protocol
computer networks;communication protocols
I had the same doubt and was getting nowhere close to grasp the concept. After banging my head for a few days I now think I have understood the basic concept. We define utilization as the total time used by the link to send good data divided by the total time link is engaged. In stop and wait, we send one frame and do nothing good unless we receive an acknowledgment this presents a low utilization.Total time link is used is :ttransmission + 2* tproptotal time link is used for sending good data : ttransmissionConsider the sliding window now we send one frame and instead of waiting for the acknowledgment we continue transferring frames until the acknowledgment arrives. The total time for the link remains the same however, we have increased the good time to:WindowSize * ttransmission.Why isn't the total time : WSxttransmission + 2* tprop ?We have sent all the additional frames between the time frame of sending the first frame and receiving the first acknowledgment.This time frame is equal to :ttransmission + 2* tprop and not WSxttransmission + 2* tpropWe have just increased the fraction of this total time from :ttransmission. to WindowSize * ttransmission.Here is a Linkconsider the figure 7.11 in the same. It beautifully illustrates the concept. I wasn't sure of posting the picture due to copyright issues.Cheers!
_softwareengineering.322409
I've been asked to write a mobile app for a business I have connections with, and I've been trying to decide what I should charge. One thing I came up with was to research what other companies would charge for such a service, but all the ones that have the 'online estimators' are really over-the-top expensive and the companies obviously don't cater for the same clientele as I do.I found a company that does, and they offer free quotes, however I'm wondering if it would be unethical to ask them for a quote in this scenario given that I do not intend to use their services, therefore effectively wasting their time. Is this unethical, or otherwise frowned upon?
Is it unethical to figure out how much to charge by asking for a quote from another company?
ethics;app;development
Yes its unethical, you are wasting their time.But its also impractical.You can only do it once or twice before they stop talking to you.The price they offer will reflect their business model and might notwork for you. Ie they might sell stuff cheap to drag customers intoanother productThe price they offer you wont be the same as the one they offer yourpotential customer. Even if the service is very comoditised theprice will reflect how much they think they can get out of thecustomer.Of course you have to research your market, but you are better off being fairly honest about it. Attend some events, ask people what they think of the market at the moment, buy them a drink, is everyone buying cheap stuff? Are people paying lots for custom things etc how much did they buy their last X for? do they think it was good value? EtcIn your particular case though it should be fairly easy. Estimate how long it will take and then check out the job boards to see how much it would cost to get a contractor with your skill set for that amount of time. Add a bit on if you are assuming any risk
_softwareengineering.274456
There is a lot I don't like about PHP, but one thing I love is multi-line strings:$query = <<<EOTselect field1 ,field2 ,field3from tableNamewhere field1 = 123EOT;What's cool about this, is that I can just copy SQL, that I've hand formatted (to my liking) from a querying tool (like dbeaver), and paste it (with formatting and all) directly into a php script, without worry about how line-breaks might corrupt the script.There's a lot I love about Javascript, but there doesn't seem to be a reliable equivalent that would allow you to copy and paste a pre-formatted SQL statement into a variable-value (with this same ease -- and preserving the formatting).I'm currently working on some small node.js projects and I'm very much missing this php feature.The only think I can think to do, is to put my queries into a plain text file and import the formatted query from a file into the variable value. Then, later, when I need to modify the query, I can copy and paste to that file (pre-formatted) and then the script will just load my modifications next run.However, sometimes I need certain parts of the query to be dynamical generated. In PHP, I could put variables into the multi-line string for such requirements. With this separate file idea (in Javascript), it seems more complicated; I'd have to make custom place-holders in the plain text file that are to be replace by the main script later. That seems like I might be reinventing a wheel that is already made. So that's why I'm posting here for advice.I've read other post that have hacks for doing this type of thing in-script, but each solution doesn't match the ease and reliability of php's built-in support for such requirements.
Preserving Pre-formatted Multi-Line Strings in Node.js Scripts
php;javascript;sql;node.js
null
_softwareengineering.66864
If you were putting some work of yours online (say, a research project still in development or something alike) and it had to be made available to the public, but you wished that if someone uses it, he has to acknowledge the original author (i.e. you don't want anyone pushing your research as their own) what would be a good licence to use?In other words, you wish to protect your own work which, were it not for some rules, would never been actually made public.
Choosing a restrictive licence for open source work
licensing
null
_unix.156329
In this answer user suggests that Normally, Uninterruptible sleep should not last long, but as under windows, broken drivers or broken userpace programs (vfork without exec) can end up sleeping in D forever.How can userspace program really lock up in D on non-buggy kernel? I though it's sort of little vulnerability for usermode to be able to stuck in D on purpose...
How can process doing vfork without exec end up in a long uninterruptible sleep?
linux;process;vfork
When a process calls vfork, the parent remains in state D as long as the child hasn't executed _exit or execve (the only two authorized functions, together with execve's relatives like execvp, etc.). The parent is still executing the vfork call, so it's in state D.If the child does something like this (which is stupid, but valid), the parent will remain in state D indefinitely, while the child will remain in state R indefinitely.if (!vfork()) while (1) {}
_unix.342511
I have an old computer which I'd very much like to be able to use with my modern Gmail and iCloud email accounts. The old computer can do IMAP, POP and SMTP - but it can't do SSL (hence the need for an intermediary). I can hear the objections already - if you have a new computer, why would you want to use your old one? I'm afraid to say that the answer is 'I just do!' One of my newer computers, the one that's on all the time, is a Raspberry Pi running Raspbian (a Debian Linux fork). So my question is, is there any software available which can be set up easily and which will act as a mail server for my old computer? It should handle the secure sign in to my email accounts, and then serve that email (Preferably IMAP, but POP is okay too) so that my old computer can retrieve it.Conversely, when email is sent from my old computer the software should then forward it on to iCloud or Gmail (or whatever).I've tried using stunnel, but I can't get it to work for me. Any suggestions will be eagerly received - and I'm sure that I'm not the only person who'd be interested!
Mail Server for Linux which can forward Gmail
email;raspbian;ssl
null
_softwareengineering.76214
I have a turbogears app that I am bringing live that uses a postgresql DB on the back end. From a performance issue am I better off having the DB and app on separate server or on the same server? If on the same server and I better off having the DB on a separate physical drive?
Webserver / DB / Application - Best way to setup the system for performance
web applications;hardware
For the vast majority of apps, its really not going to matter much where you put the database because the web server isnt likely to ever be pushed to the point where its noticably impacting database performance (or the other way around).I would recommend keeping it simple and keeping the db on the webserver unless you already know you are going to face a lot of traffic. You can always move the db to a second server (or start replicating to an additional server) as needed.One particular arrangement I use is to have the main db on the webserver, but to have a replicated copy on a second server. Reporting and similar intensive/not-real-time queries are performed against the replicated copy, but everything else is done against the main db. This prevents any 'runaway' queries done in reports from impacting the main server. But again, this really on helps when there's enough traffic in the first place to make it an issue.
_unix.126269
I am trying to setup my server so that I can restart Apache as userx without having to enter a sudo password. However when I logon as userx and run sudo /usr/sbin/service apache2 restart it asks me for a password. What have I got wrong?Below is the content of my sudoers file.## This file MUST be edited with the 'visudo' command as root.## Please consider adding local content in /etc/sudoers.d/ instead of# directly modifying this file.## See the man page for details on how to write a sudoers file.#Defaults env_resetDefaults secure_path=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin# Host alias specification# User alias specificationuserx ALL=(root) NOPASSWD: /usr/sbin/service apache2 restart# Cmnd alias specification# User privilege specificationroot ALL=(ALL:ALL) ALL# Members of the admin group may gain root privileges%admin ALL=(ALL) ALL# Allow members of group sudo to execute any command%sudo ALL=(ALL:ALL) ALL# See sudoers(5) for more information on #include directives:#includedir /etc/sudoers.dLet me add back in my edit where I point out what the answer was and explain where I found the solution in case other people stubmle across this.Turns out that userx was a member of the admin group and the %admin group entry was overwriting the settings. Moving the userx line below the %admin line solved the problem.This answer also helped How to run a specific program as root without a password prompt?
Passwordless sudo not working
sudo
null
_webapps.23463
When using wiki syntax, if I put an asterisk (*) at the beginning of a line, it gets transformed into a unordered list. How is it possible to have the asterisk to remain as it is when at the beginning of a line?Example :*Hello world, this sentence is not in an unordered list.
How do I write an asterisk at the beginning of a line in wiki syntax without transforming into a list item?
mediawiki;markdown;syntax
I think a better method is to use the 'nowiki' tag. This is generic and does not rely on knowing character codes, plus your text is more readable. <nowiki>*</nowiki> will display as an asterisk at the start of the sentence.http://www.mediawiki.org/wiki/Help:FormattingNow you can display any special characters you like!
_unix.332832
i got this snippet from a shell script , it run perfectly in Solaris environment grep -h '??.*??' $1/{CT,{MYDIR{85,97}}{,_E}}/R*txtbut when i try to run shell script in ubuntu , it gives following errorgrep: ./{MYDIR85}/R*txt: No such file or directorygrep: ./{MYDIR85}_E/R*txt: No such file or directoryafter little bit of editing it run properly, i removed curly braces of MYDIR grep -h '??.*??' $1/{CT,MYDIR{85,97} {,_E}} /R*txtI want to know what is the problem , is it command incompatibility between linux and solaris ?Note -i have three directory MYDIR85 , MYDIR97 and CT - in ubuntu , shell is /bin/bash - in solaris i don't know the shell type,but the first line of shell script is #!/bin/bash
command difference in Solaris and linux shell
ubuntu;solaris
null