id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_unix.138422
I have a problem reaching my raspberry pi from outside of my LAN and I don't remember having changed anything. It was working previously, but I don't know what changed.I've installed owncloud with nginx and mysql over HTTPS. If I try to access the server using it's local IP address everything works fine. Using the official URL with no-ip.biz spins for a while but ends in a blank page without any error. Do you have any ideas how to solve the issue?I recently updated the system but can't remember what might have changed since then.
Raspberry pi running owncloud not reachable using no-ip URL
debian;raspberry pi;nginx
Could it be that your no-ip client isn't running? The installation instructions says Read the README file in the no-ip-2.1.9 folder for instructions on how to make the client run at startup.If your Raspberry have been rebooted and doesn't start automatically, you would be able to access ownCloud on your local network address, but not through the no-ip.com address.Another possibility: When you sign up for a free account at no-ip.com, the term says that you have to reactivate your account every 30 days. This wouldn't be a unix issue, but could be the answer to your question?
_unix.2203
Is it possible to randomise or shred memory of a particular application just after its life ends, or better, whenever it deallocates some memory?A command-line utility like this would be perfect:shred-memory [options] [{params to the application...}]
Randomise or shred memory of an application
linux;bash;security;password;memory
null
_webmaster.45316
My sitemap is huge (200k+ articles), so I want to implement pagination of the sitemap itself.My question is what parameter do most search engines look for in a sitemap pagination? page=... or maybe p=...?I know about the sitemap index, but it would be a bit of an overhead to create that just now.
Paginating sitemaps
seo;sitemap
You can use various sitemaps to divide yours.In this article, it mentions:If you do provide multiple Sitemaps, you should then list each Sitemap file in a Sitemap index file. Sitemap index files may not list more than 50,000 Sitemaps and must be no larger than 10MB (10,485,760 bytes) and can be compressed. You can have more than one Sitemap index file. The XML format of a Sitemap index file is very similar to the XML format of a Sitemap file.You can also submit various sitemaps to Google.
_unix.346084
I think at some point I messed up my .bash_profiles and I have multiple now. I am trying to customize my shell but I am not sure which .bash_profile to use, if any. I thought .bashrc file was more often used? I am running OSX - El Capitanls -la | moretotal 480-rw------- 1 Matthew staff 6404 Feb 16 23:57 .bash_history-rw-r--r-- 1 Matthew staff 719 Jan 19 20:18 .bash_profile-rw-r--r-- 1 Matthew staff 335 Oct 7 12:35 .bash_profile.macports-saved_2017-01-19_at_20:18:05-rw-r--r-- 1 Matthew staff 167 Jul 16 2015 .bash_profile.pysavedrwxr-xr-x 208 Matthew staff 7072 Feb 18 19:41 .bash_sessions
I have multiple copies of .bash_profile, which one is actually being used? (if any)
shell;bashrc
null
_softwareengineering.314120
Question:Are there any techniques for communicating with methods of other components but still keep a pure Observer pattern ?If yes are they indicated/regularly-used or am I just overcomplicating stuff?A practical exampleSuppose I have an architecture with the following characteristics:System is a Word Processor appMany components, each with it's own purpose, e.g KeypressDetector, Printer, DocumentRenderer.Components modify/observe a single model, the DocumentThe components thus communicate via this model observation/modification. The components don't know about each other in any other way.If I'm not mistaken this is what the Observer Pattern is all about.So here's one case where there's a problem:For component Printer to do it's job it needs some output from component PagePreparator.This is just one edge-case where component PagePreparator can't continuously update the model that is shared between the components because it involves heavy-computation. This involves just a single aspect of PagePreparator, e.g PagePreparator.prepare() // takes a long time to run.So that's one case where It looks to me that I need to break away from this pure Observer setup and just expose the method of PagePreparator to Printer directly and call it explicitly from Printer. This will couple them explicitly together though.Are there any techniques for keeping this Observer pattern exclusively and still be able to perform this kind of invocations?Possible solutions:When Printer needs output it sets a flag on the model Document, e.g updatePages which is picked up by PagePreparator's observers. PagePreparator then sets the output on the model Document which is picked up by Printer's observer which proceeds to do it's job.Simply breaking the pattern and just expose PagePreparator's method, pagePreparator.prepare() to Printer which can then explicitly call it.Dispatching an event from Printer which is picked up by PagePreparator which proceeds to set the value on the model Document, for Printer to pick it up.
Invoking Methods of another component in Observer Pattern
design patterns
The third option seems cleanest to me. I frequently find myself making use of the Event Aggregator Pattern with applications containing isolated/disconnected modules communicating with each other via messages (Another good page Here). The pattern itself has become common at least in .NET with a lot of examples of 'generic' Event Aggregators around which should be able to translate into most languages.The benefit of using messages to communicate between modules is that those modules remain decoupled; the cost however, is adding a layer of indirection.
_unix.364036
I'm behind a very slow Internet connection most of the time. OpenSuSE TumbleWeed occasionally likes to go suck down all my bandwidth at really inopportune times to check for updates. I've got it set at the max time, which is a month. I've previously pursued trying to turn off the updater completely, but that has been a losing battle.There's also an option to have it not try to update when on a mobile connection. My super slow primary Internet seems like a good use of that... How can I tag my ethernet as mobile to keep the system from trying to update that way? That would allow the updates to still try and run when I'm on the road and someplace with fast wifi.
Setting ethernet as mobile?
opensuse;network interface
null
_cs.6443
This is a beginners question. I and reading the book Introduction to Computer Theory by Daniel Cohen. But I end up with confusion regarding simplification of regular expressions and finite automata. I want to create an FA for the regular expression$\qquad \displaystyle (a+b)^* (ab+ba)^+a^+\;.$My first question is that how we can simplify this expression? Can we we write the middle part as $(ab+ba)(ab+ba)^*$? will this simplify the expression?My second question is whether the automaton given below is equivalent to this regular expression? If not, what is the mistake?This is not a homework but i want to learn this basic example. And please bear me as a beginner.
Simplification of regular expression and conversion into finite automata
formal languages;automata;finite automata;regular expressions
At the point of writing, your NFA is still a bit off. One version of a correct answer looks like this:So this NFA is design in an ad hoc manner, but there's still some basic organisation to it. You can see that there's three basic bits, the $a,b$ loop on the start state, a forced $ab|ba$, followed by two 2-step loops, then a forced $a$ to the final state, with an $a$ loop. The first loop takes care of the $(a+b)^{\ast}$, the next little clump does the $(ab+ba)^{+}$, then the tail end does the $a^{+}$.The key thing to practice when doing things this way is breaking the RE down into a sequence of smaller REs, that you then stick together. This is essentially a 'casual' version of the systematic method.The systematic way is simple, but a bit fiddly. It's a relatively long explanation as to how to do it systematically, and as you haven't reached that bit in your reading yet, I'll refrain from working through the details here, however just as a quick reference, this explanation is pretty thorough and reasonably well explained.
_softwareengineering.231013
For decimal numbers, obviously I want to localise everything. Whatever programming language I'm working in, there will tend to be tools for this, so it's also easy to do.In my application, I happen to be formatting numbers as hexadecimal quite often. This leads me to wonder:Are there locales which group hexadecimal numbers into different groupings to me?Are there locales which use a separator other than space for the groupings?Are A-F used as the extra six digits even in locales which don't use a Latin script?I guess in general - do I have to internationalise this, or does everyone in the world look at the same hexadecimal value and intrinsically understand it the same way?
Do I have to internationalise the display of hexadecimal values?
internationalization
null
_unix.55338
I've loaded from the USB stick with Debian Live CD on it to fix the MBR after a Windows installation. Suddenly I've found that fdisk -l shows nothing but the live USB itself. What would it mean? I've used this image: http://cdimage.debian.org/debian-cd/current-live/i386/iso-hybrid/debian-live-6.0.5-i386-xfce-desktop.iso
Debian doesn't detect disks from Live CD
debian;live usb;livecd
null
_codereview.164719
This is just a little palindromic game that searches all palindromic numbers in ur random generated list. Feel free to give me some advice.import randomnumbers = []total = []dice = random.randint(1000, 50000)while len(numbers) < dice: x = random.randint(100000, 1000000) numbers.append(x)def palindrome(n): check_palin = [] for i in n[::-1]: i = str(i) check_palin.append(i) for k in check_palin: k = k[::-1] check_palin.clear() if k == i: total.append(k) print(total) numbers.clear()palindrome(numbers)length = len(total)if length > 58: print(\nHolly Shit!!! You broke my record!!! with %d. % (length))elif length == 58: print(\nWow, Nice!!! %d is my highest Palindromic number (too).\nThat's a draw % (length))
Palindromic game in Python
python;beginner;random;palindrome
null
_reverseengineering.10847
I am thinking on a decompilation method which uses the runtime behavior of the binary executable to extract usable compilation data. Analysing the runtime behavior (i.e. trapping after every cpu instruction and check what it does), we could get a lot of additional infos, like:we could differentiate between the static constant data (.text) and the binary asmadditional information, what type of data is in which register or global / local variable (pointers, floats and integers)where the cpu instructions are startingfrom the stack behavior we could get highly useful heuristics, where are the functions / internal functions and how long / what type of parameters they have.On my opinion, maybe even the holy grail, the recompilable source code wouldn't be so far away.Is it possible? Does any tool / software already exist which is capable to do this?
Decompile binary executable into c / asm code by emulation, is it possible?
disassembly;decompilation;tracing
This problem is linked to the halting problem on a Turing machine (which is known to be undecidable). Approaching decompilation through emulation suppose that you have to run through all the branches of the software at least once, and reaching all possible program points cannot be guaranteed if you have to go through a (potentially) infinite loop.Yet, this is a theoretical problem that you unlikely find in real life (except if it has been planted here intentionally to prevent the full exploration through emulation).But, in a more practical perspective, exploring all paths can be done only if you can easily run through all the path at runtime, which is not the case when the user is required to solve a challenge (possibly on-line) such as giving a password whose hash is stored in the program or prove that he posses a private key by signing a message and returning it to the software.
_cogsci.9803
For those unfamiliar, interoceptive awareness/accuracy involves awareness of, and sensitivity to, internal physiological sensations (My heart is beating fast). Interoceptive information is fundamental to how we conceptualize our affective experiences. For instance, people with high interoceptive sensitivity may be more likely to emphasize information about high/low arousal in their emotional self-reports (Barrett, Quigley, Bliss-Moreau, & Aronson, 2004). Sensitivity and awareness of interoceptive information is fundamental to many other forms of cognition as well.My question is whether we can improve people's interceptive awareness/accuracy with some sort of intervention (e.g., biofeedback) and whether this improvement might predict other adaptive outcomes.
Is it possible to improve interoceptive awareness/accuracy? If so, how?
emotion;interoception;biofeedback
Interoceptive awareness and accuracyInteroceptive awareness and accuracy are sometimes used interchangeably, but can also refer to two different things: awareness to the tendency to attend to interoception measured by self-report, and accuracy to the actual accuracy with which one does so (Chentsova-Dutton and Dzokoto, 2014). For example, a cross-cultural study involving West African and European-American found that West Africans showed higher levels of interoceptive awareness, but lower levels of interoceptive accuracy than European Americans (Ceunen, Van Diest and Vlaeyen, 2013).Heartbeat perception trainingThere have been some recent attempts to produce improvements in interoceptive awareness and accuracy. Schaefer, Egloff, Gerlach and Witthft (2014) gave 29 patients with somatoform disorders heartbeat perception training, and reported that the training selectively improved interoceptive accuracy in patients with low health anxiety, as well as improvements in symptoms.MindfulnessSilverstein, Brown, Roth and Britton (2011) also found that mindfulness training produced a statistically significant benefit in speed of interoceptive awareness, and that this improvement was associated with improvements in attentional, self-judgmental, and clinical factors of female sexual dysfunction. They reported the following about increased interoceptive awareness:Women who participated in the meditation training became significantly faster at registering their physiological responses (interoceptive awareness) to sexual stimuli compared with active controls (F(1,28) = 5.45, p = .03, $_{p}^2$ = 0.15).Another recent study of experienced meditation practitioners did not report a benefit of meditation on either interoceptive awareness or accuracy, however (Khalsa et al., 2008). Additionally, I am generally skeptical of the benefits of mindfulness on cognitive ability. See Jeromy's answer about the general effect of mindfulness on cognition. ReferencesCeunen, E., Van Diest, I., & Vlaeyen, J. (2013). Accuracy and awareness of perception: related, yet distinct (commentary on Herbert et al., 2012). Biological psychology, 92(2), 423-427.Chentsova-Dutton, Y. E., & Dzokoto, V. (2014). Listen to your heart: The cultural shaping of interoceptive awareness and accuracy. Emotion, 14(4), 666.Khalsa, S. S., Rudrauf, D., Damasio, A. R., Davidson, R. J., Lutz, A., & Tranel, D. (2008). Interoceptive awareness in experienced meditators. Psychophysiology, 45(4), 671-677.Schaefer, M., Egloff, B., Gerlach, A. L., & Witthft, M. (2014). Improving heartbeat perception in patients with medically unexplained symptoms reduces symptom distress. Biological psychology, 101, 69-76.Silverstein, R. G., Brown, A. C. H., Roth, H. D., & Britton, W. B. (2011). Effects of mindfulness training on body awareness to sexual stimuli: implications for female sexual dysfunction. Psychosomatic medicine, 73(9), 817.
_cogsci.5307
What is the origin of non-incremental, revolutionary intuition and intelligence?For example, a human mind like Albert Einstein's can come up with revolutionary ideas and theories that correctly adhere to the law of physics. On the other hand, another mind can't even understand this theory, let alone create or come up with one.Where does this initial intelligence and intuition (accurately proven) come from? Or what are the means by which modern humans achieve origins of intelligent intuition that adhere to science or nature? (Not talking about prophecy.)
How does cognitive science explain the origins of intuition and intelligence, that accurately describes the laws of nature?
intelligence;philosophy of mind;creativity;intuition
A couple of other interrelated perspectives are presented below. The first perspective comes from the article Artificial Intelligence, Logic of Discovery and Scientific Realism (Alai), where they state, using scientific discovery as an example (as per the example in the question), thatif the process of discovery is rational, mustnt it therefore follow rational criteria and rules, hence a logic? On the other hand, it is well known that chance, luck, and insight often play an important role in discovery.Effectively, almost like a case of someone 'tripping over' the final piece of their theorem. The author goes further, contending that if their were a rational set of steps, thusif discovery were just a matter of rule following, why couldnt anyone learn the necessary rules and become a great scientist? Or why couldnt the scientists themselves just follow the logic of discovery and program in advance new discoveries, and rapidly achieve such results as a cure for cancer, or the cold fusion of atom, which while sorely needed still elude the efforts of researchers?Meaning, according to this article's perspective, that luck, chance and insight play a major role.The final factor, insight, is alluded to in the website Einstein's Pathway to Special Relativity (Norton), taking the example scientist from the question, Albert Einstein and how he developed, for example, the Theory of Special Relativity, which started whenhe began to think about ether, electricity, magnetism and motion.Essentially, he had insight by pondering these developments that led Einstein to discover the special theory of relativity in 1905. A key point made is that The discovery was not momentary.This is crucial, the ideas didn't just 'pop' into his head, the theory was the outcome of having learned and developed an insight in the background information, latest developments in relevant disciplines and of course, in Einstein's own reckoning, seven and more years of work.As an independent researcher, (and I am not comparing myself to Albert Einstein), the discoveries that I have found, have had successfully peer reviewed and have been published come from having some specific insight, through background reading, training, education etc, to topics and skills required relevant to the discovery, as well as a lot of work to bring these insights together with new observations to make a discovery.
_cogsci.1980
Background: I vaguely remember reading in a book (I think it may have been Nudge - Thaler and Sunstein) about the advantages of using graphics for visualising data, such as a smiley face, or traffic lights, to communicate a message in an easily interpreted, visual language. To what extent do graphics such as smiley faces and traffic lights in visualisations facilitate ease of interpretation?What is the cause of this ease of interpretation?What research has studied this phenomena?Initial thoughts: I imagine that the ease of interpretation is due to these items being purely visual that we quickly recognise them, and they can make complicated, unfamiliar information (for instance health results) that much easier to comprehend. Is that an accurate summary? If it's any further help I'm looking into this specifically for use in the communication of health results. So for example if you have a 20% risk of developing a disease, a good way to illustrate this could be 100 smiley faces - of which 20 are :( and 80 are :)
How do graphic objects in data visualisation facilitate ease of interpretation?
cognitive psychology;software;health psychology;visualization
null
_softwareengineering.293439
On the software project I'm working there are 4 teams of 6 people. The project itself is a moderately complex distributed system, but the current user stories are mostly about implementing CRUD operations and such.My problem is that we are working in pairs non-stop. I think that this brute force approach to pair programming is wasteful since a lot of tasks (simple tasks, bugfixes) do not need two people's combined effort and I never reach flow ever since I'm working here.My question is about pair programming. When is it appropriate to use it and is it justifiable to do it all the time?There are some situations which I know from my previous experience likepair progrmaming with a new colleague so he gets up to speed quicklypair programming with a junior developer so he understands new concepts more quickly and thoroughlypair programming to effectively share domain knowledgebut I don't see why pair programming can be useful if used in all possible situations. What makes it even worse is that pairs often rotated mid-sprint which slows down development even more.
When is it justifiable to use pair programming and when is it not?
java;pair programming;extreme programming
null
_webapps.62949
I have noticed that when I tweet something with a hashtag (ex. #WorldCup2014) my tweet doesn't show in the feed or timeline of the hashtag although I have made my account public but still nothing.Can anyone help?
Tweets are not showing in hashtag streams?
twitter
null
_unix.5035
This one got closed:https://unix.stackexchange.com/questions/5030/freebsd-or-linux-or-something-elseBut I have a sincere question here. I want to know from the pros what is better for a newbie to start working on. I want to learn/contribute. If not the exact answer, please provide some rationale.
where to start open-source work?
linux;freebsd;opensource projects
null
_cstheory.24939
When I teach tail bounds, I use the usual progression: If your r.v is positive, you can apply Markov's inequalityIf you have independence and also bounded variance, you can apply Chebyshev's inequalityIf each independent r.v also has all moments bounded, then you can use a Chernoff bound. After this things get a little less clean. For exampleIf your variables have zero mean, then a Bernstein inequality is more convenientIf all you know is that the combining function is Lipschitz, then there's a generalized McDiarmid-style inequalityif you have weak dependence then there are Siegel-style bounds, (and if you have negative dependence, then Jansson's inequality might be your friend)Is there a reference anywhere to a convenient flowchart or decision tree describing how to choose the right tail bound, (or even when you have to dive into a sea of Talagrand) ? I'm asking partly so that I have a reference, partly so that I can point it to my students, and partly because if I'm sufficiently annoyed and there isn't one, I might try to make one myself.
A flowchart for concentration bounds
reference request;pr.probability;randomized algorithms
Fan Chung and Linyuan Lu. Concentration inequalities and martingale inequalities: a surveyavailable athttp://projecteuclid.org/euclid.im/1175266369 or at Fan Chung Graham's web page.
_unix.204675
I'm looking to conditionally select two columns from the third line of a file based on the first column of the first line of the file.Here is the file format:v1shortdescvalue1 value2 value3 value4 ...Using this example, I'd want value2 and value3 if v1, otherwise, I'd like value1 and value4. I know how to get the line and column using something like awk 'FNR ==1 {print $1} but how do I use the if clause?The code that is not working for me looks something like this:awk '{if(NR == 1 $1==v1) {FNR==3 print $2 \t $3;} else {FNR==3 print $1 \t $4;}}'
Use awk to get two specific columns from third line of file based on value in first line
awk
You can try this one:awk 'NR == 1 { if ($1 == v1) { p = 1; } } NR == 3 { if (p) { print $2 \t $3; } else { print $1 \t $4; } }' file
_softwareengineering.116162
We're considering teaching some employees who have either zero or general hobbyist level programming experience to take workload off me.We use Python/Django which has some of the friendliest documentation around and a breeze to learn. I'm currently a one man IT department for my company and I don't have enough hours to develop everything the company needs. We are not a software company, but it helps to have in house IT to automate tasks, develop customer service features, analyze data, etc.How do you slowly integrate rookies working on your codebase? Say you have an intern - what do they do? I'm completely reluctant to let them design or develop core code as we'll be dealing with their mistakes / strange design patterns for years. As the primary developer, I'll be the one who has to work around their code. My thought was to have rookies only modify existing code, never building core features. I can offload work to them with simple tasks after I build the feature itself.We'd like our employees to learn / find value in the company, and we generally have people 'move up the ranks'. Is it standard practice to teach people with general/hobbyist level programming? How does the moving up the ranks in a software company work for junior level programmers? When do they start working on core code?I'm trying to decide if it's going to cause more damage than help, and or if there's a way we can use their help without potentially risking core site code (isolated environments?).
How to include rookie developers into your project?
team;business
null
_reverseengineering.8128
I noticed that despite the imagebase for win32 executables be 0x400000, Ida Pro only starts the analysis at 0x401000. What is before that and how can I change IDA's settings to start the analysis at the imagebase? Thank you.
How can I make IDA start the analysis at imagebase?
ida;memory
PE executables start with a header block that consists of a little DOS exe stub (with its own little header), a structure called IMAGE_NT_HEADERS, and a section table. A normal PE has no 32-bit/64-bit executable code there, so IDA doesn't load the header block unless you check manual load.Relevant resources:Microsoft's PE COFF specification (currently at version 8.3)Matt Pietrek's classic Peering Inside the PE: A Tour of the Win32 Portable Executable File Formatits sequel An In-Depth Look into the Win32 Portable Executable File FormatReversingLabs' Undocumented PECOFF
_codereview.32449
I have a file with just 3500 lines like these:filecontent= 13P397;Fotostuff;t;IBM;IBM lalala 123|IBM lalala 1234;28.000 things;;IBMlalala123|IBMlalala1234Then I want to grab every line from the filecontent that matches a certain string (with python 2.7):this_item= IBMlalala123matchingitems = re.findall(.*?;.*?;.*?;.*?;.*?;.*?;.*?+this_item,filecontent)It needs 17 seconds for each findall. I need to search 4000 times in these 3500 lines. It takes forever. Any idea how to speed it up?
Regex to parse semicolon-delimited fields is too slow
python;performance;regex;csv;python 2.7
.*?;.*? will cause catastrophic backtracking. See this post on more details on the problem: http://www.regular-expressions.info/catastrophic.htmlTo resolve the performance issues, remove .*?; and replace it with [^;]*;, that should be much faster.
_unix.134630
I have a custom hardware, i.mx6q based board, running a custom stripped version of Debian, the usual Linux tools to make life easy are not available. Can I read and write to i2c directly with root access to /sys/bus/i2c/devices/[device] using standard tools such as echo, etc?
Direct i2c hardware access
debian;hardware
According to this Linux Journal article, titled: I2C Drivers, Part II:All I2C chip drivers export the different sensor values through sysfs files within the I2C chip device directory. These filenames are standardized, along with the units in which the values are expressed, and are documented within the kernel tree in the file Documentation/i2c/sysfs-interface (Table 1).Table 1. Sensor Values Exported through sysfs Filestemp_max[1-3] Temperature max value. Fixed point value in form XXXXX and should be divided by 1,000 to get degrees Celsius. Read/Write value.temp_min[1-3] Temperature min or hysteresis value. Fixed point value in form XXXXX and should be divided by 1,000 to get degrees Celsius. This is preferably a hysteresis value, reported as an absolute temperature, not a delta from the max value. Read/Write value.temp_input[1-3] Temperature input value. Read-only value.As the information in Table 1 shows, there is only one value per file. All files are readable and some can be written to by users with the proper privileges.So it would appear that somethings under /sys/bus/i2c/devices/[device] can be written to using standard tools such as echo, but others may not.ReferencesXilinx - Connecting the Aardvark I2C/SPI Activity Board To The ML507
_unix.43288
I have a following setup:1 postfix server: a.example.com that needs to accept all emails for any subdomain on example.com (*@*.example.com) and delivers to mailman account and also send emails to any email account (gmail, yahoo, etc) including *@example.com. 1 hosted exchange: exch11.hosted.com for example.com emails (*@example.com).Everything works in this setup except sending emails from a.example.com to *@example.com (exch11.hosted.com). If I have example.com in mydomains.db file, then a.example.com does not send out *@example.com emails and delivers locally. if I change it to *.example.com then it sends *@example.com emails to exch11.hosted.com but now does not accept *@subdomain.example.com emails and shows an error that Relay is not allowed (it should not be relaying and delivering to local maildir account).Main requirement is to have a.example.com accept mail for any subdomain and deliver emails for main domain to exch11.hosted.com. Can anyone please help me or point me towards right direction?Any help is welcome. Thanks.main.cf:command_directory = /usr/sbindaemon_directory = /usr/libexec/postfixmydestination = hash:/etc/postfix/mydomainsunknown_local_recipient_reject_code = 550alias_maps = hash:/etc/aliaseshome_mailbox = Maildir/smtpd_banner = mail.example.comdebug_peer_level = 2debugger_command = PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin xxgdb $daemon_directory/$process_name $process_id & sleep 5sendmail_path = /usr/sbin/sendmail.postfixnewaliases_path = /usr/bin/newaliases.postfixmailq_path = /usr/bin/mailq.postfixsetgid_group = postdrophtml_directory = nomanpage_directory = /usr/share/mansample_directory = /usr/share/doc/postfix-2.3.3/samplesreadme_directory = /usr/share/doc/postfix-2.3.3/README_FILESvirtual_alias_maps = hash:/etc/postfix/virtual, pcre:/etc/postfix/virtual.pcresmtpd_sasl_auth_enable = yessmtpd_sasl_security_options = noanonymoussmtpd_sasl_local_domain = $myhostnamesmtp_sasl_security_options = noplaintext#smtpd_sender_restrictions = check_sender_access hash:/etc/postfix/sender-accesssmtpd_recipient_restrictions = check_recipient_access hash:/etc/postfix/inbound-access,permit_sasl_authenticated, permit_mynetworks, reject_unauth_destinationmailbox_size_limit = 25600000transport_maps = hash:/etc/postfix/transportmessage_size_limit = 20240000virtual.pcre and virtual:/(.*)@[^.]*\.example\.com$/ mailmantransport:# demo.demo.example.com smtp:192.168.100.161:25# demo maildemo.example.com smtp:192.168.100.161# Demo2.demo2.example.com smtp:192.168.100.221:25# demo2 domaindemo2.example.com smtp:192.168.100.221mydomains:localhost OKmail.local OKexample.com OK
Postfix Configuration - different servers for subdomains and domain
centos;configuration;email;postfix
First of all i am not sure if this will work but i hope it will help get you started:Remove example.com from mydomains as this postfix instance does not handle the mail for it directly.Add virtual_alias_domains = .example.com this should solve your subdomain issueAdd relay_domains = example.com and specify an explicit transport for example.com, e.g: example.com :[exch11.hosted.com]
_unix.88331
Is there any GUI / functionality test automation tools for testing QT3 based GUI applications? I went through LDTP, dogtail, Squish, and Sikuli but all dependent on specific QT versions. Also, Sikuli is not reliable.Any others?
Test automation tools for desktop application
qt;testing
null
_unix.335293
I am stuck with this configuration here after commenting the DEFRROUTE line I get the ip r output like this. Does it really works with DEFRROUTE=no when uncommented.[root@vm1 ~]# ip rdefault via 192.168.5.1 dev eth0 proto static metric 100default via 192.168.1.1 dev eth2 proto static metric 101 169.24.0.0/17 dev eth1 proto kernel scope link src 169.24.0.5 metric 100192.168.1.0/24 dev eth2 proto kernel scope link src 192.168.1.3 metric 100192.168.5.0/28 dev eth0 proto kernel scope link src 192.168.5.10 metric 100[root@vm1 ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth2DEVICE=eth2BOOTPROTO=staticONBOOT=yesUSERCTL=noTYPE=EthernetIPADDR=192.168.1.3NETMASK=255.255.255.0GATEWAY=192.168.1.1#DEFRROUTE=no[root@vm1 ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth0DEVICE=eth0BOOTPROTO=staticONBOOT=yesUSERCTL=noTYPE=EthernetIPADDR=192.168.5.10NETMASK=255.255.255.240GATEWAY=192.168.5.1#DEFRROUTE=yes[root@vm1 ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth1DEVICE=eth1BOOTPROTO=staticONBOOT=yesUSERCTL=noTYPE=EthernetIPADDR=169.24.0.5NETMASK=255.255.128.0#DEFRROUTE=noWhen I uncomment the DEFRROUTE I get this below output without route[root@vm1 ~]# ip r169.24.0.0/17 dev eth1 proto kernel scope link src 169.24.0.5 metric 100192.168.1.0/24 dev eth2 proto kernel scope link src 192.168.1.3 metric 100192.168.5.0/28 dev eth0 proto kernel scope link src 192.168.5.10 metric 100As @artem suggested via the link, below is the screenshot.
DEFROUTE usage in RHEL 7
linux;ifconfig
null
_webmaster.4711
Looking for online advertisers like google that let you place ads in feeds?
Where can I find online advertisers that let you place ads in rss feeds?
advertising
null
_cstheory.9353
This one's hard, so all help really appreciated!I know it is NP-Complete and thus cannot be solved in polynomial time, but looking for help in analysis, i.e. what type of NP-Complete problem it reduces to, similar problems it reminds you of, etc.The story goes as follows. I own an ice cream truck business with n trucks. There are m stops where I make deliveries. Each location $m_i$ has $p_i$ people waiting for me. After buying their ice cream, everyone leaves (so $p_i$ reduce to zero). $p_i$ increases over time as more people line up to wait for the ice cream trucks. Also, all the truck drivers get commission, so they are competing against each other. All trucks have to be either at a location or moving to the next at any given time.How can I figure out where to send the trucks next in order to maximize my profit on any given day?Things to keep in mind:Two trucks that stop in the same spot at similar times will only getthe profit once, i.e. the people leave after one truck arrivesThe trucks take time to get from one location to another$p_i$ increases over time at each stop, but some stops increase fasterthan others, i.e. some locations are near malls (location, location,location)I've tried reducing this to a multi-machine scheduling problem, travelling sales person problem, ILP etc., but the main issue is that the $p_i$ at every location (i.e. the distance in the TSP or the job length in the scheduling problem) is constantly changing.Thanks in advance!
Algorithm to maximize profit: ways to solve/approach? (Advanced NP-Complete)
np hardness;optimization;gt.game theory;tsp;scheduling
null
_cstheory.23767
Hub labeling (HL) computes superlabels using the vertices visited by the forward and reverse Contraction Hierarchies (CH) search. Those labels are then pruned (see HL, sec. 4.2) to generate strict labels.I don't understand how there can be labels that can be pruned. From my understanding the shortcuts added by CH should make sure that in both forward and reverse searches we will eitherreach a node via a shortest path ornot reach a node at all.How is it possible that we reach some nodes via a path that is longer than the shortest path? Could anyone provide a minimal example?
Why is label pruning possible with hub labeling?
ds.algorithms;shortest path
I have emailed the authors and they kindly supplied me with the following example:Let the nodes be contracted in alphabetical order then the red edge will be added during contraction.Now look at the upward search from A (i.e. we can only visit nodes that have been contracted later). A will settle B with distance 1 and D with distance 2. Since we are not allowed to visit C via D (as this is not upward) we must settle C via B with distance 6. However, as can clearly be seen from the non-contracted graph, the A-C distance is 5 (via D).This means that we now have an incorrect distance label for C at A.
_unix.12195
I set up my ssh stuff with the help of this guide, and it used to work well (I could run hg push without being asked for a passphrase). What could have happened between then and now, considering that I'm still using the same home directory.$ cat .hg/hgrc [paths]default = ssh://[email protected]/tshepang/bloog$ hg pushEnter passphrase for key '/home/wena/.ssh/id_rsa': pushing to ssh://[email protected]/tshepang/bloogsearching for changes...
How to avoid being asked passphrase each time I push to Bitbucket
ssh;key authentication
You need to use an ssh agent. Short answer: try $ ssh-addbefore pushing. Supply your passphrase when asked.If you aren't already running an ssh agent you will get the following message:Could not open a connection to your authentication agent.In that situation, you can start one and set your environment up thuslyeval $(ssh-agent)Then repeat the ssh-add command.It's worth taking a look at the ssh agent manpage.
_unix.154777
Some instances of bash change the command history when you re-use and edit a previous command, others apparently don't. I've been searching and searching but can't find anything that says how to prevent commands in the history from being modified when they're reused and edited.There are questions like this one, but that seems to say how to cope with the history being edited. I've only recently come across an instance of bash that does edit the history when you reuse a command - all previous bash shells I've used have (as far as I've noticed) been configured not to change the history when you reuse and edit a command. (Perhaps I've just not been paying proper attention to my shell history for the past 15 years or so...)So that's probably the best question: CAN I tell bash NEVER to modify the history - and if so, how?
How to stop bash editing the history when I reuse and modify an entry?
bash;command history;line editor
Turns out revert-all-at-newline is the answer. I needed to include set revert-all-at-newline on in my ~/.inputrc file, since using the set command at the bash prompt had no effect. (Then, of course, I had to start a new shell.)Also, I found that ~/.inputrc is loaded instead of /etc/inputrc if present, which means that any defaults defined in the latter are no longer active when you create ~/.inputrc. To fix this, start ~/.inputrc with $include /etc/inputrc.Thanks to @StphaneChazelas for pointing me in the right direction.
_unix.166388
I have a Java application on a suseEnvironment which I start with a SH file. I use the command: startFile.sh &.If I logged in via putty, the application is still running after I've closed putty.If I'm logged in at suse directly (via UI) and I start the application, It will be terminated after I've logged out from SUSE.What is the difference?
Terminating Java Application
java;suse
null
_scicomp.27545
I'm using LAPACK zgeev routine to get eigenvalues and eigenvectors of a symmetric matrix in C++. Problem is zgeev is being called in a loop but it sorts eigenvalues (and eigenvectors) differently sometimes. For example, this is the eigenvalues from the first round of loop:(-1.29007e-5 - 5.207e-6*i)(1.28782e-5 + 7.40505e-6*i)And this is it's result from the second time:(1.28782e-5 + 7.40505e-6*i)(-1.29007e-5 - 5.207e-6*i)I need to plot the evolution of these eigenvalues and vectors as a function of the loop's variable but they keep getting swapped each time and gives me a combination of the plots I need.How to fix this?
LAPACK sorting eigenvalues differently each time
c++;eigenvalues;matrix;eigensystem;lapack
You write, that you are computing the eigenvalues of a symmetric matrix. Does the matrix have real entries? In this case all eigenvalues are real, and you can use a symmetric eigenvalue solver, which returns only real entries. Hence, sorting them should not be a problem.When your matrix has complex entries, you have to track the eigenvalues. I am assuming that your matrices change only slightly from one iteration of your loop to the next, meaning that the eigenvalues also change only slightly. Hence, you can find the eigenvalue of the next iteration that corresponds to the eigenvalue of the current iteration, by looking for the eigenvalue of the next iteration that is closest to the eigenvalue of the current iteration.In general, sorting complex eigenvalues does not solve your problem. Consider the matrix\begin{equation}A(t) =\begin{bmatrix}e^{\mathrm{i} t} & 0 \\0 & e^{\mathrm{i} (t + \pi)}\end{bmatrix}\end{equation}for $t = [0, 2\pi)$. The matrix has two eigenvalues, both lie on the circle of radius one. The two eigenvalues lie on opposit sides of the circle and with increasing $t$ they rotate around zero. When $t$ is large enough the first eigenvalue reaches the point where the second eigenvalue has been, and vice versa. Hence, any sorting technique will (at latest) at that point, switch the roles of the two eigenvalues, even though the first eigenvalue moved slowly to the position of the second, meaning it has not changed its role.If your eigenvalues vary only a little, you might get away with sorting the eigenvalues first by real part and then by imaginary part or by their absolute value. In general, however, this does not work.
_webapps.74960
Is it possible for Facebook user to restrict their photo from certain people to be seen? Even though they are not friend on Facebook. It was weird because these photos were public posted and everyone can see it. All these people are not on the friend list either. But only my account I couldn't see it.If that option is available. How can I do that?I thought we could only restricted the audience when they are on our friend list.
Facebook privacy setting
facebook
null
_cs.75005
Is it possible directly to reduce clique to set cover?I know that there are some ways of direct reduction from Clique to Vertex Cover and from Vertex Cover to Set Cover, so I am very interested to know if the is a way to reduce clique to set cover directly without the use of the transitive rule.
Reduce Clique to Set Cover
set cover;clique
null
_unix.245779
I'm currently studying scripting and I need to create an script to back up the /user/home using .bz2 compression. My teacher wants the person running the script to select the user to backup and the method of compression. I've created a very simple script, but I would like to tune it up a bit.This is what I need:#/bin/bash#Choose user to backup#choose compression method.Final results of script:user_20151126.tar.bz2My script:#!/bin/bashecho -n Enter a User Name for the back:read UserNameecho -n Enter the compression method:read CompressionMethodtar -jcvf /var/tmp/$UserName_$(date +%Y%m%d).tar.$CompressionMethod /homechmod 777 /var/tmp/$UserName_$(date +%Y%m%d).tar.$CompressionMethodecho Nightly Backup Successful: $(date) >> /var/tmp_backup.logMy results:20151126.tar.bz2
How to backup /user/home with some requirements?
backup;read
null
_softwareengineering.291061
I'm working on a server implementation for a large game with many gametypes. There are several kinds of interactable entities: players, monsters, objects, vehicles.All entities share the same base class (which is Cython):cdef class Entity: cdef public int id cdef public double x,y,z,yaw,pitch,speed def __init__(self, int id, double x, double y, double z, double yaw, double pitch): self.id = id self.x = x self.y = y self.z = z self.yaw = yaw self.pitch = pitch self.speed = 0.1Then there's a subclass for each of the earlier mentioned entity types, these subclasses implement the different packets involved for each of those types.All entities support position and rotation, and all entities can in theory support different behaviors (and there can be quite a lot depending on the gametype) but often do not need them. There could be around ~90 different behaviors, so supporting all of that on the base MonsterEntity/whatever class doesn't make sense. A lot of those behaviors depend on stuff like health though, so if I don't implement that in a base class I'd have to implement it in a subclass.. but there are so many behaviors like that that are related I'd end up with either a lot of repeated code in different subclasses or thousands of usually unnecessary lines in a single big class.I decided some kind of composition would make a lot more sense here, so I've tried using multiple inheritance since Python handles it pretty well:class EntityHealth(object): def __init__(self, maxhealth=20): self.health = maxhealth self.maxhealth = maxhealth def damage(self, amount): # damage the entity pass def setHealth(self, health): # set the entity's health passclass EntityInventory(object): def __init__(self): self.inventory = Inventory() def dropAllItems(self): # do stuff passclass SlayableMonster(Monster, EntityHealth, EntityInventory): def __init__(self, id, name, x, y, z, yaw, pitch): Monster.__init__(self, id, name, x, y, z, yaw, pitch, meta, uuid, skinblob) EntityHealth.__init__(self, 20) EntityInventory.__init__(self)I've heard people argue multiple inheritance should never be used, but this seems like a very concise design.Some thoughts...All behavior classes would inherit from object or one behavior only for extending that behavior.The diamond problem shouldn't ever happen as a result because you would never have two classes that inherit from the same class up the tree both applied to the same entity.So MRO problems should be impossible because the design is simple, there is no complex inheritance hierarchy.Is this the best solution here, or is there something equally/more concise with the same advantages? I just want to isolate relevant code together while being able to pick which entities need that kind of behavior.
Is there a better pattern than multiple inheritance here?
python;game development
Multiple inheritance is sometimes the right thing to do.You probably shouldn't inherit both from Car and OilRig, but inheriting from both Walker and Talker can make a lot of sense, particularly if using delegation would introduce a lot of trivial delegating methods that are a pain to maintain. It is particularly benign if it verges on emulating traits or implementing multiple interfaces with default implementations. It looks as if that is exactly what you are doing here. Certainly you don't have any of the issues (selection of indirectly inherited virtual methods in the diamond configuration, undefined internal layout of derived objects) that caused so many problems in C++ and influenced the conventional wisdom that you should never do it.
_cs.60647
Given a DFA (D1) with P1 states, that accepts a language L1. Modify (D1) to create another DFA (D2), such that it will accept the language L2 that is defined as: All strings in L1 that are also a palindrome (of maximum length P1).How many states would the minimized D2 have (worst case)? And time complexity?Similarly, NFA (N1) with Q1 states that accepts a Language L3. How many states would minimized (N2) have (worst case)? Along with its time complexity?The generic Palindrome Language is non-Regular hence a DFA/NFA for it is impossible but I am unaware of the limited Palindrome case in DFA/NFA?
Modify DFA/NFA that accepts Language Subset with only Palindromes (with Size Limit)?
regular languages;automata
For DFAs, the size of $D_2$ is always at most $O(P_1|\Sigma|^{P_1/2})$, and this bound is tight up to the $P_1$ factor. For the lower bound, take a DFA for $\Sigma^*$ having $P_1$ states (you haven't specified that $D_1$ is minimal). The DFA $D_2$ accepts all palindromes of length $P_1$, and so Nerode's theorem shows that for even $P_1$, the optimal DFA $D_2$ contains $\Theta(|\Sigma|^{P_1/2})$ states. The upper bound now follows by using the product construction.The exact same reasoning works for NFAs as well, although you need to replace Nerode's theorem with a suitable exchange lemma in order to show that any NFA for the language of all palindromes of length $P_1$ requires $\Omega(|\Sigma|^{P_1/2})$ states (for even $P_1$).If you insist on $D_1$ being minimal as well, then instead of a DFA for $\Sigma^*$ take a DFA for $(\Sigma^{P_1})^*$, to get the exact same results. This construction works also for NFAs.
_cstheory.37709
I have a question about whether there are faster algorithms for specific submodular minimization problems.In particular, I am trying to find a fast algorithm for minimizing the following set function$$f(S) = - [\sum_{i \in S} \alpha_i \log(\alpha_i) + (1-\sum_{i \in S} \alpha_i) \log(1-\sum_{i \in S} \alpha_i)] + \sum_{i \in S} w_i$$where $S \subset \{1,...,n\}$, $\{\alpha_i\}_{i=1}^N$ is a vector of positive numbers that add up to 1, and $w_i$ is a set of (possibly negative) weights. The first term in the function is a submodular function of $S$. The second term is a modular function of $S$. I know there exist algorithms (Fujishige-Wolfe) to minimize a general submodular function. Are there known algorithms to quickly minimize the sum of the entropy of a set and a modular function?
Minimizing entropy plus a modular function
submodularity
Unless I'm mistaken, you can solve your problem in $O(n\log n)$ time using a greedy algorithm.Minimizing $f(S)$ is equivalent to maximizing$$\textstyle g(S') = \sum_{i \in S'} b_i + \big(\sum_{i\in S'} \alpha_i\big) \log \sum_{j \in S'} \alpha_j$$for $b_i=w_i + \alpha_i\log(\alpha_i)$. Here $S'$ is the complement of your $S$.Assume WLOG that $\alpha_i>0$ (otherwise $i\in S'$ iff $b_i>0$).Introduce indicator variable $x_i$ for the event that $i\in S'$,then relax the problem by allowing $x_i\in[0,1]$. The relaxed problem is to choose $x\in[0,1]^n$ maximizing$$\textstyle G(x) = \sum_{i} x_i b_i + \big(\sum_i x_i \alpha_i\big) \log \sum_{j} x_j \alpha_j.$$The partial derivative of $G(x)$ with respect to $x_i$ is$$\textstyle b_i + \alpha_i\, \lambda(x),$$where $\lambda(x) = 1 + \log\sum_j x_j \alpha_j$.So at any optimal $x$, you have $$x_i = \begin{cases}0 & \text{if}~ b_i/\alpha_i < -\lambda(x) \\1 & \text{if}~ b_i/\alpha_i > -\lambda(x) \\? & \text{if}~ b_i/\alpha_i = -\lambda(x).\end{cases}$$WLOG, the ratios $b_i/\alpha_i$ are distinct for each $i$ (otherwise an insignificant perturbation of the $b_i$'s makes them so). So only a single $x_i$ is undetermined by the above condition. Since $G(x)$ is convex, one of the two neighboring solutions $x'$ (obtained by changing that $x_i$ to zero or one) has $G(x') \ge G(x)$.Hence, defining $S_j = \{i : b_i/\alpha_i \le b_j/\alpha_j\}$ and $S_0=\emptyset$, the optimal set is $S_j$ for some $j\in\{0,\ldots,n\}$.So, here is the algorithm. Assume that $\alpha_i > 0$ for each $i$, and (by sorting first in $O(n\log n)$ time), that$b_1/\alpha_1 > b_2/\alpha_2 > \cdots > b_n/\alpha_n$.Enumerate all sets $S_j$ (and compute $G(S_j)$ for each) in $O(n)$ time, then take the best.
_unix.146067
I have mounted a volume from NAS storage to my Solaris 10 machine using NFS. I want to give read/write permission for a user to the directories and subdirectories and files. I have tried setfacl -m user:biptip:rwx,mask:rwx NIADOCS/*setfacl -R -m d:u:biptip:rw,u:biptip:rwX NIADOCSbut I am not able give the permission.
Give a user the permission to access files in a directory
files;permissions;solaris;nfs;acl
null
_cs.24171
I am working on acyclic orientations of undirected graphs and have the following questions: Given connected undirected simple graph $G$, how to find all possible acyclic orientations of $G$ ? What is the number of acyclic orientations? It is known (from here) to be $(-1)^p\ \chi(G,-\lambda)$ for a graph $G$ with $p$ vertices where $\chi$ is the chromatic polynomial evaluated at $-\lambda$; but I wasn't successful in understanding how to evaluate $\chi$ at a negative value ($-\lambda$).
Algorithm to find all acyclic orientations of a graph
algorithms;graph theory;counting
null
_computergraphics.225
There are a number of terms for rendering techniques based on the particle model of light: forward ray-tracing, reverse ray-tracing, ray-casting, ray-marching, and possibly others. What's the difference between them?
Ray-based rendering terms
raytracing;raymarching;terminology
null
_unix.337251
I have a directory called development and I want to set its permissions I guess, in a way that if someone where to run rm -rf development it would prompt for sudo access or just deny the command, implying sudo access required. How can this be done? Right now, the folders inside of this can be deleted safely, but not from the development folder itself.
mac terminal - how to make a directory require SUDO access to delete it?
osx;sudo;rm
If you want to require sudo use to delete it, you need to make the directory and perhaps all the files inside it be owned by root with chown:chown -R root developmentTo protect the directory alone, make a root-owned file inside it:sudo touch development/.no-deletesudo chown root developmentThat will prevent anybody deleting the directory without root access even if it's otherwise empty.Just changing permissions on the directory won't help, because deleting the directory depends on permissions of the parent directory. Changing permissions on the directory will affect deletion of its children, rather than itself. The non-root owner would also be able to change the permissions regardless.
_cstheory.37845
Ezra and Sharir showed the $O(n^2\log^2 n)$ linear decision tree complexity for $k$-SUM problem [1], which improves the $O(n^3\log^3 n)$ complexity result of Cardinal et al [2].It is known that $k$-SUM and Table-$k$-SUM problems are related and can be reduced to each other in linear time[3] and both problems can be solved in polynomial time $O(m^k).$$\textbf{$k$-SUM Conjecture}$ [4]:There does not exist a $k 2$, an $ > 0$, and a randomized algorithm that succeeds (with high probability) in solving $k$-SUM in time $O(n^{ \left \lceil{k/2}\right \rceil})$.What's the consequence of the above new decision tree complexity results? What can this lead to a new bound for the time complexity of $k$-SUM problem? [1] Ezra, Esther, and Micha Sharir. The Decision Tree Complexity for $ k $-SUM is at most Nearly Quadratic. arXiv preprint arXiv:1607.04336 (2016).[2] Cardinal, Jean, John Iacono, and Aurlien Ooms. Solving $ k $-SUM using few linear queries. arXiv preprint arXiv:1512.06678 (2015).[3] Woeginger, Gerhard J. Space and time complexity of exact algorithms: Some open problems. International Workshop on Parameterized and Exact Computation. Springer Berlin Heidelberg, 2004.[4] Abboud, Amir, and Kevin Lewi. Exact weight subgraphs and the k-sum conjecture. International Colloquium on Automata, Languages, and Programming. Springer Berlin Heidelberg, 2013.
Consequence of Decision Tree Complexity of $k$-SUM Problem
cc.complexity theory;ds.algorithms;k sum
null
_codereview.53876
I was cleaning up my code when I came across this situation :var a = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];var count = 1;var html = '';for (var i = 0; i < a.length; i++) { var rowStart = '<div class=row>'; var cell = '<div class=c>'; cell += '<div class=title>' + a[i] + '</div>'; cell += '</div>'; var rowEnd = '</div>'; if (count == 1) { html += rowStart + cell; count++; } else if (count == 3) { html += cell + rowEnd; count = 1; } else { html += cell; count++ }}$('#container').append(html);jsFiddleI retrieve data from a database which I want to display in a div structure as shown above. This code however looks ugly and I think it can be way shorter, I just don't know how.I was hoping someone could give me some advice/methods/anything on how to clean up this code.
Cleanup code to add div structure to element
javascript;jquery;html
You should let CSS handle most of the job for you. ExampleJS:var a = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];var count = 1;var html = '';for (var i = 0; i < a.length; i++) { var div = $(<div> + a[i] + </div>); $('#container').append(div);}CSS (where the magic is):#container div:nth-child(3n+1) { /* Every third! */ clear: both;}#container div { float: left; width: 100px;}
_computerscience.5192
You can have blue noise sampling like these poisson disc samples:And you can have a blue noise texture like this:I get that in the first image, there is one input (the index of the sample) and two outputs (the x,y coordinate of the point) and that the second image is basically the reverse where there are two inputs (the x,y coordinate of the sample) and one output (the value of the point).I'm curious though, how are these related?If you take the DFT of the second image, you can see that it has more high frequency components than low, but I'm not sure how you'd take the DFT of the first set of data points.I'm wondering if it's possible to take other low discrepancy sequences (say, halton, or jittered grid) and make a texture out of the idea, like the second image?
Link between blue noise sampling and blue noise textures?
sampling
null
_webmaster.88903
I have a site in Hebrew #.co.il and I cnnsider changing it from a native-Hebrew site to a native-English one; That is, the direction will be LTR instead of RTL, and most of the content will be in English instead of Hebrew.Can it work if the site's domain will still be co.il?I ask only for direct experience with an identical or similar problem, or maybe a good statement from Google inc (that might be outdated).
co.il domain for sites that are not in Hebrew - Can work by means of SEO?
domains
Google will only ever rank .il domains well in Isreal. Google assumes that all content on .il domains is not very relevant outside Isreal.Google maintains a list of top level domains that are geo-targetable. There are a few country code TLDs on that list:.ad .as .bz .cc .cd .co .dj .fm .io .la .me .ms .nu .sc .sr .su .tv .tk .wsHowever, if your TLD isn't on that list, you are out of luck. Google Webmaster Tools will not allow you to geo-target most country code domains to something other than their intended country.Matt Cutts has a video where he explains Google's reasoning for this:If you have a .jp domain and are trying to target Finland, you are really going against a lot of expectations and conventions that people have on the net. So one thing to think about would be whether it would be possible to get a generic TLD and use that for other countries.For what it's worth, I also think that Google is being silly on this issue. It limits the creative use of names. You can't use TLDs for language (.de sites don't rank well in Austria where they also speak German, or .pt in Brazil)This has been Google's policy for years now though, and they haven't been willing to budge on it. If you want your site to rank worldwide, you can't use most country code top level domains.
_unix.340205
I tried both netctl and NetworkManager.Copied /etc/netctl/examples/mobile_ppp and added number and APN name as there's no pin/pass/username and set interface to /dev/ttyUSB0 (also tried the other ttyUSB1, and ttyUSB2 as well).My `/etc/netctl/mobile_ppp` file's contents are as follows:Description='Example PPP mobile connection'Interface='ttyUSB0'Connection='mobile_ppp'PhoneNumber='*99#'# Use default route provided by the peer (default: true)#DefaultRoute=true# Use DNS provided by the peer (default: true)#UsePeerDNS=true# The user and password are not always required#User='[email protected]'#Password='very secret'# The access point name you are connecting toAccessPointName='internet'# If your device has a PIN code, set it here. Defaults to 'None'#Pin=None# Mode can be one of 3Gpref, 3Gonly, GPRSpref, GPRSonly, None# These only work for Huawei USB modems; all other devices should use NoneMode=3Gonly# ^ tried all other options toonetctl start mobile_ppp connects silently with no errors on output and shown on journalctl -xe, but there's no actual connection.And it also shows * sign prepended on its name when issuing netctl list (as if really connected/operating).Currently I am connected with netctl but with wls1 (Wi-Fi profile set up with wifi-menu).Moreover the USB modem is not shown in the nm-applet of NetworkManager, what I installed separately.Also, the modem's LED turns blue as if connected or operating, but with no results.I did a lot of research on the web, came across and read wikis and other users asking about similar issues, and tried the solutions, installed many many packages in Arch Linux, but unfortunately nothing worked for me to simply connect with the modem which used to automatically connect on Fedora 25 (without GNOME even).
Cannot connect with Huawei E3131 3GMax USB Modem
arch linux;networkmanager;modem;ppp;netctl
I could finally solve it (I'm posting it using the USB connection :P).Some points to note:wvdial (as configured in /etc/wvdial.conf) could not connect anyhow (couldn't dial with ATDT and ATD commands).netctl created profile, 'connected' (netctl start) without (outputting) errors but there were no real connection.So, I installed NetworkManager, started and enabled it as service alongisde ModemManager (with systemctl start).I installed tint2 (as there's no panel (system tray) in my system) specifically to run GNOME's nm-applet on it, and configured the broadband network, and Network Manager showed it as an enabled device and I could connect through the profile I created on nm-applet (GUI, again).That's it. Thanks, gnome for nm-applet :)NetworkManager won't (probably) connect without ModemManager service.No matter how hard I'll try I couldn't connect through the default, native netctl that comes with arch-linux.I still would like to connect with the native application, if anyone knows how, or can help with it (reading my previous post, or by providing a 'better' profile file for the USB modem (model) noted above), I'd really appreciate that, and switch back to netctl.But now that the native netctl couldn't/doesn't do the job, I'll have them both installed (what I don't actually like doing for minimalism) as network managers until I could connect properly through the former one.
_softwareengineering.254576
Consider the following class:class Person: def __init__(self, name, age): self.name = name self.age = ageMy coworkers tend to define it like this:class Person: name = None age = None def __init__(self, name, age): self.name = name self.age = ageThe main reason for this is that their editor of choice shows the properties for autocompletion.Personally, I dislike the latter one, because it makes no sense that a class has those properties set to None.Which one would be better practice and for what reasons?
Is it a good practice to declare instance variables as None in a class in Python?
python
I call the latter bad practice under the this dosen't do what you think it does rule.Your coworker's position can be rewritten as I am going to create a bunch of class-static quasi-global variables which are never accessed, but which do take up space in the various class's namespace tables (__dict__), just to make my IDE do something.
_unix.240000
I want to make scripts that shows Western Zodiac which accepts as input a person's birthday on the command line and prints out the following:The day of the week on which the person was bornTheir Western zodiac sign (cancer, leo, libra, etc.)Their Chinese zodiac sign (wood rabbit, metal snake, fire pig, etc.)Their horoscope (use the Linux fortune cookie program for this)anyone ever made this ?
how to make scripts that shows Western Zodiac?
scripting
null
_webmaster.37873
I have a blog which has been active for 3 years. Recently I posted an article and it immediately appeared in google search. Maybe 5 to 10 minutes.A point to note is I was logged into my google account. Maybe google checked my post's when I searched since I am logged in?Yet I logged out and used another browser and searched again with that specific text and it appeared in google search result.How did this happen?However, if I make an article in static HTML and publish, it takes time. (I assume this is the case but I haven't tested much). Yet tested a few cases after updating it in my sitemap xml.How does google search work for a blog and other content?
New blog post shows immediately in google search results where as other HTML content takes time, why?
google search;google ranking
Were your personal search results turned off? When was the page cached? It's likely your blog pinged Google along with other search engines once you published the post. Well Google blog search at least which is different than Google Bot.Search results work just the same for a blog post page compared to any other content page. Google has been crawling, indexing, and caching pages much quicker than in the last few years. Where in the past they would push updates to their data centers lets say once per week now it's probably a few times a day if not instantaneous.The blog post when generated may have gotten naturally more internal links than some of your other pages. It's content is certainly fresher than other pages on your site most likely and the HTTP response from that page told Google the content was very recently updated.All in all what you're asking is How does Google work and there's no answer that can tell you exactly how they indexed that one blog post as quick as they did. Maybe it was luck that they were crawling your site when you posted and it coincided with an update to their index.
_datascience.8388
I am trying to cluster related areas of knowledge based in publications.For example a researcher has 3 keywords in a paper, in another paper he has 5 keywords, but 3 keywords are the same in the both papers. Then these 3 keywords are similar and It could be an area of knowledge. A sample of my file is:'Domain Ontology,Semantic Web''Linked Data,Domain Ontology,Use Case''Domain Ontology,Linked Data,Semantic Annotation''GIS,Open GIS,Integrated Geo Systems''Open GIS,GIS'My file contains 48963 rows and 19000 keywords. I have tried grouping words (like in the sample), using StringToWordVector (STWV), but I don't have good results. So I tried different K for my cluster since 3 until 13000. When K is greater my log likelihood decrease. In many models my words are grouped perfectly, but the percentages are not really good for some clusters. For example for K=3000, the 2999 have between 0,1% and 1% of the data, but the 3000 have the 21%. I am using WEKA. Anyone know some work related, some advice or any help is helpful...Cheers.
Clustering related areas with k-means
data mining;clustering;text mining
null
_softwareengineering.332736
I'm doing a little bit of cleanup and I'm trying to gather all the spread SQL queries done to an object into a single place. I have a class whose responsibility is to present a CRUD interface to the developer, and to encapsulate the results coming from selection queries into objects, that at the same time can be updated or deleted.So far so good. However, I noticed that across the site we have 115 different places where an object retrieval is done. I managed to find out that there are a total of 17 cases which, with a little bit of witchcraft and making a couple parameters optional, could be reduced to 9.9 retrieval methods feels too much to me for a class, especially if it already has many more methods to do the CRUD.I thought of using a mixin (more specifically in PHP, a trait) to keep all the methods together and in the class, although separate enough, to keep the main class as clean as possible (with just the most complete retrieval method, whose all the other methods would depend on), although since mixins are used to encapsulate and reuse across many classes, I wonder if there's a better way to do this without making the class too crowded.For the record, this class is not an ORM itself, although it uses one internally to do all the CRUD tasks. Instead, the methods are called like get_by_id, reset_timer, add_feature, and so.
Encapsulate multiple retrieval methods for a class
object oriented design;code organization;crud
null
_datascience.18754
I've been given a dataset with a number of observable states. I am trying to apply a Finite State Markov Chain to model the system, but I found that I can't estimate the transition probabilities if the observed states were sampled using different time intervals. How can I find these probabilities?I will try to make the question a more clear. I have samples collected in random intervals during a 6-month period. This samples represent the quality of a system, which is ranked from 0 to 15 in discrete intervals i.e. (0,1,2...15). I need to model de system using a FSMC to mimic the system's behavior. So far, I have estimated the transition probabilities between states using only the frequencies of those transitions using all the samples. I am not interested in modeling the time, however, I am not sure If I can estimate the transition probabilities in such a simple way or if I have to take the time between samples (which in my case is random) into consideration when estimating those probabilities.
How to estimate the transition probabilities for a Markov Chain when time intervals are non-equally spaced
probability;markov process
null
_unix.242854
This would probably never be the BEST approach to something, but I'm wondering if it's even possible.Something like:awk '/function_i_want_to_call/,/^$/{print}' script_containing_function | xargs sourcefunction_i_want_to_call arg1 arg2 arg3Except actually working.
Source only part of a script from another script?
shell script;scripting;function
First you need to rigorously determine what command will produce the specific part you want to source. For a trivial example, given the filevar1=value1var2=value2you could set only var1 using head -n1 filename. This could be a pipeline of arbitrary complexity, if you wanted.Then run:source <( pipeline_of_arbitrary_complexity some_filename )Works only in bash. To do it in POSIX, I think you'd need to make a temp file.
_unix.86625
I have a LaTeX source file with its indentation messed up.I am looking for a way to force vim (may be through one of vim-latex-suite commands) to re-run the automatic indentation commands over the whole file once again.I can easily get rid of the messed up indentation by eating up all the white spaces in the beginning of each line with a simple regex :%s/^\s\+//. My problem is how to re-run the automatic indentation commands over the whole file.( I am basically looking for something like the smart indent in MATLAB Editor or some other text editor, which can re-indent already existing text).
How to re-run vim auto-indentation on a tex file?
vim;editors;latex
Method #1: vimI believe you can do what you want with the following keyboard commands in vim, as follows.NOTE: =, the indent command can take motions.So:gg to get the start of the file= to indentG to the end of the filePutting it all together: gg=G.Method #2: without vimThis isn't a vim solution but I came across this Perl script titled LaTeXTidy.pl which might be more useful if you have multiple files you have to do this with.The original script and a copy on pastebin:http://bfc.sfsu.edu/LaTeXTidy-0.31.plhttp://pastebin.com/p7vV0GmaExampleTo run it you'll need to make it executable after downloading it and then just run it passing it the name of a latex file.download$ curl -o latextidy.pl http://bfc.sfsu.edu/LaTeXTidy-0.31.pl % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed100 4755 100 4755 0 0 1201 0 0:00:03 0:00:03 --:--:-- 1334permissions and running$ chmod +x latextidy.pl$ ./latextidy.pl <some_latex_file.tex>
_scicomp.2469
Related question: State of the Mac OS in Scientific Computing and HPCA significant number of software packages in computational science are written in Fortran, and Fortran isn't going away. A Fortran compiler is also required to build other software packages (one notable example being SciPy).However, Mac OS X does not include a Fortran compiler. How should I install a Fortran compiler on my machine?
How should I install a Fortran compiler on a Mac? (OS X 10.x, x >= 4)
software;fortran
Pick your poison. I recommend using Homebrew. I have tried all of these methods except for Fink and Other Methods. Originally, I preferred MacPorts when I wrote this answer. In the two years since, Homebrew has grown a lot as a project and has proved more maintainable than MacPorts, which can require a lot of PATH hacking.Installing a version that matches system compilersIf you want the version of gfortran to match the versions of gcc, g++, etc. installed on your machine, download the appropriate version of gfortran from here. The R developers and SciPy developers recommend this method.Advantages: Matches versions of compilers installed with XCode or with Kenneth Reitz's installer; unlikely to interfere with OS upgrades; coexists nicely with MacPorts (and probably Fink and Homebrew) because it installs to /usr/bin. Doesn't clobber existing compilers. Don't need to edit PATH.Disadvantages: Compiler stack will be really old. (GCC 4.2.1 is the latest Apple compiler; it was released in 2007.) Installs to /usr/bin.Installing a precompiled, up-to-date binary from HPC Mac OS XHPC Mac OS X has binaries for the latest release of GCC (at the time of this writing, 4.8.0 (experimental)), as well as g77 binaries, and an f2c-based compiler. The PETSc developers recommend this method on their FAQ.Advantages: With the right command, installs in /usr/local; up-to-date. Doesn't clobber existing system compilers, or the approach above. Won't interfere with OS upgrades.Disadvantages: Need to edit PATH. No easy way to switch between versions. (You could modify the PATH, delete the compiler install, or kludge around it.) Will clobber other methods of installing compilers in /usr/local because compiler binaries are simply named 'gcc', 'g++', etc. (without a version number, and without any symlinks).Use MacPortsMacPorts has a number of versions of compilers available for use.Advantages: Installs in /opt/local; port select can be used to switch among compiler versions (including system compilers). Won't interfere with OS upgrades.Disadvantages: Installing ports tends to require an entire software ecosystem. Compilers don't include debugging symbols, which can pose a problem when using a debugger, or installing PETSc. (Sean Farley proposes some workarounds.) Also requires changing PATH. Could interfere with Homebrew and Fink installs. (See this post on SuperUser.)Use HomebrewHomebrew can also be used to install a Fortran compiler.Advantages: Easy to use package manager; installs the same Fortran compiler as in Installing a version that matches system compilers. Only install what you need (in contrast to MacPorts). Could install a newer GCC (4.7.0) stack using the alternate repository homebrew-dupes. Disadvantages: Inherits all the disadvantages from Installing a version that matches system compilers. May need to follow the Homebrew paradigm when installing other (non-Homebrew) software to /usr/local to avoid messing anything up. Could interfere with MacPorts and Fink installs. (See this post on SuperUser.) Need to change PATH. Installs could depend on system libraries, meaning that dependencies for Homebrew packages could break on an OS upgrade. (See this article.) I wouldn't expect there to be system library dependencies when installing gfortran, but there could be such dependencies when installing other Homebrew packages.Use FinkIn theory, you can use Fink to install gfortran. I haven't used it, and I don't know anyone who has (and was willing to say something positive).Other methodsOther binaries and links are listed on the GFortran wiki. Some of the links are already listed above. The remaining installation methods may or may not conflict with those described above; use at your own risk.
_unix.355725
When building bash scripts, I use a lot of readonly, local, and even readonly local when making variables. That can rapidly fill your script and makes the code less readable (and repetitive). Is there a way (like a set flag at the top of the script, or something) to make all variables readonly and/or local by default?With he added caveat is has to work on 3.2.57(1)-release, as Im on macOS.Im pretty sure this isnt possible, but want to make sure.Please dont answer drop bash and use a proper scripting language. I use other scripting languages as well. bash scripts have their place and I like coding them.
Make all variables readonly and local by default in bash
bash;osx;variable
null
_codereview.112751
I'm working an open source project written in Python that is a wrapper to the Pushover API called py_pushover. The main function of this wrapper is the push_message function which allows the user to push a notification. The API has 10 possible parameters with only 3 being required. I've handled those three required with named parameters and the optional parameters using kwargs. Is this the most pythonic way of handling a large amount of parameters?push_message from py_pushover/py_pushover/message.pydef push_message(token, user, message, **kwargs): Send message to selected user/group/device. :param str token: application token :param str user: user or group id to send the message to :param str message: your message :param str title: your message's title, otherwise your app's name is used :param str device: your user's device name to send the message directly to that device :param list device: your user's devices names to send the message directly to that device :param str url: a supplementary URL to show with your message :param str url_title: a title for your supplementary URL, otherwise just the URL is shown :param int priority: message priority (Use the Priority class to select) :param int retry: how often (in seconds) the Pushover servers will retry the notification to the user (required only with priority level of Emergency) :param int expire: how many seconds your notification will continue to be retried (required only with priority level of Emergency) :param datetime timestamp: a datetime object repr the timestamp of your message's date and time to display to the user :param str sound: the name of the sound to override the user's default sound choice (Use the Sounds consts to select) :param bool html: Enable rendering message on user device using HTML data_out = { 'token': token, 'user': user, # can be a user or group key 'message': message } # Support for non-required parameters of PushOver if 'title' in kwargs: data_out['title'] = kwargs['title'] if 'device' in kwargs: temp = kwargs['device'] if type(temp) == list: data_out['device'] = ','.join(temp) else: data_out['device'] = temp data_out['device'] = kwargs['device'] if 'url' in kwargs: data_out['url'] = kwargs['url'] if 'url_title' in kwargs: data_out['url_title'] = kwargs['url_title'] if 'priority' in kwargs: data_out['priority'] = kwargs['priority'] # Emergency prioritized messages require 'retry' and 'expire' to be defined if data_out['priority'] == PRIORITIES.EMERGENCY: if 'retry' not in kwargs: raise TypeError('Missing `retry` argument required for message priority of Emergency') else: retry_val = kwargs['retry'] # 'retry' val must be a minimum of _MIN_RETRY and max of _MAX_EXPIRE if not (_MIN_RETRY <= retry_val <= _MAX_EXPIRE): raise ValueError('`retry` argument must be at a minimum of {} and a maximum of {}'.format( _MIN_RETRY, _MAX_EXPIRE )) data_out['retry'] = retry_val if 'expire' not in kwargs: raise TypeError('Missing `expire` arguemnt required for message priority of Emergency') else: expire_val = kwargs['expire'] # 'expire' val must be a minimum of _MIN_RETRY and max of _MAX_EXPIRE if not(_MIN_RETRY <= expire_val <= _MAX_EXPIRE): raise ValueError('`expire` argument must be at a minimum of {} and a maximum of {}'.format( _MIN_RETRY, _MAX_EXPIRE )) data_out['expire'] = expire_val # Optionally a callback url may be supplied for the Emergency Message if 'callback' in kwargs: data_out['callback'] = kwargs['callback'] if 'timestamp' in kwargs: data_out['timestamp'] = int(time.mktime(kwargs['timestamp'].timetuple())) if 'sound' in kwargs: data_out['sound'] = kwargs['sound'] if 'html' in kwargs: data_out['html'] = int(kwargs['html']) return send(_push_url, data_out=data_out)send from py_pushover/py_pushover/_base.pydef send(url, data_out=None, get_method=False): Sends a request to the selected url with the payload `data_out`. Set `get_method` to True to send as a GET request. Default request is a POST. :param str url: url to send the request to :param dict data_out: payload data to send :param bool get_method: True = GET request; False = POST request (default) :return dict: a dictionary with the json results of the request. if get_method: res = requests.get(url, params=data_out) else: res = requests.post(url, params=data_out) res.raise_for_status() ret_dict = res.json() if 'X-Limit-App-Limit' in res.headers: ret_dict['app_limit'] = res.headers['X-Limit-App-Limit'] if 'X-Limit-App-Remaining' in res.headers: ret_dict['app_remaining'] = res.headers['X-Limit-App-Remaining'] if 'X-Limit-App-Reset' in res.headers: ret_dict['app_reset'] = res.headers['X-Limit-App-Reset'] return ret_dictNote: In order for this code to run properly you'll need to supply an app token and user/group id which is obtained from the Pushover site. Creating an application is free, but registering a device to send a message to isn't. There is, however, a free trial period of 7 days.
Messaging API client function with many possible parameters
python
null
_unix.25527
Is it possible to follow a binary file from the beginning, a la tail -f?This is useful in some cases, for example if I'm scping a file to a remote server, and at the same time I want to feed it to another process (yes, I know I can use ssh+cat tricks).As far as I read from the FM, tail is written having text files in mind.Is there any simple way of doing such operations using standard posix tools?
How to follow (a la tail -f) a binary file from the beginning?
text processing;tail;binary
tail works with binary data just as well as with text. If you want to start at the very beginning of the file, you can use tail -c +1 -f.
_unix.319819
I'm new to linux administration and am trying to configure VSFTPD on my CentOS server to give me ftp access to the /root folder. Currently, I have access to folders in the parent directory, but not that one in particular. When trying to access /root through my ftp client I get the following:`Server said: Failed to change directory.Error -125: remote chdir failed`I can access root through as a root user through my terminal. Here are the VSFTPD config settings #nopriv_user=ftpsecure## Enable this and the server will recognise asynchronous ABOR requests. Not# recommended for security (the code is non-trivial). Not enabling it,# however, may confuse older FTP clients.#async_abor_enable=YES## By default the server will pretend to allow ASCII mode but in fact ignore# the request. Turn on the below options to have the server actually do ASCII# mangling on files when in ASCII mode.# Beware that on some FTP servers, ASCII support allows a denial of service# attack (DoS) via the command SIZE /big/file in ASCII mode. vsftpd# predicted this attack and has always been safe, reporting the size of the# raw file.# ASCII mangling is a horrible feature of the protocol.#ascii_upload_enable=YES#ascii_download_enable=YES## You may fully customise the login banner string:ftpd_banner=Welcome to ViceCraft FTP service.## You may specify a file of disallowed anonymous e-mail addresses. Apparently# useful for combatting certain DoS attacks.#deny_email_enable=YES# (default follows)#banned_email_file=/etc/vsftpd/banned_emails## You may specify an explicit list of local users to chroot() to their home# directory. If chroot_local_user is YES, then this list becomes a list of# users to NOT chroot().chroot_local_user=YES#chroot_list_enable=YES# (default follows)#chroot_list_file=/etc/vsftpd/chroot_list## You may activate the -R option to the builtin ls. This is disabled by# default to avoid remote users being able to cause excessive I/O on large# sites. However, some broken FTP clients such as ncftp and mirror assume# the presence of the -R option, so there is a strong case for enabling it.#ls_recurse_enable=YES## When listen directive is enabled, vsftpd runs in standalone mode and# listens on IPv4 sockets. This directive cannot be used in conjunction# with the listen_ipv6 directive.listen=YES## This directive enables listening on IPv6 sockets. To listen on IPv4 and IPv6# sockets, you must run two copies of vsftpd with two configuration files.# Make sure, that one of the listen options is commented !!#listen_ipv6=YESlocal_root=/pam_service_name=vsftpduserlist_enable=YEStcp_wrappers=YES
Unable to access /root in CentOS server with ' VSFTPD'
centos;vsftpd
null
_unix.116498
ls -la .will show this in it:insgesamt 1312drwxrwxr-x 6 ruben rubo77 4096 Feb 23 06:20 .drwxrwxr-x 23 ruben rubo77 4096 Feb 6 21:48 .....But it will show the whole content of the folder too. I could narrow the output with head and tail:ls -la .|head -n 2|tail -n 1But isn't there an option in ls to show only the current directory you are in?
List the file permissions of only the current directory
bash;directory
No argument to ls necessary, the -d option alone together with -l will dols -ld
_codereview.172198
I've created a simple Node script to read the IPv6 addresses of an interface and update a CloudFlare hostname with those addresses. I've designed it so that it can be activated via an instantiated systemd service that detects when the IP address changes.Here is the script:#!/usr/bin/env nodeconst os = require('os');const Cf = require('cloudflare4');const request = require('request-promise');const argv = require('yargs') .usage('Usage: $0 -c [configuration file]') .alias('c', 'config') .demandOption(['c']) .describe('c', 'path to configuraiton file') .alias('i', 'interface') .describe('i', 'Override the interface declared in the configuration file') .boolean('s') .default('s', false) .describe('s', 'skip updating of host') .help('h') .alias('h', 'help') .argv;const config = require(argv.c);if (argv.i) { config.interface = argv.i;}const cf = new Cf({ email: config.email, key: config.key,});const IPv4 = { name: 'IPv4', type: 'A', locator: getIPv4Address,};const IPv6 = { name: 'IPv6', type: 'AAAA', locator: getIPv6Address,};updateAddressesByFamily(IPv6);updateAddressesByFamily(IPv4);function updateAddressesByFamily(family) { const remoteAddressPromise = cf.zoneDNSRecordGetAll(config.zone, { type: family.type, name: config.name, }); const localAddressPromise = family.locator(); Promise.all([remoteAddressPromise, localAddressPromise]).then((result) => { const [remoteAddresses, localAddresses] = result; logAddresses(remoteAddresses.map(a => a.content), `Remote ${family.name} Addresses`); logAddresses(localAddresses, `Local ${family.name} Addresses`); const staleAddresses = remoteAddresses.filter(address => !localAddresses.includes(address.content)); logAddresses(staleAddresses.map(a => a.content), `Stale ${family.name} Addresses`); const newAddresses = localAddresses.filter(address => !remoteAddresses.map(a => a.content).includes(address)); logAddresses(newAddresses, `New ${family.name} Addresses`); const removalPromises = argv.s ? [] : staleAddresses.map(address => cf.zoneDNSRecordDestroy(config.zone, address.id)); const additionPromises = argv.s ? [] : newAddresses.map(address => cf.zoneDNSRecordNew(config.zone, { type: family.type, name: config.name, content: address, ttl: 1, })); return Promise.all([...removalPromises, ...additionPromises]); }).then(() => { console.log(`Successfully updated ${family.name} addresses`); }).catch((error) => { console.error(`Unable to update ${family.name} addresses: ${error}`); });}function getIPv4Address() { const options = { uri: 'https://ipinfo.io/json', json: true, }; return request.get(options).then(response => [response.ip]);}function getIPv6Address() { const networkInterface = os.networkInterfaces()[config.interface]; if (!networkInterface) return Promise.reject(`Unknown interface ${config.interface}`); const addresses = networkInterface.filter(x => x.family === IPv6.name && x.scopeid === 0).map(x => x.address); return Promise.resolve(addresses);}function logAddresses(addresses, label) { if (label) { console.log(`${label}: `); } console.log(`\t${addresses.sort().join(',\n\t')}`);}Here is the systemd service file:[Unit]Description=Update CloudFlare with latest IP addresses from %IBindsTo=sys-subsystem-net-devices-%i.deviceAfter=sys-subsystem-net-devices-%i.deviceWants=network-online.targetAfter=network-online.target[Service]Type=oneshotRemainAfterExit=yesExecStart=/usr/local/bin/ddns-cloudflare -c /path/to/config.json -i %I[Install]WantedBy=multi-user.target
Node.js script and systemd service to update CloudFlare on IP address change
javascript;node.js;ip address
null
_webapps.41980
I experience this annoying effect and I don't understand if the problem is of the OS (OS X), the browser (Chrome), the Flash player, or YouTube itself. Everything is upgraded to the latest version, with the exception of OS X (10.6.8).What happens is the following: when a movie is playing, the moving circle cursor indicating the position is always followed (or preceded, your choice) by a light grey area of buffering. I can freely move the cursor within this area by clicking in any position, and the movie will correctly go to that position, but if I try to click to an area that is still not buffered (dark grey), the cursor will move there for a brief interval and then immediately bounce back to the end of the available buffer (the end of the grey area). Occasionally, if I either drag the cursor instead of clicking, or if I pause the movie and then move the cursor, it will behave as I expect (starting the movie from the position I choose) but this is rare.Am I the only one experiencing this? How can I fix it?
Skipping to position in YouTube player is apparently limited to buffered data
google chrome;flash;youtube
null
_unix.91586
This is where I spent much time to know why I'm unable to connect to my local box from my own remote server (VPS); seems to be my local box's IP address issue.To begin with, let me 1st tell how I operate in Internet.I connect my laptop with my cellphone Nokia N73 having Vodafone SIM card. This way (dial-up) my laptop is connected to Internet.Regarding the remote server (VPS), I purchased it from http://lvpshosting.com/.They provide 100 Mb/s net speed.I have remote's IP address. I ssh it and connect. Now, to connect from there to my local, I need my local IP add. So, checked my IP executing ifconfig on my local box. Please see the output below:ravbholua@ravbholua-Aspire-5315:~$ ifconfigeth0 Link encap:Ethernet HWaddr 00:1b:38:d0:45:ea UP BROADCAST MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) Interrupt:18 lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:65536 Metric:1 RX packets:493 errors:0 dropped:0 overruns:0 frame:0 TX packets:493 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:85372 (85.3 KB) TX bytes:85372 (85.3 KB)ppp0 Link encap:Point-to-Point Protocol inet addr:10.224.108.37 P-t-P:10.6.6.6 Mask:255.255.255.255 UP POINTOPOINT RUNNING NOARP MULTICAST MTU:1500 Metric:1 RX packets:4848 errors:0 dropped:0 overruns:0 frame:0 TX packets:5375 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:3 RX bytes:2352345 (2.3 MB) TX bytes:698847 (698.8 KB)From here, I suppose it to be 10.224.108.37. But when using this from remote, it doesn't work to connect to my local box.I have tried using the following for my local IP address.http://www.ipchicken.com/http://whatismyip.org/These 2 links gave IP address but none worked. As someone told that the address given by these 2 links are of my cell phone and not of my laptop. Also when I connect to my remote from local via ssh, then when I log in to my remote, the remote server messages as seen below:ravbholua@ravbholua-Aspire-5315:~$ ssh rsravbholua@rs's password: Welcome to Ubuntu 13.04 (GNU/Linux 2.6.32-042stab076.5 i686) * Documentation: https://help.ubuntu.com/No mail.Last login: Tue Sep 10 08:04:49 2013 from 123.63.112.140This IP address as mentioned above is similar to what I get from the 2 links above. (And is not the one given by command ifconfig.)So, one told me that the remote server displays the IP of the cell phone which is acting as a router and your local machine is not reachable. But I couldn't get any further solution on how my local box would be reached.Please have a note here that I had posted this query on a different site (mentioned below), but couldn't get solution. It would be very useful if one please have a look at that thread of mine in that forum:http://www.linuxquestions.org/questions/linux-networking-3/not-able-to-do-password-free-access-to-remote-machine-4175475825/Much of my other related tasks are pending due to this issue. I am too hopeful from this site as a few other earlier unsolved queries of mine got solved in this site.
Not able to access my local machine from remote server; what's my local IP address?
ssh;ip;mobile
null
_softwareengineering.81743
I will not bother you with details of my discussion so I will present it in the form of a short instance.A java guy has been following articles and publications of a famous programmer (a kind of Martin Fowler of my country). He says that he is sharing some secrets which other famous programmers don't share.I never believe that there are some secrets like wizards in the programming area. But some programmers who are not good yet in this area think that other famous programmers are success because they know some secrets that we don't. I totally disagree with this and I discussed it with someone and finally he said to me you are 2 years in this area and he (java guy) is 20 years professional programmer so he knows better than you.I wanted to be sure that I am not wrong. That's why I wanted to know this.
Do some programmers know some secrets that we others don't?
skills;knowledge
null
_codereview.26242
I just wrote my first Java database program for the purpose of getting feedback on the implementation and coding. It has 1 table and 2 buttons and prompts the user to select a folder, lists the contents of the folder in the table and lists the hash of the files in the table and writes it to a database.It works fine, but I have no idea if I coded it cleanly and split the program into the proper packages and classes. It's definitely a beginner level project so there is nothing too complex about it. I'm also using the h2 database because I was told its the most efficient for small databases. Could you all please give me feedback on this?I used NetBeans 7.3 and uploaded the full project here. This is the class I'm using for the database. It contains most of the code I have in question, but there are other parts of the project as a whole I'm concerned if they were organized correctly:public class CDatabaseLayer { private static ArrayList<CFileObject> fileList = new ArrayList(); private static Server server; private static JdbcDataSource ds = new JdbcDataSource(); private static Connection conn; private static int lastId = 0; private static Statement stat; private static ResultSet rs; private static String query; static public ArrayList<CFileObject> getFileList() { connectDatabase(); return fileList; } static public boolean connectDatabase() { System.out.println(Attempting to connect to database.); if(server == null) { try { server = Server.createTcpServer(); server = server.start(); } catch (SQLException ex) { System.out.println(connectDatabase createTcpServer() exception: +ex); return false; } } //return false if connected if(conn != null) { System.out.println(Already established DB connection.); return false; } else { try { //connect to database ds.setURL(jdbc:h2:test); ds.setUser(sa); ds.setPassword(); conn = ds.getConnection(); if(conn.isClosed()) { System.out.println(Connection not established.); } else { System.out.println(Connected.); createFileListTable(); loadFileListTable(); } } catch (SQLException ex) { System.out.println(connectDatabase getConnection() exception: +ex); } } return true; } static private void loadFileListTable() { try { stat = newStatement(); rs = stat.executeQuery(select * from fileList); fileList.clear(); while(rs.next()) { CFileObject objF = new CFileObject(); objF.fileName = rs.getString(fileName); objF.filePath = rs.getString(filePath); objF.fileHash = rs.getString(fileHash); fileList.add(objF); } } catch (SQLException ex) { System.out.println(loadFileListTable exception: +ex); } } static public void manipulateFiles() throws SQLException { try { if(conn.isClosed()) { System.out.println(manipulateFiles: Connection is closed.); } } catch (SQLException ex) { System.out.println(manipulateFiles connection exception: +ex); } for(CFileObject f : fileList) { String hash = new String(); try { hash = hashFile.getMD5Checksum(f.filePath); } catch (Exception ex) { System.out.println(manipulateFiles hash exception: +ex); } f.fileHash = hash; query = update filelist set filehash = '+hash+' where filepath = '+f.filePath+'; stat = newStatement(); //QUESTION: Why does this return false?? stat.execute(query); } } static public void updateDatabaseWithFilesFromPath(File path) { ArrayList<CFileObject> list; list = CFileObject.getListFromPath(path); for(CFileObject file : list) { if(!entryExists(filelist, filepath, file.filePath)) { try { lastId = nextUnusedId(); addFileEntry(lastId, file.fileName, file.filePath); fileList.add(file); } catch (SQLException ex) { System.out.println(updateDatabaseWithFilesFromPath exception: +ex); } } } } /* static public void updateDatabase() throws SQLException { lastId = nextUnusedId(); for (final CFileObject file : fileList) { if(!entryExists(filelist, filepath, file.filePath)) { lastId = nextUnusedId(); addFileEntry(lastId, file.fileName, file.filePath); } } } */ private static Statement newStatement() { try { stat = conn.createStatement(); return stat; } catch (SQLException ex) { System.out.println(newStatement exception: +ex); } return null; } //QUESTION: Is there a more efficient way to do this? private static void createFileListTable() { try { //see if fileList table exists. if not, catch error and create it try { stat = newStatement(); stat.executeQuery(select * from fileList); } catch(SQLException e) { if(e.toString().contains(Table \FILELIST\ not found)) { System.out.println(Creating filelist table.\n); stat.execute(create table filelist(id int primary key, fileName varchar(255), filePath varchar(512), fileHash varchar(32))); } else { System.out.println(e); } } } catch(SQLException ex) { System.out.println(createFileListTable exception: +ex); } } private static int nextUnusedId() { try { stat = newStatement(); rs = stat.executeQuery(select id from fileList); if(rs.last()) { lastId = rs.getInt(id); lastId++; } } catch (SQLException ex) { System.out.println(nextUnusedId exception: +ex); } return lastId; } private static boolean entryExists(String table, String prop, String val) { try { stat = newStatement(); query = select 1 from +table+ where +prop+ = '+val+'; rs = stat.executeQuery(query); return rs.last(); } catch (SQLException ex) { System.out.println(entryExists exception: +ex); } return true; } private static void addFileEntry(int entryId, String fileName, String filePath) throws SQLException { query = insert into fileList values(+entryId+, '+fileName+', '+filePath+', 0); stat = newStatement(); //QUESTION: Why does this return false?? stat.execute(query); } static public void disconnectDatabase() { server.stop(); }}
Basic Java database
java;database
This is what I noticed after taking a quick look:I'm not a big fan of the static/singleton-ness of this class. Those attributes make this class harder to mock and unit test. Take a look at POJO/dependency injection (you don't need a container to do DI).I would consider separating the database/Connection opening stuff into its own class. There should be separation of what the data access/service layer from the resource/connection code. Take a look at DAO/Service patterns.getFileList() returns a concrete List implementation instead of the List interface.A lot of your methods don't close the ResultSet and Statement objects once they are done with them. They should be closed in finally blocks.Your catch blocks aren't doing much besides printing to System.out. You need to either handle recoverable exceptions there or propogate them up the stack as a RuntimeException.Not sure why you need newStatement().You are manually creating and executing SQL strings. This is a bad idea. Replace these with PreparedStatements.This class isn't threadsafe. It should be documented as much.
_datascience.20102
Have a dataset of a E-learning company which have information related to the students demographics, package, payment info, services used, class or grade (KG to 12), login details. If you want i can share the sample data set.Could anyone help me out in understanding what business value can be derived from this data. I am really confused. I did some analysis was able to find out the max service consumption. Any help would be appreciated
Analysis of data E-learning website
machine learning;r;predictive modeling
null
_softwareengineering.258514
Looking into DDD and something I noticed is that business logic should be in the model, otherwise you just have property bags. That said how do you handle pieces of validation that require a trip to the database?For example, you have an domain object that represent categories for a blogging engine.public class Category{ public int Id { get; set; } public string Name { get; set; }}From a developer's perspective, you could create an empty category, but this isn't valid in the business world. A Category requires a Name to be a valid category, therefore we end up with:public class Category{ public int Id { get; set; } public string Name { get; set; } public Category(string name) { Name = name; }}Now, a Category can't be created without a name. But, we can't have duplicate Category names either, that would just cause confusing and redundancy. I don't want the entity to handle it themselves because this would end up more of an Active Record Pattern and I don't want the model to be self-aware/persisting so to speak.So to this point, where should this validation take place. It is important that if the user types an duplicate Category, we would notify the user of this. Should there be a service layer that takes a UI model and turns it into the domain model and attempts to validate it, pushing errors back to the UI, or should there be something closer to the data layer that handles this?Someone please set me straight because I really like where DDD is going, I just can't make all the connections to get there myself.
Domain Model, validation, and pushing errors to the model
domain driven design;validation;layers
null
_unix.295606
I want to reduce the big file (*.jar) in unix.i have tried with tar,bzip,gzip and zip commands. but all are same result not compressed much.Could any one help on this ???
Reduce a size of a file(.jar) in unix
zip;compression
null
_unix.5107
I understand that Spinlocks are real waste in Linux Kernel Design.I would like to know why is it like spin locks are good choices in Linux Kernel Design instead of something more common in userland code, such as semaphore or mutex?
Why are spin locks good choices in Linux Kernel Design instead of something more common in userland code, such as semaphore or mutex?
linux;semaphore;spinlock
The choice between a spinlock and another construct which causes the caller to block and relinquish control of a cpu is to a large extent governed by the time it takes to perform a context switch (save registers/state in the locking thread and restore registers/state in another thread). The time it takes and also the cache cost of doing this can be significant. If a spinlock is being used to protect access to hardware registers or similar where any other thread that is accessing is only going to take a matter of milliseconds or less before it releases the lock then it is a much better use of cpu time to spin waiting rather than to context switch and carry on.
_unix.351554
How to know which custom coded language(c,c++,java) has been used in a application which is running in a production server or any server where only binary/executable files are there ?
How to know custom coded language
application
null
_codereview.78631
IntroductionI've written a simple command line todo-list in Haskell.The full code can be found here. However, given people's time constraints, I have selected three verbose functions for review.Function Oneprogram :: StateT TodoList IO ()program = do StateT $ \xs -> do (choice,_) <- runStateT requestChoice xs (_,xs') <- runStateT (parseChoice choice) xs runStateT printList xs' runStateT program xs'main = runStateT program []Questions:Am I repeating myself too much by extracting the monads using runStateT?Is there a better way to structure the main program? Function TwoparseChoice :: Text -> StateT TodoList IO ()parseChoice choice | first == add = addItem $ TodoItem second third | first == remove = removeItem $ parseInt second | first == save = saveList second | first == load = loadList second | first == quit = StateT $ \_ -> exitSuccess | otherwise = invalidChoice first where args = split (=='|') (toLower choice) first = head args second = if length args > 1 then args !! 1 else third = if length args > 2 then args !! 2 else Questions:Am I using too many guards?Function ThreeremoveItem :: Maybe Int -> StateT TodoList IO ()removeItem mn = StateT remove where remove = \xs -> case mn of Just n -> if n <= length xs - 1 then return ((),removeAt n xs) else do S.putStrLn Index too large return ((),xs) Nothing -> do S.putStrLn Invalid index entered return ((),xs)General QuestionsWhich parts are un-idiomatic?Which parts are superfluous?Should I decompose these longer functions into smaller functions that do less?How else can I improve this code?
Simple command line todo-list
haskell
It seems like you may not quite grasp the interplay between do-notation and monad transformer stacks. Take a look at how I've rewritten program here to leverage the actual machinery of StateT. The version you wrote is needlessly verbose due to your manually plumbing the state around!program :: StateT TodoList IO ()program = do choice <- requestChoice parseChoice choice printList programparseChoice can be cleaned up by favoring pattern matching over guards. Whenever you see a wall of guards that depend only on Eq, consider pattern matching instead.parseChoice :: Text -> StateT TodoList IO ()parseChoice choice = case split (== '|') (toLower choice) of [add, date, message] -> addItem $ TodoItem date message [remove, index] -> removeItem $ parseInt index [save, file] -> saveList file [load, file] -> loadList file [quit] -> lift exitSuccess (invalid:_) -> invalidChoice invalidI think you can probably guess what can change about removeItem after reading my other changes now, so before reading this next code block try rewriting it on your own.removeItem :: Maybe Int -> StateT TodoList IO ()removeItem Nothing = lift $ putStrLn Invalid index enteredremoveItem (Just n) = modify (removeAt n)
_unix.243487
I am working with the raw source content of a mail.app message in OSX, but results it gives me the text in quoted printable MIME Email encoding. so I need to remove all those strange characters to get the correct HTML.Here is an example:<p style=3Dmargin:1em 0 3px 0;><a name=3D1 style=3Dfont-family:Arial, Helvetica, sans-serif;font-size:1=8px; href=3Dhttp://feedproxy.google.com/~r/WwwhatsNew/~3/8BdOd-xRTU4/?utm=_source=3Dfeedburner&amp;utm_medium=3Demail>Hyundai ya ofrece manuales de =los coches con Realidad Aumentada</a></p>Here I have =CRLF and =3DI know how to replace all of this characters =C3=A1 =C3=A9 =C3=AD =C3=B3 =C3=BA =C3=81 =C3=89 =C3=8D =C3=93 =C3=9A =C3=B1 =C3=91 =3D =fI just need to delete this =CRLF or '=' followed by a newline.
Regex to match = followed by a newline so they both be deleted
shell script;text processing;regular expression;newlines
Why reinvent the wheel? qprint already exists:Description-en: encoder and decoder for quoted-printable encodingQprint is a command-line program that can encode or decode files from/to quoted-printable encoding (RFC1521). It can work with both text and binary data.Homepage: http://www.fourmilab.ch/webtools/qprint/Sample input:$ cat nadir.txt <p style=3Dmargin:1em 0 3px 0;><a name=3D1 style=3Dfont-family:Arial, Helvetica, sans-serif;font-size:1=8px; href=3Dhttp://feedproxy.google.com/~r/WwwhatsNew/~3/8BdOd-xRTU4/?utm=_source=3Dfeedburner&amp;utm_medium=3Demail>Hyundai ya ofrece manuales de =los coches con Realidad Aumentada</a></p>Sample output:$ qprint -d nadir.txt <p style=margin:1em 0 3px 0;><a name=1 style=font-family:Arial, Helvetica, sans-serif;font-size:18px; href=http://feedproxy.google.com/~r/WwwhatsNew/~3/8BdOd-xRTU4/?utm_source=feedburner&amp;utm_medium=email>Hyundai ya ofrece manuales de los coches con Realidad Aumentada</a></p>qprint is available pre-packaged for most linux distros.There are also several perl modules for encoding & decoding quoted-printable text, including MIME::QuotedPrint and PerlIO::via::QuotedPrint. No doubt, a quick google search would also reveal QP libraries for python and other languages.
_unix.285482
I want to refine an HTML code using sed, as an extra refinement procedure after refining it using HTML Tidy, as HTML Tidy doesnt look flexible enough for some requirements.I used this command to add some tabs and/or line breaks to some tags and remove them from others:s/<li>/\t&/gs/\n<\/li>/<\/li>/gThe first command worked fine unless li has an attribute, so, how can I target an opening tag regardless of whether it has an attribute or not?The second command didnt work at all. I want here to put the closing tag </li> at the end of the previous line.
Adding/removing some tabs and line breaks in an HTML code using sed
sed;newlines;html
Consider this sample file:$ cat sample.html <li a=x>Point One</li><li>Point Two</li>I believe that this sed command does what you ask (this may require GNU sed):$ sed -Ez 's|<li\b|\t<li|g; s|\n</li\b|</li|g' sample.html <li a=x>Point One</li> <li>Point Two</li>How it works-EUse extended regex.-zRead nul-delimited data. Since a proper html file has not nul-characters, this has the effect of reading in the whole file at once.s|<li\b|\t<li|gThis puts a tab in front of every occurrence of <li followed by a word boundary.s|\n</li\b|</li|gThis replaces every occurrence of newline followed by <li followed by a word boundary with <li.A variation: putting <li> on its own line$ sed -Ez 's|<li[^>]*>|&\n|g; s|\n</li\b|</li|g' sample.html<li a=x>Point One</li><li>Point Two</li>Obligatory warninghtml can be complex and these sed commands are only intended to work on simple cases.
_codereview.154270
I have a form that looks like this:It is initialized with a Shortcut from the keyboard. It is in a module:Public Sub ShowMainForm() With frmMain .Show vbModeless End With End SubThe form has a button:Private Sub btnRun_Click() Call MainGenerateReport End SubThe button runs a procedure, called MainGenerateReport in a module.Public Sub MainGenerateReport() ' other code; Call frmMain.MakeLabel ' other code;End SubfrmMain.MakeLabel changes a label in the form with some information:Public Sub MakeLabel() Dim c As Long Dim r As Long Me.lbInfo.Visible = checkNumbers Me.lbInfo.Clear If checkNumbers Then With Me.lbInfo .ColumnCount = 2 .ColumnWidths = CStr(Me.lbInfo.Width / 1.8 & ; & Me.lbInfo.Width / 4) For r = 0 To 7 .AddItem For c = 0 To 1 .List(r, c) = tblInfo.Cells(1 + r, 3 + c) Next c Next r End With End IfEnd SubAt the end, if I want to close the form, I use the Esc key. I have a button on the form, btnExit and its cancel property is set to True:Private Sub btnExit_Click() Unload MeEnd SubThe problem: According to VBA best practices, I should initialize the form like this (and rewrite my MakeLabel and the btnExit_Click accordingly):Public Sub ShowMainForm() With new frmMain .Show vbModeless End With End SubIs that recommended?
Working with a new form instance every time
object oriented;vba;form
Public Sub ShowMainForm() With frmMain .Show vbModeless End With End SubYou don't want that With block, it's redundant.Public Sub ShowMainForm() With New frmMain .Show vbModeless End With End SubYou don't want to do that with a vbModeless form either - the instance will be destroyed quite immediately after being created.For an object-oriented approach that uses a modeless form, I'd suggest you make the form a member of a dedicated presenter class:Option ExplicitPrivate WithEvents summaryForm As frmMain ' <~ notice WithEvents ..I'll get to it.Private Sub Class_Initialize() Set summaryForm = New frmMainEnd SubPrivate Sub Class_Terminate() Set summaryForm = NothingEnd SubPublic Sub Show() If Not summaryForm.Visible Then summaryForm.Show vbModelessEnd SubPublic Sub Hide() If summaryForm.Visible Then summaryForm.HideEnd SubNow, this presenter class shall be responsible for accessing the form; notice how it already hides the implementation detail of the modeless-ness to the outside world.When the user clicks the btnRun button, the form itself shouldn't be responsible for anything - so instead of calling MainGenerateReport directly, we'll fire an event to tell the presenter class that it needs to do something about it:Option ExplicitPublic Event OnRunReport()Public Event OnExit()Private Sub btnRun_Click() RaiseEvent OnRunReportEnd SubPrivate Sub btnExit_Click() RaiseEvent OnExitEnd SubThat way the form has no dependencies to other modules, and pretty much zero responsibilities.Back to the presenter, we can handle these events:Private Sub summaryForm_OnRunReport() MainGenerateReport RefreshEnd SubPrivate Sub summaryForm_OnExit() HideEnd SubPublic Sub Refresh() 'todoEnd SubThis leaves the problem of MakeLabel/Refresh. I don't know what tblInfo is, but I'm pretty sure it's not the form's concern. Really all it needs is some Range or ListObject that contains whatever information needs to go into that list - and instead of looping to .AddItem and explicitly set each .ListItem, you could use the control's .RowSource property and avoid looping altogether; this CR Q&A shows how.Once the presenter class is capable of providing a data source for the form's ListBox (you'll have to verify it it actually binds to the source; if that's the case then you won't even need a refresh button, the list would just update itself).That would be the Refresh implementation.The last step is to instantiate the presenter; as long as the presenter instance is alive, the encapsulated form instance lives - there's no need to explicitly Unload Me anywhere.Say you named the class SummaryPresenter, then you could have it exist in global scope:Option ExplicitPrivate presenter As SummaryPresenterPublic Sub ShowMainForm() ' macro attached to shortcut key If presenter Is Nothing Then Set presenter = New SummaryPresenter presenter.ShowEnd SubSince we made the OnRunReport handler call Refresh after MainGenerateReport runs, the procedure no longer needs to call it explicitly. Or, if it does need to (hard to tell with just a little 'other code; comment to work with), then it can do so by calling the Presenter object's Refresh method:Public Sub MainGenerateReport() ' other code; presenter.Refresh ' other code;End SubThis makes your code use the same instance of frmMain all the time, while separating responsibilities into different [class] modules... which isn't much different from working against the default instance in the first place.But then, everything boils down to why you would want a new instance every time - IMO if the form is a modeless toolwindow that you can show/hide while working in Excel, then it's objectively better (more efficient) to avoid initializing it everytime you want to show it... just like it's more efficient to avoid initializing the listbox columns everytime you refresh it ;-)
_cs.16188
BackgroundA proof-of-work system allows one peer to prove to another peer that a certain amount of computational effort was performed.In a network setting this can be used to throttle peer requests without needing to keep a precise track on the identity of the peers or prior events. The most well known use of proof-of-work is to throttle spam throughput in an email network*.Some proof-of-work systems allow certain roles on the network (say, a mailing list) to calculate the proof of work much faster by using a secret short-cut - typically a pre-calculated trapdoor or a private key depending on the proof-of-work system.HypothesisAny algorithm or a certain class of algorithms can be converted into a proof-of-work version of that algorithm. That is: A deliberately inefficient and incompressible algorithm.Such converted proof-of-work algorithms can support proof-of-work shortcuts.Such converted proof-of-work algorithms can not be converted back to the original algorithm without considerable computational power; if at all.ExtrapolationIf the hypothesis holds, then selected business logic of an application - specifically that which is unique or value-added by that application vs existing applications - could be converted to proof-of-work equivalents.End-users could then be provided such an application; which will run slowly either generally or for certain premium features. The development team however, possesses a secret PoW shortcut and set up a subscription, donation or advertising(!)-based service - an SaaS - for solving the proof-of-work bottleneck for the end-user. The end-user can now choose to run the application slower without the SaaS or faster with the SaaS. This SaaS needs to process considerably less client-side business logic than a general cloud solution (e.g. Diablo 3 style SaaS); as the goal is the speed of execution rather than no execution - and the SaaS proof-of-work speed ratio is tailored accordingly. This is especially relevant for software projects supported by charity as the developers do want the software available to anyone but can encourage donations without needing a separate fairly easy to pirate Freemium edition. The Tragedy of the Commons (freeloading) could be discouraged to a fair extent without guilt-tripping or rat poisoning, by adjusting the proof-of-work cost relative the value of the application or service.Example 1: A commercial stock market estimation tool licensed per month. If the user forgoes paying for a subscription, the estimation occurs at 1% the normal rate.Example 2: A free Triple A co-op video game runs twice fast if the user donates some money once a year.In either example the user must decide between accepting the default speed; spending money on a faster computer/cloud services; or contributing to the upkeep of the product.QuestionDoes the hypothesis hold and has anyone attempted to explore or implement this hypothesis?Any example of an open source library or application that attempts to implement the hypothesis qualifies as a sufficient answer (from my perspective); as I could dissect the code. * Which has a variety of issues for the Digital Divide, but that's another story
Using a proof-of-work system to discourage piracy or encourage donations
time complexity;one way functions;proof of work
null
_unix.258645
I can connect to my universitys server, where I have a virtual machine running on Debian 8.3 (as far as I can see, no additional software is installed yet). I have admin rights and can install new software. Working with ssh isn't a problem. But besides using the shell I'd appreciate having a GUI (like when using RPD, x2go, etc.).I already read about VPS, would this do the job?Is there an easy/fast way to get a working desktop GUI with ssh and using it remotely? Thank you very much for your help in advance.
Setup GUI via ssh
ssh;remote;gui;remote desktop
Yes, using SSH X11-Redirection.man sshhas this to say about it:-X Enables X11 forwarding. This can also be specified on a per-host basis in a configuration file.X11 forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the user's X authorization database) can access the local X11 display through the forwarded connection. An attacker may then be able to perform activities such as keystroke monitoring.For this reason, X11 forwarding is subjected to X11 SECURITY extension restrictions by default. Please refer to the ssh -Y option and the ForwardX11Trusted directive in ssh_config(5) for more information.Try the following:ssh -X yourusername@yourhostname xclockIf this works you can be sure that X11-Redirection works, given xclock is available in the system you're accessing via X11. Now you can just replace xclock with the command for the program you actually want to run.
_cstheory.33953
Edit: I originally defined a regular function as a function computable by a Mealy machine, but Denis pointed out that that was a weaker model than what I was thinking of.So to be more precise, by a finite-state transducer with input alphabet $A$ and output alphabet $B$, I mean a deterministic finite automaton over $(A \cup \{\epsilon\}) \times (B \cup \{\epsilon\})$. In particular, if both of the following hold for a transducer, then the transducer computes a function:Every transition $(q, (x,y), q')$ is uniquely determined by $q$ and $x$;If there is a transition $(q, (\epsilon, x), q')$ for any $x$, then there are no other transitions from state $q$.Feel free to generalize or restrict as desired.Definitions:Let $L$ and $M$ be languages. A regular function $f:L\to M$ is a function computable by a finite-state transducer $A$ such that $(l,m)\in L(A)$ if and only if $l \in L$ and $m=f(L)\in M$. Note that it is decidable whether the relation computed by a given FST is a function. Define the equalizer $Eq(f,g)$ of two regular functions $f,g:A\to B$ as the set of all strings $x\in A$ such that $f(x)=g(x)=y$ for some $y\in B$.Theorem: The equalizer of two regular functions is regular.Proof: Since $f$ and $g$ are regular functions, they are also regular relations. In particular, we can take their intersection $h=f\cap g$. By definition, we have $(x,y)\in h$ if and only if $(x,y)\in f$ and $(x,y)\in g$; in function notation this becomes $(x,y)\in h$ iff $f(x)=g(x)=y$. By the closure properties of regular relations, it follows that $h$ is a regular relation; and since $f$ and $g$ are functions, $h$ is also a function.Since $h$ is a regular relation, it is recognized by some finite state transducer $T$. We can take the input projection $\pi_1 T$, giving us a finite automaton which accepts a string $x$ if and only if $(x,y)\in h$ for some $y$. Let $E$ denote the language of the automaton $\pi_1 T$. By the definitions of $h$, $f$, and $g$, it follows that $x\in E$ if and only if $x\in A$ and $f(x)=g(x)=y$ for some $y\in B$. $\square$But wait. Suppose $A$ is the set of all nonempty strings $\Sigma^+$ over some alphabet $\Sigma$, and suppose $f$ and $g$ are homomorphisms (every homomorphism is a regular function.) Then we can take the equalizer $P=Eq(f,g)$, which is regular by the above theorem.Now $P$ will be nonempty iff there is a string $x\in \Sigma^+$ such that $f(x)=g(x)$. In other words, $P$ encodes the Post correspondence problem (PCP) for $f$ and $g$. But since $P$ is regular, it is recognized by some finite automaton, and emptiness is decidable for finite automata. Since intersection and projection are computable constructions on transducers, we therefore have a method to solve PCP given the transducers for the homomorphisms $f$ and $g$. But this is impossible since PCP is undecidable. So where am I wrong?
Are equalizers of regular functions always regular languages? (My guess is no because PCP, but...)
fl.formal languages;automata theory;proofs;undecidability;post correspondence
The problem is in your assumption that rational relations are closed under intersection. The following counter-example is taken from Example 2.5 in Berstel's Transductions and Context-Free Languages:Let $X, Y \subseteq \{a\}^* \times \{b,c\}^*$ be rational relations defined by\begin{align*} X ={}& \{ (a^n, b^n c^k) \mid n,k \geq 0 \} \\ Y ={}& \{ (a^n, b^k c^n) \mid n,k \geq 0 \} \end{align*}They are rational since $X = (a,b)^* (1,c)^*$ and $Y=(1,b)^*(a,c)^*$. But the intersection$$ Z = X \cap Y = \{ (a^n, b^n c^n) \} $$is not rational. If there was a transduction $\tau : \{a\}^* \to \mathcal{P}(\{b,c\}^*)$ realizing $Z$, then since transductions preserve regular languages, the language $\tau(a^*) = \{b^n c^n\}$ would be regular, a contradiction.
_unix.184182
The spec file is present inside the source directory. The specfile build section looks like%buildcd ~/path/sourcesmakeIf the spec file path can be detected then the hardcoding of the ~/path/sources can be avoided. How to get the spec file path.
How to get spec file path within rpm spec file
rpmbuild
null
_cstheory.19191
I am interested to study Graph Isomorphism (GI) complete problems.In the Paper Problems Polynomially Equivalent to Graph Isomorphism by Kellogg S. Booth, (1979), proved that many basic problems are GI complete by using Edge replacement techniques, Composition techniques etc. I would like to learn some more techniques which are used in recent papers.Can some one suggest me some recent papers which are more concentrated in proving some graph class is GI complete.
On Graph Isomorphism Complete Problems
cc.complexity theory;reference request;graph isomorphism
Graph Isomorphism Completeness for Perfect Graphsand Subclasses of Perfect GraphsC. Boucher D. Loker (2006)In this paper, we prove that deciding isomorphism of double split graphs, the class of graphs exhibiting a 2-join, and the class of graphs exhibiting a balanced skew partition are GI-complete. Further, we show that the GI problem for the larger class including these graph classesthat is, the class of perfect graphsis also GI-complete.
_unix.39722
I want to backup 1 terabyte of data to an external disk.I am using this command: tar cf /media/MYDISK/backup.tar mydataPROBLEM: My poor laptop freezes and crashes whenever I use 100% CPU or 100% disk (if you want to react about this please write here).So I want to stay at around 50% CPU and 50% disk max.My question: How to throttle CPU and disk with the tar command?Rsync has a --bwlimit option, but I want an archive because 1) there are many small files 2) I prefer to manage a single file rather a tree. That's why I use tar.
Preventing tar from using too much CPU and disk (old laptop crashes if 100%)
tar;limit
You can use pv to throttle the bandwidth of a pipe. Since your use case is strongly IO-bound, the added CPU overhead of going through a pipe shouldn't be noticeable, and you don't need to do any CPU throttling.tar cf - mydata | pv -L 1m >/media/MYDISK/backup.tar
_webapps.97531
I have data that was generated from a Google Form. The data has two parts: first a list of items the recipient checked, and second a score they gave (1-10). I would like to find the average score per item that was checked. Here is some sample data:Ultimately I want the result in this form:If I had a temporary table that looks like this:then I would be able to compute my final answer. I used this answer to write the query =QUERY(E2:F10, SELECT E, AVG(F) GROUP BY E LABEL E 'Reason', AVG(F) 'Average')I'm able to create almost what I want, but not quite. This is the closest I've gotten:Which I can get using: =ArrayFormula(QUERY(TRANSPOSE(ARRAYFORMULA(Trim(SPLIT(LOWER(CONCATENATE($A$2:$B$5&,)),,))))&{,},select Col1,0))You can find all of this sample data here.Would you please help me, either by transforming the data to be in the form I ultimately want it in (with the averages), or by helping me to create the temporary table in between?
How can I assign a single cell to the split out contents of it's neighbor?
google spreadsheets
I added a sheet called SO Test - Aurielle where you can view my resultsSo here is my suggestions - it requires 2 formulas and you would need to copy one of the formulas down as needed but otherwise its pretty simple:In column A you enter this formula:=UNIQUE(ARRAYFORMULA(TRIM(TRANSPOSE(SPLIT(JOIN(,,Sheet1!A:A),,)))))What I am doing here is first joining all the values with a common delimiter, in this case a , so it creates one long string, then splitting by that same delimiter to create a long list of all possible keywords. I use trim to clean it up and remove any unnecessary formatting, or space.I then use UNIQUE to get a list of all possible keywords.In Column B i entered: =AVERAGEIF(ARRAYFORMULA(REGEXMATCH(Sheet1!A:A,A2)),true,Sheet1!B:B)What this does is check each value in column A to see if it contains the keyword to the left of it, REGEXMATCH is great for this because it globally checks whether that word is at all contained in the original string, ignoring any other characters or punctuation. By using ARRAYFORMULA it converts the values to true or false, so if you were to expand and just show that formula by itself, it would say true,false,true, true, because food is contained in the 1st string, but not the 2nd, and is in the 3rd and 4th.Using AVERAGEIF, we use that array as the condition to check, but direct it to the column next to it, as the condition to average.
_unix.350352
I have 2 similar files (dos.txt and unix.txt) with text The quick brown fox jumps\n over the lazy dog. that differ by line endings. When I search for a word at the end of line, output from dos.txt is empty:$ grep -E 'jumps^M?$' dos.txt unix.txtunix.txt:The quick brown fox jumpsGrep finds something but doesn't print it. Actual output from grep looks like this:$ grep -E --color=always 'jumps^M?$' dos.txt unix.txt | cat -v^[[35m^[[Kdos.txt^[[m^[[K^[[36m^[[K:^[[m^[[KThe ... ^[[01;31m^[[Kjumps^M^[[m^[[K^[[35m^[[Kunix.txt^[[m^[[K^[[36m^[[K:^[[m^[[KThe ... ^[[01;31m^[[Kjumps^[[m^[[KSo it looks like the only difference is that ^M is inside colored output and it causes whole line to disappear. How can I fix this (without converting dos files using dos2unix or similar tools)?
grep --color=auto breaks when ^M is inside colored match
grep;colors
After some searching for ^[[K escape sequence, reading half of a book about VT100 terminal and checking man grep I have found that setting environment variable GREP_COLORS toGREP_COLORS=neGives desired output:$ export GREP_COLORS=ne$ grep -E --color=always 'jumps^M?$' dos.txt unix.txtdos.txt:The quick brown fox jumpsunix.txt:The quick brown fox jumps$ grep -E --color=always 'jumps^M?$' dos.txt unix.txt | cat -v^[[35mdos.txt^[[m^[[36m:^[[mThe ... ^[[01;31mjumps^M^[[m^[[35munix.txt^[[m^[[36m:^[[mThe ... ^[[01;31mjumps^[[mFrom grep man page:ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted).In my case it works good even if I set highlight color to something that change background:export GREP_COLORS=ne:mt=41;38Now the interesting question is why ^[[K produces this blank line.Character ^M means carriage return without going to next line:$ echo -e start^Mendendrt^[[K clears line from cursor to right and then writes rest of line:$ echo -e start\033[KendstartendHowever when you put ^M before ^[[K it removes content:$ echo -e start^M\033[KendendAfter writing start cursor goes to the beginning of line then ^[[K removes everything and rest of the line is written. In case of grep output first line writes everything up to word jumps, then goes back to beginning of line ^M, writes harmless ^[[m sequence and ^J that goes to new line. This is why ^[[K after ^M clears whole line.
_codereview.5545
(Originally posted on Stack Overflow)Following my findings and suggestions in my other post How to exclude a list of full directory paths in find command on Solaris, I have decided to write a Perl version of this script and see how I could optimize it to run faster than a native find command. So far, the results are impressive!The purpose of this script is to report all unowned files and directories on a Unix system for audit compliance. The script has to accept a list of directories and files to exclude (either by full path or wildcard name), and must take as little processing power as possible. It is meant to be run on hundreds of Unix system that we (the company I work for) support, and has be able to run on all those Unix systems (multiple OS, multiple platforms: AIX, HP-UX, Solaris and Linux) without us having to install or upgrade anything first. In other words, it has to run with standard libraries and binaries we can expect on all systems.I have not yet made the script argument-aware, so all arguments are hard-coded in the script. I plan on having the following arguments in the end and will probably use getopts to do it:-d = comma delimited list of directories to exclude by path name-w = comma delimited list of directories to exclude by basename or wildcard-f = comma delimited list of files to exclude by path name-i = comma delimited list of files to exclude by basename or wildcard-t:list|count = Defines the type of output I want to see (list of all findinds, or summary with count per directory)Here is the source I have done so far:#! /usr/bin/perluse strict;use File::Find;# Full paths of directories to prunemy @exclude_dirs = ('/dev','/proc','/home');# Basenames or wildcard names of directories I want to prunemy $exclude_dirs_wildcard = '.svn';# Full paths of files I want to ignoremy @exclude_files = ('/tmp/test/dir3/.svn/svn_file1.txt','/tmp/test/dir3/.svn/svn_file2.txt');# Basenames of wildcard names of files I want to ignoremy $exclude_files_wildcard = '*.tmp';my %dir_globs = ();my %file_globs = ();# Results will be sroted in this hashmy %found = ();# Used for storing uid's and gid's present on systemmy %uids = ();my %gids = ();# Callback function for findsub wanted { my $dir = $File::Find::dir; my $name = $File::Find::name; my $basename = $_; # Ignore symbolic links return if -l $name; # Search for wildcards if dir was never searched before if (!exists($dir_globs{$dir})) { @{$dir_globs{$dir}} = glob($exclude_dirs_wildcard); } if (!exists($file_globs{$dir})) { @{$file_globs{$dir}} = glob($exclude_files_wildcard); } # Prune directory if present in exclude list if (-d $name && in_array(\@exclude_dirs, $name)) { $File::Find::prune = 1; return; } # Prune directory if present in dir_globs if (-d $name && in_array(\@{$dir_globs{$dir}},$basename)) { $File::Find::prune = 1; return; } # Ignore excluded files return if (-f $name && in_array(\@exclude_files, $name)); return if (-f $name && in_array(\@{$file_globs{$dir}},$basename)); # Check ownership and add to the hash if unowned (uid or gid does not exist on system) my ($dev,$ino,$mode,$nlink,$uid,$gid) = stat($name); if (!exists $uids{$uid} || !exists($gids{$gid})) { push(@{$found{$dir}}, $basename); } else { return }}# Standard in_array perl implementationsub in_array { my ($arr, $search_for) = @_; my %items = map {$_ => 1} @$arr; return (exists($items{$search_for}))?1:0;}# Get all uid's that exists on system and store in %uidssub get_uids { while (my ($name, $pw, $uid) = getpwent) { $uids{$uid} = 1; }}# Get all gid's that exists on system and store in %gidssub get_gids { while (my ($name, $pw, $gid) = getgrent) { $gids{$gid} = 1; }}# Print a list of unowned files in the format PARENT_DIR,BASENAMEsub print_list { foreach my $dir (sort keys %found) { foreach my $child (sort @{$found{$dir}}) { print $dir,$child\n; } }}# Prints a list of directories with the count of unowned childs in the format DIR,COUNTsub print_count { foreach my $dir (sort keys %found) { print $dir,.scalar(@{$found{$dir}}).\n; }}# Call it all&get_uids();&get_gids();find(\&wanted, '/');print List:\n;&print_list();print \nCount:\n;&print_count();exit(0);If you want to test it on your system, simply create a test directory structure with generic files, chown the whole tree with a test user you create for this purpose, and then delete the user.I'll take any hints, tips or recommendations you could give me.
How can I further optimize this Perl script for finding all unowned files and directories on Unix?
perl;file system;unix
null
_unix.367762
My script with the addition function will not execute the add operator (+) with two variables that I assign numeric values based on read. The other functions will work fine using the other operators.Script:#!/bin/bash function addition { FNUM1=$1 FNUM2=$2 RESULT=$((FNUM1+FNUM2)) echo RESULT: $RESULT } function subtraction { FNUM1=$1 FNUM2=$2 RESULT=$((FNUM1-FNUM2)) echo RESULT: $RESULT } function multiplication { FNUM1=$1 FNUM2=$2 RESULT=$((FNUM1*FNUM2)) echo RESULT: $RESULT } function division { FNUM1=$1 FNUM2=$2 RESULT=$((FNUM1/FNUM2)) echo RESULT: $RESULT } clearecho Please select a calculation to make! echo Choose how to you want to calculate two numbersCOUNTER=0 while [ $COUNTER -eq 0 ] do echo echo 1 - addition echo 2 - subtraction echo 3 - multiplication echo 4 - division echo 5 - QUIT read CHOICE case $CHOICE in 1) echo YOU CHOSE ADDITION! echo Enter first number: read NUM1 echo Added by: read NUM2 addition $NUM1 $NUM ;; 2) echo YOU CHOSE SUBTRACTION! echo Enter first number: read NUM1 echo Subtracted by: read NUM2 subtraction $NUM1 $NUM2 ;; 3) echo YOU CHOSE MULTIPLICATION! echo Enter first number: read NUM1 echo Multiplied by: read NUM2 multiplication $NUM1 $NUM2 ;; 4) echo YOU CHOSE DIVISION! echo Enter first number: read NUM1 echo Divided by: read NUM2 division $NUM1 $NUM2 ;; 5) COUNTER=$(( $COUNTER + 1 )) ;; *) echo You must enter a number from 1 through 5! esac done Output:Please select a calculation to make!Choose how to you want to calculate two numbers1 - addition2 - subtraction3 - multiplication4 - division5 - QUIT1YOU CHOSE ADDITION!Enter first number:24Added by:5RESULT: 24I want the addition function to add the values that are read into the FNUM1 and FNUM2 variables.
BASH Script not adding variables in the Function
linux;bash;lubuntu
null
_cstheory.21451
It is well known that minimizing an NFA for a fixed regular language is $PSPACE-Complete$.As far as I know, there are no better than trivial algorithms for minimizing such NFA, but there's a little improvement if you consider symmetries.I've a specific regular language I'd like to compute a minimal automaton for:$$L_{k-distinct} :=\{w = \sigma_1\sigma_2...\sigma_k \mid \forall i\in[k]: \sigma_i\in\Sigma ~\text{ and }~ \forall j\ne i: \sigma_j\ne\sigma_i \}$$But at the moment I can't seem to close the gap between the automaton I know to build for it and the lower bound I can prove for it.I thought it might be fruitful to use some tool that given a language (it is finite for all $k,n$), searches (exhaustively if needed) for the smallest automaton which accept it, and see what the automaton looks like for small values of $k,n$.Does anyone know a tool which builds a minimal automaton for a given language?
A tool for minimal NFA computation
reference request;automata theory;nondeterminism;minimization;nfa
null
_unix.289207
On a RHEL7 notebook we have a: 03:00.0 Network controller: Intel Corporation Wireless 7265 (rev 59)card, which we want to use only with G mode, N should be disabled. How can we do this? iwconfig command doesn't exists by default. Question: How can we check that my wireless is using G or N currently? Under RHEL 7, no iwconfig. And how can we set it to use only G by default?It is needed to set it to G because N mode has bugs.
How to disable wireless N on Centos/RHEL 7?
rhel;wifi
To disable Wireless N in the module echo options iwlwifi 11n_disable=1 | sudo tee /etc/modprobe.d/iwl-opt.confRebootBut I would suggest enabling Wireless N on the router and trying this optionecho options iwlwifi 11n_disable=8 | sudo tee /etc/modprobe.d/iwl-opt.confThis command enables aggressive TX on Wireless-N and fixes a lot of issues
_unix.170659
The help docs mention marking for upgrade. The context menu and menu bar do not have this option listed at all, and the only non-greyed-out options are marking for removal or complete removal. There are some 40 packages in Installed (upgradeable) but there doesn't seem to be any way of actually upgrading them. This is on Linux Mint 17, 32-bit. What am I doing wrong?
Why is there no mark for upgrade in Synaptic Package Manager for upgradeable packages?
linux mint;package management;upgrade;synaptic
In Linux Mint 17 Qiana, Synaptic officially lacks the upgrade feature. This is for sake of stability - users are supposed to use mintupdate for already-installed packages. Synaptic can still be used to install additional, new packages.
_codereview.172611
I have two text boxes where a user inputs a start and a end, that is how it is supposed to work at least. Rather than throwing an error if end < start, I was thinking I could use the built in functions Min() & Max() to capture which value is actually which.Is this the most efficient way of capturing the Min() & Max() value of text box input?int start = Math.Min(Convert.ToInt32(txtStart.Text), Convert.ToInt32(txtEnd.Text));int end = Math.Max(Convert.ToInt32(txtStart.Text), Convert.ToInt32(txtEnd.Text));
Capture Min() And Max() Of Numbers Input
c#;performance
null
_codereview.82210
I want to see if anyone knows how to optimize the code below:public class smallestTest{ public static void main(String[] args) { double resultSmallest = smallest(2.5, 3.5, 4.5); System.out.println(The smallest number out of 2.5, 3.5, and 4.5 is: + resultSmallest); } /** Computes the smallest of three variables @param x, y, z @returns smallestNumber */ public static double smallest(double x, double y, double z) { double smallestNumber = 0; if ( x < y && x < z) { smallestNumber = x; } else if (y < x && y < z) { smallestNumber = y; } else if (z < x && z < y) { smallestNumber = z; } return smallestNumber; }}
Comparing multiple arguments and returns the smallest argument
java;numerical methods
You can use something called Varargs that was introduced in java 5.It is used in method declarations to declare arguments as an array.public void myMethod(double... doubleArray) {}public void callMyMethod() { myMethod(1.2, 4, 2, 1); // all those are put into a double[]}You can adapt this to your program by doing the following:public static double smallest(double... vals) { // must pass at least 1 argument. You could also return Double.NaN or something if(vals.length == 0) throw new IllegalArgumentException(smallest must be passed at least 1 value.); // start with the first value as the smallest double smallest = vals[0]; for(int i=1;i<vals.length;i++) { // see if this ones smaller than our stored smallest if(vals[i] < smallest) { smallest = val[i]; } } return smallest;}You can then call this with as many double values as you like.
_unix.139363
Recursively iterating through files in a directory can easily be done by:find . -type f -exec bar {} \;However, the above does not work for more complex things, where a lot of conditional branches, looping etc. needs to be done. I used to use this for the above:while read line; do [...]; done < <(find . -type f)However, it seems like this doesn't work for files containing obscure characters:$ touch $'a\nb'$ find . -type f./a?bIs there an alternative that handles such obscure characters well?
Recursively iterate through files in a directory
bash;directory;recursive
Yet another use for safe find:while IFS= read -r -d '' -u 9do [...]done 9< <( find . -type f -exec printf '%s\0' {} + )(This works with any POSIX find, but the shell part requires bash. With *BSD and GNU find, you can use -print0 instead of -exec printf '%s\0' {} +, it will be slightly faster.)This makes it possible to use standard input within the loop, and it works with any path.
_unix.15052
What are the advantages of swap on a raid-1 (mirror) device?(in a server environment running linux)I mean, you can just use multiple disk devices in linux for swap. And with swap devices that have the same priority, the kernel has the possibility to optimize reads and writes (i.e. striping).I can think of one: With raid-1 and hot-swappable drives you can change a failed leg of the swap-mirror without rebooting. Assuming that the kernel did not already read and use a corrupted page from the failing leg.Without raid1 you would have to either reboot or swap-off the failed device and hope that only unimportant processes (with now unavailable paged-out memory) are terminated.Is this one advantage, and are there others?
What are the advantages of swap on a raid-1 (mirror) device?
swap;raid1
You've mostly got them: slightly faster reads (but slower writes), and the ability to survive a failed drive without losing all the swapped-out processes. There's another: if your machine only has RAID-1 filesystems (or RAID-1 for the OS and RAID-5 for data, or similar arrangements), you might not want to complicate your setup further by having yet another drive arrangement just for swap.Note that RAID-1 doesn't catch data errors, so the kernel did not already read and use a corrupted page from the failing leg doesn't come into play. The assumption behind RAID-1 is that a sector read either succeeds and returns the last-stored data, or fails with an error code.
_unix.367108
I know what a while loop is. However, I've only seen it work with:while [condition]while ![condition]while TRUE (infinite loop)Where the statement after while has to be either TRUE or FALSE.There is a shell builtin command named :. It is described as a dummy command doing nothing, but I do not know if it is the same here, even if can it be TRUE or FALSE. Maybe it is something different, but what?
What does while :; mean?
bash;shell script
The syntax is:while first list of commandsdo second list of commandsdonewhich runs the second list of commands in a loop as long as the first list of commands (so the last run in that list) is successful.In that first list of commands, you can use the [ command to do various kinds of tests, or you can use the : null command that does nothing and returns success, or any other command.while :; do cmd; doneRuns cmd over and over forever as : always returns success. That's the forever loop. You could use the true command instead to make it more legible:while true; do cmd; donePeople used to prefer : as : was always builtin while true was not (a long time ago; most shells have true builtin nowadays).Other variants you might see:while [ 1 ]; do cmd; doneAbove, we're calling the [ command to test whether the 1 string is non-empty (so always true as well)while ((1)); do cmd; doneUsing the Korn/bash/zsh ((...)) syntax to mimic the while(1) { ...; } of C.Or more convoluted ones like until false; do cmd; done, until ! true...Those are sometimes aliased like:alias forever='while :; do'So you can do something like:forever cmd; doneFew people realise that the condition is a list of commands. For instance, you see people writing:while :; do cmd1 cmd2 || break cmd3doneWhen they could have written:while cmd1 cmd2do cmd3doneIt does make sense for it to be a list as you often want to do things like while cmd1 && cmd2; do...; done which are command lists as well.In any case, note that [ is a command like any other (though it's built-in in modern Bourne-like shells), it doesn't have to be used solely in the if/while/until condition lists, and those condition lists don't have to use that command more than any other command. : is also shorter and accepts arguments (which it ignores). While the behaviour of true or false is unspecified if you pass it any argument. So one may do for instance:while : you wait; do somethingdoneBut, the behaviour of:until false is true; do somethingdoneis unspecified (though it would work in most shell/false implementations).
_webapps.4902
The web application I built throws errors when presented with unknown query string variables, so I'd like to manually set the tracking values manually, much like:http://www.google.com/support/analytics/bin/answer.py?hl=en&answer=55577But by setting the values directly, not the variables to look for the values in.Is this possible?
Is it possible to set Google Analytics campaign tracking values manually?
google analytics
null
_codereview.79130
I wrote a PS script to backup data from single user pcs to their network homedrive. The purpose of this tool is to save some time and ensure process consistency when reimaging/replacing machines. I would appreciate your critiques and ideas. I am new to Powershell scripting.Breakdown of the scripts job:BACKUP:Creates a folder on the user's Home drive named Desktop Backup.Creates a subfolder within the Desktop Backup folder called %WorkstationName%.%date% (IE: H:\Desktop Backup\WC3ISYW257.1.21.2015).Copies all the Office Documents and Data files from the workstation C drive to the %WorkstationName%.%date% folder. The file types include:(.pptx,.xlsx,.accdb,.docx,.pst,.xls,.doc,.pab,.pdf,.ppt,.mdb,.jpg,.bmp,.gif,.vsd,.mp*,.doc,.xltx,.xltm,.xlam,.ppt*,.potx,.potm,.ppam,.ppsx,.ppsm,.acc*,.pdf,.jpeg,.png,.csv)Creates a subfolder within the %WorkstationName%.%Date% folder called Configuration(IE: H:\Desktop Backup\WC3ISYW257.1.21.2015\Configuration).Creates seperate text files within the Configuration folder containing information on user's mapped drives, remote desktop users on the machine, administrator accounts on the machine, and mapped printers.Creates a subfolder within the %WorkstationName%.%Date% folder called Desktop(IE: H:\Desktop Backup\WC3ISYW257.1.21.2015\Desktop).Copies all the user's Desktop folder to the Desktop folder, excluding *lnk, *.url, and *.exe files.Creates a subfolder within the %WorkstationName%.%Date% folder called Office Files(IE: H:\Desktop Backup\WC3ISYW257.1.21.2015\Office Files).Creates a subfolder within the Office Files folder called NK2(IE: H:\Desktop Backup\WC3ISYW257.1.21.2015\Office Files\NK2).Copies all the files from the user's Outlook folder to the NK2 folder.Creates a subfolder within the Office Files folder called Proof(IE: H:\Desktop Backup\WC3ISYW257.1.21.2015\Office Files\Proof).Copies all the files from the user's Proof folder to the Proof folder.Creates a subfolder within the Office Files folder called Signatures(IE: H:\Desktop Backup\WC3ISYW257.1.21.2015\Office Files\Signatures).Copies all the files from the user's Signatures folder to the Signatures folder.Creates a subfolder within the Office Files folder called Quick Launch(IE: H:\Desktop Backup\WC3ISYW257.1.21.2015\Office Files\Quick Launch).Copies all the files from the user's Quick Launch folder to the Quick Launch folder.RESTORE:Copies all the files from the users NK2 folder (IE: H:\Desktop Backup\WC3ISYW257.1.21.2015\Office Files\NK2) to the user's Outlook folder.Copies all the files from the Proof folder (IE: H:\Desktop Backup\WC3ISYW257.1.21.2015\Office Files\Proof) to the user's Proof folder.Copies all the files from the Signatures folder(IE: H:\Desktop Backup\WC3ISYW257.1.21.2015\Office Files\Signatures) to the user's Signatures folder.Copies all the files from the users Desktop folder (IE: H:\Desktop Backup\WC3ISYW257.1.21.2015\Desktop) to the user's desktop (excluding *.lnk, *.url, and *.exe).The Restore function does not put the users HomeDrive data back on the C:\ as we are trying to encourage users to not use the C:\ for storage. It also does not restore the quick launch bar. It also excludes the restore of *.lnk, *.url, and *.exe from the user's desktop. The reason for these is backwards/forwards Windows XP/7 OS compatibility.[void] [System.Reflection.Assembly]::LoadWithPartialName(System.Drawing) [void] [System.Reflection.Assembly]::LoadWithPartialName(System.Windows) [void] [System.Reflection.Assembly]::LoadWithPartialName(System.Management)#Generated Form Functionfunction GenerateForm {######################################################################### Created On: 1/19/2015# Generated By: Josh Pratt########################################################################$date = Get-Date -Format d.M.yyyy_h_m_s#region Import the Assemblies[reflection.assembly]::loadwithpartialname(System.Windows.Forms) | Out-Null[reflection.assembly]::loadwithpartialname(System.Drawing) | Out-Null#endregion#region Generated Form Objects$formDSBACKUP = New-Object System.Windows.Forms.Form$label1 = New-Object System.Windows.Forms.Label$RESTORE = New-Object System.Windows.Forms.Button$BACKUP = New-Object System.Windows.Forms.Button$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState#endregion Generated Form Objects$BACKUP_OnClick= { #region Import the Assemblies [reflection.assembly]::loadwithpartialname(System.Windows.Forms) | Out-Null [reflection.assembly]::loadwithpartialname(System.Drawing) | Out-Null #endregion #region Generated Form Objects $formBACKUP = New-Object System.Windows.Forms.Form $comboBox1 = New-Object System.Windows.Forms.ComboBox $label1 = New-Object System.Windows.Forms.Label $BACKUPall = New-Object System.Windows.Forms.Button $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState $computername = $env:COMPUTERNAME $date = Get-Date -Format M.d.yyyy #endregion Generated Form Objects $BACKUPall_OnClick= { #region Generated Form Objects $formBACKUP = New-Object System.Windows.Forms.Form $comboBox1 = New-Object System.Windows.Forms.ComboBox $label1 = New-Object System.Windows.Forms.Label $BACKUPall = New-Object System.Windows.Forms.Button $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState $date = Get-Date -Format M.d.yyyy $Include = @(*.pptx,*.xlsx,*.accdb,*.docx,*.pst,*.xls,*.doc,*.pab,*.pdf,*.ppt,*.mdb,*.jpg,*.bmp,*.gif,*.vsd,*.mp*,*.doc*,*.xltx,*.xltm,*.xlam,*.ppt*,*.potx,*.potm,*.ppam,*.ppsx,*.ppsm,*.acc*,*.pdf*,*.jpeg*,*.png*,*.csv*) $this = $env:username $this2 = $env:username $Desktop = [Environment]::GetFolderPath(Desktop) $exclude = @('*.lnk','*.url','*.exe') $dest = H:\Desktop Backup\$computername.$date\Desktop #endregion Generated Form Objects $Result = Test-Path -Path C:\Program Files (x86) if($Result -eq $true){ New-Item -ItemType Directory -Path H:\Desktop Backup\$computername.$date\configuration Get-WmiObject -Class Win32_MappedLogicalDisk | select Name, ProviderName >> H:\Desktop Backup\$computername.$date\configuration\MappedDrives.txt Get-WmiObject -class Win32_printer | ft name, systemName, shareName >> H:\Desktop Backup\$computername.$date\configuration\printers.txt net localgroup Remote Desktop Users >> H:\Desktop Backup\$computername.$date\configuration\RemoteDesktopUsers.txt net localgroup Administrators >> H:\Desktop Backup\$computername.$date\configuration\Administrators.txt Get-ChildItem c:\ -Include $include -Recurse | where {$_ -notmatch 'Windows'}| where{$_ -notmatch 'Program Files'} | where {$_ -notmatch 'inetpub'} | where {$_ -notmatch 'Desktop'}|Foreach{Copy-Item $_.fullname H:\Desktop Backup\$computername.$date} New-Item -ItemType Directory -Path H:\Desktop Backup\$computername.$date\Office Files\Quick Launch Get-ChildItem C:\Users\$this\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch | % { Copy-Item $_.FullName H:\Desktop Backup\$computername.$date\Office Files\Quick Launch -Recurse -Force } New-Item -ItemType Directory -Path H:\Desktop Backup\$computername.$date\Office Files\Signatures Get-ChildItem C:\Users\$this\AppData\Roaming\Microsoft\Signatures | % { Copy-Item $_.FullName H:\Desktop Backup\$computername.$date\Office Files\Signatures -Recurse -Force } New-Item -ItemType Directory -Path H:\Desktop Backup\$computername.$date\Office Files\Proof Get-ChildItem C:\Users\$this\AppData\Roaming\Microsoft\Proof | % { Copy-Item $_.FullName H:\Desktop Backup\$computername.$date\Office Files\Proof -Recurse -Force } New-Item -ItemType Directory -Path H:\Desktop Backup\$computername.$date\Office Files\NK2 Get-ChildItem C:\Users\$this\AppData\Roaming\Microsoft\Outlook | % { Copy-Item $_.FullName H:\Desktop Backup\$computername.$date\Office Files\NK2 -Recurse -Force } New-Item -ItemType Directory -Path $dest Get-ChildItem $Desktop -Recurse -Exclude $exclude | Copy-Item -Destination {Join-Path $dest $_.FullName.Substring($Desktop.length)}| out-null } else { New-Item -ItemType Directory -Path H:\Desktop Backup\$computername.$date\configuration Get-WmiObject -Class Win32_MappedLogicalDisk | select Name, ProviderName >> H:\Desktop Backup\$computername.$date\configuration\MappedDrives.txt Get-WmiObject -class Win32_printer | ft name, systemName, shareName >> H:\Desktop Backup\$computername.$date\configuration\printers.txt net localgroup Remote Desktop Documents and Settings >> H:\Desktop Backup\$computername.$date\configuration\RemoteDesktopUsers.txt net localgroup Administrators >> H:\Desktop Backup\$computername.$date\configuration\Administrators.txt Get-ChildItem c:\ -Include $include -Recurse | where {$_ -notmatch 'Windows'}| where{$_ -notmatch 'Program Files'} | where {$_ -notmatch 'inetpub'} | where {$_ -notmatch 'Desktop'}|Foreach{Copy-Item $_.fullname H:\Desktop Backup\$computername.$date} New-Item -ItemType Directory -Path H:\Desktop Backup\$computername.$date\Office Files\Quick Launch Get-ChildItem C:\Documents and Settings\$this2\Application Data\Microsoft\Internet Explorer\Quick Launch | % { Copy-Item $_.FullName H:\Desktop Backup\$computername.$date\Office Files\Quick Launch -Recurse -Force } New-Item -ItemType Directory -Path H:\Desktop Backup\$computername.$date\Office Files\Signatures Get-ChildItem C:\Documents and Settings\$this2\Application Data\Microsoft\Signatures | % { Copy-Item $_.FullName H:\Desktop Backup\$computername.$date\Office Files\Signatures -Recurse -Force } New-Item -ItemType Directory -Path H:\Desktop Backup\$computername.$date\Office Files\Proof Get-ChildItem C:\Documents and Settings\$this2\Application Data\Microsoft\Proof | % { Copy-Item $_.FullName H:\Desktop Backup\$computername.$date\Office Files\Proof -Recurse -Force } New-Item -ItemType Directory -Path H:\Desktop Backup\$computername.$date\Office Files\NK2 Get-ChildItem C:\Documents and Settings\$this2\Application Data\Microsoft\Outlook | % { Copy-Item $_.FullName H:\Desktop Backup\$computername.$date\Office Files\NK2 -Recurse -Force } New-Item -ItemType Directory -Path $dest Get-ChildItem $Desktop -Recurse -Exclude $exclude | Copy-Item -Destination {Join-Path $dest $_.FullName.Substring($Desktop.length)}| out-null } $outputBox.text = BACKUP COMPLETE Start-Sleep -S 10 $formBACKUP.close() } $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $formBACKUP.WindowState = $InitialFormWindowState } #---------------------------------------------- #region Generated Form Code $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 240 $System_Drawing_Size.Width = 450 $formBACKUP.ClientSize = $System_Drawing_Size $formBACKUP.DataBindings.DefaultDataSourceUpdateMode = 0 $formBACKUP.Name = formBACKUP $formBACKUP.Text = BACKUP $formBACKUP.StartPosition = CenterScreen $outputBox = New-Object System.Windows.Forms.TextBox $outputBox.Location = New-Object System.Drawing.Size(25, 187) $outputBox.Size = New-Object System.Drawing.Size(400, 50) $outputBox.MultiLine = $True $formBACKUP.Controls.Add($outputBox) $outputbox.DataBindings.DefaultDataSourceUpdateMode = 0 $BACKUPall.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 25 $System_Drawing_Point.Y = 160 $BACKUPall.Location = $System_Drawing_Point $BACKUPall.Name = BACKUPall $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 400 $BACKUPall.Size = $System_Drawing_Size $BACKUPall.TabIndex = 2 $BACKUPall.Text = BACKUP $BACKUPall.UseVisualStyleBackColor = $True $BACKUPall.add_Click($BACKUPall_OnClick) $formBACKUP.Controls.Add($BACKUPall) $Label1 = New-Object System.Windows.Forms.Label $Label1.Location = New-Object System.Drawing.Size(25, 6) $Label1.size = New-Object System.Drawing.Size(400, 800) $Label1.text = Pressing Backup will: 1. Create a folder called Desktop Backup on the H drive. 2. Create text files to record rights, mapped drives, and printers. 3. Backup all data files and office documents. 4. Backup custom features such as NK2, signature,dictionary, and quick launch files. Once pressed this tool will appear to freeze. Leave it alone until you see BACKUP COMPLETE below. $Font = New-Object System.Drawing.Font(Times New Roman,9.75,[System.Drawing.FontStyle]::bold) # Font styles are: Regular, Bold, Italic, Underline, Strikeout $label1.Font = $Font $formBACKUP.Controls.Add($Label1) #endregion Generated Form Code #Save the initial state of the form $InitialFormWindowState = $formBACKUP.WindowState #Init the OnLoad event to correct the initial state of the form $formBACKUP.add_Load($OnLoadForm_StateCorrection) #Show the Form $formBACKUP.ShowDialog()| Out-Null} $RESTORE_OnClick= { #region Import the Assemblies [reflection.assembly]::loadwithpartialname(System.Windows.Forms) | Out-Null [reflection.assembly]::loadwithpartialname(System.Drawing) | Out-Null #endregion #region Generated Form Objects $formrestore = New-Object System.Windows.Forms.Form $comboBox2 = New-Object System.Windows.Forms.ComboBox $label1 = New-Object System.Windows.Forms.Label $Restore2 = New-Object System.Windows.Forms.Button $user = [Environment]::UserName $Desktop2 = [Environment]::GetFolderPath(Desktop) $NK2 = C:\users\$user\AppData\Roaming\Microsoft\Outlook $Signatures = C:\users\$user\AppData\Roaming\Microsoft\Signatures $NK2_XP = C:\documents and Settings\$user\Application Data\Microsoft\Outlook $Signatures_XP = C:\documents and Settings\$user\Application Data\Microsoft\Signatures $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState $QL_XP = C:\documents and Settings\$user\Application Data\Microsoft\Internet Explorer\Quick Launch $QL = C:\users\$user\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch $PROOF_XP = C:\Documents and Settings\$user\Application Data\Microsoft\Proof $PROOF = C:\users\$user\AppData\Roaming\Microsoft\Proof $computername = $env:COMPUTERNAME #endregion Generated Form Objects $Restore2_OnClick= {$SelectedItem = $comboBox2.SelectedItem.ToString() $Result = Test-Path -Path C:\Program Files (x86) if($Result -eq $true){ Get-ChildItem H:\Desktop Backup\$SelectedItem\Desktop | % { Copy-Item $_.FullName -Destination $Desktop2 -Recurse } New-Item -ItemType Directory -Path $Signatures Get-ChildItem H:\Desktop Backup\$SelectedItem\Office Files\Signatures | % { Copy-Item $_.FullName -Destination $Signatures -Recurse } New-Item -ItemType Directory -Path $NK2 Get-ChildItem H:\Desktop Backup\$SelectedItem\Office Files\NK2 | % { Copy-Item $_.FullName -Destination $NK2 -Recurse } New-Item -ItemType Directory -Path $PROOF Get-ChildItem H:\Desktop Backup\$SelectedItem\Office Files\Proof | % { Copy-Item $_.FullName -Destination $PROOF -Recurse }} else {Get-ChildItem H:\Desktop Backup\$SelectedItem\Desktop | % { Copy-Item $_.FullName -Destination $Desktop2 -Recurse } New-Item -ItemType Directory -Path $Signatures_XP Get-ChildItem H:\Desktop Backup\$SelectedItem\Office Files\Signatures | % { Copy-Item $_.FullName -Destination $Signatures_XP -Recurse } New-Item -ItemType Directory -Path $NK2_XP Get-ChildItem H:\Desktop Backup\$SelectedItem\Office Files\NK2 | % { Copy-Item $_.FullName -Destination $NK2_XP -Recurse } Get-ChildItem H:\Desktop Backup\$SelectedItem\Office Files\Proof | % { Copy-Item $_.FullName -Destination $PROOF_XP -Recurse }} $formrestore.close() } $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $formrestore.WindowState = $InitialFormWindowState } #---------------------------------------------- #region Generated Form Code $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 240 $System_Drawing_Size.Width = 450 $formrestore.ClientSize = $System_Drawing_Size $formrestore.DataBindings.DefaultDataSourceUpdateMode = 0 $formrestore.Name = formrestore $formrestore.Text = RESTORE $formrestore.StartPosition = CenterScreen# $outputBox = New-Object System.Windows.Forms.TextBox# $outputBox.Location = New-Object System.Drawing.Size(10, 60)# $outputBox.Size = New-Object System.Drawing.Size(430, 160)# $outputBox.MultiLine = $True# $outputBox.ScrollBars = Vertical## $formrestore.Controls.Add($outputBox) $outputbox.DataBindings.DefaultDataSourceUpdateMode = 0 $Restore2.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 270 $System_Drawing_Point.Y = 205 $Restore2.Location = $System_Drawing_Point $Restore2.Name = Restore $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 23 $System_Drawing_Size.Width = 175 $Restore2.Size = $System_Drawing_Size $Restore2.TabIndex = 2 $Restore2.Text = Restore $Font = New-Object System.Drawing.Font(Times New Roman,9.75,[System.Drawing.FontStyle]::Bold) $Restore2.font = $Font $Restore2.UseVisualStyleBackColor = $True $Restore2.add_Click($Restore2_OnClick) $comboBox2.DataBindings.DefaultDataSourceUpdateMode = 0 $comboBox2.FormattingEnabled = $True $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 1 $System_Drawing_Point.Y = 205 $comboBox2.Location = $System_Drawing_Point $comboBox2.Name = comboBox2 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 21 $System_Drawing_Size.Width = 259 $comboBox2.Size = $System_Drawing_Size $comboBox2.TabIndex = 4$Result = Test-Path -Path C:\Program Files (x86) if($Result -eq $true){$win = Get-ChildItem H:\Desktop Backup# $ders = Where-Object {$win -like Windows.*} foreach($item in $win) { if($item.name -like *.*){ $comboBox2.items.add($item.name) }}} else {$win = Get-ChildItem H:\Desktop Backup# $ders = Where-Object {$win -like Windows.*} foreach($item in $win) { if($item.name -like Personal Settings.*){ $comboBox2.items.add($item.name) }}} $formrestore.Controls.Add($combobox2) $formrestore.Controls.Add($Restore2) $Label1 = New-Object System.Windows.Forms.Label $Label1.Location = New-Object System.Drawing.Size(1, 6) $Label1.size = New-Object System.Drawing.Size(400, 800) $Label1.text = Clicking restore will perform the following: 1. Restore Desktop documents 2. Restore NK2 files 3. Restore Signature files 4. Restore Proof files Select the Computer's Backup folder using the drop down box below. Once selected please click Restore. This window will close once items have been restored. Please note for NK2 and Signature files: You will still have to select them from within Outlook. $Font = New-Object System.Drawing.Font(Times New Roman,9.75,[System.Drawing.FontStyle]::Bold) # Font styles are: Regular, Bold, Italic, Underline, Strikeout $label1.Font = $Font $formrestore.Controls.Add($Label1) #endregion Generated Form Code #Save the initial state of the form $InitialFormWindowState = $formrestore.WindowState #Init the OnLoad event to correct the initial state of the form $formrestore.add_Load($OnLoadForm_StateCorrection) #Show the Form $formrestore.ShowDialog()| Out-Null}$OnLoadForm_StateCorrection={#Correct the initial state of the form to prevent the .Net maximized form issue $formDSBACKUP.WindowState = $InitialFormWindowState}#----------------------------------------------#region Generated Form Code$System_Drawing_Size = New-Object System.Drawing.Size$System_Drawing_Size.Height = 300$System_Drawing_Size.Width = 284$formDSBACKUP.ClientSize = $System_Drawing_Size$formDSBACKUP.DataBindings.DefaultDataSourceUpdateMode = 0$formDSBACKUP.Name = formDSBACKUP$formDSBACKUP.Text = SaveIT! - Desktop Backup Tool$formDSBACKUP.StartPosition = WindowsDefaultLocation$formDSBACKUP.StartPosition = CenterScreen$label1.DataBindings.DefaultDataSourceUpdateMode = 0$System_Drawing_Point = New-Object System.Drawing.Point$System_Drawing_Point.X = 10$System_Drawing_Point.Y = 1$Font = New-Object System.Drawing.Font(Times New Roman,9.75,[System.Drawing.FontStyle]::Bold)# Font styles are: Regular, Bold, Italic, Underline, Strikeout$label1.Font = $Font$label1.Location = $System_Drawing_Point$label1.Name = label1$System_Drawing_Size = New-Object System.Drawing.Size$System_Drawing_Size.Height = 225$System_Drawing_Size.Width = 259$label1.Size = $System_Drawing_Size$label1.TabIndex = 3$label1.Text = Choose the function you are looking to perform:BACKUP: If this is a machine that is being replaced/reimaged.RESTORE: If this is a machine that has been replaced or reimaged.PLEASE NOTE: The restore portion of this tool will only work if you used this tool to backup this users information previously$formDSBACKUP.Controls.Add($label1)$RESTORE.DataBindings.DefaultDataSourceUpdateMode = 0$System_Drawing_Point = New-Object System.Drawing.Point$System_Drawing_Point.X = 20$System_Drawing_Point.Y = 255$RESTORE.Location = $System_Drawing_Point$RESTORE.Name = RESTORE$System_Drawing_Size = New-Object System.Drawing.Size$System_Drawing_Size.Height = 23$System_Drawing_Size.Width = 240$RESTORE.Size = $System_Drawing_Size$RESTORE.TabIndex = 1$RESTORE.Text = RESTORE$RESTORE.UseVisualStyleBackColor = $True$RESTORE.add_Click($RESTORE_OnClick)$formDSBACKUP.Controls.Add($RESTORE)$BACKUP.DataBindings.DefaultDataSourceUpdateMode = 0$System_Drawing_Point = New-Object System.Drawing.Point$System_Drawing_Point.X = 20$System_Drawing_Point.Y = 225$BACKUP.Location = $System_Drawing_Point$BACKUP.Name = BACKUP$System_Drawing_Size = New-Object System.Drawing.Size$System_Drawing_Size.Height = 23$System_Drawing_Size.Width = 240$BACKUP.Size = $System_Drawing_Size$BACKUP.TabIndex = 1$BACKUP.Text = BACKUP$BACKUP.UseVisualStyleBackColor = $True$BACKUP.add_Click($BACKUP_OnClick)$formDSBACKUP.Controls.Add($BACKUP)$formDSBACKUP.Controls.Add($PRTADTW705)#endregion Generated Form Code#Save the initial state of the form$InitialFormWindowState = $formDSBACKUP.WindowState#Init the OnLoad event to correct the initial state of the form$formDSBACKUP.add_Load($OnLoadForm_StateCorrection)#Show the Form$formDSBACKUP.ShowDialog()| Out-Null} #End Function#Call the FunctionGenerateForm
Backing up single-user PC data
beginner;powershell
null
_unix.384303
The default target returned by systemctl[user@host system]$ systemctl get-defaultmulti-user.targetdiffers from the value of the /usr/lib/systemd/system/default.target link:[user@host system]$ ls -l /usr/lib/systemd/system/default.targetlrwxrwxrwx. 1 root root 16 Mar 10 21:20 /usr/lib/systemd/system/default.target -> graphical.targetMy understanding was that these were one and the same. If systemd doesn't store the default value as the default.target symlink, where is the real value of the default target stored by systemd?
systemctl get-default differs from default.target link
systemd
This is most likely because /etc/systemd/system/default.target exists and points to multi-user.targetIf you change the default.target with systemctl set-default [unit], the new default.target link is created in /etc/systemd/system/. The existing /usr/lib/systemd/system/default.target is not changed when using the set-default command. Like with all systemd units, the ones in /etc take precedence over /usr.
_unix.38390
Is there any way to substitute text in variables on several patterns at time or even using back reference?For example, I have FILE=filename.ext and I want to change it to filename_sometext.ext. But I don't know that file extension is .ext. All I know about it is that extension is after last dot.So I can do it in two steps:EXT=${FILE##*.}FILE=${FILE%.*}_sometext.$EXTCan I do it on one step (something like ${FILE/.\(*\)/_sometext.\1} [that doesn't work])?By the way I need to do it in pure shell without sed/awk/etc. My shell is ksh, but if there is way to do it with bashisms I'd like to know it too.
pure shell complex substitution in variable
bash;shell;ksh;variable substitution
Bash Parameter Expansion says that the variable (FILE in your example) must be a parameter name. So they don't nest. And the last part of ${param/pattern/replacement} must be a string. So back references aren't supported.My only advice is to use${EXT:+.$EXT}to avoid adding a trailing dot if the file has no extension.UPDATEApparently back references are supported in ksh93.So you could use something likeFILE=${FILE/@(.*)/_something\1}
_unix.127320
Is there a way to monitor all events sent to the libnotify module?I am trying to debug faulty sound notifications from Thunderbird, and I am hoping that if the way Thunderbird links with sounds is faulty, I can at least play my own sound.I am using Ubuntu 12.04 with KDE.
Is there a way to monitor all events sent to the libnotify module?
libnotify
null
_codereview.169101
I have this ordered list of datetimes that comprises of 30 minute slots:availability = [ datetime.datetime(2010, 1, 1, 9, 0), datetime.datetime(2010, 1, 1, 9, 30), datetime.datetime(2010, 1, 1, 10, 0), datetime.datetime(2010, 1, 1, 10, 30), datetime.datetime(2010, 1, 1, 13, 0), # gap datetime.datetime(2010, 1, 1, 13, 30), datetime.datetime(2010, 1, 1, 15, 30), # gap datetime.datetime(2010, 1, 1, 16, 0), datetime.datetime(2010, 1, 1, 16, 30)]And I would to split the ones with time gaps in between into a dictionary with start and end values, like so:[ {'start': datetime.datetime(2010, 1, 1, 9, 0), 'end': datetime.datetime(2010, 1, 1, 10, 30)}, {'start': datetime.datetime(2010, 1, 1, 13, 0), 'end': datetime.datetime(2010, 1, 1, 13, 30)}, {'start': datetime.datetime(2010, 1, 1, 15, 30), 'end': datetime.datetime(2010, 1, 1, 16, 30)}]So I threw this snippet of code together that does exactly that.result = []row = {}for index, date in enumerate(available): exists = False if not row: row['start'] = date try: if date + timedelta(minutes = 30) != available[index + 1]: exists = True except IndexError: exists = True if exists: row['end'] = date result.append(row) row = {}But needless to say this is super ugly and there just has to be a better, shorter and more elegant way to do this.
Splitting up a list with datetimes
python;python 2.7;datetime
It is possible to utilize itertools.groupby() using indexes to calculate if there is a gap:import datetimefrom datetime import timedeltafrom functools import partialfrom itertools import groupbyfrom operator import itemgetterdef is_consecutive(start_date, item): A grouping key function that highlights the gaps in a list of datetimes with a 30 minute interval. index, value = item return (start_date + index * timedelta(minutes=30)) - valueavailable = [ datetime.datetime(2010, 1, 1, 9, 0), datetime.datetime(2010, 1, 1, 9, 30), datetime.datetime(2010, 1, 1, 10, 0), datetime.datetime(2010, 1, 1, 10, 30), datetime.datetime(2010, 1, 1, 13, 0), # gap datetime.datetime(2010, 1, 1, 13, 30), datetime.datetime(2010, 1, 1, 15, 30), # gap datetime.datetime(2010, 1, 1, 16, 0), datetime.datetime(2010, 1, 1, 16, 30)]start_date = available[0]result = []for _, group in groupby(enumerate(available), key=partial(is_consecutive, start_date)): current_range = list(map(itemgetter(1), group)) result.append({ 'start': current_range[0], 'end': current_range[-1] })print(result)Prints:[ {'start': datetime.datetime(2010, 1, 1, 9, 0), 'end': datetime.datetime(2010, 1, 1, 10, 30)}, {'start': datetime.datetime(2010, 1, 1, 13, 0), 'end': datetime.datetime(2010, 1, 1, 13, 30)}, {'start': datetime.datetime(2010, 1, 1, 15, 30), 'end': datetime.datetime(2010, 1, 1, 16, 30)}]