id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_unix.212157
I am trying to modify a file system image packed with cpio. For that reason I first need to extract and later pack the image. As the image contains a whole file system all the files are given in absolute file names, so I can't directly pack and unpack it, since it would conflict with my machine's root system.So when unpacking I used --no-absolute-filenames to unpack it to a working directory of my choice. Now I want to pack it again. If I just pack it i'd only get files like that:/path/to/working/directory/file1/path/to/working/directory/file2/path/to/working/directory/file3or./file1./file2./file3instead of/file1/file2/file3Does anyone know how I could get the desired output? Google didn't help me so far.I really need absolute path names in the output file, because I am using it for an u-boot uImage file system image, and that requires the paths to be absolute, or it won't boot.
Create cpio file with different absolute directory
u boot;cpio
Use pax and its -s option to rename files as they are added to the archive. Pax is POSIX's replacement for the traditional utilities tar and cpio; some Linux distributions don't install it by default but it should always be available as a package.pax -w -x cpio -s '~^[/]*~~' root-directory >archive.cpio
_codereview.71876
I was asked to implement a graph and BFS and DFS.Please comment. Is it understandable? Is my algorithm correct? Are there any optimizations? using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication2{ public class Graph { public List<Node> list; public Graph() { list = new List<Node>(); } } public class Node { public int Index { get; set; } public List<Node> neighbors; public Node(int index) { Index = index; neighbors = new List<Node>(); } public void AddNeighbor(int index) { neighbors.Add(new Node(index)); } }}using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication2{ public class BFS { public BFS() { Graph graph = new Graph(); graph.list.Add(new Node(0)); graph.list.ElementAt<Node>(0).AddNeighbor(1); graph.list.ElementAt<Node>(0).AddNeighbor(2); graph.list.ElementAt<Node>(0).neighbors.ElementAt<Node>(0).AddNeighbor(3); GraphTraverseBFS(graph); } public void GraphTraverseBFS(Graph graph) { Queue<Node> queue = new Queue<Node>(); queue.Enqueue(graph.list[0]); while(queue.Count > 0) { Node tempNode = queue.Dequeue(); Console.WriteLine(Node number: +tempNode.Index); foreach (var item in tempNode.neighbors) { queue.Enqueue(item); } } } } }using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication2{ public class DFS { public Graph graph { get; set; } public DFS() { graph = new Graph(); graph.list.Add(new Node(0)); graph.list.ElementAt<Node>(0).AddNeighbor(1); graph.list.ElementAt<Node>(0).AddNeighbor(2); graph.list.ElementAt<Node>(0).neighbors.ElementAt<Node>(0).AddNeighbor(3); GraphTraverseDFS(graph); } public void GraphTraverseDFS(Graph graph) { Stack<Node> stack = new Stack<Node>(); stack.Push(graph.list[0]); while (stack.Count != 0) { Node tempNode = stack.Pop(); Console.WriteLine(Node number: + tempNode.Index); var negibours = tempNode.neighbors; foreach (var item in negibours) { stack.Push(item); } } } }}
Graph Creation and BFS + DFS in C#
c#;algorithm;interview questions;breadth first search;depth first search
Let's take a step back and consider the API.Suppose I want to test the BFS traversal on different graphs.To call GraphTraverseBFS I need to first create a BFS object. But the BFS constructor creates its own graph and runs GraphTraverseBFS on that. There is no clean way for me to just test it on my own graph.So let's say that's fixed. Now I want to write some unit tests for GraphTraverseBFS. I can't currently do this without redirecting where the output messages are written to, and then parsing the output. This is more work than I want to do. Ideally I would be able to write something likeCollectionAssert.AreEqual(new[] { 0, 1, 2, 3 }, BFS.Traverse(graph));The same comments hold for DFS.List<T> is (generally) an implementation detail.Graph has a public field List<Node> list. The fact that you're storing nodes in a List is an implementation detail, and should not be exposed to users of this code.The user now has full access to the methods of List, and can manipulate the list however they want. This is more power than they should have.The user can reassign the field, e.g. graph.list = null.It locks you in to your choice of graph representation, as the user may write code that depends on list being a List.Similar comments hold for Node.neighbors.One pattern I like for letting the user iterate over a collection, without exposing the choice of implementation is toHave a private readonly field with your choice of collection type (List, HashSet, etc)Have a public IEnumerable<T> read-only property that exposes the collection for iterationIn code, it looks like thispublic class Graph{ private readonly List<Node> nodes = new List<Node>(); public IEnumerable<Node> Nodes { get { return this.nodes; } } ...}This might not be entirely suitable for you needs, but this is the sort of API I would suggestpublic class Graph{ // Creates a new graph with `count` vertices. public Graph(int count) public IEnumerable<int> GetNeighbors(int node); public void AddEdge(int n, int m);}public static class BFS{ public static IEnumerable<int> Traverse(Graph graph, int startNode = 0);}public static class DFS{ public static IEnumerable<int> Traverse(Graph graph, int startNode = 0);}
_unix.289354
I'm trying to mount a network shared device in a linux box. I get permission issue but it was mounted properly in another linux server. The only difference on the server it works has a + permission at the end. Can anyone explain what it is and how can i set the same permission on the linux it is failing?Folder permission on the working machinedrwxr-xr-x+ 14 root root 32 Jan 1 12:02 shared_foldergetfacl: Removing leading '/' from absolute path names# file: shared_folder# owner: root# group: rootuser::rwxgroup::r-xmask::rwxother::r-xFolder permission on the non-working machinedrwxr-xr-x 14 root root 32 Jan 1 12:02 shared_foldergetfacl: Removing leading '/' from absolute path names# file: shared_folder# owner: root# group: rootuser::rwxgroup::r-xother::r-xI tried below to modify the acl permission and it don't work.setfacl -m mask:rwx /softwaresetfacl: /software: Operation not supported
How to set folder permission with + at the end?
linux;permissions;directory
null
_codereview.146629
I'm writing my first small programs in Haskell and still getting a feel for the syntax and idioms. I've written this Mad Libs implementation using recursive IO. I've used IO actions throughout and I'm sure there must be a better way of splitting up this code to separate pure functions from IO actions. Also, I'm not happy with the printf statement, but I couldn't find a native way to apply an arbitrary number of list items to printf.import Text.PrintfgetAnswer :: String -> IO StringgetAnswer question = do putStrLn question answer <- getLine return answergetAnswers :: [String] -> [String] -> IO [String]getAnswers [] ys = return ysgetAnswers (x:xs) ys = do answer <- getAnswer x let answers = ys ++ [answer] getAnswers xs answersmain = do let questions = [Enter a noun:, Enter a verb:, Enter an adjective:, Enter an adverb:] let madlib = Your %s is %s up a %s mountain %s. answers <- getAnswers questions [] printf madlib (answers!!0) (answers!!1) (answers!!2) (answers!!3) putStrLn
Mad Libs using recursive IO for user input
beginner;haskell;formatting
Can we make getAnswer simpler or out of IO? Well, not really. You want to ask the use a question, and you want to get an answer. So all we could do is to reduce the amount of unnecessary code:getAnswer :: String -> IO StringgetAnswer question = putStrLn question >> getLine-- or-- = do-- putStrLn question-- getLineHowever, getAnswers can be refactored quite heavily. First of all, its interface isn't really developer-friendly. What are the questions? What are the answers? We should probably hide that in the bowels of our function:getAnswers :: [String] -> IO [String]getAnswers xs = go xs [] where go [] ys = return ys go (x:xs) ys = do answer <- getAnswer x let answers = ys ++ [answer] go xs answersBut ++ [...] isn't really best-practice. Instead, you would ask all other questions and then combine them: where go [] = return [] go (x:xs) = do answer <- getAnswer x otherAnswers <- getAnswers x return (answer : otherAnswers)But at that point, we're merily copying mapM's functionailty. Therefore, your getAnswers should begetAnswers :: [String] -> IO [String]getAnswers = mapM getAnswerA lot simpler.Now for your main. If you don't know how many words you'll get you will need a list, correct. But lets check the structure of your result: Your %s is %s up a %s mountain %s. 1 2 3 4There is a pattern. We have our text, then whatever the user gave us, then again our text, and so on. Let's split that into fragments:[Your ,%s, is ,%s, up a ,%s, mountain ,%s,.]-- ^^^^ ^^^^ ^^^^ ^^^^This brings up the following idea: if you have a list of your answers, you only need the list of the other words, right?[Your , is , up a , mountain ,.]And then we need to zip that list with yours:interleave :: [a] -> [a] -> [a]interleave (x:xs) (y:ys) = x : y : interleave xs ysinterleave xs _ = xsWe end up with the following main:main = do let questions = [Enter a noun:, Enter a verb:, Enter an adjective:, Enter an adverb:] let madlib = [Your , is , up a , mountain ,.] answers <- getAnswers questions putStrLn $ interleave madlib questionsHere's all the code at once:getAnswer :: String -> IO StringgetAnswer q = putStrLn q >> getLinegetAnswers :: [String] -> IO [String]getAnswers = mapM getAnswerinterleave :: [a] -> [a] -> [a]interleave (x:xs) (y:ys) = x : y : interleave xs ysinterleave xs _ = xsmain :: IO ()main = do let questions = [Enter a noun:, Enter a verb:, Enter an adjective:, Enter an adverb:] let madlib = [Your , is , up a , mountain ,.] answers <- getAnswers questions putStrLn $ interleave madlib questionsExercisesThe interleave function above is left-biased. Why? Could this pose problems for your program? Why not?
_unix.384553
I want to show two pages of a pdf document at the same time in PDF viewer such thatbe able to scroll pages 1,..,N-1 at the left-hand-side viewshow all the time page N at the rigth hand-side viewThe reason is that I am inputing data on pages 1,..,N-1 from the user, while the page N aggregates the data on page N. So I want to show all the time the last page. Maybe, it is possible somehow in some internet browser. OS: Debian 9PDF viewer: any PDF viewer, but preferably Adobe acroread with Javascript installed like hereInternet browsers: Firefox 52.2.x, Google Chrome 59.x
How to scroll pages 1,..,N-1 and show page N in PDF viewer?
debian;pdf;browser;adobe acrobat
null
_webmaster.71241
In assisting with the migration of a friend's site, we discovered that 301 redirects had been created for what are, ultimately, temporary pages.These temporary pages then point to a canonical URL with an appended directory within the URL.For example, '/page.php' 301 redirects to '/page' which then canonically refers to '/category/page' . In tidying up this arrangement, would it be preferable to adjust the existing 301 redirects to point to the final destination URL, or would a second, new list of 301 redirects be more appropriate, or some other alternative?
What is an optimum redirect / canonical path for this instance?
seo;301 redirect;canonical url
null
_unix.211516
Running lxde and lxpanel on Debian 8.1. xdotool key XF86LogGrabInfo lists no actively grabbed devices in /var/log/Xorg.0.log. Clicking the Screenlock icon in the application launch bar has a long delay before activating screenlock and fails to grab the mouse, with the error couldn't grab pointer (AlreadyGrabbed). It fails to detect mouse movement to wake up the screensaver and doesn't intercept mouse events. The command xscreensaver-command -lock works properly so I've tried the following: /etc/xdg/lxpanel/LXDE/panels/panel shows:Plugin { type = launchbar Config { Button { id=lxde-screenlock.desktop } Button { id=lxde-logout.desktop } }}/usr/share/applications/lxde-screenlock.desktop shows it is executing lxlock:[Desktop Entry]Type=ApplicationName=ScreenLockName[es]=Bloqueo de pantallaName[pt_BR]=Bloquear telaName[ru]= Name[tr]=ScreenLockName[uk]= Name[zh_TW]=Comment=Lock your screenComment[es]=Bloquear pantallaComment[pt_BR]=Bloqueie sua telaComment[ru]= Comment[tr]=Ekran kilitleComment[uk]= Icon=system-lock-screenExec=lxlockTryExec=lxlockNoDisplay=trueEdited lxde-screenlock.desktop to execute xscreensaver-command --lock instead of lxlock:Exec=/usr/bin/xscreensaver-command -lockTryExec=/usr/bin/xscreensaver-commandEven though I've changed the desktop entry file and the lxsession configuration's lockscreen manager to xscreensaver-command -lock it lags and fails to grab the mouse when using the tray icon. I've restarted the lxsession and confirmed that this desktop entry is being used by the tray icon.Update:I've also tried adding the Lock Screen (XScreenSaver) menu item from the Debian section of the application menu to lxpanel's application launchbar. The problem persists. Screen lock functions properly when run by any other method (terminal, application menu, and LXDE logout menu), so I am inclined to call it a bug caused by lxpanel.Edit: I'm currently using an openbox keybinding to execute xscreensaver-command -lock as a work around, but I would still like to determine why running it from the application launcher fails.
xscreensaver screenlock Couldn't Grab Pointer - Already Grabbed
lxde;screen lock;xscreensaver
null
_codereview.119278
I am writing a class which can log the activity of an application during run time. The plan is that the SupportMI string will be sent to a DB, from where I can use some other code to format it properly for readability. I need this class to be usable with .Net-3.5 due to system limitations.What I need is the method name, the values of the parameters passed, and the output of the method (if specified). I also added a timer class to measure performance:using System;using System.Diagnostics;namespace MyTimer{ class MILogger : IDisposable { private string SupportMI; private Stopwatch stopwatch = new Stopwatch(); private string[] parameters; public static string methodoutput; public MILogger() { stopwatch.Start(); } public MILogger(params string[] args) { stopwatch.Start(); parameters = args; } public void Dispose() { stopwatch.Stop(); // New stacktrace StackTrace stackTrace = new StackTrace(); // Method var method = stackTrace.GetFrame(1).GetMethod(); string methname = method.Name; SupportMI += methname + (; // Sorting parameters for (int i = 0; i < parameters.Length; i++) { if (i > 0) { SupportMI += ,; } SupportMI += parameters[i]; } // Timer, methooutput and some punctuation SupportMI += ) { ; SupportMI += methodoutput; SupportMI += TIMER: + stopwatch.ElapsedMilliseconds.ToString(); SupportMI += }; } public static void SendMI() { // Send SupportMI to a database DBConnection db = new DBConnection(SupportMI); } }}Usage:class Program{ static void Main(string[] args) { TestMethod(HELLO, HI, 123); // Other code MILogger.SendMI(); } public static string TestMethod(string str, string qwe, int dsad) { using (new MILogger(str, qwe, dsad.ToString())) { MILogger.methodoutput = str + qwe + dsad.ToString(); return str + qwe + dsad.ToString(); } }}And the output looks like this: TestMethod(HELLO,HI,123) { HELLOHI123 TIMER: 1}With this I can more easily debug instances of the application being used by checking that the correct parameters are being passed in each method.I thought it was weird that there is no easier way to get the parameter values. Does anyone have any feedback or thoughts on how this could be done better?I'm also aware that I've used multiple ToStrings()s where this may not be strictly necessary.The DB class:class DBConnection{ public DBConnection(string objecttosend) { // connect to DB using (SqlConnection conn = new SqlConnection()) { // create the connection string conn.ConnectionString = ConnectionStringGoesHere; // open the db connection conn.Open(); // insert info into DB SqlCommand insertCmd = new SqlCommand(INSERT INTO IncidentLog (SupportMI) VALUES (@SupportMI), conn); insertCmd.Parameters.Add(new SqlParameter(@SupportMI, objecttosend)); // execute insertCmd.ExecuteNonQuery(); // close the db connection conn.Close(); } }}Example output of what I'm going for (achieved with a lot of hard-coding):INITIALISE { Servers.GetServers() { } GetSession() { CheckFile() { [server file exists] Query(XA7-02) { StdOut(QUERY SESSION HelenA /SERVER:XA7-02.mydomain.co.uk) { ExecuteCommand() { } SESSIONNAME USERNAME ID STATE TYPE DEVICE ica-cgp#0 User.Name 2 Active } } [correct server] } }}INIT 1953 GetProcList(XA7-02){ StdOutAdminList(tasklist /S XA7-02.mydomain.co.uk /FI SESSION eq 2 /FO CSV /NH) { ExecuteListCommand() { } } Creating Proc LYNC.EXE--addingLYNC.EXE--Creating Proc BUSYLIGHT.EXE--addingBUSYLIGHT.EXE--Creating Proc OUTLOOK.EXE--addingOUTLOOK.EXE--Creating Proc SLLAUNCHER.EXE--addingSLLAUNCHER.EXE--Creating Proc TOTALSPEECH.EXE--addingTOTALSPEECH.EXE--Creating Proc PROWC.EXE--addingPROWC.EXE--}Kill(){ ExecAdmin(taskkill /S XA7-02 /PID 6476 /F) { }}| EXIT |
Method/parameter tracer
c#;logging;reflection
NamingFields should be named using camelCase casing, so SupportMI -> supportMI. Abbreviations shouldn't be used for naming things, but I assume that MI has a special business meaning to you. If not, consider to rename this as well. If the field is public one should use PascalCase casing for naming it. For compound words each new word will start with an uppercase letter , so methodoutput -> MethodOutput. Using abbreviations for names is a no go as well, so andmethname->methodName`. GeneralBy using the string.Join() method the sorting of the parameter can be improved a lot. Instead of using string concatenation you should use a StringBuilder and its Append() method. This avoids the creation of a lot of string objects. The StringBuilder's methods are implemented using a fluent interface which means that the methods return the StringBuilder's instance so one code for instance use it like stringBuilderObject.Append(someValue).Append(someOtherValue)...You could implement this like so var method = stackTrace.GetFrame(1).GetMethod();var builder = new StringBuilder();builder.Append(method.Name) .Append(() .Append(string.Join(,, parameters)) .Append() { ) .Append(MethodOutput) .Append( TIMER: ) .Append(stopwatch.ElapsedMilliseconds) .Append(}); supportMI = builder.ToString();
_unix.18171
I was customizing my bash prompt (I'm on OS X 10.7) when I came across something strange. Within my prompt I included !, which should give me the history number.However the history number always starts out at 501, instead of 1. This is true even if I restart Terminal.I can't seem to find anything close to this, I was wondering if you guys could offer some insight.
Bash history number not starting at 1?
bash;terminal;command history;prompt
From man bash: On startup, the history is initialized from the file named by the vari able HISTFILE (default ~/.bash_history). The file named by the value of HISTFILE is truncated, if necessary, to contain no more than the number of lines specified by the value of HISTFILESIZE. [...] When an interactive shell exits, the last $HISTSIZE lines are copied from the history list to $HISTFILE.While that text is quite clear, let's play a bit by example (this is a deb system, but bash is bash).My history status right now:~$ set | grep HISTHISTCONTROL=ignoredups:ignorespaceHISTFILE=/home/hmontoliu/.bash_historyHISTFILESIZE=2000HISTSIZE=1000Since HISTFILESIZE is 2000 and HISTSIZE is 1000 only the last 1000 lines of the HISTFILE are available so you can get the wrong impression that my history starts at 1000.~$ history | head -1 1000 if i=1; then echo $i; done~$ history | wc -l1000But indeed the HISTFILE stores the last 2000 commands: ~$ wc -l $HISTFILE2000 /home/hmontoliu/.bash_historyIf you think that it is annoying you can equal the HISTSIZE and HISTFILESIZE~$ echo export HISTSIZE=$HISTFILESIZE >> .bashrc~$ bash -l~$ history | head -1 1 ls~$ history | wc -l2000~$ set | grep HISTHISTCONTROL=ignoredups:ignorespaceHISTFILE=/home/hmontoliu/.bash_historyHISTFILESIZE=2000HISTSIZE=2000A final hint: you should run help history to view the actions you can do with your history
_unix.348375
I want to read all java Versions on my system.for i in 'find / -name java 2>/dev/null' doecho $i checking$i -versiondoneI receive an error:find: paths must precede expression: 2>/dev/nullUsage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]What is the problem?
Using for loop with find command
find;for
You're receiving that error from the for loop because your for loop is actually looping over one element -- the string, not the command: find / -name java 2>/dev/null, so it is running:echo find / -name java 2>/dev/null checkingfind / -name java 2>/dev/null -version... which is where find's error arises.You might be trying to do:for i in `find / -name java 2>/dev/null` do echo $i checking $i -versiondone... (with backticks instead of single quotes), in which case I would suggest something more along the lines of:find / -name java -exec sh -c '$1 -version' sh {} \; 2>/dev/nullThanks to don_crissti for pointing out Stphane's better version of find ... exec and for indirectly reminding me of a bash method that is one better way to find and execute results than looping over find:shopt -s globstar dotglobfor match in /**/javado echo match is $match $match -versiondone
_webmaster.10817
I've been wondering about this for a while but never come across a solid answer.Many websites include their name in all the title tags of their articles. This is often apparent in word-press blogs etc.eg: Tsunami hits Japan and leaves thousands homeless | My Website NameThe issue I have is that Search engines strip the stop words out of this sentence to leave the words in which it compares to the body text.So if I want my article to rank well and be relevant, in this case about the terrible Tsunami that has recently struck Japan what is to STOP the MY WEBSITE NAME section of the title de-valuing the relevance of the article.Am I over-worrying?Or should I take this in to consideration?Thanks for advice in advance.
Does your company name in an article title damage Search Engine relevance
search;google;seo;search engines
null
_webmaster.108697
Suppose I want to track my website traffic those who are coming from my offline marketing such as pamphlet and hoarding or any other physical activity. I have installed Google Analytics and webmaster on the website.If it is possible, let me know the proper setting and part in Google Analytics.
How do we track offline marketing traffic to my website using Google Analytics?
google analytics;tracking;marketing;offline marketing
null
_webmaster.39907
For SEO, Content is King.I wonder what would be the SEO cost of garbage text inserted between descriptive content.The case I have in mind concerns ascii art.Such page would contain consecutive blocks containing a description of the ascii art, followed by the ascii art itself.Example:<div class='asciiart'> <div class='description'>here is an hideous kitty</div> <div class='ascii'><pre> (%(// (6%( /%7%CCGG66%%C (%7%%G#QO%C%( /%7%%%OOGC777%/ 77(%G6C6GQ%(%/ C67%%776%7%%% (O%OGQQ#GCC (77%G6CGQG%( 7%%%%%GQ%%C%/ (%77%%GQ6%%%%( /#O((%GQGGG%%7( O%7%%%OOGC%%%%( (%%77%CGQ@Q%%%(%%/ /C%766OQQ#OQG6C777%( 7%C7%%6GGQGQO6%%%%7%(7%77%OQ@Q#@#QC%((%%%/(7%7%%GG(%OQ#Q#QGC%77/ 7%77%6OOGQ@#%O6%(7%%/ /77%%6GQ@#QCOQGCO%%( /(%C6G##@@QOO%%%/ ///(O@#@(/(/ /#@6/ (GG#/ /@@O /@@6 Q@O ( /O@O @@6 /(QQ@@ (@@6@#</pre> </div></div>or maybe worse, instead of <pre> element, the ascii art can be composed of consecutive <span> in <div> in order to set different colors to each part of the art.In both case, the page is full of textual data that are non-sense for a search engine.If this implies a negative impact on SEO, is there a way to tell the search engine to ignore these garbage parts?
SEO cost of garbage text
seo
null
_cs.55268
This question is about the use of 'ranking' of regular languages in applications such as format preserving encryption.I understand format preserving encryption but I don't understand how regular expressions can be used to get an integer that is the input of an encryption algorithm. Referring to this video https://youtu.be/MT5ketZ-jLw?t=24m44s at time stamp 24:44According to the process described - In order to encrypt a string to a ciphertext of some agreed upon format, you need to rank all the possible strings it can be - then using your FPE function encrypt the integer that represents the input plain text to an integer in the same set - unrank the output integer to a ciphertext. I don't understand what is being ranked? Are they actually obtaining all possible string representations of the regular expression and ranking those? Or are they ranking something else? Where does the DFA come to play - because I can see a brute force way you can do this without bothering with the DFA - or even regular expressions to define the format. EDIT:I have already most of the paper that use ranking in regular languages for encryption such as these onesMihir Bellare, Thomas Ristenpart, Phillip Rogaway, and Till Stegers Selected Areas in Cryptography, pages 295-312. Springer-Verlag, 2009 (online, see sec 5 p 10 FPE for arbitrary RLs)Daniel Luchaup, Kevin P. Dyer, Somesh Jha, Thomas Ristenpart and Thomas Shrimpton To appear in the proceedings of USENIX Security 2014Anyway I'm just looking for a 'laymans' explanation of how this works as I cannot find any working examples online. This would be useful to understand the overall procedure. All examples I have found regarding regular expressions involve creating the DFA, and most of them end there. What happens next?The closest I could find was this post which I think is asking the same thing https://cstheory.stackexchange.com/questions/18589/algorithm-for-ranking-members-of-a-regular-language
How do you rank the strings represented by a regular expression?
regular expressions;cryptography
null
_webmaster.50537
How can I forward a 'non-existant' subdomain to a 'physical' subdomain? I.e.: api.website.com -> api.company.comWhere the first is just a CNAME pointer and the last is a real subdomain with a root.At website.com I have:api CNAME api.company.com.At company.com I have:api.website.com CNAME api.company.com (also tried this with just API)api.company.com A 1.2.3.4
Forward a 'non-existant' subdomain to a 'physical' subdomain
dns;subdomain
It appears that you want to create a subdomain to a root IP address, and then forward a subdomain from a different domain to this subdomain.First you would create an A record for the api.company.com subdomain as demonstrated here under Example 1 (ignoring the FTP part; also note that www is considered a subdomain as well, just like api). So in the DNS tables for company.com you'd create an A record for:api.company.com A 1.2.3.4This establishes an alias record for host api.company.com at IP address 1.2.3.4Next you'd create a CNAME to this external host as demonstrated here under Example 3. So in the DNS tables for website.com you'd create a CNAME record for:api CNAME api.company.com.This points api.website.com -> api.company.comThen you'd need to wait 24-48 hours for these DNS changes to propagate to DNS servers throughout the Internet in order for these subdomains to resolve properly, so don't make any other changes during that time.
_codereview.165419
Recently during my internship, I was told by one of my fellow workers who graduated from University that my programming was lacking in Math Physics formulas for my vehicle movement script and that how I did it was very wrong.I don't expect a fully rewritten script, I just want to know where and what I could improve on. Maybe the coding structure, Whether how I did everything using my way is right or wrong.using System.Collections;using System.Collections.Generic;using UnityEngine;public class VehicleManagerBackUp : MonoBehaviour{ Rigidbody rb; LogitechGSDK.DIJOYSTATE2ENGINES logitechSDK; /* Engine sound of the vehicle */ AudioSource enginesource; /* Get the button pressed on the wheel */ int wheelButtonPressed; /* Engine Variables */ bool engineStartBool; bool ranOnceEngine; bool slowDownVehicle; /* How long does it take to accelerate or turn? */ double momentumAccelerate; double momentumDecelerate; double momentumTurning; double momentumAccelerateLimit; double momentumBrake; /* Maximum number of how acceleration and turning can go to */ float lengthOfBrake; float lengthOfAcceleration; float lengthOfTurning; float lengthOfClutch; /* Raw input of acceleration and turning of wheels and pedals */ float brake; float acceleration; float turning; float clutchPedal; /* slowly increases based on momentumaccelerate and momentumturning */ double accelerationTime; double turningTime; double momentumBrakeTime; /* changes from cameraA to cameraB */ bool drivingPosition; /* clutch status */ string clutch; string previousClutch; bool vehicleReady; string actualClutch; /* checks if user was from accelerate and switches to reverse without waiting for momentum end */ bool momentumEnded; /* Rate of Momentum Multiply */ float rateOfMomentumStart; float rateOfMomentumBrake; /* Decreases when braking */ float lengthOfBrakingAndAcceleratingForce; private static VehicleManager instance = null; public static VehicleManager GetInstance() { return instance; } void Start() { rateOfMomentumStart = 1.01f; rateOfMomentumBrake = 0.0005f; clutch = Neutral; slowDownVehicle = true; enginesource = GetComponent<AudioSource>(); momentumAccelerateLimit = 0.0002f; momentumAccelerate = momentumAccelerateLimit; momentumTurning = 0.2f; momentumBrake = rateOfMomentumBrake; drivingPosition = true; rb = GetComponent<Rigidbody>(); lengthOfAcceleration = 0.05f; // 0 to 0.05 Acceleration // How fast the vehicle can go lengthOfBrake = lengthOfAcceleration; lengthOfTurning = 20f; lengthOfClutch = 10f; } void Update() { logitechSDK = LogitechGSDK.LogiGetStateUnity(0); engineStart(); convertRangePosition(); switchDrivingPosition(); if (clutchPedal != 0 && accelerationTime == 0) { setClutch(); } Debug.Log(rb.velocity); } void FixedUpdate() { brakingVehicle(); accelerationControl(drivingPosition); } void normalKeyboredControls() { if (Input.GetKeyDown(KeyCode.UpArrow)) acceleration = 1; else acceleration = 0; if (Input.GetKeyDown(KeyCode.LeftArrow)) turning = 2; else if (Input.GetKeyDown(KeyCode.RightArrow)) turning = -2; if (Input.GetKeyDown(KeyCode.U)) clutch = Accelerate; if (Input.GetKeyDown(KeyCode.I)) clutch = Neutral; if (Input.GetKeyDown(KeyCode.O)) clutch = Reverse; } void engineStart() { if (Input.GetButton(StartEngine) || Input.GetKey(KeyCode.N)) { if (!ranOnceEngine) { ranOnceEngine = true; if (engineStartBool) { /*enginesource.Stop(); */ slowDownVehicle = true; Debug.Log(Stop); } else { /*enginesource.Play(); */ slowDownVehicle = false; Debug.Log(Start); } engineStartBool = !engineStartBool; } } else { ranOnceEngine = false; } } void setClutch() { if (Input.GetButton(Accelerate1) || Input.GetButton(Accelerate2) || Input.GetButton(Accelerate3) || Input.GetButton(Accelerate4)) { if (clutch == Neutral && accelerationTime <= 0) { clutch = Accelerate; } } else if (Input.GetButton(Reverse1) || Input.GetButton(Reverse2) || Input.GetButton(Reverse3)) { if (clutch == Neutral && accelerationTime <= 0) { clutch = Reverse; } } else clutch = Neutral; } void convertRangePosition() // Changes 500 to -500 into 0 to 1000 { brake = -(((logitechSDK.lRz - 32767f) / (32767f + 32767f) * lengthOfBrake)); acceleration = -(((logitechSDK.lY - 32767f) / (32767f + 32767f) * lengthOfAcceleration)); // range from 0 to lengthOfAcceleration a^2 * how long i have accelerated velocity turning = -((((logitechSDK.lX - 32767f) / (32767f + 32767f) * lengthOfTurning)) + (lengthOfTurning / 2)); clutchPedal = -(((logitechSDK.rglSlider[0] - 32767f) / (32767f + 32767f) * lengthOfClutch)); } //Moves the vehicle forward & stops if no acceleration is given, changes view of the camera void accelerationControl(bool n) { if (accelerationTime < momentumAccelerate && acceleration == 0) { accelerationTime = 0; momentumEnded = true; } else if (accelerationTime > acceleration || slowDownVehicle || clutch == Neutral) // Stopping { if (accelerationTime > 0) { //if (acceleration == 0) //{ // if (brake > 0) // { // accelerationTime -= ((momentumAccelerate * rateOfMomentumStart) + ((brake / lengthOfBrake) * 0.001)); // } //} //else //{ accelerationTime -= ((momentumAccelerate * rateOfMomentumStart) + ((brake / lengthOfBrake) * 0.001)); //} vehicleReady = false; } else { vehicleReady = true; } momentumEnded = false; } else if (accelerationTime < acceleration) // Drive Forward { accelerationTime += momentumAccelerate; if (accelerationTime > lengthOfBrakingAndAcceleratingForce) accelerationTime = lengthOfBrakingAndAcceleratingForce; momentumEnded = false; } if (accelerationTime > 0) { if (n) { if (clutch == Reverse) { driveVehicle(accelerationTime); previousClutch = Reverse; } else if (clutch == Accelerate) { driveVehicle(-accelerationTime); previousClutch = Accelerate; } else if (clutch == Neutral) { if (previousClutch == Accelerate) driveVehicle(-accelerationTime); else if (previousClutch == Reverse) driveVehicle(accelerationTime); } turningVehicle(drivingPosition, clutch); } else { if (clutch == Reverse) { driveVehicle(-accelerationTime); previousClutch = Reverse; } else if (clutch == Accelerate) { driveVehicle(accelerationTime); previousClutch = Accelerate; } else if (clutch == Neutral) { if (previousClutch == Accelerate) driveVehicle(accelerationTime); else if (previousClutch == Reverse) driveVehicle(-accelerationTime); } turningVehicle(drivingPosition, clutch); } } } void driveVehicle(double value) { rb.MovePosition(transform.position + transform.forward * ((float)value/* / 10*/)); } void brakingVehicle() { if (brake > momentumBrakeTime) momentumBrakeTime += momentumBrake; else momentumBrakeTime -= momentumBrake; if (brake > 0) { lengthOfBrakingAndAcceleratingForce = lengthOfAcceleration - (float)momentumBrakeTime; } else { lengthOfBrakingAndAcceleratingForce = lengthOfAcceleration; } //acceleration -= brake; //if(brake > 0) //{ // if(acceleration > 0) // { //acceleration -= brake; //} //else //{ //accelerationTime //accelerationTime -= momentumAccelerate; //momentumAccelerate //} //} } void turningVehicle(bool n, string clutch) { if (n) turningTime = (((accelerationTime * 10) * turning)); else turningTime = -(((accelerationTime * 10) * turning)); if (n) { if (clutch == Accelerate) { var desiredRotQ = Quaternion.Euler(transform.eulerAngles.x, transform.eulerAngles.y + (float)-turningTime, transform.eulerAngles.x); transform.rotation = Quaternion.Lerp(transform.rotation, desiredRotQ, Time.deltaTime * 10f); } else if (clutch == Reverse) { var desiredRotQ = Quaternion.Euler(transform.eulerAngles.x, transform.eulerAngles.y + (float)turningTime, transform.eulerAngles.x); transform.rotation = Quaternion.Lerp(transform.rotation, desiredRotQ, Time.deltaTime * 10f); } else { if (previousClutch == Reverse) { var desiredRotQ = Quaternion.Euler(transform.eulerAngles.x, transform.eulerAngles.y + (float)turningTime, transform.eulerAngles.x); transform.rotation = Quaternion.Lerp(transform.rotation, desiredRotQ, Time.deltaTime * 10f); } else { var desiredRotQ = Quaternion.Euler(transform.eulerAngles.x, transform.eulerAngles.y + (float)-turningTime, transform.eulerAngles.x); transform.rotation = Quaternion.Lerp(transform.rotation, desiredRotQ, Time.deltaTime * 10f); } } } else { if (clutch == Accelerate) { var desiredRotQ = Quaternion.Euler(transform.eulerAngles.x, transform.eulerAngles.y + (float)turningTime, transform.eulerAngles.x); transform.rotation = Quaternion.Lerp(transform.rotation, desiredRotQ, Time.deltaTime * 10f); } else if (clutch == Reverse) { var desiredRotQ = Quaternion.Euler(transform.eulerAngles.x, transform.eulerAngles.y + (float)-turningTime, transform.eulerAngles.x); transform.rotation = Quaternion.Lerp(transform.rotation, desiredRotQ, Time.deltaTime * 10f); } else { if (previousClutch == Reverse) { var desiredRotQ = Quaternion.Euler(transform.eulerAngles.x, transform.eulerAngles.y + (float)-turningTime, transform.eulerAngles.x); transform.rotation = Quaternion.Lerp(transform.rotation, desiredRotQ, Time.deltaTime * 10f); } else { var desiredRotQ = Quaternion.Euler(transform.eulerAngles.x, transform.eulerAngles.y + (float)turningTime, transform.eulerAngles.x); transform.rotation = Quaternion.Lerp(transform.rotation, desiredRotQ, Time.deltaTime * 10f); } } } } //Changes the position of the driving position void switchDrivingPosition() { if (Input.GetKeyDown(KeyCode.M) && accelerationTime <= 0) { drivingPosition = !drivingPosition; } if (drivingPosition) // A is active { LoadManager.GetInstance().vehicleCamera[1].SetActive(true); LoadManager.GetInstance().vehicleCamera[0].SetActive(false); } else // B is active { LoadManager.GetInstance().vehicleCamera[0].SetActive(true); LoadManager.GetInstance().vehicleCamera[1].SetActive(false); } }}
Physics formulas for vehicle movement
c#;unity3d;physics
null
_unix.107281
I am not able to install Linux in my newly built machine.I think it can be related with my MB (Asrock Z87 Extreme6). I already have Windows 8.1 installed without UEFI.When I boot (linux) from the BluRay Drive, if I use legacy boot it won't boot at all. If I choose to use UEFI, sometimes it boots, but it fails to install.I have tried several distros (Ubuntu, Debian, Slackware), but with no success. Any idea what's the problem?I have even tried OpenBSD, but no luck there as well.Machine configuration:Kingston HyperX blu Memory 16GB Seagate 1TB SATA600 Asrock Z87 Extreme6 Intel Core i5 4570, 3.2GHzAsus BW 16D1HTUsing onboard GPU
Instaling Linux on a machine with Asrock Z87 Extreme 6
linux;uefi
Short: don't use DVI-D, use HDMI >:(Well guys, gave it a try again. And finally did it! :DJust installed Linux Mint debian based version. This time the only problem I found was the display, when I had it connected to my onboard card using the DVI-D nothing was shown, had to connect it using a HDMI cable. :( I would really like to have it connected in the DVI-D port, need to HDMI to connect other devices.I was getting tired of running Debian in a virtual machine. But this cable thing is really a big downside. :( Well, when I get more time I'll try to fix it.I am also starting to wonder if previously the live distros were starting but I didn't noticed because I got no picture. Today I found that the system has booted because I've been working on Windows and left the speakers ON, so I heard the starting sound of the Linux Mint... maybe it was always working... :(
_codereview.6895
I am building a web app that needs to access various tables in a given MySQL db. To do that, I have created a generic class, see DAO_DBRecord.php below, and I create children classes for each table I want to access, e.g., DAO_User.php is used to access the users table. The only difference in the children classes is that I change the value of the variable which contains the name of the table I wish to access.My questions are:1 - Should I make the DAO_DBRecord.php class abstract? I'm not planning to instantiate it, and in fact as it is written I cannot access any table with it.2 - Should I use constants in the DAO_DBRecord.php class (e.g., const USER_TABLENAME = 'users'; const ARTICLE_TABLENAME = 'articles';) and reference them in the children classes (e.g., private Stable = USER_TABLENAME;)?3 - Anything else I should do?Class_DB.php: <?php class DB { private $dbHost; private $dbName; private $dbUser; private $dbPassword; function __construct($dbHost, $dbName, $dbUser, $dbPassword) { $this->dbHost=$dbHost; $this->dbName=$dbName; $this->dbUser=$dbUser; $this->dbPassword=$dbPassword; } function createConnexion() { return new PDO(mysql:host=$this->dbHost;dbname=$this->dbName, $this->dbUser, $this->dbPassword); } }?>DAO_DBRecord.php <?php require_once('Class_DB.php'); class DAO_DBrecord { private $dbh; // This is an instance of Class_DB to be injected in the functions. private $table=NULL; function __construct($dbh){ $this->dbh=$dbh; } function dbConnect(){ $dbConnection=$this->dbh->createConnexion(); return $dbConnection; } function checkRecordExists($recordIdentifier, $tableColName){ $dbConnection=$this->dbConnect(); $query=$dbConnection->prepare(SELECT COUNT(*) FROM $table . WHERE $tableColName = :recordIdentifier); $query->bindParam(:recordIdentifier, $recordIdentifier); $query->execute(); $result=$query->fetch(PDO::FETCH_ASSOC); if ($result[COUNT(*)]>0){ return true; } else return false; } }?>DAO_Users.php <?php class DAO_User extends DAO_DBRecord { private $table='users'; }?>
PHP DAO classes inherit from a generic DAO classes and only change the table name
php;object oriented;pdo
If the only difference between subclasses of DAO_DBRecord is the table name I wouldn't use subclasses. I'd just pass the table name to to the constructor of DAO_DBRecord and use different instances for different tables.If the only difference between subclasses of DAO_DBRecord is the table name I would pass the name of the table to the constructor of the parent class:class UserDao extends DAO_DBRecord { public function __construct($db) { parent::__construct($db, 'users'); }}Having different classes improves type safety. In Java you can't pass a UserDao to a method with an ArticleDao parameter(1), it does not compile. I don't know whether this kind of type safety exists in PHP or not, but it could be a good practice and could results more readable code.(1) Of course except if UserDao is a subclass of ArticleDaoI don't feel that making DAO_DBRecord class abstract would make a big difference. If your clients wants to misuse the class they can create a dummy (non-abstract) subclass for that:class AnyDao extends DAO_DBRecord { public function __construct($db, $tableName) { parent::__construct($db, $tableName); }}If you want to protect DAO_DBRecord from instantiation with unknown table names make its constructor private and create static factory functions for your tables inside the DAO_DBRecord:class DAO_DBrecord { private $db; private $tableName; private function __construct($db, $tableName) { $this->db = $db; $this->tableName = $tableName; } public static function createUserDao($db) { return new DAO_DBrecord($db, 'users'); } public static function createArticleDao($db) { return new DAO_DBrecord($db, 'articles'); } ...}So, DAO_DBrecord cannot be used with other tables.If you use your table names only once creating constants for them looks unnecessary in this case.
_unix.238201
Every time upon booting and then unlocking my GUI session on Kali Linux 2.0, I get another of this error in Virtual Console 1:[ 1235.586792] [drm:intel_set_cpu_fifo_underrun_reporting [i915]] *ERROR* uncleared fifo underrun on pipe A[ 1235.586827] [drm:ironlake_irq_handler [i915]] *ERROR* CPU pipe A FIFO underrunWhat does this error mean? Is it any significant thing to worry about?
CPU Pipe Underrun Errors
boot;kali linux;cpu
null
_datascience.8967
My main question is it looks like Zeppelin limit the display of the results to on 1000, I know that I can change this number but when I change it Zeppelin become slow. And it looks like the default plotting tool of Zeppelin also plot the first 1000 results.Is there a configuration or a way to make the plotting tool plot all the data?If no, is there any equivalent for Matlibplot to Scala on Zeppelin?
Plotting libraries for Scala on Zeppelin
visualization;scala
null
_codereview.66469
Example project (and code presented here) on GitHubAt first, simple example.layout / activity_slide_show.xml<RelativeLayout xmlns:android=http://schemas.android.com/apk/res/android xmlns:tools=http://schemas.android.com/tools android:layout_width=match_parent android:layout_height=match_parent android:paddingLeft=@dimen/activity_horizontal_margin android:paddingRight=@dimen/activity_horizontal_margin android:paddingTop=@dimen/activity_vertical_margin android:paddingBottom=@dimen/activity_vertical_margin > <ImageView android:id=@+id/image_view_1 android:layout_centerInParent=true android:layout_width=wrap_content android:layout_height=wrap_content/> <ImageView android:id=@+id/image_view_2 android:layout_centerInParent=true android:layout_width=wrap_content android:layout_height=wrap_content/></RelativeLayout>SlideShowActivitypublic class SlideShowActivity extends ActionBarActivity { private static final List<String> IMAGE_PATHS = prepareImagePaths(); private SlideShowController slideShowController; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_slide_show); } @Override protected void onStart() { super.onStart(); slideShowController = startSlideShow(); } @Override protected void onStop() { slideShowController.stop(); super.onStop(); } private SlideShowController startSlideShow() { SlideShow<String> slideShow = new SlideShow(String.class).items(imagePaths).period(5000).animationDuration(1000); ImageView imageView1 = findImageViewById(R.id.image_view_1); ImageView imageView2 = findImageViewById(R.id.image_view_2); return slideShow.start(this, imageView1, imageView2, new SlideShowOptions.ImageViewsFromPaths()); } private ImageView findImageViewById(int id) { return (ImageView) findViewById(id); }}All helper classes in the same package.Actually there is no need to subclass AlphaAnimation. But I create SlideShowAnimation to separate AlphaAnimation initialization and to add helper method duration() for method chaining.SlideShowAnimationpublic class SlideShowAnimation extends AlphaAnimation { public static SlideShowAnimation newAppearance() { return new SlideShowAnimation(0.0f, 1.0f); } public static SlideShowAnimation newDisappearance() { return new SlideShowAnimation(1.0f, 0.0f); } public SlideShowAnimation(float fromAlpha, float toAlpha) { super(fromAlpha, toAlpha); } public SlideShowAnimation duration(long duration) { setDuration(duration); return this; }}I divide slide show into the two classes SlideShow and SlideShowController to separate stored data and code to manage slide show (start\stop, etc.). You can't share SlideShow instance to show several slide shows at the same time.SlideShowpublic class SlideShow<ItemType> implements Parcelable { public static final Creator<SlideShow> CREATOR = new Creator<SlideShow>() { @Override public SlideShow createFromParcel(Parcel parcel) { return new SlideShow(parcel); } @Override public SlideShow[] newArray(int size) { return new SlideShow[size]; } }; private static final String PERIOD_UNIT = ms; private static final long MIN_PERIOD = 100; private static final long MIN_ANIMATION_DURATION = 100; int currentImage; private final Class<ItemType> itemType; // required parameters private List<ItemType> items; private Long period; // optional parameters private Long animationDuration; public SlideShow(Class<ItemType> itemType) { this.itemType = itemType; this.items = null; this.period = null; this.animationDuration = null; this.currentImage = 0; } public SlideShow items(List<ItemType> items) { if (items == null) { throw new NullPointerException(items can't be null); } if (items.isEmpty()) { throw new IllegalArgumentException(You couldn't set empty list of items.); } this.items = items; return this; } List<ItemType> getItems() { return new ArrayList<ItemType>(items); } public SlideShow period(long period) { if (period < MIN_PERIOD) { throw new IllegalArgumentException( You couldn't set period lower than + MIN_PERIOD + + PERIOD_UNIT); } this.period = period; return this; } long getPeriod() { return period; } public SlideShow animationDuration(long animationDuration) { if (animationDuration < MIN_ANIMATION_DURATION) { throw new IllegalArgumentException( You couldn't set minimum animation duration lower than + MIN_ANIMATION_DURATION + ms); } this.animationDuration = animationDuration; return this; } Long getAnimationDuration() { return animationDuration; } public <TransformedItemType, ViewType extends View> SlideShowController start(Context context, ViewType view1, ViewType view2, SlideShowOption<ItemType, TransformedItemType, ViewType> slideShowOption) { checkAllRequiredParametersAreSet(); SlideShowController controller = new SlideShowController(this, context, view1, view2, slideShowOption); controller.start(); return controller; } private void checkAllRequiredParametersAreSet() { for (Object requiredParameter : getRequiredParameters()) { if (requiredParameter == null) { throw new IllegalArgumentException( You should set all required parameters to start slide show ); } } } private Iterable<? extends Object> getRequiredParameters() { return Arrays.asList(items, period); } public SlideShow(Parcel in) { itemType = (Class<ItemType>) in.readSerializable(); items = new ArrayList<ItemType>(); in.readList(items, itemType.getClassLoader()); period = (Long) in.readSerializable(); animationDuration = (Long) in.readSerializable(); currentImage = in.readInt(); } @Override public void writeToParcel(Parcel out, int i) { out.writeSerializable(itemType); out.writeList(items); out.writeSerializable(period); out.writeSerializable(animationDuration); out.writeInt(currentImage); } @Override public int describeContents() { return 0; }}SlideShowControllerpublic class SlideShowController<ItemType, TransformedItemType, ViewType extends View> { private static class Visibility { static final int SHOW_VIEW = View.VISIBLE; static final int HIDE_VIEW = View.GONE; } private final Object LOCK_START = new Object(); private final Object LOCK_STOP = new Object(); private final Handler handler = new Handler(); private final Context context; private final int numberOfItems; private final List<ItemType> items; private final List<TransformedItemType> transformedItems; private final long animationDuration; private final long period; private final SlideShow slideShow; private final SlideShowOption<ItemType, TransformedItemType, ViewType> slideShowOption; private boolean isStarted; private boolean isStopped; private ViewType view1; private ViewType view2; SlideShowController(SlideShow slideShow, Context context, ViewType view1, ViewType view2, SlideShowOption<ItemType, TransformedItemType, ViewType> slideShowOption) { this.slideShowOption = slideShowOption; this.slideShow = slideShow; this.animationDuration = getAnimationDuration(context, slideShow); this.items = slideShow.getItems(); this.numberOfItems = items.size(); this.transformedItems = newArrayListWithSize(items.size()); this.period = slideShow.getPeriod(); this.context = context; this.view1 = view1; this.view2 = view2; this.isStarted = false; this.isStopped = false; } private static long getAnimationDuration(Context context, SlideShow slideShow) { Long duration = slideShow.getAnimationDuration(); if (duration == null) { duration = (long) context.getResources().getInteger(R.integer.default_slideshow_animation_duration); } return duration; } private static <T> ArrayList<T> newArrayListWithSize(int size) { ArrayList<T> list = new ArrayList<T>(size); for (int i = 0; i < size; ++i) { list.add(null); } return list; } void start() { synchronized (LOCK_START) { if (isStarted) { throw new IllegalStateException(Slide show is already started); } isStarted = true; handler.post(new Runnable() { @Override public void run() { slideShowOption.render(null, view1); slideShowOption.render(null, view2); slider.run(); } }); } } private final Runnable slider = new Runnable() { public void run() { synchronized (LOCK_STOP) { if (isStopped) { return; } try { slide(); } catch (Throwable exception) { exception.printStackTrace(); } } } }; private void slide() { startAnimationHideImage(view1); startAnimationShowImage(view2, slideShow.currentImage); handler.postDelayed(new Runnable() { @Override public void run() { slideShowOption.render(null, view1); view1.setVisibility(Visibility.HIDE_VIEW); view1.clearAnimation(); view2.clearAnimation(); swapImageViews(); slideShow.currentImage = nextImageIndex(); handler.postDelayed(slider, period); } }, animationDuration); } private void startAnimationHideImage(final ViewType imageView) { handler.post(new Runnable() { @Override public void run() { Animation animationHide = SlideShowAnimation.newDisappearance().duration(animationDuration); imageView.startAnimation(animationHide); } }); } private void startAnimationShowImage(final ViewType view, final int index) { final TransformedItemType transformedItem = getTransformedItem(index); handler.post(new Runnable() { @Override public void run() { view.setVisibility(Visibility.HIDE_VIEW); slideShowOption.render(transformedItem, view); Animation animationShow = SlideShowAnimation.newAppearance().duration(animationDuration); animationShow.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { handler.post(new Runnable() { @Override public void run() { view.setVisibility(Visibility.SHOW_VIEW); } }); } @Override public void onAnimationEnd(Animation animation) { // skip } @Override public void onAnimationRepeat(Animation animation) { // skip } }); view.startAnimation(animationShow); view.bringToFront(); } }); } private TransformedItemType getTransformedItem(int index) { TransformedItemType transformedItem = transformedItems.get(index); if (transformedItem == null) { ItemType item = items.get(index); transformedItem = slideShowOption.transform(item); transformedItems.set(index, transformedItem); } return transformedItem; } private void swapImageViews() { ViewType temp = view1; view1 = view2; view2 = temp; } private int nextImageIndex() { int index = slideShow.currentImage + 1; return (index < numberOfItems) ? index : 0; } public void stop() { synchronized (LOCK_START) { if (!isStarted) { throw new IllegalStateException(You couldn't stop not started slide show); } isStarted = false; synchronized (LOCK_STOP) { if (isStopped) { throw new IllegalStateException(You couldn't stop slide show more than once); } isStopped = true; releaseResources(); } } } private void releaseResources() { String prefix = getClass().getName() + .releaseResources(): ; for (int i = 0; i < transformedItems.size(); ++i) { Log.d(Leonid, prefix + recycle item # + i); slideShowOption.releaseResources(items.get(i), transformedItems.get(i)); items.set(i, null); transformedItems.set(i, null); } }}SlideShowOptionpublic interface SlideShowOption<ItemType, TransformedItemType, ViewType extends View> { TransformedItemType transform(ItemType what); void render(TransformedItemType itemToRender, ViewType view); void releaseResources(ItemType item, TransformedItemType transformedItem);}SlideShowOptionspublic class SlideShowOptions { public static class ImageViewsFromPaths implements SlideShowOption<String,Bitmap,ImageView> { @Override public Bitmap transform(String what) { return BitmapFactory.decodeFile(what); } @Override public void render(Bitmap bitmap, ImageView view) { BitmapDrawable drawable = new BitmapDrawable(view.getResources(), bitmap); if (Build.VERSION.SDK_INT >= 16) { view.setBackground(drawable); } else { view.setBackgroundDrawable(drawable); } } @Override public void releaseResources(String item, Bitmap bitmap) { if (bitmap != null && !bitmap.isRecycled()) { bitmap.recycle(); } } } public static class TextViewsFromResourceIds implements SlideShowOption<Integer,Integer,TextView> { @Override public Integer transform(Integer what) { return what; } @Override public void render(Integer resId, TextView view) { view.setText(resId); } @Override public void releaseResources(Integer resId1, Integer resId2) { // do nothing } }}
Helper to show simple slide show
java;android
Pardon me if I am underestimating your requirement, but if you are only swapping images using ImageView, I think you can achieve the same effect using one ImageView with a LevelListDrawable.If you look at the xml example at the top of the LevelListDrawble page, it shows how you can define a level-list by grouping multiple tags, each consisting an integer value and a drawable reference. You can then set this level-list to an ImageView as its drawable.After that, you can use setImageLevel(int level) from the ImageView to set the drawable to display and you can also apply fade in / fade out animation on the ImageView before and after you change the images.This will eliminate the need of Bitmap decoding in your SlideShowOptions class.Also, if you need to resume an interrupted slideshow, you only need to remember which level your ImageView was displaying and you can resume from there.UPDATE:To achieve a simple cross-fade effect, try using a TransitionDrawable.Here is some pseudo code:Drawable[] drawableLayer = new Drawable[2];drawableLayer[0] = current drawabledrawableLayer[1] = drawable to be displayedTransitionDrawable td = new TransitionDrawable(d);td.setCrossFadeEnabled(true);imageView.setImageDrawable(td);td.startTransition(1000); // cross-fade durationOne downside I can think of right now is that you cannot set an Interpolator to the transition animation.
_cstheory.11157
I am looking for an algorithm that, given a large weighted undirected graph, would find the node that has minimum average distance from a given set of nodes in the graph.
Finding the nearest node to a given set of nodes in a graph
ds.algorithms;graph theory;graph algorithms
null
_datascience.22446
I am a completely new to XGboost. I attempted to make a first execution today with 5k samples and 700 features on a pretty strong machine (25 CPUs), but for some reason it was extremely slow. It took 10 minutes to run a single tree on 25 CPUs when I trained on 66% of the data (so 3300 observations, 700 features). In another execution, it took only 3 sec to train a single tree on 5% of the data (250 observations, 700 features). This is still a lot, but it seems the runtime increases dramatically with increased data (x12 increase in data, increased runtime by x200).I used the same configuration as this guy who trained 500 trees under a minute.What could I possibly be doing wrong?
Why is xgboost extremely slo wfor me?
scikit learn;xgboost
null
_vi.8113
I frequently use Programming Puzzles and Code-golf. Lots of users over there have written custom languages purely for golfing. I'm even working on my own right now. Lots of these languages have their own custom encodings so that they can squish more commands into a single byte. For example, seriously, jelly and 05AB1E. Can I configure vim to use my own custom encoding? I'd like to configure a mapping of bytes to unicode code-points. For example:0x01 == Then, when I type <C-v><C-a>, it would display a character, and when I write, it would save the byte 0x01.Is this even remotely possible? And also, would this work well with the system clipboard? (e.g., I can copy and paste from my browser to vim and vice-versa)
Can I define a custom encoding for vim?
encoding
As romainl suggested, you can achieve so with the conceal feature of vim.Here is a script example that can be used:let rules = [ \ ['01' , ''], \ ['02' , ''], \ ['03' , ''], \ ['04' , ''], \ ['05' , ''], \ ['06' , ''], \ ['07' , ''], \ ['08' , ''], \ ['^A' , ''], \ ]for [value, display] in rules execute syntax match vartest /.value./ conceal cchar=.displayendfor Ensure the character is concealedset conceallevel=2set concealcursor=nvcAs you can see, I took some of the seriously mapping and your ^A example.Careful if you want to copy/paste this code, the ^A needs to be typed <C-v> <C-A>.What this code does is, it define for each value/display pair a syntax matching.e.g.syntax match vartest /08/ conceal cchar=Will match every 08 sequence and the file and conceal them with the character.You will see , but the actual text in the file is 08.You can then take a list of rules and (with a fancy macro, i.e. for seriously: 0i\ ['^[f s', '^[lxf)s'],^[ld$) transforme each line into a usable vim array.Also, if you want to type literal unicode with vim, you can use this workflow:<C-V> u XXXXWhere XXXX is the unicode value, so typing <C-V>u0001 will insert ^A as desired.If you want to verify the content of the file, I recommend using a hex dump of the file, that you can have with xxd.e.g.$ vim<C-V><C-A><C-V><C-B>:x a.txt$ xxd a.txt0000000: 0102 0a ...You can see here your ^A as 01 and your ^B as 02. (0a represents the new line at the end of the file)
_cstheory.8249
Define a decision problem H as follows. The input of H is a pair (G1,G2) of graphs, and the problem is to verify whether the number of Hamiltonian cycles in G1 is greater than the number of Hamiltonian cycles in G2. Is there a known complexity class C such that H is in C and H is C-hard under many-one reductions? Clearly H is in P^{#P}, and it is possible to prove that H is PP-hard under many-one reductions. But is H in PP? Or is H hard for the class P^{#P} under many-one reductions?
A decision problem related to the problem of counting Hamiltonian cycles
counting complexity;hamiltonian paths
null
_unix.128673
I am tryting to make initrd file system following [this tutorial][1] My host system is RHEL 6 64 bit. I am unable to get the required command: genext2fs No rpm is available for it, neither yum is helping me. I hope there is an alternate to this command.
Is there any alternative to genext2fs in RHEL?
linux;kernel;rhel;compiling;ext2
If you want genext2fs, it's easy to find; build it from source. But you probably don't want it. Create an initramfs instead. That's the normal method these days.
_scicomp.8381
Is there a way to understand what happens when a singular operator is discretized and inverted using the pseudoinverse (say using the SVD Moore-Penrose pseudoinverse)? For example, if we discretize $(\nabla u, \nabla v) $ with a finite element method or something, the operator should usually be singular due to the fact that constants are in the nullspace. Is it known what the pseudoinverse does in such cases - i.e. will it project the solution onto $U/\mathbb{R}$, or does its effect depend other factors such as the choice of basis/discretization?
Pseudo-inverse of a discretized operator with a null space?
finite element;linear solver;discretization;svd
The Moore-Penrose pseudoinverse of a matrix has the property that $x=A^{\dagger}b$is a least squares solution, and that among all least squares solutions (if there's a nontrivial nullspace of $A$), $x$ will be the least squares solution that minimizes $\| x \|_{2}$. When it comes to discretizing a PDE and solving the linear system of equations $Ax=b$ that results from that discretization, using the pseudoinverse will get you a least squares solution that minimizes the norm of $x$, but depending on the discretization that you've used (or even a change of basis for the linear system of equations), minimizing the norm of the vector $x$ might not be equivalent to minimizing the norm of the solution. It's easy to construct examples of bases where this doesn't work out. If your change of basis is orthogonal, then you'll actually be OK. For example, consider using the discrete Fourier transform as a change of basis.
_unix.7870
I would like to avoid doing this by launching the process from a monitoring app.
How to check how long a process has been running?
process
On Linux with the ps from procps(-ng) (and most other systems since this is specified by POSIX):ps -o etime= -p $$ Where $$ is the PID of the process you want to check. This will return the elapsed time in the format [[dd-]hh:]mm:ss. Using -o etime tells ps that you just want the elapsed time field, and the = at the end of that suppresses the header (without, you get a line which says ELAPSED and then the time on the next line; with, you get just one line with the time).Or, with newer versions of the procps-ng tool suite (3.3.0 or above) on Linux or on FreeBSD 9.0 or above (and possibly others), use:ps -o etimes= -p $$(with an added s) to get time formatted just as seconds, which is more useful in scripts.On Linux, the ps program gets this from /proc/$$/stat, where one of the fields (see man proc) is process start time. This is, unfortunately, specified to be the time in jiffies (an arbitrary time counter used in the Linux kernel) since the system boot. So you have to determine the time at which the system booted (from /proc/stat), the number of jiffies per second on this system, and then do the math to get the elapsed time in a useful format.It turns out to be ridiculously complicated to find the value of HZ (that is, jiffies per second). From comments in sysinfo.c in the procps package, one can A) include the kernel header file and recompile if a different kernel is used, B) use the posix sysconf() function, which, sadly, uses a hard-coded value compiled into the C library, or C) ask the kernel, but there's no official interface to doing that. So, the ps code includes a series of kludges by which it determines the correct value. Wow.So it's convenient that ps does that all for you. :)As user @336_ notes, on Linux (this is not portable), you can use the stat command to look at the access, modification, or status change dates for the directory /proc/$$ (where again $$ is the process of interest). All three numbers should be the same, sostat -c%X /proc/$$will give you the time that process $$ started, in seconds since the epoch. That still isn't quite what you want, since you still need to do the math to subtract that from the current time to get elapsed time I guess something like date +%s --date=now - $( stat -c%X /proc/$$ ) seconds would work, but it's a bit ungainly. One possible advantage is that if you use the long-format output like -c%x instead of -c%X, you get greater resolution than whole-number seconds. But, if you need that, you should probably use process-auditing approach because the timing of running the stat command is going to interfere with accuracy.
_unix.328779
I am looking to write a script that will open a file data.txt and add a line break after every nth instance of the | delimiter, so that each line contains one observation with all four variables. Basically splitting up and reshaping a single line from wide to long. Thanks for your help.Input:a1|b1|c1|d1|a2|b2|c2|d2|a3|b3|c3|d3|a4|b4|c4|d4Output: a1|b1|c1|d1| a2|b2|c2|d2| a3|b3|c3|d3| a4|b4|c4|d4
How to add line breaks after every nth instance of a delimiter in perl
text processing;perl
null
_softwareengineering.136536
I am creating use cases for a project. A generic user is extended by user categories which then is extended by an administrator (that can do all tasks possible). Is the following acceptable to portray? Is there a better way to portray such info?sample use case http://i43.tinypic.com/adm0b4.jpg
Use Case Structure
requirements;use case
Yes. This is acceptable. Making all actors a subclass of User is needless. That goes without saying.The original Objectory method (on which UML is based) explicitly makes the case that Actor is a kind of classifier, and has subclasses and superclasses.Don't go crazy however. The inheritance among users should be kept quite simple.
_datascience.15743
I have a field in a Redshift table that has user-generated text. The field is where users can say how much they think something costs.Ideally it'd just be a decimal, but it's varchar. So users can typeI think this is worth \$25, or I'd pay 55 or \$117.So I'm trying to use regexp_substr to pull this out. Specifically regexp_substr(f.comment_text, '\\$?[0-9]*'). But this doesn't work on a subset of entries for some reasons (eg Could do for $115).If I remove the ? it works on that, but no longer on entries that don't use $. Why? And what should I use instead?
Using regex in redshift to find dollar values
redshift;regex
null
_unix.271409
I am connecting to my server with SSH from Windows 10 with MINGW32 (Git).When I connect and user the root user everything works correctly but when I login with another user and use special characters like backspace or similar, the console shows incorrect characters and I can't erase.An example:root@sample:/# php -r 'echo I can write\n;'I can writeroot@sample:/# php -r 'echo I can erase without problem\n;'I can erase without problemroot@sample:/# su sample$ php -r 'echo I can write some characters;'I can write some characters$ php -r 'echo I cant erase and I cant use the up arrow for repeat the last command;'I cant erase and I cant use the up arrow for repeat the last command$$ ^[[A : not found$ : 16:$ trying erase^H^H^H^H^HWith Putty I have not problems.Regards and thanks.
Problem with characters in SSH with MingW32 and not super-user
ssh
null
_unix.186769
I'm trying to group files automatically into subdirectories using a command like this:$ rename 's/(.)(.)(.+)/$1\/$2\/$1$2$3/' *.*A dry run with the -n parameter shows me what I want:test.jpg renamed as t/e/test.jpgBut the actual renaming fails withCan't rename test.jpg t/e/test.jpg: No such file or directorybecause the subdirectories do not exist yet.How can I achieve this without creating all subdirectories manually beforehand?
Rename command with non-existing target directory
files;perl;rename
There is difference between renaiming and moving to somewhere. In the case easyest way (in modern bash) is loop through all files:for f in *.*do d=${f::1}/${f:1:1} [ -d $d ] || mkdir -p $d mv $f $ddone
_vi.8887
At the moment I'm writing, I removed matchit plugin and the % works well, making the cursor jump from a (, [, or { to the corresponding closing character and vice versa.Now I installed matchit again, adding Plugin 'vim-scripts/matchit.zip' to my .vimrc and then running Vundle's :PluginInstall. Having done so, I can now jump forth and back from subroutine to end subroutine in my .f90 files and so on (and I can do it with .cpp and so on).But I cannot make this jumps with parenthesis and brackets and other standard pairs.I have no idea of which could be the reason of such strange Vim's behavior. I hope the following observations can be useful for you to help me.Wherever I press % (to jump between a standard or non standard pair, or on an empty line with no reason), then I cannot use it anymore, as well as the cursor remains in the buffer related to a .f90 file.If I move to another buffer/window related to a NON .f90 file (by :n<CR>, :N<CR>, <C-W><C-W> and so on, or simply :help<CR>) and press % at least once (to jump between ... as before), then I can go back to a .f90 buffer/window and use % with standard pairs once (just once!) again.Jumping between new pairs (IF, DO, and so on) is not affected.Maybe I should underline that I got the feeling that this happens only with Fortran files (.f90 and .f95), since it doesn't happen with help pages (.txt) nor with .cpp files.
with matchit installed %match parenthesis and brackets only once in Fortran files
delimiter matching;plugin matchit
null
_scicomp.24267
So I have a collection of systems of equations, basically $n$ systems of equations, each composed of $k$ equations:$$\frac{a_1x_{1j}}{a_1x_{1j} + \cdots + a_kx_{kj}} + \log x_{1j} + 1 - B_{1j} = 0$$$$\frac{a_2x_{2j}}{a_1x_{1j} + \cdots + a_kx_{kj}} + \log x_{2j} + 1 - B_{2j} = 0$$$$\vdots$$$$\frac{a_kx_{kj}}{a_1x_{1j} + \cdots + a_kx_{kj}} + \log x_{kj} + 1 - B_{kj} = 0$$for $j = 1,...,n$, with the restriction that each $(x_{1j},...,x_{kj})$ lies on the simplex.As you can see the systems are all very similar to each other, the only difference being the $B_{ij}$ constant at the end. Also if it helps all the $a_i$ and $B_{ij}$ are positive. I'm wondering first if these systems are actually simple enough that they have analytic solutions, and if not, then upon finding the solution to one of them (probably by using some sort of constraint-modified Newton's method), whether I can basically use this solution to immediately find the solution to the others.
Finding quick solution to a collection of systems of fairly simple but nonlinear equations
optimization;nonlinear equations
null
_unix.146089
So I have some output that has very long lines, and I want to have it formatted to lines no more than 80 columns wide, but I don't want to split words because they are in the column limit.I tried sed 's/.\{80\}/&\n/g' but has the problem of splitting words and making some lines begin with a space.I managed to do it with Vim, setting textwidth to 80, going to the beginnig of the file and executing gqG to format the text. But would rather do it with sed, awk or something similar to include it in a script.
Format output to a specific line length
text processing;sed;awk;text
Use fmt instead:fmt --width=80 fileFrom man fmt:-w, --width=WIDTH maximum line width (default of 75 columns)
_unix.134340
I live in Poland, and we have some accented characters - . Due to various reasons I resurrected talk usage on my server, which works great, but I wasn't able to figure out how to make it work with accents.On both ends of talk I have UTF-8 based locale (en_US.UTF-8), and Polish characters work great in everything - bash, vim, mutt, slrn, everything, but talk.What is the reason of the problem, and how could it be solved?I'm using it on Debian testing, and have tried talk/utalk/inetutils-talk, and none of them seems to support unicode/utf8.What can be done to achieve talk with full UTF8 support?
Unicode support in talk?
unicode
indeed for those old programs there is little hope to see them ported to unicode (I have a hard time finding a package to test :) ).As Gilles said, luit is the pragmatic answer.I used it some time ago for another 8bit only program.define a bash alias like this:alias talk='LC_ALL=pl_PL.ISO-8859-2 luit -- talk'you need luit installed, and the proper 8bit locale too.you can also use talk='luit -encoding 8859-2 -- talk' if you don't have the 8bit locale.
_webapps.100658
I have a spreadsheet and between B2:B101, I have a number on each one. I am trying to get a rank on E2:E101, regarding to their given number. I tried using =rank, and it successfully shows the result in a tooltip, but when I press enter, it doesn't write the value.The cell is blank.View > All Formulas is unchecked, also tried with checked. No luck. What am I doing wrong?
Formula result doesn't show, leaves blank cell
google spreadsheets
null
_webapps.104955
Is there a way to way to link two cells so when one is altered the other is altered also?Like this:I alter `A1` to 1, `B1` is now 1I alter `B1` to -1, `A1` is now -1
Sync two cells value
google spreadsheets
You can link two cells using a google script. You can use on Edit trigger of each sheet to poll for which cell is getting modified and modify the other one in the other sheet.The below code will link cell A1 in Sheet1 in of Spreadsheet with ID spd1ID to B1 in Sheet1 in Spreadsheet with ID spd2ID var spd1ID = ID of first sheet herevar spd2ID = ID of second sheet herefunction myLinkCells() { ScriptApp.newTrigger(callOnEdit).forSpreadsheet(spd1ID).onEdit().create() ScriptApp.newTrigger(callOnEdit).forSpreadsheet(spd2ID).onEdit().create()}function callOnEdit(e){ var range = e.range var cellAdd = range.getA1Notation() Logger.log(Called) var ssID = e.source.getId() var sName = range.getSheet().getSheetName() if( ssID == spd1ID && sName == Sheet1){ if(cellAdd == A1){ var ss = SpreadsheetApp.openById(spd2ID) var rng = ss.getSheetByName(Sheet1).getRange(B1) rng.getSheet().getSheetName() rng.setValue(e.value) Logger.log(In Cell A1) } } else if(ssID == spd2ID && sName == Sheet1){ if(cellAdd == B1){ var ss = SpreadsheetApp.openById(spd1ID) var rng = ss.getSheetByName(Sheet1).getRange(A1) rng.setValue(e.value) Logger.log(In Cell B1) } }}Where to paste this code?Open your spreadsheet Tools>Script EditorWhat is spreadsheet ID?https://developers.google.com/sheets/api/guides/concepts#spreadsheet_idAfter you paste the code and modify the ID, run myLinkCells() function using Run menu.That will link the cells. Hope that helps!
_datascience.6018
I have an algorithm which have as an input about 20-25 numbers. Then in every step it uses some of these numbers with a random function to calculate the local result which will lead to the final output of A, B or C.Since every step has a random function, the formula is not deterministic. This means that with the same input, I could have either A, B or C.My first thought was to take step by step the algorithm and calculating mathematically the probability of each output. However, it is really difficult due to the size of the core.My next thought was to use machine learning with supervised algorithm. I can have as many labeled entries as I want.So, I have the following questions:How many labeled inputs should I need for a decent approach of the probabilities? Yes, I can have as many as I want, but it needs time to run the algorithm and I want to estimate the cost of the simulations to gather the labeled data.Which technique do you suggest that works with so many inputs that can give the probability of the three possible outputs?As an extra question, the algorithm run in 10 steps and there is a possibility that some of the inputs will change in one of the steps. My simple approach is to not include this option on the prediction formula, since I have to set different inputs for some of the steps. If I try the advanced methods, is there any other technique I could use?
Create a prediction formula from data input
machine learning;predictive modeling
I'm not sure if I understood your question! Probably better to plot a scheme at least. But according to what I guess from your question:Q2- You probably need a simple MLP (Multilayer Perceptron)! it's a traditional architecture for Neural Networks where you have $n$ input neurons (here 20-25), one or more hidden layers with several neurons and 3 neurons as output layer. If you use a sigmoid activation function ranged from 0 to 1, the output for each class will be $P(Y=1|X=x)$.Q1- So your question probably is: how many training data you need for learning a model? and to the best of my knowledge the answer is as many as possible!and about the last question, I really could not figure out what you mean. You apparently have a very specific task so I suggest to share more insight for sake of clarification.I hope I could help a little!
_softwareengineering.242999
All, I have a WPF DataGrid. This DataGrid shows files ready for compilation and should also show the progress of my compiler as it compiles the files. The format of the DataGrid is Image|File Path |State-----|----------|----- * |C:\AA\BB |Compiled& |F:\PP\QQ |Failed> |G:\HH\LL |Processing....The problem is the image column (the *, &, and > are for representation only). I have a ResourceDictionary that contains hundreds of vector images as Canvas objects: <ResourceDictionary xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation><Canvas x:Key=appbar_acorn Width=48 Height=48 Clip=F1 M 0,0L 48,0L 48,48L 0,48L 0,0> <Path Width=22.3248 Height=25.8518 Canvas.Left=13.6757 Canvas.Top=11.4012 Stretch=Fill Fill={DynamicResource BlackBrush} Data=F1 M 16.6309,18.6563C 17.1309,8.15625 29.8809,14.1563 29.8809,14.1563C 30.8809,11.1563 34.1308,11.4063 34.1308,11.4063C 33.5,12 34.6309,13.1563 34.6309,13.1563C 32.1309,13.1562 31.1309,14.9062 31.1309,14.9062C 41.1309,23.9062 32.6309,27.9063 32.6309,27.9062C 24.6309,24.9063 21.1309,22.1562 16.6309,18.6563 Z M 16.6309,19.9063C 21.6309,24.1563 25.1309,26.1562 31.6309,28.6562C 31.6309,28.6562 26.3809,39.1562 18.3809,36.1563C 18.3809,36.1563 18,38 16.3809,36.9063C 15,36 16.3809,34.9063 16.3809,34.9063C 16.3809,34.9063 10.1309,30.9062 16.6309,19.9063 Z /></Canvas></ResourceDictionary>Now, I want to be able to include these in my image column and change them at run-time. I was going to attempt to do this by setting up a property in my View Model that was of type Image and binding this to my View via:<DataGrid.Columns> <DataGridTemplateColumn Header= Width=SizeToCells IsReadOnly=True> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Image Source={Binding Canvas}/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn></DataGrid.Columns>Where in the View Model I have the appropriate property. Now, I was told this is not 'pure' MVVM. I don't fully accept this, but I want to know if there is a better way of doing this. Say, binding to an enum and using a converter to get the image? Any advice would be appreciated.
Best Practice Method for Including Images in a DataGrid using MVVM
c#;mvvm
null
_softwareengineering.127959
Given the existential typeT = X.{op:X, op:Xboolean}and this generic Java interface:interface T<X> { X op(); boolean op(X something);}What are the fundamental differences between the existential type and the Java interface?Obviously there are syntactical differences, and Java's object-orientation (which also includes details such as hidden this parameters etc.). I'm not so much interested in these as in conceptual and semantic differences though if someone would like to shed light on some finer points (such as the notational difference between T vs. T<X>), that would be appreciated too.
How do existential types differ from interfaces?
java;interfaces;type systems
null
_unix.351123
In the process of learning/understanding Linux (difficult but enjoying it). I have written a very short shell script that uses wget to pull an index.html file from a website. #!/bin/bash#Script to wget website mywebsite and put it in /home/pi/binindex=$(wget www.mywebsite.com)And this works when i enter the command wget_test into command line. It outputs a .html file into /home/pi/bin.I have started trying to do this via cron so i can do it at a specific time. I entered the following by using crontab -e23 13 * * * /home/pi/bin/wget_testIn this example I wanted the script to run at 13.23 and to output a .html file to /home/pi/bin but nothing is happening.
Cron not working with shell script
cron
This line index=$(wget www.mywebsite.com) will set the variable $index to nothing. This is because (by default) wget doesn't write anything to stdout so there's nothing to put into the variable.What wget does do is to write a file to the current directory. Cron jobs run from your $HOME directory, so if you want to write a file to your $HOME/bin directory you need to do one of two thingsWrite wget -O bin/index.html www.mywebsite.comWrite cd bin; wget www.mywebsite.comIncidentally, one's ~/bin directory is usually where personal scripts and programs would be stored, so it might be better to think of somewhere else to write a file regularly retrieved from a website.
_unix.114988
I'm currently trying to set up a MySQL replication and I don't have a /etc/sysconfig/iptables. So I tried to install it with yum install. It showed the following output. Installed PackagesName : iptablesArch : x86_64Version : 1.4.7Release : 11.el6Size : 836 kRepo : installedFrom repo : anaconda-RedHatEnterpriseLinux-201311111358.x86_64Summary : Tools for managing Linux kernel packet filtering capabilitiesURL : http://www.netfilter.org/License : GPLv2Description : The iptables utility controls the network packet filtering code in : the Linux kernel. If you need to set up firewalls and/or IP : masquerading, you should install this package.Available PackagesName : iptablesArch : i686Version : 1.4.7Release : 11.el6Size : 247 kRepo : rhel-x86_64-server-6Summary : Tools for managing Linux kernel packet filtering capabilitiesLicense : GPLv2Description : The iptables utility controls the network packet filtering code in : the Linux kernel. If you need to set up firewalls and/or IP : masquerading, you should install this package.So far so good but when I try to run iptables I get a Segmentation fault Do I need a better hardware? [root@wltwd1 sysconfig]# iptablesSegmentation fault (core dumped)This is my lscpu output:[root@wltwd1 sysconfig]# lscpuArchitecture: x86_64CPU op-mode(s): 32-bit, 64-bitByte Order: Little EndianCPU(s): 1On-line CPU(s) list: 0Thread(s) per core: 1Core(s) per socket: 1Socket(s): 1NUMA node(s): 1Vendor ID: GenuineIntelCPU family: 6Model: 47Stepping: 2CPU MHz: 1995.034BogoMIPS: 3990.06Hypervisor vendor: VMwareVirtualization type: fullL1d cache: 32KL1i cache: 32KL2 cache: 256KL3 cache: 18432KNUMA node0 CPU(s): 0
Segmentation fault (core dumped) when try to run iptables rhel6
rhel;mysql;segmentation fault;replication
Check what CPU architecture you have on your system. You're likely mixing the 32-bit and 64-bit binaries and libraries together which is probably giving you this error message.You can find out with this command:# 64-bit system$ getconf LONG_BIT64# 32-bit system$ getconf LONG_BIT32If you have 32 then you should uninstall the 64-bit package of iptables. If you have 64-bit, then uninstall the 32-bit.How to uninstall?On the surface it would appear that the packages have the same name but I assure you they're different. You can get their actual names using this command:$ rpm -aq iptables*iptables-services-1.4.18-1.fc19.x86_64iptables-1.4.18-1.fc19.x86_64iptables-1.4.18-1.fc19.i686So to get rid of the 32-bit version you can use this command:$ yum remove iptables-1.4.18-1.fc19.i686Obviously substitute your result in for the example above.References32-bit, 64-bit CPU op-mode on Linux
_cs.69251
I am reviewing for a test, and i am stuck on this question.the problem is to show it is hard to approximate (for any constant) the following problem:given m CNF formulas f1,..,fm over variables x1,..,xn find the assignment which maximizes the number of satisfied formulas.I believe I need to reduce this problem to some kind of graph problem (CSG,IS,CLIQUE), which I know cannot be approximated for any constant. I can't find a way to do this. To what problem do I reduce this to? thank you.
m-CNF formulas satisfiability approximation
complexity theory
null
_softwareengineering.109653
During development, should developers each have their own copy of the database to work on ? Or should there be a common shared development database ?The former will give developers more flexibility. For ex., they can run their own regression tests during development and unit testing without worrying about corrupting the data for other developers. However, it is difficult to maintain for database adminstrators.The latter is easier to maintain (less integration overheads as everyone's working on the same schema) but requires more effort to ensure data sanctity (developers should be careful and not make changes that will impact others).
Should there be separate database schemas for each developer or should there be just one that all developers share?
database development
null
_softwareengineering.87519
Sorry if this question is a duplicate, I did some extensive searching and found nothing on quite the same topic (though a couple on partially-overlapping topics).Recently, whilst on holiday in Munich, Germany, I was taken aback by the sheer number of programming-related posts available in the city that I easily qualify for (both in terms of knowledge, and experience). The advertised working environments seemed good and the pay seemed to be at least as good as what I'd expect here in the UK. Probably 80% of the advertisements I saw on the underground were for IT-related jobs, and a good 60% of those I was easily qualified for.At the moment, I work as a freelancer mostly on web and small software projects, but seeing the vast availability of jobs in Munich versus my local area has me thinking about remote working.I'm unable to relocate for a job for the next 3 years (my wife has a contract to continue being a doctor at her current hospital for that time) but would almost certainly be open to it after that (after all, my wife and I both love Munich). In the meanwhile, I would be very interested in remote-working.So, my question is thus do companies ever take on remote workers (even with semi-frequent trips to the office) from abroad, with a view to later relocation? And, if so, how do you go about broaching the topic with a recruiter when getting in contact about a job posting?Language isn't a barrier for me, here, as 90% of the jobs I've looked up in Munich don't require German speakers (seems they have a big recruiting market abroad). I'm also under no illusions about the disadvantages of remote working, but I'm more interested in the viability of the scenario rather than the intricacies (at least at this point).I'd really appreciate any contributions, especially from those who have experience with working in such a scenario!
Remote Working & Relocation
hiring;telecommuting
I'm lucky enough currently to be remote working from British Columbia, Canada, while preparing to relocate to the UK. I applied to a development job in London because a friend worked for the company, thinking they'd laugh my CV all the way into the bin, but rather astonishingly they were impressed by my qualifications and agreed to give me a try.Because of the unusualness of the situation - they don't make a habit of hiring people on from the other side of the world, in fact I don't know if they've ever done it before! - they decided to give me a project to work on remotely for a few months on a contract basis. When that went relatively well, they flew me in for a week on site, and then offered me a job. I've started working full-time from Canada, even though it's still a month till I actually fly into the UK to work there on a permanent basis.Based on my experiences, I'd suggest that an imaginative company could definitely contemplate the possibility of hiring a suitably qualified individual from abroad; in such a case, it makes excellent sense for them to let you work remotely for a while, as no one on either side of the equation wants to relocate an employee thousands of miles only for it not to work out for some reason, three months later. That'd just be unpleasant. Of course, I imagine you'd have to be a really good fit for the role, to beat off competition from local candidates, who are obviously, all other things being equal, less hassle to hire. Either that, or take advantage of nepotism and have a friend at the company in question, like I did!
_unix.230220
I got this script ~/bin/align-tables from emacs stackexchange#!/bin/sh# -*- mode: shell-script -*-## tangle files with org-mode#DIR=`pwd`FILES=# wrap each argument in the code required to call tangle on itfor i in $@; doFILES=$FILES \$i\doneemacs -Q --batch \--eval (progn (require 'org)(require 'org-table) (mapc (lambda (file) (find-file (expand-file-name file \$DIR\)) (org-table-map-tables 'org-table-align) (write-file file nil) (kill-buffer)) '($FILES)))I want to apply this script to every .org file in the directory ~/foo. If my working directory is /foo, then issuing $ align-tables *.org works perfectly. However, if I'm in a different directory, issuing $ align-tables ~/foo/*.org gives the error Opening output file: no such file or directory, ~/foo/foo/#bar.org#Since the target directory is listed twice in the error message, I'm assuming the problem is the line DIR='pwd' in the script but I'm not sure how to go about modifying the script.My motivation is that I'm writing a perl program that applies align-tables to many different directories.Any ideas how I can get my script to cooperate?
Why can't I apply this script to files not in my current directory?
bash;shell script;files;emacs
null
_unix.32880
I've created a script in /etc/init/mms-agent.conf :start on runlevel [2345]stop on runlevel [06]exec /usr/bin/env python /home/mms/mms-agent/agent.py >> /home/mms/agent.log 2>&1service mms-agent start/stop work fine, but i'd like to start this service with the user mmsWhen I try to change the script as following :exec su mms -c /usr/bin/env python /home/mms/mms-agent/agent.py >> /home/mms/agent.log 2>&1I get 3 process running instead of 1 expected (su, bash + my python script):mms 8864 0.0 0.2 37816 1332 ? Ss 22:30 0:00 su mms -c /usr/bin/env python /home/mms/mms-agent/agent.py >> /home/mms/agent.log 2>&1mms 8865 0.0 0.2 11452 1196 ? S 22:30 0:00 bash -c /usr/bin/env python /home/mms/mms-agent/agent.py >> /home/mms/agent.log 2>&1mms 8866 4.0 1.8 54672 10640 ? Sl 22:30 0:00 python /home/mms/mms-agent/agent.pyWhat does that mean ? What is the best way to start a script with a user different than root ?ThanksPS : exec start-stop-daemon --start -u mms --exec /usr/bin/env python /home/mms/mms-agent/agent.pydoesn't work, I got no error but the process isn't started.
linux launch script /etc/init with a specific user
su;services;upstart
When you exec su, the shell is replaced with the su process. su then forks and execs bash. bash sets up the output redirection and then forks and execs env. env searches PATH, finds python and execs it. So you're left with three processes, 1) su, waiting for bash to exit, 2) bash, waiting for python (previously env) to exit, and 3) python, which is busily running your script.There is nothing wrong with this. su is the Unix time-honored way to temporarily switch users, so that's what you should be using. Similarly, the way to run a command line is to use a shell, so su runs bash and lets bash handle it. Again, this follows the general Unix toolbox approach, letting the shell do what the shell is good at, and not reinventing shell command line and PATH search functionality in another application.Also, since bash is already doing the PATH search, you can drop the use of env and invoke python directly.
_unix.5600
Running vlc /path/to/dvd-video.iso, I'm getting:[0x8787ccc] main decoder error: no suitable decoder module for fourcc `undf'. VLC probably does not support this sound or video format.notes:The version of vlc is 1.1.3.The DVD plays well when not in iso format (when it's normal files on the filesystem).
How to make VLC play an iso file directly?
vlc
null
_softwareengineering.238843
My understanding of Akka is that it allows you to define groups of mini-threads (Actors) and then have them communicate with each other (and do work) using events.My understanding of ZeroMQ is that its a TCP socket library that allows threads to communicate with each other over TCP/ports.My question: these seem like very similar concepts. However, I'm sure that in reality, they are meant to solve entirely different problems. So:Intention-wise, what is the difference between these two tools? What different problems do they solve? Are there clear/concrete use cases where one is preferable to the other?
When should I use ZeroMQ and when should I use Akka?
multithreading;akka
null
_unix.110558
As root, I'm connecting to a remote host to execute a command. Only standarduser has the appropriate id-file and correct .ssh/config, so I'm switching the user first:su standarduser -c 'ssh -x remotehost ./remotecommand'The command works fine, but despite the fact that I used -x (disable X11-Forwarding) and having X11Forwards disabled in /etc/ssh/ssh_config, I still get the error message:X11 connection rejected because of wrong authentication.I'm not getting the error message when I'm logged in as standarduser.This is quite annoying as I would like to integrate the command in a cron job file. I understand that the error message refers to the wrong authentication of root's .XAuth file, but I'm not even trying to connect via X11.Why is ssh -x not disabling the X11 connection and throwing the error message?UPDATE:The message only shows when I'm logged in within a screen, when using the command stated above on the local machine itself (without screen), I don't get an error message, so this should be fine with cron, too.I also started the same command with -v and surprisingly got the error message FIRST, even before the status information from SSH:root@localhost:~# su standarduser -c 'ssh -x remotehost ./remotecommand'X11 connection rejected because of wrong authentication.OpenSSH_6.2p2 Ubuntu-6ubuntu0.1, OpenSSL 1.0.1e 11 Feb 2013This led me to the problem itself, it is NOT the ssh which is throwing the error message, it's su:root@localhost:~# su standarduser -c 'echo Hi'X11 connection rejected because of wrong authentication.HiWhy do I only get this error within screen? How can I disable this error message?
su with error X11 connection rejected because of wrong authentication
bash;gnu screen;su;xauth
null
_webapps.89923
The link to search IMDB is http://www.imdb.com/search/titleThere is a box to select the language. I have to select English to eliminate all the foreign movies with fake votes. I tried to select English/German/French/Spanish to only show movies with any of those languages, but instead it only searches for movies with all of those languages, which is none. I tried to watch some of the top Indian/Turkish/Pakistani movies, and some of them are good, but most of them obviously have fake ratings.
How to exclude certain language movies form IMDb search
imdb
null
_unix.191185
I'm using Ubuntu 14.10 virtual machine located on Azure and I'm accessing it via Putty client. I've installed required software like Nginx and Mono, and I'm trying to host ASP.NET 5 webapp on Ubuntu. Which IP can be used instead of domain name (because I don't have one :) ) to test webapp hosted on Ubuntu ? I want to access website from anywhere, Windows, my phone etc. In one tutorial, these are the Nginx configurations in .conf fileserver { listen 80; server_name <domain-name> www.<domain.name>; client_max_body_size 10M; location / { proxy_pass http://localhost:5004/; proxy_redirect off; proxy_set_header HOST $host; proxy_buffering off; } }I can't see website inside Ubuntu because I don't have any king of GUI installed. So,please help, I don't know much about Ubuntu and this is opportunity to test Asp.Net 5's cross-platform possibilities. Thanks :)
How to access a website hosted on Ubuntu virtual machine on Azure?
ubuntu;ip;nginx;asp.net
null
_unix.59621
I am running CentOS with cPanel, which creates a custom log directory and writes the logs there. The result is that the IO for the hard disk goes sky high.If I do lsof I got:hostsite.comhttpd 2383 nobody 3779w REG 253,0 0 422463 /usr/local/apache/domlogs/mygamecardotcobnao.super hostsite.com-bytes_loghttpd 2383 nobody 3780w REG 253,0 5265 420994 /usr/local/apache/domlogs/myfreefreedatixuua.super hostsite.comhttpd 2383 nobody 3781w REG 253,0 36 422464 /usr/local/apache/domlogs/myfreefreedatixuua.super hostsite.com-bytes_loghttpd 2383 nobody 3782w REG 253,0 3101 415849 /usr/local/apache/domlogs/myfreedatingfrekeuo.supe rhostsite.comhttpd 2383 nobody 3783w REG 253,0 72 422465 /usr/local/apache/domlogs/myfreedatingfrekeuo.supe rhostsite.com-bytes_loghttpd 2383 nobody 3784w REG 253,0 672 419338 /usr/local/apache/domlogs/myfreedatingblogsxgo.sup erhostsite.comhttpd 2383 nobody 3785w REG 253,0 0 422466 /usr/local/apache/domlogs/myfreedatingblogsxgo.sup Disabling this domlog is impossible because there are tons of those lines automatically generated.I just want to point /usr/local/apache/domlogs/ to /dev/null. Can that be done?
How do I point certain directory to /dev/null?
filesystems;directory
If you can afford some RAM, you can set up a RAM disk and let your logs go there:mount -t tmpfs -o size=200M none /usr/local/apache/domlogsAdditionally, you should setup logrotate to rotate the logs every minute/hour/day/night/week/* and delete the old logs. This is not exactly what you want, but it should fix your problem as RAM I/O won't slow down your disks.
_webmaster.87550
Do you know some real world examples that AggregateRating improved the website SEO?
Any example that adding schema.org/AggregateRating to the website is really SEO beneficial?
seo;schema.org
Various consumers could do various things with this markup. You did not specify what counts as improve for you. How about displaying the review information in the result snippet for your page?Google Search has the Aggregate Ratings Rich Snippets, which is currently shown like this (query: site:goodreads.com lord of the rings):Bing shows this in a similar way (same search query):The result (http://www.goodreads.com/book/show/33.The_Lord_of_the_Rings) is using Schema.orgs AggregateRating type.
_unix.343184
I'm re-phrasing the question because it was highly confusing and was badly phrased... )-:I have a docker container and I'm reading logs from it like this:docker exec -it my-container sh -c export TERM=xterm && ls -t /logs/my-log.* | xargs zless -Rnow, I want to use 'grep' on the output and I am facing a problem because this one is working:docker exec -it my-container sh -c export TERM=xterm && ls -t /logs/my-log.* | xargs zless -R | grep sometextwhile this one is not working:docker exec -it my-container sh -c export TERM=xterm && ls -t /logs/my-log.* | xargs zless -R | grep sometext(note that the 1st working command includes the grep within the command I send and in the 2nd one I run grep on the output)it is important to me because I am running the command in a script and I want to allow running grep on this script's output.
running grep on a docker exec command's output
shell script;docker
null
_codereview.145611
We have a working implementation that is doing I/O operations, returning data from blobs in an async/await manner from Azure Blob Storage. //Method1 is not async, this is what is called from the controllerpublic IEnumerable<Data> Method1(){ //Running the async method and returning the result from task return Task.Run(() => GetDataAsync()).Result;}private async Task<IEnumerable<Data>> GetDataAsync(){ //There are multiple blob address where the data is held. The code creates, in parallel multiple tasks for each address. //It returns tasks that will be run in Async pattern var tasks = multipleBlobAddress.AsParallel.Select(blobAddress =>{ Task<IEnumerable<Data>> task = GetDataFromBlobsAsync(blobAddress); return task; }); //Awaits all tasks to complete var completedTasks = await Task.WhenAll<IEnumerable<Data>>(tasks); //Selects all the tasks and returns them. Each tasks has data. return completedTasks.SelectMany(t => t);}private Task<IEnumerable<Data>> GetDataFromBlobsAsync(string address){ //Opens the blob and reads from it using (var blobStream = blobService.OpenRead(address)) { //Deserialises the data read from the blob data = service.DeserialiseData(blobStream); } return Task.FromResult<IEnumerable<Data>>(data);}We have understood that the best way to read from blobs is to follow the async/await pattern and not using the AsParallel method (other suggestions are most welcomed). I have the following questions:By creating tasks in parallel and then waiting for all of them to complete, do we lose any performance?What are the obvious areas where we got it wrong or we can improve and potentially increase the performance or make the code better to maintain/read?Are we correctly following the async / await pattern?If you need any extra information about the code, I will happily provide it and hope to make it clearer.
Downloading blobs asynchronously
c#;async await;azure
There is never a need to do this:return Task.Run(() => GetDataAsync()).Result;Why start a new task and then synchronously wait with .Result? This is the sort of code that will bite you later when you find out that a synchronisation context can cause a deadlock. See Stephen Cleary's blog post on the subject of an async deadlock. Stephen's blog is an absolute gold mine of information on aysnc and await.Either use the synchronous api all the way from your controller down into the Azure Storage SDK or use the asynchronous one (with async and await). Don't mix and match - that's a source of errors and also pointless. Aysnc is useful when there's something else the thread could be doing. E.g. in a web app that's serving requests. If the web app is blocked by .Result or Wait then there is no benefit and you should use the synchronous API.
_webapps.27285
I hear you can now link Google Docs to Trello and I was wondering how to go about this.
How do I link Google Docs to Trello?
google drive;trello
null
_computergraphics.5486
In my opinion, geometric surface normal is the cross product of triangle edge vectors, and shading surface normal is the interpolation of the predefined normals at the three vertexes.I used Mitsuba to render the geometric normal channel and the shading normal channel:geometric normal:shading normal:
What's the difference between geometric surface normal and shading surface normal?
computational geometry;geometry;shading
Your existing opinion is correct, though there's one extra detail. The geometric normal is the normal of the actual triangle, based on the vertices' positions (the cross-product of edge vectors, as you said). The shading normal is altered from this, and is used when shading a fragment or ray hit. In the simple case, it's the interpolation of the three normals set at the vertices. This is used for curved objects to hide the polygon boundaries. It might also be modified by a bump map or normal map, to add finer detail to the appearance than the polygon mesh has.
_codereview.122424
This function scrapes data from a webpage by spawning a process that executes a CasperJS web scraping script. The spawned process outputs data to stdout. This function has an event listener for stdout and this is how the parent process (Node) gets the scraped data back. How can I make this more modular? Also, would creating a child_process class make more sense?function scrapeLinks(location, callback) { // stores any data emitted from the stdout stream of spawned casper process var processData = ; // stores any errors emitted from the stderror stream of spawned casper process var processError = ; // initialises casperjs link scraping script as spawned process var linkScrapeChild = child_process.spawn(casperjsPath, ['casperLinkScript.js ' + location]); linkScrapeChild.stdout.on('data', function onScrapeProcessStdout(data) { processData += data.toString(); console.log(data.toString()) }); linkScrapeChild.stderr.on('data', function onScrapeProcessError(err) { processError += err.toString(); }); linkScrapeChild.on(error, function onScrapeProcessError(err) { processError = err.toString(); }); //once spawned casper process finishes execution call the callback linkScrapeChild.on('close', function onScrapeProcessExit(code) { console.log('Child process - Location Scrape: ' + location + ' - closed with code: ' + code); processData = convertToArray(processData); // filter out non valid listing links listingLinks = filterLinks(processData); //console.log(listingLinks); // filter duplicates var uniqueLinks = [ ...new Set(listingLinks) ]; if(uniqueLinks.length === 0){ processError += 'No valid listings found for ' + location } logScrapeResults(processError, uniqueLinks, location); callback(processError || null, uniqueLinks); });}
Spawning child processes and event-listening
javascript;node.js;child process
null
_softwareengineering.222559
On this blog post aphyr (who is a brilliant programmer) states:Clojure macros come with some important restrictions. Because theyre expanded prior to evaluation, macros are invisible to functions. They cant be composed functionallyyou cant (map or ...), for instance.The classic example of this is:(reduce and [true true false true]);RuntimeExceptionYet we can write:(reduce #(and %1 %2) [true true false true]);falseIs 'macros don't compose' a valid claim? Surely the only valid point is that macros are not first class functions and shouldn't be treated as such.
Is it fair to say that macros don't compose?
clojure;composition;macros
I think this depends on what you mean by compose. I would say that it's mostly true but can be taken too far.First, note that in the quote you cited aphyr didn't say macros don't compose; the phrase was can't be composed functionally. That more limited claim is indisputably true. Macros in Clojure aren't values[1]. They can't be passed as arguments to other functions or macros, can't be returned as the result of computations, and can't be stored in data structures.There are, of course, ways to work around these limitations. Besides your #(and %1 %2) example, there's a sense in which the code below represents composition.(ns some.macros (:refer-clojure :exclude [when when-not]))(defmacro when [test & body] `(cond ~test (do ~@body)))(defmacro when-not [test & body] `(when (not ~test) ~@body))I intentionally used cond rather than if in the definition of when because cond is itself a macro.But, back to the larger point, #(and %1 %2) isn't really an argument that macros compose, it's an argument that you can use macros within functions. And, because we have many powerful ways of working with functions, this is generally the best way to go. Use macros (when functions aren't appropriate) to abstract away boilerplate, repetitive code, but, when possible, ultimately expose as much of your API as possible as functions so that they can be stored in hash-maps, mapped over sequences of widgets, negated with complement, juxtaposed with juxt, and so on.[1] It would be difficult for it to be otherwise. Imagine if macros were values and could be passed as arguments to functions. How could you compile code that used such a macro, given that its expansion wouldn't be known until runtime (and could vary between invokations of the function)?AddendumAs a point of interest, consider that macros are functions, they're just treated specially by the compiler.Check this out:some.macros> (defn when [&form &env test & body] `(cond ~test (do ~@body)))#<Var@1a37b98: #<macros$eval7806$when__7807 some.macros$eval7806$when__7807@d1cf9c>>some.macros> (when nil nil true 1 2)(clojure.core/cond true (do 1 2))some.macros> (. #'when (setMacro))nilsome.macros> (when true 1 2)2This is, in fact, exactly how defmacro works. (See here for an explanation of the &form and &env pseudo-arguments).
_unix.331561
Ok, so I can write a shell script with bash, sh, or zsh in mind etc. And I can put a hashbang at the top of the file like so:#!/usr/bin/env bashwhich will tell the kernel which interpreter to use to execute the file.However, I just realized, I don't know how to tell the machine which interpreter to use at the command line.e.g., if I write:$ foo bar bazat the command line, how do I know what interpreter is being used to interpret that command? How can I tell the computer to use a particular interpreter?Hopefully the question is clear.
Specify which interpreter to use at command line
bash;shell script;shell;zsh
To get your login shell, which is most likely the shell you're currently running, unless you have deliberately chosen a different shell (e.g., by choosing a shell other than your login shell in your terminal emulator's preferences, or by explicitly invoking a shell at login time, such as with ssh remote-host /path/to/shell):echo $SHELLTo use a different shell:exec /path/to/shellE.g.:exec /bin/bash
_unix.98630
I downloaded a setup of Ubuntu 12.04 LTS of about 600 MB (don't remember the actual size) and burned it on a USB using unetbootin. So, is that Ubuntu the offline installer? I can't run an online installer as I have a Broadband with a speed of 256 kbps.
Would my downloaded Ubuntu, require an Internet Conncetion?
ubuntu;usb;live usb;iso
This is a standalone installer that you plug into your USB port and then boot your computer from the USB drive. It contains all of the basic stuff to install a complete, working Ubuntu system.According to the installation instructions on the website, they recommend you stay connected to the Internet so you can receive updates as you're installing. This ensures that your system will be up to date after installing. However, it isn't required.Once fully installed, you'll still need to connect to the Internet and update all of the packages, and you'll need to do this frequently in order to continue to keep the software up to date.
_cs.80461
Let $L \in BPP$ be decided by a poly-time $TM M (x, u)$ using certificates ofpoly-length $p(n)$.Then for every $n \in \mathbb{N}$ there exists a certificate $u_n$ s.t. for all $x$ with $|x| = n$:$$x \in L \iff M(x, un) = 1$$Can someone gives a intuitive reasont why above theorem is true?
$BPP$ class and theorem
complexity theory;probability theory
null
_unix.353230
So I've got two fresh (4TB) drives destined to serve as main storage for a desktop system. The primary requirement is redundancy and reliability. Secondary considerations are data read speed and maintainability especially in case of drive failure.The file system of choice will be BTRFS for reasons outside the scope of this question. What I can not decide on is, whether to create an MD raid 10 array in 'far 2' configuration with non-raided BTRFS on top or to use the raid 1 functionality included in BTRFS for both metadata and file content. Either option will fulfil the redundancy requirement and the fact that BTRFS is included in the Linux kernel and not flagged as experimental reassures me that it will probably be reliable enough, escpecially in respect to potential data corruption (I am writing this as kernel 4.10.3 has just been released). I have not been able to find any performance data so far that covers this setup specifically. While the administrative details are different for each setup I dont' think there is much difference in the complexity of maintaining the two - but I am saying this without experience with btrfs so far (but with md).I currently favour md10 over btrfs raid 1 because it is raid 10 that can run on only two disks and has there a decided performance advantage over md1. However the underlying architecture of btrfs raid 1 is different to md1 as it only guarantees two copies of each dataset, even on setups with more than two disks, rather than a complete mirror of each disk. The question is now if this freedom of data allocation has been implemented in a way that there are speed improvements in btrfs raid 1 over md1 that make it perform on par with md10? Are there configuration options I should consider?A second question is, whether the integration of the raid architecture into the file system itself gives any benefits at all?And then of course I would like to hear if any of my assumptions regarding redundancy, reliability and maintainability are incorrect.
btrfs on two physical drives: md raid 10 or btrfs raid 1
raid;btrfs
As a general rule, MD will outperform BTRFS for the foreseeable future. BTRFS currently serializes writes to multiple devices, and only reads from one for a given read() call.As far as data safety though, you're better off using BTRFS for replication than MD or LVM2. Because of the internal block checksumming done by BTRFS, it can tell when you make a read call whether or not the data is good and automatically fall back to the other copy if it isn't, and it will correctly select the good copy of a block on a per-block basis when scrubbing.Now, all of that said, the best option I've found so far is actually to use BTRFS in raid1 mode on top of two MD or LVM2 RAID0 volumes. While this does not perform quite as well as ext4 or XFS on top of MD RAID10, it still performs far better than the BTRFS raid10 implementation or running a single BTRFS device on top of MD RAID10 on the same devices, and provides the same data safety guarantees. Unfortunately, that does require four devices.
_scicomp.26249
I have worked on mathematical modeling based on differential equations, and now I want to simulate a cellular automaton based on a system of mixed ode-pde coupled first order differential equations \begin{eqnarray}\dfrac{dR}{dt}(t)&=&v_r(R,t),\\\dfrac{\partial v_r}{\partial r}(r,t)&=&\dfrac{R\sinh(r)}{r\sinh(R)}[1-\zeta_1\sqrt{\sigma_r^2(r,t)+2(\sigma_r(r,t)-\beta(r,t))^2}]-\epsilon[1+\zeta_2\sqrt{\sigma_r^2(r,t)+2(\sigma_r(r,t)-\beta(r,t))^2}]-2\dfrac{v_r(r,t)}{r},\\\dfrac{\partial\sigma_r}{\partial r}(r,t)&=&-\dfrac{2\beta}{r},\\\gamma(r,t)&=&\left(\dfrac{\partial}{\partial t}+v_r(r,t)\dfrac{\partial}{\partial r}\right)\beta(r,t),\end{eqnarray}where $\gamma$ is a given function depending also of $R,\;\sigma_r,\;v_r,\;\beta$ corresponding to a model with domain $\Omega\subset\mathbb{R}^2$ compact (and of course with the necessary initial and boundary conditions). But I am new in this and I have no idea of a programming platform or software (I'm not really sure how to say that) to achieve my goal.Can anyone recommend a good program to simulate cellular automaton?
A program to simulate cellular automaton model
pde;ode;simulation;reference request;cellular automata
As @BlaisB mentioned, Mathematica has quite a bit of stuff built-in to do cellular automata. You might want to check that out if you have a license. I find Mathematica to be very nice when something has library functions you can use, but if you can't solve the problem by easily stringing together library functions then I find Mathematica much tougher to use than other languages.If you will need good performance, the ideal is to use Julia, C/C++, or FORTRAN. These days I would usually recommend Julia, but other scripting languages which can do this are Python, MATLAB, and even R.But what language you use really doesn't matter all that much (except for performance. There is a difference between the languages in terms of performance which might matter if your PDEs are difficult to solve).
_softwareengineering.331772
I am using Typescript in Webstorm with Angular 2 and I am frequently getting warnings that a given method can be static. Yes, these specific methods do not depend on the state of the object they are a part of, but there will not be a time when it is used and the object is not instantiated. Should I still make those methods static?
Should a method always be static if it can be?
design;object oriented;web development;typescript
null
_codereview.33135
I've just wrote a program in C# for counting sort.space complexity is O(N+K)time complexity is O(N+K)I want reviews on my code and any better ways to implement this.namespace SortingSelfCoded{ public static class CountingSorter { public static int[] CountingSort(int [] input) { // O(1) int max = input[0]; // O(N) for (int i = 0; i < input.Length; i++) { if (input[i] > max) { max = input[i]; } } // Space complexity O(N+K) int[] counts = new int[max + 1]; int[] output = new int[input.Length]; // O(N) for (int i = 0; i < input.Length; i++) { counts[input[i]]++; } int j=0; // O(N+K) for (int i = 0; i < counts.Length; i++) { while (counts[i] > 0) { output[j] = i; j++; counts[i]--; } } return output; } }}
Counting sort review
c#;algorithm;sorting
From a practical use point of view:I'd use input.Max() (LINQ) to obtain the maximum. Less code to write and does the same.While it is ok to use single letter variables for loop counter j is not really a loop counter. It's the index of the current element so I would rename j into currentIndex.Consider changing your last while loop into a for loop. This avoids mutating the state of the count array (saves you a read and write on every iteration):for (int k = 0; k < count[i]; k++){ output[currentIndex++] = i;}Even on a 64 bit system the size of an array is limited to 2GB. So if your largest key is in the vicinity of Int32.Max / 4 or larger then you will get an OutOfMemoryException. Depending what else you are doing in your program you will get it much earlier. If you are experimenting around with sorting algorithms then there are some interesting approaches reducing the key space.
_webmaster.23377
I'm offering a page through HTTP and HTTPS, both with the same URL scheme. I.e., a page is available as http://www.example.com/page1.html as well as https://www.example.com/page1.html.Should I add rel=canonical to one of those pages?
rel=canonical required for HTTPS?
https;canonical url
null
_cs.76326
In programming languages we usually see the following data types:The bottom type: a type that has no value (eg: void in C++)The top type: all other types are subtypes of it (eg: std::any or void* in C++)Union type: one value/several typesTuple or product type: several values of several typesUnit type: a type that allows only one value...The question I have is the following: is there a name for a data structure that would be the product of unit types. In C++ a std::tuple<int, double, std::string> is a type that can hold one of all the values of ints, one of all the values of doubles and one of all the values of std::string. But how would you call the type built from {1, 1.5, Hello World!} that would only contain {1, 1.5, Hello World!}?
Name of the data type obtained from the composition of exactly one value of several data types
data structures;type theory;category theory;naming
null
_unix.73736
I use mpd to stream music to my phone (connected to Hi-Fi) via http.Yet, this only works for songs in my mpd database. I oftentimes want to play stuff in my browser and would like that to be streamed over mpd, too.Is there a way to route the pulse audio output to mpd instead of the speakers?
Stream system audio through mpd
pulseaudio;http;streaming;mpd
mpd doesn't accept pulseaudio input sources, so there is no direct way to route pulseaudio through mpd.However, what you want to accomplish is still possible, with the help of gstreamer and some cleverness. I accomplished this a few years ago.I wrote this program which implements the Gstreamer Pipeline Script component of this diagram:stream diagram http://tiyukquellmalz.org/sean/stream.svgTo sum up the diagram, here is what happens:mpd reads music files off of the disk, decodes them, and plays them to a module-null-sink type audio output of pulseaudio.Any other programs you want to run on your computer that output sound -- Adobe Flash, beeps from the gnome shell, the web browser, etc. also send their audio output to the module-null-sink of pulseaudio (it's made the default audio device of the system).The module-null-sink output has a .monitor source, which lets you take the audio that's pushed out to a null sink and capture it back in as if it were an input device (like a microphone).Pulseaudio performs software mixing on the fly of all the audio programs on the entire computer, including mpd, web browsers, and everything else using pulseaudio.The tribblify program that I wrote uses GStreamer to capture the pulseaudio null sink monitor audio, which contains mixed audio of both mpd as well as any other programs on the system; perform MP3 encoding; then stream it to a shoutcast / icecast server. tribblify essentially becomes a streaming source.The tribblify program automatically detects when mpd changes tags of the playing audio and pushes those tags down the shoutcast stream.The icecast or shoutcast server, which can be on the same computer or a different one, streams out the results to all the connected clients.
_unix.303778
My firefox didn't respond when I wanted to download a picture from photos.google.com. Then I clicked x to close its window which has multiple tabs open. Then I wanted to start firefox, but it didn't respond. I find there are several related processes in the output of ps aux | grep -i firefox, but kill their pid doesn't work. How can I remove the firefox-related processes, so that i can restart firefox?The statuses of the firefox-related processes are D, Dl, and S+. What do they mean respectively? My os is Ubuntu 14.04. Thanks.
Why can't I kill the firefox processes?
process
null
_unix.65701
Ok, so installed portmaster and I'm trying with it, I'm hoping it won't take time.So I've been up all night and my vim installation is still going on.I have an amazon ec2 freebsd server setup. I was hoping to setup jails, which took 4-5 hours to make world then crashed. I got that fixed and realized I didn't have vim. I google and found this article.So like a moron I did a make install for vim instead of vim-lite like the article says. It has been 5 hours or so and it's still going on and I have no clue what to do. It also keeps coming up with different prompts which I have to answer to continue.If I kill this installation, can I just start from scratch and install vim-lite? Will my system will be ok? Will it take this long again?Should I wait? I can't stay up any longer though to keep pressing enter!Background: On EC2 freebsd doesn't come with ports installed at all. So I installed it, took some time. Other than that, since I did make install clean inside /usr/ports/editors/vim/ it has just been spitting at my screen non-stop.
vim install on freebsd has taken 5 hours and counting
vim;software installation;freebsd;amazon ec2
It is perfectly safe to stop the build. If the system has already installed some of the dependencies, you can simply uninstall them, using a tool like ports-mgmt/pkg_cutleaves. You can then start again with the editors/vim-lite port, which has a much smaller list of dependencies (only gettext and libiconv, instead of the 72 dependencies for the full editors/vim port!), so should build much more quickly.
_codereview.15249
Just seeing if there is anyway to shorten these for statements?... fillMonthSelect: function() { var month = new Date().getMonth() + 1; for (var i = 1; i <= 12; i++) { $('.card-expiry-month').append($('<option value='+i+' '+(month === i ? selected : )+'>'+i+'</option>')); } }, fillYearSelect: function() { var year = new Date().getFullYear(); for (var i = 0; i < 12; i++) { $('.card-expiry-year').append($(<option value='+(i + year)+' +(i === 0 ? selected : )+>+(i + year)+</option>)); } },...
Anyway to shorten these for statements?
javascript;jquery
null
_unix.202286
I am currently running Fedora 16 on my laptop, which is like 3 years EOL-ed. The reason that's the case is because it is not easy to upgrade to the current version in Fedora (at least v16) and it requires a complete reinstall. So everything on it it old and doesn't work too well and I am just too lazy to move my data on an external medium and rebuild the OS. Ideally, I would like to upgrade by running a simple yum/apt-get command.So my lesson learned from this experience is that I would like my next Linux distro to be idiotically easy to bring up-to-date, not because I am incompetent to deal with Linux but simply because I am lazy and want to remain so. I also believe that, in this day and age, OSs should be very easily upgraded.What Linux distros make upgrades easy to conform to this agenda? I specifically do not want to have to move the data or the file system to a separate medium before performing the upgrade.I also would like the distro to support KDE, which is my preferred interface.
What Linux distros make upgrades easy?
distributions
Debian is probably one of the easiest to upgrade - even across major releases.From the Debian FAQ, Chapter 9, Keeping your Debian system up-to-date there is this statement,A Debian goal is to provide a consistent upgrade path and a secure upgrade process. We always do our best to make upgrading to new releases a smooth procedure.Opinion: I have just upgraded a number of systems from release 7 (wheezy) to release 8 (jessie). For the most part it just worked. One had previously been upgraded from release 6 (squeeze). This is one of the major reasons I prefer to use Debian.More information in answers to the Question Will Debian Wheezy (stable) automatically upgrade to Jessie once Jessie becomes the stable releaseUpdate: since you have amended your Question to indicate a preference for KDE, you might like to review KDE's software in Debian and these Live install images
_unix.249885
I'm writing a script to change on the fly the firefox home page through a text variable:sed -i 's|\(browser.startup.homepage,\) \(.*\)|\1 $ddrs|' /home/max/.mozilla/firefox/*.default/prefs.jsI need an help on bypassing the issue of expanding the $ddrs variable inside the sed single quote statement.
Help on edit a sed statement
sed;quoting;variable
FOUND A SOLUTION BY MYSELFInstead of insist in something cool as replace a targeted string inside a line I've opted to replace the entire line, so:First I've put the urls.txt file in the ~/.mozilla/firefox/*.default/ directory.Then I've wrote the follow code at the very begin of the /usr/lib/firefox/firefox.sh file:ddrs=$(shuf -n1 ~/.mozilla/firefox/*.default/urls.txt)nwli=user_pref(\browser.startup.homepage\, $ddrs);sed -i /browser.startup.homepage/c\\$nwli ~/.mozilla/firefox/*.default/prefs.js
_softwareengineering.323091
I have a Spring application, where we make few service calls to fetch data. There is a Data Layer in between the Controller and the Service layers.Controller (Request-Mapping) -> Data Layer -> Service LayerIf we do not get the data from the underlying service, we intend to throw an exception. My question is regarding the best practice to adopt here:Should I make the DataProvider (data layer) and the controller throw the exception and let the tomcat handle it via web.xml?Should I catch the exception in Data Layer itself, log it and not propagate the exception to the Controller?Specifically, would it be a good thing mark the controller as throws CustomException ?
What is the recommended way to handle exception in Spring MVC
java;spring mvc
Contrary to the opinion that throwing exceptions from Controller handler methods is bad, I do recommend to do so. The reasons are following:It eliminates a lot of boilerplate code. Almost all try-catches in controllers are the same and are frequently copy-pasted from one place to another. It increases code maintenance burden and coupling between controllers and exception hierarchy.There are other ways to handle exceptions correctly. Best solution is to have a global exception handler, which translates specific types of exceptions to HTTP response codes. E.g. when your database query or remote call fails with timeout, you can translate it to HTTP 503. When your repository throws ObjectNotFoundException, you can return HTTP 404. When validation fails, respond with HTTP 400. You can also have controller-specific handlers in few specific cases (vary rare situtation).That said, it does not mean, that you should have throws Exception in method signature. In layered architecture objects in higher layers like controllers cannot expect low-level exceptions (e.g. from JDBC driver), because it would violate encapsulation. There should be separate exception hierarchy per layer, which has semantics specific for that layer, and there should be exception translation (normally done by wrapping). For example, ConstraintViolationException in Repository may result in InvalidServiceRequestException in Service and translated to HTTP 400 by exception handler.
_softwareengineering.135300
I am doing legacy software programming in Visual Basic 6.0.How do I unit test it?
How to unit test Visual Basic 6 legacy code?
testing;quality;legacy;visual basic 6
null
_unix.122122
Admitted: My search in this regard was not so successful there were different approaches.I want to install it in a Debiandistro. I am a beginner!!Thanks for your suggestions.
Installing a .tgz....how?
software installation
null
_unix.324597
I try establishing USB tethering between my phone (Android 2.3) and my laptop (Antergos) by following the related article on ArchWikiHowever, when I use command 'ip link' (as it is mentioned in the guide at point 2: USB tethering) only 3 connections are shown: lo, wlp3s0, enp0s25It is the same when the phone is connected, indicating that my laptop is unable to recognize the shared connection.I've found no method for solving it so far - even stranger: regular access to my phone's memory card is entirely possible.What can be the reason, and how can I solve this issue?(EDIT: tethering is obviously turned on in any case in which I tried - connection is still not recognized)
USB tethering: interface not recognized
arch linux;usb;ethernet;android
null
_softwareengineering.146961
Meaning that OOP allows me to have data-trees, of arbitrary depth and breadth, with some leafs being functions (and those leafs would be called methods) ? Because everything else that people often put near OOP mark, just don't seem to have anything to do with it. (Inheritance, subtype polymorphism and encapsulation seem to be orthogonal to OOP).Am I right? Or I'm missing something ?
Is it fair to reduce OOP to mere hierarchical composition of data structures?
object oriented;paradigms;definition
Is it fair to reduce OOP to mere hierarchical composition of data structures? Meaning that OOP allows me to have data-trees, of arbitrary depth and breadth, with some leafs being functions (and those leafs would be called methods) ?I guess you can choose to look at it that way, but I don't believe it's a particularly useful way to look at it. Specifically, your use of the word data (even if you specifically mention functions in there) seems to reduce OOP to a way to model data (or at least, to a data-centric approach). In my opinion, this is missing the point.OOP is a particular way to structure code; both behaviour as well as data. Its main ideas are the normalisation of behaviour (DRY principle), as opposed to, say, the normalisation of data (as in the relational DB concept), and concepts like encapsulation. At its simplest, encapsulation is achieved by providing an external interface to classes (your public stuff), and an internal implementation (private / protected stuff). This is quite different to traditional modular programming, since your module boundaries are structured completely differently - in the case of OO, each class is a mini-module. It is also important to note that the concept of encapsulation, in the generic sense, is quite different to a specific implementation of encapsulation. OOP has a specific way that encapsulation is done, inherently (of course, I'm only referring to the core cases here, not patterns, etc). Inheritance and polymorphism are much more OOP specific ways to achieve other principles (code reuse being one of them). I'm not sure I'd lump them in the same sentence as encapsulation, they exist at a slightly different level.OOP also tends to map quite nicely on to a problem domain, allowing you to model a problem in a way that remains understandable to semi-technical users.What was the point of going through the above mini OOP discussion? The above is the best I can do to summarise OOP in a few sentences - it highlights the main points of OOP from the perspective of someone who has worked with the technology for a long time. I don't think reducing it to a hierarchical composition of data structures does it justice. We can also reduce it to an array of characters in text files, but it doesn't mean that it captures the essence of the paradigm.
_unix.285728
I wonder what's the exact difference between these 2 commands:1. su2. su - . Can anyone please explain?
Difference between su and su -
su
null
_softwareengineering.271342
I am an avid Go player and play on the Kiseido Go Server.I would like to write an open source client for this, but the KGS protocol is a well-kept secret. Is there any way to catch the http requests made by the *.jar file to the Go server?I know this is possible because at least one other client app (CGoban) exists.
How to identify http requests made from a closed-source java app?
java;web applications
null
_codereview.124049
I have been working on a Scrabble Word Finder for a couple of days now and have it working pretty much but would love to improve the efficiency.The code is made up of 2 classes: one for creating and managing a pool of letter tiles and another for iterating over a word dictionary (from a .txt file) to check/score word matches in the letter rack (from the tile pool) and a cross letter. As I mentioned, everything works so far, but I feel like it could be faster. I have tried taking advantage of generators but am running into problems with them in the WordFinder class as I am not very experienced in them. I will post my code as well as the code I am using to test it.scrabble_challenge.py (My Code)import csvimport randomclass TilePool(list): def __init__(self): Initializes the Tile Pool by reading the given 'tile.csv' file and converting it into a tile pool list with one list item per tile based on the amount of tiles for each letter # Open csv file with open(tiles.csv) as f: # Read csv into list of lists of each lines values tiles_csv = csv.reader(f, delimiter=,) # Convert the list into a tile pool list.__init__(self, ((line[0], line[1]) for line in tiles_csv if len(line[0]) == 1 for x in xrange(int(line[2])))) del tiles_csv def pop(self, tile_count=None): Returns a list of tiles from the tile pool based on the amount specified in the 'tile_count' parameter and the amount of tiles left in the pool. :param tile_count: The amount of tiles desired (If not specified up to 7 tiles will be returned) :return: A new list of tiles from tile pool assert len(self), # Tile Pool is empty # When the tile count is None return (up to) 7 tiles if tile_count is None: tile_count = 7 assert tile_count in xrange(1, 8), # Tile Count must be between 1 and 7 new_tiles = [] counter = 1 while len(self) and counter <= tile_count: # Return tiles while tile pool has tiles AND tile count not reached rand_choice = random.choice(self) # Get a random tile new_tiles.append(rand_choice) # Add it to new_tiles list self.remove(rand_choice) # Delete it from pool counter += 1 return new_tiles def view_pool(self): Prints each tile in the pool with it's 'Score' value :return: None assert len(self), # Tile Pool is empty for tile in self: print({letter}: {score}.format(letter=tile[0], score=tile[1]))class WordFinder: def list_words(self, letters, cross_letter): if cross_letter is None: cross_letter = '' with open(word_dictionary.txt) as x: word_dict = (line.strip() for line in x) accepted = [] for word in word_dict: if cross_letter in word: min_cross = list(word.replace(cross_letter, '', 1)) score = 0 for letter in letters: if not min_cross: accepted.append((word, score)) break elif letter[0] in min_cross: min_cross.remove(letter[0]) score += int(letter[1]) return acceptedtesting_code.pyimport sysimport scrabble_challengedef main(): cross_letters = [chr(x) for x in xrange(97, 123)] cross_letters.insert(0, None) # the first word has no cross letter tile_pool = scrabble_challenge.TilePool() word_finder = scrabble_challenge.WordFinder() while len(tile_pool): letters = tile_pool.pop() for cross_letter in cross_letters: for word, score in word_finder.list_words(letters, cross_letter): print word, score return 0if __name__=='__main__': sys.exit(main())I would like to have some way of initializing the word_dict generator in the __init__ so it isn't being generated in every loop in my testing_code.py. But when I tried adding this:with open(word_dictionary.txt) as x: word_dict = (line.strip() for line in x)in the __init__ I would get a ValueError: I/O operation on closed file error. But this structure works on the list comprehension in class TilePool.I'd also like to get the list_words method to yield as opposed to return. My attempts at both of these have failed. Any other code efficiency suggestions (for scrabble_challenge.py) are certainly welcome.
Scrabble word finder
python;performance;generator
null
_ai.1658
I was reading that the Valkyrie robot was originally designed to 'carry out search and rescue missions'.However there were some talks to send it to Mars to assist astronauts.What kind of specific trainings or tasks are planned for 'him' to be able to carry on its own?Refs:NASA-JSC-Robotics at GitHubgithub.io pagegitlab page
What would the Valkyrie AI robot do on Mars?
robotics;nasa
null
_webmaster.13286
My team is launching a new site soon.Is it worth blocking spiders from indexing the landing page right now? What effects will this have on my long term SEO results. Is this question even relevant? Edit: title changed to reflect real nature of the question.Edit2: great answers below, but in reality I am looking for an answer that directs me to whether the practice of blocking robots pre launch is good or bad for future SEO results.
Pre-launch Disallow in robots.txt?
seo;web crawlers;robots.txt
If the landing page could allow your competitor's to gain an advantage or steal some of your ingenuity, then YES - BLOCK IT. However that doesn't mean your page won't appear in search engine results. It is better to add <meta content=noindex> to each page but more of a pain to add and adjust.This article is great and will help with the details -> robots.txt and effect on SEO
_softwareengineering.337513
How do game makers/engines like Buildbox, GameSalad, Construct, GameMaker, etc work in principle? I am not interested in getting a list of technologies (programming languages, APIs, etc), since I know this kind of question would be immediately closed here on this site as too broad, but how - from a software engineering perspective - do these programs convert the user's interactions into exportable code?To avoid this getting too broad, what I'm looking for is only a rough outline how the software creates code/source files from the user interactions with the software. While details would be awesome, a high level overview would be sufficient.I'm a second year CS major and have some experience with Java/C/C++ as well as some web languages and framework. It's hard to find information on how a game creation software works because there's more content on how to make games in general.EDIT: In case you don't know, Buildbox, GameSalad, Construct, GameMaker are popular drag and drop game builders. While Buildbox is exclusively drag and drop, the others have optional scripting languages as a feature.
General architecture of game makers (without coding)?
game development;code generation
The earliest of this kind of system I encountered was an engine called HURG. They've become at lot more advanced since then, but basically they all work the same way: they have an embedded pre-programmed engine (or a few different engines for different genres of games) that have a very large number of options for customizing them, a simple way of programming behaviour for game objects graphically (and in most cases also ways of linking those objects to externally-written programs in some kind of scripting language), and a graphic asset pipeline for importing your artwork. They then have a method that packages up everything except the editor into an installable module with an executable that simply loads the engine with your options and assets and starts it.In other words, they're really not very much different from a highly customizable game that supports full conversion mods (e.g. the Half Life series, which supports mods that are almost as well known as the game itself, e.g. Counterstrike), except that they're supplied with the development tools you'll need rather than having to obtain those separately.
_codereview.35664
I've attempted to write a program to find the largest palindrome in a sentence. Spaces are included and characters are case-sensitive. Can you suggest better ways of doing this?//public static void main(String args[])--String source = my malayalam is beautiful;//Find the the largest palindrom in this sentenceStringBuilder sb = new StringBuilder( source);String p = sb.reverse().toString();System.out.println(p);System.out.println(source);int largest = 0;try{ for (int start=0; start <=source.length(); start++ ){ for (int end=start+2; end < source.length(); end++){ if (largest < (end-start)){ String sub = source.substring(start, end); if (p.indexOf(sub) > 0){ largest = sub.length(); System.out.println(sub+ +largest); } } } }}catch(Exception e){ System.out.println(2); e.printStackTrace();}
Finding largest string palindrome
java;strings;palindrome
There are two things that can be criticized here: Your coding style and your algorithm.Code StyleThere are unnecessary spaces inside some parens: new StringBuilder( source), for (; start++ ){. Make a conscious decision to follow one style and follow it through.Improve readability by consistently putting a space around most operators like =, -, + and <=.Never ever catch (Exception e)! If there is a specific exception you would like to catch, then please do, but specify the appropriate class or interface. But often it is better to just let the exception bubble up through the call stack.Do not catch exceptions you are not interested in actually handling. Do not catch exceptions you have no idea where they would come from. Why are you currently catching an ArithmeticException? Is there any chance e.g. for a division by zero in your code? ArrayIndexOutOfBoundsException? Where are you using arrays? ArrayStoreException? Where are you storing stuff into an array? ClassCastException? Your code does not contain a single cast. ClassNotFoundException? You have no dynamic class loading in your code. CloneNotSupportedException? You don't call clone on any object.Use good variable names that make it clear what a certain variable means. Shouldn't p be reversed or something like that?I would not introduce a sb variable for the StringBuilder, but rather: String reversed = new StringBuilder(source).reverse().toString();The palindrome finding code is not callable as a method. Extracting code into sensible methods improves testability, and can make it easier to design good programs.BugsSome bounds you choose are rather weird. For example, start <=source.length() should be start < source.length() or even better start <= source.length() - largest.The indexOf method returns an index on success, and -1 on failure. The snippet if (p.indexOf(sub) > 0) is therefore misleading. Anyway, you should be actually using if (p.contains(sub)).Your logic just asserts that the source string contains both a substring and the reversed substring. It does not assert that it contains any palindrome. For example, computers return will cause your code to output uter. You would have to check the actual indices, or better: that the substring equals itself reversed.AlgorithmYour current algorithm works by extracting all possible substrings of length 2 or longer, and then checks whether the substring reversed is contained in the source string. As explained above, this is wrong. It is also quite inefficient, because your algorithm runs in O(n) (two nested loops).The problem could be solved in a fraction of the code by a recursive regular expression, e.g. in Perl/PCRE: (.)(?:(?R)|.?)\1. Sadly, the regex implementation of the Java standard library does not support this.According to the Wikipedia article on Longest Palindromic Substrings, it is possible to find them in linear time. You may want to implement such an existing algorithm.
_codereview.132104
I'm having trouble optimising the project euler #50 exercise, it runs for around 30-35 seconds, which is terrible performance.The prime 41, can be written as the sum of six consecutive primes:41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred.The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.Which prime, below one-million, can be written as the sum of the most consecutive primes?The catch here is that it's not necessary to start from 2, the sum of consecutive primes which add to 953 are starting from 7.Here's my code : static void Main(string[] args) { int max = 0; int maxCount = 1; List<int> primes = new List<int>(); Stopwatch sw = Stopwatch.StartNew(); bool[] allNumbers = SetPrimes(1000000); for (int i = 0; i < allNumbers.Length; i++) { if (allNumbers[i]) { primes.Add(i); } } foreach (int prime in primes) { int startingIndex = 0; while (primes[startingIndex] < prime/maxCount) { int n = prime; int j = startingIndex; int sum = 0; int count = 0; while (n > 0) { sum += primes[j]; n -= primes[j]; j++; count++; } if (sum == prime) { if (count > maxCount) { maxCount = count; max = prime; } } startingIndex++; } } sw.Stop(); Console.WriteLine(max); Console.WriteLine($Time to calculate : {sw.ElapsedMilliseconds}); Console.ReadKey(); } private static bool[] SetPrimes(int max) { bool[] localPrimes = new bool[max + 1]; for (int i = 2; i <= max; i++) { localPrimes[i] = true; } for (int i = 2; i <= Math.Sqrt(max); i++) { if (localPrimes[i]) { for (int j = i * i; j <= max; j += i) { localPrimes[j] = false; } } } return localPrimes; }
Project Euler #50 Consecutive prime sum
c#;performance;programming challenge;primes
Even though your prime number generator is not the bottleneck, you should not do this:for (int i = 2; i <= Math.Sqrt(max); i++) ^^^^^^^^^Do not calculate the same square root in every loop iteration. Sqrt is an expensive enough operation that you don't want to call unnecessarily. Calculate it only once, store that in a variable and use that in the loop.I couldn't completely analyze your algorithm, but I ran through the first few steps with the debugger. It looks like you're doing a lot of unnecessary work.For each prime, you start by looking for a sum of length 1, then length 2, then 3, etc. Even if you have already found a sum of length 100, you always start at 0 again. I'm guessing that's where your bottleneck is.You want to find the longest anyway, so why not start at the maximum length and shorten it as you go? You can stop as soon as you find one. (there are a lot more possible sums of length 2 than of length 500)My algorithm works like this:We have a sum of primes: p(1), p(2), p(3), ... p(n-1), p(n)See if this sum is a prime also (by doing a binary search on the prime numbers)If it's not, check the next sum of the same length by substracting p(1) and adding p(n+1). Keep doing this until we find a prime or until the sum becomes greater than 1000000.Then, shorten the length by 1 by subtracting the last prime, so we get the sum p(1),p(2),p(3)...p(n-1) and check each sum of this length, etc.(This code is a few years old and might still be a little sloppy)public int Solve050() { const int Limit = 1000000; int[] primes = WhateverPrimeGenerator.PrimesUpTo(Limit).ToArray(); int sum = 0, length = 0; //Find the maximum possible length by adding up primes, while sum < Limit while (sum < Limit) { int newSum = sum + primes[length]; if (newSum >= Limit) break; sum = newSum; length++; } int answer = 0; for (; length > 1; length--) { answer = FindPrime(primes, Limit, sum, length - 1); if (answer > 0) break; sum -= primes[length - 1]; } return answer;} //Tries to find a prime of sum-length defined by lastIndexprivate static int FindPrime(int[] primes, int maxSum, int sum, int lastIndex){ int result = 0; int index = lastIndex + 1; for (int firstIndex = 0; lastIndex < primes.Length && sum <= maxSum; firstIndex++, lastIndex++) { index = Array.BinarySearch(primes, index, primes.Length - index, sum); if (index > 0) result = primes[index]; //Prime found if (index < 0) index = ~index; sum = sum - primes[firstIndex] + primes[lastIndex + 1]; } return result;}
_unix.137590
I'm connected via SSH to a PC running Linux kernel 3.11.1:root@alix:~# uname -r3.11.1how can I find out which package installed this specific file or kernel version respectively?I triedroot@alix:/boot# dpkg -S vmlinuz-3.11.1 dpkg-query: no path found matching pattern *vmlinuz-3.11.1*Other installed kernel versions can be found with dpkg -S:root@alix:/boot# dpkg -S vmlinuz-3.2.23linux-image-3.2.23-ath5kmod: /boot/vmlinuz-3.2.23-ath5kmodMy purpose: I would like to install the corresponding Linux headers for version 3.11.1 to compile a kernel module for it. apt-cache search linux-headers lists 15 different header versions but not that one for 3.11.1.Thank you very much.
Debian: get package name for installed file
debian;kernel;dpkg;header file
You can list every installed package with dpkg -l and filter through the results with grep for the kernel packagesdpkg -l | grep 'linux-image'dpkg -l | grep 'linux-image' | grep '3.11'To find the kernel headers package for your running kernel:apt-cache search linux-headers-`uname -r`
_webapps.108933
I am thinking about a way to make Alexa send for a list the current playing song, so whenever I discover a new music I really like, I can say Alexa, get me this song, and she sends this one specific song to my spotify list. IFTTT offers tools to send spotify musics for lists, but not the specific one playing at the moment.My first strategy was:1- Alexa, what is playing? # and then she answers2- Alexa, add name of the music (which she just told me) to my to-do-list3- Set IFTTT to get a spotify music to a list when I add a to-do4- Set the then spotify part to use the string in the to-do to search the musicBut there are two problems:a) Spotify searches with the string yo give it and add the first result, which may or may not be what you wantedb) Spotify would add something when you add a to-do, even if it's not a music, but a simple thing you have to do in your dayThinking about the second problem, I was searching for a way to set a second condition... like... If I send a to-do AND the to-do begins with get me the music (and the name of music ans artist), then spotify searches for that name and add the result.I found apilio.io that would allow me to create conditions, but I'm a total noob and I couldn't manage to use apilioWell... I wonder if there is a way to get the current song for a list... Anyne knows something about it or could give me tips or references of material where I can learn and built something? Thanks in advance for your time and attentionPS.: Is this the right stack to post a question like this?
Get Alexa to send the current spotify song to a list
if this then that;spotify;alexa
null
_webmaster.72027
Recently new TLD's such as .actor, .agency and many more were introduced. There is a significant price difference between the 'old' and new TLD's.For example:I can buy a .com for $9.45 but .ceo costs $75.00. There are differences between the registrars but I can't find them anywhere cheaper.So why are the new TLD's so expensive? Some are a lot cheaper but the most are very expensive.
Why are the new TLD's so expensive?
domains;top level domains;cost
null
_unix.22419
For example, from this file:CREATE SYNONYM I801XS07 FOR I8010.I801XT07 *ERROR at line 1:ORA-00955: name is already used by an existing objectCREATE SYNONYM I801XS07 FOR I8010.I801XT07 *ERROR at line 1:ORA-00955: name is already used by an existing objectTable altered.Table altered.Table altered.Table altered.Table altered.Table altered.Table altered.Table altered.DROP INDEX I8011I01 *ERROR at line 1:ORA-01418: specified index does not existIndex created.I want a way to find ORA- and show the ORA- line and the previous 4 lines:CREATE SYNONYM I801XS07 FOR I8010.I801XT07 *ERROR at line 1:ORA-00955: name is already used by an existing objectCREATE SYNONYM I801XS07 FOR I8010.I801XT07 *ERROR at line 1:ORA-00955: name is already used by an existing objectDROP INDEX I8011I01 *ERROR at line 1:ORA-01418: specified index does not exist
Show lines matching a pattern and the 4 lines before each
command line;grep;sed;awk;hp ux
Supposing you're on an elderly system, like HP-UX, that doesn't have GNU utilities, just the old, original BSD or AT&T grep. You could do something like this:#!/bin/shawk '/ORA-/ { print line1; print line2; print line3; print line4; print $0 }\// {line1 = line2; line2 = line3; line3 = line4; line4 = $0}' $1Yes, there's tons of edge conditions this doesn't get right, but whatta ya want for nothing? Also, given that you're working on some decroded, antiquated OS and hardware, you probably don't have the CPU horsepower for fancy error handling.
_webapps.49235
I put my tasks on my calendar as 'all-day' events (there is Google Tasks for Calendar but I don't want to use it). However, since August ended with a Saturday, there is not a single day of September displayed on the month view of August, so I can't drag-and-drop my events from August to September. I don't want to click and go to the edit view of every single August event/task and change the date to September. Is there a faster way?
How do transfer Google Calendar 'all day' events from one month to the other?
google calendar
Go to your settings and change Week starts on: to Monday. Drag all your events, then change Week starts on: back to Sunday (if that is what you prefer).You can also use the mini-calendar in the left sidebar: click and hold on the first day of August, then drag down into September. All the days you select will appear in the main calendar view.
_codereview.112044
WE_ALL_LOVE_SHOUTY_SNAKE_CASE_SO_I_WROTE_A_PROGRAM_FOR_IT!!1!Alright, enough of this. This is a rags-to-riches from this question. The pattern is pretty simple, it takes a String input, verifies if it is numerical, and if so, converts it to SHOUTY_SNAKE_CASE.Example : 1231 -> ONE_TWO_THREE_ONEIt is fairly simple but it is also the first time I used the Java 8's streams, so I wanted an opinion on my (simple) use of it.private static final String[] words = new String[]{zero,one,two,three,four,five,six,seven,eight,nine};public static String convertNumbersToWords(final String input) { if(input == null || !input.matches(^\\d*$)){ throw new IllegalArgumentException(input cannot be null or non-numerical.); } return input.chars() .mapToObj(c -> getWordFromCharCode(c).toUpperCase()) .collect(Collectors.joining(_));}private static String getWordFromCharCode(int code){ return words[code - 48];}
SHOUTY_SNAKE_CASED NUMBERS
java;rags to riches;numbers to words
Since you need an enumerated set of LOUD_WORDS that aligns with numbers, preferably as some form of numeric indices... an enum instead of String[] seems to be the perfect fit:enum Word { ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE;}(I think you can figure out the derivation.)edit: Just one note about using Word.values() as pointed out in @Simon's comments: it creates a new array each time and this may not be desirable, performance-wise.Since you're also experimenting with some of the Java 8 features, you may want to consider using an Optional too, to eliminate the if-validation:private static final String NUMBERS_ONLY = ^\\d+$;// UsageOptional.ofNullable(input) .filter(v -> v != null && v.matches(NUMBERS_ONLY)) .orElseThrow(IllegalArgumentException::new) .chars() // ...If you prefer to throw NullPointerException for null values, you can stick with Optional.of(T).
_ai.1334
Is there any simple explanation how Watson finds and scores evidence after gathering massive evidence and analyzing the data?In other words, how does it know which precise answer it needs to return?
How does Watson find and evaluate its evidence to the answer?
watson
Watson starts off by searching its massive database of sources for stuff that might be pertinent to the question. Next, it searches through all of the search results and turns them into candidate answers. For example, if one of the search results is an article, Watson might pick the title of the article as a possible answer. After finding all of these candidate answers, it proceeds to iteratively score them to determine which one is best.The scoring process is very complicated, and involves finding supporting evidence for each answer, and then combining many different scoring algorithms to determine which candidate answer is the best. You can read a more detailed (but still very conceptual) overview here, by the creators of Watson.
_unix.106070
By default, the monospace font for my distribution (Trisquel) is Font A. I would like to change it to font B. Some time ago, I managed to make a partial change to Font C, but I have since forgotten this method and cannot reproduce it.The trouble is that now I may see all three fonts in monospaced contexts. Using gnome-tweak-tool as both root and user, I have changed the monospace field to Font B. I have also done this via the command line on gsettings, again as both root and user. However:If a web page requests the style {font-family: monospace;}, Font C displays. Edit: this was a setting in Firefox, which I have changed.In the Inkscape and gedit font menus, there is a font called simply Monospace, which is font A. My distribution's default UI fonts, which I have changed, also display in these menus under the names Sans and Serif.When Thunderbird messages I have received are formatted as plain text, they are displayed in Font A. Unless explicitly changed, messages I write also display in the fonts Sans and Monospace.How can I fix this situation, such that Font B displays in all contexts described above, and the mysterious Sans font is replaced by the UI font I am currently using?
Changing monospace fonts system-wide
fonts;fontconfig;trisquel
I figured it out by searching the system for the name of Font A. There should be a file (more accurately, a link to a file) /etc/fonts/conf.d/01-trisquel.conf. You will need to edit this file to include the names of your chosen fonts as highest priority (above the existing <family> entries).
_unix.167378
Is there a way to mirror a directory structure and files there contained with rsync, giving out facade zero length files? I mean, mirroring dirs (-d flag I think) exactly as they are, while not copying the files and substituting them some sort or symlink(?) or something like an empty file with his name and attr and no size?In short I want to mirror an env entirely while minimizing uninportqnt files size.
rsync copy only files facade
rsync;file copy
null
_webmaster.74222
We are creating a movie database site and I have a big dilemma...Shall we keep the movie posters, episodes, screen images in our host or shall we use TMDB (themoviedb API) for loading those images? What is better in terms of SEO?I'm thinking that saving those images locally will take a lot of disk space but Google will crawl those images and it will be better for SEO. Also I can optimize all those images and load the page faster since we are using a good dedicated server.In the case of using TMDB API will affect the SEO? Is it good to load sources from external sites in terms of SEO even its API?
Movie Database - Load images from API or locally?
seo;google search;images;api
It would be better to do it yourself.You don't want to rely on an API (if it goes down or it gets discontinued).More often than not, relying on external APIs will slow down the load times of your site. As you probably already know, page speed is a ranking factor.