id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_unix.310105 | I access my machine via ssh with the -Y parameter. I have a local X server installed (XQuartz for Mac)The remote server is a barebones command line only box.What is the bare minimum I would need to install on the remote linux box to be able to run a GUI application?As an example of the GUI apps I want to run, I would like to run Oracle SQLDeveloper and Eclipse. Potentially Firefox too.I don't need a desktop, or window manager, or any associated tools, if I can help it. | What is the bare minimum I should install on a headless Red Hat (or CentOS), or Ubuntu, box to be able run GUI programs through X11 via SSH | linux;x11;gui | For your use-case you only need to install xauth (and its dependencies) on the distant machine, and the applications you want to run along with their dependencies. For example, for Eclipse you should only need a non-headless JDK and Eclipse itself.You don't need a desktop environment or even a window manager, you'll end up using their equivalents on your local system (the machine running the X server). |
_softwareengineering.262954 | This is what most of my database-related library code looks like:lib.php<?php$dbh = new PDO(...);function doSomeDatabaseThing() { global $dbh; return $dbh->doStuff();}function doSomeOtherThing() { global $dbh; return $dbh->doSomeOtherStuff();}index.php<html> <head>...</head> <body> <?php require_once('lib.php'); echo doSomeDatabaseThing(); ?> </body></html>I keep reading that globals in PHP are generally bad. Of course, this doesn't mean that I should never use globals, but it seems wrong to repeatedly use this pattern in almost all database code I write.So, how should I do this without globals? I could try something likelib.php$dbh = new PDO(...);function doSomeDatabaseThing($dbh) { ... }index.phpdoSomeDatebaseThing($dbh);but it looks ugly to have to write ($dbh) every single time I call a database function.Is there a better way to solve this? | How can I avoid the global $dbh anti-pattern? | php;anti patterns;globals | Object-oriented design + Dependency Injection (DI)You should consider using object-oriented design together with Dependency Injection container. I recommend Symfony specifically because it has a great DI container component.Instead of having a bunch of DB-related functions, consider grouping them into classes which deal with particular types of domain objects, like so:// repository interfaceinterface Repository{ public function findById($id);}// specific repository dealing with user objectsclass UserRepository implements Repository{ private $dbh; function __construct(PDO $dbh) { $this->dbh = $dbh; } public function findById($id) { // just an example, should use at least prepared statement here $userRow = $this->dbh->query(...); // ... return $user; }}Instead of having global $dbh you now inject it into constructor of SomethingRepository as a dependency, hence the name of the pattern. That is called constructor injection, and there are other types.Injection is basically instantiating all the dependencies and passing them into constructors/setters. That's what DI containers do. You provide a configuration describing how objects depend on each other, framework builds them.Why is global $x considered anti-pattern?Name of $x can be a subject to change => happy time renamingAny object using $x can overwrite it => happy time debuggingCan cause security issues in case you have register_globals enabled or if you including third-party source files => happy time dealing with hacker attacksOf course, this doesn't mean that I should never use globalsThat means you should avoid using global $x construct at all costs. You can totally build any application without it, unless you stuck with some legacy code or prehistoric version of PHP. |
_cseducators.473 | I would like my students to get the most out of the course by experiencing an agile development structure in their projects. Currently I give 5 assignments, each building on the previous one and adding to the complexity of the final product. Although this is far from letting students experience real agile development, it is a first step. How can I incorporate an agile development methodology backbone to the course, letting students experience it first-hand? The courses are taught in Python (CS1) and Java (CS2) and this is an Applied Information Technology program. | How can I incorporate agile development into CS1/CS2 courses? | curriculum design;problem structure;agile development | null |
_cs.63550 | In programming language theory, which concept means that a name can refer to values of different types at different points of execution of a program,dynamic typing,implicit i.e. inferred typing, defined as opposed to explicit i.e. manifest typing,something else?Let me explain the above question.My question comes from reading following two sources.From Wikipedia https://en.wikipedia.org/wiki/Programming_language#Static_versus_dynamic_typingStatically typed languages can be either manifestly typed or type-inferred. In the first case, the programmer must explicitly write types at certain textual positions (for example, at variable declarations). In the second case, the compiler infers the types of expressions and declarations based on context. Most mainstream statically typed languages, such as C++, C# and Java, are manifestly typed. Complete type inference has traditionally been associated with less mainstream languages, such as Haskell and ML. However, many manifestly typed languages support partial type inference; for example, Java and C# both infer types in certain limited cases.[48] Additionally, some programming languages allow for some types to be automatically converted to other types; for example, an int can be used where the program expects a float.Dynamic typing, also called latent typing, determines the type-safety of operations at run time; in other words, types are associated with run-time values rather than textual expressions.[47] As with type-inferred languages, dynamically typed languages do not require the programmer to write explicit type annotations on expressions. Among other things, this may permit a single variable to refer to values of different types at different points in the program execution. However, type errors cannot be automatically detected until a piece of code is actually executed, potentially making debugging more difficult. Lisp, Smalltalk, Perl, Python, JavaScript, and Ruby are dynamically typed.In this may permit a single variable to refer to values of different types at different points in the program execution, isit correct that this means implicit typing?So does it imply that it is implicit typing instead of dynamictyping which may permit a single variable to refer to values ofdifferent types at different points in the program execution?From https://pythonconquerstheuniverse.wordpress.com/2009/10/03/static-vs-dynamic-typing-of-programming-languages/In a dynamically typed language, every variable name is (unless it is null) bound only to an object.Names are bound to objects at execution time by means of assignment statements, and it is possible to bind a name to objects of different types during the execution of the program.Does it imply that it is dynamic typing which may permit a single variable to refer to values of different types atdifferent points in the program execution?In order to answer the above questions, some counterexameples mayhelp. Specifically,Can you give an example when a programming language is dynamic typing, but a name is not allowed to refer to values of differenttypes at different points of execution of a program?Can you give an example when a programming language is implicit typing, but a name is not allowed to refer to values of differenttypes at different points of execution of a program? | What concept is for a name referring to different types at different points in execution? | programming languages;typing | A couple of things would fit the bill: polymorphism and dynamic typing.PolymorphismSay you have a polymorphic function, first:first : (A, B) -> Afirst (a, b) = aAt runtime, the variables a and b may refer to values of different types on different invocations. e.g. first (1, 'a') and first (Fred, 42). Polymorphic means many forms/types.Dynamic typingDynamically typed languages also have variables that refer to values of different types at runtime. This happens for functions like first above but also in other situations like:$ python>>> a = hi>>> a = 42Type InferenceYou also mentioned implicit or inferred typing for statically typed languages. Type inference happens at compile time. If the type inference process decides that a variable is of a monomorphic type (like Int), then that variable will always refer to a value of type Int. Monomorphic simply means a single form/type. The type inferencer can also decide that a function has polymorphic arguments, then it will be as first above. I hope you can see that type inference is a red herring when it comes to the main thrust of your question. |
_unix.296743 | Change Title to: I have a Canon MG3500 printer which SEEMS incompatible with Ubuntu 15.04 and LinuxMint-17, Anybody have workaround suggestions.------------< title change above >------------I called Canon, and they don't seem to be interested in coming up with driver which could be used with LinuxThe Canon MG3500 had everything I wanted, except the problems. Right now I don't print enough to justify buying a new printer. What really irks me is all troubleshooting issues are addressed through the installed software. Hence, the following paragraph.One thought I have is installing Wine, and setting up my computer using the Windos install disk--somehow though, this seems like a pretty stupid idea. Comments gratefully accepted.joePS: I'm not sure if these changes need to be approved before they are posted--especially because I suggest a changed title.Or does this post get deleted, and the approved version posted as new. I did get excellent replies to the original post--FWIW. | ubuntu 15.04 user experience with printer problems and suggestions for better printers | ubuntu;linux mint | null |
_unix.28972 | I understand that source based distributions like Gentoo or Slackware do not need *-dev versions of programs. They include the source code as well as header files for compiling everything locally.But I never saw *-dev packages in Arch Linux, although it is package based. I ran across lots of *-dev packages in other distributions. | Why are there no -dev packages in Arch Linux? | arch linux;package management;compiling;source | The -dev packages usually contain header-files, examples, documentation and such, which are not needed to just running the program (or use a library as a dependency). They are left out to save space.ArchLinux usually just ships these files with the package itself. This costs a bit more disk space for the installation but reduces the number packages you have to manage. |
_unix.197663 | I have searched online for 10 hours now and tried various codes, but still need help. I am attempting to merge three files using 'paste' and 'awk'. However, the columns are not adjusting to the longest string of characters. All files are formatted in the same manner as below. F gge0001x D 12-30-2006 T 14:15:20 S a69 B 15.8M gge06001P 30.1Below is my faulty code.$ paste <(awk '{print $1}' lineid) <(awk '{printf(%-13.10s\n, $1)}' gge0001x) <(awk '{printf(%-13.10s\n, $1)}' gge0001y) <(awk '{printf(%-13.10s\n, $1)}' gge0001z)This code results in misaligned columns as pictured below.I would greatly appreciate your help.Input File 1F D T S B M P Q R U X A G H O C K W L Input File 2gge0006x12-30-200614:05:23a6915.4gge0600130.8 19.2 1006.2 1012.7 36.238.994 107.71 8.411 37.084 7.537 28.198 212.52 68.1Input File 3gge0006y12-30-2006 14:05:55a6915.3gge0600130.6 21.1 1006.6 1014.6 36.138.994 107.71 8.433 36.705 7.621 27.623 210.51 68 Input File 4gge0006z12-30-200614:06:28a6915.7gge0600130.3 23.5 1008 1014.1 36.638.994 107.71 8.434 36.508 7.546 27.574 208.08 67.6 Results for paste file1 file2 file3 file4 | column -t | Format Column Width with Printf | bash;awk;printf;paste | Your input files have DOS \r\n line endings. Remove the carriage returns with the dos2unix command or with sed -i 's/\r$//' |
_unix.117233 | Does anyone know of a program (or even bash script) that can take photos from various folders and then consolidate them into one place and organise them into a directory structure by date in the way that Shotwell and simliar can if using a GUI?I have a headless server that I intend to auto sync family phones (all android) photographs to. The idea would be that newly uploaded photos go into a holding directory and then a script runs on cron to import these into the main picture repository.I'm currently looking to build this around Owncloud but the android app is very basic and just syncs pictures into the root of the Owncloud folder.I already have an archive of photos that spans about 10 years and is nicely organsied into folder by the various succession of Linux photo management apps that I have used.I do suspect that a nice bash script would suffice but I'm looking for a decent off the shelf solution first. If I have to write my own bash script then so be it, any tips you have would be appreciated. | Command Line Photo Organiser Like Shotwell but to run on headless server | linux;bash;command line;images | null |
_unix.307619 | Which open source software can calculate crystal diffraction diagrams for neutron and x-ray diffraction?The software should finally create a picture like this by simulation:https://commons.wikimedia.org/wiki/Category:Powder_diffraction#/media/File:Getit4.jpg | Which open source software can calculate crystal diffraction diagrams? | linux;software rec | Try Fox.From the description:FOX is a program for the ab initio structure determination from powder diffraction (neutrons, X-Ray).There are several others for xtallography processing and visualisation, that's just the first I could find.I highly recommend that you also look at the Debian Science Blend - lists of science and research related packages either already packaged for debian, in progress towards being packaged, and some not packaged for debian at all. The Chemistry and Nanoscale Physics sections will probably be of most interest to you, but there's also a lot of useful software in other sections.Other distros will also have similar science package pages which will be worth looking at. Scientific Linux in particular. |
_webapps.16797 | When using Skype as a mobile application, if I'm just logged in but not using it, does it consume data (i.e. Kb) during this log in? | Skype for mobile applications | mobile;skype for web | null |
_unix.150004 | When sending a text file to the printer from the command line (by, e.g., lpr -P printer-name file.txt), is it possible to specify that inverted colors be used by the printer (i.e., white text on black background)? | lpr with reverse video | printing;lpr | null |
_scicomp.19207 | When reading about discontinuous Galerkin methods one finds the argument that these methods allow higher-order accuracy while maintaining a compact stencil (a cell only communicates with its direct neighbors) and that this is beneficial for parallel computations. I can understand why a wider stencil would be bad for parallelization with domain decomposition: it would require more than one layer of overlap and thereby increase the communication cost. But how big is this penalty in practice? | communication penalty when using wide stencils in parallel computations | parallel computing;discretization;cluster computing | null |
_cs.16391 | Consider the following problem:There are $n$ points in the plane.Starting from one of them I want to visit each of them once (except the starting node which has to be visited twice) but in a way that minimizes the cost of the total path.The weight of each edge changes depending on the path followed.For example imagine $n=3$: $A$, $B$, $C$ and we start at $A$. The weight of the edge $xy$ is $Sd_{xy}$, where $d_{xy}$ is the distance between the points $x$ and $y$ and $S$ is a given constant)If I pick the edge $A\to B$, the weight of the edge $B\to A$ is now$(S-s_B)d_{AB}$ because $B$ changes $S$ by a constant amount $s_B$. Similarly if I pick the edge $A\to C$, the weight of the edge $B\to C$ is now$(S-s_C)d_{AC}$ because visiting $C$ changes $S$ by a constant amount $s_C$. Developing the $n=3$ case, imagine S=11, $d_{AB}=5,d_{AC}=3,d_{BC}=4$ and $s_{A}=2,s_{B}=5,s_{C}=4$.Then there are 4 possible paths:A->B->C->A with cost $11*5+(11-5)*4+(11-5-4)*3$(we stop once we reach A because 11-5-4-2=0)A->B->A->C with cost $11*5+(11-5)*5+(11-4-2)*3$A->C->B->A with cost $11*3+(11-4)*4+(11-4-5)*5$A->C->A->B with cost $11*3+(11-4)*3+(11-4-2)*5$For $n=4$ there will be 3*3!=18 possible paths and so on.I know that $s_A+s_B+s_C=S$. This generalizes for $n$ points. What is an efficient algorithm for finding the minimum cost path? | Fast algorithm for finding a minimum cost path through points in the plane | dynamic programming;greedy algorithms | null |
_codereview.20281 | I have been working on a php driven template engine. This is fairly light weight, and fast from all of my testing, but I was hoping to get some feed back on it. First I would like to show you an example usages before I show the actual library. For full documentation and more examples: http://plater.phpsnips.com/This first part is a example users homepagetemplates/user.tpl<!DOCTYPE html><html> <head> <title>User Home Page</title> </head> <body> <h2>Welcome, $session.first.ucfirst();</h2> <p> Here is where you will find the last 5 images that you have uploaded. </p> $each(myimages): <div style=border: solid 1px activeborder;margin-bottom: 5px;> <p> <img src=images/$image; /> </p> <p> $description; </p> </div> $endeach; </body></html>This next section is the php part for the above template.user.php<?phpsession_start();require_once Plater.php;require_once db.php;$tpl = new Plater();// Query a database$user_id = (int)$_SESSION[user_id];$sql = mysql_query(select * from images where user_id = $user_id order by date desc limit 5);$images = [];// put into the arraywhile($row = mysql_fetch_assoc($sql)){ $images[] = [image => $row[filename], description => $row[descr]];}// replacemet$tpl->assign(myimages, $images);// show$tpl->show(templates/user.tpl);That was just a little taste of the template system. Here are some of the current features that it has so far:Import templates within the templateRun PHP functionsRun Custom functionsTidyImport css (decreases http requests)Loopsglobals$get$post$session$cookie$serverTemplate comments (Won't display in html output)Multi line: /$ Multiline comment $/Single line: $$ Single line commentRemove empty tags after all replacements are doneAnd finally, here is the main library:<?php/** * @author php Snips <[email protected]> * @copyright (c) 2012, php Snips * @version 0.0.1 * @see http://plater.phpsnips.com/docs/ */class Plater{ protected $template = , $replacements = array(), $cssFiles = array(), $disableTidy = false; public function __construct(){ } public function show($filename){ try{ $this->template = $this->import($filename); $this->format(); echo $this->template; }catch(Exception $e){ echo $e->getMessage(); } } public function attachCSS($filename = null){ $tmp = $this->template; if(empty($filename)){ $matches = array(); preg_match_all(/\\\$attachCSS\((\|')(.+)(\|')\);/U, $tmp, $matches); $tmp = preg_replace(/\\\$attachCSS\((\|')(.+)(\|')\);/U, , $tmp); foreach($matches[2] as $filename){ $this->cssFiles[] = $this->import($filename); } $this->template = $tmp; }else{ $this->cssFiles[] = $this->import($filename); } } public function import($filename){ if(!is_file($filename)){ throw new Exception(Could not find \<b>$filename</b>\ it does not exist.); } return file_get_contents($filename); } public function assign($key, $value){ $this->replacements[$key] = $value; } public function disableTidy($boolean){ $this->disableTidy = (bool)$boolean; } private function format(){ $this->loadIncludes(); $this->get(); $this->post(); $this->session(); $this->server(); $this->cookie(); $this->template = $this->removeComments(); $this->runWhileLoops(); $this->template = $this->replaceTags(); $this->loadIncludes(); $this->template = $this->replaceTags(); $this->template = $this->removeEmptyTags(); $this->attachCSS(); $this->template = $this->replaceCSS(); if(!$this->disableTidy){ $this->template = $this->tidy(); } } private function tidy(){ if(class_exists(tidy)){ $tmp = $this->template; $tidy = new \tidy(); $config = array( indent => true, indent-spaces => 4, clean => true, wrap => 200, doctype => html5 ); $tidy->parseString($tmp, $config, 'utf8'); $tidy->cleanRepair(); $string = $tidy; } return $string; } private function get(){ foreach($_GET as $k => $v){ $this->replacements[get. . $k] = $v; } } private function post(){ foreach($_POST as $k => $v){ $this->replacements[post. . $k] = $v; } } private function server(){ foreach($_SERVER as $k => $v){ $this->replacements[server. . $k] = $v; } } private function session(){ if(isset($_SESSION)){ foreach($_SESSION as $k => $v){ $this->replacements[session. . $k] = $v; } } } private function cookie(){ foreach($_COOKIE as $k => $v){ $this->replacements[cookie. . $k] = $v; } } private function loadIncludes(){ $tmp = $this->template; $matches = array(); preg_match_all('/(\\$import\((|\')(.+?)(|\')\).*;)/i', $tmp, $matches); //print_r($matches); $files = $matches[3]; $replace = 0; foreach($files as $key => $file){ $command = preg_replace(/\\\$import\((\|').+?(\|')\)/, , $matches[0][$key]); $string = $this->import($file); $string = $this->runFunctions($string, blah . $command); $f = preg_quote($file, /); $tmp = preg_replace('/\\$import\((|\')' . $f . '(|\')\).*;/i', $string, $tmp); $replace++; } $this->template = $tmp; if($replace > 0){ $this->loadIncludes(); } } private function runWhileLoops(){ $tmp = $this->template; $matches = array(); preg_match_all(/\\\$each\((\|')(.+)(\|')\):(.+)\\\$endeach;/isU, $tmp, $matches); if(isset($matches[4]) && !empty($matches[4])){ foreach($matches[4] as $id => $match){ $new = ; $match = ; $name = $matches[2][$id]; $ntmp = $matches[4][$id]; if(isset($this->replacements[$name])){ foreach($this->replacements[$name] as $val){ $new .= $this->replaceTags($val, $ntmp); } } $name = preg_quote($name); $tmp = preg_replace(/\\\$each\((\|')$name(\|')\):(.+)\\\$endeach;/isU, $new, $tmp); } } $this->template = $tmp; } private function replaceCSS(){ $tmp = $this->template; $css = <style>\n; foreach($this->cssFiles as $cssStr){ $css .= $cssStr\n; } $css .= </style>\n; if(preg_match(/<\/head>/i, $tmp)){ $tmp = preg_replace(/<\/head>/i, $css</head>, $tmp, 1); }else{ $tmp .= $css; } return $tmp; } private function replaceTags($keys = null, $tmp = null){ if(empty($tmp)){ $tmp = $this->template; } if(!empty($keys)){ $replacements = $keys; }else{ $replacements = $this->replacements; } foreach($replacements as $key => $value){ if(is_array($value)){ continue; } $matches = array(); preg_match_all('/\\$' . $key . '\..+?;/', $tmp, $matches); if(!empty($matches[0])){ foreach($matches[0] as $match){ $result = $this->runFunctions($value, $match); $m = preg_quote($match); $tmp = preg_replace('/' . $m . '/', $result, $tmp); } } if(!is_array($value)){ $tmp = str_replace('$' . $key . ';', $value, $tmp); } } return $tmp; } private function runFunctions($value, $functions){ $functions = explode(., $functions); array_shift($functions); foreach($functions as $func){ $func = trim($func, $();); if(function_exists($func)){ $value = $func($value); /* if(empty($value)){ throw new Exception(Invalid parameter for <b>$func</b> received \<b>$v</b>\ within template.); } */ } } return $value; } private function removeEmptyTags(){ $tmp = $this->template; $tmp = preg_replace(/\\$[^\' ]+?;/, , $tmp); return $tmp; } private function removeComments(){ $tmp = $this->template; $tmp = preg_replace(/\/\\$.*\\$\//isU, , $tmp); $tmp = preg_replace(/.*\\$\\$.+(\n|$)/iU, , $tmp); return $tmp; }}So, after review, what are your thoughts on this library?Thanks! | PHP Template Engine | php;html;template | null |
_unix.272851 | I have previously used ip netns exec command to modify netns interfaces. But if there is no name associated with a netns (eg: docker), how can I use nsid result of ip netns list-id command for modifying the netns interface. | 'ip netns exec' command execution using nsid obtained from 'ip netns list-id' | networking;ip;network interface;iproute | null |
_unix.74908 | I have a folder(which contains a lot of sub-folders and files) on a machine,I used du -m and it shows the disk usage of all sub-folders and files,anyway, the overall disk usage is 78MI used scp -r to copy the folder into another machine,this time, du -m get the overall disk usage: 12M,very different.Why does this happen?I'm afraid some of the files or sub-folders are not copied fully,so are there any other ways to check the total number of bytes? | `du` get different results on different machines for the same folder | disk usage;size | null |
_codereview.32966 | I took a JavaScript challenge to finish a task related to logo of Breaking Bad where letters in your first name and last name are spotted with elements of periodic table and its respective atomic number. I wrote the below code, any suggestions to improve performance or any best coding practices function Process() { var ellist = { h: 1, he: 2, li: 3, be: 4, b: 5, c: 6, . . . Lv:116, Uus:117, Uuo:118 }; var fname = document.getElementById(firstname); var lname = document.getElementById(lastname); var splits = fname.split(); var value; for (var i = 0; i < splits.length; i++) { var onevalue = fname.indexOf(splits[i]); var singlev = fname.substring(onevalue, onevalue + 1); var doublev = fname.substring(onevalue, onevalue + 2); var triplev = fname.substring(onevalue, onevalue + 3); if (ellist[splits[i]] || ellist[doublev] || ellist[triplev]) { value = splits[i]; if (ellist[doublev] || ellist[triplev]) { value = ellist[doublev]; if (ellist[triplev]) { value = ellist[triplev]; // some code here } // some code here } // some code here } }Using the Process() function which contains the logic. The object ellist contains the list of elements of periodic table with its atomic number. First name is taken from textbox on webpage and stored in fname and similarly the last name in lname and in the for loop it contains the code which checks whether the firstname contains the string which matches the elemetns of periodic table. Any suggestions? | Encoding strings using periodic table abbreviations | javascript;performance;strings | Any suggestions?Yes, a few.First off, split your function into parts (SRP), to separate the view (DOM elements and their values) from the logic (finding element names in strings).var splits = fname.split();for (var i = 0; i < splits.length; i++) { var onevalue = fname.indexOf(splits[i]);That doesn't make much sense to me. Don't you expect onevalue == i? If not, you might annotate this explicitly and/or make the comparison. Maybe it's inside the some code?var doublev = fname.substring(onevalue, onevalue + 2);var triplev = fname.substring(onevalue, onevalue + 3);Notice that these will have the same value as singlev in the last [two] iterations of your loop, where the end is outside of the string.if (ellist[splits[i]] || ellist[doublev] || ellist[triplev]) { value = splits[i]; if (ellist[doublev] || ellist[triplev]) { value = ellist[doublev]; if (ellist[triplev]) { value = ellist[triplev];Ouch. Simplify this toif (triplev in ellist) { value = ellist[triplev];} else if (doublev in ellist) { value = ellist[doublev];} else if (splits[i] in ellist) { // are you sure you don't want `singlev`? value = splits[i];} |
_codereview.152850 | Mostly in my applications for given class when there is need to create collection i do it in separate class like as presented below. As you are experts here i would like to ask you whether am i doing that correctly in context of OOP programming. Awaiting your opinions especially i saw in that some people sometimes for their collection class inherits e.g from ICollection or IList but don't get the point - please tell what is the difference then between my collection class and their once. If there is something i have to know please also some samples what could be modified or whatever. Thanks in advance.Regular class:Public Class Variation Inherits Base Implements IComparable(Of Variation)'Properties..'Constructor..'Some methods..#Region list features: compare, sort etc..'this is required for sorting Public Function CompareTo(pother As Variation) As Integer Implements IComparable(Of Variation).CompareTo 'we can sort because of this Return String.Compare(Me.Position, pother.Position) End Function Public Function FindPredicate(ByVal pvariation As Variation) As Predicate(Of Variation) Return Function(pvariation2 As Variation) pvariation.Id = pvariation2.Id End Function Public Function FindPredicateByUserId(ByVal pvariation As String) As Predicate(Of Variation) Return Function(pvariation2 As Variation) pvariation = pvariation2.Id End Function#End RegionCollection class: (this case for List) Public Class Variations Implements IDisposable Public Collection As List(Of Variation) Sub New() Collection = New List(Of Variation) End Sub Public Function AddToCollection(ByVal variation As Variation) As Boolean Collection.Add(variation) Return True End Function Public Sub RemoveFromCollection(index As Integer) If Not IsNothing(Collection.Item(index)) Then Collection.RemoveAt(index) End If End Sub Public Sub SortByPosition() Collection.Sort() End Sub#Region IDisposable Support Private _disposedValue As Boolean ' To detect redundant calls ' IDisposable Protected Overridable Sub Dispose(disposing As Boolean) If Not Me._disposedValue Then If disposing Then ' TODO: dispose managed state (managed objects). End If ' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below. ' TODO: set large fields to null. End If Me._disposedValue = True End Sub ' This code added by Visual Basic to correctly implement the disposable pattern. Public Sub Dispose() Implements IDisposable.Dispose ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. Dispose(True) GC.SuppressFinalize(Me) End Sub#End Region End Classother Collection class: (this case for Dictionary(Of x, x))for some Artikel class:Imports BAL.ArticleNamespace Collections Public Class ArticlesVariations Public Property Collection As Dictionary(Of Integer, Artikel) Sub New() Collection = New Dictionary(Of Integer, Artikel) '-- new collection object End Sub Sub New(pId As Integer, pArtikel As Artikel) Collection.Add(pId, pArtikel) End Sub '-- Get next number of article to be added to new article Public Function GetNextArtikelNumber() Dim lastValue As Artikel = Collection(Collection.Keys.Max()) Dim newnumber As String = TextUtils.IncreaseNumberAtTheEnd(lastValue.Nummer, 1, .) Return newnumber End Function '-- Delete from collection just deleted articles and their combination Public Sub RemoveAllMarkedAsDeleted(keys As List(Of Integer)) '-- Check whther anything has been marked as deleted If keys.Count > 0 Then For Each row In keys Collection.Remove(row) Next ReorderKeys() End If End Sub '-- Unfortunetly we cannot change dictionary collection keys, so we have to create new collection to reorder keys when something was deleted to keep correct order Private Sub ReorderKeys() Dim newCollection As New Dictionary(Of Integer, Artikel) Dim index = 0 For Each collitem In Collection newCollection.Add(index, collitem.Value) index += 1 Next Collection.Clear() Collection = newCollection End Sub '-- Check and if required rechange articles numbers from 1 to ... Private Sub UpdateArtikelNumbers() If Collection.Count > 0 Then For i = 0 To Collection.Count - 1 Dim artikelNUmmer As String = Collection.Item(i).Nummer Dim lastDigit As String = artikelNUmmer.Last If CInt(lastDigit) <> i + 1 Then lastDigit = i + 1 Collection.Item(i).Nummer = TextUtils.RemoveAllAfterLastOccurenceOf(., Collection.Item(i).Nummer, True) + lastDigit 'CStr(collection.Item(i).Nummer.Substring(0, collection.Item(i).Nummer.Length - 1) & lastDigit) 'Remove last char and add lastChar - to nie dzialalo prawidlowo End If Next End If End Sub '-- Get current collection object Public Function GetCollection() As Dictionary(Of Integer, Artikel) Return Collection End Function '-- Get whether empty list (if no images for given article) or existing path's list Public Function GetImagesForArticle(partikelNummerOrKey As String) As List(Of ArticleImage) Dim imgList As New List(Of ArticleImage) 'dla modulu Newartikel - tutaj nie ma jeszcze numerow artykulow - stad pobieramy zdjecia w/g indexow kolekcji If Not _isEditModule Then If Collection.Count > 0 Then imgList = Collection.Item(CInt(partikelNummerOrKey)).ArtikelImages '-- get images list for that article End If Else If Collection.Count > 0 Then For i = 0 To Collection.Count - 1 Dim artikelNummer As String = Collection.Item(i).Nummer If artikelNummer = partikelNummerOrKey Then '-- search for article in collection imgList = Collection.Item(i).ArtikelImages '-- get images list for that article Exit For End If Next End If End If Return imgList End Function '-- Pass artikel nummer and current images list for it. old one will be completly decomissed Public Sub AddImagesToArticle(partikelNummerOrKey As String, pImages As List(Of ArticleImage)) 'dla modulu Newartikel - tutaj nie ma jeszcze numerow artykulow - stad dodajemy zdjecia nie do numerow artykulow, ale do indexow kolekcji If Not _isEditModule Then If Collection.Count > 0 Then Collection.Item(CInt(partikelNummerOrKey)).ArtikelImages = Nothing Collection.Item(CInt(partikelNummerOrKey)).ArtikelImages = pImages End If Else If Collection.Count > 0 Then For i = 0 To Collection.Count - 1 Dim artikelNummer As String = Collection.Item(i).Nummer If artikelNummer = partikelNummerOrKey Then Collection.Item(i).ArtikelImages = Nothing Collection.Item(i).ArtikelImages = pImages Exit For End If Next End If End If End Sub End ClassEnd Namespace | Collection class for specific class | reinventing the wheel;vb.net;collections | null |
_unix.238754 | How does this VM replace Microsoft Active Directory, on a network with Windows Machines on it? Is there a specific component that is installed that replaces it? Is it Samba or Webmin? Are there any limitations in comparison to actual Active Directory? | How does this Turnkey Linux domain-controller replace Microsoft Active Directory? | active directory;samba4;webmin;turnkey | The current Domain Controller container from Turnkey uses Samba, and includes the web-based interface (webmin). Samba is the component that replaces AD.It's difficult to say whether there are limitations compared to Microsoft AD; it depends on what components you are using from Microsoft. Generally speaking: no, there is no limitation, and in fact you might find SAMBA far more liberating, since it's a more flexible system than Microsoft's implementation. But obviously, it does depend on what you are used to, what you are expecting, and so on. Given that Turnkey is $0 to try, a trial run is probably the best determining factor. |
_codereview.10539 | I'm trying to implement TCP connection pooling and return a connection back to the pool using IDisposable. I'm wondering if my implementation is correct. It seems to be working but I think because the base class also implements IDisposable and finalize, my code might be leaky.public class BaseClass : IDisposable{ internal bool IsDisposed { get; set; } private object someResource; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~BaseClass() { Dispose(false); } protected virtual void Dispose(bool disposing) { if (someResource != null) { // some clearn up return; } if (disposing) { //dispose un managed resources } }}public class ChildClass : BaseClass{ // adds some functionality}public class MyClass : ChildClass, IDisposable{ MyPoolManager manager = null; public MyClass(MyPoolManager manager) { this.manager = manager; } void IDisposable.Dispose() { manager.ReturnPooledConnection(this); }}public class MyPoolManager{ private static MyPoolManager instance = new MyPoolManager(); private static object objLock = new object(); private static Queue<MyClass> que = null; private string name; static MyPoolManager() { que = new Queue<MyClass>(); // enqueue some instances of MyClass here MyClass client = new MyClass(instance); que.Enqueue(client); } private MyPoolManager() { } public MyPoolManager(string name) { this.name = name; } public MyClass GetPooledConnection() { lock (objLock) { while (que.Count == 0) { if (!Monitor.Wait(objLock, 1000)) throw new TimeoutException(Connection timeout); } return que.Dequeue(); } } public void ReturnPooledConnection(MyClass client) { lock (objLock) { que.Enqueue(client); Monitor.Pulse(objLock); } }}Use it like this in your program:MyPoolManager pool = new MyPoolManager();using (var conn = pool.GetPooledConnection()){ // use the conn here}// when you reach here the conn should have returned back to the pool | Implementing IDisposable correctly to return TCP connection back to pool | c#;.net | null |
_webapps.9508 | How do I get an online live radio broadcast feed in the U.S. using a laptop w/Windows Vista. | How do listen to radio online | webapp rec;streaming;internet radio | null |
_cstheory.20723 | One way to show that checking the feasibility of a linear system of inequalities is as hard as linear programming is via the reduction given by the ellipsoid method. An even easier way is to guess the optimal solution and introduce it as a constraint via binary search. Both of these reductions are polynomial, but not strongly polynomial (i.e they depend on the number of bits in the coefficients of the inequalities). Is there a strongly polynomial reduction from LP optimization to LP feasibility ? | Equivalence of feasibility checking and optimization for linear systems | ds.algorithms;linear programming | null |
_unix.374619 | In my cluster, I am running some experiments that uses the network bandwidth aggressively.(It's on Cent OS 7 Linux)Right after starting up the experiment, the machines use their maximum network bandwidth. After a short period of time, their network speed drops significantly (it becomes 20~25 times slower).After long period of time, when most of machines terminate, the remaining few machines are still struggling with the slow network speed.I suspect the TCP's congestion control, so am cosidering trying turning it off.How can I completely turn off TCP congestion control? | How to completely turn off TCP congestion control? | linux;tcp | null |
_unix.384346 | : [arguments] Do nothing beyond expanding arguments and performing redirections.How can a pipeline or a compound command be used with :? Braces don't seem to solve the problem:$ : { echo hello | cat; }bash: syntax error near unexpected token `}'$ : { if test 1; then echo hello; fi; }bash: syntax error near unexpected token `then'Double quotes will prevent some expansions, which : allows.The same problem happens when using echo instead of :.$ echo { echo hello | cat; }bash: syntax error near unexpected token `}'$ echo { if test 1; then echo hello; fi; }bash: syntax error near unexpected token `then'Basically I want to run a command up to expansions and redirections with :, and check the result with echo. The quote doesn't mention pipe and control flow keywords won't work, so I only expect that alias expansion will not happen. Thanks. | How can a pipeline or compound command be used with `:` and `echo`? | bash | : { echo hello | cat; }The shell parses this command line. First it tries to find the end of the first command. That end is the pipe.So the first command is: { echo hellowhich does nothing. Especially it pipes nothing into cat. With: { echo hello | cat;being gone there is only the } left which is not a valid command. |
_unix.212266 | I have the below block of data.Heap after GC invocations=31 (full 3): par new generation total 131008K, used 0K [0x00000000eac00000, 0x00000000f2c00000, 0x00000000f2c00000) eden space 130944K, 0% used [0x00000000eac00000, 0x00000000eac00000, 0x00000000f2be0000) from space 64K, 0% used [0x00000000f2be0000, 0x00000000f2be0000, 0x00000000f2bf0000) to space 64K, 0% used [0x00000000f2bf0000, 0x00000000f2bf0000, 0x00000000f2c00000) concurrent mark-sweep generation total 131072K, used 48549K [0x00000000f2c00000, 0x00000000fac00000, 0x00000000fac00000) concurrent-mark-sweep perm gen total 30000K, used 19518K [0x00000000fac00000, 0x00000000fc94c000, 0x0000000100000000) }I need to extract the below data of total and used numeric data without K for the below. i.e. value1=131008, value2=0,value3=131072,value4=48549,value5=30000 and value6=19518should be extracted from the below:par new generation ***total*** 131008K, ***used*** 0Kconcurrent mark-sweep generation ***total*** 131072K, used 48549K concurrent-mark-sweep perm gen ***total*** 30000K, ***used*** 19518KI know how to extract the data for fixed length values like below.value1=`grep par new generation | cut -c27-31However, the above block of data has variable length values. Not sure how extract these. Can you please help. | Extract values from block of data | sed;awk;grep | If your goal is to extract those six numbers into shell variables, it is probably more convenient to put them in a bash array like this:$ data=($(awk '/^ *(par|concurrent)/{printf %s %s ,$5+0,$7+0}' file))You can verify that the array has the correct values using declare:$ declare -p datadeclare -a data='([0]=131008 [1]=0 [2]=131072 [3]=48549 [4]=30000 [5]=19518)'If, instead, you just want to print the values:$ awk '/^ *(par|concurrent)/{printf value%s=%s\nvalue%s=%s\n,++c,$5+0,++c,$7+0}' filevalue1=131008value2=0value3=131072value4=48549value5=30000value6=19518How is works/^ *(par|concurrent)/This matches only on the lines that start with par or concurrent.printf %s %s ,$5+0,$7+0For the matched lines, we print out the fifth and seventh fields. By adding zero to these values, we force awk to convert them to numbers. This has the side-effect of removing the k. |
_unix.31311 | I want find out where the backup script of a Fedora 8 server is. I haven't found it so far ( my Linux knowledge is very spare). I looked with crontab -l and I only can find a tempdelete.pl. Than I looked into /etc/cron.daily and I can see000-delay.cronlogrotatemlocate.cronrpmtmpwatch0anacroncupsmakewhatis.cronprelinktetex.conNothing which looks like a backup script if taken the name. Nothing in the /etc/cron.hourly directory and etc/cron.weekly looks similar.The backup script includes backup from Windows and Linux machines (about 5 machines). I also saw that there is a separate backup user. It came to my mind that the backups are started from the other machines, not from the machine which holds the backup. I also looked under /mnt and there are three entries, but all are empty.I looked on one Windows machine and didn't found something in the task planner. Also the other backup software which is on this machine doesn't make this backup.How can I find out how the backup mechanism is working? Hope someone can help me out.@Zoredache:Yes, I inherited it from my precursor. I think it is a script, because no backup system was mentioned. On one Windows machine there is CA ARCserve Backup Manager, but it only makes backup on tapes. My precursor told me that it exists and one time I looked on it and the disk space is now empty. Therefore I want to find out how the backup looks like. I don't really know if it is running, I only saw that the diskspace is empty and thats why I think it is running. I add an excerpt of /var/log, but I don't know if it is logged.anaconda.loganaconda.sysloganaconda.xlogauditbittorrentboot.logboot.log-20120115boot.log-20120122boot.log-20120129boot.log-20120205btmpbtmp-20120201croncron-20120115cron-20120122cron-20120129cron-20120205cupsdmesgfailloggdmhttpdlastlogmailmaillogmaillog-20120115maillog-20120122maillog-20120129maillog-20120205messagesmessages-20120115messages-20120122messages-20120129messages-20120205ntpstatspppprelinkproftpdrpmpkgsrpmpkgs-20120115rpmpkgs-20120122rpmpkgs-20120129rpmpkgs-20120205sambasecuresecure-20120115secure-20120122secure-20120129secure-20120205setroubleshootspoolerspooler-20120115spooler-20120122spooler-20120129spooler-20120205tallylogvboxwtmpwtmp-20120201xferlogXorg.0.logXorg.0.log.oldyum.logIn which log file should I look? In cron I see thisFeb 9 19:01:01 backup CROND[19717]: (root) CMD (run-parts /etc/cron.hourly) | Where can I look for backup script? | linux;windows;backup;fedora | null |
_unix.49589 | Which Linux distribution would you recommend for preparing myself for LPIC and gain some experience in configuring the system? | Which distro to study for LPIC? | linux | From Wikipedia:The exams are distribution-neutral, requiring a general knowledge of Linux rather than specifics about a certain distribution. This is shown in the way that the exams deal with the differing package management formats .deb and .rpm. In earlier versions of the test one of these was chosen by the candidate; in the current version the candidate is expected to know both formats.Thus, learning Red Hat (or CentOS, which is based upon Red Hat's source code) and Debian/Ubuntu should be enough.However, looking beyond the certification, it's a good idea to have at least basic knowledge of other distros; in fact, trying your hand at Arch, Slackware, Gentoo or even LFS can be used to develop other useful skills. |
_datascience.14495 | I have millions of lines of statements containing both subjective(like I prefer the red skirt) and objective(Washington was born on February 22, 1732) statements or opinions. How can I separate them? Not manually. By objective, I mean if the object or predicative of the sentence changed it would be in conflict with the truth. For illustration, She prefer red skirt. if we change red or skirt, the (new) statement would remain right, which can not apply to statements like Washington was born on February 22, 2016.The statements which should be pushed out:1. Washington was born on February 22, 17322. Washington was born on February 21, 17313. Obama was born on February 22, 17324. Nobody A was born on February 22, 20165. Red is blue6. Color is a day7. I'm a robot8. You are a person Statements which should be kept:1. I like coffee2. Red is my favorite color3. I hate him4. You are awesome5. You are clever6. I was born years ago7. You are very old8. Tomorrow will be better | Any method to filter out objective statements(or say facts)? | classification;data cleaning | null |
_datascience.18208 | I have a dataset which belongs to a hospital. It contains data about patients and healthy people. The problem is separating healthy ones from patients. I add some new features to dataset to solve this problem. When I reduce the dimensions of data including the new features and visualize the data, the patient and healthy individuals are distinguishable(visually separable). Now if one asks what is the relation between the used approach (feature extraction, visualization, using the human ability, unsupervised methods) and expert system, what can I say? How can I use this method to build an expert system?Thank you in advance. | unsupervised learning in medical systems and intelligent systems? | visualization;feature extraction;unsupervised learning;knowledge base | null |
_vi.9941 | I can check vim's version by using v:version, and I can check if I am running in nvim by doing has('nvim'). Is there a variable like v:version in neovim to let me know the nvim version, like 0.1.4 or 0.1.6? | How do I check the version of NeoVim in vimscript? | vimscript;neovim | null |
_codereview.28201 | I got tired of stringing together objectAtIndex: and objectForKey: and hoping nothing fails along the way. I parse a lot of JSON from sources like the Google Directions API and it was cluttering my code and hard to read. In this example I am parsing the JSON returned by this call:http://maps.googleapis.com/maps/api/directions/json?origin=415OliveStMenloPark&destination=425ShermanAvePaloAlto&sensor=false&mode=drivingI just learned Objective-C and how to program (beyond Matlab) and want some feedback on the best practices for what I am doing. UsageI call the class method below and pass in a dictionary along with a cascading series of keys for a dictionary and indexes for arrays. I defined a couple of macros to reduce typing. Usage code NSTimeInterval flightTime = [(NSNumber *)[RDUtilities objectFromNestedJSON:responseDictionary usingCascadedKeys:RDJSONKey(@routes),RDJSONIndex(0), RDJSONKey(@legs), RDJSONIndex(0), RDJSONKey(@duration), RDJSONKey(@value)] doubleValue];Implementation Code#define RDJSONKey(x) @{@dKey:x}#define RDJSONIndex(x) @{@aIndex:@x} @implementation RDUtilities+(id) objectFromNestedJSON:(id)JSONObject usingCascadedKeys:(NSDictionary*)firstArg,...{ NSMutableArray *keyDexList = [[NSMutableArray alloc] init]; NSArray *subArray = nil; NSDictionary *subDictionary = nil; id subObject = nil; va_list args; va_start(args, firstArg); // Figure out the type of JSONObject. if ([JSONObject isKindOfClass:[NSDictionary class]]) { subDictionary = JSONObject; } else if ([JSONObject isKindOfClass:[NSArray class]]) { subArray = JSONObject; } else { return nil; } // Iterate through the list of arguments. for (NSDictionary *arg = firstArg; arg != nil; arg = va_arg(args, NSDictionary *)) { if ( [[arg allKeys] containsObject:@dKey] || [[arg allKeys] containsObject:@aIndex]) { [keyDexList addObject:arg]; } else { NSLog(@Invalid input types); return nil; } } // Look at the keyDex and pull out the next subObject from the current correct subObject. NSArray *allButLastKeyDex = [keyDexList objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [keyDexList count]-1)]]; for (NSDictionary *keyDex in allButLastKeyDex) { if (subDictionary != nil && [[keyDex allKeys] containsObject:@dKey]) { // Get the sub object that this key references. subObject = [subDictionary objectForKey:[keyDex objectForKey:@dKey]]; // Figure out what we got. if ([subObject isKindOfClass:[NSDictionary class]]) { subDictionary = subObject; subArray = nil; // We can be sure we don't try to use this incorrectly now. } else if ([subObject isKindOfClass:[NSArray class]]) { subArray = subObject; subDictionary = nil; // We can be sure we don't try to use this incorrectly now. } // Unneeded due to containsObject constraint. continue; } if (subArray != nil && [[keyDex allKeys] containsObject:@aIndex]) { // Get the sub object that this key references. subObject = [subArray objectAtIndex:[(NSNumber *)[keyDex objectForKey:@aIndex] integerValue]]; // Figure out what we got. if ([subObject isKindOfClass:[NSDictionary class]]) { subDictionary = subObject; subArray = nil; // Safer until we verify logic. } else if ([subObject isKindOfClass:[NSArray class]]) { subArray = subObject; subDictionary = nil; // Safer until we verify logic. } // Unneeded due to containsObject constraint. continue; } } // Get the last key or index. NSDictionary *finalKeyDex = [keyDexList lastObject]; // Pull out the final value and return it. if ([[finalKeyDex allKeys] containsObject:@dKey]) { return [subDictionary objectForKey:[finalKeyDex objectForKey:@dKey]]; } else if ([[finalKeyDex allKeys] containsObject:@aIndex]) { return [subArray objectAtIndex:[(NSNumber *)[finalKeyDex valueForKey:@aIndex] integerValue]]; } else { return nil; }}@end | Pulling Objects & Values From Arbitrarily Nested JSON | objective c;json;ios | First off, good job recognizing this problem and coming up with an innovative solution! I definitely like, and it's always nice to see a variadic argument list implementation. I also like that the code is written fairly accessibly, and doesn't try to get into any particularly clever solution.The primary issue I see with this code is that it relies on conditional logic based on the type of objects rather than polymorphism, object-oriented programming, or useful features of Objective-C. This code does considerable work that the Objective-C runtime could be handling.For instance we see groups of repeated, quite similar logic in the loop that iterates the key / index dictionaries. We could instead add methods to NSArray and NSDictionary using categories that will handle the key or index dictionaries as appropriate.There are a few other issues, too. There is a repetition of logic at the end of the method to allow returns from the body of the if/else statements, but you could have iterated your entire loop and then just return subObject. The code in most cases due to missing/incorrect object types will return nil but in the case of an incorrect array index it throws an exception. I think a consistent behavior there is best. Also, some style issues - abbreviations like keyDex that aren't particularly explicit (something like keyOrIndexDictionary would be an improvement). This class method could easily be a function, actually, as it never refers to self - remember that in Objective-C you don't have to make your utility functions class methods on some Utilities class like you do in Java. Finally, I notice a lot of use of hard-coded strings, those should be moved out into constants.As part of reviewing this code, I placed it in an empty iOS project with a unit test target, and document its behavior so that I could refactor it and demonstrate an alternative way of doing things. I used the sample response you linked to as input to the tests, and wrote the following test case:@implementation RDUtilitiesTests- (void)testOneKey{ id responseObject = [self responseObject]; id returnValue = [RDUtilities objectFromNestedJSON:responseObject usingCascadedKeys:RDJSONKey(@status),nil]; STAssertEqualObjects(returnValue, @OK, nil);}- (void)testKeyThenIndex{ id responseObject = [self responseObject]; id value = [RDUtilities objectFromNestedJSON:responseObject usingCascadedKeys:RDJSONKey(@routes),RDJSONIndex(0),nil]; STAssertTrue([value isKindOfClass:[NSDictionary class]], nil); STAssertNotNil([(NSDictionary *)value objectForKey:@bounds], nil);}- (void)testSelfCheck{ id responseObject = [self responseObject]; STAssertNotNil(responseObject, nil);}- (void)testIndexFirstReturnsNil{ id responseObject = [self responseObject]; id value = [RDUtilities objectFromNestedJSON:responseObject usingCascadedKeys:RDJSONIndex(0),nil]; STAssertNil(value, nil); value = [RDUtilities objectFromNestedJSON:responseObject usingCascadedKeys:RDJSONIndex(1),nil]; STAssertNil(value, nil);}- (void)testOutOfBoundsIndexThrowsException{ id responseObject = [self responseObject]; STAssertThrows(([RDUtilities objectFromNestedJSON:responseObject usingCascadedKeys:RDJSONKey(@routes),RDJSONIndex(1),nil]),nil);}- (void)testNonexistentKeyReturnsNil{ id responseObject = [self responseObject]; id value = [RDUtilities objectFromNestedJSON:responseObject usingCascadedKeys:RDJSONKey(@routes),RDJSONIndex(0),RDJSONKey(@LOLOLOLOLOL),nil]; STAssertNil(value, nil);}- (void)testReturnsNilWhenGivenNonDictionaryNonArrayObject{ NSObject *object = [[NSObject alloc] init]; id value = [RDUtilities objectFromNestedJSON:object usingCascadedKeys:RDJSONKey(@routes),nil]; STAssertNil(value, nil); value = [RDUtilities objectFromNestedJSON:object usingCascadedKeys:RDJSONIndex(0),nil]; STAssertNil(value, nil);}- (void)testReturnsNilWhenIndexLeadsToNonDictionaryNonArrayObject{ id value = [RDUtilities objectFromNestedJSON:[self responseObject] usingCascadedKeys:RDJSONKey(@routes),RDJSONIndex(0),RDJSONKey(@bounds),RDJSONKey(@northeast),RDJSONKey(@lat),RDJSONKey(@value),nil]; STAssertNil(value, nil); value = [RDUtilities objectFromNestedJSON:[self responseObject] usingCascadedKeys:RDJSONKey(@routes),RDJSONIndex(0),RDJSONKey(@bounds),RDJSONKey(@northeast),RDJSONKey(@lat),RDJSONIndex(0),nil]; STAssertNil(value, nil);}- (void)testReturnsPrimitive{ id value = [RDUtilities objectFromNestedJSON:[self responseObject] usingCascadedKeys:RDJSONKey(@routes),RDJSONIndex(0),RDJSONKey(@bounds),RDJSONKey(@northeast),RDJSONKey(@lat),nil]; STAssertTrue([value isKindOfClass:[NSNumber class]], nil); NSNumber *expected = @37.45040780; STAssertEqualObjects(value, expected, nil);}- (id)responseObject{ NSString *responsePath = [[NSBundle bundleForClass:[self class]] pathForResource:@response ofType:@json]; NSData *responseData = [NSData dataWithContentsOfFile:responsePath]; id object = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:NULL]; return object;}@endIt seems to provide decent coverage of the behavior to give us the freedom to change things with confidence.As I said, the primary issue is using conditional logic based on types rather than take advantage of polymorphism. I ended up with the following implementation:RDUtilities.h:#import <Foundation/Foundation.h>extern NSString *const RDJSONKeyKey;extern NSString *const RDJSONIndexKey;#define RDJSONKey(x) @{@dKey:x}#define RDJSONIndex(x) @{@aIndex:@x}@interface RDUtilities : NSObject+(id) objectFromNestedJSON:(id)JSONObject usingCascadedKeys:(NSDictionary*)firstArg,...;@endRDUtilities.m:#import RDUtilities.hNSString *const RDJSONKeyKey = @dKey;NSString *const RDJSONIndexKey = @aIndex;@interface NSObject (RDUtilityAdditions)- (id)rdValueForKeyOrIndexDictionary:(NSDictionary *)dictionary;@end@implementation NSObject (RDUtilityAdditions)- (id)rdValueForKeyOrIndexDictionary:(NSDictionary *)dictionary{ return nil;}@end@implementation NSArray (RDUtilityAdditions)- (id)rdValueForKeyOrIndexDictionary:(NSDictionary *)dictionary{ id toReturn = nil; NSUInteger index = NSUIntegerMax; NSNumber *indexNumber = dictionary[RDJSONIndexKey]; if ([indexNumber respondsToSelector:@selector(unsignedIntegerValue)]) { index = [indexNumber unsignedIntegerValue]; } if (index < [self count]) { toReturn = self[index]; } return toReturn;}@end@implementation NSDictionary (RDUtilityAdditions)- (id)rdValueForKeyOrIndexDictionary:(NSDictionary *)dictionary{ id toReturn = nil; id key = dictionary[RDJSONKeyKey]; if (key) { toReturn = self[key]; } return toReturn;}@end@implementation RDUtilities+(id) objectFromNestedJSON:(id)JSONObject usingCascadedKeys:(NSDictionary*)firstArg,...{ /*** rename for clarity - Objective-C style is usually very explicit about purpose and type ***/ NSMutableArray *mutableKeysAndIndexes = [[NSMutableArray alloc] init]; id subObject = nil; va_list args; va_start(args, firstArg); // Iterate through the list of arguments. for (NSDictionary *arg = firstArg; arg != nil; arg = va_arg(args, NSDictionary *)) { if ( [[arg allKeys] containsObject:RDJSONKeyKey] || [[arg allKeys] containsObject:RDJSONIndexKey]) { [mutableKeysAndIndexes addObject:arg]; } else { NSLog(@Invalid input types); return nil; } } subObject = JSONObject; for (NSDictionary *pathDictionary in mutableKeysAndIndexes) { subObject = [subObject rdValueForKeyOrIndexDictionary:pathDictionary]; } return subObject;}@endAs you can see, the complexity of the method has been reduced significantly. We no longer have hard-coded string checks, or separate code paths for arrays and dictionaries, or extra logic for the last key or index.As I mentioned earlier, passing an out of bounds index as an index key threw an exception; since the other errors seemed to return nil I decided to follow that convention with the code and I adjusted the unit tests appropriately, replacing testOutOfBoundsIndexThrowsException with testOutOfBoundsIndexReturnsNil:- (void)testOutOfBoundsIndexReturnsNil{ id responseObject = [self responseObject]; id value = [RDUtilities objectFromNestedJSON:responseObject usingCascadedKeys:RDJSONKey(@routes),RDJSONIndex(1),nil]; STAssertNil(value, nil);}Taking a look at this refactor, I then realized that this allows key or index arguments to not be passed within dictionaries, but rather we can simply pass the keys or indexes themselves in the argument list. I rewrote the category methods and the dictionary wrapper macros, as well as modifying the types in the RDUtilities class method, and ended with the following implementation:RDUtilities.h, second refactor:#import <Foundation/Foundation.h>#define RDJSONKey(x) x#define RDJSONIndex(x) @x@interface RDUtilities : NSObject+(id) objectFromNestedJSON:(id)JSONObject usingCascadedKeys:(id)firstArg,...;@endRDUtilities.m, second refactor:#import RDUtilities.h@interface NSObject (PrivateRDUtilityAdditions)- (id)rdValueForKeyOrIndex:(id)keyOrIndex;@end@implementation NSObject (PrivateRDUtilityAdditions)- (id)rdValueForKeyOrIndex:(id)keyOrIndex{ return nil;}@end@implementation NSArray (PrivateRDUtilityAdditions)- (id)rdValueForKeyOrIndex:(id)keyOrIndex{ id toReturn = nil; NSUInteger index = NSUIntegerMax; if ([keyOrIndex respondsToSelector:@selector(unsignedIntegerValue)]) { index = [keyOrIndex unsignedIntegerValue]; } if (index < [self count]) { toReturn = self[index]; } return toReturn;}@end@implementation NSDictionary (PrivateRDUtilityAdditions)- (id)rdValueForKeyOrIndex:(id)keyOrIndex{ id toReturn = nil; if (keyOrIndex) { toReturn = self[keyOrIndex]; } return toReturn;}@end@implementation RDUtilities+(id) objectFromNestedJSON:(id)JSONObject usingCascadedKeys:(id)firstArg,...{ NSMutableArray *mutableKeysAndIndexes = [[NSMutableArray alloc] init]; id subObject = nil; va_list args; va_start(args, firstArg); // Iterate through the list of arguments. for (id arg = firstArg; arg != nil; arg = va_arg(args, id)) { [mutableKeysAndIndexes addObject:arg]; } subObject = JSONObject; for (id indexOrKey in mutableKeysAndIndexes) { subObject = [subObject rdValueForKeyOrIndex:indexOrKey]; } return subObject;}@endThis code is considerably simpler, and opens up more opportunities for flexibility. One could develop a system of passing strings that represent a key/index path, much like the existing Cocoa key paths work. There are other opportunities for passing arguments now that can allow more dynamic use of the method. You could potentially refactor all of the work into categories, and then simply call a method specifying the order of keys and indexes on the deserialized JSON object without having to involve a separate object.Bottom line, make sure that any time you are using an Objective-C object's class as control flow, you take a step back and look at how you could simplify that by use of polymorphism and other object oriented principles. |
_codereview.140060 | This code copies files to our Test server and places the executable on a file share for the tester to access. I'm new to Powershell, so I'm sure I'm not doing this in the most efficient way. Any criticisms would be appreciated.# the destination that we are copying TO.$codeToDeploy = \\deployment_server\App-Shares\Developer_Area\Code to Deploy\;# all the local folders we'll need$myProjectFolder = C:\MTS\ProjectFolder\Project\;$myLocalOurProjectName = ($myProjectFolder + OurProjectName\bin\Debug\);$myLocalLauncher = ($myProjectFolder + OurProjectName_Launcher\bin\Debug\);$myLocalWcfService = ($myProjectFolder + ProjectWCFService\bin\);$myLocalWebsite = ($myProjectFolder + MTSWebsite\bin\);#----------------------------------------------------------------# 1. prep the code to deploy folder on the server to receive files#----------------------------------------------------------------# set our current folderSet-Location $codeToDeploy# create the name of the new top level folder with today's date $datedFolderName = MM + (get-date -Format yyyy-MM-dd) + \;# create the date-named folder - overwrite if it already existsNew-Item $datedFolderName -ItemType directory -Force;# set our current folder to the date-named folderSet-Location $datedFolderName;# create the sub foldersNew-Item OurProjectName Client -ItemType directory -Force;New-item OurProjectName Launcher -ItemType directory -Force;New-item ProjectWCFService\front end -ItemType directory -Force;New-item Website\front end -ItemType directory -Force;#----------------------------------------------------------------# 2. copy all the files from local debug to the target folders#----------------------------------------------------------------# copy to the MM Client folder$destination = ($codeToDeploy + $datedFolderName + OurProjectName Client\);Set-Location $myLocalOurProjectName Copy-Item *.dll,OurProjectName.exe $destination -Force;# copy to the Launcher Folder$destination = ($codeToDeploy + $datedFolderName + OurProjectName Launcher\);Set-Location $myLocalLauncher;Copy-Item OurProjectName_Launcher.exe $destination -Force;# copy to the Service Folder$destination = ($codeToDeploy + $datedFolderName + ProjectWCFService\);Set-Location $myLocalWcfService;Copy-Item *.dll $destination -Force;Set-Location -Path ..Copy-Item AllService.svc -Destination ($destination + front end\) -Force;# copy to the Website Folder$destination = ($codeToDeploy + $datedFolderName + Website\);$frontEnd = ($destination + front end\)Set-Location $myLocalWebsite;Copy-Item *.dll $destination -Force;Set-Location -Path ..Copy-Item *.aspx,*.master,CSS,SiteImages $frontEnd -Recurse -Force;#----------------------------------------------------------------# 3. copy all the files from local debug to the server's# client install\binaries location for serving up to the launcher #----------------------------------------------------------------# copy to the MM Client folder$destination = \\app-ttps2-tst\App-Shares\Project\Client Install\Binaries\OurProjectName\;Set-Location $myLocalOurProjectName Copy-Item *.dll,OurProjectName.exe -Destination $destination -Force;#----------------------------------------------------------------# 4. copy all the files from local debug to the UI Testing location#----------------------------------------------------------------$folders = Get-ChildItem \\nw\data\TnFS\Project\ProjectFolder\UI TESTING\MM * | Sort-Object#save the latest config file for later#$latestConfigFile = $folders | Select-Object -Last | Get-ChildItem OurProjectName.exe.config# copy to the MM Client folder$destination = \\nw\data\TnFS\Project\ProjectFolder\UI TESTING\ + $datedFolderName;New-Item $destination -ItemType directory -Force;Set-Location $myLocalOurProjectName Copy-Item *.dll,OurProjectName.exe -Destination $destination -Force; | Using Powershell to Copy Files to Several Locations | powershell | null |
_codereview.121003 | It is just one of the files. I have also tried to write some tests using PHPUnit. Please give me some suggestions to improve my coding-writing skills.The below is the test file for the above file:<?phpclass TestParseXML extends PHPUnit_Framework_TestCase{ public function testSetup() { $objectParseXML = new ParseXML(test.txt); return $objectParseXML; } /** * @depends testSetup */ public function testParseObject($objectParseXML) { $objectParseXML->current_line = <Article>; return $objectParseXML->current_line; } /** * @depends testSetup * @depends testParseObject */ public function testtagNameOn($objectParseXML, $currentLine){ $this->assertEmpty($objectParseXML->tree); $objectParseXML->scanCharacter('<', 0); $this->assertTrue($objectParseXML->isTagName); } /** * @depends testSetup * @depends testParseObject */ public function testTagContentOn($objectParseXML){ $objectParseXML->isTagName = True; $objectParseXML->scanCharacter('>', 3); $this->assertTrue($objectParseXML->isTagContent); $this->assertNotTrue($objectParseXML->isTagName); }}?>Code Files:<?phprequire('XML.php');class OpenXML extends XML{ var $fileHandler; public function openXMLFile($filename, $mode='r'){ $this->fileHandler = @fopen($filename, $mode); } public function getHandler() { return $this->fileHandler; } public function getHandlerType(){ return get_resource_type($this->fileHandler); }}?><?phprequire('ReadXML.php');class ParseXML extends ReadXML{ public $handle; public $current_line; public $isTagName = False; public $isTagContent = False; public $startParse = False; public $tagName; public $tagContent; public $tree = array();//Call appropriate function depend on $isTagName and $isTagContent public function scanCharacter($char, $index) { if(strcmp($char, '<')==0) { if($this->isTagContent){ $this->isTagContent = False; } if($index+1 < $this->getLen()) { $this->isTagName = $this->tagNameOn($this->current_line[$index+1]); } } elseif($this->isTagName and (strcmp($char, '>')==0)) { $this->isTagName = $this->tagNameOff(); $this->isTagContent = $this->tagContentOn(); } elseif((strcmp($char, '/')==0)){ $this->isTagName = False; $this->isTagContent = False; } elseif($this->isTagName and !strcmp($char, ' ')) { $this->isTagName = $this->tagNameOff(); } elseif($this->isTagName) { $this->gatherTagName($char); } elseif($this->startParse and $this->isTagContent) { $this->gatherTagContent($char); } } public function tagNameOn($nextChar) { if(!strcmp($nextChar, '/')==0) { $this->tagName = ; return True; }// print_r($this->tagName);// print_r(\n);// print_r($this->tagContent); $this->isTagContent = False; return False; } public function tagNameOff() { if(!($this->startParse) and strcmp($this->tagName, 'Document') == 0){ $this->startParse = True; } return False; } public function getLen(){ return strlen($this->current_line); } public function tagContentOn() { return True; } public function gatherTagName($char){ $this->tagName.= $char; } public function gatherTagContent($char){ $this->tagContent.= $char; } public function getTag() { $this->tagContent = trim($this->tagContent); if($this->tagName and $this->tagContent){ if(!$this->isTagContent){ array_push($this->tree, array($this->tagName, $this->tagContent)); $this->tagContent = ; $this->tagName = ; } } } public function getTagContent(){ $listNames = array(); forEach($this->tree as $value){ array_push($listNames, $value[1]); } return $listNames; } public function getTagNames(){ $listNames = array(); forEach($this->tree as $value){ array_push($listNames, $value[0]); } return $listNames; } public function readLine() { $this->handle = $this->getHandle(); $this->current_line = fgets($this->handle); while($this->current_line) { for ($i = 0; $i < $this->getLen(); $i++) { $char = $this->current_line[$i]; $this->scanCharacter($char, $i); } $this->getTag(); } return $this->tree; } public function goOverLine(){ }}$a = new ParseXML('../IMQ+AZIBPrototyp.xml');$a->openXMLFile($a->getFileName());$a->acquireHandler();$a->readLine();print_r($a->getTagContent());?>ReadXML.php<?phprequire('OpenXML.php');class ReadXML extends OpenXML{ var $content; var $line; public function acquireHandler() { $this->content = $this->getHandler(); } public function getHandle() { return $this->content; } public function isReadLine() { return feof($this->content); } public function getLine() { if(!($this->isReadLine())) { $this->line = fgets($this->content); return $this->line; } }}?> | XML parser using PHP | php;parsing;xml;phpunit | Good to see you are using PHPUnit as testing method :)Issuelist:Curly brackets are sometimes in same line as a method header and sometimes in the followingThere are both empty methods and methods that return always true/falseNot every method has a self-describing nameThere are global attributes with the access modifier publicThere are multiple returns in one methodClasses are included manuallyPHP-tags are closedRecommendationCurly brackets are sometimes in same line as a method header and sometimes in the followingFor the sake of a good code-reading and understanding code should be structured. Write curly brackets either in the same line as the method header or in the following.There are both empty methods and methods that return always trueParseXML::goOverLine(): When a method body is empty it usually means you have not implemented its logic yet. It is possible that one forget to include its logic but calls the method which can leads to a difficult to identify bug at a later time. Therefor I recommend to throw an Exception with message Method not implemented.ParseXML::tagContentOn(), ParseXML::tagNameOff(): Why does this method returns true/false anytime? Does it switches tags on/off?ParseXML::gatherTagName($char), ParseXML::gatherTagContent($char): These methods rather append, do they? Or does this word describes appending as well?Not every method has a self-describing nameParseXML::getLen(): What does it return? Object Length, Current Line Length, ...? I recommend to rename the method to what it does - getCurrentLineLength().There are global attributes with the access modifier publicAn object is responsible for its valditity. As of that its attributes has to be setted via setters always and the attributes has to have as access modifier either protected or private.There are multiple returns in one methodThis makes the code less maintainable. Having more than one return means there are multiple scenarios when the method can be stopped. In case of a bug one need to debug through the whole method to figure out the return-point.Classes are included manuallyInstead of including classes manually it is recommended to make usage of the autoloader function (http://php.net/manual/en/function.spl-autoload-register.php). The advantage is that you don't have to worry about including a class.PHP-tags are closedIt is not recommend to close the PHP-tag. It can happen that you have an empty space after the closed PHP-tag which leads to headers already sent error. Not closing them reduces headaches :) |
_softwareengineering.68662 | I have /src/main/ with all my code (i also have /src/online, /src/prvlibs, /src/test, etc) but now i am thinking about moving a few non active projects out of the folder. Sure i could go in and delete all objs, (some) project files, etc so it doesnt take 200mb of generated data. But i think it might be nice for only 20projects or less instead of dozen of prototypes that aren't throwaway test.I use git for source control (but i'm sure all scm do the same thing). They dislike files are missing and if i delete them they aren't easy to browse. I like how i can commit all of my source by going to /src/main and commiting. And i can push all of them just as easily. But moving folders (to my external HD and keep history) is the problem.Should i have every folder have its own repo? or is there some kind of workaround i can use? If every folder has its own repo is there an easy way to push all my folders to my HD (or website) for backup? | How should i set up my source folder? | version control;backups | You should not keep all your projects (not even the experiments) under the same version control repository. Yes, you should have one repository for each project.As to the pushing, write down a small process that you follow when you work on a project, include a push in it, and make provisions for backup.Private repositories in public GIT sites (like GitHub) are an easy way to backup to the cloud using a simple process.I'm paranoid about version control because I had really bad things happen when I wasn't. My process for an ongoing project is:Commit frequently.Push to central repository when a feature is complete or before taking a break.Backup working directory after a session.Backup central repository.Pull in working directories under other OSs or other workstations, test, fix, and repeat the above.Push to bitbucket. |
_unix.45826 | Suppose I have an image home.img of a home partition of another linux machine (B). On that machine there is a users userB and there is a special group, groupB. Consider for example a file fileB in the home partition of machine B. Suppose it is owned by userB and groupA.Now if I mount (via mount home.img /mnt/homeB -o ro) the img file on another linux machine A (logged in as userA), fileB is now owned by userA. Is it possible to modify the mount options such that the owner, groups and permissions are shown on machine A, as it would be shown directly on machine B (for example that fileB is owned by userB and not by userA)? Do I have to create a dummy userB and groupB on machine A? | Correct owner, group and permissions when mounting an image file | filesystems;permissions;mount;users | null |
_unix.60050 | My Linux version is Ubuntu:> cat /etc/lsb-releaseDISTRIB_ID=UbuntuDISTRIB_RELEASE=9.04DISTRIB_CODENAME=jauntyDISTRIB_DESCRIPTION=Ubuntu 9.04running as virtual machine.I did as said hereNow when I typesudo apt-get install google-chrome-stableI getReading package lists... DoneBuilding dependency treeReading state information... DoneSome packages could not be installed. This may mean that you haverequested an impossible situation or if you are using the unstabledistribution that some required packages have not yet been createdor been moved out of Incoming.The following information may help to resolve the situation:The following packages have unmet dependencies: google-chrome-stable: Depends: libasound2 (> 1.0.22) but 1.0.18-1ubuntu9 is to be installed Depends: libatk1.0-0 (>= 1.29.3) but 1.26.0-0ubuntu2 is to be installed Depends: libc6 (>= 2.11) but 2.9-4ubuntu6.3 is to be installed Depends: libcups2 (>= 1.4.0) but 1.3.9-17ubuntu3.9 is to be installed Depends: libdbus-1-3 (>= 1.2.14) but 1.2.12-0ubuntu2.1 is to be installed Depends: libfontconfig1 (>= 2.8.0) but 2.6.0-1ubuntu12 is to be installed Depends: libgconf2-4 (>= 2.27.0) but 2.26.0-0ubuntu1 is to be installed Depends: libgcrypt11 (>= 1.4.2) but 1.4.1-2ubuntu1 is to be installed Depends: libgtk2.0-0 (>= 2.18.0) but 2.16.1-0ubuntu2 is to be installed Depends: libstdc++6 (>= 4.4.0) but 4.3.3-5ubuntu4 is to be installed Depends: libudev0 (>= 147) but it is not going to be installedE: Broken packagesWhat does it mean? Why it doesn't install required packages automatically?My linux is Linux ubuntu3 2.6.24-19-xen #2 SMP Fri May 23 03:11:08 JST 2008 i686 GNU/LinuxUPDATEIf I use dpkg, I get apparently the same> sudo dpkg --install google-chrome-stable_current_i386.debSelecting previously deselected package google-chrome-stable.(Reading database ... 31919 files and directories currently installed.)Unpacking google-chrome-stable (from google-chrome-stable_current_i386.deb) ...dpkg: dependency problems prevent configuration of google-chrome-stable: google-chrome-stable depends on libasound2 (>> 1.0.22); however: Version of libasound2 on system is 1.0.18-1ubuntu9. google-chrome-stable depends on libatk1.0-0 (>= 1.29.3); however: Version of libatk1.0-0 on system is 1.26.0-0ubuntu2. google-chrome-stable depends on libc6 (>= 2.11); however: Version of libc6 on system is 2.9-4ubuntu6.3. google-chrome-stable depends on libcups2 (>= 1.4.0); however: Version of libcups2 on system is 1.3.9-17ubuntu3.9. google-chrome-stable depends on libdbus-1-3 (>= 1.2.14); however: Version of libdbus-1-3 on system is 1.2.12-0ubuntu2.1. google-chrome-stable depends on libfontconfig1 (>= 2.8.0); however: Version of libfontconfig1 on system is 2.6.0-1ubuntu12. google-chrome-stable depends on libgconf2-4 (>= 2.27.0); however: Version of libgconf2-4 on system is 2.26.0-0ubuntu1. google-chrome-stable depends on libgcrypt11 (>= 1.4.2); however: Version of libgcrypt11 on system is 1.4.1-2ubuntu1. google-chrome-stable depends on libgtk2.0-0 (>= 2.18.0); however: Version of libgtk2.0-0 on system is 2.16.1-0ubuntu2. google-chrome-stable depends on libstdc++6 (>= 4.4.0); however: Version of libstdc++6 on system is 4.3.3-5ubuntu4. google-chrome-stable depends on libudev0 (>= 147); however: Package libudev0 is not installed. google-chrome-stable depends on libxss1; however: Package libxss1 is not installed. google-chrome-stable depends on xdg-utils (>= 1.0.2); however: Package xdg-utils is not installed.dpkg: error processing google-chrome-stable (--install): dependency problems - leaving unconfiguredProcessing triggers for menu ...Processing triggers for man-db ...Errors were encountered while processing: google-chrome-stableUPDATE 2I don't want to participate in upgrading race. I have many machines and systems and if I would upgrade them all the times they want this, I would spent all my time upgrading. Also after upgrading, many components become uncompilable too. | How to install google chrome with apt-get? | apt;chrome | null |
_codereview.136402 | I get malformed HTML input with divs inside other HTML elements like the html_string variable in the below code. As this is not valid HTML, parsers give me unexpected results and it can't be used logically. I am trying to fix this HTML by reading it as an XML initially using BeautifulSoup and then re-positioning the div to the body element which is where it belongs in my case.Understanding that this is a valid XML but invalid HTML is one of the the keys to this solution. Can anyone review this code?This is used to fix page-break divs that come from a certain source and it is not a regular HTML.import bs4html_string = <html><head> <title></title></head><body> <p align=center> This is before. <div style=page-break-after:always> </div> This is after. </p></body></html>html_element = bs4.BeautifulSoup(html_string, features=xml)style = {'style': 'page-break-after:always'}page_break_elements = html_element.findAll('div', style)for page_break_element in page_break_elements: current = page_break_element while True: parent = current.parent if parent is None: break if parent.name == 'body': current.insert_before(page_break_element) break current = parent | Moving a div inside p by to the body element | python;html;parsing | null |
_unix.211744 | I wanted to find the source code of embedded Linux that is used in Shenzhen Apexis Electronic Co.,Ltd products.For example in this page: http://apexis.com.cn/productsdetails_244.htmlYou see they mentioned 'Embedded LINUX System' as the OS used in their product.I sent an email with this text to them:Source code of your Embedded LINUX SystemHi. As you should know linux is open source and under GPLv2 that says if anyone uses it he must release it under GPLv2 that means source code must be available to requestors. I saw that you use an Embedded LINUX System in your product in this page: http://apexis.com.cn/productsdetails_244.html I searched but could not find its the source code of your linux OS. Where can I find it?Thank you. Regards.But they replied:Hi ,Sir Sorry to us can not provide source code of the linux OS .Please Understand .I am not sure but recently some guy told me that, legally, Open source software like Linux kernel used in embedded systems need not to remain/be released as open source. But I think Linux is under GPLv2 that hasn't such an exception and is a copyleft license that doesn't let its use in proprietary software. It says the source code should be available to requestors.Can this be a violation of GPL? | Legal status of an embedded Linux case | linux kernel;embedded;free software;gpl;open source | null |
_unix.346833 | I have a reverse proxy setup in Debian 8.2 (Jessie) with Apache 2.4.10-10+deb8u where I have two separate virtual hosts, one for http and another for https, based on the following config:<IfDefine IgnoreBlockComment><VirtualHost *:80>CustomLog /tmp/just_size.log just_size DocumentRoot /var/www/ ServerName XXXXXXXXXX TraceEnable off RewriteEngine On RewriteCond %{REQUEST_METHOD} ^TRACE RewriteRule .* - [F] ExpiresActive On ExpiresByType image/gif access plus 1 year ExpiresByType image/jpeg access plus 1 year ExpiresByType image/png access plus 1 year ExpiresByType audio/mpeg access plus 1 year ExpiresByType video/mpeg access plus 1 year ExpiresByType text/html modification plus 5 minutes CustomLog /dev/null combined env=!no-registrar ProxyPreserveHost On CustomLog /tmp/non_https.log non_https ProxyPass /telemetria-ws/ http://10.1.0.116:8080/telemetria-ws/ ProxyPassReverse /telemetria-ws/ http://10.1.0.116:8080/telemetria-ws/ ProxyTimeout 1200 ProxyPass /ecobox-ws/ http://10.1.0.116:8080/ecobox-ws/ ProxyPassReverse /ecobox-ws/ http://10.1.0.116:8080/ecobox-ws/ ProxyPass / http://10.1.0.116:8080/WebService/ connectiontimeout=300 timeout=300 KeepAlive=On retry=1 acquire=3000 ProxyPassReverse / http://10.1.0.116:8080/WebService/ ProxySet http://10.1.0.116:8080/WebService/ connectiontimeout=300 timeout=300 FileETag MTime Size Header append X-Frame-Options DENY</VirtualHost></IfDefine><VirtualHost *:443>CustomLog /tmp/just_size.log just_size ServerName XXXXXXX DocumentRoot /var/www DirectoryIndex index.php index.html TraceEnable off RewriteEngine On RewriteCond %{REQUEST_METHOD} ^TRACE RewriteRule .* - [F] #RequestHeader set Front-End-Https On CustomLog /dev/null combined env=!no-registrar ProxyPreserveHost On RequestHeader set x-forwarded-server https://XXXXXXX/ RequestHeader set x-forwarded-host https://XXXXXXX/ SSLEngine On SSLCertificateKeyFile /etc/apache2/ssl/cert.key SSLCertificateFile /etc/apache2/ssl/cert.crt SSLCertificateChainFile /etc/apache2/ssl/gd_bundle-g2-g1.crt ProxyPass /telemetria-ws/ http://10.1.0.116:8080/telemetria-ws/ ProxyPassReverse /telemetria-ws/ http://10.1.0.116:8080/telemetria-ws/ ProxyTimeout 1200 ProxyPass /TrackViewRealTime/ http://10.1.0.235:8080/TrackViewRealTime/ ProxyPassReverse /TrackViewRealTime/ http://10.1.0.235:8080/TrackViewRealTime/ ProxyPass /TrackViewLogin/ http://10.1.0.235:8080/TrackViewLogin/ ProxyPassReverse /TrackViewLogin/ http://10.1.0.235:8080/TrackViewLogin/ ProxyPass /TrackViewData/ http://10.1.0.235:8080/TrackViewData/ ProxyPassReverse /TrackViewData/ http://10.1.0.235:8080/TrackViewData/ ProxyPass /ecobox-ws/ http://10.1.0.116:8080/ecobox-ws/ ProxyPassReverse /ecobox-ws/ http://10.1.0.116:8080/ecobox-ws/ ProxyPass /puerto-coronel-ws/ http://10.1.0.116:8080/puerto-coronel-ws/ ProxyPassReverse /puerto-coronel-ws/ http://10.1.0.116:8080/puerto-coronel-ws/ProxyPass / http://10.1.0.116:8080/WebService/ connectiontimeout=300 timeout=300 KeepAlive=On retry=1 acquire=3000 ProxyPassReverse / http://10.1.0.116:8080/WebService/ ProxySet http://10.1.0.116:8080/WebService/ connectiontimeout=300 timeout=300 FileETag MTime Size Header append X-Frame-Options DENY</VirtualHost>I have several web services (and their WSDL) exposed from the internal IP 10.1.0.116 as you may see in the Proxy* config directives, the problem is that I haven't been able to redirect incoming plain http traffic into those web services, and they are only working using https, so I guess there must be something wrong with my VirtualHost config at port 80.Even stranger is that when the request URL is like:http://HOST/telemetria-ws/frioChileTempService/I do get a response*, but an empty one with the following Response headers: *Response seems to be HTTPS as valid certificates appear in the SOAP-UI SSL InfoBut when I add the port 80 to the URL (which should be the same as above):http://HOST:80/telemetria-ws/frioChileTempService/The server interprets it as SSL but using a plaintext connection:Wed Feb 22 10:52:21 ART 2017:ERROR:javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?Where can I be having the mismatched config? The desired would be to redirect plain http to https, but don't exactly understand what could be happening. | Apache http vs https reverse proxy mismatch | debian;apache httpd;http;https;reverse proxy | null |
_unix.66642 | Currently I have these installed on my Scientific Linux 6.3: [root@localhost ~]# rpm -qa | egrep -i 'java|jre'java-1.7.0-openjdk-1.7.0.9-2.3.7.1.el6_3.x86_64java-1.6.0-openjdk-1.6.0.0-1.56.1.11.8.el6_3.x86_64tzdata-java-2012j-1.el6.noarch[root@localhost ~]# Do I need to remove then to be safe from the recent Java vulnerabilities? (If I try to remove the java-1.6.0-openjdk.. then it wants to remove libreoffice too..)Or the vulnerabilities are just related to java webbrowser plugins? | Do I need to remove all java|jre packages from my system to be secure from java vulnerabilities? | security;java | Yes, most vulnerabilities are related to the webbrowser-plugin. In most (all?) cases you must (actively) execute malicious java-code that exploits these weaknesses.From the perspective of an attacker this is most easily done by putting that code into the web and luring you onto it, so you execute that code.A more subtle approach might be to upload some java code into your application and have it execute that code (by exploiting other weaknesses like code-injections).So if you have neither a running, externally exposed application that can execute code, nor have a browser installed, you should be pretty safe. |
_softwareengineering.247209 | In most popular programming languages like Java and C# there is a way to define enums, which are essentially datatypes with a fixed set of values, e.g. DayOfWeek.The problem is, given a value, e.g. DayOfWeek.Monday, how do I get the next value of the enum, in this particular case DayOfWeek.Tuesday?I realize that not all enums are ordered and there might be different kinds of orders for them (cyclic, partial etc.), but a simple next operation would be sufficient in most cases. In fact, since the set of values in a enum is fixed and limited, this could be done completely declaratively, assuming there is a means in the language to do so. However in most programming languages that is simply not possible, at least not as easily as it could be in theory.So, my question is: why is that so? What are the reasons for not providing a simple syntax for declaring the next value for a enum? I suggest, in C# or Java this could even be done with a special attribute or annotation, resp. But there are none, as far as I know.I am explicitly not asking for workarounds; I know that there are alternative solutions. I just want to know why I have to employ a workaround in the first place. | Why isn't there a next operation on enums? | programming languages;language design;syntax;data types;enum | Why isn't there a next operation on enums?It is difficult to generalize.It is an decision made by each programming language designer / team. But note that some programming languages do provide a next operation for enumerated types. In Pascal, the succ function returns the next value of an enumerated type, and the pred function returns the previous value. But this only works for classic enumerated types. C-style enumerated types have holes in the type domain, and the succ and pred functions are not allowed.Reference: http://www.freepascal.org/docs-html/ref/refse12.html#QQ2-27-32And, in fact, that gives a clue as to why many languages with enumeration / enumerated types don't have a next operation. It is prohibitively expensive when you can't implement next by using integer addition under the hood.Of course, in the languages that don't support next directly, it is always possible to implement it for yourself ... if you need it ... as some kind of helper method / function. |
_softwareengineering.27240 | I have this question since my friend told me that if we have frequent appraisal such as 4 months or 6 months once, people will be turned to a money minded.But I am thinking this in another aspect like, people will be getting feedback and boost quickly than one year appraisal. We do not need to increase the salary much. But the token advancement would help them to get some refreshment. | how often do we need to do appraisal for a developer? | management | After being in management for a few years after being a developer for many years (and headed back TO development), I believe that regular, non-formal appraisal is important. Not everyone needs this, but human nature dictates that saving this for once or twice per year is detrimental. Everyone needs regular feedback, not only for motivational purposes, but just to help keep someone from straying too far off the path. No one likes being kept in the dark on the value they're perceived to add (or improvements they need to make). |
_webmaster.16288 | Possible Duplicate:What are the best ways to increase your site's position in Google? I have developed my website few months ago and I added meta tags and described everything as much as I could but my site is still not on the top when I search kashif ejaz on google. Please help ! | How can I bring my website up in the google search result? | seo;google;search | null |
_codereview.157108 | I have two sets of toggles that need to uncheck each other. This is my current solution which is working. Can it somehow get more functional/elegant?let unscheduledLayerToggles = [unscheduledLayerToggle, unscheduledLayerToggleToolbar];let availableLayerToggles = [availableLayerToggle, availableLayerToggleToolbar];flipToggles(firstToggles, secondToggles)flipToggles(secondToggles, firstToggles)function flipToggles(firstToggles, secondToggles) { firstToggles.forEach(function (toggle) { on(toggle, change, function () { secondToggles.forEach(function(element) { element.checked = false }) }) })} | Functional way to have two toggles that turn each other off | javascript;functional programming;dom;ecmascript 6 | The logic itself is simple enough. I see that you are using ECMAScript 6, with it there are some things you could do to simplify the code and make it more robust.constYou are using let for unscheduledLayerToggles and availableLayerToggles, which is fine, but in the case that you will not be reassigning different values/arrays to those names, you could simply use const instead of let. Note that this will not make the arrays immutable, so you can still manipulate their contents, it only disallows assigning something different to them.flipToggles functionIn the same manner as you can use const to declare function (in the style of var foo = function () { ... }). It helps to make the intentions clear that the function will not change.Arrow functionsES6 provides a great way to both shorten/simplify function declarations, as well as isolate their scope better: Arrow Functions. The syntax is explained well on MDN like I provided. In the case of your flipToggles function, we could write the code this way and eliminate all the unnecessary function() declarations.const unscheduledLayerToggles = [unscheduledLayerToggle, unscheduledLayerToggleToolbar];const availableLayerToggles = [availableLayerToggle, availableLayerToggleToolbar];flipToggles(firstToggles, secondToggles)flipToggles(secondToggles, firstToggles)const flipToggles = (firstToggles, secondToggles) => { firstToggles.forEach(toggle => { on(toggle, change, () => { secondToggles.forEach(element => { element.checked = false }) }) })}(mind the indentation, which is a personal preference of mine for 2 spaces indent instead of 4) |
_unix.383400 | I am a beginner in shell scripting. I wanted to know how do we grep for say two strings with AND condition within a block if the strings don't appear on the same line. I tried the following but they do not work for strings not in the same line:-grep 'string1.*string2\|string2.*string1' filenamegrep -P '^(?=.*pattern1)(?=.*pattern2)' filenameFor example I have an xml file with the following lines:- <test-result exectime=2017-07-07 result=FAILURE isdone=TRUE logicalname=this.is.test1 duration=10050 > <test-case testcasename=this.is.test.case.name1 testunit=abcd-mc testpath=file:/this/is/the/file/path1/abcd.xml > </test-case> </test-result> <test-result exectime=2017-07-07 result=SUCCESS isdone=TRUE logicalname=this.is.test1 duration=10050 > <test-case testcasename=this.is.test.case.name1 testunit=abcd-mc testpath=file:/this/is/the/file/path1/uvwx.xml > </test-case> </test-result>Note that the 2 blocks of code within <test-result></test-result> tags differ in case of the testpath. So, I want to grep for the logicalname and the result (grep this.is.test1 AND FAILURE) and find the respective testpath for the same block.Next, once I have the testpath for the FAILURE scenario, how can I modify the file to make the result to SUCCESS for the block with the testpath that I found and the logicalname? Any pointers on how to go about it will be helpful | How to grep for 2 strings (AND condition) within a block which are not in the same line and then find something else within that same block | text processing | With having note that Parsing XML is bad practice, here is an awk solution for your question : )awk -v RS=<test-result ' /logicalname=this\.is\.test1/&&/result=FAILURE/ { sub(FAILURE,SUCCESS)}1' RS='' infile.txtAt above, we are telling awk that Record Seperator RS is <test-result, then for each record will look the both PATTERNs (logicalname=this.is.test1 and result=FAILURE), if it was there (within a same block) then change FAILURE to SUCCESS from given infile.txtAs we talked in comments since you want to change specific block with testpath=...., you can add another 3rd condition to the command only. below will change only if testpath=file:/this/is/the/file/path1/abcd.xml also seen.note that you need to escape /, and better to escape .s as well.awk -v RS=<test-result ' /logicalname=this\.is\.test1/&&/result=FAILURE/&&/testpath=file:\/this\/is\/the\/file\/path1\/abcd\.xml/ {sub(FAILURE,SUCCESS)}1' RS='' infile.txt |
_unix.381732 | I cloned Lucene++ from the following repository https://github.com/luceneplusplus/LucenePlusPlus, executed cmake then make and got the following error[ 66%] Linking CXX executable indexfiles../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::zlib::finish'../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::zlib::mem_error'../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::zlib::no_flush'../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::detail::zlib_base::xdeflate(int)'../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::detail::zlib_base::before(char const*&, char const*, char*&, char*)' ../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::zlib_error::check(int)' ../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::zlib::default_compression' ../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::detail::zlib_base::do_init(boost::iostreams::zlib_params const&, bool, void* (*)(void*, unsigned int, unsigned int), void (*)(void*, void*), void*)'../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::zlib::stream_end'../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::detail::zlib_base::zlib_base()'../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::detail::zlib_base::~zlib_base()'../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::detail::zlib_base::after(char const*&, char*&, bool)'../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::zlib::default_strategy'../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::zlib::okay'../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::zlib::data_error'../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::zlib::buf_error'../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::zlib::stream_error'../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::detail::zlib_base::reset(bool, bool)'../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::zlib::sync_flush'../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::zlib::version_error'../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::detail::zlib_base::xinflate(int)'../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::zlib::best_compression'../core/liblucene++.so.3.0.7: undefined reference to `boost::iostreams::zlib::deflated'collect2: error: ld returned 1 exit statussrc/demo/CMakeFiles/indexfiles.dir/build.make:108: recipe for target 'src/demo/indexfiles' failedmake[2]: *** [src/demo/indexfiles] Error 1CMakeFiles/Makefile2:466: recipe for target 'src/demo/CMakeFiles/indexfiles.dir/all' failedmake[1]: *** [src/demo/CMakeFiles/indexfiles.dir/all] Error 2Makefile:138: recipe for target 'all' failedmake: *** [all] Error 2I think the problem is with boost library, but I really have no idea what it is exactly. My system is Lubuntu 16.04. | Getting error while installing Lucene++ | make;lubuntu | null |
_unix.318104 | i have Huge list like 67603;4716-5469-1335-0870;5450-7938-7992-5530;14523593;03 Oct 2016 - 17:01:1563123;5592-6762-4853-6320;4532-4142-5613-9690;1441407;03 Oct 2016 - 17:01:1562562;4532-5581-3790-0140;5292-4905-4356-2840;28898987;03 Oct 2016 - 17:01:1568080;5188-1564-9611-7580;4556-9998-5999-3300;2262361;03 Oct 2016 - 17:01:15i Want Search more Dublicate number after 2 ; and before 3th ;for first line the number is 5450-7938-7992-5530 and another line 4532-4142-5613-9690 and etc | Find More Duplicate | sed;awk;grep | Creating few duplicate value in stack.txt file and then printing output - 67603;4716-5469-1335-0870;5450-7938-7992-5530;14523593;03 Oct 2016 - 17:01:1563123;5592-6762-4853-6320;4532-4142-5613-9690;1441407;03 Oct 2016 - 17:01:1562562;4532-5581-3790-0140;5292-4905-4356-2840;28898987;03 Oct 2016 - 17:01:1568080;5188-1564-9611-7580;4556-9998-5999-3300;2262361;03 Oct 2016 - 17:01:1567603;4716-5469-1335-0870;5450-7938-7992-5530;14523593;03 Oct 2016 - 17:01:1563123;5592-6762-4853-6320;4532-4142-5613-9690;1441407;03 Oct 2016 - 17:01:1562562;4532-5581-3790-0140;5292-4905-4356-2840;28898987;03 Oct 2016 - 17:01:1568080;5188-1564-9611-7580;4556-9998-5999-3300;2262361;03 Oct 2016 - 17:01:1567603;4716-5469-1335-0870;5450-7938-7992-5530;14523593;03 Oct 2016 - 17:01:1563123;5592-6762-4853-6320;4532-4142-5613-9690;1441407;03 Oct 2016 - 17:01:15Use below command - awk 'BEGIN{FS=;}{a[$3]++} END {for(k in a) print a[k],k}' stack.txtOutput - 3 4532-4142-5613-96902 5292-4905-4356-28403 5450-7938-7992-55302 4556-9998-5999-3300 |
_cstheory.36593 | Input: a bunch of binary strings: x_0, x_1, ... , x_nOutput: a binary string y that minimizes edit(x_0, y) + edit(x_1, y) + ... edit(x_n, y) where edit(x, y) denotes the levenshtein distance, i.e. the minimum number of insertions, deletions, and substitutions to transform x into y.What complexity class is this problem in? Does it have an efficient exact or approximation algorithm? | Find a string with minimal edit distance from a set of given strings | cc.complexity theory;ds.algorithms;search problem;edit distance | Your problem is called the Median string problem. Nicolas and Rivals proved that the Median String problem (under the Levenshtein distance) is NP-complete even for binary strings. |
_unix.90020 | I am working on passing through the internet from my computer to my phone (running Android) over USB. I'm not sure how to achieve this, but I know I will need a usb network interface, such as usb0. This interface is not automatically created when plugging in the phone.How do I create this USB network interface? Can this be done within Linux or must it be done from the Android phone?Note: If I enable USB tethering on the phone, then a corresponding USB interface is created in Linux. However this is automatically configured to use the phone as a network device (or a gateway?) and pass the internet from my phone to my computer, which is the opposite of what I'm trying to do. | How do I create a USB networking interface for passing internet to my Android phone? | networking;usb;android | null |
_softwareengineering.269506 | As a mid-level developer on my team, I participate in requirements gathering/scope planning meetings of projects that I will be part of. I have been finding it difficult to come up with the questions that add value to the discussion or to my knowledge. After some self analysis, I found that knowing that there is a senior engineer in charge of the project who would lead the discussion, has caused me to be laid back in some of these discussions. But I do want to get to a point where I am entrusted with more responsibility and gain skills to handle projects on my own. Though mindset is a bit abstract term to ask about, I would like to get some advice on few things listed below:What kind of preparation will I need to gain most out of these meetings. From observations from team members, I noticed that understanding what all systems that the project is going to impact, What business decisions will majorly impact the project design etc. are some of them.Do I need to avoid thinking about low level implementation details for every requirement. On one hand, I feel it's important to consider them because I will know about the feasibility but I also understand it hinders considering all choices.Finally, as a developer, what is something that I should not be worried about? | What is the ideal mindset for a developer participating in a requirements gathering meeting? | requirements;communication | Answering your questions in order:The mindset going into this in terms of preparation, is to ask the right questions so that the user knows exactly what they want. This is much more difficult than it seems. I need to emphasize asking the right questions. Be specific, if there is any ambiguity, ask another question. Usually during these meetings one answer from the client spawns 3 new questions. Once you know what they want, then it is your job to figure out how it impacts the different systems, not theirs.If there is anything that the client wants in terms of requirements that are impossible, then tell them (my professors used to call it wings on a car). Sometimes clients just don't know software well enough to know the capabilities. Work around that.No, that comes during the design phase. If it can't work, the requirements are revisited.Don't worry about getting it right the first time, because you most definitely won't. Requirements get screwed up all the time by feature creep, clients wanting new things but never telling you, etc. Over prepare then go with the flow. |
_unix.39817 | I often run into the case where I'm working inside a Python virtualenv, and I want to run an executable Python program (e.g., bpython). I run it, forgetting that I have not installed it in my virtualenv so it won't do the right thing. Then, I install bpython in my virtualenv, but if I try to run the new version, bash remembers the old one and calls it instead. To be more concrete:(venv)$ bpython (whoops, system-level bpython!)(venv)$ which bpython/usr/local/bin/bpython(venv)$ type bpythonbpython is hashed (/usr/local/bin/bpython)(venv)$ pip install bpython (venv)$ which bpython/Users/lorin/.virtualenvs/venv/bin/bpython(venv)$ type bpythonbpython is hashed (/usr/local/bin/bpython)How do I tell the bash prompt to forget that the location of bpython is /usr/local/bin/bpython for that session? | Forget a hashed executable location in bash interactive shell | bash | You can tell bash to rehash:hash -r |
_cs.13608 | According to CLRS, the Prim's algorithms is implemented as below -- $\mathtt{\text{MST-PRIM}}(G,w,r)$ for each $u \in V[G]$ do$\mathtt{\text{key}}[u] \leftarrow \infty$ $\pi[u] \leftarrow \mathtt{\text{NIL}}$ $\mathtt{\text{key}}[r] \leftarrow 0$ $Q \leftarrow V[G]$ while $Q \ne \emptyset$ do // ... $O(V)$ $u$ $\leftarrow$ $\mathtt{\text{EXTRACT-MIN}}(u)$ // ... $O(\lg V)$for each $v \in \mathtt{\text{adj}}[u]$ do // ... $O(E)$if $v \in Q$ and $w(u,v) \gt \mathtt{\text{key}}[v]$ then $\pi[v] \leftarrow u$ $\mathtt{\text{key}} \leftarrow w(u,v)$ // $\mathtt{\text{DECREASE-KEY}}$ ... $O(\lg V)$The book says the total complexity is $O(V \lg V + E \lg V) \approx O(E \lg V)$. However, what I understood is that the inner for loop with the DECREASE-KEY operation will cost $O(E \lg V)$, and the outer while loop encloses both the EXTRACT-MIN and the inner for loop, so the total complexity should be $O(V (\lg V + E \lg V)) = O(V \lg V + EV \lg V) \approx O(EV \lg V)$. Why the complexity analysis is not performed as such? and What is wrong with my formulation? | MST: Prim's algorithm complexity, why not $O(EV \lg V)$? | algorithms;algorithm analysis;spanning trees | The complexity is derived as follows. The initialization phase costs $O(V)$. The $while$ loop is executed $\left| V \right|$ times. The $for$ loop nested within the $while$ loop is executed $degree(u)$ times. Finally, the handshaking lemma implies that there are $\Theta(E)$ implicit DECREASE-KEYs. Therefore, the complexity is: $\Theta(V)* T_{EXTRACT-MIN} + \Theta(E) * T_{DECREASE-KEY}$.The actual complexity depends on the data structure actually used in the algorithm. Using an array, $T_{EXTRACT-MIN} = O(V), T_{DECREASE-KEY} = O(1)$, complexity is $O(V^2)$ in the worst case.Using a binary heap, $T_{EXTRACT-MIN} = O(\log V), T_{DECREASE-KEY} = O(\log V)$, complexity is $O(E \log V)$ in the worst case. Here is why: since $E$ is at most $V^2$, then $\log E$ is at most $2 \log V$. Probably, you missed this point. Using a Fibonacci Heap, $T_{EXTRACT-MIN} = O(\log V)$ amortized, $T_{DECREASE-KEY} = O(1)$ amortized, complexity is $O(E + V \log V)$ in the worst case. |
_cstheory.37180 | Say that a node of a circuit is small if it has fan-in at most 2 and large if it has fan-in greater than 2. The weft of a circuit is the maximum number large nodes in any path from an input node to an output node. Let $C_{t,d}$ be the class of circuits of weft at most $t$ and depth at most $d$. The notion of weft is used fundamentally in parameterized complexity theory to define the W hierarchy. Namely, a parameterized problem P belongs to $W[t]$ if there is a parameterized reduction from P to $WCS[C_{t,d}]$ for some $d>1$, where $WCS[C_{t,d}]$ is the problem of determining whether a circuit in $C_{t,d}$ has a satisfying assignment of Hamming weigth exactly $k$. I'm interested in circuits in which only OR gates are allowed to be large. More precisely, say that a circuit $C$ has OR-weft at most $t$ if the following conditions are satisfied. All negation gates are in the bottom layer. $C$ has weft at most $t$.All AND gates have fan-in $2$. Let $D_{t,d}$ be the class of circuits of depth at most $d$ and OR-weft at most $t$. Say that a problem $P$ belongs to OR-$W[t]$ if there is a parameterized reduction from $P$ to $WCS[D_{t,d}]$ for some $d$. Questions: Has some notion similar to the OR-Weft hierarchy been studied in parameterized complexity theory? What kind of functions can be computed by circuits of constantOR-weft? | OR-weft Hierarchy | circuit complexity;parameterized complexity;circuit families;circuit depth | First of all: your definition of $WCS[C_{t,d}]$ does not match the usual one. The common definition asks for a satisfying assignment of Hamming weight exactly $k$, rather than at most $k$, and this can make an important difference. However, regardless of whether you want at most, or exactly, Hamming weight $k$, the weighted circuit-sat problem for constant-depth circuits of constant OR-weft is polynomial-time computable. Here's why.Consider a circuit of weft at most $c$, depth at most $d$, in which the negations are at the bottom and the AND-gates have constant fan-in. Starting at the bottom of the circuit, we will compute for each gate the set of minimal partial assignments that cause the gate to evaluate to true. By 'minimal partial satisfying assignment for gate g' I mean the following: a partial assignment of some input variables to true and false, so that any way of extending the partial assignment to a complete assignment satisfies gate $g$; and if any variable is removed from the partial assignment, then there is an extension that causes the gate to evaluate to false.The main idea is that in the given type of circuit, for each gate we can give a polynomial-sized description of the set of its minimal satisfying assignments. By computing these bottom-up, we find a description of the minimal satisfying assignments of the output gate, from which we deduce the answer.For a negation gate $g$ with input variable $x_i$, its only minimal satisfying assignment is $x_i \to 0$.For an OR-gate $g$ with inputs $g_1, \ldots, g_m$, take the union of the sets of satisfying assignments for its input gates, and then prune the list to make it minimal. That is: if resulting union contains two partial assignments where one is a sub-assignment of the other (assigns values to a strict subset of the variables, and agrees with the other on values it gives to those variables) then remove the larger assignment from the list.For an AND-gate $g$ with two inputs $g_1, g_2$, to satisfy it one needs to satisfy both $g_1$ and $g_2$. So for any combination of a minimal satisfying assignment for $g_1$ and a minimal satisfying assignment for $g_2$ such that these do not give any contradictory assignments, the combined assignment satisfies the AND-gate $g$. Compute all combined non-contradictory assignments by choosing a minimal satisfying assignment for $g_1$ and one for $g_2$, and then prune the resulting list to make it minimal as in the OR-case.After computing the list of minimal satisfying partial assignments for the output gate, the answer to the weighted circuit sat problem can easily be read off. If there is a partial assignment that causes the output gate to be satisfied and that assigns values to at most $k$ variables, then there is a satisfying assignment of Hamming weight $k$; just set additional variables to true until reaching an assignment of weight exactly $k$. By the definition of partial satisfying assignment, this does not change the output gate's answer.The main point is then to analyze the runtime of the procedure when applied to a circuit of depth $d$ with $n$ gates. The runtime depends on the sizes of the sets of partial assignments, i.e., the number of different minimal partial satisfying assignments for each gate. The minimal satisfying assignments for the input gates have size 1. The set for an OR-gate has size at most $n$ times the size of sets one level lower. The sets for an AND-gate have size at most quadratic in the size of the sets one level lower. So we get a recurrence.Let $S(d)$ denote the maximum number of minimal partial satisfying assignments for a gate at depth $d$. Then $S(0) = 1$ and $S(d) \leq \max(n \cdot S(d-1), S(d-1)^2)$. It follows that $S(d) \leq n^{O(2^d)}$, so that for constant depth the sizes of the sets remains polynomial. Hence the algorithm runs in polynomial time. |
_cs.37257 | I'm working on a dependency managemen solution for a JavaScript. I'm trying to find the best pattern for grouping similar items in a graph into their own 'modules'.Given a dependency tree like shown below, I have a 'main' module ( app ), that has 5 children ( login, dashboard, form, builder, users ). These children might share some common deps amongst them.I'd like to create a function that would find the commons and group them upwards or in some cases where the overlap would out weight the benefit, creating a new module between them.In a perfect world, would create a graph like this. Obviously given a big enough tree, it could over-optimize creating too many child trees so probably stopping at level-3 would be ideal.In this example: d1 was shared 90% of the time, lets move it into the main module. d6 was used in 3 of the 5 modules, lets create a separate module for that combo. - d5 was used in 2 of the 5 modules, lets create a separate module for that combination.d3 was used in 2 of the 5 modules, lets create a separate module for that combo. | Finding and Grouping like children | graphs;search algorithms;search trees | null |
_codereview.36394 | The following is a program that lets a Human play Rock Paper Scissors Lizard Spock against the computer... (almost playable at: http://ideone.com/EBDlga)Note I have posted a follow-up question incorporating the suggestions that have been made in answers and comments on this question.Comments, critiques, suggestions are welcome and encouraged.import java.util.Arrays;import java.util.Random;import java.util.Scanner;/** * Rock Paper Scissors Lizard Spock * <p> * http://en.wikipedia.org/wiki/Rock-paper-scissors-lizard-Spock * <p> * Interface for a human to play against the computer. */public class RPSLS { /** * Set up the rules for the game. * What are the moves, and what beats what! */ public enum Move { Rock, Paper, Scissors, Lizard, Spock; static { Rock.willBeat(Scissors, Lizard); Paper.willBeat(Rock,Spock); Scissors.willBeat(Paper, Lizard); Lizard.willBeat(Spock,Paper); Spock.willBeat(Rock,Scissors); } // what will this move beat - populated in static initializer private Move[] ibeat; private void willBeat(Move...moves) { ibeat = moves; } /** * Return true if this Move will beat the supplied move * @param move the move we hope to beat * @return true if we beat that move. */ public boolean beats(Move move) { // use binary search in case someone wants to set up crazy rules. return Arrays.binarySearch(ibeat, move) >= 0; } } // This is a prompt that is set up just once per JVM private static final String MOVEPROMPT = buildOptions(); private static String buildOptions() { StringBuilder sb = new StringBuilder(); sb.append( -> ); // go through the possible moves, and make a prompt string. for (Move m : Move.values()) { sb.append(m.ordinal() + 1).append() ).append(m.name()).append( ); } // include a quit option. sb.append( q) Quit); return sb.toString(); } /** * get some input from the human. * @param scanner What we read the input from. * @param prompt What we prompt the user for. * @param defval If the user just presses enter, what do we return. * @return the value the user entered (just the first char of it). */ private static final char prompt(Scanner scanner, String prompt, char defval) { // prompt the user. System.out.print(prompt + : ); // it would be nice to use a Console or something, but running from Eclipse there isn't one. String input = scanner.nextLine(); if (input.isEmpty()) { return defval; } return input.charAt(0); } /** * Simple conditional that prompts the user to play again, and returns true if we should. * @param scanner the scanner to get the input from * @return true if the user wants to continue. */ private static boolean playAgain(Scanner scanner) { return ('n' != prompt(scanner, \nPlay Again (y/n)?, 'y')); } /** * Prompt the user for a move. * @param scanner The scanner to get the move from * @return the move the user wants to do. */ private static Move getHumanMove(Scanner scanner) { // loop until we get some valid input. do { char val = prompt(scanner, MOVEPROMPT, 'q'); if ('q' == val) { // user does not want to make a move... or just presses enter too fast. return null; } int num = (val - '0') - 1; if (num >= 0 && num < Move.values().length) { // we got valid input. Return. return Move.values()[num]; } System.out.println(Invalid move + val); } while (true); } /** * Run the game.... Good Luck! * @param args these are ignored. */ public static void main(String[] args) { final Random rand = new Random(); final Move[] moves = Move.values(); final Scanner scanner = new Scanner(System.in); int htotal = 0; int ctotal = 0; do { System.out.println(\nBest of 3.... Go!); int hscore = 0; int cscore = 0; bestofthree: do { final Move computer = moves[rand.nextInt(moves.length)]; final Move human = getHumanMove(scanner); if (human == null) { System.out.println(Human quits Best-of-3...); // quit the best-of-three loop break bestofthree; } if (human == computer) { System.out.printf( DRAW... play again!! (%s same as %s)\n, human, computer); } else if (human.beats(computer)) { hscore++; System.out.printf( HUMAN beats Computer (%s beats %s)\n, human, computer); } else { cscore++; System.out.printf( COMPUTER beats Human (%s beats %s)\n, computer, human); } // play until someone scores 2.... } while (hscore != 2 && cscore != 2); // track the total scores. if (hscore == 2) { htotal++; } else { // perhaps the human quit while ahead, computer wins that too. ctotal++; } String winner = hscore == 2 ? Human : Computer; System.out.printf(\n %s\n **** %s wins Best-Of-Three (Human=%d, Computer=%d - game total is Human=%d Computer=%d)\n, winner.toUpperCase(), winner, hscore, cscore, htotal, ctotal); // Shall we play again? } while (playAgain(scanner)); System.out.printf(Thank you for playing. The final game score was Human=%d and Computer=%d\n, htotal, ctotal); }} | Rock Paper Scissors Lizard Spock as a code-style and challenge | java;game;community challenge;rock paper scissors | You seem to like static things, but this gives me a feeling that your code is more procedural-oriented than object-oriented.Although not an issue in your actual implementation, I think willBeat should call Arrays.copyOf to create a copy of the input. If you would call someMove.willBeat(someArray) and then later change the indexes in someArray, you would change the rules of the game.The documentation of Arrays.binarySearch states:The array must be sorted (as by the sort(byte[]) method) prior to making this call. If it is not sorted, the results are undefinedYour code does not guarantee that the items are sorted. (It might work correctly anyway since your arrays only contains two items, but it still feels wrong) The values for Lizard are not sorted in the same way the others are.You are using htotal and ctotal, hscore and cscore, Move computer and Move human. Assuming htotal stands for Human Total, player classes would be useful here.2 and 3 are very Magic numbers.The variable names htotal and hscore is a bit confusing.Your main method is quite long and does a lot of things. Some of these things could be extracted into other methods/objects. Your main method currently is responsible for:Keeping scoreKeeping score (of a single best of three)Randomize a computer moveDetermine who wins a gameI like your playAgain method and the way you are handling user input-output.Overall, your code is not very abstracted. It seems to work, and it seems to do it's job well though. |
_unix.50228 | I have CP210x Composite Device. This device is USB-to-RS232 converter. When I plug it into Ubuntu-11.10, module named cp210x get inserted but I don't know why it did not create usb0 network device ( which is the desired result ).Does anyone knows, what is the process to make it work ?lsusbBus 004 Device 005: ID 10c4:ea60 Cygnal Integrated Products, Inc. CP210x Composite Device | Usb-ethernet device | linux;networking | null |
_unix.97860 | I'm using a legacy system and I'm stuck with FreeBSD 5.4 and Samba 2.2.12, trying to access it from a Windows 7 system.I've created a unix account in FreeBSD using the adduser command and added myself to a group that allows read write access to a shared location. I then created a Samba account for myself using the smbpasswd -a <user> command.When I map a network drive to this account under Win 7, I check the Connect using different credentials option in the Map Network Drive dialog and provide the Samba username and password to the password challenge. The system accepts it and maps the drive to my account.When I follow the above procedure to create another user however, every time I provide the account name and password, it rejects the credentials and comes back with another password challenge dialog and won't map to the drive. I've run through the procedure several times and I'm pretty sure that the username and password are correct.I'm not sure why it is doing this and I was wondering if somehow my Windows 7 login is influencing my Samba account. It is a bit odd if it does, because besides my full name being associated with the accounts, the unix/samba account has a different username from my Windows account.The content of smb.conf is detailed below, with some changes here and there to retain anonymity.# This is the main Samba configuration file. You should read the# smb.conf(5) manual page in order to understand the options listed# here. Samba has a huge number of configurable options (perhaps too# many!) most of which are not shown in this example## Any line which starts with a ; (semi-colon) or a # (hash) # is a comment and is ignored. In this example we will use a ## for commentry and a ; for parts of the config file that you# may wish to enable## NOTE: Whenever you modify this file you should run the command testparm# to check that you have not many any basic syntactic errors. ##======================= Global Settings =====================================[global]# workgroup = NT-Domain-Name or Workgroup-Name, eg: REDHAT4 workgroup = EAGLE# server string is the equivalent of the NT Description field server string = EAGLE systems# This option is important for security. It allows you to restrict# connections to machines which are on your local network. The# following example restricts access to two C class networks and# the loopback interface. For more examples of the syntax see# the smb.conf man page; hosts allow = 192.168.1. 192.168.2. 127.# If you want to automatically load your printer list rather# than setting them up individually then you'll need this load printers = no# you may wish to override the location of the printcap file; printcap name = /etc/printcap# on SystemV system setting printcap name to lpstat should allow# you to automatically obtain a printer list from the SystemV spool# system; printcap name = lpstat# It should not be necessary to specify the print system type unless# it is non-standard. Currently supported print systems include:# bsd, sysv, plp, lprng, aix, hpux, qnx; printing = bsd# Uncomment this if you want a guest account, you must add this to /etc/passwd# otherwise the user nobody is used; guest account = pcguest# this tells Samba to use a separate log file for each machine# that connects log file = /var/log/log.%m# Put a capping on the size of the log files (in Kb). max log size = 50# Security mode. Most people will want user level security. See# security_level.txt for details. security = user# Use password server option only with security = server# The argument list may include:# password server = My_PDC_Name [My_BDC_Name] [My_Next_BDC_Name]# or to auto-locate the domain controller/s# password server = *; password server = <NT-Server-Name># Note: Do NOT use the now deprecated option of domain controller# This option is no longer implemented.# You may wish to use password encryption. Please read# ENCRYPTION.txt, Win95.txt and WinNT.txt in the Samba documentation.# Do not enable this option unless you have read those documents encrypt passwords = yes# Using the following line enables you to customise your configuration# on a per machine basis. The %m gets replaced with the netbios name# of the machine that is connecting; include = /usr/local/etc/smb.conf.%m# Most people will find that this option gives better performance.# See speed.txt and the manual pages for details# You may want to add the following on a Linux system:# SO_RCVBUF=8192 SO_SNDBUF=8192 socket options = TCP_NODELAY # Configure Samba to use multiple interfaces# If you have multiple network interfaces then you must list them# here. See the man page for details.; interfaces = 192.168.12.2/24 192.168.13.2/24 interfaces = 180.207.29.26/24# Browser Control Options:# set local master to no if you don't want Samba to become a master# browser on your network. Otherwise the normal election rules apply local master = no# OS Level determines the precedence of this server in master browser# elections. The default value should be reasonable; os level = 33# Domain Master specifies Samba to be the Domain Master Browser. This# allows Samba to collate browse lists between subnets. Don't use this# if you already have a Windows NT domain controller doing this job domain master = no# Preferred Master causes Samba to force a local browser election on startup# and gives it a slightly higher chance of winning the election preferred master = no# Enable this if you want Samba to be a domain logon server for # Windows95 workstations. domain logons = no# if you enable domain logons then you may want a per-machine or# per user logon script# run a specific logon batch file per workstation (machine); logon script = %m.bat# run a specific logon batch file per username; logon script = %U.bat# Where to store roving profiles (only for Win95 and WinNT)# %L substitutes for this servers netbios name, %U is username# You must uncomment the [Profiles] share below; logon path = \\%L\Profiles\%U# Windows Internet Name Serving Support Section:# WINS Support - Tells the NMBD component of Samba to enable it's WINS Server; wins support = yes# WINS Server - Tells the NMBD components of Samba to be a WINS Client# Note: Samba can be either a WINS Server, or a WINS Client, but NOT both; wins server = w.x.y.z# WINS Proxy - Tells Samba to answer name resolution queries on# behalf of a non WINS capable client, for this to work there must be# at least one WINS Server on the network. The default is NO. wins proxy = no# DNS Proxy - tells Samba whether or not to try to resolve NetBIOS names# via DNS nslookups. The built-in default for versions 1.9.17 is yes,# this has been changed in version 1.9.18 to no. dns proxy = no # Client codepage settings# for Greek users; client code page=737# for European users (Latin 1); client code page=850# for European users (Latin 2); client code page=852# for Icelandic users; client code page=861# for Cyrillic users; client code page=866# for Japanese Users; client code page=932; coding system=cap# for Simplified Chinese Users; client code page=936; coding system=cap# for Korean Users; client code page=949; coding system=cap# for Traditional Chinese Users; client code page=950; coding system=cap#============================ Share Definitions ==============================[homes] comment = Home Directories browseable = no writeable = yes# Un-comment the following two lines to add a recycle bin facility to a samba share# NOTE: It currently doesn't work with the [homes] virtual share, use a regular share instead; vfs object = /usr/local/lib/samba/recycle.so; vfs options= /usr/local/etc/recycle.conf.default# Un-comment the following and create the netlogon directory for Domain Logons; [netlogon]; comment = Network Logon Service; path = /usr/local/samba/lib/netlogon; guest ok = yes; writeable = no; share modes = no# Un-comment the following to provide a specific roving profile share# the default is to use the user's home directory;[Profiles]; path = /usr/local/samba/profiles; browseable = no; guest ok = yes# NOTE: If you have a BSD-style print system there is no need to # specifically define each individual printer;[printers]; comment = All Printers; path = /var/spool/samba; browseable = no;# Set public = yes to allow user 'guest account' to print; guest ok = no; writeable = no; printable = yes# This one is useful for people to share files;[tmp]; comment = Temporary file space; path = /tmp; read only = no; public = yes# A publicly accessible directory, but read only, except for people in# the Bird group.# New files/directories put in group Bird, and group write permission added.[BIRD_disk] comment = The nesting place. path = /BIRD_disk browseable = yes public = no writeable = yes printable = no write list = @Bird force group = +Bird force create mode = 0775 force directory mode = 0775# Other examples. ## A private printer, usable only by fred. Spool data will be placed in fred's# home directory. Note that fred must have write access to the spool directory,# wherever it is.;[fredsprn]; comment = Fred's Printer; valid users = fred; path = /homes/fred; printer = freds_printer; public = no; writeable = no; printable = yes# A private directory, usable only by fred. Note that fred requires write# access to the directory.;[fredsdir]; comment = Fred's Service; path = /usr/somewhere/private; valid users = fred; public = no; writeable = yes; printable = no# a service which has a different directory for each machine that connects# this allows you to tailor configurations to incoming machines. You could# also use the %U option to tailor it by user name.# The %m gets replaced with the machine name that is connecting.;[pchome]; comment = PC Directories; path = /usr/pc/%m; public = no; writeable = yes# A publicly accessible directory, read/write to all users. Note that all files# created in the directory by users will be owned by the default user, so# any user with access can delete any other user's files. Obviously this# directory must be writeable by the default user. Another user could of course# be specified, in which case all files would be owned by that user instead.;[public]; path = /usr/somewhere/else/public; public = yes; only guest = yes; writeable = yes; printable = no# Un-comment the following two lines to add a recycle bin facility to a samba share; vfs object = /usr/local/lib/samba/recycle.so; vfs options= /usr/local/etc/recycle.conf.default# The following two entries demonstrate how to share a directory so that two# users can place files there that will be owned by the specific users. In this# setup, the directory should be writeable by both users and should have the# sticky bit set on it to prevent abuse. Obviously this could be extended to# as many users as required.;[myshare]; comment = Mary's and Fred's stuff; path = /usr/somewhere/shared; valid users = mary fred; public = no; writeable = yes; printable = no; create mask = 0765 | Samba 2.2.12 accepts my password, but is rejecting other user accounts? | freebsd;windows;samba | It turns out that Windows does not allow multiple connections to a shared resource by the same user and using different usernames → http://support.microsoft.com/kb/938120Some suggested workaround can be found here → https://superuser.com/questions/95872/sambawindows-allow-multiple-connections-by-different-usersTook me a while to figure this out because sometimes the Windows 7 client just throws another password challenge dialog even though you just provided the correct credentials, and sometimes it displays the error dialog indicating that multiple connections by the same user are not allowed. |
_codereview.14736 | I'm making requests to Parse.com to 3 different objects that are needed to render a View.I'd like to know what's the general/best approach in cases like these in which there are multiple requests before actually handling the data.Code: var Parse = require('parse-api').Parse; var parse = new Parse(); exports.single = function() { parse.find('Class_1',params1,function(error,response1){ parse.find('Class_2',params2,function(error, response2){ parse.find('Class_3',params3,function(error3, response3){ // handle responses.... // render view.... }) }) }) }Thanks! | Node.js Nested Callbacks, multiple requests | javascript;node.js;asynchronous | Use Step.js or async.js to make this look cleaner. Step.js is simpler, but async.js gives you more flexibility. Also, your function single needs to have a callback, and cannot return values since the functions it's invoking are not returning values.Additionally, generally the data retrieval methods should be separate from the rendering methods.With Step.js, this could look like: var Parse = require('parse-api').Parse, Step = require('step'); var parse = new Parse();exports.getAndRenderData = function(res, params1, params2, params3){ getData(params1, params2, params3, function(err, data){ if(err) throw err: else { res.render('viewname', data); } });}var getData = function(params1, params2, params3, callack) { var data = {}; Step()( function getClass1(){ parse.find('Class_1',params1, this); }, function getClass2(err, class1data){ if (err) throw err; data.class1 = class1data; parse.find('Class_2',params2, this); }, function getClass3(err, class2data){ if (err) throw err; data.class2 = class2data; parse.find('Class_3',params3, this); }, function callbackWithAll(err, class3data){ if (err) callback(err); else { data.class3 = class3data; callback(null, data); } } );} |
_unix.24062 | I'm having some issues with fullscreen games ruining my display and forcing me to reboot.I'm wondering if there's a way to trick the game into thinking its going in fullscreen, when really I've restricted it to a window. Is this possible?Here is the output of ldd:linux-gate.so.1 => (0xffffe000)libvorbisfile.so.3 => /usr/lib/libvorbisfile.so.3 (0xf76d7000)libfltk.so.1.1 => not foundlibSDL-1.2.so.0 => /usr/lib/libSDL-1.2.so.0 (0xf7636000)libSDL_ttf-2.0.so.0 => not foundlibSDL_image-1.2.so.0 => not foundlibGL.so.1 => /usr/lib/libGL.so.1 (0xf75ce000)libGLU.so.1 => /usr/lib/libGLU.so.1 (0xf755a000)libCg.so => not foundlibCgGL.so => not foundlibopenal.so.0 => not foundlibalut.so.0 => not foundlibstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xf746a000)libm.so.6 => /lib/libm.so.6 (0xf7440000)libgcc_s.so.1 => /lib/libgcc_s.so.1 (0xf7422000)libc.so.6 => /lib/libc.so.6 (0xf72b4000)libpthread.so.0 => /lib/libpthread.so.0 (0xf7299000)libvorbis.so.0 => /usr/lib/libvorbis.so.0 (0xf726e000)libogg.so.0 => /usr/lib/libogg.so.0 (0xf7266000)libasound.so.2 => /usr/lib/libasound.so.2 (0xf7181000)libdl.so.2 => /lib/libdl.so.2 (0xf717c000)libX11.so.6 => /usr/lib/libX11.so.6 (0xf703e000)libXext.so.6 => /usr/lib/libXext.so.6 (0xf702c000)libXdamage.so.1 => /usr/lib/libXdamage.so.1 (0xf7028000)libXfixes.so.3 => /usr/lib/libXfixes.so.3 (0xf7022000)libXxf86vm.so.1 => /usr/lib/libXxf86vm.so.1 (0xf701c000)libdrm.so.2 => /usr/lib/libdrm.so.2 (0xf700e000)/lib/ld-linux.so.2 (0xf770c000)librt.so.1 => /lib/librt.so.1 (0xf7004000)libxcb.so.1 => /usr/lib/libxcb.so.1 (0xf6fe4000)libXau.so.6 => /usr/lib/libXau.so.6 (0xf6fe0000) | Forcing a fullscreen game to run windowed? | xorg;opensuse;games | This is just a guess but could using something like xnest or xephyr work, i.e., letting the game use the entire screen which is not really the entire screen? |
_codereview.21633 | I was recently asked to implement an interface for a job interview. the class has methods to add customers and movies, the customers can watch or like movies and add friends. there are methods to get recommendations for users. All public methods in SocialMoviesImpl were defined by the interface, so I could not change themthe company decided not to continue with the hiring process, I would like some feedback in what I implemented. I used hashmaps to store the information since it is fast to accessimport java.util.Collection;import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Set;public class SocialMoviesImpl implements SocialMovies {Map<Integer,String> movies;Map<Integer,Customer> customers;public SocialMoviesImpl(){ this.movies= new HashMap<Integer,String>(); this.customers= new HashMap<Integer,Customer>();}/** * add a movie, runtime complexitiy is O(1) //hashmap * @param movieId the id of the movie * */public void addMovie(int movieId, String title) { this.movies.put(movieId,title);}/** * gets a movie, O(1) */public String lookupMovie(int movieId) { return this.movies.get(movieId);}/** * adds a new customer, O(1) */public void addCustomer(int customerId, String name) { this.customers.put(customerId, new Customer(customerId, name));}/** * obtains the customer, O(1) */public String lookupCustomer(int customerId) { Customer cust= this.customers.get(customerId); return cust!=null?cust.getName():null;}/** * O(4), 3 searches and 1 add */public void addLikedMovie(int customerId, int movieId) { if(this.customers.containsKey(customerId) && this.movies.containsKey(movieId)){ this.customers.get(customerId).addLike(movieId); }else{ throw new IllegalArgumentException(movie or client does not exists); }}/** * O(4) */public void addWatchedMovie(int customerId, int movieId) { if(this.customers.containsKey(customerId) && this.movies.containsKey(movieId)){ this.customers.get(customerId).addWatch(movieId); }else{ throw new IllegalArgumentException(movie or client does not exists); }}/** * O(6) */public void addFriend(int customerId1, int customerId2) { if(this.customers.containsKey(customerId1) && this.customers.containsKey(customerId2)){ //we add a key to the customers friend entry this.customers.get(customerId1).addFriend(customerId2); this.customers.get(customerId2).addFriend(customerId1); }else{ throw new IllegalArgumentException(the customerId or movieId provided does not exists); }}/** * returns any movie that has been liked by a friend. * * */public Collection<Integer> getRecommendationsFromFriends(int customerId) { return getFriendRecommendations(customerId, 1);}/** * returns every movie that has been liked by a defined number of friends. * O(n^2) * */public Collection<Integer> getFriendRecommendations(int customerId, int minimumCommonFriends) { if(minimumCommonFriends<1){ //negative doesnt make sense and zero will mean every movie throw new IllegalArgumentException(please provide a positive non-zero number of minimum common friends); } //iterate through all friends and their movies Map<Integer,Integer> recommends= new HashMap<Integer,Integer>(); Collection<Integer> friends=this.customers.get(customerId).getFriends(); for(Integer friendId:friends){ Customer friend= this.customers.get(friendId); for(Integer movie: friend.getLikes()){ Integer ammount=recommends.get(movie); ammount=ammount!=null?ammount+1:1; //increment or set to 1 if first time recommends.put(movie,ammount); //we dont care about who is recommending it } } //now, filter only those recommended by at least the treshold Set<Integer> keys=recommends.keySet(); Set<Integer> toRemove= new HashSet<Integer>(); //we cannot remove during iteration for(Integer movie: keys){ Integer commonFriends= recommends.get(movie); //ammount of friends who liked it if(commonFriends<minimumCommonFriends){ toRemove.add(movie); } } keys.removeAll(toRemove); return recommends.keySet();}/** * class that holds information about the customer (liked, watched, etc). * @author santiago * */class Customer{ private int customerId; private String name; private Set<Integer> likes; private Set<Integer> watched; private Set<Integer> friends; public Customer(int id, String name){ this.customerId=id; this.name=name; this.likes= new HashSet<Integer>(); this.watched= new HashSet<Integer>(); this.friends= new HashSet<Integer>(); } public String getName(){ return this.name; } public Set<Integer> getLikes() { return likes; } public Set<Integer> getWatched() { return watched; } public Set<Integer> getFriends() { return friends; } public void addFriend(int friend){ this.friends.add(friend); } public void addWatch(int movie){ this.watched.add(movie); } public void addLike(int movie){ this.likes.add(movie); }}}this is the provided interfaceimport java.util.Collection;// Maintains a network of movies and customers// All methods should return an empty collection, -1, or null on failure, as appropriate <---*** I just noted this and feel very very bad.public interface SocialMovies {// Defines a movie ID to title mapping in the systemvoid addMovie(int movieId, String title);// Returns the title of the given movieString lookupMovie(int movieId);// Defines a customer ID to name mapping in the systemvoid addCustomer(int customerId, String name);// Returns the name of the given customerString lookupCustomer(int customerId);// Record that a movie was liked by the given customervoid addLikedMovie(int customerId, int movieId);// Record that a movies has been watched by the given customervoid addWatchedMovie(int customerId, int movieId);// Associate two customers as being friendsvoid addFriend(int customerId1, int customerId2);// Returns the IDs of movies that:// - Have not been watched by the given customer// - Have been liked by at least one of the given customer's friendsCollection<Integer> getRecommendationsFromFriends(int customerId);// Returns the IDs of customers that have at least <minimumCommonFriends> in common// with the given customerCollection<Integer> getFriendRecommendations(int customerId, int minimumCommonFriends);} | interview question, friends, movies and likes | java;interview questions | Your getRecommendationsFromFriends and getFriendRecommendations implementations are incorrect as the documentation shows:getRecommendationsFromFriends: return movie id'sgetFriendRecommendations: return customer id'sThis is the biggest issue with your implementation. getRecommendationsFromFriends is fairly straight-forward:public Collection<Integer> getRecommendationsFromFriends(int customerId) { /* 1. Validate Customer * 2. Collect the id's for movies his friends like * 3. Remove the customer's watched movies from the friend likes * 4. Return the collection (a set is good here, maybe even a TreeSet for sorting */}2 and 3 could be combined (a helper method in Customer could be handy)GetFriendRecommendations is slightly more complicated, but not unreasonable for an interview. (keep in mind there could be many many customers!). Remember to always read (and re-read!) the documentation to make sure you have a firm grasp on what the interface is supposed to provide. |
_cstheory.3373 | Could you recommend a survey article or textbook chapter that introduces the theory of recursive functions? Thanks | Survey Article on the Theory of Recursive Functions? | reference request;computability | null |
_cstheory.811 | Two papers I would include are:D. Kozen, Indexing of subrecursive classes, STOC, 1978.R. Ladner, On the Structure of Polynomial Time Reducibility, JACM, 1975. | What are the classic papers from the recursion theoretic area of complexity theory? | cc.complexity theory;lo.logic;computability;big list;structural complexity | Hajek, P. Arithmetical hierarchy and complexity of computation. Theoret. Comp. Sci. 8 (2): 227-237, 1979. Started the study of the complexities of index sets (where their complexities often lie somewhere in the arithmetical hierarchy; see this answer to another question.)On the study of polynomial-time degrees (buzzword=polynomial-time degree theory, for the sake of future searches) I'd say these papers are of interest (several of them are based on Ladner's technique):Homer, S. Minimal degrees for polynomial reducibilities. J. ACM 34(2):480-491, 1987.Schning, U. Minimal pairs for P. Theoret. Comp. Sci. 31: 41-48, 1984.Downey, R. Nondiamond theorems for polynomial time reducibility. Journal of Computer and System Sciences 45(3):385-195, 1992.Downey, R. and Fortnow, L. Uniformly hard languages. Theoret. Comp. Sci. 298(2): 303-315, 2003.Fenner, S., Homer, S., Prium, R. and Schaefer, M. Hyper-polynomial hierarchies and the polynomial jump. Theoret. Comp. Sci. 262: 241-256, 2001.Probably a forward and backwards reference search will find several more papers in the same area (though it's not that big an area!). |
_codereview.150136 | I made a variation on the program that moves the character to the next character. This version moves the characters n steps forward and takes care of white spaces in between. It works but wonder if there is a better way of coding this.It only works with lowercase alphabet characters.import java.util.Scanner;public class NextCharacters{ public static char nextCharacterInAlphabet(char character , int step) { char nextChar; int ascii = (int) character; if (ascii ==32) //ascii code for a space is 32 /*space stays space that separates the different strings seperated by the spaces */ nextChar = (char) ascii; /*at ascii 104=h remainder goes to zero so i have to add 104, have to add 104 till ascii=122=z*/ else if ((ascii +step) % 26>=0 && (ascii +step) % 26 <=18) { nextChar = (char) ( ((ascii +step) % 26)+104); } else nextChar = (char) ( ((ascii +step) % 26)+78); /*first character is the 'a' with ascii value 97. Remainder of 97%26 is 19 so to come up with 97 you have to add 78 to get the value for a. The same applies if you increase the number of positions you want the chars to move forward, have to this till it reaches ascii =104 where the remainder gets to 0 and have to add 104*/ return nextChar; } public static void main(String[] args) { Scanner inputChars = new Scanner( System.in ); Scanner inputSteps = new Scanner( System.in ); StringBuilder sb = new StringBuilder(); System.out.println(Please enter the characters ); String characterString = inputChars.nextLine(); System.out.println(Please enter the number of positions you want each character to move forward); int numberOfMovesForward = inputSteps.nextInt(); for (char c : characterString.toCharArray() ) { sb.append(nextCharacterInAlphabet(c,numberOfMovesForward )); } System.out.println(sb.toString()) ; }} | Program that moves characters in n steps to the next character in alphabet based on ASCII code | java;caesar cipher | null |
_codereview.88285 | It is a code eval challenge question https://www.codeeval.com/open_challenges/14/.My answer was accepted, and I modified my code again to improve it. Please let me know is it possible to improve it more.#include <iostream>#include<fstream>#include<algorithm>#include<string>void create_permute( std::string &record ){ if( !record.empty() ) { std::sort( record.begin(), record.end() ); bool flag=0; do{ if( flag ) { std::cout<<,; } flag = 1; std::cout << record; } while( std::next_permutation( record.begin(), record.end() ) ); std::cout << \n; }}void readInputFile( std::string filename ) { std::ifstream infile; infile.open( filename ); std::string record; while( std::getline( infile,record ) ) { create_permute( record ); }}int main( int argc, char* argv[] ){ if( argc < 2 ) { std::cout << usage: filesize filename << \n; exit( 0 ); } std::ios_base::sync_with_stdio( false ); readInputFile( argv[ 1 ] ); return 0;} | Printing all the permutations of a string in alphabetical order | c++;c++11;sorting;combinatorics | If you have preconditions return earlyif( !record.empty() ) { // CODE}// If the precondition for doing work is that it is not empty// Then test and return immediately.if (record.empty()) { return;}// CODENow your code does not suffer lots of indenting and becomes easier to read.Use constructorsstd::ifstream infile;infile.open( filename );// Easier to read and write as:std::ifstream infile( filename );I think we can simplify that loop:std::sort( record.begin(), record.end() );std::cout << record;while( std::next_permutation( record.begin(), record.end() )){ std::cout << , << record}std::cout << \n; |
_unix.294479 | I thought that make interprets the rule's set of commands literally, passing them to the sub-shell. But this doesn't seem to work in this case:default: loop echo $$RANDOM This prints echo $RANDOM in my shell but doesn't actually print the number. | How to use bash variables inside make | bash;make;gnu make | null |
_webmaster.9635 | I still remember one of my high school teachers lecturing us about the web safe colors. A set of 216-256 colors that you should confine your designs to use, and nothing else besides them. Last I knew, Photoshop still has the web safe yield icon1 on it's color picker.Are web safe colors still a concern? Outside of the obvious application (accessibility, legacy software versions, etc.), how much consideration should I give to limiting my color choice for my general audience?1Or was it the cube? I never remember. | Are Web Safe Colors Still Relevant? | accessibility | No, they're not. Fewer than 1% of Internet users are now on the 8-bit displays that made them necessary. |
_cs.64838 | I have used Rabin Karp Rolling Hash for searching a pattern $P$ in a text $T$. Now I am allowing $k$-mismatches, but not able to do a faster implementation.I tried modifying RK algorithm by splitting the pattern into few blocks, but that does not improve the speed. I'm trying to use locality sensitive hashing, but not sure how could I calculate hash with sliding window manner. Any help would be appreciated. For my case, the length of $P$ is 50~75 and $T$ is 100~150. | pattern search with k-mismatch | algorithms;strings;searching;rolling hash | null |
_webapps.29779 | I had a setting so that my comments on other's walls would not show on my own. Now I'd like to change it back so my comments show up on my 'timeline' but the instructions for doing so that I find online all seem to be outdated.Is it even possible? | Have Facebook comments on others walls show on mine(New Facebook) | facebook | null |
_unix.266871 | I'm trying to install the VMware tools in a VMPlayer VM but in a certain point of the installation I need to set the linux-headers path. So I go and try to install it with this command:apt-get install gcc make linux-headers-$(uname -r)Then I get the error:Couldnt find any package by glob 'linux-headers-4.3.0-kali-amd64'My sources.list file has these sources: deb http://http.kali.org/kali kali-rolling main contrib non-free deb http://http.kali.org/kali kali main contrib non-free deb http://http.kali.org/kali sana main contrib non-free deb http://http.kali.org/kali-security kali/updates main contrib non-free deb http://http.kali.org/kali-security sana/updates main contrib non-freeI already did and apt-get update before trying to install the headers. What can I do to download it? | Cannot find linux-headers-4.3.0-kali-amd64 | software installation;kali linux;vmware | null |
_unix.365542 | From the Arch Wiki I found that setting the environment variable DESKTOP_SESSION=gnome makes Qt4 apps use the system icon theme but not Qt5 apps. Also setting this in /etc/profile makes Xfce unbootable. Is there a way to make Qt4 and Qt5 apps use the same system icon theme? If not how do I install separate icon theme specially for Qt apps? | How to make Qt apps in Xubuntu 16.04 to use native icon theme? | ubuntu;qt;xubuntu;icons;qt4 | null |
_softwareengineering.205351 | I am aware of the floating point errors as I had gained some knowledge with my question asked here in SE Floating Point Errors.What I am finding it difficult to understand is, the output of the following program. double d1 = 0 + 1.123 + 2.456; double d2 = 3.579; float f1 = 0f + 1.123f + 2.456f; float f2 = 3.579f; long l1 = (long)(0 + 1.123 + 2.456); long l2 = (long)3.579; System.out.println(d1==d2); // Output = false; System.out.println(f1==f2); // Output = true; System.out.println(l1==l2); // Output = true;Why is the output false for double and not for float, even when float is single precision 32 bit and double is double precision 64 bit. Oracle docsAny help with this would be highly appreciated. | Addition of double's is NOT Equal to Sum of the double as a whole | java;numeric precision;floating point | Consider this hypothetical.You have two data types. One is a floating point number with 32 bits of precision that is base 3 (represented by the digits 0, 1, and 2). The other is a floating point number with 64 bits of precision that is base 4.Given this code:float a = .3 + .6float b = .9;print(a == b)The comparison will return true if base 3 floats are used, and false if base 4 floats are used, even though the base 4 float has a much higher precision.Why is this? Because the numbers 3, 6, and 9 can be represented exactly in the base 3 float, but can only be approximated in the base 4 float, no matter how many digits of precision there are.This is why floating point numbers should never be compared using ==. They should always be compared using a range of allowable error. |
_softwareengineering.316570 | I'm writing a quite simple application that deals with hotel rooms reservation. I've got a problem at one stage.I'm processing a queue of orders. For every order one of the receptionists should choose a room (one or none at all) for the client according to his strategy. That's why I decided to go with Java Optional. The problem is that if there are simply no free rooms at the desired date the order should be cancelled, but if there are some rooms available and none of them fit to the receptionist's strategy that order should be put back to the queue.Choosing rooms definitely should be receptionist's duty. What do you think is the best way to deal with that problem in a clean way? Should I throw an exception instead of returning empty Optional when there are no rooms at date? Unfortunately, exceptions aren't usually a good solution for controlling the code flow.Code fragment: Optional<Room> selectedRoom = receptionist.chooseRoom(rooms, order.getQuestionnaire()); boolean decision = selectedRoom .map(room -> receptionist.askClient(order.getClient(), room, order.getQuestionnaire())) .orElse(false); if (shouldProcessAgain(order, selectedRoom.isPresent(), decision)) { orders.add(order); } | OOP design problem. Two kinds of empty Optional | java;object oriented;coding style | I think you could model it in two ways:Option 1: Using an wrapper + enum for the receptionist response:enum ReceptionistDecision { BOOK_ROOM, NO_ROOM, RETURN_TO_QUEUE,}class ReceptionistResponse { ReceptionistDecision Decision; Optional<Room> Room; ReceptionistResponse(Room room) { ... } ReceptionistResponse(ReceptionistDecision decision) { ... }}Option 2: Or you could an interface class, and make each of the responses inherit from it. Something like:interface class ReceptionistResponse {}class ReturnToQueueReceptionistResponse implements ReceptionistResponse {}class NoRoomsBookedQueueReceptionistResponse implements ReceptionistResponse {}class RoomBookedReceptionistResponse implements ReceptionistResponse { Room BookedRoom;}The chooseRoom method would be:ReceptionistResponse chooseRoom(List<Rooms> allRooms, Questionnaire questionnaire) { if (/* all rooms are full */) { // Option 1 return new ReceptionistResponse(ReceptionistDecision.RETURN_TO_QUEUE); // Option 2 return new ReturnToQueueReceptionistResponse(); } if (/* Choose no rooms */) { // Option 1 return new ReceptionistResponse(ReceptionistDecision.NO_ROOM); // Option 2 return new NoRoomsBookedQueueReceptionistResponse(); } if (/* Choose some room */) { // Option 1 return new ReceptionistResponse(choosenRoom); // Option 2 return new RoomBookedReceptionistResponse(choosenRoom); }}And the client code for option 1:ReceptionistResponse response = receptionist.chooseRoom(rooms, order.getQuestionnaire());// options 1if (response.Decision == ReceptionistDecision.RETURN_TO_QUEUE) {// option 2if (response instanceof(ReturnToQueueReceptionistResponse)) { orders.add(order);} |
_unix.210625 | I accidentally ran badblocks on my entire 320 GB disk instead of a single partition:sudo badblocks -s -v -n -f /dev/sdaIt's been running for 42 hours now. How can I tell when it will be finished? Can I interrupt it safely with Ctrl+C? | Is it safe to interrupt badblocks? | badblocks | null |
_codereview.1911 | I have been reviewing the code of a new co-worker and, although in general I think it's OK, there's a thing that causes me mixed feelings: private void Method(...) { Thread t = new Thread(() => { // Some ~50 lines of code here }); t.Start(); }This is no big deal, but I'm curious about what you guys think of it.Is this exactly what lambdas are for? Or just the opposite? I try to avoid any lambda which doesn't fit on a couple lines at most... | Long function as a lambda, right or wrong? | c#;lambda | In my opinion no preferable answer can be given without seeing the exact code. I don't like splitting code into smaller methods just for the sake of making methods smaller, as opposed to Brian Reichle's answer (and many other people that follow this approach).If the code of the thread is and can only be used locally, I would leave it in there regardless of the LOC. Using a lambda has the advantage that you don't 'pollute' your class with an extra private method which is only called from one location. This provides for better encapsulation, which is a core principle of OO which makes it shine.If the code of the thread were to be reuseable, I would rather think about splitting the behavior in a separate class than in a separate method, unless the code only makes sense in the original class.Also as a sidenote; I realize you probably just named your code as to get the idea across, but I'd make sure the name of Method would indicate it only starts a certain action, but doesn't finish it. E.g. StartSomeMethod. |
_reverseengineering.6862 | How can someone with little programming knowledge except for some Ruby on Rails/Ruby begin on a path of Reverse Engineering as a hobbyist to help the exploitation process of modern-day gaming consoles like Xbox Ones and PS4s?I realize there is no simple do this, then that spoon-fed process of learning an extremely diverse subject matter like reversing but there are such vast amounts of tutorials that I have no idea which ones really pertain to my interest of specifically game console exploitation! I really want to help contribute to the long-term process of finding these vulnerabilities and get unsigned code running on these systems | How to start learning reverse engineering to eventually help exploiting of modern consoles like Xbox One, PS4? | disassembly;obfuscation;exploit;embedded | Some things you will inevitably have to know at some degree to be able to reverse engineer Game Consoles:Learn a lower level language such as C or C++. Most, if not all, Console games, modern and old, use these two languages for the bulk of the game (AKA, the Engine). This is important for my next point, which is:Learn about the architecture of game software. Internally, games are not very different from one another. There are common data structures and algorithms that are needed by most games, and these needs reflect in the hardware. Learning the tools that engineers used to create these structures (C/C++) and knowing the structures and algorithms themselves, will help a lot when you have to make assumptions and guesses during the hacking process.You'll obviously have to get familiar with hexadecimal dumps and assembly languages to be able to make sense of reversed Console code and ROMs.Write a console game, preferably using an unofficial SDK. This is something that can also greatly improve your knowledge of the hardware and platform. Find out about the home brew community for your favorite Console and attempt to write a simple game using the available tools. You will have to solve a lot of hardware-specific problems and do a lot of guessing, since documentation is frequently rare. You'll gain valuable knowledge in the process.Contribute to an emulator project. This is also a great way of acquiring knowledge about the hardware. The best possible way, I'd argue, since you will be trying to mimic the hardware with a piece of software. |
_cs.2501 | I cannot seem to find an answer to this question with Google, so I am going to ask here: is it required for a good neighbourhood function that it in principle (i. e. by recursively considering all neighbours of a certain solution - which is not practical) can reach all possible solutions?My question is whether there are references in literature that explicitely state it's a requirement - I can see that it is a good property of a neighbourhood. | Neighbourhood in local search metaheuristic | optimization;heuristics | I think the property of being able to reach all the successor states from a current state is crucial and needed in order for the problem to be well-defined. If this was not the case, you might miss out on good solutions. Moreover, you might never reach a goal state and hence run forever.The classic AI book by Russell & Norvig, 3rd edition, page 67 gives a formal definition for a problem. One of the components is a successor function which returns all the successor states for a current state. Together the formal components create a search space, that is the set of all states reachable from the initial state. If one uses a different successor function, namely such that it leaves out some successors, the resulting search space is a different one: goal state(s) might be missing and optimal solutions might very well differ. Perhaps the reason you are unable find it from the literature is that the requirement is obvious. |
_softwareengineering.77313 | Usually I just throw my unit tests together using copy and paste and all kind of other bad practices. The unit tests usually end up looking quite ugly, they're full of code smell, but does this really matter? I always tell myself as long as the real code is good that's all that matters. Plus, unit testing usually requires various smelly hacks like stubbing functions.How concerned should I be over poorly designed (smelly) unit tests? | If your unit test code smells does it really matter? | unit testing;code quality;code smell | Are unit test smells important? Yes, definitely. However, they are different from code smells because unit tests serve a different purpose and have a different set of tensions that inform their design. Many smells in code don't apply to tests. Given my TDD mentality, I would actually argue that unit test smells are more important than code smells because the code is just there to satisfy the tests.Here are some common unit testing smells:Fragility: do your tests fail often and unexpectedly even for seemingly trivial or unrelated code changes?State Leak: do your tests fail differently depending on, for instance, what order they are run?Setup/Teardown Bloat: Are your setup/teardown blocks long and growing longer? Do they perform any sort of business logic?Slow Runtime: Do your tests take a long time to run? Do any of your individual unit tests take longer than a tenth of a second to run? (Yes, I'm serious, a tenth of a second.)Friction: Do existing tests make it difficult to write new tests? Do you find yourself struggling with test failures often while refactoring?The importance of smells is that that they are useful indicators of design or other more fundamental issues, i.e. where there's smoke, there's fire. Don't just look for test smells, look for their underlying cause as well.Here, on the other hand, are some good practices for unit tests:Fast, Focused Feedback: Your tests should isolate the failure quickly and give you useful information as to its cause.Minimize Test-Code Distance: There should be a clear and short path between the test and the code that implements it. Long distances create unnecessarily long feedback loops.Test One Thing At A Time: Unit tests should only test one thing. If you need to test another thing, write another test.A Bug Is A Test You Forgot To Write: What can you learn from this failure to write better, more complete tests in the future? |
_codereview.115339 | I would like to reverse a list using cdr, car and cons. Since lists in lisp are asymmetrical (can only insert at the beginning), I am interested on how one would write a procedure to do that without using (append). Please review my code.(define (reverse l) (define (aux orig result) (if (null? orig) result (aux (cdr orig) (cons (car orig) result)))) (aux l '()))Is this good enough? Are there better or more efficient ways to do this? | Reversing a list without (append) | performance;beginner;lisp;scheme;sicp | Given that you don't want to use append, this looks great to me. I'm not sure if I can even think of a different way to do it.My only suggestion would be naming related. l is a terrible name for a variable - it's too close to 1. orig is questionable, since it's not really the original list, it's the list you're currently popping (logically, not literally) off of - so you could simply rename both l and orig to something like lst or xs or elems or .... |
_codereview.145222 | This is my wrapper, how can i improve this? (With a Singleton too)<?php define(DB_HOST, );define(DB_USER, ); define(DB_PASS, ); define(DB_DATA, );class Connection extends PDO{ public function __construct($host = DB_HOST , $data = DB_DATA , $user = DB_USER , $pass = DB_PASS){ try { parent::__construct(mysql:host=$host;dbname=$data; , $user , $pass); } catch(PDOException $e){ print Error!: . $e->getMessage() . <br/>; die(); } } public function query($query , array $valori = [] ){ try { $res = parent::prepare($query); if($res === false ){ throw new \PDOException(#01); } if($res->execute($valori) === false ){ throw new \PDOException(#02); } return $res ; } catch(PDOException $e) { print Error!: . $e->getMessage() . <br/>; die(); } } }?> | Wrapper Connection PDO PHP | php;database;pdo;wrapper | Honestly, you can improve your application by discarding this wrapper. You are not going to derive any value from it.You can find similar discussion around this very common Codereview topic in questions such as those I have listed below.Class for reducing development timeSimple PDO database class in PHPPhishing Project Error LoggingWhat you should hopefully take away from this is that you are adding an unnecessary level of abstraction around an existing database abstraction (PDO) and adding no additional value to it. Typically one might write database-related classes to do things like:connection management (like a Singleton or connection pool implementation)adding model capabilities (i.e. ORM, active record pattern, etc.)adding fluent, natural language query capabilities ($db->select('field')->from('table')->where('id = ?') or similar).You are doing none of that. You are just obfuscating the underlying PDO implementation from the caller, while simultaneously leaking implementation details outside the class (you are throwing PDOException for example).Some specific comments on codeConsider moving your database configuration to outside of your code. There is no reason login credentials should be present in any of your code. Ideally you derive these from environmental configuration.Why are you defining variables in your parameters here => public function __construct($host = DB_HOST , $data = DB_DATA , $user = DB_USER , $pass = DB_PASS)? Why do you even need parameters if these values are defined as constants? You could build your DB connection string in your constructor directly from the constants. Are you really expecting to have to make dynamic/runtime assignment for these host and login credentials as you are trying to allow for?Don't echo out error messages to standard out (i.e. die('message')). These errors should be logged and an appropriate exception raised to inform the caller of the error. It should not be the place of this class to determine end-user messaging. The calling code is better positioned to do this.You should validate parametric data passed into public methods. Here on your query() method you do nothing to valdiate you have a reasonable query string to work with. You should validate and throw appropriate InvalidArgumentException or similar if validation fails. You don't to try to make queries against the database when an empty string is passed, for example. |
_cs.3034 | The following predicate logic formula is invalid (i.e. not a tautology):$\Bigl[\forall x \,\exists y {\,.\,} P(x,y)\Bigr] \implies \Bigl[\exists y \, \forall x {\,.\,} P(x,y)\Bigr]$Which of the following are counter-models (i.e. counterexamples) for it?The predicate $P(x,y) \equiv \bigl[ y \cdot x = 1 \bigr]$, where the domain of discourse is $\mathbb{Q}$.The predicate $P(x,y) \equiv \bigl[ y<x \bigr]$, where the domain of discourse is $\mathbb{R}$.The predicate $P(x,y) \equiv \bigl[ y \cdot x = 2 \bigr]$, where the domain of discourse is $\mathbb{R} \smallsetminus \{ 0 \}$.The predicate $P(x,y) \equiv \bigl[y \,x \,y = x\bigr]$, where the domain of discourse is $\{0,1\}^\ast$ — that is, theset of all binary strings, including the empty string).Is my answer below true ?Answer:I think the first model is not a counter model since 0 is a member of rational numbers there exists no rational y for which $x \cdot y = 1$. So $\forall x \,\exists y {\,.\,} P(x,y)$ is false, thereby validating the conditional for this choice of predicate $P$. Also sentence 4 is not a counter model. The other two are counter-models. | Validity of predicate logic formulas | logic;logical validity | null |
_webapps.26787 | I was under the impression that by using Google Drive, I can edit my files in MS Word or Excel and it will all sync but apparently I can't open .gdoc .gsheet in MS Office.So basically, aside from seeing what files I have in Google Docs from my Local Drive, I don't see any functional capabilities since I cannot edit it without going to Google Docs website? It's simply just a shortcut to the Google Docs website. If any, it only reveals my Google docs file names to other users of my PC. Or, am I missing something? | What is the purpose of the presence of Google Docs in Google Drive? | sync;google;google drive | Google Docs have been merged into Google Drive. Consider Drive as an overlay that just maps your previously existing Docs collection to your local hard drive. Since neither Word nor other applications have a way to edit Google Docs documents on the fly (plus the fact that there's no API for this), the only way to represent those documents on your local computer is to show them as .gdoc and .gsheet files.To edit them, you still have to use the Google Docs website.To view them, use the Docs offline modebeta. Click the settings button, and enable it from there.Then download the Google Docs app for Google Chrome. After all, you still need a browser though. |
_unix.29578 | I want to create a log file for a cron script that has the current hour in the log file name. This is the command I tried to use:0 * * * * echo hello >> ~/cron-logs/hourly/test`date +%d`.logUnfortunately I get this message when that runs:/bin/sh: -c: line 0: unexpected EOF while looking for matching ``'/bin/sh: -c: line 1: syntax error: unexpected end of fileI have tried escaping the date part in various ways, but without much luck. Is it possible to make this happen in-line in a crontab file or do I need to create a shell script to do this? | How can I execute `date` inside of a cron tab job? | cron;quoting;command substitution | Short answer:Try this:0 * * * * echo hello >> ~/cron-logs/hourly/test`date +\%d`.logNote the backslash escaping the % sign.Long answer:The error message suggests that the shell which executes your command doesn't see the second back tick character:/bin/sh: -c: line 0: unexpected EOF while looking for matching ``'This is also confirmed by the second error message your received when you tried one of the other answers:/bin/sh: -c: line 0: unexpected EOF while looking for matching `)'The crontab manpage confirms that the command is read only up to the first unescaped % sign:The sixth field (the rest of the line) specifies the command to be run. The entire command portion of the line, up to a newline or % character, will be executed by /bin/sh or by the shell specified in the SHELL variable of the cronfile. Percent-signs (%) in the command, unless escaped with backslash (\), will be changed into newline charac- ters, and all data after the first % will be sent to the command as standard input. |
_codereview.166517 | I have some code in a particular coding language, and I am trying to clean it up by adding spaces around the variables. I wrote this code, and it works on small amounts of text and if I set a break point and run through it manually for large amounts of text. But when I try to run through it without frequently stopping the macro, Word stops responding and I have to restart the program. I think it is because the code is inefficient, but I don't have enough knowledge of vba to make it more efficient.My codeSub SpaceVarsAndEqns()Dim i As LongDim paragraphIndex As LongDim characterIndex As LongDim isVar As BooleanDim varIndexBegin As LongDim varIndexEnd As LongDim Doc As RangeDim Par As RangeDim Char As RangeSet Doc = ActiveDocument.RangeFor paragraphIndex = 1 To Doc.Paragraphs.Count Set Par = Doc.Paragraphs(paragraphIndex).Range isVar = False characterIndex = 1 Do Set Char = Par.Characters(characterIndex) If isVar Then If Char.Text = $ Then varIndexEnd = characterIndex If Not Par.Characters(varIndexEnd + 1).Text = Then Par.Characters(varIndexEnd).InsertAfter ( ) characterIndex = characterIndex + 1 End If If Not Par.Characters(varIndexBegin - 1).Text = Then Par.Characters(varIndexBegin).InsertBefore ( ) characterIndex = characterIndex + 1 End If varIndexBegin = 0 varIndexEnd = 0 isVar = False ElseIf Not (IsAlphaNumber(Char.Text) Or (Char.Text = .)) Then varIndexBegin = 0 varIndexEnd = 0 isVar = False End If Else If Par.Characters(characterIndex).Text = $ Then varIndexBegin = characterIndex isVar = True End If End If characterIndex = characterIndex + 1 Loop While (characterIndex <= Par.Characters.Count)Next paragraphIndexEnd SubText Before\begin{bmatrix} $eval(($d$*$d.pmv$)/(|$d.et$|)*($d.et$*$xm$) + (($b$*-1)*$d.pmv$)/(|$d.et$|)*($d.et$*$ym$) + $dist5$,0.###)\\ $eval((((($a$*$d$)-$d.et$)/($b$))*$d.pmv$*-1)/(|$d.et$|)*($d.et$*$xm$) + ($a$*$d.pmv$)/(|$d.et$|)*($d.et$*$ym$)+ $dist6$,0.###) \end{bmatrix}Text After\begin{bmatrix} $eval(( $d$ * $d.pmv$ )/(| $d.et$ |)*( $d.et$ * $xm$ ) + (( $b$ *-1)* $d.pmv$ )/(| $d.et$ |)*( $d.et$ * $ym$ ) + $dist5$ ,0.###)\\ $eval((((( $a$ * $d$ )- $d.et$ )/( $b$ ))* $d.pmv$ *-1)/(| $d.et$ |)*( $d.et$ * $xm$ ) + ( $a$ * $d.pmv$ )/(| $d.et$ |)*( $d.et$ * $ym$ )+ $dist6$ ,0.###) \end{bmatrix}I think it could be improved by using a find method to find two consecutive $ symbols, and checking if the characters in between are consistent with a variable. However, I don't know how I would add spaces doing it this way. | Add spaces around variable with $ symbol bookends | strings;vba;time limit exceeded;formatting;ms word | Here's a version using Regular Expressions. Option ExplicitSub SpaceVarsAndEqns() Dim DocumentRange As Range, ParagraphRange As Range Dim i As Long, P As Paragraph Dim Pattern As String, Replace As String, RegEx As New RegExp Dim ParagraphText As String Pattern = (?:\s?)\$[^$(]*\$(?:\s?) Replace = $& With RegEx .Global = True .MultiLine = True .IgnoreCase = True .Pattern = Pattern End With Set DocumentRange = ActiveDocument.Range For i = 1 To DocumentRange.Paragraphs.Count Set P = DocumentRange.Paragraphs(i) ParagraphText = P.Range.Text If RegEx.Test(ParagraphText) Then P.Range.Text = RegEx.Replace(ParagraphText, Replace) End If NextEnd SubBefore:\begin{bmatrix} $eval(($d$*$d.pmv$)/(|$d.et$|)*($d.et$*$xm$) + (($b$*-1)*$d.pmv$)/(|$d.et$|)*($d.et$*$ym$) + $dist5$,0.###)\\ $eval((((($a$*$d$)-$d.et$)/($b$))*$d.pmv$*-1)/(|$d.et$|)*($d.et$*$xm$) + ($a$*$d.pmv$)/(|$d.et$|)*($d.et$*$ym$)+ $dist6$,0.###) \end{bmatrix}After:\begin{bmatrix} $eval(( $d$ * $d.pmv$ )/(| $d.et$ |)*( $d.et$ * $xm$ ) + (( $b$ *-1)* $d.pmv$ )/(| $d.et$ |)*( $d.et$ * $ym$ ) + $dist5$ ,0.###)\\ $eval((((( $a$ * $d$ )- $d.et$ )/( $b$ ))* $d.pmv$ *-1)/(| $d.et$ |)*( $d.et$ * $xm$ ) + ( $a$ * $d.pmv$ )/(| $d.et$ |)*( $d.et$ * $ym$ )+ $dist6$ ,0.###) \end{bmatrix}This requires adding a reference to the Microsoft VBScript Regular Expressions 5.5 by going to Tools > References and checking that box:You can read more on Regular Expressions in VBA in this Stack Overflow answer. |
_unix.66352 | How can I grep for a given string in all files in the current directory, and recursively so, only considering the first line? (the #! line, if present, but only if #! is in the -first- line)? | Grep for string in first line of all files in directory and descendants | shell;grep | null |
_softwareengineering.343965 | I started a job as junior programmer a few months ago. The system we are working on has been in production for ~2 years. I wasn't involved in the begging of the system and the design.One thing I have noticed is that the system major version is already 11.Y.Z. Form my experience working with other systems and libraries, I don't recall seeing a product bumping major version that fast. There are products that have been for years in 1.X.Y, and still receiving features and bugfixes.Assuming that the semantic versioning is used properly, does this indicate that the system is poorly designed since it makes major breaking changes almost every four months? | Is fast major version bumping an evidence of poor design? | versioning;semantic versioning | Assuming that the semantic versioning is used properly, does this indicate that the system is poorly designed since it makes major breaking changes almost every four months?Not necessarily.You mentioned in the comments that this is an internal API. Breaking an API is bad, because you break everybody's code. But for an internal API everybody is just you, and you are perfectly capable of coordinating such API changes with yourself, so the pain that is usually associated with API changes is much less worse.Also, the average could be massively misleading: maybe they had 11 breaking API changes during the first couple of days of early development and have been stable for 4 years ever since? SemVer does allow you to make breaking changes without increasing the major number if the major number is 0, but it doesn't force you to. Maybe they started using SemVer from day 0, even during the prototyping / exploratory phases? |
_unix.151090 | Is there something similar to script that records ONLY the commands and not any output from them to a file? | Script command without output | scripting | historyIt shows you what your shell last did. Every command. No output. It is editable. |
_unix.58439 | I created a new user in CentOS 6.3 using this commandsuseradd deployerpasswd deployervisudothen I added this line to file:deployer ALL=(ALL) ALLFine!Now I trying to install rbenv, to deploy an RoR application. I followed this steps:cd /home/deployersu deployercurl https://raw.github.com/fesplugas/rbenv-installer/master/bin/rbenv-installer | bashIt worked. After, I added rbenv to .bashrc and tried to reload .bashrc file andget this error:[deployer@mycentos ~]$ . ~/.bashrc bash: /home/deployer/.rbenv/bin/rbenv: Permission deniedAnyone know why? | Unable to install rbenv with deployer user in CentOS - Permission denied | centos;deployment | Solved!I was getting this error because /home folder was mounted with noexec option.$cat /etc/fstab .../dev/mapper/VG00-LVhome /home ext4 defaults,noexec,nosuid 1 2Now, I changed app to /usr folder and it works!Thank you! |
_unix.128414 | I am using vi-editing-mode on Bash. According to man readline, there are a couple of default binding keys working on vi-editing-mode. Some keys work well, but some other default keys do not work. For example, man readline says,VI Command Mode functions... C-E emacs-editing-mode...But bind -p on my linux box says that 'emacs-editing-mode` is not bound on any key.$ bind -p | grep emacs-editing# emacs-editing-mode (not bound)Is this a normal situation? How to turn on all default binding keys of vi-editing-mode on bash? Do I have to bind keys manually on .inputrc? | How to turn on all default binding keys of vi-editing-mode on bash? | bash;readline | null |
_codereview.141970 | I am using the following code in a Node.js / React project. It works fine but it looks like it could be consolidated a little more using a OO pattern. import projectsData from '../data/index.js';function Project(project) { this.name = project.name; this.order = project.order; this.title = project.title; this.date = project.date; this.tags = project.tags; this.logo = project.logo; this.html = project.html; this.agency = project.agency; this.slides = Object.values(project.slides).map(slide => slide); this.path = `projects/${this.name}`; this.route = `/projects/${this.name}`; this.slidesPath = `/projects/${this.name}/slides/`; this.hiDefAffix = '@2x';};const all = {};Object.values(projectsData).map(project => all[project.name] = new Project(project));const projects = { all, sorted(){ return Object.values(this.all).sort((a, b) => a.order - b.order) }, get(project) { try { if (this.all[project]){ return this.all[project]; } else { throw new Error(`Project ${project} not found.`); } } catch (error) { return false; } }, toJSON() { return JSON.stringify(this.all); }};export default projects;Basically I have a constructor and an exported object that ends up having a bunch of objects created by the constructor above it. Can these be consolidated in some way? | Exporting a list of projects in Node.JS | javascript;object oriented;node.js;react.js | null |
_reverseengineering.3668 | I recently found out about a tool called cycript that apparently does runtime analysis of binaries written with Objective-C. I have a Mac OS X binary that is compiled as x86_64 and is intended to run on Intel Macs. I know cycript is intended to for iOS applications but I wouldn't mind using it on this binary to poke around and see what is going on inside the binary. Most instructions I see for cycript state to start off with UIApp, and then investigating further objects from there.My problem is when I try to investigate UIApp with cycript I get the following error message,ReferenceError: hasProperty callback returned true for a property that doesn't exist.I am assuming I am getting this error message because the binary does not have a UIApp class / method in it because it is a Mac OS X binary and not an iOS.Where would be a good starting point for using cycript with a Mac OS X binary? | How to use cycript to investigate a mach-o x86_64 binary? | osx | UIApp is a shorthand for [UIApplication sharedApplication].As this is not an iOS app, but an OS X app you need to use [NSApplication sharedApplication] instead. |
_softwareengineering.180569 | I'm a beginner-level C++ programmer, but I understand the concepts of the language fairly well. When I began to learn external C++ libraries, like SDL, OpenGL (maybe something else too), to my great surprise I found out that they don't use C++ concepts at all. For example, neither SDL, nor OpenGL use classes or exceptions, preferring functions and error codes. In OpenGL I've seen functions like glVertex2f, which takes 2 float variables as an input and probably would be better as a template. Moreover, these libraries sometimes use marcos, while it seems to be a common agreement that using macroses is bad.All in all, they seem to be written more in C style, than in C++ style. But they are completely different incompaitable languages, aren't they?The question is: why modern libraries do not use the advantages of the language they are written in? | Why don't modern libraries use OOP | c++;object oriented;libraries;opengl | Both OpenGL and SDL are C libraries and expose a C interface to the rest of the world (as pretty much every language out there can interface with C but not necessarily with C++). Thus, they're restricted to the procedural interface that C gives you and the C way of declaring and using data structures.Over and above the interfacing with other languages aspect that a C interface offers you, C in general tends to be a bit more portable than C++, which in turn makes it easier to get the non-platform dependent part of the code of libraries like these working on another OS or hardware architecture. Pretty much every platform out there has a decent C compiler, but there are still some that have restricted C++ compilers or ones that are just not very good.While C and C++ are very different languages, they are not incompatible, in fact, to a large extent C++ is a superset of C. There are some incompatibilities but not many, so using a C interface from C++ is a very easy thing to do. |
_webapps.100605 | What's the significance of Bing's enboldening in some search result entries?I have found no answer to this from web search using Google... or Bing :)For example, some words in some entries (inc. different words in identical phrases):http://www.bing.com/search?q=London&q1=site%3Ahttp%3A%2F%2Fwww.chrisjj.com%2Ftango%2Fcjjsets%2F-> | Significance of Bing's enboldening of some search results | bing | null |
_codereview.97203 | I'm writing 2x2x2 rubics cube simulator. In my code I have a concept of Face which is individual side of the cube, and State which is agregate of all six sides. When I create new State, in addition to creating faces I need to set all neighbour faces for a given face. Currently I do this in manual way, as in:faces[Side.Top][Direction.Up] = faces[Side.Back]; faces[Side.Top][Direction.Down] = faces[Side.Front]; faces[Side.Top][Direction.Left] = faces[Side.Left]; faces[Side.Top][Direction.Right] = faces[Side.Right]; faces[Side.Bottom][Direction.Up] = faces[Side.Front]; faces[Side.Bottom][Direction.Down] = faces[Side.Back]; faces[Side.Bottom][Direction.Left] = faces[Side.Left]; faces[Side.Bottom][Direction.Right] = faces[Side.Right];...However I feel theres more algorithmical approach which I can't figure out. Does anyone know better way to do this?Here's full code I've got so far if anyone's interested. | Get neighbour sides of a Rubics cube | c#;simulation | One more algorithmic approach could be to use a different object model more closely relating to the actual cube. That is instead of keeping the state of faces, keep the state of each part of the cube, i.e.The 8 corner pieces of a 2x2x2 cube, and then keep track of the state of each of these, and then have methods to handle the cube and to get the different faces based on the pieces.If you do this kind of modelling, then your code would also expand easily to larger cube dimensions, as the general movement methods would/should be generic and be applicable to any dimension of the cube.Edit: Added pseudo codeAs always when approaching a problem you need to visualise and simplify into something you are able to comprehend and code. Some givens for this particular problem:The cube is 3D, but at any given time you are only revolving one plane/face of the cubeWhen revolving any given face, pieces keep their internal place in that face, albeit the global position has changed, i.e. the corner piece remains the corner piece, but the top-left corner piece could become the top-right corner pieceAll pieces in a plane is related and will move as oneFor a 2x2x2 cube, use positions from [0, 0, 0] through [1, 1, 1], where [0, 0, 0] is the bottommost, leftmost, frontfacing pieceHow does this help us? Well, one can define and code the 2d operations available, and apply them to the cube, which in turn applies them to each piece in turn. Lets define the operations as Rot + Plane + Direction, where Plane can be X, Y, and Z, and direction is either CW - Clockwise or CCW - CounterClockWise. Operations then become: RotXCW, RotXCCW, RotYCW, and so on. But we need to know which of n=2 planes we're rotating, so lets pass that as an argument.In order to execute the operation RotXCW(1) on the cube, that is rotate the face to the right clockwise, we need to loop through all pieces having x==1, and call RotXCW on each piece:Change piece orientation correctlyLet the piece calculate its own position: x = prevX y = ( prevZ == 0 ) ? 0 : (n-1) z = ( prevY == 0 ) ? (n-1) : 0 To find the new position I wrote down all combinations based on previous position, and looked for the easiest way to represent this acknowledging that the coordinate of a corner piece is always 0 or n-1. Here is the table for rotating clockwise: Old Z Old Y New Z New Y 0 0 > 1 0 1 0 > 1 1 1 1 > 0 1 0 1 > 0 0 This table leads to implementation given that the new Yis the previous Z, and the new Z is the opposite of the previous YIn order to implement this you need a Cube class of dimension n, and this concists of Piece's which has a position, and an orientation. Both classes needs to have rotational methods, and in addition you need a method to display the face, and rotate the face of a given piece. Hopefully this should give you enough to start coding. It might seem heavy, but isolating and diving the concern into handling single pieces will, in my experience, be well worhth it. Now you can call the rotation operation on the cube, and the single concern of that method is to call rotate on the pieces. |
_cogsci.618 | In real-world problem-solving tasks that many people call complex (like flying a jet, programming, fixing a car, fighting a fire - the type investigated by the naturalistic decision making community) what are the key characteristics that separate problem solving in these types of tasks and problem solving in toy or experiment tasks where one or two stimuli are presented to participants? What are the characteristics that make complex problem solving complex?Are there levels of complexity that can capture the differences? | What are the characteristics that make complex problem solving complex? | terminology;decision making;problem solving | null |
_unix.51815 | In Gentoo Linux it is possible to set the MAKEOPTS variable in /etc/portage/make.conf to tell make how many jobs it should run in parallel when building packages. Since I have a dual-core CPU, I naively chose to use the -j2 option: one job per core, so both have something to do. The problem is there are a lot of references that tell users having a dual-core CPU to set the -j3 option instead. Some of them are:Gentoo handbookGentoo wikimake.conf(5) man pageFor example, the Gentoo handbook says:A good choice is the number of CPUs (or CPU cores) in your system plus one, but this guideline isn't always perfect. But what is the rationale for CPUs + 1 rule? Why the extra job?The make.conf(5) man page even says:Suggested settings are between CPUs+1 and 2*CPUs+1.I also read section 5.4 (Parallel Execution) in the make info page and make man page explanation for the -j option, but it seems there's no answers there. | Why people recommend the -j3 option for make when having a dual-core CPU? | gentoo;make | There isn't a simple rule that always works. People might recommend a particular figure because they experimented with a particular compilation on a particular machine and this was the best setting, or because they followed some reasoning that may or may not have some relation with reality.If you're blessed with a lot of RAM, then the limiting factor in a long compilation will be CPU time. Then one task per CPU, plus one pending task for those occasional I/O blocks, is a good setting. That makes it -j3 for a dual-core CPU (or more precisely, for a dual-CPU machine if each core is hyperthreaded, that would be 4 CPUs, so -j5).If you have very little RAM, then a limiting factor may be that you can't have many concurrent jobs, or else they'll keep making each other swap out. For example, if you can't comfortably fit two compiler instances in memory, make -j2 may already be slower than make. Since this is dependent on how many compiler processes you can fit in RAM at once, there's no way to derive a general figure.In between, it may be beneficial to have more jobs. If each compiler process is small, but the build as a whole touches a lot of data, then disk I/O may be the blocking factor. In this case, you'll want several jobs per CPU at once, so that there is always one job using each CPU while others are waiting for I/O. Again, this is very dependent on the build job and on the available RAM, here on what's available for data cache (there's an optimum after which having too many jobs pollutes the cache too much). |
_codereview.119997 | I'd like to make sure error details are never sent out in responses from my restify-powered API. The best way to achieve that seemed to be via wrapping server.formatters in another function which filtered-out Errors before passing the transformed body on to the relevant formatter. I've probably missed some more obvious way to achieve this, but here's what I came up with. Does this seem reasonable, or is there a simpler solution?const server = restify.createServer()// wraps all formatters in a function filtering out Error bodiesObject.keys(server.formatters).forEach((name) => { const formatter = server.formatters[ name ] server.formatters[ name ] = (req, res, body, next) => { // keep possibly sensitive details from going out in error messages if (body instanceof Error && !(body instanceof errors.HttpError) && !(body instanceof errors.RestError) ) { body = new errors.InternalServerError('Internal Server Error') } return formatter(req, res, body, next) }}) | Keeping error details out of responses (Restify) | javascript;node.js;error handling | null |
_codereview.153654 | Here is my code which is going to through multiple for loops to get the matching product attribute.I have single product with attributes trying to find out the matching product with same attribute value from a list of Product. I am having a multiple for loop. Can anyone suggest a way to optimize this solution?// This is my single product which is empty with listOf attributes// (Example : brand, size, color etc.)Product singleProduct = new Product().setAttrs( new ArrayList<ProductAttribute>());int productFound = 0;// Get List of product from respose objectList<Product> products = response.getProductList();for (Product product : products) { for (ProductAttribute proAttr : product.getAttrs()) { for (ProductAttribute singleProdAttr : singleProduct.getAttrs()) { if (proAttr.getValue().equals(singleProdAttr.getValue())) { productFound++; } } }} | Counting items that have a matching attribute | java;performance;join | null |
_unix.271587 | I'm making a opkg package for a software update.This package require a reboot after installation and needs some work done after the next reboot.I added a shutdown -h now in postinst script but it seems to shutdown too early and interrupts the opkg install command.Then the opkg system won't have the package info recorded, like opkg list-installed won't list the package as installed.So the problem I'm trying to solve is: how to reliably schedule a shutdown/reboot in postinst script of OPKG package?But I guess the fundamental question is, how to schedule a task in a shell script that runs as soon as the all the ancestors of current shell die, but not sooner than that? Reference: What's postinst script and opkg package management system | How to schedule a task in a shell script that runs as soon as the all the ancestors of current shell die? | opkg | The problem is ill-defined. If you follow the chain of processes from child to parent, you'll eventually reach process 1 (init). When it dies, it means the system is rebooting.Rebooting a machine is not something that's normally done as part of an upgrade because only the administrator knows when it's safe to reboot. Rebooting during an upgrade is definitely not safe. (Yes, Windows does it, and it's a shining example of what not to do many Windows users have horror stories of lost work because of forced upgrades causing reboots.)If the upgrade is attended, show the administrator a message telling them to reboot as soon as possible.If the upgrade is not attended, then have your automatic upgrade system arrange the reboot. Only your upgrade system knows the particular circumstances that make it safe to reboot at a certain time because you've activated the failover on your server, or because the production line that your embedded device controls is stopped. Your upgrade system runs opkg, and then checks whether an upgrade is needed; for example, it might reboot (when it's safe) if a file /reboot_needed exists. |
_cstheory.18949 | Is there any paper which can be used to show that there can be no relativizing construction of a secret-coin Collision-Resistant Hash Family from a one-way function and unlike this paper, does not claim to show more than it actually shows?The second link shows some result, and I believe that what it actually showsis strong enough, but I'm quite hesitant to cite that paper because the author writes we show that relative to an oracle non-interactive weakly-binding honest-receiver statistically-secret commitments schemes do not exist despite his definition of non-interactive weakly-binding honest-receiver statistically-secret bit commitment schemes corresponding to an otherwise semi-honest receiver that is allowed to choose its random bits maliciously, and requiring perfect completeness and gives a definition of a black-box one-way permutation that does not require injectivity. | one-way functions vs. secret-coin CRHFs | cr.crypto security;hash function;relativization;one way function | null |
_unix.107615 | So, can anyone explain why this doesn't work?Everything from remote host (192.168.1.3):ssh -L 9000:192.168.1.2:80 [email protected] http:127.0.0.1:9000and I can see a web page.other host with www (192.168.1.1):ssh -L 9000:192.168.1.3:80 [email protected] 127.0.0.1:9000and I see another web page.BUT when I try to access a Virtual Machine on 192.168.1.2, then nothing:ssh -L 9000:172.31.255.29:80 [email protected] was trying to log rejected packages (nothing found), tcpdump shows answer from vm to virbr0What could be the problem? I have got only one clue, that it might be unix socket related but need advice from somebody who understands that better than me. | ssh local tunnel to VM | ssh;kvm;ssh tunneling | null |
Subsets and Splits