id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_webapps.16762 | Possible Duplicate:How do I download a YouTube video? Im looking for an app, which downloads the playlist videos one after another from youtube.For example in the webpage top documentary flims for story of science, the youtube video has 36 video in a playlist. I would like an app to download all the 36 video automatically. | Downloading youtube playlist | youtube;download | null |
_codereview.19274 | I'm currently clearing my console window with this piece of code:void clrScr(){ COORD cMap = { 0, 3 }; if(!FillConsoleOutputAttribute(hCon, 0, 2030, cMap, &count)) { std::cout << Error clearing the console screen. << std::endl; std::cout << Error code: << GetLastError() << std::endl; std::cin.get(); }}, which I call once in the main loop.But since my window is quite large (70x35), it's flickering quite a bit.I was wondering if there are any faster methods of doing this? | Is there a faster way to clear the screen? | c++;optimization;performance;console | I decided that the best way to clear the screen - at least for a text-based game in console - is to clear literally only the individual squares that need to be cleared, instead of the whole window. |
_softwareengineering.272757 | At the moment I am using one repository for project with the following default structure:project - trunk - docs - branches - tagsI would like to know if is a good practice store the docs outside trunk folder example:project - docs - trunk - branches - tags | Where should documentation files be saved in SVN? | svn | The (dis-)advantages of having your documentation inside the trunk of the repository depends on a number of factors. Some of the more important ones are:Your branching strategyHow comparable the documentation lifecycle and the software lifecycle areYour workflow for keeping the documentation up-to-date and the format of your documentationIf you create a new tag/branch for each release and the documentation gets released in tandem with the code, keeping the documentation inside the trunk has the advantage that it becomes easy to find the documentation that goes with a particular past release, as the documentation gets copied to the tag/branch together with the sources.On the other hand, if your documents are released on a different cycle than the code (for example, the code gets tagged and released daily, but the documentation only once every 3 weeks), then there is no advantage to having the documentation inside trunk, as most software releases will then contain unreleased (and probably incomplete) documentation.As a final possibility, if you regularly work on feature branches (and you are in the habit of updating the documentation as you write the code), then keeping binary documentation files inside trunk can cause you a lot of merge grief when merging the branch back to trunk. It should be noted that the fileformats used by the major wordprocessors are all binary (either proprietary or compressed XML). |
_unix.41456 | I want to kill a process, after finding the id in a single step.I currently use these two commands:pidof <name>kill <#number_which_is_result_of_command>How can I write a single command to do this? | How to kill a process with a single command? | command line;process;kill | null |
_webapps.17425 | How can I stop the YouTube player from showing related video thumbnails and links?I am in search of YouTube video code that shows only the videos in our YouTube stream, i.e., only the videos we have uploaded. | How to stop YouTube player from showing related videos? | youtube;video | null |
_codereview.75397 | I implemented sequenceA:sequenceA :: Applicative f => [f a] -> f [a]sequenceA [] = pure []sequenceA (x:xs) = (++) <$> (fmap (\y -> [y]) x) <*> sequenceA xsI don't like the fact that I'm making a new list, and then concatenating the result via ++.However, I'm not sure how to make use of cons, i.e. :, in this function.Please critique it. | Implementing `sequenceA` | haskell;reinventing the wheel | null |
_softwareengineering.259919 | I'm working on a document processing system.I feel confident with a Document class which represents each document being processed.The issue:Each Document can have a CoverSheet, and if it does, we need to get CoverSheetInfo from this CoverSheet (for renaming and processing). But checking for a CoverSheet and coercing the info into CoverSheetInfo involves a fair amount of Apache PDFBox code.I'm trying to decide on the best place to have this functionality.Option 1Document class will have these methods:public boolean hasCoverSheet()public CoverSheetInfo getCoverSheetInfo()Pros:Behavior is close to the data -- the process of checking a Document for a CoverSheet takes place in Document which seems sensible.Cons:This adds a lot of PDFBox - related parsing lines which make the other-wise simple set-get Document look cluttered and makes the Document class exceed 300 lines to include this functionality. Thus Option 2...Option 2Create a DocumentParser class which would have:public boolean hasCoverSheet(Document document)public CoverSheetInfo getCoverSheetInfo(Document document)Pros:All the PDFBox - specific parsing code is in it's own Class. I think this is a good example of enforcing Single Responsibility/Law of Demeter As I don't think Document should necessarily know how to parse information from cover sheets.Cons:Awkward(?) separation of behavior from data(?)Which one seems most reasonable and how so?Edit: I'm desperate. Any feed back would be absolutely. fricken. loved.Edit 2A Document is in this case a scanned mortgage document, and it will always be a PDF. A Document is created when my app finds files in a directory (one Document is made for each file found). DocumentParser should process Documents, right, File was a typo.At this point, Document is just a wrapper around the File essentially. In Option 1, it would have CoverSheetInfo as a field and File stubFile as well as boolean regarding the existence of these things.Here's the story for what I'm doing:Someone will scan a document. It will end up in a directory. My app needs to look at that directory, and rename the files by their cover sheet (if they have one) make a stub out of the first 8 pages (if the file is very large) Upload these files (and any stubs made) to Google Drive. | Design - Parser.hasInfo(MyClass) vs MyClass.hasInfo() | java;design;class design | As far as I understood, the cover page is an important property of a document in your application. Then I'd represent it with a getter. The business classes dealing with renaming the document then only need the Document object and have no dependency to a parser which they do not care about. How that getter is implemented is a different question. You could for example provide a mock implementation that provides a pre-defined cover page for unit testing. To solve the problem of a long class with multiple responsibilities, you could extract the parsing code to a separate class that is used by the real Document implementation.To go one step further, the parser instance could be provided to the Document constructor. That's called dependency injection and decoples the parser from the document, so that other parsers could be used. For exapmle, the unit test of Document can use a mock implementation of the parser. There are frameworks like weld which essentially provide a factory to create classes without knowing the exact dependency (i.e. the parser). |
_codereview.6304 | I'm trying to convert from random bytes to integers within a range. Basically converting as such:byte[] GetRandomBytes(int count) -> int NextInteger(int min, int max)Another way to think about it would be: I have a RNGCryptoServiceProvider but would rather have the interface to Random.My current algorithm works out how many bits it needs based on min and max, gets a random int (after masking off any bits it doesn't need), then loops until it gets a number less than max - min.Question 1: Is my algorithm sound? Question 1a: Is the below implementation sound (c#) (specifically: RandomSourceBase.Next(int, int))?using System;using System.Collections.Generic;using System.Security.Cryptography;namespace ConsoleApplication1{ public abstract class RandomSourceBase { public abstract byte[] GetRandomBytes(int numberOfBytes); public int Next() { return Next(0, Int32.MaxValue); } public int Next(int maxValue) { return Next(0, maxValue); } public int Next(int minValue, int maxValue) { if (minValue < 0) throw new ArgumentOutOfRangeException(minValue, minValue, MinValue must be greater than or equal to zero.); if (maxValue <= minValue) throw new ArgumentOutOfRangeException(maxValue, maxValue, MaxValue must be greater than minValue.); int range = maxValue - minValue; if (range == 1) // Trivial case. return minValue; // Determine how many bits are required for the range requested. int bitsRequired = (int)Math.Ceiling(Math.Log(range, 2) + 1); int bitmask = (1 << bitsRequired) - 1; // Loop until we get a number within the range. int result = -1; while (result < 0 || result > range - 1) { var bytes = this.GetRandomBytes(4); result = (Math.Abs(BitConverter.ToInt32(bytes, 0)) & bitmask) - 1; } return result + minValue; } } public class CryptoRandomSource : RandomSourceBase { private RNGCryptoServiceProvider _RandomProvider; public CryptoRandomSource() { this._RandomProvider = new RNGCryptoServiceProvider(); } public override byte[] GetRandomBytes(int numberOfBytes) { var result = new byte[numberOfBytes]; this._RandomProvider.GetBytes(result); return result; } } class Program { static void Main(string[] args) { TestNextInt32(new CryptoRandomSource(), 50); TestNextInt32(new CryptoRandomSource(), 64); Console.ReadLine(); } private static void TestNextInt32(RandomSourceBase randomness, int max) { var distributionTable = new Dictionary<int, int>(); for (int i = 0; i < max; i++) distributionTable.Add(i, 0); Console.WriteLine(Testing CryptoRandomStream.Next({0})..., max); int trials = max * 50000; for (int i = 0; i < trials; i++) { var choice = randomness.Next(max); distributionTable[choice] = distributionTable[choice] + 1; } for (int i = 0; i < max; i++) Console.WriteLine({0}, {1}, i, distributionTable[i]); Console.WriteLine(); } }}Question 2: Assuming GetRandomBytes is actually random, will my algorithm / implementation also be random (specifically a uniform distribution?).I've done a few test runs and graphed the distribution in Excel. They look random-ish to me. But, well, I'm no security expert, and the stats course I did was in 2003 and my memory isn't very good! Specifically, I don't know if the variation of up to 800 or ~1.6% (point #3 on the 50 graph) is acceptable or if I've done something horribly wrong.(Note, the Y axis isn't zeroed. 50,000 is the desired number).Context: I'm building a plugin for KeePass and its RNG returns a byte[] but most of my logic is tied up in choosing indexes from a collection, hence my need to convert random bytes to random ints within a range. Actual real life code (for those who are interested):http://readablepassphrase.codeplex.com/SourceControl/changeset/changes/aa085616bc23Relevant code located in: trunk/ReadablePassphrase/Random | Algorithm to convert random bytes to integers | c#;random | Yes, the algorithm as described is sound, although not the most efficient use of the random number source. However, there are a few surprises in the code. Making the default Next() capable of returning 2^31 - 1 distinct values is a bit unexpected, and slightly skews the distribution of the lower bits. It might be worth changing the names, too, in case you want to add more output types later. I would adjust as follows: public int NextInt32() { byte[] bytes = GetRandomBytes(4); int i = BitConverter.ToInt32(bytes); return i & Int32.MaxValue; } public int NextInt32(int maxExcl) { if (maxExcl <= 0) throw new ArgumentOutOfRangeException(maxExcl, maxExcl, maxExcl must be positive); // Let k = (Int32.MaxValue + 1) % maxExcl // Then we want to exclude the top k values in order to get a uniform distribution // You can do the calculations using uints if you prefer to only have one % int k = ((Int32.MaxValue % maxExcl) + 1) % maxExcl; while (true) { int rnd = NextInt32(); if (rnd <= Int32.MaxValue - k) return rnd % maxExcl; } } public int NextInt32(int minIncl, int maxExcl) { if (minIncl < 0) throw new ArgumentOutOfRangeException(minIncl, minIncl, minValue must be non-negative); if (maxExcl <= minIncl) throw new ArgumentOutOfRangeException(maxExcl, maxExcl, maxExcl must be greater than minIncl); return minIncl + NextInt32(maxExcl - minIncl); } |
_webapps.104469 | My project data doesn't easily lend itself to filters that will bring the row count under 100,000 for case export.What are my options to get around this issue?Are there ways download case data without going through the export case interface? | What are my options for getting around the 100,000 maximum row limit for case export? | commcare | For now the best way to get around this is to use filters.Date Range - You can use date ranges to select smaller chunks of data. These dates are based on the last time the case was modified (see Does the date filter for a CommCare case export filter forms by last modified date or opened date?)Use reporting groups - You can further break down your case data by only downloading cases for a set of users, groups, or organizations. (For example, if your cases are evenly distributed amongst your users, you can put them in two separate groups which will halve the number of rows downloaded).If all of that still doesn't work for you, and you have technical capacity, you can look into using the commcare-export tool |
_unix.296870 | I want to grep tag value of and if its 01 it must print another tag and along with its value .Sample XML file :<CustName>Unix</CustName><CustomerId>999</CustomerId><dept>developer</dept><account>01</account>Desired output :If value of account is 01 it must print the below along with total count of occurance of 01 value in account tag:<CustName>Unix</CustName><CustomerId>999</CustomerId><account>01</account>count :1What i have tried :grep -oP '(?<=<<c>account>).*(?=<<c>/account)' cust.xml01grep -C 10 -oP '(?<=<<c>account>).*(?=<<c>/account)' cust.xml-C 10 will print 10 line above and below but it did not work . | how to grep a tag value in xml file and print another two tag values in same xml file | grep;xml | null |
_unix.250379 | This is my first post on this particular SE site, but I have used the wisdom, shared here, more than once. Using this opportunity, I'd like to thank everyone on this site and Stack Exchange, in general, and wish all a great holiday season and a happy and healthy New Year!Now, on to the question. The situation is as follows. Currently I have a need to be able to access my work desktop PC remotely. Usually, that involves using ssh via my employer's VPN tunnel. However, I today I have discovered that the Ethernet outlet, which my PC is assigned to (due to the enterprise VLAN setup), is malfunctioning and there is no way it could be fixed soon (due to holidays). However, I have some quite urgent work that requires me to use this machine, including remotely. After trying to alleviate the outlet issue to no avail, I have decided that a feasible alternative would be to just use my employer's wireless network, where normally people, myself including, authenticate via LDAP/AD username and password (AFAIK, it is conformant to 802.1x). I was about to buy a USB wireless network adapter, but my colleague kindly lended me one that he doesn't need at the moment. I have enthusiastically attached the adapter to my PC just to find out that my current kernel on Debian doesn't support this adapter (TP-LINK TL-WN725N). It is supported in newer kernels, however, since I have to use this particular kernel (2.6.32-openvz-042stab112.15-amd64) due to some specific software dependencies, the problem has remained. My further step was to determine that the manufacturer provides Linux driver, which has to be compiled for this kernel in order to be installed. Following instructions in TP-LINK's included documentation, I have tried to compile the driver, but the process failed.[SIDE NOTE: The reason it failed likely deserves a separate question and I actually have seen similar questions, but most advice out there implies that a PC has Internet access and, thus, can easily install all dependencies for the build. Since my PC (Debian side) so far cannot be connected to the Net, I tried to download relevant packages to my laptop and install them from there. The main problem was the lack of the build directory under /lib/modules/$(KVER)/build. I installed both kernel headers package and other dependencies, such as relevant version on gcc, etc., but the error still remained. Perhaps, I should have tried these instructions for the adapter's generic driver for this chipset, but I thought that the lack of build directory will fail that attempt, too.]Therefore, now I think that I have three options:Find and buy a USB wireless network adapter, which is old enough to have a driver for in my 2.6.32 kernel (using this handy list).Figure out why, despite installing kernel headers package and other dependencies (perhaps, I missed some, but I can't use apt-get), I cannot build the TP-LINK's driver (and, likely, the generic rtl8188eu).Buy an inexpensive (but good!) portable USB wireless router (such as TP-LINK TL-WR802N) or regular wireless router (such as TP-LINK TL-WR841N), supporting so called client operating mode, so that I could connect my PC to my wireless network at work. This would be the easiest route, especially since I have found this nice page from Ubuntu documentation, which I hope is quite applicable to my Debian 7.9. However, after some review, it is still not clear whether TL-WR802N supports 802.1x or not and, similarly, whether TL-WR841N supports 802.1x or not. It is certainly possible to achieve my goal, using open source firmware, such as OpenWRT, on one of those TP-LINK devices, but it seems to me like an overkill.My apologies for the lengthy post, but I felt that decent answers will require describing the situation with high enough level of detail. Thank you for your attention. Your help will be greatly appreciated. | Setting up wireless on a Debian 7.9 (with older kernel) and connecting to it via 802.1x | debian;wifi;802.1x | null |
_softwareengineering.219156 | My P2P app needs to locate peers, but I don't want to hard-code a DNS address... One example I've seen is bootstrapping via IRC, but I'd like to do this over HTTP/s if possible.What are my options and techniques for bootstrapping a P2P app? | How do I bootstrap a P2P service so that users can locate each other? | c#;architecture;p2p | null |
_unix.72427 | I am trying to set up vim for writing email. I have a plugin to provide autocompletion of email addresses (notmuch abook ). If I do :set completefunc it tells me it is CompleteAddressBook as expected.However, when I hit Tab I get what appear to be spelling suggestions from a word dictionary. I do have spell set, but I'm confused as to how to get past spell to get completefunc used.You can see my vimrc in case there is something weird in there.Ideas for debugging steps welcome. | Why is vim offering me spelling suggestions instead of using the completefunc? | vim;autocomplete | It turned out that rather than using Tab I had to use Ctrlx CtrluSee the compl-function docs for more. |
_cs.66772 | When reasoning with NP-completeness, I find SAT and k-clique more convenient to reason with than generalized games that are NP-complete or the Turing machine model. I'm looking for something similar for EXPTIME-completeness. Wikipedia mentions:Another set of important EXPTIME-complete problems relates to succinct circuits. Succinct circuits are simple machines used to describe some graphs in exponentially less space. They accept two vertex numbers as input and output whether there is an edge between them. For many natural P-complete graph problems, where the graph is expressed in a natural representation such as an adjacency matrix, solving the same problem on a succinct circuit representation is EXPTIME-complete, because the input is exponentially smaller; but this requires nontrivial proof, since succinct circuits can only describe a subclass of graphs.[8]8: Papadimitriou (1994), section 20.1, page 492.I understand the concept that you can describe some graphs using exponentially less space and use that as input, but I can't find the mentioned resource or find out how succinct graphs work exactly or how to construct an EXPTIME-complete problem. | How to use succinct circuits to construct an EXPTIME complete problem? | complexity theory;graphs;time complexity;complexity classes | null |
_unix.177593 | I am creating a script that will ssh to a host and print all the user accounts and when they will expire.On a host I can run awk -F':' '{ print $1}' /etc/passwd and it will give me a list of all user accounts.I have added this to a script that should go to a server, create this list and use it to print when it will expie.#!/bin/bashfor i in `cat /admin/lists/testlist`do echo $i UNAME=`su - admin -c ssh $i uname` if test $UNAME = Linux then LIST=`su - admin -c ssh $i awk -F':' '{ print $1}' /etc/passwd` for j in $LIST do echo $j ; `su - batch -c ssh $i sudo chage -l $j | grep Account` done else echo Exiting. The OS type is not found. fi echo ======================================================================== echo doneexit 0The issue I am having is when I run the script I get the following error.[admin@testserver bin]$ sudo checkPasswdExpiration.shtestserver02awk: cmd. line:1: {awk: cmd. line:1: ^ unexpected newline or end of string========================================================================Why does the awk command not work in this script? | awk in ssh in su in a command substitution | bash;shell script;ssh;awk;quoting | The first set of quotes is eaten up by the command line for su, and the second set by the command line for ssh, so that the quoted { print $1} is actually seen as three separate arguments by awk. Escape the quotes (and $, and any other special character you may use):su - admin -c ssh $i awk -F: \'{ print \$1}\' /etc/passwdOr:su - admin -c ssh $i getent passwd | awk -F: '{print $1}' |
_webmaster.34477 | I'm going to add a news page to my website which will include short snippets from other copyrighted sources, I'm going to only mention the title and maybe a short descriptions and link them to the source.But I'm not sure how many words I'm allowed to use for each snippet on my website? also consider that it's going to be exact copy/paste. | How much is not too much? using snippets from other copyrighted sources | legal;copyright | Getting hit for duplicate content shouldn't be his primary concern. It should be who the copyright holders are.This is a question of fair use and should be answered by lawyers (unfortunately). |
_cstheory.12666 | Title pretty much explains the question. E.g. http://en.wikipedia.org/wiki/Selection_algorithm#Linear_general_selection_algorithm_-_Median_of_Medians_algorithmShould there in theory also be an algorithm with guaranteed runtime that is also linear? Not looking for a response to this specific case necessarily, but more generally.Thanks all. | For a given algorithm with expected runtime M, does there exist (in theory) an algorithm with equivalent guaranteed runtime? | cc.complexity theory | No. See Chapter 2 of the book Randomized Algorithms by Motwani and Raghavan. They discuss a tree-evaluation problem for which:any deterministic algorithm takes linear time;there is a Las Vegas randomized algorithm with sublinear expected running time. |
_softwareengineering.171671 | I recently found a framework named ecto.In this framework, a basic component named plasm, which is the ecto Directed Acyclic Graph.In ecto, plasm can be operated by ecto scheduler. I am wondering what's the advantage of this mechanism, and in what other situations can we exploit the concept of DAG? | When to use DAG (Directed Acyclic Graph) in programming? | algorithms;data structures;frameworks;graph | Nice Question. Code may be represented by a DAG describing theinputs and outputs of each of the arithmetic operations performedwithin the code; this representation allows the compiler to performcommon subexpression elimination efficiently.Most Source Control Management Systems implement the revisions as aDAG.Several Programming languages describe systems of values that arerelated to each other by a directed acyclic graph. When one valuechanges, its successors are recalculated; each value is evaluated asa function of its predecessors in the DAG.DAG are handy in detecting deadlocks as they illustrate thedependencies amongst a set of processes and resources.In many randomized algorithms in computational geometry, thealgorithm maintains a history DAG representing features of somegeometric construction that have been replaced by later finer-scalefeatures; point location queries may be answered, as for the abovetwo data structures, by following paths in this DAG.Once we have the DAG in memory, we can write algorithms tocalculate the maximum execution time of the entire set.While programming spreadsheet systems, the dependency graph thatconnects one cell to another if the first cell stores a formula thatuses the value in the second cell must be a directed acyclic graph.Cycles of dependencies are disallowed because they cause the cellsinvolved in the cycle to not have a well-defined value. Additionally,requiring the dependencies to be acyclic allows a topological orderto be used to schedule the recalculations of cell values when thespreadsheet is changed.Using DAG we can write algorithms to evaluate the computations inthe correct order.EDIT :Ordering of formula cell evaluation when recomputing formula valuesin spreadsheets can be done using DAGsGit uses DAGs for content storage, reference pointers for heads,object model representation, and remote protocol.DAGs is used at Trace scheduling: the first practical approach forglobal scheduling, trace scheduling tries to optimize the controlflow path that is executed most often.Ecto is a processing framework and it uses DAG to model processinggraphs so that the graphs do ordered synchronous execution. Plasm inEcto is the DAG and Scheduler operates on it.DAGs is used at software pipelining, which is a technique used tooptimize loops, in a manner that parallels hardware pipelining.Good Resources :http://www.biomedcentral.com/1471-2288/8/70http://www.ncbi.nlm.nih.gov/pubmed/12453109http://www.ericsink.com/vcbe/html/directed_acyclic_graphs.htmlhttp://xlinux.nist.gov/dads/HTML/directAcycGraph.html |
_unix.94357 | What command(s) can one use to find out the current working directory (CWD) of a running process? These would be commands you could use externally from the process. | Find out current working directory of a running process? | shell;command line;process;cwd | There are 3 methods that I'm aware of:pwdx$ pwdx <PID>lsof$ lsof -p <PID> | grep cwd/proc$ readlink -e /proc/<PID>/cwdExamplesSay we have this process.$ pgrep nautilus12136Then if we use pwdx:$ pwdx 1213612136: /home/samlOr you can use lsof:$ lsof -p 12136 | grep cwdnautilus 12136 saml cwd DIR 253,2 32768 10354689 /home/samlOr you can poke directly into the /proc:$ readlink -e /proc/12136/cwd//home/saml |
_unix.178970 | I tried modifying my ~/.ssh/config file to allow automatic fast X forwarding as per this sitehttp://xmodulo.com/how-to-speed-up-x11-forwarding-in-ssh.htmlI then tried logging into a server and running xeyes just to see if things were working. They weren't. It seems to me like nothing is reading the config file.These sites suggest the permissions of home should be 755 or less; .ssh should be 755 or less; config 644 or less. The permissions I am using then are 750 (home), 700 (.ssh) and 644 (config). Still nothing. Any ideas?Edit1: As requested in the comments.ssh -vvv -F ~/.ssh/config [email protected] generates the following outputOpenSSH_6.6.1, OpenSSL 1.0.1f 6 Jan 2014debug1: Reading configuration data /home/ohnoplus/.ssh/configdebug3: ciphers ok: [blowfish-cbc,arcfour]debug2: ssh_connect: needpriv 0debug1: Connecting to HOST [IP] port 22.debug1: Connection established.debug1: identity file /home/ohnoplus/.ssh/id_rsa type -1debug1: identity file /home/ohnoplus/.ssh/id_rsa-cert type -1debug1: identity file /home/ohnoplus/.ssh/id_dsa type -1debug1: identity file /home/ohnoplus/.ssh/id_dsa-cert type -1debug1: identity file /home/ohnoplus/.ssh/id_ecdsa type -1debug1: identity file /home/ohnoplus/.ssh/id_ecdsa-cert type -1debug1: identity file /home/ohnoplus/.ssh/id_ed25519 type -1debug1: identity file /home/ohnoplus/.ssh/id_ed25519-cert type -1debug1: Enabling compatibility mode for protocol 2.0debug1: Local version string SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2debug1: Remote protocol version 2.0, remote software version OpenSSH_5.3debug1: match: OpenSSH_5.3 pat OpenSSH_5* compat 0x0c000000debug2: fd 3 setting O_NONBLOCKdebug3: load_hostkeys: loading entries for host HOST from file /home/ohnoplus/.ssh/known_hostsdebug3: load_hostkeys: found key type RSA in file /home/ohnoplus/.ssh/known_hosts:1debug3: load_hostkeys: loaded 1 keysdebug3: order_hostkeyalgs: prefer hostkeyalgs: [email protected],[email protected],ssh-rsadebug1: SSH2_MSG_KEXINIT sentdebug1: SSH2_MSG_KEXINIT received---kex_parse_kexinit lines removed---debug2: mac_setup: setup hmac-md5debug1: kex: server->client aes128-ctr hmac-md5 nonedebug2: mac_setup: setup hmac-md5debug1: kex: client->server aes128-ctr hmac-md5 nonedebug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<3072<8192) sentdebug1: expecting SSH2_MSG_KEX_DH_GEX_GROUPdebug2: bits set: 1558/3072debug1: SSH2_MSG_KEX_DH_GEX_INIT sentdebug1: expecting SSH2_MSG_KEX_DH_GEX_REPLYdebug1: Server host key: RSA redacteddebug3: load_hostkeys: loading entries for host redactedhost.edu from file /home/ohnoplus/.ssh/known_hostsdebug3: load_hostkeys: found key type RSA in file /home/ohnoplus/.ssh/known_hosts:1debug3: load_hostkeys: loaded 1 keysdebug3: load_hostkeys: loading entries for host redactedip from file /home/ohnoplus/.ssh/known_hostsdebug3: load_hostkeys: found key type RSA in file /home/ohnoplus/.ssh/known_hosts:2debug3: load_hostkeys: loaded 1 keysdebug1: Host 'redactedhost.edu' is known and matches the RSA host key.debug1: Found key in /home/ohnoplus/.ssh/known_hosts:1debug2: bits set: 1531/3072debug1: ssh_rsa_verify: signature correctdebug2: kex_derive_keysdebug2: set_newkeys: mode 1debug1: SSH2_MSG_NEWKEYS sentdebug1: expecting SSH2_MSG_NEWKEYSdebug2: set_newkeys: mode 0debug1: SSH2_MSG_NEWKEYS receiveddebug1: Roaming not allowed by serverdebug1: SSH2_MSG_SERVICE_REQUEST sentdebug2: service_accept: ssh-userauthdebug1: SSH2_MSG_SERVICE_ACCEPT receiveddebug2: key: ohnoplus@winterrain (0x7fab75e63000),debug2: key: /home/ohnoplus/.ssh/id_rsa ((nil)),debug2: key: /home/ohnoplus/.ssh/id_dsa ((nil)),debug2: key: /home/ohnoplus/.ssh/id_ecdsa ((nil)),debug2: key: /home/ohnoplus/.ssh/id_ed25519 ((nil)),debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,passworddebug3: start over, passed a different list publickey,gssapi-keyex,gssapi-with-mic,passworddebug3: preferred publickey,keyboard-interactive,passworddebug3: authmethod_lookup publickeydebug3: remaining preferred: keyboard-interactive,passworddebug3: authmethod_is_enabled publickeydebug1: Next authentication method: publickeydebug1: Offering RSA public key: ohnoplus@host1debug3: send_pubkey_testdebug2: we sent a publickey packet, wait for replydebug1: Server accepts key: pkalg ssh-rsa blen 279debug2: input_userauth_pk_ok: fp 61:79:08:... redacteddebug3: sign_and_send_pubkey: RSA 61:79:08:... redacteddebug1: Authentication succeeded (publickey).Authenticated to redactedhost.edu ([redactedip]:22).debug1: channel 0: new [client-session]debug3: ssh_session2_open: channel_new: 0debug2: channel 0: send opendebug1: Requesting [email protected]: Entering interactive session.debug2: callback startdebug2: fd 3 setting TCP_NODELAYdebug3: packet_set_tos: set IP_TOS 0x10debug2: client_session2_setup: id 0debug2: channel 0: request pty-req confirm 1debug2: channel 0: request shell confirm 1debug2: callback donedebug2: channel 0: open confirm rwindow 0 rmax 32768debug2: channel_input_status_confirm: type 99 id 0debug2: PTY allocation request accepted on channel 0debug2: channel 0: rcvd adjust 2097152debug2: channel_input_status_confirm: type 99 id 0debug2: shell request accepted on channel 0Last login: Wed Jan 14 10:54:32 2015 from redacted | ssh not using ~/.ssh/config, even after I play around with permissions | ssh;permissions | null |
_webmaster.81433 | By now, I've already read a lot about the myths and realities concerning the sub-domain vs sub-directory chaos. But that is not what my question really is. What I really want to know is that whether the sub-domains provided by free hosting sites hurt the SEO of my site. Take, for example, freehostingnoads.net - a website that provides free hosting but imposes a must-have sub-domain restriction. If I wanted to register a site called mysite, I would rather have to choose mysite.freehostingnoads.com. Now, if I choose this (or any similar site) for hosting my website, will my SEO ranking be impacted?For what I've come to know, it's just the content that matters. But they probably didn't even consider the free hosting sub-domain case. | Are Subdomains provided by free website hosting services SEO Friendly? | seo;subdomain | null |
_webmaster.71425 | So I'm creating a form for users to purchase things from my site, and currently, I have the following fields (all required):EmailCC NumberCVCExpiry MM/YYName on CardBilling Postal CodeBut I'm curious about the viability of that last one. My payment gateway supports validation of those fields when charging a card, and I'd like as much as possible when validating a payment to prevent fraud. However, in doing a bit of validation research, I came across this very helpful map on the postal code Wikipedia page that details where postal codes of what length are used. And in looking at the map, there are some countries that don't use a postal code, which would likely mean validation based on that may not work as a required field.For example, from the looks of the map, Ireland does not seem to have a postal code. Does that mean that postal codes cannot be used to validate credit card transactions there? Clearly if they don't have a postal code, making it a required field seems problematic.But, in doing the transactions, I'm also going to need to do verification for sales taxes that need to be paid, and Zip/postal code seems like the best way to accomplish this.Is Postal Code a valid required field when processing credit cards? And if not how can I support international sales with a decent level of fraud prevention, and still be able to calculate sales tax worldwide? | Are Zip/Postal codes a viable requirement for credit card validation? | ecommerce;creditcard | null |
_softwareengineering.338769 | A developer built for me a SaaS for document analysis and one of the library used is GPLv3. The developer has shared source code with me as GPL. Now if i want to launch that SaaS for public consumption do I need to share publicly the source code i paid the developer for?there are two usage scenarios.user uploaded the file to our servers. I am assuming for this we don't have to share code as the code is not downloaded to user system.user points the application to local file system and our system processes the content on client machine so the code calling the GPL code is downloaded on the system e.g. its in the browser/javascript. This is the scenario i am not sure about. | Do i need to make available source code of my SAAS if it uses GPLv3 library? | gpl | null |
_unix.152855 | Have a problem with primitive routing.Have a CentOs with 3 NICs (1 external). I want to confgure forwarding between two internal. Config:eth0 - 192.168.1.105 \ 24eth1 - 10.10.10.1 \ 25eth2 - 10.10.10.129\ 25Clients have a gateway 10.10.10.1 and 10.10.10.129 (depending on subnet)Here is route:sysctl.conf net.ipv4.ip_forward = 1 - enabled.When i'm test ping from clients, clients can ping their gateway, other NIC ip(ex. client with ip 10.10.10.10 pings 10.10.10.1(gw) and 10.10.10.129), but cannot ping any client from neighbour subnet. There is the problem? | Again about routing | routing;forwarding | null |
_unix.313916 | I'd like to run a find command and process the files it returns, but also echo a count of the files processed as it goes, to give me a sense of its progress.Right now, my command is (as an example):COUNT=0\; find . -name '*.*' -exec echo $COUNT: \c \; -exec echo {} \;But as a result, I don't get the count to echo (and I can't figure out how to increment it). I'd like it to give me something like:0: ./FileOne.txt1: ./FileTwo.txt...205: ./FileTwoHundredAndFive.txt | Print and update variable inside find | bash;find;echo | The commands executed by find are independent. Each -exec starts a new command. There's no way to transfer the current count from one command to the next, except by storing it somewhere (in a file) which would be very slow.You can make find print something each time it sees a file, and pipe the output to a program that counts the input lines.find -print -exec 'the stuff you want to do' | nlThis will print counts after a delay due to buffering. See Turn off buffering in pipe on turning off buffering.stdbuf -oL -eL find -print -exec 'the stuff you want to do' | nl |
_cs.77583 | The extensional version of Intuitionistic Type Theory is usually formulated in a way that makes extensional concepts like functional extensionality derivable. In particular, equality reflection, together with $\xi$- and $\eta$-rules for $\Pi$ types are enough to get the standard formulation of $\textsf{funext}$$\Pi_{x \in A}\textsf{Eq}(B(x), f x, g x) \implies \textsf{Eq}(\Pi_{x \in A}B(x), f, g)$where $\textsf{Eq}$ is the identity type with rules of reflection and uniqueness of identity proofs (see page 61 of M. Hofmann, Extensional Constructs in Intensional Type Theory).But what if $\eta$ is not assumed? In particular, consider a standard intensional Martin-Lf type theory with $\Pi$ formulated with $\xi$-rule and elimination as application, and to which we only add an extensional identity type $\textsf{Eq}$ as described above.What is the power of the resulting theory, in terms of extensional constructs (like functional extensionality) that can be derived in it? It seems to me that neither $\eta$ nor $\textsf{funext}$ should be derivable, although we can surely get to a weaker version using equality reflection and $\xi$:$\Pi_{x \in A}\textsf{Eq}(B(x), f x, g x) \implies \textsf{Eq}(\Pi_{x \in A}B(x), \lambda x . f x, \lambda x . g x)$(so, from $\eta$ we could get to $\textsf{funext}$, and obviously vice versa).Here R. Garner shows that the $\eta$ rule is not derivable if $\Pi$ types are given with elimination as application. He does that for an intensional theory, but the same argument should be applicable in the presence of $\textsf{Eq}$ too, I think.Are my suspicions correct? Are there any proofs of this in the literature, and in general any investigations on the kind of extensional constructs that can be derived in such minimal versions of ETT? What do we gain by only adding $\textsf{Eq}$, in the presence of such a limited $\Pi$ type (no $\eta$ equality, and no induction principle)? | Extensional constructs in minimal extensional type theory without eta equality | type theory;dependent types;equality | null |
_webapps.8055 | I have a website and want to let users pay monthly fees to get the service and in some cased will pay once per transaction.I am asking if there a simple service i can integrate in my website to handle this and allow users to pay using different ways, such as PayPal, visa, ....Note: I don't have a PayPal account and it is not possible to have one here in my country. It will be nice if payments can transfer to my bank account.I am from Egypt | Is there a service where I can use and setup on my website to handle users payments? | webapp rec | Try Plimus - I have heard good things about them.Other good options are Shareit or RegNow. |
_webmaster.79916 | I am converting my site to be mobile friendly according to Google's check.Is there a tool or extension that will allow me to check my local development site meets the requirements?I've tried this mobile-friendly-checker for Chrome but it's not reporting anything. | Check Mobile Friendlyness on local development site | google;mobile | null |
_webmaster.95280 | I have the following in my .htaccess file to only allow access from a block of IP's and everyone else is being redirected:<IfModule mod_rewrite.c>RewriteEngine OnOptions +FollowSymlinksRewriteCond %{REQUEST_URI} !/custom-page.php$RewriteCond %{REMOTE_ADDR} !^111.\111\.111\.111RewriteCond %{REMOTE_ADDR} !^222\.222\.222\.222RewriteRule $ custom-page.php [R=302,L]</IfModule>For some reason the IP's that are on the whitelist are still getting redirected to the custom-page.php | .htaccess IP whitelist is being ignored | htaccess;wordpress | null |
_unix.24128 | Is to possible to convert pdf file to epub format without errors? Is there some application in Linux that can do it? I found only Ecub and Calibre which give bad results or fail.A command-line application is sufficient.It's an ordinary pdf (not scanned), so OCR is not needed. | Convert pdf file to epub | pdf;conversion;epub;ebooks | null |
_softwareengineering.290457 | Take this code:requestAnimationFrame(function (timestamp) { console.log('one', timestamp);});requestAnimationFrame(function (timestamp) { console.log('two', timestamp);});// logs:// one, 184.6999999834225// two, 184.6999999834225The timestamp is milliseconds since the page loaded. Note these two rAF calls return different IDs which you can cancel individually.Now let's make the first callback do something very expensive:requestAnimationFrame(function (timestamp) { console.log('one', timestamp); // block for 1 second const endAt = Date.now() + 1000; while (true) { if (Date.now() >= endAt) break; }});requestAnimationFrame(function (timestamp) { console.log('two', timestamp);});// LOGS:// one, 189.32800000533462// two, 189.32800000533462 (this appears one second later)I'm confused: the second one runs a whole second later, but gets the same timestamp. Why can't it get a new timestamp, one corresponding with whatever the current monitor refresh frame is now at the time it's being called?If rAF decides ahead of time that your callback must be run in the same frame as another callback, regardless of how long that other callback might take, then the 'frame' seems like a meaningless concept that doesn't correspond with a single monitor refresh - so what's the point?I'm sure there's a good reason why it's implemented this way, I just want to understand it. | Does requestAnimationFrame() really align with monitor refreshes? | javascript;animation | null |
_computergraphics.1441 | I have heard that recent GPUs all support non-power-of-2 textures and all features just work. However, I don't understand how mip-mapping would work in such a scenario. Can someone explain? | How does mip-mapping work with non-power-of-2 textures? | texture | The rule is that to compute the next mipmap size, you divide by two and round down to the nearest integer (unless it rounds down to 0, in which case, it's 1 instead). For example, a 57x43 image would have mipmaps like:level 0: 57x43level 1: 28x21level 2: 14x10level 3: 7x5level 4: 3x2level 5: 1x1UV mapping, LOD selection, and filtering work just the same way as for power-of-two texture sizes.Generating good quality mips for a non-power-of-two texture is a little trickier, as you can't simply average a 2x2 box of pixels to downsample in all cases. However, a 2x2 box filter wasn't that great to begin with, so using a better downsampling filter such as Mitchell-Netravali is recommended regardless of the texture size. |
_cstheory.2908 | Given a random walk on a graph the cover time is the first time (expected number of steps) that every vertex has been hit (covered) by the walk. For connected undirected graphs, the cover time is known to be upper bounded by $O(n^3)$. There are strongly connected digraphs with cover time exponential in $n$. An example of this, is the digraph consisting of a directed cycle $(1, 2, ..., n, 1)$, and edges $(j, 1)$, from vertices $j = 2, ..., n 1$. Starting from vertex $1$, the expected time for a random walk to reach vertex $n$ is $\Omega(2^n)$. I have two questions :1) What are the known classes of directed graphs with polynomial cover time ? These classes might be characterized by graph-theoretic properties (or) by properties of the corresponding adjacency matrix (say $A$). For example, if $A$ is symmetric then cover time of the graph is polynomial.2) Are there more simple examples (like the cycle example mentioned above) where the cover time is exponential ?3) Are there examples with quasi-polynomial cover time ?I would appreciate any pointers to good surveys/books on this topic. | Cover Time of Directed Graphs | graph theory;co.combinatorics;markov chains;random walks | null |
_unix.131134 | I'm new for Linux. Now, I have to write a c program and use clone() to make process do things asynchronous. I've read the manual of clone(); however, I still don't know how to make it work asynchronous. I use flags CLONE_THREAD, CLONE_VM and CLONE_SIGHAND and there's an infinite loop in parameter fn. I got segmentation fault(core dumped) first, then using gdb to debug. Then, I got Program received signal SIGSEGV, Segmentation fault. [Switching to LWP xxx]. I would like to make the processes switch successfully ?Below is my code:#define _GNU_SOURCE#include <stdio.h>#include <stdlib.h>#include <sched.h>#define FIBER_STACK 1024*1024*8int counter;void * stack;int do_something(){ int i; while(1) { if (counter == 1000) { free(stack); exit(1); } else { counter++; i++; } printf(Process %d running total runs %d, and this process runs %d \n, getpid(), counter, i); }}int main() { void * stack; counter = 1; stack = malloc(FIBER_STACK); if(!stack) { printf(The stack failed\n); exit(0); } int i; for (i = 0; i < 26; i++) { clone(&do_something, (char *)stack + FIBER_STACK, CLONE_THREAD|CLONE_SIGHAND|CLONE_VM, 0); // CLONE_VFORK }}I've asked this question in stackoverflow, but there's still no one answering me. Hope someone can help me to solve this problem. If that is inappropriate to ask the same question here, please let me know. Thanks in advance. | Process switch with clone() | process;async | I got segmentation fault(core dumped) firstOf course. The point of handing the clone a stack is that it needs memory of its own. But you hand the same stack to 26 different processes! Also this is an off by one error:(char *)stack + FIBER_STACKSince if stack starts at 0x1 and FIBER_STACK is 5, it was allocated 5 addresses, 0x1, 0x2, 0x3, 0x4, 0x5. But 0x1 + 5 is 0x6. So you should subtract 1 from that.Anyway, try something like:#define NUM_PROC 8int main() { void *stack[NUM_PROC]; // --std=c99 for (int i = 0; i < NUM_PROC; i++) { stack[i] = malloc(FIBER_STACK); if(!stack[i]) { printf(Out of memory?!\n); exit(0); } } for (i = 0; i < NUM_PROC; i++) { clone(&do_something, (char *)stack[i] + FIBER_STACK - 1,And it will run without faulting. But to keep the main process around you'll also want, e.g.: while (counter < 1000) sleep(1);After the for() loop. |
_unix.292097 | I registred because I didn't manage running cgroups with several tutorials/comments/whatever you find on google. I want to limit the amount of ram a specifix user may use. Internet says cgroups. My testserver is running Ubuntu 14.04. You can divide the mentioned tutorials in two categories. Directly set limits using echo and use specific config. Neither is working for me.Setting Limits using echocgcreate -g cpu,cpuacct,...:/my_groupfinishes without any notices. When I try to run echo 100M > memory.limit_in_bytesit just says not permitted even when using sudo. I don't even reach any point of limiting another user.Setting limits using configI read about two config files. So here are my config files:cgconfig.confmount { memory = /cgroup/memory;}group limit_grp { memory { memory.limit_in_bytes=100M; memory.memsw.limit_in_bytes=125M; }}cgrules.conftestuser memory limit_grpWhen I runcgconfigparser -l /etc/cgconfig.confit mounts to systemd. Now I log on with testuser, run an memory intense task - and it runs without caring about my limit. I tried rebooting, nothing changed. Even some strange attempts using kernel config didn't work. I'm new to cgroups and didn't expect it to be that complicated. I'd appreciate any suggestions to my topic. Thank you in advance! | Limiting users ram with cgroups not working (for me) | ubuntu;systemd;limit;ram;cgroups | null |
_unix.377345 | I am following this guide:https://wiki.archlinux.org/index.php/Orange_PiI get errors on this command:$ make -j4 ARCH=arm CROSS_COMPILE=arm-none-eabi-Here is the errors:make: arm-none-eabi-gcc: Command not found/bin/sh: 1: arm-none-eabi-gcc: not founddirname: missing operandTry 'dirname --help' for more information.scripts/kconfig/conf --silentoldconfig Kconfig CHK include/config.h UPD include/config.h CFG u-boot.cfg/bin/sh: 1: arm-none-eabi-gcc: not found GEN include/autoconf.mk.dep/bin/sh: 1: arm-none-eabi-gcc: not foundscripts/Makefile.autoconf:79: recipe for target 'u-boot.cfg' failedmake[1]: *** [u-boot.cfg] Error 1make[1]: *** Waiting for unfinished jobs....scripts/Makefile.autoconf:50: recipe for target 'include/autoconf.mk.dep' failed CFG spl/u-boot.cfgmake[1]: *** [include/autoconf.mk.dep] Error 1/bin/sh: 1: arm-none-eabi-gcc: not foundscripts/Makefile.autoconf:82: recipe for target 'spl/u-boot.cfg' failedmake[1]: *** [spl/u-boot.cfg] Error 1make: *** No rule to make target 'include/config/auto.conf', needed by 'include/config/uboot.release'. Stop.My guess is because I don't have the arm-none-eabi-gcc installed on my system but when I enter the command sudo apt-get install arm-none-eabi-gcc I get an error saying there is no such package. | Installing arm-none-eabi-gcc | software installation;toolchain | null |
_codereview.59569 | I have a WCF service that itself uses another third party WCF service. It's basically a proxy. So I'm getting a request to my own one and I have just to forward it to the third party one.I would like then to map from my flattened request (that's the way it's been decided to be coded) to the slightly more complex request the other service needs.Although quite a few of the properties in each request are a naming match my issues are the followingThere are properties flattened in my request in relation to theirsThere's a huge load of my properties that should go into theirs generic Data[] ApplicationDetails property being both as follows:public class ApplicationDetails{ public Data[] Data { get; set; }}public class Data{ public string category { get; set; } public string attribute { get; set; } public string Value { get; set; }}And those will come from my request as a property named as the attribute should be, i.e. my request will have a property named AIM and I should put that as an the attribute of one of the elements of the Data array, it's value as the element's value and hardcode the category (there are 3 of them).I couldn't see many advantages (apart for the equally named properties) for using Automapper (or any other it could be) and ended up with a massive static Mapper class that looks this waypublic static class Mapper{ public static Request FromDecisionRequestToZRequest(DecisionRequest request) { var applicationDetails = new Data[] { new Data {category = ID, attribute = PubID, Value = request.PubID}, new Data {category = ID, attribute = AID, Value = request.AID}, new Data {category = APP, attribute = NID, Value = request.NID}, new Data {category = BOOK, attribute = DupeApps90, Value = request.DupeApps90}, new Data {category = BOOK, attribute = DupeApps30, Value = request.DupeApps30}, //And many others of each of the three categories }; var address = new Address[] { new Address{ City = request.City, Country = request.Country, HouseNumber = request.HouseNumber, HouseNumberExtension = request.HouseNumberExtension, Street = request.Street, ZIP = request.ZIP, kind = MAIN } }; var ret = new Request() { UserName = request.UserName, RequestDateTime = Convert.ToDateTime(request.RequestDateTime), CompanyRegistrationID = request.CompanyRegistrationID, //And many others direct mappings Addresses = new Addresses { Address = address }, Phone1 = new Phone1 { type = 1, Value = request.Phone1 }, Phone2 = new Phone2 { type = 2, Value = request.Phone2 }, Phone3 = new Phone3 { type = 3, Value = request.Phone3 }, Email = request.Email, Amount = new Amount { Value = request.Amount }, ApplicationDetails = new ApplicationDetails { Data = applicationDetails } }; return ret; }}How would you tackle this? To me this static class looks horrible (taking into account that the full one has more than 150 lines but not sure how I could improve it). | Proper way of mapping in C# | c#;wcf | I would create two extension method , ToApplicationData and ToAddress and will define mapping over there. it will sorten you code and much better readablity. you can break this methods too if you want. public static class Mapping { public static Data[] ToApplicationData (this DecisionRequest request) { return new[] { new Data {category = ID, attribute = PubID, Value = request.PubID}, new Data {category = ID, attribute = AID, Value = request.AID}, new Data {category = APP, attribute = NID, Value = request.NID}, new Data {category = BOOK, attribute = DupeApps90, Value = request.DupeApps90}, new Data {category = BOOK, attribute = DupeApps30, Value = request.DupeApps30} }; } public static Address[] ToAddresses(this DecisionRequest request) { return new Address[] { new Address { City = request.City, Country = request.Country, HouseNumber = request.HouseNumber, HouseNumberExtension = request.HouseNumberExtension, Street = request.Street, ZIP = request.ZIP, kind = MAIN } }; } }This is how I will use this code public static class Mapper { public static Request FromDecisionRequestToZRequest(DecisionRequest request) { var applicationDetails = request.ToData(); var address = request.ToAddresses(); var mappedRequest = new Request { UserName = request.UserName, RequestDateTime = Convert.ToDateTime(request.RequestDateTime), CompanyRegistrationID = request.CompanyRegistrationID, Addresses = new Addresses {Address = address}, Phone1 = new Phone1 {type = 1, Value = request.Phone1}, Phone2 = new Phone2 {type = 2, Value = request.Phone2}, Phone3 = new Phone3 {type = 3, Value = request.Phone3}, Email = request.Email, Amount = new Amount {Value = request.Amount}, ApplicationDetails = new ApplicationDetails {Data = applicationDetails} }; return mappedRequest; } } |
_codereview.121242 | I finished Codeacademy and I'm looking to practice and get better at JavaScript. Is this coded correctly or should I have made a function for it somehow? The purpose of this code is to move a square around the page with arrow keys or buttons.I have the entire script hosted here.I mostly want to Simplify this chain of if statements but also the post about using a map instead of the if statements is something I needed to know.function anim(e){ if((e.keyCode === 37)||(e === 37)){ y = shipLeft; shipLeft -= 11; y -= 11; y.toString(); y = y + 'px'; ship.style.left = y; changeColor(); return shipLeft} else if ((e.keyCode === 39) || (e === 39)){ y = shipLeft; shipLeft += 11; y += 11; y.toString(); y = y + 'px'; ship.style.left = y; changeColor(); return shipLeft } else if ((e.keyCode === 40) || (e === 40)){ y = shipTop; y += 11; shipTop += 11; y.toString(); y = y + 'px'; ship.style.top = y; changeColor(); return shipTop; } else if ((e.keyCode === 38) || ( e === 38)){ y = shipTop; y -= 11; shipTop -= 11; y.toString(); y = y + 'px'; ship.style.top = y; changeColor(); return shipTop; } } | Keyboard handler to move a shape in response to arrow keys | javascript;event handling;dom | If you move shipLeft and shipTop into an object called shipPositions rather than just top level variables, you could also use a map-driven approach like this:function anim(e) { var key = e.KeyCode || e, val, info; var keyMap = { 37: {direction: left, ship: shipLeft, delta: -11}, 39: {direction: left, ship: shipLeft, delta: 11}, 40: {direction: top, ship: shipTop, delta: 11}, 38: {direction: top, ship: shipTop, delta: -11}, }; info = keyMap[key]; if (!info) { return; } shipPositions[info.ship] += info.delta; val = shipPositions[info.ship]; ship.style[info.direction] = val + 'px'; changeColor(); return val;} |
_unix.61020 | I had Windows installed on my laptop and suddenly one morning Windows couldn't start. Then I tried after formatting and for once it became possible.I also installed Ubuntu as logical drive (deleted all HDD partitions) and then tried to install Windows but in the middle of the installation process (after expanding Windows files) it showed an error and stopped.I'm using Ubuntu with live CD. In the Ubuntu disk utility, I see all HDDs as unallocated free space. The following points are being shown:----smart status: disk failure is imminent>>>results of selt-test--self assessment-failing--power cycles-1834--bad sectors-2047--overall assessment-disk failure is imminent(backup all data and replace the disk)>>>Attributesfor reallocated sector unit-assessment is failingvalues--- normalized-1 worst-1 threshold-50 value-2047 sectors>>>Now I'm using the badblocks command.sudo badblocks -v /dev/sdaBut it has been running for 106 hours, and still continues.I don't want to replace my HDD. Please help me so that I can use Windows on my laptop. | Issue with bad sectors on a laptop hard drive | linux;ubuntu;hard disk | null |
_webapps.33405 | When I want to see updates of a friend in Google Plus, I currently have to go to his home page to see them - while in facebook, what I need to do is to add him/her to my Close Friend list.Is there a similar feature in Google Plus? | Google Plus get notification of a friend activity similarly to Close Friend list in facebook | facebook;google plus;notifications;list | Pretty much similar, yes. You could easily add your friend to a circle.Click on that circle, and set the slider in the top right corner to Show all posts from [circle name] on your start page.Then, all posts from friends you have added to the circle will show up in your start page stream. |
_codereview.20723 | I've been working on my first Angular JS app for the past few days.It's in a very early stage (no real functionality), but that will only make it easier to review what IS there.The client side is written in CoffeeScript. The app used Requirejs to manage files AMD style (it loads compiled CoffeeScript).The server side is very minimal at the moment. It will have a local SQLite database and uses SQLAlchemy as an ORM. Furthermore I make use of the (very nice) Flask framework to provide an restful API to the Angular app.Right now the server side is not much concern to me; it works.The client side works as well, but since I'm new to Angular I am really curious to know whether I do things correctly and using the Angular JS way.The code lives in this repository.The parts I'm not so sure about are the way I am dealing with scopes right now.For example:I have a general dialog directive and use it to display a dialog for importing images. I would think I could have the import directive live inside the dialog (transcluded), but to be able to handle the dialog apply event (handle by uploading the images in this particular instance...), the import directive needs to wrap the dialog. It works, but was rather counterintuitive. Is it the right way to do things?Another example:To display the dialog I have its visibile attribute linked to a root scope property. This also seems rather hacky.<body ng-controller=MainCtrl > {# let angularjs compile the templating from here #} {% raw %} <header> <h1>Sight <span>beta</span></h1> <div class=buttons> <button ng-click=show_import_dialog = ! show_import_dialog>Import</button> </div> </header> <div id=content> <!-- import dialog --> <div sg-import> <div sg-dialog title=Import Photographs visible=show_import_dialog sg-apply=upload() > <p> Drag images into the dropzone below or click on it to browse. </p> <br /> <div class=drop-zone> <div ng-repeat=file in files sg-photo title={{ file.name }}> </div> <!-- hidden input --> <input type=file accept=image/* multiple /> <!-- push size --> <div class=clear></div> </div> </div> </div> </div> <footer> </footer> {% endraw %}</body>The directives and controllers live here. | Angular JS photo app for personal cloud | html;angular.js | null |
_codereview.162245 | I have a quite large unit test case for one class that currently does not exist, I am going to write it after finishing the test case.I am wondering if my unit test doesn't lack something important, or alternatively, if it is not too complex. I have to describe what the tested class is supposed to do, although some details are left out, and I can answer questions about them if needed.This class is a key matcher, part of a library implementing things like json web signing/json web key.The key matcher will take input from some other classes like JWS processors, that will process json objects. The json representation of, for example, a signed object, can contain a key used to verify the signatures on the object. This key can be given as a json web key or certificate, or can be given by key id. A key set can also be provided, that would mean the key identified by the key id is to be looked up in that set. The protocol does not specify the policy of determining which key to use for verification, so in theory all those fields can be present at once.The key matcher will match keys, trying in some predetermined order, like explicit key has priority over a certificate, and it has priority over matching in key set, last is an external source of keys or certificates that is application specific. However, usually when the matcher looks for keys in different sources, and a higher priority source is found, a lower priority source is usually not tried even if keys from the higher priority source do not match. It stems from the fact that if an application sends a signed or encrypted object containing multiple incompatible keys, it is an application error and such cases should not be handled, because they make no sense.This test case tests matching in case of each possible source of key material, and most but not all cases of match failure. However, it does not test for cases where matcher would throw NullPointerException or IllegalArgumentException or possibly IllegalStateException, for example if a key type is not specified. I am not sure if I should test for good reaction to bugs in the user of the matcher class. The last test will test if the order of matching is correct.I would like to know if my unit test too complex, or if it misses something important./*** Copyright (c) 2016-2017, acme-client developers* All rights reserved.** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:** 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.** 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/package io.github.webczat.acmeClient.jws.keyMatching;import static org.junit.Assert.assertEquals;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.when;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.security.cert.X509Certificate;import java.util.*;import org.junit.Test;import io.github.webczat.acmeClient.jws.KeyType;import io.github.webczat.acmeClient.jws.NoMatchingKeyException;import io.github.webczat.acmeClient.jws.WebKey;import io.github.webczat.acmeClient.jws.WebPublicKey;import io.github.webczat.acmeClient.testUtil.CertificateTestUtils;/** * This class tests key matcher. * * @author webczat */@SuppressWarnings({ javadoc })public class KeyMatcherTest { /** * Test for matching an explicitly given key. */ @Test public void testExplicitKeyMatchWithAlgorithm() { WebPublicKey key = mock(WebPublicKey.class); when(key.getKeyType()).thenReturn(KeyType.RSA); when(key.getAlgorithm()).thenReturn(test); assertEquals(new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).setWebKey(key).match(), key); } /* * Test for explicitly given key without match without algorithm on the key. */ @Test public void testExplicitKeyMatchWithoutAlgorithm() { WebPublicKey key = mock(WebPublicKey.class); when(key.getKeyType()).thenReturn(KeyType.RSA); assertEquals(new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).setWebKey(key).match(), key); } /** * Test explicit key match with bad algorithm. */ @Test(expected = NoMatchingKeyException.class) public void testExplicitKeyMatchWithBadAlgorithm() throws NoMatchingKeyException { WebPublicKey key = mock(WebPublicKey.class); when(key.getKeyType()).thenReturn(KeyType.RSA); when(key.getAlgorithm()).thenReturn(test2); new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test2).setWebKey(key).match(); } /** * Test for explicit key with bad key type. */ @Test(expected = NoMatchingKeyException.class) public void testExplicitKeyMatchWithBadType() throws NoMatchingKeyException { WebPublicKey key = mock(WebPublicKey.class); when(key.getKeyType()).thenReturn(KeyType.EC); new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).match(); } /** * Tests for explicit key match with a key validator passing. */ @Test public void testExplicitKeyMatchWithPassingValidator() { WebPublicKey key = mock(WebPublicKey.class); when(key.getKeyType()).thenReturn(KeyType.RSA); assertEquals( new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).setKeyValidator((k) -> true).setWebKey( key).match(), key); } /** * Test for explicit key match with failing validator. */ @Test(expected = NoMatchingKeyException.class) public void testExplicitKeyMatchWithFailingValidator() throws NoMatchingKeyException { WebPublicKey key = mock(WebPublicKey.class); when(key.getKeyType()).thenReturn(KeyType.RSA); new KeyMatcher().setWebKey(key).setKeyValidator((k) -> false).setAlgorithm(test).setKeyType( KeyType.RSA).match(); } /** * Test for matching a key from the given set of keys, with given key * identifier. * */ @Test public void testSetKeyMatchWithKeyId() { WebPublicKey key1 = mock(WebPublicKey.class), key2 = mock(WebPublicKey.class), key3 = mock(WebPublicKey.class); when(key1.getKeyType()).thenReturn(KeyType.RSA); when(key1.getKeyId()).thenReturn(test); when(key2.getKeyType()).thenReturn(KeyType.EC); when(key2.getKeyId()).thenReturn(test); when(key3.getKeyType()).thenReturn(KeyType.RSA); LinkedHashSet<WebKey> keySet = new LinkedHashSet<WebKey>( Arrays.asList(new WebKey[] { key3, key2, key1, key1 })); assertEquals(new KeyMatcher().setKeyId(test).setKeyType(KeyType.RSA).setAlgorithm(test).setWebKeySet( keySet).match(), key1); } /** * Test for no matching keys for key id when matching by key set. */ @Test(expected = NoMatchingKeyException.class) public void testSetKeyMatchWithKeyIdAndNoCandidates() throws NoMatchingKeyException { WebPublicKey key = mock(WebPublicKey.class); when(key.getKeyType()).thenReturn(KeyType.RSA); LinkedHashSet<WebKey> keySet = new LinkedHashSet<WebKey>(Arrays.asList(new WebKey[] { key })); new KeyMatcher().setAlgorithm(test).setKeyId(test).setKeyType(KeyType.RSA).setWebKeySet(keySet).match(); } /** * Tests key matching using a key set, with no key id given. */ @Test public void testSetKeyMatchWithoutKeyId() { WebPublicKey key1 = mock(WebPublicKey.class), key2 = mock(WebPublicKey.class); when(key1.getKeyType()).thenReturn(KeyType.RSA); when(key2.getKeyType()).thenReturn(KeyType.EC); LinkedHashSet<WebKey> keySet = new LinkedHashSet<>(Arrays.asList(new WebKey[] { key2, key1 })); assertEquals(new KeyMatcher().setAlgorithm(test).setKeyType(KeyType.RSA).setWebKeySet(keySet).match(), key1); } /** * Test for matching keys from set with no key id and no candidates. */ @Test(expected = NoMatchingKeyException.class) public void testSetKeyMatchWithoutKeyIdAndCandidates() throws NoMatchingKeyException { WebPublicKey key = mock(WebPublicKey.class); when(key.getKeyType()).thenReturn(KeyType.EC); HashSet<WebKey> keySet = new HashSet<>(Arrays.asList(new WebKey[] { key })); new KeyMatcher().setAlgorithm(test).setKeyType(KeyType.RSA).setWebKeySet(keySet).match(); } /** * Test for matching key from external source. */ @Test public void testExternalKeyMatch() { WebPublicKey key1 = mock(WebPublicKey.class), key2 = mock(WebPublicKey.class); when(key1.getKeyType()).thenReturn(KeyType.RSA); when(key2.getKeyType()).thenReturn(KeyType.EC); KeyProvider kp = mock(KeyProvider.class); when(kp.lookupKey(test)).thenReturn(Arrays.asList(new WebKey[] { key2, key1 })); assertEquals(new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).setKeyId(test).setKeyProvider( kp).match(), key1); } /** * Test matching keys from external source when no keys match. */ @Test(expected = NoMatchingKeyException.class) public void testExternalKeyMatchWithNoCandidates() throws NoMatchingKeyException { WebPublicKey key = mock(WebPublicKey.class); when(key.getKeyType()).thenReturn(KeyType.EC); KeyProvider kp = mock(KeyProvider.class); when(kp.lookupKey(test)).thenReturn(Arrays.asList(new WebKey[] { key })); new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).setKeyId(test).setKeyProvider(kp).match(); } /** * Test for external key matching when no key id specified, it should not * work at all. */ @Test(expected = NoMatchingKeyException.class) public void testExternalKeyMatchWithNoKeyId() throws NoMatchingKeyException { WebPublicKey key = mock(WebPublicKey.class); when(key.getKeyType()).thenReturn(KeyType.RSA); KeyProvider kp = mock(KeyProvider.class); when(kp.lookupKey(test)).thenReturn(Arrays.asList(new WebKey[] { key })); new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).setKeyProvider(kp).match(); } /** * Test for certificate matching when cert chain is explicitly given. */ @Test public void testExplicitCertificateMatch() { List<X509Certificate> certs = CertificateTestUtils.newChain(3, null).getCertificateChain(); assertEquals(new KeyMatcher().setAlgorithm(test).setKeyType(KeyType.RSA).setCertificateChain(certs).match(), certs); } /** * Test explicit certificate match that fails. */ @Test(expected = NoMatchingKeyException.class) public void testExplicitCertificateMatchFailure() throws NoMatchingKeyException { List<X509Certificate> certs = CertificateTestUtils.newChain(3, null).getCertificateChain(); new KeyMatcher().setKeyType(KeyType.EC).setAlgorithm(test).setCertificateChain(certs).match(); } /** * Test SHA256 fingerprint matching. */ @Test public void testFingerprintCertificateMatchWithSha256() throws NoSuchAlgorithmException { List<X509Certificate> certs = CertificateTestUtils.newChain(3, null).getCertificateChain(); byte[] fingerprint = MessageDigest.getInstance(SHA2-256).digest(certs.get(0).getEncoded()); CertificateProvider cp = mock(CertificateProvider.class); when(cp.lookupCertificateBySha256Fingerprint(fingerprint)).thenReturn(certs); assertEquals(new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).setSha256Fingerprint( fingerprint).setCertificateProvider(cp).match(), certs); } /** * Test certificate matching using SHA1 fingerprint. */ @Test public void testFingerprintCertificateMatchWithSha1() throws NoSuchAlgorithmException { List<X509Certificate> certs = CertificateTestUtils.newChain(3, null).getCertificateChain(); byte[] fingerprint = MessageDigest.getInstance(SHA1).digest(certs.get(0).getEncoded()); CertificateProvider cp = mock(CertificateProvider.class); when(cp.lookupCertificateBySha1Fingerprint(fingerprint)).thenReturn(certs); assertEquals(new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).setCertificateProvider( cp).setSha1Fingerprint(fingerprint).match(), certs); } /** * Test for matching by sha256 fingerprint when key type is invalid. */ @Test(expected = NoMatchingKeyException.class) public void testFingerprintCertificateMatchWithSha256AndBadKeyType() throws NoMatchingKeyException, NoSuchAlgorithmException { List<X509Certificate> certs = CertificateTestUtils.newChain(3, null).getCertificateChain(); byte[] fingerprint = MessageDigest.getInstance(SHA2-256).digest(certs.get(0).getEncoded()); CertificateProvider cp = mock(CertificateProvider.class); when(cp.lookupCertificateBySha256Fingerprint(fingerprint)).thenReturn(certs); new KeyMatcher().setKeyType(KeyType.EC).setCertificateProvider(cp).setAlgorithm(test).setSha256Fingerprint( fingerprint).match(); } /** * Test for sha1 fingerprint matching when wrong key type is given. */ @Test(expected = NoMatchingKeyException.class) public void testFingerprintCertificateMatchWithSha1AndBadKeyType() throws NoMatchingKeyException, NoSuchAlgorithmException { List<X509Certificate> certs = CertificateTestUtils.newChain(3, null).getCertificateChain(); byte[] fingerprint = MessageDigest.getInstance(SHA1).digest(certs.get(0).getEncoded()); CertificateProvider cp = mock(CertificateProvider.class); when(cp.lookupCertificateBySha1Fingerprint(fingerprint)).thenReturn(certs); new KeyMatcher().setCertificateProvider(cp).setKeyType(KeyType.EC).setAlgorithm(test).setSha1Fingerprint( fingerprint).match(); } /** * Test for fingerprint matching with no fingerprints set. */ @Test(expected = NoMatchingKeyException.class) public void testFingerprintCertificateMatchWithNoFingerprint() { new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).setCertificateProvider( mock(CertificateProvider.class)).match(); } /** * Test for matching when no parameters are set. */ @Test(expected = NoMatchingKeyException.class) public void testKeyMatchWithNoData() throws NoMatchingKeyException { new KeyMatcher().setKeyType(KeyType.RSA).setAlgorithm(test).match(); } /** * Test for matching order. */ @Test public void testMatchingOrder() { WebPublicKey key1 = mock(WebPublicKey.class); when(key1.getKeyType()).thenReturn(KeyType.RSA); KeyMatcher km = new KeyMatcher(); km.setKeyType(KeyType.RSA).setAlgorithm(TEST).setWebKey(key1); List<X509Certificate> certs1 = CertificateTestUtils.newChain(1, null).getCertificateChain(); km.setCertificateChain(certs1); WebPublicKey key2 = mock(WebPublicKey.class); when(key2.getKeyType()).thenReturn(KeyType.RSA); when(key2.getKeyId()).thenReturn(test); Set<WebKey> keySet = new HashSet<>(); keySet.add(key2); km.setWebKeySet(keySet); km.setKeyId(test); List<X509Certificate> certs2 = CertificateTestUtils.newChain(1, null).getCertificateChain(); byte[] fingerprint1 = MessageDigest.getInstance(SHA2-256).digest(certs2.get(0).getEncoded()); km.setSha256Fingerprint(fingerprint1); List<X509Certificate> certs3 = CertificateTestUtils.newChain(1, null).getCertificateChain(); byte[] fingerprint2 = MessageDigest.getInstance(SHA1).digest(certs3.get(0).getEncoded()); km.setSha1Fingerprint(fingerprint2); CertificateProvider cp = mock(CertificateProvider.class); when(cp.lookupCertificateBySha256Fingerprint(fingerprint1)).thenReturn(certs2); when(cp.lookupCertificateBySha1Fingerprint(fingerprint2)).thenReturn(certs3); km.setCertificateProvider(cp); WebPublicKey key3 = mock(WebPublicKey.class); when(key3.getKeyType()).thenReturn(KeyType.RSA); KeyProvider kp = mock(KeyProvider.class); when(kp.lookupKey(test)).thenReturn(Arrays.asList(new WebKey[] {key3})); km.setKeyProvider(kp); assertEquals(km.match(), key1); km.setWebKey(null); assertEquals(km.match(), certs1); km.setCertificateChain(null); assertEquals(km.match(), key2); km.setWebKeySet(null); assertEquals(km.match(), certs2); km.setSha256Fingerprint(null); assertEquals(km.match(), certs3); km.setSha1Fingerprint(null); assertEquals(km.match(), key3); }} | Unit test for the right kind of cryptography key | java;unit testing;cryptography | I really like the small test methods. But without seeing the actual implementation, it is very hard to tell, if a test case makes sense or does what it should do.Small improvements:Split your test methods into three blocks, when-given-then and use a empty line between those. It can help a lot, not always, but I recommend to do it. It's like using your indicator: Even though noone is around (= quite an easy test case), it's a good habit to use it always, so you will use it, when it's actually needed.You can make WebPublicKey an instance variable and use the @Mock annotation. In the setup (@Before), you can use MockitoAnnotations.initMocks(this);. So you can save the first line of every test.I have a hard time to understand, what match() does, or what it should do (= the intention is not clear). Why must match() equal key? When I read matches(), I expect to have a boolean returned. Shouldn't it be something like findMatchingKey() or something?The test-prefix of your test cases aren't needed, it's used back in the day, before annotations were a thing in java/junit. Instead of testExplicitKeyMatchWithAlgorithm, you can write explicitKeyMatchesWithAlgorithmThe JavaDoc for the methods are first of all, most of the times it is JavaDoc, but not always. 2nd: I'm 99% sure, noone will ever read those java docs (you guys do even generate those for test cases?). 3rd: Test for matching an explicitly given key. vs testExplicitKeyMatchWithAlgorithm. So, you have a comment, a method name, and the actual code. Rhetorical question: which one is true? The java doc does not talk about algorithm, the method name does.The test algorithm: I usually declare those explicitly as variable in the test case, so the reader sees where it's used (WebPublicKey and KeyMatcher)There's a lof of repetition of the WebPublicKey instantiation (RSA KeyType and test algorithm), you might want to add a static helper method for that, something like rsaWithTestAlgorithmKeyMatcher(), or even add a constant. For the other creations, I'd provide a method like keyMatcher(keyType: KeyType, algorithm: String): KeyMatcher.testMatchingOrder: Now, that's quite the confusing test method. You wrote, that the implementation does not exist. The actual test driven approach would be write failing test case, implement, refactor. Now important is, you write one failing test case. And you only implement what is needed for the test case to run (Know when to stop.), so you do not implement too much. And an important thing, too, is: What do I need to change, to make my test fail. I mention all that especially because of the last test case. Do you actually have to use four different Keys, wouldn't be two enough to ensure the correct return value? If not: Then something's different, you have to consider writing two different test cases.testMatchingOrder 2: Also to point out the other points I've mentioned, especially the helper-methods and then give-when-then block: Those applied should make this method a lot easier to understand. Beside that: There's nothing wrong to write keyMatcher instead of km, certificateProvider instead of cp and so on. It certainly would have helped me. testMatchingOrder 3: After reading that, I still do not understand the expected behavior of the KeyMatcher, especiall the latest part. You call match, and expect key1. Why? Then you set the webKey to null (why?), and then you expect certs1 (why?). The setup of the test doesn't really help to understand it either.Hope that helps,... |
_codereview.161002 | I was solving this question:Given there is a 6 sided dice. Find the total number of ways W, in which a sum S can be reached in N throws.Example:S = 1, N = 6 => W = 0S = 6, N = 6 => W = 1S = 7, N = 6 => W = 6S = 3, N = 2 => W = 2How to improve its complexity and make it more readable?def get_sum_dp(n,s): t = [[0 for i in xrange(1,s+2)] for j in xrange(1,n+2)] for j in xrange(1,7): t[1][j] = 1 for i in range(2, n+1): for j in range(1, s+1): for k in range(1,7): if k < j: t[i][j] += t[i-1][j-k] print t[n][s] get_sum_dp(2,8) | Find the total number of ways W, in which a sum S can be reached in N throws of a dice | python;python 2.7;combinatorics;complexity;dice | 1. ReviewThe sum \$s=0\$ can be reached in \$n=0\$ throws in exactly one way, but:>>> get_sum_dp(0, 0)Traceback (most recent call last): File <stdin>, line 1, in <module> File cr161002.py, line 32, in get_sum_dp t[1][j] = 1IndexError: list index out of rangeThe name get_sum_dp could be clearer (what does dp mean? dynamic programming?). I would use a name like dice_rolls.A docstring would be helpful in understanding what the function does.It's usually more convenient to return a result instead of printing it. This would allow the result to be used in other computations if needed.Instead oft = [[0 for i in xrange(1,s+2)] for j in xrange(1,n+2)]you could write:t = [[0] * (s + 1) for _ in xrange(n + 1)](It's conventional to use _ for a loop variable whose value is not used.)The initial condition is:for j in xrange(1,7): t[1][j] = 1but it would be simpler to use the following initial condition:t[0][0] = 1and change:for i in range(2, n+1): for j in range(1, s+1): if k < j:to:for i in range(1, n+1): for j in range(1, s+1): if k <= j:(This also fixes the bug I noted in point 1 above.)In the nested loops:for i in range(2, n+1): for j in range(1, s+1):the loop over j goes all the way from 1 to s. But some of this may be wasted, because the sum of i dice must be between i and i * 6. So you could reduce the amount of work by writing:for i in range(2, n+1): for j in range(i, min(s, i * 6) + 1):Similarly, instead of checking k on every loop iteration:for k in range(1,7): if k < j: t[i][j] += t[i-1][j-k]you could compute the loop bounds in advance:for k in xrange(1, min(6, j) + 1): t[i][j] += t[i - 1][j - k]2. Revised codedef dice_rolls(n, s): Return the number of ways in which a sum s can be reached in n throws of a 6-sided die. t = [[0] * (s + 1) for _ in xrange(n + 1)] t[0][0] = 1 for i in xrange(1, n + 1): for j in xrange(i, min(s, i * 6) + 1): for k in xrange(1, min(6, j) + 1): t[i][j] += t[i - 1][j - k] return t[n][s]3. Alternative approachDynamic programming builds up a table of solutions to sub-problems from the bottom up (starting with small problems and using those to solve larger problems). But an alternative approach works from the top down, using recursion to compute the sub-problems, and memoization to avoid duplicated work. This often results in clearer code and it is easier to compute only the table entries that you need.In Python 3.2 or later, you can easily memoize a function using the @functools.lru_cache decorator, like this:import [email protected]_cache(maxsize=None)def dice_rolls(n, s): Return the number of ways in which a sum s can be reached in n throws of a 6-sided die. if s < n or s > n * 6: return 0 elif n == s == 0: return 1 else: return sum(dice_rolls(n - 1, s - i) for i in range(1, 7))(Python 2.7 lacks functools.lru_cache, but there's a backport package.) |
_softwareengineering.355395 | According to the eslint documentation:Trailing commas simplify adding and removing items to objects and arrays, since only the lines you are modifying must be touched. Another argument in favor of trailing commas is that it improves the clarity of diffs when an item is added or removed from an object or arrayHowever, dangling commas appear to have inconsistent behavior in JavaScript. Consider the following:var a = [ 'x', 'y',]// a.length --> 2var b = [ 'x', 'y']// b.length --> 2var c = [ ,]// c.length --> 1var d = []// d.length --> 0In the first two examples (a and b), the trailing does not affect the length of the array; however, looking at the second two examples (c and d), the existence of a dangling comma does affect the length of the array.I agree that trailing commas make for nicer git diffs, as well as make it easier to add/remove items in objects and arrays, but are there other arguments in favor of it, considering that there are potential tradeoffs? | Arguments for and against comma-dangle in JavaScript | javascript;coding style;code quality | null |
_softwareengineering.206781 | I have read Would a NoSQL DB be more efficient than a relational DB for storing JSON objects? and am building a small test project in Asp.Net. I have a webapi up in Azure. It returns a List<Company> and Company is my object which has several properties and child list and a lat/long value.//id, name etc.public List<Certification> Certifications { get; set; }public float Latitude { get; set; }public float Longitude { get; set; }public GeoCoordinate Cordinate // etc. GeoCoordinate is from System.Device referenceI return this List of companies and use the JSON output.Now internally, loading this list I load the complete list of companies out of a json file. and if there is no file, a file will be created. This is all good. But the Latitude and Longtitude is empty on the initial basis. So I fill it using googles reverse geocode. That works, but has a request limit. So I'd like to load the list and if lat/long is empty, retrieve the values from google's service and store it. But I am looking for a solution not to store the complete json list to a file again. And I am not looking for a relational database solution, because that is something that I have done enough. Now I have read about mongoDB. But it is a bit hard to set up on Azure. I have had Redis on Azure. What easy and fast solution do you recommend for me to store my list of objects? Do you even recommend it to store it as JSON? or something else? like XML? and use xpath to update values?So I am looking for an architecture/design to update all lat/longs untill google gives the quota limit error and give it a go next try I access the list of companies.ps. I do not want to store a list of Certification's. I am curious if I can keep it as property of company and store the complete company project. | JSON object and storage of nosql | c#;nosql;json;azure | I'm gonna show how I would solve this using the Starcounter database to store the data and using it's internal web server to fetch the data as JSON models. The application model is automatically the database if [Database] attribute is set.The database[Database]public class Company{ public String Name; public String RegistrationNumber; ... and so on public IEnumerable<Certificate> Certificates{ get{ return Db.SQL(SELECT c FROM Certificate where c.Position=?,this); } } private Coordinate Coordinate; public double Latitude{ get{ if(Coordinate == null){ AssureCoordinates(); } return Coordinate.Latitude; } } public double Longitute get{ if(Coordinate == null){ AssureCoordinates(); } return Coordinate.Longitute; } } private void AssureCoordinates(){ ... fetch from whatever source and set to Coordinate }And then in the integrated web server I would define a JSON model for the Company:{ Name:ACME Ltd, RegistrationNumber:555-5555, Longitude:123.4, Latitude:123.4, Certificates:[ { ... certifcates properties }], $:{DataType:Company}, $Certificates:{DataType:Certificate }This JSON model will be automatically bound to the persistent data in the database upon request.And lastly register the REST verb+URI to respond to:Handle.GET(/company/?, (String registrationNumber) =>{ CompanyModel cModel = new CompanyModel(); Company comp = ... find company in DB using SQL cModel.Data = comp;return cModel;});Now a JSON model of the requested company would be returned and all data is filled automatically from the database. The Coordinate will be fetched if not set upon first call to Long/Lat. You could of course also return a list of these Companies as well.This setup will make your regular database act like a JSON source, and you can skip the regular web server as well.Hope this helped you on how to solve this problem using a NoSQL database! |
_softwareengineering.233548 | We are developing a data model for a marketing database that will import transaction, customer, inventory, etc. files and the directive is ONE process that works for every client. We have been told every client will have different import layouts and different columns that identify a table's primary key. Our initial idea is to get definitions from the client on what columns make each record unique, store those in a mapping table, and then have lookup tables that translate those primary keys to an internal surrogate keys automatically for every destination table so that every table conforms to an integer primary key no matter how many columns/types are used to make up the real pk.The first major problem I saw was when/if have to map back to the lookup tables to get data that we did not store in the main data model, but I have ben assured that anything we ever want to query will be duplicated in the lookup and main tables so that should not be a concern.This kind of flexibility seems like it will cause some serious limitations on:Technology stack (no way to dynamically map these import files inSSIS, need lot of dynamic SQL or java/c#)Scalability (based on previous concern and initial testing, thiswould be difficult to scale without speed concerns) Complexity (we are already running into some complex code changeswhen we try to implement all these tables with historical changelogging while maintaining mapping to the lookup tables for example)My question - Is this feasible or is there another obvious solution we are missing? | Should We Use Surrogate Primary Keys for Every Table? | design;design patterns;architecture;database;database design | null |
_webmaster.18475 | I have just finished the development of my application. Now I would like to promote\publicize that (I have no money!). What are techniques most commonly used to do that on the web? And the most efficient? | How effectively to promote\publicize my web application? | marketing;website promotion | null |
_unix.37101 | Having TLS certificate in local file, I can display its details using syntax like:openssl x509 -text -noout -in cert_filenameIs there any way to display remote SMTP/POP3/HTTP server's TLS certificate in this same format in bash terminal? | How to display server's TLS certicicate details in terminal? | command line;openssl;tls | openssl s_client -connect server:port display some informations. Maybe is it sufficient for you. It is not exactly the same format, but it can help. |
_unix.357974 | At the moment of launch from terminal it gives the next info>pulseaudio-equalizer-gtkTraceback (most recent call last): File /usr/share/pulseaudio-equalizer/pulseaudio-equalizer.py, line 13, in <module> import gtk, gobject File /usr/lib64/python2.7/site-packages/gtk-2.0/gtk/__init__.py, line 40, in <module> from gtk import _gtkImportError: /usr/lib64/libharfbuzz.so.0: undefined symbol: FT_Get_Var_Blend_CoordinatesAs I understand this one the undefined symbol are more or less related to the unavailability of the library , making a zypper search *libharfbuzz*yieldsS |-name |-description | type --+------------------------+----------------------------------------+-----------i | libharfbuzz-icu0 | OpenType - ICU -> | i | libharfbuzz-icu0-32bit | OpenType - ICU -> | i | libharfbuzz0 | OpenType | i | libharfbuzz0-32bit | OpenType | So I dont get what is causing that the UI does not start.Thanks in advance | How to start the pulseaudio-equalizer-gtk? | opensuse;pulseaudio;mate | null |
_softwareengineering.86983 | Is creating a huge public site fully in Silverlight really advisable? for eg. an ecommerce site. I don't want to start any debate but actually I feel Silverlight shouldn't be used for full website because the biggest loss you incur is of SEO. No search engines till today can parse the xap file and index it based on it's content. You can get around it by doing ifs and thens like if Silverlight is not supported then make an Asp.Net equivalent page for it but that only doubles our effort of making application, more than anything else. Why write double code in 2 applications meant for the same purpose. If that is the only option why not create Asp.Net application only. What are your views?Thanks in advance :) | Is creating a full application in Silverlight advisable? | c#;asp.net;silverlight | Short answer: no. Right now the future of Silverlight seems unsure. But this is just my personal opinion. SkyDrive drops SilverlightSilverlight developers rally against Windows 8 plansMicrosoft surrenders Silverlight to HTML5 on cross-platform front |
_webmaster.38805 | I'm really new to this SEO world and I've been reading a lot to try and figure it out.We have a site that allows users to browse/create events anywhere. And we fill it with content from the main cities in the US.We would like it to show for searches for things like events in san francisco or what to do in new york, however, since the site is not really location-specific, I'm not really sure where to begin.I've been thinking a couple of things, maybe you can help me decide if these would be a good way to start or if I should try something different.1- Allow something like location-specific urls (e.g. example.com/browse/san-francisco) could just show the main page centered in San Francisco.2- Change the headers/title of the page so it adapts automatically to the city being browsed (and change this dynamically as the user changes the location of the map).3- Add internal links to different locations (e.g. add a link at the footer of the page that says Events in Seattle that makes the site load events in that city. (this would probably depend on implementing #1).What do you guys think? will any of these really help or should I look for a different approach? any advice is welcome. | SEO: Getting site to show in location-specific searches | seo;geolocation | null |
_unix.155637 | Some time in 3.15, someone moved the rts5139 driver out of staging (I cannot find a changelog of this) and it got renamed to rtsx_usb. This, unfortunately, broke support for at least the RTS5139 card reader. I have found about zero other people on the internet having this problem (buried under all of the SVC repos that got indexed?), and was curious as to whether anyone here was having a similar problem and had fixed it.Kernel versions tested to be experiencing the problem:3.17.0-rc4lsmod | grep rts:rtsx_pci 37855 0 rtsx_usb 17487 0 mfd_core 12601 3 lpc_ich,rtsx_pci,rtsx_usbusbcore 187093 9 btusb,snd_usb_audio,uvcvideo,rtsx_usb,snd_usbmidi_lib,ehci_hcd,ehci_pci,usbhid,xhci_hcdlsusb | grep -i rts:Bus 001 Device 009: ID 0bda:0139 Realtek Semiconductor Corp. RTS5139 Card Reader ControllerRemoving/reinserting the rtsx_usb module does nothing. Logs are silent when the reader is interacted with. Strange. | rts5139/rtsx_usb borked in 3.15+ | linux kernel;drivers;kernel modules | null |
_unix.112217 | I'm trying to setup XForwarding over ssh, but it fails. The same result happens whether I use the argument -X or -Y for ssh. The error I get.a@ASUS-N53SM:~$ ssh -X -p 6623 [email protected]@192.168.0.200's password: Last login: Sun Feb 2 18:42:08 2014 from 192.168.0.201/usr/bin/xauth: (stdin):1: bad display name pinker-server:10.0 in remove command/usr/bin/xauth: (stdin):2: bad display name pinker-server:10.0 in add commandxdpyinfo: unable to open display pinker-server:10.0.In the client file ~/.ssh/configForwardX11 yesIn the client file /etc/ssh/ssh_config (comments removed).Host *ForwardX11 yesForwardX11Trusted yesSendEnv LANG LC_*HashKnownHosts yesGSSAPIAuthentication yes GSSAPIDelegateCredentials noIn the server file /etc/ssh/sshd_config (comments removed).Port 6623Port 6624Port 6625Protocol 2HostKey /etc/ssh/ssh_host_rsa_keyHostKey /etc/ssh/ssh_host_dsa_keyHostKey /etc/ssh/ssh_host_ecdsa_keyUsePrivilegeSeparation yesKeyRegenerationInterval 3600ServerKeyBits 768SyslogFacility AUTHLogLevel INFOLoginGraceTime 120PermitRootLogin yesStrictModes yesRSAAuthentication yesPubkeyAuthentication yesIgnoreRhosts yesRhostsRSAAuthentication noHostbasedAuthentication noPermitEmptyPasswords noChallengeResponseAuthentication noX11Forwarding yesX11DisplayOffset 10PrintMotd noPrintLastLog yesTCPKeepAlive yesAcceptEnv LANG LC_*Subsystem sftp /usr/lib/openssh/sftp-serverUsePAM yesX11UseLocalhost noAllowTcpForwarding yesI found this similar Question, but none of the answers work.UPDATE:On the server, I added to the file /etc/hosts.127.0.0.1 pinker-serverOn the server, I installed the package xbase-clients. On the ssh connection echo $DISPLAY outputs :0.0.Now I'm getting a new error.X11 connection rejected because of wrong authentication.X11 connection rejected because of wrong authentication.X11 connection rejected because of wrong authentication.X11 connection rejected because of wrong authentication.xdpyinfo: unable to open display pinker-server:10.0. | SSH XForwarding fails - xauth bad display name | ssh;xforwarding;xauth | null |
_webapps.104194 | How can I create a page in Google+ for my website?I want it to have a URL like plus.google.com/+MyWebsiteName. | How to create a Google+ page for my website? | google plus;google plus pages | Sign in to your regular G+ account.At the bottom of the left panel, click Google+ for your brand.On the following screen, click Create Google+ Page.Create your Brand Account.On the following screen, under Enable Google+ for your brand, click Enable.(source)In order to get a custom URL, you need to satisfy some criteria first:Have ten or more followers (people who have added you to their circles)Account is at least 30 days old and in good standingProfile has a profile photoIf you meet the criteria, then you'll see a banner at the top of the screen when signed in to your G+ Brand page.Important: You cant change your custom URL after you create it, so be sure you like yours before you finalize it.(source) |
_webmaster.49821 | Suppose there is a website for my company named Seven Season which manufactures T-Shirts. In the website for this company, I have the following pages:HomeAbout usOur ProductsDisclaimerContact UsAll pages have unique content.But following content is the same in each link:Logo and name of the company (i.e., Seven Season)Today's date Front image slide showScrolled company sloganNavigation menu having links of: Home, About us, Our Products, Disclaimer, Contact UsI want to confirm that:Because of above 5 content items which are the same on each page, would I be penalized for duplicate content?Are all these repeated items treated as duplicate content by search engines?If these are considered to be duplicate content, then if I mention the company name as Seven Season in my Home page, then Six Season in my About Us page, and then Five Season in my Product page...is this alternative wise according to SEO?To provide unique content, should I add different menu options in different pages?Should I mention different dates as Today's date in each page? | Would using the same name, logo, date, and menu on each page be considered duplicate content? | seo | null |
_webapps.23980 | On my Facebook account there is an automatically created photo album called Profile Pictures which contains all the images I've used as profile pictures in the past. I'd like to set one of these images to be my profile picture (not the one which is currently my profile picture, of course). Is there some way to do this without having to upload a new copy of the same image? | Reusing an old Facebook profile picture | facebook;profile picture | Click your name or existing profile photo at the upper left corner of the screen to go into your profile.Once there, the third or so item under your big profile pic at upper left should be Photos. Click on this.Click on your Profile Pictures album.Click on the photo you want to use as your profile picture. It will expand into the centre of the screen with a bunch of stuff on the right.In the upper right corner there are three icons, a gear, a downward arrowhead, and an X. Click the gear icon.A drop-down menu will appear. The second-last item on the menu should be Make Profile Picture. Click on this.After a few seconds you will be back at your profile screen, with the selected picture as your profile picture. |
_codereview.135260 | I have a program which finds, well, a magic square of squares. The problem is, it's quite slow - it processes around 50 numbers in half a second when the number range is above 40,000.Is there any way to improve this code?from math import floor# checksquare checks for the possibility of a set being a magic square.# One example of an incoming list (split for readability) is:# [[1634],# [15, 25, 28], [11, 27, 28], [8, 27, 29],# [3, 28, 29], [12, 23, 31], [13, 21, 32],# [9, 23, 32], [4, 23, 33], [3, 20, 35]]# The square of each number in the lists of length 3# add up to the single number in the list of length 1.# (e.g. 15^2 + 25^2 + 28^2 = 1634)# This function checks for this possibility by doing so:# If all of the numbers in the sets of 3 are repeated at least once,# Then it outputs it to a separate file.def checksquare(listin): # listcheck only contains the lists of length 3. listcheck = listin[1:] # dictofnos is used to check the amount of each number in listcheck. dictofnos = {} # setof0s is used to remove numbers which are not repeated. setof0s = [] # The first loop checks the amount of each number in listcheck. for e in range(len(listcheck)): for f in range(3): try: dictofnos[(listcheck[e])[f]] += 1 except KeyError: dictofnos[(listcheck[e])[f]] = 1 # The second loop removes any value that is not repeated. for g in dictofnos: if dictofnos[g] == 1: for h in range(len(listcheck)): if g in listcheck[h]: for j in range(3): if dictofnos[(listcheck[h])[j]] == 0: pass dictofnos[(listcheck[h])[j]] -= 1 listcheck.remove(listcheck[h]) listcheck.append([]) for i in range(len(listcheck)): if len(listcheck[i]) != 3: listcheck.remove(listcheck[i]) # This if/elif is used to catch any lists that passed the two loops # while having non-repeating numbers. if 0 in dictofnos.values(): [setof0s.append(k) for k in dictofnos if dictofnos[k] == 0] elif 1 in dictofnos.values(): listcheck = listin[:1] + listcheck checksquare(listcheck) return None # The final loop is deleting entries in the dict which are removed # (hence the use of setof0s). for l in setof0s: del dictofnos[l] # Outputs to output.txt. if len(listcheck) != 0: output = open(output.txt, a+) output.write(\n + str(listin[0]) + \n + str(dictofnos) + \n + str(listcheck) + \n) output.close()# powers checks if 3 squares add up to a number.def powers(limit): numberrange = 3 * ((limit + 1) ** 2) for a in range(numberrange): # Everything here is for efficiency. temp = 0 templist = [[a]] check = 1 b = 0 c = int(floor((a / 4.0) ** 0.5)) d = int(floor((a / 2.0) ** 0.5)) while b <= c <= d <= limit and d ** 2 < a: b += check if b == c or (b * 2) ** 2 > a: c += 1 b = 1 continue if c == d: d += 1 c = int(floor((a / 4.0) ** 0.5)) b = 1 continue if (b + c + d) % 2 != a % 2: check = 2 b -= 1 continue if b ** 2 + c ** 2 + d ** 2 == a: templist.append([b, c, d]) temp += 1 # If 8 solutions for b^2 + c^2 + d^2 = a are found # for any a, then it is sent to checksquare. if temp >= 8: checksquare(templist)# The usage of these functions would be to put# powers(whatever the upper bound of d is).powers(100)EDIT: Added explanation (sorry if it's really long), and improved some minor things. | Program to find magic square of squares | python;performance;python 2.7;mathematics | This is at least a start. I did not look very heavily in finding a better algorithm itself, just making small improvements of you algorithm. Nevertheless this resulted in a speed-up of about 30%.For comparison (I changed the call to powers(50) so it does not take so long):# Your code$ python -m cProfile magic_square_orig2.py 81524 function calls in 3.462 seconds# With the changes below$ python -m cProfile magic_square2.py 18110 function calls (18107 primitive calls) in 2.496 secondsWith powers(75):# Your code$ python -m cProfile magic_square_orig2.py 336810 function calls in 30.210 seconds# With the changes below$ python -m cProfile magic_square2.py 148883 function calls (148880 primitive calls) in 18.832 secondsUse better names (!!)Even now, where you changed some variable names for better names, the function checksquare is very hard to understand because of variables called g, h, j, k. But since I will take away their meaning as integers below, anyways, we can find better names for them.Iterate over the contents of a listIt is always easier to iterate over the list, instead of iterating an index, compare:for i in range(len(l)): print l[i]for element in l: print elementThe latter is a lot easier to read (and understand). It is the recommended way to iterate over a list. So I changed your logic and gave the variables better names:Use collections.Counter()There is already an existing construct that builds a dictionary with counts of objects, it is callen collections.Counter. This way you can replace:for e in range(len(listcheck)): for f in range(3): try: dictofnos[(listcheck[e])[f]] += 1 except KeyError: dictofnos[(listcheck[e])[f]] = 1with:from collections import Counter...dictofnos = Counter(item for sublist in listcheck for item in sublist)Use list comprehensions where possibleList comprehensions are in general faster than manually writing the for loop, because they are implemented in C (they are not, see e.g. here) a more succinct way to write simple loops that build a list. You can replace some loops:for i in range(len(listcheck)): if len(listcheck[i]) != 3: listcheck.remove(listcheck[i])becomes one of these two:listcheck = filter(lambda powers: len(powers) == 3, listcheck)listcheck = [powers for powers in listcheck if len(powers) == 3]which seem to be about the same speed. where the latter should be slightly faster, because the filter has to take a lambda instead of a predefined function. But using the fact that the only two possible lengths are 0 and 3 and bool(0) == False and bool(3) == True we can just uselistcheck = filter(len, listcheck)in this case.function powersYou compute for example b**2 more than once. It saves quite some time if you save b2 = b**2 (and similar for the other variables) at appropriate places.int() already performs floor so it is not needed here. (int(3.14) == 3 and int(3.99) == 3)You can collect what to write to the output file and write it in one go. This should be faster than repeated opening, writing and closing of the file. For this the function checksquare needs to be adapted to return the values instead of writing it:if listcheck: return listin[0], dictofnos, listcheckand in powers we add a list to collect the return values:def powers(limit): out = [] .... if temp >= 8: squares = checksquare(templist) if squares: out.append(squares) .... return outAdditionally, we can put the writing part to a new function, separating the calculation and output part:def write_powers(n): with open(output2.txt, w) as out_file: for power in powers(n): out_file.write(\n{}\n{}\n{}\n.format(*power))This also guarantees that the file will be overwritten with each subsequent call to the script (w writes, over-writing the file, while you a+ was always appending).MiscUse the __name__ hook in order to allow importing you function from another script without executing powers(75) every time:if __name__ == __main__: write_powers(75)Use an actual set for setof0s.Resultfrom collections import Counterdef checksquare(listin): # listcheck only contains the lists of length 3. listcheck = listin[1:] # dictofnos is used to check the amount of each number in listcheck. dictofnos = Counter(factor for factors in listcheck for factor in factors) # setof0s is used to remove numbers which are not repeated. setof0s = set() # The first loop checks the amount of each number in listcheck. # The second loop removes any value that is not repeated. for factor in dictofnos: if dictofnos[factor] == 1: for factors in listcheck: if factor in factors: for power in factors: if dictofnos[power] == 0: pass dictofnos[power] -= 1 listcheck.remove(factors) #listcheck = filter(lambda powers: len(powers) == 3, listcheck) listcheck = [powers for powers in listcheck if len(powers) == 3] # This if/elif is used to catch any lists that passed the two loops # while having non-repeating numbers. if 0 in dictofnos.values(): setof0s |= set(k for k in dictofnos if dictofnos[k] == 0) elif 1 in dictofnos.values(): listcheck = listin[:1] + listcheck checksquare(listcheck) return # The final loop is deleting entries in the dict which are removed # (hence the use of setof0s). for l in setof0s: del dictofnos[l] # Outputs to output.txt. if listcheck: return listin[0], dict(dictofnos), listcheck# powers checks if 3 squares add up to a number.def powers(limit): out = [] numberrange = 3 * ((limit + 1) ** 2) for a in range(numberrange): # Everything here is for efficiency. temp = 0 templist = [[a]] check = 1 b = b2 = 0 c = int((a / 4.0) ** 0.5) d = int((a / 2.0) ** 0.5) c2, d2 = c**2, d**2 while b <= c <= d <= limit and d2 < a: b += check b2 = b**2 if b == c or 4*b2 > a: c += 1 c2 = c**2 b = b2 = 1 continue if c == d: d += 1 d2 = d**2 c = int((a / 4.0) ** 0.5) c2 = c**2 b = b2 = 1 continue if (b + c + d) % 2 != a % 2: check = 2 b -= 1 b2 = 1 continue if b2 + c2 + d2 == a: templist.append([b, c, d]) temp += 1 # If 8 solutions for b^2 + c^2 + d^2 = a are found # for any a, then it is sent to checksquare. if temp >= 8: squares = checksquare(templist) if squares: out.append(squares) return outdef write_powers(n): with open(output2.txt, w) as out_file: for power in powers(n): print power out_file.write(\n{}\n{}\n{}\n.format(*power))# The usage of these functions would be to put# powers(whatever the upper bound of d is).if __name__ == __main__: write_powers(75) |
_unix.104040 | I have a log file and I'm making a script to do some actions. An action is to print a specific area of the log.Every block at the log starts with a specific time stamp and inside the block may have other dates etc.I want to get the block that inside it there is the word exception. Tried with sed but as I know process line by line, also tried with awk and FS \n but again nothing....A part of the log file,06:14:27.9 starting web server06:14:33.3 Initializing Spring framework LogsOct 18, 2013 6:14:33 AM org.apache.catalina.startup.Embedded startINFO: Starting tomcat serverOct 18, 2013 6:14:34 AM org.apache.catalina.core.StandardEngine startINFO: Starting Servlet Engine: Apache Tomcat/6.0.32Oct 18, 2013 6:14:35 AM org.apache.catalina.startup.ContextConfig DefaultWebConfigINFO: No default web.xmlOct 18, 2013 6:14:38 AM org.apache.catalina.session.StandardManager doLoadSEVERE: IOException while loading persisted sessions: java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: ads.doc.backoffice.StoreInfosjava.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: ads.doc.backoffice.StoreInfos at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1354) at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1990) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1915)........................ at ads.tools.AppServerMain.main(AppServerMain.java:83)Caused by: java.io.NotSerializableException: ads.doc.backoffice.StoreInfosINFO: Jk running ID=0 time=0/105 config=null06:14:48.6 Starting exporter server06:14:48.6 starting cron serveranother part of a log03:19:13.4 Begin summary update for ads.doc.inventory.InventoryItemSummary03:19:33.9 CronServer:: DailyJob ads.tools.UpdateSummaries@17c5d6cf failed with exception ads.util.AppError: Cannot create UnitName from keys: Eachads.util.AppError: Cannot create UnitName from keys: Eachat ads.db.DBObjectDefault.createFromKeys(DBObjectDefault.java:42)at ads.db.DBTable.createFromKeys(DBTable.java:227)at ads.db.DBValue.getValue(DBValue.java:621)at ads.dbmanager.DBObjectsManager.initObjects(DBObjectsManager.java:400)at ads.dbmanager.DBObjectsManager.reload(DBObjectsManager.java:447)at ads.dbmanager.DBObjectsManager.loadFromStore(DBObjectsManager.java:497)at ads.doc.inventory.InventoryItemSummary.refreshSince(InventoryItemSummary.java:173)at ads.db.DBSummaryTable.refreshAll(DBSummaryTable.java:67)at ads.tools.CronServer$DailyThread.run(CronServer.java:271)[SOAPException: faultCode=SOAP-ENV:Client; msg=Error opening socket: java.net.ConnectException: Connection refused; targetException=java.lang.IllegalArgumentException: Error opening socket: java.net.ConnectException: Connection refused]at org.apache.soap.transport.http.SOAPHTTPConnection.send(SOAPHTTPConnection.java:354)at org.apache.soap.rpc.Call.invoke(Call.java:248)at ads.support.SupportCall.call(SupportCall.java:56)at ads.tools.SupportThread.run(SupportThread.java:101)03:46:42.5 Periodic support request failed: ads.support.SupportException: Error opening socket: java.net.ConnectException: Connection refused06:31:36.1 Upload failed: java.io.FileNotFoundException: c:/tmp/cygwin1.dll (No such file or directory)08:01:08.0 connect from /172.22.3.28I want to print from the first till the second last (06:14:33.3 till 06:14:48.6). And inside the log there are multiple blocks as this.Tried this:awk '/^[0-9][0-9]\:[0-9][0-9]\:[0-9][0-9]\.[0-9].*[e|E]xception.*[0-9][0-9]\:[0-9][0-9]\:[0-9][0-9]\.[0-9]/ {print}' FS=\n RS= log.txtand also this:sed '/^[0-9][0-9]\:[0-9][0-9]\:[0-9][0-9]\.[0-9].*[e|E]xception.*/,/^[0-9][0-9]\:[0-9][0-9]\:[0-9][0-9]\.[0-9]/!d' log.txtbut I can't get the result I want. | bash script, printing multiple lines that matching to a specific patern | bash;sed;awk;regular expression | null |
_webapps.100271 | I have been trying to get Net Assets and 1 Week Return for SPY on Google Spreadsheets but keep ending up with #N/A.I have been following the information from this sheet but have yet to figure out what I am doing wrong: https://support.google.com/docs/answer/3093281?hl=enMy Spreadsheet: https://docs.google.com/spreadsheets/d/1kuAhDjzZT845s0tfAMM8s85ZUkONKF_7qlAX2JKW4yA/edit?usp=sharingHave the codes for Google Finance stopped working or am I writing the codes wrong? | Google Finance / Spreadsheets | google spreadsheets;google finance | The following formula works fine:=googlefinance(spy, price)There are some attributes that are not available for some stocks, this could the the case for SPY. |
_webmaster.10300 | Quick question:I'm trying to decide on the best domain name for my niche. I have it narrowed down to the following options:keyword.comykeyword.comkeywordnetwork.comWhich of these domain names will perform the best from an SEO perspective? | SEO Domain Name Optimization | seo;domains | From an SEO perspective:keyword.co - perfect for the keyword but if you're targeting a specific country the .co (Columbia) TLD will hurt you. If not you're good to go.mykeyword.com - Good keyword usage but not targeted toward any countrykeywordnetwork.com - Good keyword usage but not targeted toward any country. If there is such a things as keyword density in domain names/URLs then technically you have diluted it a bit by having network in it but in practice this won't make much of a difference at all.Remmeber, there's more to a domain name then SEO. If you don't keep your users in mnd you've lost before you've even begun. .coms are easy to remember vs country specific TLDs. Also, it wouldn't surprise me if people accidentally added the m to .co when typing in the first one. I'm not saying it's going to happen a lot but I can see it happening simply out of habit. |
_unix.217335 | I'm debugging an issue where I think my server is spamming other servers because it is infected but all my logs stop in august last year, and rsyslog is missing from the system /etc/rsyslog.d still exists and clearly it was writing logs once but there are no new logs being generated for /var/log/mail.log or /var/log/messagesbut runningrsyslogresults in command not found, should I run: apt-get install rsyslog and then service rsyslog startand has any one seen anything like this before? | rsyslog seems to have vanished from my system | ubuntu;logs;email;rsyslog | null |
_unix.224692 | I'm working with the Octopi distro and it's supposed to have a few networking things already put together to make things easy out of the box. One of them is an easy-to-use hostname and/or DNS name: octopi.local. However it doesn't work. I can't ping it or resolve it from a Windows 7 machine. My Netgear WNDR3800 sees the name just fine in its list of connected devices.I'm using a Wi-Pi for wireless networking on the Octopi, and have configured the file octopi-network.txt with my wireless settings. I can access the Octopi's web interface from the Windows machine by using the IP address. The Windows machine is using Wi-Fi as well.I've already started another question on the Linux stack Exchange to try to get hostname resolution working on a different Raspberry Pi, and never got that working.This question is different because Octopi uses avahi (aka Bonjour) (Here's a how-to) and all the docs and videos refer to octopi.local, thereby implying that we're working with a DNS name. From what I can tell, it should work out of the box.If I try to ping/nslookup octopi/octopi.local and it fails, what should I look at next?On the Windows machine, I have tried to do an ipconfig /flushdns, nslookup octopi and nslookup octopi.local with no success. | Octopi.local does not resolve - DNS name resolution issue | networking;raspberry pi;raspbian | As it turns out, there is an FAQ question on the Octprint/Octopi FAQ that addresses this very same question, and there's plenty of detail too (reprinted below). I can't reach my OctoPi under octopi.local under Windows, why?The third post has some good details about this issue:Octoprint discussionI can't reach my OctoPi under octopi.local under Windows, why?That .local part makes it a special address. Linux and MacOS already know how to understand it, Windows needs a little extra help.You'll have to download the Bonjour Print Services for Windows and install them. Then make sure your Windows Firewall allows Traffic on UDP Port 5353 and grant internet access to the mDNSresponder.exe (part of the Bonjour support you just installed).Note: This will only work if you home LAN is not set up to use .local as it's own LAN specific top level domain. This should usually not be the case, but if it is and you can't get your home LAN setup differently (e.g. by switching to .lan) you'll need to access your OctoPi instance by its IP address, sorry. |
_softwareengineering.191344 | I'm very confused. I can't even begin to understand how MVC would be implemented outside of web development. This might seem like too general a question, but how would one apply MVC. I have the following general questions: Are M, V, and C all meant to be one class each, or many. If many, how wouldthat work. Most classes I've made previously have had their data inside them, not in a separate class. How would this work with MVC?1) For instance, lets say you have a class where you take care of a virtual dog. I would think that you would make a Dog class with, for example, a bark command that would play a sound along with a name variable and a coat_color variable. I know this is very simple, but how would this fit inside MVC? It seems that you would end up with MC and V, where the information (model) AND the controls were in the Dog class, which would maybe access swing, or whatever library, to update the view.2) Or, what about a program like sims (simplified version) where each person would have their own information... would you put all that info in another class?Sorry if these are all based on giant misconceptions, but I'm pretty confused. Right now I'm using Java, if that matters for MVC... | How to use MVC in practice | java;design patterns;mvc;design | You're a little all over the map there, perhaps getting ahead of yourself thinking about video games and dogs and what not. The easiest way to think of MVC is to think of the responsibilities of the things in the acronyms. At its core level, each of the components answers a question:Model: What should we show the user?View: How should we show it to the user (what will it look like)?Controller: How do I figure out which models and views to show the user?So, I'd suggest digesting that a bit and perhaps focusing your questions a little. MVC is a presentation pattern, meaning that it's not the basis for your entire application nor is it a philosophy or a universal approach to software development. All it really gives you is a way to separate the responsibilities involved in presenting information to your users. In this sense, you can use it on the web or the desktop or anywhere that you show things to users. |
_softwareengineering.291494 | I am having difficulty with the answer provided here, but I couldn't understand how to implement it. My code is pretty much identical:<script language=javascript> function check(form) { if(form.userName.value == User && form.userPass.value == averyobviouspassword) { window.open('testok/menu.html') } else { alert(Wrong Password Or Username) } }</script>The problem with this is, if you were to Inspect Element on the page, you can plainly see the password. I'm not looking for other solutions like a SQL database, because this is just a test website. The solution I thought might work was this:if(hash(enteredPassword) == storedHash)I just don't know how to implement it. | Javascript Password Security | javascript;web development;security;html | null |
_unix.40856 | RPM Fusion and Livna.org are common third party package repositories for Fedora. You need them if you want to install media players, codecs and/or DVD playback libraries that are not part of the primary Fedora repository because of assumed issues like distribution licensing or similar.Thus my question how to enable them in Fedora (>= 17)? | How to add the RPM Fusion and livna repositories to Fedora? | fedora;yum;dnf;multimedia | For RPM Fusion (free repository):Get the release rpm:$ curl -O https://download1.rpmfusion.org/free/fedora/\rpmfusion-free-release-$(rpm -E %fedora).noarch.rpmCheck the archive's integrity via:$ rpm --checksig rpmfusion-free-release-$(rpm -E %fedora).noarch.rpmWhich should fail with:[..] MISSING KEYS: GPG#KEY_ID [..]Add key to your gpg keyring for checking:$ gpg --keyserver pgp.mit.edu --recv-keys KEY_ID In case the key is not available on a keyserver you have to download it from the rpmfusion key page:$ curl -o RPM-GPG-KEY-rpmfusion-free-fedora-25 'https://rpmfusion.org/\ keys?action=AttachFile&do=get&target=RPM-GPG-KEY-rpmfusion-free-fedora-25'Compare the fingerprint with the published information on the RPM Fusion key site, via a web-search and possibly check the web of trust:$ gpg --fingerprint KEY_IDIf successful make the key known to rpm:$ gpg --export -a KEY_ID > RPM-GPG-KEY-rpmfusion-free-fedora-$(rpm -E %fedora)# rpm --import RPM-GPG-KEY-rpmfusion-free-fedora-$(rpm -E %fedora)Check the integrity of the package for real:$ rpm --checksig rpmfusion-free-release-$(rpm -E %fedora).noarch.rpmIf it is ok install it:# dnf install rpmfusion-free-release-$(rpm -E %fedora).noarch.rpmOr with older Fedora versions:# yum localinstall rpmfusion-free-release-stable.noarch.rpmThis will create config files under /etc/yum.repos.d/ and key files under /etc/pki/rpm-gpg.Note that the # means that you have to execute those commands as root.For the nonfree RPM Fusion repository you have to curl the analogous setup rpm as well.For livna.org you have to:$ curl -O http://rpm.livna.org/livna-release.rpmThe other steps are analogous.In case the livna repository doesn't include the current release, yet, you can workaround that via editing /etc/yum.repos.d/livna.reposuch that:the mirrorlist line is commented outthe baseurl is commented in and the $release variable is replaced with - say - 23For example, most of the libraries available from livna for Fedora 21 should work as-is also under Fedora 23.FingerprintsAs the time of writing the following keys were used:https://download1.rpmfusion.org/free/fedora/\ rpmfusion-free-release-25.noarch.rpmKEY_ID: 6806A9CBkey fingerprint: 286F 52F7 E9D4 7B46 3EAD D8AB A1E5 4A0F 6806 A9CBhttp://rpm.livna.org/livna-release.rpmsha256: 18d08b96bc0d6912ba2e957a33ff5c50d7f8f3bae710f5186f3ebc0c78458e13KEY_ID: a109b1eckey fingerprint: 037B 5D9B E1B6 B673 2A23 13B5 7129 5441 A109 B1E |
_webmaster.69034 | I'm now working in a server environment where I can access and edit httpd.conf, which is preferable from a performance and a revision control standpoint. I have a few sites (they are Drupal) running in subdirectories along the lines of dev.blah.com/yourname, dev.blah.com/anothername, dev.blah.com/anotherdev. Right now they have a rewrite rule along the lines of RewriteBase /yournamein each of their htaccess files. This doesn't work in httpd.conf and some of the documentation I've been reading says Rewritebase is bad to put in httpd.conf anyway. Any insight into the right approach would be greatly appreciated. | Moving RewriteBase rule in htaccess to httpd.conf | apache;subdirectory | null |
_cs.23096 | so I am a bit confused here. I read a memory-map ranging from certain hex values and I'm trying to find out how large RAM is by it. Here's the code:const char *memorybottom = 0x00000000;const char *memorytop = 0xAA55D0AB;The bottom is 0, and the top is AA55D0AB. I tried to convert that to binary and increased each 2 byte by a power of 2, left to right, but the result is 0.25 kilobytes; 256 bytes, which is 1/4th of a kilobyte. However, someone told me that AA55D0AB is for MB sized RAM.Can anyone help me translate between hex to determine maximum RAM capacity in MB, GB, KB, etc.? PS: This is for emulation. I am trying to emulate memory for an Atari 2600 by providing a lowest mem. value pointer to memorybottom, and the opposite with memorytop. However, I am not too familiar with hex but better with binary. | How to find out memory size by hex ranges? | memory hardware | null |
_cstheory.21019 | A graph is an interval graph iff it is chordal and asteroidal triple free.An interval graph is proper interval graph iff it is $K_{1,3}$ free.However i googled intensely to find a minimal set of forbidden subgraphs for proper interval graphs,but in vain.My question is : What are the minimal set of forbidden subgraphs for proper interval graphs ?Any link to journal/paper is welcome. | Forbidden subgraph characterisation of interval graphs | graph theory;graph algorithms;interval graphs | ISGCI's page on proper interval graphs (from our FAQ) lists a few equivalent classes; one of them is the class of $(C_{n+4}$, $S_3$, claw, net)-free graphs (see the same website for definitions). |
_cs.2794 | I have the grammar: $\qquad \begin{align} S &\to S = P \mid S \neq P \mid P \\ P &\to NUM\end{align}$This grammar suffers from left recursion. To eliminate left recursion, I got: $\qquad \begin{align} S &\to PS' \\ S' &\to\, = PS' \mid\, \neq PS' \mid \varepsilon \\ P &\to NUM\end{align}$However when constructing the LL(1) parsing table, it turns out the grammar is ambiguous. Is there a way to disambiguate the grammar without changing the generated language, or did I make a mistake somewhere?This is my work so far: Non-terminal Nullable First FollowS False NUM $ S' True !=, ==, epsilon $P False NUM $, ==, !=Parse Table != == NUM $S ->PS'S' ->!=PS' ->==PS' ->epsilonP ->NUM | Is this grammar ambiguous? | formal grammars;parsers;ambiguity | null |
_unix.60901 | Possible Duplicate:Recover formatted ext3 partition I have a folder of about 5GB that suddenly disappeared. When I checked its hard disk, I found out it has bad sector for about 2-3MB on this folder. Maybe it is on the folder's pointer.The partition is EXT3 , and operating system is Debian.I tried the fsck command , but it hasn't worked.What should I do? How can I recover data? Any program or command? | Recover ext3 files from hard disk with bad sector | debian;ext3;fsck | Maybe testdisk will handle this. |
_unix.59950 | If I were connected by wifi in my network, there isn't any problem because with AirDroid I can access the sdcard files using the browser.However when I am out, how can I transfer a file from my phone to my PC? I can access my PC using SSH, but then from the PC I can't access the phone for get file using SCP.I guess the question is: Is there any app that allow do such action? I think the only possible thing is install a SSH server in the phone, isn't it? | Transfer a file from Android to a PC (not in the same network) | linux;ssh;scp;android | null |
_datascience.18140 | Say we have used the TFIDF transform to encode documents into continuous-valued features. How would we now use this as input to a Naive Bayes classifier? Bernoulli naive-bayes is out, because our features aren't binary anymore.Seems like we can't use Multinomial naive-bayes either, because the values are continuous rather than categorical. As an alternative, would it be appropriate to use gaussian naive bayes instead? Are TFIDF vectors likely to hold up well under the gaussian-distribution assumption? The sci-kit learn documentation for MultionomialNB suggests the following:The multinomial Naive Bayes classifier is suitable for classification with discrete features (e.g., word counts for text classification). The multinomial distribution normally requires integer feature counts. However, in practice, fractional counts such as tf-idf may also work.Isn't it fundamentally impossible to use fractional values for MultinomialNB?As I understand it, the likelihood function itself assumes that we are dealing with discrete-counts:(From Wikipedia):${\displaystyle p(\mathbf {x} \mid C_{k})={\frac {(\sum _{i}x_{i})!}{\prod _{i}x_{i}!}}\prod _{i}{p_{ki}}^{x_{i}}}$How would TFIDF values even work with this formula, since the $x_i$ values are all required to be discrete counts? | How to use TFIDF vectors with multinomial naive bayes? | scikit learn;naive bayes classifier;text | null |
_webapps.47103 | I'm trying to find the first archived message in a Google Group (brought over from Usenet, alt.games.sf2).The default view for Google Groups is most recent first, which makes sense.However, I can't seem to find a way to reverse that (not that I want to read all of them going forward).I can filter by a certain date range, but I'm not sure of which range I'm looking for. I know I could whittle it down by using old date ranges and then moving forward, but it seems like there should be a way to do this with a simple sort.I can't seem to find anything in the settings either to dictate sort order. | How to view posts from oldest to newest in Google Groups | google groups;usenet | Google Groups doesn't sort posts or threads by oldest first.The topics view displays threads by the most recent first.The search results view has two sorting options, by relevance and by date, but by date is sorted by most recent first too.Maybe the next will help you:According to Get started with Usenet on Google Groups - Groups Help the oldest USENET post on Google Groups is from May 11, 1981. |
_unix.367927 | I recently installed Debian 8 on a GoBook XR-1 laptop. Debian detects it as having a Realtek ALC260 sound card.The sound card worked fine when Windows was installed.I previously had an identical model of laptop running Debian 7 and sound worked after following the steps found at Askubuntu . These steps failed in Debian 8, causing Debian 8 to not boot up until I deleted the files in recovery mode.I unmuted sound using alsamixer. AlsaMixer v1.0.28 Card: HDA Intel F1: Help Chip: Realtek ALC260 F2: System information View: F3:[Playback] F4: Capture F5: All F6: Select sound card Item: Master [dB gain: -20.00] Esc: Exit OO OO OO MM MM MM MM 41 25 100<>100 1<>1 0<>0 0<>0 0<>0 < Master >Speaker PCM Line CD Mic Beep I also tried changing from the HDA Intel/Realtek ALC260 to PulseAudio in alsamixer. AlsaMixer v1.0.28 Card: PulseAudio F1: Help Chip: PulseAudio F2: System information View: F3:[Playback] F4: Capture F5: All F6: Select sound card Item: Master Esc: Exit OO 97<>97 < Master > I tried unmuting sound from the FN keys.I tried using an external speaker, and using it without.When I play an MP3 with mplayer, then run pavucontrol, the bar pavucontrol indicates that sound is playing. When I mute the sound in alsamixer, this bar stops moving.Output of dmesg | grep snd:[ 9.499756] snd_hda_intel 0000:00:1b.0: irq 46 for MSI/MSI-XOutput of dmesg | grep sound:[ 10.029252] sound hdaudioC0D0: autoconfig: line_outs=1 (0xf/0x0/0x0/0x0/0x0) type:line[ 10.029258] sound hdaudioC0D0: speaker_outs=1 (0x11/0x0/0x0/0x0/0x0)[ 10.029262] sound hdaudioC0D0: hp_outs=0 (0x0/0x0/0x0/0x0/0x0)[ 10.029265] sound hdaudioC0D0: mono: mono_out=0x0[ 10.029268] sound hdaudioC0D0: inputs:[ 10.029271] sound hdaudioC0D0: Mic=0x12[ 10.029274] sound hdaudioC0D0: Line=0x14[ 10.029277] sound hdaudioC0D0: CD=0x16[ 10.094057] input: HDA Digital PCBeep as /devices/pci0000:00/0000:00:1b.0/sound/card0/hdaudioC0D0/input15Output of sudo alsactl init:Found hardware: HDA-Intel Realtek ALC260 HDA:10ec0260,02601635,00100400 HDA:10573055,10573055,00100700 0x14ff 0xa001Hardware is initialized using a generic methodOutput of lspci -nn | grep Audio:00:1b.0 Audio device [0403]: Intel Corporation NM10/ICH7 Family High Definition Audio Controller [8086:27d8] (rev 02)UpdateTurning off PulseAudio with pulseaudio --kill, then switching alsamixer to the audio card does not work, even when testing aplay /usr/share/sounds/alsa/Noise.wav.Output of cat /proc/asound/card*/codec\#*:Codec: Realtek ALC260Address: 0AFG Function Id: 0x1 (unsol 1)Vendor Id: 0x10ec0260Subsystem Id: 0x02601635Revision Id: 0x100400No Modem Function Group foundDefault PCM: rates [0x560]: 44100 48000 96000 192000 bits [0xe]: 16 20 24 formats [0x1]: PCMDefault Amp-In caps: N/ADefault Amp-Out caps: N/AState of AFG node 0x01: Power states: D0 D1 D2 D3 Power: setting=D0, actual=D0GPIO: io=4, o=0, i=0, unsolicited=1, wake=0 IO[0]: enable=0, dir=0, wake=0, sticky=0, data=0, unsol=0 IO[1]: enable=0, dir=0, wake=0, sticky=0, data=0, unsol=0 IO[2]: enable=0, dir=0, wake=0, sticky=0, data=0, unsol=0 IO[3]: enable=0, dir=0, wake=0, sticky=0, data=0, unsol=0Node 0x02 [Audio Output] wcaps 0x11: Stereo Device: name=ALC260 Analog, type=Audio, device=0 Converter: stream=5, channel=0 PCM: rates [0x560]: 44100 48000 96000 192000 bits [0xe]: 16 20 24 formats [0x1]: PCMNode 0x03 [Audio Output] wcaps 0x211: Stereo Digital Converter: stream=0, channel=0 Digital: Digital category: 0x0 IEC Coding Type: 0x0 PCM: rates [0x560]: 44100 48000 96000 192000 bits [0x1e]: 16 20 24 32 formats [0x1]: PCMNode 0x04 [Audio Input] wcaps 0x10011b: Stereo Amp-In Control: name=Capture Volume, index=0, device=0 ControlAmp: chs=3, dir=In, idx=0, ofs=0 Control: name=Capture Switch, index=0, device=0 ControlAmp: chs=3, dir=In, idx=0, ofs=0 Device: name=ALC260 Analog, type=Audio, device=0 Amp-In caps: ofs=0x00, nsteps=0x23, stepsize=0x03, mute=1 Amp-In vals: [0x0c 0x0c] Converter: stream=1, channel=0 SDI-Select: 0 PCM: rates [0x160]: 44100 48000 96000 bits [0x6]: 16 20 formats [0x1]: PCM Connection: 7 0x12* 0x13 0x14 0x15 0x16 0x0f 0x10Node 0x05 [Audio Input] wcaps 0x10011b: Stereo Amp-In Control: name=Capture Volume, index=1, device=0 ControlAmp: chs=3, dir=In, idx=0, ofs=0 Control: name=Capture Switch, index=1, device=0 ControlAmp: chs=3, dir=In, idx=0, ofs=0 Device: name=ALC260 Alt Analog, type=Audio, device=2 Amp-In caps: ofs=0x00, nsteps=0x23, stepsize=0x03, mute=1 Amp-In vals: [0x80 0x80] Converter: stream=0, channel=0 SDI-Select: 0 PCM: rates [0x160]: 44100 48000 96000 bits [0x6]: 16 20 formats [0x1]: PCM Connection: 8 0x12* 0x13 0x14 0x15 0x16 0x07 0x0f 0x10Node 0x06 [Audio Input] wcaps 0x100391: Stereo Digital Converter: stream=0, channel=0 SDI-Select: 0 Digital: Digital category: 0x0 IEC Coding Type: 0x0 PCM: rates [0x160]: 44100 48000 96000 bits [0x1e]: 16 20 24 32 formats [0x1]: PCM Unsolicited: tag=00, enabled=0 Connection: 1 0x19Node 0x07 [Audio Mixer] wcaps 0x20010b: Stereo Amp-In Control: name=Mic Playback Volume, index=0, device=0 ControlAmp: chs=3, dir=In, idx=0, ofs=0 Control: name=Mic Playback Switch, index=0, device=0 ControlAmp: chs=3, dir=In, idx=0, ofs=0 Control: name=Line Playback Volume, index=0, device=0 ControlAmp: chs=3, dir=In, idx=2, ofs=0 Control: name=Line Playback Switch, index=0, device=0 ControlAmp: chs=3, dir=In, idx=2, ofs=0 Control: name=CD Playback Volume, index=0, device=0 ControlAmp: chs=3, dir=In, idx=4, ofs=0 Control: name=CD Playback Switch, index=0, device=0 ControlAmp: chs=3, dir=In, idx=4, ofs=0 Control: name=Beep Playback Volume, index=0, device=0 ControlAmp: chs=3, dir=In, idx=5, ofs=0 Control: name=Beep Playback Switch, index=0, device=0 ControlAmp: chs=3, dir=In, idx=5, ofs=0 Amp-In caps: ofs=0x23, nsteps=0x41, stepsize=0x03, mute=1 Amp-In vals: [0x00 0x00] [0x80 0x80] [0x33 0x33] [0x80 0x80] [0x00 0x00] [0x2d 0x2d] [0x80 0x80] [0x80 0x80] Connection: 8 0x12 0x13 0x14 0x15 0x16 0x17 0x0f 0x10Node 0x08 [Audio Mixer] wcaps 0x20010f: Stereo Amp-In Amp-Out Control: name=PCM Playback Volume, index=0, device=0 ControlAmp: chs=3, dir=Out, idx=0, ofs=0 Amp-In caps: ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1 Amp-In vals: [0x00 0x00] [0x00 0x00] Amp-Out caps: ofs=0x40, nsteps=0x40, stepsize=0x03, mute=0 Amp-Out vals: [0x2f 0x2f] Connection: 2 0x02 0x07Node 0x09 [Audio Mixer] wcaps 0x20010f: Stereo Amp-In Amp-Out Amp-In caps: ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1 Amp-In vals: [0x00 0x00] [0x80 0x80] Amp-Out caps: ofs=0x40, nsteps=0x40, stepsize=0x03, mute=0 Amp-Out vals: [0x40 0x40] Connection: 2 0x02 0x07Node 0x0a [Audio Mixer] wcaps 0x20010e: Mono Amp-In Amp-Out Control: name=Speaker Playback Volume, index=0, device=0 ControlAmp: chs=1, dir=Out, idx=0, ofs=0 Amp-In caps: ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1 Amp-In vals: [0x00] [0x00] Amp-Out caps: ofs=0x23, nsteps=0x41, stepsize=0x03, mute=0 Amp-Out vals: [0x2d] Connection: 2 0x02 0x07Node 0x0b [Audio Selector] wcaps 0x300101: Stereo Connection: 2 0x08* 0x09Node 0x0c [Audio Selector] wcaps 0x300101: Stereo Connection: 2 0x08* 0x09Node 0x0d [Audio Selector] wcaps 0x300101: Stereo Connection: 2 0x08* 0x09Node 0x0e [Audio Selector] wcaps 0x300101: Stereo Connection: 2 0x08* 0x09Node 0x0f [Pin Complex] wcaps 0x40018d: Stereo Amp-Out Control: name=PCM Playback Switch, index=0, device=0 ControlAmp: chs=3, dir=Out, idx=0, ofs=0 Control: name=Line Out Phantom Jack, index=0, device=0 Amp-Out caps: ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1 Amp-Out vals: [0x00 0x00] Pincap 0x0001003f: IN OUT HP EAPD Detect Trigger ImpSense EAPD 0x2: EAPD Pin Default 0x01014110: [Jack] Line Out at Ext Rear Conn = 1/8, Color = Green DefAssociation = 0x1, Sequence = 0x0 Misc = NO_PRESENCE Pin-ctls: 0xc0: OUT HP Unsolicited: tag=00, enabled=0 Connection: 1 0x08Node 0x10 [Pin Complex] wcaps 0x40018d: Stereo Amp-Out Amp-Out caps: ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1 Amp-Out vals: [0x80 0x80] Pincap 0x0001003f: IN OUT HP EAPD Detect Trigger ImpSense EAPD 0x2: EAPD Pin Default 0x411111f0: [N/A] Speaker at Ext Rear Conn = 1/8, Color = Black DefAssociation = 0xf, Sequence = 0x0 Misc = NO_PRESENCE Pin-ctls: 0x20: IN Unsolicited: tag=00, enabled=0 Connection: 1 0x09Node 0x11 [Pin Complex] wcaps 0x40010c: Mono Amp-Out Control: name=Speaker Playback Switch, index=0, device=0 ControlAmp: chs=1, dir=Out, idx=0, ofs=0 Control: name=Speaker Phantom Jack, index=0, device=0 Amp-Out caps: ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1 Amp-Out vals: [0x00] Pincap 0x00000010: OUT Pin Default 0x99030120: [Fixed] Line Out at Int ATAPI Conn = ATAPI, Color = Unknown DefAssociation = 0x2, Sequence = 0x0 Misc = NO_PRESENCE Pin-ctls: 0x40: OUT Connection: 1 0x0aNode 0x12 [Pin Complex] wcaps 0x40018d: Stereo Amp-Out Control: name=Mic Phantom Jack, index=0, device=0 Amp-Out caps: ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1 Amp-Out vals: [0x80 0x80] Pincap 0x0000133f: IN OUT HP Detect Trigger ImpSense Vref caps: HIZ 50 80 Pin Default 0x01a1993e: [Jack] Mic at Ext Rear Conn = 1/8, Color = Pink DefAssociation = 0x3, Sequence = 0xe Misc = NO_PRESENCE Pin-ctls: 0x21: IN VREF_50 Unsolicited: tag=00, enabled=0 Connection: 1 0x0bNode 0x13 [Pin Complex] wcaps 0x40018d: Stereo Amp-Out Amp-Out caps: ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1 Amp-Out vals: [0x80 0x80] Pincap 0x0000133f: IN OUT HP Detect Trigger ImpSense Vref caps: HIZ 50 80 Pin Default 0x411111f0: [N/A] Speaker at Ext Rear Conn = 1/8, Color = Black DefAssociation = 0xf, Sequence = 0x0 Misc = NO_PRESENCE Pin-ctls: 0x20: IN VREF_HIZ Unsolicited: tag=00, enabled=0 Connection: 1 0x0cNode 0x14 [Pin Complex] wcaps 0x40018d: Stereo Amp-Out Control: name=Line Phantom Jack, index=0, device=0 Amp-Out caps: ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1 Amp-Out vals: [0x80 0x80] Pincap 0x0000133f: IN OUT HP Detect Trigger ImpSense Vref caps: HIZ 50 80 Pin Default 0x01813130: [Jack] Line In at Ext Rear Conn = 1/8, Color = Blue DefAssociation = 0x3, Sequence = 0x0 Misc = NO_PRESENCE Pin-ctls: 0x20: IN VREF_HIZ Unsolicited: tag=00, enabled=0 Connection: 1 0x0dNode 0x15 [Pin Complex] wcaps 0x40018d: Stereo Amp-Out Amp-Out caps: ofs=0x00, nsteps=0x00, stepsize=0x00, mute=1 Amp-Out vals: [0x80 0x80] Pincap 0x0000133f: IN OUT HP Detect Trigger ImpSense Vref caps: HIZ 50 80 Pin Default 0x411111f0: [N/A] Speaker at Ext Rear Conn = 1/8, Color = Black DefAssociation = 0xf, Sequence = 0x0 Misc = NO_PRESENCE Pin-ctls: 0x20: IN VREF_HIZ Unsolicited: tag=00, enabled=0 Connection: 1 0x0eNode 0x16 [Pin Complex] wcaps 0x400001: Stereo Control: name=CD Phantom Jack, index=0, device=0 Pincap 0x00000020: IN Pin Default 0x99330131: [Fixed] CD at Int ATAPI Conn = ATAPI, Color = Unknown DefAssociation = 0x3, Sequence = 0x1 Misc = NO_PRESENCE Pin-ctls: 0x00:Node 0x17 [Pin Complex] wcaps 0x400000: Mono Pincap 0x00000020: IN Pin Default 0x99830132: [Fixed] Line In at Int ATAPI Conn = ATAPI, Color = Unknown DefAssociation = 0x3, Sequence = 0x2 Misc = NO_PRESENCE Pin-ctls: 0x00:Node 0x18 [Pin Complex] wcaps 0x400380: Mono Digital Pincap 0x00000014: OUT Detect Pin Default 0x411111f0: [N/A] Speaker at Ext Rear Conn = 1/8, Color = Black DefAssociation = 0xf, Sequence = 0x0 Misc = NO_PRESENCE Pin-ctls: 0x00: Unsolicited: tag=00, enabled=0 Connection: 1 0x03Node 0x19 [Pin Complex] wcaps 0x400280: Mono Digital Pincap 0x00000024: IN Detect Pin Default 0x411111f0: [N/A] Speaker at Ext Rear Conn = 1/8, Color = Black DefAssociation = 0xf, Sequence = 0x0 Misc = NO_PRESENCE Pin-ctls: 0x00: Unsolicited: tag=00, enabled=0Node 0x1a [Vendor Defined Widget] wcaps 0xf00040: Mono Processing caps: benign=0, ncoeff=13Node 0x1b [Volume Knob Widget] wcaps 0x600080: Mono Volume-Knob: delta=0, steps=64, direct=0, val=61 Unsolicited: tag=00, enabled=0 Connection: 0Codec: Motorola Si3054Address: 1MFG Function Id: 0x2 (unsol 1)Vendor Id: 0x10573055Subsystem Id: 0x10573055Revision Id: 0x100700Modem Function Group: 0x1Output of lspci -nn:00:00.0 Host bridge [0600]: Intel Corporation Mobile 945GM/PM/GMS, 943/940GML and 945GT Express Memory Controller Hub [8086:27a0] (rev 03)00:01.0 PCI bridge [0604]: Intel Corporation Mobile 945GM/PM/GMS, 943/940GML and 945GT Express PCI Express Root Port [8086:27a1] (rev 03)00:1b.0 Audio device [0403]: Intel Corporation NM10/ICH7 Family High Definition Audio Controller [8086:27d8] (rev 02)00:1c.0 PCI bridge [0604]: Intel Corporation NM10/ICH7 Family PCI Express Port 1 [8086:27d0] (rev 02)00:1c.1 PCI bridge [0604]: Intel Corporation NM10/ICH7 Family PCI Express Port 2 [8086:27d2] (rev 02)00:1c.2 PCI bridge [0604]: Intel Corporation NM10/ICH7 Family PCI Express Port 3 [8086:27d4] (rev 02)00:1c.3 PCI bridge [0604]: Intel Corporation NM10/ICH7 Family PCI Express Port 4 [8086:27d6] (rev 02)00:1c.4 PCI bridge [0604]: Intel Corporation 82801GR/GH/GHM (ICH7 Family) PCI Express Port 5 [8086:27e0] (rev 02)00:1d.0 USB controller [0c03]: Intel Corporation NM10/ICH7 Family USB UHCI Controller #1 [8086:27c8] (rev 02)00:1d.1 USB controller [0c03]: Intel Corporation NM10/ICH7 Family USB UHCI Controller #2 [8086:27c9] (rev 02)00:1d.2 USB controller [0c03]: Intel Corporation NM10/ICH7 Family USB UHCI Controller #3 [8086:27ca] (rev 02)00:1d.3 USB controller [0c03]: Intel Corporation NM10/ICH7 Family USB UHCI Controller #4 [8086:27cb] (rev 02)00:1d.7 USB controller [0c03]: Intel Corporation NM10/ICH7 Family USB2 EHCI Controller [8086:27cc] (rev 02)00:1e.0 PCI bridge [0604]: Intel Corporation 82801 Mobile PCI Bridge [8086:2448] (rev e2)00:1f.0 ISA bridge [0601]: Intel Corporation 82801GHM (ICH7-M DH) LPC Interface Bridge [8086:27bd] (rev 02)00:1f.2 IDE interface [0101]: Intel Corporation 82801GBM/GHM (ICH7-M Family) SATA Controller [IDE mode] [8086:27c4] (rev 02)01:00.0 VGA compatible controller [0300]: Advanced Micro Devices, Inc. [AMD/ATI] RV370/M22 [Mobility Radeon X300] [1002:5460]02:00.0 Ethernet controller [0200]: LSI Corporation ET-131x PCI-E Ethernet Controller [11c1:ed00] (rev 03)06:00.0 Network controller [0280]: Intel Corporation PRO/Wireless 3945ABG [Golan] Network Connection [8086:4222] (rev 02)0b:03.0 CardBus bridge [0607]: O2 Micro, Inc. OZ711MP1/MS1 MemoryCardBus Controller [1217:7134] (rev 21)0b:03.1 CardBus bridge [0607]: O2 Micro, Inc. OZ711MP1/MS1 MemoryCardBus Controller [1217:7134] (rev 21)0b:03.4 FireWire (IEEE 1394) [0c00]: O2 Micro, Inc. Firewire (IEEE 1394) [1217:00f7] (rev 02)What can I do to get sound working on my laptop? | Why does no sound play with Realtek ALC260 driver in Debian? | debian;audio | null |
_unix.124502 | How do you share a directory/home/sharedbetween two users eris and discordia such that both can access the directory in their respective home directory, e.g./home/eris/sharedand/home/discordia/sharedand both have full recursive read and write permission on the respective directory? The directories should lie on the same filesystem.I tried using bind mounts and ACLs but these do not work well when moving (and copying?) files into the shared directory, in which case the default ACL will not be applied and the files will keep their original permissions instead,The same holds for using the setguid flag,bindfs with the mirror option does what I am looking for, but at the cost of dramatically poor performance, as shown by Guy Paddock.setting the global umask to 002 is not an option,neither is using vfat. | Sharing a local directory between local users with full permissions | permissions;files;mount;file sharing | null |
_unix.176215 | Exactly what is the difference between devfs and sysfs? Both seem to maintain a list of hardwares attached to the system. Then why the need for 2 separate fs even arose? As far as I can get /sys maintains somewhat raw list of devices(like ser0). Udev acts on those devices, gets various informations and applies various rules to present them as recognizable names which are then mapped onto /dev(like camera). Is this the only reason? And then we mount the corresponding devices from the /dev fs(can't we do that from the /sys fs) into the /media fs. I have read the answer at Difference between /dev and /sys/class?. But I cannot get the sys fs part where it states that Sysfs contain the hierarchy of devices, as they are attached to the computerAre the files in /sys not device node files? Then what type of files are they? | Difference between /dev and /sys | linux;mount;devices;udev;sysfs | null |
_cs.27625 | I am currently reading and watching about genetic algorithm and I find it very interesting (I haven't had the chance to study it while I was at the university).I understand that mutations are based on probability (randomness is the root of evolution) but I don't get why survival is.From what I understand, an individual $I$ having a fitness $F(i)$ such as for another individual $J$ having a fitness $F(j)$ we have $F(i) > F(j)$, then $I$ has a better probability than $J$ to survive to the next generation.Probability implies that $J$ may survive and $I$ may not (with bad luck). I don't understand why this is good at all? If $I$ would always survive the selection, what would go wrong in the algorithm? My guess is that the algorithm would be similar to a greedy algorithm but I am not sure. | Why do low fitness individuals have a chance to survive to the next generation? | algorithms;optimization;genetic algorithms | The main idea is that by allowing suboptimal individuals to survive, you can switch from one peak in the evolutionary landscape to another through a sequence of small incremental mutations. On the other hand, if you only are allowed to go uphill it requires a gigantic and massively unlikely mutation to switch peaks.Here is a diagram showing the difference:Practically, this globalization property is the main sellling point of evolutionary algorithms - if you just want to find a local maxima there exist more efficient specialized techniques. (eg., L-BFGS with finite difference gradient and line search)In the real world of biological evolution, allowing suboptimal individuals to survive creates robustness when the evolutionary landscape changes. If everyone is concentrated at a peak, then if that peak becomes a valley the whole population dies (eg., dinosaurs were the most fit species until there was an asteroid strike and the evolutionary landscape changed). On the other hand, if there is some diversity in the population then when the landscape changes some will survive. |
_codereview.150207 | Here is my Go code to interact with a Redis serverpackage redisclientimport ( time gopkg.in/redis.v5)type RedisClient struct { client *redis.Client}func New() (rc * RedisClient) { return &RedisClient{ client: redis.NewClient(&redis.Options{ Addr: localhost:6379, DialTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 30 * time.Second, PoolSize: 10000, PoolTimeout: 30 * time.Second, }), }}func (rc *RedisClient) SetClient(){ if rc.client != nil{ return } rc.client = redis.NewClient(&redis.Options{ Addr: localhost:6379, DialTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second, WriteTimeout: 30 * time.Second, PoolSize: 10000, PoolTimeout: 30 * time.Second, })}// dur = int64 nanosecond count.func (rc *RedisClient) SaveKeyValTemporary(key string, val interface{}, dur time.Duration) error{ rc.SetClient() err := rc.client.Set(key, val, dur).Err() if err != nil { return err } return nil}// func (rc *RedisClient) SaveKeyValForever(key string, val interface{}) error{ rc.SetClient() return rc.SaveKeyValTemporary(key, val, 0)}// func (rc *RedisClient) DelKey(key string) (int64, error){ rc.SetClient() return rc.client.Del(key).Result()}// func (rc *RedisClient) KeyExists(key string) (bool, error){ rc.SetClient() return rc.client.Exists(key).Result()}// func (rc *RedisClient) GetVal(key string) (string, error){ rc.SetClient() return rc.client.Get(key).Result()}func (rc *RedisClient) AddToSet(setName string, Score float64, Member interface{}) (int64, error){ rc.SetClient() return rc.client.ZAdd(setName, redis.Z{Score, Member}).Result()} // returns ([]Z, error)func (rc *RedisClient) GetTop(setName string, topAmount int64) (interface{}, error){ rc.SetClient() if topAmount <= 0 { topAmount = 1 } return rc.client.ZRevRangeWithScores(setName, 0, topAmount-1).Result()}// Rank starts from 0func (rc *RedisClient) GetRank(setName string, key string) (int64, error){ rc.SetClient() return rc.client.ZRevRank(setName, key).Result()}func (rc *RedisClient) GetScore(setName string, key string) (float64, error){ rc.SetClient() return rc.client.ZScore(setName, key).Result()}func (rc *RedisClient) RemScore(setName string, key string) (int64, error){ rc.SetClient() return rc.client.ZRem(setName, key).Result()}And this is the package to test RedisClientpackage redisclient_testimport ( rcl gogameserver/redisclient testing reflect time)const tempKeyStr string = 00NeverAddThiskeytempconst keyStr string = 00NeverAddThiskeyconst valStr string = 00NeverAddThisValconst setName string = 00NeverAddThisSetconst setKey string = 00NeverAddThisSetKeyvar tempStrs = [] string{00NeverAddThiskey0, 00NeverAddThiskey1, 00NeverAddThiskey2, 00NeverAddThiskey3, 00NeverAddThiskey4, 00NeverAddThiskey5}func TestSaveKeyValTemporary(t *testing.T) { rc := rcl.New() rc.SaveKeyValTemporary(tempKeyStr, valStr, 1*time.Second) // 10 seconds 10*1000 000 000 exists,_ := rc.KeyExists(tempKeyStr) if !exists { t.Errorf(Key should exist!) } time.Sleep(3 * time.Second) exists,_ = rc.KeyExists(tempKeyStr) if exists { t.Errorf(Key should be deleted!) rc.DelKey(tempKeyStr) }}func TestSaveKeyValForever(t *testing.T) { rc := rcl.New() rc.SaveKeyValForever(keyStr, valStr) exists,_ := rc.KeyExists(keyStr) if !exists { t.Errorf(Key should exist!) } rc.DelKey(keyStr)}func TestGetVal(t *testing.T) { rc := rcl.New() rc.SaveKeyValForever(keyStr, valStr) tempVal, _ := rc.GetVal(keyStr) if valStr != tempVal{ t.Errorf(Key should exist and be equal to %s!, valStr) } rc.DelKey(keyStr)}func TestAddToSet(t *testing.T) { rc := rcl.New() score := 12.0 rc.AddToSet(setName, score, setKey) tempScore, _ := rc.GetScore(setName, setKey) if tempScore != score { t.Errorf(Stored Score is wrong!) } rc.RemScore(setName, setKey)}func TestGetTop(t *testing.T) { rc := rcl.New() scores := []float64{2,1,7,4, 3} rev_sorted_scores := []float64{7,4,3} for i:=0; i<5; i++ { rc.AddToSet(setName, scores[i], tempStrs[i]) } top3,_ := rc.GetTop(setName, 3) s := reflect.ValueOf(top3) for i:=0; i<3; i++ { f := s.Index(i).Field(0) if rev_sorted_scores[i] != f.Interface() { t.Errorf(%d: %s = %v\n, i, f.Type(), f.Interface()) } } for i:=0; i<5; i++ { rc.RemScore(setName, tempStrs[i]) }}func TestGetRank(t *testing.T) { rc := rcl.New() scores := []float64{2,1,7,4, 3} for i:=0; i<5; i++ { rc.AddToSet(setName, scores[i], tempStrs[i]) } rank,_ := rc.GetRank(setName, tempStrs[2]) if rank != 0{ t.Errorf(Rank is : %d\n, rank) } for i:=0; i<5; i++ { rc.RemScore(setName, tempStrs[i]) }}func TestGetScore(t *testing.T) { rc := rcl.New() scores := []float64{2,1,7,4, 3} for i:=0; i<5; i++ { rc.AddToSet(setName, scores[i], tempStrs[i]) } for i:=0; i<5; i++ { score, _ := rc.GetScore(setName, tempStrs[i]) if score != scores[i] { t.Errorf(%d: Expected score: %f. Score is %f\n, i, scores[i], score) } } for i:=0; i<5; i++ { rc.RemScore(setName, tempStrs[i]) }}func TestRemScore(t *testing.T) { rc := rcl.New() rc.AddToSet(setName, 2, tempStrs[0]) rc.RemScore(setName, tempStrs[0]) score, _ := rc.GetScore(setName, tempStrs[0]) if score != 0 { t.Errorf(%s exists with score: %f\n, tempStrs[0], score) }}Can above code be done better?Repo is here: https://github.com/ediston/gogameserver | Redis Client: Go based Game server | go;redis | null |
_reverseengineering.3227 | I need a database of malicious code for MIPS processor Assembly or C to inject in Mibench and evaluate my detection mechanism at run time. Is there anything like this for MIPS? what about for other processors?I have shellcodes for MIPS and I want virus like codes for MIPS.Don't we have any attack benchmark for this purpose? | Is there any database of malicious code for MIPS processor to evaluate detection method? | assembly;mips | null |
_computergraphics.1640 | I've written an implementation of the sphere tracing algorithm in OpenGL 4+.As an experiment/toy project, I'm re-implementing it using the OpenGL 4.3 compute shader, but I'm having trouble with the whole local/global invocation ID thing.The basic idea is to use the compute shader to calculate the image and output it in a texture, then use a trivial program to copy it onto the framebuffer.This is the compute shader I'm using:#version 430 corelayout (binding = 0, rgba32f) writeonly uniform image2D output_image;layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in;void main(){ ivec2 coord = ivec2(gl_GlobalInvocationID.xy); imageStore(output_image, coord, vec4(0.0, 0.0, 1.0, 1.0));}This is how I initialize the texture:GLuint offscreen_texture;glGenTextures(1, &offscreen_texture);glActiveTexture(GL_TEXTURE0);glBindTexture(GL_TEXTURE_2D, offscreen_texture);glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, WINDOW_WIDTH, WINDOW_HEIGHT, 0, GL_RGBA, GL_FLOAT, nullptr);glBindImageTexture(0, offscreen_texture, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F);And these are the trivial vertex shader I'm using:#version 430 corevoid main(){ const vec4 verts[4] = vec4[4](vec4(-1.0, -1.0, 0.5, 1.0), vec4( 1.0, -1.0, 0.5, 1.0), vec4(-1.0, 1.0, 0.5, 1.0), vec4( 1.0, 1.0, 0.5, 1.0)); gl_Position = verts[gl_VertexID];}And fragment:#version 430 corelayout (location = 0) out vec4 color_out;layout(binding = 0) uniform sampler2D source_image;void main(){ color_out = texture(source_image, gl_FragCoord.xy);}And this is the render code:compute_program.use();glDispatchCompute(WINDOW_WIDTH / 16, WINDOW_HEIGHT / 16, 1);glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);copy_program.use();glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);Up to this point everything works correctly and I see my screen completely blue instead of the usual clear color.Things start to break down when I try to use the Invocation ID to generate actual data (like the rays from the camera).I tried to switch to a compute shader like:#version 430 corelayout (binding = 0, rgba32f) writeonly uniform image2D output_image;layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in;void main(){ ivec2 coord = ivec2(gl_GlobalInvocationID.xy); imageStore(output_image, coord, vec4(0.0, 0.0, coord.x / 1280.0, 1.0));}which uses the global ID to generate the blue tint of the pixel.As I understand from the OpenGL Suberbible book and the OpenGL wiki, I should be able to use the global ID as screen space coordinates (it's pretty easy to do the math using local IDs and work groups IDs and confirm that), much like gl_FragCoord, and this is confirmed by the previous trivial compute shader which paint every pixel.I would expect a sort of horizontal gradient going from black to blue as an output of this compute shader, but instead everything turns black.I've tried several combination of painting based on the local/global IDs of the threads, but I haven't got any luck no matter what.Did I misunderstand the way the whole threads ID work?What is the correct way to use them/map them to screen space coordinates like gl_FragCoord?EDIT: Just to add, I've tested this with both my integrated Intel HD 5100 and my discrete Nvidia 765M GPUs and the result is the same, so there is clearly something wrong on my side. | How to convert a thread ID into Screen Space Coord in an OpenGL Compute Shader? | opengl;glsl;compute shader;c++ | The problem is actually in your fragment shader:color_out = texture(source_image, gl_FragCoord.xy);The texture() function accepts normalized coordinates which range from 0.0 to 1.0. The gl_FragCoord built in contains window coordinates which range from (0.0, 0.0) to (window width, window height).To fix this, change the fragment shader to this:color_out = texture(source_image, gl_FragCoord.xy / vec2(1280.0, 720.0));That is assuming your window is 1280x720, change as necessary. |
_softwareengineering.187245 | I have an interesting problem for you all. I have a partial solution but I feel you guys can come up with an efficient solution. What I have a SQL table with following structure:StockId <- a unique ID for the shareStockHolderId <- a unique ID for the share holderStockPrice <- The price of the stock - if this is a request to purchase this is kept -1BuyingorSelling <- value of 1 means the holder wants to buy, value 2 means he is sellingStockQuality <- a special record that stores a value calculated based on some complex computation. The values are 1, 2, or 3 based on let us say bad, neutral, good.What I want to do is to find out who all can give me the stock I want to buy and who can purchase the ones I got. I want the person who gives a good quality stock (local value) at cheapest price (global value) to be my best selling match and the person who can buy most (semi global) of my stocks to be my best buying match. The formula to rank the seller is 0.5 * price + 0.3 * availability + 0.2 * quality. How would you go about it? Any ideas? I have created a table that joins with itself to get info of every match and then grouping but how can I acquire the price value to be cheapest? | Calculating local results from global values using SQL and PHP | algorithms | null |
_softwareengineering.342963 | I'm reading Tanenbaum's Modern Operating Systems and I really can't grasp the following concept: how does a program make a system call? I mean, i got the very basics down (correct me if I'm wrong): the OS is just another program running on the machine (the difference being that it can run in kernel mode having complete access to the machine's hardware) and when an user's program want to have a sort of advanced feature given by the OS, it tries to get it through a system call to the OS itself, writing the call's type and parameters on its stack and making a trap call. Now, I got this down, but the question is, how does a program know that, let's say, the read call on Unix is identified by the ReadFile call on the Win32 API? For example, in a program written in C, is this info known by the compiler? And let's say in the future a new OS introduces the foo system call, that does the exact same thing as the Unix's read... Well, how would a user's program know that? | How does a program make a system call | operating systems | null |
_datascience.19863 | Does test classification rate and training time the best evaluation criteria for a classifier! Basically I have used the training time and test classification rate as a criteria to evaluate my classifier ( as in many papers, many studies they used training test CR)Is there anyone could explain why test CR and training time are the most used? Once we are asked to justify why these evaluation criteria, what a good answer should be? Honstly it starts to be a habit ( as in all papers I read) we asked how long the classifer does take? and the % of correct answer.. But I need more logical answers ( more explained...) | Evaluation criteria of classifiers (test classification rate and training time) | classification | null |
_unix.212084 | I check my server on WAN with ping and https by Nagios Core 3.5.1.Here is the host alert history.June 23, 2015 18:00 Service Ok[06-23-2015 18:13:47] SERVICE ALERT: webserver;PING;OK;HARD;3;PING OK - Packet loss = 0%, RTA = 33.72 msService Ok[06-23-2015 18:13:40] SERVICE ALERT: webserver;HTTPS;OK;HARD;3;HTTP OK: HTTP/1.1 200 OK - 359 bytes in 0.201 second response timeHost Up[06-23-2015 18:06:29] HOST ALERT: webserver;UP;SOFT;8;PING OK - Packet loss = 0%, RTA = 33.92 msHost Down[06-23-2015 18:05:25] HOST ALERT: webserver;DOWN;SOFT;7;CRITICAL - Time to live exceeded (1.2.)Host Down[06-23-2015 18:04:19] HOST ALERT: webserver;DOWN;SOFT;6;PING CRITICAL - Packet loss = 100%Service Critical[06-23-2015 18:03:53] SERVICE ALERT: webserver;PING;CRITICAL;HARD;3;PING CRITICAL - Packet loss = 100%Host Down[06-23-2015 18:03:49] HOST ALERT: webserver;DOWN;SOFT;5;PING CRITICAL - Packet loss = 100%Service Critical[06-23-2015 18:03:49] SERVICE ALERT: webserver;HTTPS;CRITICAL;HARD;3;CRITICAL - Socket timeout after 10 secondsHost Down[06-23-2015 18:02:19] HOST ALERT: webserver;DOWN;SOFT;4;(Host check timed out after 30.01 seconds)Service Critical[06-23-2015 18:01:53] SERVICE ALERT: webserver;PING;CRITICAL;SOFT;2;PING CRITICAL - Packet loss = 100%Service Critical[06-23-2015 18:01:49] SERVICE ALERT: webserver;HTTPS;CRITICAL;SOFT;2;CRITICAL - Socket timeout after 10 secondsHost Down[06-23-2015 18:01:48] HOST ALERT: webserver;DOWN;SOFT;3;(Host check timed out after 30.01 seconds)Host Down[06-23-2015 18:00:18] HOST ALERT: webserver;DOWN;SOFT;2;PING CRITICAL - Packet loss = 100%June 23, 2015 17:00 Service Critical[06-23-2015 17:59:53] SERVICE ALERT: webserver;PING;CRITICAL;SOFT;1;PING CRITICAL - Packet loss = 100%Service Critical[06-23-2015 17:59:49] SERVICE ALERT: webserver;HTTPS;CRITICAL;SOFT;1;CRITICAL - Socket timeout after 10 secondsHost Down[06-23-2015 17:58:48] HOST ALERT: webserver;DOWN;SOFT;1;(Host check timed out after 30.02 seconds)Service Ok[06-23-2015 17:29:48] SERVICE ALERT: webserver;PING;OK;SOFT;2;PING OK - Packet loss = 0%, RTA = 34.72 msSo, 17:29 o'clock was everthing all right.17:58 o'clock till 18:05 o'clock was Packet loss = 100% and Socket timeout.My Question is, why didn't I get a notification?Some days bevor and today I get warning notifications just fine, but I never get a critical notification.Here is my contact.cfgdefine contact{ contact_name nagiosadmin ; Short name of user use generic-contact ; Inherit default values from generic-contact template (defined above) alias Nagios Admin ; Full name of user email user@localhost ; <<***** CHANGE THIS TO YOUR EMAIL ADDRESS ****** }Here is my templates.cfgdefine contact{ name generic-contact ; The name of this contact template service_notification_period 24x7 ; service notifications can be sent anytime host_notification_period 24x7 ; host notifications can be sent anytime service_notification_options w,u,c,r,f,s ; send notifications for all service states, flapping events, and scheduled downtime events host_notification_options d,u,r,f,s ; send notifications for all host states, flapping events, and scheduled downtime events service_notification_commands notify-service-by-email ; send service notifications via email host_notification_commands notify-host-by-email ; send host notifications via email register 0 ; DONT REGISTER THIS DEFINITION - ITS NOT A REAL CONTACT, JUST A TEMPLATE! } | Nagios missing alert notification | nagios | null |
_codereview.115907 | From SICPExercise 2.27: Modify your deep-reverse procedure of Exercise 2.18 to produce a deep-deep-reverse procedure that takes a list as argument and returns as its value the list with its elements deep-reversed and with all sublists deep-deep-reversed as well. For example, (define x (list (list 1 2) (list 3 4)))x((1 2) (3 4))(deep-reverse x)((3 4) (1 2))(deep-deep-reverse x)((4 3) (2 1))Please review my code.(define (deep-deep-reverse lst) (cond ((null? lst) '()) ((list? lst) (append (deep-deep-reverse (cdr lst)) (list (deep-deep-reverse (car lst))))) (else lst)))I spent an hour doing this, and I am actually extremely surprise on how small this code is in the end. How can I improve this code? Perhaps make it faster? | SICP - exercise 2.27 - reversing elements of a list and sublists | performance;beginner;lisp;scheme;sicp | If you actually indented it that way please use an editor that doesautomatically - usually the individual cases of the cond should align,e.g. like so:(define (deep-deep-reverse lst) (cond ((null? lst) '()) ((list? lst) (append (deep-deep-reverse (cdr lst)) (list (deep-deep-reverse (car lst))))) (else lst)))The function looks good. For clarity it might make sense to move themiddle case to the end, but it's not like that changes much.However consider that append used in this way is quite expensivebecause it repeatedly recreates a long list (from the cdr recursion)to stick the short list (from the car part) at the end.(As an exercise for the reader) you can use an accumulator instead toavoid append completely (instead cons is enough). The functionwould look pretty similar:(define (deep-deep-reverse2 lst) (define (aux lst acc) ...) (aux lst '())) |
_softwareengineering.236668 | Imagine a small local business (in my case a dog daycare) with a few dozen part-time employees . The goal is to automatically create weekly staff schedules. My question is about what algorithmic approaches to explore for this problem.There are many constraints to keep in mind, chiefly (1) the availability of the staff and (2) the needs of each shift, not just how many staff for each shift but the skills needed for each shift (e.g. for a certain shift, you may need someone who knows how to drive to do pick-ups/drop-off of dogs, for another, someone who know how to give dogs baths, etc). Other constraints include things like avoiding or requiring certain staff combos -- perhaps due to personality conflicts on one hand, or need for training by osmosis from a senior to junior staff on the other.Also, there are preferences to take into account. Some staff prefer mornings, some two days in a row rather than say Monday and Thursday, etc. We know we can't always accommodate everyone's preferences. In fact we have a hierarchy of which employees get first dibs on their choices.I have a hunch that there is a way to reduce or express this problem into an existing, already solved algorithm. But I don't know which algorithms to explore. Which existing, specific algorithms would be most promising? | What algorithm should I use to create an automatic staff scheduling feature? | algorithms | Algorithms such as Local Search (Tabu Search, Simulated Annealing, Late Acceptance) work very well on such problems.As Bob suggests, if you're working in Java, take a look at OptaPlanner (open source). See this video on employee rostering. |
_unix.365253 | I'm using Amazon Linux and am creating a bash script. I'm tryhing to email an attachment and am having success with(cat $TFILE1; uuencode $output_file $output_file) | mailx -s $subject $to_emailHowever the issue I'm having is taht the attachment is showing up (at least in Gmail) with the name noname. Is there a way I can make the attachment show up with the same name as the $output_file variable? | How do I create a file name for my email attachment? | shell script;cat;mailx;amazon linux | null |
_cs.71886 | I am stuck on a problem in which I have to print sum of 2Pi mod 1000000007 for all i where Pi is sum of numbers in ith subset of a set X.Length of set can be upto 100000.Value of element in the range [0,1012].Here's the link of the Problem.Problem StatementI could not find any approach other than Brute-Force which gives verdict TLE.@Moderators,admins etc.Before putting this question on hold or marking off-Topic or closed....Please comment the reason so that I can know the reason and if possible reword it or ask on any other StackExchange Site.I first posted it on codegolf.stackexchange.com and people(moderators) there have suggested me to post it here as it comes under algorithm category.You can read about it here.Programming Puzzles and Code golfThank You | Sum of 2^Pi mod 1000000007 for all i where Pi is sum of numbers in ith subset of a set X | discrete mathematics;sets | If the set you're using is $X=\{x_1,x_2, \dotsc,x_n\}$, then the expression you want to evaluate is equivalent to$$(2^{x_1}+1)(2^{x_2}+1)\dotsm(2^{x_n}+1)\bmod{1000000007}$$This isn't too hard to prove; here's an example to help you see what's going on:Suppose $X=\{a,b,c\}$. Then the subsets of $X$ are, obviously,$$\{\},\{a\},\{b\},\{c\},\{a,b\},\{a,c\},\{b,c\},\{a,b,c\}$$and the corresponding sums of elements in those subsets will be$$0,a,b,c,a+b,a+c,b+c,a+b+c$$leading to the sum$$2^0+2^a+2^b+2^c+2^{a+b}+2^{a+c}+2^{b+c}+2^{a+b+c}=(2^a+1)(2^b+1)(2^c+1)$$The general result can be established by a fairly simple induction proof. |
_softwareengineering.266311 | I run a development team that recently started using Jira and we began using agile scrum. I'm curious about a certain aspect of backlogged issues.So far I have been marking new issues as unassigned until the issues are actually assigned to anyone. Most of the time this process is done during the sprint planning meeting.A different team leader began assigning my name to the unassigned issues and changed the setting to the default assignee is myself rather than unassigned. Does this sound logical? | Scrum and backlogged issues | agile;scrum;jira | I think how you manage your Jira is really up to you and your team. We use a different issue tracking system to Jira that has the ability to create virtual accounts. Our last lead developer used to like all issues assigned to him which he would then dish out.When I took over temporarily I created a virtual account called Up For Grabs and moved all un-assigned work to this account. I did this because I didn't want people thinking that work was being done because it was assigned to someone (me) when it was not. So I moved anything that was not being worked on to this account. Since our new team leader has joined us and we have adopted scrum, we have kept the Up For Grabs account and used that as our default assignee. We find this works best because no one in our team assigns work out, instead we pick up tasks ourselves from the current sprint. This also means no one has anything else attached to them other than what they're currently working on.However if you have multiple teams it could potentially get confusing. I'm not very familiar with Jira but perhaps having something you can assign it to that is called something like Team X - Up For Grabs or something akin to a virtual user (not attached to any team member individually). This would mean your other team leaders don't get confused with unassigned work, but you also don't have a swamped account with loads of assigned work. |
_webmaster.11672 | With the introduction of the Semantic Web we (SEOs) have the opportunity to mark-up our content in such a way that robots/crawlers have a better understanding about the meaning of our content. And, we (SEOs) are keen on presenting our website's content in such a way it matches the search query of the Google (or Bing or Yahoo) user in the best possible way. On the search engine side engineers are keen on providing search results that provide the best match and information related to the search query that is being used. Thus, the introduction of the rich snippet. And this might very well be the development in the transition from Web 2.0 to Web 3.0?When it comes to internet users: There is an enormous amount of people that use search engines because they have a question and they are looking for the right answer to that question. As a response we now have a wide variety of question and answer (Q&A) websites for a wide variety of topics. To me the logic next step would be to use a semantic markup that tells a robot/crawler what is a/the question and what are answers to that question. Even cooler is the fact that the community of a specific Q&A website is able to rate (e.g. by up- or downvote or starred rating) a certain answers and can mark a question as 'the correct answer'.The search engines could interpret the markup and create a SERP containing rich snippets pointing out the Q&A. Now, doesn't that provide the opportunity to present the search engine user with a search result that:Matches the question;Provides a title and description of the question;Provides the top 'x number' of answers / best rated answers;Provides the correct answer.The snippet could look (for example!) like this:It goes without saying that the formatting of the snippet can have many varieties, but that's not really up to me ;)I have done some research and I cannot find any markup or Microformat that support Q&A semantics within a website. Is this something that is around and that I am simply missing? Or is it coming up? To me it seems perfect to have the correct answer to your question directly visible and accessible through from SERP's rich snippets. | Microformatting questions & answers - Semantic Web 3.0? | search engines;rich snippets;structured data;semantic web | null |
_scicomp.20028 | I have an infinitely long cylinder defined usingradiusa point in 3d Axis defined using a 3d vectorI have a set of points with 3d coordinates placed in a grid.I want to wrap this grid of points around the curvature of my cylinder. How to do it | Wrapping grid of points around curvature of an infinitely long cylinder | computational geometry | It seems like you are trying to project the grid points onto the cylindrical surface. You can do this via a few vector projections.Let r be the cylinder radiusLet P be a grid point.Let a be the cylinder axis unit vector.Project P along a Pa = (P · a) * a Compute projection of grid point perpendicular to axis P⊥ = P - Pa Compute unit vector of perpendicular projection p⊥ = P⊥ / ||P⊥|| Compute the projection of the grid point on the cylinder Pcyl = Pa + r * p⊥ Pcyl is the value you want. Compute it for each grid point. Basically, you are moving up the cylinder axis until you reach the grid point in that direction, then you move toward the grid point until you hit the cylinder, then you stop. |
_unix.85922 | How do I run/install this: https://github.com/kevmoo/kbuild?I installed the dependencies and tried to execute the bin/kbuild Python script, but it's giving me this error:Traceback (most recent call last): File kbuild/bin/kbuild, line 12, in <module> BREW_PREFIX = subprocess.check_output(['brew', '--prefix']).strip() File /usr/lib/python2.7/subprocess.py, line 537, in check_output process = Popen(stdout=PIPE, *popenargs, **kwargs) File /usr/lib/python2.7/subprocess.py, line 679, in __init__ errread, errwrite) File /usr/lib/python2.7/subprocess.py, line 1259, in _execute_child raise child_exceptionOSError: [Errno 2] No such file or directoryMy guess is that this tool was intended for OSX and Homebrew and that's why it's choking. I just wasn't sure based on the minimalist installation instructions. | How do I install kbuild? | python | Looking at the kbuild script it does appear to be OS X & brew specific.https://github.com/kevmoo/kbuild/blob/master/bin/kbuildexcerpt from script...BREW_PREFIX = subprocess.check_output(['brew', '--prefix']).strip()compiler_search_path = path.join(BREW_PREFIX, 'Cellar/closure-compiler', '*', 'libexec/build/compiler.jar')compilers = glob.glob(compiler_search_path)...The homebrew directory on github would seem to lead credence to this too:If you'd like to install kbuild via Homebrew:brew install https://raw.github.com/kevmoo/homebrew-kevmoo/master/kbuild.rborbrew tap brew tap kevmoo/kevmoo brew install kbuild |
_webmaster.3596 | I would like to be able to specify some meta keywords and meta descriptions for some of my pages in our Drupal (version 6) site. However, there does not appear to be a way to do that within Drupal (at least out of the box). I've seen some references to some Drupal modules which might allow you to do this, but it doesn't look like they've been updated in a long time. Any suggestions?As a correlary, if meta keywords and meta descriptions really aren't worth bothering with any more, is there a way I can tell Hubspot to stop reminding me to add them? :) | Is there a way to specify meta keywords and descriptions with Drupal? | seo;drupal;meta keywords;meta description | I'm using NodeWords: http://drupal.org/project/nodewords(but it does not run on Drupal 7, so your success will depend on what version of Drupal you are using for your site)Regarding the updates, the dev version was updated just yesterday, and the released version is not that old as to make me doubt its usefulness or support status.Meta descriptions will help Google show a description for your page under the search result instead of some random snippet of text taken from the page. It may be worth it just for that :) |
_softwareengineering.333546 | I am trying to understand how interpreter pattern can actually be implemented. As per the diagram; an expression has 2 nodes: terminal & non-terminal. Can it have multiple type of nodes as well? Because I believe it is drawn considering the math expression transformed in binary tree DS where leaf nodes are number and non-leaf nodes are operations: +,-,/ etc.Somewhere I read that java.util.Pattern is an example of interpreter pattern. Pattern pattern = Pattern.compile(^[abc](ab|c?d)?ef$);Matcher matcher = pattern.matcher(some RE);if(matcher.matches()){ .. }So I was trying to relate if my implementation of RE engine: BooleanSequence is also an example of interpreter pattern.BooleanSequence seq = new BooleanSequence([abc](ab|c?d)?ef);seq.compile();seq.minimize();Matcher matcher = seq.getCoreMatcher();matcher.match(some RE);Implementation note:Main class BooleanSequence(BS) takes RE (can be considered as context) and build some kind of in-memory DS, where each char of RE is a node. There are many types of node, like: normal, range, lazy, any etc. I believe it can be considered as expression as given in diagram.Node class also has match(). BS gives a matcher or it can be created separately. It is completely isolated from BS class. And there are many types of matchers (currently 3). Matcher calls match() of all the nodes until whole expression is evaluated. | Understanding Interpreter pattern | design patterns | This class diagram means that an AbstractExpression is either a TerminalExpression or a NonTerminalExpression. If its a NonTerminalExpression, it is itself an aggregation of one or several AbstractExpression. In fact this structure is a tree. Typically the terminals would be further derived into vriables and litterals, and the non terminals would be further derived at lest in unary and binary operators, but may be even more. An example of instantiation could be: In your java.util.Pattern example: the calling code is the client, who first build the abstract syntax tree when compiling a regex pattern (i.e. building an internal representation of the regex pattern).the Pattern is the interpreter. It would in principle correspond to the top level AbstractExpression. The only particularity is that the structure of the expression is encapsulated in the interpreter and not accessible. the Pattern.matcher() is the equivalent of a call to interpret(), the string to parse being the context. the Matcher object is the result of the interpretation with on a particular string. |
_vi.6167 | I would like the first line of some documents I have to be highlighted as a comment.I would like something like:syntax match myTypeComment /{apply only to first line}^.*$/But I don't know how this regex should work for only one line (e.g. the first line) in syntax matching. Thank you very much! | Define syntax in only one line | syntax highlighting;regular expression | You can use the \%1l; this will match a specific line.For example, to highlight the first line if it starts with # Hello::syntax match myTypeComment /\%1l# Hello.*/:hi myTypeComment ctermfg=redThis also works for other lines (e.g. \%42l for the 42nd line) and you can use \%42<l and \%42>l for lines before or after the 42nd line.Also see :help /\%l. |
_softwareengineering.338945 | I want a feasible way to compare my project with my friend's project. I first thought it was enough to compare based on the number of code lines. But for some reason, people kept saying LOC is not a good measure. So, is the following method (I cooked up myself and I don't know if there is anything like this) good enough to compare my project with my friend's project? We can calculate the effort_factor using the following algorithm:effort_factor = 0mini_method = 0.01proper_method = 1min_avg_LOC_of_each_method = 6for each_class in source_code: avg_LOC_of_each_method = LOC(each_class)/no_of_methods(each_class) for each_method in each_class: if avg_LOC_of_each_method < min_avg_LOC_of_each_method: avg_LOC_of_each_method = min_avg_LOC_of_each_method if LOC(each_method) < avg_LOC_of_each_method: effort_factor += mini_method else: effort_factor += proper_methodreturn effort_factorDefinitions for the symbols used here:effort_factor: The measured amount of effort delivered by the developer (If the developer was maintaining an existing code, the absolute difference between the initially measured effort_factor and the final effort_factor must be the developer's contributed effort factor assuming he didn't reduce the functionality of the source-code by removing any existing features). mini_method : The score-value (or weight) given to methods that contain less-than-average number of lines of code. proper_method : The score-value (or weight) given to methods that contain more-than-average number of lines of code (these methods are assumed to be vital for the task carried over by the class). min_avg_LOC_of_each_method : In cases where there are classes with no methods that exceed 6 lines of code, we must ensure that all the methods of the class are considered to be mini-methods (small methods). This constant that ensures that avg_LOC_of_each_method value never gets below 6. avg_LOC_of_each_method : holds the number of lines of code per method in a class. LOC() : computes the number of lines of code (for either a class or a method). The basic idea of this method is to count the number of methods instead of the code-lines. Also we can assume, methods that have too less number of lines don't add much value to the code, as they can't solve any vital problems. At the same time methods with many lines of code can be assumed to solve a vital problem and hence can be given a greater weight-value.Is this method feasible to measure and compare source codes? Or are there any flaws in it? | Is the following method to compare source codes or work effort reliable? | source code;metrics | The basic idea of this method is to count the number of methods instead of the code-lines. Well here's your problem. The reason LOC counting doesn't work is because a programmer can spend days getting a one line regular expression just right or they can whip out a one line print statement in 2 seconds. If you pay them by loc they'll write a 5 page monster that does what the regex does.Counting the number of methods has the same problem. How many ways do you really want to encourage me to implement toString()? Code simply isn't something you can look at and decide how much effort has been put into it. You may be looking at something that's been revised 5 times that replaced 7 classes and took a week just to decouple from the framework we no longer use to say nothing of the whiteboard work and meetings that went into making these decisions.So effort isn't something stored in the code. I doubt it's even in source control.The only good metric I know for code isn't even about effort. It's about quality. Which is more important anyway. It's this:The more interesting question:I want a feasible way to compare my project with my friend's project.When you compare your car with your buddies car you don't do it by looking under the hood. You do it on the track.Ask your moms to use your programs to accomplish something and count the questions they ask before they finish.Mom makes a great product tester. |
_unix.352929 | Here is my code.... I am having issues with putting detected invalid hostnames into a file and then nslookup valid hostnames. When I run this script, I'm trying to get it to ignore the invalid hostnames and do a nslookup on valid. I have tried using host as well as dig instead of nslookup, but still no seeing results#!/bin/sh#Query Theater DB for cnames#Pulling cnames#Lets use sed to clean up and remove EMPTY strings, , @, and * mssql -f csv -c ~/applications/mssql/mssql.json -q SELECT * FROM Cname | cut -f 3 -d , | sed '/^\s*$/d' | sed 's/[]//g' | sed 's/[@]//g' | sed 's/[*]//g' | sort | uniq > /tmp/final.csv#Added this to get rid of the hidden M from /tmp/final.csvdos2unix /tmp/final.csv#Validating cnameswhile read -r hostdo echo $host | egrep ^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)+([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$ >/dev/null 2>&1 if [ $? -eq 0 ] then echo $host >> /tmp/cnames.csv else echo $host is not a valid hostname >> /tmp/badcnames.csv fi done < /tmp/final.csv#Lets validate good hostnamesfor i in `cat /tmp/final.csv`; do nslookup $i | grep Name | awk '{print $2}'; nslookup $i | grep Add | grep -v '#' | awk '{print $2}'; done > /tmp/output.csv | Help validating hostnames from .csv file | shell script;hostname;nslookup | null |
_softwareengineering.180771 | One of things that annoys me about SQL is that it can't think in terms of objects and it's lack of encapsulation makes me constantly have to escape commands to prevent injections.I want a database language that can be polymorphic and secure. I have searched online for non-procedural database programming languages and so far my google search has been unsuccessful.I know in languages like php there are ways to prevent the injections by making the PHP encapsulated well, but not all database programming situations involve embedding the database language in another language.In situations where it's database programming only, is there a database programming language that is object oriented in itself? If not, are they working on one? | Is there a database programming language with encapsulation to prevent the injections? | database;encapsulation;sql injection | null |
_unix.206809 | There plenty of tools working with keyrings: ssh-agent, gpg-agent, gnome-keyring, kwallet, wrappers like keychain, keyctl talking to GNU/Linux kernel. There are various recommendation on how/when to start it tailored for different environments.This make it rather confusing. I'm using modern GNU/Linux distro with systemd and I start my user session with systemd --user as well. I expect this setup to last decades so I wonder what's the best way to get keyring into picture?The main use-case is to store passwords from chromium/firefox in one consolidated place.Shall I start keychain from my user shell autostart script (I use fish for interactive and dash as login shells if that matters)? Right now gnome-keyring-daemon --daemonize --login is spawned via PAM. Shall I start gnome-keyring --start from user systemd unit? Is there some dbus service which would start some keyring daemon upon first request?The list of questions go on but you get the idea - what is the right way to get keyring-as-a-service? | keyring best practices with systemd | systemd;gnome keyring;kwallet | null |
_softwareengineering.163766 | We would like to implement the Agile/ Scrum process in our daily software management, so as to provide better progress visibility and feature managements, here are some of the activities that we want to do:Daily stand-up Release cycles of 6 weeks with 3 2-week iterations.Having a product back-log of tasks (integrate with bugzilla) and bugs estimated out.Printing a daily burn down to make velocity visible. When used as motivator, it's great.Easy feature development tracking and full blown visibility, especially for the sales and stake holders ( this means that it must be a web based tool).My team is distributed, so physical whiteboards aren't feasible. Is there such a web based tool that meets our needs? I heard icescrum may be one, but I've never used it so I don't know. There are a few more suggestions as here, but I've never heard of them, anyone cares to elaborate or suggest new tools? | Software Management Tools for Agile Process Development | project management;agile;scrum | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.