id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_opensource.625 | Many programming languages have popular open-source implementations: C, C++, Java, Javascript, Python, C#, PHP. Does statistical data exist that shows how much of the software (open source or not) is built with open source compilers or interpreters and how much with closed source? And does the data provide historical data, so that it can be seen if the usage of open-source development systems in programming has increased or decreased over time? | Are there statistics showing the usage over time of open source implementations of programming languages compilers/interpreters? | history;statistics | The data from blackduck isn't broken down by open/closed compilers, but it does cover the specific languages and provide historical information.Additionally, it is focused on language use solely within open source projects. Obtaining this information for closed/proprietary projects is obviously problematic.With the possible exception of the Visual Studio/.NET specific languages such as VB.NET, and probably C# and Apple's objective C, I suspect that most of the compiled language use is from gcc (which is, of course, more than just a c or c++ compiler).This is especially likely as I doubt too many open source projects use proprietary compilers, as the cost is a barrier to contributions.This is the closest I've been able to find in the ten days since you asked the question. |
_cstheory.25129 | The Watts-Strogatz model describes a mechanism of generating small-world networks.The idea is to start from a ring network in which each node is connected a fixed number of its closest neighbors. After that, a rewiring is performed in which each link present in the network has a probability $p$ of changing one of its endpoints to a new random node. The closer $p$ to 1, the more random is the network.Is there a similar small-world model for bipartite graphs? That is, is there a mechanism for generating random bipartite graphs that possess the usual properties of small-world networks (a.k.a., the maximum of the minimum distance between any pair of nodes scales no higher than as the logarithm of the number of nodes)? | Bipartite small-world networks | graph theory;network modeling | null |
_softwareengineering.67923 | What methods seem to work best to coax requirements out of non-tech business people? I am working with a team thats trying to get a spec together for a project. Every time we have met and it comes down to expectations for the next meeting, we ask for the business people to bring back their requirements. They usually respond something like this: Well, do you think you guys could whip up a prototype so we can see what we like next weekyou know, not with any data or anything since its a prototype, just the functionality. This is a 6 month plus project so that is obviously infeasible (we would have to develop the entire thing!), and we dont even know what to prototype without some sort of spec. Frankly, I think like most people, they have some idea of what they want, they just are not thinking about it in the focused sort of way necessary to gather true requirements. As an alternative to simply telling them, give us what you want or we cant/wont do any work (we do want them to be happy with the results), are there ways to help them decide what they want? For example, we could tell them:Draw out some screens (in Powerpoint, on a napkin, whatever) that show the UI you would like with all of the data you want to see and a description of the functionality in the margins. From this, we will polish it up and build the backend based on this set of behavior requirements.ORDont worry about how it will look right now (the number 1 hang up). Just give us a list of all the data you want about each thing the program keeps track of. So for Customer you might list: name, address, phone number, orders, etc. It does not have to be a perfect database structure, but we can work something out from this and get an idea of what you are looking forDo either of these alternative approaches to get business people focused on what they want make sense? Are there alternatives that you have seen in action? | Coaxing requirements out of business people? | design;business;requirements | I have spent the last 3 months in an exhaustive - and exhausting - requirements-gathering phase of a major project and have learned, above all else, that there is no one-size-fits-all solution. There is no process, no secret, that will work in every case. Requirements analysis is a genuine skill, and just when you think you've finally figured it all out, you get exposed to a totally different group of people and have to throw everything you know out the window.Several lessons that I've learned:Different stakeholders think at different levels of abstraction.It is easy to say talk at a business level, not technical, but it's not necessarily that easy to do. The system you're designing is an elephant and your stakeholders are the blind men examining it. Some people are so deeply immersed in process and routine that they don't even realize that there is a business. Others may work at the level of abstraction you want but be prone to making exaggerated or even false claims, or engage in wishful thinking.Unfortunately, you simply have to get to know all of the individuals as individuals and understand how they think, learn how to interpret the things they say, and even decide what to ignore.Divide and ConquerIf you don't want something done, send it to a committee.Don't meet with committees. Keep those meetings as small as possible. YMMV, but in my experience, the ideal size is 3-4 people (including yourself) for open sessions and 2-3 people for closed sessions (i.e. when you need a specific question answered).I try to meet with people who have similar functions in the business. There's really very little to gain and very much to lose from tossing the marketing folks in the room with the bean counters. Seek out the people who are experts on one subject and get them to talk about that subject.A meeting without preparation is a meeting without purpose.A couple of other answers/comments have made reference to the straw-man technique, which is an excellent one for those troublesome folks that you just can't seem to get any answers out of. But don't rely on straw-men too much, or else people will start to feel like you're railroading them. You have to gently nudge people in the right direction and let them come up with the specifics themselves, so that they feel like they own them (and in a sense, they do own them).What you do need to have is some kind of mental model of how you think the business works, and how the system should work. You need to become a domain expert, even if you aren't an expert on the specific company in question. Do as much research as you can on your business, their competitors, existing systems on the market, and anything else that might even be remotely related.Once at that point, I've found it most effective to work with high-level constructs, such as Use Cases, which tend to be agreeable to everybody, but it's still critical to ask specific questions. If you start off with How do you bill your customers?, you're in for a very long meeting. Ask questions that imply a process instead of belting out the process at the get-go: What are the line items? How are they calculated? How often do they change? How many different kinds of sales or contracts are there? Where do they get printed? You get the idea.If you miss a step, somebody will usually tell you. If nobody complains, then give yourself a pat on the back, because you've just implicitly confirmed the process.Defer off-topic discussions.As a requirements analyst you're also playing the role of facilitator, and unless you really enjoy spending all your time in meetings, you need to find a way to keep things on track. Ironically, this issue becomes most pernicious when you finally do get people talking. If you're not careful, it can derail the train that you spent so much time laying the tracks for.However - and I learned this the hard way a long time ago - you can't just tell people that an issue is irrelevant. It's obviously relevant to them, otherwise they wouldn't be talking about it. Your job is to get people saying yes as much as possible and putting up a barrier like that just knocks you into no territory.This is a delicate balance that many people are able to maintain with action items - basically a generic queue of discussions that you've promised to come back to sometime, normally tagged with the names of those stakeholders who thought it was really important. This isn't just for diplomacy's sake - it's also a valuable tool for helping you remember what went on during the meetings, and who to talk to if you need clarification later on.Different analysts handle this in different ways; some like the very public whiteboard or flip-chart log, others silently tap it into their laptops and gently segue into other topics. Whatever you feel comfortable with.You need an agendaThis is probably true for almost any kind of meeting but it's doubly true for requirements meetings. As the discussions drag on, people's minds start to wander off and they start wondering when you're going to get to the things they really care about. Having an agenda provides some structure and also helps you to determine, as mentioned above, when you need to defer a discussion that's getting off-topic.Don't walk in there without a clear idea of exactly what it is that you want to cover and when. Without that, you have no way to evaluate your own progress, and the users will hate you for always running long (assuming they don't already hate you for other reasons).Mock ItIf you use PowerPoint or Visio as a mock-up tool, you're going to suffer from the issue of it looking too polished. It's almost an uncanny valley of user interfaces; people will feel comfortable with napkin drawings (or computer-generated drawings that look like napkin drawings, using a tool like Balsamiq or Sketchflow), because they know it's not the real thing - same reason people are able to watch cartoon characters. But the more it starts to look like a real UI, the more people will want to pick and paw at it, and the more time they'll spend arguing about details that are ultimately insignificant.So definitely do mock ups to test your understanding of the requirements (after the initial analysis stages) - they're a great way to get very quick and detailed feedback - but keep them lo-fi and don't rush into mocking until you're pretty sure that you're seeing eye-to-eye with your users.Keep in mind that a mock up is not a deliverable, it is a tool to aid in understanding. Just as you would not expect to be held captive to your mock when doing the UI design, you can't assume that the design is OK simply because they gave your mock-up the thumbs-up. I've seen mocks used as a crutch, or worse, an excuse to bypass the requirements entirely; make sure you're not doing that. Go back and turn that mock into a real set of requirements.Be patient.This is hard for a lot of programmers to believe, but for most non-trivial projects, you can't just sit down one time and hammer out a complete functional spec. I'm not just talking about patience during a single meeting; requirements analysis is iterative in the same way that code is. Group A says something and then Group B says something that totally contradicts what you heard from Group A. Then Group A explains the inconsistency and it turns out to be something that Group C forgot to mention. Repeat 500 times and you have something roughly resembling truth.Unless you're developing some tiny CRUD app (in which case why bother with requirements at all?) then don't expect to get everything you need in one meeting, or two, or five. You're going to be listening a lot, and talking a lot, and repeating yourself a lot. Which isn't a terrible thing, mind you; it's a chance to build some rapport with the people who are inevitably going to be signing off on your deliverable.Don't be afraid to change your technique or improvise.Different aspects of a project may actually call for different analysis techniques. In some cases classical UML (Use Case / Activity diagram) works great. In other cases, you might start out with business KSIs, or brainstorm with a mind map, or dive straight into mockups despite my earlier warning.The bottom line is that you need to understand the domain yourself, and do your homework before you waste anyone else's time. If you know that a particular department or component only has one use case, but it's an insanely complicated one, then skip the use case analysis and start talking about workflows or data flows. If you wouldn't use the same tool for every part of an app implementation, then why would you use the same tool for every part of the requirements?Keep your ear to the ground.Of all the hints and tips I've read for requirements analysis, this is probably the one that's most frequently overlooked. I honestly think I've learned more eavesdropping on and occasionally crashing water-cooler conversations than I have from scheduled meetings.If you're accustomed to working in isolation, try to get a spot around where the action is so that you can hear the chatter. If you can't, then just make frequent rounds, to the kitchen or the bathroom or wherever. You'll find out all kinds of interesting things about how the business really operates from listening to what people brag or complain about during their coffee and smoke breaks.Finally, read between the lines.One of my biggest mistakes in the past was being so focused on the end result that I didn't take the time to actually hear what people were saying. Sometimes - a lot of the time - it might sound like people are blathering on about nothing or harping about some procedure that sounds utterly pointless to you, but if you really concentrate on what they're saying, you'll realize that there really is a requirement buried in there - or several.As corny and insipid as it sounds, the Five Whys is a really useful technique here. Whenever you have that knee-jerk that's stupid reaction (not that you would ever say it out loud), stop yourself, and turn it into a question: Why? Why does this information get retyped four times, then printed, photocopied, scanned, printed again, pinned to a particle board, shot with a digital camera and finally e-mailed to the sales manager? There is a reason, and they may not know what it is, but it's your job to find out. Good luck with that. ;) |
_unix.59182 | I resized with lvresize the swap from 4 to 2G and can't turn it on. swapon /dev/VolGroup/lv_swapswapon: /dev/VolGroup/lv_swap: swapon failed: Invalid argumentlvdisplay /dev/VolGroup/lv_swap --- Logical volume --- LV Name /dev/VolGroup/lv_swap VG Name VolGroup LV UUID h7DEfK-cdVr-UzeQ-8qDJ-rAhH-ejYS-k2wyY6 LV Write Access read/write LV Status available # open 0 LV Size 2.06 GiB Current LE 66 Segments 1 Allocation inherit Read ahead sectors auto - currently set to 256 Block device 253:1 | Turn on Swap after resize / | lvm;swap | You need to run mkswap on that device:# mkswap /dev/VolGroup/lv_swapResizing the device will not, by itself, re-prepare the device for swapping. |
_reverseengineering.5896 | Immunity Debugger offers a feature called PyPlugin. However there is not enough documentation on it. The help for immdbg says this :PyPlugins are python scripts located at PyPlugins\ directory, PyPlugins are called when F4 or the PyPlugin icon located at the main toolbar are pressed. Both (F4 or the PyPlugin icon) will popup a file browse dialog, where the starting folder is the PyPlugin Directory. When a pyplugin is executed, its main() gets called. Please note a pyplugin can not receive any arguments and will not return any value other than inscreen errors.In reality when the F4 key is pressed, nothing special happens. F4 is actually the shortcut to Run to selection. Further there is no PyPlugin icon located at the main toolbar. The PyPlugins directory under Immunity Debugger directory is also empty, so no examples to look.My question is what is a PyPlugin ? Are there any ready made PyPlugins to refer as an example ?Note : I am only talking about PyPlugins, not PyCommands | Immunity Debugger PyPlugin | python;immunity debugger | Going over ImmunityDbg presentation - page 26, v1.73 dir - dir structureImmDbg help file - PyHooks ... they look exactly as a python plugin, only that they are placed inside PyHooks directory.I'm making and educated guess that PyPlugins is probably a leftover from previous versions of the debugger and at some point it became known as PyScripts.So, the actual examples and guidance could be found here |
_unix.263683 | I installed Letsencrypt during the beta, following the instructions in the email, and now it seems broken on my debian jessie server.I try to uninstall letsencrypt and want to start over with my (misconfigured apache)What I did:mkdir -p /backupsmv /etc/letsencrypt /backups/cp -a /etc/apache2/sites-available /backups/for i in /etc/apache2/sites-available/* ; do sed -i '/letsencrypt/d' $i; donerm /etc/apache2/sites-available/*ssl.conf /etc/apache2/sites-enabled/*ssl.confapache2ctl gracefulIs this enough? Or are there more files that would make a problem, when I start over again? | Uninstall all changes made by Letsencrypt | ssl;letsencrypt | null |
_softwareengineering.227812 | I start every .java file in my project with a license (BSD, in my case). And its first line says:/** * Copyright (c) 2011-2014, Firstname Lastname * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions etc.The question is, why do I need to show years there? I see many other projects are doing the same. What will I lose by just saying Copyright (c) Firstname Lastname, without that time interval. | Why do we need years in a software license? | licensing | null |
_opensource.2880 | I'm using portlet-api.jar within my maven project, but I can't find any hint on an applicable license. Is it public domain? And if so, is it written down somewhere?<dependency> <groupId>javax.portlet</groupId> <artifactId>portlet-api</artifactId> <version>1.0</version></dependency> | What license is portlet-api.jar in version 1.0? | licensing;relicensing;java | The answer isn't all that obvious. The portlet-api 1.0 POM on Maven Central contains a link to the original download URL, which is that of JSR-168, the portlet spec. Downloads there are made available pursuant to the acceptance of a software license agreement which is typical of JSRs and not open source. Further, the archive you get then contains a license.txt file which doesn't grant any rights, and the source code is marked asCopyright 2003 IBM Corporation and Sun Microsystems, Inc.All rights reserved.Use is subject to license terms.There is however an Apache 2.0-licensed repository, hosted by the Apache Software Foundation. Given that the Maven Central JAR was built by Emmanuel Venisse of the ASF (as documented the manifest in the JAR), it's quite likely that it is effectively Apache-licensed.I don't know what the history of the code is, so you may take all this with a pinch of salt. The ASF are careful about the code they host though, so the risk is minimal; Debian uses that to build its own portlet-api JARs. |
_unix.387635 | During the installation of e.g. Ubuntu with the debian-installer, is there any visible (debug) output, where I can see what is downloaded from where?(I have a local mirror configured, but it is so slow that I want to investigate the situation.)The problems are:the installer does neither show from where it downloads, nor the speed in its normal outputin /var/log/syslog is constantly filled with status updatesthe pager more of busybox cant scroll back nor search, so it is hard to tell if the installer even echoed the server before downloading a bunch of filesps does not reveal wget or any other download tool with argumentsthere is no netstat or ntop or similar installedIm not sure where the files are downloaded, so I cant not even make a download speed estimate with ls -la by watching some files grow | Can I debug download/network issues while using a standard ISO with debian-installer? | debian;ubuntu;system installation;busybox;debian installer | null |
_codereview.3770 | I'm writing a BitTorrent client. Part of the protocol is an exchange of length-prefixed messages between peers. The forms of these messages are described in the official specification and also in the unofficial specification that is maintained by the community. This is my code for writing out this messages into a stream. I'm currently using C++11 as supported by GCC 4.6.I have a header file:#ifndef MESSAGE_HPP#define MESSAGE_HPP#include <ostream>#include <string>#include <type_traits>namespace greed { // This type defines all the message types and the matching codes // It uses C++11's ability to define an enum's underlying type enum message_type : signed char { // this keep_alive as negative is a hack I'm not too happy with keep_alive = -1, choke = 0, unchoke = 1, interested = 2, not_interested = 3, have = 4, bitfield = 5, request = 6, piece = 7, cancel = 8 }; // There are three basic kinds of messages // These three basic templates are used in CRTP below // - messages with no payload: these contain only the length // and the type code template <message_type Type> struct no_payload_message { std::ostream& put(std::ostream& os) const; }; // - messages with a fixed-length payload: these contain the length, // the type code, and a payload of a fixed-length, that is // determined by the message type. template <typename Message> struct fixed_payload_message { std::ostream& put(std::ostream& os) const; }; // - messages with a payload of variable length: these contain the length, // the type code, and the payload. template <typename Message> struct variable_payload_message { std::ostream& put(std::ostream& os) const; }; // A template definition for messages, templated on the message type. template <message_type Type> struct message {}; // A specialization for keep-alives, which are special messages that // consist of a single zero byte. template<> struct message<keep_alive> { public: std::ostream& put(std::ostream& os) const; }; // Specializations for the no-payload messages types // The only difference between these is the message type. template <> struct message<choke> : public no_payload_message<choke> {}; template <> struct message<unchoke> : public no_payload_message<unchoke> {}; template <> struct message<interested> : public no_payload_message<interested> {}; template <> struct message<not_interested> : public no_payload_message<not_interested> {}; // The specializations for fixed-length payload messages contain: // - appropriate constructors // - a type that defines the format of the message (data_type) // - a function that returns the data (data) // These are used by the fixed_payload_message template template<> struct message<have> : public fixed_payload_message<message<have>> { public: message() = delete; explicit message(unsigned index); struct data_type; data_type data() const; private: unsigned index; }; // The specializations for variable-length payload messages contain: // - appropriate constructors // - a type that defines the format of the message (data_type) // - a function that returns the variable payload (payload) // - a function that writes out the parts of the message that are not variable (init) // These are used by the variable_payload_message template template<> struct message<bitfield> : public variable_payload_message<message<bitfield>> { public: message() = delete; explicit message(std::string bits); const std::string payload() const; struct data_type; void init(char* ptr) const; private: std::string bits; }; template<> struct message<request> : public fixed_payload_message<message<request>> { public: message() = delete; message(unsigned index, unsigned begin, unsigned length); struct data_type; data_type data() const; private: unsigned index; unsigned begin; unsigned length; }; template<> struct message<piece> : public variable_payload_message<message<piece>> { public: static const message_type id = piece; message() = delete; message(unsigned index, unsigned begin, std::string block); const std::string payload() const; struct data_type; void init(char* ptr) const; private: unsigned index; unsigned begin; std::string block; }; template<> struct message<cancel> : public fixed_payload_message<message<cancel>> { public: message() = delete; message(unsigned index, unsigned begin, unsigned length); struct data_type; data_type data() const; private: unsigned index; unsigned begin; unsigned length; }; // A simple type trait that determines if a type is a message type template <typename NonMesssage> struct is_message : std::false_type {}; template <message_type Type> struct is_message<message<Type>> : std::true_type {}; // Implementation of operator<< for all message types // This requires the put member function template <typename Message> std::ostream& operator<<(std::ostream& os, typename std::enable_if<is_message<Message>::value,const Message&>::type message);}#endifAnd an implementation file:#include message.hpp// this header contains the hton function#include util.hpp#include <memory>#include <new>namespace greed { // simple implementation of operator<< for messages template <typename Message> std::ostream& operator<<(std::ostream& os, const Message& message) { return message.put(os); } // implementation of no-payload message base class template <message_type Type> std::ostream& no_payload_message<Type>::put(std::ostream& os) const { // make sure this struct is not padded or anything // this is a gcc attribute, I'll change this when there is // support for the C++11 attribute alignas struct __attribute__ ((packed)) data_type { unsigned len; message_type type; }; // hton is a function that converts from host-endianness to network-endianness data_type buffer = { hton(sizeof(data_type)-sizeof(data_type::len)), Type }; // lay out the length and the message type return os.write(reinterpret_cast<char*>(&buffer), sizeof(data_type)); // write it } // implementation of fixed-length payload message base class template <typename Message> std::ostream& fixed_payload_message<Message>::put(std::ostream& os) const { auto buffer = static_cast<const Message*>(this)->data(); // get the data from the derived class return os.write(reinterpret_cast<char*>(&buffer), sizeof(buffer)); // write it } // implementation of variable-length payload message base class template <typename Message> std::ostream& variable_payload_message<Message>::put(std::ostream& os) const { typedef typename Message::data_type header_type; auto m = static_cast<const Message*>(this); const auto payload = m->payload(); // get the payload const auto data_type_size = sizeof(header_type)+payload.size(); // get the total size std::unique_ptr<char[]> mem(new char[data_type_size]); // allocate a buffer for it m->init(mem.get()); // write out the fixed-length portion std::copy(payload.begin(), payload.end(), mem.get()+sizeof(header_type)); // copy the payload to the buffer return os.write(mem.get(), data_type_size); // write it } std::ostream& message<keep_alive>::put(std::ostream& os) const { return os.put(0); // keep-alives are just a simple zero byte } message<have>::message(unsigned index) : index(index) {} struct __attribute__ ((packed)) message<have>::data_type{ unsigned len; message_type type; unsigned index; }; // have message data message<have>::data_type message<have>::data() const { return data_type{ hton(sizeof(data_type)-sizeof(data_type::len)), have, hton(index) }; } message<bitfield>::message(std::string bits) : bits(bits) {} struct __attribute__ ((packed)) message<bitfield>::data_type { unsigned len; message_type type; }; // bitfield message payload const std::string message<bitfield>::payload() const { return bits; } void message<bitfield>::init(char* ptr) const { // construct a new message<bitfield>::data_type in place new(ptr) data_type{ hton(sizeof(data_type)-sizeof(data_type::len)+bits.size()), bitfield }; } message<request>::message(unsigned index, unsigned begin, unsigned length) : index(index), begin(begin), length(length) {} struct __attribute__ ((packed)) message<request>::data_type { unsigned len; message_type type; unsigned index; unsigned begin; unsigned length; }; // request message data message<request>::data_type message<request>::data() const { return data_type{ hton(sizeof(data_type)-sizeof(data_type::len)), request, hton(index), hton(begin), hton(length) }; } message<piece>::message(unsigned index, unsigned begin, std::string block) : index(index), begin(begin), block(block) {} struct __attribute__ ((packed)) message<piece>::data_type { unsigned len; message_type type; unsigned index; unsigned begin; }; const std::string message<piece>::payload() const { return block; } void message<piece>::init(void* ptr) const { // construct a new message<piece>::data_type in place new(ptr) data_type{ hton(sizeof(data_type)-sizeof(data_type::len)+block.size()), piece, index, begin }; } message<cancel>::message(unsigned index, unsigned begin, unsigned length) : index(index), begin(begin), length(length) {} struct __attribute__ ((packed)) message<cancel>::data_type { unsigned len; message_type type; unsigned index; unsigned begin; unsigned length; }; // cancel message data message<cancel>::data_type message<cancel>::data() const { return data_type{ hton(sizeof(data_type)-sizeof(data_type::len)), cancel, hton(index), hton(begin), hton(length) }; } // explicit template instantiations for all message types template struct message<keep_alive>; template struct message<choke>; template struct message<unchoke>; template struct message<interested>; template struct message<not_interested>; template struct message<have>; template struct message<bitfield>; template struct message<request>; template struct message<piece>; template struct message<cancel>; template std::ostream& operator<<(std::ostream& os, const message<keep_alive>& message); template std::ostream& operator<<(std::ostream& os, const message<choke>& message); template std::ostream& operator<<(std::ostream& os, const message<unchoke>& message); template std::ostream& operator<<(std::ostream& os, const message<interested>& message); template std::ostream& operator<<(std::ostream& os, const message<not_interested>& message); template std::ostream& operator<<(std::ostream& os, const message<have>& message); template std::ostream& operator<<(std::ostream& os, const message<bitfield>& message); template std::ostream& operator<<(std::ostream& os, const message<request>& message); template std::ostream& operator<<(std::ostream& os, const message<piece>& message); template std::ostream& operator<<(std::ostream& os, const message<cancel>& message);}I'm a bit unsure about how I dealt with the variable-length messages, especially the usage of placement new, without calling the destructor.So, opinions? | BitTorrent peer protocol messages | c++;c++11;memory management;networking | enum message_type : signed charDo you have a specific reason (e.g. protocol requirements?) that this be signed? Bit-level stuff usually involves unsigned types. The protocol specs also explicity mention the size of the message type field: a single byte. So I recommend std::uint8_t here. // A template definition for messages, templated on the message type. template <message_type Type> struct message {};If only the specializations are meant to be used (I couldn't tell from looking at your code), I usually 'forbid' the base template to catch mistakes early. Errors about how message<...> has no put member are confusing and not necessarily near the code that instantiated the template. The simplest way to do it is to leave the template undefined but lately I've been using a trick: static_assert( dependent_false<Type>::value, Only specializations should be used );, where dependent_false<T>::value is always false but won't trigger the assert until instantiation (whereas static_assert( false, ... ) always triggers and won't let you compile, ever.) template<> struct message<bitfield> : public variable_payload_message<message<bitfield>> { public: message() = delete; explicit message(std::string bits); const std::string payload() const;I'd prefer returning std::string here. (Ditto for message<piege>::payload.) // A simple type trait that determines if a type is a message type template <typename NonMesssage> struct is_message : std::false_type {}; template <message_type Type> struct is_message<message<Type>> : std::true_type {};Lately I've been making my traits more convenient to use by adding forwarding specializations: template<typename T> struct is_message<T&>: is_message<T> {};, and another one for const. They help with perfect forwarding because if you have e.g. template<typename M> void perfectly_forwarded(M&&); then M might be T const& for some T. Since you're not doing that in your code I don't think you need it -- just a head's up. // Implementation of operator<< for all message types // This requires the put member function template <typename Message> std::ostream& operator<<(std::ostream& os, typename std::enable_if<is_message<Message>::value,const Message&>::type message);Deduction can't work here. C++03-style code uses enable_if at the return type, or when there is no return type (e.g. constructors) as a default argument. Maybe you tried to 'collapse' the default argument with the actual, interesting parameter, but you can't do that. C++0x-style code can put enable_if as a defaulted template parameters but that's moot since you really want (credit to CatPlusPlus):template<message_type M>std::ostream&operator<<(std::ostream& os, message<M> const& m); // simple implementation of operator<< for messagesChange definition to match previous declaration. // implementation of no-payload message base class template <message_type Type> std::ostream& no_payload_message<Type>::put(std::ostream& os) const { // make sure this struct is not padded or anything // this is a gcc attribute, I'll change this when there is // support for the C++11 attribute alignas struct __attribute__ ((packed)) data_type { unsigned len; message_type type; }; // hton is a function that converts from host-endianness to network-endianness data_type buffer = { hton(sizeof(data_type)-sizeof(data_type::len)), Type }; // lay out the length and the message type return os.write(static_cast<char*>(&buffer), sizeof(data_type)); // write it }Again, following protocol specs, I'd make len a std::uint32_t. The unofficial spec use 1 as the length, I'm not sure what you're computing here. Minor note: I always write os.write(static_cast<char*>(&buffer), sizeof buffer) to future-proof (unlikely to matter here but still). // implementation of fixed-length payload message base class template <typename Message> std::ostream& fixed_payload_message<Message>::put(std::ostream& os) const { auto buffer = static_cast<const Message*>(this)->data(); // get the data from the derived class return os.write(static_cast<char*>(&buffer), sizeof(buffer)); // write it }And in fact here you do take the size of the object! // implementation of variable-length payload message base class template <typename Message> std::ostream& variable_payload_message<Message>::put(std::ostream& os) const { typedef typename Message::data_type header_type; auto m = static_cast<const Message*>(this); const auto payload = m->payload(); // get the payload const auto data_type_size = sizeof(header_type)+payload.size(); // get the total size std::unique_ptr<char[]> mem(new char[data_type_size]); // allocate a buffer for it m->init(mem.get()); // write out the fixed-length portion std::copy(payload.begin(), payload.end(), mem.get()+sizeof(header_type)); // copy the payload to the buffer return os.write(mem.get(), data_type_size); // write it }I don't see the need to copy the final message into a buffer. Why not use two calls to ostream::write? You could replace the init members (which you already dislike) with a data member like the fixed-length messages.// Lots of definitions/instantiationsAgain, I didn't check conformance to the specs. I also already mentioned to you how most of the explicit instantiations aren't needed.I'd also write sizeof field0 + sizeof field1 + ... for computing the various sizes that you need rather than subtracting from the total size. I'd do that for clarity and I don't think it's a correctness issue however.Final remarks on the general design:I think you're somewhat abusing specializations here: there's is no need (IMO) for a message catch-all template since the three kinds of messages are not similar in use. This really shows I think with the constructors that aren't compatible: you can't write a generic message<M> m(arguments go here);. Personally I'd have used overloaded function templates to return those three types.Also I personally typically use std::vector<unsigned char> for binary stuff rather than std::string but I don't think that really matters (plus you may have a use for some std::string-specific stuff that is not in the code you presented). |
_unix.361135 | I have a USB-Stick from which I would like to read the serial number.If I invoke the command lsusb -v the output in the line iSerial is as follows:iSerial 3If i go to /proc/scsi/usb-storage and look into the file i get the following output:Host scsi10: usb-storageVendor: USBProduct: Disk 2.0Serial Number: 92071573E1272519149Protocol: Transparent SCSITransport: BulkQuirks:Why is there no serial output with the lsusb command on the one hand, but on the other hand I get a serial number from /proc/scsi/usb-storage. Where is the difference between the two methods to gather the serial? | USB serial number not shown with lsusb -v command | linux;usb;proc;lsusb | null |
_unix.290868 | I'd like to copy from /A to /C only paths missing on /B and /C. (Please assume those are paths, and can represent also remote locations e.g. mounted via sshfs)I wonder... Is there more concise way then writing a loop, iterating over filesystem and making check, file by file ?Example contents of tree directories /A, /B, /C :/A:/A/1abc/qwe/A/2abc/asd/A/3abc/zxc/A/4abc/rty/B:/A/2abc/asd/A/3abc/zxc/C:/C/1abc/qweexpected:to copy from /A to /C only path 4abc/rty:/A/4abc/rty -> /C/4abc/rtyTo illustrate practical examples of /A, /B, /C, leading to such scenario:you make backup, copy from some /source (/A) to some /destination (/B) and some paths failed to be copied. So you want to have copy anyway of missing ones. So you find /another_destination (/C) that can accept them, and you want to copy only missing ones. Here are example limitations why copy from /A to /B could fail: disc got full; limitation of filesystem of /B (like filename lenght), while not present on /C filesystem; etc. | copy_only_missing? - Copy from /A to /C only paths missing on /B and /C - concise way | rsync;backup;synchronization | null |
_webapps.106888 | I am using multiple accounts in Gmail (including external ones) and have noticed since about 3 months the following issue: some emails that I receive on my uni email account show up in my inbox a couple weeks up to a couple of months late.The concerned emails seem to exclusively come from LinkedIn and other mass-emailing platforms (not really an issue), but also from some coworkers that send me messages manually (can be a big deal). Any idea where this might come from? | Late email reception in Gmail | gmail | null |
_unix.249105 | I'm sorry not being too specific in the title but I couldn't get it more specific than that.Why can't I use if($l =~ $ARGV[0]) but I can use if($l =~ /$ARGV[0]/g?first case$ perl script.pl '/^[\w]/g'second case$ perl script.pl '^[\w]' | Perl - Why I can't use a variable into regex? | perl | $ARGV[0] is a scalar string. When you do if($l =~ $ARGV[0]) and $ARGV[0] is '/^[\w]/g' this is equivalent to if($l =~ '/^[\w]/g') instead of if($l =~ /^[\w]/g). In the former case the slashes are simply characters in a string while in the later they are a part of the Perl syntax that delimits a regular expression. |
_webapps.108479 | How can I archive content on Facebook that requires me to be logged in to be visible on an external service? I have seen Archive-IT but as I understand it, their service it is not open for the public but rather just for their members (universities and similar). Furthermore, Archive.is can archive public content on Facebook but not stuff that has a more limited audience.I imagine a couple of different solutions:Provide my login credentials. Of course, you wouldn't wanna do this to some shady service with an unknown track record and owners.That I upload the content I want to archive using some scriptlet, browser extension or similar.A service using the Facebook API similar to how Facebook applications are working.At the moment I don't need to limit the access to the archived content (I mostly need this to save threads in more or less public groups with thousands of members. In other words, they are in practise already available to anyone on the internet) but of course, it would be a nice to have for future purposes. | How can I archive, externally, a Facebook page that requires login? | facebook;archive.org;facebook archive | null |
_codereview.87032 | I have a function that converts an integer to its binary representation. I am wondering if there is any way I can improve the function. public List<string> Conversion(int x) { var bitConversion = new List<string>(); var result = x; while (result >= 0) { if (result == 0) { bitConversion.Add(0); break; } bitConversion.Add((result % 2).ToString(CultureInfo.InvariantCulture)); result = result / 2; } bitConversion.Reverse(); return bitConversion; } | Function that convert decimal to binary | c#;performance;converting | One major improvement would be to just use what is supplied through .NET:Convert.ToString(int, 2);where int is your supplied argument.Convert.ToString Method (Int32, Int32)Converts the value of a 32-bit signed integer to its equivalent string representation in a specified base.Note that this returns you a string value like 10000110100001, which is the representation of a binary number. In your code you store them as string representations and in separate entries in your collection, which is not the way a number should be stored. It's like creating an array with values 1 and 2 to represent the number 12.If this is your intention then you can always work towards that of course but it might be an indication that something else is wrong for needing it like that.However if you want to stay with your own implementation, there are a few things you could change around:public List<string> Conversion2(int x){ var bitConversion = new List<string>(); while (x >= 0) { if (x == 0) { bitConversion.Add(0); break; } bitConversion.Add((x % 2).ToString(CultureInfo.InvariantCulture)); x /= 2; } bitConversion.Reverse(); return bitConversion;}Remove the unnecessary result variableContract x = x / 2 to x /= 2 (compound assignment operator) |
_softwareengineering.244373 | I've learned how to program primarily from an OOP standpoint (like most of us, I'm sure), but I've spent a lot of time trying to learn how to solve problems the functional way. I have a good grasp on how to solve calculational problems with FP, but when it comes to more complicated problems I always find myself reverting to needing mutable objects. For example, if I'm writing a particle simulator, I will want particle objects with a mutable position to update. How are inherently stateful problems typically solved using functional programming techniques? | Dealing with state problems in functional programming | functional programming | Functional programs handle state very well, but require a different way of looking at it. For your position example, one thing to consider is having your position be a function of time instead of a fixed value. This works well for particles following a fixed mathematical path, but you require a different strategy for handling a change in the path, such as after a collision.The basic strategy here is you create functions that take in a state and return the new state. So a particle simulator would be a function that takes a Set of particles as input and returns a new Set of particles after a time step. Then you just repeatedly call that function with its input set to its previous result. |
_unix.124405 | I was trying to install a package using pkg add, but I got the reply thatpackage manager not installedTo install that I used:tar -C /tmp -zvxf pkg-1.2.1_1.txzand then:/tmp/usr/local/sbin/pkg-static pkg-1.2.1_1.txzIt worked out for the first time. But when I rebooted my PC I got an error:error exit delayed from previous errorsHow to install package manager from FreeBSD installation DVD now? | Install a package manager in FreeBSD 10 | package management;freebsd | null |
_webapps.50311 | I want to print a list of songs (with artist, album, rating and, if possible, number of plays and duration) from my Google Play Music account.There is no easy way to do this from the app. Doing print-screens as I page through a long list of songs is not tenable.I would be happy with an export of data to a standard format (plain text, CSV, XML, etc.) that I can manipulate myself.Any suggestions? | Print Playlist from Google Play Music | export;google play music | Modifying darkliquid's answer, I came up with the following which allows for multiple playlists to be saved at once.Instructions:Go to https://play.google.com/music/listen?u=0#/wmp.Paste in the JavaScript code below into your console.Click on a playlist that you want to save to text.Once on the playlist page, scroll to the bottom relatively slowly.After you've scrolled to the bottom, navigate back to the playlists page (same as in step 1.) using the menu or your browsers back button.Repeat steps 3-5 for all playlists you want to save to text.Once you've done this for all the playlists you want to save to text, you can either type JSON.stringify(tracklistObj, null, '\t') (change the '\t' to ' ' if you want minimal indentation) or tracklistObj if you just want the JavaScript object to manipulate it your own way.// Setupvar tracklistObj = {}, currentPlaylist, checkIntervalTime = 100, lastTime;// Process the visible tracksfunction getVisibleTracks() { var playlist = document.querySelectorAll('.song-table tr.song-row'); for(var i = 0; i < playlist.length ; i++) { var l = playlist[i], title = l.querySelector('td[data-col=title] .column-content').textContent, artist = l.querySelector('td[data-col=artist] .column-content').textContent, duration = l.querySelector('td[data-col=duration] span').textContent album = l.querySelector('td[data-col=album] .column-content').textContent, playCount = l.querySelector('td[data-col=play-count] span').textContent, rating = l.querySelector('td[data-col=rating]').textContent; // Add it if it doesn't exist already if(!tracklistObj[currentPlaylist].includes(artist + - + title)) { tracklistObj[currentPlaylist].push(artist + - + title); if(printTracksToConsole) { console.log(artist + ' - ' + title); } } }}// Listen for page changeswindow.onhashchange = function(e) { var playlistName = document.querySelector('.gpm-detail-page-header h2[slot=title]').innerText; if(playlistName != null) { currentPlaylist = playlistName; if(tracklistObj[currentPlaylist] === undefined) { tracklistObj[currentPlaylist] = []; } console.log(===================================); console.log(Adding to playlist + currentPlaylist); getVisibleTracks(); }}// Check for new tracks every so oftensetInterval(function() { getVisibleTracks();}, checkIntervalTime);// Whether or not to print the tracks obtained to the consolevar printTracksToConsole = false;You can also print out track names to the console as you go by changing printTracksToConsole to true.Also note that currently it's setup only to give Artist - Track name, but you can easily edit the line that has tracklistObj[currentPlaylist].push(artist + - + title); with album, playCount, duration, or rating, and/or whatever formatting you want (including CSV format if you so please).If you want to be able to scroll faster, you can decrease checkIntervalTime to something lower, but will take up more processing (if you're close to 0 it may freeze the window).Example output (all Google Play playlists I currently have) with default settings. It took about 5 minutes in total to navigate to each of the 32 playlists, scroll down them, and then convert the result to text.P.S. You might be interested using a site I found called roll.io to make (informal) YouTube playlists from the output so your friends can listen to your Google Playlists. If you do this, you probably want to use something like TextMechanic to remove the quotes from the outputted list. |
_webmaster.11000 | Can anyone tell me based on experience what to use or what to do?I want to enable users(my family) to create their own simple homepage including a background image, some text and hyperlinks based on templates on my website hosted on my server. What is the best way to approach this? I dont have any website created yet so Im open to all suggestions. I want to present them with a webbased GUI, so there is no HTML or programming knowlegde needed. It needs to have a low learing curve.I searched the web and came across Wordpress, Movabletype and some other CMS like tools. (Joomla and such) Are these any good?Please advice,Darrell. | Enable users to create own homepage | web development;website design;web hosting | null |
_unix.321297 | I recently installed Debian Jessie (8) to my Lark Ultimate 7i WIN. I successfully installed all essential things on it, but one thing is still irritating me. I have LXDE installed, and I added battery monitor applet to the bottom bar, but it only shows black rectangle. It says 0%, 0:00 until full charge. I installed upower, and it says that the battery is 100%. And acpi -b says the same as lxde. The driver that the battery is using is Intel Real Battery Monitor and the battery is model SR Real Battery (from /sys/class/power_supply/BTBM/). I have tried adding some lines to lxde autostart, but nothing, that I tried did not work. | Debian Battery Monitoring driver | debian;lxde;battery | null |
_codereview.134339 | I wrote my first Python program today after working through a few books. I decided to build a group initiative tracker for our D&D group and was hoping to get some feedback. Critiques on code efficiency, formatting, suggestions, etc would be appreciated. My plan is to eventually take this from a command-line application to a django or flask web app, or maybe an iOS app.print('Welcome to Initiative Tracker!')while True: try: loop_count=int(input(\nHow many PC's and NPC's total? )) loop_start = 0 initiative_tracking = {} while loop_start < loop_count: player_name = input('What is the Players name? ') player_initiative = int(input('What is ' + player_name + ' initiative? ')) if player_initiative in initiative_tracking: initiative_tracking[player_initiative].append(player_name) else: initiative_tracking[player_initiative] = [player_name] loop_start += 1 continue print('\nYour initiative order is: ') for key in sorted (initiative_tracking.keys(), reverse=True): print(str(key) + ': ' + ', '.join(initiative_tracking[key])) break except ValueError: print(Sorry I didn't catch that. How many PC and NPC total? ) | Python Tabletop Initiative Tracker | python;python 3.x | I see that you have some error handling for int(input(...)). I would change it, however. Let's say that the user types a valid number of PC's, but does not type a valid player initiative. That would trigger a ValueError, and your except block would ask again how many PC's. Why should it restart the whole process for one little mistake? You should have different try blocks for each of those. Also, a try block should include only the code that you expect might throw an error. If some other code throws an error, you want to know about it.For the first use of int(input(...)), I would just take it out completely. Why should the user need to specify how many PC's? Why not just keep going until he runs out and then hit Enter on a blank line? That can be done quite simply with iter(). Usually, iter() is given an iterable, but if it is given two arguments, the first argument is a callable (usually a function) that returns a value. (In our case, we use lambda: input(...)). The second argument is the stopping point. iter() will keep calling that function and yielding the result until it returns the second argument. Therefore, we give it '', and we get all of the user's inputs until he types nothing in a line.The second use of int(input(...)) is when you are retrieving the player initiative. It should have its own try-except block to make sure the input is an integer. I would then put that block inside of its own while loop so that the program keeps asking until it gets a valid answer.Instead of a chain of string concatenations, use string formatting:player_initiative = input('What is {} initiative? '.format(player_name))andprint('{}: {}'.format(key, ', '.join(initiative_tracking[key])))A loop is called that because it loops. You don't need to tell it to keep looping. It will keep looping until it is told to stop. Sometimes it is stops because a condition is not met, but sometimes it stops because it encounters a break. You should use continue only if you want to skip the code beneath and jump straight to the beginning of the loop. It really doesn't make sense to put continue at the end of the loop.The argument that is given to sorted() has only one requirement: that it is iterable. To test if a type of object is iterable, go into a Python shell and create an instance of it. Then, do for item in my_object: print(item). If there is an error, your object is not iterable. Otherwise, you will see what happens when iterates. For a dictionary, you get all of the keys. Therefore, sorted(initiative_tracking.keys(), reverse=True) can be simplified to sorted(initiative_tracking, reverse=True).Full code:print('Welcome to Initiative Tracker!')initiative_tracking = {}for player_name in iter(lambda: input(What is the player's name? ), ''): player_initiative = input('What is {} initiative? '.format(player_name)) while True: try: player_initiative = int(player_initiative) break except ValueError: player_initiative = input('Please enter an integer: ') if player_initiative in initiative_tracking: initiative_tracking[player_initiative].append(player_name) else: initiative_tracking[player_initiative] = [player_name]print('\nYour initiative order is: ')for key in sorted(initiative_tracking, reverse=True): print(str(key) + ': ' + ', '.join(initiative_tracking[key])) |
_vi.5452 | I can set the text width and can manually line break imported paragraphs with the following as an example.set textwidth=72gqqI can also navigate English text files with the standard 'w' 'b' 'e' '*' commands, etc.This works well for English, however Thai and other Brahmic scripts of South and South-east Asia space at the phrasal level. Libreoffice, Word, Indesign, TeX, etc. know where line breaks should occur. And except for TeX, I can navigate by Thai word in these programs. My question: How can vim be taught to recognize Thai words (or any Indic language for that matter) for the purpose of navigation, word wrapping, and line breaking. | Set line breaks, word wraps and word searching for Thai and other non-latin languages | vimscript;vimrc;wrapping;line breaks | null |
_softwareengineering.122440 | Say you have a document with an essay written. You want to parse this essay to only select certain words. Cool. Is using a regular expression faster than parsing the file line by line and word by word looking for a match? If so, how does it work? How can you go faster than looking at each word? | How do regular expressions actually work? | regular expressions | How does it work?Take a look at automata theoryIn short, each regular expression has an equivalent finite automaton and can be compiled and optimized to a finite automaton. The involved algorithms can be found in many compiler books. These algorithms are used by unix programs like awk and grep. However, most modern programming languages (Perl, Python, Ruby, Java (and JVM based languages), C#) do not use this approach. They use a recursive backtracking approach, which compiles a regular expression into a tree or a sequence of constructs representing various sub-chunks of the regular expression. Most modern regular expression syntaxes offer backreferences which are outside the group of regular languages (they have no representation in finite automata), which are trivially implementable in recursive backtracking approach. The optimization does usually yield a more efficient state machine. For example: consider aaaab|aaaac|aaaad, a normal programmer can get the simple but less efficient search implementation (comparing three strings separately) right in ten minutes; but realizing it is equivalent to aaaa[bcd], a better search can be done by searching first four 'a' then test the 5th character against [b,c,d]. The process of optimization was one of my compiler home work many years ago so I assume it is also in most modern regular expression engines.On the other hand, state machines do have some advantage when they are accepting strings because they use more space compared to a trivial implementation. Consider a program to un-escape quotation on SQL strings, that is: 1) starts and ends with single quotation marks; 2) single quotation marks are escaped by two consecutive single quotations. So: input ['a'''] should yield output [a']. With a state machine, the consecutive single quotation marks are handled by two states. These two states serve the purpose of remembering the input history such that each input character is processed exactly only once, as the following illustrated:...S1->'->S2S1->*->S1, output *, * can be any other character S2->'->S1, output 'S2->*->END, end the current stringSo, in my opinion, regular expression may be slower in some trivial cases, but usually faster than a manually crafted search algorithm, given the fact that the optimization cannot be reliably done by human.(Even in trivial cases like searching a string, a smart engine can recognize the single path in the state map and reduce that part to a simple string comparison and avoid managing states.)A particular engine from a framework/library may be slow because the engine does a bunch of other things a programmer usually don't need. Example: the Regex class in .NET create a bunch of objects including Match, Groups and Captures. |
_vi.12731 | I understand it's the place to put things that should have the final say and not be overridden by another source, but I'm unclear on how to decide when to put something in, say, ~/.vim/after/ftplugin/ rather than ~/.vim/ftplugin/.Do people generally use ~/.vim/ftplugin/ and only move stuff into ~/.vim/after/ftplugin/ if they observe unwanted behavior, or do they just put it all in the after-directory right away? | When to use the after/ directory? | options | Generally, if you want to add your own plugin, or replace a standard plugin with your own, it would go into ~/.vim/plugin or ~/.vim/ftplugin. If instead you want to keep the functionality of an existing plugin but add to it, or change just a few settings made by it, then your plugin would go into ~/.vim/after/plugin or ~/.vim/after/ftplugin. |
_vi.12239 | I'm trying to improve the cmake-syntax-highlighting for vim.I'm unable to have vim highlight a keyword which is inside a text which is already matching a region. I'm talking about variables:For example CMAKE_SOURCE_DIR is a built-in variable which is listed in a syn keyword cmakeVariable-list.When accessing values of a variable in cmake you use ${...}. Highlighting this is done with a region:syn region cmakeVariableValue start=/\${/ end=/}/ \ contained oneline contains=CONTAINED,cmakeTodo,cmakeVariableBoth highlightings work, except when mixed together. Keywords listed in cmakeVariable are not highlighted specially when being in a ${}-region.How can I tell vim to apply special highlighting in a region when a keyword is used? | How to highlight keywords in a syntax region? | syntax highlighting | You need to use the contained argument in your keyword definition. Here's a random snippet that works for me:syntax keyword toBeContained contained foo barsyntax region fooRegion start={ end=} contains=toBeContainedhi toBeContained ctermfg=51 guifg=cyanhi fooRegion ctermfg=30 guifg=darkcyanNote: This will make keyword toBeContained not work when it's not in a region that contains it. So you might need to make two definitions, one with contained and one without.I recommend this great tutorial on creating syntax files, as well as :help :syn-keyword for more information. |
_cs.20039 | I plot several arrays containing xy-coordinates of points (using plot(x,y)) and obtain a plot with some curves. The curves form some very distinctive closed shapes (that is, the points describing the curves lie close to each other).Now I need to find the (possibly approximate) centers of the closed shapes. Alternatively, it's good to recognize the closed shapes and to fill them. I don't know what is easier given the coordinates of points forming the shapes.A possible example with 3 closed shapes to detect is given below.Points can be also added along the image's borders, thus, closing all open shapes. Then all regions in the figure will be closed, but the question persists. | detect closed shapes formed by points | algorithms;computational geometry | find all intersections by checking all pairs of segments, belonging to different curves. Of course, filter them before real check for intersection.Number all curves 1..n. Set some order of segments in them.For every point create a sequence of intersections SOI, so: if it starts from the border end, SOI[1] is null. If not, SOI[1]= (number of the first curve it is intersecting with, the sign of the left movement on the intersecting curve). Go on, writing down into SOI every intersection - number of curve if there is some, or 0 if it is the intersection with the border.Obviously, you are looking only for simple bordered areas, that have no curves inside.Pieces of curves between two adjacent non-null intersection points we'll call segments. Having SOI for each curve:for segment of the curve 1, starting from the first point of the segment, make 2 attempts to draw a polygon of segments. It is 2 because you can go to 2 sides along the first intersecting curve. For the right attempt, make only left turns, for the left attempt, make only the right turns. If you arrive at point with no segment in the correct direction, the attempt fails. If you return to the curve 1, it success. You have a closed area.Remember all successful attemptsRepeat this for all segments of curve 1Repeat this for all other curves, checking all found areas against the already found ones. Two same adjacent segments is enough to consider areas equal.Edit:How to find the orientation of the intersection. When segment p(p1,p2) crosses segment q(q1,q2), we can count the vector multiplication of vectors pXq. We are interested in only sign of its Z coordinate - that is out of our plane. If it is +, q crosses p from left to right. If it is -, the q crosses p from right to left.The Z coordinate of the vector multiplication is counted here as a determinant of matrix: 0 0 1p2x-p1x p2y-p1y 0q2x-q1x q2y-q1y 0(of course, it could be written more simply, but it is a good memorization trick)Of course, if you'll change all rights for lefts, nothing really changes in the algorithm as a whole. |
_softwareengineering.269501 | I have a bunch of x-y graphs given to me and I need to be able to transform them into some kind of data structure from which I will be able to get Y with X value.The problem is, though that I have 4, at max 5 values of Y given to me, and my X values can range up to 9000. So the information I have is something of the formPoint # X Y1 1000 1002 3250 4603 6000 3204 6500 300My idea initially was something like:function getY($x){ $data[1000] = 100; $data[3250] = 460; $data[6000] = 320; $data[6500] = 300; if(isset($data[$x])){ return $data[$x]; } $minKnown = null; $maxKnown = null; foreach($data as $_x => $y){ if($_x < $x){ $minKnown = $_x; } if($_x > $x){ $maxKnown = $_x; break; } } return $data[$minKnown] + (($x - $minKnown) / ($maxKnown - $minKnown)) * ($data[$maxKnown] - $data[$minKnown]);} }This function I just wrote to illustrate my idea. Basically if a point is not defined but somewhere between 2 known points, assuming there are no curves between the two points get the value that co-responds to the position of X between the two known values of X. I'm not even sure if my verbal explanation is actually correct or not but I guess that's what I wrote the function for. Anyway, I was thinking, since graphs something that's widely used, are there any better ways of doing this, and I'm hoping there are otherwise I might turn out to be smarter than I thought, which is scary. | Setting and getting values from a x-y graph | php;graph | Since you said, that you assume that there are no curves, the graph itself would probably look like a stock development. So I would try a vector calculation approach. With the data you gave in your example you would get 3 vectors defined by two points. (To generalize it, you would get one vector less then you got points.)In your example:Vector1: Point1->Point2 (Point2[x] - Point1[x], Point2[y] - Point1[y]) Vector2: Point2->Point3 (Point3[x] - Point2[x], Point3[y] - Point2[y])Vector3: Point3->Point4 (Point4[x] - Point3[x], Point4[y] - Point3[y])With values:Vector1: (3250 - 1000, 460 - 100) = (2250, 360)Vector2: (6000 - 3250, 320 - 460) = (2750, -140)Vector3: (6500 - 6000, 300 - 320) = (500, -20)Now the standard linear function has the form y = m*x + b. The vector itself won't need the b. So for Vector1 it is: 360 = m * 2250 Resolved for m we get: m = 360 / 2250 = 0.16Now we get back to the original line between P1 and P2, which will require a value for b.We get this now with: 100 = 0.16 * 1000 + b => b = -60With that we know each y value between Point1 and Point2 will be defined by this equation: y = 0.16 * x - 60.You can check this by simply inserting the values of one of the points into the equation:P1 100 = 1000 * 0.16 - 60 P2 460 = 3250 * 0.16 - 60 Code example:$vector1x = $Point2->X - $Point1->X;$vector1y = $Point2->Y - $Point1->Y;$m1 = $vector1y / $vector1x$b1 = $Point1->y - $Point1->x * $m1// do the same for the other points as described.Now when you get a value for x which you want to get the y value of do sth like this:function getY($x){ if($x >= $Point1->X && $x <= $Point2->X) { $y = $m1 * $x + $b1; } else if($x <= $Point3->X) { $y = $m2 * $x + $b2; } else if($x <= $Point4->X) { $y = $m3 * $x + $b3; } else { throw new Exception(Cannot calculate value with given data!); } return $y; }I hope this approach serves your needs and helps you in solving the problem. |
_softwareengineering.238666 | Is there a design pattern or well known algorithm to build a simple map with roads and city blocks?To have an idea of what's my target i describe some of the constraints and the context:a matrix which represents a (rectangular) mapfew possible city blocks represented as rectangles (eg, 4x3, 5x2, 1x6)few possible road sizes (eg, 1, 2)block are never connected, meaning that there is always a road between themthe result would be an array like this:111101111100110111101111100110111100000000110000001110000110000001110000000...where as for example, 1 are the blocks and 0 are the roads.What I intend to do is to place a block where it is possible, then circumscribe with roads, and go on. This would be ok, but could lead to some place where blocks don't fit.I would like to know if there is something in the state of the art of such algorithms. | Build a map with city blocks and road | design patterns;algorithms | null |
_unix.296620 | Hello I am new to this unix background. I had set up a server on centOs 7. i had given ip as 192.0.2.123 and host name as www.example.com. now when i www.example.com hit the hostname in the browser i am gettingThis site cant be reachedThe connection was reset.Some timesThis site cant be reachedwww.example.coms server DNS address could not be found.DNS_PROBE_FINISHED_NXDOMAINIs their any steps to map ip to hostname.Please help. | Site cannot be reached after installing centos 7 | centos;hostname | null |
_unix.226041 | I have trouble adding usb device to rules.d list, I want to be able to use it without root. Here is my USB device:Bus 001 Device 007: ID 1162:2200 Secugen Corp.And this is entry I made in /etc/udev/rules.d/98-secugen-usb-device.rules:SYSFS{idVendor}==1162, SYSFS{idProduct}==2200, SYMLINK+=input/fdu05-%k, MODE=0660, GROUP=SecuGen KERNEL==uinput, MODE=0660, GROUP=SecuGenI'm not quite sure what is SYMLINK+=input/fdu05-%k part, it was set as this in readme.txt.Unfortunately this rule does not work. Usually it is quite straight forward, add vendorId/productId and it works, but not this time.Any suggestions?UPDATE:This is output I get from dmesg:usb 1-1.1.3: new high-speed USB device number 12 using ehci-pciusb 1-1.1.3: New USB device found, idVendor=1162, idProduct=2200usb 1-1.1.3: New USB device strings: Mfr=1, Product=2, SerialNumber=0usb 1-1.1.3: Product: SecuGen USB U20usb 1-1.1.3: Manufacturer: SecuGen Corp.This is how my /dev/input looks like: by-id usb-LITEON_Technology_USB_Multimedia_Keyboard-event-kbd -> ../event0 usb-Microsoft_Comfort_Mouse_6000-event-mouse -> ../event1 usb-Microsoft_Comfort_Mouse_6000-mouse -> ../mouse0 by-path pci-0000:00:1a.0-usb-0:1.2:1.0-event-kbd -> ../event0 pci-0000:00:1a.0-usb-0:1.3:1.0-event-mouse -> ../event1 pci-0000:00:1a.0-usb-0:1.3:1.0-mouse -> ../mouse0 platform-pcspkr-event-spkr -> ../event4 event0 event1 event10 event2 event3 event4 event5 event6 event7 event8 event9 mice mouse0Log I get from unbuffer udevadm monitor --environment :UDEV [4656.200575] add /devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.1/1-1.1.3 (usb)ACTION=addBUSNUM=001DEVNAME=/dev/bus/usb/001/016DEVNUM=016DEVPATH=/devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.1/1-1.1.3DEVTYPE=usb_deviceID_BUS=usbID_MODEL=SecuGen_USB_U20ID_MODEL_ENC=SecuGen\x20USB\x20U20\x20\x20\x20\x20\x20\x20\x20ID_MODEL_ID=2200ID_REVISION=2206ID_SERIAL=SecuGen_Corp._SecuGen_USB_U20ID_USB_INTERFACES=:ffffff:ID_VENDOR=SecuGen_Corp.ID_VENDOR_ENC=SecuGen\x20Corp.\x20\x20\x20\x20ID_VENDOR_FROM_DATABASE=Secugen Corp.ID_VENDOR_ID=1162MAJOR=189MINOR=15PRODUCT=1162/2200/2206SEQNUM=1702SUBSYSTEM=usbTYPE=0/0/0UDEV_LOG=6USEC_INITIALIZED=56185634UDEV [4657.235375] add /devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.1/1-1.1.3/1-1.1.3:1.0 (usb)ACTION=addDEVPATH=/devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.1/1-1.1.3/1-1.1.3:1.0DEVTYPE=usb_interfaceID_VENDOR_FROM_DATABASE=Secugen Corp.INTERFACE=255/255/255MODALIAS=usb:v1162p2200d2206dc00dsc00dp00icFFiscFFipFFin00PRODUCT=1162/2200/2206SEQNUM=1703SUBSYSTEM=usbTYPE=0/0/0UDEV_LOG=6USEC_INITIALIZED=186134adb_user=yesDistro: Debian GNU/Linux 8 (jessie) | Adding USB device to rules.d | usb | null |
_webmaster.60438 | Can a rule that filters and redirect traffic based on country of origin be implemented in .htaccess?Can it be implemented in any other way then by an IP address? I need the solution to be as accurate as possible. | Htaccess redirect based on country of origin | htaccess;redirects;country specific | null |
_unix.68768 | I am a complete amateur in Linux. There is a software that only runs on Linux. It came with a virtual machine package and every thing.When inside the virtual machine, I run a .py file in the terminal and it starts downloading the software. The software file is quite large.I noticed every time I let the software to download, the installation wants to start and asks me for the password. I am usually not there to enter and it fails.I wanted to see how I can get over this problem. Thanks | Installing a software on Linux- Centos | centos;software installation | null |
_softwareengineering.72347 | It is really frustrating to find that every other open source project's source code and documentation etc., follows slightly or hugely different directory structure and naming conventions. How do I quickly orient my self to the directory/naming conventions? Get to the overall architecture of the app without going through a bunch of source code files? How do I make reaching to the relevant code (that I am interested in) quicker? | How to browse an open source project efficiently? | open source | The best way is to download the whole project under your favorite IDE and use the IDE tools to gain a first overview.For the Apache Software Foundation for example, they have just one huge Subversion root from which you can pull any single project in a few clicks using Eclipse. This creates a project in your workspace and you can use all the powerful tools of Eclipse to understand the class hierarchy, navigate (Ctrl/click) from one class to the next or just search artefacts in files. The same holds true for Intellij or Netbeans of course. For github, just add a git plugin to Eclipse and do the same. At Sourceforge they use Subversion as well and used to rely on CVS, but the same will apply.It seems like a lot of work but believe me it isn't. This strategy will also allow you to understand the various ways to build and architecture OSS (Maven, Hudson/Jenkins, Ant, make/nmake etc...). Once you've done it once, it's much easier the second time and you'll find out it's always the same process. Your developer skills will get a boost from taking this option seriously. |
_cs.53428 | The following is an exercise which I am stuck at ( source: Sanjeev Arora and Boaz Barak; its not homework ) :Show that there is an oracle $A$ and a language $L \in NP^A$ such that $L$ is not polynomial-time reducible to 3SAT even when the machine computing the reduction is allowed access to $A$.What I tried was, take $A$ to be the oracle to halting problem and let $L=\{1^n | \;\exists \; \langle M,w \rangle \; \text{s.t.} \; |\langle M,w \rangle|=n \; \text{ and Turing machine M halts on w} \} $. With this assignment I ensure $L \in NP^{A}$ and $L$ is not polynomial reducible to 3SAT if oracle is not provided to the machine carrying out reduction. Although to map an instance $1^n$ I would have to search through $2^n$ strings even if oracle is provided to the reduction machine. But this does not seem like a proof for absence of polynomial reduction in this case. Is there a way to prove it using the same example ? Is there a simpler example ? | How can I show that the Cook-Levin theorem does not relativize? | complexity theory;np;nondeterminism;oracle machines;relativization | Please refer Does Cook Levin Theorem relativize?. Also refer to Arora, Implagiazo and Vazirani's paper: Relativizing versus Nonrelativizing Techniques: The Role of local checkability.In the paper by Baker, Gill and Solovay (BGS) on Relativizations of the P =? N Pquestion (SIAM Journal on Computing, 4(4):431442, December 1975) they give a language $B$ and $U_B$ such that $U_B \in NP^B$ and $U_B \not\in P^B$, thus proving that there are oracles $B$ for which $P^B \neq NP^B$.We shall modify the $U_B$ and $B$ to $U_{B'}$ and $B'$ such that we get a new language that cannot be reduced to 3SAT even if there is availability of $B'$ as an oracle.First assume that we can pad every $3SAT$ boolean instance $\phi$ to $\phi'$ with some additional dummy 3CNF expressions such that $|\phi'|$ is odd and they are equivalent, i.e., $\phi$ is satisfiable iff $\phi'$ is satisfiable. We can do it in $n+O(1)$ time and with $O(1)$ padding, but even if it takes polynomial time and extra polynomial padding it does not matter.Now we need to combine the $B$ and $3SAT$ to $B'$ somehow so that BGS theorem still holds but additionally $3SAT \in P^{B'}$. So we do something like the following.$U_{B'} = \{1^n \ \ |\ \ \exists x \in B, $ such that $|x| = 1^{2n}\}$ and$B' = B'_{constructed} \ \cup \{\phi \ \ |\ \ \phi \in 3SAT $ and $ |\phi| $ is odd $\}$. Now we shall construct $B'_{constructed}$ according to the theorem such that if the deterministic machine $M_i^{B'}$ for input $1^n$ ($n$ is determined as in theorem) asks the oracle $B'$ a query of odd length we check if it is in $3SAT$ and answer correctly but if it asks a query of even length we proceed according to the construction, that is, answering correctly if it is already in the table, otherwise answer no every time. Then since we are running for $1^n$ we flip the answers at $2n$ length so that $M_i^{B'}$ does not decide $U_{B'}$.We can prove similarly as in the BGS theorem that for this $B'$ and $U_{B'}$ too, we have $U_{B'} \in NP^{B'}$ and $U_{B'} \not\in P^{B'}$. $U_{B'} \in NP^{B'}$ is easy to prove. We construct a non-deterministic Turing Machine which for input $1^n$ creates non-deterministic branches that runs for $2n$ steps to generate a different $2n$-length string and then asks oracle $B'$ if the $2n$-length string is in $B'$, and if the answer is yes it accepts $1^n$ else it rejects $1^n$. This construction shows that $U_{B'} \in NP^{B'}$.$U_{B'} \not\in P^{B'}$ can be proved with the help of diagonalization argument. Basically it is different from every $L(M_i^{B'})$ for every oracle Turing Machine that have $B'$ as an oracle. This is because of how we construct $B'_{constructed}$.Now we shall prove by contradiction that there does not exist a reduction from $U_{B'}$ to $3SAT$ even with the availability of oracle $B'$.Assume there is a reduction using oracle $B'$, i.e., $U_{B'} \leq^{B'}_P 3SAT$. That means we can reduce a string of the form $1^n$ to a 3SAT instance $\phi$ using a polynomial-time deterministic machine which uses $B'$ as oracle. We can now describe a deterministic TM $M^{B'}$ which will decide strings $U_{B'}$ in polynomial time using $B'$ as an oracle. First this machine reduces the input $1^n$ to a 3SAT-instance $\phi$ using $B'$ as an oracle. This can be done because we have the reduction above. Then if $\phi$ is not odd length $M^{B'}$ will pad it to make $\phi'$ which is odd length. Next, it will give this $\phi'$ to oracle $B'$ and get the answer yes/no. It will accept if the answer is yes and reject if the answer is no. This machine is deterministically polynomial and uses oracle $B'$.Thus we have proved that $U_{B'} \in P^{B'}$, a contradiction.Therefore $U_{B'} \not\leq^{B'}_P 3SAT$. |
_unix.287783 | This question is similar to the one about resuming from hibernate in a dual boot PC, but i do not assume here that the two systems share the swap. Even though answers to these questions would probably be very similar, I think my question is a bit different.As follow from this answer to my other question, and according to this document on kernel.org, between a hibernation and the subsequent resume of a system, no mounted partition should be modified.This looks to me like a rather strict requirement for a dual boot configuration: if I want to have a partition writable by both systems (for example, for /home), I should probably disable hibernation...Has anybody found any workaround yet? For example, allowing the machine to only boot into the hibernated system after hibernation would be a perfect solution IMO. | Hibernation of a dual boot machine with a shared writable partition | dual boot;hibernate;shared partition | null |
_unix.316306 | I have a text file that looks like this:UICEX_0001 UICEX_0001_T1.bam UICEX_0001_C2.bam chr1:16946335 chr19:9064309 chr8:10480278 UICEX_0003 UICEX_0003_T1.bam UICEX_0003_C2.bam chr1:16974893I am trying to use this information to create something like the following, combining strings and dynamically inputting information from the text file. I want to:loop through each lineassign the first three columns to variablesprint some text with those variablesthen loop through the 4th-end column print something specific. Here's an example of my output file:Output Fileload UICEX_0001_T1.bamload UICEX_0001_C2.bamgoto chr1:16946335collapsesnapshot UICEX_0001_chr1:16946335.pnggoto chr19:9064309collapsesnapshot UICEX_0001_chr19:9064309.pnggoto chr8:10480278collapsesnapshot UICEX_0001_chr8:10480278.pngload UICEX_0003_T1.bamload UICEX_0003_C2.bamcollapsesnapshot UICEX_0003_chr1:16974893.pngWhat I've triedI thought I could do this by nesting gawk commands. Here's one I've tried:SAMPLEFILE = 2016-10-13_mutation_table.txtgawk -F; 'BEGIN{gawk -F; -v SAMPLE=$(cat $SAMPLEFILE | cut -d\t -f1) -v BAMT=$(cat $SAMPLEFILE | cut -d\t -f2) -v BAMN=$(cat $SAMPLEFILE | cut -d\t -f3);}{print new \nload $BAMN;}{print new \nload $BAMT;}{awk {for(i=4; i<=NF-1; i++){ print goto $i ; print collapse\nsnapshot $SAMPLE_$i.png;} } 2016-10-13_mutation_table.txt;}END{print exit \n}'But running this gets errors such as this:gawk: cmd. line:2: gawk -F; -v SAMPLE=$(cat $SAMPLEFILE | cut -d\t -f1) ...gawk: cmd. line:2: ^ syntax errorI'm a beginner at bash coding, so please include some explanation if possible. | gawk - Dynamic creation of text file using input file fields | text processing;gawk | null |
_unix.8584 | I'm setting up a Cronjob that will backup a MySQL database I have in my server, but I don't want it to keep overwriting the same file over and over again. Instead, I want to have an array of backups to choose from, done automatically. For example:## Cronjob, run May 21st, 2011:mysqldump -u username -ppasword database > /path/to/file/21-03-2011.sql## SAME Conjob, run May 28th, 2011:mysqldump -u username -ppasword database > /path/to/file/28-03-2011.sqlAnd so on.Is there any way that I can use the system date and/or time as some kind of variable in my Cronjob? If not, what are your suggestions to accomplish the same? | Using the system date / time in a Cron Script | bash;terminal;cron | null |
_unix.182429 | There are two (unix) users who are allowed to connect to my Debian Wheezy server using ssh: git and peter. While git is allowed to connect from everywhere, peter (who is in the sudo group) should be only allowed to connect from my local network.I therefore added the lineAllowUsers git [email protected]/24to my /etc/ssh/sshd_configAnd it first seemed to work, as git is allowed to connect remotely over the internet, while peter isn't. My desktop, which has the ip address 192.168.2.24 is allowed to connect as peter, but my laptop isn't when connected using VPN (with local ip 192.168.2.201). It works when using it directly connected to my LAN.This is what I can find in the /var/log/auth.log file. It doesn't make any sense to me, why is that IP not allowed?Feb 2 11:44:54 srv sshd[7275]: User peter from 192.168.2.201 not allowed because not listed in AllowUsersFeb 2 11:44:54 srv sshd[7275]: input_userauth_request: invalid user peter [preauth] | Restrict SSH login to local network: VPN connection not allowed | ssh;sshd;openssh | Use:AllowUsers git [email protected].*or for example:AllowUsers git [email protected]??if only 200-254 are allocated for VPN connections.And make sure to read man ssh_config (the section PATTERNS). Yes, that's ssh_config, not sshd_config. But if you read the latter, you'll notice it refers to the former. |
_softwareengineering.349973 | What are some techniques that you can use to prevent over-engineering among the Software Developers? Meaning, how do you keep them focused on creating solutions of only the current requirements? Without trying to anticipate all future changes. | How to prevent over-engineering from Developers? | design;complexity;engineering | null |
_codereview.148138 | This code is meant to compute the height for the tallest stack of boxes out of a given collection of boxes. A box has width, height, and depth dimensions. The height of a stack of boxes is the sum of all of the heights of the boxes in the stack. The boxes cannot be rotated. A box can only be stacked on top of another box if its width, height, and depth are strictly smaller.I'm doing this to improve my style and to improve my knowledge of fundamental algorithms/data structures for an upcoming coding interview.from operator import attrgetterclass Box: def __init__(self, width, height, depth): self.width = width self.height = height self.depth = depth def smaller_than(self, other_box): return (self.width < other_box.width and self.height < other_box.height and self.depth < other_box.depth) def tallest(boxes): boxes = sorted(boxes, reverse=True, key=attrgetter('height')) largest_height = 0 for i in range(len(boxes)): bottom_box = boxes[i] total_height = bottom_box.height cur_top_box = bottom_box for j in range(i+1,len(boxes)): if boxes[j].smaller_than(cur_top_box): total_height += boxes[j].height cur_top_box = boxes[j] if total_height > largest_height: largest_height = total_height return largest_heightThe question wasn't clear about how the boxes were represented or inputted. I just made them into a Box class and assumed that they were passed as a list to tallest(). If there are any better ways of representing the boxes or inputting them (especially in an interview environment) I would be happy to hear it.I think this code has time complexity O(n^2) and space complexity O(n). Please correct me if I'm wrong. Any suggestions about how I can improve these complexities are welcome. | Get height for tallest possible stack of boxes | python;performance;programming challenge;python 3.x | null |
_codereview.166874 | I am programming a parallel tree algorithm where I have to send data to other processors. The amount of data is not constant. Therefore I have to work with dynamic arrays using malloc() and realloc(). Since I am new to C I wondered if I am doing it right. I do not get any error. But I think that is not proof enough, that it works all the time. How could I really test this code? Do I have memory leaks? Do I occupy to much memory with this method? Here I have an array containing 10 double values. Then I want add 3 new double values to that array. Finally I want to delete the whole array.Here is my code:#include <stdio.h>#include <stdlib.h>int main(){ int n = 10; double *p; p = malloc(sizeof(*p)*n); // similar to int array[n] if(p==NULL){ printf(Error! Memory not allocated.); return 1; } for(int i=0; i<n; i++) printf(%lf\n, p[i]); printf(\n); int add = 3; double *temp; temp = realloc(p,(n+add)*sizeof(*temp)); if(temp != NULL){ p = temp; }else{ free(p); printf(Error! Memory not reallocated\n); return 1; } for(int i=0; i<n+add; i++) printf(%lf\n, p[i]); return 0; free(p);}I tried to check the size of the arrays before and after reallocation. But it seems to me that this is not possible in C. | Allocation and reallocation of memory | c;memory management | If you swap the last two lines, so you actually free the memory before returning, then the code looks to be leak-free in the face of errors - well done! You do read uninitialized values from the allocated memory; don't do that even in a test program (Valgrind complains a lot).Some notes:This reads easier if you re-order the multiplication:p = malloc(sizeof(*p)*n); // yoursp = malloc(n * sizeof *p); // mine(BTW, it's good that you are using sizeof *p rather than sizeof (double), as this means no risk of the type becoming out of step with the size allocated. Definitely a good practice to be encouraged!).Testing pointers against NULL is more idiomatic if you use the default conversion to boolean:if(p==NULL){ // yoursif (!p) { // mineError messages should go to standard error, not standard output, and should end with a newline: printf(Error! Memory not allocated.); // yours fprintf(stderr, Error! Memory not allocated.\n); // mineThe reallocation can be simplified in a similar manner to the initial allocation; I'd declare and allocate in a single line like this:double *temp; // yourstemp = realloc(p,(n+add)*sizeof(*temp)); // yoursdouble *temp = realloc(p, (n+add) * sizeof *temp); // mineComplete program#include <stdio.h>#include <stdlib.h>int main() { int n = 10; double *p = malloc(n * sizeof *p); if (!p) { fprintf(stderr, Error! Memory not allocated.\n); return 1; } /* initialize these values */ for (int i = 0; i < n; ++i) p[i] = i; for (int i = 0; i < n; ++i) printf(%lf\n, p[i]); printf(\n); int add = 3; double *temp = realloc(p, (n+add) * sizeof *temp); if (temp) { p = temp; } else { free(p); fprintf(stderr, Error! Memory not reallocated.\n); return 1; } /* initialize the new values */ for (int i = n; i < n+add; ++i) p[i] = 100 + i; for (int i = 0; i < n+add; ++i) printf(%lf\n, p[i]); free(p); return 0;}If we build this with my usual Makefile and run it in Valgrind, we see no leaks:gcc -std=c11 -fPIC -g -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds 166874.c -o 166874valgrind --leak-check=full ./166874==30432== Memcheck, a memory error detector==30432== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.==30432== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info==30432== Command: ./166874==30432== 0.0000001.0000002.0000003.0000004.0000005.0000006.0000007.0000008.0000009.0000000.0000001.0000002.0000003.0000004.0000005.0000006.0000007.0000008.0000009.000000110.000000111.000000112.000000==30432== ==30432== HEAP SUMMARY:==30432== in use at exit: 0 bytes in 0 blocks==30432== total heap usage: 3 allocs, 3 frees, 1,208 bytes allocated==30432== ==30432== All heap blocks were freed -- no leaks are possible==30432== ==30432== For counts of detected and suppressed errors, rerun with: -v==30432== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) |
_webapps.109061 | I'm trying to create a facebook messenger ad and have the automated reply message have an emoji in it. I can't seem to get it to show up properly though. Do I need to put it in a different field than text? I tried inserting the unicode, but it doesn't seem to like having escape characters in the field.{type: template,payload: { template_type: button, text: Welcome! \U+1F44B Click the date/time you would like:, buttons: [ { type: postback, payload: THINGS, title: AUGUST }, { type: postback, payload: THINGS, title: AUGUST } ]}} | How to insert emoji into facebook messenger JSON | facebook;facebook messages;facebook ads;facebook messenger | null |
_unix.155516 | I am using SUSE 11SP3 and formatted the devices with a block size of 4KB using mkfs.ext3./sys/block/sda/queue/logical_block_size and /sys/block/sda/queue/physical_block_size show the OS is using 512 bytes.How can I change the OS block size to match the 4KB FS block size?I created a RAID0 array form the disks. Do I need to change the block size of the RAID array and the disks it is comprised of or should I only change the RAID0 array? | How do I change the OS block size | filesystems;block device;mkfs | null |
_unix.11873 | I installed 'linux-patch-grsecurity2' and it has some sort of interface.~$ sudo gradm2gradm 2.1.14grsecurity administration programUsage: gradm [option] ...Examples: gradm -P gradm -F -L /etc/grsec/learning.logs -O /etc/grsec/policyOptions: -E, --enable Enable the grsecurity RBAC system -D, --disable Disable the grsecurity RBAC system -C, --check Check RBAC policy for errors -S, --status Check status of RBAC system -F, --fulllearn Enable full system learning -P [rolename], --passwd Create password for RBAC administration or a special role -R, --reload Reload the RBAC system while in admin mode -L <filename>, --learn Specify the pathname for learning logs -O <filename>, --output Specify where to place policies generated from learning mode -M <filename|uid>, --modsegv Remove a ban on a specific file or UID -a <rolename> , --auth Authenticates to a special role that requires auth -u, --unauth Remove yourself from your current special role -n <rolename> , --noauth Transitions to a special role that doesn't require authentication -p <rolename> , --pamauth Authenticates to a special role through PAM -V, --verbose Display verbose policy statistics when enabling system -h, --help Display this help -v, --version Display version informationI didn't successfully find any documentation on how to use it to limit the 'ps aux' list for users? | I don't want other users see my processes in ps aux. I have root. It's Debian. How to use grsec? | linux;security;process;grsecurity | null |
_unix.103102 | I use proftpd and configure it via Webmin. I want to limit users access to certain directories Their homes/sampleSo I go to Files and Directories->Limit users to directories and option: Home directory works fine. The problem is with other directory. It is set just like home directory but users still can see only their home folder without /sample. What happened?Ubuntu 13.10 | Proftpd and Webmin - directory limits | ftp;webmin;proftpd | null |
_reverseengineering.16059 | After reading a number of blog posts, forums, and watching tutorials I figured I would start learning to reverse software the old fashion way. Creating simple C files and looking at their disassembly. In my quest to truly understand reversing, I thought also comparing optimized and unoptimized code would be beneficial. While looking through I came across a couple lines of code that appear to do nothing.I would love if someone can explain what the mov[es] in the unoptimized code is doing. All of these were disassembled using Hopper v4.C Code: #include <stdio.h> int main(int arg, char** arg) { printf(Hello World!\n); return 0; }Unoptimized Code (gcc -m32) :; Variables: ; arg_4: 12 ; arg_0: 8 ; var_4: -4 ; var_8: -8 ; var_C: -12 ; var_10: -16 ; var_18: -24push ebpmov ebp, espsub esp, 0x18call _main+11pop eax ; CODE XREF=_main+6-- What purpose do these moves serve? --mov ecx, dword [ebp+arg_4]mov edx, dword [ebp+arg_0]-- --lea eax, dword [eax-0x1f5b+0x1fa6] ; Hello World!\\n-- And what do these moves also serve? --mov dword [ebp+var_4], 0x0mov dword [ebp+var_8], edxmov dword [ebp+var_C], ecx-- --mov dword [esp+0x18+var_18], eax ; method imp___symbol_stub__printfcall imp___symbol_stub__printfxor ecx, ecx mov dword [ebp+var_10], eaxmov eax, ecx add esp, 0x18 pop ebpretOptimized Code (gcc -m32 -O3):push ebpmov ebp, espsub esp, 0x8call _main+11pop eax ; CODE XREF=_main+6lea eax, dword [eax-0x1f6b+0x1f9e] ; Hello World!mov dword [esp+0x8+var_8], eax ; %s for imp___symbol_stub__putscall imp___symbol_stub__putsxor eax, eaxadd esp, 0x8pop eepret | Optimized vs Unoptimized code comparison | x86;intel | First of all, I would advise you to read about the SystemV ABI for i386 and amd64. You can find the documents here:System V i386 ABISystem V amd64 ABIThese documents define as precisely as possible how a compiler coder should translate some C/C++ code into i386/amd64 assembly code for a Unix-like system. They are extremely important documents and you should refer to it as often as possible because they contain a lot of answers for most of your questions.Now, back to your original question, in your case the main differences between the two codes is that gcc has optimized data movements in the memory as we will see.First code snippet-- What purpose do these moves serve? --mov ecx, dword [ebp+arg_4]mov edx, dword [ebp+arg_0]-- --Here, ecx and edx are loaded with the arguments of main (very likely argc and argv).Note that, none of argc and argv are of any use in the main() function. But, the compiler does not know about it because it did not performed dead-code/dead-variables analysis at this level of optimization. Of course, this code will be removed when the appropriate analysis will be performed.Second code snippet-- And what do these moves also serve? --mov dword [ebp+var_4], 0x0mov dword [ebp+var_8], edxmov dword [ebp+var_C], ecx-- --Here, the program seems to store the arguments in the local memory frame (below ebp). Note that the arguments are above ebp and the automatic variables below (we say automatic variable for the variable which are within the function's scope).Of course, these data movements are totally unnecessary, but the compiler just apply a default template for starting a function which transfer a copy of the arguments in the local memory stack-frame. And, once again, when the compiler realize that these variables are of no use, then these moves will disappear. |
_codereview.132363 | I solved this exercise of displaying a table of numbers from 1 to 256 in binary, octal and hexadecimal. I made this program to convert from decimal to binary and took that binary number to convert to octal and hexadecimal to made a table of binary, octal and hexadecimal. You might see that the way I found out which was the binary representation of the decimal number can be applied to the other bases and I didn't do it that way because I wanted to see if I could do it like this, I'll try to apply that method to the other basis now. Note: I overloaded the method binToBase () because I just learnt how to do it this week and seemed like the perfect oportunity to test it, haha.is this good code? I'm pretty ashamed of how long it took for me to solve this ( 2 days )public class Table { public static final int BIN_BASE = 2 ; public static final String HEX_BASE = Hexa ; public static final int OCT_BASE = 8 ; public static final int ROOF = 256 ; public static void main ( String[] args ) { int bin ; System.out.println ( Binary\t\tOctal\t\tHexadecimal ); for ( int i = 1 ; i <= ROOF ; i++ ){ bin = convertToBin ( i ) ; System.out.printf ( %10d\t , bin ) ; System.out.printf ( %10s\t , convertToBase ( bin , OCT_BASE ) ) ; System.out.printf ( %10s\n , convertToBase ( bin, HEX_BASE ) ) ; } } public static String convertToBase ( int convert , String base ) { String hex = ; int bin = convert ; do { switch ( bin % 10000 ) { case 0 : hex = '0' + hex ; break ; case 1 : hex = '1' + hex ; break ; case 10 : hex = '2' + hex ; break ; case 11 : hex = '3' + hex ; break ; case 100 : hex = '4' + hex ; break ; case 101 : hex = '5' + hex ; break ; case 110 : hex = '6' + hex ; break ; case 111 : hex = '7' + hex ; break ; case 1000 : hex = '8' + hex ; break ; case 1001 : hex = '9' + hex ; break ; case 1010 : hex = 'A' + hex ; break ; case 1011 : hex = 'B' + hex ; break ; case 1100 : hex = 'C' + hex ; break ; case 1101 : hex = 'D' + hex ; break ; case 1110 : hex = 'E' + hex ; break ; default : hex = 'F' + hex ; break ; } bin /= 10000 ; } while ( bin > 0 ) ; return hex ; } public static int convertToBase ( int convert , int base ){ int factor = 1 ; int bin = convert ; int oct = 0 ; do { switch ( bin % 1000 ) { case 0 : break ; case 1 : oct += factor * 1 ; break ; case 10 : oct += factor * 2 ; break ; case 11 : oct += factor * 3 ; break ; case 100 : oct += factor * 4 ; break ; case 101 : oct += factor * 5 ; break ; case 110 : oct += factor * 6 ; break ; default : oct += factor * 7 ; break ; } bin /= 1000 ; factor *= 10 ; } while ( bin > 0 ) ; return oct ; } public static int convertToBin ( int original ) { int bin = 0 ; int sum = 0 ; int exponent = 0 ; while ( sum < original ){ sum += Math.pow ( 2 , exponent ) ; exponent ++ ; bin *= 10 ; bin ++ ; } while ( sum > original && exponent >= 0 ){ if ( sum - Math.pow ( 2 , exponent ) >= original ) { sum -= Math.pow ( 2 , exponent ) ; bin -= Math.pow ( 10 , exponent ) ; } exponent-- ; } return bin ; }}And this is the outputBinary Octal Hexadecimal 1 1 1 10 2 2 11 3 3 100 4 4 101 5 5 110 6 6 111 7 7 1000 10 8 1001 11 9 1010 12 A 1011 13 B 1100 14 C 1101 15 D 1110 16 E 1111 17 F 10000 20 10 10001 21 11 10010 22 12 10011 23 13 10100 24 14 10101 25 15 10110 26 16 10111 27 17 11000 30 18 11001 31 19 11010 32 1A 11011 33 1B 11100 34 1C 11101 35 1D 11110 36 1E 11111 37 1F 100000 40 20 100001 41 21 100010 42 22 100011 43 23 100100 44 24 100101 45 25 100110 46 26 100111 47 27 101000 50 28 101001 51 29 101010 52 2A 101011 53 2B 101100 54 2C 101101 55 2D 101110 56 2E 101111 57 2F 110000 60 30 110001 61 31 110010 62 32 110011 63 33 110100 64 34 110101 65 35 110110 66 36 110111 67 37 111000 70 38 111001 71 39 111010 72 3A 111011 73 3B 111100 74 3C 111101 75 3D 111110 76 3E 111111 77 3F 1000000 100 40 1000001 101 41 1000010 102 42 1000011 103 43 1000100 104 44 1000101 105 45 1000110 106 46 1000111 107 47 1001000 110 48 1001001 111 49 1001010 112 4A 1001011 113 4B 1001100 114 4C 1001101 115 4D 1001110 116 4E 1001111 117 4F 1010000 120 50 1010001 121 51 1010010 122 52 1010011 123 53 1010100 124 54 1010101 125 55 1010110 126 56 1010111 127 57 1011000 130 58 1011001 131 59 1011010 132 5A 1011011 133 5B 1011100 134 5C 1011101 135 5D 1011110 136 5E 1011111 137 5F 1100000 140 60 1100001 141 61 1100010 142 62 1100011 143 63 1100100 144 64 1100101 145 65 1100110 146 66 1100111 147 67 1101000 150 68 1101001 151 69 1101010 152 6A 1101011 153 6B 1101100 154 6C 1101101 155 6D 1101110 156 6E 1101111 157 6F 1110000 160 70 1110001 161 71 1110010 162 72 1110011 163 73 1110100 164 74 1110101 165 75 1110110 166 76 1110111 167 77 1111000 170 78 1111001 171 79 1111010 172 7A 1111011 173 7B 1111100 174 7C 1111101 175 7D 1111110 176 7E 1111111 177 7F 10000000 200 80 10000001 201 81 10000010 202 82 10000011 203 83 10000100 204 84 10000101 205 85 10000110 206 86 10000111 207 87 10001000 210 88 10001001 211 89 10001010 212 8A 10001011 213 8B 10001100 214 8C 10001101 215 8D 10001110 216 8E 10001111 217 8F 10010000 220 90 10010001 221 91 10010010 222 92 10010011 223 93 10010100 224 94 10010101 225 95 10010110 226 96 10010111 227 97 10011000 230 98 10011001 231 99 10011010 232 9A 10011011 233 9B 10011100 234 9C 10011101 235 9D 10011110 236 9E 10011111 237 9F 10100000 240 A0 10100001 241 A1 10100010 242 A2 10100011 243 A3 10100100 244 A4 10100101 245 A5 10100110 246 A6 10100111 247 A7 10101000 250 A8 10101001 251 A9 10101010 252 AA 10101011 253 AB 10101100 254 AC 10101101 255 AD 10101110 256 AE 10101111 257 AF 10110000 260 B0 10110001 261 B1 10110010 262 B2 10110011 263 B3 10110100 264 B4 10110101 265 B5 10110110 266 B6 10110111 267 B7 10111000 270 B8 10111001 271 B9 10111010 272 BA 10111011 273 BB 10111100 274 BC 10111101 275 BD 10111110 276 BE 10111111 277 BF 11000000 300 C0 11000001 301 C1 11000010 302 C2 11000011 303 C3 11000100 304 C4 11000101 305 C5 11000110 306 C6 11000111 307 C7 11001000 310 C8 11001001 311 C9 11001010 312 CA 11001011 313 CB 11001100 314 CC 11001101 315 CD 11001110 316 CE 11001111 317 CF 11010000 320 D0 11010001 321 D1 11010010 322 D2 11010011 323 D3 11010100 324 D4 11010101 325 D5 11010110 326 D6 11010111 327 D7 11011000 330 D8 11011001 331 D9 11011010 332 DA 11011011 333 DB 11011100 334 DC 11011101 335 DD 11011110 336 DE 11011111 337 DF 11100000 340 E0 11100001 341 E1 11100010 342 E2 11100011 343 E3 11100100 344 E4 11100101 345 E5 11100110 346 E6 11100111 347 E7 11101000 350 E8 11101001 351 E9 11101010 352 EA 11101011 353 EB 11101100 354 EC 11101101 355 ED 11101110 356 EE 11101111 357 EF 11110000 360 F0 11110001 361 F1 11110010 362 F2 11110011 363 F3 11110100 364 F4 11110101 365 F5 11110110 366 F6 11110111 367 F7 11111000 370 F8 11111001 371 F9 11111010 372 FA 11111011 373 FB 11111100 374 FC 11111101 375 FD 11111110 376 FE 11111111 377 FF 100000000 400 100 | Binary-octal-hexadecimal conversion table | java;beginner;formatting;number systems | You should use the same format for both the headers and the contents of the table.It pays to read the documentation. The task could be accomplished very simply.public static void main(String[] args) { String tableFmt = %11s %11s %11s\n; System.out.printf(tableFmt, Binary, Octal, Hexadecimal); for (int i = 1; i <= 256; i++) { System.out.printf(tableFmt, Integer.toBinaryString(i), Integer.toOctalString(i), Integer.toHexString(i).toUpperCase()); }}Your choice of the base-two representation using an int rather than a String (using one hundred one to represent five) is very unconventional and not recommended.You have also abused method overloading. The base parameter is unused. Rather, you are relying on just the type of the second parameter to pick which method to call. |
_unix.336991 | I'm trying to configure a virtual network in VirtualBox with a central node as gateway & DHCP & DNS server (I'm using the dnsmasq).Central node has two interfaces: enp03 which faces the host network. It configured by host network DHCP and has a dynamic IP address.enp08 which faces the virtual network. dnsmasq is listening this interfase.Now I want to set some static configuration for enp08.Is it possible to do something like that in /etc/network/interfaces:auto enp03iface enp03 inet dhcpauto enp08iface enp08 inet static address 10.0.5.1 netmask 255.255.255.0 gateway enp03 | How to point to network interface from other inteface configuration in /etc/network/interface | linux;networking;routing;network interface | If I understand correctly, you want to define a gateway for the enp08 interface, and tell the kernel that this gateway is the same than the one used on enp03, right?Then just remove/comment that gateway line. It defines a default gateway and the default is already set (by DHCP on enp03), no need to add a duplicate. |
_webapps.78182 | I am using Google Maps to determine my route to work. It is about an hour currently, but I know that when I factor in traffic it will be longer. I want to know just how much longer it will be. I was wondering if there is a way to use the past traffic delays to calculate what my travel time might be given a specific travel time for that day? | Is there a way to calculate a Google Maps commute based on past traffic delay times? | google maps | If you hover over the directions box (top-left) on the map, you will see that it tells you the estimated time for leaving now. If you click on the Leave Now part, you can change the departure or arrival time. When you do, you will see the estimated time update to take into account known traffic flows for that date/time.That's as good as it gets since those kinds of calculations are highly complex and based on all sorts of factors including road works and average traffic flows. |
_webapps.8596 | I receive email to these addresses:[email protected] : This is my team's primary method of communication. I want all of this email to go to my [email protected] : This belongs to another team at my organization, but I monitor it. I have a filter on this sort of email. It skips the Inbox. I'll usually read it later.If an email is sent to both [email protected] and [email protected], the label for 'other-team' is applied, and the email is removed from my Inbox. But, this email was sent to [email protected], so I would like this email to remain in my Inbox.How can I tell Gmail to leave any email to [email protected] in my Inbox, even the email matches other rules?Or, to ask the question another way, can I tell Gmail to stop processing filters after it has matched a filter? This is a common practice with Microsoft Outlook.I tried to create a Filter using a Label named Inbox, but Gmail says Sorry, you can't create a label named inbox (it's a reserved system label). | Gmail filters/labels: Force email to stay in Inbox? | gmail;gmail filters;gmail labels | null |
_unix.134076 | You have no necessity to install any additional packages. Everything should work fine. Thus check whether files /proc/net/tcp6, /proc/net/tcp exist. If they are absent, just add them. sir you gave this answer at given link:https://serverfault.com/questions/425345/why-dstat-failed-with-tcp-option can you please tell me about how to add tcp6 on raspbian. actually i am using raspberry pi for my thesis. thanks in advance. | How to add tcp6 on raspbian? | linux | null |
_unix.318992 | The Makefile is:%.pdf: %.tex rubber -d $<If there is a doc.tex in the directory, then make doc.pdf builds doc.pdf. The problem is that when I type make, the autocompletion gives nothing: it doesn't even allow to autocomplete to make doc.tex. What can be done about it? | Autocomplete in make based on possible targets | bash;make;autocomplete | null |
_unix.275088 | I am trying to search all IP addresses that connected to my server and want to find abusive servers from nslookup results.nslookup 31.204.150.10 | grep in-addrSome example results:209.190.54.154 154.54.190.209.in-addr.arpa name = 9a.36.be.static.xlhost.com.209.51.199.34 34.199.51.209.in-addr.arpa name = 22.c7.33.static.xlhost.com.209.51.197.234 234.197.51.209.in-addr.arpa name = ea.c5.33.static.xlhost.com.31.204.150.10 10.150.204.31.in-addr.arpa name = hosted-by-i3d.net.209.51.197.218 218.197.51.209.in-addr.arpa name = da.c5.33.static.xlhost.com.207.46.13.25 25.13.46.207.in-addr.arpa name = msnbot-207-46-13-25.search.msn.com.200.105.189.165 165.189.105.200.in-addr.arpa name = static-200-105-189-165.acelerate.net.198.62.109.139 139.109.62.198.in-addr.arpa name = jangan.sebok.share.78.187.209.209 209.209.187.78.in-addr.arpa name = 78.187.209.209.static.ttnet.com.tr.197.33.99.78 78.99.33.197.in-addr.arpa name = host-197.33.99.78.tedata.net.197.157.0.45 ** server can't find 45.0.157.197.in-addr.arpa.: NXDOMAIN180.76.15.6 6.15.76.180.in-addr.arpa name = baiduspider-180-76-15-6.crawl.baidu.com.176.10.104.243 243.104.10.176.in-addr.arpa name = tor2e1.privacyfoundation.ch.174.129.237.157 157.237.129.174.in-addr.arpa name = ec2-174-129-237-157.compute-1.amazonaws.com.174.102.192.129 129.192.102.174.in-addr.arpa name = cpe-174-102-192-129.wi.res.rr.com.As an example, for nslookup 97.33.99.78 result97.33.99.78 78.99.33.197.in-addr.arpa name = host-197.33.99.78.tedata.net.I want to extract tedata.net domain base.But some domain base have 3 or 4 components: wi.res.rr.com and static.ttnet.com.trAlso for XLHOST, I am not sure to chose static.xlhost.com or xlhost.com for search repeating pattern.209.190.54.154 154.54.190.209.in-addr.arpa name = 9a.36.be.static.xlhost.com.209.51.199.34 34.199.51.209.in-addr.arpa name = 22.c7.33.static.xlhost.com.209.51.197.234 234.197.51.209.in-addr.arpa name = ea.c5.33.static.xlhost.com.What do you recommend to detect abusive IPs that generate from specific server? | Determining Domain Base Name from Nslookup Results | bash;shell script;nslookup | null |
_softwareengineering.207205 | I have WCF webservice which serves to various mobile application. This was implemented with typical HTTPS/SSL. But there are some cases like Replay Attack needs to be considered in the security aspect.OAuth 2.0 looks like a viable solution for this problem (using nonce). And I can see some examples on web using DotnetOpenOAuth library to implement a server.Is OAuth is a right choice to use with WCF services?Is there any alternatives with .NET framework/Microsoft technologies to implement a secure WCF server? | Is OAuth (2.0) is the right choice to make WCF WebService secure? | design;.net;architecture;rest;wcf | null |
_cstheory.34271 | In a read-twice opposite CNF formula each variable appears twice, once positive and once negative.I'm interested in the $\oplus\text{Rtw-Opp-CNF}$ problem, which consists in computing the parity of the number of satisfying assignments of a read-twice opposite CNF formula.I was unable to find any reference about the complexity of such problem. The closest I was able to find is that the counting version $\#\text{Rtw-Opp-CNF}$ is $\#\text{P}$-complete (see section 6.3 in this paper).Thanks in advance for your help.Update 10th April 2016In this paper, the $\oplus\text{Rtw-Opp-SAT}$ problem is shown to be $\oplus\text{P}$-complete, however the formula produced by reduction from $3\text{SAT}$ is not in CNF, and as soon as you try to convert it back into CNF you get a read-thrice formula.The monotone version $\oplus\text{Rtw-Mon-CNF}$ is shown to be $\oplus\text{P}$-complete in this paper. In such paper, $\oplus\text{Rtw-Opp-CNF}$ is quickly mentioned at the end of section 4: Valiant says it is degenerate. It is not clear to me what being degenerate exactly means, nor what does it imply in terms of hardness.Update 12th April 2016It would be also very interesting to know if anyone has ever studied the complexity of the $\Delta\text{Rtw-Opp-CNF}$ problem. Given a read-twice opposite CNF formula, such problem asks to compute the difference between the number of satisfying assignments having an odd number of variables set to true and the number of satisfying assignments having an even number of variables set to true. I've not found any literature about it.Update 29th May 2016As pointed out by Emil Jebek in his comment, it is not true that Valiant said that the problem $\oplus\text{Rtw-Opp-CNF}$ is degenerate. He only said that a more restricted version of such problem, $\oplus\text{Pl-Rtw-Opp-3CNF}$, is degenerate. In the meanwhile, I continue to not know what degenerate exactly means, but at least now it seems clear that it is a synonym of lack of expressive power. | Complexity of computing the parity of read-twice opposite CNF formula ($\oplus\text{Rtw-Opp-CNF}$) | cc.complexity theory;ds.algorithms;counting complexity | null |
_unix.310820 | I'm configuring buttons on my mouse I want to set volume buttons but I don't know the keycode fo volume buttons. I used xbindkeys but didn't work. | Keycode for volume buttons | linux;audio;mouse;xbindkeys | null |
_unix.85308 | I did so many searches on search engines, but could not find a relevant solution.Is there any research or source that shows an approximate value for servers? | What's the approximate percentage of Linux servers in the world? | linux;webserver | Here are a couple of resources for Linux deployments. The best resource is likely going to be articles.Wikipedia topic titled: Usage share of operating systemsLinux Leads Server Growth - thejournal.comIf you search for Linux server market share or linux servers worldwide you'll likely find more if you need them.excerpt from that wikipedia topicscanning the internetServer market share can be measured with statistical surveys of publicly accessible servers, such as web servers, mail servers or DNS servers on the Internet: the operating system powering such servers is found by inspecting raw response messages. This method gives insight only into market share of operating systems that are publicly accessible on the Internet. There will be differences in the result depending on how the sample is done and observations weighted. Usually the surveys are not based on a random sample of all ip numbers, domain names, hosts or organisations, but on servers found by some other method. Additionally many domains and ip numbers may be served by one host and some domains may be served by several hosts or by one host with several ip numbers. Notes:W3Techs survey in January 2013 checked the top 1 million Web servers (according to Alexa).Security Space survey in August 2009 checked 38,549,333 publicly accessible Web servers.Netcraft SSL survey in January 2009 also checked 1,014,301 publicly accessible Web servers, but the survey is only valid for SSL Web servers and it is not a good measure for our purpose.hardware sales methodA method to measure the overall server market, rather than subsets like publicly accessible web servers, is to count server hardware sales, using data from server manufacturers. Using this method, market share can be measured either in units or in revenue. In either case, the measure refers to server hardware, not to software. Units refers to the number of physical servers running a given OS, and revenue refers to hardware revenue for physical servers running that OS. It does not refer to software licensing or support revenue, which often varies considerably from one OS to another. |
_unix.172640 | I want to run two scripts at the same time. How exactly do I do this? If I have a variable called foo in script1 and change its value to 5, and if I'm using a variable with the same name in script2 (that runs simultaneously with script1), will the value of variable foo in script2 also become 5? | Run two scripts at the same time | shell;scripting;parallelism | null |
_webmaster.1734 | I'm not an advocate of the no-www movement. I like the www because it adds as a buffer to distinguish between our public and private/static sites.The problem is that with one of our sites, our traffic is split pretty much 50/50 between those that use our www and those that don't.Should I bother rewriting those who hit our non-www site to our WWW site? Or should I just leave them alone? All our google SEO whatnot is on our www site, so I'm not concerned about any of that, only about user perception.Has anyone here had this problem before? I'm not concerned about the technial aspect (that's easy with a quick rewrite rule), primarily the social side. | Removing non-www support | htaccess;no www | Either way is fine from a user perspective, as long as both work when you type them in the address bar. The problem is having both without redirecting one to the other. Google and other search engines will count www.example.com and example.com as two different URLS. This, along with inconsistently ordered URL parameters, is one of the major causes of duplicate content. If people are linking to both the www and non-www versions of pages, you're effectively diluting your PageRank between two different pages with the same content. Since most of your Google traffic is coming through the www version, I'd 301 redirect the non-www to the www URLs. By doing it that way, you lose less potential PageRank through the 301 than you would the other way around. |
_cogsci.1687 | The goal is to take simple measurements of mood using Likert scale over an extended period of time (e.g. two months). I know there is a large number of mobile apps for tracking mood on every possible platform and there is an extensive list of those tools on Quantify Self website. All those tools allow you to record your mood in a simple format, customize your tracking, and choose yourself time when you want to record you mood. And this is exactly the point where all of those tools are missing a critical feature. To get a more reliable sample of a behaviour or experience, you ought to sample the experience in a random time during the waking day, rather then give the person a choice of the time of sampling (Csikszentmihalyi et al., 1987). Csikszentmihalyi et al. (1977) did just that by giving people pagers and send them random beeps, after which they filled the questionnaire. It's a basic rule in any longitudinal experience sampling studies that I remember from the first year undergraduate classes. The need of this kind of approach rises from the inability of respondents to provide an accurate retrospective information on their daily behaviour and experience.So I am looking for mobile mood tracking tool that meets those particular requirements:it allows you to set up waking time within which you want to receive random reminders,it allows you to set up number of reminders you want to receive during the waking hours,during the day you receive a random reminder that directs you to a single question asking you to rate your mood at the moment, for example on 1-9 scaleyour response is time-stamped and saved either on the mobile phone or send directly to the server if possible.Now, it sounds simple enough, but the only app I found that matches some aspects of it is Mappiness. They DO send you random reminders, and their project, idea, and app execution are awesome. But the problem with Mappiness is that it collects a lot of extra information that I don't need, and I personally got very annoyed with the length of their questionnaire (check yourself if you got an iPhone). I want a random notice, single question, 5-seconds of your time to respond, and some data export option.Am I missing something here or such app doesn't exist and I need to write it? I realise that this question might be more relevant for http://productivity.stackexchange.com but it's hard to say, it's kind of a middle-area.References:Csikszentmihalyi, M., & Larson, R. (1987). Validity and reliability of the experience-sampling method. The Journal of Nervous and Mental Disease, 175(9), 526.Csikszentmihalyi, M., Larson, R., & Prescott, S. (1977). The ecology of adolescent activity and experience. Journal of Youth and Adolescence, 6(3), 281294. | Longitudinal mobile mood tracking app with random reminders | reference request;measurement;emotion;methodology;experimental psychology | null |
_unix.281615 | The easiest/simplest understanding of the web is a. When you connect to your ISP, the ISP gives a dyanmic address (like a temporary telephone number) only for the duration of that connection, the next time you connect, you will again have a different dynamic IP Address. b. You use the browser to to different sites which have static IP Address (like permanent numbers or/and permanent address of an establishment). Now is there a way to get self's IP address instead of going to a web-service like whatismyipaddress.com. The connection is as follows :-ISP - Modem/Router - System Edit - The Modem/Router is a D-Link DSL-2750U ADSL router/modem. http://www.dlink.co.in/products/?pid=452I did see How to track my public IP address in a log file? but that also uses an external web-service, it would be better/nicer if we could do without going to an exernal URL/IP address for the same. | Is there a way to find self's dynamic public ip address using cli in Debian? | bash;debian;networking;ip;dynamic dns | In addition to Tonys answer, of querying OpenDNS, which I use in my scripts upon logging on to my servers to display both the local machine and remote public IP address:echo `hostname` `hostname -i` `dig +short +time=1 myip.opendns.com @resolver1.opendns.com`Google also offers a similar service.dig TXT +short o-o.myaddr.l.google.com @ns1.google.com | awk -F'' '{ print $2}'If you have a private IP address, behind a home or corporate router/infra-structure, or even if you are your own router, these services in the Internet will reveal the public IP address you are using to reach them, as it is what arrives to them doing the request. Please do note that the above methods only work if the Linux machine in question has direct access to the Internet.If your Linux server is your router, besides you being able to have a look at your current interfaces, you might also do:hostname -iAs normally the public IP address is often the main/first interface. If not the first interface, you might also do:$hostname -I95.xx.xx.xxx 192.168.202.1 192.168.201.1 Which shows you all the IP addresses of the machine interfaces.Please read too:How To Find My Public IP Address From Command Line On a LinuxAgain, if the Linux server is the router, it might be interesting to place a script in /etc/dhcp/dhclient-exit-hooks.d to track and act on your IP changes, as I documented in this question: Better method for acting on IP address change from the ISP? |
_unix.11469 | root@ip-10-194-97-94:~# apt-get install uwsgiReading package lists... DoneBuilding dependency tree Reading state information... DoneSome packages could not be installed. This may mean that you haverequested an impossible situation or if you are using the unstabledistribution that some required packages have not yet been createdor been moved out of Incoming.The following information may help to resolve the situation:The following packages have unmet dependencies: uwsgi: Depends: uwsgi-python2.6 (>= 0.9.6.5-0ubuntu1~lucid1) or uwsgi-python3.1 (>= 0.9.6.5-0ubuntu1~lucid1)E: Broken packages | Can't install uwsgi on ubuntu | install;apt | null |
_reverseengineering.4565 | Note: I'm aware of the technical and legal implications of reverse-enginneering binaries.I have the firmware for a Netgear WGR614v7 router, in the form of a .chk file, coming from Netgear themselves, and I wish to unpack the file. My understanding is that a firmware .chk file is a header before a TRX image, and I've tried to untrx the ile I had sans header, or with header as well. Neither that nor binwalk succeeded. Two useful strings are seen very close to the beginning of the file:AH00I8U12H064T00_NETGEARInspecting the file in a hex editor, I'm unable to find the TRX file signature (I was looking for ASCII HDR0). I also cannot find any sort of compression magic values, except fairly far into the file where they're not likely to signify the beginning of the actual content I'm looking for. Am I looking for the wrong filetypes? Is anything about this structure known that I haven't found yet?Edit: The firmware has been downloaded from Netgear's site. I tried chopping off various lengths but cannot find a reasonably-located compression or TRX header. The characteristic ff ff ff ff of IMG images used as a method of preventing a repetitive boot firmware is also not existent.Edit 2: I did some searching of my own, and found a decompression utility. When I chopped the file such that sqz had been the first characters, that utility seemed to find valid Huffman structures but incur a size mismatch. A result of the decompression yielded 11 bytes, while the program warned me:Warning: Unpacked file should be 7537274 bytes but is 396409921 bytes! at ./unpack.pl line 61, <STDIN> line 3.Of course, it could be that many kinds of data that is corrupt might be partially readable as huffman giving me strange results as seen here. | Format of .chk firmware package on WGR614v7 | file format;firmware | The file begins:0000000: 4148 3030 4938 e66c 000e aa28 9835 0589 AH00I8.l...(.5..0000010: 3004 125a 1b39 65ff 47e4 b95c 0001 0014 0..Z.9e.G..\....0000020: 5531 3248 3036 3454 3030 5f4e 4554 4745 U12H064T00_NETGE0000030: 4152 0000 AR..The reason for picking this size will soon become clear.The first four bytes (AH00) are probably file magic. Googling just that string brings up this page, which has a detailed breakdown of a different firmware file with a similar structure.The next four bytes are not described by the linked page. Reading them as a 32-bit big-endian value (BE32), though, you get 0x4938e66c = 1228465772, which is plausibly a recent UNIX timestamp (usually values from around 800,000,000 to 1,500,000,000). Indeed, it decodes to Fri Dec 5 08:29:32 2008 GMT, which is plausibly the build date of the hardware (and I note that the linked article has 0x481ac265 = Fri May 2 07:27:33 2008 GMT, which also seems plausible).The next four bytes read as a BE32 value give 961064. The total filesize is 961116 bytes, so this is likely the payload size, leaving 52 bytes for the header (and thus explaining why I chose to show the first 52 bytes here).The next 32 bytes are the MD5 sum of the payload as indicated by the linked page. I deleted the first 52 bytes and MD5 summed the result:983505893004125a1b3965ff47e4b95c /tmp/fw.sqzwhich is exactly what the header contains.The next two bytes are unknown.The next two bytes are 0x0014, which is the length of the string that follows (including two padding NULs). While I'm not familiar with Netgear routers, I'm guessing this is a model/revision number for the hardware target.And there you go: that's the .chk file header.char magic[4];uint32_t timestamp; // UNIX timestampuint32_t payload_size;char md5sum[32];uint16_t unknown; // = 1 on all files seen so faruint16_t model_size;char model[model_size];In the original linked page, the payload was a plain ELF file. Unfortunately, in your firmware, the payload is some other kind of file, with the magic sqz (squeeze?). It's clearly compressed, but I can't tell what it's compressed with. For now, this will have to be an incomplete answer until someone figures out what the compression format is. |
_codereview.42264 | char *cat_string(char *to_cat, char *destination) { char *copy = destination; while (*copy != '\0') { *copy++; } while (*to_cat != '\0') { *copy++ = *to_cat++; } *copy = '\0'; return destination;}I would like to know if this is an efficient and effective way of writing this function. It seems silly to have to iterate through the whole array just to find the \0 character.Also, should I be returning the pointer to the destination? What's the best practice there? | Writing strcat (string concatenate) in C | c;beginner;strings | You renamed strcat() to cat_string(), so I suppose it's fitting that you reversed the traditional order of the parameters as well. I would make three changes:Changing the first argument to const helps prevent users notice if they call the function with the parameters swapped (but doesn't prevent it in all cases).You have a stray pointer dereference. It was misleading, but luckily harmless. (In the first while loop, you just want to advance the copy pointer. You don't care about what value it points to as you advance; you only care when you check for the NUL terminator.)You can remove a statement just by changing the loop structure.Edit (Rev 3): Previous recommendation was buggy, and has been retracted. Credit to @MarcvanLeeuwen.To answer your questionsThe only way to find out where to start appending is to walk the entire destination string to locate where it ends. That's just how C-style strings work.Yes, returning destination seems appropriate. It's analogous to what strcat() does.One final note: two spaces for indentation is too stingy, in my opinion. It's insufficient for readability, and it also encourages inappropriately deep nesting (which would be a symptom of poorly organized code).char *cat_string(const char *to_cat, char *destination) { char *copy = destination; while (*copy != '\0') { copy++; /* Removed superfluous dereference. */ } } |
_unix.233814 | I use multiple accounts in mutt, and wish to save sent messages to different $record directories. I am aware of folder-hook; if I compose in different folders, I can change $record depending on the associated account of the initial folder.However, sometimes, I might want to compose from a different folder, or forward an email to one account from another, or reply from a different account, or change my mind mid-composition (I have set edit_headers=yes). Hence, it makes more sense to save the sent email to a specific directory based on the from field. Is that possible?I understand that fcc-hook could change $record based on recipients, but I'd like to change it based on sender instead. | How can I change $record in mutt depending on the from address? | mutt | You can use fcc-hook to change the folder depending on all sorts of parameters.fcc-hook '~f [email protected]' '=foo-folder'fcc-hook '~f [email protected]' '=bar-folder'I also use it to depend on the subject (all messages whose subject contains ISDN go to my =ISDN folder, for example), use '~s' for that. |
_unix.37682 | I just installed Linux Mint 12 using mint4win just to test it out. I have a problem with my wireless connection.When I start Mint, it sees the network I wish to join, I select it, enter the correct password, and 1 minute later I am being prompted for a password again. During that waiting time, I was not connected at all.It appears if I turn off my Wireless (by tapping on the Wireless LED on the laptop), it wont turn on again either.My Ethernet port is broken as well, so I cannot connect with a cable either. In Windows I can connect fine using Wireless.Is there any drivers required for this to work? I cant seem to find any, and they have to be downloadable from Windows so I can put them on an USB and run them in Mint.Thank you in advanceEDIT: My Wireless chip is an Atheros AR9285 | Linux Mint 12 on HP Pavillion DV7 - Wireless is not working | networking;linux mint;wifi | null |
_unix.19210 | It seems that usually it is talked about snapshots as read-only. (In a scenario where one creates a snapshot, then does some experiments with the main volume, and then restores the old state by merging the snapshot into the main volume.)Is an alternative scenario possible in LVM? I.e., where one doesn't even want the temporary experiments to be visible in the main volume, so one creates a temporary snapshot, makes it writable, does the experiments there, in that branch, and then discards the snapshot (or perhaps merges it if one is satisfied with the results)?And if writable snapshots are possible in LVM, then what happens when merging a modified snapshot into the main volume which also has had some different modifications?(BTW, btrfs snapshots seem to be writable by default, so this scenario seems to be well possible in btrfs.) | Can LVM snapshots be writable? (and used for temporary experiments) | lvm;restore;tmp;sandbox | LVM does support read-write snapshots in fact that's the default. Merging a modified snapshot will delete the data on the snapshot origin volume the same way merging an unmodified snapshot would.If you expect to discard modifications then I recommend RW snapshots and merge if you want to keep them. If you expect to keep the modifications then you should create a RO snapshot (or RW just don't mount it) and merge if something goes wrong.An example for the first situation could be: You want to start a virtual machine with the exact same software every day. Sometimes you want to keep the changes because you installed patches but most of the time you want to start fresh.The second situation could be a system upgrade. Most of the time it works and you can remove the snapshot. But every now and then it fails and you want to merge. |
_datascience.5040 | I'm using a set of features, says $X_1, X_2, ..., X_m $, to predict a target value $Y$, which is a continuous value from zero to one.At first, I try to use a linear regression model to do the prediction, but it does not perform well. The root-mean-squared error is about 0.35, which is quite high for prediction of a value from 0 to 1.Then, I have tried different models, e.g., decision-tree-based regression, random-forest-based regression, gradient boosting tree regression and etc. However, all of these models also do not perform well. (RMSE $\approx $0.35, there is not significant difference with linear regression)I understand there are many possible reasons for this problem, such as: feature selection or choice of model, but maybe more fundamentally, the quality of data set is not good.My question is: how can I examine whether it is caused by bad data quality?BTW, for the size of data set, there are more than 10K data points, each of which associated with 105 features.I have also tried to investigate importance of each feature by using decision-tree-based regression, it turns out that, only one feature (which should not be the most outstanding feature in my knowledge to this problem) have an importance of 0.2, while the rest of them only have an importance less than 0.1. | How to determine whether a bad performance is caused by data quality? | machine learning | First, it sounds like your choice of model selection is a problem here. Your outputs are binary-valued, not continuous. Specifically you may have a classification problem on your hands rather than a traditional regression problem. My first recommendation would be to try a simple classification approach such as logistic regression or linear discriminant analysis.Regarding your suspicions of bad data, what would bad data look like in this situation? Do you have reason to suspect that your $X$ values are noisy or that your $y$ values are mislabeled? It is also possible that there is not a strong relationship between any of your features and your targets. Since your targets are binary, you should look at histograms of each of your features to get a rough sense of the class conditional distributions, i.e. $p(X_1|y=1)$ vs $p(X_1|y=0)$. In general though, you will need to be more specific about what bad data means to you. |
_unix.164275 | OK, so I have an old office reject printer, the OKI B4350.Works great with CUPS and Evince except for one thing: often it prints the page all messed up: offset from the upper left corner and truncated in the lower right corner, and the word x0y or xOy added.So far, this has never ever happened on the first page I print, but it happens often later in a multi-page print job.My wild hypothesis is that it's when a preceding page goes to close to (or out in) the margins.So ideally I'd like to figure out what's wrong, and fix it, and be able to print really tight margins. But if that's not possible, maybe some sort of filter I could put things through to make it happy? pdfcrop hasn't been enough. | How can I workaround or fix a printer offset x0y? | pdf;cups;printer | null |
_unix.44384 | I hope this does not count as a question without a real answer, as I can't seem to find a good reason to use cp(1) over rsync(1) in virtually all circumstances. Should one typically favour rsync over cp? Is there any good guideline for their use?rsync: Transfers the diffs, it can use compression, it can be used remotely (and securely), it can be restarted despite an interruption, even during the transfer of a single large file. 'cp : Perhaps it's just simpler to use? Is it faster than rsync? | cp or rsync, is cp really worth it? | bash;shell;rsync;utilities;cp | cp is a part of coreutils, therefore it is present everywhere. furthermore, it primarily was designed to copy files inside one computer.rsync isn't a part of coreutils, it isn't present even on the default environment. moreover it was primarily designed to transfer files over network. Also rsync has more dependencies comparing to coreutils, however this difference doesn't make a big sense.ps. By the way the CPU usage is still matters on the embedded systems. |
_unix.343775 | IntroductionFirst of all, here's what I use: Ubuntu 16.04I happened to install the package systemd-shim on my computer. However, it returned an error saying it could not be configured.So for the time being I let it be just like that. However, whenever I want to perform any other operation using apt, it shows up in the list: 1 package not installed and yet it does not get installed properly even with a --reinstall command.The problemThen I decided that I'd simply remove it, using apt purge.However, that does not work either. Here's a part of the error I get:insserv: Starting .depend.start depends on plymouth and therefore on system facility `$all' which can not be true!insserv: There is a loop between service .depend.start and dns-clean if startedinsserv: loop involving service dns-clean at depth 1insserv: exiting now without changing boot order!update-rc.d: error: insserv rejected the script headerdpkg: error processing package cgmanager (--purge): subprocess installed post-removal script returned error exit status 1Processing triggers for man-db (2.7.5-1) ...Errors were encountered while processing: cgmanagerE: Sub-process /usr/bin/dpkg returned an error code (1)The same is true regarding the package cgmanager, which was apparently also incompletely configured at the time of incomplete configuration of systemd-shim.The same error occurs also when executing sudo apt install --reinstall mdadm, a step recommended by this answer:insserv: Starting .depend.start depends on plymouth and therefore on system facility `$all' which can not be true!insserv: There is a loop between service .depend.start and dns-clean if startedinsserv: loop involving service dns-clean at depth 1insserv: Starting .depend.start depends on plymouth and therefore on system facility `$all' which can not be true!insserv: exiting now without changing boot order!update-rc.d: error: insserv rejected the script headerdpkg: error processing package mdadm (--configure): subprocess installed post-installation script returned error exit status 1Processing triggers for systemd (229-4ubuntu16) ...Processing triggers for ureadahead (0.100.0-19) ...Errors were encountered while processing: mdadmE: Sub-process /usr/bin/dpkg returned an error code (1)I tried clearing the apt cache, i.e., the local directory where downloaded .deb packages are stored for them to be installed on the current/next run, but to no avail.I am unable to find a solution anywhere specific to my situation, hence the question. Other questions (A, B) involve issues that have arisen during 16.04-->16.10 upgrade. However, I am using 16.04 and do not intend to upgrade my system in the near future. I had manually tried to install the package(s) and encountered the above-mentioned errors.My system works properly and doesn't encounter any functional errors due to this, but it is better to resolve it than just leave it lying there, so I would appreciate any help that you can offer.UpdateI ran the command sudo dpkg --reconfigure -a and here's more such output:W: mdadm: /etc/mdadm/mdadm.conf defines no arrays.Processing triggers for plymouth-theme-ubuntu-text (0.9.2-3ubuntu13.1) ...update-initramfs: deferring update (trigger activated)Processing triggers for initramfs-tools (0.122ubuntu8.8) ...update-initramfs: Generating /boot/initrd.img-4.4.0-62-genericW: Possible missing firmware /lib/firmware/i915/kbl_dmc_ver1.bin for module i915_bpoW: mdadm: /etc/mdadm/mdadm.conf defines no arrays.Errors were encountered while processing: mdadmUpdate [2017-02-22]Here are the contents of mdadm.postinst file: Pastebin link.Also, here is the output of dpkg -C:The following packages are only half configured, probably due to problemsconfiguring them the first time. The configuration should be retried usingdpkg --configure <package> or the configure menu option in dselect: keyboard-configuration system-wide keyboard preferences mdadm tool to administer Linux MD arrays (software RAID) | Unable to purge or reinstall 'systemd-shim' and 'cgmanager' | ubuntu;apt;package management;systemd;dpkg | null |
_webmaster.34096 | So I have a website which displays all my content vertically. (like modern websites often do these days). Thus I can't create static links to each section. I'm currently handling the scrolling with javascript. My navigation looks like this.<ul> <li><a href=#services>Services</a></li> <li><a href=#references>References</a></li> <li><a href=#blog>Blog</a></li> <li><a href=#contact>Contact</a></li></ul>I also created 301 redirect links with htaccess. E.g. /services which leads to /#services.If I were to use them in my navigation, I'd have to trigger the scrolling with the onpopstate event. Thats not really a problem, but would searchengines accept that kind of setup ?I also created a sitemap and submitted it to google, but the indexing is still pending. | SEO: Make hashtag links look static | seo;sitemap;links | You have 1 page. All the content is loaded as the page loads and all the content is visible. So, there is only 1 page and 1 canonical URL that identifies that page. (This is not an AJAX loaded page where sections are loaded later on request.)Search engines (ie. Google) index pages, not parts of pages. So, I can't see as there is any benefit (from an SEO viewpoint) in attempting to identify these separate sections as different pages, when they are not. You could even end up with duplicate content issues!? IMO the sitemap (if indeed you supply one at all) should have just 1 page.However, Google might actually handle this for you and offer the appropriate link to your sub section in the SERPs. I'm not sure how prevalent this is, but Google is able to index in-page links to some extent. For example:Example#1 Search Google for: the document body site:www.w3.orgYou will see that the very top result shows:Jump to The BODY element is an in-page anchor half way down the page, which is simply linked to from the page contents at the top.Example#2 Search Google for: google safe searchPart way down the SERPs (currently #3) you will see:I would have hoped that Google would be able to identify both elements with an id=foo and named anchors eg. <a name=foo></a> as the target. But all the examples I've seen in the wild use named anchors in order to identify the target. And I've also only seen it applied to large/established sites?! (But that might be partly because many sites don't use named anchors these days?)Here is some information from Google themselves (Sept 2009) on Using named anchors to identify sections on your pages:http://googlewebmastercentral.blogspot.co.uk/2009/09/using-named-anchors-to-identify.html |
_datascience.17628 | I would like to examine an existing Git repository and extract all defined releases into a subfolder. For example, if application A had 26 releases, my bash script would extract all 26 versions into subfolders such as:A/(folder) for each of the defined releasesThe preferred language is bashThanks all | Extract all releases from GIT repository | version control;linux | null |
_webmaster.105134 | Suppose Mr.X visits a blog post on my website, views an advertisement by Google Adsense, gets what he came for and leaves the site. After some time, for some reason, he again visits the same blog post on my site and sees the same advertisement.Will the return visit of Mr.X be counted as 2 impressions by Google Adsense or 1 impression? And is there any time span (or something) after which it will be counted as 2 impressions?I searched Google, but did not manage to find a specific answer.Found a QA at this link: Does page impression get counted for unique visits? but neither did I understand the question nor do I think it addresses my problem. | Does a returning visitor to a web page count as a page impression in Google Adsense? | google analytics;google adsense | Yes, That will be counted as 2 impression because An impression is counted for each ad request that returns at least one ad to the site. It is the number of ad units (for content ads) or search queries (for search ads) that showed ads.So there will be two Ad request for the same Ad but the Unique impression will be counted as 1. Source: https://support.google.com/adsense/answer/6157410?hl=en |
_unix.359979 | Why does Blutooth not connect? The Bluetooth unit can find, but not connect to other devices on Debian Testing (9.0 Stretch). Bluetooth works well with a different Operating System. BIOS settings permit wireless.The following packages were installed: bluez-firmwarebroadcom-sta-commonbroadcom-sta-dkmsbroadcom-sta-sourcefirmware-brcm80211firmware-misc-nonfree$ sudo dmesg | grep -i blue[ 18.086647] Bluetooth: Core ver 2.22[ 18.086660] Bluetooth: HCI device and connection manager initialized[ 18.086663] Bluetooth: HCI socket layer initialized[ 18.086664] Bluetooth: L2CAP socket layer initialized[ 18.086668] Bluetooth: SCO socket layer initialized[ 18.149652] Bluetooth: hci0: BCM: chip id 63[ 18.165659] Bluetooth: hci0: BCM20702A[ 18.166653] Bluetooth: hci0: BCM20702A1 (001.002.014) build 0000[ 18.176624] bluetooth hci0: firmware: failed to load brcm/BCM20702A1-13d3-3404.hcd (-2)[ 18.176665] bluetooth hci0: Direct firmware load for brcm/BCM20702A1-13d3-3404.hcd failed with error -2[ 18.176668] Bluetooth: hci0: BCM: Patch brcm/BCM20702A1-13d3-3404.hcd not found[ 18.553154] Bluetooth: BNEP (Ethernet Emulation) ver 1.3[ 18.553156] Bluetooth: BNEP filters: protocol multicast[ 18.553160] Bluetooth: BNEP socket layer initialized[ 18.574361] Bluetooth: RFCOMM TTY layer initialized[ 18.574365] Bluetooth: RFCOMM socket layer initialized[ 18.574368] Bluetooth: RFCOMM ver 1.11$ lsmod | grep wlwl 6443008 0cfg80211 589824 1 wl$ sudo modprobe -v broadcom-sta-dkmsmodprobe: FATAL: Module broadcom-sta-dkms not found in directory /lib/modules/4.9.0-2-amd64$ sudo dmesg | grep -i blu [ 18.086647] Bluetooth: Core ver 2.22 [ 18.086660] Bluetooth: HCI device and connection manager initialized [ 18.086663] Bluetooth: HCI socket layer initialized[ 18.086664] Bluetooth: L2CAP socket layer initialized[ 18.086668] Bluetooth: SCO socket layer initialized[ 18.149652] Bluetooth: hci0: BCM: chip id 63[ 18.165659] Bluetooth: hci0: BCM20702A[ 18.166653] Bluetooth: hci0: BCM20702A1 (001.002.014) build 0000[ 18.176624] bluetooth hci0: firmware: failed to load brcm/BCM20702A1-13d3-3404.hcd (-2)[ 18.176665] bluetooth hci0: Direct firmware load for brcm/BCM20702A1-13d3-3404.hcd failed with error -2[ 18.176668] Bluetooth: hci0: BCM: Patch brcm/BCM20702A1-13d3-3404.hcd not found[ 18.553154] Bluetooth: BNEP (Ethernet Emulation) ver 1.3[ 18.553156] Bluetooth: BNEP filters: protocol multicast[ 18.553160] Bluetooth: BNEP socket layer initialized[ 18.574361] Bluetooth: RFCOMM TTY layer initialized[ 18.574365] Bluetooth: RFCOMM socket layer initialized[ 18.574368] Bluetooth: RFCOMM ver 1.11Related Resources:BCM4352 WikiDevi Debian | Broadcom BCM4352 : Bluetooth does not connect | debian;bluetooth;connectivity | You are missing firmware for the bluetooth.cd /lib/firmware/brcmsudo wget https://github.com/winterheart/broadcom-bt-firmware/raw/master/brcm/BCM20702A1-13d3-3404.hcdsudo modprobe -r btusbsudo modprobe btusbSee if it works |
_unix.225609 | My brother recently bought a touch screen monitor Dell S2240T, I connected it to my laptop using HDMI interface. I'm using OpenSuse 13.2 with latest stable KDE4. Initially monitor display looks blurred, after manually setting monitor frequency to 60Hz, it look better. It recognized proper resolution 1080p but not using full width ofscreen.It is incorrectly recognizing location of touch input (for example if I touch on a folder in dolphin, it opens other folder) . Also multi-touch is not working.Is there any utility to properly calibrate touch screen? | Configuring touch screen monitor | kde;touch screen;multi touch | null |
_reverseengineering.11838 | I recently saw a video of someone doing some rop work. And I have a lot of trouble about what is going on. His setup is like this:[garbage][xor eax][xor ebx][address of sh][pop ecx][address of Null byte][pop edx][address of Null byte][add eax 11]The first instruction is xor eax (where eip return is) , and I don't understand where the esp is when there are the pop instructionsLink to the video : https://youtu.be/uYHOxlYzH0A | Trouble understanding this rop chain | assembly;buffer overflow | The ROP chain uses gadgets, which are short code snippets performing a basic function. The instruction what you see in the Python script in the video are the gadgets names, which were selected in the beginning.As an example, the XOREAX gadget was a code snippet at address 0x080512c0, which contains the following instructions:xor eax, eaxretSo, whet the XOREAX gadget is called, the eax register is cleared and a ret instruction is executed. Because the ret load an address from the stack and jumps to it, this instruction is used to call the next gadget.What you see in the Python script is the construction of the payload, which will be placed into the stack. The first address will be the overwritten return address and the next values will be the addresses of the gadgets. In some places in the payload you see SH and NULL. It is because the previous gadget load some value from the stack into a register, so the value should be placed into the stack also. The SH is an address points to the sh string, while the NULL is an address points to a 0 value in the memory.So, the whole ROP chain is only initializes the registers to execute a system call.XOREAX -> clears EAXPOPEBX, SH -> moves 'sh' string to EBXPOPECX, NULL -> moves a pointer to a NULL value to ECXPOPEDX, NULL -> moves a pointer to a NULL value to EDXADDEAX3, ADDEAX3, ADDEAX3, ADDEAX2 -> set EAX to 11SYSCALL -> perform syscall instruction |
_webmaster.100885 | Most of the time, comment sections seem to be a playgrounds for arguments, insults and vulgarity.Maybe I shouldn't put one on my website, but if I do, what factors determine if a comment section thrives?The comment section will obviously vary enormously depending on the content of your website, but I am afraid that since my website is targeting a non-technical large audience, there is too much room for the kind of comments we can see on 9gag or Youtube.(I will not be able to moderate or hire someone to do so). | What factors determine if a comment section thrives? | html;design;comments | If you won't be moderating it, then don't put one there. It WILL draw in the worst of the internet. Do what better sites do. Don't allow comments. Less than a third of all comments are beneficial and mostly in the smallest of ways. |
_unix.169819 | How can I compare and print data from different text files to one in Shell. I have captures NAS details of three different boxes using SSH, now I need to combine all the three text files to one file and MOUNT NAME should be in the first column and if the same MOUNT were present in he three boxes then it should print in same line and if the MOUNT is presented only in BOX_B and BOX_C then MOUNT name should present in first column and Column for Box_A should be kept blankLets take two examples df_BoxA.txt and df_BoxB.txt and df_BoxC.txtExample:$cat df_BoxA.txt /logs/boxA 2G 1.2G 7.7G 62% NAS:/logs/boxA/data/boxA 2G 1.8G 2.0G 91% NAS:/data/boxA /apps/boxA 2G 1.4G 5.7G 72% NAS:/apps/boxA /data/java 1G 67M 9.3G 7% NAS:/data/java/home/admin 10G 4.6G 54G 46% NAS:/home/admin/admin/arch 10G 8.3G 19G 83% NAS:/admin/arch/apps/dist 10G 8.3G 19G 83% NAS:/apps/dist$cat df_BoxB.txt /logs/boxA 2G 1.2G 7.7G 62% NAS:/logs/boxB/data/boxA 2G 1.8G 2.0G 91% NAS:/data/boxB /apps/boxA 2G 1.4G 5.7G 72% NAS:/apps/boxB /home/user 40G 29.3G 107G 74% NAS:/home/user1 /data/java 1G 67M 9.3G 7% NAS:/data/java/home/admin 10G 4.6G 54G 46% NAS:/home/admin/apps/dist 10G 8.3G 19G 83% NAS:/apps/dist$cat df_BoxC.txt /logs/boxA 2G 1.2G 7.7G 62% NAS:/logs/boxC/data/boxA 2G 1.8G 2.0G 91% NAS:/data/boxC /apps/boxA 2G 1.4G 5.7G 72% NAS:/apps/boxC /home/user1 40G 29.3G 107G 74% NAS:/home/user1 /home/admin 10G 4.6G 54G 46% NAS:/home/admin/admin/arch 10G 8.3G 19G 83% NAS:/admin/arch/apps/dist 10G 8.3G 19G 83% NAS:/apps/distAfter combining all the three files the result should be like$cat result.txt /logs/boxA 2G 1.2G 7.7G 62% NAS:/logs/boxA 2G 1.2G 7.7G 62% NAS:/logs/boxB 2G 1.2G 7.7G 62% NAS:/logs/boxC/data/boxA 2G 1.8G 2.0G 91% NAS:/data/boxA 2G 1.8G 2.0G 91% NAS:/data/boxB 2G 1.8G 2.0G 91% NAS:/data/boxC/apps/boxA 2G 1.4G 5.7G 72% NAS:/apps/boxA 2G 1.4G 5.7G 72% NAS:/apps/boxB 2G 1.4G 5.7G 72% NAS:/apps/boxC /data/java 1G 67M 9.3G 7% NAS:/data/java 1G 67M 9.3G 7% NAS:/data/java/home/admin 10G 4.6G 54G 46% NAS:/home/admin10G 4.6G 54G 46% NAS:/home/admin 10G 4.6G 54G 46% NAS:/home/admin/admin/arch 10G 8.3G 19G 83% NAS:/admin/arch 10G 8.3G 19G 83% NAS:/admin/arch/apps/dist 10G 8.3G 19G 83% NAS:/apps/dist 10G 8.3G 19G 83% NAS:/apps/dist 10G 8.3G 19G 83% NAS:/apps/dist/home/user 40G 29.3G 107G 74% NAS:/home/user1 /home/user1 40G 29.3G 107G 74% NAS:/home/user1I have tried of using pr command which is combining of the files which not the required result.Also tried of using sdiff but unable to get result.How can I solve this? | Compare and print data from different text files to one in Shell | shell;awk;sort;join | null |
_unix.237717 | On a Debian machine, I have the BSD games installed, but I wanted to know if it was possible for the monop game to be played with other users on the server. This type of inter-terminal play is a feature of a few other BSD games in the suite but not this one.Is it possible to make monop inter-terminal? Or is there perhaps another Monopoly program somewhere else that has been created that does this already? | Creating inter-terminal applications for Linux systems | linux;debian;terminal;bsd | null |
_softwareengineering.309971 | We have UI automation test framework based on selenium web driver. We are in the early stages of building out load tests and are wondering if it is possible or recommended to use a browser based UI Automation framework for load testing vs the more traditional approach of simulating client requests at the HTTP layer. We are hoping to avoid having two different frameworks for UI testing and Load testing if possible.I have found little information on the web regarding using automation UI tests for load testing. What I have found states that although it is possible using some tool sets, it's impractical to reliably scale out.Should we attempt to build out a load test suite using UI automation tests or should we use a more traditional tool set built specifically for load testing? | Is it feasible to scale UI automation tests for load testing a web application? | automation;load testing | In my own experience, UI testing is relatively slow and not easy to scale, which will make load testing not really reliable or representative.When creating good webrequests for a load test, it will be easier to generate a heavy load and scale that up or down as you desire. |
_cs.48301 | The question I'm faced with:Let $A[1], A[2], ...,A[n]$ be an array containing $n$ very large positive integers.Describe an efficient algorithm to find the minimum positive difference between any two integers in the array.What is the complexity of your algorithm? Explain.I would assume you apply a Merge Sort or Quick Sort $\Theta(n(log (n))$ and then scan through the array, subtracting the second element from the previous element, all the way to the end? Or $n-1$ comparisons?So the complexity would be $\Theta(n(log(n) + (n-1))$? | Algorithm to find min pos difference between two integers in an array | algorithms;asymptotics;sorting;searching | null |
_softwareengineering.226189 | I'd like to create an app similar to Barbell Pro for Android, for practice / interest / educational purposes really. Or even as another example for database purposes, Fitocracy The problem is, I have no idea how the database could be designed... For example:We have a 1000 Persons using the app Each Person could have 1-7 individualised WorkoutRoutines, depending on the day. (Perhaps even more -> AM workouts / PM workouts) Each WorkoutRoutine has an individual set of Exercises, with some crossover e.g. someone could do Bench Press on Monday and on Friday afterall.Each Exercise has a number of SetsEach Set has a number of RepsNow to me, this seems like it could potentially be a large amount of information to store for Each Person, and maybe pretty complicated to do so. I only have some experience with relational databases and I don't know how I'd go about designing that in an efficient matter for a relational database.I'm not asking for a design, just how I'd begin to go about it. The potential complexity is daunting for me due to lack of database experience. Maybe it's not even that complicated, but like I say, ignorance from myself. | Designing a fitness / weight lifiting routine database | design patterns;database design | Here is a prototype database schema. It allows the creation of different exercise routines, assigns those routines to a person by date, and even has a place to log the exercises executed, and the number of reps. |
_codereview.7587 | What do you think of http://websilon.org/? Are there things that can be improved? Is there something missing? See the source of the webpages for code.<!DOCTYPE HTML><html><head><title>Websilon - Mathematical Knowledge Base</title><meta http-equiv=Content-Type content=text/html; charset=UTF-8 /><meta http-equiv=X-UA-Compatible content=IE=EmulateIE7 /><meta name=robots content=index, follow /><meta name=keywords content=websilon, mathematics, math, knowlegde /><meta name=description content=Websilon - Mathematical knowledge base /><meta http-equiv=Content-Language content=en /><meta name=rating content=safe for kids /><meta name=copyright content=Websilon.org /><meta name=publisher content=Websilon.org /><meta name=author content=Websilon.org /><link rel=shortcut icon href=/favicon.ico> <link rel=apple-touch-icon href=/apple-touch-icon.png /><link rel=stylesheet href=/css/page/1.css /><meta name=viewport content=initial-scale=1.0; maximum-scale=1.0; user-scalable=yes; /><script src=/module/jquery/js/jquery-1.6.2.min.js /></script><script src=/module/jquery/js/jquery-ui-1.8.16.custom.min.js /></script><link rel=stylesheet href=/module/jquery/css/smoothness/jquery-ui-1.8.16.custom.css /><script type=text/x-mathjax-config>MathJax.Hub.Config({ extensions: [tex2jax.js], jax: [input/TeX,output/HTML-CSS], tex2jax: {inlineMath: [[$,$]]}});</script><script type=text/javascript src=/module/mathjax/MathJax.js></script><script type=text/javascript> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-28191597-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();</script></head><body> <style>.menu { margin: 0; padding: 0;}.menu .content { width: 98%; padding: 0; margin: 1%; margin-top: 0; margin-bottom: 0;}.menu .content button { margin-right: 10px;}.menu { display: none; width: 100%; height: 50px; line-height: 50px; background-color: #333333; color: #FFFFFF; font-size: 80%;}.menu ul { display: none; margin: 0; padding: 0; width: 200px; position: absolute; left: 0; top: 50px; border-top: 0; font-size: 90%; z-index: 99999; background-color: #252525;}.menu ul li a:active,.menu ul li a:hover,.menu ul li a:link,.menu ul li a:visited,.menu ul li { padding: 0px 20px; text-decoration: none; color: #AFAFAF;}.menu ul li { padding: 0;}.menu ul li:hover > a { color: #FFFFFF;}.menu ul li:hover { background-color: #0B5ED9;}.menu ul li a { display: block;}.menu > li a:active,.menu > li a:hover,.menu > li a:link,.menu > li a:visited,.menu > li { font-size: 120%; text-decoration: none; color: #FFFFFF;}.menu > li:hover { background-color: #666666;}.menu > li { position: relative; float: left;}.menu > li > a { display: block; padding: 15px; padding-top: 0; padding-bottom: 0; height: 50px; width: 100%;}.menu > li:hover > ul { display: block;}.menu li { list-style-type: none;}hr { width: 100%; border: 1px solid #CCCCCC; border-bottom: 0;}</style><script>function TopMenu(selector) { var mainClass = this; var environment = selector; $(selector).css('z-index', 999999); $(window).scroll(function(e) { if ($(window).scrollTop() > 0) { $(selector).css({ position: 'fixed', top: '0' }); } else { $(selector).css({ position: 'static' }); } }); $(selector).css('display', 'none'); $(selector).ready(function() { if (typeof(mainClass.onLoad) == 'function') { mainClass.onLoad($(this)); } $(selector).css('display', 'block'); }); /** * Get the height of the menu. * * @return Menu height (int, pixels) */ this.getHeight = function() { return parseInt($(selector).outerHeight()); }}</script><ul class=menu><li><a href=/>Home</a></li><li><a href=#>Me</a> <ul> <li><a href=http://websilon.org/users/1/kevin/>Dashboard</a></li> <li><a href=/user/edit/>Settings</a></li> <li><a href=/user/logout/>Log out</a></li> </ul></li><li><a href=#>Talk</a><ul> <li><a href=/talk/>Discussions</a></li> <li><a href=/talk/create/>New discussion</a></li></ul></li><li><a href=#>Knowledge</a> <ul> <li><a href=/kb/>Overview</a></li> <li><a href=/kb/create/>Create</a></li> </ul></li></ul><script>TopMenu('.menu');</script> <div id=content> <h1>Websilon.org</h1> <p> Websilon is an open knowledge platform. It's a dynamic study environment. Books are static; if there is new knowledge, it will take a while before you can read it in books. </p> <p> Now we are in developing stage. You can partly use it and share some knowledge. If you would like to join or give ideas, please visit the <a href=/talk/view/1>Development</a> discussion. </p> </div></body></html> | New web project | javascript;html;css | null |
_codereview.172945 | I've written some code in vba for the purpose of making twofold POST requests to get to the destination page and harvest name and address from there. There are two types of structures within which the desired results lie. One type of structure holds name and address in a single th storage and the other holds name in one td and address in another td. So, to handle this I had to use error handler to get the most out of it. By using xmlhttp I could not get any result so I used WinHttpRequest in my script to get the result by enabling redirection. My script is running errorlessly at this moment. However, any suggestion to improve my code specially by handling error more efficiently will be highly appreciated.Here is the full working code:Sub reverse_scraping() Dim http As New WinHttp.WinHttpRequest, html As New HTMLDocument Dim posts As Object, post As Object Dim ArgStr As String, ArgStr_ano As String, cNo As String, cName As String For Each cel In Range(A2:A & Cells(Rows.Count, 1).End(xlUp).Row) If cel.Value <> Then cNo = cel.Value cName = Replace(cel.Offset(0, 1).Value, , +) End If ArgStr = search=addr ArgStr_ano = TaxYear=2017&stnum= & cNo & &stname= & cName With http .Option(6) = True .Open POST, https://public.hcad.org/records/QuickSearch.asp, False .setRequestHeader Content-type, application/x-www-form-urlencoded .setRequestHeader User-Agent, Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36 .setRequestHeader Referer, https://public.hcad.org/records/quicksearch.asp .send ArgStr End With With http .Option(6) = True .Open POST, https://public.hcad.org/records/QuickRecord.asp, False .setRequestHeader Content-type, application/x-www-form-urlencoded .setRequestHeader User-Agent, Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36 .setRequestHeader Referer, https://public.hcad.org/records/quicksearch.asp .send ArgStr_ano html.body.innerHTML = .responseText End With On Error Resume Next Set posts = html.getElementsByClassName(data)(2).getElementsByTagName(th) Set post = html.getElementsByClassName(bgcolor_1)(0).getElementsByTagName(tr)(1).getElementsByTagName(td) If posts.Length Or post.Length Then cel.Offset(0, 2) = posts(0).innerText cel.Offset(0, 2) = post(1).innerText cel.Offset(0, 3) = post(2).innerText End If Next celEnd SubHere are the two links to show how to reach the destination page (in first link it is needed to click on the search by address button to get the search option):1 https://www.dropbox.com/s/e9on9zwqzmcboze/1Untitled.jpg?dl=02 https://www.dropbox.com/s/0lchpde8uq63jps/pics.jpg?dl=0search to be made using the below documents placing those in column A and B respectively and results will be placed in column c to the corresponding cells.Street No Street Name6330 LAUTREC DR5522 DARLING ST7411 SANDLE ST10234 LUCORE ST | Fetching data from a website using POST request | vba;web scraping | null |
_softwareengineering.344671 | I need to process a large number of data items, and I need to restrict the speed at which they are processed. For example, not more than 20 items per minute.I've thought about an algorithm for that, where I'd keep a list with the time when each past item was processed, then I can know how many more I can process at a given time.However, this is not very elegant since I need to manage this list. I'm wondering, is there any known algorithm that handles this problem?Edit:To answer the comments: processing should be as fast as possible. And it's 1-minute intervals no matter when they start. I will be sending data to a server, so the goal is not to overload that server. However, the faster the processing can be done the better. | Algorithm to limit the speed of processing items | algorithms;speed;stream processing | null |
_codereview.140254 | I developed a program that creates and displays a Newton fractal based on a complex polynomial.For example, the complex polynomial:$$z^{3}-1$$which is what is given as input in the code, will produce an image similar to this one:Basically what happens is that the program finds the function's derivative, uses it to perform Newton's method, and then gets the result from Newton's method to color in the pixels of a BufferedImage, each of which represents a point on the complex plane. Each color represents a solution (a.k.a. root or zero) of the polynomial that a point inside that color will converge to through Newton's method, and the different color shades represent how many iterations of Newton's method it takes for the resulting series of points to converge, with a darker shade indicating a greater number of iterations.This program works fine. The issue I'm having is that each time I change the polynomial function, I also have to manually insert the solutions of said polynomial into the zeros array, which (unsurprisingly?) has become somewhat tedious. But as far as I know, I have to do so in order for the program to know which solutions the points converge to.Is there any way to modify the code such that I don't have to re-enter the polynomial's solutions, such as calculating them beforehand?import java.awt.Color;import java.awt.Dimension;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.util.function.Function;import java.util.ArrayList;import java.util.List;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.SwingUtilities;public class FractalGenerator { private BufferedImage img; private int imageWidth = 500, imageHeight = imageWidth; private double xMin = -2, xMax = 2, yMin = -2, yMax = 2; private final ComplexNumber[] zeros; private Function<ComplexNumber, ComplexNumber> function, preDerivative, derivative; public FractalGenerator() { double h = 1E-8; function = z -> z.pow(3).subtract(1, 0); preDerivative = function.compose((ComplexNumber c) -> c.add(h, 0)); derivative = c -> preDerivative.apply(c).subtract(function.apply(c)).divide(h); zeros = new ComplexNumber[] {new ComplexNumber(1, 0), new ComplexNumber(-.5, Math.sqrt(3)/2), new ComplexNumber(-.5, -Math.sqrt(3)/2)}; createImage(); createAndShowGUI(); } private void createAndShowGUI() { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame(); JPanel panel = new JPanel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(img, 0, 0, this); } @Override public Dimension getPreferredSize() { return new Dimension(imageWidth, imageHeight); } }; frame.add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); }); } private void createImage() { double reductionFactor = .96; double graphWidth = xMax - xMin, graphHeight = yMax - yMin; img = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); Graphics g = img.getGraphics(); for (int y = 0; y < imageHeight; y++) { double graphY = yMax - y * graphHeight /(double) imageHeight; for (int x = 0; x < imageWidth; x++) { double graphX = xMin + x * graphWidth / (double) imageWidth; int[] arr = applyNewtonMethod(graphX, graphY); if (arr[0] == -1) g.setColor(Color.black); else { Color color = getColor(arr[0]); int red = color.getRed(), green = color.getGreen(), blue = color.getBlue(); for (int i = 0; i < arr[1]; i++) { red = (int) (red * reductionFactor); green = (int) (green * reductionFactor); blue = (int) (blue * reductionFactor); } g.setColor(new Color(red, green, blue)); } g.drawLine(x, y, x, y); } } } private int[] applyNewtonMethod(double x, double y) { ComplexNumber c = new ComplexNumber(x, y); double tolerance = 1E-6; int iterations = 1, max = 512; while (iterations < max) { c = c.subtract(function.apply(c).divide(derivative.apply(c))); for (int k = 0; k < zeros.length; k++) { ComplexNumber z = zeros[k], difference = c.subtract(z); if (Math.abs(difference.getReal()) < tolerance && Math.abs(difference.getImaginary()) < tolerance) return new int[] {k, iterations}; } iterations++; } return new int[] {-1}; } private Color getColor(int num) { switch (num) { case 0: return Color.red; case 1: return Color.green; case 2: return Color.blue; case 3: return Color.yellow; case 4: return Color.magenta; case 5: return Color.cyan; case 6: return Color.white; case 7: return new Color(139, 69, 19); case 8: return new Color(255, 165, 0); case 9: return new Color(255, 192, 203); default: return Color.black; } } public static void main(String[] args) { new FractalGenerator(); }}Here's ComplexNumber.java for convenience:public class ComplexNumber { double real, imaginary; public ComplexNumber(double real, double imaginary) { this.real = real; this.imaginary = imaginary; } public ComplexNumber add(double real, double imaginary) { return new ComplexNumber(this.real + real, this.imaginary + imaginary); } public ComplexNumber add(ComplexNumber c) { return new ComplexNumber(this.real + c.real, this.imaginary + c.imaginary); } public ComplexNumber subtract(double real, double imaginary) { return new ComplexNumber(this.real - real, this.imaginary - imaginary); } public ComplexNumber subtract(ComplexNumber c) { return new ComplexNumber(this.real - c.real, this.imaginary - c.imaginary); } public ComplexNumber multiply(double scalar) { return new ComplexNumber(real * scalar, imaginary * scalar); } public ComplexNumber multiply(ComplexNumber c) { return new ComplexNumber(real * c.real - imaginary * c.imaginary, real * c.imaginary + imaginary * c.real); } public ComplexNumber divide(double scalar) { return multiply(1.0 / scalar); } public ComplexNumber divide(ComplexNumber c) { return multiply(c.getConjugate()).multiply(1.0 / (c.real * c.real + c.imaginary * c.imaginary)); } public ComplexNumber getConjugate() { return new ComplexNumber(real, imaginary * -1); } public ComplexNumber pow(int exp) { ComplexNumber c = new ComplexNumber(real, imaginary); for (int k = 1; k < exp; k++) { c = multiply(c); } return c; } public ComplexNumber exp() { return new ComplexNumber(Math.exp(real) * Math.cos(imaginary), Math.exp(real) * Math.sin(imaginary)); } public static ComplexNumber exp(ComplexNumber c) { return c.exp(); } public ComplexNumber cos() { return exp(multiply(new ComplexNumber(0, 1))).add(exp(multiply(new ComplexNumber(0, -1)))).divide(2); } public static ComplexNumber cos(ComplexNumber c) { return c.cos(); } public ComplexNumber sin() { return exp(multiply(new ComplexNumber(0, 1))).subtract(exp(multiply(new ComplexNumber(0, -1)))).divide(new ComplexNumber(0, 2)); } public static ComplexNumber sin(ComplexNumber c) { return c.sin(); } public ComplexNumber tan() { return sin().divide(cos()); } public static ComplexNumber tan(ComplexNumber c) { return c.sin().divide(c.cos()); } public double getReal() { return real; } public double getImaginary() { return imaginary; } @Override public String toString() { return + real + (imaginary >= 0 ? + : ) + imaginary + i; }} | Creating a Newton fractal based on a polynomial | java;algorithm;graphics;fractals | for (int i = 0; i < arr[1]; i++) { red = (int) (red * reductionFactor); green = (int) (green * reductionFactor); blue = (int) (blue * reductionFactor); }That loop could be avoided with double pixelReductionFactor = Math.pow(reductionFactor, arr[1]); red = (int) (red * pixelReductionFactor); green = (int) (green * pixelReductionFactor); blue = (int) (blue * pixelReductionFactor);Although perhaps it would be nicer still to interpolate in a more uniform colour space than RGB. In my Newton fractal code (golfed, I'm afraid), I use Color.HSBtoRGB. while (iterations < max) { c = c.subtract(function.apply(c).divide(derivative.apply(c))); for (int k = 0; k < zeros.length; k++) { ComplexNumber z = zeros[k], difference = c.subtract(z); if (Math.abs(difference.getReal()) < tolerance && Math.abs(difference.getImaginary()) < tolerance) return new int[] {k, iterations}; } iterations++; }If you want to avoid hard-coding the zeroes, the easy approach is to check for convergence to itself. With a tiny bit of optimisation this becomes while (iterations < max) { ComplexNumber difference = function.apply(c).divide(derivative.apply(c)); if (Math.abs(difference.getReal()) < tolerance && Math.abs(difference.getImaginary()) < tolerance) // TODO Find k return new int[] {k, iterations}; } iterations++; c = c.subtract(difference); }Since this approach starts without a list of zeroes, it must build it up as it goes. The TODO would search a list for a zero within 2 * tolerance, and if there is none it would add c (or perhaps better c.add(difference.divide(2))) to the list. |
_unix.116770 | I have a directory which contains image files with names like image1.jpg image2.jpg image3.jpg...Unfortunately, the image names must be zero based, so image1.jpg should be image0.jpg, image2.jpg should be image1.jpg and so on. I can write a script to generate mv commands like these, put them in a shell script, and then execute them - mv image1.jpg image0.jpgmv image2.jpg image1.jpgmv image3.jpg image2.jpg...But I suppose there is a neater way to do it in Unix. So what is it? | Subtract 1 from all file names (rename them) in a directory. | command line;rename | The good old perl rename:rename 's/(\d+)(\.jpg)/($1-1).$2/e' *[Remarks]Image numbers should be greater than 0.In case images are greater than 9 and have not leading 0s,use $(ls -v1 *) to avoid clobbering. Proposed by @arielf and noticed by @Graeme.When in doubt use also -v for verbose and -n for no-action. |
_computergraphics.5236 | tl;dr Is there a name for a type of (non-physical) projection that causes objects to become larger the farther they are from a camera?With a fisheye projection, an object twice as far from the camera is less than half the size on screen. (I think; my understanding of fisheye math is fuzzy. I gather there are various projections/mapping functions.) There is massive foreshortening, objects shrink very quickly as they move away.With a rectilinear projection, an object twice as far from the camera is always half the size on screen, regardless of FoV. This is how trigonometry works. Infinitely-far objects have zero size.With an orthographic projection, an object twice as far from the camera is always the same size on screen. There is no foreshortening. Infinitely-far objects have the same size.Now, go one step farther. I want negative foreshortening. I want to see an object get bigger the farther away it gets. Infinitely-far objects have infinite size. | 3D projection that increases objects' size as they become more distant | rendering;3d;projections | After a quick google of 'Inverted perspective' I found out that you have five different names for it; Reverse perspective, inverse perspective, inverted perspective, divergent perspective and Byzantine perspective. https://en.wikipedia.org/wiki/Reverse_perspectiveI think that if you want to use it in a render engine using a projection matrix, in the perspective divide, you use multiply by w instead of divide. This is because in a perspective projection, the divide by w is what actually gives the perspective. In a orthographic projection w is always 1, meaning that there is no actual perspective.For a ray tracer you probably just need to scale the image plane up of course, but probably instead of having the origin of the ray to be the center of the camera, you have some kind of second image plane that is larger than the actual image plane. If both are the same size, the rays are straight and you have an orthographic projection, if the actual image plane is smaller then you have your Reverse perspective.Quick extra note: If you have proper lenses, you might be able to get this effect in real life. Yes, you would need to have a lens that is a few meters in diameter, but I do not think it is impossible! :PI hope this will help you and that I have not made any mistakes. Good luck with whatever you are doing! |
_codereview.169318 | I've spent a couple of weeks implementing a simple text editor. The entire program uses only immutable objects and a functional, fluid programming style.After reading about ways to implement Fluent Interfaces in Java I came to the conclusion there was no elegant solution. The language just can't handle it in a nice way. One of the main issues is trying to return the immutable object from bases class with() methods. If you just return 'this' then you get back the base class, not the concrete class that you need from calling code.This is the system I am using in my code now. Let me know if there are ways of doing it in a less hackish, ugly way.My main requirements are:Use inheritance so common functionality doesn't need to get cut and paste into subclassesAllow calling code to chain methods in a fluent style: object.withColor(red).withHeight(50) etc..Avoid 3rd party libraries or source code buildersCode:public abstract class Animal<TConcrete extends Animal<TConcrete>> { public final int height; protected Animal(int height) { this.height = height; } // Need to return 'this' sometimes in base methods but if you just use // keyword 'this' then the type is wrong (i.e. different than TConcrete). protected abstract TConcrete self(); // Base classes normally can't instantiate the concrete class because it // might have extra constructors and members that the base cannot possibly // know // about. // // With this method you are able to construct a new object that has a copy // of all the subclass members but with a new base class member value. protected abstract TConcrete copy(int height); public TConcrete withHeight(int height) { return copy(height); }}public abstract class Mammal<TConcrete extends Mammal<TConcrete>> extends Animal<TConcrete> { // This is the only mandatory field for this whole hierarchy. Naming is just // to illustrate in this example. public final int furColorMandatory; // The constructor now takes 2 parameters, unlike Animal class which takes // just 1. It takes all the parameters of base classes plus the new member // 'furColor'. protected Mammal(int height, int furColorMandatory) { super(height); this.furColorMandatory = furColorMandatory; } // Now implement a new copy() method for the subclass to implement. The old // copy() from base class gets implemented below. // // This forms a chain where the base class is able to instantiate a copy // of the object by calling the copy method. protected abstract TConcrete copy(int height, int furColor); // Each class in the hierarchy needs to implement the copy() // method of the abstract class below. This allows the base // class to instantiate a concrete object. // // Note the current value for 'furColor' is used because this is a copy // operation as opposed to totally new construction of an object. @Override protected final TConcrete copy(int height) { return copy(height, furColorMandatory); } public TConcrete withFurColor(int furColorMandatory) { return copy(height, furColorMandatory); }}public final class Cat extends Mammal<Cat> { public final int numberOfWhiskers; protected Cat(int height, int furColorMandatory, int numberOfWhiskers) { super(height, furColorMandatory); this.numberOfWhiskers = numberOfWhiskers; } // Finally implement the concrete 'this' method used only by base classes. @Override protected Cat self() { return this; } protected Cat copy(int height, int furColorMandatory, int numberOfWhiskers) { return new Cat(height, furColorMandatory, numberOfWhiskers); } // This should be final but the class is final so keyword is not needed. @Override protected Cat copy(int height, int furColorMandatory) { return copy(height, furColorMandatory, numberOfWhiskers); } public Cat withNumberOfWhiskers(int numberOfWhiskers) { return copy(height, furColorMandatory, numberOfWhiskers); } // Only way to instantiate this for callers. Ensures mandatory is taken care of. public static Cat of(int furColorMandatory) { return new Cat(0, furColorMandatory, 0); }}Usage:Cat tom = Cat.of(5).withHeight(10); | Instantiating an animal using fluent classes with inheritance | java;fluent interface | null |
_webapps.15314 | I believe the answer is no, but I think that just having the question out there may let the community work together to figure out what we can do to get what we are looking for done. My organization started using Google Apps for our internal email system and documents over a year ago now. As anyone who has ever used this system knows, at that time you couldn't use the same login to use software like Adwords or Analytics; you needed a personal login. Google was perfectly happy to let you use the same e-mail address that you used for your Apps account as a login. Now they are telling me that is no longer the case, that we can use the Apps account to login to 'regular' Google. They describe it here: conflicting account overview. However, their only solution is to rename your existing personal Google account. There is no way to just say merge these accounts. I mean even all my Stack Exchange accounts are linked through my personal account with the same name as my Apps account. I don't want to start messing with my personal account, renaming it (which I assume I cant undo once they take over that login with my apps account) with the potential of messing up all sorts of things I didn't predict would get messed up like for example having to login to my personal Gmail (different name than my Apps account username from my organization) to get into Stack Exchange and a whole host of other sites. Does anyone have any experience with merging, or just with this whole process in general? I just want my Gmail and Apps accounts with the same username to become one happy login! | Merging Conflicting Google Accounts | gmail;google;google apps | It's not possible. I ran into the same problem, and spent many hours trying to merge things, and all I did was run into various Google bugs (for example, I can't use Google Groups at all anymore since it won't change my e-mail address). You're going to have to keep track of the two separate accounts, and you probably won't be able to associate your desired e-mail address with one of them.A little bit of good news, some services can be migrated from one Google account to another (and Analytics and Adwords are among them): http://www.google.com/support/accounts/bin/answer.py?answer=58582 |
_unix.119947 | I have a file of the following form (with '-' serving as delimiters), and I want to find the appearance of a number only when it follows a delimiter. I suppose it's a concatenation of grep '-\n' and $number, but I can't find the way to do it right. thanks..14002132342-7656711234-872140054- | grep change of line followed by a variable | grep | null |
_codereview.45864 | I used a standard calculator design from Java. I wanted to expand it so I created a class to create buttons for different operations, like +, -, *, /. The original program didn't do this, they just made them individually without a template method. Do you think I should do it like this?//The java Template Calculator TODOimport java.awt.EventQueue;import java.awt.GridLayout;import java.awt.BorderLayout;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.JButton;import java.awt.Container;public class JavaCalculator implements ActionListener{JFrame guiFrame;JPanel buttonPanel;JTextField numberCalc;int calcOperation = 0;int currentCalc;public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { new JavaCalculator(); } });}public JavaCalculator(){ guiFrame = new JFrame(); guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); guiFrame.setTitle(Simple Calculator); guiFrame.setSize(300,300); guiFrame.setLocationRelativeTo(null); numberCalc = new JTextField(); numberCalc.setHorizontalAlignment(JTextField.RIGHT); numberCalc.setEditable(false); guiFrame.add(numberCalc, BorderLayout.NORTH); buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(4,4)); guiFrame.add(buttonPanel, BorderLayout.CENTER); for (int i=0;i<10;i++) { addNumberButton(buttonPanel, String.valueOf(i)); } addActionButton(buttonPanel, 1, +); addActionButton(buttonPanel, 2, -); addActionButton(buttonPanel, 3, *); addActionButton(buttonPanel, 4, /); addActionButton(buttonPanel, 5, ^2); JButton equalsButton = new JButton(=); equalsButton.setActionCommand(=); equalsButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if (!numberCalc.getText().isEmpty()) { int number = Integer.parseInt(numberCalc.getText()); if (calcOperation == 1) { int calculate = currentCalc + number; numberCalc.setText(Integer.toString(calculate)); } else if (calcOperation == 2) { int calculate = currentCalc - number; numberCalc.setText(Integer.toString(calculate)); } else if (calcOperation == 3) { int calculate = currentCalc * number; numberCalc.setText(Integer.toString(calculate)); } else if (calcOperation == 4) { int calculate = currentCalc / number; numberCalc.setText(Integer.toString(calculate)); } else if (calcOperation == 5) { int calculate = currentCalc * currentCalc; numberCalc.setText(Integer.toString(calculate)); } } } }); buttonPanel.add(equalsButton); guiFrame.setVisible(true); }private void addNumberButton(Container parent, String name){ JButton but = new JButton(name); but.setActionCommand(name); but.addActionListener(this); parent.add(but);}private void addActionButton(Container parent, int action, String text){ JButton but = new JButton(text); but.setActionCommand(text); OperatorAction addAction = new OperatorAction(1); but.addActionListener(addAction); parent.add(but);}public void actionPerformed(ActionEvent event){ String action = event.getActionCommand(); numberCalc.setText(action); }private class OperatorAction implements ActionListener{ private int operator; public OperatorAction(int operation) { operator = operation; } public void actionPerformed(ActionEvent event) { currentCalc = Integer.parseInt(numberCalc.getText()); calcOperation = operator; }}} | Basic Calculator in Java with Swing | java;swing;calculator | null |
_cstheory.29244 | Is there a simple example of a Turing machine $M$, such that whether $M$ halts or not on the empty input cannot be proved within the current mathematical system?Specifically, I'm curious whether there exists an example simple enough that the state transition of the Turing machine can be drawn as a reasonably-sized diagram. | Simple example of halting-unprovable Turing machine | turing machines | null |
_webmaster.18050 | I currently run a small web-app that connects local businesses with new customers in a very specific niche. In the past few months this model has worked very well and the growth is excellent, so much so in fact that I'm preparing to expand the app to support multiple sites/niches. Ultimately it will be structured very similarly to StackExchange in that each site will have it's own domain, design and focus, but running off of the same platform.With that said, I've been trying to think of the best way to handle the analytics (specifically Google Analytics) for this setup.My two requirements are basically that I want to be able to see aggregate statistics for all sites so that I can get an overview of how the system is performing generally on a day-to-day basis, but also be able to narrow down to specific site and track at that level for SEO, marketing, and debugging purposes.What I'm hoping is that other people who may have done this or have more experience with Google Analytics may be able to tell me whether I would be better off creating one multi-domain analytics profile (and figuring out how to break it out by site) or creating a profile for each site and having the unique profile id configured with the sites in my system.From a development standpoint I would much rather do the former.Thank you in advance for your time and insights! | One multi-domain analytics profile, or one analytics profiles per domain? | google analytics;analytics | Neither method is perfect; both have their pros and cons.It is definitely simpler to have one distinct Google Analytics key for every domain or subdomain. There is no question about this. However, that breaks down when you have, say, dozens or hundreds of domains.If you have many SUBdomains using the same Google Analytics key, you must push the domain name on each request, like so.var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-5620270-24']); _gaq.push(['_setDomainName', '.stackexchange.com']); _gaq.push(['_trackPageview']);Then you can segment fairly easily based on Hostname... just use the Advanced Segments dropdown in the top right and create a segment for hostname=gaming.stackexchange.com or something similar. You can even make aggregate segments hostname=gaming.stackexchange.com OR hostname=webapps.stackexchange.com OR hostname=cooking.stackexchange.com etc.If you have many different domains, it's much harder.Call the _link() method in any links between the domains. If your current links have the form: <a href=https://www.secondsite.com/?login=parameters>Login Now</a>change them to: <a href=https://www.secondsite.com/?login=parameters onclick=_gaq.push(['_link', 'http://www.firstsite.com']); return false;>Login Now</a>For different domains, we simply use different Google Analytics keys.. |
_softwareengineering.143836 | I recently found out about strong typing in VB.Net (naturally it was on here, thanks!) and am deciding I should take another step toward being a better programmer. I went from vba macros -> VB.Net, because I needed a program that I could automate and I never read anything about strong typing, so I kind of fell into the VB.Net default trap. Now I am looking to turn it on and sort out this whole type thing.I was hoping someone could direct me towards some resources to make this transistion as painless as possible. I have read around some and ctype seems to come up a lot, but past that I am at a bit of a loss. What are the benefits of switching? Is there more to it than just using ctype to cast things? I feel like there is a good article that I have failed to come across and any direction would be great.Would a good approach to be to rewrite a program that is written with option strict off and note differences? | I want to turn VB.Net Option Strict On | vb.net | null |
_unix.251674 | Im trying to match a string agains a regular expression inside an if statement on bash. Code below:var='big'If [[ $var =~ ^b\S+[a-z]$ ]]; then echo $varelse echo 'none'fiMatch should be a string that starts with 'b' followed by one or more non-whitespace character and ending on a letter a-z. I can match the start and end of the string but the \S is not working to match the non-whitespace characters. Thanks in advance for the help. | Any non-whitespace regular expression | bash;regular expression | In non-GNU systems what follows explain why \S fail:The \S is part of a PCRE (Perl Compatible Regular Expressions). It is not part of the BRE (Basic Regular Expressions) or the ERE (Extended Regular Expressions) used in shells.The bash operator =~ inside double bracket test [[ use ERE.The only characters with special meaning in ERE (as opposed to any normal character) are .[\()*+?{|^$. There are no S as special. You need to construct the regex from more basic elements:regex='^b[^[:space:]]+[a-z]$'Where the bracket expression [^[:space:]] is the equivalent to the \S PCRE expressions : The default \s characters are now HT (9), LF (10), VT (11), FF (12), CR (13), and space (32).The test would be:var='big' regex='^b[^[:space:]]+[a-z]$'[[ $var =~ $regex ]] && echo $var || echo 'none'However, the code above will match bi for example. As the range [a-z] will include other characters than abcdefghijklmnopqrstuvwxyz if the selected locale is (UNICODE).To avoid such issue, use:var='bi' regex='^b[^[:space:]]+[a-z]$'( LC_ALL=C; [[ $var =~ $regex ]]; echo $var || echo 'none')Please be aware that the code will match characters only in the list: abcdefghijklmnopqrstuvwxyz in the last character position, but still will match many other in the middle: e.g. bg.Still, this use of LC_ALL=C will affect the other regex range: [[:space:]] will match spaces only of the C locale. To solve all the issues, we need to keep each regex separate:reg1=[[:space:]] reg2='^b.*[a-z]$' out=noneif [[ $var =~ $reg1 ]] ; then out=noneelif ( LC_ALL=C; [[ $var =~ $reg2 ]] ); then out=$varfiprintf '%6.8s\t|' $outWhich reads as: If the input (var) has no spaces (in the present locale) thencheck that it start with a b and ends in a-z (in the C locale).Note that both tests are done on the positive ranges (as opposed to a not-range). The reason is that negating a couple of characters opens up a lot more possible matches. The UNICODE v8 has 120,737 characters already assigned. If a range negates 17 characters, then it is accepting 120720 other possible characters, which may include many non-printable control characters.It should be a good idea to limit the character range that the middle characters could have (yes, those will not be spaces, but may be anything else). |
_unix.170990 | The following command will delete directories and sub directories that are older then 100 days:find /var/tmp -type d -ctime +100 -exec rm -rf {} \;But actually I want to perform the test to verify if the command will remove all directories.So I set -ctime +0 (in order to perform remove directories that old then 0 days)find /var/tmp -type d -ctime +0 -exec rm -rf {} \;But the find command did not remove the directories.How can I change the -ctime in order to perform the test? | Find command with -ctime +0 for testing | find | null |
_cogsci.1776 | What's the original source of the SEEV (Salience Effort Expectancy Value) Model for predicting the distribution of visual attention? I've seen it mentioned in many papers and presentations but everyone of them lacks a reference to the source of this model.Does anyone have a valid reference? | Origin of the SEEV Model of visual attention distribution | reference request;cognitive modeling;vision;attention | Wickens et al. (2003) is the earliest I'm aware of:Wickens, C. D., Goh, J., Helleberg, J., Horrey, W. J., & Talleur, D. A. (2003). Attentional models of multitask pilot performance using advanced display technology. Human Factors: The Journal of the Human Factors and Ergonomics Society, 45(3), 360-380.Actually, in that paper he cites Wickens et al. (2001), but I can't seem to finda copy of this manuscript anywhere, and it has fewer citations:Wickens, C. D., Helleberg, J., Goh, J., Xu, X., & Horrey, W. J. (2001). Pilot task management: Testing an attentional expected value model of visual scanning. Savoy, University of Illinois Institute of Aviation.If you're using N-SEEV, cite one of these instead:Steelman-Allen, K. S., McCarley, J. S., Wickens, C., Sebok, A., & Bzostek, J. (2009, October). N-SEEV: A computational model of attention and noticing. In Proceedings of the Human Factors and Ergonomics Society Annual Meeting (Vol. 53, No. 12, pp. 774-778). SAGE Publications.Wickens, C., McCarley, J., & Steelman-Allen, K. (2009, October). NT-SEEV: A model of attention capture and noticing on the flight deck. In Proceedings of the Human Factors and Ergonomics Society Annual Meeting (Vol. 53, No. 12, pp. 769-773). SAGE Publications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.