id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_codereview.105455 | GivenRoy wanted to increase his typing speed for programming contests. So, his friend advised him to type the sentence The quick brown fox jumps over the lazy dog repeatedly, because it is a pangram. (Pangrams are sentences constructed by using every letter of the alphabet at least once.) After typing the sentence several times, Roy became bored with it. So he started to look for other pangrams. Given a sentence s, tell Roy if it is a pangram or not. Input Format Input consists of a line containing s.ConstraintsLength of s can be at most 103 \$(1|s|103)\$ and it may contain spaces, lower case and upper case letters. Lower case and upper case instances of a letter are considered the same.Solution 1from collections import defaultdictimport stringdef is_pangram(astr): lookup = defaultdict(int) for char in astr: lookup[char.lower()] += 1 for char in string.ascii_lowercase: if lookup[char] == 0: return False return Trueprint pangram if is_pangram(raw_input()) else not pangramSolution 2from collections import Counterimport stringdef is_pangram(astr): counter = Counter(astr.lower()) for char in string.ascii_lowercase: if counter[char] == 0: return False return Trueprint pangram if is_pangram(raw_input()) else not pangramWhich is better in terms of running time and space complexity? | Pangrams python implementation | python;programming challenge | Since you do not actually need the count of each character, it would be simpler to use a set and the superset operator >=:def is_pangram(astr): return set(astr.lower()) >= set(string.ascii_lowercase):Your two solutions are almost identical, though herefor char in astr: lookup[char.lower()] += 1 it would be faster to lowercase the whole string at once (like you already do in solution 2):for char in astr.lower(): lookup[char] += 1 Other than that, the only difference is defaultdict vs. Counter. The latter makes your code more elegant, but since the standard library implements Counter in pure Python, there may be a speed advantage to defaultdict. |
_cs.26180 | The $G(n,p)$ random graph model creates graphs with $n$ vertices and each possible edge exists independently with probability $p\in (0,1)$. Much is known about the (expected) size of a largest clique in these graphs, and it has been shown that the expected number of maximal cliques of size $d$ is $${n\choose d} p^{d \choose 2} (1-p^d)^{n-d}.$$To find the expected number of maximal cliques, just sum over all values of $d$ to get $$\mu (G(n,p)) := \sum_{d=1}^n {n\choose d} p^{d \choose 2} (1-p^d)^{n-d}.$$I'm interested in the asymptotic growth of $\mu (G(n,p))$ as a function $n$. For example, if $p$ is fixed, does $\mu$ grow polynomially in $n$? A quasi-polynomial bound is not hard to show. Since the expected maximum clique size is roughly $\omega(G(n,p))\approx\frac{2 \log n}{\log(1/p)}$, the number of cliques (not necessarily maximal) is $O( {n \choose \omega(G(n,p))+1}) = O(n^{\omega(G(n,p))+1})=O(n^{\frac{2 \log n}{\log(1/p)}+1})$. | Expected number of maximal cliques in $G(n,p)$ | graph theory;probability theory;random graphs;clique | null |
_unix.321192 | I've tried making backups using the default tools in my Linux distro (Mint 17.3), and I seem to have run into a problem. It took me awhile to figure out why, but apparently it's trying to follow some of my links, which point to various places on the root drive and tries to back them up too. Considering that my /home/$USER folder is currently several hundred GB in size, my last backup was nearly ago, and my disk was under heavy use for awhile due to a known issue with ASRock mobos spamming the logfiles, I'm a bit concerned for the safety of my data and would like to get started soon.I've tried the GUI tool and I've tried tar, cp, and 7z (no flags on any because I don't know which ones to use and the man pages can be pretty dense), but I don't know what other ways there are of doing this that I haven't tried. If it matters, the links I know it's hanging on were created by POL and Steam (I can't tell you whether they're hard, soft, or symbolic), though I think there are others that will mess it up too. The source and destination drives are both EXT4, though I experienced the same problem when the destination drive was an NTFS.Clearly, the reason the operation is aborting due to a permission error when trying to access / . However, even if I was to run this as root, the backup operation would simply find its way back to / and recursively back everything up until my external drive is full. I need some way to prevent it from following links, but to just copy them as-is.I just need a simple archive of my home folder I can copy back over if my current hard drive dies. I don't need a bootable backup, my system settings are only lightly modified and is easy to get back in order if I need to reinstall. The best solution is something I already have, the next-best would be free software in the repos, the next best would be a source-distributed free software tool, and if none of those are available, a trusted commercial tool of some sort. | What tool can I use to create backups? | linux;linux mint;backup | I would simply use rsync. It's simple, fast and does exactly what you want. Here's how a command could look likersync -avz --delete /home/user /mnt/bkpSee man rsync for the meaning of the flags. -avz is quite standard. Note that I added the --delete option as well, that means when you delete a file in your home directory and you make a backup, it will also be removed from your backup. Be careful when testing! |
_cstheory.10720 | It is known how to construct lossless unbalanced bipartite expanders with the following properties: the bipartite graph has $n$ left vertices, $m$ right vertices, left-degree $D$, and for all left-sets $S$ of size up to $\gamma n$, the neighbor set $\Gamma(S)$ has size at least $(1 - \epsilon)D|S|$, and this is achieved for any $m \leq n, \epsilon > 0$, and $D = \Theta(\log(n/m)/\epsilon)$, $\gamma = \Theta(\frac{\epsilon m}{Dn})$. The construction due to Capalbo, et al. achieves these parameters.It's clear that $\gamma \leq m/(Dn)$, but how large can $\gamma$ be? In particular, I'm wondering if it's possible to make $\gamma$ very close to $1/4$, say; this would essentially require one to make $m = n$ and $D = 4$ for any hope of accomplishing this -- $\epsilon$ hasn't even been considered yet! However, does anyone familiar with expander constructions have a sense of what hidden constants lay within the $\Theta$'s? | Lossless, constant-degree expanders that expand large sets | graph theory;co.combinatorics;expanders | null |
_cs.42773 | On partial planarization I understand an algorithm, which tries to reach a optimal, or nearly-optimal solution for non-planar graphs. For example, which minimizes the number of the crossing edges (but I can imagine some other viewpoint, too).I think, a such algorithm could be maybe even fast (around $O(V^3)$ or maybe faster).Is there a such algorithm? | Is there a fast, partial planarization algorithm for non-planar graphs? | graphs;planar graphs | null |
_cs.62572 | Im searching about conditional random fields for a long time and cant understand the concepts of this algorithm.I understood markov chains, and understood that conditional random field is a more complex modification of markov chain, Im right?So, what is the best didactic explanation of conditional random fields? | How the conditional random fields algorithm work? | algorithms;machine learning;natural language processing;markov chains | null |
_unix.251570 | I'm using openSUSE 42.1 and opened a fresh install of Firefox, but somehow when I try to download a zip file from my Google Drive, an error is shown:Could not download [filename]. HTTP error.This is the second time, and it only happens with Firefox.I found only one solution, which is to remove cookies.sqlite, but it did not work for me. | Google Drive HTTP Error when downloading .zip file with Firefox | files;download;http;google drive | null |
_unix.283924 | I have a micro-controller device that is sending newline-terminated strings through the USB-attached serial port and (so far) I'm using minicom version 2.6 to read from /dev/ttyACM0. I've setup the terminal application for line wrapping but I'd like it to go to the beginning of the next line when receiving a line feed character from my serial device. Can [and how does] minicom do that?EDIT: I've also tried ways known by me such as stty /dev/ttyACM0 ...,inlcr and screen /dev/ttyACM0 ...,inlcr, which I know have options to translate incoming new-line into carriage-return+line-feed (CR+LF) and none of these work either. I've tried other options as well (such as ocrnl, in case my logic was wrong, nl and -nl), none work and I don't know why.Ah, and I'm running Manjaro 16.06-rc1. | How can minicom permanently translate incoming newline (\n) to CR+LF? | serial port;newlines;minicom | Took me long enough but here I am at last! I've had to download minicom source code to get an idea what to do to avoid the hassle of constantly pressing Ctrl+Z, U... Here it is.minicom stores its parameters in a configuration file, which defaults to $HOME/.minirc.dfl. Put the following line, to the letter:pu addcarreturn Yesand now minicom adds a carriage return to all incoming lines. I have no idea why it didn't save that option along with its configuration file in the first place but, heck, I don't care now!Beware that every option after pu must take exactly 16 characters, padded with spaces to the right. |
_softwareengineering.188895 | I'm tinkering with a query abstraction over WebSQL/Phonegap Database API, and I find myself both drawn to, and doubtful of, defining a fluent API that mimics the use of natural English language grammar.It might be easiest to explain this via examples. The following are all valid queries in my grammar, and comments explain the intended semantic://find user where name equals foo or email starts with foo@find(user).where(name).equals(foo).and(email).startsWith(foo@)//find user where name equals foo or barfind(user).where(name).equals(foo).or(bar);//find user where name equals foo or ends with barfind(user).where(name).equals(foo).or().endsWith(bar);//find user where name equals or ends with foofind(user).where(name).equals().or().endsWith(foo);//find user where name equals foo and email is not like %contoso.comfind(user).where(name).equals(foo).and(email).is().not().like(%contoso.com);//where name is not nullfind(user).where(name).is().not().null();//find post where author is foo and id is in (1,2,3)find(post).where(author).is(foo).and(id).is().in(1, 2, 3);//find post where id is between 1 and 100find(post).where(id).is().between(1).and(100);Edit based on Quentin Pradet's feedback: In addition it seems, the API would have to support both plural and singular verb forms, so://a equals bfind(post).where(foo).equals(1);//a and b (both) equal cfind(post).where(foo).and(bar).equal(2);For the sake of question, let's presume that I haven't exhausted all possible constructs here. Let's also presume that I can cover most correct English sentences - after all, the grammar itself is limited to the verbs and conjuctions defined by SQL.Edit regarding grouping: One sentence is one group, and the precedence is as defined in SQL: left to right. Multiple groupings could be expressed with multiple where statements://the conjunctive and() between where statements is optionalfind(post) .where(foo).and(bar).equal(2).and() .where(baz).isLessThan(5);As you can see, the definition of each method is dependent on the grammatical context it is in. For example the argument to conjunction methods or() and and() can either be left out, or refer to a field name or expected value.To me this feels very intuitive, but I would like you hear your feedback: is this a good, useful API, or should I backpedal to more straighforward implementation?For the record: this library will also provide a more conventional, non-fluent API based on configuration objects. | Using natural language grammar in fluent API | javascript;api | I think it's very wrong. I study natural langage and it's full of ambiguity that can only be resolved with context and a lot of human knowledge. The fact that programming languages are not ambiguous is a very good thing! I don't think you want meaning of methods to change according to context:This is adds more surprises since you bring ambiguityYour users will want to use constructions that you will not have covered, eg. find(user).where(name).and.(email).equals(foo);It's hard to report errors: what can you do with find(user).where(name).not().is().null();?Let's also presume that I can cover most correct English sentences - after all, the grammar itself is limited to the verbs and conjuctions defined by SQL.No, you can't cover most correct English sentences. Others have tried before, and it gets very complicated very quickly. It's called Natural language understanding but nobody really tries that: we're trying to solve smaller problems first. For your library, you basically have two options:either you restrict yourself to a subset of English: that gives you SQL,or you try to cover English and you find out that it's not possible due to the ambiguity, complexity and diversity of the language. |
_unix.27506 | I had difficulties installing Cisco5.0 VPN on my Ubuntu 10.04 LTS. I asked for assistance in this question: link to previous question. The answer is that this Cisco program will run on only older versions of the kernel. I would like to use the VPN to connect through my university's network so that I can view academic journals under their subscription. One option could be to downgrade the kernel; how can this be done and what consequences would this have? The second question is whether I can install an alternative VPN client to connect? I have a .pcf file from the university to use with the Cisco client. Would this be compatible information to allow another client to connect? Is the connection independent of the software used? | Installing OpenVPN to replace Cisco VPN because Cisco will not work with the kernel I am on or downgrade instead? | ubuntu;kernel;software installation;vpn;openvpn | I installed VPNC instead through the synaptic package manager. It was able to import the .pcf file for the cisco VPN. It was then able to connect properly. |
_softwareengineering.85764 | According to a popular SO post is it considered a bad practice to prefix table names. At my company every column is prefixed by a table name. This is difficult for me to read. I'm not sure the reason, but this naming is actually the company standard. I can't stand the naming convention, but I have no documentation to back up my reasoning. All I know is that reading AdventureWorks is much simpler. In this our company DB you will see a table, Person and it might have column name:Person_First_Name or maybe even Person_Person_First_Name (don't ask me why you see person 2x)Why is it considered a bad practice to pre-fix column names? Are underscores considered evil in SQL as well? Note: I own Pro SQL Server 2008 - Relation Database design and implementation. References to that book are welcome. | Why is prefixing column names considered bad practice? | sql | Underscores are not evil just harder to type. What is bad is changing standards midstream without fixing all the existing objects. Now you have personId, Person_id, etc. and can't remember which table uses the underscores or not. Consistency in naming (even if you personally don't like the names) helps make it easier to code.Personally the only place I feel the need to use the tablename in a column is on the ID column (the use of just ID is an antipattern in database design as anyone who has done extensive reporting queries can tell you. It's so much fun to rename 12 columns in your query every time you write a report.) That also makes it easier to immediately know the FKs in other tables as they have the same name. However, in a mature database, it is more work than it is worth to change an existing standard. Just accept that is the standard and move on, there are far more critical things that need to be fixed first. |
_unix.20844 | I'm just getting into server administration and now everybody needs something. Lately I'm getting stuck on package hunting, so I'm on the search to find the most comprehensive repo list of LAMP packages.What repositories do you use in your list for LAMP resources and why do you use them? | What is the best CentOS 6 repo list for LAMP stacks? | package management;yum | null |
_softwareengineering.344089 | I'm relatively new to jwt.io and authentication and I'm using JWT.io in following manner.Server SideOnce user logs in, I generate a token with userid embedded inside and pass it back to the user in the message bodyClient Side Browser/JSI'm storing the token in localStorage and for each subsequent request, I'm passing the token in the headers.Authorization: Basic someEncryptedValueI've also usedX-Auth-Token: someEncryptedValueCould I use this in a cookie?Then on the server side, I'm verifying the token against the secret, checking expiry, getting the id out of the token and then serving the request.Is everything correct in this workflow? | Authentication via tokens | authentication;session;authorization;cookies | null |
_webapps.22621 | How do you unsubscribe someone that has subscribed to you? My son has a woman who has subscribed to him on Facebook and is sending him links to objectionable sites. How does he stop this? | How do you block someone who has subscribed to you? | facebook | null |
_unix.276759 | I am a moderately experienced vim user, who is now beginning to use GNU emacs. At about the same time as I learned that Ctrl-p and Ctrl-n are the default for up and down in emacs, I also learned they are variants of k and j in normal mode in vim.Does anyone know the origin of these shortcuts? I suppose that logically they come from p(revious) and n(ext), or maybe (u)p and (dow)n, but I am asking about what programme, system or standard they were part of. It seems unlikely that a couple of random emacs shortcuts were borrowed into vim, so their inclusion in both makes me think that they probably predate both emacs and vim.*It's hard to find the answers to questions of keystrokes using Google, but interestingly they are not mentioned as arrow keys on the seemingly comprehensive Wikipedia article.*Thanks to Thomas Dickey and Mark Plotnick who have pointed out in comments that the shortcuts in question are documented in 1984 vi (sic), and 1978 emacs reference works, but I think the question of common origin still stands. | What is the historical origin of CTRL + P for up and CTRL + N for down? | vim;keyboard shortcuts;emacs;history | null |
_unix.341731 | I've spent the last hour deliberating on what to name a property which means the total opposite of resolved, physical realpath.For example, let's assume /foo/bar/ is an ordinary physical path. If a symlink was created at /quux which simply pointed to /foo, is it appropriate to refer to everything accessed via /quux/foo/bar/ as a symlinked path...?This is mostly a question about nomenclature, because I'm uncertain if there's a more accurate way of referring to an unresolved pathname. I'd use working path, but the term sounds too process-specific.If context is needed, it's for a filesystem API where a routine determines if an extra system-call should be made for a resource whose path isn't entirely physical. | Is there a proper term for a physical path accessed through a symbolic link? | symlink;filenames | If you want to be really pedantic, you may say that there is not really such a thing as a physical path. Unix hasAbsolute Pathname: A pathname beginning with a single or more than two <slash> characters.Relative Pathname: A pathname not beginning with a <slash> character.If a pathname contains a symbolic link, it is still a pathname. There is no other terms for it in the POSIX standard.However, the pwd utility has two flags, -P and -L, but with no indication as to what these letters abbreviate:-LIf the PWD environment variable contains an absolute pathname of the current directory and the pathname does not contain any components that are dot or dot-dot, pwd shall write this pathname to standard output, except that if the PWD environment variable is longer than {PATH_MAX} bytes including the terminating null, it is unspecified whether pwd writes this pathname to standard output or behaves as if the -P option had been specified. Otherwise, the -L option shall behave as the -P option.-PThe pathname written to standard output shall not contain any components that refer to files of type symbolic link. If there are multiple pathnames that the pwd utility could write to standard output, one beginning with a single <slash> character and one or more beginning with two <slash> characters, then it shall write the pathname beginning with a single <slash> character. The pathname shall not contain any unnecessary <slash> characters after the leading one or two <slash> characters.Of course, it's possible to infer the meaning of logical and physical to these two flags, and the GNU coreutils version of this utility even has these two words as long options.So the answer is logical path. |
_cs.77520 | I want to build the distance constrained k-Nearest Neighbours Graph, i.e. for every point $p$ in the data cloud $P$ there are at most $k$ undirected edges to points that are closest among all possible vertices using $L_2$ metric with additional constraint that are no further than $d$.There are only insertions (in batches of $10^6$ points) and neighbourhood retrieval queries used. The results have to be exact - I cannot use approximate nearest neighbours or reduce dimensions.The setting is following:There are 50 dimensions, not correlated. The $k=9$ is number of neighbours, $d$ is given distance. The data is sparse in every dimension, mean and median are meaningful, data is random and unstructured in any way (but for sure not from uniform or Gaussian distribution).So far I have tried to build parallel kd-tree with partial rebalancing, the ball trees, m-trees, r-trees, Sparse ktree (octree with more dimensions) partitioning and two-projection hashes. But I am facing problem, that either insertion time is far too long or k-nng queries are too long. I think this happens because the structures are either static or not really prepared to maintain full neighbourhood graph.I have tried linear scan, it performs good for very small data, worse than z-curve localised version or sparse ktree. Up to some $n$ it outperforms any treelike structure. I made one modification to nave algorithm: used one AVL (right threaded) per dimension keeping nodes connected among trees and checked only points within distance $d$ at each dimension - this one performs well, but due to its memory consumption and lack of multidimensional structure scales poorly.What data structure would be the best in practice for dk-NNG?If this is not enough, I would like to optimize the number of neighbours checked, for localised data the number of bins traversed. | What is the best known data structure for online dk-NNG? | data structures;online algorithms;nearest neighbour | null |
_softwareengineering.85472 | Can anybody tell me how I can give my paid app a free download option to one of my friend from iTunes Connect. What I mean is that I will give my friend a code by which he can download my app without paying. Can anyone tell me if there is any option in iTunes Connect to do this? | How do I distribute free copies of a paid iOS app? | iphone | null |
_softwareengineering.328740 | I'm lead on a team with a half-dozen senior engineers. I very much believe it would benefit us greatly to do code reviews for all the standard reasons. Not necessarily every change but at least a steady stream of background reviews. So people at least see other's changes and start talking about them.Is there a good way to introduce reviews? I sense a large reluctance from the team, because it's just one more thing to do, and conversations can get painful. I feel like reviewing every change is a non-starter, at least as a first step. I'd like people get into the rhythm and practice of doing reviews with some low frequency first before amping up the quantity.Has anyone successfully introduced code reviews gradually? How? I've though about requiring reviews on hot files or libraries. Or picking at random. Or me picking choice must-review changes. Or is taking the plunge and doing every change the only way to go? | How to gradually introduce code reviews? | code reviews;team leader | This is not a problem of tooling or process. It's about culture. You describe a team that is comprised of people who are sensitive of criticism and protective of their own work. It's very, very common. But it is not professional.My advice is to start leading by example. Offer your commits for review. Be open about requesting that people highlight the problems in your approach. Be receptive to feedback. Do not be defensive, but instead explore the reasons behind the feedback & agree on actions as a team. Encourage an atmosphere of open dialog. Find a champion or two in your team who are willing to do this also.It's hard work. |
_unix.122272 | Is it possible to start an xfreerdp session into Microsoft windows from a command-line only install of Linux?The command I use from a full blown Linux install is this:$ sudo xfreerdp /v:farm.company.com /d:company.com \ /u:oshiro /p:oshiro_password /g:rds.company.comThis command works fine. However, when I run the same command from a command-line install of Linux, I get the following error message:Warning xf_GetWindowProperty (client /X11/xf_window.c:178): Property 340 does not exist | Logging into an RDS session from the command-line | ubuntu;command line;xorg;remote desktop;freerdp | If you're just logged into a system that doesn't have a X desktop running then no you won't be able to make use of xfreerdp or any such application that requires the use of a GUI. Remember that the X desktop is driving the videocard & monitor locally and is providing a basis (the X protocol) on which other graphical applications can also display GUIs through it as well. Without it any applications such as xfreerdp have no way to access the the display directly.If you're familiar with the DOS/Windows model then think of trying to run a Windows application directly from DOS. This wouldn't be possible here either. There are libraries and services that Windows provides APIs to, which applications then utilize. This is the tradeoff one makes when developing an application for a given environment vs. developing it as a standalone entity that can interact with a given system's hardware directly. |
_unix.202391 | Using the following command, could someone please explain what exactly is the purpose for the ending curly braces ({}) and plus sign (+)?And how would the command operate differently if they were excluded from the command?find . -type d -exec chmod 775 {} + | Understanding find(1)'s -exec option (curly braces & plus sign) | find | The curly braces will be replaced by the results of the find command, and the chmod will be run on each of them. The + makes find attempt to run as few commands as possible (so, chmod 775 file1 file2 file3 as opposed to chmod 755 file1,chmod 755 file2,chmod 755 file3). Without them the command just gives an error. This is all explained in man find: -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invoca tions of the command will be much less than the number of matched files. |
_codereview.133342 | I have Producer Threads A, B and C producing 3 different types of events Events A, B and C respectively. The Consumer thread can only process only one Event B at a time, where as it can process any number of Events A & C at a point of time.Event class:package codility.question;public class Event { private String type; public Event(String repository) { super(); this.type = repository; } @Override public String toString() { return Event [repository= + type + ]; } public String getType() { return type; } public void setType(String type) { this.type = type; }}ProducerConsumer class:package codility.question;import java.util.concurrent.BlockingQueue;import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class ProducerConsumer { private static final String SPECIAL_EVENT_TYPE_B = B; private static int CAPACITY = 10; public static void main(String[] args) { final BlockingQueue<Event> queue = new LinkedBlockingQueue<Event>(CAPACITY); final Lock lock = new ReentrantLock(); Thread eventSchedulerAlpha = new Thread(Event A) { public void run() { try { Event event = new Event(A); queue.put(event); // thread will block here System.out.printf([%s] published event : %s %n, Thread.currentThread().getName(), event.toString()); } catch (InterruptedException e) { e.printStackTrace(); } } }; eventSchedulerAlpha.start(); Thread eventSchedulerBeta = new Thread(Event B) { public void run() { try { Event event = new Event(SPECIAL_EVENT_TYPE_B); queue.put(event); // thread will block here System.out.printf([%s] published event : %s %n, Thread.currentThread().getName(), event.toString()); } catch (InterruptedException e) { e.printStackTrace(); } } }; eventSchedulerBeta.start(); Thread eventSchedulerKappa = new Thread(Event C) { public void run() { try { Event event = new Event(C); queue.put(event); // thread will block here System.out.printf([%s] published event : %s %n, Thread.currentThread().getName(), event.toString()); } catch (InterruptedException e) { e.printStackTrace(); } } }; eventSchedulerKappa.start(); Thread builder = new Thread(Builder) { public void run() { System.out.println(Started the Builder); try { Event processPR = null; while(queue.size()>0) { Event pr = queue.peek(); if(pr!=null && SPECIAL_EVENT_TYPE_B.equals(pr.getType())) { lock.lock(); processPR = queue.take(); processEvents(processPR); lock.unlock(); } else { processPR = queue.take(); processEvents(processPR); } // thread will block here System.out.printf([%s] consumed event : %s %n, Thread.currentThread().getName(), pr.toString()); } } catch (InterruptedException e) { e.printStackTrace(); } } }; builder.start(); } public static void processEvents(Event pr) { System.out.println(The build process BEGINS for + pr.toString()); try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(The build process ENDS for + pr.toString()); }} | Multithreaded Producer-Consumer pattern | java;multithreading;concurrency;producer consumer | null |
_cstheory.170 | The exact phrasing of the title is due to Anand Kulkarni (who proposed this site be created). This question was asked as an example question, but Im insanely curious. I know very little about algebraic geometry, and in fact also only have a cursory, undergraduate understanding of the obstacles at play in the P/poly versus NP question (non-relativizing, non-algebrazing, likely wont be a natural proof).What makes algebraic geometry seem like it can bypass these sorts of obstacles? Is it just field expert intuition or do we have a really good reason to believe the approach is fundamentally more powerful than previous approachs? What weaker results have this approach been able to achieve? | How does the Mulmuley-Sohoni geometric approach to producing lower bounds avoid producing natural proofs (in the Razborov-Rudich sense)? | cc.complexity theory;np hardness;lower bounds;gct;barriers | [I'll answer the question as stated in the title, leaving the litany of other questions about GCT for other threads.] Proving the conjectures arising in GCT seems like it will crucially use the fact that the functions under consideration (determinant and permanent, and other related polynomials for P/poly and NP) are characterized by their symmetries. This necessity is not a formal result, but an intuition expressed by several experts. (Basically that in the absence of characterization by symmetries, understanding the algebraic geometry and representation theory that arises is far harder.)This should bypass Razborov-Rudich because very few functions are characterized by their symmetries (bypassing the largeness condition in the definition of natural proofs). Again, I have not seen a proof of this, but it is an intuition I have heard expressed by several experts.Now, over the complex numbers, it's not clear to me that there's an analog of Razborov-Rudich. Although most of GCT currently focuses on the complex numbers, there are analogs in the finite characteristic (promised in the forthcoming paper GCT VIII). In finite characteristic, one might actually be able to prove a statement of the form Very few functions are characterized by their symmetries.[In response to Ross Snider's comment, here's an explanation of characterization by symmetries.]First, an explanation-by-example. For the example, define an auxiliary function $q$. If $A$ is a permutation matrix, then $q(A)=1$ and if $A$ is diagonal, then $q(A)=det(A)$ (product of the diagonal entries). Now, suppose $p(X)$ is a homogeneous degree $n$ polynomial in $n^2$ variables (that we think of as the entires of an $n \times n$ matrix $X$). If $p$ has the following symmetries:$p(X) = p(X^t)$ (transpose)$p(AXB) = p(X)$ for all pairs of matrices $(A,B)$ such that $A$ and $B$ are each either permutation matrices or diagonal matrices and $q(A)q(B) = 1$then $p(X)$ is a constant multiple of $perm(X)$ for all matrices $X$. Hence we say the permanent is characterized by its symmetries.More generally, if we have a (homogeneous) polynomial $f(x_1, ..., x_m)$ in $m$ variables, then $GL_m$ (the group of all invertible $m \times m$ matrices) acts on $f$ by $(Af)(x_1,...,x_m) = f(A^{-1}(x_1),...,A^{-1}(x_{m}))$ for $A \in GL_m$ (where we are taking the variables $x_1,...,x_m$ as a basis for the $m$-dimensional vector space on which $GL_m$ naturally acts). The stabilizer of $f$ in $GL_m$ is the subgroup $\text{Stab}(f) = \{ A \in GL_m : Af = f\}$. We say $f$ is characterized by its symmetries if the following holds: for any homogeneous polynomial $f'$ in $m$ variables of the same degree as $f$, if $Af' = f'$ for all $A \in \text{Stab}(f)$, then $f'$ is a constant multiple of $f$. |
_softwareengineering.51553 | To start an open-source project is not just to throw up the source code on some public repository and then being happy with that. You should have technical (besides user) documentation, information on how to contribute etc.If creating a checklist over important things to do, what would you include on it? | Checklist for starting an open-source project | open source | The most important thing is:use the project yourself and get it into a useful state where you enjoy using it. be sure the project works and is useful.Things I'd put in the early priorities are:have a simple what is it? web site with links to some discussion forum (whether email or chat) and to the source code repositorybe sure the code compiles and usually works, don't commit work-in-progress or half-ass patches on the main branch that break things, because then other people's work would be disruptedput a license file in the code repository with a well-known license, and mark the copyright owner (probably you, or your company). don't omit the license, make up a license, or use an obscure license.have instructions for how to contribute, say in a HACKING file or include in your README. This should include where to send patches, how to format patches, code indentation rules, any other important conventions of the projecthave instructions on how to report a bugbe helpful on the mailing list or whatever your forums areAfter those priorities I'd say:documentation (this saves you work on the mailing list... make a FAQ from your list posts is a simple start)try to do things in a normal way (don't invent your own build system or use some weird one, don't use 1-space indentation, don't be annoyingly quirky in general because it adds learning curve)promote your project. marketing marketing marketing. You need some blogs and news sites and stuff like that to cover you, and then when people show up interested, you need to talk to them and be sure they get it working and look at their patches. Maybe mention your project in the forums for related projects.always review and accept patches as quickly as humanly possible. Immediately is perfect. More than a couple days and you are losing lots of people.always reply to email about the project as quickly as humanly possible.create a welcoming/positive/fun atmosphere. don't be a jerk. say please and thank you and hand out praise. chase off any jackasses that turn up and start to poison the community. try to meet people in person when you can and form bonds. |
_unix.83496 | What I've tried:root@host [/home1]# cp -f hello /home3cp: omitting directory `hello'root@host [/home1]# cp -rf hello /home3cp: overwrite `/home3/hello/.buildpath'? ycp: overwrite `/home3/hello/.bash_logout'? ycp: overwrite `/home3/hello/.project'? ^CThey always ask me whether I want to overwrite. Using mv doesn't work either. So what should I do?Other things I tried:root@host [/home1]# cp -rf hello /home3cp: overwrite `/home3/hello/.buildpath'? ycp: overwrite `/home3/hello/.bash_logout'? ycp: overwrite `/home3/hello/.project'? ^Croot@host [/home1]# cp -force hello /home3cp: invalid option -- 'o'Try `cp --help' for more information.root@host [/home1]# cp --remove-destination hello /home4cp: omitting directory `hello'root@host [/home1]# cp --remove-destination hello /home3cp: omitting directory `hello'root@host [/home1]# cp --remove-destination -r hello /home3cp: overwrite `/home3/hello/.buildpath'? ^Croot@host [/home1]# | How to copy or move files without being asked to overwrite? | shell;alias;cp | null |
_unix.92971 | I use internet behind http proxy, and that requires authentication. I tried using polipo to bypass the authenticated proxy to 127.0.0.1:9134.Applying these settings to my browser, works fine for http://examplewebsite.combut for https://examplewebsite.com, it asks for authentication. Also my host proxy authentication does not work in the authentication dialog.Settings I have changed in my /etc/polipo/configproxyPort=9134parentProxy = 172.31.1.10:8080parentAuthCredentials = username:mypassword | HTTPS Authentication problem : Polipo | networking;proxy;authentication;http proxy;htaccess | null |
_codereview.29403 | I have a manager class (included below) and sub data types that are included inside it. All of the different stored types are more or less the same with some wrapper functions calling the exact same named function below to the sub object. This feels dirty and I can't help but think there's a better way to do this. Suggestions?using System;using System.Collections.Generic;using System.Linq;using Inspire.Shared.Models.Enums;using Lidgren.Network;namespace GameServer.Editor.ContentLocking{ /// <summary> /// The content lock manager helps provide delegation /// </summary> public class ContentLockManager { // This is a mapping of all the different content lock stores available Dictionary<ContentType, ContentLockStore> _contentLockStores = new Dictionary<ContentType, ContentLockStore>(); public ContentLockManager() { // Generate the ContentMap dynamically, assinging everyone a backing foreach (var contentType in GetValues<ContentType>()) _contentLockStores.Add(contentType, new ContentLockStore()); } /// <summary> /// Invalidates and purges all locks for a given connection. /// This is typically called when a connection has disconnected from the node. /// </summary> /// <param name=connection></param> public void PurgeLocks(NetConnection connection) { foreach (var contentLockStore in _contentLockStores.Values) { contentLockStore.ReleaseLocks(connection); } } public List<int> GetLockedContent(ContentType contentType) { var contentStore = _contentLockStores[contentType]; return contentStore.GetLockedContentIDs(); } public bool HasLock(NetConnection connection, int ID, ContentType contentType) { var contentStore = _contentLockStores[contentType]; return contentStore.HasLock(connection, ID); } public bool AnyoneHasLock(NetConnection connection, int ID, ContentType contentType) { var contentStore = _contentLockStores[contentType]; return contentStore.AnyoneHasLock(connection, ID); } public bool TryAcquireLock(NetConnection connection, int ID, ContentType contentType) { var contentStore = _contentLockStores[contentType]; return contentStore.TryAcquireLock(connection, ID); } public bool TryReleaseLock(NetConnection connection, int ID, ContentType contentType) { var contentStore = _contentLockStores[contentType]; return contentStore.ReleaseLock(connection, ID); } private static IEnumerable<T> GetValues<T>() { return Enum.GetValues(typeof(T)).Cast<T>(); } }}And then I have a mapping inside like so:using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using Lidgren.Network;namespace GameServer.Editor.ContentLocking{ /// <summary> /// A collection of keys internally of content that has been locked /// </summary> public class ContentLockStore { // Current locks on a particular piece of content private Dictionary<int, NetConnection> _contentLocks = new Dictionary<int, NetConnection>(); public bool TryAcquireLock(NetConnection connection, int ID) { // Trying to aqquire a lock for something you already have or you're not authorized to obtain if (_contentLocks.ContainsKey(ID)) return false; // Noone has taken it - go ahead and grab this _contentLocks.Add(ID, connection); return true; } /// <summary> /// Release sall locks with an associated contention /// </summary> /// <param name=connection></param> public void ReleaseLocks(NetConnection connection) { var keys = _contentLocks.Where(cLock => cLock.Value == connection).ToList(); keys.ForEach(x => ReleaseLock(x.Value, x.Key)); } public bool ReleaseLock(NetConnection connection, int ID) { // If they don't have a lock, they can't release it if (!HasLock(connection, ID)) return false; // Release the lock _contentLocks.Remove(ID); return true; } /// <summary> /// Returns a list of all the locked content IDs for a particular store /// </summary> /// <returns></returns> public List<int> GetLockedContentIDs() { return _contentLocks.Keys.ToList(); } /// <summary> /// Determines whether a particular connection has a lock on a piece of content /// </summary> /// <param name=connection></param> /// <param name=ID></param> /// <returns></returns> public bool HasLock(NetConnection connection, int ID) { // If the key dosen't even exist, don't bother if (!_contentLocks.ContainsKey(ID)) return false; return _contentLocks[ID] == connection; } public bool AnyoneHasLock(NetConnection connection, int ID) { return _contentLocks.ContainsKey(ID); } }} | How can I avoid seemingly unneccessary wrappers like this? | c# | null |
_unix.114210 | For people from the US with certain cable TV subscriptions, NBC offers footage of the 2014 winter Olympics from a website, nbcolympics.com. However, I find I am unable to view any of the video content from my Linux machine. I have tried from Chrome and Firefox.Chrome:When clicking on a video, I am taken to the webpage of the video and all of the non-video content (e.g. the twitter stream, the summary of the video) loads. However, the page is covered in a dark transparent overlay and a waiting spinner continuously spins. I cannot click on anything from the web page.Firefox:When clicking on a video, I am taken to the webpage of the video and all of the non-video content loads. The page is also covered with a dark, transparent overlay, but this time with a window in the middle to choose my cable provider. When I select my cable provider, xfinity, the page re-loads and the same screen appears again, with the same transparent overlay and the same dialog asking for my cable provider.Here is a screenshot of the Firefox window: I am using Fedora 19 and do not generally have problems viewing other flash content.Is there any method to watching the videos on nbcolympics.com from a Linux computer? | How do I watch protected flash videos (such as on nbcolympics.com) using Linux? | video;firefox;chrome;adobe flash | For Fedora, try this.DISCLAIMER: This is mostly copy-pasted from here.I'm not really sure if this will work (I don't use Fedora), but it will help you install HAL, and maybe it will. After all, NBC would seem an appropriate place for DRM-laden Flash content to show up. Anyway, here goes:First, head to http://get.adobe.com/flashplayer/ and download the YUM for Linux (YUM) RPM. Then:# Install Adobe Flash and its browser pluginsudo yum install -y adobe-release-x86_64-1.0-1.noarch.rpmsudo yum install -y flash-plugin# Install a simple SELinux policy file for Flashsudo yum install -y policycoreutils-develwget http://togami.com/~warren/archive/2012/adobedrm.techeckmodule -M -m -o adobedrm.mod adobedrm.tesudo semodule_package -o adobedrm.pp -m adobedrm.modwget http://thinkingconcurrently.com/files/f19_flash/fakehal-0.5.14-7.fc19.x86_64.rpmwget http://thinkingconcurrently.com/files/f19_flash/fakehal-libs-0.5.14-7.fc19.x86_64.rpm# Install the fakehal RPMssudo yum install -y fakehal-0.5.14-7.fc19.x86_64.rpm \ fakehal-libs-0.5.14-7.fc19.x86_64.rpmAt this point, make sure all Firefox windows are closed.cd ~/.adobe/Flash_Playerrm -rf NativeCache AssetCache APSPrivateData2Note: I inserted the above 2 lines based on what unqualified said.rm -rf ~/.adobe/Flash_Player/sudo mkdir -p /usr/share/hal/fdi/preprobe \ /usr/share/hal/fdi/information \ /usr/share/hal/fdi/policy/20thirdparty \ /var/cache/hald/sudo ln -s /usr/share/hal /etc/halsudo touch /var/cache/hald/fdi-cachesudo systemctl start haldaemon.serviceThe bit I'm unsure about is the line where it deletes the FlashPlayer dir. I would wait for someone to comment and confirm this or reject it before trying it.I'd repeat, try this at your own risk. I'm not at all sure that this will work or even help.Anyway, hope you can watch!evamvid |
_codereview.42862 | After reading a lot of documents, I wrote this object pooling code. Can anyone help me to improve this code? I am lagging in validating the object, confirming whether I can reuse it or not./* * To change this template, choose Tools | Templates * and open the template in the editor. */package iaccount.ui;import java.util.Enumeration;import java.util.Hashtable;/** * * @author system016 */public class ObjectPool<T> { private long expirationTime; private Hashtable locked, unlocked; ObjectPool() { expirationTime = 30000; // 30 seconds locked = new Hashtable(); unlocked = new Hashtable(); }// abstract public Object create(Class<T> clazz) throws InstantiationException, IllegalAccessException { Object obj = clazz.newInstance(); unlocked.put(clazz.newInstance(), expirationTime); return obj; } ;// abstract boolean validate( Object o );// abstract void expire( Object o ); synchronized Object checkOut(Class<T> clazz) { long now = System.currentTimeMillis(); Object o = null; if (unlocked.size() > 0) { Enumeration e = unlocked.keys(); while (e.hasMoreElements()) { o = e.nextElement(); if ((clazz.isAssignableFrom(o.getClass()))) {// } if ((now - ((Long) unlocked.get(o)).longValue()) > expirationTime) { // object has expired unlocked.remove(o);// expire(o); o = null; } else {// if (validate(o)) { unlocked.remove(o); locked.put(o, new Long(now)); return (o);// } else {// // object failed validation// unlocked.remove(o);//// expire(o);// o = null;// } } } } } return o; }// public boolean validate(Object o){return true;};}// synchronized void checkIn( Object o ){...} | Reusing objects using a generic object pool | java;beginner;synchronization | null |
_unix.10378 | Heres the closest I've gotten: I installed gitolite in the /Private folder using ecryptfs-utils (sudo apt-get install ecryptfs-utils adduser git ecryptfs-setup-private then the rest was configuring gitolite using a root install).It worked just fine as long as someone was logged in as the user git using a password (su git using root does not work). Since the private folder activates through logging in with a password and gitolite uses RSA keys (required) the private folder is hidden thus error occurs.Is there a way I can log into my server after a reboot, type in the password and have the git user private folder available until next time the machine restarts?Or maybe theres an easy way to encrypt a folder for git repositories? | How do I encrypt git on my server? | security;git | You simply need to remove the file ~/.ecryptfs/auto-umount.This file is a flag that pam_ecryptfs checks on logout. This file exists by default at setup, along with ~/.ecryptfs/auto-mount, such that your private directory is automatically mounted and unmounted at login/logout. But each can be removed independently to change that behavior. Enjoy! |
_unix.362441 | Preface: Every couple of days there comes a question of this type, which is easy to solve with sed, but takes time to explain. I'm writing this question and answer, so I can later refer to this generic solution and only explain the adaption for the specific case. Feel free to contribute.I have files with variable definitions. Variables consist of uppercase letters or underscore _ and their values follow after the :=. The values can contain other variables. This is Gnom.def:NAME:=GnomFULL_NAME:=$FIRST_NAME $NAMEFIRST_NAME:=SmanSTREET:=Mainstreet 42TOWN:=NowhereBIRTHDAY:=May 1st, 1999Then there is another file form.txt with a template form:$NAMEFull name: $FULL_NAMEAddress: $STREET in $TOWNBirthday: $BIRTHDAYDon't be confused by $NAMESNow I want a script which replaces the variables (marked with $ and the identifier) in the form by the definitions in the other file, recursively, if necessary, so I get this text back:GnomFull name: Sman GnomAddress: Mainstreet 42 in NowhereBirthday: May 1st, 1999Don't be confused by $NAMESThe last line is to ensure that no substrings of variables get replaced accidentally. | How to perform replacements defined in one file on another file | text processing;sed | The basic idea to solve problems like this is to pass both files to sed. First the definitions, which are stored in the hold space of sed. Then each line of the other file gets the hold space appended and each occurrence of a variable which can be found repeated in the appended definitions gets replaced.Here is the script:sed '/^[A-Z_]*:=.*/{H;d;} G :b s/$\([A-Z_]*\)\([^A-Z_].*\n\)\1:=\([^[:cntrl:]]*\)/\3\2\1:=\3/ tb P d' Gnom.def form.txtAnd now the detailed explanation:/^[A-Z_]*:=.*/{H;d;}This collects the definitions to the hold space. /^[A-Z_]*:=.*/ selects all lines starting with a variable name and the sequence :=. On these lines the commands in {} are performed: The H appends them to the hold space, the d deletes them and starts over, so they won't get printed.If you can't assure that all lines in the definition file follow this pattern, or if lines in the other file could match the given pattern, this part needs to be adapted, like explained later.GAt this point of the script, only lines from the second file are processed. The G appends the hold space to pattern space, so we have the line to be processed with all definitions in the pattern space, separated by newlines.:bThis starts a loop. s/$\([A-Z_]*\)\([^A-Z_].*\n\)\1:=\([^[:cntrl:]]*\)/\3\2\1:=\3/This is the key part, the replacement. Right now we have something likeAt the $FOO<newline><newline>FOO:=bar<newline>BAR:=baz ----==================--- ###in the pattern space. (Detail: there are two newlines before the first definition, one produced by appending to the hold space, another by appending to the buffer space.)The part underlined with ---- matches $\([A-Z_]*\). The \(\) makes it possible to backreference to that string later on.\([^A-Z_].*\n\) matches the part underlined with ===, which is everything up to the backreference \1. Starting with a not-variable character ensures we don't match substrings of a variable. Surrounding the backreference with a newline and := makes sure that a substring of a definition will not match.Finally, \([^[:cntrl:]]*\) matches the ### part, which is the definition. Note, that we assume the definition has no control characters. If this should be possible, you can use [^\n] with GNU sed or do a workaround for POSIX sed.Now the $ and the variable name get replaced by the variable value \3, the middle part \2 if left as it was and the definition line is reconstructed as \1:=\3. tbIf a replacement has been made, the t command loops to mark b and tries another replacement. PIf no further replacements were possible, the uppercase P prints everything unto the first newline (thus, the definition section will not get printed and dwill delete the pattern space and start the next cycle. Done.LimitationsYou can do a nasty thing like including FOO:=$BAR and BAR:=$FOO in the definition file and make the script loop forever. You can define a processing order to avoid this, but is will make the script more difficult to understand. Leave this away, if your script doesn't need to be idiot proof.If the definition can contain control characters, after the G, we can exchange newline with another character like y/\n#/#\n and repeat this before printing. I don't know a better workaround.If the definition file can contain lines with different format or the other file can contain lines with definition format, we need a unique separator between both files, either as last line of the definition file or as first line of the other file or as separate file you pass to sed between the other files. Then you have one loop to collect the definitions until the separator line is met, then do a loop for the lines of the other file. |
_unix.71964 | When I tried to sudo su instead of sudo su - after having been logged in as root and su-ing to another user, it tries to sudo me as the new user, but via root... When I type env, it shows still username=root in the environment. Is sudo not looking at the currently logged in user, but at the enviroment parameters? [oracle@tst-01]$ sudo su gridSorry, user oracle is not allowed to execute '/bin/su grid' as root on tst-01.testdomain.com.[oracle@tst-01]$ envHOSTNAME=tst-01.testdomain.comTERM=xtermSHELL=/bin/bashHISTSIZE=1000QTDIR=/usr/lib64/qt-3.3USER=oracleSUDO_USER=ujjainUSERNAME=rootMAIL=/var/spool/mail/ujjainPATH=/usr/lib/oracle/10.2.0.4/client64/bin:/usr/lib/oracle/10.2.0.4/client64/bin:/sbin:/bin:/usr/sbin:/usr/binPWD=/home/ujjainLANG=en_US.utf8HOME=/opt/apps/oracleSUDO_COMMAND=/bin/suSHLVL=2LOGNAME=oracleCVS_RSH=sshLESSOPEN=|/usr/bin/lesspipe.sh %sSUDO_GID=3000ORACLE_HOME=/usr/lib/oracle/10.2.0.4/client64G_BROKEN_FILENAMES=1_=/bin/env[oracle@tst-01 ujjain]$ sudo su - grid[grid@tst-01 ~]$ It seems that sudo su newuser should also work if sudo would only be looking if the currently logged in user has sudo rights to sudo to the new user. What is sudo su doing and why is it important for non-root users to use sudo su - newuser with the hyphen? | Where does sudo get the currently logged in username from? | sudo;su | In su - username, the hyphen means that the user's environment is replicated, i.e. the default shell and working directory are read from /etc/passwd, and any login config files for the user (e.g. ~/.profile) are sourced. In short, you pretty much get the same environment as if you logged in normally. (Though the new user may not own the terminal, causing programs like screen to fail.) Not using the hyphen, will cause you to more or less keep the environment of the user that invoked su, including leaving you in the same working directory, where you may not have permissions. su won't ask for a password if the root user invoked it, so if you first have used sudo (or su) to become root, you won't need a password to become any other user. |
_unix.105734 | I have an Epson Perfection 660 flatbed scanner that works on my laptop. This is what appears in /var/log/syslog when I plug it in:Dec 18 15:43:57 lap kernel: [ 31.868278] usb 6-2: new full-speed USB device number 2 using uhci_hcdDec 18 15:43:57 lap kernel: [ 32.033506] usb 6-2: New USB device found, idVendor=04b8, idProduct=0114Dec 18 15:43:57 lap kernel: [ 32.033514] usb 6-2: New USB device strings: Mfr=1, Product=2, SerialNumber=0Dec 18 15:43:57 lap kernel: [ 32.033519] usb 6-2: Product: EPSON ScannerDec 18 15:43:57 lap kernel: [ 32.033524] usb 6-2: Manufacturer: EPSONNow I want to use that scanner in my desktop computer. I followed the same instructions, but it does not work. The problem is that it's not recognized as a valid USB device. It does not appear on lsusb, and this is what shows in syslog:Dec 18 15:31:34 desktop kernel: [ 390.193219] usb 3-14: new full-speed USB device number 18 using xhci_hcdDec 18 15:31:39 desktop kernel: [ 395.213900] usb 3-14: unable to read config index 0 descriptor/start: -110Dec 18 15:31:39 desktop kernel: [ 395.213902] usb 3-14: can't read configurations, error -110Dec 18 15:31:39 desktop kernel: [ 395.325902] usb 3-14: new full-speed USB device number 19 using xhci_hcdDec 18 15:31:44 desktop kernel: [ 400.346570] usb 3-14: unable to read config index 0 descriptor/start: -110Dec 18 15:31:44 desktop kernel: [ 400.346572] usb 3-14: can't read configurations, error -110Dec 18 15:31:45 desktop kernel: [ 400.458648] usb 3-14: new full-speed USB device number 20 using xhci_hcdDec 18 15:31:50 desktop kernel: [ 405.479280] usb 3-14: unable to read config index 0 descriptor/start: -110Dec 18 15:31:50 desktop kernel: [ 405.479282] usb 3-14: can't read configurations, error -110Dec 18 15:31:50 desktop kernel: [ 405.591352] usb 3-14: new full-speed USB device number 21 using xhci_hcdDec 18 15:31:55 desktop kernel: [ 410.611960] usb 3-14: unable to read config index 0 descriptor/start: -110Dec 18 15:31:55 desktop kernel: [ 410.611962] usb 3-14: can't read configurations, error -110Dec 18 15:31:55 desktop kernel: [ 410.611973] hub 3-0:1.0: unable to enumerate USB device on port 14At first sight, looks like the laptop uses UHCI, whereas the desktop uses XHCI. Both systems use Linux Mint 16, kernel 3.11.0-12 x86_64. The behavior is the same regardless of the usb port used. What can I do? | Scanner works in laptop, not in desktop | linux mint;usb;scanner | null |
_unix.153551 | I just installed CentOS 7 on a vServer to play around with.Usually I use Debian.Since I had good results, I want to use zswap. I enabled it by putting zswap.enabled=1 zswap.compressor=lz4 in the GRUB_CMDLINE_LINUX in /etc/default/grubBut it falls back to using lzo, because the CentOS 7 Kernel doesn't have the lz4 module, it seems.Is there any way to add this module without recompiling the whole Kernel? How would this work? Great would be some way to automate it on kernel updates, but that's not that important. (I only install updates manually and without the lz4 and lz4_compress modules nothing breaks, zswap just falls back to lzo)I want to stay as close as possible to using the package manager. A yum upgradeshould still patch all fixed bugs. | lz4 Kernel Module in CentOS without recompiling | centos;kernel modules | null |
_unix.32240 | The default GCC package available in the Fedora 16 repositories is gcc-4.6. I need to install gcc-4.5 on my system.I downloaded the packages from the kijo repository, but when I try to install them it shows that a newer libstdc++4.6 is installed. If I try to uninstall libstdc++4.6 it tries to uninstall the system itself! (Almost every package in the system). And it would not allow me install libstdc++4.5 along with libstdc++4.6.Is there a easy way that I can install gcc-4.5 on my system? | Installing GCC 4.5 on Fedora 16 | fedora;software installation;gcc | Getting the build errors worked out is preferable, so I hope that works out for you.But it is possible to install alternate versions of gcc on Fedora. Just not from packages -- you'll need the source, available from http://gcc.gnu.org/. Look to download gcc-4.5.3.tar.gz from one of the download mirrors.The following is modeled after some info by Zhongliang Chen on installing gcc-4.3 on Fedora 15.Download and unpack the gcc source tarball. Make sure your Fedora 16 has the packages necessary for building:yum install gcc mpfr-devel libmpc libmpc-devel glibc-develThen create a new, empty build directory and build gcc with a suffix of 45 -- you'll build compilers gcc45 and g++45 for example. You might want a new, separate install directory like /usr/local/gcc45/$cd PATH_TO_BUILD_DIR$PATH_TO_SOURCE_DIR/configure --prefix=PATH_TO_INSTALL_DIR --program-suffix=45 --enable-languages=c,c++$make$sudo make install |
_codereview.4729 | I have classes representing gates (OR, XOR, AND etc) with the following method that is called whenever a property changes.Here is the XORGate code:public void computeOutput() { if (this.input1 != null && this.input0 != null) { if (this.input0.getValue() || this.input1.getValue()) { if (this.input0.getValue() && this.input1.getValue()) { this.output.setValue(false); } else { this.output.setValue(true); } } else { this.output.setValue(false); } } else { this.output.Value = false; } }It's horrible, but I can't think of a nicer way. It works as follows:If any of the inputs are null, treat the output as false. If any of the inputs are true BUT not all of the outputs are true (i.e just one is true), set the output to true. If BOTH input terminals are true, output is false. And finally, if none of the input is true, output is false.Very basic stuff. | Ternary gate handling - more succinct way then a bunch of if statements | java | public void computeOutput() { output.setValue( (input1 == null || input0 == null) ? false : (input0.getValue() ^ input1.getValue()));} |
_opensource.4254 | Maybe I start with an example: I use currently SystemJS for Angular2 Applications, it is a great tool, works properly and free.As I see the contributors here and the work, what already has been done, I've thought: What kind of great job, but who pays for all this work? Sometimes I also try to help, but I've limited time and have to pay my everlasting bills.How can such of libraries can come into existence? The idea (which is already great) alone is not enough. Karma would not also be the real reason, I think.Why do these talented programmers invest amount of time of creating free libraries? What research has been done into why so many programmers invest their time in FLOSS projects? | What research explains why so many programmers invest time in creating free libraries? | community | Of course there is no single answer to this question. The motivation can change over time and over individuals but I will try to list a few common reasons.For ideological reasonsPeople who invented free software (RMS et al.) did it originally for very ideological reasons (all software should be free - that is, respect four fundamental freedoms) and this was motivation enough to start the GNU project. For reference, see this 1989 NYT's article and the original GNU manifesto.Because it's a free-time activityLots of people like to program so much that they do it even during their free time. When absolutely no financial benefit is to be expected from a software (either because you don't think it is worth much or because you don't want to spend time selling it), it can be seen as natural to share it as free software (it will help others and could even contribute to your own reputation).Because it's a jobMany companies profit directly or indirectly from free and open source software (RedHat but also Google, Facebook and Microsoft) and consequently pay people to contribute to it. The most famous person to be paid for writing free software full-time is probably Linus Torvalds but there are lots of examples of people whose job is to develop proprietary software part of the time and to contribute to open source part of the time.Github's founder and former CEO Tom Preston-Warner has a very good entry on his blog on why it pays for a company to have its employees contribute to open source software.If you want to dive more into motivation issues, here is an academic article talking about that. |
_webapps.6262 | The Gmail sidebar displays the list of our labels (or some of them, according to settings). Next to every label name there is a number showing how many unread messages we have for that label.Is there a way to display also the total number of messages for each label?Example:[to answer] (0/36)[to do] (0/55)[waiting answer] (0/7)cooking (2/48)family (6/352)friends (1/1828)website (2/412)work (12/12801) | Is there a way to display the number of messages for any label in the Gmail label list? | gmail;gmail labels | There doesn't seem to be a way to do this currently.The best places to look for this feature to be implemented is one of the following:An official Gmail setting accessible via the settings page.A Gmail labs feature.A 3rd party Gmail gadget which can be added via the Add any gadget by URL Gmail lab.A Greasemonkey scirpt.The first two would require Google to implement the feature, which you could suggest here for it to be implemented in the official version, or you could suggest it here for it to be implemented as a lab. The last two could be implemented by anyone with the knowhow.I couldn't find anything that is already implemented by doing a simple Google search. |
_unix.21338 | After reading this question, I was a little confused; it sounds like some daemon reacting by rebooting a system. Is that right? Is it a common occurrence in embedded *nixes? | What is a watchdog reset? | kernel;embedded;watchdog | Having a watchdog on an embedded system will dramatically improve the availability of the device. Instead of waiting for the user to see that the device is frozen or broken, it will reset if the software fails to update at some interval. Some examples:Linux System http://linux.die.net/man/8/watchdogVxWorks (RTOS) http://fixunix.com/vxworks/48664-about-vxworks-watchdog.htmlQNX Watchdog http://www.qnx.com/solutions/industries/netcom/ha.htmlThe device is designed in such a way that its state is saved somewhere periodically(like Juniper routers that run FreeBSD, Android phones, and dvrs that run linux). So even if it is rebooted it should re-enter a working configuration. |
_unix.186524 | What does top command in linux stand for ? Is it an abbreviation of something. If so what?I've tried to look around on wikipedia and its home page but there is not information about this. | What does top command in linux stand for? | top | null |
_scicomp.7722 | I have a Matrix<double> on a single core, the result of doing an MPI_Reduce. I want to do the Cholesky, so I need to distribute over multiple cores. What's the easiest/most standard way of doing this in Elemental? Do I need to MPI_Bcast it out to all nodes first, and then move it into a DistMatrix, or is there some way of doing something like:Matrix<double> A = doSomeStuff();DistMatrix<double, single-node> AdistSingle( A );DistMatrix<double> Adist(AdistSingle );or perhaps:Matrix<double> A = doSomeStuff();DistMatrix<double> Adist(A ); | How to convert a Matrix to a DistMatrix in Elemental? | linear algebra;parallel computing;grid | DistMatrix<T,CIRC,CIRC> was recently created for exactly this situation and stores a fully copy of the matrix on a single process. If you have an $n \times n$ Matrix<double> stored on the root process, you can distribute it as follows:// Construct an n x n matrix owned by process 0DistMatrix<double,CIRC,CIRC> ARoot( n, n );// Have the root process fill the local matrix of ARootif( commRank == 0 ) ARoot.Matrix() = A;// Redistribute ARoot into the standard matrix distribution// (via a scatter)DistMatrix<double> ADist( ARoot );Note that the DistMatrix<T,CIRC,CIRC> class is very new and that the syntax might be simplified in the near future. |
_webmaster.35717 | Hi I have a site and my site map is being indexed by google correctly (almost I have 1.165 links and it indexed 1.156).But when I go to the Indexed pages view in Google webmaster tools it only show 60 indexed pages and also I am not getting a lot of keywords because of that.How can I improve that ?My site is a single page Ajax filled app and I create a sitemap so google can find my content. | My sitemap is indexed but I don't see the site pages being indexed | seo;google;google search console | Get more links to your pages particularly the ones that aren't indexed yet. Google does not automatically index every page it knows about and that includes URLs submitted via sitemap. Sitemaps are meant to inform the search engines of the existence of pages but in no way guarantees inclusion in a search engine's index. |
_unix.386485 | I need to connect additional monitors on my computer and I get Fresco Logic FL2000DX USB display adapters. This adapters works perfect on Windows but I need to use on my development machine based on Ubuntu 16.04.I find this on git hub: https://github.com/fresco-fl2000/fl2000 and try to install it but installation fail. Can anyone help me regarding this?Thanks! | How to properly install USB display driver for Fresco Logic FL2000DX on Ubuntu? | ubuntu;drivers;display settings;proprietary drivers | null |
_unix.226889 | I am installing CentOS 7 in a 200GB partition of a 2TB hard drive whose other partitions will later become managed by this master CentOS 7 installation. How big should the boot mount installation be? In my CentOS 7 devbox, navigating to the /boot directory and typing du results in about 195MB. So is 230MB big enough for the boot mount point capacity? What factors should I consider in planning the size of the /boot mount point capacity? | how big should the /boot directory be in a CentOS 7 server? | centos;mount;boot | null |
_softwareengineering.206205 | I have a set of classes from a 3rd party library. These classes use an inheritance structure to share logic. I would like to add a layer of abstraction in the middle of their inheritance tree to add functionality to all of the children (concrete) implementations.Here is a simplified example of the classes in the 3rd party lib:public interface IAnimal{ bool IsMammal { get; }}public abstract class Animal : IAnimal{ public abstract bool IsMammal { get; } public string Name { get; set; }}public class Cat : Animal{ public override bool IsMammal { get { return true; } } public void Pur() {}}public class Dog : Animal{ public override bool IsMammal { get { return true; } } public void Fetch() {}}public class Snake : Animal{ public override bool IsMammal { get { return false; } } public void ShedSkin() {}}I would like to add the concept of an AnimalWithSuperPower. These types of animals should have 1 additional Property; SuperPower. I would like to be able to have classes like CatWithSuperPower which derive from Cat, AnimalWithSuperPower, & Animal so that I can access all the functionality of those.Here is the definition of SuperPower:public enum SuperPower { Invisibility, SuperStrength, XRayVision }My first idea was to use multiple inheritance. But unfortunately, C# doesn't support multiple base classes.private abstract class AnimalWithSuperPower : Animal{ public SuperPower SuperPower { get; set; }}// doesn't compile because you can't extend 2 classesprivate class DogWithSuperPower : AnimalWithSuperPower, Dog {}My next attempt uses a combination of inheritance, composition, and generics to try to deliver the functionality of the base classes.private abstract class AnimalWithSuperPower<TAnimalType> : Animal where TAnimalType : IAnimal{ public SuperPower SuperPower { get; set; } protected readonly TAnimalType Animal; protected AnimalWithSuperPower() { Animal = (TAnimalType) Activator.CreateInstance(typeof(TAnimalType)); }}private class SuperCat : AnimalWithSuperPower<Cat>{ public override bool IsMammal { get { return Animal.IsMammal; } }}private class SuperCatWithPur : AnimalWithSuperPower<Cat>{ public override bool IsMammal { get { return Animal.IsMammal; } } public void Pur() // needing duplicate pass-through methods/properties like this is painful :( { Animal.Pur(); }}private static void ExampleUsage(){ var invisibleCat = new SuperCat { SuperPower = SuperPower.Invisibility }; invisibleCat.Pur(); // doesn't compile - can't access Pur() method because doesn't extend Cat var xrayCat = new SuperCatWithPur { SuperPower = SuperPower.XRayVision }; xrayCat.Pur(); // only works because I exposed the method with the EXACT same signature}This solution is not very good (IMO) because of these reasons:SuperCat and SuperCatWithPur aren't actually instances of Catany method you wish to use from Cat needs to be mirrored in the container classfeels kind of messy: AnimalWithSuperPower is an Animal but it also takes an Animal type parameterI also tried doing it with an extension method but it wasn't any better than the above two attempts:private abstract class AnimalWithSuperPower : Animal{ public SuperPower SuperPower { get; set; }}private static AnimalWithSuperPower WithSuperPower(this Animal animal, SuperPower superPower){ var superAnimal = (AnimalWithSuperPower) animal; superAnimal.SuperPower = superPower; return superAnimal;}private static void ExampleUsage(){ var dog = new Dog { Name = Max }; var superDog = dog.WithSuperPower(SuperPower.SuperStrength); superDog.Fetch(); // doesn't compile - superDog isn't an instance of Dog}If I had control of the 3rd party classes, I could likely do this cleanly by introducing a new class in the middle of the inheritance tree, but I can'tMy Question:How can I model AnimalWithSuperPower so that:instances are considered of types Cat (or appropriate sub-class), Animal, & AnimalWithSuperPowerall the methods and properties are available without extra pass-through calls | Adding base-class (inherited) functionality to classes that you don't control | c#;inheritance;modeling;generics;multiple inheritance | Why don't you just use interfaces?If you're concerned about sharing functionality, you can use extension methods to serve as your pseudo-base class. It's not exactly ideal, but it should get what you're looking for done.Something along the lines of:public interface IAnimalWithSuperPower { public SuperPower power { get; set; }}public class SuperCat : Cat, IAnimalWithSuperPower { public SuperPower power { get; set; } public SuperCat() { SuperPower = SuperPower.SuperStrength; }}public static void UseSuperPower(this IAnimalWithSuperPower animal) { animal.power.doSomething();} |
_codereview.108231 | The proper title of this question should be Summations and products, and factorials oh my!.After getting quite a bit of useful feedback on this question from @mjolka, and a comment, I decided that there were many things to be improved.These are the following things that I've added/changed:A factorial function which uses the product function.Support for getting the sum, and product of sequences with no elements.Strongly typed anonymous function parameters.Again, for those who don't know, a summation is defined as follows:$$\sum_{n=a}^{b}f(n)$$And a product is defined as follows:$$\prod_{n=a}^{b}f(n)$$I'd like to know the following things, which are more or less mostly the same as the ones in the last question:Am I writing this in a proper functional way?How can I reduce the repetitiveness in my code?Is there a way to improve performance? It already runs pretty fast, at approximately \$0.025\$ seconds for inputs of \$10\$).Anything else?Here's the code:let inline summation (f: (double -> double)) low high = match (low, high) with | (low, high) when low <> high -> { low .. high } |> Seq.map f |> Seq.sum | (low, high) when low = high -> 0.0 | _ -> -1.0let inline product (f: (double -> double)) low high = match (low, high) with | (low, high) when low <> high -> { low .. high } |> Seq.map f |> Seq.fold Checked.op_Multiply 1.0 | (low, high) when low = high -> 1.0 | _ -> -1.0let inline factorial n = product (fun x -> x) 1.0 nHere's a few small tests to ensure that the code works:[<EntryPoint>]let main argv = System.Console.WriteLine(summation (fun x -> x) 1.0 10.0) System.Console.WriteLine(product (fun x -> x) 1.0 10.0) System.Console.WriteLine(factorial 10.0) 0And here's expected output of the above tests:5536288003628800 | Summations and products and factorials oh my | functional programming;mathematics;f# | There are a few problems with this code.If low = high then product f low high should be equal to f low. In this code, it is equal to 1.Similarly, if low = high then summation f low high should be equal to f low. In this code, it is equal to 0.The code posted in my previous answer already correctly deals with empty sequences:> let inline summation f low high = Seq.map f { low .. high } |> Seq.sum ;;val inline summation : f:( ^a -> ^b) -> low: ^a -> high: ^a -> ^b when ^a : (static member get_One : -> ^a) and ^a : (static member ( + ) : ^a * ^a -> ^a) and ^a : comparison and ^b : (static member ( + ) : ^b * ^b -> ^b) and ^b : (static member get_Zero : -> ^b)> summation id 0 -10 ;;val it : int = 0> let inline product f low high = Seq.map f { low .. high } |> Seq.fold Checked.(*) LanguagePrimitives.GenericOne< _ > ;;val inline product : f:( ^a -> ^b) -> low: ^a -> high: ^a -> ^c when ^a : (static member get_One : -> ^a) and ^a : (static member ( + ) : ^a * ^a -> ^a) and ^a : comparison and ( ^c or ^b) : (static member ( * ) : ^c * ^b -> ^c) and ^c : (static member get_One : -> ^c)> product id 0 -10 ;;val it : int = 1The third case of each function definition seems to be there just to get rid of the warning about incomplete pattern matches.Since the second case of the match is incorrect, and the third case should never run, we can do away with the pattern matching.There is no need to constrain the type of f. Doing so removes the benefits of declaring the functions inline.Whenever you find yourself writing (fun x -> x) you can just replace it with id. |
_webmaster.85101 | We have two websites whose content align with each other:Site #1 - Industry editorial website that provides high quality, original and current content. This site is mature and has high authority relatively speaking. Site #2 - Industry resource website that educates general public and insiders about the industry. Content is professionally written with fantastic art and basically breaks down different manufacturing processes/materials and walks people through the benefits.Would it be a sound approach to add anchor text/link within articles on site #1 to site #2? Below are a few scenarios:1) Article on site #1 is about using [manufacturing process] to make something and site #2 has a page that describes [manufacturing process] in great detail.2) Article on site #1 is about using [material] and site #2 has a page that describes [material] in great detail.3) Article on site #1 is about why it's beneficial to use a particular [material] or [manufacturing process] and site #2 has a page that describes all benefits of [material] or [manufacturing process] in great detail.Obviously, these links will only be sprinkled in here and there and not in every article. It should provide users with more insight but will search engines see it that way? | Using your other web properties for link building | seo;google;backlinks | null |
_webapps.4002 | Say I have a car dealership with a website.Is there any legal or YouTube usage issues in creating a YouTube profile and uploading videos of cars for sale, and putting car, dealership and website info/links in the video descriptions?And does the same thing apply to Facebook and Vimeo? | Using YouTube to sell cars | youtube | It is completely fine to upload videos to YouTube for commercial purposes, with links to your site, etc.From the YouTube TOS:http://www.youtube.com/t/termsProhibited commercial uses do not include:- uploading an original video to YouTube, or maintaining an original channel on YouTube, to promote your business or artistic enterprise; - showing YouTube videos through the Embeddable Player on an ad-enabled blog or website, subject to the advertising restrictions set forth above in Section 4.D; - or any use that YouTube expressly authorizes in writing.And given this: http://www.google.com/support/youtube/bin/answer.py?answer=71011&hl=en-US, it appears to be fine even to embed those videos for commercial (non-ad) usage.We've updated our Terms of Use to clarify what kinds of uses of the website and the YouTube Embeddable Player are permitted. We don't want to discourage you from putting the occasional YouTube video in your blog to comment on it or show your readers a video that you like, even if you have general-purpose ads somewhere on your blog. We will, however, enforce our Terms of Use against, say, a website that does nothing more than aggregate a bunch of embedded YouTube videos and intentionally tries to generate ad revenue from them.Vimeo however appears to be a different story:Vimeo is intended for non-commercial use. By using the Site, you agree to abide by these Terms of Service.Facebook I believe is fine, as many of the largest brands in the world use it for promotion, such as Coca Cola and Pepsi - so I think yours would be fine.Hope this helps. |
_codereview.17662 | I am trying to generate LCM by prime factorization. I have already done the other way around to generate LCM using GCD but I am trying to achieve it using prime factorization. I am getting right prime factors but the problem is that to generate LCM we need to multiply each factor the greatest number of times it occurs in either number's factors. ReferenceNow I don't like the code I come up with to achieve this. The logic is to retrieve factors of both numbers and then create a hash/counter for each factor. Finally multiply the factor with the result so far and the greatest number of times in each hash counter list.I would like to request to review my all methods IsPrime, PrimeFactors, LeastCommonMultipleByPrimeFactorization etc. In particular the main LeastCommonMultipleByPrimeFactorization method. Please feel free to pass your comments and suggestions. I would be happy to see some simplest way to achieve this. Code snippet: public static bool IsPrime(int n) { for (int i = 2; i <= n; i++) { if (n % i == 0) { if (i == n) return true; else return false; } } return false; } public static int[] PrimeFactors(int n) { var factors = new List<int>(); for (int i = 2; i <= n; i++) { while (n % i == 0 && IsPrime(i)) { factors.Add(i); n = n / i; } } return factors.ToArray(); } public static int LeastCommonMultipleByPrimeFactorization(int m, int n) { //retrieve prime factors for both numbers int[] mFactors = PrimeFactors(m); int[] nFactors = PrimeFactors(n); //generate hash code to get counter for each factor var mFactorsCountHash = CreateCounterHash(mFactors); var nFactorsCountHash = CreateCounterHash(nFactors); var primeFactors = new List<int>(); primeFactors.AddRange(mFactors); primeFactors.AddRange(nFactors); int result = 1; //On each distinct factor... check either which number factors foreach (int factor in primeFactors.Distinct()) { int mfactorCount = 0; int nfactorCount = 0; if (mFactorsCountHash.ContainsKey(factor)) { mfactorCount = mFactorsCountHash[factor]; } if (nFactorsCountHash.ContainsKey(factor)) { nfactorCount = nFactorsCountHash[factor]; } int numberOfCount = mfactorCount > nfactorCount ? mfactorCount : nfactorCount; result = factor * result * numberOfCount; } return result; } private static Dictionary<int, int> CreateCounterHash(IEnumerable<int> mFactors) { Dictionary<int, int> hash = new Dictionary<int, int>(); foreach (var factor in mFactors) { if (hash.ContainsKey(factor)) hash[factor]++; else hash.Add(factor, 1); } return hash; }To test method, I am using following code[Test] public void LeastCommonMultipleByPrimeFactorizationPositiveTest() { Assert.AreEqual(42, ArthmeticProblems.LeastCommonMultipleByPrimeFactorization(21, 6)); Assert.AreEqual(12, ArthmeticProblems.LeastCommonMultipleByPrimeFactorization(4, 6)); }Note: This is just for fun and revision of my basic concepts | Prime numbers, Prime Factors and LCM | c#;algorithm;primes | IsPrimepublic static bool IsPrime(int n){ for (int i = 2; i <= n; i++) { if (n % i == 0) { if (i == n) return true; else return false; } } return false;}Under what circumstances can the final return false be reached? Why not handle those special cases explicitly, and then simplify the loop body by reducing it?public static bool IsPrime(int n){ if (n < 1) throw new ArgumentException(n); if (n == 1) return false; for (int i = 2; i < n; i++) { if (n % i == 0) return false; } return true;}Of course, there are better ways of testing primality than trial division, but that's beside the point.PrimeFactorspublic static int[] PrimeFactors(int n){ var factors = new List<int>(); for (int i = 2; i <= n; i++) { while (n % i == 0 && IsPrime(i)) { factors.Add(i); n = n / i; } } return factors.ToArray();}Any particular reason for returning int[] instead of IEnumerable<int>?What's the purpose of the IsPrime call there? It's easy to prove that it always returns true (and so the IsPrime method isn't needed at all).As a point of style, I prefer op= methods, but this is really subjective.The loop guard might be more intelligible as n > 1.public static IEnumerable<int> PrimeFactors(int n){ var factors = new List<int>(); for (int i = 2; n > 1; i++) { while (n % i == 0) { factors.Add(i); n /= i; } } return factors;}CreateCounterHashprivate static Dictionary<int, int> CreateCounterHash(IEnumerable<int> mFactors){ Dictionary<int, int> hash = new Dictionary<int, int>(); foreach (var factor in mFactors) { if (hash.ContainsKey(factor)) hash[factor]++; else hash.Add(factor, 1); } return hash;}Why does the return type use the implementation Dictionary rather than the interface IDictionary?Why hard-code the type? You don't do anything with it other than equality checking, so it could be IDictionary<T, int> CreateCounterHash<T>(IEnumerable<T> elts) (and then could potentially be an extension method of IEnumerable<T>).ContainsKey followed by a get is a minor inefficiency. Since TryGetValue will give default(int) (i.e. 0) if the key isn't, found, this can be fixed:private static IDictionary<T, int> CreateCounterHash<T>(IEnumerable<T> elts){ Dictionary<T, int> hash = new Dictionary<T, int>(); foreach (var elt in elts) { int currCount; hash.TryGetValue(elt, out currCount); hash[elt] = currCount + 1; } return hash;}LCMpublic static int LeastCommonMultipleByPrimeFactorization(int m, int n){ //retrieve prime factors for both numbers int[] mFactors = PrimeFactors(m); int[] nFactors = PrimeFactors(n); //generate hash code to get counter for each factor var mFactorsCountHash = CreateCounterHash(mFactors); var nFactorsCountHash = CreateCounterHash(nFactors); var primeFactors = new List<int>(); primeFactors.AddRange(mFactors); primeFactors.AddRange(nFactors); int result = 1; //On each distinct factor... check either which number factors foreach (int factor in primeFactors.Distinct()) { int mfactorCount = 0; int nfactorCount = 0; if (mFactorsCountHash.ContainsKey(factor)) { mfactorCount = mFactorsCountHash[factor]; } if (nFactorsCountHash.ContainsKey(factor)) { nfactorCount = nFactorsCountHash[factor]; } int numberOfCount = mfactorCount > nfactorCount ? mfactorCount : nfactorCount; result = factor * result * numberOfCount; } return result;}Looks buggy: factor * numberOfCount will only be correct when numberOfCount == 1 or factor == 2 && numberOfCount == 2.Also a tad repetitive. Can't you merge the two counts earlier?public static IDictionary<K, V> MergeDictionaries<K, V>(IDictionary<K, V> d1, IDictionary<K, V> d2, Func<V, V, V> mergeFunc){ // Left as an exercise // Only call mergeFunc when both dictionaries contain the key}You can also use a bit of Linq to do the aggregate, so the LCM simplifies topublic static int LeastCommonMultipleByPrimeFactorization(int m, int n){ //retrieve prime factors for both numbers int[] mFactors = PrimeFactors(m); int[] nFactors = PrimeFactors(n); //generate hash code to get counter for each factor var mFactorsCountHash = CreateCounterHash(mFactors); var nFactorsCountHash = CreateCounterHash(nFactors); var combinedCounts = MergeDictionaries(mFactorsCountHash, nFactorsCountHash, Math.Max); return combinedCounts.Aggregate(1, (prod, primeWithMult) => prod * pow(primeWithMult.Key, primeWithMult.Value));} |
_webmaster.106481 | This is a WordPress page (not blog post), how do I remove this X days ago text from SERP?I looked for answers on Google and all of them are for blog posts, not pages | How to remove X days ago on WordPress page from Google SERP? | google;google search;html;wordpress;serps | null |
_webmaster.81439 | I am not sure what an application pool is in IIS. I did manage to find a basic explanation, boiling down to:Websites can be assigned to application pools, all application pools containing specific settings for applications (allowing you to isolate websites).Looking at the documentation, it seems there is much more to it. I cannot find a good explanation though. | What is an application pool in IIS? | iis;iis6 | Applications Pools are a way to segregate the worker processes that on IIS between web applications. They provide the ability to group common applications together so that they can share resources.Each Application Pool has their own set of worker processes assigned to and and does not share processes with other pools. This way, the worker processes for one application pool can not communicate directly with the worker processes of another pool (thus protecting the applications from one another). For example, putting applications for different clients into individual pools to prevent their application's processes from talking to other client's processes.Additionally, it allows more worker processes to be allocated to pools to need them. For example, you might assign more worker processes to a customer-facing store website to handle extra load and fewer to a customer facing support site that might not need the resources for static content. |
_computerscience.2434 | I am making a 2d game in opengl es 2.0Inside are tons of rectangles defined by 4 points and one 4 component color. I am using vertex buffer objects, and I have heard that it is efficent to interlace the data. So like traditionally you would doCorner.xCorner.yCorner.zCorner.rgba(repeat for each corner) However in my situations two assumptions can be made that can probably make things faster1. All the rectangles z values are 02. All corners of the rectangle have the same color. Is it possible, and what would it look like to have a buffer object structured like this. Corner.xyCorner.xyCorner.xyCorner.xyColor.rgba? Is it even possible to have opengl assume that the Z is always 0? Is it possible to reuse the color like to hat? | Interlacing vertex buffer data with extra efficiency | opengl es | Is it even possible to have opengl assume that the Z is always 0?Yes it is. Just set the component count to 2 in glVertexAttribPointer and the other 2 components (z and w) will be auto filled with 0 and 1 resp.Is it possible to reuse the color like to hat? No it is not. Opengl (and most other graphics apis) require that each vertex is referenced by only a single index. |
_unix.258924 | I have an infrared remote control which sends RC-5 signals and a computer with an IR receiver. The computer runs Debian 8 and I'm trying to set up LIRC so that I can control the music player daemon (MPD) with the remote.I have installed the lirc package and added a configuration file for RC-5 signals in /etc/lirc/lircd.conf.d/.The daemon seems to be active:$ systemctl status lirc.service lirc.service - LSB: Starts LIRC daemon. Loaded: loaded (/etc/init.d/lirc) Active: active (exited) since Sun 2016-01-31 20:18:17 CET; 32s ago Process: 408 ExecStart=/etc/init.d/lirc start (code=exited, status=0/SUCCESS)However, when I try to test the remote control with irw it fails:$ irwconnect: No such file or directoryAccording to man irw this seems to be cause by the absence of the socket file /var/run/lirc/lircd. The directory /var/run/lirc is empty.Any clues would be greatly appriciated. | Setting up LIRC in Debian 8 | debian;remote control | Here are the steps I needed to perform to make it work. Initially I got stuck at step two.Install LIRC:# apt-get install lircIn /etc/lirc/hardware.conf, set DRIVER and DEVICE:DRIVER=defaultDEVICE=/dev/lirc0Download a configuration file for the remote control and copy it to /etc/lirc/lircd.conf. In my case the protocol is RC-5 and I found a working configuration file at http://lirc.sourceforge.net/remotes/rc-5/RC-5.Restart the LIRC daemon:# systemctl restart lircTo find out the name for each button, run irw, point the remote control to the IR receiver and press buttons.Specify what should happen when a button is pressed in the file /etc/lirc/lircrc. Here is the file I created for MPD:begin button = sys_14_command_21 prog = irexec config = mpc prevendbegin button = sys_14_command_20 prog = irexec config = mpc nextendbegin button = sys_14_command_35 prog = irexec config = mpc playendbegin button = sys_14_command_30 prog = irexec config = mpc pauseendbegin button = sys_14_command_36 prog = irexec config = mpc stopendStart irexec:$ irexec --daemon |
_unix.370001 | Intro:The following was done on a RHEL 6.9 32bit OS.I installed the oracle (not openjdk) version of JRE rpm using the rpm -Uvh command.I then built a package using rpmbuild that requires libjvm.so which is provided by the oracle JRE and verified this using the command.rpm -ql jre1.8.0_111-1.8.0_111-fcs.i586Problem:However, when I go to install the rpm I built or use the command rpm -q libjvm.so I am getting told that libjvm.so is not installed.I know I can put in the spec file for my rpm AutoReqProv: noto get around the dependency issue, however, that does not seem like good practice and I have also rebuilt the rpm database to no avail.Question:Thus I am left pondering and trying to solve, how the jre rpm says it provides libjvm.so yet the RPM database keeps saying that the dependency libjvm.so is not installed. Any ideas?EDITThe JRE rpm also provides the followingjaxp_parser_impl xml-commons-apis java java-1.8.0 java-fonts jre jre-1.8.0 jre1.8.0_111 = 1.8.0_111-fcs | RPM database not seeing file installed as part of RPM | rhel;rpm;java;dependencies | The libjvm.so requirement in the OpenJDK packages comes from$ rpm -qp --provides java-1.8.0-openjdk-headless-1.8.0.121-1.b13.el6.x86_64.rpm \ 2>/dev/null | grep libjvmlibjvm.so()(64bit)libjvm.so(SUNWprivate_1.1)(64bit)which the Oracle RPM by contrast does not provide. Apart from removingthat requirement from the package you are building (either with the hammer that is AutoReqProv or more complicated options involving the dependency scripts) another option is tocreate a shim package that does nothing more than provide the necessaryrequirement (and possibly to Conflict with OpenJDK).Name: shim-libjvmVersion: 1Release: 1%{?dist}Summary: Shim for libjvmGroup: Development/LanguagesLicense: CC BY-SA 3.0URL: http://example.orgProvides: libjvm.soBuildArchitectures: noarch%descriptionShim for libjvm%installmkdir -p %{buildroot}/usr/share/doc/shim-libjvmecho shim-libjvm is merely a provider for libjvm.so > %{buildroot}/usr/share/doc/shim-libjvm/README%files%doc/usr/share/doc/shim-libjvm/README%changelog* Thu Jun 8 2017 John Doe <[email protected]>- Release on a mostly unsuspecting world. |
_unix.64344 | I want to delete duplicates in a massive bunch of images. Well as I have dups of the same picture in a different resolution I will make the deletion myself. BUT I want to do this in linear time. So I thought it woud be smart to sort the images via renaming the images with an average color prefix with a little script. The problem is that I don't know any software that is able to compute the average color in the CLI. Is there any? | Delete duplicate images. Need Software for computing average color of an image | colors;sort;images | Finally I played around a while and found the ImageMagick software pack. It's great because it lets me do it in a one-liner in the console without the need for a script.for i in ./*; do mv $i $(convert $i -scale 1x1\! -format '%[pixel:s]' info:- | cut -db -f2-)${i#./} ;doneIt just does nothing more than loop through the folder (precondition: it just contains images!), get the average color via convert $i -scale 1x1\! -format '%[pixel:s]' info:- extract the relevant part from the output cut -db -f2- and finally rename the file. Horribly how well it worked.Greets |
_softwareengineering.156512 | I have a c++/cli tcp client application sending a data in a specific format like L,20100930033425093,-5.929958,13.164021to a main application on port 9000.The main application is actually done by the other vendor and I dont have the source code for that.Now,I can communicate to the desired application using the IP and Port No.But the data supposed to be visible on the Main Application GUI is not showing up. But I used a different socket server demo application with same IP as the main application to receive the data I am sending.It works perfectly fine. Now I do not know where the error is or whether the stream is received on the other side. How can I effectively solve this situation. I am asking this in a broader picture to get some ideas.Any suggestions or discussion on this will be helpful? | How to find an error in a tcp server application for which there is no source code | c++;.net;problem solving;sockets | null |
_cs.41827 | A rather basic question but I am confused about the characterization of a certain local search method which I want to describe in the framework of EAs. In particular, consider an EA which in every step of the evolution has a neighborhood of size 2; one element in the neighborhood is the current hypothesis (hypothesis in the traditional sense of learning theory) and the other element in the neighborhood is another hypothesis that has arisen from the current hypothesis after applying some transformation/mutation. It is clear that for such algorithms in the neighborhood we can find at most 1 hypothesis that has strictly better fitness compared to our current hypothesis (our current hypothesis is neutral compared to our current hypothesis). Thus, my question is, how would one characterize an algorithm of this form that always picks among the beneficial set if the set is non-empty, otherwise it would pick among the neutral set (at random - or with some prescribed probability distribution)? Note that the neutral set is always non-empty as the current hypothesis is always there. So, can this algorithm be described as a $(1+1)$-EA or should it be described as a $(1, 1)$-EA? Is there a difference between a $(1+1)$-EA and a $(1, 1)$-EA?And since we are here, if anyone would be able to clarify the following I would be indebted. What is the difference between a $(1+k)$-EA and a $(1, k)$-EA for $k > 1$. As far as I have understood the comma description (i.e. $(1, k)$-EA) refers to the fact that the algorithm picks the most fit hypothesis among the $k+1$ elements in the neighborhood. The understanding that I have for $(1+k)$-EAs is that they pick at random (however that will be defined) among the hypotheses that have strictly larger fitness values compared to the current hypothesis. Is this understanding correct?Thank you for your time in advance. | A clarification on the taxonomy of Evolutionary Algorithms | machine learning;genetic algorithms;learning theory;evolutionary computing | I'm not 100% sure I understand your formulation (things like our current hypothesis is neutral compared to our current hypothesis are a bit confusing), but if I understand it correctly, it's this:You have a current solution and at each time step, you generate a new one based on the current one and some random variation operator. If the new one is better than the current one, you accept the new one. Otherwise, you keep the current one.That's a $(1+1)$-ES. A $(1,1)$-ES always accepts the new hypothesis/solution, regardless of quality. A $(1,1)$-ES is just a random walk on the graph defined by your variation operator. For a $(\mu$, $\lambda)$-ES, the algorithm generates $\lambda$ hypotheses at each step, and selects the best $\mu$ of them to form the population for the next generation -- the current hypotheses never survive (unless your variation operator produces a copy of one of them). The $(\mu+\lambda)$ strategy takes the best $\mu$ from the union of the current population and the new one. |
_softwareengineering.219213 | In a recent project I was asked to implement an events system. An Event had to have a Location which was originally specced out as simply a physical location with some optional extra notes. Then the spec changed (as they have a habit of doing) and we needed to have online events too. These would not have a physical address but would still need notes on how to attend (e.g. the URL, joining instructions).We decided to adapt the existing Location table by adding an IsOnline field and it wound up looking like this:+-----------------+ +---------------+| Event | | Location |+-----------------+ +---------------+| Id | .--+ Id || Name | | | Name || Summary | | | Address || Date | | | Postcode || Capacity | | | IsOnline || LocationId +--' | Notes |+-----------------+ +---------------+An example of a physical and an online entry in the Location table look like this:+----+----------------+--------------------------------------+----------+----------+---------------------------------------+| Id | Name | Address | Postcode | IsOnline | Notes |+----+----------------+--------------------------------------+----------+----------+---------------------------------------+| 1 | Physical Event | 10 Downing Street, London | SW1A 2AA | 0 | Ask the policeman to let you in || 2 | Online Event | http://programmers.stackexchange.com | null | 1 | You will need a stackexchange account |+----+----------------+--------------------------------------+----------+----------+---------------------------------------+It works (currently) for our simple use case but it is clearly a bit of a hack and it got me thinking - what would be the correct, normalized way to model this kind of relationship (Where an entity must have an A or a B but not both)? | How should this relationship be structured in a relational database? | database design;relational database | You can keep the fields common to all locations in that table, but have multiple tables handling different location types. You could add a third location-type table like GeoSpacialAddress which would have Lat/Longs instead of physical addresses.This prevents having a lot of null fields. You just have to be aware in your querying and may need to use a UNION to get a complete list of all types addresses. IsOnline can be determined by a location having one or more OnlineAddress records.LocationIDNameNotesOnlineAddressIDLocationIDURLPhysicalAddressIDLocationIDAddressPostCodeGeoSpacialAddressIDLocationIDLatLong |
_webapps.45862 | I have a Google presentation with many slides. I tried File Download As SVG or PNG, but only the first slide was converted. Is there a way to automatically convert all slides to images? | Save all Google presentation slides as images | images;google presentations | If you have access to MS PowerPoint, one option is to save the Docs presentation as a .ppt, and then use the Save As option from PowerPoint which does have all slides option. |
_softwareengineering.95718 | Design patterns are good, but complex. Should we use them in small projects? Implementing design patterns needs more sophisticated developers, which in turn raises project costs. On the other hand, they make code neat and clean. Are they necessary for small projects?Update: Should we insist on using design patterns when the team is not efficient at working with them? | To design pattern, or not to design pattern | design patterns | Design patterns are good, but complex.This is a false assumption. Design Patterns are meant to strip complexity off existing code and to aid communication between developers. When Design Patterns introduce a higher grade of complexity, then they are misused.Implementing design patters need more sophisticated developers and which in turn raises project costs.This is also a false assumption. Any developer should strive for a minimum amount of complexity in his code. A good developer is well worth his money as the maintenance and extensibility costs decrease.Are they necessary for small projects?They are necessary when they help making the code more expressive and less complex. This is independent of project size. A good developer (tm) will not overengineer and use them when appropriate. |
_softwareengineering.315947 | I don't know where else to ask this.I have an Android app I want to release on the store, and I want to charge a low fee for it. But if part of my application uses code I did not write (i.e. code I've added as a dependency to my Gradle file, found through a project's Github page) under the Apache 2.0 license, am I not allowed to charge for my app? Do I have to release the source to my entire project? What am I allowed to do and not allowed to do? | Can you charge for apps that use open source software? | open source;android;apache license;android market | null |
_codereview.42851 | In my code I have a base type which is OnlinePaymentTransaction:public abstract class OnlinePaymentTransaction{ public abstract void Complete( PaymentGatewayCallbackArgs args );}The problem I am having is that each class that inherits from this base class require different dependency's in the complete method. Currently I have just added the dependency's as extra parameters to the complete method which doesn't seem right. For example my base class is now like this. public abstract class OnlinePaymentTransaction{ public abstract void Complete( Dependency1 dep1, Dependency2 dep2, PaymentGatewayCallbackArgs args );}I cannot inject the dependency's in the constructor as the OnlinePaymentTransactions are retrieved from using nhibernate.What would you recommend because I don't like using ServiceLocator as it hides the dependency and also makes it harder to test. An suggestions would be greatly appreciated. | Dependency on overridden method | c#;dependency injection | I cannot inject the dependency's in the constructor as the OnlinePaymentTransactions are retrieved from using nhibernate.There's your problem. Your OnlinePaymentTransaction class is/should-be a POCO whose job is to convey data. The Complete() method doesn't belong on that type, it's breaking SRP and making your life much harder than it needs to be.I'd suggest to introduce another type, call it OnlinePaymentTransactionProcessor or whatever - that type will take the dependencies in its constructor, and have a Complete method that takes an OnlinePaymentTransaction instance.Kudos for striving to avoid a Service Locator :) |
_codereview.39337 | I am learning Java as my first programming language and have written a bit of code. I would love to read expert reviews on this code and suggestions to improve right from naming conventions to logic. Please let me know if there is any kind of mistake.public class Sudoku { public static void main(String[] args) { long startTime = System.currentTimeMillis(); int[][] array = { { 0, 2, 0, 5, 0, 0, 0, 9, 0 }, { 5, 0, 0, 0, 7, 9, 0, 0, 4 }, { 3, 0, 0, 0, 1, 0, 0, 0, 0 }, { 6, 0, 0, 0, 0, 0, 8, 0, 7 }, { 0, 7, 5, 0, 2, 0, 0, 1, 0 }, { 0, 1, 0, 0, 0, 0, 4, 0, 0 }, { 0, 0, 0, 3, 0, 8, 9, 0, 2 }, { 7, 0, 0, 0, 6, 0, 0, 4, 0 }, { 0, 3, 0, 2, 0, 0, 1, 0, 0 } }; solve(array); System.out.println(Solution is ); for (int row = 0; row < 9; row++) { for (int col = 0; col < 9; col++) { System.out.print( + array[row][col] + ); } System.out.println(); } long endTime = System.currentTimeMillis(); long totalTime = endTime - startTime; System.out.println(Time taken (in MilliSeconds)= + totalTime); } public static boolean solve(int[][] array) { if (isSum45(array)) { return true; } for (int row = 0; row < 9; row++) { for (int col = 0; col < 9; col++) { if (array[row][col] == 0) { for (int num = 1; num <= 9; num++) { if (noConflict(array, row, col, num)) { array[row][col] = num; if (solve(array)) { return true; } } array[row][col] = 0; } return false; } } } return false; } // This method edited is after taking suggestions from this forum public static boolean noConflict(int[][] array, int row, int col, int num) { for (int k = 0; k < 9; k++) { if (array[row][k] == num) { return false; } if (array[k][col] == num) { return false; } } int m = row - (row % 3); int n = col - (col % 3); for (int p = m; p < m + 3; p++) { for (int q = n; q < n + 3; q++) { if (array[p][q] == num) { return false; } } } return true; } public static boolean isSum45(int[][] array) { for (int row = 0; row < 9; row++) { for (int col = 0; col < 9; col++) { int sum = 0; int m = row - (row % 3); int n = col - (col % 3); for (int p = m; p < m + 3; p++) { for (int q = n; q < n + 3; q++) { sum = sum + array[p][q]; } } if (sum != 45) { return false; } } } return true; }} | Alternative methods of solving Sudoku | java;beginner;recursion;sudoku | null |
_webmaster.11115 | I have had this problem for quite some time. It wasn't actually a big issue until lately when one of our conference site has a lot of IE6 users.The black loading screen appears right after I include a youtube clip into our site. The site is content managed with Joomla but I don't see any reason how Joomla has got any compatibility issues with youtube and IE6 !Anyone knows how, why or has experienced this similar issue b4 ?Tried using but the youtube div wouldn't appear on firefox. Is the code right?url of website: http://schoolcontingency.comUse http://ipinfo.info/netrenderer/index.php to render IE6 images. Would love to upload the photo but I have 0 reputation :(or refer to here https://stackoverflow.com/questions/5408808/annoying-ie6-black-screen-with-loading-when-youtube-is-added | Annoying IE6. Black screen with loading when youtube is added | html;css;joomla;internet explorer;browsers | Seems is not youtube's fault but something of your site, some plugin or Drupal setting. It's simply a preloading image, that in modern browsers shows just the loading text part while it is preloading something (tried with IEtester, it does not only happen with youtube clips,it's global) it loads a div or other element -have not checked- which has a huge extension, probably at full page, and shows transparent in these modern browsers due this exact line of css: background:transparent url(loading.png) no-repeat scroll 0 0; , but iE6, as long as I remember, does not support the transparent attribute, so, shows black. My solution would be alternative css code, or a javascript loading a totally different css, etc, or alternative html when calling it. Another solution might be just deactivate the plugin/feature of your drupal site, find where it's being activated, seems a gobal value, so should be easy.The thing happens at boxplus.css , in this block./* Progress indicator */#boxplus .boxplus-dialog .boxplus-progress {position:absolute;left:0;right:0;top:0;bottom:0;height:32px;width:32px;margin:auto;background:transparent url(loading.png) no-repeat scroll 0 0;}So, dig for progress indicator feature, deactivate it, or tweak the html or css to support IE6. Should be pretty easy for anyone having some html/css knowledge, provided you tried first the GUI way of simply touching the drupal plugin.Edit: Doing it by hand, the hard way, it'd be making just a full page div, and try first just setting no background property at all, and use a small transparent gif (if know how to do smooth aliased borders with a gif, I mean, not being too sharp) instead of the png. And of course, all conditional css/html needed. |
_unix.341249 | I am trying to debug a problem with my program using gdb. I compiled using the debug setup in the makefile; clean build:...#no -O2 for debug but need -gC++FLAGS = -c -fPIC -g -DLINUX -D_DEBUG -D_FILE_OFFSET_BITS=64 -m64 -Wall#C++FLAGS = -c -fPIC -O2 -DLINUX -DNDEBUG -D_FILE_OFFSET_BITS=64 -m64 -Wallifeq ($(OS),Darwin) LDFLAGS = -m64 -pthread -ldl -L../$(LIB_DIR1)/debug \ -L$(DEP_DIR)/s/$(LIB_DIR1) \ -L$(DEP_DIR)/t/$(LIB_DIR2)/debugelse ...endifLDLIBS = -lu_debug -ls_debug -lt_debug -ltmalloc_debug...to run gdb I did the following:copied the file I needed to the current dir.At mac command line:gdb ./ExampleProgram(gdb) b 2612(gdb) set env DYLD_LIBRARY_PATH=/full/path/to/dependency/darwin/lib:/full/path/to/dependency/darwin/lib/debug:/full/path/to/athother/dependency/darwin/lib/debug(gdb) r filenameIt says starting program: /full/path/to/example/./ExampleProgram filenamearch: realpath failed on /full/path/to/program/example/./ExampleProgramprogram exited with code 01.I'm not finding a lot of good info on the problem. unix gdb use, no executable was what it said when I tried to run it in emacs. | gdb arch: realpath failed when try to run with parameter | osx;gdb | null |
_cogsci.12712 | We remove children from anything that is sex related, including talks and photos. When I think about it, it seems deeply and morally wrong to not do it.When I first thought about that, I thought that it might be because we don't want to encourage them to become sexual. But we also don't want them to be violent, and no one thinks it's wrong to send a 5 year old to a martial arts class. For any other aspect of life, we let them, to some degree, experience.That made me think that it might be something more than cultural. Of course the definition of child may vary depending on the society, but not the moral code of that ruling. | Why do many parents prevent children from being exposed to anything sex-related? | sexuality;moral psychology;evolutionary psychology | null |
_webmaster.20584 | Possible Duplicate:Do dedicated IP addresses improve SEO? There are occasionally cases in which a client owns multiple domains for his business. For example a client may own landscaping.com, and also own newyork-landscaping.com and etc...I have a question regarding the SEO strategy for a business in such cases, assuming that there are 50 domains for different cities, and assuming that there is unique content on every one of those 50 domains.Is it better to have different IP addresses for each domain? | Multidomain website SEO strategy | seo | IP addresses should be irrelevant. In terms of SEO, what matters is that the content on the sites not be cloned content. Google catches that and realizes you're running a keyword site farm.Hopefully Google will get smarter and also penalize companies that use 50 domains to promote one company even when the sites have different content as well. ;o) |
_codereview.123053 | I have an implementation of flatmap for std::vector. However, I find the repetition of the inferred return type to be ugly. And, in general, I suspect that the implementation could be cleaner or more general.template<typename T, typename FN>static auto flatmap(const std::vector<T> &vec, FN fn) -> std::vector<typename std::remove_reference<decltype(fn(T())[0])>::type> { std::vector<typename std::remove_reference<decltype(fn(T())[0])>::type> result; for(auto x : vec) { auto y = fn(x); for( auto v : y ) { result.push_back(v); } } return result;};It can be used like this:TEST_F(MarkdownUtilTests, testFlatmap) { std::vector<int> v = { 1, 2, 3}; std::vector<int> result = flatmap(v, [](int x) { return std::vector<int> { x, x*2, x*3 }; } ); assertThat(result, is(std::vector<int> {1,2,3,2,4,6,3,6,9} ));} | Flatmap implementation | c++;c++11 | null |
_unix.30295 | cp a b and cat a > b, what's the difference?In x86 install script of linux kernel's source tree (arch/x86/boot/install.sh),both are used:cat $2 > $4/vmlinuzcp $3 $4/System.mapWhy don't they just keep the same format if one is better than the other? | cp vs. cat to copy a file | bash;linux kernel | One more issue comes to my mind where cat vs. cp makes a significant difference:By definition, cat will expand sparse files, filling in the gaps with real zero bytes, while cp at least can be told to preserve the holes.Sparse files are files where sequences of zero bytes have been replaced by metadata to preserve space. You can test by creating one with dd, and duplicate it with the tools of your choice. Create a sparse file (changing to /tmp beforehand to avoid trouble - see final note):15> cd /tmp16> dd if=/dev/null of=sparsetest bs=512b seek=5 0+0 records in 0+0 records out 0 bytes (0 B) copied, 5.9256e-05 s, 0.0 kB/ssize it - it should not take any space.17> du -sh sparsetest0 sparsetestcopy it with cp and check size18> cp sparsetest sparsecp19> du -sh sparsecp0 sparsecpnow copy it with cat and check size20> cat sparsetest > sparsecat21> du -sh sparsecat1.3M sparsecattry your preferred tools to check on their behaviourdon't forget to clean up.Final note of caution:Experiments like these have the inherent chance of rising your fame with your local sysadmin if you're doing them on a filesystem that's part of his backup plan, or critical for the well-being of the system. Depending on his choice of tool for backup, he might end up needing more tape media than he ever considered possible to back up that one 0-byte file which gets expanded to terabytes of zeroes.Other files which cannot be copied with neither cat nor cp would include device-special files, etc.It depends on your implementation of copying tool if it is able to duplicate the device node, or if it would merrily copy its contents instead. |
_cs.23428 | Let $M$ be a square matrix with entries that are $0$ or $1$ and let $v$ be a vector with values that are also $0$ or $1$. If we are given $M$ and $y = Mv$, we can computer $v$ if $M$ is non-singular. Now let us take the second bit (from the right) of the binary representation of each $y_i$ as another vector $z$. So $z$ also has entries which are $0$ or $1$. If $y_i$ has fewer than two bits we just let $z_i=0$. If we are given $z$ and $M$, how (and when) can you find a $v$ so that $Mv$ would produce $z$ under this operation?Here is an example$$M = \begin{pmatrix} 0 & 0 & 1 & 0\\ 1 & 1 & 0 & 1\\ 1 & 1 & 1 & 0\\ 0 & 1 & 1 & 1\\\end{pmatrix}, v = \begin{pmatrix} 0 \\ 1 \\ 1 \\ 1\\\end{pmatrix}\implies Mv=\begin{pmatrix} 1 \\ 2 \\ 2 \\ 3\\\end{pmatrix}.$$So in this case $$z = \begin{pmatrix}0 \\1 \\1 \\1 \\\end{pmatrix}.$$Is this problem in fact NP-hard? | How to compute a curious inverse | algorithms;np hard;linear algebra | This problem can be cast into a familiar form: it's an example of what is known as a 0-1 linear programming problem. You have a set of variables $v_1, v_2, \dots v_n$ subject to constraints of the form $m\le a_1v_1+a_2v_2+\cdots +a_nv_n\le M$. In your particular problem, we also have $a_i \in \{0, 1\}$. You are looking for any feasible solutions, namely tuples $(v_1, \dots, v_n)$ which satisfy all the constraints.For example, suppose we have$$M = \left( \begin{array}{cccc} 0 & 0 & 1 & 0\\ 1 & 1 & 0 & 1\\ 1 & 1 & 1 & 0\\ 0 & 1 & 1 & 1 \end{array} \right), \quad{\text{and}}\quadz= \left( \begin{array}{c} 0\\1\\0\\1 \end{array}\right)$$then you want $$v= \left( \begin{array}{c} a\\b\\c\\d \end{array}\right)$$such that $Mv$ will be, in binary (with the lower-order bit unspecified)$$Mv=\left(\begin{array}{c}c \\ a+b+d \\ a + b + c \\ b + c + d \end{array}\right)=\left(\begin{array}{c}\mathtt{0\_}\\ \mathtt{1\_}\\ \mathtt{0\_}\\ \mathtt{1\_}\end{array}\right)$$From this we have the constraints$$\begin{array}{c}0\le a, b, c, d\le 1\\2\le a + b + d\le 3\\0\le a + b + c\le 1\\2\le b + c + d\le 3\end{array}$$and you want to find $a, b, c, d$ such that all the constraints are simultaneously satisfied.We've moved into 0-1 LP land because there are established procedures for solving problems like this, though sadly there's nowhere near enough room in this post to introduce them, so you'll have to do the legwork yourself. Be aware that problems like this are very compute-intensive (by which I mean NP-hard) and as far as I know you're not going to get anything like an elegant formulation of the form This can be solved if and only if $z$ is of the form ...By the way, the example I used does indeed have a solution, $v$, and in this particular case is unique, though in general you'll have several solutions (if there are any at all). |
_cstheory.14786 | The oracles that are used in relativized collapses or separations of complexity classes rarely represent $natural$ algorithmic problems. They are typically constructed artificially with techniques like diagonalization, for the sole purpose of achieving the relativized collapse or separation. A notable exception is that for any ${\bf PSPACE}$-complete set $L$ it holds that ${\bf P}^L={\bf NP}^L$. This indeed leads to natural relativized worlds, since there are ${\bf PSPACE}$-complete languages that correspond to natural algorithmic tasks. Generally, I am looking for such examples, where the oracle represents a natural problem. (And, of course, it is not trivially implied by the above example). In particular, is there any such known natural relativized world in which ${\bf P}$ and ${\bf NP}$ are separated?$Note:$ A random oracle here does not count as natural, because it does not represent a natural algorithmic problem. It rather represents that a statement holds for almost all oracles, regardless to their naturality. | Natural relativized worlds | cc.complexity theory;complexity classes;oracles | null |
_cs.18178 | I have a practice exam question that I don't know how to set up a recurrence for. It is dealing with a hash table. The question is as follows:Suppose that a hashing strategy is designed so that it starts with an initial hash table size of $H= 8$. You may assume that only insertions are performed (no deletions).Any time the hash table is going to be more than 50% full (when an attempt is made to add item $\frac{H}{2} + 1$ to a table of size $H$), the hash table size is doubled to $2\times H$, and then the $\frac{H}{2}$ keys in the previous hash table are rehashed using $\frac{H}{2}$ extraneous key insertions into the new table of size $2 \times H$. The key insertions used to initially place each key into the hash table are called necessary key insertions (these are not extraneous).The question is asking to derive a recurrence relation $E(H)$ for the number of extraneous key insertions that have occurred in total up until the point in time that the hash table size is $H$ and to explain where the terms in the recurrence relation derive from.If someone could help me out with this, it would provide very helpful as I am practicing for an exam that I have in a week. Thanks everyone.I got the result $E(H)=2\times E(\frac{H}{2})$ because after each rehash there are $\frac{H}{2}$ extraneous key insertions being put into the table of size $2\times H$. So if the size is twice the amount of $H$, I figured the recurrence would be $E(H)=2\times E(\frac{H}{2})$. I only posted here because I was hoping someone could assist me with this because this question has me a bit stumped. | Recurrence for total number of extraneous key insertions in a hash table | data structures;runtime analysis;recurrence relation;hash tables | null |
_softwareengineering.173025 | Suppose there are some methods to convert from X to Y and vice versa; the conversion may fail in some cases, and exceptions are used to signal conversion errors in those cases.Which would be the best option for defining exception classes in this context?A single XYConversionException class, with an attribute (e.g. anenum) specifying the direction of the conversion (e.g.ConversionFromXToY, ConversionFromYToX).A XYConversionException class, with two derived classesConversionFromXToYException and ConversionFromYToXException.ConversionFromXToYException and ConversionFromYToXException classeswithout a common base class. | Designing exceptions for conversion failures | design;exceptions | The foremost reason for having different exception types is to be able to catch them selectively.So the question you should ask yourself is: Will you ever have a piece of code where conversion might fail and you only want to catch conversion errors in one direction and not the other? If so, having two distinct exception classes is the best way to go. If you want to be able to catch both in the same clause, then you need a common super class as well.If you do find it hard to anticipate how the exceptions are caught, then stick to YAGNI and go with the first option. You can always add the subclasses later if you ever actually need them.Apart from that, I think you should ask yourself whether exceptions are the right way to signal conversion failure, because in fact failure is an expected option. In fact a lot of APIs merely use sentinel values for that.Another nice way to propagate errors would be to wrap return information of any call that can fail like this (in pseudo-code): class Outcome<Result, Error> { const Bool success; const Result result; const Error error; Result sure() { if (success) return result; else throw error; } } Outcome<X, { value: Y, message: String }> convertYToX(Y y) { if (suitable(y)) return Outcome{ success: true, result: convert(y) }; else return Outcome{ success: false, error: { }}; }And then either do: handleX(convertXToY(myY).sure());//will throw an exception if an error occurredOr inspect the result yourself: var o = convertXToY(myY); if (o.success) handleX(o.result); else { log('error occured during conversion:'); log(o.error.message); log('using default'); handleX(defaultX); } |
_cstheory.27143 | Following a fruitful question in MO, I thought it would be worthwhile to discuss some notable paper names in CS.It is quite clear that most of us might be attracted to read (or at least glance at) a paper with an interesting title (at least I do so every time I go over a list of papers in a conference), or avoid reading poorly named articles.Which papers do you remember because of their titles (and, not-necessarily, the contents)?My favorite, while not a proper TCS paper, is The relational model is dead, SQL is dead, and I dont feel so good myself. . | Most memorable CS paper titles | soft question;big list | null |
_cs.68763 | I need to Find grammar for the following language: $\{ a^{m_1}ba^{m_2}b\dots a^{m_k}bca^n \mid m_j = n \text{ for some } 1 \le j \le k \}$.can someone help me to solve it? I am not sure how to start. | Find grammar for the following language: $\{ a^{m_1}ba^{m_2}b\dots a^{m_k}bca^n \mid m_j = n \text{ for some } 1 \le j \le k \}$ | formal languages;formal grammars | null |
_unix.127490 | I already installed FreeBSD 10, Apache 2.4 and PHP 5.5. I also just bought a domain from GoDaddy, and I would like to setup a web-hosting in my server, in order to make my website to be reachable from any web browser. So should be my configuration?I assigned my server (running FreeBSD 10) the static IP address 192.168.1.130My domain.com has x1.x1.x1.x1My internet service provider is (ISP) is x2.x2.x2.x2Questions:From these 3 IP addresses above, which one should my httpd.conf in Apache 2.4 have to be listen to? In my DNS A record at GoDaddy, which IP address should my domain point to?Do I need to make any changes in my /etc/hosts file?Note: I use x1.x1.x1.x1 and x2.x2.x2.x2 as examples. | Hosting on freeBSD | networking;apache httpd | null |
_cstheory.31878 | Due to the symmetry of information, it follows up to an additive constant thatK(X,Y) = K(Y,X) Does this hold for more than two data objects as well? | Is joint Kolmogorov Complexity order invariant? | cc.complexity theory;it.information theory;kolmogorov complexity | You don't need symmetry of information. The invariance theorem does the trick. Let $p$ the smallest program such that $U(p) = \langle x, y\rangle$. One way of producing $(y, x)$ is to take make a program $q$ that runs whatever program it is given as input, interprets the output as a pair, and flips the two parts. This gives you a program $\overline{q}p$ to produce $\langle y, x\rangle$. Since $\overline{q}$ is only a constant number of bits long, the two $K$'s are equal up to a constant.Now for higher numbers of arguments, the same idea works in principle. However, the constant does depend on the number of arguments: if I want to write a $q$ program to compute some $n$-tuple of numbers and re-arrange it into an arbitrary order, I need to encode the order in $\log(n!)$ bits (if the ordering is random). So if the number of arguments is not fixed to a constant, you need to take that into account.Isn't there some other way, besides the $q$ program? No, if there were we could encode free information in the ordering of the tuple.Assume for a contradiction that $K(x_1, \ldots, x_n)$ is invariant up to a constant to permutation of the arguments, with the constant independent of $n$. Let $X = \langle x_1, \ldots, x_n\rangle$ be the enumeration of the first $n$ binary strings, so that $K(X) \leq_+ K(n)$. Let $z$ be a random string with $|z| = \log(n!)$ Let $\langle x_1, \ldots, x_n \rangle$ be a random string. Index all permutations of $n$ elements by binary strings and pick the one corresponding to $z$. Call this permutation of our tuple $X_z$. Let $p$ and $p_z$ be the shortest programs for $X$ and $X_z$ respectively. Build a program $q$ that reads input $\overline{p}p_z$ and returns $z$. Putting all this together gives us $$\log(n!) \leq_+ K(z) \leq_+ |\overline{q}\overline{p}p_z| \leq_+ 2K(X) \leq_+ 2K(n) \leq_+ 4\log(n).$$ |
_codereview.109341 | I am fairly new to C++, and to have a break from all that Java programming, I decided to do something in C++, which is sorting. The four sorting algorithms are:Bubble SortInsertion SortQuick SortMerge SortCode:#include <iostream>#include <ctime>#include <cstdlib>#include <iterator>#include <chrono>#define SIZE 100#define MAX 1000typedef std::chrono::high_resolution_clock Clock;void bubbleSort(int toSort[], int length);void insertionSort(int toSort[], int length);void quickSort(int toSort[], int length);void mergeSort(int toSort[], int length);void printArray(int arr[], int length){ for (int i = 0; i < length; i++) { std::cout << arr[i] << ; } std::cout << \n;}int main(){ srand(time(NULL)); int arr[SIZE]; for (int i = 0; i < SIZE; i++) { arr[i] = rand() % MAX; } int arrCopy[SIZE]; std::copy(std::begin(arr), std::end(arr), std::begin(arrCopy)); auto start = Clock::now(); bubbleSort(arrCopy, SIZE); auto end = Clock::now(); printArray(arrCopy, SIZE); std::cout << Time taken (nanoseconds): << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() << std::endl; std::copy(std::begin(arr), std::end(arr), std::begin(arrCopy)); start = Clock::now(); insertionSort(arrCopy, SIZE); end = Clock::now(); printArray(arrCopy, SIZE); std::cout << Time taken (nanoseconds): << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() << std::endl; std::copy(std::begin(arr), std::end(arr), std::begin(arrCopy)); start = Clock::now(); quickSort(arrCopy, SIZE); end = Clock::now(); printArray(arrCopy, SIZE); std::cout << Time taken (nanoseconds): << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() << std::endl; std::copy(std::begin(arr), std::end(arr), std::begin(arrCopy)); start = Clock::now(); mergeSort(arrCopy, SIZE); end = Clock::now(); printArray(arrCopy, SIZE); std::cout << Time taken (nanoseconds): << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() << std::endl; return 0;}void swapElements(int toSort[], int i, int j) { int temp = toSort[i]; toSort[i] = toSort[j]; toSort[j] = temp;}void insertionSort(int toSort[], int length){ int temp; for (int i = 0; i < length; i++) { for (int j = i; j > 0; j--) { if (toSort[j] < toSort[j - 1]) { temp = toSort[j]; toSort[j] = toSort[j - 1]; toSort[j - 1] = temp; } } }}void bubbleSort(int toSort[], int length){ int temp; for (int i = 0; i < length; i++) { for (int j = 1; j < length - i; j++) { if (toSort[j] < toSort[j - 1]) { temp = toSort[j]; toSort[j] = toSort[j - 1]; toSort[j - 1] = temp; } } }}int partitionElements(int toSort[], int beginPtr, int endPtr) { int pivot = toSort[(rand() % endPtr - beginPtr + 1) + beginPtr]; beginPtr--; while (beginPtr < endPtr) { do { beginPtr++; } while (toSort[beginPtr] < pivot); do { endPtr--; } while (toSort[endPtr] > pivot); if (beginPtr < endPtr) { // Make sure they haven't crossed yet swapElements(toSort, beginPtr, endPtr); } } return beginPtr;}void quickSort(int toSort[], int beginPtr, int endPtr){ if (endPtr - beginPtr < 2) { return; } if (endPtr - beginPtr == 2) { // Optimization: array length 2 if (toSort[beginPtr] > toSort[endPtr - 1]) { swapElements(toSort, beginPtr, endPtr - 1); } return; } int splitIndex = partitionElements(toSort, beginPtr, endPtr); quickSort(toSort, beginPtr, splitIndex ); quickSort(toSort, splitIndex, endPtr);}void quickSort(int toSort[], int length){ srand(time(NULL)); quickSort(toSort, 0, length);}void copyArray(int src[], int srcPos, int dest[], int destPos, int toCopyLength){ for (int i = 0; i < toCopyLength; i++) { dest[i + destPos] = src[i + srcPos]; }}void mergeParts(int toSort[], int buffer[], int beginPtr, int middle, int endPtr) { copyArray(toSort, beginPtr, buffer, beginPtr, endPtr - beginPtr); int index1 = beginPtr; int index2 = middle; int resultindex = beginPtr; while (index1 < middle && index2 < endPtr) { if (buffer[index1] < buffer[index2]) { toSort[resultindex++] = buffer[index1++]; } else { toSort[resultindex++] = buffer[index2++]; } } if (index1 < middle) { copyArray(buffer, index1, toSort, resultindex, middle - index1); } if (index2 < endPtr) { copyArray(buffer, index2, toSort, resultindex, endPtr - index2); }}void mergeSort(int toSort[], int buffer[], int beginPtr, int endPtr) { if (beginPtr + 1 < endPtr) { mergeSort(toSort, buffer, beginPtr, (beginPtr + endPtr) / 2); mergeSort(toSort, buffer, (beginPtr + endPtr) / 2, endPtr); mergeParts(toSort, buffer, beginPtr, (beginPtr + endPtr) / 2, endPtr); }}void mergeSort(int toSort[], int length){ mergeSort(toSort, new int[length], 0, length);}Results:...Time taken (nanoseconds): 0...Time taken (nanoseconds): 0...Time taken (nanoseconds): 0...Time taken (nanoseconds): 0NOTE: The results above do not print the correct time taken. Please ignore that fact, and review my code.Questions:Any bad practices? I carry everything from Java, and anything that is different (e.g. System.nanoTime() and std::chrono::high_resolution_clock) I get off SO.Algorithm criticism?Anything that can be done more efficiently and/or with less code? | Quad-sort: 4 sorting methods in one C++ file | c++;beginner;c++11;sorting | This answer is mostly about design and good practice, and not so much about the algorithms themselves. Therefore, I will mostly use mergeSort in the examples.For the sake of completeness: a sorting algorithm with an array + size interface is really C-ish. A proper C++ algorithm would take a pair of iterators and would be templated:template<typename RandomAccessIterator>void mergeSort(RandomAccessIterator first, RandomAccessIterator last);Moreover, most of the standard library that deal with algorithms additionally accept an optional Compare parameter so that you use use something else than operator< to compare two elements. Assuming you have a C++14 compiler, you can use std::less<> as a default:template< typename RandomAccessIterator, typename Compare = std::less<>>void mergeSort(RandomAccessIterator first, RandomAccessIterator last, Compare compare={});Now, lets have a look at the functions that you have reimplemented and that you can already find in the standard library (there is some overlap with other answers):swapElements actually performs std::swap(toSort[i], toSort[j]);, or std::swap(*it1, *it2); if we consider that it1 and it2 are iterators corresponding to toSort + i and toSort + j. Note that we have templated mergeSort so that it can sort any random-access collection of any type. We would like our program to be able to use user-defined swap function instead of std::swap so that it can take advantage of the potential optimizations. We can use argument-dependent lookup to do the job:using std::swap;swap(*it1, *it2);The first line tells the compiler to take std::swap into account for unqualified calls to swap. The second makes an unqualified call to swap: the compiler will check the types of *it1 and *it2 and search for a swap function in their associated namespace. If the lookup finds such a function, it will use it, otherwise it will use std::swap instead. Note that you can also use std::iter_swap which does exactly that:std::iter_swap(it1, it2);partitionElements could probably be replaced by std::partition.You can replace copyArray by std::copy, or std::move if you know that you won't read the elements after they have been moved-from. Note that std::sort from the standard library is required to work with move-only types too, so it would be nice if you could ensure that your sorting algorithms work with such types (agreed, it's not trivial for quicksort).I am pretty sure that mergeParts could be replaced by std::inplace_merge too.So, taking all of that into account, here is how a modern C++ mergesort should look:template<typename RandomAccessIterator, typename Compare>void mergeSort(RandomAccessIterator first, RandomAccessIterator last, Compare compare, std::size_t size) { if (size < 2) return; auto middle = first + size / 2; mergeSort(first, middle, compare, size / 2); mergeSort(middle, last, compare, size - size/2); std::inplace_merge(first, middle, last, compare);}template< typename RandomAccessIterator, typename Compare = std::less<>>void mergeSortImpl(RandomAccessIterator first, RandomAccessIterator last, Compare compare={}){ std::size_t size = last - first; mergeSortImpl(first, last, compare, size);}This is better, bu still not perfect: the agorithm currently works with random-access iterators, which is ok with std::vector, std::deque or std::array, but it also means that it doesn't work with std::list or std::forward_list which respectively expose bidirectional iterators and forward iterators. std::inplace_merge doesn't work with forward iterators (yet?) but it works fine with bidirectional iterators; here is what we have to change to make our mergeSort work with bidirectional iterators:Change iterators subtractions by a call to std::distance.Change the iterator-size addition by std::next.Change the name of the template parameters so that they do not lie.Those simple functions from the header <iterator> work with any category of iterator that is at least forward iterator. That also means that if one day std::inplace_merge works with forward iterators, then mergeSort will also work with forward iterators out-of-the-box and allow to sort, for example, singly linked lists. Here is our new enhanced algorithm:template<typename RandomAccessIterator, typename Compare>void mergeSort(RandomAccessIterator first, RandomAccessIterator last, Compare compare, std::size_t size) { if (size < 2) return; auto middle = std::next(first, size / 2); mergeSort(first, middle, compare, size / 2); mergeSort(middle, last, compare, size - size/2); std::inplace_merge(first, middle, last, compare);}template< typename RandomAccessIterator, typename Compare = std::less<>>void mergeSortImpl(RandomAccessIterator first, RandomAccessIterator last, Compare compare={}){ std::size_t size = std::distance(first, last); mergeSortImpl(first, last, compare, size);}More than an in-depth review of your algorithms, this answer was more about good pratices when writing algorithms. Basically, here is what you should keep in mind:Make your algorithms generic when possible.Iterators are the way to go (even though ranges will enhance things).The standard library can help you.Categories of iterators matter.Custom comparisons are cool (if you give std::greater<> instead of std::less<> to a sorting algorithm, it will sort the collection in reverse order). |
_codereview.84052 | Is there a better way to check if a number is a prime?#include <iostream>#include <math.h>using namespace std;bool doAgain();bool isPrime(int num);int main(){ do { int num = 0; do { cout << Enter a positive integer to check: ; cin >> num; } while(num < 1); if(isPrime(num)) { cout << Prime!!! << endl; } else { cout << Not a prime. << endl; } } while(doAgain()); cout << Bye! << endl;}bool doAgain() { while(true) { cout << Again? (Y/N) ; char again; cin >> again; if(again == 'Y') { return true; } else if(again == 'N') { return false; } }}bool isPrime(int num) { if(num < 2) { return false; } else if(num == 2) { return true; } else if(num % 2 == 0) { return false; } for(int i = 3, max = sqrt(num); i < max; i += 2) { if(num % i == 0) { return false; } } return true;} | Checking if a number is prime | c++;performance;beginner;c++11;primes | Unfortunately, your isPrime function returns incorrect results for the squares of odd numbers.This is a pretty common oversight though, so don't feel too bad.A better implementation of isPrime looks more like this:bool isPrime(int num) { if (num <= 3) { return num > 1; } else if (num % 2 == 0 || num % 3 == 0) { return false; } else { for (int i = 5; i * i <= num; i += 6) { if (num % i == 0 || num % (i + 2) == 0) { return false; } } return true; }}In the first if, we handle the special cases of 0 through 3 as well as all of the negative numbers.In the second, we eliminate all of the multiples of 2 and 3.Finally, in the catch-all else, we're handling everything else.By starting at 5 and incrementing by 6, we're able to skip all of our multiples of 2 and 3 which we already eliminated. So we're checking 2/3rds of the numbers your original implementation checks.Moreover, because we're dealing with integers, i * i <= num is a bit better than i < sqrt(num) (which actually needs to be <=). |
_cs.68250 | Expert systems seem to have been left at the wayside a little bit in the 21st century. In fact, expert-systems was not even a tag on this site (until I just created it). The traditional focus in expert systems has been on rule based systems and logical resolution via, for example, 2-SAT backward chaining. Have there been attempts to integrate modern machine learning with traditional expert systems theory? | Evolving expert systems with machine learning | machine learning;expert systems | null |
_reverseengineering.13209 | I'm trying to get the hang of IDA and I try to reverse engineer some code with a similar code [not 100% the same] to help me, I'm just using it to check.The problem is that I came accros this issue: How could I convert this into a friendlier pointer format ?This blocks me because this is not using the classic BASE+OFFSET format plus it's using two variables...Thank you for your help. | IDA pseudocode: [var*size+ var + offset] to [structure pointer] format | ida | null |
_unix.154023 | I'm messing around with having both /home and /var on a seperate partition which will be mounted in /myhdd.Next, I use mount --bind to mount /var on /myhdd/var and /home on /myhdd/home. With this configuration I am able to successfully install Arch Linux but as soon as I boot to the installed system /var and /home are not mount although /myhdd is.Due to this issue I can't get pacman and more important stuff working. I do get working system if I manually mount all directories, so it looks like fstab problem, so here it is:# /dev/sda1UUID=f192b003-abf9-4e1a-87ee-d187d64423ce / ext4 rw,relatime,data=ordered 0 1# /dev/sda2UUID=b4c5571f-ddb7-440e-b591-759e888b268d /myhdd ext4 rw,relatime,data=ordered 0 2# /mnt/myhdd/home/mnt/myhdd/home /home none bind 0 0# /mnt/myhdd/var/mnt/myhdd/var /var none bind 0 0Any ideas why fstab doesn't mount my /var and /home directories? | bind mount /var with fstab | mount;fstab;bind mount | Your problem:/myhdd ... /mnt/myhdd/... /mnt/myhdd/...It should read either:/mnt/myhddd ... /mnt/myhdd/... /mnt/myhdd/...or.../myhdd ... /myhdd/... /myhdd/... |
_unix.35426 | I recently started using mutt with my gmail IMAP mail address. Because I loved it so much, I also set it up with my college email address.This, sadly, is hosted by the college ICT team under Outlook Webapp, which seems not to adhere to some vary basic standards such as message quoting.On every mail service I've used (not many but hey), a message is quoted using the following method:This is my new message>this is >a quoted message>> this is a >> quoted message inside the quoted messageor something similar. Mutt seems to pick this up and colorize them appropriatly. However, the Outlook Webapp has following qutoing scheme:This is my new message-----Original Message-----From: Foo@BarSubject: FoobarDate: 1st of Foo, 2012 20:18To: Bar@Bazthis is a quoted message-----Original Message-----From: Bar@BazSubject: FoobarDate: 1st of Foo, 2012 20:13To: Foo@Barthis isa quoted message inside the quoted messageIs there a way to tell mutt how to pick this up?Note that when different users have different languages set in the web app this will also reflect in the quoting, eg a Dutch person will have -----Oorspronkelijk bericht----- instead of it's english counterpart, and it will be sent around like that. So there will be some mixing up.It feel saddened by the lack of respect for simple standards like this, because they make life so much harder than it has to be.Note: I have renounced using the outlook webapp, and thus I set up a new gmail account. My outlook webmail get's forwarded to this gmail account and I can reply to it using my normal college email adress from the gmail webapp or mutt. The bad quotin remains a problem though. | Mutt: can I define my own rules for quoted message detection? | quoting;mutt | Well, I could not find any Mutt color like configuration statements that allow to apply color information over multiple lines.Perhaps the easiest way to deal with Outlook message is to setup a filter, e.g. something like:$ awk '/-----Original Message-----/ { level++; } { for (i=0;i<level;++i) printf(>); printf(%s%s, $0,\n); } 'mutt has even a display_filter command:When set, specifies a command used to filter messages. When a message is viewed it is passed as standard input to $display_filter, and the filtered message is read from the standard output.Probably you can make this command conditional (via hooks) - i.e. only execute it when the message has a outlook specific user agent header. Perhaps via the message-hook:This command can be used to execute arbitrary configuration commands before viewing or formatting a message based upon information about the message. command is executed if the pattern matches the message to be displayed. |
_cstheory.8317 | Are there cases where extra publications can hurt your record?This is avoiding the obvious cases where you publish incorrect, or controversial results. Also avoiding the case of finite-time: you only have so much time to think and write, so writing a paper might cause you to lose time on another project. An example use-case might be: you are aiming for a position in theoretical computer science, but often publish in non-theoretical areas which might be under the broader CS canopy or maybe even completely unrelated to CS. On the one hand, this can show broad interests and breadth. On the other hand, this could show a lack of focus, opportunism, or lack of commitment to the field.Can you avoid the problem by simply listing 'selected publications' on your CV that tailors to the specific position, or will the hiring committee always google scholar you? If so, when should you consider not publishing or publishing under pseudonym (or alternative spelling of name)? | When are more publications less? | soft question;advice request;career | At Aaron's suggestion, here is my second comment from the complexity blog, warts and all. Italics are (linked) quotes from earlier comments.I've seen candidates publishing more than 15 papers a year and then a question was asked whether these 15+ papers are good or not....because more often than not, the answer is no. Most of the uncharacteristically long CVs I've seen in hiring committee meetings are chock full of crap. Or they're good in the aggregate, but appear to advance their research in too many incremental steps. Even if there are diamonds in the slurry, I have to askwhy did they publish all that other stuff? Why didn't they make one big splash instead of this long, meager dribble? Did they not notice that most of their papers were weak? Are they publishing so many papers to advance the state of the art, or only to make their CV longer? Are they going to value quantity over quality in their own PhD students? Or am I in fact witnessing a miracle candidate?Despite what Dr. Anonymous two steps above me suggests, these are not irrelevant issues. I don't want my department associated with someone known to publish reams of crap, or who wastes my colleagues' time reviewing tons of incremental papers, or who thinks they're Thor's gift to computer science when they're not, or who tries to convince PhD students that their CVs need to look like the Manhattan Yellow Pages. Those aren't the people I want to work with; that's not the culture I want to work in; that's not (in my opinion) what's best for the Advancement of Knowledge.And notice I said suspicious, not deadly. Of course we read recommendation letters and search citation indices and even (gasp) read the actual papers. Sometimes that's enough to allay my suspicions; yes, there are miracle candidates. But just often enough for me to keep my suspicions, they're proven right.So where exactly does the long CV comes in as a negative, rather than the fact that the person does not have significant contributions?The problem isn't just that they may not have significant contributions, but also that they may have too many not-significant contributions. (See my earlier comment about max vs sum.)Sounds like you guys are rationalizing a case of paper envy, rather than following sound academic decisions.What the hell is paper envy? Result envy or impact envy or reputation envy I could get behind, but paper envy? Really? Since when are papers something to be envious about?Also: Not publicly taking credit for your opinions? Deeply suspicious. |
_softwareengineering.352213 | I have developed a JavaFX 8 application backed by a BaseX database and have got to the stage where it is getting a bit too difficult to add features: so I thought the logical thing would be to break the application into separate layers and would like some confirmation I am heading in the correct direction with this.Fundamentally, I would like to break it down into JavaFX Jars, so that each feature contains it's own FXML, controllers, resources and models.I am using NetBeans 8.2 and am thinking about using Maven to achieve this. I would like to make sure I understand the basics.I want to separate out database access and JAXB parts into one JAR which can be imported as a dependency into the JARs that use it, that way I can create features in isolation specifying the database JAR as a dependency.Is this a sensible approach? | Approach for Breaking JavaFX Application into Jars / Layers | maven;javafx;netbeans | null |
_unix.227369 | I am trying to install debian on my new laptop (lenovo G5O 70) and I get an error on the step choose and install softwares.The installation apears to be stuck on execution of triggers of udev. | Installation fails on choose and install softwares | debian;system installation;debian installer | Unetbooin provided a wrong installation image. I used Rufus and everything works fine. |
_unix.153768 | I am trying to check out code on a Unix box in the Z shell. When I run the following commandsvn checkout https://svn.example.net/svn/trunk/source buildI get the following error message:svn: SSL is not supportedThe error message is in no way informative so I'd like to see if anyone has had a similar problem and even better if they have a solution. Thanks | svn: SSL is not supported | subversion;ssl | null |
_unix.259116 | I want to write a script using a for loop and ssh, to log in several server. After logging in using awk command I want to get 7th column printed as output.I tried the script below but couldn't worked out.I created a list of IP's in /tmp/list.for i in `cat /tmp/list`doecho $iecho ***********ssh $i |grep tsm |awk -F : '{print $7, \t}'echodone | How to write a script to log in multiple server using for loop and ssh? | ssh;awk | pssh makes this much easier, but for your simple use case ssh will also work.While what you have above could have worked, provided the server is set up to run a command and exit on login (which is somewhat unlikely) you probably meant something like this: ssh $i <command> | grep tsm | ...If you really need to check a login banner for tsm, try using the command exit to immediately return back from the ssh rather than starting an interactive shell:ssh $i exit | grep tsm | ... |
_unix.304858 | I wish to run a command which will create a binary file where the length of the file is specified on issuing the command. | Create binary file of specific length | terminal;osx;command | null |
_codereview.119786 | I have my class DBFuntcions containing this 2 methods:The method for the connection to the database:Connection connection_db(String username, String password, String dbname, Connection c) { try { Class.forName(org.postgresql.Driver); c = DriverManager.getConnection(jdbc:postgresql://localhost:5432/ + dbname, username, password); System.out.println(Opened database successfully); } catch (ClassNotFoundException | SQLException e) { System.err.println(e.getClass().getName() + : + e.getMessage() + \n\n\n); } return c;}And the method for the query.void viewAll(String tableName, long startDate, long endDate, Connection c, String path) { String query = SELECT * FROM + tableName + WHERE CAST(receivedtime AS integer) BETWEEN ? AND ? ORDER BY source, receivedtime;; try (PreparedStatement stmt = c.prepareStatement(query)) { //try with resources stmt.setLong(1, startDate); //prepare query stmt.setLong(2, endDate); ResultSet rs = stmt.executeQuery(); try { while (rs.next()) { ... }My question it is the best to open and close the connection? Just before calling the query and closing right after? Opening and closing the connection inside the query method?Or it is better to open it in the main and close it at the end? I think it should depends of the number of time I try to access to it. Let's say for the moment I only have this query and run it only once. | Database Connection and Query methods | java;database | null |
_cs.55386 | For the following finite state machine:The language recognized by it is given to be: $0+(10+11)(0+1)^*$ in my samples book, which I think is clearly wrong, since there's no return path to the final state.I think the language recognized should be just an epsilon or nothing. I wanted to confirm if I am right or wrong with the answer. | Regular expression for a finite automaton appears to be wrong | automata;finite automata;regular expressions | null |
_softwareengineering.138977 | Given a parent entity with a collection of child entities where there must be exactly one primary child of the group?To make the question more concrete, I've seen a number of ways that this pattern might come up -- a group of people where one person is the leader or the contact details for a person where one is primary. Here are two different approaches that I've seen.1. Flag the member as primaryIn this approach, a field is added on the member to designate it as primary. The advantage is that it is simple to implement and avoids additional relationships. The disadvantage is that it is more difficult to enforce in the data model that one and only one member is primary and from an object perspective, potentially puts the responsibility on the child that should be on the parent.2. Additional associationIn this approach the parent tracks the primary member of the group and stores the id of the child. This is in addition to the children storing the id of the parent as a member of the group. This makes it explicit in the data model that there is only one primary member and an index can be added to enforce it. The disadvantage is that it requires two relationships and there is a chance that they can disagree (parent points to a child that doesn't belong to the parent).It seems to me that this is a common pattern and must be documented as a design pattern or model pattern in an architecture book somewhere. A similar pattern might be where the collection is a history and there is one current, but that is a bit easier as each member would have a date range that can be indexed. Are there better approaches? Or can someone point to where this pattern might be documented more formally? | Pattern for group of entities with one required primary member | design patterns;architecture;database design | null |
_webapps.39918 | You can obviously prioritize cards within boards, but is there a way to prioritize cards between boards? For example, if I have 10 boards and 35 cards, instead of having my developer check each board for what is the next priority, is there a way to create a summary prioritization of the 35 cards into one place? | Trello - prioritize cards between boards | trello | null |
_unix.185135 | Is there a way to download forum jpeg image attachments, possibly using Wget or Curl or some other tool? I would like to download jpeg attachments from specific pages on forums. I'm not interested in downloading all forum attachments, but attachments specific to a page in a thread. I also don't want to download attachments one at a time. I want to be able to go to a page on a forum and download all attached images from that page using one command/action.I can retrieve forum attachment urls by using the Firefox Addon Copy All Links:http://forum.sample.com/attachmentshow.php?attachmentid=5332197&d=1391102903http://forum.sample.com/attachmentshow.php?attachmentid=5332198&d=1391102903http://forum.sample.com/attachmentshow.php?attachmentid=5332199&d=1391102903http://forum.sample.com/attachmentshow.php?attachmentid=5683368&d=1407242372But it would be more convenient if I could give Wget or Curl (or some other tool) the url of the forum page, and the command would automatically retrieve the attachment urls and download the images. | Download Forum Attachments | wget;curl;download | null |
_cs.78172 | I have implemented my own CSP solver using a Backtracking algorithm.Within the Backtracking algorithm I apply a Forward Checking algorithm (reducing domains of connected, unnasigned variables) that only works with Binary constraints.The problem I have is that the CSP I try to solve has lots of n-ary constraints, making the FC algorithm mostly redundant. Is there a way to enhance or replace my FC algorithm, so it works with n-ary constraints.Or is there a simple procedure to convert n-ary constraints to binary constraints?EDIT:Added pseudo code (attempt) of the Forward Checking algorithm:function ForwardChecking(variable, csp) list of variables with new domains, or failure for each constraint in connectedConstraints(variable) do if connectedVariable is assigned then if constraint is not satisfied then return failure else for each value in connectedVariable.domain do connectedVariable.assign(value) if constraint is not satisfied do remove value from connectedVariable.domain if connectedVariable.domain.count == 0 then return failure add connectedVariable to solution return solution | CSP Forward checking with n-ary (and binary) constraints | algorithms;satisfiability;sat solvers;constraint satisfaction;constraint programming | null |
_unix.231839 | I tried upgradinfg Fedora 22 to Fedora 23 using this guideHowever things have failed and it seems I am still on Fedora 22. However the system thinks it is running Fedora 24 $ cat /etc/*-releaseFedora release 24 (Rawhide)NAME=FedoraVERSION=24 (Workstation Edition)ID=fedoraVERSION_ID=24PRETTY_NAME=Fedora 24 (Workstation Edition)ANSI_COLOR=0;34CPE_NAME=cpe:/o:fedoraproject:fedora:24HOME_URL=https://fedoraproject.org/BUG_REPORT_URL=https://bugzilla.redhat.com/REDHAT_BUGZILLA_PRODUCT=FedoraREDHAT_BUGZILLA_PRODUCT_VERSION=RawhideREDHAT_SUPPORT_PRODUCT=FedoraREDHAT_SUPPORT_PRODUCT_VERSION=RawhidePRIVACY_POLICY_URL=https://fedoraproject.org/wiki/Legal:PrivacyPolicyVARIANT=Workstation EditionVARIANT_ID=workstationFedora release 24 (Rawhide)Fedora release 24 (Rawhide)and dnf does not work because it searches in the repos for Fedora 24.How can I fix this. | Upgrading Fedora 22 to 23 failed. Now using Fedora 24 | fedora;upgrade;dnf | Try this:For every file /etc/*-release, set the version value to 23.Disable the fedora-rawhide repo (modify the /etc/yum.repo.d/fedora-rawhide.repo by setting enable=0)In a terminal, do dnf distro-syncIf an error is thrown with package during this step and only if the package contains f24 value on the name, do a dnf remove <entier package name>.re-do dnf distro-syncThis solution should result in a valid Fedora 23 installation. |
_unix.207604 | I have an older SSH key that I'm replacing, and I would like ssh-agent to warn me if it used the older key, so I know to update it on that server.Is there a way to do this? | How can I have ssh-agent warn if using a particular key? | ssh;ssh agent | You can make it confirm before using a key with the -c option to ssh-add. From the manpage: -c Indicates that added identities should be subject to confirmation before being used for authentication. Confirmation is performed by the SSH_ASKPASS program mentioned below. Successful confirma tion is signaled by a zero exit status from the SSH_ASKPASS pro gram, rather than text entered into the requester.That's per-key. So you can add one key with -c and the other one without. The default program will ask you to enter your passphrase; but you can just click OK or Cancel (that's what it means by signaled by the exit status). |
_softwareengineering.236571 | Just started learning about classes in C++ and I'm have trouble understanding why object orientated programming (OOP) is useful. I understand the syntax, how to use them etc.But I'm still confused as to why OOP is advantageous. Here are some specifics I'm having trouble with:Private variables. What is the use? Many sources tell me its to prevent outsiders from changing internal variables of the object, to protect the insides. That doesn't make sense to me because wouldn't someone who wanted to change the variable just call the setter (mutator) functions and change it? Anyone can open the source file and call the setter and change the value of the variable. How is that protection? It's also mentioned that it makes debugging easier because instead of looking for every instance of the variable x, you know x is only accessible through the class. So instead of ctrl+F x you just ctrl+F memberFunction?? How does that make debugging easier?I read somewhere that using getters and setters is bad. Although sometimes unavoidable, its generally bad. I read Don't ask for the information you need to do the work; ask the object that has the information to do the work for you. Can someone explain why this is important?The big picture. I don't understand why implementing objects is more efficient than just if-statements and function calls....when there are functions in objects too. Objects don't seem to save tons of time in terms of coding. What am I missing? | Understanding object-oriented programming: why is it important? | java;c++;object oriented | Perhaps an example can help explaining the benefits of object oriented programming.Consider a linked list, it consist of node structures containing some data and pointing to other nodes:struct Node { Node* next; int data;}Assume a list of these (I named them for convenience):Node c{null, 4};Node b{&c, 73};Node a{&b, 42};Node* list = &a;You can use this list as follows:std::cout << list->data; // prints 42std::cout << list->next->data; // prints 4All is fine here, but imagine somewhere in your program the following happens:Node d{&a, 17};list->next->next = &d;Now the list is messed up, it is: [a, b, d, a, b, d, ]; node c is lost and the list has become an endless repetition.1aTo answer the first part of part 1 of your question, when Node::next is private the problematic assignment list->next->next = &d; can not happen.1b & 2Given a public setter:void Node::setNext(Node* new_next) { this->next = new_next; }As you say, then anyone can just use list->next->setNext(&d);. This leads to the answer to part two of your question: having a setter setNext() is bad. Lists should have modifying operations like insert(value), append(value), and remove(value).This is an example of the general rule: classes should have operations that fit their intended meaning and use, not getters and setters for every field the implementation happens to have. Or the version you read: Don't ask for the information you need to do the work; ask the object that has the information to do the work for you.3Your question, I don't understand why implementing objects is more efficient than just if-statements and function calls, is a difficult one. First the word 'efficient' can have two meanings:the programs run faster and/or consume less resourceswriting a program takes less effortFor the first point running faster or consuming less resources, both object oriented programs and programs using if-statements and function calls can be efficient in this sense or very inefficient. For some problems thinking about them in an object oriented manner, leads to a more elegant and efficient solution than the if-statements and function calls approach. For other problems object oriented programming just gets in the way and causes overhead.On the second interpretation of 'efficient': writing a program takes less effort.As @JB_King states object orientation helps to organize things that belong together.Once you have the list class, in other parts of the code you can think in terms of maintaining a list of 'x'es and sending a list of 'y's, instead of pointer manipulations. In addition when you look at the C++ standard library, the java runtime library, Boost Collection, Commons collections, Google guava, and others you'll find that others have already written List classes and that perhaps for your programming problem a list is not the best class but some other kind of collection.So once you have (or someone else has) written a class you can reuse it and you do not have to write it again.NOTE: of course the same holds for good libraries of functions, my answer is lacking a good explanation of why object oriented is better reusable than functional libraries.Elaborations and side nodesEven if you decide that this list class really does require a setNext()-method, then the method can have advantages over directly manipulating the Node::next-field. The method can perform extra checks; e.g.:Node:setNext(Node* newNext) { if (this->next == null) { this->next = newNext; } else { throw new Error(); } }Making fields private does not prevent malicious programmers/code from reading and manipulating the field; i.e.class SecurityController {private: std::string secretPassword;};andstruct SecurityController2 { std::string secretPassword;}are both equally (in)secure.Declaring things private (and other methods of hiding implementation details) only helps well behaving programmers to create better code.InitializationSometimes initializing an object is the only time that direct access to an object's fields is required. Then you can define a constructor that accepts and sets the field, e.g.:Node::Node(int value_) { this->value = value_;}However, often there are better constructors that do not require the caller providing values. For example:List::List() { }to construct an empty List, andList::List(std::iterator<int> start, std::iterator<int> end) { }to create a list containing copies of the values from the C++ STL range [start, end>. |
_unix.203106 | I have a zte 3g modem. I use carrier provided dialer for connection establishment. Once the ppp connection is active, i would like to send some AT commands(for ex. Query signal strength, AT+CSQ). But the dialer i use locks the /dev/ttyUSB0 port, which is the command port to send AT commands for my modem. So is there any way, to send the commands, once the connection is active?Edit: I also tried the additional port /dev/ttyUSB1. But the port is flowing with random data from the modem. A sample is given below.T^PREFMODE?? ^PREFMODE:8 OK TC ^DSDORMANT:1 +CSQ:19, 99 OK T^SYSINFO ^SYSINFO:2,3,0,4,255 OK TT^SYSINFO? ^SYSINFO:2,3,0,4,255 I tried adding my commands, i even got output. But the response is very poor. Most of the times, my AT commands went unnoticed. | How to send AT commands to modem once the connection is established? | linux;networking;serial port;modem;ppp | As long as the device is used for ppp traffic, it is not possible to run AT commands at the same time1.For this reason all modern modems will provide more than one serial interfaces, e.g. /dev/ttyUSB0 and /dev/ttyUSB1 (or /dev/ttyACM0 and /dev/ttyACM1 for USB CDC modems on linux).Back in the days when phones had RS-232 compatible connectors (perhaps with additional IrDA), 3GPP standardized a multiplexing protocol as 07.10 to overcome the physical limitation, although that required special drivers on the PC so it never took off. Today with USB's inherent multiplexing capabilities, there are no excuses for not providing multiple serial interfaces (usually there are only two though).So as already mentioned in a comment, you should use the other serial device, e.g. /dev/ttyUSB1.1 In theory it might be possible for the modem to support +++ escaping which would then allow you to run AT commands while the connection was ongoing, although then you would have to in some way modify the dialer program to inject those and extract the response... |
_softwareengineering.334877 | Im going to make a program that build SQL like queries based on settings.Basically you have queries that are in an initial state and based on these settings the queries will at application start be built to fit the settings stored in what ever format.So a method takes in the queries and return new queries based on settings.I need some help on how these settings are stored. What is typical? to store settings in a file(ini, conf) or in a SQL DB? | How are typical settings stored in a program? | settings | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.