id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_reverseengineering.9350 | I have no idea how, when or why, but now, the default address (the one executed when pressing F9) is 0x77960884. It should be 0x00401000 (when I manually go to 0x00401000, everything works).The problem is, I manually have to change the Origin every time I run any program.Additionally, restarting Windows / reinstalling OllyDBG doesn't fix it. A few hours ago it was working fine, but now... I have no idea. | Wrong default starting address | ollydbg;debugging | null |
_vi.8048 | I am running a simple substitution on many files with :argdo %s/foo/\rfoo/ge | update. Vim shows the progress through files (number of substitutions in file) and when the screen fills up it blocks with the prompt:...Data_357.csv 63 lines, 22551 charactersData_358.csv 204 lines, 946953 characters-- More -- SPACE/d/j: screen/page/line down, b/u/k: up, q: quit How can I make it run non-stop? | Block-less argdo on many files? | buffers;substitute | :silent argdo %s/foo/\rfoo/ge | updateor:silent! argdo %s/foo/\rfoo/g | updatesilent skips displaying normal messages! skips error messages as wellAs per this vimcast, the e flag in substitute command can also be removedFor more options and in-built help, refer to this Q&A |
_softwareengineering.204672 | In my team, we are about to start the reimplement of a service. One of the important steps to do to accomplish this is how do we ensure that we are doing it in the right way and we are not introducing new bugs.So, what we have in mind is create a bunch of test to verify the following:The behavior. Both services should behave the same way (store data in the same places, send same, notificacions, etc...)Results. Object returned by the service's calls should be exactly the same.So, the things that we have thought is to do the following:Create a set of test that verifies the behavior and results of old service.Create the new service adding unit test, and whitebox integration test for the new serviceCreate some kind of Mirror test that checks if the new service is working as the old one. Is there a way to do this?Thanks for any help.Note: None of the code of the previous version is reusable. There is no test for the older version of the service[Edited]replaced original word migrate with reimplement | Best way to test a reimplemented web service | testing;web services | Well, after diving deep in this, we have two possible solutions:Replay prod data: It will be kinda complicated to do it, but the good thing is that if you can capture and replay prod data against your service, then all whitebox integration test will be done for you. the bad thing is that you are just testing the inputs and outputs and not how the data is changed by the service.A different approach is the following: Apply factory pattern for both service's clients, the old one and the new one, then create a test for the old service (here you want to check result objects and data changes), migrate the service, test your new service against the test of the old one. |
_unix.321983 | Is there any way to bring down wireless on wired link detection using the tools mentioned in the title? Two automatic services are enabled: netctl-auto and netctl-ifplugd on coresponding interfaces. | Bring down wireless on detection of ethernet link [ifplugd + netctl] | networking;arch linux;netctl | null |
_unix.359906 | In remote directory, i have below files and need to copy only the current days files + previous run failures to my local directory.Example:in Remote:aa.txtaa-18-04-2017.txtaa-17-04-2017.txtin local, I have to rsync the file aa.txt to my new directory.in case previous run got failed I need to rsync two files (aa.txt, aa-18-04-2017.txt).Can someone help me here to resolve this.Thanks in advanceCurrently, RSYNC is copying all the files to our local directory and this causing storage issue on daily basis. | RSYNC to copy new files in different directory | ssh;rsync;archive | null |
_softwareengineering.317816 | I have a car maintenance garage program that has an abstract Vehicle class that has several derived classes like Car MotorCycle, etc. Each of those derived vehicles in turn is either a fuel or an electric vehicle. So instead of having a FuelCar, ElectricCar, FuelMotorCycle, ElectricMotorCycle etc, I'm trying to implement it using composition. The problem now is that I would have to check all the time if it's an electric or fuel vehicle, and then do as cast (that's like reinterpret_cast from c++) accordingly, or would have to wrap each as cast with try catch. It adds complexity to the code.Another option was removing the EnergySource empty class and have each vehicle to hold both Fuel and Electric and to initialize only one in the ctor, but it doesn't seem right to have a fuel car that also have an electric part (even if that part is null). Although this seems the simplest of the three.Any suggestions on what is the best approach?Here's the UML diagram of what I currently have:Code: http://pastebin.com/Rt5HccHC | Applying composition over inheritance to Vehicle classes | c#;design;inheritance;composition | @radarbob those members are specified, I didn't choose them.My sympathies.... Hybrid cars shouldn't be allowed and are irrelevant. Ok. Then you'd better not have both a Fuel and Electric properties in Vehicle. It sends the wrong message.... I don't see how placing properties in interfaces help here, I'm still in square one. Throughout the StackExchange universe I see the way over-use of interfaces (the keyword kind). I think it is an exuberant mis-application and mis-understanding of code to interfaces not implementation.... Lastly, you mean a solid rhombus en.wikipedia.org/wiki/Class_diagram#Relationships Jessica Simpson on UML ... Anything else you would like to add?Yes.Wrap a Vehicle in a VehicleEnergy classGiven the design as shown, pass a Vehicle instance into a VehicleEnergy class with appropriate wrapper methods, or properties, to query the vehicle-EnergySource kind that it is. But I don't see how you can get around the fact that somewhere, somehow you have to interrogate the object.This feels like a good separation of concerns compromise. I wonder if the flurry of comments on this thread is the result of - a symptom of - conflicting concerns.I think this hybrid design (pun intended) expresses the separate aspects and then expresses their interaction in a coherent interface (the non-keyword kind).The Vehicle object can always be used as-is, or disguise itself, so to speak.Oh, yes... I might use the factory pattern and pass in an enum for the vehicle-enery desired. There will be no enum member for a hybrid vehicle so this becomes a strongly typed way of communicating that hybrid is undefined. |
_cs.33650 | Specifically I'm studying towards a research degree in HCI (human computer interaction). I have problems however differentiating theory and practice, or science and engineering. I know science is about advancing human knowledge. Providing evidence about something specific in a field. But it's also about theory right? I guess there's different ways to do science; you can prove something with numbers and results, but you can also do science simply by creating a new method or theory about how something should work right? Engineering on the other hand is more about putting into practice the theory, right?I'd like to have some guidance, perhaps with examples, to what differentiates theory and practice, science and engineering. Also books/articles to read on the subject would be greatly appreciated.PS: In HCI it's hard to do research with experiments - it's very subject and not quantifiable as other fields of computer science. Perhaps this is why my confusion is greater than one would expect. | As a wannabe computer scientist I have problems differentiating theory and practice | software engineering;research;hci | null |
_cs.43639 | I try to construct a TM that accepts the language $\{ ww \mid w \in \{a,b\}^* \}$.Between the words $w$ is no delimeter, so I don't know, how my TM can know where the first $w$ ends and the second $w$ begins. Is there a trick for this? | Construct Turing Machine which accepts the language $ww$ | formal languages;turing machines;automata | Here is a sketch for how a deterministic machine might work:place a marker in front of the input.go through the input, checking if the length is even. If not, reject.place a marker behind the input.going back and forth, move the markers towards each other until they meet in the middle.as long as the halves are nonempty, compare and erase their first letters and reject if not equal.accept. |
_computerscience.4920 | I was thinking that I could pass a timestamp in (from requestAnimationFrame) to the vert shader, and just have my easing curves in the GPU instead of using (for example) Tween.js from the outside.Is this a good idea? Why or why not?EDIT: After learning more GL and thinking about it, it doesn't seem like I want every shader instance to run a tween that I may only use for a handful of vertices. Can we have only certain shaders run tween calculations if the vertex being animated is the one of the current shader? | Easing curves on the GPU? | opengl;shader;glsl;webgl;javascript | null |
_codereview.168897 | I'm working on a game which utilises a variant of the entity component system pattern. In my current code, I have been communicating between components using code of the form:_entity.GetComponent<MovementComponent>().TargetPosition = targetPosition;I wanted to remove this very strong coupling which my components have (as a result of specifying exactly which component should receive the message), and transition towards an event / message system.As a result, I've written an implementation which seems ideal, however it uses run-time dynamic typing which has me concerned that there may be a better way to achieve my goals.My code is as follows, currently:Inside Entity:public void SendMessage<T>(T message) { _components.ForEach(x => (x as dynamic).Message(message));}Inside Abstract Component class:public virtual void Message(IComponentMessage componentMessage) { }Inside an example component (MovementComponent) that receives a move message:public void Message(MoveMessage message) { Console.Write(Received message);}Dispatching a command to move:private void IssueMovement(TileCoordinate targetPosition) { Console.Write(Dispatching move message); _entity.SendMessage(new MoveMessage(targetPosition));}Example Message class - MoveMessage:public class MoveMessage : IComponentMessage { public readonly TileCoordinate MoveTo; public MoveMessage(TileCoordinate coordinates) { MoveTo = coordinates; }}NB: IComponentInterface is just an empty interface at the current moment in time.The way I see it, my current approach has some big advantages:Adding a new message type does not require any modification elsewhere to be supported.Subscribing to an event is as easy as creating a method with the correct event class.There is practically no overhead for listening to a specific event - no need to instantiate a class, inherit some event-specific interface, register interest at run-time with a subscribe method, etc.As messages are represented by classes (like a MoveMessage), they can contain all the relevant data without needing to be cast or coerced.However, as mentioned at the beginning of my question, I am concerned about using run-time dynamic typing in this fashion (See my dispatch code in Entity - the second snippet in this post). This system will probably be handling a lot of messages, and I have some concerns about the overhead incurred (it also feels like a code smell in general)I would really appreciate feedback on this approach; particularly whether it seems like an abuse of dynamic to more experienced C# developers than I, but would also appreciate alternative suggestions.Alternative approaches I've considered, and why I did not go with them initially:Exhaustive set of event properties which components can subscribe to manually - adds extra code overhead to each message type, which I'd like to avoidDictionary from event Type to handler in each component - have to subscribe at run-time, which feels undesirable.Switching dynamically inside a non-overloaded handler - more viable than it sounds since most components will not listen to more than a few message types, but still has unpleasant code overheadI am quite sure this code is okay, outside of the overhead induced by the run-time typing - my apologies if this makes it a bad fit. I am just hoping for a once-over review by someone more experienced to reassure me that this is a good design. | Communicating events between entity components with minimal code overhead | c#;game;entity component system | You have one big problem with this design. It's easiest to explain the problem with the example. So, let's say you add a new feature where you can issue a speak message. You'll need to add SpeakMessage and SpeakComponent classes. SpeakComponent would have public void Message(SpeakMessage message) method. In this scenario, when someone calls your IssueMovement method, it will call SendMessage method which in turn will iterate over _components (which now contains MoveComponent and SpeakComponent) and try to call their Message method that has one argument of type MovementMessage. Since SpeakComponent doesn't have that method, it will throw an exception. The only way to avoid that with your current design is to have your component classes each handle every message in the system which is not what you would want to do.So, to improve your design, your entity will need to know which component handles which message. The best way to do it, IMO, is to have an interface IMessageComponent<T> where T: IComponentMessage with a single method void Message(T componentMessage). MoveComponent would then implement IMessageComponent<MoveMessage> and SpeakComponent would implement IMessageComponent<SpeakMessage>. Your SendMessage method inside the entity would then become:public void SendMessage<T>(T message) { _components.OfType<IMessageComponent<T>>().ForEach(x => x.Message(message));}If you want one component to handle more than one message type (although, that would violate SRP), your component could implement multiple IMessageComponent<T> interfaces with different message classes. |
_codereview.5234 | I'm wondering if there is a simplier regex I could use in my code to remove the beginning and ending char in a line. Maybe combine some regex's? In this instance, it's a comma at the beginning and ending of a line. My output should be the fields seperated into CSV format.#!/usr/local/bin/perluse strict;use warnings;parse_DPCRS();sub parse_DPCRS { open ( FILEIN, 'txt_files/AKR_DPCRS.txt' ); open ( FILEOUT, '>txt_files/AKR_DPCRS.csv' ); while (<FILEIN>) { next if /^(\s)*$/; #skip blank lines next if /^\>/; #skip command line that start with > next if /^\s+POINT\sCODE/; #skip header next if /^\s+NODE\sNAME/; #skip header next if /^\s+\=+/; #skip header next if /^\s+CCS\sDPCRS/; #skip pageination footer chomp; #removing trailing newline character s/\s+/,/g; #replace white space with a comma s/^,//; #replace beginning comma with empty s/,$//; #replace ending comma with empty my ( $nodeName, $pointCodeDec ) = split( , ); print FILEOUT ($nodeName . , . $pointCodeDec . \n); #print $_\n; }};close (FILEOUT);close (FILEIN);exit;Here's a slice of the text file I'm parsing>DISP CCS DPCRS ALL 0 POINT CODE POINT CODE TYPE OF ROUTESET NOTIFY NODE NODE NAME DECIMAL HEX ROUTE MASTER SCCP LOCATION =========== =========== ========== ======= ======== ====== ======== PBVJPRCO01T 1-1-1 010101 FULL PC 119 NO NON-ADJ ROCHNYXA06T 1-6-1 010601 FULL PC 58 NO NON-ADJ NYCNNYDRW17 1-6-2 010602 FULL PC 58 NO NON-ADJ SYRCNYSW01T 1-6-3 010603 FULL PC 22 NO NON-ADJ SYRCNYSWDS0 1-6-15 01060F FULL PC 58 NO NON-ADJ ROCHNYFEDS0 1-6-17 010611 FULL PC 58 NO NON-ADJ NYCMNYHD01T 1-9-11 01090B FULL PC 22 NO NON-ADJ NWRKNJ1001T 1-9-14 01090E FULL PC 22 NO NON-ADJ BSTNMABL01T 1-9-16 010910 FULL PC 22 NO NON-ADJ | Best way to replace a beginning and end character in Perl using Regular Expression? | performance;perl;regex | Here is a single regex that removes , (comma) at the beginig or at the end of a string:$str =~ s/^,+|,+$//g;and here is a benchmark that compares this regex with a double one:use Benchmark qw(:all);my $str = q/,a,b,c,d,/;my $count = -3;cmpthese($count, { 'two regex' => sub { $str =~ s/^,+//; $str =~ s/,+$//; }, 'one regex' => sub { $str =~ s/^,+|,+$//g; }, });The result: Rate one regex two regexone regex 597559/s -- -58%two regex 1410348/s 136% --We can see that two regex are really faster than one regex that combines the two. |
_webmaster.53326 | I have a Tumblr blog which I want to move to somewhere else. I don't want my Google visibility resetted after moving. I am thinking to do it this way;1) I believe Tumblr allows custom domain names. I will point it to my new domain, and wait for some time for Google to see the changes.2) I will copy all my posts to new host, but they will use different URL pattern like category-name/post-title3) In my new host, I will set 301 redirects for every page that existed on old blog to correct place for them on my new blog. For example, links like post/61879534273/title-of-the-page will be redirected to category-name/title-of-the-page on new host.4) In my domain name settings, I will point my domain name to my new host.Would this setup work as I intended? If not, is there another way to do it? | How to move a Tumblr blog without hurting PageRank? | seo;domains;tumblr | Yes, this will work.When you use a custom domain with tumblr, tumblr issues a 301 redirect1 (moved permanently) for all pages and subpages to redirect your tumblr subdomain at example.tumblr.com/path/ to your registered domain at example.com/path/.When Google has re-indexed the site to display URLs with your registered domain instead of the original tumblr domain, it's safe to migrate your site to your own server by repointing the A record in your domain records, provided that you set up redirect rules on your server first, as you describe.1 I confirmed that tumblr issues 301 redirects by sending a GET request for a post on my tumblr subdomain, which redirects to the custom domain with a 301 status: |
_webmaster.95027 | Is there a generic way to detect and preferably escape from in-app browsers like the ones used by Facebook, Twitter and some news apps.We are running an add-campaign on both Facebook and a common dutch news site.In both cases people end up in my web-app with limited browsers, not allowing people to upload a picture for-example.I'd like to give these people a simple option to escape from the handicapped in-app browser.I did find this for detecting on IOS . . but not really anything on Android.https://stackoverflow.com/questions/4460205/detect-ipad-iphone-webview-via-javascript | Way to escape or at-least detect in-app browsers | browser detecting | These in-app browsers are basically a cut down version of the native browser and so have the same user agent string. Unfortunately there is no way strictly speaking to detect them and break out of them as the apps (such as the facebook app) will always open the links using the in-app browser instead of closing the app and opening up the complete browser app. The only thing I can suggest is using javascript to check and see if the feature you are trying to use is available in the browser before presenting it to the end user. You can take a look at http://diveinto.html5doctor.com/detect.html which shows how to use Modernizr to check if certain HTML5 features are supported in the users browser which can be used to switch off unsupported features on your site. |
_scicomp.25719 | Consider a simplex $T$ in $R^d$ with $N_1(T) = \left\{N_i\right\}_{i=0}^{d}\subset P_1^{*}(T)$ be the Lagrange nodal variables (or nodal evaluation). By the Riesz representation theorem, there exist functions $\lambda_{i}^{*}\in P_1(T)$ (which is the representation of $N_i\in P_1(T)$) such that $N_j(\lambda_{i}) = \int_{T} \lambda_{i}\lambda_{j}^{*} = \delta_{ij}$ for each $0\leq i\leq d$. Show that $\lambda_{i}^{*} = \frac{(1+d)^2}{|T|}\lambda_{i} - \frac{1+d}{|T|}\sum_{j\neq i} \lambda_j$My attempt: I was thinking that $\lambda_i^{*}$ plays a role like a Fourier coefficient, so I multiply both sides by $\lambda_j$ and integrate over $T$. Then LHS would be $\delta_{ji}$, while RHS $= \frac{(1+d)^2}{|T|}\int_{T} \lambda_{i}\lambda_{j} - \frac{1+d}{|T|}\sum_{j\neq i}\int_{T} \lambda_{i}\lambda_{j}$. Now, for $i=j$, then $LHS=1$, and I was thinking of $\int_{T} \lambda_{i}\lambda_{i} = $ the area of region $T$, but then if that's the case, the RHS would be $(1+d)^2,$ which is certainly not equal to $1$ (contradiction). So I don't think my interpretation is correct, but I could not see how to proceed further without knowing the explicit formula for $\lambda_i$.My question: Could anyone please help me with this problem? It seems to be such a beautiful identity, yet quite hard to prove. Any thoughts would really be appreciated. | Determine Lagrange nodal variables of a simplex $T$ | finite element;pde | null |
_bioinformatics.2056 | For DNA/RNA quantification machines like the Bioanalyzer or TapeStation, the DNA Integrity Number (DIN) or RNA Integrity Number (RIN) numbers are quoted as a measure of the fragmentation of the material.How is the DNA Integrity Number (DIN) calculated in Bioanalyzer/TapeStation? Is there any open-source software to parse/collate the data from the machines? | how is the DNA Integrity Number (DIN) calculated in Bioanalyzer/TapeStation? | dna;quantification;bioanalyzer | null |
_cogsci.15508 | I was recently trying to argue that the Democratic National Committee's efforts to undermine the Bernie Sanders campaign were probably ineffective, and that those who attempted to do so probably suffered from a specific cognitive bias. Namely, due to their presence in the political operative nexus, they tended to overestimate, in general, the impact that political operations have on elections, swaying public opinion, etc. I wonder whether social scientists have observed that, in general, experts overestimate their ability to make an impact, because they put the system they belong to on a pedestal. Has such a cognitive bias ever been discussed in the literature? Is there a name for it? | Is there a cognitive bias which describes expert communities' overestimation of their potential impact? | cognitive psychology;bias | null |
_scicomp.7572 | Currently the way I compute histograms for data is by generating grid in $N$ dimensions (where $N$ is the dimension of the data) and searching through the $M$ data points in each dimension to see in which bin each one of them fits.This is the same as an exhaustive search and takes very long if $N$ and $M$ are large (in my case $N=6$, $M=125,000$).My question is: is there a faster way to accurately compute (or possibly estimate) the number of samples in each bin given a grid and data?Alternatively, if there is no way to estimate/compute a histogram, is there an alternative method for construct distributions that is fast for high-dimensional large datasets? I've used kernel density estimators, but they are sensitive to which type of kernel you use and depend on prior knowledge of the nature of the data to get good results. (I have no prior knowledge of the nature of the data.) | Is there a fast way to compute histograms for high-dimensional large datasets? | algorithms;statistics;data visualization;data management | Histograms are not useful for high dimensional data. The curse of dimensionality affects one quite fast. As in your case if the grid is of size 7**6, you have on average one point in one bin. Kernel density estimator are better suited as long as you keep the kernel bandwidth large enough. In my experience the top hat kernel as k-nearest neighbor yields reasonable results up to D=10, if sampling is sufficient. There is also a quite efficient algorithm for calculating k-nearest neighbors in higher dimensions, which I can recommend.Also, the kernel shape doesn't really matter so much, because you need to keep the bandwidth large enough due to lack of data. If you see a dependency on the kernel shape your bandwidth is likely too small.There are a couple of rule of thumbs how to select the bandwidth. If you calculate some other property from the probability density, in nearly all cases you are better off not computing the density at all.Edit to properly comment on the commentI am afraid you cannot capture nuanced differences in high dimensional data with histograms if you check the statistical error for each bin. Go ahead and do some simple random number experiment and check the fluctuation in each bin with your sample size. Unless you use a really small grid size like 2**6, which is pointless to begin with, you will only see noise as nuanced differences.For calculating entropies == Jensen Shannon divergences I recommend following papers which I used in my phd thesis. Article (Hnizdo2007) Hnizdo, V.; Darian, E.; Fedorowicz, A.; Demchuk, E.; Li, S. & Singh, H. Nearest-neighbor nonparametric method for estimating the configurational entropy of complex molecules. Journal of computational chemistry, J Comput Chem, 2007, 28, 655Article (Hnizdo2008) Hnizdo, V.; Tan, J.; Killian, B. & Gilson, M. Efficient calculation of configurational entropy from molecular simulations by combining the mutual-information expansion and nearest-neighbor methods Journal of computational chemistry, NIH Public Access, 2008, 29, 1605I have no idea for the earth mover distance and have never used that before though. It kinda looks like that you need the work for a phase space transformation bringing two distributions together. It seems to me that is similar to a free energy difference between the two systems given by the distributions. |
_softwareengineering.185611 | Is there are any standards or conventions on naming methods which add something if it not exist into another something.For example: Store.instance().addItemIfNotExist(item)IfNotExist is really ugly part. What workaround may be? | addIfNotExist alternative | naming;coding standards;methods | Some databases use the term Upsert to mean Update or Insert as needed, but you may not want the Update aspect.In general, an addItem() function has an implied, expected failure if the item already exists within the database, so you could use that. Your error handling code after the addItem() call would make it clear that failure because of already existing was okay.Finally, you could consider addItemExclusive() to better indicate that the routine will check for existence prior to adding the item. |
_unix.186778 | I've read the Ceph OS recommendations document, but still I have a question.Which file system is better for Ceph?XFS, ext4, or something else? | Which file system is better for Ceph? | filesystems;ext4;xfs;openstack | According to ceph documents,they recommend configuring Ceph to use the XFS file system in the near term, and btrfs in the long term once it is stable enough for production and at the end, ext4.document 1document 2document 3 |
_unix.311752 | Let's say I want to create an internal network with 4 subnets. There is no central router or switch. I have a management subnet available to link the gateways on all four subnets (192.168.0.0/24). The general diagram would look like this:10.0.1.0/24 <-> 10.0.2.0/24 <-> 10.0.3.0/24 <-> 10.0.4.0/24In words, I configure a single linux box on each subnet with 2 interfaces, a 10.0.x.1 and 192.168.0.x. These function as the gateway devices for each subnet. There will be multiple hosts for each 10.x/24 subnet. Other hosts will only have 1 interface available as a 10.0.x.x. I want each host to be able to ping each other host on any other subnet. My question is first: is this possible. And second, if so, I need some help configuring iptables and/or routes. I've been experimenting with this, but can only come up with a solution that allow for pings in one direction (icmp packets are only an example, I'd ultimately like full network capabilities between hosts e.g. ssh, telnet, ftp, etc). | Routing Between Multiple Subnets | linux;networking;iptables;routing;subnets | Ok, so you have five networks 10.0.1.0/24, 10.0.2.0/24, 10.0.3.0/24, 10.0.4.0/24 and 192.168.0.0/24, and four boxes routing between them. Let's say the routing boxes have addresses 10.0.1.1/192.168.0.1, 10.0.2.1/192.168.0.2, 10.0.3.1/192.168.0.3, and 10.0.4.1/192.168.0.4.You will need to add static routes to the other 10.0.x.0/24 networks on each router box, with commands something like this (EDITED!):# on the 10.0.1.1 boxip route add 10.0.2.0/24 via 192.168.0.2ip route add 10.0.3.0/24 via 192.168.0.3ip route add 10.0.4.0/24 via 192.168.0.4and the corresponding routes on the other router boxes. On the non-routing boxes with only one interface, set the default route to point to 10.0.x.1. Of course you will also have to add the static addresses and netmasks on all the interfaces.Also note that linux does not function as a router by default, you will need to enable packet forwarding withecho 1 > /proc/sys/net/ipv4/ip_forwardThe ip commands above do not make the settings persistent, how to do that is dependent on the distribution.As I said, I haven't tested this and may have forgotten something. |
_cs.41124 | I am looking for the function $y=f(x)$ that would map the integer interval $[0,n)$ into itself $[0,n)$. The function must be bijective, so it is a permutation of n elements. It should randomize the input variable, ie.for every $x_1$ and $x_2$ that are close $|x_1 - x_2| < 100$ the outputs of the function should differ very much $|f(x_1) - f(x_2)| > n/{100}$changing any digit in the input should change most of digits in the outputShannon's Confusion and diffusion: http://en.wikipedia.org/wiki/Confusion_and_diffusionThere should be very little or no fixed points (for every $x$: $f(x) \neq x$).or any combination of the above conditions.I don't need the inverse function. It should also be easy to compute from the closed form expression (a maximum of a few thousands simple computer operations like addition, multiplication, modulo etc.) for $n=10^{100}$.I found some examples in Google:Linear congruential generator. Equation:$X_{n+1} = (aX_n + c) \mod m$Wikipedia states that: Provided that the offset $c$ is nonzero, the LCG will have a full period for all seed values if and only if:$c$ and $m$ are relatively prime,$a - 1$ is divisible by all prime factors of $m$,$a - 1$ is a multiple of 4 if $m$ is a multiple of 4.I've tried using another function $f(x) = (ax + c) \mod m$, because I wanted to get rid of the recursion, and as long as $m$ is prime and $a \ge 1$ I get the permutation. However the result is not that wild or chaotic as I expect it to be.Minimal perfect hash functionThe concept is similar to what I'm looking for, but if I understand correctly the computation of this kind of function is very complicated and time-consuming and it cannot be expressed in a closed form as a simple expression for $n=10^{100}$.Substitution-permutation networkI am not sure how to apply S-boxes and P-boxes to the interval [0,n), but maybe it could be used.The question is: Could you give me some examples of functions that satisfy the above conditions (or some pointers like the mathematical term for the object I am looking for)? | What are the examples of the easily computable wild permutations? | cryptography;hash;one way functions | Yes, such things exist. They have been studied in the cryptographic literature: the key name is format-preserving encryption.To learn about this subject, I suggest taking a look at https://en.wikipedia.org/wiki/Format-preserving_encryption and https://crypto.stackexchange.com/q/16561/351 and https://crypto.stackexchange.com/q/504/351 and https://crypto.stackexchange.com/q/20035/351 and https://crypto.stackexchange.com/q/18988/351 and https://crypto.stackexchange.com/questions/tagged/format-preserving. You could also construct a suitable block cipher yourself using a Feistel construction, but it's probably better to use a standard scheme that has been analyzed in the literature.There are many constructions. The best one will depend on the specific value of $n$ in your application. Take a look at the schemes in the cryptographic literature, then if you have a more specific question about how to use one of those schemes, you can ask either here or on Crypto.SE. |
_unix.44888 | I want to read the file (1600 rows) and get rows only the columns have different values (sno1, sno2, sno3 & sno4-should be not be equal value) and it should be above50%.The example of output given belowinput.txt (tab-delimited)id sno1 sno2 sno3 sno4R1 98.4 88.8 98.4 67.6R2 100 100 100 100R3 33.4 23.5 98.8 45.5R4 53.5 78.7 88.8 67.5R5 0 0 0 0R6 88.8 98.8 67.6 100ouput.txtR4 53.5 78.7 88.8 67.5R6 88.8 98.8 67.6 100Here in R4 & R6 rows- all column values have not equal to each other and all are above 50%. Any help in awk/sed/perl is appreciated. | Get row data for non-matching column values | sed;awk;perl | A perl-oneliner:perl -nae 'undef %saw ; next if $. == 1; shift @F; next if grep { $_ < 50 or $saw{$_}++ } @F; print ' input.txtThis basically translates to:#!/usr/bin/env perluse strict;while (<>) { my @F = split(' '); # split the current line my %seen; next if $. == 1; # skip the heading shift @F; # ignore first element next if grep { $_ < 50 or $seen{$_}++ } @F; # ignore lines with # duplicate entries and # entries less than 50 print; # print current line} |
_unix.281581 | Can someone please help me understand the output that I get from the top command? This is the point that the oom-killer is invoked and kills my main application. What exactly is under the VSZ and %VSZ? What is 502m304.5?? | Top command output explanation (in embedded system) | linux;memory;command;top;busybox | Your output shows that top is printing some escape sequences that the terminal doesn't recognize. The bits where you see a blank followed by [ followed by more garbage characters are escape sequences that work on most terminals; the first character of those sequences is the escape character, which your terminal prints as a blank. For example, [7m at the beginning of the title line starts inverse video, [0m stops inverse video, etc.I'm not sure exactly what's going on with the STAT and VSZ column but it seems that top has printed some color-changing sequences there too (that's where the m is coming from), and they've been partially overwritten (top is probably printing a character which does make the cursor go left so that the next character overwrites what was there).With many programs, setting the TERM environment variable correctly is enough: it should indicate a terminal type that doesn't support any escape sequences. Make sure that you don't have a script that hard-codes a value of TERM somewhere. Try TERM=dumb. If you're using BusyBox, I think its top hard-codes escape sequences that work on most terminals, so you're out of luck. You could run it through a filter that removes escape sequences. Untested, but should work with BusyBox.#!/bin/shscript=$(printf 's/\033\\[[0-9;]*[A-Za-z]//g')sed -e $script $@(From this more complete Perl script) |
_reverseengineering.8113 | My OS is Windows 7 64-bit and my processor is an Intel Core i7-4700MQ running on the x64 architecture. My program is 32-bit.Recently, I read an article here describing how it is possible and legal in C to write the main function simply as a constant array of integers, characters, floats, doubles, etc. The article went step-by-step in the process of writing assembly in linux and then transforming it into an array of constant integers in order to print Hello world!\n\0. I had never seen such a program before, so I decided it would be cool to make one that works on Windows.In my program, I display an ANSI style MessageBox with the title Made by CaptainObvious!\n\0 and the the message C and assembly are for real men\n\0. I have the working inline assembly code in my C program shown below :int main( ){ __asm__ ( sub $0x10, %esp;\n movl $0x0, 0x0(%esp);\n lea message, %eax;\n movl %eax, 0x4(%esp);\n lea title, %eax;\n movl %eax, 0x8(%esp);\n movl $0x00000040, 0xc(%esp);\n call _MessageBoxA@16;\n movl $0, %eax;\n leave;\n ret;\n message: .ascii \C and assembly are for real men.\\n\\0\; title: .ascii \Made by CaptainObvious!\\n\\0\; ); return 0;}Also to ensure that I could implement the technique used by the article, I wrote a simple array of opcodes that functions to return the value of 10 immediately after execution. The test was successfull, and that array is shown below :const char main[] = { 0x55, 0x89, 0xe5, 0x83, 0xe4, 0xf0, 0x83, 0xec, 0x10, 0xe8, 0, 0, 0, 0, 0xb8, 10, 0, 0, 0, 0xc9, 0xc3 };Yet when I tried to convert my more complex program to a constant array of integers, my program failed to execute with SIGILL (Illegal Instruction). Here is the relavent disassembly output from gdb :0x00403040 and $0xffffff89,%ebp0x00403043 push %ebp0x00403044 add %ch,%al0x00403046 lock in $0x83,%al ; <--- SIGILL; ...Upon seeing the disassembly output from gdb, I suspected that my array of integers were wrong, but although I caught a few mistakes, it still throws the exact same SIGILL exception shown above. Here is what the current integer array is :const unsigned int main[] ={ 0x5589e583, 0xe4f0e800, 0x00000083, 0xec10c704, 0x24000000, 0x008d053d, 0x00000089, 0x4424048d, 0x055f0000, 0x00894424, 0x08c74424, 0x0c400000, 0x00e80000, 0x0000b800, 0x000000c9, 0xc3432061, 0x6e642061, 0x7373656d, 0x626c7920, 0x61726520, 0x666f7220, 0x7265616c, 0x206d656e, 0x2e0a004d, 0x61646520, 0x62792043, 0x68726973, 0x204f2754, 0x6f6f6c65, 0x210a00b8, 0x00000000, 0xc9c39090};Currently to get the hexadecimal opcodes, I dump the .text section of my program using the objdump.exe program that comes with the MinGW package. Here is the output of my program upon dumping the .text section :Disassembly of section .text:00000000 <_main>: 0: 55 push %ebp 1: 89 e5 mov %esp,%ebp 3: 83 e4 f0 and $0xfffffff0,%esp 6: e8 00 00 00 00 call b <_main+0xb> b: 83 ec 10 sub $0x10,%esp e: c7 04 24 00 00 00 00 movl $0x0,(%esp) 15: 8d 05 3d 00 00 00 lea 0x3d,%eax 1b: 89 44 24 04 mov %eax,0x4(%esp) 1f: 8d 05 5f 00 00 00 lea 0x5f,%eax 25: 89 44 24 08 mov %eax,0x8(%esp) 29: c7 44 24 0c 40 00 00 movl $0x40,0xc(%esp) 30: 00 31: e8 00 00 00 00 call 36 <_main+0x36> 36: b8 00 00 00 00 mov $0x0,%eax 3b: c9 leave 3c: c3 ret0000003d <message>: 3d: 43 inc %ebx 3e: 20 61 6e and %ah,0x6e(%ecx) 41: 64 20 61 73 and %ah,%fs:0x73(%ecx) 45: 73 65 jae ac <title+0x4d> 47: 6d insl (%dx),%es:(%edi) 48: 62 6c 79 20 bound %ebp,0x20(%ecx,%edi,2) 4c: 61 popa 4d: 72 65 jb b4 <title+0x55> 4f: 20 66 6f and %ah,0x6f(%esi) 52: 72 20 jb 74 <title+0x15> 54: 72 65 jb bb <title+0x5c> 56: 61 popa 57: 6c insb (%dx),%es:(%edi) 58: 20 6d 65 and %ch,0x65(%ebp) 5b: 6e outsb %ds:(%esi),(%dx) 5c: 2e 0a 00 or %cs:(%eax),%al0000005f <title>: 5f: 4d dec %ebp 60: 61 popa 61: 64 65 20 62 79 fs and %ah,%fs:%gs:0x79(%edx) 66: 20 43 61 and %al,0x61(%ebx) 69: 70 74 jo df <title+0x80> 6b: 61 popa 6c: 69 6e 4f 62 76 69 6f imul $0x6f697662,0x4f(%esi),%ebp 73: 75 73 jne e8 <title+0x89> 75: 21 0a and %ecx,(%edx) 77: 00 b8 00 00 00 00 add %bh,0x0(%eax) 7d: c9 leave 7e: c3 ret 7f: 90 nopThis brings me back to my question, how do I convert assembly to a constant array of integer opcodes for my main function? | How can I write my main function as assembly opcodes in an integer array? | windows;assembly;c;gcc | null |
_codereview.150044 | The purpose of this code is to simulate epidemics across a population. There are 625 (pop) individuals at random locations. The epidemic parameters are infectious period (inf_period), trans (transmissibility of the disease - essentially virulence), susc (the susceptibility of each individual to the disease), and eps (epislon, the probability of an individual becoming infectious randomly, not due to contact with an infectious person). The argument 'reps' is the number of times to simulate one set of epidemic parameters - that is, one set of [susc, trans, inf_period, eps].In this example, there are 24 possible combinations of parameter values, and we want 400 reps per combination, so 24*400 = 9600 runs. Those values cannot change. To make this code faster, how can the number of loops be reduced (I've heard those are slow)?This has many loops and if statements, and to run the full version will take roughly 2.5 days. How can it be made more efficient in terms of time? I know that may be vague, so if there's a way I can clarify please let me know! I should also mention I have access to a GPU.import numpy as npfrom scipy import spatialimport jsondef fun(susc, trans, inf_period, eps, reps, pop): epi_list = [] count_list = [] new_susc = [] new_trans = [] new_inf_period = [] new_eps = [] count = 0 epi_file = file1.json count_file = file2.json with open(epi_file, 'w') as f, open(count_file, 'w') as h: for i in range(len(trans)): for j in inf_period: for k in eps: should_restart = True while should_restart: should_restart = False broken = False count_2 = 0 for rep in reps: failcount = 0 g1 = external_function_call(pop, susc, trans[i], j, k, full_mat) while(len(g1.keys()) < 10 or np.max(g1.values()) < 10): failcount += 1 if failcount > 50: trans[i] += 1 broken = True break g1 = external_function_call(pop, susc, trans[i], j, k, full_mat) #run again with new i, rep times if not broken: g2 = inf_per_count_time(g1) count += 1 epi_list.append(g1) #if the first epi in the reps works, but the subsequent ones do not, still writes. Bad! count_list.append(g2) new_susc.append(susc) new_trans.append(trans[i]) new_inf_period.append(j) new_eps.append(k) else: #start from rep should_restart = True if rep > 0: #if we've already written an epidemic using this set of parameters for i in range(rep-1, -1, -1): del epi_list[i] del count_list[i] del new_susc[i] del new_trans[i] del new_inf_period[i] del new_eps[i] count -=1 break else: break paras = np.array([np.asarray(new_susc), np.asarray(new_trans), np.asarray(new_inf_period), np.asarray(new_eps)]).T print 'number of parameter rows', paras[:,0].shape with open('parameters.txt', 'w') as newfile1: np.savetxt(newfile1, paras, fmt = ['%f', '%f', '%f', '%f']) print countif __name__ == __main__: pop = 625 susc = 0.3 trans = [1.5, 2.5, 3] inf_period = [2, 3] eps = [0, 0.01, 0.02, 0.05] reps = np.arange(400) fun(susc, trans, inf_period, eps, reps, pop) | Epidemic simulation | python;performance;simulation;scipy | 78 characters of indentation at its deepest: this code is unreadable. We can't easily match the core of the code with the definition of the parameters.To improve that, you can:use 4 space per indentation level instead of 8 as recommended per PEP 8;use itertools.product to iterate over all the combinations of parameters in one single loop instead of 3;remove unused variable declaration such as your opens;use the break ... else construct that can be applied to any loop, this will save you the use of the broken flag;use slice deletion rather than deleting items one by one in a for loop (plus it will be more efficient).This lead to the more readable:import numpy as npfrom scipy import spatialimport jsonimport itertoolsdef fun(susc, trans, inf_period, eps, reps, pop): epi_list = [] count_list = [] new_susc = [] new_trans = [] new_inf_period = [] new_eps = [] count = 0 for i, j, k in itertools.product(range(len(trans)), inf_period, eps): should_restart = True while should_restart: should_restart = False for rep in reps: failcount = 0 g1 = external_function_call(pop, susc, trans[i], j, k, full_mat) while(len(g1.keys()) < 10 or np.max(g1.values()) < 10): failcount += 1 if failcount > 50: trans[i] += 1 break g1 = external_function_call(pop, susc, trans[i], j, k, full_mat) #run again with new i, rep times else: g2 = inf_per_count_time(g1) count += 1 epi_list.append(g1) #if the first epi in the reps works, but the subsequent ones do not, still writes. Bad! count_list.append(g2) new_susc.append(susc) new_trans.append(trans[i]) new_inf_period.append(j) new_eps.append(k) continue # Cleanup because we failed too many times should_restart = True # restart from rep deletion_range = slice(0, rep, 1) del epi_list[deletion_range] del count_list[deletion_range] del new_susc[deletion_range] del new_trans[deletion_range] del new_inf_period[deletion_range] del new_eps[deletion_range] if rep > 0: #if we've already written an epidemic using this set of parameters count -=1 break paras = np.array([np.asarray(new_susc), np.asarray(new_trans), np.asarray(new_inf_period), np.asarray(new_eps)]).T print 'number of parameter rows', paras[:,0].shape with open('parameters.txt', 'w') as newfile1: np.savetxt(newfile1, paras, fmt = ['%f', '%f', '%f', '%f']) print countif __name__ == __main__: pop = 625 susc = 0.3 trans = [1.5, 2.5, 3] inf_period = [2, 3] eps = [0, 0.01, 0.02, 0.05] reps = np.arange(400) fun(susc, trans, inf_period, eps, reps, pop)Now we can start thinking a bit about the code.First off, you don't need to write the call to external_function_call twice, especially with the same set of parameters. It is more idiomatic to use a while True: <call> if <condition>: break rather than <call> while <condition>: <call>. This also let you handle the successful case within that if rather than with your broken flag.In this test, you can also take the len of g1 directly, it's equivalent to using len(g1.keys()). And since g1 seems to be a regular Python dictionnary, there is no need in involving numpy there, Python already has a max builtin.The fail count could also be better handled with a for loop and a named constant:import numpy as npfrom scipy import spatialimport jsonimport itertoolsMAX_FAILED_ATTEMPS = 50def fun(susc, trans, inf_period, eps, reps, pop): epi_list = [] count_list = [] new_susc = [] new_trans = [] new_inf_period = [] new_eps = [] count = 0 for i, j, k in itertools.product(range(len(trans)), inf_period, eps): should_restart = True while should_restart: should_restart = False for rep in reps: for _ in range(MAX_FAILED_ATTEMPS): g1 = external_function_call(pop, susc, trans[i], j, k, full_mat) if len(g1) >= 10 and max(g1.values()) >= 10: g2 = inf_per_count_time(g1) count += 1 epi_list.append(g1) #if the first epi in the reps works, but the subsequent ones do not, still writes. Bad! count_list.append(g2) new_susc.append(susc) new_trans.append(trans[i]) new_inf_period.append(j) new_eps.append(k) break else: trans[i] += 1 # Cleanup because we failed too many times should_restart = True # restart from rep deletion_range = slice(0, rep, 1) del epi_list[deletion_range] del count_list[deletion_range] del new_susc[deletion_range] del new_trans[deletion_range] del new_inf_period[deletion_range] del new_eps[deletion_range] if rep > 0: #if we've already written an epidemic using this set of parameters count -=1 break paras = np.array([np.asarray(new_susc), np.asarray(new_trans), np.asarray(new_inf_period), np.asarray(new_eps)]).T print 'number of parameter rows', paras[:,0].shape with open('parameters.txt', 'w') as newfile1: np.savetxt(newfile1, paras, fmt = ['%f', '%f', '%f', '%f']) print countif __name__ == __main__: pop = 625 susc = 0.3 trans = [1.5, 2.5, 3] inf_period = [2, 3] eps = [0, 0.01, 0.02, 0.05] reps = np.arange(400) fun(susc, trans, inf_period, eps, reps, pop)Now looking at this rewrite and the comment that was associated to the second call to external_function_call, it seems unlikely that this loop is doing any good. No parameters are updated between the various calls. So If the call fail once, it will fail 50 times slowing down the whole thing unnecessarily Unless you meant to trans[i] += 1 before each new call; or if external_function_call relly on some form of randomness.An other thing that bothers me in your code, is how fragile the code is when handling the number of repetitions (reps). You seem to relly on it always starting at 0. But as it is written, I can pass any range, like range(5000, 5801, 2) to get 400 repetitions, not necessarily something that will start at 0.Most importantly, you could have had some combinations of parameters that ran for each rep, say the first 2, so you will already have 800 results in your arrays. But all of a sudden, the third set of parameter fail 50 times at rep = 40. So you are deleting elements 39 down to 0 in your array Wait, what? Why? These are results of previous sets of parameters, they are deemed valid, why on earth should we delete them and keep the 40 last results that we know should be restarted from rep = 0?In the same vein, I don't understand why you count -= 1 if rep is over 0, instead of count -= rep every time.import numpy as npfrom scipy import spatialimport jsonimport itertoolsMAX_FAILED_ATTEMPS = 50def fun(susc, trans, inf_period, eps, repetitions, pop): epi_list = [] count_list = [] new_susc = [] new_trans = [] new_inf_period = [] new_eps = [] count = 0 for i, j, k in itertools.product(range(len(trans)), inf_period, eps): while True: for rep in range(repetitions): for _ in range(MAX_FAILED_ATTEMPS): g1 = external_function_call(pop, susc, trans[i], j, k, full_mat) if len(g1) >= 10 and max(g1.values()) >= 10: g2 = inf_per_count_time(g1) count += 1 epi_list.append(g1) #if the first epi in the reps works, but the subsequent ones do not, still writes. Bad! count_list.append(g2) new_susc.append(susc) new_trans.append(trans[i]) new_inf_period.append(j) new_eps.append(k) break else: trans[i] += 1 # Cleanup because we failed too many times del epi_list[-rep:] del count_list[-rep:] del new_susc[-rep:] del new_trans[-rep:] del new_inf_period[-rep:] del new_eps[-rep:] if rep > 0: #if we've already written an epidemic using this set of parameters count -=1 break else: break # do not restart if we made it through the whole repetitions paras = np.array([np.asarray(new_susc), np.asarray(new_trans), np.asarray(new_inf_period), np.asarray(new_eps)]).T print 'number of parameter rows', paras[:,0].shape with open('parameters.txt', 'w') as newfile1: np.savetxt(newfile1, paras, fmt = ['%f', '%f', '%f', '%f']) print countif __name__ == __main__: pop = 625 susc = 0.3 trans = [1.5, 2.5, 3] inf_period = [2, 3] eps = [0, 0.01, 0.02, 0.05] fun(susc, trans, inf_period, eps, 400, pop)And one last note, I am not entirely sure that modifying trans[i] in place is a good idea, as it affect not only this set of parameters but also every further combinations using this particular value. Instead, I would only increment a local copy.Oh, and make something for these meaningless, one-letter, variable names:import numpy as npfrom scipy import spatialimport jsonimport itertoolsMAX_FAILED_ATTEMPS = 50def fun(susc, trans, inf_period, eps, repetitions, pop): epi_list = [] count_list = [] new_susc = [] new_trans = [] new_inf_period = [] new_eps = [] count = 0 parameters_product = itertools.product(trans, inf_period, eps) for transmissibility, infectious_period, epsilon in parameters_product: while True: for rep in range(repetitions): for _ in range(MAX_FAILED_ATTEMPS): g1 = external_function_call( pop, susc, transmissibility, infectious_period, epsilon, full_mat) if len(g1) >= 10 and max(g1.values()) >= 10: g2 = inf_per_count_time(g1) count += 1 epi_list.append(g1) count_list.append(g2) new_susc.append(susc) new_trans.append(transmissibility) new_inf_period.append(infectious_period) new_eps.append(epsilon) break else: transmissibility += 1 # Cleanup because we failed too many times del epi_list[-rep:] del count_list[-rep:] del new_susc[-rep:] del new_trans[-rep:] del new_inf_period[-rep:] del new_eps[-rep:] if rep > 0: # if we've already written an epidemic # using this set of parameters count -=1 break else: # do not restart if we made it through the whole repetitions break paras = np.array([ np.asarray(new_susc), np.asarray(new_trans), np.asarray(new_inf_period), np.asarray(new_eps) ]).T print 'number of parameter rows', paras[:,0].shape with open('parameters.txt', 'w') as newfile1: np.savetxt(newfile1, paras, fmt = ['%f', '%f', '%f', '%f']) print countif __name__ == __main__: pop = 625 susc = 0.3 trans = [1.5, 2.5, 3] inf_period = [2, 3] eps = [0, 0.01, 0.02, 0.05] fun(susc, trans, inf_period, eps, 400, pop) |
_unix.181395 | I am using OMAPL138 and kernel version 2.6.37 and I would like to improve the boot time. By analyzing the kernel boot process I think it is taking a long time at MII PHY CONFIGURATION. The printscreen is shown below and we can see that it takes almost 19 seconds to configure MII PHY. Is it possible to improve this and make the boot run faster? | Improve kernel boot time | kernel;boot;time | null |
_webmaster.57593 | I'm using Google Tag Manager to track click events.These events are contained within a certain section of the site - within a div class=splash-slide-contentThis div is not the parent div, from inspect element it looks like the grand parent.What would be the best method of restricting the firing of this event? I'd like to create a new macro along the lines of something like: New macro ancestor element > ancestor class contains splash-slide-content.Then I could create a rule that says only fire if ancestor class contains some string (in this case splash-slide-content)Put another way, is there a way to specify only fire this tag if it has an ancestor with class splash-slide-content? | How to restrict Google Tag Manager click events to fire only when in a specific area of the page? | google analytics;google tag manager | Although an old question, in case someone is looking for the answer:Simply replace the div with the clicked element of choice (span,p,li,etc.). |
_unix.91233 | On an RHEL6 system, I'd like my postGIS implementation (ie my postgres/postgresql databases) to use Enthought's Canopy distribution of python, rather than the built-in GNU's distribution. (This is because postGIS needs some packages that seem hard to install from RHEL's built-in repositories.)How can I change the python path / etc just for postgres? | Change default python distribution for postgres from the system's python (to Enthought Canopy) | python;postgresql | null |
_unix.127581 | $ sudo -iu cyrussudo: unable to change directory to /srv/cyrus: Permission deniedsudo: unable to execute /bin/zsh: Permission deniedI don't understand why I would get permission denied for /bin/zsh at all:$ stat /bin/zsh File: `/bin/zsh' -> `/etc/alternatives/zsh' Size: 21 Blocks: 0 IO Block: 4096 symbolic linkDevice: ceh/206d Inode: 49686869 Links: 1Access: (0777/lrwxrwxrwx) Uid: ( 0/ root) Gid: ( 0/ root)Access: 2014-05-02 22:19:33.464671249 +0800Modify: 2014-05-02 22:12:21.447725196 +0800Change: 2014-05-02 22:12:21.452724872 +0800 Birth: -and /srv/cyrus:$ stat /srv/cyrus/ File: `/srv/cyrus/' Size: 4096 Blocks: 8 IO Block: 4096 directoryDevice: ceh/206d Inode: 50467467 Links: 3Access: (0750/drwxr-x---) Uid: ( 1002/ cyrus) Gid: ( 1002/ cyrus)Access: 2014-05-02 22:05:57.702641011 +0800Modify: 2014-05-02 22:05:58.135612918 +0800Change: 2014-05-02 22:11:39.313461373 +0800 Birth: -How do I debug this type of problem? | Can't simulate initial login using sudo | permissions;sudo;users | null |
_codereview.52585 | I have built a delete button in Android, just like in Windows, which removes the string on the right hand side of the cursor (one by one). (Instead of the mainstream Backspace which removes the left side.)Tell me if you have any better ideas.package com.example.app;import android.annotation.SuppressLint;import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.text.Editable;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.view.inputmethod.InputMethodManager;import android.widget.Button;import android.widget.EditText;import android.widget.TextView.BufferType;import android.widget.Toast;public class MainActivity extends Activity { public Toast t, t1,t2; Editable a, b, d, f, a1; String e; public int c, d1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText ed; Button dlt; dlt = (Button) findViewById(R.id.button1); ed = (EditText) findViewById(R.id.editText1); ed.clearFocus(); dlt.setOnClickListener(new OnClickListener() { @SuppressLint(NewApi) public void onClick(View v) { InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); boolean check = mgr.isActive(ed); if(check==true){ Toast.makeText(getApplicationContext(), Welcome, t2.LENGTH_SHORT) .show(); } a = ed.getEditableText(); b = a; c = ed.getSelectionStart(); String a11 = b.toString().substring(c); Toast.makeText(getApplicationContext(), a11, t1.LENGTH_SHORT) .show(); String a22 = b.toString().substring(0, c); boolean daj = b.toString().isEmpty(); if (a11 != null && !a11.trim().equals()) { int strChar = a11.length(); String strcut = a11.substring(1, strChar); e = a22.concat(strcut); ed.setText(e, BufferType.EDITABLE); b = ed.getEditableText(); ed.setSelection(c); } else { Toast.makeText(getApplicationContext(), Cool, t.LENGTH_SHORT).show(); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; }} | Delete (Reverse Backspace) Button | java;android | Name your variables and fields meaningfully. I have no idea what a,b,e, etc are. Don't split your variable declaration and initalization. Instead offinal EditText ed;Button dlt;dlt = (Button) findViewById(R.id.button1);ed = (EditText) findViewById(R.id.editText1);do final EditText ed = (EditText) findViewById(R.id.editText1); final Button dlt = (Button) findViewById(R.id.button1);And be consistent with your final usage. Either use it everywhere where appropriate or don't. Otherwise I start to wonder why ed is final and dlt is not. There a TextUtils.isEmpty() method available on Android. Use it instead of a11 != null && !a11.trim().equals()Use static field access. Instead of t1.LENGTH_SHORT use Toast.LENGTH_SHORT. All the fields t,t1 and t2 are unnecessary.All your fields should be local variables. |
_softwareengineering.244576 | There are a ton of questions like this, but they are mostly very generalized, so I'd like to get some views on my specific usage.General:I'm building a new project on my own in Django. It's focus will be on small businesses. I'd like to make it somewhat customizble for my clients so they can add to their customer/invoice/employee/whatever items. My models would reflect boilerplate items that all ModelX might have. For example:first namelast nameemailaddress...Then my user's would be able to add fields for whatever data they might like. I'm still in design phase and am building this myself, so I've got some options. Working on...Right now the 'extra items' models have a FK to the generic model (Customer and CustomerDataPoints for example). All values in the extra data points are stored as char and will be coerced/parced into their actual format at view building. In this build the user could theoretically add whatever values they want, group them in sets and generally access them at will from the views relavent to that model. Pros: Low storage overhead, very extensible, searchableCons: More sql joinsMy other option is to use some type of markup, or key-value pairing stored directly onto the boilerplate models. This coul essentially just be any low-overhead method weather XML or literal strings. The view and form generated from the stored data would be taking control of validation and reoganizing on updates. Then it would just dump the data back in as a char/blob/whatever.Something like:<datapoint type='char' value='something' required='true' /><datapoint type='date' value='01/01/2001' required='false' />...Pros: No joins needed, Updates for validation and views are decoupled from data Cons: Much higher storage overhead, limited capacity to search on extra contentSo my question is:If you didn't live in the contraints impose by your company what method would you use? Why? What benefits or pitfalls do you see down the road for me as a small business trying to help other small businesses?Just to clarify, I am not asking about custom UI elements, those I can handle with forms and template snippets. I'm asking primarily about data storage and retreival of non standardized data relative to a boilerplate model. | Should custom data elements be stored as XML or database entries? | database;xml;django;custom control | null |
_codereview.105100 | I am working through UPenn CIS 194: Introduction to Haskell (Spring 2013). Since I am not able to take the course for real I am asking for CR (feedback) as it could be from teacher in that course.HW3 - Code golf - Full descriptionmodule Golf whereimport Data.List-- [apple,orange,plum] example-- ... [(apple,0),(orange,1),(plum,2)] added indexes-- ... [(apple,0),(orange,1),(plum,2)] filtered by predicate: index `mod` 1 == 0-- [[apple,orange,plum]] ++ ... [(orange,0),(plum,1)] added indexes-- [[apple,orange,plum]] ++ ... [(orange,0)] filtered by predicate: index `mod` 2 == 0-- [[apple,orange,plum]] ++ [[orange]] ++ ... [[(plum,0)]] added index-- [[apple,orange,plum]] ++ [[orange]] ++ ... [[(plum,0)]] filtered by predicate: 0 `mod` 3 == 0 -- [[apple,orange,plum]] ++ [[orange]] ++ [[plum]]-- [[apple,orange,plum],[orange],[plum]]skips :: [a] -> [[a]]skips = skips' 1skips' :: Integer -> [a] -> [[a]]skips' _ [] = []skips' n root@(_:xs) = [fst $ unzip $ filter devidedByIndex $ zip root [0..]] ++ skips' (n + 1) xs where devidedByIndex x = (snd x) `mod` n == 0-- [1,2,9,3]-- 2 > 1 && 2 > 9 = False-- localMaxima [2,9,3]-- 9 > 2 && 9 > 3 = [9] ++ localMaxima [3]-- [9] ++ []-- [9]localMaxima :: [Integer] -> [Integer]localMaxima [] = []localMaxima (x:[]) = []localMaxima (x:y:[]) = []localMaxima (x:y:z:xz) | y > x && y > z = [y] ++ localMaxima (z:xz) | otherwise = localMaxima (y:z:xz)-- putStr (histogram [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5,6,6,6,6,7,7,7,8,8,9])-- *-- ***-- *****-- *******-- *********-- ==========-- 0123456789histogram :: [Integer] -> Stringhistogram m = transform (maximum n) n where n = countElements mtransform :: Int -> [Int] -> Stringtransform 0 _ = ==========\n0123456789\ntransform i n = intercalate ((map transform' n) ++ [\n]) ++ transform (i - 1) n where transform' x | x >= i = * | otherwise = -- count how many times each number appears in arraycountElements :: [Integer] -> [Int]countElements n = map count [0..9] where count x = length (elemIndices x n) | UPenn CIS 194 Homework 3: Code golf | haskell;homework | goFirst just a blanket statement about names. Since this isa golfing challenge you should pick short names forvaribles, helper functions, etc. Of course, that makesthings less readable, but there are some conventions thatHaskellers follow:go - names a local helper functionxs, ys, zs - a list(x:xs) - xs is the tail of a list whose head is xx' - a value related to xSome people complain about the heavy use of single lettervariable names in Haskell, but when used judiciously I thinkit actually aids readability.skipsYou can perform filter, fst and unzip all in a singlelist comprehension like this:skips' n root@(_:xs) = [ x | (x,k) <- zip root [0..], mod k n == 0] ++ ...Also, note that you define devidedByIndex, but you only call it once.In a situation like that you can always inline the definition where it is used,and that's what we've done here by putting the mod k n ... expressiondirectly into the list comprehension.localMaximumYou have three cases which return the same value, so just put thelast case first and use a default pattern for the others:localMaxima (x:y:z:xz) = ...localMaximum _ = []Next, because we're golfing, you can avoid the otherwise clause andduplicating the recursion call like this:localMaxima (x:y:z:zs) = (if x < y && y > z then [y] else []) ++ localMaximum ...histogramThere are two sub-problems:Computing the countsBuilding the picture.Let's start with #2, and say we have the counts in a list ns, i.e. the countsfor the example is [0,1,2,3,4,5,4,3,2].A quick way to create the row for the k-th level is:row k ns = [ if n >= k then '*' else ' ' | n <- ns ]and then we just need to stack those lines together:(row 9 ns) ++ \n ++ (row 8 ns) ++ \n ++ ... (row 1 ns) ++ \nPerhaps this gives you some ideas on how to improve the code.In your computeElements, again note that your helper count is only used once,so for golfing purposes you can inline it:countElements n = map (\x -> length (elemIndices x n)) [0..9]Also, compare:elementIndices x n - 16 non-space chars[ y | y <- n, y == x ] - 13 non-space charsSince you only interested in the length both will work.Finally, whenever you have map (\x -> ...) [...] it's the same asa list comprehension:map (\x -> .A.) [.B.] = [ .A. | x <- [.B.]]and the list comprehension is shorter by a few characters.import ...The exercise encourages you to look for standard library functions to helpyou reduce your code size.Here are some library functions which might be applicable to these problems:tails :: [a] -> [[a]]sort :: Ord a => [a] -> [a]group :: Eq a => [a] -> [[a]]unlines :: [String] -> String |
_webmaster.19216 | In my website, most of the pages has a linkedin sharing button written in this way:<li> <a id=share_linkedin href=/link/share/linkedin/Dance+Combo+%28Jazz%2C+Tap%2C+Contemporary+Dance%29+%28Age+16+or+above%29 rel=external nofollow class=share_icon title=LinkedIn target=_blank> <span></span> </a></li>I'm sure this is the only code that I use in all the pages for the button.I have also blocked crawling of all the /link/share/ URLs in the robots.txt file.However, I saw many Restricted by robots.txt errors in Google Webmaster. These errors are all associated to /link/share/linkedin/ URLs. Almost every day I got hundreds of such errors, I'm afraid these daily errors will cause negative impact on the ranking of the website.So I'm wonder why google will report error for nofollow links, and what's wrong with my codes?Update: I've got 400 such errors in 4/9/2011 and 370 in 3/9/2011. If there is nothing wrong with the website, then is there an option to get rid of it? | nofollow doesn't stop crawling? | google search console;robots.txt;googlebot;google index;nofollow | According to Google:In general, we don't follow them. This means that Google does not transfer PageRank or anchor text across these links. Essentially, using nofollow causes us to drop the target links from our overall graph of the web. However, the target pages may still appear in our index if other sites link to them without using nofollow, or if the URLs are submitted to Google in a Sitemap.Google doesn't gaurentee that they won't crawl the URL, just that the contents won't affect your PageRank. In fact, Wikipedia entry nofollow explicitly claims that Google does crawl nofollow links, but again, doesn't use the contents to affect your PageRank any.The Restricted by robots.txt message is fine--it won't affect your PageRank either. It is informational only.You could drop the external part of the attribute though; using the standard rel=nofollow is probably safer for crawler parsers that aren't as robust. |
_webapps.22823 | You rate films you've watched and get recommendations on new movies based on other people rates. | Are there any websites providing movies recommendations based on your ratings? | webapp rec;movies;films | You can try TasteKid or Jinni.EDIT: Lifehacker has just posted a top 5 movie recommendation services. |
_bioinformatics.528 | I'm trying to find a programmatic way to automatically extract the following information from a PDB file:RNA sequence Secondary structure restraints in bracket format, e.g. . (( . ( . ) . ))Does software exist that can take a PDB file as input and generate these two pieces of information? e.g. file. 3NDB_ba.pdbThe nucleotide sequence is: gUCUCGUCCCGUGGGGCUCGGCGGUGGGGGAGCAUCUCCUGUAGGGGAGAUGUAACCCCCUUUACCUGCCGAACCCCGCCAGGCCCGGAAGGGAGCAACGGUAGGCAGGACGUCGGCGCUCACGGGGGUGCGGGAC.And the secondary structure :.(((.(..(((((((((.(((((..(((((.(((((((((....)))))))))..)))))....((((((.....(((.....(((....))).....)))..)))))).))))))).))))))).....).))). | How to extract RNA sequence and secondary structure restrains from a PDB file | public databases;pdb;rna;rna structure | I suggest you take a look at rna-pdb-tools we do way more than you need! :-) The tools can get you a sequence, secondary structure and much more using various algorithms, and all is well documented http://rna-pdb-tools.readthedocs.io/en/latest/To get sequence http://rna-pdb-tools.readthedocs.io/en/latest/main.html#get-sequence $ rna_pdb_tools.py --get_seq 5_solution_1.pdb> 5_solution_1.pdb A:1-576CAUCCGGUAUCCCAAGACAAUCUCGGGUUGGGUUGGGAAGUAUCAUGGCUAAUCACCAUGAUGCAAUCGGGUUGAACACUUAAUUGGGUUAAAACGGUGGGGGACGAUCCCGUAACAUCCGUCCUAACGGCGACAGACUGCACGGCCCUGCCUCAGGUGUGUCCAAUGAACAGUCGUUCCGAAAGGAAGor you can get sequence and secondary structure via x3dna (http://x3dna.org/)[mm] py3dna$ git:(master) ./rna_x3dna.py test_data/1xjr.pdbtest_data/1xjr.pdb >1xjr nts=47 [1xjr] -- secondary structure derived by DSSR gGAGUUCACCGAGGCCACGCGGAGUACGAUCGAGGGUACAGUGAAUU ..(((((((...((((.((((.....))..))..))).).)))))))The problem is not trivial. I hope rna-pdb-tools has stuff that can solve this issue for you (http://rna-pdb-tools.readthedocs.io/en/latest/want.html#module-rna_pdb_tools.utils.rna_x3dna.rna_x3dna) |
_unix.309848 | My mousepad is not working after suspend on a Lenovo E460. It used to work perfectly but after this it no longer even appears in xinput. I have tried to plug in a mouse and that works fine. Edit: Restarting etc. does not make it work again, it is completely gone as of after the suspend. | Touchpad not working after suspend Ubuntu 16.04 | ubuntu;touchpad;xinput | Editing the grub file from, GRUB_CMDLINE_LINUX= to, GRUB_CMDLINE_LINUX=i8042.reset i8042.nomux i8042.nopnp i8042.noloop then updating grub solved the problem. |
_unix.162436 | I am working on Kubuntu at work and sometimes I plug wireless headset instead of using standard laptop speakers. Headset works using additional usb plug so it is detected as a separate device by system. I know how to set it as a default audio device for most application (i.e. Amarok) but for some reason browsers (tested with Chrome, Chromium and Firefox) ignore this setting and play audio using embedded speakers. Why? | Browser audio output (Kubuntu) | browser;kubuntu;usb audio | null |
_softwareengineering.157341 | we have some API which will be called either by client A, B, C or DCurrent codedoSomething(String client){if (client.equals(A)){...}else if (client.equals(B)){...}Proposed refactoring 1separate into multiple methods and have each client call the dedicated method such asdoSomethingForClientA()doSomethingForClientB()we need this because internally each method will call other private methods defined in the same classProposed refactoring 2Use strategy (or template) pattern and separate into multiple classes for the clients to callthe method call from client remains doSomething()Which approach is better in the long run? Is there any design pattern to help with option 1 ?or a 3rd option? | Refactoring options - multiple methods in same class or into separate classes | java | Proposed refactoring 2 is better in the long run.This will allow you to extend additional functionality for additional (unforeseen ) client types later, without modifying tested parts of code, for already existing clients. |
_webmaster.69795 | Sorry, I am using a profanity below.I am observing the following behaviour:SafeSearch ON, search fucka: amazon.com is a first result.SafeSearch ON, search a: amazon.com is a sixth result.SafeSearch OFF, search fucka: amazon.com is not even on the first page.SafeSearch OFF, search a: amazon.com is a sixth result.Is there an objective explanation? I could not find anything. | How does Google's SafeSearch affect SEO? | seo;google;moderation | null |
_unix.330466 | I have a synology DS411 device which has a raid5 array of 4 disks. I had what seems to be a one disk failure... which I have raised tickets with Synology I have no progress in last 3 weeks so this is my last resort.Here's what I have been able to dig up so far.############################################################ check mdstat###########################################################mgupta@DiskStation:/etc$ cat /proc/mdstat Personalities : [linear] [raid0] [raid1] [raid10] [raid6] [raid5] [raid4] md2 : active raid5 sdb5[0] sdc5[2] sda5[1] 5846338944 blocks super 1.2 level 5, 64k chunk, algorithm 2 [4/3] [UU_U]md1 : active raid1 sda2[0] sdb2[1] sdc2[2] 2097088 blocks [4/3] [UUU_]md0 : active raid1 sda1[1] sdb1[0] 2490176 blocks [4/2] [UU__]unused devices: <none>Hmm let's check the array status.############################################################ check array status###########################################################sudo mdadm --examine /dev/sda5/dev/sda5: Magic : a92b4efc Version : 1.2 Feature Map : 0x0 Array UUID : 4eaec43d:77af7b98:5f64d654:4b1721a2 Name : DiskStation:2 (local to host DiskStation) Creation Time : Sun Nov 18 12:57:42 2012 Raid Level : raid5 Raid Devices : 4 Avail Dev Size : 3897559680 (1858.50 GiB 1995.55 GB) Array Size : 11692677888 (5575.50 GiB 5986.65 GB) Used Dev Size : 3897559296 (1858.50 GiB 1995.55 GB) Data Offset : 2048 sectors Super Offset : 8 sectors State : clean Device UUID : 1acf0046:de3f9281:ce23b9c8:4173f4f5 Update Time : Wed Dec 14 12:26:33 2016 Checksum : c9902770 - correct Events : 1898945 Layout : left-symmetric Chunk Size : 64K Device Role : Active device 1 Array State : AAAA ('A' == active, '.' == missing)mgupta@DiskStation:/etc$ sudo mdadm --examine /dev/sdb5/dev/sdb5: Magic : a92b4efc Version : 1.2 Feature Map : 0x0 Array UUID : 4eaec43d:77af7b98:5f64d654:4b1721a2 Name : DiskStation:2 (local to host DiskStation) Creation Time : Sun Nov 18 12:57:42 2012 Raid Level : raid5 Raid Devices : 4 Avail Dev Size : 3897559680 (1858.50 GiB 1995.55 GB) Array Size : 11692677888 (5575.50 GiB 5986.65 GB) Used Dev Size : 3897559296 (1858.50 GiB 1995.55 GB) Data Offset : 2048 sectors Super Offset : 8 sectors State : clean Device UUID : bd37470d:75dabe88:4d46f70e:cb9e4206 Update Time : Wed Dec 14 12:26:33 2016 Checksum : ee8f78b0 - correct Events : 1898945 Layout : left-symmetric Chunk Size : 64K Device Role : Active device 0 Array State : AAAA ('A' == active, '.' == missing)mgupta@DiskStation:/etc$ sudo mdadm --examine /dev/sdc5/dev/sdc5: Magic : a92b4efc Version : 1.2 Feature Map : 0x0 Array UUID : 4eaec43d:77af7b98:5f64d654:4b1721a2 Name : DiskStation:2 (local to host DiskStation) Creation Time : Sun Nov 18 12:57:42 2012 Raid Level : raid5 Raid Devices : 4 Avail Dev Size : 3897559680 (1858.50 GiB 1995.55 GB) Array Size : 11692677888 (5575.50 GiB 5986.65 GB) Used Dev Size : 3897559296 (1858.50 GiB 1995.55 GB) Data Offset : 2048 sectors Super Offset : 8 sectors State : clean Device UUID : 52820ab3:78740646:95548e58:29c187d9 Update Time : Wed Dec 14 12:26:33 2016 Checksum : ee728df2 - correct Events : 1898945 Layout : left-symmetric Chunk Size : 64K Device Role : Active device 3 Array State : AA.A ('A' == active, '.' == missing)Hmm so /dev/sdc5 is missing a disk? ############################################################ check events###########################################################mgupta@DiskStation:/etc$ sudo mdadm --examine /dev/sd[a-c]5 | egrep 'Event|/dev/sd'/dev/sda5: Events : 1898945/dev/sdb5: Events : 1898945/dev/sdc5: Events : 1898945The event count on all disks looks good.. so maybe I can still get all my data back?############################################################ gentle array rebuild...###########################################################mgupta@DiskStation:/etc$ sudo mdadm -v --assemble --force /dev/md2 /dev/sda5 /dev/sdb5 /dev/sdc5 mdadm: looking for devices for /dev/md2mdadm: cannot open device /dev/sda5: Device or resource busymdadm: /dev/sda5 has no superblock - assembly aborted############################################################ Lets get info for all 3 disks###########################################################mgupta@DiskStation:/etc$ sudo smartctl -a /dev/sda5smartctl 6.5 (build date Apr 26 2016) [armv5tel-linux-2.6.32.12] (local build)Copyright (C) 2002-16, Bruce Allen, Christian Franke, www.smartmontools.org=== START OF INFORMATION SECTION ===Vendor: WDCProduct: WD20EARX-00PASB0Revision: 51.0User Capacity: 2,000,398,934,016 bytes [2.00 TB]Logical block size: 512 bytesSerial number: WD-WMAZA7614058Device type: diskLocal Time is: Wed Dec 14 17:36:16 2016 ESTSMART support is: Unavailable - device lacks SMART capability.=== START OF READ SMART DATA SECTION ===Current Drive Temperature: 0 CDrive Trip Temperature: 0 CError Counter logging not supported[GLTSD (Global Logging Target Save Disable) set. Enable Save with '-S on']Device does not support Self Test loggingmgupta@DiskStation:/etc$ sudo smartctl -a /dev/sdb5smartctl 6.5 (build date Apr 26 2016) [armv5tel-linux-2.6.32.12] (local build)Copyright (C) 2002-16, Bruce Allen, Christian Franke, www.smartmontools.org=== START OF INFORMATION SECTION ===Model Family: Seagate Barracuda Green (AF)Device Model: ST2000DL003-9VT166Serial Number: 6YD0RVPVLU WWN Device Id: 5 000c50 03def0174Firmware Version: CC32User Capacity: 2,000,398,934,016 bytes [2.00 TB]Sector Size: 512 bytes logical/physicalRotation Rate: 5900 rpmDevice is: In smartctl database [for details use: -P show]ATA Version is: ATA8-ACS T13/1699-D revision 4SATA Version is: SATA 3.0, 6.0 Gb/s (current: 3.0 Gb/s)Local Time is: Wed Dec 14 17:36:22 2016 ESTSMART support is: Available - device has SMART capability.SMART support is: Enabled=== START OF READ SMART DATA SECTION ===SMART overall-health self-assessment test result: PASSEDGeneral SMART Values:Offline data collection status: (0x82) Offline data collection activity was completed without error. Auto Offline Data Collection: Enabled.Self-test execution status: ( 0) The previous self-test routine completed without error or no self-test has ever been run.Total time to complete Offline data collection: ( 612) seconds.Offline data collectioncapabilities: (0x7b) SMART execute Offline immediate. Auto Offline data collection on/off support. Suspend Offline collection upon new command. Offline surface scan supported. Self-test supported. Conveyance Self-test supported. Selective Self-test supported.SMART capabilities: (0x0003) Saves SMART data before entering power-saving mode. Supports SMART auto save timer.Error logging capability: (0x01) Error logging supported. General Purpose Logging supported.Short self-test routine recommended polling time: ( 1) minutes.Extended self-test routinerecommended polling time: ( 327) minutes.Conveyance self-test routinerecommended polling time: ( 2) minutes.SCT capabilities: (0x30b7) SCT Status supported. SCT Feature Control supported. SCT Data Table supported.SMART Attributes Data Structure revision number: 10Vendor Specific SMART Attributes with Thresholds:ID# ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED WHEN_FAILED RAW_VALUE 1 Raw_Read_Error_Rate 0x000f 117 099 006 Pre-fail Always - 152709864 3 Spin_Up_Time 0x0003 084 075 000 Pre-fail Always - 0 4 Start_Stop_Count 0x0032 092 092 020 Old_age Always - 8491 5 Reallocated_Sector_Ct 0x0033 100 100 036 Pre-fail Always - 0 7 Seek_Error_Rate 0x000f 052 036 030 Pre-fail Always - 1383036844200 9 Power_On_Hours 0x0032 070 011 000 Old_age Always - 26495 10 Spin_Retry_Count 0x0013 100 100 097 Pre-fail Always - 0 12 Power_Cycle_Count 0x0032 100 100 020 Old_age Always - 121183 Runtime_Bad_Block 0x0032 100 100 000 Old_age Always - 0184 End-to-End_Error 0x0032 100 100 099 Old_age Always - 0187 Reported_Uncorrect 0x0032 100 100 000 Old_age Always - 0188 Command_Timeout 0x0032 100 100 000 Old_age Always - 0189 High_Fly_Writes 0x003a 100 100 000 Old_age Always - 0190 Airflow_Temperature_Cel 0x0022 056 049 045 Old_age Always - 44 (Min/Max 21/44)191 G-Sense_Error_Rate 0x0032 100 100 000 Old_age Always - 0192 Power-Off_Retract_Count 0x0032 100 100 000 Old_age Always - 64193 Load_Cycle_Count 0x0032 096 096 000 Old_age Always - 8496194 Temperature_Celsius 0x0022 044 051 000 Old_age Always - 44 (0 19 0 0 0)195 Hardware_ECC_Recovered 0x001a 021 006 000 Old_age Always - 152709864197 Current_Pending_Sector 0x0012 100 100 000 Old_age Always - 0198 Offline_Uncorrectable 0x0010 100 100 000 Old_age Offline - 0199 UDMA_CRC_Error_Count 0x003e 200 200 000 Old_age Always - 0240 Head_Flying_Hours 0x0000 100 253 000 Old_age Offline - 17309 (200 184 0)241 Total_LBAs_Written 0x0000 100 253 000 Old_age Offline - 3099252822242 Total_LBAs_Read 0x0000 100 253 000 Old_age Offline - 2293937892SMART Error Log Version: 1No Errors LoggedSMART Self-test log structure revision number 1No self-tests have been logged. [To run self-tests, use: smartctl -t]SMART Selective self-test log data structure revision number 1 SPAN MIN_LBA MAX_LBA CURRENT_TEST_STATUS 1 0 0 Not_testing 2 0 0 Not_testing 3 0 0 Not_testing 4 0 0 Not_testing 5 0 0 Not_testingSelective self-test flags (0x0): After scanning selected spans, do NOT read-scan remainder of disk.If Selective self-test is pending on power-up, resume after 0 minute delay.mgupta@DiskStation:/etc$ sudo smartctl -a /dev/sdc5smartctl 6.5 (build date Apr 26 2016) [armv5tel-linux-2.6.32.12] (local build)Copyright (C) 2002-16, Bruce Allen, Christian Franke, www.smartmontools.org=== START OF INFORMATION SECTION ===Model Family: Seagate Barracuda 7200.14 (AF)Device Model: ST2000DM001-9YN164Serial Number: Z1E0S6X0LU WWN Device Id: 5 000c50 05139e6f0Firmware Version: CC4BUser Capacity: 2,000,398,934,016 bytes [2.00 TB]Sector Sizes: 512 bytes logical, 4096 bytes physicalRotation Rate: 7200 rpmDevice is: In smartctl database [for details use: -P show]ATA Version is: ATA8-ACS T13/1699-D revision 4SATA Version is: SATA 3.0, 6.0 Gb/s (current: 3.0 Gb/s)Local Time is: Wed Dec 14 17:36:48 2016 EST==> WARNING: A firmware update for this drive may be available,see the following Seagate web pages:http://knowledge.seagate.com/articles/en_US/FAQ/207931enhttp://knowledge.seagate.com/articles/en_US/FAQ/223651enSMART support is: Available - device has SMART capability.SMART support is: Enabled=== START OF READ SMART DATA SECTION ===SMART overall-health self-assessment test result: PASSEDGeneral SMART Values:Offline data collection status: (0x82) Offline data collection activity was completed without error. Auto Offline Data Collection: Enabled.Self-test execution status: ( 0) The previous self-test routine completed without error or no self-test has ever been run.Total time to complete Offline data collection: ( 575) seconds.Offline data collectioncapabilities: (0x7b) SMART execute Offline immediate. Auto Offline data collection on/off support. Suspend Offline collection upon new command. Offline surface scan supported. Self-test supported. Conveyance Self-test supported. Selective Self-test supported.SMART capabilities: (0x0003) Saves SMART data before entering power-saving mode. Supports SMART auto save timer.Error logging capability: (0x01) Error logging supported. General Purpose Logging supported.Short self-test routine recommended polling time: ( 1) minutes.Extended self-test routinerecommended polling time: ( 211) minutes.Conveyance self-test routinerecommended polling time: ( 2) minutes.SCT capabilities: (0x3085) SCT Status supported.SMART Attributes Data Structure revision number: 10Vendor Specific SMART Attributes with Thresholds:ID# ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED WHEN_FAILED RAW_VALUE 1 Raw_Read_Error_Rate 0x000f 103 099 006 Pre-fail Always - 6147256 3 Spin_Up_Time 0x0003 095 095 000 Pre-fail Always - 0 4 Start_Stop_Count 0x0032 093 093 020 Old_age Always - 7563 5 Reallocated_Sector_Ct 0x0033 100 100 036 Pre-fail Always - 800 7 Seek_Error_Rate 0x000f 074 060 030 Pre-fail Always - 25741443 9 Power_On_Hours 0x0032 066 066 000 Old_age Always - 30275 10 Spin_Retry_Count 0x0013 100 100 097 Pre-fail Always - 0 12 Power_Cycle_Count 0x0032 100 100 020 Old_age Always - 84183 Runtime_Bad_Block 0x0032 100 100 000 Old_age Always - 0184 End-to-End_Error 0x0032 100 100 099 Old_age Always - 0187 Reported_Uncorrect 0x0032 099 099 000 Old_age Always - 1188 Command_Timeout 0x0032 100 100 000 Old_age Always - 0 0 0189 High_Fly_Writes 0x003a 096 096 000 Old_age Always - 4190 Airflow_Temperature_Cel 0x0022 053 049 045 Old_age Always - 47 (Min/Max 24/47)191 G-Sense_Error_Rate 0x0032 100 100 000 Old_age Always - 0192 Power-Off_Retract_Count 0x0032 100 100 000 Old_age Always - 50193 Load_Cycle_Count 0x0032 097 097 000 Old_age Always - 7572194 Temperature_Celsius 0x0022 047 051 000 Old_age Always - 47 (0 22 0 0 0)197 Current_Pending_Sector 0x0012 100 100 000 Old_age Always - 0198 Offline_Uncorrectable 0x0010 100 100 000 Old_age Offline - 0199 UDMA_CRC_Error_Count 0x003e 200 200 000 Old_age Always - 0240 Head_Flying_Hours 0x0000 100 253 000 Old_age Offline - 15399h+51m+07.327s241 Total_LBAs_Written 0x0000 100 253 000 Old_age Offline - 25716789180543242 Total_LBAs_Read 0x0000 100 253 000 Old_age Offline - 15598169133360SMART Error Log Version: 1No Errors LoggedSMART Self-test log structure revision number 1No self-tests have been logged. [To run self-tests, use: smartctl -t]SMART Selective self-test log data structure revision number 1 SPAN MIN_LBA MAX_LBA CURRENT_TEST_STATUS 1 0 0 Not_testing 2 0 0 Not_testing 3 0 0 Not_testing 4 0 0 Not_testing 5 0 0 Not_testingSelective self-test flags (0x0): After scanning selected spans, do NOT read-scan remainder of disk.If Selective self-test is pending on power-up, resume after 0 minute delay.mgupta@DiskStation:/etc$ ############################################################ try stopped md2###########################################################mgupta@DiskStation:/etc$ sudo mdadm --stop /dev/md2mdadm: failed to stop array /dev/md2: Device or resource busyPerhaps a running process, mounted filesystem or active volume group?Can I just re-assemble it?############################################################ try reassemble###########################################################mgupta@DiskStation:/etc$ sudo mdadm --assemble --run --force /dev/md2 /dev/sda5 /dev/sdb5 /dev/sdc5mdadm: cannot open device /dev/sda5: Device or resource busymdadm: /dev/sda5 has no superblock - assembly abortedHmm... no superblock? Not sure what I can do now...############################################################ space history to see raid config###########################################################mgupta@DiskStation:/etc$ sudo more space/space_history_20161203_222319.xml<?xml version=1.0 encoding=UTF-8?><spaces> <space path=/dev/vg1000/lv reference=/volume1 uuid=XVJ3ii-EoQW-Y4B3-DeVC-o0Yq-TqtR-7o2MCI device_type=1 drive_type=0 container_type=2 limited_raidgroup_num=12 > <device> <lvm path=/dev/vg1000 uuid=Jv3wdF-3ARY-qlN7-Rl5B-ctD2-DiOg-pli8Pz designed_pv_counts=1 status=normal total_size=5986647539712 free_size=0 pe_size=4194304 expansible=0 max_size=5846338944> <raids> <raid path=/dev/md2 uuid=4eaec43d:77af7b98:5f64d654:4b1721a2 level=raid5 version=1.2> <disks> <disk status=normal dev_path=/dev/sda5 model=WD20EARX-00PASB0 serial=WD-WMAZA7614058 partition_version=7 partition_start=9453280 partition_size=3897561728 slot=1> </disk> <disk status=normal dev_path=/dev/sdb5 model=ST2000DL003-9VT166 serial=6YD0RVPV partition_version=7 partition_start=9453280 partition_size=3897561728 slot=0> </disk> <disk status=normal dev_path=/dev/sdc5 model=ST2000DM001-9YN164 serial=Z1E0S6X0 partition_version=7 partition_start=9453280 partition_size=3897561728 slot=3> </disk> </disks> </raid> </raids> </lvm> </device> <reference> <volumes> <volume path=/volume1 dev_path=/dev/vg1000/lv uuid=XVJ3ii-EoQW-Y4B3-DeVC-o0Yq-TqtR-7o2MCI type=ext4> </volume> </volumes> </reference> </space></spaces>############################################################ mdadm detail ###########################################################mgupta@DiskStation:/dev/vg1000$ sudo mdadm --detail --scanmdadm: cannot open /dev/md/0: No such file or directorymdadm: cannot open /dev/md/1: No such file or directoryARRAY /dev/md2 metadata=1.2 name=DiskStation:2 UUID=4eaec43d:77af7b98:5f64d654:4b1721a2ARRAY /dev/md/0_0 metadata=0.90 UUID=a4880af1:1fc10752:3017a5a8:c86610be############################################################ dmsetup###########################################################mgupta@DiskStation:/dev/vg1000$ sudo dmsetup lsvg1000-lv (253:0)mgupta@DiskStation:/dev/vg1000$ sudo dmsetup tablevg1000-lv: 0 11692670976 linear 9:2 1152mgupta@DiskStation:/dev/vg1000$ ############################################################ cat /proc/partitions###########################################################mgupta@DiskStation:/etc$ cat /proc/partitionsmajor minor #blocks name 8 0 1953514584 sda 8 1 2490240 sda1 8 2 2097152 sda2 8 3 1 sda3 8 5 1948780864 sda5 8 16 1953514584 sdb 8 17 2490240 sdb1 8 18 2097152 sdb2 8 19 1 sdb3 8 21 1948780864 sdb5 8 32 1953514584 sdc 8 33 2490240 sdc1 8 34 2097152 sdc2 8 35 1 sdc3 8 37 1948780864 sdc5 31 0 512 mtdblock0 31 1 2048 mtdblock1 31 2 1280 mtdblock2 31 3 64 mtdblock3 31 4 128 mtdblock4 31 5 64 mtdblock5 31 6 4096 mtdblock6 9 0 2490176 md0 9 1 2097088 md1 9 2 5846338944 md2 253 0 5846335488 dm-0 9 127 2490176 md127What should I do next? | mdadm cannot start failed raid5 array synology | mdadm;raid5;synology | null |
_webmaster.47016 | I need to design a mobile site for phones and tablet, should I design for retina and scale down or the opposite? Or should I even design for retina? Thanks | Designing for mobile site? | mobile;design | null |
_cs.3190 | I need to show that $\qquad \displaystyle S = \{(10^p)^m \mid p \geq 0, m \geq 0\}$is not a regular language using pumping lemma.Can I multiply the product of the powers and express it to: $S = \{ 1^m 0^{pm} \mid \dots \}$ and apply the pumping lemma where I pump 1's then say that the language doesn't accept the new string? | Pumping Lemma: is it valid to multiply the product of powers in this case? | formal languages;regular languages;pumping lemma | null |
_webmaster.25142 | I want to use images that I created in PS for page titles. Because they will be images they will not be picked up by Google, etc. What is the best practice for hiding the <h1>? I was planning on setting the <h1> visibility to hidden. Is this ok to do?updateI want to hide <h1> tag behind header image. I read how to do it if I just link an image (fine). My header is a little different. I have a background image taking up the whole header div. On top of that I have a flash file playing (mostly transparent) with some star burst effects. I want this to be SEO friendly. | Best and safest SEO way to hide h1 tags | html;css;seo | Use it like this<h1> <a href=http://website.com> <img src=image.jpg alt=My Website /> </a></h1>Check this link from a Google Webmaster: https://www.youtube.com/watch?v=fBLvn_WkDJ4 |
_ai.3089 | What are bottleneck features? (Mentioned herehttps://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html).Do they change with the architecture? Do are they final output of Conv. layers before the FC layer?Why are they called so? | What are bottleneck features? | terminology | null |
_webmaster.36275 | In my site I prefix the images and links with the domain of the site for better SEO using the code below:public static string GetHTTPHost() { string host = ; if (HttpContext.Current.Request[HTTP_HOST] != null) host = HttpContext.Current.Request[HTTP_HOST]; if (host == site.co.uk || host == site.com) { return http://www. + host; } return http://+ host; }This works great, but for some reason, lots of links have now changed to http://www.baidu.com/...There is no sign of this in any of the code or project, the files on the server also have a change date when i last did the publish at 11 yesterday, so all the files on there look fine. I am using ASP.net and Umbraco 4.7.2Does anyone have any ideas? thanks | Links in my site have been hacked | asp.net;iis7;c# | null |
_softwareengineering.334225 | In a Lisp dialect, I've implemented ANSI-CL-like support for printing objects such that their circular and shared structure is encoded. This is enabled by the special variable *print-circle*. Similarly to ANSI-CL, I have it working when it traverses objects that have custom print methods. But there are tricky corner cases.For reference, let's make this diagram. Object X is the thing being printed, and the pyramid underneath it represents the dependent tree of constituent objects: nested lists, and whatever. Object O is a constituent which is an OOP object with a custom print method. When this is invoked, it can print various objects such as objects R and NR. R is reachable through one or more of the slots of object O. Object NR is not reachable that way: the print method pulls it from a global variable or whatever: X | / \ / \ / \ / \ / \ <_________O_> | / print ,-' `---. | | R NR | | / \ / \ <___> <___>Now I developed an algorithm which works in two passes. When the printer is called out of the blue to print X (not a recursive call) and circle printing is enabled, it creates a new circle printing context which contains a hash table for cycle detection. Before doing anything else, the function walks the entire graph rooted at X, which reaches O and recurses into R. It then knows all the duplicate objects and cycles, and can proceed to walk the structure and generate the circular notation. It has no knowledge of NR. However, when object O's print method is called, and recurses into the printer to print the object NR, the printer will supplement the hash table by walking the object NR at that point. Everything is cool if NR is self-contained: it can have internal cycles and shared substructure. What we ensure is that the label numbering for the objects occurring in NR doesn't conflict. If X and R use labels 1 through 21, then any labels under NR start at 22.The troublesome case is this one: X | / \ / Y < ----------. / \ | / \ | / \ | <_________O_> | | | / print | ,-' `---. | | | | R NR | | | | / \ / \ | <___> <>--'Suppose NR contains a backpointer into the previously traversed structure, either X or R, to some object Y. The algorithm will break down; if that referenced object Y does not appear two or more times in the originally traversed structure, then it was not noted by the algorithm as requiring the special label def/ref notation. It cannot be correctly rendered as a #<n># reference. (If Y did appear two or more times prior to processing NR, then the occurrence of it encountered via NR is just another occurrence that will be rendered correctly. For instance if Y is represented as label 17, it will turn into #17#.) If Y appeared once, though, we can no longer go back and patch the #17= label definition in front of it in the output that we already printed; by the time we call the print method which recurses into NR, prior structure has already been printed.Good sub-case of bad case: X | / \ rendered as #17=Y / Y < ----------. / \ | / \ | / \ | <_________O_> | | | / print | ,-' `---. | | | | R NR | | | | / \ / \ | <_Y_> <__Y>---' Rendered as #17# Also rendered as #17#: lucky!If the second occurrence of Y under R is missing, then the top Y is just rendered as itself without the #17= label. When printing NR, we therefore cannot render Y as #17#; that would be a dangling label ref. We might render Y as a new object, say number 256: #256=(...) which might recurse into NR again, where the second printing of Y becomes #256#. Or we could recognize the situation and throw an exception: a print method pitched us a curve ball unsupported by *print-circle*.The question is: is it a requirement in ANSI Common Lisp to handle that case? Can print methods procure absolutely any existing object from the image, pass it to the printer recursively, and must it be handled properly, no matter that it is unrelated to the object O and not reachable through that object's slots? | Lisp: circular structure printing through user-defined print methods: what are the requirements? | lisp;common lisp | null |
_unix.166421 | I am using a Lenovo IdeaPad Y580 laptop with an Intel i7 CPU, an Intel HD4000 integrated GPU, and NVIDIA GeForce GTX660M discrete GPU.I have recently installed Debian testing (jessie) on it, previously using Ubuntu 14.10.To be able to use the discrete graphics card, I have installed Bumblebee, following the guide on Debian wiki. All apps seemed to run right using optirun.Then, I installed Steam from the repository. Problem is, that optirun fails to launch any game ran from Steam (you can notice that the user status changes to In-Game for a while, but then reverts to online). Running games using the integrated GPU works perfectly fine.I believe that there is some problem with the libraries. I noticed, that when editing the Bumblebee config from:PrimusLibraryPath=/usr/lib/x86_64-linux-gnu/primus:/usr/lib/i386-linux-gnu/primusto:PrimusLibraryPath=/usr/lib/x86_64-linux-gnu:/usr/lib/i386-linux-gnuSteam appears to launch the game using optirun. However, it is launched by the IGP, guiding by the low FPS. | Can't launch Steam games using optirun (Bumblebee) | debian;steam;bumblebee | This problem is caused by the faulty libdrm-intel package, version 2.4.58-2 to be exact. Downgrading to 2.4.56-1 (and installing the dependencies, unfortunately) fixes the problem.The packages can be downloaded from here (this is from the official debian server, no need to worry). Don't forget to download both i386 and amd64 packages if you are using multiarch. |
_codereview.154079 | I often need to perform LinQ queries to get distinct items from a IEnumerable based on one of its properties. I would like to know if this is a good way to wrap this operation:<Extension()> Function DistinctOn(Of T)(iet As IEnumerable(Of T), identity_property As Func(Of T, Object) ) As IEnumerable(Of T) Return iet.GroupBy(identity_property).Select(Function(g) g.First)End FunctionUsing example (pastas is a IEnumerable of Newtonsoft.Json.Linq.JObject):Dim dpastas = pastas.DistinctOn(Function(jo) jo.Value(Of Integer)(id)).ToArrayIt works Ok, but I'd like to know if it is good code also. Thank you very much! | LinQ wrapper to get distinct items from a IEnumerable based on a function of item | linq;vb.net | null |
_unix.278514 | Okay, so I been trying to figure this problem for a while and I'm coming up with errors left and right. This is my first time trying to learn the basics. So any advice would be helpful! Problem: I'm trying to write a Bash shell script program that prompts for and reads two integers from the user. The second argument is assumed to be greater than the first. The output of the program is a counting of numbers beginning at the first number and ending with the second number. In other words the output would look like this: Please enter the first number: 3 Please enter the second number, larger than the first: 6 3 4 5 6Okay, so this is what I have so far~ read -p Please Enter the first number : n1 echo $n1 read -p Please Enter the second number, larger than the first : n2 echo $n2 FIRSTV=0 SECONDV=1 if [ 1 -gt 0] then count=$((FIRSTV-SECONDV)) echo $COUNT fi | Bash shell script program that prompts for and reads two integers from the user. | bash;shell;shell script;centos;arithmetic | If you can use seq, you could do this:read -p Please Enter the first number : n1echo $n1read -p Please Enter the second number, larger than the first : n2echo $n2seq $n1 $n2If you have to do it entirely in shell and can use a modern shell like bash, ksh, zsh etc (but not ash or dash or similar strictly POSIX shell), you could replace the seq command with:eval printf '%s\n' {$n1..$n2}You need to use eval for the second version because bash/ksh/etc sequences expect actual integers like {1..5}, not variables like {$n1..$n2}. eval expands the variables so that their actual values are used inside the {...} sequence.if you want to do it with a loop and no fancy bash/ksh/etc features, you could replace the seq or eval lines with something like:c=$n1while [ $c -le $n2 ] ; do echo $c c=$((c+1))doneThis works in any POSIX-compatible shell, including dash and ash, as well as bash etc. |
_scicomp.3482 | I know that long back Dr. Leszek Demkowicz finite elements codes(1Dhp,2Dhp,3Dhp) were available in his website. I'm finding it difficult to locate it now. Is there any alternatives available to these codes in FORTRAN(77/90) only. | Where to find Leszek Demkowicz's finite element codes or alternatives? | finite element | Prof. Demkowicz has asked me to post the following reply (I have slightly edited it so that fits better with the site's format):1D and 2D codes come with the first volume of my book. I can E-mail both codes following a personal request but it is impossible to read them w/o my book...The (old) 3D code has been described in the second volume of our books. It is still in use by my colleagues in Cracow including Dr. Rachowicz. Please contact him directly for a working copy of that code. Again, it is impossible to use that code w/o reading the book first.We have a new, very powerful 3Dhp code (developed by current students) that it is accessible to my collaborators. Interested parties should get in touch with me directly... |
_datascience.9741 | The objective function of kernel K-means is $$ \sum\limits_{c=1}^k \sum\nolimits_{a_i \in c} w_i \Vert \phi(a_i)- m_c \Vert^2 \ $$where$$ m_c = \frac{\sum\nolimits_{a_i \in c }w_i\phi(a_i)}{\sum\nolimits_{a_i \in c }w_i} $$I need to know how to determine wi | How to set weight in Weighted Kernel K-Means? | machine learning;data mining;clustering;k means;clusters | null |
_codereview.77302 | I want to convert string arrays with following structure:static String[] lines = { @1 var_decl name: testStr parent: @7, srcp: Auto.cpp:6 };into Java objects with following structure:class Token { String type; String name; String source; Token parent;}So far I'm parsing this in this way:Token parseLines(String[] lines) { String[] firstElements = lines[0].split( ); String[] secondElements = lines[1].split( ); Token newToken = new Token(); newToken.type = firstElements[6]; newToken.name = firstElements[16]; String parentName = firstElements[19]; newToken.parent = getParent(parent); // find parent by name newToken.source = secondElements[26]; return newToken;}As you can see, this is far from elegant. How can I improve this? | Parsing objects from complex String in Java | java;parsing | null |
_unix.294864 | lspci gives me the following information:$ lspci|grep VGA01:00.0 VGA compatible controller: NVIDIA Corporation GF104 [GeForce GTX 460] (rev a1)This is all correct, but this is generic name of the GPU. But Driver ManagerKDE Control Modulegives me much more interesting information: above all the options of drivers to install it saysNVIDIA Corporation N460GTX Cyclone 1GD5/OCThis is exactly the name the vendor (MSI) gave it.How can I find out such names without using KDE utilities? I'd prefer a console-based solution.In other words, where does the KCM take this name from? | How do I get vendor-given name of my video card? | linux;command line;hardware | You can use udevadm to get this information. For example on my system lspci gives me:# lspci|grep VGA 01:00.0 VGA compatible controller: NVIDIA Corporation GK106 [GeForce GTX 650 Ti Boost] (rev a1)Querying udev instead I get:# udevadm info -q property -p /sys/bus/pci/devices/0000:01:00.0 DEVPATH=/devices/pci0000:00/0000:00:02.0/0000:01:00.0DRIVER=nvidiaID_MODEL_FROM_DATABASE=GK106 [GeForce GTX 650 Ti Boost] (GeForce GTX 650 Ti Boost TwinFrozr II OC)ID_PCI_CLASS_FROM_DATABASE=Display controllerID_PCI_INTERFACE_FROM_DATABASE=VGA controllerID_PCI_SUBCLASS_FROM_DATABASE=VGA compatible controllerID_VENDOR_FROM_DATABASE=NVIDIA CorporationMODALIAS=pci:v000010DEd000011C2sv00001462sd00002874bc03sc00i00PCI_CLASS=30000PCI_ID=10DE:11C2PCI_SLOT_NAME=0000:01:00.0PCI_SUBSYS_ID=1462:2874SUBSYSTEM=pciUSEC_INITIALIZED=22791556The ID_MODEL_FROM_DATABASE gives a more detailed description of the card.As for how to know the value to use for the -p argument, use the first part of the lspci output. For example if lspci showed 12:34.5, you would use /sys/bus/pci/devices/0000:12:34.5 |
_codereview.18300 | (function( $ ){ var monthNames = [ , , , , , , , , , , , ]; var dayNames = [,,,,,,]; var now = new Date(); var methods = { init : function( options ) { var settings = $.extend( { 'year' : now.getFullYear(), 'month' : now.getMonth(), 'link' : '%y/%m/%d', 'url' : '', 'dates' : [] }, options); return this.each(function(){ if (!$(this).data('year')){ $(this).data('year',settings.year); } if (!$(this).data('month')){ $(this).data('month',settings.month); } if (!$(this).data('link')){ $(this).data('link',settings.link); } $(this).data('dates',settings.dates); $(this).data('url',settings.url); methods.render($(this)); }); }, destroy : function( ) { return this.each(function(){ $(this).html(''); }) }, render : function( elem ) { year = elem.data('year'); month = elem.data('month'); link = elem.data('link'); dates = elem.data('dates'); date = new Date(year,month,1); elem.html('<table class=calendar></table>'); var calendar=elem.find('.calendar'); calendar.append('<tr class=calendar-header><th colspan=7><a href=# class=icon-chevron-left calendar-prev-month></a>'+monthNames[month]+' '+year+'<a href=# class=icon-chevron-right calendar-next-month></a></th></tr>'); calendar.append('<tr class=calendar-week><th>'+dayNames.join('</th><th>')+'</th></tr>'); var str = '<tr>'; var week = date.getDay(); if (week == 0) { week=7} for (day=1;day<week;day++){ str=str+<td></td>; } date.setMonth(month+1); date.setDate(0); for (day=1;day<=date.getDate();day++){ var link_href = link.replace(%y,year).replace(%m,month+1).replace(%d,day); var day_text = ''; if ($.inArray(day, dates)>=0){ day_text = '<a href='+link_href+' class=calendar-day-link>'+day+'</a>'; } else { day_text = day; } str=str+'<td>'+day_text+'</td>'; if (week++ % 7 == 0){ str=str+</tr></tr>; } } str = str + '</tr>'; calendar.append(str); calendar.find('.calendar-next-month').click(methods.next_month); calendar.find('.calendar-prev-month').click(methods.prev_month); }, next_month : function( e ) { e.preventDefault(); elem = $(this).parents('.calendar').parent(); year = elem.data('year'); month = elem.data('month')+1; url = elem.data('url'); if (month>11){ year++; month=0; } elem.data('year',year).data('month',month); $.getJSON(url+'?year='+year+'&month='+(month+1),function(data) { elem.data('dates',data); methods.render(elem); }); }, prev_month : function( e ) { e.preventDefault(); elem = $(this).parents('.calendar').parent(); year = elem.data('year'); month = elem.data('month')-1; url = elem.data('url'); if (month==-1){ year--; month=11; } elem.data('year',year).data('month',month); $.getJSON(url+'?year='+year+'&month='+(month+1),function(data) { elem.data('dates',data); methods.render(elem); }); }, }; $.fn.calendar = function( method ) { // Create some defaults, extending them with any options that were provided if ( methods[method] ) { return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + method + ' does not exist on jQuery.tooltip' ); } }; })( jQuery ); | jQuery calendar plugin | javascript;jquery;datetime | null |
_cs.54424 | I am a bit confused by the notation here, http://www.boazbarak.org/sos/files/lec3.pdf Given 3 Boolean variables $x_i, x_j, x_k$ what is supposed to be the meaning of $x_i \oplus x_j \oplus x_k$? Is this to be understood as say $((x_i \oplus x_j )\oplus x_k )$? And hence this is true for only $2$ cases $x_i =0, x_j = 1, x_k =0$ and $x_i = 1, x_j = 0, x_k = 0$ ?But then we could have bracketed it as $(x_i \oplus (x_j \oplus x_k))$ and then the only true assignments would have looked as $x_i = 0, x_j =1, x_k = 0$ and $x_i = 0, x_j =0, x_k = 1$ and these are different. Also one could have used commutativity to write it in other re-arranged forms and gotten different true selections!But then the note above seems to claim that if the $x_a$s are coming as coordinates of a vector $x \in \{\pm 1\}^n$ then the product $x_ix_j x_k$ is the same as having a linear equation in those $3$ variables. Why so? (for example an assignment $x_i = x_j = x_k =1$ will evaluate to $1$ for the product but under mod 2 arithmetic $x_i + x_j + x_k = 0$ for this assignment!) Also it is being claimed that the value of $x_ix_jx_k$ can only be $\pm 1$ (which they denote as $a_{ijk}$) for $x \in \{\pm 1\}^n$ and that is okay only if one ignores the first claim that these are supposed to be linear equations! This $x_ix_j x_k$ product notation looks more confusing later on when they say that corresponding to two subsets $S, T \subset \{1,..,n\}$ one can take two expressions of the form $x_S = \prod_{i \in S} x_i$ and $x_T = \prod_{i \in T} x_i$ and construct $x_U = x_S x_T$ and that this somehow corresponds to doing ``$U = S \oplus T$ - and I don't know what it means to take a XOR of two subsets! | About the notation of XOR-SAT | np complete;optimization;np hard;np | XOR is an associative operation, so $x_i \oplus x_j \oplus x_k$ is unambiguous. There are in fact four satisfying assignments, given by$$ (x_i,x_j,x_k) \in \{(0,0,1),(0,1,0),(1,0,0),(1,1,1)\}. $$XOR satisfies the useful property$$ (-1)^{x \oplus y} = (-1)^x (-1)^y. $$Therefore $x_i \oplus x_j \oplus x_k = 1$ is the same as$$ (-1)^{x_i} (-1)^{x_j} (-1)^{x_k} = (-1)^1.$$If we think of our variables as $X_i = (-1)^{x_i}$, then the equation $x_i \oplus x_j \oplus x_k = 1$ is completely equivalent to $X_i X_j X_k = -1$. Since XOR is really just addition in the group $\mathbb{Z}_2$, you can think of both formulations as linear equations.Yet another interpretation of XOR is in terms of sets. Just as AND corresponds to intersection and OR to union, the XOR operation corresponds to symmetric difference, sometimes denoted $\triangle$ or $\Delta$. You can easily check that $x_S x_T = x_{S \triangle T}$, essentially using $x_i^2 = 1$. |
_webmaster.12197 | is it possible to create pages in more than one language without having to create separate pages for each language in Google Sites?This isn't a feature of Google Sites, but I was hoping there might be a workaround.Greets,Kenny | Creating multi-language pages in Google Sites | multilingual;google sites | null |
_unix.153006 | Using a live CD\USB to try a Linux distribution failed me to test aspects like graphics\wireless drivers. I remember when I tried an Ubuntu live CD it was loaded using a virtual machine so I couldn't test if my graphics drivers will be stable or not.So is there a way to fully test Linux distributions without having to install them which is a time consuming task and requires formatting the hard-disk with every installation ?Or at least test the graphics drivers availability ? | How to try every bit of a Linux distro without installing it? | drivers;live usb;livecd;proprietary drivers | null |
_unix.12177 | I have just bought a Dell Inspiron 1510 and loaded Fedora 12 along with Windows. I cannot detect any wireless networks through my network applet on the tool bar. $:lscpi12:00.0 Network controller: Broadcom Corporation Device 4727 (rev 01)13:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8101E/RTL8102E PCI Express Fast Ethernet controller (rev 02)I installed the following rpms: kmod-wl-2.6.31.5-127.fc12.i686.PAE-5.10.91.9.3-3.fc12.6.i686kmod-wl-PAE-5.10.91.9.3-3.fc12.6.i686broadcom-wl-5.10.91.9.3-1.fc12.noarchand restarted the system but it still doesn't work. | Fedora 12 No wireless networks detected | fedora;wifi;rpm;broadcom | null |
_softwareengineering.246612 | Moinsen,I am somehow stucked in a design problem. Language is ANSI-C.Lets assume we have a tinkerbox of software-modules:one module for the logic Logic(at least) one module doing some logging Loggertwo modules, both giving a frame to let the program run, lets sayone with a GUIone for commandline...Therefore, the same logic could used in a comandline- and a graphic-version of the software. The Logic has to log some errors but should not know anything about the specific logger as it could be dependent on the frame. It is obvious to give Logic a function pointer that has to be filled by the frame to bind the used Logger to the Logic.At Logging-Module (all code Pseudo-ANSI-C): void Logger_Log(char *sLogText) { //do some stuff }At Logic-Module: void Logic_PseudoLog(char *sLogText) { printf(sLogText); } void(* Logic_Log)(char *sLogText) = &Logic_PseudoLog; void Logic_SetLogger(void(* LogFct)(char *sLogText)) { Logic_Log = LogFct; }At GUI/Cmd-Line: #include Logger.h #include Logic.h Logic_SetLogger(&Logger_Log);Now I want to introduce different severity levels for logging and implement them as an enum in Logger: //Logger.h: typedef enum { DEBUG, INFO, ERROR } teLogLevel; void Logger-Log(char *sLogText, teLogLevel eLevel);And here the problem rises: The function-pointer at Logic needs to have the correct signature. To do so, it has to know about teLogLevel. Therefore Logic has to know about the Logger, exactly the case I wanted to avoid with the indirection in the first place. #include Logger.h void(* Logic_Log)(char *sLogText, teLogLevel eLevel);The situation as layed out is just an example. Please don't solve it by saying something like use int instead of enum or build three functions for the levels. The bottemline question is:How to handle enums in an indirection with functionpointers at ANSI-C?How to inject enums into a module, that should not now about the origin of the enums? | How to handle enums in an indirection with functionpointers at ANSI-C? | design;c;project structure | In your current design, the Logic module already has a dependency on the Logger module, but that dependency is hidden. The dependency lies in the fact that both Logic and Logger must agree on the set of functions used for logging (one function) and their signatures (void (char*)).The way out of here is to clearly separate the interface from the implementation. In particular, the Logger module only provides the logging interface. The implementations are either provided by the GUI/Cmd-Line modules, or by separate Logger-Implementation modules that can depend on the GUI/Cmd-Line modules.The Logger module would only consist of a single header file, like this/* File: Logger.h */typedef enum { DEBUG, INFO, ERROR} teLogLevel;typedef void (*LoggerFuncT)(char *sLogText, teLogLevel eLevel);/* Logger function that discards all logging. Can be used as a safe default. */static void NullLogFunc(char*, teLogLevel) {}All other modules that either use or implement logging functionality need to refer to this header to know the correct function signatures and other types (including enums).For example, the Logic module would use it like this:#include Logger.hLoggerFuncT Logic_Log = NullPseudoLog;void Logic_SetLogger(LoggerFuncT LogFct){ Logic_Log = LogFct;}void Logic_DoSomething(){ Logic_Log(Entering Logic_DoSomething(), DEBUG); //... Logic_Log(Leaving Logic_DoSomething(), DEBUG);}In the GUI module, you could have an implementation like this:void GUI_LogToDebugWindow(char* sText, teLogLevel eLevel){ //...}/* Let the Logic module use this function as logger. * The compiler will complain here if the logger signatures don't match. */Logic_SetLogger(GUI_LogToDebugWindow); |
_unix.388497 | According to the book Advanced Programming in the Unix Environment :-The character l in the name lseek means long integer. Before the introduction of the off_t data type, the offset argument and the return value were long integers. lseek was introduced with Version 7 when long integers were added to C. (Similar functionality was provided in Version 6 by the functions seek and tell.)We know that there is a limit on the value of file descriptors.That value lies in the range 0-OPEN_MAX-1.So,if earlier versions use long integer for file descriptors ,then this could mean that the maximum number of files which can be opened per process must vary according to the system word format(32 bit or 64 bit),and this means that the number of available file descriptors could be of the order of 10^18.Am I right? | What was the reason for lseek function to return file descriptors as long integer? | c;programming;historical unix | null |
_unix.68900 | My kid wants to use Linux and wants to be ageek in Linux. I am really glad at my kid's wish. Now I want to introduce my kid to Linux. Which linux distribution or distributions should I suggest? | Recommended Linux distribution or distributions for children | distribution choice | I don't know how young are your children, so I don't know how relevant this is, but there are projects targeted at kids:Edubuntu: A project going after schools. It's developed with young kids in mind.Qimo: Is based on the popular Ubuntu, and is developed for children aged 3 and up.DoudouLinux: A project that suit children from 2 to 12 years old but also makes it easy for Dad and Mum. |
_codereview.70804 | I have a data set with close to 6 million rows of user input. Specifically, users were supposed to type in their email addresses, but because there was not pattern validation put in place we have a few months worth of interesting input.I've come up with a script that counts every character, then combines it that so I can see the distribution of all characters. This enables me to do further analysis and get a sense of the most common mistakes so I can begin to clean the data. My question is: how would you optimize the following for speed?import pandas as pdimport numpy as npfrom pandas import Series, DataFramefrom collections import Counterdf = pd.DataFrame({'input': ['Captain Jean-Luc Picard <[email protected]>','[email protected]','geordi @starfleet.com','[email protected]','rik#[email protected]'],'metric1': np.random.randn(5).cumsum(),'metric2': np.random.randn(5)})l = []for i in range(len(df.index.values)): l.append(dict(Counter(df.ix[i,'input'])))dist = pd.DataFrame(l).fillna(0)dist = dist.sum(axis=0)print(dist)I've run this over ~1/3 of my dataset, and it takes a while; it's still tolerable, I'm just curious if anyone could make it faster. | Speed up script that calculates distribution of every character from user input | python;pandas | Since you are using Counter already, it should be faster to do the whole job with it:c = Counter()for i in range(len(df.index.values)): c.update(df.ix[i,'input'])for k, v in c.items(): print(k, v) |
_softwareengineering.228999 | We are redesigning our corporate website with the following functions:we want to give the marketing users flexibility and freedom to add new static pages, change the static pages or contents of static pages without the developer(s)/deployment team getting involved.we want developers to work on the dynamic portion of the website. How to architect the website to make sure that the layout/look and feel of the website stays same across all the pages and achieve the above mentioned work?Any experience? Suggestions? | Corporate website design | web development;web services;web;websites;web framework | Step 1) Research the content management systems out in the world, as Mickey Sly says.Step 2) Select one that nearly fits. Implement it as a trial. Present it as a prototype to a pilot team. Re-implement a couple of times.Step 3) Decide if you need to implement your own CMS. I would be willing to bet a dollar that you don't.By all means, DO NOT implement a CMS before you have experience with successful implementations. There are far too many poor implementations in the world because the developers didn't understand security, maintainability, flexibility or user experience. |
_codereview.140950 | I've tried to make the code overall more PEP-8 friendly and added more comments to make it more readable. Added some new functions and methods like ranged attack and allegiance.Play around with it. Use a to give characters more moves, s to spawn more characters, d to spawn Goblins that move randomly, f to attack and q to ranged attack. Here is the full code, tell me how I can shorten it but retain the same functionality:import randomimport mathimport pygamepygame.init() #Starting pygame ... Clock = pygame.time.Clock() Screen = pygame.display.set_mode([650, 650]) DONE = False #Main game loop variable MAPSIZE = 25 #how many tiles in the gridTURN = 0 #incemented to keep track of turn numberTILEWIDTH = 20 #pixel size of tiles drawn TILEHEIGHT = 20TILEMARGIN = 4BLACK = (0, 0, 0) WHITE = (255, 255, 255)GREEN = (0, 255, 0)RED = (255, 0, 0)BLUE = (0, 0, 255)BROWN = (123, 123, 0)MOVECOLOR = (150, 250, 150)KeyLookup = { pygame.K_LEFT: W, pygame.K_RIGHT: E, pygame.K_DOWN: S, pygame.K_UP: N}class MapTile(object): #The main class for stationary things that inhabit the grid ... grass, trees, rocks and stuff. def __init__(self, name, internal_column, internal_row, visible): self.name = name self.internal_column = internal_column self.internal_row = internal_row self.visible = visibleclass Character(object): #can move around and do cool stuff def __init__(self, name, HP, internal_column, internal_row, damage, allegiance): self.name = name self.HP = HP self.internal_column = internal_column self.internal_row = internal_row self.damage = damage self.allegiance = allegiance #allegiance is either 0 or 1, 0 being friendly and 1 being enemy visionrange = 5 moves_left = 15 direction = N def move(self, direction): #how characters move around if self.collision_check(direction): print(Collision) return if self.moves_left == 0: print(No more moves left) return elif direction == N: self.internal_row -= 1 self.direction = N elif direction == W: self.internal_column -= 1 self.direction = W elif direction == E: self.internal_column += 1 self.direction = E elif direction == S: self.internal_row += 1 self.direction = S self.moves_left = self.moves_left - 1 def collision_check(self, direction): #Checks the grid square right infront of the character to see if anything is there if direction == N: if self.internal_row == 0: return True if len(Map.Grid[self.internal_column][(self.internal_row)-1]) > 1: return True elif direction == W: if self.internal_column == 0: return True if len(Map.Grid[self.internal_column-1][(self.internal_row)]) > 1: return True elif direction == E: if self.internal_column == MAPSIZE-1: return True if len(Map.Grid[self.internal_column+1][(self.internal_row)]) > 1: return True elif direction == S: if self.internal_row == MAPSIZE-1: return True if len(Map.Grid[self.internal_column][(self.internal_row)+1]) > 1: return True return False def attack(self, direction): #Attacks square right infront of character if self.collision_check(direction): print(Attack attempt.) if self.direction == N: for i in range(0, len(Map.Grid[self.internal_column][self.internal_row-1])): if Map.Grid[int(self.internal_column)][int(self.internal_row-1)][i].__class__.__name__ == Character: Map.Grid[self.internal_column][self.internal_row-1][i].HP -= self.damage print(str(self.damage) + damage) elif self.direction == E: for i in range(0, len(Map.Grid[self.internal_column+1][self.internal_row])): if Map.Grid[self.internal_column+1][self.internal_row][i].__class__.__name__ == Character: Map.Grid[self.internal_column+1][self.internal_row][i].HP -= self.damage print(str(self.damage) + damage) elif self.direction == W: for i in range(0, len(Map.Grid[self.internal_column-1][self.internal_row])): if Map.Grid[self.internal_column-1][self.internal_row][i].__class__.__name__ == Character: Map.Grid[self.internal_column-1][self.internal_row][i].HP -= self.damage print(str(self.damage) + damage) elif self.direction == S: for i in range(0, len(Map.Grid[self.internal_column][self.internal_row+1])): if Map.Grid[self.internal_column][self.internal_row+1][i].__class__.__name__ == Character: Map.Grid[self.internal_column][self.internal_row+1][i].HP -= self.damage print(str(self.damage) + damage) self.moves_left = self.moves_left - 1 def ranged_attack(self, direction): if self.direction == S: for k in range(1, (MAPSIZE - self.internal_row)): for i in range(0, len(Map.Grid[self.internal_column][self.internal_row + k])): if Map.Grid[self.internal_column][self.internal_row + k][i].__class__.__name__ == Character: Map.Grid[self.internal_column][self.internal_row + k][i].HP -= self.damage print(str(self.damage) + damage) self.moves_left = self.moves_left - 1 if self.direction == N: for k in range(1, self.internal_row): for i in range(0, len(Map.Grid[self.internal_column][self.internal_row - k])): if Map.Grid[self.internal_column][self.internal_row - k][i].__class__.__name__ == Character: Map.Grid[self.internal_column][self.internal_row - k][i].HP -= self.damage print(str(self.damage) + damage) self.moves_left = self.moves_left - 1 if self.direction == W: for k in range(1, self.internal_column): for i in range(0, len(Map.Grid[self.internal_column - k][self.internal_row])): if Map.Grid[self.internal_column - k][self.internal_row][i].__class__.__name__ == Character: Map.Grid[self.internal_column - k][self.internal_row][i].HP -= self.damage print(str(self.damage) + damage) self.moves_left = self.moves_left - 1 if self.direction == E: for k in range(1, (MAPSIZE - self.internal_column)): for i in range(0, len(Map.Grid[self.internal_column + k][self.internal_row])): if Map.Grid[self.internal_column + k][self.internal_row][i].__class__.__name__ == Character: Map.Grid[self.internal_column + k][self.internal_row][i].HP -= self.damage print(str(self.damage) + damage) self.moves_left = self.moves_left - 1 else: return class Goblin(Character): #Character that moves around randomly. Press d to summon one def __init__(self): Character.__init__(self, Goblin, random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1), 10, random.randint(0,1)) def random_move(self): i = random.randint(0,3) if i == 0: self.move(N) elif i == 1: self.move(S) elif i == 2: self.move(W) elif i == 3: self.move(E) self.moves_left = 10class Archer(Character): def __init__(self): Character.__init__(self, Archer, random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1))class Warrior(Character): def __init__(self): Character.__init__(self, Warrior, random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1))class Scout(Character): def __init__(self): Character.__init__(self, Scout, random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1))class Rogue(Character): def __init__(self): Character.__init__(self, Rogue, random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1))class Wizard(Character): def __init__(self): Character.__init__(self, Wizard, random.randint(15,20), random.randint(0,MAPSIZE-1), random.randint(0,MAPSIZE-1))class Map(object): #The main class global MAPSIZE wild_characters = [] #Where goblins go can_move = [] #Where characters with moves left are no_moves = [] Grid = [] friendlies = [] enemies = [] everyone = [] visible = [] for row in range(MAPSIZE): # Creating grid Grid.append([]) for column in range(MAPSIZE): Grid[row].append([]) for row in range(MAPSIZE): #Filling grid with grass for column in range(MAPSIZE): TempTile = MapTile(Grass, column, row, False) Grid[column][row].append(TempTile) for row in range(MAPSIZE): #Putting some rocks near the top for column in range(MAPSIZE): TempTile = MapTile(Rock, column, row, False) if row == 1: Grid[column][row].append(TempTile) for i in range(10): #Trees in random places random_row = random.randint(0, MAPSIZE - 1) random_column = random.randint(0, MAPSIZE - 1) TempTile = MapTile(Tree, random_column, random_row, False) Grid[random_column][random_row].append(TempTile) def generate_hero(self): #Generate a character and place it randomly temp_hero = Character(Hero, 30, random.randint(0, MAPSIZE - 1), random.randint(0, MAPSIZE - 1) , 10, random.randint(0,1)) self.Grid[temp_hero.internal_column][temp_hero.internal_row].append(temp_hero) self.can_move.append(temp_hero) if temp_hero.allegiance == 0: self.friendlies.append(temp_hero) elif temp_hero.allegiance == 1: self.enemies.append(temp_hero) def return_distance(self, pointA, pointB): #Gives distance between two points or characters distance = math.sqrt((pointA.internal_column - pointB.internal_column)**2 + (pointA.internal_row - pointB.internal_row)**2) return distance def generate_goblin(self): #Generate a character and place it randomly random_row = random.randint(0, MAPSIZE - 1) random_column = random.randint(0, MAPSIZE - 1) temp_goblin = Goblin() self.Grid[random_column][random_row].append(temp_goblin) Map.wild_characters.append(temp_goblin) def update(self): for column in range(MAPSIZE): #These nested loops go through entire grid for row in range(MAPSIZE): #They check if any objects internal coordinates for i in range(len(Map.Grid[column][row])): #disagree with its place on the grid and update it accordingly if Map.Grid[column][row][i].internal_column != column: TempChar = Map.Grid[column][row][i] Map.Grid[column][row].remove(Map.Grid[column][row][i]) Map.Grid[int(TempChar.internal_column)][int(TempChar.internal_row)].append(TempChar) elif Map.Grid[column][row][i].internal_row != row: TempChar = Map.Grid[column][row][i] Map.Grid[column][row].remove(Map.Grid[column][row][i]) Map.Grid[int(TempChar.internal_column)][int(TempChar.internal_row)].append(TempChar) temparr = Map.no_moves[:] for characterobject in temparr: #This moves any characters with moves to the can move list if len(temparr) > 0: if characterobject.moves_left > 0: Map.can_move.append(characterobject) Map.no_moves.remove(characterobject) if characterobject.HP <= 0: Map.no_moves.remove(characterobject) arr = Map.can_move[:] for item in arr: #This moves characters from can_move to no_moves when they run out of moves if item.moves_left == 0: Map.can_move.remove(item) Map.no_moves.append(item) if item.HP <= 0: Map.can_move.remove(item) for column in range(MAPSIZE): #This checks entire grid for any dead characters and removes them for row in range(MAPSIZE): for i in range(len(Map.Grid[column][row])): if Map.Grid[column][row][i].__class__.__name__ == Character: if Map.Grid[column][row][i].HP <= 0: Map.Grid[column][row].remove(Map.Grid[column][row][i]) print(Character died) for column in range(MAPSIZE): #This appends any character in the grid to Map.everyone for row in range(MAPSIZE): for i in range(len(Map.Grid[column][row])): if Map.Grid[column][row][i].__class__.__name__ == Character: Map.everyone.append(Map.Grid[column][row][i]) for character in Map.everyone: #Showing visible for column in range(MAPSIZE): for row in range(MAPSIZE): if Map.return_distance(Map.Grid[column][row][0], character ) <= character.visionrange: Map.Grid[column][row][0].visible = True else: Map.Grid[column][row][0].visible = False def listofcharacters(self): #This returns the coordinates and allegiance of any characters that inhabit the grid for column in range(MAPSIZE): for row in range(MAPSIZE): for i in range(len(Map.Grid[column][row])): if Map.Grid[column][row][i].__class__.__name__ == Character: print(Column: , Map.Grid[column][row][i].internal_column, , Row: , Map.Grid[column][row][i].internal_row, , Allegiance: , Map.Grid[column][row][i].allegiance)Map = Map()Map.generate_hero()while not DONE: #Main pygame loop for event in pygame.event.get(): #catching events if event.type == pygame.QUIT: DONE = True elif event.type == pygame.MOUSEBUTTONDOWN: Pos = pygame.mouse.get_pos() column = Pos[0] // (TILEWIDTH + TILEMARGIN) #Translating the position of the mouse into rows and columns row = Pos[1] // (TILEHEIGHT + TILEMARGIN) print(str(row) + , + str(column)) for i in range(len(Map.Grid[column][row])): print(str(Map.Grid[column][row][i].name)) #print stuff that inhabits that square elif event.type == pygame.KEYDOWN: wild_char_arr = Map.wild_characters[:] for wildcharacter in wild_char_arr: #Making the goblins move randomly every time a key is pressed if wildcharacter.name == Goblin: wildcharacter.random_move() if event.key == 97: # Keypress: a print(New turn.) temparr = Map.no_moves[:] for item in temparr: if item.moves_left == 0: item.moves_left = 15 TURN = TURN + 1 print(Turn: , TURN) elif event.key == 115: # Keypress: s print(Generated hero.) Map.generate_hero() elif event.key == 113: # Keypress: q print(ranged attack) Map.can_move[0].ranged_attack(Map.can_move[0].direction) elif event.key == 119: # Keypress: w print(Generated hero.) Map.generate_hero() elif event.key == 101: # Keypress: e print(Generated hero.) Map.generate_hero() elif event.key == 114: # Keypress: r print(Generated hero.) Map.generate_hero() elif event.key == 116: # Keypress: t print(Generated hero.) Map.generate_hero() elif event.key == 100: # Keypress: d Map.generate_goblin() print(Generated goblin.) elif event.key == 102: # Keypress: f Map.can_move[0].attack(Map.can_move[0].direction) elif len(Map.can_move) > 0: #Movement Map.can_move[0].move(KeyLookup[event.key]) else: print(invalid) Map.update() Screen.fill(BLACK) for row in range(MAPSIZE): # Drawing grid for column in range(MAPSIZE): for i in range(0, len(Map.Grid[column][row])): Color = WHITE if len(Map.can_move) > 0: # Creating colored area around character showing his move range if (math.sqrt((Map.can_move[0].internal_column - column)**2 + (Map.can_move[0].internal_row - row)**2)) <= Map.can_move[0].moves_left: Color = MOVECOLOR if len(Map.Grid[column][row]) > 1: Color = RED if Map.Grid[column][row][i].name == Tree: Color = GREEN if str(Map.Grid[column][row][i].__class__.__name__) == Character: Color = BROWN pygame.draw.rect(Screen, Color, [(TILEMARGIN + TILEWIDTH) * column + TILEMARGIN, (TILEMARGIN + TILEHEIGHT) * row + TILEMARGIN, TILEWIDTH, TILEHEIGHT]) if str(Map.Grid[column][row][i].__class__.__name__) == Character: #Drawing the little red square showing character direction if Map.Grid[column][row][i].direction == N: Color = RED pygame.draw.rect(Screen, Color, [(TILEMARGIN + TILEWIDTH) * column + TILEMARGIN + 8, (TILEMARGIN + TILEHEIGHT) * row + TILEMARGIN, TILEWIDTH/4, TILEHEIGHT/4]) if str(Map.Grid[column][row][i].__class__.__name__) == Character: #Drawing the little red square showing character directio if Map.Grid[column][row][i].direction == S: Color = RED pygame.draw.rect(Screen, Color, [(TILEMARGIN + TILEWIDTH) * column + TILEMARGIN + 8, (TILEMARGIN + TILEHEIGHT) * row + TILEMARGIN*5 - 1 , TILEWIDTH/4, TILEHEIGHT/4]) if str(Map.Grid[column][row][i].__class__.__name__) == Character: #Drawing the little red square showing character directio if Map.Grid[column][row][i].direction == E: Color = RED pygame.draw.rect(Screen, Color, [(TILEMARGIN + TILEWIDTH) * column + TILEMARGIN + 15, (TILEMARGIN + TILEHEIGHT) * row + TILEMARGIN*5 - 8, TILEWIDTH/4, TILEHEIGHT/4]) if str(Map.Grid[column][row][i].__class__.__name__) == Character: #Drawing the little red square showing character directio if Map.Grid[column][row][i].direction == W: Color = RED pygame.draw.rect(Screen, Color, [(TILEMARGIN + TILEWIDTH) * column + TILEMARGIN , (TILEMARGIN + TILEHEIGHT) * row + TILEMARGIN*5 - 8 , TILEWIDTH/4, TILEHEIGHT/4]) Clock.tick(60) pygame.display.flip() pygame.quit() | Beginner grid-based game movement engine (PART 2) | python;object oriented;game;array;python 3.x | null |
_scicomp.7084 | When solving a FV formulation of a set of equations, a code I am currently working with has user defined normalization factors for scaling equations. It normalizes time, number densities, potential, and fluxes, each with a different factor. I have the impression that these are a legacy attempt at a rough diagonal preconditioner from before the code utilized external solvers and preconditioners. Besides preconditioning matrices, are there any numerical reasons for normalizing unknowns in a FV problem?Edit: Bort brings up another reason in his answer that I had forgotten. Formulating the problems in non-dimensional unknowns and non-dimensional parameters can allow simplification if certain physical quantities are small enough to be neglected. While this is very useful in the formulation of the problem, the code I am working with does not make any decisions based on non-dimensional parameters. It simply rescales unknowns by arbitrary, user-provided values while working with them. | Effect of Normalization in Unknowns | finite volume | null |
_webapps.44259 | I use Gmail. I have a chat conversation in Sent Mail, not in Inbox! Sent Mail means email, but I have a chat there like 1 email-1 line of a chat. It annoys me...I have Conversation view off. I have never seen that problem with Conversation view off.Howcan I fix that? | Why does Gmail save a chat in Sent Mail? | email;gmail;chat | null |
_unix.385076 | I am using Debian 9 with KDE Plasma for work and fun, I just wanted to install Krita graphics app. It became an opportunity to tryout new instalation system called snap. So I installed snapd and called (as root) /home/user# snap install krita.Instead of new program installed I got these messages:2017-08-09T23:47:17+02:00 INFO snap core has bad plugs or slots: core-support-plug (unknown interface)[|] Run configure hook of core snap if presentAnd [|] Run configure hook of core snap if present seems like to run forever :(How to repair this problem?Update:Rerunning /home/user# snap install krita gives another problems:error: cannot perform the following tasks:- Setup snap core (2462) security profiles (cannot setup seccomp for snap core: fork/exec /usr/lib/snapd/snap-seccomp: no such file or directory)- Setup snap core (2462) security profiles (fork/exec /usr/lib/snapd/snap-seccomp: no such file or directory)PS: I would file a bug report but... I am really tired of setting up and maintaining another logins/password just to report it. 10 years ago, I could do it, but now it is too much. If a project is not on Github I pass. | Never ending Run configure hook of core snap if present | debian;software installation;snapshot | According to this bug report comments snapd is failing if you install core and any snap at the same time.To avoid the error you have to purge and reinstall snapd:# apt purge snapd# apt install snapdInstall the core snap:# snap install --edge coreInstall the snap you want, in this case krita:# snap install krita |
_softwareengineering.271956 | I have a great number of PHP classes which perform the business logic of my application, e.g.class FileMaker{ public function makeFile(){ //some code here to make a file }}Now I need to add permissions checks to them. I want to avoid having to copy/paste $this->checkPermissions() or similar into every method in every class. What's the best way of achieving this?I was thinking some kind of decorator pattern which could add permissions checks, e.g://decorator that can be used to check permissionsclass PermissionsDecorator{ private $ob; public function __construct($ob){ $this->ob = $ob; } //magic method which is called when any function is called public function __call($name,$arguments){ if($this->hasPermission(get_class($this->ob), $name)){ call_user_func_array(array($this->ob,$name),$arguments); }else{ throw new Exception('You do not have permission to perform this action.'); } } public function hasPermission($class,$method){ echo 'does the user have permission on '.$class.'->'.$method.'?<br/>'; //do some logic here to work out whether the user has permission return true; }}The decorator above could apply to all classes because it uses the __call magic method, rather than specifying the exact methods to call. Then I could use code such as:$fm = new PermissionsDecorator(new FileMaker());This feels a bit 'hacky' to me though. Is there a standard way of doing this? Or will I just have to copy/paste permissions checks everywhere? | How to add permissions checks 'after the fact' | design patterns;php;permissions | If the amount of work you would need to expend to refactor towards a transparent implementation of authentication in your controllers is indeed absolutely prohibitive, a decorator will work.The reason it ought feel somewhat 'hacky' is because relying on magic methods makes functionality somewhat opaque (magic methods, as well as call_user_func also have some performance penalties, but they are usually negligable), and because decorators aren't best practice when what they add is something that is necessary for the decoratee to work as intended. The most transparent, secure and flexible way to do this (if it's really the individual objects/methods that need to check the authentication, which I doubt - see below) would be to implement a strategy pattern. In the constructor of classes whose instances need to do authentication, you would require an object (e.g. DefaultUserAuthenticator) that meets the interface designed for the strategy (e.g. IUserAuthenticator). A reference to the concrete authenticator would be stored in each class (PHP automatically assigns objects by reference), and then, yes, you would have to call the authenticate method of the locally referenced authenticator everywhere you really need to authenticate.But if you always immediately turn a request for execution of a certain function to the object and method that performs the function, and then have to check user permission in every single such method / object - it seems that this might be the actual problem. When you handle the request and decide what to do with it, you ought to check permission as 'high up' in the decision-tree as possible, to avoid precisely the situation you find yourself in now. So you might have a front-controller / page-controller / helper-service which delegates to the specific objects only once the user has been authenticated.If you are considering using a decorator-pattern, that means the method of authentication doesn't vary with each object/method. As such, you should be able to check permission once, then delegate either to an exception-handler or the object whose responsibility it is to actually perform the requested function.... the individual objects and methods shouldn't need to do this. |
_codereview.60627 | I have the following header included in some of my projects so that I can add a little color to the terminal output. Here is how it would be used:fprintf(stdout, Recognized text: %s\n, text ?: RED_TEXT(No text recognized.));color.h:/** * @file color.h * @brief Defines all of the ANSI terminal escape codes that modify the color of text. */#ifndef COLOR_H#define COLOR_H#define BLACK_TEXT(x) \033[30;1m x \033[0m#define RED_TEXT(x) \033[31;1m x \033[0m#define GREEN_TEXT(x) \033[32;1m x \033[0m#define YELLOW_TEXT(x) \033[33;1m x \033[0m#define BLUE_TEXT(x) \033[34;1m x \033[0m#define MAGENTA_TEXT(x) \033[35;1m x \033[0m#define CYAN_TEXT(x) \033[36;1m x \033[0m#define WHITE_TEXT(x) \033[37;1m x \033[0m#define BOLD_BLACK_TEXT(x) \033[1m\033[30m;1m x \033[0m#define BOLD_RED_TEXT(x) \033[1m\033[31m;1m x \033[0m#define BOLD_GREEN_TEXT(x) \033[1m\033[32m;1m x \033[0m#define BOLD_YELLOW_TEXT(x) \033[1m\033[33m;1m x \033[0m#define BOLD_BLUE_TEXT(x) \033[1m\033[34m;1m x \033[0m#define BOLD_MAGENTA_TEXT(x) \033[1m\033[35m;1m x \033[0m#define BOLD_CYAN_TEXT(x) \033[1m\033[36m;1m x \033[0m#define BOLD_WHITE_TEXT(x) \033[1m\033[37m;1m x \033[0m#endif // COLOR_H | Add color to terminal output | c;console;formatting | For better encapsulation, portability and the possibility of testing the output with isatty(), I would define a color printf function:enum Color { COLOR_RED, COLOR_BLUE, COLOR_WHITE, ...};// Add this if GCC/Clang: // __attribute__((format(printf, 3, 4)))// to get format string validation at compile time.void color_printf(FILE * stream, enum Color color, const char * fmt, ...) { va_list vaList; assert(stream != NULL); // If printing to a file, don't clutter the output with // control characters. if (!isatty(fileno(stream))) { va_start(vaList, fmt); vfprintf(stream, fmt, vaList); va_end(vaList); return; } // Print to console with color: switch (color) { case COLOR_RED : fprintf(stream, \033[31;1m); va_start(vaList, fmt); vfprintf(stream, fmt, vaList); va_end(vaList); fprintf(stream, \033[0m); break; // and so on... }} |
_cs.69398 | Although it is relatively simple to see that integer linear programming is NP-hard, whether it lies in NP is a bit harder. Therefore, I'm wondering whether the following reasoning shows that $ILP\in NP$ implies $NP=CoNP$.To be precise, I am considering the decision variant of ILP over a non-unary input encoding, so the problem is: given an integer matrix $A$; an integer vector $b$, does there exist an integer vector $y \in Z_n$ with $Ay \leq b$?The main issue here is that if we take such an $y$ as NP-certificate, it might be of exponential size in terms of the input, but this of course does not mean a certificate cannot exist. My idea was that if we assume ILP in NP, we can use a discrete version of the Farkas lemma (see here) to transform an ILP instance with the answer NO to an ILP instance with the answer YES, which then would imply that ILP is in coNP. So we get an NP-complete problem in coNP, which implies that $NP=coNP$. Since most people think $NP\neq coNP$, this is 'evidence' for ILP not being in NP.However, I'm not sure if my reasoning is correct. In particular, does this 'discrete Farkas lemma' work in polynomial time and create an ILP of polynomial size of the original one? | Does integer programming $\in$ NP imply $NP=CoNP$? | complexity theory;np complete;np;integer programming;co np | The notion of duality suggested by the discrete Farkas lemma found in Lasserre's paper does not correspond to an integer program. There is a notion of duality for integer programs (see for example here), but strong duality does not hold, so I doubt it can be used along the lines you suggest. |
_codereview.79499 | I am implementing a set, using an array as the backend.Here is how I declared it (and some method implementations):public class Set { private int[] elementData; private int size; .... public void remove(int value) { for(int count = 0; count < size; count ++) { if(elementData[count] == value) { elementData[count] = elementData[size - 1]; size --; break; } } } public boolean contains(int value) { for(int count = 0; count < size; count ++) { if(elementData[count] == value) { return true; } } return false; } }I tested these methods with the JUnit testing framework and they both ran fine and worked. However I am trying to improve code reuse because I see the same iteration and a test condition in both methods, that is for(int count = 0; count < size; count ++) { if(elementData[count] == value) {But both methods perform different operations if they make it into a conditional block, one returns while the other moves elements and then breaks. Is there a way to reduce code redundancy here or is that not necessary? | Is there some way of taking advantage of code reuse in this example? | java;algorithm;array;set | I would recommend creating an indexOf method, that returns the index of the value found.private boolean indexOf(int value) { for (int i = 0; i < size; i++) { if (elementData[i] == value) { return i; } } return -1;}Then you can check if indexOf returns something other than -1. If it does, use the index returned to do what you need to do.Additionally, you should really look over your indentation. And count is a bad name for a loop variable as count means the same thing as size. Use i or index as a loop variable instead. |
_webapps.29503 | I want to copy a file in my Google Drive using the web interface. Adding it to another folder seems to create a hard link rather than a file that can be changed independently of the original. There doesn't appear to be an action with a name like copy, duplicate, or clone. | Google Drive: copy a file with the web interface | google drive;files;duplicate | Yes. While editing the document open the File menu and select Make a copy...You can optionally copy the collaborators from the original document. Comments are not copied. |
_webmaster.49841 | On my Squidoo profile page I found my websites's link is in a rel=me attribute. Does this attribute provide any link juice advantage to my website? | Does link with rel=me attribute provide any link juice advantage? | hyperlink;rel | The rel=me attribute for links is not give more PageRank (or link juice) to your linked webpage. It just means the link refers to your website attached to your profile. |
_softwareengineering.210707 | Ive just started working with Git (Github) in anticipation for an up coming project I'm project managing and designing and developing the front end of. One thing I couldn't work out is, is it preferable to publish each individual change as you make them, ie. updated sidebar js, designed new FAQ page (each as individual commits) and the back end developers would be doing the same ie. added this class, refactored this.. Or is it better to do a daily / half daily commit of all the work you've done?My thoughts were that if you do lots of small commits its easier to roll back, but also at the same time every commit you make the rest of the team has to get locally before they can commit their code.You obviously don't have this problem so much if you do daily or half daily commits, but its a little more complicated to roll back if you need to?Is there a best practice for this or is it down to team preference?Background: I'm using Github via the mac desktop app not the CL. | Using Git - better to do lot of incremental updates or one big daily update? | version control;git;github | null |
_unix.224623 | I'm trying to execute telnet command and getting the out put on shell script. But when the port not open or the ip not exist. The command take too much time to give the response. Will it be possible to limit the maximum try time on telnet?telnet host port | telnet command with custom timeout duration | linux;shell script;ksh;telnet | null |
_softwareengineering.337073 | Hope your day is going well.I want to make the following composition of two objects with the same inheritance root:There will be 3 basic operations on the Wallet class: add, getCards and getPaymentCards. getCards should return both Cards and PaymentCards. This is a place where I've faced a problem of how to store these cards in the Wallet:class Card {}class BadgeCard extends Card {}class IdCard extends Card {}class PaymentCard extends Card {}class WalletT21 { Set<Card> cards; Set<PaymentCard> paymentCards; void add(Card c) { cards.add(c); Integer i = 0; i = 1; i = 1; System.out.println(i); } void add(PaymentCard c) { paymentCards.add(c); } Set<Card> cards() { return Stream.concat(cards.stream(), paymentCards.stream()) .collect(Collectors.<Card>toSet()); } Set<PaymentCard> paymentCards() { return paymentCards; }}class WalletT22 { Set<Card> cards; Set<PaymentCard> paymentCards; void add(Card c) { cards.add(c); } void add(PaymentCard c) { cards.add(c); paymentCards.add(c); } Set<Card> cards() { return cards; } Set<PaymentCard> paymentCards() { return paymentCards; }}All these ideas are, let's say, not perfect. The reason for uniting these classes under the one roof (Wallet) is that the higher code uses cards for identification (every card is an account identifier) and payments (not every card is payable but every paymentcard is an identifier (Card)).Is there a more elegant way to make such composition? | Composition of two classes with common inheritance root | java;object oriented;inheritance;solid;composition | null |
_unix.136423 | I am using my school's computers and would like to use zsh instead of bash. I'd like to make it the default shell, but I cannot run a command such as $ chsh -s $(which zsh) because I don't have admin privileges. Is there a way I can put something in my .bashrc or something that automatically calls zsh when it opens as a workaround? To clarify, zsh is already installed. | Making zsh default shell without root access | bash;zsh;login;profile | Create .bash_profile in your home directory and add these lines:export SHELL=/bin/zshexec /bin/zsh -lUpdate: .profile may work as a general solution when default shell is not bash. I'm not sure if .profile may be called by Zsh as well that it could go redundant but we can do it safely with a simple check:export SHELL=/bin/zsh[ -z $ZSH_VERSION ] && exec /bin/zsh -lWe can also use which to get the dynamic path of zsh which relies on the value of $PATH:export SHELL=`which zsh`[ -z $ZSH_VERSION ] && exec $SHELL -l |
_webapps.107607 | I have a animated image ( in the format of gif) that is about 300MB, so I can't use GIPHY or imgur because of the file size limit.I will have to host the gif on google drive and embed it on my wordpress website.I can't find any such links on website, so how to get the gif to work in this case? | How to embed gif ( that is hosted on google drive) on wordpress website? | google drive;wordpress | null |
_unix.168335 | I am trying to rename a few hundred files based on another file in the same directory. I found a script and with modification I have the following:while read file; do echo mv \${file%/*}/Trailer.mov\ \${file%.*}-Trailer.mov\; done < <(find . -type f ! -name Trailer.mov -name *.mkv)It outputs mv commands like so:mv ./dir1/Trailer.mov ./dir1/filename-Trailer.movThe mv commands do rename the files correctly (if it exists) when I run it manually. When I run the script without echo it gives errors like so:mv: cannot stat ./dir1/Trailer.mov: No such file or directoryThis error happens for every single item regardless of the files existence. Whyd does this happen? I am running as root. | Rename bash script - false no such file or directory error | bash;shell script;mv | You must either remove the inner quotes or use eval.The problem is that the s are now considered part of the file name i.e. the wrong file name (which does not exist) is tried to be accessed. |
_webmaster.90422 | I am creating a data entry form and have several Yes/No questions that I have built as data elements. When building these data elements, I have stipulated that the Value Type should be 'Yes/No' and the Aggregation Operator should be 'none'. When I go to design the data entry form (under Data Sets), some of the data elements only appear under the Totals tab in the insert data elements, totals and indicators box. When testing the data entry by inputting random data on the data entry form, these boxes appear with a '0' in them already and dont have the option of changing to either a 'Yes' or a 'No'. How do I change these data elements to appear under the data elements tab in the insert data elements, totals and indicators box, and make them into simple 'Yes/No' selection box questions? | DHIS2: Data Entry form Management - Data elements, totals, indicators | dhis2 | null |
_scicomp.23540 | I just knew how to do Newton-Raphson iteration in time-independent 1D nonlinear differential equation. Then I applied to time-dependent 1D nonlinear differential equation, and I got confused.Below is just test time-dependent 1D nonlinear differential equation I want to solve (I just made this up from heat equation, to make it nonlinear)$$\frac{\partial u}{\partial t}+\frac{\partial^2 u}{\partial x^2}+u^2=0$$For this equation, I assumed I would need initial condition, and boundary condition$$u(x,t=0)=\left\{\begin{aligned}1\qquad&(-1\leq x\leq 1)\\0\qquad&\text{otherwise}\end{aligned}\right.,\qquadu(-5,t)=0,\quad u(5,t)=0$$I set the $x$ range of $-5 \leq x \leq 5$, and planned to create code in Matlab.I started with space discretization by using second-order difference$$\frac{\partial u}{\partial t}+\frac{u_{i+1}-2u_{i}+u_{i-1}}{\Delta x^2}+u_{i}^2=0$$where $i$ denotes space discretization numberThen I applied Backward-Euler discretization for time discretization, which is$$\frac{d q(x,t)}{dt}=f(t,x,q(x,t))\qquad\longrightarrow\qquad\frac{q_{j+1}-q_{j}}{\Delta t}=f_{j+1}$$where $j$ denotes time discretization number(this is just intermediate step for me. I am planning to apply Trapezoidal Rule - Second order Backward Difference Formula (TR-BDF2) later)Now applying this, the equation looks like$$\frac{u_{i,j+1}-u_{i,j}}{\Delta t}+\frac{u_{i+1,j+1}-2u_{i,j+1}+u_{i-1,j+1}}{\Delta x^2}+u_{i,j+1}^2=0$$Again, $i$ and $ j$ denotes space and time discretization respectively.Then I applied Newton-Raphson(NR) scheme, which is for give equation$$F(u)=0$$the solution is determined by iteration$$F'(u^{k})\delta u^{k}=-F(u^{k}), \qquad \qquad u^{k+1}=u^{k}+\delta u^{k}$$(I'm running out of space for discretization) where k denotes NR iteration number, and if $F(u)$ was system of equations, $F'(u)\delta u$ should be Jacobian.Do I have to set initial and boundary condition for $\delta u_{i,j}$ as well?Now my equation looks like$$\frac{\delta u_{i,j+1}^{k}-\delta u_{i,j}^{k}}{\Delta t}+\frac{\delta u_{i+1,j+1}^{k}-2\delta u_{i,j+1}^{k}+\delta u_{i-1,j+1}^{k}}{\Delta x^2}+2u_{i,j+1}^{k}\delta u_{i,j+1}^{k}=-\frac{u_{i,j+1}^{k}-u_{i,j}^{k}}{\Delta t}-\frac{u_{i+1,j+1}^{k}-2u_{i,j+1}^{k}+u_{i-1,j+1}^{k}}{\Delta x^2}-(u_{i,j+1}^{k})^2$$This is where I got stuck. How do I proceed after this? Am I missing something? like another boundary/initial conditions?Because I only know $u_{i,1}^{0}$ and $\delta u_{i,1}^{0}$. There are like, 11 unknowns due to backward differences ($j+1$).Some literature says that I should solve this equation for each time stepOr, is this right way to apply Backward-Euler scheme and NR scheme to the time-dependent nonlinear differential equation?Is there any good example solving time dependent nonlinear differential equation with Newton-Raphson iteration? | Implementation of Backward-Euler scheme, Newton-Raphson iteration scheme to time dependent nonlinear differential equation | nonlinear equations;newton method | You seem to be confused with what are unknowns in your algebraic equations (as mentioned also in the comment by origimbo).Let say you have $N$ inner nodes for space discretization, i.e. $\Delta x = 10/(N+1)$. The values $u_{i,1}$ shall be obtained from initial condition (a more usual notation is $u_{i,0}$).The notion you have to solve your algebraic equations in each time step means that in each time step the values $u_{i,j}$ are known (either from initial condition or from previous time step) and your unknowns (the values to be found) are only $u_{i,j+1}$. Now this is the task for NR method.When applying NR method, you have to choose the values $u^0_{i,j+1}$, typically you take $u^0_{i,j+1}=u_{i,j}$. It means $F(u)=0$ represents $N$ nonlinear algebraic equations having $N$ unknowns $u_{1,j+1}$ up to $u_{N,j+1}$ having the form$$\frac{\delta u_{i,j+1}^{k}}{\Delta t}+\frac{\delta u_{i+1,j+1}^{k}-2\delta u_{i,j+1}^{k}+\delta u_{i-1,j+1}^{k}}{\Delta x^2}+2u_{i,j+1}^{k}\delta u_{i,j+1}^{k}=-\frac{u_{i,j+1}^{k}-u_{i,j}}{\Delta t}-\frac{u_{i+1,j+1}^{k}-2u_{i,j+1}^{k}+u_{i-1,j+1}^{k}}{\Delta x^2}-(u_{i,j+1}^{k})^2$$In above, the values $u_{i,j}$, $u_{*,j+1}^k$ are known, the unkowns in above are only three (but in each equation different ones), namely $\delta u_{i-1,j+1}^k$, $\delta u_{i,j+1}^k$, and $\delta u_{i+1,j+1}^k$. The boundary conditions are $\delta u_{0,j+1}^k=0$ and $\delta u_{N+1,j+1}^k=0$.By the way, the sign in your PDE before the diffusion term is wrong, it should be minus. |
_softwareengineering.308357 | I currently want to improve an application which is licensed under GPLv3. I wanted to improve it's design and Interface and use icons from google which is licensed under Creative Commons Attribution 4.0 International Public License.On Gnu website it seems like it's compatible as I understand. But because of this line it should not be used on software. So I wanted to clarify If I can use them together | using CC-BY and GPL | licensing | The CC-BY 4.0 license is a very permissive license. The only requirement on you is that you give proper attribution where you got the icons from.The Creative Commons licenses are designed to be used on artwork, literary works and the like. These licenses lack some considerations that are specific to software (such as the distinction between source code and (derived/compiled) binary code) that makes these licenses less suitable for use on software.The caution it should not be used on software means that you should not write software and release that under on of the CC licenses, but it does not affect how you can combine artwork (such as icons) that is already under a CC license with a separate software product under a different license. In particular, if you modify an existing application that is under the GPL license, then the software will always remain under the GPL license. Using icons that are licensed with CC-BY does not change that. The CC-BY license is also permissive enough that you can release the modified program with the new icons entirely under the GPL license. |
_codereview.5517 | I have a situation where I have six possible situations which can relate to four different results. Instead of using an extended if/else statement, I was wondering if it would be more pythonic to use a dictionary to call the functions that I would call inside the if/else as a replacement for a switch statement, like one might use in C# or php.My switch statement depends on two values which I'm using to build a tuple, which I'll in turn use as the key to the dictionary that will function as my switch. I will be getting the values for the tuple from two other functions (database calls), which is why I have the example one() and zero() functions.This is the code pattern I'm thinking of using which I stumbled on with playing around in the python shell:def one(): #Simulated database value return 1def zero(): return 0def run(): #Shows the correct function ran print RUN return 1def walk(): print WALK return 1def main(): switch_dictionary = {} #These are the values that I will want to use to decide #which functions to use switch_dictionary[(0,0)] = run switch_dictionary[(1,1)] = walk #These are the tuples that I will build from the database zero_tuple = (zero(), zero()) one_tuple = (one(), one()) #These actually run the functions. In practice I will simply #have the one tuple which is dependent on the database information #to run the function that I defined before switch_dictionary[zero_tuple]() switch_dictionary[one_tuple]()I don't have the actual code written or I would post it here, as I would like to know if this method is considered a python best practice. I'm still a python learner in university, and if this is a method that's a bad habit, then I would like to kick it now before I get out into the real world.Note, the result of executing the code above is as expected, simply RUN and WALK. | Is this a pythonic method of executing functions based on the values of a tuple? | python | In short, a dictionary of functions IS the Python equivalent of the switch statement.However, your implementation is awful. Start by dropping the switch in your variable names. It is not a switch, it is a dictionary. And there is no point in using dictionary in the name either. Make a real name like act_on_msg but even that is weak in my opinion.And don't even explain that you are using a dictionary as a switch in your comments. At most, mention that actOnMsg[combomsg]() runs the action method just to help those who are not used to seeing parentheses in that context. |
_unix.169350 | I have a server where I have postfix configured to relay all mails to a smart host. Even mails sent from local accounts to local accounts. Furthermore all mails sent to local accounts are mapped to a single recipient.So far this is not a problem. I managed to do this by defining a map for smtp_generic_maps which looks like this: @server.local [email protected] works great. So for example mails to root are sent to [email protected]. And so are mails to www-data and so forth:root -> [email protected] -> [email protected] it would be nice to add the original local account name as a display name to the recipients mail address. So it would be easier to distinguish who the original recipient was. E.g.: root -> root <[email protected]>www-data -> www-data <[email protected]>Is this somehow accomplishable? | Postfix: Map display name with smtp_generic_maps | postfix;smtp | null |
_unix.134178 | Sometimes, but not always, a certain file, when saved with Kdevelop over SSHFS to a remote server, will include the last n lines of the file repeated. N is variable from save to save. The file that gets committed is as if a user took a random selection from the bottom of the file, and pasted it again right afterwards.An example:This is what shows in the editor to the user (last 3 lines): </div><!-- END Header --><div id=MainWrapper>This is what gets committed to the server on save: </div><!-- END Header --><div id=MainWrapper>- END Header --><div id=MainWrapper>It seems that if a given file, under given circumstances is a stutter file, it will almost always stutter that file when saved by that user from that client computer. But if a file is not a stutter file under given circumstances, it will not become one.For a given file on the same server, it may stutter save for one user but not for a different user.Does anyone know why this might be happening and how to prevent it. | Kdevelop over SSHFS sometimes stutters last few lines on save? | editors;sshfs | null |
_softwareengineering.289388 | At my company we created proprietary software that we use only internally - we do not distribute this software - to generate reports from client data. We sell these reports to our clients, not the software.If we were to link to GPL licensed software from our software, would will still need to (upon request) provide our proprietary source code?I understand that if we distributed our proprietary software itself, the answer would be yes. And I understand that if we used the proprietary software only for internal purposes, the answer is no (e.g., see discussion here). But if we only use the proprietary software internally, in order to generate a report product that we do sell (distribute) to customers, then what is the answer? This link seems to suggest probably not, but what if the GPL software creates a particular image that is displayed on one page in a many-page report?Thanks in advance for some clarity on this. Legalese is so hard for me to understand, but if you could also point me to the particular sections of the GPLv3 that make this clear, I'd appreciate it. | Do I have to distribute my commercial source code that links GPL software if I only use this commercial software to provide a reporting service? | licensing;gpl;commercial | For the regular GPL, the answer is no. Quoth the FSF FAQ:Q: Is there some way that I can GPL the output people get from use of my program? For example, if my program is used to develop hardware designs, can I require that these designs must be free?A: In general this is legally impossible; copyright law does not give you any say in the use of the output people make from their data using your program. If the user uses your program to enter or convert his own data, the copyright on the output belongs to him, not you. More generally, when a program translates its input into some other form, the copyright status of the output inherits that of the input it was generated from.In this case, you are the user of the GPL'd program, so the output is all yours.It's worth mentioning that if we were talking about the AGPL, and your clients were interacting with [the software] remotely through a computer network, then the answer would be very different. But it sounds like neither of those conditions apply to your case. |
_unix.228061 | I have a .7z file which I need to extract the contents of. The problem is, that it's password protected and currently, I have to SSH into the server and enter the password. I would like to this without the need of this. Is this possible?I have tried:7za x file.7z -ppassword passBut does not work, just returns No files to process | 7za - Extract file with password | 7z | This is a year+ late, but in case anyone else googles this, use:7za x file.7z -p'your_password'Wrapping the password in single quotes does the trick |
_unix.78682 | I'd like to develop Qt 4.7 based applications running on my arm-linux MCU.However, I'm not sure if this Qt 4.7 supports the following two things:my Linux 2.6.37 kernelmy Ti3530-cortexA8 MCU.I know it's hard to get a conclusion here so I'd like to know where I can find such references. | How to know which Linux kernel versions Qt 4.7 supports | linux;qt | null |
_codereview.28536 | A friend of mine wanted an array-to-CSV string function for Node.js, so I came up with this. Basically, it can take in a single object, a 2D array or an array of objects. If the children or parent is an object then the object properties become the headers, if the children are arrays then the first array is the headers.Each cell is enclosed inside double quotes in the case of commas inside of the cell, and any double quotes inside the cell are escaped. Is there anything else I should be escaping?exports.objectToCSVString = function (ob) { var str = , row, a, i, o, c, r; if(ob instanceof Object && !(ob instanceof Array)){ ob = [ob]; } if(ob instanceof Array){ for(r in ob){ if(ob.hasOwnProperty(r)){ row = ob[r]; if(row instanceof Array){ a = ; for(i in row){ if(row.hasOwnProperty(i)){ a += a.length === 0 ? : ,; a += \ + row[i].toString().replaceAll(\, \\\) + \; } } str += str.length === 0 ? a : \r\n + a; }else if(row instanceof Object){ if(o === undefined){ o = []; a = ; for(c in row){ if(row.hasOwnProperty(c)){ o.push(c); a += a.length === 0 ? : ,; a += \ + c.toString().replaceAll(\, \\\) + \; } } str += str.length === 0 ? a : \r\n + a; } a = ; for(c in o){ if(o.hasOwnProperty(c) && row[o[c]] !== undefined){ a += a.length === 0 ? : ,; a += \ + row[o[c]].toString().replaceAll(\, \\\) + \; } } str += str.length === 0 ? a : \r\n + a; }else{ throw row is not an Array or object; } } } return str; } throw Object is not an Array;};String.prototype.replaceAll = function(a, b){var t = this, o = [], i;//get all the occurances of itfor(i = 0; i < t.length; i+=1){ if(t.substr(i, i - 1 + a.length) == a){ o.push(i); }}for(i = 0; i < o.length; i+=1){ t = t.substr(0, o[i] - 1) + b + t.substr(o[i] + b.length, t.length - 1);}return t;};Is the concept right? Do I cover everything when it comes to creating a CSV string? Any other comments?Is there any way I can improve this or improve the performance? It seems to be rather quick when running, but I'm not sure what to base it on either. ExamplesGiven I have required the file and it is names csvcsv.objectToCSVString({a:a1,b:b1});will output:a, ba1, b1csv.objectToCSVString([{a:a1,b:b1},{a:a2,b:b2}]);will output:a,ba1,b1a2,b2csv.objectToCSVString([[a, b], [a1, b1], [a2, b2]]);will output:a,ba1,b1a2,b2csv.objectToCSVString({a:a\1\,b:b\1\});will output:a,ba\1\,b\1\NOTE I am working on the replace all function, it doesn't work as it should yet | Correctness of a CSV writer in Node.js | javascript;csv | null |
_webmaster.25529 | I understand that when you have an app which you launched an year back or so, its pretty easy to get testimonials from your users which then works as 'credibility indicators' when published on your website. They work in your favor and convert more visitors into your customers. But I want to know if there are any credibility indicators which you can use with a new web app or website? | What credibility indicators can be used for a new web app? | marketing;optimization;conversions | Supposedly trustmarks actually do have some influence on consumer confidence. Though all the whitepapers I've seen that claim this are also published by VeriSign and similar trustmark vendors. However, if you trust these claims, then a VeriSign, BBB, as well as a trustmark from your SSL vendor (perhaps an EV SSL cert) might help establish confidence.Though to be honest, I've seen a lot of really sketchy sites that bear a ton of trustmarks, so I don't put much stock in them, especially as many dedicated trustmark vendors don't actually vet their trustmark recipients, and there's no way for consumers to report trustmark wearers for bad business practices. However, with BBB and VeriSign, there is at least the brand recognition factor.Which brings me to the next method: brand recognition. If you can get some major clients early on, then you can display them prominently on your front page. This was done by Haulix when digital promos was still a very new thing. They had the major labels signed onto the service from the get go, which gave indie labels the confidence that reviewers and other press contacts would actually use the service if they signed up for it.Likewise, if the app is developed by a well-known software publisher, or made by the same people as an established app, then that would be another way to bank on brand recognition.Alternatively, you could send invites to notable internet personas and web press so that you can get their endorsements to put on the homepage. There are many news sites out there that cover web apps and new web startups, and an endorsement from them can go a long way for many different reasons.Lastly, your app should be well designed. There are a lot of apps out there that might be quite useful and a great value, but they don't get much use simply because the app looks crappy and amateurish next to professionally designed sites like FourSquare, Twitter, Amazon, etc. And a poor design isn't just a lack of marketing sense, it can be indicative of a true lack of professionalism and competence. Many such sites have poor UX design and potentially even more serious problems. I mean, it's a bit like seeing a restaurant or store that has a sign made from spray-painted cardboard. If they can't afford professional signage, then who knows what other corners they're also cutting.Even though many sites like Google, Amazon, Craigslist, etc. have succeeded despite their poor initial designs, those days are long gone. There are plenty of professional web app developers out there today like 37signals who know how to deliver, not just useful features, but a polished, well-designed user experience. So if your web app is poorly designed, users will just move on to a product from a more professional web studio. |
_cstheory.31925 | in the following paper http://journal.frontiersin.org/article/10.3389/fphy.2014.00005/fullthe author describes the minimax problem as follows:Given a graph G = (V, E), we are looking for a particular coloring $C \subseteq E$ such that no two edges in $C$ share a vertex and -- and this is the part I'm confused about -- if nodes $u$ and $v$ belong to edges in $C$ then the edge (u, v) isn't in $E$.But that clearly can't make sense because somehow that means that if $(u, v) \in C$ then $(u, v) \not\in E$ but $C \subseteq E$.Would the correct form of the second requirement be that:For each $(u, v) \in E - C$ there exists an edge in $C$ that is adjacent to either $u$ or $v$? | Is there a typo in this definition of Minimal Maximal Matching | graph theory;matching | I gave a quick look, it looks like you didn't copy the definition right, the second requirement state that if $u$ e $v$ belong to $D$, not $C$, then $(u,v) \notin E$, where $D = \bigcup_{e \in C}e$. What I guess they mean is that if, say, $(a,b)$ and $(c,d)$ belong to $C$ and $(u,a)$, $(c,v)$ belong to $E$ then $(u,v) \notin E$ otherwise it could be added to $C$ and it would still be a valid matching. |
_codereview.85662 | I am trying to build a high performance socket server and this is what I have come up with so far. Can anyone please review my code and see if I can make any improvements on it?// State object for reading client data asynchronouslypublic class StateObject{ // Client socket. public Socket workSocket = null; // Size of receive buffer. public const int BufferSize = 1024; // Receive buffer. public byte[] buffer = new byte[BufferSize]; // Received data string. public StringBuilder sb = new StringBuilder(); // GUID of client for identification public string guid = string.Empty;}public class CAsnycSocketServer : IDisposable{ public AsyncCallback workerCallBack; private Socket mainSocket = null; private static ArrayList ClientSockets; private Socket workerSocket = null; private bool shutdownServer = false; public static ManualResetEvent allDone = new ManualResetEvent(false); public int MaxConnections { get; set; } //Not implemented /// <summary> /// Default constructor /// </summary> public CAsnycSocketServer() { } /// <summary> /// Constructor to start listening /// </summary> /// <param name=port></param> public CAsnycSocketServer(int port) { StartListening(port); } public void ShutdownServer() { shutdownServer = true; CloseSockets(); } public void Dispose() { shutdownServer = true; CloseSockets(); mainSocket.Dispose(); ClientSockets.Clear(); } /// <summary> /// Gets the current connected client count /// </summary> /// <returns></returns> public int getConnectedClientCount() { lock (ClientSockets.SyncRoot) { return ClientSockets.Count; } } /// <summary> /// Closes the main listening socket and all the clients /// </summary> public void CloseSockets() { if (mainSocket != null) { mainSocket.Close(); } lock (ClientSockets.SyncRoot) { foreach (StateObject so in ClientSockets) { if (so.workSocket != null) { so.workSocket.Close(); so.workSocket.Dispose(); } } } ClientSockets.Clear(); } /// <summary> /// Starts listening for client connections /// </summary> /// <param name=port></param> public void StartListening(int port) { try { mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port); // Bind to local IP Address... mainSocket.Bind(ipLocal); // Start listening... mainSocket.Listen(100); ClientSockets = new ArrayList(); while (!shutdownServer) { // Set the event to nonsignaled state. allDone.Reset(); // Start an asynchronous socket to listen for connections. Console.WriteLine(Server listening for connections); mainSocket.BeginAccept(new AsyncCallback(ClientConnectCallback), mainSocket); // Wait until a connection is made before continuing. allDone.WaitOne(); } } catch (Exception ex) { } } /// <summary> /// Callback which occurs when a client connects to the server /// </summary> /// <param name=ar></param> public void ClientConnectCallback(IAsyncResult ar) { // Signal the main thread to continue. allDone.Set(); try { // Get the socket that handles the client request. Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); // Create the state object. StateObject state = new StateObject(); state.guid = Guid.NewGuid().ToString(); state.workSocket = handler; ClientSockets.Add(state); Console.WriteLine(Client connected : + state.guid + Count : + ClientSockets.Count); handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ClientDataCallback), state); } catch (ObjectDisposedException) { } catch (SocketException se) { } } /// <summary> /// Callback for when a client sends data to the server /// </summary> /// <param name=ar></param> public void ClientDataCallback(IAsyncResult ar) { try { String content = String.Empty; // Retrieve the state object and the handler socket // from the asynchronous state object. StateObject state = (StateObject)ar.AsyncState; Socket handler = state.workSocket; // Read data from the client socket. int bytesRead = handler.EndReceive(ar); if (bytesRead == 0) { //Client has disconnected Console.WriteLine(Client disconnected : {0}, state.guid); CleanAndRemoveClient(state); } if (bytesRead > 0) { // There might be more data, so store the data received so far. state.sb.Append(Encoding.ASCII.GetString( state.buffer, 0, bytesRead)); // Check for newline, If it is not there, read // more data. content = state.sb.ToString(); if (content.EndsWith(Environment.NewLine) == true) { // All the data has been read from the // client. Display it on the console. Console.WriteLine(Read {0} bytes from socket. \n Data : {1} GUID : {2}, content.Length, content, state.guid); // Echo the data back to the client. //Send(handler, content); state.sb = new StringBuilder(); } else { // Not all data received. Get more. handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ClientDataCallback), state); } } } catch (Exception ex) { CleanAndRemove(); } } /// <summary> /// Not implemented /// </summary> /// <param name=handler></param> /// <param name=data></param> //private static void Send(Socket handler, String data) //{ // // Convert the string data to byte data using ASCII encoding. // byte[] byteData = Encoding.ASCII.GetBytes(data); // // Begin sending the data to the remote device. // handler.BeginSend(byteData, 0, byteData.Length, 0, // new AsyncCallback(SendCallback), handler); //} /// <summary> /// Sends data to a client based on the passed GUID to identify the client /// </summary> /// <param name=guid></param> /// <param name=data></param> private void SendToClient(string guid, string data) { // Convert the string data to byte data using ASCII encoding. byte[] byteData = Encoding.ASCII.GetBytes(data); foreach (StateObject so in ClientSockets) { if (so.guid == guid) { if (so.workSocket.Connected) { // Begin sending the data to the remote device. so.workSocket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), so.workSocket); } } } } /// <summary> /// Overload - send byte data to a client /// </summary> /// <param name=guid></param> /// <param name=data></param> private void SendToClient(string guid, byte[] data) { foreach (StateObject so in ClientSockets) { if (so.guid == guid) { if (so.workSocket.Connected) { // Begin sending the data to the remote device. so.workSocket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), so.workSocket); } } } } /// <summary> /// Callback when a send completes to a client /// </summary> /// <param name=ar></param> private void SendCallback(IAsyncResult ar) { try { // Retrieve the socket from the state object. Socket handler = (Socket)ar.AsyncState; // Complete sending the data to the remote device. int bytesSent = handler.EndSend(ar); Console.WriteLine(Sent {0} bytes to client., bytesSent); //handler.Shutdown(SocketShutdown.Both); //handler.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } /// <summary> /// Closes, disposes and removes a disconnected client from the ClientSockets arrayList /// </summary> /// <param name=state></param> private void CleanAndRemoveClient(StateObject state) { lock (ClientSockets.SyncRoot) { for (int i = ClientSockets.Count - 1; i >= 0; i--) { StateObject so = (StateObject)ClientSockets[i]; if (so == state) { so.workSocket.Close(); so.workSocket.Dispose(); ClientSockets.RemoveAt(i); } } } } /// <summary> /// Closes, disposes and removes a any disconnected clients from the ClientSockets arrayList /// </summary> /// <param name=state></param> private void CleanAndRemove() { lock (ClientSockets.SyncRoot) { for (int i = ClientSockets.Count - 1; i >= 0; i--) { StateObject so = (StateObject)ClientSockets[i]; if (so.workSocket.Connected == false) { so.workSocket.Close(); so.workSocket.Dispose(); ClientSockets.RemoveAt(i); } } } }} | Socket server class | c#;socket;server | null |
_unix.376017 | I have two backup job instances that backup the bareos director:BackupBareosFiles, which backs up the director configuration.BackupMyCatalog, which backs up the sql database of the director.At the moment both these job instances are backed up into the same pools and the same volumes:Monthly (Full Backup) Weekly (Full Backup) Daily (Differential Backup)This seems wrong to me, since you need a related Full backup job to restore a differential backup job. It seems to me that:Each volume with the same label should contain one or more backup jobs from the same backup job instance.Each volume with the same label should not contain backup jobs from multiple backup instances. However, it also seems to me that there might be the need to some how group together a backup of a configuration with the same backup of a catalog, to make sure both are restored together. Is it correct to have separate pools and volumes for both of these director backup jobs? | Should the two jobs that backup the bareos director be split into seperate pools and volumes? | backup;bacula;bareos | null |
_webapps.49179 | Lots of email services are OpenID providers: Gmail, Yahoo, AOL, and so on. However, as far as I can tell, those services themselves don't allow for OpenID authentication.What email services, preferably free, will enable me to create a new email account using my pre-existing OpenID? | What email services allow authentication from a different OpenID provider? | email;openid | null |
_vi.10368 | I would like to know if i could select some code in visual mode and git add it ?I checked with fugitive.vim but i didn't find how to do it.Is it possible ? Or is there any other plugin to do it ? | Git Fugitive how to git add a visually selected chunk of code | visual mode;git;plugin fugitive | null |
_softwareengineering.51311 | Consider there is a manager and a programmer in a project. A manager crates a task which a programmer performs.In this situation who should check that a programmer didn't make some non-testable mistakes like using non thread-safe map in a singleton service? And who checks the overall project code structure? | Code checking role | development process | null |
_webmaster.16949 | Possible Duplicate:Which Content Management System (CMS) should I use? What would it cost or is there already a system with a CMS like Joomlathat would create the back-end of a website like this one:http://www.appliance-appointment.com/ | PHP / Database Advertising Directory | php;database;cms;advertising | null |
_codereview.110850 | My code takes input from the user and creates a receipt with the information the program receives from the user:import easyguiitems = []prices = []amount = []amounts = 0finished = Falsetotal_price = 0.00list_num = -1def take_item(): global list_num, amounts, finished item = easygui.enterbox(What item is it?) if item == done or item == None: finished = True else: how_many = easygui.integerbox(How many {0:} do you have?.format(item)) amounts = how_many items.append(item) amount.append(how_many) list_num += 1def pricing(): global list_num, total_price if finished: pass else: try: price = easygui.enterbox(What is the price of 1 {0:}.format(items[list_num])) new_price = float(price) except ValueError: easygui.msgbox(Please enter a number.) pricing() else: total_price += float(price) * amounts prices.append(new_price)def create_receipt(): print Item \t Amount \t Price \t Total Price for i in range(0, list_num+1): print items[i], \t\t, amount[i], \t\t 3, prices[i] print \t\t\t , $,total_price print Thank you for using Tony's Receipt Maker! print -----------------------------------------------------------while 1: take_item() pricing() if finished: create_receipt() else: continueAre there any ways to improve the efficiency of the code and shorten it? Is there anything I should improve in my code? | Python Receipt Creator | python;finance | null |
_unix.275960 | When we do kill -l we get a list of all the signals that are supported, but is there any man page that describes each signal in detail? | Where can I find detailed documentation on Linux signals? | linux;signals;documentation | Yes, it's man 7 signal which, among other things, includes the following table: Signal Value Action Comment SIGHUP 1 Term Hangup detected on controlling terminal or death of controlling process SIGINT 2 Term Interrupt from keyboard SIGQUIT 3 Core Quit from keyboard SIGILL 4 Core Illegal Instruction SIGABRT 6 Core Abort signal from abort(3) SIGFPE 8 Core Floating point exception SIGKILL 9 Term Kill signal SIGSEGV 11 Core Invalid memory reference SIGPIPE 13 Term Broken pipe: write to pipe with no readers SIGALRM 14 Term Timer signal from alarm(2) SIGTERM 15 Term Termination signal SIGUSR1 30,10,16 Term User-defined signal 1 SIGUSR2 31,12,17 Term User-defined signal 2 SIGCHLD 20,17,18 Ign Child stopped or terminated SIGCONT 19,18,25 Cont Continue if stopped SIGSTOP 17,19,23 Stop Stop process SIGTSTP 18,20,24 Stop Stop typed at terminal SIGTTIN 21,21,26 Stop Terminal input for background process SIGTTOU 22,22,27 Stop Terminal output for background process |
_unix.371097 | I run these commands:df /stat -fc '%f * %s' / and getFilesystem 1K-blocks Used Available Use% Mounted on/dev/ma....Vol00 26409212 15604380 9441888 63% /and2701196 * 4096 (which is 11064201216)So df says 9,44 GB free and stat says 11,06 GB freeThat is quite a difference. Why is stat giving a larger value? Who should I trust? | Why the difference between stat and df | linux;disk usage;stat | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.