id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_softwareengineering.324046 | I have a set of about 300 unit tests that have been through a difficult few months. The poor tests were subject to being upgraded from a V110 compiler (Visual Studio 2008) alongside Visual Studio 2012 to a V120 (Visual Studio 2013) compiler alongside an upgrade to Visual Studio 2015.These tests were passing in VS2012. They broke horribly after the compiler/IDE upgrade. Some things were very odd, I spent weeks trying to fix them, worked with several engineers, and found very little traction. Then a beam of hope came in the form of VS2015 Update 3. It fixed the tests. For about 2 days. Now I'm met with a dreaded, Failed to set up the execution context to run the test, for a test that was working last week. So, the tests have been a bit battered recently. These are critical tests that my team needs to be running (and that we can't put in the gated builds because of the failing tests). We have workarounds to run the tests piece-by-piece, in an older IDE, from the command line, or any other number of tricks and hacks...but we really can't have tricks and hacks for important unit tests. I'm not asking how to fix this specific set of tests, but moreover how should I as a software engineer start to regain stability with a set of unit tests that became unstable. As I'm writing this the answer seems obvious: Snap off the smallest subset of failing tests and analyze the failures/start the debugging process (which of course I'm doing), but things always have a rub. The upgrade happened, and there's no going back, so at the moment we're stuck with some (occasionally) unreliable tests.Because the tests can be (not easily and not always all of them) ran, fixing these tests doesn't ever seem to be a higher priority for my team than pushing out new features. I'm an SD1 and so I don't have a lot of sway to get the more senior members of the team to analyze these test failures and I feel like I'm spinning my wheels trying to fix tests while waiting for the next test/tool failure. What should I do? | Unit tests became unstable after upgrading compilers and IDEs | unit testing | The problem you describe is in no way restricted to unit tests, and when approaching this from a software engineering perspective, one might ask the more general question We picked a certain framework as a platform for our program system, but when upgrading to a newer version, we run into lots of unexpected compatibility problems, because the vendor did not make a good job in respect to downwards compatibility. What can we do?The possible answers to this question might not please you, but the measures are well known:make sure your software is not more tightly coupled to the framework than absolutely necessarymake sure whenever you install an upgrade of the framework, there is a way back to the former version when this causes too much problemsmake sure you know your framework well, and avoid to use the latest and greatest features immediately, better be a little bit conservative, rely on mature featureswhen the problems become intolerable, consider to change your platform. Try to pick a framework which has a reputation to be mature and stable, especially when it comes to backwards compatibility.In your case, for example, you used the unit testing framework of Visual Studio. Of course, frameworks often force you to couple your software to them tightly, but in this case, whenever you need to ugrade the IDE, you also need to upgrade the unit testing environment. AFAIK you cannot upgrade those components individually. As you wrote, there is currently no easy way back for you to a former version of VS.So is there an alternative? Yes there is - pick a different unit testing framework which is not so tightly coupled to the IDE. Unit tests directly inside the IDE is a nice gimmick, but nothing you cannot live without. For example, we have a full unit testing suite for one of our products since more than ten years, developed with NUnit, and we never encountered any of the problems you mentioned when we upgraded from VS 2003 to 2015 with almost any intermediate VS version which was released by Microsoft. NUnit was available at a time where VS unit testing was not, and nowadays there are VS plugins to run NUnit tests directly from inside the IDE. Nevertheless, the latter is still dispensable, we can also run all tests outside VS, just by using the NUnit GUI.Of course, when we upgraded the NUnit version from time to time, we had to deal with some minor issues, but never anything which was as severe as you described it, not even close.There might be other Unit testing frameworks with similar properties and also not so entangled with the IDE; the correct choice needs surely an evaluation for your case. And when you pick such a framework, you have an additional third party vendor on whom you have to rely on, which can have a lot of new drawbacks and dependencies, too. Maybe our team was just lucky to pick the better framework several years ago. If one is not so lucky, and picks some framework which is abandoned after some months by the vendor - well, shit happens.But I think this is the best recommendation I can give you here. Maybe changing the framework is not an option for you now, may cause too much effort. Maybe after you analyse your code and think about it, the effort might not be so high as it seems at a first glance. Maybe you can isolate most of the problems you have now and get your problems under control by using what you have now. But do not expect the silver bullet - framework and library decisions always have a certain risk of showing up to be wrong in the future, you are not the first one who made that experience. |
_cogsci.1982 | Is there a game theory analysis or other research or modeling describing the commonly perceived phenomenon whereby the amount by which people underpay a gratuity seems to be proportional to the number of people at the table?In other words is there term of art for this behavioral pattern just as we use the phrase Prisoner's Dilemma to describe the game theoretical mechanics of two parties who can collude (to their mutual benefit) with risk, or betray their colleague in an effort reduce or eliminate their own risk?(I would suggest that the mechanisms by which people exploit common resources and by which people fail to invest and maintain such resources (for example ecologically) are similar to this other group dynamic but I'm curious what research has been done on this). | Stiffing the tip as groups get larger ... like the prisoner's dilemma but ...? | social psychology;economics;game theory | null |
_softwareengineering.284060 | I am writing code on top an established Enterprise application. I see that the application has 4 modules as shown below.-Srk-SrkEJB-SrkUtils-SrkWebI have gone through the code and I see that some modules are tiny for example: SrkEJB module has got just 2 EJBS. I don't see any reason to create a separate module for 2 Java classes.I have simplified the above approach and is shown below.Srk - com.srk.utils - com.srk.ejb - com.srk.webHow is the first module based architecture different from the second from an architectural stand point? Generally, which is the followed mostly, when creating an application from scratch? If not, What could be the trade-offs of each of the approaches? I believe this is a not specific to Java alone. | Module based project vs Normal project | design patterns;object oriented;language agnostic;java ee;architectural patterns | null |
_unix.235066 | I installed a Debian Jessie machine on a 1.4TB disk (technically a hardware RAID but this shouldn't matter). At installation, I created an unencrypted LVM with 3 volumes, including a 30 GB volume I installed the system on.I want to backup the system, so I picked Clonezilla to backup the 30 GB partition.Unfortunately, Clonezilla only offers me to clone /dev/sda, that is the whole 1.4 TB partition. As if it didn't recognize the LVM.Is there some specific procedure to follow?I don't see anything in the docs/FAQ so I assume it should be straightforward. | Backup partition in LVM using Clonezilla | lvm;clonezilla | null |
_softwareengineering.102874 | I had asked this question on Stackoverflow, and before it got booed off, I received the helpful suggestion from Pter Trk that this might be a better place to post it.I've been programming in Java for a few years. I've often discussed design decisions with colleagues on the basis of what constitutes 'good style'. Indeed, there are a number of StackOverflow questions/answers that discuss a design on the basis of whether something is 'good style'. But what makes 'good style'? Like many things, I know it when I see it... but I wanted to have better idea than just my conscience saying that this design doesn't feel right.What are the things you think about in order to produce good, well designed code?(I acknowledge that this is somewhat subjective, as what is 'good style' will depend on the task at hand). (Also, I should add that I'm not interested in team styles - e.g. we use indents of 2 spaces rather than 4..., and I'm not interested in the Java code conventions.)Edit: thanks for all the good answers/comments so far. I'm especially keen for answers that would help codify those things that make a programmer's conscience (and possibly stomach) wrench? | What makes for good style in Java? | java;coding style | null |
_unix.159072 | According to the packet path diagram, and its description:Table 6-2. Source local host (our own machine)[...]Routing decision, since the previous mangle and nat changes may have changed how the packet should be routed.[...]there is a second route lookup after the OUTPUT chain, because NAT and other things might have changed the actual output interface. But in my tests I found that it is impossible to change the output interface once it's chosen.For example, you have an application that sends an UDP packet from an unbound socket to some destination: the main table is queried and a default source, interface and gateway is chosen. Then you set a fwmark on it, and use that in policy-based routing to try put the packet on another interface:[root@localhost ~]# ip rule add fwmark 1 lookup 1[root@localhost ~]# ip route add default dev lo table 1The packet will have these lookups#first lookup, assuming main NIC is in LAN with address 192.168.1.2/24, gateway 192.168.1.1[root@localhost ~]# ip route get 8.8.8.88.8.8.8 from 192.168.1.2 via 192.168.1.1 dev eth0 cache #second lookup, source address and oif chosen[root@localhost ~]# ip route get 8.8.8.8 oif eth0 from 192.168.1.2 mark 18.8.8.8 from 192.168.1.2 via 192.168.1.1 dev wlp3s0 mark 1 cache Your packet will still have the already chosen output interface. Note that if you don't set the oif parameter you get the right interface:[root@localhost ~]# ip route get 8.8.8.8 from 192.168.1.2 mark 18.8.8.8 from 192.168.1.2 dev lo mark 1 cache So what's the point? It seems (and I have tested) that you can effectively only change the gateway, but you cannot even use blackhole or unreachable. | What is the point of the second route lookup after OUTPUT? | linux;iptables;routing;port forwarding | null |
_unix.122886 | I have this file I use to set my username and password before exporting the value. #!/bin/bashecho -n User:;read userecho -n Password:;read -s passwordexport http_proxy=http://$user:$password@$domain:$portnumif curl -silent http://www.google.com | grep authentication_failed;then echo NO CONNECT unset http_proxyelse echo OKfiin history, printenv, and export -p I'm able to see the value that I have setfurthermore, I'd like an encrypted form of my password inside $password, versus that value containing my password verbatim. I'm familiar with using openssh to salt passwords, or printing hash using perl's crypt(), but for my purpose, I cannot see it's usage? any tips will be appreciated? | What are ways to encrypt a password inside an environment variable | linux;security;bash;encryption | I am unable to reproduce the issue you mentioned with password showing up in the output from the history command.The password showing up in the output from printenv and export -p is working as intended. Those commands display the environment variables, and that's where you put the http_proxy string.The environment variables are automatically inherited by child processes, but not by any other processes. I don't see why you think that is a major concern, as it is only visible to processes within the same security domain.But you could stop putting it in an environment variable and instead use normal shell variables. Then it would not be inherited by child processes. Since you probably want curl to have access to the environment variable, then you could pass the environment variable to just that one command and not all the other commands.#!/bin/bashecho -n User:;read userecho -n Password:;read -s passwordproxy=http://$user:$password@$domain:$portnumif http_proxy=$proxy curl -silent http://www.google.com | grep authentication_failed;then echo NO CONNECTelse echo OKfi |
_scicomp.8132 | I'm looking to learn more about Sparse Optimization and apply it to machine learning problems. Could you please recommend some books/resources on this topic? Both theoretical and applied are fine. | Books/Resources on Sparse Optimization? | reference request;optimization;machine learning | First, just to clarify things, you're talking about solving optimization problems of the form$\min \| x \|_{1}$subject to $\| Ax - b \|_{2} \leq \delta$and related forms, right? There are many different applications in which problems are formulated as the minimization of the 1-norm of a vector subject to linear or least squares constraints. An important area of theoretical research is proving conditions under which solving the $L_{1}$ minimization problem will recover the sparsest solution. Many folks working in convex optimization have gravitated to this area because of the new found demand for solvers for these problems. The methods that they develop can be used in many different applications, and the solvers are effectively black boxes to most users of the codes. It isn't clear whether you're more interested in the application of sparse optimization to machine learning or in theoretical questions or in methods for actually solving the resulting optimization problems. These are really very disjoint though related areas of research. As a starting point, I'd suggest looking at the list of resources for compressive sensing at:http://dsp.rice.edu/csIf you can supply more details about what it is you want to learn about, and also give me some idea of your background in optimization and other areas of mathematics, then perhaps I could suggest more specific references. |
_softwareengineering.127472 | I've been developing web apps for a while now and it is standard practice in our team to use agile development techniques and principles to implement the software.Recently, I've also become involved in Machine Learning and Natural Language Processing. I heard people primarily use Matlab for developing ML and NLP algorithms. Does agile development have a place there or is that skill completely redundant?In other words, when you develop ML and NLP algorithms as a job, do you use agile development in the process? | Is Agile Development used in Machine Learning and Natural Language Processing? | agile;development process;machine learning;natural language processing | Maching Learning and Natural Language Processing is somewhat data-driven. Without a continuous supply of high-quality data (which must be re-captured whenever new criteria are added), the software development may miss its intended target.The customer and product owner may devote a bigger fraction of their time toward test data collection.The adaptations will depend on:The balance of time allocated toward spike versus implementationspike: open-ended research / exploratory prototyping (where the benefits are possible but not certain, and where priorities are fast-changing)implementation (where the benefits and costs are somewhat more predictable, but each task unit will take much longer to finish).Average size of a task unit. How long does a spike take? How long does an implementation take? Unlike typical application development, partial algorithm implementations are usually not runnable.Whether canned algorithms i.e. existing libraries / algorithm packages are available. When these are available, time spent on implementation is reduced (because they're already written) and thus more time will be spent on spikes.There will be two feedback loops:In each iteration, customer and product owner collect/update data periodically (and with better quality / newer criteria) based on business need and developers' feedback.In each iteration, developers try to improve algorithm quality based on the data available, and the algorithm is packaged into a usable system and delivered at the end of each iteration. Customer and product owner should be allowed to take the beta system elsewhere, redistribute them, etc.Thus, we see that data replaces features as the main definition of progress.Because of the increased importance of research / spike in ML/NLP development, there is a need for a more organized approach to spike - something you may have already learned from any graduate research teams. Spikes are to be treated as mini-tasks, taking from hours to days. Implementation of one algorithm suite will take longer, in some cases weeks. Because of task size differences, spikes and implementations are to be prioritized separately. Implementations are costly, something to be avoided if possible. This is one reason for using canned algorithms / existing libraries.The scrummaster will need to constantly remind everyone to: (1) note down every observation, including passing thoughts and hypotheses, and exchange notes often (daily). (2) Spend more time on spikes (3) use existing libraries as much as possible (4) don't worry about execution time - this can be optimized later.If you do decide to implement something that's missing in libraries, do it with good quality.Daily activities:Reprioritize spikes (short tasks / hours - days) and exchange research notes.De-prioritize spikes aggressively if yesterday's result don't seem promising.Everyone must commit a fraction of time on implementation (long tasks / weeks), otherwise nobody would be working on them because they tend to be more boring on tasks.Sprint activities:Demo, presentation of beta softwareNew data collectionRetrospect: data collection criteria / new measures of quality, algorithm satisfaction, balance between spikes and implementationsAbout the note on deferring optimization: The thought-to-code ratio is much higher in ML/NLP than in business software. Thus, once you have a working idea, rewriting the algorithm for an ML/NLP application is easier than rewriting a business software. This means it is easier to get rid of inefficiencies inheritant in the architecture (that is, in the worst case, simply do a rewrite.)(All editors are welcome to rearrange (re-order) my points.) |
_reverseengineering.11969 | I'm trying to get into reverse engineering and am beginning with .NET, attempting various CrackMes and KeygenMes that I've found on the internet. Until now, I haven't really struggled but this latest one is driving me mad:https://tuts4you.com/download.php?view.1894VT link if needed: https://www.virustotal.com/en/file/9bd07d7cbd053f6ad27792487679b18b2f72b589440d8ab81f9cdc4d84301178/analysis/1454947890/Decompiling with ILSpy reveals the license check performed: FileStream fileStream = new FileStream(key.dat, FileMode.Open, FileAccess.Read); StreamReader streamReader = new StreamReader(fileStream); string text = streamReader.ReadToEnd(); byte[] bytes = Encoding.Unicode.GetBytes(this.TextBox1.Text); SHA512 sHA = new SHA512Managed(); sHA.ComputeHash(bytes); if (Operators.ConditionalCompareObjectEqual(this.CodeCrypt(text), Convert.ToBase64String(sHA.Hash), true)) { Interaction.MsgBox(Good job, make a keymaker, MsgBoxStyle.Information, Done); } else { Interaction.MsgBox(Try again, it is very simple, MsgBoxStyle.Critical, No ....); } streamReader.Close(); fileStream.Close();Here is the CodeCrypt method:Key = AoRE;public string CodeCrypt(string text){ string text2 = ; int arg_0F_0 = 1; int num = Strings.Len(text); checked { for (int i = arg_0F_0; i <= num; i++) { int num2 = i % Strings.Len(this.Key); if (num2 == 0) { num2 = Strings.Len(this.Key); } text2 += Conversions.ToString(Strings.Chr(Strings.Asc(Strings.Mid(this.Key, num2, 1)) ^ Strings.Asc(Strings.Mid(text, i, 1)) - 6)); } return text2; }}Seemed quite straight forward to reverse, so I generated my own key generation method: private static string Key(string name) { string key = ; SHA512 sHA = new SHA512Managed(); string hash = Convert.ToBase64String(sHA.ComputeHash(Encoding.Unicode.GetBytes(name))); for (int i = 1; i <= hash.Length; i++) { int num2 = i % 4; if (num2 == 0) { num2 = 4; } var test = Convert.ToChar((AoRE[num2 - 1] ^ hash[i - 1]) + 6); key += test; } return key; }Then I wrote my license: using (StreamWriter sw = new StreamWriter(File.Open(key.dat, FileMode.Create), Encoding.Unicode)) sw.Write(Key(Tom));But it fails. I set a breakpoint to see what the output from CodeCrypt() and the SHA512 hash was, and saw this:CodeCrypt: 8dmVQYHqap7MbFngePjLSxvaC9kVgaDiyR2p550IFO2kzGAuC9yWufBs5LZGbKeR/KAFGVTBb47z4sa686eBTA==SHA512: 8dmVQYHqap7MbFngePjLSxvaC9/VgaDiyR2p550IFO2kzGAuC9yWufBs5LZGbKeR/KAFGVTBb47z4sa686eBTA==The 27th character differs in these outputs and I just don't understand why. What am I missing here?Thanks in advance. | KeygenMe - My output has one wrong character | decompilation | Your algorithm calculates the correct byte for each character of the base64 encoded hash, however your implementation of that byte's string encoding is not correct.Convert.ToChar() simply casts the byte to a char.VB's Strings.Chr() converts the byte to unicode, using the system's current default code page. This is most likely Windows-1252 for US/Western Europe.For bytes 0x00-0x7F, UTF-8 and Windows-1252 have the same binary representation. But things are different for bytes 0x80-0xFF, and it just so happens that the / character is the only character XOR'd to a value greater than 0x7F (it's 0x83).In Windows-1252, 0x80-0xFF represent single-byte extended characters.In UTF-8, these extended characters require two bytes of storage: 0x01 0x92.This means that the crackme is buggy, because the license file depends on the system's character encoding (which could change). The license file should have used unicode consistently.To fix your code, replace Convert.ToChar() with Encoding.Default.GetString()var test = Encoding.Default.GetString( new[] { (byte)((AoRE[num2 - 1] ^ hash[i - 1]) + 6) });Edited to addOne thing I want to point out is that a char in C# is 2 bytes and stores a 16-bit unicode character (unlike C where a char is 1 byte). This is why casting and using the default encoding are different operations. |
_unix.219257 | Sometimes I forgot to press ESC to return to command mode and enter :w<enter> in some line I was editing. So I get the following:some line of code:w I was typing ^ cursor positionSo what I do is pressing ESC+k+A+Backspace+Backspace+ESC+j or something similar.Someone has a shorter/better/quicker way of doing this? | VIM: What's the quickest way to return from typing :w in insert mode? | vim | If the extra :w<enter> is the only insertion in that place I use ESC + u (undo).If not it's just as long as yours but depending on personal preferences/habits it might be faster: ESC + up arrow + J (join) + left arrow + left arrow + x + x (delete current char).Technically the longer sequence can be saved as a macro and then invoked with just ESC + @ + key (where key corresponds to the register in which the macro was saved) - but I just couldn't get the macros into my habits :) |
_cogsci.467 | Possible Duplicate:Any work being done on Perception, Action, and/or Cognition in Video games? What is the relationship between computer game performance and measures of ability? | What is the relationship between computer game performance and measures of ability? | intelligence;test;measurement;video games;hci | null |
_webapps.28004 | I have admin rights on three Facebook pages for organizations. However, I really need to stop the many daily notifications appearing in my top menu pulldown telling me when this or that new user has Liked the page or liked this or that image in the page. These are totally cluttering up my new items notices in that menu.How do I tell it to tell me LESS about those three pages I have admin roles on, up in that top pulldown menu?In short: I really want my little globe pulldown menu to not have items about the pages that I am ADMIN of. I want the globe pulldown menu to only have items about my PERSONAL facebook account. | Suppress notifications in top menu about new Likes for Facebook Page admin | facebook | null |
_unix.313180 | I have a bare metal running Ubuntu server 16.04 with KVM and 3 NIC's that are connected by bridges br1, br2 and br3 to a guest VM running also Ubuntu server 16.04.The first NIC - br1 - is connected to the internet and it's router address is defined as the default gateway for the guest.I have a code running on my guest that needs to listen to the packets received by br2 and br3, the code should listen to 1 NIC only,I tried forwarding the traffic from en2 (the name of the guest NIC that is bridged via br2) to en3 (the same with br3) by following this:sudo nano /etc/sysctl.confuncomment net.ipv4.ip_forward = 1sudo sysctl -psudo iptables -t nat -A POSTROUTING --out-interface en3 -j MASQUERADE sudo iptables -A FORWARD --in-interface en2 --out-interfac en3 -j ACCEPTYet there is nothing recorded when using sudo tpcdump -i en3 and send a ping message to NIC2 (while if I run sudo tpcdump -i en2 i can see the ping messages)What am I missing here? Is there a better way for me to get my desired result (that my code will listen to 1 NIC and get both NIC's trafic) ? | Iptables FORWARD chain traffic not seen by tcpdump | linux;debian;networking;iptables;tcpdump | null |
_cstheory.1000 | Does anyone know (or can anyone think of) a simple reduction from (for example) PARTITION, 0-1-KNAPSACK, BIN-PACKING or SUBSET-SUM (or even 3SAT) to the UBK problem (integral knapsack with unlimited number of objects of each type)? I'm writing an introduction to a few of these problems, and noticed that I hadn't really heard of a standard reduction here. Shouldn't be that hard (it's a relatively expressive problem), but I can't think of anything right now Thoughts/references? | Simple reduction to unbounded knapsack? | cc.complexity theory;ds.algorithms;np hardness;reductions | There is a simple reduction from the subset sum problem. (We usually give it as an exercise.)The idea is to encode in the weights that an element can only be included 0 or 1 times.Assume the subset sum instance consists of numbers $w_1,\dots,w_n$ with target $W$. Assume that $w_i < B$ for all $i$.We will have two new elements for each old element, simulating whether the element is used 0 or 1 times. For element $i$ we get two new weights $w^1_i = (2^{n+1} + 2^i)nB + w_i$ and $w^0_i = (2^{n+1} + 2^i)nB$. The new weight bound is defined as $W' = (n2^{n+1} + 2^n + \dots + 2^1)nB + W$. Values of elements are the same as their weights, and the target value is $W'$ |
_codereview.98564 | While writing a C++ GUI application more or less from scratch I needed some form of an event-listener system, preferably using lambdas. An event should be able to have multiple listeners and the user should not have to worry about the lifetime of the objects. I came up with this bit using shared and weak pointers to determine object lifetime:#include <functional>#include <list>template <typename ... Args> struct event:public std::shared_ptr<std::list<std::function<void(Args...)>>>{ using handler = std::function<void(Args...)>; using listener_list = std::list<handler>; struct listener{ std::weak_ptr<listener_list> the_event; typename listener_list::iterator it; listener(){ } listener(event & s,handler f){ observe(s,f); } listener(listener &&other){ the_event = other.the_event; it = other.it; other.the_event.reset(); } listener(const listener &other) = delete; listener & operator=(const listener &other) = delete; listener & operator=(listener &&other){ reset(); the_event = other.the_event; it = other.it; other.the_event.reset(); return *this; } void observe(event & s,handler f){ reset(); the_event = s; it = s->insert(s->end(),f); } void reset(){ if(!the_event.expired()) the_event.lock()->erase(it); the_event.reset(); } ~listener(){ reset(); } }; event():std::shared_ptr<listener_list>(std::make_shared<listener_list>()){ } event(const event &) = delete; event & operator=(const event &) = delete; void notify(Args... args){ for(auto &f:**this) f(args...); } listener connect(handler h){ return listener(*this,h); }};Example usage:#include <iostream>using click_event = event<float,float>;struct gui_element{ click_event click; void mouse_down(float x,float y){ click.notify(x, y); }};int main(int argc, char **argv) { gui_element A,B; click_event::listener listener_1,listener_2; listener_1.observe(A.click,[](float x,float y){ std::cout << l1 : A was clicked at << x << , << y << std::endl; }); listener_2.observe(B.click,[](float x,float y){ std::cout << l2 : B was clicked at << x << , << y << std::endl; }); { auto temporary_listener = A.click.connect([](float x,float y){ std::cout << tmp: A was clicked at << x << , << y << std::endl; }); // A has two listeners, B has one listeners A.mouse_down(1, 0); B.mouse_down(0, 1); } listener_2 = std::move(listener_1); // A has one listener, B has no listeners A.mouse_down(2, 0); B.mouse_down(0, 2);}Output:l1 : A was clicked at 1, 0tmp: A was clicked at 1, 0l2 : B was clicked at 0, 1l1 : A was clicked at 2, 0While the usage is exactly how I wanted, I am not sure the implementation is elegant or optimal. Any way how to improve this? | Event-listener implementation | c++;c++11;event handling;lambda | As I said in the comments, your system is pretty close to a system of signals and slots. Congratulations if you never heard of the pattern before, that's an excellent way to implement an the observer design pattern! I still have few notes:I don't know which compiler you use, but mine won't compile your code unless I include <memory> for std::shared_ptr. I suppose that it may be transitively included from <functional> or <list> in your implementation. Never rely on transitive includes from the standard library and always include the exact header that contains what you need.Qt, which is the emblematic library when it comes to signals and slots, tends to use past participle for its signas names. For example, instead of click, it would be clicked:button.clicked.connect(/* whatever */);It allows to read the line easily as when button is clicked, do whatever. Also, it makes the object look more like a trigger and less like an action.From a design point of view, connect being a method taking only one function, I would expect it to add the function to the list, not to return a listener.You should encapsulate std::shared_ptr<std::list<std::function<void(Args...)>>> instead of inheriting from it. Frankly, you don't want people to expose every method of std::shared_ptr. You don't want people to think of pointers when they want events, right?The truth is my answer isn't really personal. Since your class obviously looks like a signal class, everything I am saying tends to mean make your design closer to those of existing signal classes like Boost.Signals2 :/ |
_cs.68022 | I'm revising for an upcoming exam and was wondering if someone could help me with a practice problem:We model a set of cities and highways as an undirected weighted graph $G = (V,E,l)$, where the vertices $V$ represent cities, edges $E$ represent highways connecting cities, and for every undirected edge $e = {v, w}\in E$ the number $\ell[e]$ denotes the number of litres of fuel that your motorcycle needs in order to ride the distance between cities $v$ and $w$. There are fuel stations in every city but none on the highways between the cities. Therefore, if the capacity of your motorcycle's fuel tank is $L$ litres, then you can only follow a path (a sequence of adjacent highways), if for every highway $e$ on this path, we have $L\geq \ell[e]$, because you can only refuel in the cities.Design an algorithm with a running of time of $O(m\log n)$ that, given an undirected weighted graph $G=(V,E,\ell)$ modelling a setting of cities and highways, and a city $s \in V$ as inputs, computes for every other city $v \in V$, the smallest fuel tank capacity $M[v]$ that your motorcycle needs in order to be able to reach city $v$ from city $s$.I'm not sure how to solve this problem, but I do have a few ideas. I thought of possibly running Kruskal's algorithm since that would give me the MST of the graph. I'm not sure how I would then efficiently get the answer I need to produce.Alternatively, I was thinking of using dynamic programming in some way since that's one of the things that we use a lot in the course, but I'm not really sure how to go about it.Any help or hints would be appreciated. | Algorithm for finding lowest cost edge in each path in a graph | graph traversal | Let $T = \{s\}$, and let $Q$ be a new empty priority queue. Insert each edge incident on $s$ in $Q$. While there are still nodes with $d$ from $s$ yet to be computed, extract and remove the minimum from $Q$. If such edge connects a node $u$ in $T$ with a node $v$ not in $T$, add each edge incident on $v$ that still isn't in $Q$ to $Q$, then set $M[v]$ to $\max\{M[u], w(u, v)\}$. Otherwise, disregard the extracted edge and extract more edges until you find a suitable one.The overall complexity is $O(|E| \log |E|) = O(|E| \log |V|^2) = O(|E| \log |V|)$.To informally prove correctness, we can observe that whenever we set $M[v]$ to a certain value $x$, we can certainly reach $v$ from $s$ with a path in which each edge weighs at most $x$. On the other hand, no better path exists, because we already gave each edge lighter than $x$ a chance to connect to $s$. |
_computerscience.3926 | I need to find the transformation matrix(homogeneous coordinates) that flips anobject about a plane whose normal isdirected towards (-2 2 0), and intersects they-axis at y=2.I know how to do that when I have 3 points on the plane (A,B,C): translate to origin, find the orthonormal basis of the plane (u,v,w axes) and then rotate the plane to match XYZ coordinate system (with the axes I found), perform the reflection, rotate back and translate back.However in this case I have a normal and another data which I don't know how to use.Any ideas? | Transformations about a Plane | 3d;transformations | null |
_webmaster.81669 | I'm creating an invite only website, so my question is if I need to create a sitemap xml and upload to Google and others search engines with all pages? With only the main page (that'll be open for everyone)? And what others SEO tips I could use in a scenario like this? I'm new to SEO, sorry for the newbie questions.Thanks! | Should I create a sitemap for an invite only website? | seo;google;sitemap | SEO is an abbreviation for Search Engine Optimization. In Layman terms, it basically means trying to make your site appear as the first result in search engines based on keywords mostly related to your site.Making a sitemap is like asking search engines to prepare themselves to index your pages until you submit the sitemap to any search engine, in which case the indexing starts.I assume by invite only you mean that only selected individuals will know the URL to sections not available to the public. If you make a sitemap, then to maintain security, don't include these URLs in the sitemap.Other than that, I'll have to go with a no for sitemap creation unless that introductory page on your site is so spectacular that millions of people will want to see it, in which case you'd only index that one page, but even then, search engines might have already indexed it.If by chance search engines have indexed your private pages and you still want to make them accessible to selected individuals just by typing in the URL only, then you want to add the following between <head> and </head> section of the HTML code of each affected private page:<meta name=robots content=noindex>That way, search engines will remove the affected pages off their index and eventually will no longer list them. |
_unix.119198 | I have started using CentOS recently. I have some packages which end with .ipk. I need to install a cross compiler and the steps in the compiler's manual says I should do the following:ipkg install libstdc++6_4.1.2-r10_armv5te.ipkI have tried to install ipkg or opkg, but it didn't work. Can anyone tell how to install any of them or if there is an alternative to install .ipk file? | How to install ipkg in CentOS 6.5 | centos;ipkg | null |
_webapps.84339 | I am trying to have a pricing request form that exports to excel in the proper formatting. When it does export to excel it creates 4 tabs with information in each tab. I need to have the request export in the proper formatting so I can automate the a proposal. | Cognito Forms: How do I Export a form in the format I need? | cognito forms | null |
_unix.353636 | I have a shell script to set up the environment and install a relatively complex web application on a webserver, which has gradually evolved from a quick bad hack into a larger and slightly less bad hack.Previously, my script had a built-in 'bootstrap' function to allow me to easily copy it from my development computer to the remote server for use, requesting root login to create a folder to place the script into and then to copy the script.As this project has evolved, it now turns out that additional software that we will need to rely on expects a 'sudo' environment (rather than root login) for its own setup script, and so I'd like to switch the working of my setup script from expecting root to using sudo (especially as we may wish to share this with others, and for it to be able to work on servers where root is not available (eg, Ubuntu)).At present, my bootstrap function does:bootstrap(){ INSTALL_DIR=/local/bin SCRIPT=`basename $0` echo Copying script '${SCRIPT}' onto server: '${RHOST}' into '${INSTALL_DIR}' echo (You need to login (as root) 2 times.) ssh root@$RHOST umask 027; mkdir -p $INSTALL_DIR scp -p $SCRIPT root@$RHOST:/$INSTALL_DIR echo Done. Now login to the server and run the script as root. exit}I am not sure how I can translate this to using sudo?scp expects me to login as the user who will be able to write to the folder where the file should go, which I won't be able to do if there is no root account?Or perhaps I am making this too complicated? If the normal user on the remote server is essentially root-one-step-removed anyway, perhaps, rather than trying to create a 'tidy' place to store these admin scripts, I could just scp it somewhere into the user's own filespace, and the user could then in turn run the install part of the script from there using sudo. (I suppose the only issue that might then arise might be if a different administrator needed to run the script and couldn't access the other user's files..) | Can I transfer a file to a folder (on a remote server) which is writable only by root (via sudo)? | shell script;permissions;sudo;not root user | null |
_unix.291260 | I recently started using Ranger as my default file manager, and I'm really enjoying it. Right now, I've managed to change rifle.conf so that when I play audio or video from Ranger, mpv opens in a new xterm window and the media starts to play.However, if possible, I would like Ranger to open the gnome-terminal instead of xterm. In /.config/ranger/rifle.conf, it says that using the t flag will run the program in a new terminal:If $TERMCMD is not defined, rifle will attempt to extract it from $TERMI tried setting $TERMCMD in both my .profile and .bashrc files, but even though echo $TERMCMD would print gnome-terminal, Ranger would still open xterm. I also messed with setting $TERM to gnome-terminal, but that was messy and I decided to leave it alone.Any suggestions? Thanks! | Ranger file manager - Open gnome-terminal instead of xterm | linux;environment variables;gnome terminal;xterm;file manager | The source-code (runner.py) does this: term = os.environ.get('TERMCMD', os.environ.get('TERM')) if term not in get_executables(): term = 'x-terminal-emulator' if term not in get_executables(): term = 'xterm' if isinstance(action, str): action = term + ' -e ' + action else: action = [term, '-e'] + actionso you should be able to put any xterm-compatible program name in TERMCMD. However, note the use of -e (gnome-terminal doesn't match xterm's behavior). If you are using Debian/Ubuntu/etc, the Debian packagers have attempted to provide a wrapper to hide this difference in the x-terminal-emulator feature. If that applies to you, you could set TERMCMD to x-terminal-emulator. |
_codereview.110032 | So this is my first project.I made a Calculator using Tkinter. For the next version, I will try addingoops conceptsCustom parser for inputHere's the code #!/usr/bin/env python3.4from tkinter import *import parserroot = Tk()root.title('Calculator')i = 0def factorial(): Calculates the factorial of the number entered. whole_string = display.get() number = int(whole_string) fact = 1 counter = number try: while counter > 0: fact = fact*counter counter -= 1 clear_all() display.insert(0, fact) except Exception: clear_all() display.insert(0, Error)def clear_all(): clears all the content in the Entry widget display.delete(0, END)def get_variables(num): Gets the user input for operands and puts it inside the entry widget global i display.insert(i, num) i += 1def get_operation(operator): Gets the operand the user wants to apply on the functions global i length = len(operator) display.insert(i, operator) i += lengthdef undo(): removes the last entered operator/variable from entry widget whole_string = display.get() if len(whole_string): ## repeats until ## now just decrement the string by one index new_string = whole_string[:-1] print(new_string) clear_all() display.insert(0, new_string) else: clear_all() display.insert(0, Error, press AC)def calculate(): Evaluates the expression ref : http://stackoverflow.com/questions/594266/equation-parsing-in-python whole_string = display.get() try: formulae = parser.expr(whole_string).compile() result = eval(formulae) clear_all() display.insert(0, result) except Exception: clear_all() display.insert(0, Error!)root.columnconfigure(0,pad=3)root.columnconfigure(1,pad=3)root.columnconfigure(2,pad=3)root.columnconfigure(3,pad=3)root.columnconfigure(4,pad=3)root.rowconfigure(0,pad=3)root.rowconfigure(1,pad=3)root.rowconfigure(2,pad=3)root.rowconfigure(3,pad=3)display = Entry(root, font = (Calibri, 13))display.grid(row = 1, columnspan = 6 , sticky = W+E)one = Button(root, text = 1, command = lambda : get_variables(1), font=(Calibri, 12))one.grid(row = 2, column = 0)two = Button(root, text = 2, command = lambda : get_variables(2), font=(Calibri, 12))two.grid(row = 2, column = 1)three = Button(root, text = 3, command = lambda : get_variables(3), font=(Calibri, 12))three.grid(row = 2, column = 2)four = Button(root, text = 4, command = lambda : get_variables(4), font=(Calibri, 12))four.grid(row = 3 , column = 0)five = Button(root, text = 5, command = lambda : get_variables(5), font=(Calibri, 12))five.grid(row = 3, column = 1)six = Button(root, text = 6, command = lambda : get_variables(6), font=(Calibri, 12))six.grid(row = 3, column = 2)seven = Button(root, text = 7, command = lambda : get_variables(7), font=(Calibri, 12))seven.grid(row = 4, column = 0)eight = Button(root, text = 8, command = lambda : get_variables(8), font=(Calibri, 12))eight.grid(row = 4, column = 1)nine = Button(root , text = 9, command = lambda : get_variables(9), font=(Calibri, 12))nine.grid(row = 4, column = 2)cls = Button(root, text = AC, command = clear_all, font=(Calibri, 12), foreground = red)cls.grid(row = 5, column = 0)zero = Button(root, text = 0, command = lambda : get_variables(0), font=(Calibri, 12))zero.grid(row = 5, column = 1)result = Button(root, text = =, command = calculate, font=(Calibri, 12), foreground = red)result.grid(row = 5, column = 2)plus = Button(root, text = +, command = lambda : get_operation(+), font=(Calibri, 12))plus.grid(row = 2, column = 3)minus = Button(root, text = -, command = lambda : get_operation(-), font=(Calibri, 12))minus.grid(row = 3, column = 3)multiply = Button(root,text = *, command = lambda : get_operation(*), font=(Calibri, 12))multiply.grid(row = 4, column = 3)divide = Button(root, text = /, command = lambda : get_operation(/), font=(Calibri, 12))divide.grid(row = 5, column = 3)# adding new operationspi = Button(root, text = pi, command = lambda: get_operation(*3.14), font =(Calibri, 12))pi.grid(row = 2, column = 4)modulo = Button(root, text = %, command = lambda : get_operation(%), font=(Calibri, 12))modulo.grid(row = 3, column = 4)left_bracket = Button(root, text = (, command = lambda: get_operation((), font =(Calibri, 12))left_bracket.grid(row = 4, column = 4)exp = Button(root, text = exp, command = lambda: get_operation(**), font = (Calibri, 10))exp.grid(row = 5, column = 4)## To be added :# sin, cos, log, lnundo_button = Button(root, text = <-, command = undo, font =(Calibri, 12), foreground = red)undo_button.grid(row = 2, column = 5)fact = Button(root, text = x!, command = factorial, font=(Calibri, 12))fact.grid(row = 3, column = 5)right_bracket = Button(root, text = ), command = lambda: get_operation()), font =(Calibri, 12))right_bracket.grid(row = 4, column = 5)square = Button(root, text = ^2, command = lambda: get_operation(**2), font = (Calibri, 10))square.grid(row = 5, column = 5)root.mainloop()Any Suggestions on how could I improve upon it guys?Edit:Here's the link to the repo if anybody wants to download the executable for this.https://github.com/prodicus/pyCalc | Calculator using Tkinter | python;beginner;tkinter | null |
_webapps.76439 | As the title says, I have data (Q & A grouped by subject) that I have to export to a document file.As shown above, the source data on the left should be formatted like the example on the rightI'm looking for a free solution. Google helped me find THIS which looks deprecated according to comments. So 'I'll be very glad if at least you put me on the right path to realise this task given that I have some basic JS experience (but I've never scripted in GS). Edit.1:I started indeed learning how to script with google-apps since it's a time saver as long as I'm using google for almost everything xDAt the end I'll post the full code here to help any beginner else like me.For now i'm stuck at these points:I'm adding a title, then I'm trying to customize it's style (font, color, alignment), but it doesnt work as expected (not everything). Plus, it looks like that order matters :-/The following snippet gives the output in the picture:// Define a stylevar titleStyle1 = {};titleStyle1[DocumentApp.Attribute.FONT_FAMILY] = DocumentApp.FontFamily.COMIC_SANS_MS;titleStyle1[DocumentApp.Attribute.FOREGROUND_COLOR] = '#ff0000'; // RedtitleStyle1[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;titleStyle1[DocumentApp.Attribute.HEADING] = DocumentApp.ParagraphHeading.TITLE;var titleStyle2 = {};titleStyle2[DocumentApp.Attribute.HEADING] = DocumentApp.ParagraphHeading.TITLE;titleStyle2[DocumentApp.Attribute.FONT_FAMILY] = DocumentApp.FontFamily.COMIC_SANS_MS;titleStyle2[DocumentApp.Attribute.FOREGROUND_COLOR] = '#ff0000'; // RedtitleStyle2[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;var titleStyle3 = {};titleStyle3[DocumentApp.Attribute.HEADING] = DocumentApp.ParagraphHeading.TITLE;titleStyle3[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;titleStyle3[DocumentApp.Attribute.FONT_FAMILY] = DocumentApp.FontFamily.COMIC_SANS_MS;titleStyle3[DocumentApp.Attribute.FOREGROUND_COLOR] = '#ff0000'; // Redvar titleStyle4 = {};titleStyle4[DocumentApp.Attribute.FONT_FAMILY] = DocumentApp.FontFamily.COMIC_SANS_MS;titleStyle4[DocumentApp.Attribute.FOREGROUND_COLOR] = '#ff0000'; // RedtitleStyle4[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;//titleStyle4[DocumentApp.Attribute.HEADING] = DocumentApp.ParagraphHeading.TITLE;// Create and open a new document.var doc = DocumentApp.create(outputDocDesiredName);var body = doc.getBody();body.setAttributes(docStyle)// Append a document header paragraph.body.appendParagraph('Test title').setAttributes(titleStyle1);body.appendParagraph('Test title').setAttributes(titleStyle2);body.appendParagraph('Test title').setAttributes(titleStyle3);body.appendParagraph('Test title').setAttributes(titleStyle4);Notice that in the last case, only when DocumentApp.Attribute.HEADING isnt set that the other styles are taken into account. I wonder why :>Instead of setting everytime the font COMIC_SANS_MS for every added text, is there a way to set a default font (among other attributes) for the newly created document ?The following code does change nothing:var docStyle = {};docStyle[DocumentApp.Attribute.FONT_FAMILY] = DocumentApp.FontFamily.COMIC_SANS_MS;var body = doc.getBody();body.setAttributes(docStyle); | Generate a formatted Google document from spreadsheet | google spreadsheets;google apps script;google documents | There are several add-ons for Google Documents and Sheets that already do that. One of them is Autocrat.Some of these add-ons work on merge model: a template and data source.The template holds the formatting, fixed text and placeholders for variable text.The spreadsheet is used as the data source, sometimes it has the menu options to trigger the merge function.ReferencesOverview of add-ons - Docs editors Help |
_cstheory.2880 | I have a list of tracks (model railroad tracks) with different length, example: TrackA on 3.0cm, TrackB on 5.0cm, TrackC on 6.5cm, TrackD on 10.5cmThen I want to find out of what kind of track I should put together to get from point A to point B with a given distance and a margin. And I should also be able to a prioritizes the use of track type.Example; Distance from point A to B is 1.7m, and I have lot of TrackC and few of TrackB. And I will allow a margin on +/- 0.5cm to the distance.What kind of tracks should I use, and how many of each track, and how many combination do I have, sorted after the track where I have most of.I have Google after some C# help using genetic algorithm, but I am lost in, how I can implement this in a good method.Or just a mathematical method, that can solve my problem..Please help.. | Find the right/best track combination for a given distance, using a genetic algorithm or ?. | ds.algorithms;optimization | null |
_codereview.18040 | explain:from start day till now I've got 7.7 mb size, how long it will be to make it 10 gb sizeopen Systemlet dd = (DateTime.Now - DateTime.Parse(12/09/2012)).Dayslet oneday = 7.7 / Convert.ToDouble(dd)let in10gb = Convert.ToInt32( Math.Round (10.0 * 1024.0 / oneday) )let years = Convert.ToInt32( Math.Round (float in10gb / 365.0) )let mutable months = Convert.ToInt32( Math.Round (float (in10gb - years * 365) / 30.0) )let days = let d = in10gb - years * 365 - months * 30 if d > 0 then d else month = month - 1; (30 - d)printf %d years %d months %d days years months daysConsole.ReadKey() |> ignoreAlso / 30.0 for months is dirty hack here... I'm not sure how to avoid it in easy way. | TimeSpan don't support years so how do I deal with it? Is there could be smarter solution? | f# | I would propose an alternative method of calculating your time, using seconds and DateTimes:open Systemlet startDate = DateTime.Parse (2012-09-12)let now = DateTime.Now;let currentRuntime = (now - startDate).TotalSecondslet timePerGig = currentRuntime / 7.7;let tenDate = startDate + TimeSpan.FromSeconds (10.0 * timePerGig);With that done, you can do whatever you like to represent the final date relative to the current date.An overly simplistic example is as follows:printf %d years %d months %d days (finalDate.Year - now.Year) (finalDate.Month - now.Month) (finalDate.Day - now.Day)Of course, you would have to account for roll-over for days and months in any final piece of code, but it illustrates how you could pull the date parts back out. |
_webmaster.44142 | I have a client that asked me to move his domains to a new private server, this is my first experience on using private name servers so I am unsure if I am doing something incorrectly.According to what I have read, at my registrar I have to register the private name servers, in this case ns1.vetology.net and ns2.vetology.net which I have done last Wednesday and testing the name servers they are pointing to the correct IPhttp://reports.internic.net/cgi/whois?whois_nic=NS1.VETOLOGY.NET&type=nameserverhttp://reports.internic.net/cgi/whois?whois_nic=NS2.VETOLOGY.NET&type=nameserver So that means that Godaddy did it's job and registered the nameservers, the very same day I pointed a domain which is not in use at the moment.dogcatmri.com to the private nameservers, since them I have been receiving a not found error on some browsers and chrome gives me a Error 137 (net::ERR_NAME_RESOLUTION_FAILED): Unknown error..First I thought well I have to wait for both the private name servers to propagate and then the domain DNS change to propagate but since Wednesday up to today it seems a very long time for me.Note that if I use Google DNS servers 8.8.8.8 the domain resolves, but the domain does not resolve in any other way.So my questions is, does the fact that using Google's dns resolve the domain means that the NS servers are setup correctly and I just have to wait for propagation to complete and it is taking an awful lot of time or there is something not setup right but Google's DNS uses some other sort of domain resolution and there maybe something wrong on my setup?This is some further testing I did, the command was run from the host machine:[root@web ~]# dig dogcatmri.com; <<>> DiG 9.3.6-P1-RedHat-9.3.6-20.P1.el5_8.6 <<>> dogcatmri.com;; global options: printcmd;; Got answer:;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 60662;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0;; QUESTION SECTION:;dogcatmri.com. IN A;; Query time: 325 msec;; SERVER: 4.2.2.2#53(4.2.2.2);; WHEN: Mon Feb 25 04:27:53 2013;; MSG SIZE rcvd: 31Edit 1:I am not sure if I am doing something incorrectly but my assumption is that given the following setupdomain.com domain2.com server1 server2 So server1 is hosting domain.com properlyserver2 is hosting ns1.domain.com and ns22.domain.comdomain.com has nameservers ns1.domain.com and ns2.domain.comNot moving domain.com to point to ns1.domain.com and ns2.domain.com will cause the other domains not to resolve or the two things are independent?Just to clarify, my reason not to move domain.com at the moment is because domain.com is a live site and I don't want to mess with it unless I am 100% sure the server is responding as expected. | Private NS propagation | dns;nameserver | Okay, so I figured out what the problem was, basically I had added all records correctly in both server and registrar, however the fact that I did not point vetology.net to the ns1 and ns2.vetology.net servers was causing the problem, so all I had to do was add A records for ns1.vetology.net, and ns2.vetology.net in the old server to point to the new server and the sites started resolving. |
_unix.248837 | Very new to regex and have a directory of files that I would like run this regex on but don't know how. help would be great.This is the regex:(?<=#).* | Regex on multiple files | regular expression | The regex pattern (?<=#).* is a zero width positive look-behind pattern that requires PCRE (Perl Compatible Regular Expression) supported grep to be implemented. If your grep supports -P option then you can do it.Seeing the pattern, i think you might also need -o option to get only the matched portion, as (?<=#) makes sure there is a # before the desired portion .*.So you can do recursive grep (-r):grep -rPo '(?<=#).*' /directory |
_softwareengineering.68558 | I just read hibernate reference and they say that you should use constans for HQL queries. However that is not always possible, for example if you do search function and have 10 criterias (not jpa criterias, just columns you are searching by). I bet you can do some hacky HQL that is transformed into badly performing SQL, but I feel that is not the best choice.I do know you can use The Criteria API, but its not as powerfull as HQL and some people just don't like it (I'm one of them).How you do it in Yours applications?I mean code like (its just an example!)String hql = from Biuro where ;List parameters = ...if (dateFrom!=null){ hql += dateFrom>=? ; parameters.add(dateFrom);} | Hibernate building HQL queries | java;hibernate | null |
_reverseengineering.8100 | Looking around for IR's used for reverse engineering, I find quite a few interesting ones. Assuming that I have a function that I'm trying to reverse engineer, I'm considering the following approach.Lift the assembly to an IR, run an optimisation pass on it and convert it back into assembly. How hard would it be to implement something like this? Are there any IRs that you'd recommend. I'm guessing that being able to lift the assembly code into an LLVM IR would be pretty useful and one could run the LLVM optimisation passes on it.Do you have any suggestions on this? | Running an optimization pass on an IR | program analysis | null |
_codereview.165680 | I'm currently writing an insert function for a linked list. The code works but I would like to know if there is any way I can improve this code and at the same time covering all the special cases.`private class Node{ Node next; int data; public Node(int data, Node next){ this.data = data; this.next = next; } public Node(){ this.next = null; this.data = 0; }}`public void insert(int data) { if(first == null || first.item != data){ first = new Node(data, first); } else{ Node x = first; while(x.next != null && x.next.item != data){ x.next = new Node(data, x.next); } x = x.next; }} | Inserting a Node in a singly linked list | java;linked list | null |
_unix.102466 | I have Ubuntu 13.04 running in a VM in VirtualBox. Originally, I was just trying it out, but now I've started using it a lot, and I have many of my programs and files in it. Is it possible to transfer this to a partition on my hard drive? Also, (this would be much more preferable), is it possible for me to transfer it to a bootable USB?My System: Ubuntu 13.04 64 bit running in VirtualBox Windows 8.1 Pro 64 Bit | Transferring Operating System from VM to Physical System | ubuntu;virtualbox;bootable | The terminology you're looking for is often called physical to virtual or virtual to physical. It's often shortened to P2V and V2P.There's a tutorial on how to do this for VMware and Virtualbox over on the AskUbuntu site. The Q&A is titled: Migrate from a virtual machine (VM) to a physical system.Migrating a Windows GuestI found these instructions for migrating a Windows VM V2P. They're untested by me but seem plausible. The tutorial is titled: V2P Virtual to Physical.This is an easy tutorial on how to take a Windows installation in Virtual Box, or any other Virtual software for that matter, and turn it into a physical machine. This has been tested on Windows XP x86 and x64 as well as Windows Vista,7 X86 and x64. This tutorial is assuming you have advanced knowledge of installing Windows/Virtual OSes/changing boot settingsetc etc OK? Now lets get started.These are the steps, verbatim.1) First off, make sure you have the machine configured the way you want before making an image of it. This is assuming you are using it to test software or make an image for multiple computers. Install the software you want and the updates you need as well as any antivirus software. An important note when installing software: Do not install the Virtual Machine Add Ons (VirtualBox) or VMware tools (VMWare) as this is almost always likely to cause a bluescreen due to the IDE Controller driver being totally, and not even remotely the same, as a physical IDE controller. 2) Download Macrium Reflect Free Edition. (do a Google search, everyone knows how!) Then install it on your Virtual Machine. Right click on the virtual drive you installed Windows too and right click and choose Create Image of this Disk Some Side notes: I would recommend mapping an external drive as the place of backup for this image. Plug in a USB hard drive or map a network drive in the Virtual Machine settings. (maybe Ill do a tutorial on this). I say an external drive because making a backup on the same drive the virtual machine is running off of could cause the time it takes to copy the backup increase drastically. 3) After the image has been successfully created, restore that image to the hard drive you will be using to install in your physically machine. To do this, right click on the image that Macrium has created and choose Restore Partition. When you go through the steps, one of the options asks you to assign a drive letter. Click Do Not assign a drive letter If you Assign it anything other than C, itll causes issues since thats what your virtual machine drive letter was to being with. You cant assign it C:/ anyways because the computer you are on most like has that drive letter taken already. The other option to look out for is when it asks if you want to restore the MBR with a default one. ALWAYS choose to restore the MBR with the one from the backup.4) After that has completed successfully, go into Windows Disk management in Windows and right click the drive you just restored the image too as Active. This will tell the BIOS of the machine you are placing this drive in that it has a bootable partition on it. If you dont set it to active, the BIOS will tell you that there is no boot device available.5) Go ahead and put the hard drive in the computer you wish to boot it from. Make sure all the plugs are in the proper place and IDE is configured properly (AKA Master and Slave jumpers if on IDE)6) Next step, before you even turn on the computer, is to pop in your windows CD. Whether is be Windows XP or Windows Vista/7. Always remember to use the right version of the architecture that corresponds to the one you used when installed in a virtual machine. I.E. if you installed Windows 7 x86 then use a Windows 7 x86 USB/DVD for the next step.7) Boot from the proper DVD/CD and choose Repair your Computerand choose Command Prompt (Both Windows XP an Vista/7)8) now type bootrec /fixboot9) Restart your laptop/desktop and windows should start booting up! |
_reverseengineering.16012 | Below is a part of a code that I reversed with repy2exe and I want to understand what it does and especially how to decode the value in the secret variable:using = [ 'Mg==\n', 'MTA1\n', 'Nzg=\n', 'ODI=\n', 'NzM=\n', 'Njg=\n', 'Nzk=\n', 'OTg=\n', 'ODg=\n', 'Njc=\n', 'Njg=\n', 'ODM=\n', 'MTk=\n', 'MTc=\n', 'MTY=\n', 'MjI=\n']secret = 'BZh91AY&SY\xf2\xbfIg\x00\x00\x01\x89\x80\x05\x002\x00\x08\x00 \x00!\x80\x0c\x01[6\xe2\xeeH\xa7\n\x12\x1eW\xe9,\xe0'pas = raw_input('Please Enter The Password:')a = ''for i in range(len(pas)): a += pas[i]coun = 0win = 16 | Can anyone help me identify and decode this string? | disassembly;binary analysis;python;entropy | Although the code is clearly incomplete, some things can be guessed:1) The strings ending with == are most likely base64-encoded (Base64 uses = for padding). Let's try to decode them.>>>x = [a.decode('base64') for a in using]'2', '105', '78', '82', '73', '68', '79', '98', '88', '67', '68', '83', '19', '17', '16', '22']So they decode to string representations of some numbers. Not sure if this means anything, we need to see how they're used.2) The BZ sequence hints at Bzip2. We can try to decompress it as such:>>> import bz2>>> bz2.decompress(secret)'base64'And we're back to square one. |
_codereview.128741 | I have a winforms app and I've been using the following approach to update controls on the main form from worker threads:GamepadManager class has:public static event EventHandler OnGamepadConnected;Main app class has:GamepadManager.OnGamepadConnected += OnGamepadConnected;private void OnGamepadConnected(){ Invoke((Action)(() => { gamepadStatusLabel.Text = Connected; }));}That looks kinda bad, but without the Invoke thing I get a cross-thread operation exception because I can't update controls from worker threads (from where the call comes from).Is there a way to reduce the number of parentheses used? Maybe there's a whole other, better way to do this?Previously I've been using timers to check for every small thing like that, which ran on GUI thread (apparently?) and there was no trouble simply calling controlName.Text = something; without all the Invoke() stuff. But that means even more code and more processing cost due to constant checks. | Improving GUI update call from a worker thread in winforms | c#;multithreading;winforms;gui | null |
_unix.274648 | I've installed Terminator from the homebrew/gui tap, but when I ran it, it raised this error:You need to install the python bindings for gobject, gtk and pango to run Terminator.I edited /usr/local/bin/terminator (it's just Python) to display the error message, and I got this:dlopen(/usr/local/lib/python2.7/site-packages/glib/_glib.so, 2): Library not loaded: /usr/local/lib/libgobject-2.0.0.dylib Referenced from: /usr/local/lib/python2.7/site-packages/glib/_glib.so Reason: Incompatible library version: _glib.so requires version 4401.0.0 or later, but libgobject-2.0.0.dylib provides version 3401.0.0The fact that this is showing up does not surprise me, as I've had a similar error with pretty much every Python program that uses GTK.Let me know if I should ask on Ask Different instead. | Terminator installed via Homebrew Incompatible library version | osx;python;gtk | null |
_cstheory.17545 | I posted this earlier on MSE, but it was suggested that here may be a better place to ask.Universal approximation theorem states that the standard multilayer feed-forward network with a single hidden layer, which contains finite number of hidden neurons, is a universal approximator among continuous functions on compact subsets of Rn, under mild assumptions on the activation function.I understand what this means, but the relevant papers are too far over my level of math understanding to grasp why it is true or how a hidden layer approximates non-linear functions.So, in terms little more advanced than basic calculus and linear algebra, how does a feed-forward network with one hidden layer approximate non-linear functions? The answer need not necessarily be totally concrete. | Universal Approximation Theorem Neural Networks | approximation algorithms;ne.neural evol;na.numerical analysis | Cybenko's result is fairly intuitive, as I hope to convey below; what makes things more tricky is he was aiming both for generality, as well as a minimal number of hidden layers. Kolmogorov's result (mentioned by vzn) in fact achieves a stronger guarantee, but is somewhat less relevant to machine learning (in particular, it does not build a standard neural net, since the nodes are heterogeneous); this result in turn is daunting since on the surface it is just 3 pages recording some limits and continuous functions, but in reality it is constructing a set of fractals. While Cybenko's result is unusual and very interesting due to the exact techniques he uses, results of that flavor are very widely used in machine learning (and I can point you to others).Here is a high-level summary of why Cybenko's result should hold.A continuous function on a compact set can be approximated by a piecewise constant function.A piecewise constant function can be represented as a neural net as follows. For each region where the function is constant, use a neural net as an indicator function for that region. Then build a final layer with a single node, whose input linear combination is the sum of all the indicators, with a weight equal to the constant value of the corresponding region in the original piecewise constant function.Regarding the first point above, this can be taken as the statement a continuous function over a compact set is uniformly continuous. What this means to us is you can take your continuous function over $[0,1]^d$, and some target error $\epsilon>0$, then you can grid $[0,1]^d$ at scale $\tau>0$ (ending up with roughly $(1/\tau)^d$ subcubes) so that a function which is constant over each subcube is within $\epsilon$ of the target function.Now, a neural net can not precisely represent an indicator, but you can get very close. Suppose the transfer function is a sigmoid. (Transfer function is the continuous function you apply to a linear combination of inputs in order to get the value of the neural net node.) Then by making the weights huge, you output something close to 0 or close to 1 for more inputs. This is consistent with Cybenko's development: notice he needs the functions involved to equal 0 or 1 in the limit: by definition of limit, you get exactly what I'm saying, meaning you push things arbitrarily close to 0 or 1.(I ignored the transfer function in the final layer; if it's there, and it's continuous, then we can fit anything mapping to $[0,1]$ by replacing the constant weights with the something in the inverse image of that constant according to the transfer function.)Notice that the above may seem to take a couple layers: say, 2 to build the indicators on cubes, and then a final output layer. Cybenko was trying for two points of generality: minimal number of hidden layers, and flexibility in the choice of transfer function. I've already described how he works out flexibility in transfer function.To get the minimum number of layers, he avoids the construction above, and instead uses functional analysis to develop a contradiction.Here's a sketch of the argument.The final node computes a linear combination of the elements of the layer below it, and applies a transfer function to it. This linear combination is a linear combination of functions, and as such, is itself a function, a function within some subspace of functions, spanned by the possible nodes in the hidden layer.A subspace of functions is just like an ordinary finite-dimensional subspace, with the main difference that it is potentially not a closed set; that's why cybenko's arguments all take the closure of that subspace. We are trying to prove that this closure contains all continuous functions; that will mean we are arbitrarily close to all continuous functions.If the function space were simple (a Hilbert space), we could argue as follows. Pick some target continuous function which is contradictorily supposed to not lie in the subspace, and project it onto the orthogonal complement of the subspace. This residual must be nonzero. But since our subspace can represent things like those little cubes above, we can find some region of this residual, fit a little cube to it (as above), and thereby move closer to our target function. This is a contradiction since projections choose minimal elements. (Note, I am leaving something out here: Cybenko's argument doesn't build any little cubes, he handles this in generality too; this is where he uses a form of the Riesz representation theorem, and properties of the transfer functions (if I remember correctly, there is a separate lemma for this step, and it is longer than the main theorem).) We aren't in a Hilbert space, but we can use the Hahn-Banach theorem to replace the projection step above (note, proving Hahn-Banach uses the axiom of choice).Now I'd like to say a few things about Kolmogorov's result. While this result does not apparently need the sort of background of Cybenko's, I personally think it is much more intimidating.Here is why. Cybenko's result is an approximation guarantee: it does not say we can exactly represent anything. On the other hand, Kolmogorov's result is provides an equality. More ridiculously, it says the size of the net: you need just $\mathcal O(d^2)$ nodes. To achieve this strengthening, there is a catch of course, the one I mentioned above: the network is heteregeneous, by which I mean all the transfer functions are not the same.Okay, so with all that, how can this thing possible work?!Let's go back to our cubes above. Notice that we had to bake in a level of precision: for every $\epsilon>0$, we have to go back and pick a more refined $\tau >0$. Since we are working with (finite) linear combinations of indicators, we are never exactly representing anything. (things only get worse if you include the approximating effects of sigmoids.)So what's the solution? Well, how about we handle all scales simultaneously? I'm not making this up: Kolmogorov's proof is effectively constructing the hidden layer as a set of fractals. Said another way, they are basically space filling curves which map $[0,1]$ to $[0,1]^d$; this way, even though we have a combination of univariate functions, we can fit any multivariate function. In fact, you can heuristically reason that $\mathcal O(d^2)$ is correct via a ridiculous counting argument: we are writing a continuous function from $\mathbb{R}^d$ to $\mathbb R$ via univariate continuous functions, and therefore, to capture all inter-coordinate interactions, we need $\mathcal O(d^2)$ functions...Note that Cybenko's result, due to using only one type of transfer function, is more relevant to machine learning. Theorems of this type are very common in machine learning (vzn suggested this in his answer, however he referred to Kolmogorov's result, which is less applicable due to the custom transfer functions; this is weakened in some more fancy versions of Kolmogorov's result (produced by other authors), but those still involve fractals, and at least two transfer functions).I have some slides on these topics, which I could post if you are interested (hopefully less rambly than the above, and have some pictures; I wrote them before I was adept with Hahn-Banach, however). I think both proofs are very, very nice. (Also, I have another answer here on these topics, but I wrote it before I had grokked Kolmogorov's result.) |
_softwareengineering.53282 | Every time I've finished a project, there is always something that I've learned (otherwise I don't find it very motivating). But I can't remember everything, and much later I may stumble across the same problem that I encountered in a previous project but no longer how I solved it (or at least what attempts I made).So would it be a good idea to write this down in a journal of some sort? I know that writing stuff down feels like writing documentation (which not everyone enjoys doing), and hope our memory to serve us when needed. But having it documented, it could be shared with other programmers and learn what lessons they learned.So, what do you think? | Should every programmer keep a Lessons Learned journal? | experience;documentation;journal | null |
_softwareengineering.159007 | In a EF 4.1 Code First tutorial the following code is given:public class Department{ public int DepartmentId { get; set; } [Required] public string Name { get; set; } public virtual ICollection<Collaborator> Collaborators { get; set; }}Then it is explained that the fluent interface is more flexible: Data Annotations are definitely easy to use but it is preferable to use a programmatic approach that provides much more flexibility.The example of using the fluent interface is then given:protected override void OnModelCreating(ModelBuilder modelBuilder){ modelBuilder.Entity<Department>().Property(dp => dp.Name).IsRequired(); modelBuilder.Entity<Manager>().HasKey(ma => ma.ManagerCode); modelBuilder.Entity<Manager>().Property(ma => ma.Name) .IsConcurrencyToken(true) .IsVariableLength() .HasMaxLength(20);}I can't understand why the fluent interface is supposedly better. Is it really? From my perspective it looks like the data annotations are more clear, and have more of a clean semantic feel to it.My question is why would a fluent interface be a better option than using attributes, especially in this case?(Note: I'm quite new to the whole concept of fluent interfaces, so please expect no prior knowledge on this.)Reference: http://codefirst.codeplex.com/ | Are fluent interfaces more flexible than attributes and why? | c#;coding style | Data annotations are static, for instance this method declaration cannot change at runtime: [MinLength(5)] [MaxLength(20,ErrorMessage=Le nom ne peut pas avoir plus de 20 caractres)] public new string Name { get; set; }The fluent interface can be dynamic: if (longNamesEnabled) { modelBuilder.Entity<Manager>().Property(ma => ma.Name) .HasMaxLength(100); } else { modelBuilder.Entity<Manager>().Property(ma => ma.Name) .HasMaxLength(20); }not to mention the code can be reused between properties. |
_ai.3442 | I might be wrong, but if we have well designed A.I. then why won't the USA government allow it to be witnessed in the public. | Why is it illegal for google's autonomous car to drive on the road by itself? | google | Good question, however, it is based on a false fact. In Michigan, it is currently legal (under certain conditions described here ) for an autonomous car to operate without a driver. The reason that the federal government has not enacted any direct legislation (although they have enacted guidelines) on autonomous cars is because it is still a developing technology (as great as those Cruise videos look, I wouldn't trust most companies working on the technology to have driverless cars on the road without operators) and that it arguably falls under the state governments jurisdictions. Some companies have appealed to the House to pass national legislation to allow autonomous testing (GM,Toyota,Lyft), but nothing has come of it yet. |
_scicomp.5591 | I have the following algorithm given:Input: Regular Matrix $A \in \mathbb R^{n,n}$Output: LU-Decomposition of A = LUfor k = 1, . . . , n dofor j = k, . . . , n do$r_{kj} = a_{kj} \sum_{i=1}^{k-1} l_{ki}r_{ij}$ end forfor i = k + 1, . . . , n do$l_{ik} = (a_{ik} \sum_{j=1}^{k-1} l_{ij}r_{jk})/r_{kk}$ end forend forGiven every elementary operation (+,-,*,/) has the cost 1, how can it be derived that the complexity of this algorithm is 2/3n^3 - 1/2n^2 - 1/6n? I am really interested in understanding how such a closed formulae for the complexity is derived. | How to calculate the complexity of a given Algorithm | algorithms;complexity | null |
_unix.290405 | One part of /usr/share/X11/xkb/symbols/us starts with xkb_symbols dvorak { and ends with the closing curly bracket }; which line-number I want to find. partial alphanumeric_keysxkb_symbols dvorak { name[Group1]= English (Dvorak); key <TLDE> { [ grave, asciitilde, dead_grave, dead_tilde ] }; key <AE01> { [ 1, exclam ] }; key <AE02> { [ 2, at ] }; key <AE03> { [ 3, numbersign ] }; key <AE04> { [ 4, dollar ] }; key <AE05> { [ 5, percent ] }; key <AE06> { [ 6, asciicircum, dead_circumflex, dead_circumflex ] }; key <AE07> { [ 7, ampersand ] }; key <AE08> { [ 8, asterisk ] }; key <AE09> { [ 9, parenleft, dead_grave] }; key <AE10> { [ 0, parenright ] }; key <AE11> { [ bracketleft, braceleft ] }; key <AE12> { [ bracketright, braceright, dead_tilde] }; key <AD01> { [ apostrophe, quotedbl, dead_acute, dead_diaeresis ] }; key <AD02> { [ comma, less, dead_cedilla, dead_caron ] }; key <AD03> { [ period, greater, dead_abovedot, periodcentered ] }; key <AD04> { [ p, P ] }; key <AD05> { [ y, Y ] }; key <AD06> { [ f, F ] }; key <AD07> { [ g, G ] }; key <AD08> { [ c, C ] }; key <AD09> { [ r, R ] }; key <AD10> { [ l, L ] }; key <AD11> { [ slash, question ] }; key <AD12> { [ equal, plus ] }; key <AC01> { [ a, A, adiaeresis, Adiaeresis ] }; key <AC02> { [ o, O ] }; key <AC03> { [ e, E ] }; key <AC04> { [ u, U ] }; key <AC05> { [ i, I ] }; key <AC06> { [ d, D ] }; key <AC07> { [ h, H ] }; key <AC08> { [ t, T ] }; key <AC09> { [ n, N ] }; key <AC10> { [ s, S ] }; key <AC11> { [ minus, underscore ] }; key <AB01> { [ semicolon, colon, dead_ogonek, dead_doubleacute ] }; key <AB02> { [ q, Q ] }; key <AB03> { [ j, J ] }; key <AB04> { [ k, K ] }; key <AB05> { [ x, X ] }; key <AB06> { [ b, B ] }; key <AB07> { [ m, M ] }; key <AB08> { [ w, W ] }; key <AB09> { [ v, V ] }; key <AB10> { [ z, Z ] }; key <BKSL> { [ backslash, bar ] };};I can find the start of the environment which returns 192grep -n 'xkb_symbols dvorak' /usr/share/X11/xkb/symbols/us | cut -d : -f1 > /tmp/lineNumberStartEnvironmentI do but blank output# http://unix.stackexchange.com/a/147664/16920grep -zPo 'pin\(ABC\) (\{([^{}]++|(?1))*\})' /usr/share/X11/xkb/symbols/usPseudocodeGo first to the linenumber given by file /tmp/lineNumberStartEnvironment. Find the closing bracket of the thing located at the line of /tmp/lineNumberStartEnvironment. do this with the data content in the body but also with the complete file /usr/share/X11/xkb/symbols/usAttempt for heredoc until next line [cas, Kusalananda]I do where I do not know what I should put to the deliminator; -n returns blank toosed -n -f - /usr/share/X11/xkb/symbols/us <<END_SED | cut -f1/xkb_symbols dvorak {/,/^};/{ /xkb_symbols dvorak {/= /^};/=}END_SEDbut blank output. Systems: Ubuntu 16.04Grep: 2.25 | grep: How to find Closing Bracket? | text processing;awk;sed;grep | This sed script prints the line number of the line matching /^};/ in the range of lines from /xkb_symbols dvorak {/ to the next /^};/ (which will be the same }; as the one we get the line number for):/xkb_symbols dvorak {/,/^};/{ /^};/=}If you need both start and end line numbers:/xkb_symbols dvorak {/,/^};/{ /xkb_symbols dvorak {/= /^};/=}$ sed -n -f tiny_script.sed /usr/share/X11/xkb/symbols/us192248Alternatively:$ sed -n -f - /usr/share/X11/xkb/symbols/us <<END_SED/xkb_symbols dvorak {/,/^};/{ /xkb_symbols dvorak {/= /^};/=}END_SEDEDIT: To get these two numbers in a variable, assuming you're using Bash:pos=( $( sed -n -f - /usr/share/X11/xkb/symbols/us <<END_SED /xkb_symbols dvorak {/,/^};/{ /xkb_symbols dvorak {/= /^};/= }END_SED) )echo start = ${pos[0]}echo end = ${pos[1]}Also, hi! Another Dvorak user! |
_codereview.165499 | This C program implements a so-called natural merge sort that identifies existing runs in the list and exploits them in order to sort in sub-linearithmic time whenever possible. The running time of this sort is \$\Theta(n \log m)\$, where \$n\$ is the length of the list and \$m\$ is the number of ordered runs (ascending or descending sublists). Since \$m\$ is at most \$\lceil n / 2 \rceil\$, this runs in worst-case linearithmic time. Here we go:linked_list.h#ifndef LINKED_LIST_H#define LINKED_LIST_H#include <stdlib.h>typedef struct linked_list_node_t { int value; struct linked_list_node_t* next;} linked_list_node_t;typedef struct { linked_list_node_t* head; linked_list_node_t* tail; size_t size;} linked_list_t;void linked_list_init(linked_list_t* list);void linked_list_append(linked_list_t* list, int value);void linked_list_sort(linked_list_t* list);int linked_list_is_sorted(linked_list_t* list);void linked_list_display(linked_list_t* list);#endif /* LINKED_LIST_H */linked_list.c#include linked_list.h#include <stdlib.h>#include <stdio.h>void linked_list_init(linked_list_t* list){ list->head = NULL; list->tail = NULL;}void linked_list_append(linked_list_t* list, int value){ linked_list_node_t* node = malloc(sizeof *node); node->value = value; node->next = NULL; if (list->head) { list->tail->next = node; list->tail = node; } else { list->head = node; list->tail = node; } list->size++;}int linked_list_is_sorted(linked_list_t* list){ linked_list_node_t* node1; linked_list_node_t* node2; if (list->size < 2) { return 1; } node1 = list->head; node2 = node1->next; while (node2) { if (node1->value > node2->value) { return 0; } node1 = node2; node2 = node2->next; } return 1;}void linked_list_display(linked_list_t* list){ char* separator = ; for (linked_list_node_t* node = list->head; node; node = node->next) { printf(%s%d, separator, node->value); separator = , ; }}static linked_list_node_t* reverse(linked_list_node_t* head){ linked_list_node_t* new_head = head; linked_list_node_t* tmp_head; tmp_head = head; head = head->next; tmp_head->next = NULL; while (head) { tmp_head = head; head = head->next; tmp_head->next = new_head; new_head = tmp_head; } return new_head;}static linked_list_node_t* merge(linked_list_node_t* left_list, linked_list_node_t* right_list){ linked_list_node_t* merged_head = NULL; linked_list_node_t* merged_tail = NULL; linked_list_node_t* tmp_node; if (left_list->value < right_list->value) { merged_head = left_list; merged_tail = left_list; left_list = left_list->next; } else { merged_head = right_list; merged_tail = right_list; right_list = right_list->next; } while (left_list && right_list) { if (left_list->value < right_list->value) { tmp_node = left_list; left_list = left_list->next; merged_tail->next = tmp_node; merged_tail = tmp_node; } else { tmp_node = right_list; right_list = right_list->next; merged_tail->next = tmp_node; merged_tail = tmp_node; } } // Add the rest to the merged list: if (left_list) { merged_tail->next = left_list; } else { merged_tail->next = right_list; } return merged_head;}typedef struct { linked_list_node_t** run_length_array; size_t head_index; size_t tail_index; size_t size; size_t capacity;} run_list_t;static void run_list_enqueue(run_list_t* run_list, linked_list_node_t* run_head){ run_list->run_length_array[run_list->tail_index] = run_head; run_list->tail_index = (run_list->tail_index + 1) % run_list->capacity; run_list->size++;}static linked_list_node_t*scan_ascending_run(run_list_t* run_list, linked_list_node_t* run_start_node){ linked_list_node_t* node1 = run_start_node; linked_list_node_t* probe; linked_list_node_t* before_probe = NULL; int last_read_integer = run_start_node->value; probe = node1->next; while (probe && last_read_integer <= probe->value) { last_read_integer = probe->value; before_probe = probe; probe = probe->next; } if (probe) { if (before_probe) { before_probe->next = NULL; } } run_list_enqueue(run_list, run_start_node); return probe;}static linked_list_node_t*scan_descending_run(run_list_t* run_list, linked_list_node_t* run_start_node){ linked_list_node_t* node1 = run_start_node; linked_list_node_t* probe; linked_list_node_t* before_probe = NULL; int last_read_integer = run_start_node->value; probe = node1->next; while (probe && last_read_integer >= probe->value) { last_read_integer = probe->value; before_probe = probe; probe = probe->next; } if (probe) { if (before_probe) { before_probe->next = NULL; } } run_start_node = reverse(run_start_node); run_list_enqueue(run_list, run_start_node); return probe;}static void run_list_build(run_list_t* run_list, linked_list_t* list){ linked_list_node_t* node1; linked_list_node_t* node2; linked_list_node_t* tmp_node; run_list->capacity = list->size / 2 + 1; run_list->size = 0; run_list->run_length_array = malloc(run_list->capacity * sizeof(linked_list_node_t*)); run_list->head_index = 0; run_list->tail_index = 0; node1 = list->head; node2 = node1->next; while (node1) { node2 = node1->next; if (!node2) { run_list_enqueue(run_list, node1); return; } // Get run direction (ascending 1,2,3... or descending 3,2,1): if (node1->value <= node2->value) { node1 = scan_ascending_run(run_list, node1); } else { node1 = scan_descending_run(run_list, node1); } }}static linked_list_node_t* run_list_dequeue(run_list_t* run_list){ linked_list_node_t* ret = run_list->run_length_array[run_list->head_index]; run_list->head_index = (run_list->head_index + 1) % run_list->capacity; run_list->size--; return ret;}static size_t run_list_size(run_list_t* run_list){ return run_list->size;}void linked_list_sort(linked_list_t* list){ run_list_t run_list; linked_list_node_t* left_run; linked_list_node_t* right_run; linked_list_node_t* merged_run; if (!list || list->size < 2) { // Trivially sorted or non-existent list once here. return; } run_list_build(&run_list, list); while (run_list_size(&run_list) != 1) { left_run = run_list_dequeue(&run_list); right_run = run_list_dequeue(&run_list); merged_run = merge(left_run, right_run); run_list_enqueue(&run_list, merged_run); } list->head = run_list_dequeue(&run_list);}main.c#include linked_list.h#include <stdio.h>#include <stdlib.h>#include <time.h>#include <sys/time.h>void load_linked_list(linked_list_t* list, size_t len){ size_t i; int value; srand((unsigned int) time(NULL)); for (i = 0; i < len; ++i) { value = rand(); linked_list_append(list, value); }}void load_presorted_list(linked_list_t* list, size_t len){ int i; size_t chunk_length = len / 4; for (i = 0; i < len; ++i) { linked_list_append(list, i % chunk_length); }}static size_t milliseconds(){ struct timeval t; gettimeofday(&t, NULL); return t.tv_sec * 1000 + t.tv_usec / 1000;}int main(int argc, const char * argv[]) { size_t ta; size_t tb; linked_list_t list; linked_list_t large_list; linked_list_t large_presorted_list; linked_list_init(&list); linked_list_init(&large_list); linked_list_init(&large_presorted_list); linked_list_append(&list, 5); linked_list_append(&list, 1); linked_list_append(&list, 2); linked_list_append(&list, 9); linked_list_append(&list, 6); linked_list_append(&list, 7); linked_list_append(&list, 10); linked_list_append(&list, 8); linked_list_append(&list, 4); linked_list_append(&list, 3); // Small demo: linked_list_display(&list); puts(); linked_list_sort(&list); linked_list_display(&list); puts(); // Large benchmark: load_linked_list(&large_list, 1000 * 1000); ta = milliseconds(); linked_list_sort(&large_list); tb = milliseconds(); printf(Sorted large array in %zu milliseconds. Sorted: %d\n, tb - ta, linked_list_is_sorted(&large_list)); // Large presorted benchmark: load_presorted_list(&large_presorted_list, 1000 * 1000); ta = milliseconds(); linked_list_sort(&large_presorted_list); tb = milliseconds(); printf(Sorted large presorted array in %zu milliseconds. Sorted: %d\n, tb - ta, linked_list_is_sorted(&large_presorted_list)); return 0;}Critique requestPlease tell me how can I improve my C programming routine. | Sorting a singly linked list with natural merge sort in C | algorithm;c;sorting;linked list;mergesort | malloc can fail. Deal with it.If you don't modify something passed by pointer, mark it const. Const-correctness, if rigorously followed, is a great help for debugging and understanding, and a right pain otherwise.Consider taking advantage of the possibility to intersperse variable-declarations in code since C99. It's succh a nice feature even ancient C90 compilers allow it as an extension.This way you can declare and initialize variables where you need them, keeping their scopes minimal and easier to review.There is nobody stopping you from modifying function-arguments. Might eliminate some variables that way...ints are easily copied. And sentinels allow for the elimination of special-cases, the bane of elegance and efficiency.int linked_list_is_sorted(const linked_list_t* list) { int last = INT_MIN; for(linked_list_node_t* node = list->head; node; node = node->next) if(node->value < last) return 0; else last = node->value; return 1;}Consider const-qualifying all pointers to string-literals. While in C the type is still char[N], it is immutable.How about changing the format-string instead of an insert?void linked_list_display(const linked_list_t* list) { const char* format = %d; for(linked_list_node_t* node = list->head; node; node = node->next) { printf(format, node->value); separator = , %d; }}The conditional operator (exp ? true_val : false_val) is superb for choosing between two expressions.Double-pointers are not scary. And using them allows you to avoid needless duplication.static linked_list_node_t* merge(linked_list_node_t* a, linked_list_node_t* b) { linked_list_node_t* head = NULL; linked_list_node_t** insert = &head; while (a && b) { if (a->value < b->value) { *insert = a; a = a->next; } else { *insert = b; b = b->next; } insert = &(*insert)->next } *insert = a ? a : b; return head;}Integral remainder is a very costly operation. And as you know that 0 <= n < 2 * m in n % m, you can replace it with a cheaper conditional subtraction.return 0; is implicit for main() since C99. Might be interesting... |
_unix.278438 | I'm trying to build an embedded linux system based on an Atmel AT91SAM9G25 SoC (ARM9 @ 400Mhz) CPU. I'm using the AT91Bootstrap bootloader. As the subject of my post suggests, I have an issue with resume from hibernation functionality. Suspend to disk process seems to work fine, but upon waking up, the system doesn't restore previous session.The issue Im facing in detail is as follows:I have built a linux image for my system using buildroot and I have activated/configured accordingly the following kernel parameters:Power management options --> Suspend to RAM and standbyPower management options --> Hibernation & Default resume partition /dev/mmcblk0p3(The kernel version I'm using is 4.0.4 and /dev/mmcblk0p3 is the swap partition of the sdcard.)When I booted the system for the first time, I noticed that the swap partition didnt mount automatically. I managed to mount the swap partition manually with mkswap /dev/mmcblk0p3 and swapon -a commands. I also inserted the corresponding line to the fstab file: /dev/mmcblk0p3 none swap sw 0 0After rebooting, I could not find any swap partition mounted. To address this issue I included the mentioned mkswap and swapon commands to the inittab file. After reboot, swap partition was successfully mounted on startup.With the swap partition mounted, Im requesting the system to hibernate (suspend to disk). The suspend process seems to work as expected.The problem starts when I reconnect the power. Although the system seems to understand that it woke up from a suspend state, it doesnt restore the previous session. Its like performing a cold boot. Suspend to memory is working fine. I can put the system into sleep with rtcwake -s20 -m mem and when it wakes up previous session is restored succesfully. Therefore, I assume that something goes wrong with the swap partition, but I've run out of ideas.I've tried to hibernate the system using the following commands:rtcwake -s20 -m diskecho shutdown > /sys/power/diskecho disk > /sys/power/statepm-hibernatebut all of them fail as described above.Some useful dmesg and console outputs can be found hereAny suggestions or ideas of what I might be doing wrong? | Resume from hibernation is not working on embedded linux system | embedded | null |
_softwareengineering.138548 | In my subscription form I want to use a double opt-in method:First, the visitor subscribesThen a confirmation email is dispatched. If he replies...Then I add him to the system. In the case where the user does not reply, how long can I store their email address? Are there any legal requirements with regard to that? I am from U.S. and I am also interested in the policy in European countries. | How long can I store the subscribe personal information? | privacy | However for easier conversion, you can send the subscriber a reminder as follows:a) 15 days - thanking them for subscribing to your services, and letting them know that there is only one more step to go to activate their accountb) 45 days - Letting them know that they are missing out on the goodies on your site or news letterc) 75 days - letting them know a while ago they signed up and you would like them to complete activationAfter 90 days delete their information, because they are not going to come back anyway. I remember Google and Microsoft would only hold data for 3 months before deleting it, but I am not yet sure anymore what the number is. |
_unix.354263 | May I use full Ubuntu in a not bootable hard drive?My hard drive can't boot (320GB). I used it just as a storing device.But then I remember the power of Linux, and thought there could possibly be a way of booting from a flash-drive and then switch to full Ubuntu in the hard drive. Is it possible? | May I use full Ubuntu in a not bootable hard drive? | boot | Yes, it's possible, even you can use floppy disc to boot linux. Or you can install lilo or grub on your primary booting hard drive, and configure it that it point to linux from this not booting HD. (is it really only 320MB)? |
_webapps.29905 | This is probably not possible but...I'm looking to update cells in a Google spreadsheet using the conditional formatting tool.(Changes to SERPs rankings) So when the number in a cell is changed, it recognises if the number was greater or lesser than the current number and then changes the cell colour to red for lesser and green for greater.So it needs to be able to store the last changed figure in order to make the decision, it doesn't look to be achievable from the conditional formatting options. | Is it possible to add conditional formatting when number changes? | google spreadsheets;conditional formatting | null |
_unix.265944 | Am wondering if there are any tools that will do this:Exmaple XML:<node1> <Data> <Unique>123456789-1234567891</Unique> </Data></node1>What i was hoping to search was where Unique is Less than 10 left to - And if Right is less than 9 from - to right. So the search would flag this record/node as a problem<Unique>6789-1234567891</Unique>I was trying to use Grep to do this, but there have been various XML tools i have started using in Bash, so i thought i would ask the question first on a specific tool maybe. xmllint was one i was using. | Is there any tools that will let me check String length of XML Node | bash;grep;xml;xmllint | (sorry to spam you) Using a XML parser in perl (if ncessary: sudo cpan XML::DT)#!/usr/bin/perluse XML::DT;my $file = shift;# $c - contents after child processingprint dt( $file, 'Unique' => sub{$c =~ s/^(\d{1,9}-\d+|\d+-\d{1,8})$/FIXME:$1/; toxml },)In this case you get a XML anotated with FIXMEs |
_codereview.26642 | I am breaking my head with how to get rid of semantic duplication(Code that is syntactically the same but does different things).I can't find anywhere a post or something that mentions a bit how to refactor this kind of duplication. All I found was this: http://blogs.agilefaqs.com/tag/code-smells/ but it does not go into detail on how to refactor it. This is the code that is causing me problem:public class TeamValidator { public boolean isThereALeader(List<Member> team) { Iterator<Member> iterator = team.iterator(); while(iterator.hasNext()) { Member member = iterator.next(); String role = member.getRole(); if(role.equals(Leader)) return true; } return false; } public boolean areThereAtLeast2NewJoiners(List<Member> team) { int amountOfNewJoiners = 0; for(Member member:team) { if(amountOfNewJoiners == 2) return true; DateTime aMonthAgo = DateTime.now().minusMonths(1); if(member.startingDate().isAfter(aMonthAgo)) { amountOfNewJoiners++; } } return false; }}In this 2 methods there is semantical duplication, because both Iterate a list and also check some condition/s. Any idea how could I make this semantic duplication disappear? I would really appreciate some tip or suggestion on how to refactor this. | How to get rid of semantic duplication | java | null |
_unix.344487 | Can someone clarify this piece of gibberish:lvrename [-A|--autobackup {y|n}] [-d|--debug] [-h|--help] [-t|--test] [-v|--verbose] [--version] [-f|--force] [--noudevsync] {OldLogicalVolume{Name|Path} NewLogicalVolume{Name|Path} | VolumeGroupName OldLogicalVolumeName NewLogicalVolumeName}I've formatted it exactly as I see it in my terminal.How do you go from the command spec above tolvrename /dev/vg2/lv2 /dev/vg2/lvm02 | How do you parse `lvrename [-A|--autobackup {y|n}] [-d|--debug] [-h|--help] [-t|--test] [-v|--verbose] [--version] [-f|--force] [--noudevsync] | lvm | null |
_bioinformatics.604 | I got a customized GRCh38.79 .gtf file (modified to have no MT genes) and I need to create a reference genome out of it (for 10xGenomics CellRanger pipeline). I suspect that the .79 part is the Ensembl number, which according this ensembl archive list is paired with the GRCh38.p2 patch.Should I use this patch's fasta file, or it would be fine to use any of the GRCh38 patches? | Can a customized GRCh38 .gtf file be used with any of the GRCh38 released patches? | human genome;reference genome;gtf;10x genomics | null |
_webmaster.11476 | i have h2 and h5 headings with generic names here NSFW: such as 'editor picks' 'tags' 'all articles' would it be better for seo to give them unique and almost playful names with keywords? | SEO Heading Tags | seo | null |
_unix.46310 | When booting my Debian server, I'm presented with the following error concerning my external hard drive:/dev/disk/by-label/elements:The superblock could not be read or does not describe a correct ext2 filesystem.........fsck died with exit status 8.......A maintenance shell will now be started. CONTROL-D will terminate this shell andresume system boot.The thing is that if I type Ctrl-d or enter the maintenance shell the disk is correctly mounted and calls to e2fsck /dev/disk/by-label/elements report no errors.This is very annoying since I need to type ctrl-d every time the server is rebooted and I would rather not have a keyboard attached to the server at all. | Why does e2fsck fail during boot, but not later? | debian;filesystems;boot;hard disk;fsck | I solved it by following the advice described here: https://bugs.launchpad.net/ubuntu/+source/util-linux/+bug/367782 |
_unix.84624 | Can anyone tell me how to set a directory only in read/write mode as below?-rw-rw-r--I tried with 640,644 but I am able to achieve... | Mode to set Directory in Only READ-WRITE mode | linux;directory | null |
_unix.356123 | I have a windows machine, where I have shared a location and made it open through browser using https. Something like this- https://my-windows/test.I am writing a shell script which will post a file to this machine/url. I am able to download file using curl from this location but when I post/put, it gives me error. It says that I am trying to put it in a folder and expected is a file.I don't want to over write an existing file. I want to create a new file. Is this possible with curl? I am writing this shell script in Linux box and destination is a windows box.I tried following:1. curl -D- -u user:pass -X POST --data @test.txt https://my-windows/testHTTP/1.1 200 Connection establishedHTTP/1.1 405 Method Not Allowed2. curl -D- -u user:pass -X PUT --data @test.txt https://my-windows/test{ errors : [ { status : 500, message : Expected a file but found a folder } ]}3. curl -D- -u user:pass -F [email protected];filename=nameinpost https://my-windows/testHTTP/1.1 200 Connection establishedHTTP/1.1 100 ContinueHTTP/1.1 405 Method Not AllowedAllow: GET,PUT,DELETEContent-Length: 0 | Can I create file in server using CURL? | windows;curl;http | The error in the second message suggests that you need to include the file name, like this:curl -D- -u user:pass -X PUT --data @test.txt https://my-windows/test/test.txt |
_softwareengineering.343868 | Background:We are in the process of converting a traditional multi-service Windows Service (WS) application into an Azure Service Fabric microservices grid running on a Service Bus messaging layer. In the WS application, the data loader service was a singleton to prevent duplication of effort with regards to loading data into a DB from external sources as part of a job.In the new grid (and because we're using SQL Server 2016 with it's parallelised bulk data import functionality), we would like to have multiple instances of the data loader service but it is still a standard scenario that two or more jobs with dependencies on the same data set may be pushed onto the processing grid at one time.Question:Is there a standard pattern for ensuring that the duplication of effort with regards to loading specific sets of data in this type of architecture is avoided? | Multi-instance Microservice Grid: Preventing Duplication Of Effort When Resolving Cached Resources | microservices;architectural patterns;messaging;grid computing | Create a centralized data import job assigner object that assigns data import jobs to other objects. The jobs may be executed by threads within the same process, or by external processes, if running on multiple computers. The centralized assigner object avoids duplication of effort.With regards to the Single Responsibility Principle mentioned in your comment: this principle is difficult to follow because the word responsibility is vague. The definition of a responsibility should vary according to the level of abstraction and the specific software to be designed. At the highest level of abstraction, a responsibility may encompass a wide range of tasks, while at the lowest level of abstraction, a responsibility may be limited and specific. At the lowest level, some people consider two lines of code to be two separate responsibilities. Having worked with code that reduces all methods to nearly one line, I believe this type of design just as horrible, or worse, than a giant monolithic class or method. |
_cs.75818 | What does the following symbols or expression mean? | The meaning of symbols | discrete mathematics | $x$ and $y$ are elements of a set $S$. For example, if $S = \{1, 2, 3\}$, we can select $x = 1$ and $y = 2$. EDIT:As pointed out by David below, $*$ could be multiplication or convolution, it's hard to tell from the context. $\in$ means 'in', that is, that $x$ and $y$ are in a set. We can write 'x and y are elements of the set $S$ ' in math as: $x, y \in S$Again, following my example, that would be $1$ and $2$ are in the set $\{1, 2, 3\}$.$\forall$ is verbalized 'for all'. It means for every element in the set, something is either true or false. For example:$\forall x \in S, x < 5$ means that all of the elements in my set $S$ are less than 5.$I$ is the identity function. The entire phrase $I: \forall X. X \rightarrow X$(EDIT: removed example, as it was misleading)means the identity function preserves the value of the variable $X$. More concretely, $I$ is the function that maps $X$ to itself. For all values of X, the output of the function is X.Hope that helps! |
_softwareengineering.244867 | Currently working on a web based CRM type system that deals with various Modules such as Companies, Contacts, Projects, Sub Projects, etc. A typical CRM type system (asp.net web form, C#, SQL Server backend). We plan to implement role based security so that basically a user can have one or more roles. Roles would be broken down by first the module type such as:-Company-ContactAnd then by the actions for that module for instance each module would end up with a table such as this:Role1 Example: Module Create Edit Delete View Company Yes Owner Only No Yes Contact Yes Yes Yes YesIn the above case Role1 has two module types (Company, and Contact). For company, the person assigned to this role can create companies, can view companies, can only edit records he/she created and cannot delete. For this same role for the module contact this user can create contacts, edit contacts, delete contacts, and view contacts (full rights basically).I am wondering is it best upon coming into the system to session the user's role with something like a:List<Role> roles;Where the Role class would have some sort of List<Module> modules; (can contain Company, Contact, etc.).? Something to the effect of:class Role{string name;string desc;List<Module> modules;}And the module action class would have a set of actions (Create, Edit, Delete, etc.) for each module:class ModuleActions{List<Action> actions;}And the action has a value of whether the user can perform the right:class Action{string right;}Just a rough idea, I know the action could be an enum and the ModuleAction can probably be eliminated with a List<x, y>. My main question is what would be the best way to store this information in this type of application: Should I store it in the User Session state (I have a session class where I manage things related to the user). I generally load this during the initial loading of the application (global.asax). I can simply tack onto this session.Or should this be loaded at the page load event of each module (page load of company etc..). I eventually need to be able to hide / unhide various buttons / divs based on the user's role and that is what got me thinking to load this via session.Any examples or points would be great. | How to store Role Based Access rights in web application? | web development;security;session | Well, I think your design is fine I would only recommend you only a simple thing on how to store the roles. I have here a system that has almost the same concepts. It is not based on roles as per the name. So I have a user session object with objects of type Map that store the permissions that the user has. And this Map objects is filled on demmand It will be something like:public class UserSession { HashMap<Application, Action> map; public boolean hasPermissionApp( Application app ){ if ( !map.containsKey(app) ){ //check if the user has the permission on the DB or whatever you store it //if it has add it to the map with the action that //it came along and return true //if it hasn't return false } return true; } public boolean hasPermissionAction( Application app, Action act ) { if ( hasPermissionApp(app) ){ if ( !map.get(app).containsKey(act) ){ //check if the user has permission to that action of the app //if it has add to the map and return true //if not return false } } return false; }}That way you load the user permisson and store it by demmand and don't overload the session object with the full set of permissions that the user has. EDITAs OP asked on the comments:Do you fill this hashmap at every sort of click event that requires role permissions?The answer is almost this. When the user logs in an application the user session object is empty, so for the Application that He is logging in I would check if He has access and if so, I add it to the map with the first Action that was called by that Application lets say 'View'. And with this Action the user can see the search form. Here you can have two approach. Which is what you asked!Check permissions when the user fire the events like with this 'View' Action it can see the entire form with the buttons search, add, cancel (or whatever others) But the permission will be checked only when the user press the button. Then it if have you add to the map or send him a message saying that it does not have that permission.Check the permission when rendering the actions. You only show the buttons on the form if the user has that appropriate Action associated to it. So lets say you are using a component library like Richfaces it would be like this:<a4j:commandButton rendered=#{userSessionObject.hasPermissionAction('appBla','search')} ..... />And since this is created on the construction of the page the map would be filled on every check permission that is made on the page or other resources.And on my application i choose for the second approach, because I don't think that make sense to show a button to a user that does not have the access to it.Edit 2A thing that maybe is usefull is that I associate a thread timing (configurable time) to the user session that clean up the maps on the userSessionObject, so if some administrator change permissions to that user at some point it will have his permissions updated automatically, not exactly at prompt but this was a acceptable requirement to this particular system. |
_unix.57715 | I am looking for a tool which takes a file in input and a word to search. It should display the file with color the words if it corresponds to the search.Like grep --colors but displays all the file.Is there something already exists ?Example : cat /etc/passwd | colors rootDisplay all /etc/passwd file and color the words rootIf I can change the color easily it would be great ! | Display words in color | command line;sed;grep | A little trick with grep will do the job:grep --color ^\|root /etc/passwdOtherwise look here. |
_codereview.79381 | I have a function that accepts a \$255\times1024\$ array and remaps it to another array in order to account for some hardware related distortion (lines that should be straight are curved by the lens). At the moment it does exactly what I want, but slowly (roughly 30 second runtime). Specifically, I'm looking at the nested for loops that take 18 seconds to run, and the interpolation that takes 10s. Is there any way to optimize/speed up this process? EDIT: Nested for loops have been optimized as per vps' answer. Am now only interested in optimizing the interpolation function (if that's even possible).def smile(Z): p2p = np.poly1d([ -3.08049538e-07, 3.61724996e-04, -7.78775408e-02, 3.36876203e+00]) Y = np.flipud(np.rot90(np.tile(np.linspace(1,255,255),(1024,1)))) X = np.tile(np.linspace(1,1024,1024),(255,1)) for m in range(0,255): for n in range(0,1024): X[m,n] = X[m,n] - p2p(m+1) x = X.flatten() y = Y.flatten() z = Z.flatten() xy = np.vstack((x,y)).T grid_x, grid_y = np.mgrid[1:1024:1024j, 1:255:255j] newgrid = interpolate.griddata(xy, z,(grid_x,grid_y), method = 'linear',fill_value = 0).T return newgrid | Remapping and interpolating 255x1024 array | python;matrix;numpy;time limit exceeded | p2p(m + 1) does not depend on n. You may safely extract its calculation from the inner loop:for m in range(0,255): p2p_value = p2p(m + 1) for n in range(0,1024): X[m,n] = X[m,n] - p2p_valueIf you call smile() multiple times, it is worthwhile to precompute p2p once.Some further savings can be achieved by accounting for the sequentiality of p2p arguments. Notice that p2p(m+1) - p2p(m) is a polynomial of lesser degree; you maycalculate it incrementally: p2p_value += p2p_delta(m)Edit:Some math:Let \$P(x) = ax^3 + bx^2 + cx + d\$. You may see that \$P(x+1) - P(x) = 3ax^2 + 3ax + a + 2bx + b + c = 3ax^2 + (3a + 2b)x +(a+b+c)\$ is a second degree polynomial, a bit easier to calculate than the original third degree one. Which leads to the code (fill up the list of coefficients according to the above formula): p2p_delta = np.poly1d([...]) p2p_value = p2p_delta(0) for m in range(0, 255) for n in range(0, 1024) X[m,n] -= p2p_value p2p_value += p2p_delta(m) |
_codereview.79398 | Making an Android app involves making a lot of images of various sizes:The app's launcher icon, in high/low/medium resolutionButtons, menu buttons, if any, in high/low/medium resolutionImages for listing on Google Play: main icon, feature graphicsTo simplify this, I use high-resolution source images+ ImageMagick to cut to the various sizes+ Makefile to only regenerate the images whose source image has changed.For the feature graphics I cheat:I just generate a transparent canvas with the required dimensions,and overlay on top of it the app's icon, as big as it fits.src_dir:=srchdpi_dir:=res/drawable-hdpildpi_dir:=res/drawable-ldpimdpi_dir:=res/drawable-mdpinames:=$(patsubst $(src_dir)/%,%,$(wildcard $(src_dir)/*.png $(src_dir)/*.jpg))hdpi_target:=$(patsubst %,$(hdpi_dir)/%,$(names))ldpi_target:=$(patsubst %,$(ldpi_dir)/%,$(names))mdpi_target:=$(patsubst %,$(mdpi_dir)/%,$(names))appicon:=googleplay/appicon.pngfeature:=googleplay/feature.pngcanvas:=googleplay/canvas.pngwork:=googleplay/work.pngdefault: allhdpi: $(hdpi_dir) $(hdpi_target)ldpi: $(ldpi_dir) $(ldpi_target)mdpi: $(mdpi_dir) $(mdpi_target)googleplay: $(appicon) $(feature)all: hdpi ldpi mdpi googleplayclean: rm $(hdpi_target) $(ldpi_target) $(mdpi_target) $(appicon) $(feature)$(hdpi_dir): @mkdir -p $@$(ldpi_dir): @mkdir -p $@$(mdpi_dir): @mkdir -p $@$(hdpi_dir)/btn_%.png: $(src_dir)/btn_%.png convert -geometry 48x $< $@ identify $@$(ldpi_dir)/btn_%.png: $(src_dir)/btn_%.png convert -geometry 24x $< $@ identify $@$(mdpi_dir)/btn_%.png: $(src_dir)/btn_%.png convert -geometry 36x $< $@ identify $@$(hdpi_dir)/launcher_%.png: $(src_dir)/launcher_%.png convert -geometry 72x $< $@ identify $@$(ldpi_dir)/launcher_%.png: $(src_dir)/launcher_%.png convert -geometry 36x $< $@ identify $@$(mdpi_dir)/launcher_%.png: $(src_dir)/launcher_%.png convert -geometry 48x $< $@ identify $@$(appicon): $(src_dir)/launcher_main.png @mkdir -p $(@D) convert -geometry 512x $< $@ identify $@$(feature): $(src_dir)/launcher_main.png @mkdir -p $(@D) convert -size 1024x500 xc:transparent $(canvas) convert -geometry 1024x500 $< $(work) convert -composite $(canvas) $(work) -gravity west $@ identify $@If you want to play with this,save this script as Makefile,put an image file in src/launcher_main.png,and assuming you have ImageMagick installed,simply run make to have the images of various sizes generated in the res directory.In Android projects I have res pointing to the real resources directory of the project.This works well, but it's a bit repetitive at some places.I'm wondering if this can be more DRY,or if there are other ways to improve. | Slicing and dicing images for Google Play | image;makefile;make | Use target- and pattern-specific variables:$(ldpi_dir)/btn_%.png : GEOMETRY := 24x$(mdpi_dir)/btn_%.png : GEOMETRY := 36x$(hdpi_dir)/btn_%.png : GEOMETRY := 72xand similar definitions for launcher_%.pngThen you can combine all the individual recopies into a single one:$(ldpi_dir)/%.png $(mdpi_dir)/%.png $(hdpi_dir)/%.png) : convert -geometry $(GEOMETRY) $< $@ identify $@ |
_softwareengineering.323964 | I got this problem in an interview and want to confirm multi threading adds no value here. Case:You are writing an agent to buy stocks.The agent is initialized with a set of stocks to buy when they hit a certain price. A separate (out of scope) service monitors the market and invokes a callback on your agent when a pice changes (agent implements some interface that provides the callback method) The callback can be invoked for stocks you don't care about, and when it's invoked for a stock you do care about, you need to check the price is the price you want to buy at.When you determine you should buy, you invoke some external out of scope service. The agent will be run asynchronously from some engine that creates it. When all the stocks (at the desired price) have been bought, the agent shuts down. The engine that inits the agent is out of scope. I don't see the benefit of having the agent asynchronous. | Multi threaded and event driven | multithreading;asynchronous programming | null |
_unix.327826 | Hope someone can help me. I use rsync to copy directories including files, with --remove-source-files I let rsync delete source files. Unfortunately it doesn't delete directories so I would like to delete all empty directories under SOURCE1 and SOURCE2.The find -exec rmdir command does this but unfortunately it also deletes the SOURCE directories itselfCopy.shSOURCE1=/mnt/download/transmission/complete/SOURCE2=/mnt/download/sabnzbd/completed/sudo rsync --remove-source-files --progress --ignore-existing -vr /mnt/download/transmission/complete/ /mnt/dune/DuneHDD_1234sudo rsync --remove-source-files --progress --ignore-existing -vr /mnt/download/sabnzbd/completed/ /mnt/dune/DuneHDD_1234find $SOURCE1 -not -name complete -type d -empty -prune -exec rmdir --ignore-fail-on-non-empty -p \{\} \;find $SOURCE2 -not -name completed -type d -empty -prune -exec rmdir --ignore-fail-on-non-empty -p \{\} \;I also tried the following code*find $SOURCE1 -mindepth 2 -type d -empty -prune -exec rmdir --ignore-fail-on-non-empty -p \{\} \;find $SOURCE2 -mindepth 2 -type d -empty -prune -exec rmdir --ignore-fail-on-non-empty -p \{\} \;And without*find $SOURCE1 -type d -empty -prune -exec rmdir --ignore-fail-on-non-empty -p \{\} \;find $SOURCE2 -type d -empty -prune -exec rmdir --ignore-fail-on-non-empty -p \{\} \;I could add a mkdir test and change SOURCE1 to /mnt/download/transmission/complete/test and this way it always deletes the directory that I just created but I would like to do it the proper wayExample: I created 6 directories:test10/test10/test11/test10/test11/test12/test10/test11/test12/testtest1/test1/test2/test1/test2/test3/test1/test2/test3/testAfter running copy.sh I end up with perfectly copyed directories and files (test1/test2/test3/test and test10/test11/test12/test) on destination and deleted directories and files on source INCLUDING source ($SOURCE1 and $SOURCE2) itself.Is there a way to tell find to exclude the source directory itself?In other words: Everything UNDER the folowing directories shoud be deleted but not the directories themselves:SOURCE1=/mnt/download/transmission/complete/SOURCE2=/mnt/download/sabnzbd/completed/Thanks a lot in advance | Raspbian, debian: Howto make find $SOURCE return all directories under $SOURCE without itself | debian;rsync;find;raspbian | null |
_unix.78776 | I have a text file encoded as following according to file:ISO-8859 text, with CRLF line terminatorsThis file contains French's text with accents. My shell is able to display accent and emacs in console mode is capable of correctly displaying these accents.My problem is that more, cat and less tools don't display this file correctly. I guess that it means that these tools don't support this characters encoding set. Is this true? What are the characters encodings supported by these tools? | Characters encodings supported by more, cat and less | command line;terminal;character encoding;less;more | Your shell can display accents etc because it is probably using UTF-8. Since the file in question is a different encoding, less more and cat are trying to read it as UTF and fail. You can check your current encoding withecho $LANGYou have two choices, you can either change your default encoding, or change the file to UTF-8. To change your encoding, open a terminal and typeexport LANG=fr_FR.ISO-8859For example:$ echo $LANG en_US.UTF-8$ cat foo.txt J'ai mal la tte, c'est chiant!$ export LANG=fr_FR.ISO-8859$ xterm <-- open a new terminal $ cat foo.txt J'ai mal la tte, c'est chiant!If you are using gnome-terminal or similar, you may need to activate the encoding, for example for terminator right click and:For gnome-terminal :Your other (better) option is to change the file's encoding:$ cat foo.txt J'ai mal la tte, c'est chiant!$ iconv -f ISO-8859-1 -t UTF-8 foo.txt > bar.txt$ cat bar.txt J'ai mal la tte, c'est chiant! |
_softwareengineering.63549 | In the real world , why do we need to implement method level security ?We either have a web application or a desktop application , where the user accesses the user interface (and therefore directly cannot access the method) . So where does accessing methods directly come into picture here ?edit : I ask this question because I am experimenting with spring security , and I see authorizing users for accessing methods . something like : @ROLE_ADMINpublic void update() { //update} | Why do we need method level security? | security | In a properly designed application the backend and frontend are disconnected.The backend security system can't assume any specific frontend will correctly handle security, so it has to handle it itself. |
_cs.29343 | I've been coming across a problem in one of my assignments requiring the calculation of the speedup of a two-way superscalar cpu. The problem is as follows:There is a two-way superscalar CPU with 2 pipelines U & V. The instruction pipeline U processes the complex instructions, while the instruction pipeline V processes the simple instructions. The ratio of the processing times in the phases of pipelines U and V is 3:1. I'm required to calculate the processing time for 1000 instructions in GPSS (General Purpose Simulation System) - Student Version, for the following cases:50% complex and 50% simple instructions25% complex and 75% simple instructions75% complex and 25% simple instructionsProbability of 50% complex and 50% simple instructionsProbability of 25% complex and 75% simple instructionsProbability of 75% complex and 25% simple instructionsI have the simulation files and i can deduce the execution time for each case T(Supuperscalar).However I'm stuck with the requirement of finding the speedup for each case.I'm aware that the speed up can be calculated as Speedup = T(Sequential)/T(superscalar) = k*n/k+(n-1) where k is the number of stages and n is instruction number, however I'm having a hard time figuring out how to calculate the sequential time for the above cases.I would really appreciate if somebody can give me a hint here. | Calculating speedup for a two-way superscalar cpu | computer architecture;cpu pipelines | null |
_cs.60737 | I have a rooted tree with $n$ vertices.I want to be able to answer the given queries in logarithmic time after setting up some sort of data structure (preferably in time $n\log n$.The query is given by $v$ and $k$.I want to find the number of ancestors of $v$ of degree less than or equal to $k$.( I call ancestors of degree $1$ sons).I don't know how to do it.At first I thought that I should only store the number of ancestors of $v$ of degree less than $2^j$. But this doesn't seem to work. | FInding number of ancestors at given depth | algorithms;trees | We do a dfs starting from the root. we save the entry-time and exit time of each vertex. We build a list containing (height(v),entrytime(v)). Where entrytime is the time in the dfs where we first reached vertex v.we now sort our list lexicographically (this takes time $\mathcal O(n\log(n))$ ) . Inside this order, the vertices at height $h$ that are ancestors of a vertex $v$ are the elements in the list that are between $(h,entrytime(v))$ and $(h,exittime(v))$.So the problem is essentially reduced to the following:Suppose we have an array of integers $a_1,a_2,\dots, a_n$, given $x$ and $p$ how can we find the number of elements in the range $a_1,a_2,\dots, a_p$ that are greater than $x$? (we just need $p-k$).Various efficient solutions to this are discussed here: |
_webmaster.7831 | I had registered with a particular DNS provider X and I have been unhappy with their services and now when the time for renewal came, I did not renew and I let it expire. I am hoping that once it is expired from this provider, I would be able to sign up for the same domain name from an alternative provider which I have tested and I am satisfied.What kind of precautions should I take? The domain name is not a critical one, it is of a NGO and we prefer to own it again without any change in the name.The information given by the expiry notice saysDomains can be renewed between 90 days before and 14 days after the expiry date. If domains are not renewed they will be removed from the account and set for deletion.Should I wait for time till gets deleted at their end so that I can sign up for the same from another provider? | Moving from one DNS provider to another | domains | null |
_unix.158760 | I want to make a diff of hostnames using grep. I have 2 files. One yaml and one .pp. In the yaml I have domain names with ips and in the .pp file I have fqdn and ip in hash style. Like this: In the fist file I Have a list of hosts: {host => host1, ip = x.x.x.x },{host => host2, ip = x.x.x.x },In the second file I have another group of hosts like this:host1:ip: x.x.x.xhost2:ip: x.x.x.xI'm trying first to get the list of hosts of the first file and at the same time get the list of hosts of the second file. If the host of the first file is in the second one I skip it. cat FILEONE.pp | grep 'host =>' | grep -v cat FILETWO.yaml | grep '[0-9]:' | grep -v ipFilterI want to pass this: cat FILETWO.yaml | grep '[0-9]:' | grep -v ip as parameter to the -v flag to the previous grep to make an inverse grep but I can't make it work... Is it possible to make this on the fly?The question could be reduced to:How can I make this:grep -v {cat file | command2 | command3 | command4}I want to make a list which contains the hosts in the first file only if they are not in the second file. (Exclude the hosts of the second file from the first file) | How to make a grep which excludes a bunch of pipes? | linux;grep | null |
_codereview.83547 | Because the ambient transaction isn't supported with informix, I pass the transaction and the connection through my methods.I want to ask about three things:Is the following code written well? I mean, no redundant steps and no logical errors.Is calling this transaction method with many null parameters in a specific case okay?Is there a better way to handle this problem? public static int Insert(string processMethod, object[] processParameters, Type processType, object process, UserTransactionDTO transObj, string spPostConfirm, int toEmpNum,int confirmState) { int affectedRows = -7; using (IfxConnection conn = new IfxConnection(ConfigurationManager.ConnectionStrings[crms].ToString() + Enlist=true;)) { if (conn.State == ConnectionState.Closed) { conn.Open(); } using (IfxTransaction tran = conn.BeginTransaction()) { if (!string.IsNullOrEmpty(processMethod))//business Method { processParameters[1] = conn; processParameters[2] = tran; MethodInfo theMethod = processType.GetMethod(processMethod, new[] { processParameters.First().GetType(), typeof(IfxConnection), typeof(IfxTransaction) }); object res = theMethod.Invoke(process, processParameters); transObj.ValuesKey = res.ToString(); } if (!string.IsNullOrEmpty(transObj.ValuesKey)) { affectedRows = RunPreConfirm(transObj.TaskCode, transObj.UserStateCode, transObj.ValuesKey, conn, tran, confirmState);//sp_confirm if (affectedRows != 1) { tran.Rollback(); tran.Dispose();//Dispose conn.Close(); conn.Dispose(); return -1;//Fail } affectedRows = InsertTrans(transObj, conn, tran);//MainTransaction --->df2usertrans if (affectedRows == 1)//Success { if (!string.IsNullOrEmpty(spPostConfirm)) { affectedRows = RunPostConfirm(spPostConfirm, transObj.ValuesKey, conn, tran);//sp_post_confirm if (affectedRows != 0) { tran.Rollback(); tran.Dispose();//Dispose conn.Close(); conn.Dispose(); return -2;//Fail } } affectedRows = RunAfterTrans(transObj.TaskCode, transObj.OldStatusCode, transObj, toEmpNum, conn, tran);//sp_after_trans if (affectedRows != 1) { tran.Rollback(); tran.Dispose();//Dispose conn.Close(); conn.Dispose(); return -3;//Fail } tran.Commit(); tran.Dispose(); conn.Close(); conn.Dispose(); return 1; } else { tran.Rollback(); tran.Dispose();//Dispose conn.Close(); conn.Dispose(); return -1;//Fail } } else { tran.Rollback(); tran.Dispose();//Dispose conn.Close(); conn.Dispose(); return -1;//Fail } } } return affectedRows; }Examples for calling:int res = DocumentFlowModuleDAL.UserTransactionDAL.Insert(InsertRequest, reqObj, typeof(EnhancementRequest), new EnhancementRequest(), transObj, string.Empty, 0,0);result = UserTransactionDAL.Insert(string.Empty, null, null, null, obj, sp_PostConfirm, x, 0); | Implementing transaction method with invoking business methods in a one transaction | c#;asp.net;reflection | Do not return error code if possible. If the method fails to do what it needs to do, just throw an exception. In your case, do not return -1, -2, etc, you should create new type of exception and wrap your error code inside.The using clause guarantees that Dispose() of the object you use will be called , even in case of exception, before exiting the enclosed block, so all Close() and Dispose() in your code is redundant. In C#, transaction usage usually goes likeusing(var tran = conn.BeginTransaction()) { try { ... // your code here ... tran.Commit(); } catch { tran.Rollback(); throw; }}This will work well when you do not return error code.Edit: Here is an example of the exception classpublic enum YourErrorCode { Unknown, ErrorCode1, ErrorCode2,}public class YourException : Exception { public YourErrorCode ErrorCode { get; private set; } public YourException() { } public YourException(string message) : base(message) { } public YourException(string message, Exception inner) : base(message, inner) { } public YourException(YourErrorCode errorCode) : this(errorCode, null) { } public YourException(YourErrorCode errorCode, Exception inner) : base(The operation failed with error code + errorCode.ToString(), inner) { this.ErrorCode = errorCode; }}And throw it likethrow new YourException(YourErrorCode.ErrorCode1);instead of returning error code. |
_webmaster.9961 | My homepage has a PR of 5. However, 99% of my internal pages have PR of 0 for some reason.What can be the cause of it? I have a sitemap and Google Webmaster Tools shows that all my website pages are indexed.(The internal pages are built with SEO in mind, and have several sources linking to them).Thanks!Joel | Internal pages PR | seo;pagerank | PR is all about links. Internal pages have fewer links then home pages because most incoming links from other sites point ot the home page and internal pages link to the home page more then other internal pages. So the homepage naturally tends to have a high PR and internal pages are lower.If you want your internal page to have higher PR get more links to those pages from other sites and do a better job of internal inking within your site. |
_unix.4364 | Notice: This is not about dual booting, I can setup GRUB to dual boot with Windows 7 later. I just need to be able to get into Arch Linux.Last night I installed Arch onto my computer via netinstall and it all went smoothly, but when I went to reboot... it loaded up the GRUB menu and it listed Arch Linux, but when I select it, I get Error 15: File not found.I've been googling and trying various way to fix this problem but I always get the same error.Some info about my partitions:/dev/sda:Windows 7 System ReservedWindows 7/dev/sdb:Data (Movies, Music, etc..)/dev/sdc:Separate Boot PartitionSwapSeparate Home PartitionRoot/dev/sdd:PendriveThe followings are outputs of various programs and contents of various files.ubuntu@ubuntu:~$ sudo blkid/dev/loop0: TYPE=squashfs /dev/sdb1: LABEL=Stuff UUID=72D6355E32F06BD5 TYPE=ntfs /dev/sda1: LABEL=System Reserved UUID=A8F8AC7FF8AC4CFE TYPE=ntfs /dev/sda2: UUID=2A20B02620AFF6CB TYPE=ntfs /dev/sdc1: UUID=2a23abcf-b29f-4119-b406-0b1817e5c8e1 TYPE=ext2 /dev/sdc2: UUID=f3d9ce0d-5953-4f4e-885a-4cd2ebf6b6e9 TYPE=swap /dev/sdc3: UUID=2a53bdc8-7a9a-4dd2-9aef-5b7b4c3e74a4 TYPE=ext4 /dev/sdc4: UUID=7b4faa93-98db-49e3-ad41-92e9dc60deda TYPE=ext4 /dev/sdd1: LABEL=PENDRIVE UUID=0290-E580 TYPE=vfat menu.lsttimeout 5default 0color light-blue/black light-cyan/blue#===--- Arch Linuxtitle Arch Linuxroot (hd2,0)kernel /vmlinuz26 root=/dev/disk/by-uuid/2a53bdc8-7a9a-4dd2-9aef-5b7b4c3e74a4 ro vga=775initrd /kernel26.img#===--- Arch Linux Fallbacktitle Arch Linux Fallbackroot (hd2,0)kernel /vmlinuz26 root=/dev/disk/by-uuid/2a53bdc8-7a9a-4dd2-9aef-5b7b4c3e74a4 ro vga=775initrd /kernel26-fallback.img#===--- Windows 7title Windows 7rootnoverify (hd0,0)chainloader +1fstab# # /etc/fstab: static file system information## <file system> <dir> <type> <options> <dump> <pass>devpts /dev/pts devpts defaults 0 0shm /dev/shm tmpfs nodev,nosuid 0 0/dev/sdc1 /boot ext2 defaults 0 1/dev/sdc2 / ext4 defaults 0 1/dev/sdc3 /home ext4 defaults 0 1/dev/sdc4 swap swap defaults 0 1 | Grub won't boot Arch Linux | arch linux;grub legacy | null |
_codereview.78065 | I am trying to reverse a sentence contained in a string and return a string in the quickest way possible using the least amount of memory. Also I don't want to use any unsafe code, so no pointers are allowed. Please let me know if anything can be improved. My input example isstring mystring = Hello! my name is;My result is is name my Hello!My results on i7 4770S for 1000000 iterations is on average around 650ms.public static string ReverseTheString(string MyString){ int Length = MyString.Length; Char[] NormalArray = new char[Length]; Char[] FinalArray = new char[Length]; for (int i = 0; i < Length; i++) { NormalArray[i] = MyString[i]; } Length = Length - 1; //use for last index int SpacesCount = 0; int AlphaCount = 0; Stack<char[]> ReversedArray = new Stack<char[]>(); for (int i = 0; i < NormalArray.Length; i++) { if (NormalArray[i] == ' ' && i != Length)//Space { if (i != Length) { if (AlphaCount > 0) { char[] temparray = new char[AlphaCount]; int tempindex = i - AlphaCount; for (int j = tempindex, k = 0; k < AlphaCount; j++, k++) { temparray[k] = NormalArray[j]; } ReversedArray.Push(temparray); AlphaCount = 0; temparray = null; } SpacesCount++; } else { SpacesCount++; if (SpacesCount > 0) { char[] temparray = new char[SpacesCount]; int tempindex = i + 1 - SpacesCount; for (int j = tempindex, k = 0; k < SpacesCount; j++, k++) { temparray[k] = NormalArray[j]; } ReversedArray.Push(temparray); SpacesCount = 0; temparray = null; } } } if (NormalArray[i] != ' ' ) //alpha { if (i != Length) { if (SpacesCount > 0) { char[] temparray = new char[SpacesCount]; int tempindex = i - SpacesCount; for (int j = tempindex, k = 0; k < SpacesCount; j++, k++) { temparray[k] = NormalArray[j]; } ReversedArray.Push(temparray); SpacesCount = 0; temparray = null; } AlphaCount++; } else { AlphaCount++; if (AlphaCount > 0) { char[] temparray = new char[AlphaCount]; int tempindex = i + 1 - AlphaCount; for (int j = tempindex, k = 0; k < AlphaCount; j++, k++) { temparray[k] = NormalArray[j]; } ReversedArray.Push(temparray); AlphaCount = 0; temparray = null; } } } } int Pos = 0; while (ReversedArray.Count > 0) { char[] temparray = ReversedArray.Pop(); for (int j = 0; j < temparray.Length; j++) { FinalArray[Pos] = temparray[j]; Pos++; } } return new string(FinalArray);} | Reverse a sentence quickly without pointers | c#;performance;strings | Bug For a given string string mystring = Hello! my name is ; <- see the space at the last characteryour method fails (does not produce the correct result). Naming Based on the naming guidelines input parameters should be named using camelCase casing.Although there is nothing mentioned in the naming guidelines about naming variables which are local to methods, you should consider to use camelCase casing. int Length -> int length etc. Measurement On my pc your code runs for 1.000.000 iterations in 480 ms.Improvements by skipping NormalArray and instead using MyString[] directly you can reduce the amount of time to 470 ms. here SpacesCount++;if (SpacesCount > 0) and here AlphaCount++;if (AlphaCount> 0) you can skip the if condition, because you don't decrement SpaceCount nor AlphaCount in your code. Now your code is running in 460 ms and your code is more readable. declaring an array inside an if block limits its scope to this block. There is no need to set this array = null. So skipping temparray = null; reduces the amount of code and therefor increases readability. constructs like char[] temparray = new char[AlphaCount];int tempindex = i + 1 - AlphaCount;for (int j = tempindex, k = 0; k < AlphaCount; j++, k++){ temparray[k] = MyString[j];}are reducing the readability of the code. A better style would be char[] temparray = new char[AlphaCount];int tempindex = i + 1 - AlphaCount;for (int k = 0; k < AlphaCount; k++){ temparray[k] = NormalArray[tempindex]; tempindex++;}by skipping the whole stack and just using a char array I reduced the processing time to 70 ms.public static string ReverseTheStringM(String myString){ int length = myString.Length; char[] tokens = new char[length]; int position = 0; int lastIndex; for (int i = length - 1; i >= 0; i--) { if (myString[i] == ' ') { lastIndex = length - position; for (int k = i + 1; k < lastIndex; k++) { tokens[position] = myString[k]; position++; } tokens[position] = ' '; position++; } } lastIndex = myString.Length - position; for (int i = 0; i < lastIndex; i++) { tokens[position] = myString[i]; position++; } return new string(tokens);} |
_codereview.169173 | I'm looking for reviews about my first dockfile. I don't want to develop bad habits. The purpose is to quickly deploy my Laravel (5.4) application. I'm going to connect it with others database containers (mognodb and mysql).I used Ubuntu as parent image because it's my development environment but I planned to change it to debian or alpine later.# Use an official Ubuntu LTS as a parent imageFROM ubuntu:16.04MAINTAINER name <email>#=================================Dependencies================================# Install dependenciesRUN apt-get -qq update && \ apt-get -qq install -y --no-install-recommends \ apache2 \ composer \ curl \ git \ libapache2-mod-php7.0 \ libssl-dev \ libsslcommon2-dev \ npm \ php-curl \ php-dev \ php-mbstring \ php-mysql \ php-pear \ php-xml \ php-zip \ php7.0 \ phpunit \ pkg-config \ zip && \ # Get repository for node 8 and install it curl -sL https://deb.nodesource.com/setup_8.x | bash && \ apt-get -qq install -y nodejs && \ # Remove useless package : curl apt-get autoremove --purge -y curl && \ # Clean temporary apt data rm -rf /var/lib/apt/lists/*# Install php dependenciesRUN pecl -q install mongodb#=================================PhpSettings================================# Enable Mongo driverRUN echo extension=mongodb.so >> /etc/php/7.0/cli/php.ini && \ echo extension=mongodb.so >> /etc/php/7.0/apache2/php.ini#===============================ApacheSettings===============================# Set Apache environment variablesENV APACHE_RUN_USER www-dataENV APACHE_RUN_GROUP www-dataENV APACHE_LOG_DIR /var/log/apache2ENV APACHE_PID_FILE /var/run/apache2.pidENV APACHE_RUN_DIR /var/run/apache2ENV APACHE_LOCK_DIR /var/lock/apache2# Create Apache directoriesRUN mkdir -p $APACHE_RUN_DIR $APACHE_LOCK_DIR $APACHE_LOG_DIR# Enable 'mod_rewrite' for rewrite URL then remove 'index.php'RUN a2enmod rewrite# Copy Apache configuration fileCOPY apache2.conf /etc/apache2/apache2.confCOPY 000-default.conf /etc/apache2/sites-available/000-default.conf#=================================AppDownload================================# Create App directoryRUN mkdir /var/www/appWORKDIR /var/www/app# Copy sources without version controlRUN git clone --branch=v2.0.1 \ https://my_name:[email protected]/app/repository.git . \ && find . -name .git* -type f -delete# Add write access to storage and cacheRUN chmod -R a+w storage/ bootstrap/cache/#==========================Download/InstallVendors=========================# Download PHP vendors# Clean cacheRUN composer -q install && \ composer clear-cache# Download CSS/JS vendors# Compile required assets# Clean cache and downloadRUN npm -q install && \ npm run production && \ rm -rf node_modules && \ npm cache clean --force#=================================AppSettings================================# Set .env file with relevent settingsRUN sed -i 's/APP_ENV=\S*/APP_ENV=production/' .env && \ sed -i 's/APP_DEBUG=\S*/APP_DEBUG=false/' .env &&#===================================Cleanup===================================# Clean temporary Laravel dataRUN php artisan cache:clear && \ php artisan view:clear && \ php artisan config:cache# Remove useless foldersRUN rm -rf /var/www/html#================================RunContainer================================# Make port 80 available to the world outside this containerEXPOSE 80# Run Apache in the backgroundENTRYPOINT [ /usr/sbin/apache2 ]CMD [-D,FOREGROUND]After building the image size is 550 MB.And after run the container the application work like expected. What is right, and wrong with this dockerfile? How could I optimise it? | Dockerfile for Laravel deployment | bash;laravel;dockerfile | null |
_unix.9101 | Is there a software tool that will allow me to measure the length of a curved line? I have a series of lines in an image that I want to measure the length of. I have a tablet so I can trace over the lines in the image in order to identify the distance to be measured. There are plenty of tools that do straight lines but sofar I can't find on that does free form curves. | Measuring the length of a curved line | linux;free software;image manipulation | null |
_softwareengineering.258105 | I have been doing a lot of reading about polymorphism, inheritance and typing (specifically how it applies to Java).I have seen some interesting examples, but not much explanation as to why.I.e.: Person p = new Student();I am assuming we have a Person class and a Student class which extends the Person class.My question is: Why would you want to do this kind of assignment at all? | Why return back or assign to a supertype rather than the implementation type? | java;polymorphism | Using something like that, we can have many different types that all support the interface of Person, which means we can write code that takes a Person and doesn't care which specific type it is, as long as it supports whatever a Person supports.You might not anticipate an AncientZombieLord class when first writing some generic code that takes a Person, but if AncientZombieLord is a subtype of Person, all the code written for a Person will work for AncientZombieLord too. If you take a look at Java's collections, there are ArrayList and LinkedList types, which are both subtypes of List. They have different performance characteristics, but both support a common interface, so I can write code that uses a List that will work with either kind of list. You can use this sort of thing to write a generic algorithm that uses one type now, and then switch it to something else without needing to fiddle with a lot of code -- just change one type. In general, being able to abstract away from details that don't matter is a big win. |
_unix.261276 | #!/usr/bin/expect -fpsps -ef > test.txtNow if I want to check whether test.txt has certain keywords present, in it, how do we go about?say: 'apache' or 'fast'Can we use the if statement here, if yes, how? i'm new to shell scripting.TIA! | Check if a file contains a certain pattern? | bash;shell script | null |
_codereview.116320 | Given an angle in degrees, output a pretty string representation of its value in radians as a fraction.Where pretty means:Simplified as much as possible.With no unnecessary ones.Using the Unicode character that represents pi: With a single minus in front if negative (a minus at the denominator is not allowed).For example: degrees_to_pretty_radians(-120) #=> '-2/3'I wanted to write this in Python too to compare it to how it looked implemented in JavascriptThe code is pretty straightforward and passes a lot of test-cases, but I am still interested in any kind of feedback:def degrees_to_pretty_radians(angle: in degrees) \ -> Pretty string for the value in radians.: >>> tests = [0, 1, 18, 31, 45, 60, 120, 180, 270, 360, 480] >>> all_tests = tests + [-x for x in tests] >>> for angle in all_tests: print(angle, degrees_to_pretty_radians(angle)) 0 0 1 /180 18 /10 31 31/180 45 /4 60 /3 120 2/3 180 270 3/2 360 2 480 8/3 0 0 -1 -/180 -18 -/10 -31 -31/180 -45 -/4 -60 -/3 -120 -2/3 -180 - -270 -3/2 -360 -2 -480 -8/3 gcd = fractions.gcd(angle, 180) denominator = if 180 // gcd == 1 else /{}.format(180 // gcd) numerator = if abs(angle // gcd) == 1 else abs(angle // gcd) sign = - if angle < 0 else return {}{}{}.format(sign, numerator, denominator) | Converting an angle in degrees to a pretty string representing it in radians | python;python 3.x;formatting | Personally, function annotations are best used with types or almost-types. Unlike holroy, I appreciate their use, but like him I'd move what you put in the annotation inside the docstring. I'd instead usedef degrees_to_pretty_radians(angle: int) -> strAlternatively you can use Real or Integral from numbers as the angle parameter.Further, I'd use the argument name to clarify:def pretty_radians(*, degrees: int) -> strThis way one writespretty_radians(degrees=1234)instead ofdegrees_to_pretty_radians(1234)This is both more self-explanatory and easier to read. |
_opensource.5538 | After reading about the PocketC.H.I.P., I assumed that it comes with FLOSS only, because:Their page advertises:Open Source Hardware and Software mean you can do almost anything!Their FAQ says:Is PocketC.H.I.P. Open Source? Yes, and you can get the hardware files at our github repo.But I guess that these statements only apply to a subset of the product, as PICO-8 (which is proprietary) is pre-installed.So is there anything else? Or does it become a fully free/libre/open system (software-wise) after uninstalling PICO-8?Im not only worried about applications (PICO-8 would be in this category), but also about firmware/drivers (e.g., for the WiFi, the GPU, etc.). | Proprietary software pre-installed on the PocketC.H.I.P.? | software | null |
_softwareengineering.218078 | I've just built a self-balancing tree (red-black) in Java (language should be irrelevant for this question though), and I'm trying to come up with a good means of testing that it's properly balanced. I've tested all the basic tree operations, but I can't think of a way to test that it is indeed well and truly balanced. I've tried inserting a large dictionary of words, both pre-sorted and un-sorted. With a balanced tree, those should take roughly the same amount of time, but an unbalanced tree would take significantly longer on the already-sorted list. But I don't know how to go about testing for that in any reasonable, reproducible way. (I've tried doing millisecond tests on these, but there's no noticeable difference - probably because my source data is too small.) Is there a better way to be sure that the tree is really balanced? Say, by looking at the tree after it's created and seeing how deep it goes? (That is, without modifying the tree itself by adding a depth field to each node, which is just wasteful if you don't need it for anything other than testing.) | Unit testing to prove balanced tree | java;unit testing;junit;binary tree | One way to do this would be to create a method on your tree that measures the depth of the tree at a given node. You don't have to store the value, and if you use such a getDepth() method only for testing, then there's no extra overhead for normal tree operations. The getDepth() method would recursively traverse its child nodes and return the maximum depth found.Once you have that, you can then check that your whole tree is balanced by recursing over each node of the tree, and verifying a condition something like:Math.abs(getDepth(left) - getDepth(right)) <= 1 |
_webapps.109074 | I'm building a simple app in Google Sheets for personal use. I have a few dropdown lists on my dashboard. I have drawn forward and back buttons around them and can't figure out how I would script the buttons to move through the dropdown list (and cycle around if on the first/last option). | Script forward/back buttons to move through a dropdown list? | google spreadsheets;google apps script | null |
_softwareengineering.287187 | My boss is planning on a new db and wants to support multilingual data in this manner:LocalizedDescs (Guid / LanguageGuid being the primary key)ClusterGuidLanguageGuidDescProductCategoriesClusterGuid(...)ProductsClusterGuidCategoryGuidDetailedDescGuid(...)The way it works is that every table is having a Guid field, used as the primary key. The LocalizedDesc table's Guid field, in turn, corresponds to any guid used in tables throughout the db, making it a parent table to every table in the system.In rare cases where a table record needs another localized resource, an additional field is used in the table that will also point to a LocalizedDesc record. As an example, the Products table has a DetailedDescGuid that is meant to contain a throughout, longer description of a product. This way we have both a summary description and a detailed description, both of which can be localized to different languages.Originally, we were supposed to have a LocalizedDescGuid field in each table needing a description. But my boss claims the db indexes will be smaller if we do this the other way.Design-wise, what is this solution's worth? Was it better when it used an additional field in each table? Or are we doing this all wrong? | An approach to multilingual db design | design;architecture;database design | I would suggest the following structure due to my experiences in some other applications.First of all I would build a language table:language_id (PK)iso_country_codeiso_language_codecodepagetranslation_id (FK)The language_id would represent the primary key. Each available language is added to this table. iso_country_code can contain the ISO country code (GB - Britain, DE - Germany, ...). iso_language_code can be used to cover different located languages (e.g. en_US, en_GB,...)codepage is the codepage which will be sent out.translation_id more on this later on.The second thing should be a translation table. The translation table should hold back all translations for every translatable term.translation_id PKlanguage_id PK (FK -> language)termThe table consists of an combined primary key over translation_id and language_id which will prevent double insertion. language_id will refer to the language table.term itself will just be the translated term (e.g.: Table in german -> Tabelle)The next thing will happen on each table which holds translatable items. For example a Table which holds your products for example called products.product_id PKproduct_informationproduct_price...translation_id (FK)Only the translation_id is needed. It will refer to the translation table and retrieve the correct translation. The application can give or user session can be joined into the statement to filter the proper language for the logged in user. The other positive thing on this solution is that if you have multiple translations in different tables which all means the same but in a different context and all can have the same translation_id, they already can share the same translation_id which will reduce your data weight and will improve the translation.Hopefully this will give you a good hint and help you to improve your solution. |
_unix.141420 | I'm brand new to UNIX and I am using Kirk McElhearn's The Mac OS X Command Line to teach myself some commands. I am attempting to use tr and grep so that I can search for text strings in a regular MS-Office Word Document. $ tr '\r' '\n' < target-file | grep search-stringBut all it returns is:Illegal byte sequence.robomechanoid:Position-Paper-Final-Draft robertjralph$ tr '\r' '\n' < Position-Paper-Final-Version.docx | grep DeCSStr: Illegal byte sequencerobomechanoid:Position-Paper-Final-Draft robertjralph$ I've actually run the same line on a script that I created in vi and it does the search correctly. | tr complains of Illegal byte sequence | text processing;grep;character encoding;binary;tr | null |
_scicomp.26179 | I'm going through an article with title Solving constrained quadratic binary problems via quantum adiabatic evolution (reference 1). And there are several points confusing me a lot.This article is aimed to solve the CBQP (constrained binary quadratic programming) with the following format.\begin{align}&\min &x^{T}Qx \cr&\text{subject to} &Ax\leq b\end{align}and $x\in \lbrace0,1\rbrace^{n}$, where $Q\in Z^{n\times n}$ and $A\in Z^{m\times n}$. Let's call this optimization problem the problem $P$. The outline is like this. Suppose there is a UBQP (Unconstrained binary quadratic programming) oracle, and with the successive application of LP(linear programming), the lagrangian dual of $P$ (or lower bound of $P$ can be provided) can be solved. And then with the branch-bound-approach, the problem $P$ can be solved. I can understand almost of it until the section 5 counting the solution density on page 9. I'm not exactly sure how the branch-bound process is combined with the optimization process to finally tackle this problem. Could anyone point a direction or share some thoughts? Any comments would be greatly appreciated.ReferencesRonagh, P., Woods, B., & Iranmanesh, E. (2015). Solving constrained quadratic binary problems via quantum adiabatic evolution. arXiv preprint:1509.05001. | constrained quadratic binary problems and quantum adiabatic evolution | optimization;constrained optimization;quantum mechanics | null |
_codereview.84171 | I'm just starting out using OOP; classes and methods etc. I've been looking around for some PDO classes/wrappers out there, but there's not much to choose from. So I've tried to make my own. Started out by writing an insert method.As a man with low self esteem, I never like what I do myself, so I thought I'd ask you guys here for feedback. Here it is:public function insert($tbl, $data) { $this->_stmt = $this->_dbh->prepare(INSERT INTO $tbl ( . implode(', ', array_keys($data)) . ) VALUES (: . implode(', :', array_keys($data)) . )); foreach($data as $key => $value) { $this->_stmt->bindValue($key, $value, PDO::PARAM_STR); } $this->_stmt->execute();}The meaning was that it could all be done in one sweep instead of having several methods to do one thing; inserting a record.An example of using this code:$message = 'A message for the ones who like to read it!';$sent_on = 'Saturday 23rd 2012';$unique_id = 'unique_as_can_get';$data = array( 'message' => $message, 'sent_on' => $sent_on, 'unique_id' => $unique_id);$insert = new DB;$insert->insert('tablename', $data);I've put the database connection into the constructor.The code works as I want it to, but I'm still confused if it's accepted amongst you people who are way more skilled that I will ever be.Please let me know if this code if usable and/or what is wrong with it, what can be improved/changed etc. | Class method to insert a record into MySQL | php;mysql;classes;pdo | There's nothing wrong with it, but it's a small piece of code. Some minor details are: 1: I would write $table instead of $tbl, why abbreviate it? You also write foreach ($data as $key => $value), which is very general. Why not specify it better: `foreach ($row as $column => $value)'? What I mean is that variable names should have meaning. I know an array has keys and values, but they are general names. Here you should use names that tell you what a variable really represents.2: $this->_stmt is a class variable, where a local $statement variable would do. Local variables are always more efficient and have even better encapsulation.3: Also watch your line length: 156 characters is too much. Instead of writing this:$this->_stmt = $this->_dbh->prepare(INSERT INTO $tbl ( . implode(', ', array_keys($data)) . ) VALUES (: . implode(', :', array_keys($data)) . ));(I wrapped it for clarity), you could have written something like;$rowkeys = array_keys($row); $columns = implode(',',$rowkeys);$values = ':'.implode(',:',$rowkeys);$query = INSERT INTO $table ($columns) VALUES($values);$statement = $this->handle->prepare($query);This makes it easier to read, and debug. It may seem longer, but effectively it does the same thing. 4: You could build in error checks. Is the array a valid array to insert? Start with is_array() for instance. Do the column names exist in the table? Does the insert execute properly? No errors? 5: you could return the lastInsertID(): http://php.net/manual/en/pdo.lastinsertid.php6: You cannot insert multiple rows at once with this method. Perhaps you don't need this, but if you do you could add that functionallity.7: You bind values, so that's quite secure. However, are you sure your column names can never be influenced by outside sources (= hackers)? Another good reason to check them, because they go straight into your SQL command.8: Please note that wrapping PDO can be a burden later. See: Class for reducing development time If that puts you complete off, don't worry, I also use a wrapper despite all that good advice. |
_codereview.31543 | The backgroundTwo beginners without access to an experienced mentor write an ASP .NET MVC application, mostly simple CRUD, using Linq to SQL for the data access layer. Beginner number 1 writes the model part. I, beginner number 2, start writing controllers and views. When using the web and a textbook for learning best practices, I notice that our code differs from the established patterns in some way. Still, I create a way for the user to edit data without changing my coworker's code, and as far as we have tested, it does what it is supposed to do. If our slightly unorthodox approach works, we cannot afford to refactor the whole thing right now. But I am afraid that we can have programmed us into a corner and be too inexperienced to notice it. So please tell us: what are the potential downsides of our current implementation? A big picture of the conceptWe save edits to an entity of type Animal line in the following way: On submitting the form with the edits, the model binder returns a viewmodel to the controller. Every time the controller is initialized, it creates a a new repository instance, initializing it with a new instance of a data context. When the user submits edits, the default model binder returns a new viewmodel object to the controller action. The controller calls the viewmodel's UpdateBaseAnimalLine method, which changes the properties of the entity class. Then the controller calls the repository's Update method on the newly changed entity class. It does nothing more than calling SubmitChanges on the repository's data context. Problems I have seen so farAs far as I am aware, the data context is never disposed of in our code. After looking around, it seems that having one data context per repository instance is good practice, so we probably don't want to change that, but I cannot think of a good place to add a dispose call, what am I overlooking? The examples I found on the web use custom-written factories which provide a datacontext, and I hope there is a simpler way to do it right. It looks weird to me that we have to change the state of the actual entity object somewhere, and then just call SubmitChanges in the repository. Doesn't this open us to potential race conditions? Or is the framework intelligent enough to take care of that behind the scenes? More to the point, does it take care of it in the way we are using it? Is there a way to get the default model binder to use a viewmodel constructor which takes an int parameter, instead of just initializing all primitive type fields with the values from the form? (I suppose that it is possible if I write a custom one, but as I have a workaround, I don't want to go that deep for now). Please look into the code for further problems, I suppose there must be more than I can find. The codeAs a shortened example, we have the business entity Animal Line, with the two properties name and database ID. [Table(Name = AnimalLine)]public class AnimalLine { [Column(Name = AnimalLine_ID, IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)] public int AnimalLineId { get; set; } [Column(Name = FullName, CanBeNull = false)] public string FullName { get; set; }}There is a class functioning as a repository, called AnimalLineManagement. It can update an existing animal line either from a bunch of properties, or from an existing object. public class AnimalLineManagement{ private DataContext dataContext; private Table<AnimalLine> animalLine; public AnimalLineManagement(DataContext dataContext) { // as far as I can see, he has forgotten to dispose of the data context. this.dataContext = dataContext; animalLine = dataContext.GetTable<AnimalLine>(); } // other methods left out for brevity public bool Update(String fullName, int id) { try { var al = animalLine.SingleOrDefault(a => a.AnimalLineId == id); if (al != null) { if (!String.IsNullOrEmpty(fullName)) { al.fullName= fullName; } } dataContext.SubmitChanges(); return true; } else { return Insert(fullName); } } catch { return Insert(fullName); } } public void Update(AnimalLine al) { dataContext.SubmitChanges(); }}There is also a view model class, which wraps an actual animal line class. It provides the properties of the animal line in a way which will not produce an exception (in the real application, a call like AnimalLine.Species.LatinName produces an exception if Species is not set, and I don't want to catch this in the view in the middle of all the HTML), and packs some more info which would have been stuffed in the ViewBag else (not shown here). public class AnimalLineVM{ private AnimalLine animalLine; public string errorMessage = An error occured while trying to retrieve this information; private string fullName; //I would have preferred to always initialize the base animal line //in the constructor, but when the instance is created by the model binder, //I don't think I can do this. So I set the base animal line later, //using this variable to ensure that once set, it can't be changed. private bool animalLineAlreadySet; public AnimalLineVM(AnimalLine baseAnimalLine) { this.animalLine = baseAnimalLine; animalLineAlreadySet = true; } public AnimalLineVM() { animalLineAlreadySet = false; } public AnimalLine BaseAnimalLine { get { return animalLine; } set { if (!animalLineAlreadySet) { animalLine = value; animalLineAlreadySet = true; } else { throw new InvalidOperationException(The base animal line has already been set. It is not possible to change it.); } } } [Display(Name = ID)] public int AnimalLineId { // read only, so we cannot get a discrepancy between the base animal line and the ID in the viewmodel get { if (animalLineAlreadySet) { int id = BaseAnimalLine.AnimalLineId; if (id == null || id < 0) { return -1; } else return id; } else return -1; } } [Display(Name = Full name)] public string FullName { get { fullName = fullName ?? errorMessage; return fullName; } set { fullName = value; } } public void updateBaseAnimalLine() { BaseAnimalLine.FullName = this.FullName; }}And this is the controller: public class AnimalLineController : Controller{ private IAnimalLineManagement animalLineManagement; public TumorModelsController() :base() { animalLineManagement = new AnimalLineManagement(new DataContext(ConfigurationManager.ConnectionStrings[TumorModelsDB].ConnectionString)); }public ActionResult EditAnimalLine(int animalLineId){ AnimalLine al = animalLineManagement.GetSingleLine(animalLineId); return View(EditAnimalLine, new AnimalLineVM(al)); } //TODO: implement validation of user input [HttpPost] public ActionResult EditAnimalLine(AnimalLineVM animalLine) { int alId; if (int.TryParse(Request.Form[animalLineId], out alId)) { animalLine.BaseAnimalLine = animalLineManagement.GetSingleLine(alId); animalLine.updateBaseAnimalLine(); } return View(AnimalLine, animalLine); }} | Does this unusual data access pattern create any problems? | c#;beginner;linq to sql | null |
_webmaster.58968 | A client has a site since 1999 with a domain consisting of two, very descriptive of the business, words (let's say dog-toys.ie). In about 2001 he decided to change to dogtoys.ie (was running radio ads and figured the dash may add confusion to the site name). So without thinking too much about it, I just parked dogtoys.ie onto dog-toys.ie. Also, for both domains, we have not made www canonical so www.dogtoys.ie/example.html or dog-toys.ie/example.html are the same page.We have read many times that Google etc do not like this, however the site has performed fairly well SEO wise for the last 10 year and the client and I are torn between leaving things as is, and fixing it to make www.dogtoys.ie canonical via mod rewrite (or would the dashed version offer better performance?)Thanks in advance! | 2 x domains for same site in Google make canonical or not? | seo;google;domains;duplicate content | You're in a tough spot. You know what you're doing is problematic but so far it hasn't caught up to you yet. And you're doing fairly well in the rankings to boot so if you make any changes you risk hurting that.So you need to decide:1) Do you setup canonical URLs and make changes that can potentially affect your rankings?When things are going well SEO-wise, it is generally wise to not make any changes as even an optimization can turn out to change things for the worse. But in your case you may be feeling the effects of duplicate content and not actually realize it. While you clearly have not been removed from Google's index or received any kind of catastrophic penalty, you may have some pages that are not ranking well or could be ranking better due to duplicate content. So using canonical URLs may actually improve your rankings. Unfortunately there is no way to know unless you actually make the changes.2) Do you leave things as is and in the future potentially have your rankings plummet in the future due to duplicate content?If it ain't broke, don't fix it. I've seen many webmasters asking for help here because they made changes to a site that was doing well in the search results but they thought they could do better. But in this case waiting could mean you suddenly disappear from the search results and it could take weeks or months to get your old rankings back even if you immediately add canonical URLs.This is a business decision. Which risk is more acceptable to the business? |
_unix.217879 | I've noticed, if a file is renamed, lsof displays the new name.To test it out, created a python script:#!/bin/pythonimport timef = open('foo.txt', 'w')while True: time.sleep(1)Saw that lsof follows the rename:$ python test_lsof.py &[1] 19698$ lsof | grep foo | awk '{ print $2,$9 }'19698 /home/bfernandez/foo.txt$ mv foo{,1}.txt$ lsof | grep foo | awk '{ print $2,$9 }'19698 /home/bfernandez/foo1.txtFigured this may be via the inode number. To test this out, I created a hard link to the file. However, lsof still displays the original name:$ ln foo1.txt foo1.link$ stat -c '%n:%i' foo*foo1.link:8429704foo1.txt:8429704$ lsof | grep foo | awk '{ print $2,$9 }'19698 /home/bfernandez/foo1.txtAnd, if I delete the original file, lsof just lists the file as deleted even though there's still an existing hard link to it:$ rm foo1.txtrm: remove regular empty file foo1.txt? y$ lsof | grep foo | awk '{ print $2,$9,$10 }'19698 /home/bfernandez/foo1.txt (deleted)So finally...My questionWhat method does lsof use to keep track open file descriptors that allow it to:Keep track of filename changesNot be aware of existing hard links | How does `lsof` keep track of open file descriptors' filenames? | files;hard link;lsof;deleted files | You are right in assuming that lsof uses the inode from the kernel's name cache. Under Linux platforms, the path name is provided by the Linux /proc file system.The handling of hard links is better explained in the FAQ:3.3.4 Why doesn't lsof report the correct hard linked file path name?When lsof reports a rightmost path name component for a file with hard links, the component may come from the kernel's name cache. Since the key which connects an open file to the kernel name cache may be the same for each differently named hard link, lsof may report only one name for all open hard-linked files. Sometimes that will be correct in the eye of the beholder; sometimes it will not. Remember, the file identification keys significant to the kernel are the device and node numbers, and they're the same for all the hard linked names.The fact that the deleted node is displayed at all is also specific to Linux (and later builds of Solaris 10, according to the same FAQ). |
_webapps.102853 | I changed my relationship status a few weeks ago from single to in a relationship (leaving the person-in-question box empty). Today I want this info as-is to be publicly accessible on my profile, but not have it plastered on other people's news feeds. How do I accomplish this?Will it suffice to change the only me privacy setting to public? | Public in a relationship Facebook status without news feeding? | facebook;facebook privacy | When you change any activity, and don't want it to appear in friends News Feed, keep the audience Only Me, After sometime (around 24-hrs) change the audience to Public or Friends or any custom. It will not appear to anyone's Timeline, but whenever someone visit your profile they will be able to see latest update.So, yes, it will suffice to change the Only Me privacy setting to Public. |
_unix.191400 | I need some help with a combination of awk & while loop.I have two simple files with columns (normal ones are very large), one representing simple intervals for an ID=10(of coding regions(exons),for chromosome 10 here): #exons.bed10 60005 60100 10 61007 61130 10 61200 61300 10 61500 61650 10 61680 61850 and the other representing sequenced reads(=just intervals again but smaller) with an other value as last column, that I ll need later: #reads.bed10 60005 60010 34 10 61010 61020 4010 61030 61040 2210 61065 61070 35 10 61100 61105 41So, I would like to search in a quick and efficient way and find which read intervals (of which line in the file) and how many, fall in one coding region:exon 1(first interval of table 1) contains reads of line 1,2,3, etc. of reads.file(2nd table)so that I can get the value of 4th column of these lines later, for each exon.I 've written a code,that probably needs some corrections on the while loop, since I cannot make it parse the reads lines one by one for each awk. Here it is:while read chr a b cov; do #for the 4-column file#if <a..b> interval of read falls inside exon interval:awk '($2<=$a && $b <= $3) {print NR}' exons.bed >> out_lines.beddone < reads.bedAt the moment I can make the awk line running when I give manually a,b, but I want to make it run automatically for each a,b pair by file.Any suggestion on changing syntax, or way of doing it, is highly appreciated! FOLLOW UPFinally I worked it out with this code: awk 'NR==FNR{ a[NR]=$2; b[NR]=$3; next; } { #second file s[i]=0; m[i]=0; k[i]=0; # Add sum and mean calculation for (i in a){ if($2>=a[i] && $3<=b[i]){ # 2,3: cols of second file here k[i]+=1 print k #Count nb of reads found in out[i]=out[i] FNR # keep Nb of Line of read rc[i]=rc[i] FNR|$4 #keep Line and cov value of $4th col s[i]= s[i]+$4 #sum over coverages for each exon m[i]= s[i]/k[i] #Calculate mean (k will be the No or #reads found on i-th exon) }} } END{ for (i in out){ print Exon, i,: Reads with their COV:,rc[i],\ Sum=,s[i],Mean=,m[i] >> MeanCalc.txt }}' exons.bed reads.bedOUTPUT: Exon 2 : Reads with their COV: 2|40 3|22 4|35 5|41 Sum= 138 Mean= 34.5 etc. | Nested 'awk' in a 'while' loop, parse two files line by line and compare column values | shell script;text processing;awk;bioinformatics | The first issue is that you can't use bash variables inside awk like that. $a within awk evaluates to field a but a is empty since it is not defined in awk, but in bash. One way around this is to use awk's -v option to define the variable -v var=val--assign var=val Assign the value val to the variable var, before execution of the program begins. Such variable values are available to the BEGIN rule of an AWK program.So, you could do:while read chr a b cov; do awk -v a=$a -v b=$b '($2<=a && b <= $3) {print NR}' exons.bed > out$a$b done < reads.bedYou have another mistake there though. In order for a read to fall within an exon, the read's start position must be greater than the start position of the exon and its end position smaller than the end position of the exon. You are using $2<=a && b <= $3 which will select reads whose start is outside the exon's boundaries. What you want is $2>=a && $3<=b.In any case, running this type of thing in a bash loop is very inefficient since it needs to read the input file once for every pair of a and b. Why not do the whole thing in awk?awk 'NR==FNR{a[NR]=$2;b[NR]=$3; next} { for (i in a){ if($2>=a[i] && $3<=b[i]){ out[i]=out[i] FNR }}} END{for (i in out){ print Exon,i,contains reads of line(s)out[i],\ of reads file }}' exons.bed reads.bedThe script above produces the following output if run on your example files:Exon 1 contains reads of line(s) 1 of reads fileExon 2 contains reads of line(s) 2 3 4 5 of reads fileHere's the same thing in a less condensed form for clarity#!/usr/bin/awk -f## While we're reading the 1st file, exons.bedNR==FNR{ ## Save the start position in array a and the end ## in array b. The keys of the arrays are the line numbers. a[NR]=$2; b[NR]=$3; ## Move to the next line, without continuing ## the script. next;} ## Once we move on to the 2nd file, reads.bed { ## For each set of start and end positions for (i in a){ ## If the current line's 2nd field is greater than ## this start position and smaller than this end position, ## add this line number (FNR is the current file's line number) ## to the list of reads for the current value of i. if($2>=a[i] && $3<=b[i]){ out[i]=out[i] FNR } } } ## After both files have been processed END{ ## For each exon in the out array for (i in out){ ## Print the exon name and the redas it contains print Exon,i,contains reads of line(s)out[i], of reads file } |
_codereview.71358 | I have an interface and a concrete class which I am using in the code below: /// <summary> /// Converts a DataSet read from the DB to a list of objects of a type /// TemplatePart. /// </summary> /// <param name=templatePartDataSet>DataSet containing the information. /// </param> /// <returns>List of unprocessed TemplateParts.</returns> private static List<ITemplatePart> DataSetToTemplatePart(DataSet templatePartDataSet) { var rawTemplateParts = new List<ITemplatePart>(); foreach (DataTable table in templatePartDataSet.Tables) { var tableName = table.ToString(); foreach (DataRow row in table.Rows) { if (string.IsNullOrEmpty( row.Field<string>(Strings.TemplateSpreadSheet_Column_PartName))) { continue; } // THE LINE RELATED TO MY QUESTION. var rawTemplatePart = TemplatePart.CreateTemplatePart(table, row); rawTemplateParts.Add(rawTemplatePart); } } return rawTemplateParts; }TemplatePart is a simple class with 4 properties with the definition of:{ public class TemplatePart : ITemplatePart { #region Creator internal static TemplatePart CreateTemplatePart(DataTable table, DataRow row) { return new TemplatePart { PartName = row.Field<string>(Strings.TemplateSpreadSheet_Column_PartName), BasePart = row.Field<string>(Strings.TemplateSpreadSheet_Column_BasePart) }; } #endregion // Creator #region Public Properties public string PartName { get; set; } public string BasePart { get; set; } public double? PriceDom { get; set; } public double? PriceInt { get; set; } #endregion // Public Properties }}and the ITemplatePart as: namespace PriorityPriceGenerator2.Model.TemplatePart{ interface ITemplatePart { }}of course the interface hasn't been implemented completely. And also the concrete class doesn't have the IDisposable yet.Would you prefer (/if it's necessary or even totally wrong) to do such thing in the marked line.using (var rawTemplatePart = TemplatePart.CreateTemplatePart(table, row)) rawTemplateParts.Add(rawTemplatePart);And why? I want to know what happens to a member added to the list which is in the Using. Would it get destroyed and recreated in the List? Would it get destroyed because of using after I am done with the List ?And please, let me know if you see any other issues. | Would you utilise Using on a member which is going to be added to a list? | c#;interface | No, you shouldn't use using on the object that you add to the list.When you add the object to the list, it's just the reference to the object that gets added. There is no copy of the object created for the list.If you use using on the object, it will be disposed at the end of the code block, which is a single statement in your example. Right after you have added the object to the list it will be disposed.Although nothing happens automatically when you dispose an object, it's customary that the object should be unusable after the Dispose method has been called. The IDisposable interface is intended for controlling the lifespan of objects, usually to free unmanaged resources when you are done using the object.After you are done using the objects in the list, you should dispose them.However, from what I can tell there isn't going to be any unmanaged resources in your object, so there wouldn't be any need for it to implement IDisposable. The (supposedly) database related objects are only used during the creation of the object, and so far there are nothing unmanaged in the class. |
_webmaster.81100 | Following Google guidelines for creating an sitemap.xml file to add a href lang annotations, I'm getting display issue when viewing the sitemap.xml file in my browser.Instead of looking like a normal xml sitemap, it just displays like text on a single line:I think this is just a display issue, if you view source it looks fine and all data is there, it also tests in GWT with no errors, but what is causing it to displays like that?Here is an example of the code:<?xml version=1.0 encoding=UTF-8?><urlset xmlns=http://www.sitemaps.org/schemas/sitemap/0.9 xmlns:xhtml=http://www.w3.org/1999/xhtml><url><loc>http://www.example.com/en/</loc><xhtml:link rel=alternate hreflang=en-sg href=http://www.example.com/en/ /><xhtml:link rel=alternate hreflang=en-ph href=http://www.example.com/ph/ /><xhtml:link rel=alternate hreflang=en-my href=http://www.example.com/my/ /></url><url><loc>http://www.example.com/ph/</loc><xhtml:link rel=alternate hreflang=en-sg href=http://www.example.com/en/ /><xhtml:link rel=alternate hreflang=en-ph href=http://www.example.com/ph/ /><xhtml:link rel=alternate hreflang=en-my href=http://www.example.com/my/ /></url><url><loc>http://www.example.com/my/</loc><xhtml:link rel=alternate hreflang=en-sg href=http://www.example.com/en/ /><xhtml:link rel=alternate hreflang=en-ph href=http://www.example.com/ph/ /><xhtml:link rel=alternate hreflang=en-my href=http://www.example.com/my/ /></url></urlset> | href lang annotations in xml sitemap file displays issues | google;xml sitemap;xml;hreflang | null |
_unix.58145 | According to Wikipedia (which could be wrong)When a fork() system call is issued, a copy of all the pages corresponding to the parent process is created, loaded into a separate memory location by the OS for the child process. But this is not needed in certain cases. Consider the case when a child executes an exec system call (which is used to execute any executable file from within a C program) or exits very soon after the fork(). When the child is needed just to execute a command for the parent process, there is no need for copying the parent process' pages, since exec replaces the address space of the process which invoked it with the command to be executed.In such cases, a technique called copy-on-write (COW) is used. With this technique, when a fork occurs, the parent process's pages are not copied for the child process. Instead, the pages are shared between the child and the parent process. Whenever a process (parent or child) modifies a page, a separate copy of that particular page alone is made for that process (parent or child) which performed the modification. This process will then use the newly copied page rather than the shared one in all future references. The other process (the one which did not modify the shared page) continues to use the original copy of the page (which is now no longer shared). This technique is called copy-on-write since the page is copied when some process writes to it.It seems that when either of the processes tries to write to the page a new copy of the page gets allocated and assigned to the process that generated the page fault. The original page gets marked writable afterwards.My question is: what happens if the fork() gets called multiple times before any of the processes made an attempt to write to a shared page? | How does copy-on-write in fork() handle multiple fork? | linux;c;fork | Nothing particular happens. All processes are sharing the same set of pages and each one gets its own private copy when it wants to modify a page. |
_unix.377947 | I installed a SanDisk 240GB SSD. My old HDD will now be my storage. I've partitioned the SSD into 4 roughly 55GB partitions. I've also done a pvcreate, vgcreate, and an lvcreate for each partition named for the OS it will house. I have the .iso files saved to my HDD Downloads folder. Do I need to make a file system on each partition now before I install the OS? Or do I simply dd if=..., etc? I tried the DD route, but my boot menu only shows the SSD as a whole.Not sure what to do now. | Partitioning SSD for multiple OS's | dd | null |
_webmaster.61508 | I am running a Moodle 2.4.8 (Build: 20140113) on a Debian Squeeze box, with Apache 2.2. Whenever a user (even the admin user) makes changes to certain settings (i.e. adding a user), or just accessing certain courses (in this case, Math 9), the page pops up with a 503 error, Fatal error: $CFG->dataroot is not writable, admin has to fix directory permissions! Exiting.Checking my /config.php file, I see the path is set to /var/moodledata2, which is owned by www-data www-data, and permissions are lined up with the Moodle documentation. This was intermittent at the start of the week, but now it's getting to be constant. There is lots of free space available (as shown below):# df -hFilesystem Size Used Avail Use% Mounted on/dev/md2 83G 37G 42G 48% /tmpfs 2.0G 0 2.0G 0% /lib/init/rwudev 2.0G 224K 2.0G 1% /devtmpfs 2.0G 0 2.0G 0% /dev/shm/dev/md1 939M 35M 857M 4% /boot/dev/md3 822G 355G 426G 46% /var/dev/md4 917G 72G 799G 9% /var/moodledata2# cat config.php<?php // Moodle configuration fileunset($CFG);global $CFG;$CFG = new stdClass();$CFG->dbtype = 'mysqli';$CFG->dblibrary = 'native';$CFG->dbhost = 'localhost';$CFG->dbname = 'moodle2';$CFG->dbuser = 'root';$CFG->dbpass = '<removed>';$CFG->prefix = 'mdl_';$CFG->dboptions = array ( 'dbpersist' => 0, 'dbsocket' => 0,);$CFG->wwwroot = 'http://example.com/moodle2'; // <removed>$CFG->dataroot = '/var/moodledata2';$CFG->admin = 'admin';$CFG->directorypermissions = 0777;$CFG->passwordsaltmain = '<removed>';require_once(dirname(__FILE__) . '/lib/setup.php');// There is no php closing tag in this file,// it is intentional because it prevents trailing whitespace problems!#I'm at a loss for what to do. Permissions seem logical in how they should be (www-data owning everything, and having full access to the /var/moodledata2 folder). What is my next step? | Moodle error - Fatal error: $CFG->dataroot is not writable, admin has to fix directory permissions! Exiting. | moodle | null |
_scicomp.21106 | I want to solve a integer programming problem with binary variables $x_1,\ldots,x_n.$ I have a permutation group $G \leq S_n$ such that for every $f \in G$ the vector $\overline{x}_1,\ldots,\overline{x}_n$ is a feasible solution if and only if $\overline{x}_{f(1)}, \ldots ,\overline{x}_{f(n)}$ is a feasible solution.I am wondering whether there is any clever way to take into account the symmetries given by $G?$If we fix a specific $f \in G$ we can always add the single constraint $x_1 \leq x_{f(1)}$ but I don't see how to fully generalize this for the whole domain of $f$ and perhaps every element of $G.$I am well aware of the following exposition but I'm yet to see if the presented approaches work well for this case.In the meantime I wanted to pose this question here in case there is an obvious solution.Edit. To clarify the question. I was wondering if there is a way to encode the symmetry of $G$ as constraints of the integer program. I've tried using both CPLEX and Gurobi, setting both to exploit symmetries to the maximum but I am pretty sure they do not get the full range of symmetries and are performing quite a large chunk of redundant computation. | Breaking symmetries in a (binary) integer program | linear programming;mixed integer programming;symmetry | null |
_unix.303613 | Under Linux, I have a process that is blocked in uninterruptible sleep (state D). How can I investigate what's causing this?I am running an ordinary kernel (a Debian build), without any special debugging features.There is no relevant log entry in fact nothing got logged between the time the process started and the time I noticed it.strace can't even attach to the process since it's in uninterruptible sleep. And even if I knew what system call was called, that wouldn't necessarily help me. I need to know what's going on inside the kernel.Specifically, the sync command goes into uninterruptible sleep :( So I must have an I/O problem somewhere but all my filesystems appear to work normally. There may well be an old log entry about an I/O error but I can't find it (this machine hasn't rebooted in a long time, that's a lot of log entries). Can I at least know which subsystem is blocking sync? For example, get a kernel backtrace for the kernel thread corresponding to a particular PID/TID?(I'm sure that rebooting would either fix this or reveal the error but I'm asking how to investigate this, not how to blindly press a button.) | Find the cause of a permanently-blocked I/O (process in uninterruptible sleep) | linux;process;io;debugging | null |
_unix.165229 | Below is my shell script which is written in another x to find the health of server y. ( I have not written in server y because there is no functionality of getting mails) #!/bin/bashtarget=10.9.34.52count=$( ping -c 5 $target | grep icmp* | wc -l )if [ $count -eq 0 ]then echo The Tomcat Dev server GMP_Dev_Tomcat_cvgrhegmpd003 with ip address 10.9.34.52 is DOWN Please check your server ASAP | mail -s Dev Tomcat Server Status [email protected] echo The Tomcat Dev server GMP_Dev_Tomcat_cvgrhegmpd003 with ip address 10.9.34.52 is UP and WORKINGfiI am not getting any alert. I have added my shell script to crontab -e which runs every 1 min. But if I run the script ./scriptname.sh, I do get mails (I was checking when my server was up). | Unix shell script for server alerts | shell;ping | null |
_unix.151333 | I've become far too trained to use <C-C> to return to normal mode. I understand there is a difference between <C-C> and <ESC> but that's beside the point of this question.I use the mapping nnoremap <C-C> <silent> <C-C> so I don't see the message Type :quit<Enter> to exit vim when pressing <C-C> in normal mode.When in normal mode and pressing r I can't cancel with <C-C>, instead it will just insert the non printable character. Is there a way to change this behavior? | Vim: Exit single character replace mode with when using `nnoremap ` | vim | First, thatnnoremap <C-C> <silent> <C-C>has the <silent> parameter in the wrong position; it works, but not the way you think it does (and it beeps). Better use this:nnoremap <C-C> <Nop>To avoid the insertion of ^C when aborting r, define a special mapping for that, too:nnoremap r<C-c> <Nop> |
_reverseengineering.6089 | I'm trying to create a .sig file for sqlite3. I downloaded the source code from the website, compiled it into a .lib (smoothly), and this is what I get when I try to turn it into a .pat file:plb.exe -v sqlite.libsqlite.lib: invalid module at offset 143146. Skipping.sqlite.lib: invalid module at offset 2587742. Skipping.sqlite.lib: skipped 2, total 2The resulting .pat file is empty and I cannot proceed to create the final file with sigmake.Google doesn't seem to indicate that anyone has ever had an invalid module at offset problem in the entire world, so I'm guessing this is pretty unique. I'm stuck. Help? | Unable to create FLIRT signature for IDA | ida;flirt signatures | plb.exe is designed for OMF libraries (primarily used for 16 bit Borland compilers). What you probably want is pcf.exe, which parses COFF libraries commonly used in 32 bit windows. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.