id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_softwareengineering.304187 | I need to know if I can get acceleration data from an IMU at 500Hz via USB. I've been going through the code that the manufacturer provides and trying to improve it. Right now I cannot go faster than 166Hz. Things I've tried:Switched from streaming mode to polling. The reason is that in streaming mode the SDK of the manufacturer uses the ioctl library to know if there is new data to be read. The faster I would go was 10Hz. In polling mode, every N milliseconds data gets read from the port using a standard read command. I went from 10Hz to 166Hz, that is, for N=6. But with N<6 I get no improvement. 166Hz is a ceiling right now.Increased the process priority. This has no effect at all. Maybe because I'm only running the browser and the code I'm working on?Yes, I know linux is not a real time system. At the end of the day I'll have to live with that. I may use xenomai later on the code. But right now I need to know how fast I can go. Not theoretically, but in a real application. Any ideas about how to increase the performance?EDIT: This are the timestamps of the time I get the data, in millisencods. Note the bursts. 1449258970519 1449258970519 1449258970525 1449258970531 1449258970531 1449258970543 1449258970543 1449258970543 1449258970549 1449258970555 1449258970555 1449258970562 1449258970567 1449258970567 1449258970573 1449258970579 1449258970579 1449258970585EDIT: The amount of data that I have to transfer is very small... say at most 16 floats, plus some headers. I can safely assume 128 bytes is enough. So 128x1000 is still A LOT less than the 480 Mpbs that USB 2 offers. | Read data from a device through usb port at high frequency | linux;real time;usb | After looking around quite a log, reading manuals, and getting some output from the linux kernel USB mailing list, I'm going to say that is not a good idea to use a USB for 500Hz continous data transfer.At first I thought that it should be possible, and the math proved it. Meaning, if USB 2.0 offers 480Mbs, I should be able to poll my imu for a few floats at 500Hz. I think that I needed at most 128kps. Well, as proposed by someone at the linux kernel mailing list (someone who very kindly answered all my questions!) I profiled the data transfer and it came at 27 Kbs, which is way lower than the theoretical 480 Mpbs of USB 2.0.Then, on several places I found reference to the issues of bursts in USB data. For reasons that I don't fully understand yet, that's how the USB driver works.So, for frequencies above 150 (maybe even lower), USB is not your guy if you need to get data at regular intervals.I tested different drivers, on different computers, and always got a similar result. Data in burst after a 6ms sampling interval. |
_unix.322225 | when cross-compiling a package, do you also cross-compile the dependencies or just install the dependencies, and then cross-compile the final package for my target embedded Linux device? | Do you cross-compile the dependencies of a package or just perform install? | compiling;dependencies | You need to cross-compile all the dependencies: every piece of code linked to the final binary (whether statically or dynamically) needs to be built for the target platform.Depending on the platform (and distribution) you're building on, and the target platform, you might find your cross-dependencies are already available in your distribution. |
_unix.377970 | I've been writing one-line bash scripts on the command line since 1989. These usually have the form:for name in 1 2 3; do wc $name.txt; doneNow I'm trying to do some image manipulation with GIMP, using a script that takes two filenames for arguments. Here's something that gives me a valid command line:/Applications/GIMP.app/Contents/MacOS/GIMP -b '(script-fu-overlay png0004.tif png0000.tif) (script-fu-overlay png0004.tif png0001.tif) (script-fu-overlay png0004.tif png0002.tif) (script-fu-overlay png0004.tif png0003.tif)'It was generated with the help of a typical one-liner:X=\'$(for name in 0 1 2 3; do echo \(script-fu-overlay \png0004.tif\ \png000$name.tif\\) ; done)\'But...and here is my question:echo /Applications/GIMP.app/Contents/MacOS/GIMP -b $Xgives me the exact command line above, but when I run/Applications/GIMP.app/Contents/MacOS/GIMP -b $XI get errors about not being able to open filenames that have quotes around them, but when I run/Applications/GIMP.app/Contents/MacOS/GIMP -b $Xeverything works. My real goal is to understand whether it's possible for me to write a one-liner without resorting to variables at all. Something like:/Applications/GIMP.app/Contents/MacOS/GIMP -b \'$(for name in 0 1 2 3; do echo \(script-fu-overlay \png0004.tif\ \png000$name.tif\\) ; done)\'But that fails in apparently the same way that/Applications/GIMP.app/Contents/MacOS/GIMP -b $Xfails. | Confusion about bash command vs. variable substitution | bash;command substitution;variable substitution | Yes you can do it on the command line without resorting to shell variables./Applications/GIMP.app/Contents/MacOS/GIMP -b $(for name in 0 1 2 3; do echo \(script-fu-overlay \png0004.tif\ \png000$name.tif\\) ; done)Note that we need to do away with the escaped single quotes since we are not doing an eval here. Only thing that is needed are the double quotes around the command expansion $(...) to prevent word split from happening PLUS pass the result as one single argument to gimp. |
_cogsci.16822 | The problem I have is that the MRI scan is stopped manually, before the exam card is completed.Thus data anaylsis programs read the header and expect a certain number of volumes but it has less, and on top of that the final volume is partial so I can't simply modify the header so that it looks for less.Programs such as fslroi that allow trimming volumes do not handle partial volumes.How can I remove the partial data so that the file is correctly read? | How to fix a nii or rec file with partial volume | cognitive neuroscience;fmri | I found the solution using the python package nibabel.The code is rather simple. If filename is your nii, or rec file use:import nibabel as nibimg = nib.load(filename,permit_truncated=True)print(Saving image with shape:,img.shape)nib.save(img,truncated_{0}.format(filename)) |
_webmaster.63227 | Say there's a web application that runs on example.com, would there be a penalty for 301 redirecting the root of the domain (example.com/) to subdomain.example.com for purposes of hosting the marketing website for an application? Obviously we would expect subdomain.example.com to be what is ranked in the search engine, not example.com. We would want other paths on example.com like example.com/path/to/resource to index normally, and be unaffected by the 301 on the root path. | Redirect root path on root domain to subdomain | seo;redirects;subdomain | It is fine to do that if that is what you wish.Not really sure what else to add as this is a relatively common practice and if implemented correctly, there are no negative repercussions from this. |
_softwareengineering.339048 | (For more backstory/explanation, see my previous question.)I'm a middle school student working on a very, very informal project; my problem statement is as follows:There is no way for theoreticians, researchers, and students in the field of quantum computing to simulate and test complex, large quantum circuits in an intuitive, efficient way without creating the code for the application themselves. A web application that works in popular browsers with an simple interface that could accurately produce results on the outcomes of quantum algorithms, error correction codes, entanglement, decoherence, and the other aspects of both an ideal and realistic interface would allow professionals and students alike to test their ideas and get a better understanding of the field of quantum computing.So, as I am working through the book Code Complete, the next step was to list requirements. As I've never done this before and it is such an informal project, I am unsure if the requirements list I came up with is any good, or if there are improvements that should be made to it. So here's the list:Takes in as input starting state of the qubits, each gate to be applied to which qubit, how many qubits should be used, and what implementation of quantum computing they'd like to test in (for decoherence time estimates).Outputs should be current state of every qubit and probability of |0> and |1> state for every qubit.Outputs should be given on the website and downloadable along with inputs in a text file. State of qubits should be a vector, probability should be a number from 0 to 1, gates should be one of several commonly used gates or the custom gate option.Inputs for gates should be one of several buttons (pressed).Inputs for state and number of qubits should be integer input.Once user inputs data and presses the button to compute, it should not take very long to produce the answer (e.g., one minute max for 5 qubit calculations is one benchmark).Should be a website interface, with input blanks based on previous user input, i.e., create an account to save your simulations (takes in email and password), then a tab to look at previous text files from simulations and a tab to create a new simulation. Then, the user would input the number of qubits and starting state of qubits, click next and it will have you list gates for 1st qubit, click done, 2nd qubit, etc. If the option inputted is custom gate, a blank pops up where you can fill in the necessary data for the gate. When done, it transitions to a calculating style screen, and then gives the result and text file to download, with an option to save and an option to start over (last option available throughout).The safety of the user's email, password, and text files must be high, as there could be important/confidential research-related information stored there.Place on site to report bugs and request improvements.Has common quantum gates available and a custom gate option.Simulates decoherence, entanglement, and other common features of quantum computing.Allows choice between ideal (no decoherence) and non-ideal (decoherence) quantum computer.Generalizable to large numbers of qubits (runs as efficiently as possible). Documentation on-site for users.Accurate results (basic cases, at minimum, checked against accepted results.Option to make text files public/private and a location to access public simulations? | One-person, informal project - creating good requirements | design;requirements;software;code complete | Takes in as input starting state of the qubits, each gate to be applied to which qubit, how many qubits should be used, and what implementation of quantum computing they'd like to test in (for decoherence time estimates).Outputs should be current state of every qubit and probability of |0> and |1> state for every qubit.Outputs should be given on the website and downloadable along with inputs in a text file. The ones above seem reasonable and testableState of qubits should be a vector, probability should be a number from 0 to 1, gates should be one of several commonly used gates or the custom gate option.Huh? How does this allow me to tell if a bad kind of gate was used? List or cite your definition of commonly used gates.Inputs for gates should be one of several buttons (pressed).So, gate input can only ever be buttons? One of which buttons?Inputs for state and number of qubits should be integer input.You remembered that -1 is an integer right?Once user inputs data and presses the button to compute, it should not take very long to produce the answer (e.g., one minute max for 5 qubit calculations is one benchmark).Sounds like this was meant to be a performance requirement but it's turned into a requirement to have a performance requirement. If you want 5 qubits calculations to take 1 minute then just say that.Should be a website interface, with input blanks based on previous user input, i.e., create an account to save your simulations (takes in email and password), then a tab to look at previous text files from simulations and a tab to create a new simulation. Then, the user would input the number of qubits and starting state of qubits, click next and it will have you list gates for 1st qubit, click done, 2nd qubit, etc. If the option inputted is custom gate, a blank pops up where you can fill in the necessary data for the gate. When done, it transitions to a calculating style screen, and then gives the result and text file to download, with an option to save and an option to start over (last option available throughout).This is a use case not a requirement. The safety of the user's email, password, and text files must be high, as there could be important/confidential research-related information stored there.High? Please define high.Place on site to report bugs and request improvements.Does this just mean it's deployed so people can use it?Has common quantum gates available and a custom gate option.Again, define common quantum gates.Simulates decoherence, entanglement, and other common features of quantum computing.Here we need objective examples of what this can do when these features are working.Allows choice between ideal (no decoherence) and non-ideal (decoherence) quantum computer.This is fineGeneralizable to large numbers of qubits (runs as efficiently as possible). What is large? Everything runs as efficiently as possible until something better comes along. This is an attempt at a performance requirement that in the end doesn't demand anything.Documentation on-site for users.A popup that says ask a friend fulfills this requirement. Accurate results (basic cases, at minimum, checked against accepted results.This would work if the cases and accepted results were included or cited.Option to make text files public/private and a location to access public simulations?This seems to be two requirements smushed into one.Requirements are not a wish list. They are not a set of value statements. They should not be fuzzy. Each should clearly define when a feature is completed or not. |
_cogsci.8930 | I often encounter publications where the authors try to increase the SNR (signal-to-noise ratio) of electroencephalogram (EEG) signals. Some define a numeric value of SNR of EEG signals, but I am confused as to the exact definition of the SNR and how it can be measured for ERPs?Previously, I have calculated the SNR using a model of noise, for example a Gaussian model. I have also encountered SNR calculations based on a ratio between the mean and the standard deviation of a signal, but both of these approaches seem to be impractical. When I process the EEG signal, I would like to emphasize how the ERP changes in the EEG signal. All of this is strongly related with variance. If the variance approaches to zero, then theory tells me that SNR goes to infinity (a really good signal), but the signal that I will have is useless.Is there a better way to measure the SNR then I have mentioned? | How is the signal-to-noise ratio of an event-related-potential measured? | methodology;eeg;event related potential | Based on your comments I interpret your question as:(1) What is the definition of the signal-to-noise-ratio (SNR) and (2) how do I determine the SNR for event-related potential (ERP) amplitudes in an EEG signal?.(1) Signal-to-noise-ratio (SNR) is a term often encountered in electrophysiology (e.g. EEG) and signal processing and can be loosely defined as the ratio of the relevant signal divided by the noise level. The signal in this example is the ERP amplitude, while the noise is the remaining background activity in the EEG that distorts the ERP (unwanted noise). Noise includes hardware noise, movement artifacts by the subjects, random synchronized brain activity and so on. So SNR = signal/noise.(2) In case of ERP amplitude being the signal you are after, than the noise is the amplitude of the background EEG (SNRERP_amplitude = ERPamplitude / NOISEamplitude). The ERP amplitude can be defined by determining peak amplitude (e.g. relative to baseline). A straightforward (and widely accepted method) to characterize noise amplitude is determining the standard deviation (SD) of the entire EEG epoch (e.g., 500 ms) in which the ERP was recorded (Hu et al., 2010). Then, the SNR becomes ERPamplitude / SDEEGepoch. PS: your comment If the variance approaches to zero, then theory tells me that SNR goes to infinity (a really good signal), but the signal that I will have is useless.is incorrect. The signal is always part of the EEG epoch. Assuming there is a measurable ERP on a flatline background EEG (amplitude=0), than the signal will be the only thing that adds to the noise component. This is counter intuitive, but note that when noise amplitude is defined as, e.g., the SD, than this SD will be very small as it is determined across the entire EEG epoch. Hence, the peak-amplitude of the ERP will be much larger than the SD. In this ideal ERP recording the SNR will be large, but it will never become infinitely large. Reference- Hu et al., NeuroImage (2010); 50(1): 99-111 |
_unix.337614 | I have a bug that occurs with th AUR package freetype2-infinality due to the fact that it's no longer maintained. I want to install freetype2 instead but it requires to uninstall freetype2-infinality first however I am confronted with :resolving dependencies...looking for conflicting packages...:: freetype2 and freetype2-infinality are in conflict. Remove freetype2-infinality? [y/N] yerror: failed to prepare transaction (could not satisfy dependencies):: grip-git: removing freetype2-infinality breaks dependency 'freetype2-infinality'Any idea on how to fix this ? | How to replace a package when other package are depending on it? | arch linux | null |
_unix.340871 | I try to cross-compile a program for the aarch64 architecture with a x86_64 computer. The aarch64 libs are in place and my toolchain looks like this:set(CMAKE_SYSTEM_NAME Linux)set(CMAKE_SYSTEM_VERSION 1)set(CMAKE_SYSTEM_PROCESSOR aarch64)set(CMAKE_C_COMPILER aarch64-linux-gnu-gcc)set(CMAKE_CXX_COMPILER aarch64-linux-gnu-g++)set(CMAKE_FIND_ROOT_PATH /usr /usr/lib/aarch64-linux-gnu /opt/ros/kinetic /lib/aarch64-linux-gnu)set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM BOTH)set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)set(CMAKE_LIBRARY_PATH /usr/lib/aarch64-linux-gnu)set(CMAKE_IGNORE_PATH /usr/lib/x86_64-linux-gnu/ /usr/lib/x86_64-linux-gnu/lib/)But now I'm stuck with the following error:Linking CXX executable /home/martin/Desktop/AARCH64/test/devel_isolated/beginner_tutorials/lib/beginner_tutorials/talker/usr/lib/gcc-cross/aarch64-linux-gnu/5/../../../../aarch64-linux-gnu/bin/ld: warning: libicudata.so.55, needed by //usr/lib/aarch64-linux-gnu/libicuuc.so.55, not found (try using -rpath or -rpath-link)//usr/lib/aarch64-linux-gnu/libicuuc.so.55: undefined reference to `icudt55_dat'collect2: error: ld returned 1 exit statusCMakeFiles/talker.dir/build.make:113: recipe for target '/home/martin/Desktop/AARCH64/test/devel_isolated/beginner_tutorials/lib/beginner_tutorials/talker' failedmake[2]: *** [/home/martin/Desktop/AARCH64/test/devel_isolated/beginner_tutorials/lib/beginner_tutorials/talker] Error 1CMakeFiles/Makefile2:325: recipe for target 'CMakeFiles/talker.dir/all' failedmake[1]: *** [CMakeFiles/talker.dir/all] Error 2Makefile:138: recipe for target 'all' failedmake: *** [all] Error 2The files /usr/lib/aarch64-linux-gnu/libicuuc.so.55 and /usr/lib/aarch64-linux-gnu/libicudata.so.55 exist. But why is there a undefined reference error? Both files are copied from the arm64 target board. Is it possible to ignore this error and continue compilation?Do you have a hint for me? :)Thanks in advance! | Cross compilation for arm64 fails during linking | cross compilation | null |
_unix.131059 | Is there any difference between wine-wingdings and wingdings (the true-type font available with Microsoft Windows)? By difference, I just mean is there any symbol that could be represented by wingdings (the true-type font available with Microsoft Windows) could not be represented by wine-wingdings. | Difference between wine-wingdings and wingdings? | linux;windows;fonts;wine | null |
_codereview.7731 | I wrote a function (get_last_word_of) that takes a C string and a destination buffer, and then copies the last word into the buffer. The code was originally C++, and was changed into C later.#include <assert.h>#include <stdio.h>#include <string.h>// Check whether the two values are equal, and print an error if they are not.void AssertEq(int lhs, int rhs, int line) { if (lhs != rhs) printf(Fail: %d != %d (line %d), lhs, rhs, line);}#define ASSERT_EQ(lhs, rhs) do { AssertEq(lhs, rhs, __LINE__); } while (0);// Given a valid C string pointer, find the index of the last character that// is not whitespace. If str points to an empty string, return -1.int find_index_of_last_nonwhitespace(char const* str) { assert(str && str must point to a valid C string); int const length = strlen(str); // We subtract 1 to skip the null terminator. Seeing as we check p >= str // before we do anything else, this should be okay even for a str that is empty. char const* p = str + length - 1; while (p >= str && *p == ' ') --p; return p - str;}// Return the index of the beginning last word in the given C string. If the string// is empty, return 0.int find_index_of_beginning_of_last_word(char const* str) { assert(str && str must point to a valid C string); int end_of_last_word = find_index_of_last_nonwhitespace(str); // Subtract 1 so that we have the index of the first letter char const* p = str + end_of_last_word; while (p >= str && *p != ' ') --p; return p - str + 1; // To compensate for this being the index prior to the word.}// Given a destination buffer and a source C string pointer, copy the source// into the destination until a space or the end of the string is hit.// The buffer must be large enough to store the word and a \0 character after it.// If dest == src, simply truncate after the first word.void wordcpy(char* dest, char const* src) { assert(src && src must point to a valid C string); assert(dest && dest must point to a valid buffer); char* d = dest; char const* s = src; for ( ; *s != '\0' && *s != ' '; ++s, ++d) *d = *s; *d = '\0';}// Given a pointer to a C string, and a pointer to an output buffer that is at least// as large as the last word in the input plus one, copy the last word of the input// into the output buffer.void get_last_word_of(char const* input, char* output) { assert(input && input must be a valid C string); assert(output && output must be a valid buffer); int index_of_last_word = find_index_of_beginning_of_last_word(input); wordcpy(output, input + index_of_last_word);}int main() { ASSERT_EQ(find_index_of_last_nonwhitespace(Test ), 3); ASSERT_EQ(find_index_of_last_nonwhitespace(Test), 3); ASSERT_EQ(find_index_of_last_nonwhitespace(Te st ), 4); ASSERT_EQ(find_index_of_last_nonwhitespace(Te st), 4); ASSERT_EQ(find_index_of_last_nonwhitespace(), -1); ASSERT_EQ(find_index_of_last_nonwhitespace( ), -1); ASSERT_EQ(find_index_of_beginning_of_last_word(Test), 0); ASSERT_EQ(find_index_of_beginning_of_last_word(Test ), 0); ASSERT_EQ(find_index_of_beginning_of_last_word(Test test), 5); ASSERT_EQ(find_index_of_beginning_of_last_word(Test test ), 5); ASSERT_EQ(find_index_of_beginning_of_last_word(), 0); ASSERT_EQ(find_index_of_beginning_of_last_word( ), 0); char buf[100]; wordcpy(buf, Hello); ASSERT_EQ(strcmp(buf, Hello), 0); wordcpy(buf, Hello ); ASSERT_EQ(strcmp(buf, Hello), 0); wordcpy(buf, ); ASSERT_EQ(strcmp(buf, ), 0); return 0;}I'm primarily interested in:What inputs (if any) could cause these functions to perform undefined behaviour?Are there enough comments?Is the ASSERT_EQ macro safe to use, and is there any way to let it be used with types other than int? (I used templates in C++, but am at a loss in C.)Would there be a significant advantage to using size_t instead of int here?Are the tests sufficient? Are there any cases I missed? Are some unnecessary?Any further nitpicking is of course welcome. | Defensive programming in C | c;strings | Found some inputs that could cause wordcpy to perform undefined behaviour. See below.Enough comments? Pretty close, though some needed tweaking. What IS lacking is some definition of what is meant by word, space, whitespace especially as they relate to the presence of punctuation, tabs, newlines, etc.As for ASSERT_EQ, I'm pretty sure you need separate per-type macros, functions, and format strings in C.size_t would probably be cleaner for all lengths and offsets, but I don't know of any specific environments where int would be an actual issue. Are the tests sufficient? Cases missed? I added a few and suggested the shape of a few more. Are some unnecessary? You never know when you'll break an edge case.I didn't compile anything, so consider all mods to be c-like pseudo code.#include <assert.h>#include <stdio.h>#include <string.h>// Check whether the two values are equal, and print an error if they are not.void AssertEq(int lhs, int rhs, int line) { if (lhs != rhs)OP had printf(... fprintf(stderr, Fail: %d != %d (line %d), lhs, rhs, line);}#define ASSERT_EQ(lhs, rhs) do { AssertEq(lhs, rhs, __LINE__); } while (0);// Given a valid C string pointer, find the index of the last character thatOP had ...If str points to an empty string, return -1.// is not whitespace. If str points to an empty or all-whitespace string, return -1.int find_index_of_last_nonwhitespace(char const* str) { assert(str && str must point to a valid C string); int const length = strlen(str); // We subtract 1 to skip the null terminator. Seeing as we check p >= str // before we do anything else, this should be okay even for a str that is empty. char const* p = str + length - 1;OP had while (p >= str && *p == ' ') while (p >= str && isspace(*p)) --p; return p - str;}OP had ...index of the beginning last word ... is empty, return 0.// Return the index of the beginning of the last word in the given C string. If the string// is empty or all whitespace, return 0.Design Note: It seems a little strange that you get the same 0 result for inputs abc and int find_index_of_beginning_of_last_word(char const* str) { assert(str && str must point to a valid C string); int end_of_last_word = find_index_of_last_nonwhitespace(str);OP had // Subtract 1 so that we have the index of the first letter(Comment removed -- no subtraction in sight)Suggestion: add a reassuring comment around here about what happens for an empty/blank input. char const* p = str + end_of_last_word;OP had while (p >= str && *p != ' ') while (p >= str && ! isspace(*p)) --p; return p - str + 1; // To compensate for this being the index prior to the word.}Needs buffer overlap validation -- passed a dest pointer between src+1 and the last character in the first word of src, this will loop forever trashing memory.// Given a destination buffer and a source C string pointer, copy the source// into the destination until a space or the end of the string is hit.// The buffer must be large enough to store the word and a \0 character after it.// If dest == src, simply truncate after the first word.void wordcpy(char* dest, char const* src) { assert(src && src must point to a valid C string); assert(dest && dest must point to a valid buffer); char* d = dest; char const* s = src;Do we really mean space or general white space including \n \t, etc.? Up until now, I had been assuming white space as defined by isspace, so I'm following through, here.OP had for ( ; *s != '\0' && *s != ' '; ++s, ++d) for ( ; *s != '\0' && ! isspace(*s); ++s, ++d) *d = *s; *d = '\0';}Consistency in argument ordering (and argument naming? dest/output src/input) between wrdcpy and this function might reduce caller confusion and might improve readability.// Given a pointer to a C string, and a pointer to an output buffer that is at least// as large as the last word in the input plus one, copy the last word of the input// into the output buffer.void get_last_word_of(char const* input, char* output) { assert(input && input must be a valid C string); assert(output && output must be a valid buffer); int index_of_last_word = find_index_of_beginning_of_last_word(input); wordcpy(output, input + index_of_last_word);}int main() { ASSERT_EQ(find_index_of_last_nonwhitespace(Test ), 3); ASSERT_EQ(find_index_of_last_nonwhitespace(Test), 3); ASSERT_EQ(find_index_of_last_nonwhitespace(Te st ), 4); ASSERT_EQ(find_index_of_last_nonwhitespace(Te st), 4); ASSERT_EQ(find_index_of_last_nonwhitespace(), -1); ASSERT_EQ(find_index_of_last_nonwhitespace( ), -1); ASSERT_EQ(find_index_of_beginning_of_last_word(Test), 0); ASSERT_EQ(find_index_of_beginning_of_last_word(Test ), 0); ASSERT_EQ(find_index_of_beginning_of_last_word(Test test), 5); ASSERT_EQ(find_index_of_beginning_of_last_word(Test test ), 5); ASSERT_EQ(find_index_of_beginning_of_last_word(), 0); ASSERT_EQ(find_index_of_beginning_of_last_word( ), 0);Add: ASSERT_EQ(find_index_of_beginning_of_last_word( Test ), 1); ASSERT_EQ(find_index_of_beginning_of_last_word( Test), 1); ASSERT_EQ(find_index_of_beginning_of_last_word( Test ), 2); ASSERT_EQ(find_index_of_beginning_of_last_word( Test), 2);Suggestion: (Re)initialize buf before each test to a distinctive pattern like 'XXXXXX...'and validate that buf[strlen(buf)+1] is still 'X'. char buf[100]; wordcpy(buf, Hello); ASSERT_EQ(strcmp(buf, Hello), 0); wordcpy(buf, Hello ); ASSERT_EQ(strcmp(buf, Hello), 0); wordcpy(buf, ); ASSERT_EQ(strcmp(buf, ), 0);Test the claim made in the wordcpy comment that it will just null out the first space when dest == src. strcpy(buf, ); strcpy(buf+strlen(buf)+1, XYZ); wordcpy(buf, buf); ASSERT_EQ(strcmp(buf, ), 0); ASSERT_EQ(strcmp(buf+strlen(buf)+1, XYZ), 0); strcpy(buf, ); strcpy(buf+strlen(buf)+1, XYZ); wordcpy(buf, buf); ASSERT_EQ(strcmp(buf, ), 0); ASSERT_EQ(strcmp(buf+strlen(buf)+1, ), 0); ASSERT_EQ(strcmp(buf+strlen(buf)+2, XYZ), 0); strcpy(buf, ); strcpy(buf+strlen(buf)+1, XYZ); wordcpy(buf, buf); ASSERT_EQ(strcmp(buf, ), 0); ASSERT_EQ(strcmp(buf+strlen(buf)+1, ), 0); ASSERT_EQ(strcmp(buf+strlen(buf)+3, XYZ), 0); strcpy(buf, ABC); strcpy(buf+strlen(buf)+1, XYZ); wordcpy(buf, buf); ASSERT_EQ(strcmp(buf, ABC), 0); ASSERT_EQ(strcmp(buf+strlen(buf)+1, XYZ), 0); strcpy(buf, ABC XYZ); wordcpy(buf, buf); ASSERT_EQ(strcmp(buf, ABC), 0); ASSERT_EQ(strcmp(buf+strlen(buf)+1, XYZ), 0); strcpy(buf, ABC XYZ); wordcpy(buf, buf); ASSERT_EQ(strcmp(buf, ABC), 0); ASSERT_EQ(strcmp(buf+strlen(buf)+1, XYZ), 0);Try strange offsets. strcpy(buf, ABC XYZ); wordcpy(buf, buf+2); ASSERT_EQ(strcmp(buf, C), 0); ASSERT_EQ(strcmp(buf+strlen(buf)+1, C XYZ), 0); strcpy(buf, ABC XYZ); wordcpy(buf, buf+2); ASSERT_EQ(strcmp(buf, C), 0); ASSERT_EQ(strcmp(buf+strlen(buf)+1, C XYZ), 0);Fix the forever loop before trying these strange offsets. strcpy(buf, ABC XYZ); // Until fixed, this will trash memory with ABABAB... // wordcpy(buf+2, buf); // Assuming this will be caught and do nothing. ASSERT_EQ(strcmp(buf, ABC XYZ), 0);Also, both to show that it works as intended AND to give examples of what you intend, add tests for handling of non-alphabetics, especially common cases like punctuation, tabs, and newlines.Suggestion: test get_last_word_of return 0;} |
_cs.39760 | According to Galvin and Silberschatz, 5 queues are maintained in multilevel queue scheduling, each for: System Process Interactive ProcessInteractive Editing ProcessBatch processStudent Process where System process has highest priority and Student process has lowest priority. What is meant by Student Process? Also, I only have a vague idea about the rest except system process. If possible, elucidate them. | What is a student process? | terminology;operating systems;process scheduling;os kernel;multi tasking | null |
_unix.184061 | I am an infrequent user of UNIX, I'm sure this will be fairly trivial for any regular user so I appologize for that. I have the following code: for file in /home/sub1/samples/aaa*/*_novoalign.bam do samtools depth -r chr9:218026635-21994999 *_novoalign.bam < $file > /home/sub2/sub3/${file}.out doneI was hoping the output would be sent to a file in sub2/sub3/ with its name like the input folder. It says 'no file or directory'. I would ideally like to send it here with the '_novoalign.bam' removed and a new ending eg '_output.txt' added. Any tips?p.s. I don't have permission to write to the directory in which the input file is found. | Unix how to loop through directories, send output to another directory with base name of input file | shell script;io redirection;filenames | null |
_softwareengineering.18180 | I saw this in a job posting for an ASP.net developer.An understanding of basic software development practices such as ...and Dependency Analysis.I read the wikipedia entry for Dependency Analysis and understand that it basically means one thing depends on the other so you can't reorder or parallelize them.What does this mean in practice? Is there a tool that is used to do a Dependency Analysis? What should I know about it for an interview and in practice if I get the job? | What is dependency Analysis and how is it done? | .net;dependency analysis | null |
_softwareengineering.271778 | I'm making a mobile application, and I use JSON Web Token Authentication (JWT Auth), but I have three questions about:Should I use refresh-tokens or non-expiring access tokens?In case I use refresh-tokens, when the token expires, should I sign out the user (and force the user to login again) or create a new one and send it back to the app so it can be used for future requests?How should I save the token on the mobile (database, preferences,etc.)?Any help and resource about this (books,documents,blog,etc.) would be appreciated, thanks in advance! | How to handle authentication to web service from mobile? | design patterns;web services;mobile;app | null |
_codereview.131875 | As stated in the title, the code produces a simple drop-down menu that allows you to select your Starter, Main and Dessert courses, and will show your order in a small box underneath (like a bill).$(document).ready(function() { //Variables var selectedStarter = { dish: (None), price: 0 }; var selectedMain = { dish: (None), price: 0 }; var selectedDessert = { dish: (None), price: 0 }; var starter = { firstDish: Salad, firstDishPrice: 15, secondDish: Soup, secondDishPrice: 7, thirdDish: Fish rolls, thirdDishPrice: 12 }; var main = { firstDish: Steak, firstDishPrice: 17, secondDish: Salmon, secondDishPrice: 12, thirdDish: Rissotto, thirdDishPrice: 9 }; var dessert = { firstDish: Sorbet, firstDishPrice: 4, secondDish: Fruit salad, secondDishPrice: 6, thirdDish: Apple pie, thirdDishPrice: 5 }; function total() { return selectedStarter.price + selectedMain.price + selectedDessert.price; } function selectedStarterFnc(dish, price) { selectedStarter.price = price; selectedStarter.dish = dish; $(#total).html(total()); return dish + ( + price + ); } function selectedMainFnc(dish, price) { selectedMain.price = price; selectedMain.dish = dish; $(#total).html(total()); return dish + ( + price + ); } function selectedDessertFnc(dish, price) { selectedDessert.price = price; selectedDessert.dish = dish; $(#total).html(total()); return dish + ( + price + ); } // Instantiating HTML Button Elements // Starter Elements document.getElementById(btStarter1).value = starter.firstDish + : + starter.firstDishPrice; document.getElementById(btStarter2).value = starter.secondDish + : + starter.secondDishPrice; document.getElementById(btStarter3).value = starter.thirdDish + : + starter.thirdDishPrice; // Main Elements document.getElementById(btMain1).value = main.firstDish + : + main.firstDishPrice; document.getElementById(btMain2).value = main.secondDish + : + main.secondDishPrice; document.getElementById(btMain3).value = main.thirdDish + : + main.thirdDishPrice; // Dessert Elements document.getElementById(btDessert1).value = dessert.firstDish + : + dessert.firstDishPrice; document.getElementById(btDessert2).value = dessert.secondDish + : + dessert.secondDishPrice; document.getElementById(btDessert3).value = dessert.thirdDish + : + dessert.thirdDishPrice; // Your Order: Elements document.getElementById(selectedStarter).innerHTML = selectedStarter.dish + ( + selectedStarter.price + ); document.getElementById(selectedMain).innerHTML = selectedMain.dish + ( + selectedMain.price + ); document.getElementById(selectedDessert).innerHTML = selectedDessert.dish + ( + selectedDessert.price + ); // Functions (JQuery) // Main menu onClicks handler $(#btMenu).click(function() { $(#liMainMenu).toggle(slow); }); $(#btStarter).click(function() { $(#liStarter).toggle(slow, function() { if ($(this).css(display) == none) { $(#btStarter).css(background-color, black); } else { $(#btStarter).css(background-color, blue); } }); }); $(#btMain).click(function() { $(#liMain).toggle(slow, function() { if ($(this).css(display) == none) { $(#btMain).css(background-color, black); } else { $(#btMain).css(background-color, blue); } }); }); $(#btDessert).click(function() { $(#liDessert).toggle(slow, function() { if ($(this).css(display) == none) { $(#btDessert).css(background-color, black); } else { $(#btDessert).css(background-color, blue); } }); }); // Starter onClicks $(#btStarter1).click(function() { $(#liStarter).children(li).children(input).css(background-color, red); $(this).css(background-color, green); $(#selectedStarter).html(selectedStarterFnc(starter.firstDish, starter.firstDishPrice)); }); $(#btStarter2).click(function() { $(#liStarter).children(li).children(input).css(background-color, red); $(this).css(background-color, green); $(#selectedStarter).html(selectedStarterFnc(starter.secondDish, starter.secondDishPrice)); }); $(#btStarter3).click(function() { $(#liStarter).children(li).children(input).css(background-color, red); $(this).css(background-color, green); $(#selectedStarter).html(selectedStarterFnc(starter.thirdDish, starter.thirdDishPrice)); }); // Main onClicks $(#btMain1).click(function() { $(#liMain).children(li).children(input).css(background-color, red); $(this).css(background-color, green); $(#selectedMain).html(selectedMainFnc(main.firstDish, main.firstDishPrice)); }); $(#btMain2).click(function() { $(#liMain).children(li).children(input).css(background-color, red); $(this).css(background-color, green); $(#selectedMain).html(selectedMainFnc(main.secondDish, main.secondDishPrice)); }); $(#btMain3).click(function() { $(#liMain).children(li).children(input).css(background-color, red); $(this).css(background-color, green); $(#selectedMain).html(selectedMainFnc(main.thirdDish, main.thirdDishPrice)); }); // Dessert onClicks $(#btDessert1).click(function() { $(#liDessert).children(li).children(input).css(background-color, red); $(this).css(background-color, green); $(#selectedDessert).html(selectedDessertFnc(dessert.firstDish, dessert.firstDishPrice)); }); $(#btDessert2).click(function() { $(#liDessert).children(li).children(input).css(background-color, red); $(this).css(background-color, green); $(#selectedDessert).html(selectedDessertFnc(dessert.secondDish, dessert.secondDishPrice)); }); $(#btDessert3).click(function() { $(#liDessert).children(li).children(input).css(background-color, red); $(this).css(background-color, green); $(#selectedDessert).html(selectedDessertFnc(dessert.thirdDish, dessert.thirdDishPrice)); });});.button { background: #353535; outline: solid 2px #353535; border: solid 2px white; color: white; padding: 10px 15px; text-decoration: none; width: 200px; margin-top: 50px;}.ul li { display: inline; margin-right: 8px;}.ul { display: none;}.table { margin-top: 50px; border: 10px solid blue; width: 33%;}.table th { padding-top: 20px; text-align: left; font-size: 24px; margin: 30px;}.table tr,td { text-align: left; padding-left: 50px; padding-right: 20px; padding-top: 20px; padding-bottom: 20px}<!doctype html><html lang=en><head> <meta charset=utf-8> <title>Restaurant Menu With JQuery</title> <link rel=stylesheet type=text/css href=style.css> <script src=https://code.jquery.com/jquery-1.12.4.js></script></head><body> <input type=button class=button id=btMenu value=Menu> <ul id=liMainMenu class=ul> <li> <input type=button class=button id=btStarter value=Starter> </li> <li> <input type=button class=button id=btMain value=Main> </li> <li> <input type=button class=button id=btDessert value=Dessert> </li> </ul> <ul id=liStarter class=ul> <li> <input type=button class=button id=btStarter1 value=> </li> <li> <input type=button class=button id=btStarter2 value=> </li> <li> <input type=button class=button id=btStarter3 value=> </li> </ul> <ul id=liMain class=ul> <li> <input type=button class=button id=btMain1 value=> </li> <li> <input type=button class=button id=btMain2 value=> </li> <li> <input type=button class=button id=btMain3 value=> </li> </ul> <ul id=liDessert class=ul> <li> <input type=button class=button id=btDessert1 value=> </li> <li> <input type=button class=button id=btDessert2 value=> </li> <li> <input type=button class=button id=btDessert3 value=> </li> </ul> <table class=table> <th>Your Order:</th> <tr> <td>Starter :</td> <td id=selectedStarter></td> </tr> <tr> <td>Main :</td> <td id=selectedMain></td> </tr> <tr> <td>Dessert :</td> <td id=selectedDessert></td> </tr> <tr> <td>Total :</td> <td id=total></td> </tr> </table></body><script src=app.js type=text/javascript></script></html> | Simple restaurant menu | javascript;beginner;jquery;html;css | Let me first warn you that you have fallen into a classic anti-pattern. When you see yourself tempted to write code that starts naming variables/objects/item with names like btStarter* (with * being numbers), usually this means you should be thinking of these things as an array.Also you have a lot of repetitive code that you can refactor out.You need to begin to come to terms that jQuery is especially powerful at dealing with collections of DOM elements. So again, when you begin doing things like make element ID's like btStarter* this probably means you should be dealing with the collections of buttons logically using the same class.Finally, you really haven't embraced an object oriented paradigm at all, which is something that could really help organize your code. I will show you an alternate implementation that you might find helps prompt some different thinking.This may seem like a lot of code, but you might find this sort of approach helpful over the long term with regards to being able to more easily maintain and reuse this code.The approach:Put your logic into classes and import via include file that you load in document header. This also enables this logic to be transportable. You need to create another menu page? Just include this file.Example: // build Dish class function Dish(name, price) { // not shown - you should validate proper data types and values // for name(string) and price(int or float, positive value, etc.) this.name = name; this.price = price; // in future you might add other properties here (ingredients, picture URL's, etc.) } // add methods to the Dish prototype to expose dish behavior Dish.prototype = { // not currently used }; // build Menu class to store menu information function Menu() { this.categories = []; this.menuTree = {}; } // add methods to the Menu prototype to expose menu behavior Menu.prototype = { addCategory: function addCategory(category) { // not shown - you should validate proper data type // for category(string) // add category to menu tree this.menuTree[category] = []; // add category to list of categories on Menu this.categories.push(category); // return the object for method chaining return this; }, addDish: function addDish(dish, category) { if(dish instaceof Dish === false) { console.log('Need to pass a Dish object.'); return null; } // if category was not passed, use last category added if(category === undefined) { var lastCatArray = this.categories.slice(-1); category = lastCatArray[0]; } this.menuTree[category].push(dish); return this; } } // build object to define an orderable Meal // we will later use this class when rendering the menu selection // this simple example assumes that the meas consists of one item from // each menu category function Meal(menu) { // not shown - validate valid menu object is passed // set menu object in this class this.menu = menu; // object to store current menu selections this.menuSelections = {}; // build out slots to hold menu selections this.menu.categories.forEach(function (value, index) { this.menuSelections[value] = null; }); } // add methods to Meal Meal.prototype = { selectCourseOption: function(course, dish) { // not shown - validate course and dish parameters this.menuSelections[course] = dish; return this; }, getMealCost: function() { var totalCost = 0; for (course in this.menuSelections) { totalCost += this.menuSelections[course].price; } return totalCost; } } // create class to render HTML view necessary for meal selection function MealSelectionHTMLFactory(meal, config) { // not shown - validate valid Meal object passed this.meal = meal; // extend/override default config if if anything passed // not currently used this.config = $.extend(this.config, config); } MealSelectionHTMLFactory.prototype = { // store some base config for rendering // we apply this at prototype level, // as we want to apply to all instances of this class this.config = { // Not used currently. It could be good idea to put things // such as default DOM element id and class names into this // config such that they are not hard coded into the jQuery // DOM element generation code in this class. }, renderMenuDOM(targetSelector) { // local variable to use as handle to menu tree var menuTree = this.meal.menu.menuTree; // start building elements for DOM inserting // you may ultimately weant to consider some sort of // templating engine, rather than building DOM elements this way // create wrapper div to contain this whole thing var $menuDOM = $('div'); // main button $menuDOM.append( '<input type=button class=button id=btMenu value=Menu>' ); // start with menu shell $menuDOM.append( '<ul id=liMainMenu class=ul>' ); // get handle for main menu $mainMenu = $menuDom.find('#liMainMenu'); // create shell for order table var $orderTable = $( '<table id=orderTable class=table>' ); $orderTable.append('<th>Your Order:</th>'); // iterate through courses updating navigation, selection form // and order summary table for (course in this.menuSelections) { // update main menu $mainMenu.append( '<li>' + '<input type=button class=button courseToggle value=' + course + '></li>' ); // add course menu // note that I am applying courseMenu class to this item var $courseMenu = $( '<ul class=ul courseMenu ' + course + '>' ); // iterate dish options for this course adding them to menu for (var i = 0; i < menuTree[course].length; i++)) { var localDish = menuTree[course][i]; // note we capture current course and index position of dish // into data-* properties var $dish = $.( '<li>' + '<input type=button class=button dishToggle value=' + localDish.name + ' data-course= + course + ' ' + data-index=' + i + '></li>' ); $courseMenu.append($dish); } // add this course menu to menu DOM $menuDOM.append($courseMenu); // update order table var $tableRow = $.('<tr class=orderTableRow ' + course + '>'); $tableRow.append('<td>' + course + ' :</td>'); $tableRow.append('<td class=selectedDish>'); $orderTable.append($tableRow); } // add total area to order table $orderTable.append( '<tr><td>Total :</td><td id=mealTotal>0</td>' ); // now add elements to DOM at target selector $(targetSelector).append($menuDom); $(targetSelector).append($orderTable); }, addEventHandlers: function () { // local variable for access meal var mealLocal = this.meal; // local variable to use as handle to menu tree var menuTree = mealLocal.menu.menuTree; // main button behavior toggle $(#btMenu).click(function() { // togle button class $(this).toggleClass('active'); // show/hide menu $(#liMainMenu).toggle(slow); }); // course menu toggles $('.courseToggle').click(function() { var clickedCourse = $(this).attr(value); // change button class $(this).toggleClass('active'); // show/hide menu $('.courseMenu.' + clickedCourse).toggle('slow'); }); // dish selection toggles $('.dishToggle').click(function() { // get jQuery collection for all dishes of this same course var $allDishesForCourse = $(this) .closest('.courseMenu') .find('.dishToggle'); // toggle all dishes into notSelected state $allDishesForCourse.addClass('notSelected'); // put selected class in selected state $(this).removeClass('notSelected'); $(this).addClass('selected'); // update meal object to reflected selected item // first get data from clicked element so we can locate // the dish object in menu tree var selectedDishCourse = $(this).data('course'); var selectedDishIndex = parseInt($(this).data('index')); // get dish object var selectedDish = menuTree[selectedDishCourse][selectedDishIndex]; // set dish object to meal mealLocal.selectCourseOption(selectedDishCourse, selectedDish); // now update the order table // first course selection $('.orderTableRow.' + selectedDishCourse + ' .selectedDish) .html(selectedDish.name); // thence total price $('#mealTotal').html(mealLocal.getMealCost()); }); }, renderMenu: function(targetSelector) { this.renderMenuDOM(targetSelector); this.addEventHandlers(); } }Now, you can REALLY simplify your code in the document.ready handler. This code should only contain the specific configuration and execution information for this specific menu page.Example:$(document).ready(function() { // build your actual menu var menu = new Menu(); menu.addCategory('Starter') .addDish(new Dish('Salad', 15)) // repeat for other dishes in this category .addDish(...); menu.addCategory('Main') // add dishes to this category as shown above .addDish(...); menu.addCategory('Dessert') // add dishes to this category as shown above .addDish(...); // create Meal instance var meal = new Meal(menu); // render menu view var factory = MealSelectionHTMLFactory(meal); factory.renderMenu('body');}You also simplify your HTML source code, as the classes now perform all the HTML DOM element creation necessary to build the meal selector. All you need to do is tell the MealSelectionHTMLFactory what DOM element to insert the menu into and it does its thing. You have componetized the meal selection menu such that it can be reused anywhere.Example:<!doctype html><html lang=en><head> <meta charset=utf-8> <title>Restaurant Menu With JQuery</title> <link rel=stylesheet type=text/css href=style.css> <script src=https://code.jquery.com/jquery-1.12.4.js></script> <script src=https://yourdomain/path/to/jsincludes.js></script></head><body></body> |
_datascience.14142 | The Hopkins statistic, is a statistic which gives a value which indicates the cluster tendency, in other words: how well the data can be clustered.If the value is between {0.01, ...,0.3}, the data is regularly spaced.If the value is around 0.5, it is random.If the value is between {0.7, ..., 0.99}, it has a high tendency to cluster.I have a question about my implementation of the Hopkins statistic.Is it correct? If so, other people can use it :)X is the data with shape (n,m).d = len(vars) # columnsn = len(X) # rowsm = int(0.1 * n) # heuristic from article [1]from sklearn.neighbors import NearestNeighborsnbrs = NearestNeighbors(n_neighbors=1, algorithm='brute').fit(X)from random import samplerand_X = sample(range(0, n, 1), m)ujd = []wjd = []for j in range(0, m): u_dist, _ = nbrs.kneighbors(np.random.normal(size=(1, d)).reshape(1, -1), 2, return_distance=True) ujd.append(u_dist[0][1]) w_dist, _ = nbrs.kneighbors(X[rand_X[j]].reshape(1, -1), 2, return_distance=True) wjd.append(w_dist[0][1])H = sum(ujd) / (sum(ujd) + sum(wjd))print HAny recommendations are much appreciated.[1] Validating Clusters using the Hopkins Statistic from IEEE 2004. | Cluster tendency using Hopkins statistic implementation in Python | machine learning;python;clustering;statistics;unsupervised learning | null |
_unix.323054 | I'm using a Lenovo Thinkpad Yoga 14 with OpenSUSE 42.2 64 bit. When I want to use the touch screen to start an application from the desktop by touching an icon, the mouse pointer is moved over the icon but nothing is clicked and started. When I try the same thing on the application dashboard, it is only working when I hit the middle of the area between the symbol and the title below. I installed the tablet PC package right at the beginning. Is this a bug, a compatibility issue or am I missing something? | Icons on KDE application dashboard and desktop not touchable | kde;opensuse;plasma;touch screen | null |
_webapps.72870 | I have a some data in key-value pairs setup like so: A B1 Key: Value:2 Cars 53 Bikes 44 Vans 95 Trucks 6What I can't seem to figure out (mind-block) is the formula to answer this: Product with higest sales: <answer should be 'Vans'>What formula would I need to get the result Vans? I've tried this: =FILTER(A2:A6, MAX(B2:B6))To which I get an error stating that the Fliter has mismatched array sizes. | Google Sheets list key with highest value in key value pair | worksheet function;google spreadsheets | You need to specify a condition, not just a value, for the FILTER function.So:=FILTER(A2:A6, B2:B6 = MAX(B2:B6))I have set up a demonstration spreadsheet for this, feel free to have a look or copy it. |
_unix.189388 | Can a who command be integrated to find the current logged in users password file entry? | How would I grep for a password file entry without using 'username' | grep;who | null |
_webapps.4421 | How can I get mint.com to work correctly with my ING Direct account?For the life of me I can't get it to validate and pull the data down correctly, is there some trick to it? Seems like their screen scraping isn't working correctly. | Using Mint.com to pull and validate data from my ING Direct account | import;mint.com | null |
_codereview.79150 | I am creating a simple support ticket system. I thought It would be a nice little feature to show the current date and time. Since I want to show the current time I thought JavaScript would be best versus using PHP. I have looked at different questions posted by other user about the topic and created the following snippet. My question is if this is a efficient way to get and display the date and time using JavaScript date object. I also thought is would be appropriate to use the <time> tag. I also ask if I have used it in the correct form.JavaScript and HTMLvar monthName = new Array('January', 'Febuary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');var hourap = new Array(12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);function showTime(){ var dateObj = new Date(); var day = dateObj.getDate(), month = dateObj.getMonth(), year = dateObj.getFullYear(), hour = dateObj.getHours(), minutes = (dateObj.getMinutes()<=9?'0'+dateObj.getMinutes():dateObj.getMinutes()); var string = monthName[month]+ ' '+day+ ', '+year+ '<br />'+hourap[hour]+ ':'+minutes+ ' '+(hour<=11?'am':'pm'); var timeDiv = document.getElementById('time'); if(timeDiv !== null) { timeDiv.innerHTML = string; timeDiv.setAttribute('datetime',year+'-'+(month+1<=9?'0'+(month+1):month+1)+'-'+day+' '+hour+':'+minutes); };};setInterval(showTime,1000);<time id=time></time>HTML output<time id=time datetime=2015-01-30 22:00>January 30, 2015<br>10:00 pm</time>Any suggestions or comments would be appreciated. Please note that I wish to script it using pure JavaScript and not jQuery. | Displaying current date and time using JavaScript and HTML time tag | javascript;datetime;html5 | null |
_unix.204963 | If I'm asked for the sudo password, after typing it in correctly, the terminal moves on almost instantaneously. However, if I mistype my password, it takes a few seconds before working it out and asking me again. I timed it a few times, and mostly takes around 2.2 seconds.Why does it take so much longer, and is there a way to speed it up?(I have a few dodgy keys on my mechanical keyboard that often don't register, or register twice, so I often mistype my password.) | Why is sudo slow when I mistype my password? | terminal;sudo | The built-in delay is to slow down the process of password guessing. Looks like someone could programmatically guess about 27 potential passwords per minute, which, as you've observed is a good deal less than if there was no delay. |
_codereview.71790 | I would like to know if my approach is correct and how could it could be improved? Also, is there a way to get rid of the relation between the Piece and the Board? At the moment, I am storing the position of the piece both in the piece and on the board. Is there some way to change that?I have considered a Game to contain an instance of the Board and the two Players (one black, one white). The pieces contain a connection to the Board, because in order to determine if they are valid, we need to know the relationship to other pieces.Could I use design patterns for this? Should I use interfaces instead of the super class?Game.javapublic class Game { private Board board = new Board(); private Player white; private Player black; public Game() { super(); } public void setColorWhite(Player player) { this.white = player; } public void setColorBlack(Player player) { this.black = player; } public Board getBoard() { return board; } public void setBoard(Board board) { this.board = board; } public Player getWhite() { return white; } public void setWhite(Player white) { this.white = white; } public Player getBlack() { return black; } public void setBlack(Player black) { this.black = black; } public boolean initializeBoardGivenPlayers() { if(this.black == null || this.white == null) return false; this.board = new Board(); for(int i=0; i<black.getPieces().size(); i++){ board.getSpot(black.getPieces().get(i).getX(), black.getPieces().get(i).getY()).occupySpot(black.getPieces().get(i)); } return true; }}Player.javapublic class Player { public final int PAWNS = 8; public final int BISHOPS = 2; public final int ROOKS = 2; public boolean white; private List<Piece> pieces = new ArrayList<>(); public Player(boolean white) { super(); this.white = white; } public List<Piece> getPieces() { return pieces; } public void initializePieces(){ if(this.white == true){ for(int i=0; i<PAWNS; i++){ // draw pawns pieces.add(new Pawn(true,i,2)); } pieces.add(new Rook(true, 0, 0)); pieces.add(new Rook(true, 7, 0)); pieces.add(new Bishop(true, 2, 0)); pieces.add(new Bishop(true, 5, 0)); pieces.add(new Knight(true, 1, 0)); pieces.add(new Knight(true, 6, 0)); pieces.add(new Queen(true, 3, 0)); pieces.add(new King(true, 4, 0)); } else{ for(int i=0; i<PAWNS; i++){ // draw pawns pieces.add(new Pawn(true,i,6)); } pieces.add(new Rook(true, 0, 7)); pieces.add(new Rook(true, 7, 7)); pieces.add(new Bishop(true, 2, 7)); pieces.add(new Bishop(true, 5, 7)); pieces.add(new Knight(true, 1, 7)); pieces.add(new Knight(true, 6, 7)); pieces.add(new Queen(true, 3, 7)); pieces.add(new King(true, 4, 7)); } }}Board.javapublic class Board { private Spot[][] spots = new Spot[8][8]; public Board() { super(); for(int i=0; i<spots.length; i++){ for(int j=0; j<spots.length; j++){ this.spots[i][j] = new Spot(i, j); } } } public Spot getSpot(int x, int y) { return spots[x][y]; }}Spot.javapublic class Spot { int x; int y; Piece piece; public Spot(int x, int y) { super(); this.x = x; this.y = y; piece = null; } public void occupySpot(Piece piece){ //if piece already here, delete it, i. e. set it dead if(this.piece != null) this.piece.setAvailable(false); //place piece here this.piece = piece; } public boolean isOccupied() { if(piece != null) return true; return false; } public Piece releaseSpot() { Piece releasedPiece = this.piece; this.piece = null; return releasedPiece; }}Piece.javapublic class Piece { private boolean available; private int x; private int y; public Piece(boolean available, int x, int y) { super(); this.available = available; this.x = x; this.y = y; } public boolean isAvailable() { return available; } public void setAvailable(boolean available) { this.available = available; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public boolean isValid(Board board, int fromX, int fromY, int toX, int toY){ if(toX == fromX && toY == fromY) return false; //cannot move nothing if(toX < 0 || toX > 7 || fromX < 0 || fromX > 7 || toY < 0 || toY > 7 || fromY <0 || fromY > 7) return false; return true; }}King.javapublic class King extends Piece{ public King(boolean available, int x, int y) { super(available, x, y); // TODO Auto-generated constructor stub } @Override public boolean isValid(Board board, int fromX, int fromY, int toX, int toY) { if(super.isValid(board, fromX, fromY, toX, toY) == false) return false; if(Math.sqrt(Math.pow(Math.abs((toX - fromX)),2)) + Math.pow(Math.abs((toY - fromY)), 2) != Math.sqrt(2)){ return false; } return false; }}Knight.javapublic class Knight extends Piece{ public Knight(boolean available, int x, int y) { super(available, x, y); } @Override public boolean isValid(Board board, int fromX, int fromY, int toX, int toY) { if(super.isValid(board, fromX, fromY, toX, toY) == false) return false; if(toX != fromX - 1 && toX != fromX + 1 && toX != fromX + 2 && toX != fromX - 2) return false; if(toY != fromY - 2 && toY != fromY + 2 && toY != fromY - 1 && toY != fromY + 1) return false; return true; }}Bishop.javapublic class Bishop extends Piece{ public Bishop(boolean available, int x, int y) { super(available, x, y); // TODO Auto-generated constructor stub } @Override public boolean isValid(Board board, int fromX, int fromY, int toX, int toY) { if(super.isValid(board, fromX, fromY, toX, toY) == false) return false; if(toX - fromX == toY - fromY) return true; return false; }}Rook.javapublic class Rook extends Piece{ public Rook(boolean available, int x, int y) { super(available, x, y); // TODO Auto-generated constructor stub } @Override public boolean isValid(Board board, int fromX, int fromY, int toX, int toY) { if(super.isValid(board, fromX, fromY, toX, toY) == false) return false; if(toX == fromX) return true; if(toY == fromY) return true; return false; }}Queen.javapublic class Queen extends Piece{ public Queen(boolean available, int x, int y) { super(available, x, y); } @Override public boolean isValid(Board board, int fromX, int fromY, int toX, int toY) { if(super.isValid(board, fromX, fromY, toX, toY) == false) return false; //diagonal if(toX - fromX == toY - fromY) return true; if(toX == fromX) return true; if(toY == fromY) return true; return false; }} | Design a chess game using object-oriented principles | java;object oriented;design patterns;game;chess | Without offering a deep code review (as I don't have a lot of specific Java knowledge), let's look at what a full move entails in chess:Player chooses piece to move.Piece makes legal move according to its own move rules.In addition to purely move-based rules, there's also capture logic, so a bishop cannot move from a1-h8 if there's a piece sitting on c3.If the player was previous under check and the move does not remove the check, it must be undone.If the move exposes check, it must be undone / disallowed.If player captures a piece, remove the piece (including en passant!)If the piece is a pawn reaching the back rank, promote it.If the move is a castling, set the new position of the rook accordingly. But a king and rook can only castle if they haven't moved, so you need to keep track of that. And if the king moves through a check to castle, that's disallowed, too.If the move results in a stalemate or checkmate, the game is over.There may be more even (?). This is a complicated step, more than just counting and subsequently occupying spaces.So my general intuition would be to just call:Game.move(currentSpot, NewSpot);And the move method would contain all the code to validate the steps above:Check Piece.isValidMove(currentSpot, newSpot); - probably need castling logic here since king moves more than 1 space and rook jumps the king)Check Player.isChecked() (which is just sugar for Player.Pieces[King].CanBeCaptured() - more fun logic here!)Check if newSpot contains a piece and if so, newSpot.Piece.Remove();Build some logic to call Piece.CheckEnPassant() (Piece is pawn, first move, 2 steps, past an enemy pawn who moved into capturing position on previous move - have fun with that!)Piece.CheckPromote() (Piece is pawn, move ends on opposing player's back rank)Check if Game.isOver(), which checks Game.isStaleMate() and Game.isCheckMate().Your Board class is highly anemic, you're only using it in your code as a proxy object for the array of spots. You might as well just create Board as an array of Spots in Game. In either case, you can already remove it from all your piece logic since all your logic is entirely predicated on the Xs and Ys you're passing in.UPDATEI would remove all your position properties from the piece. You're only using it as a proxy to figure out what spot the piece occupies during initializiation. Instead, remove Player.initializePieces() and just initialize the Board with the pieces in the right spot (Board.Spot.Piece = King, etc.) and then let players choose a color. |
_codereview.25581 | I have not completed this but want to make my own template library for wrapping the Win32 API to make it compatible with std::string/std::wstring... Here's a sample of what I've worked with so far. My questions are:Is this a good idea? Is it acceptable to undefine Windows API macros (e.g. #undef GetWindowText)?Is there perhaps a better way to do this besides changing the name scheme (e.g. getWindowText or GetWindowString as opposded to GetWindowText)? I prefer not to change the names.Note: Please don't provide answers like why don't you just use WTL? or just use MFC. I prefer to deal directly with the Windows API; I just want to make it easier to work with std::basic_string. Implementation#ifdef _WINUSER_#undef GetWindowTextLengthtemplate<typename _T> int GetWindowTextLength(HWND hWnd);template<> int GetWindowTextLength<wchar_t>(HWND hWnd) { return ::GetWindowTextLengthW(hWnd); }template<> int GetWindowTextLength<char>(HWND hWnd) { return ::GetWindowTextLengthA(hWnd); }#undef GetWindowTexttemplate<typename _T> std::basic_string<_T> GetWindowText(HWND hWnd);template<> std::basic_string<wchar_t> GetWindowText(HWND hWnd){ std::size_t len = GetWindowTextLength<wchar_t>(hWnd)+1; std::vector<wchar_t> buffer(len); ::GetWindowTextW(hWnd, buffer.data(), len); return std::basic_string<wchar_t>(buffer.begin(), buffer.end());}template<> std::basic_string<char> GetWindowText(HWND hWnd){ std::size_t len = GetWindowTextLength<char>(hWnd)+1; std::vector<char> buffer(len); ::GetWindowTextA(hWnd, buffer.data(), len); return std::basic_string<char>(buffer.begin(), buffer.end());}#endif//_WINUSER_Example Usagestd::basic_string<TCHAR> text = GetWindowText(hWnd); | std::string/std::wstring template wrapper for Win32 API | c++;template;windows;winapi | I have not completed this but want to make my own template library for wrapping the Win32 API to make it compatible with std::string/std::wstring...Is this a good idea?If you have the time to do that as an exercise, probably (there should be a lot of effort involved).If you want to create a library for future use with an intentional name clash, probably no.Is it acceptable to undefine Windows API macros (e.g. #undef GetWindowText)?Not really. If you are careful about it, you can make it work, but these macros can change, their implementation can change depending on where MS wants to take their API in the future and what is behind them may change. You are better off writing your library so that there are no name clashes with MS's macro names.Is there perhaps a better way to do this besides changing the name scheme (e.g. getWindowText or GetWindowString as opposded to GetWindowText)? I prefer not to change the names.No. You are better off using new names. Seeing the old names in code would make me (as a client of your lib) assume they have the same semantics, parameters and behavior as the WinAPI defines (macros and all). I would assume the names belong to WinAPI and look automatically to MSDN documentation if I had questions (as in, not in your library's documentation).Using the same name would create confusion for other people using your code, for you as a developer (consider what happens when you have an error due to a macro name accidentally included where you define your API: you'd have errors caused by name clash in macro expansion, when you don't want the macro defined. For you it would be (almost) easy to fix, as you know the problem. Consider what happens though, when a client of your code writes:#include <yourcode.h> // undefines macros and defines your interface#include <windows.h> // redefines macros and causes errorsThis is an error that is easy to make for client code (especially for someone not familiar with the implementation details/constraints of your library) and it is something that you cannot enforce in your library code (you actually could, if you issue #error directives in your includes but that is as brittle as the whole concept - MS changes some implementation details and you have to update your code).Also consider that your library would have to be complete from the start - if you only implement wrappers for what you need and discover you need a new API, you'd have to define a wrapper to use it - you will be unable to simply include the WinAPI headers and using it from there (as doing so would cause macro expansion clashes).I prefer to deal directly with the Windows API; I just want to make it easier to work with std::basic_string.Nothing is stopping you from wrapping the calls. Just don't undefine WinAPI function access macros and replace them with functions (using undefined macro names). You'd introduce a naming/include limitation in client code that would be hard to get around to in specific cases, and would only work with ugly workarounds in client code or by requiring modifications to your library). |
_unix.354012 | How can I set custom application which is being invoked when I press Differences button in File Conflict dialog?I did not find corresponding option in File Management Preferences.I did not find it using dconf Editor in org.mate.caja.*.I did not find it in files located at /usr/share/caja and ~/.config/caja.Where is this option being stored at? | Set custom application for file comparison in caja | settings;file comparison;caja | null |
_webmaster.90532 | I have just completed an FTP upgrade of my whole site. However, it is not working, when you type is www.gas-sense.co.uk, then you get a splashpage from my shared hosting, as though there is nothing on the site, previously, this would redirect to /index.html and would be fine. However, if I go to the file manager and click on http://gas-sense.co.uk/Index.html, I get the site loading as expected. Why is this and how do I get the route domain to direct straight to /index ? | Domain not directing to index.html | web hosting;redirects;indexing;file manager | Ahhh, just spotted it... My index.html file had a capital letter - Index.html - hence it wasn't recognised! |
_codereview.35357 | I am having a slight issue here, i am trying to think of a faster way of finding two elements from 2 different lists that match. The problem is that if i have lists which both have 1000 elements ( rules ) and the very last one [index.1000] matches then in order to find it i have to loop through booth lists from top to bottom. What i have is fine and it works however its not very efficient. Could any one perhaps suggest a better way ? (if there is any ? )The loop in this meethod is where the iteration through the lists happen. For furthere reference below this method you will find what ContextRule and Context is.public ContextRule match(Context messageContext, ContextRuleList contextRules) { ContextRule matchedContextRule = null; for(ContextRule contextRule : contextRules) { if(this.match(messageContext, contextRule)) { matchedContextRule = contextRule; break; } } if(matchedContextRule == null) { matchedContextRule = this.getDefaultContextRule(); } return matchedContextRule;}match() method which does comparason.private boolean match(Context messageContext, ContextRule contextRule) { return match(contextRule.getMessageContext().getUser(), messageContext.getUser()) && match(contextRule.getMessageContext().getApplication(), messageContext.getApplication()) && match(contextRule.getMessageContext().getService(), messageContext.getService()) && match(contextRule.getMessageContext().getOperation(), messageContext.getOperation()); } private boolean match(String value, String contextValue) { return value.equals(ContextRuleEvaluator.WILDCARD) || value.equals(contextValue); }Context ( which is an interface ) public interface Context { public String getUser(); public void setUser(String user); public String getApplication(); public void setApplication(String application); public String getService(); public void setService(String service); public String getOperation(); public void setOperation(String operation);}And finally ContextRulepublic interface ContextRule { public Context getMessageContext(); public int getAllowedConcurrentRequests(); }any help or suggestions appreciated. | Trying to find a better way of finding something rather then looping through list from top to bottom. | java;performance | Can your context rules be precomputed into any sort of hierarchical match tree once at application initialization?HashMap<String, HashMap<String, List<ContextRule>>> contextRuleMappublic boolean match (Context context, Map<String, Map<String, List<ContextRule>> contextRuleMap){ Map<String, List<ContextRule>> rulesByApplication = contextRuleMap[context.getUser()]; for (ContextRule contextRule : rulesByApplication[context.getApplication()]) { // Existing logic for remaining 'match' of service and operation } return false;}You can pre-compute your 'match tree' to as many 'levels deep' as you need to by User -> Application -> Service -> Operation to achieve the necessary performance. |
_cs.31970 | Is there any hardware device inside computer that helps to convert high level language into machine, like compiler and assembler ? | is there any hardware device to convert source code into machine language? | compilers;interpreters | null |
_unix.145527 | So here's the thing, and it's really just conceptual so don't let it bug you:I've got reasons for not wanting to rely on a specific build system. I don't mean to dis anybody's favorite, but I really just want to stick to what comes with the compiler. In this case, GCC. Automake has certain compatibility issues, especially with Windows. <3 GNU make is so limited that it often needs to be supplemented with shell scripts. Shell scripts can take many forms, and to make a long story short and probably piss a lot of people off, here is what I want to do --The main entry point is God. Be it a C or C++ source file, it is the center of the application. Not only do I want the main entry point to be the first thing that is executed, I also want it to be the first thing that is compiled. Let me explain --There was a time when proprietary and closed-source libraries were common. Thanks to Apple switching to Unix and Microsoft shooting themselves in the foot, that time is over. Any library that needs to be dynamically linked can be included as a supporting file of the application. For that reason, separate build instructions for .SOs (and maybe .DLLs ;]) is all fine and dandy, because they are separate executable files. Any other library should be statically linked. Now, let's talk about static linking --Static linking is a real bitch. That's what makefiles are for. If the whole project was written in one language (for instance C OR C++), you can #include the libraries as headers. That's just fine. But now, let's consider another scenario --Let's say you're like me and can't be arsed to figure out C's difficult excuse for strings, so you decide to use C++. But you want to use a C library, like for instance MiniBasic. God help us. If the C library wasn't designed to conform to C++'s syntax, you're screwed. That's when makefiles come in, since you need to compile the C source file with a C compiler and the C++ source file with a C++ compiler. I don't want to use makefiles. Bear with me --I would hope that there is a way to exploit GCC's preprocessor macros to tell it something like this:Hi, GCC. How are you doing? In case you forgot, this source file you're looking at right now is written in C++. You should of course compile it with G++. There's another file that this file needs, but it's written in C. It's called lolcats.c. I want you to compile that one with GCC into an object file and I want you to compile this one with G++ into the main object file, then I want you to link them together into an executable file.How might I write such a thing in preprocessor lingo? Does GCC even do that? | Compiling C/C++ code by way of including preprocessor build instructions in an actual C/C++ source file | gcc;c++;programming;linker;static linking | The main entry point is God. Be it a C or C++ source file, it is the center of the application.Only in the same way that nitrogen is the center of a pine tree. It is where everything starts, but there's nothing about C or C++ that makes you put the center of your application in main().A great many C and C++ programs are built on an event loop or an I/O pump. These are the centers of such programs. You don't even have to put these loops in the same module as main().Not only do I want the main entry point to be the first thing that is executed, I also want it to be the first thing that is compiled.It is actually easiest to put main() last in a C or C++ source file.C and C++ are not like some languages, where symbols can be used before they are declared. Putting main() first means you have to forward-declare everything else.There was a time when proprietary and closed-source libraries were common. Thanks to Apple switching to Unix and Microsoft shooting themselves in the foot, that time is over. Tell 'im 'e's dreamin'!OS X and iOS are full of proprietary code, and Microsoft isn't going away any time soon.What do Microsoft's current difficulties have to do with your question, anyway? You say you might want to make DLLs, and you mention Automake's inability to cope effectively with Windows. That tells me Microsoft remains relevant in your world, too.Static linking is a real bitch.Really? I've always found it easier than linking to dynamic libraries. It's an older, simpler technology, with fewer things to go wrong.Static linking incorporates the external dependencies into the executable, so that the executable stands alone, self-contained. From the rest of your question, that should appeal to you.you can #include the libraries as headersNo... You #include library headers, not libraries.This isn't just pedantry. The terminology matters. It has meaning.If you could #include libraries, #include </usr/lib/libfoo.a> would work. In many programming languages, that is the way external module/library references work. That is, you reference the external code directly.C and C++ are not among the languages that work that way.If the C library wasn't designed to conform to C++'s syntax, you're screwed.No, you just have to learn to use C++. Specifically here, extern C.How might I write such a thing in preprocessor lingo? It is perfectly legal to #include another C or C++ file:#include <some/library/main.cpp>#include <some/other/library/main.c>#include <some/other/library/secondary_module.c>#include <iostream>int main(){ call_the_library(); do_other_stuff(); return 0;}We don't use extern C here because this pulls the C and C++ code from those other libraries directly into our C++ file, so the C modules need to be legal C++ as well. There are a number of annoying little differences between C and C++, but if you're going to intermix the two languages, you're going to have to know how to cope with them regardless.Another tricky part of doing this is that the order of the #includes is more sensitive than the order of library references if a linker command. When you bypass the linker in this way, you end up having to do some things manually that the linker would otherwise do for you automatically.To prove the point, I took MiniBasic (your own example) and converted its script.c driver program to a standalone C++ program that says #include <basic.c> instead of #include <basic.h>. (patch) Just to prove that it's really a C++ program now, I changed all the printf() calls to cout stream insertions.I had to make a few other changes, all of them well within a normal day's work for someone who's going to intermix C and C++:The MiniBasic code makes use of C's willingness to tolerate automatic conversions from void* to any other pointer type. C++ makes you be explicit.Newer compilers are no longer tolerating use of C string constants (e.g. Hello, world!\n) in char* contexts. The standard says the compiler is allowed to place them into read-only memory, so you need to use const char*.That's it. Just a few minutes work, patching GCC complaints.I had to make some similar changes in basic.c to those in the linked script.c patch file. I haven't bothered posting the diffs, since they're just more of the same.For another way to go about this, study the SQLite Amalgamation, as compared to the SQLite source tree. SQLite doesn't use #include all the other files into a single master file; they're actually concatenated together, but that is also all #include does in C or C++. |
_unix.59393 | I am using /bin/rbash for some users. It's working as expected but there is some hack like when users run bash or dash, then they got unrestricted shells, so to avoid these commands, I have added below functions in their .bashrc files.bash() {echo WARNING: NOT ALLOW!!}sh() {echo WARNING: NOT ALLOW!!}So my question is:1# can we use functions with multiple names as belowfunc1,func2 () { # do stuff}2# I also tried:case $BASH_COMMAND in # check each command` bash|dash|sh) echo WARNING: NOT ALLOW!! ;;esac3# /bin/rbash -> bash it's just a soft link of bash, then how does it work as restricted?Also there is some command to avoid users to execute that like unset HISTFILE and kill -9 $$Is there any alternate way to achieve the same? | Bash restricted Shell using rbash | bash;shell;account restrictions;restricted shell | Do not do this. rbash should only be used within a chroot unless you know what you are doing. There are many ways to break out a restricted bash shell that are not easy to predict in advance.Functions can easily be overridden simply by doing command bash or command sh.As for your questions:You can't define multiple functions at the same time directly. You'd have to do something like this:x() { foo; }alias f1=xalias f2=xrbash works because bash checks the value of argv[0] on launch. If the basename, with leading dashes stripped, is equal to RESTRICTED_SHELL_NAME (defaulting to rbash, see config.h), it runs in restricted mode. This is the same way that it runs in POSIX-compliance mode if invoked as sh. You can see this in the following code from shell.c in bash 4.2, lines 1132-1147:/* Return 1 if the shell should be a restricted one based on NAME or the value of `restricted'. Don't actually do anything, just return a boolean value. */intshell_is_restricted (name) char *name;{ char *temp; if (restricted) return 1; temp = base_pathname (name); if (*temp == '-') temp++; return (STREQ (temp, RESTRICTED_SHELL_NAME));} |
_unix.291363 | Ok, so I've been googling this for almost a week now...without any luck.When I open the Keyboard settings pane, the options are only limited to (ones that have Space in them) Alt+Space and Super+Space - there is no Ctrl+SpaceI've found a couple of answers, non of which seem to work.First one is to install the xfce4-xkb-plugin (which I already had installed), then set use system default flag in the Keyboard settings pane, after which use plugin Properties to set the languages and shortcuts. Doesn't work - the Properties pane only has options on how the pane item looks...that's itNumber two is this line:-option grp:ctrl_space_toggle,grp_led:scroll en,ruDoesn't work either. If I put this in my .Xmodmap file, there is an error and the file isn't parsed anymore.I give up on searching, but I really need this, as it's a long time reflex.Please help me set Ctrl+Space as a shortcut to change layout. (I use Arch Linux if that makes any difference) | Xfce Keyboard Layout change Ctrl+Space | keyboard shortcuts;xfce;keyboard layout;xkb | null |
_unix.246605 | On my Beaglebone Black I added a I2C real-time-clock to not being reliant on ntpd to maintain accurate timing. The outcome is that there are two special device files in /dev. These are /dev/rtc0 and /dev/rtc1 but there is also /dev/rtc which is a symlink to /dev/rtc0. /dev/rtc0 is the real-time-clock within the ARM SOC on the board, /dev/rtc1 is the I2C device. At the moment I'm using scripts that read and write the time manually to the I2C clock but I'd rather like the symlink /dev/rtc to point to /dev/rtc1. Hence the question, how can this be done? The Linux distro on my beaglebone black is Arch Linux which uses systemd for all the house keeping. When I delete the symlink and create a new one pointing to /dev/rtc1 not surprisingly it is reset after the next reboot and I didn't find any config files or systemd-units so far.Help is much appreciated. | How can the link target of /dev/rtc be changed? | arch linux;systemd | That udev rule hint pointed me in the right direction. After a quick review of writing udev rules I did the following.udevadm info -a -p /sys/class/rtc/rtc1The output (shortened) revealed some useful properties to define a udev rule.looking at device '/devices/platform/ocp/4802a000.i2c/i2c-1/1-0068/rtc/rtc1':KERNEL==rtc1SUBSYSTEM==rtcDRIVER==ATTR{date}==2015-12-04ATTR{hctosys}==0ATTR{max_user_freq}==64ATTR{name}==ds1307ATTR{since_epoch}==1449230817ATTR{time}==12:06:57...So the rules file needs to reside in /etc/udev/rules.d/ with a naming scheme like 99-rtc1.rules.The files content is KERNEL==rtc1, SUBSYSTEM==rtc, DRIVER==, ATTR{name}==ds1307, SYMLINK=rtc, MODE=0666To test the rule you can runudevadm test /sys/class/rtc/rtc1and the important lines in the output are...creating link '/dev/rtc' to '/dev/rtc1'atomically replace '/dev/rtc'...The result in /dev is the desired configuration. |
_cogsci.6379 | or the mind is a mere collection of memories, experiences stored in the brain? | is the mind independent of the brain? | philosophy of mind | null |
_codereview.58873 | I have this obsession with esoteric programming languages. So I decided to spiff up my previous Brainfuck interpreter. # Simple BrainF*** interpreter# Class that stores lang variablesclass Lang(object): step = 0 cell = [0] * 30000 test_cell = [0] * 30000 pos = 0 test_pos = 0 loop = False loop_ret = 0# Main interpreter functiondef interpreter(): code_input = raw_input('Code: ') steps = len(code_input) while Lang.step < steps: if code_input[Lang.step] == '+': Lang.cell[Lang.pos] += 1 elif code_input[Lang.step] == '-': Lang.cell[Lang.pos] -= 1 elif code_input[Lang.step] == '>': if Lang.pos < 30000: Lang.pos += 1 elif Lang.pos > 30000: Lang.pos = 0 elif code_input[Lang.step] == '<': if Lang.pos > 0: Lang.cell_pos -= 1 elif Lang.pos < 0: Lang.pos = 30000 elif code_input[Lang.step] == '[': if Lang.loop == False: Lang.loop_ret = Lang.step Lang.loop = True elif code_input[Lang.step] == ']': if Lang.cell[Lang.pos] != 0: Lang.step = Lang.loop_ret elif Lang.cell[Lang.pos] == 0: Lang.loop = False elif code_input[Lang.step] == '.': print str(chr(Lang.cell[Lang.pos])) elif code_input[Lang.step] == ',': Lang.cell[Lang.pos] = int(raw_input()) elif code_input[Lang.step] == :: Lang.test_cell[Lang.test_pos] += 1 elif code_input[Lang.step] == ;: Lang.test_cell[Lang.test_pos] -= 1 elif code_input[Lang.step] == }: if Lang.test_pos > 30000: Lang.test_pos += 1 elif Lang.test_pos < 30000: Lang.test_pos = 0 elif code_input[Lang.step] == {: if Lang.test_pos > 0: Lang.test_pos -= 1 elif Lang.test_pos < 0: Lang.test_pos = 30000 elif code_input[Lang.step] == $: if Lang.test_cell[Lang.test_pos] == Lang.cell[Lang.pos]: print True elif Lang.test_cell[Lang.test_pos] != Lang.cell[Lang.pos]: print False Lang.step += 1# Running the programif __name__ == __main__: interpreter()If there are any issues, please mention them. All I'm looking for is any general improvements. | Basic Brainfuck interpreter (part 2) | python;python 2.7;interpreter;brainfuck | In a word: dictionaries. You have a class that only has class attributes and lacks any methods; that could just be a dictionary:lang = dict( step = 0, cell = [0] * 30000, test_cell = [0] * 30000, pos = 0, test_pos = 0, loop = False, loop_ret = 0)(Alternatively, if you really want attribute (foo.bar) rather than key (foo['bar']) access to the values, look into collections.namedtuple.)You have a whole bunch of elifs; that could also be a dictionary (with some judiciously-named functions):commands = { +: increment_byte, -: decrement_byte, ...}This makes your interpreter loop:def interpreter(): lang = dict(...) commands = {...} code_input = raw_input('Code: ') steps = len(code_input) while lang['step'] < steps: command = code_input[lang['step']] if command in commands: commands[command](lang) lang['step'] += 1along with e.g.:def increment_byte(lang): Increment the byte at the data pointer. val = lang['cell'][lang['pos']] lang['cell'][lang['pos']] = ((val + 1) % 256)(Note use of % per @user50399's answer.)This has two advantages:very simple loop in interpreter; andcommands acts as a syntax guide (covering @Dagg's comment). You could also add some input validation:def accept_input(lang): Accept one char of input, storing its value in the byte at the data pointer. while True: try: i = ord(raw_input(Enter char: )) except TypeError: pass else: if i in range(256): lang['cell'][lang['pos']] = i break print(Not a valid input.)(Note switch to ord per @user50399's answer.) |
_webmaster.30005 | This is my first question on this forum please be indulgent with me if my questions are somewhat too simplistic for you. i joined this community in order to improve myself and help others.Thank you.I received a mail from my hosting company saying the Zend Framework 1.10.8 site that am responsible for (the first one that i developed myself) is been hacked. so the moved the content of public_html to public_html_hacked . someone actually managed to upload 2 php files db5.php sys.php. I need to get the site back up.The only thing i managed to do is to change the cpanel password. I've changed the public_html permission to 754 but i think that's not going to work.Please give me advice, best pratices and guidance. Thank you for reading this | How to deal with attacks on Zend Framework web site? site currently down | php;security;lamp | null |
_unix.197377 | I've been trying to run a plugin inside a I have hired, and I've constantly been getting this error:[04:13:41] /bin/sh: /usr/java/jre1.8.0_31/bin/java.exe: No such file or directoryNot too sure what's causing it or how to fix it, the owner cannot be contacted so that's not an option for me.I've tried downgrading my java, but this still occurs. | /usr/java/jre1.8.0_31/bin/java.exe: No such file or directory | linux;centos;java | null |
_webapps.60662 | I have a Google spreadsheet with two tabs.First one is a public one where I want to invite specific customers to edit it.Second one is just for my team and I would like it to be invisible to the customers.In new (may 2014) Google Docs I am not able to do it.In a few words: On a Google Spreadsheet with two tabs how to let some users edit only 1st tab and not show them the 2nd tab, while keeping the full spreadsheet editable for another group of users? | How to share only one tab in the new Google Spreadsheets? | google drive;google spreadsheets | null |
_softwareengineering.117015 | I'm a project manager for a team of firmware engineers making the transition to adopting Scrum and I'm moving to support the team in a Product Owner role. We've just gone through Scrum training and are beginning a month of coaching which is going to be invaluable. Coming from a technical background I can already see the challenge of shifting my point of view from the solution domain to focusing on business value. For me it's very tempting to think of how to solve a problem. But I like the concept of user stories and defining vertical slices of functionality that give value to the customer and letting the team determine the how. Forgive me if this is a naive question, but as the PO how can I provide guidance on specific technical direction through user stories? My concern is that in some cases without guidance the team may head down the wrong path on key technical decisions.As a simplistic example I might have a user story:As a clinician I want the device to record information about the patient's treatment so that I can determine if the patient's therapy has been effective.Now say time to market is critical and I want to fork out for an off-the-shelf file system stack to save time, what conveys that to the team? They might go off and start writing their own stack from scratch. Is this sort of guidance provided through:Conversations during sprint planning and backlog grooming? But if so, is it my place as the PO to even be suggesting how to solve a problem.Acceptance criteria? I don't really like this, I have a bad feeling about making acceptance criteria so prescriptive that they specify how to solve a problem.Constraints?Thanks in advance. I could (and will) ask our Scrum coach but I won't be able to do that before Monday and this question has been really bugging me :) | How can I provide guidance on technology choices through user stories? | scrum;product owner | null |
_unix.231339 | For the purposes of this discussion, I have a very current always-on linux machine with two nics:wifi0eth0A very crude diagram of my desired configuration looks like this: (----------------------------) | linux/main computer | | | ----------- / ~ ~ ~ ~ ~ \ ------- -------| | internet |-- ~ wifi ~ --| wifi0 |------------| eth0 |======) ----------- \ ~ ~ ~ ~ ~ / ------- -------| | | | | (----------------------------) | \ subnet / | \ wifi / | ------------ | | dd-wrt |=================================================) | router |====\ subnet | |====\ subnet ------------eth0 is connected to a router with a preconfigured firewalled gateway that I trust and is the nic from/to which I should prefer all general traffic flow.The problem is that the firewalled gateway I trust is no longer a gateway; it has no internet connection.Rather my internet access comes from wifi0. I wish to wall off wifi0, to forward all its traffic through to my trusted gateway over eth0, and to be able to maintain my own local subnet as managed by my router/gateway primarily on my router/gateway.So basically I'm looking for a way to configure wifi0 to accept all incoming traffic and forward it immediately through eth0 to my router. I want all outgoing traffic not bound for my local subnet to be sent directly out over wifi0 to the wide-world, but all subnetted traffic to be handled by my local router, and all outgoing traffic - whether from my router or from my internet-connected computer to undergo nat and appear as if it originates from the same address.It has to be possible, and I'd really like to do it just with iptables and/or the tools included with current iproute2 packages. My preference is networkd for nic init/setup, and I'm aware that I might need to bring up a virtual nic or two in the connected linux box to make it happen, but am fuzzy on details. Will someone please help me with this? I'm very bad with packet filters and similar.p.s. I'm hardly married to the title of this question and if someone can think of a more succinct/descriptive one I would be grateful. If it makes any difference, I can also do:----- \ router /box \ \ ________ /---- | / \eth0 [========] wan port |---- | | |eth1 [========] lan port [=======\subnet____ / \ ________ /...because I do actually have two ethernet nics in my main box besides the wifi0 where the internet is sourced. So I supposed I could forward (or bridge?) all traffic between wifi0 and eth0 and for most intents and purposes ignore those two completely while routing all day-to-day traffic through eth1. I just really don't understand iptables or nftables or any of the rest well enough to effect my goal. Please give me a hand. | Forward public network around current network | iptables;firewall;nat;iproute;systemd networkd | null |
_datascience.22179 | I am currently studying this paper (page 53), in which the suggest convolution to be done in a special manner. This is the formula:\begin{equation} \tag{1}\label{1}q_{j,m} = \sigma \left(\sum_i \sum_{n=1}^{F} o_{i,n+m-1} \cdot w_{i,j,n} + w_{0,j} \right)\end{equation}Here is their explanation: As shown in Fig. 4.2, all input feature maps (assume I in total), $O_i (i = 1, , I)$ are mapped into a number of feature maps (assume $J$ in total), $Q_j (j = 1, , J)$ in the convolution layers based on a number of local filters ($I J$ in total), $w_{ij}$ $(i = 1, , I; j = 1, , J)$. The mapping can be represented as the well-known convolution operation in signal processing.Assuming input feature maps are all one dimensional, each unit of one feature map in the convolution layer can be computed as equation $\eqref{1}$ (equation above).where $o_{i,m}$ is the $m$-th unit of the $i$-th input feature map $O_i$, $q_{j,m}$ is the $m$-th unit of the $j$-th feature map $Q_j$ of the convolution layer, $w_{i,j,n}$ is the $n$th element of the weight vector, $w_{i,j}$, connecting the $i$th feature map of the input to the $j$th feature map of the convolution layer, and $F$ is called the filter size which is the number of input bands that each unit of the convolution layer receives.So far so good:What i basically understood from this is what I've tried to illustrate in this image. It seem to me what they are doing is actually processing all data points up to F, and across all feature maps. Basically moving in both x-y direction, and compute on point from that. Isn't that basically 2d- convolution on a 2d image of size $(I x F)$ with a filter equal to the image size?. The weight doesn't seem to differ at all have any importance here..? | Why is this not ordinary convolution? | neural network;convnet;convolution | null |
_webapps.9978 | What site can I use to create a donation pool? I want to display how much money is raised in realtime. I have seen one for charities only, which this is not. I also found Kickstarter which looked good but it doesn't seem to be friendly to non US donators and requires the project host to live in the U.S. which I do not.It looks like Paypal supports it but I am unsure if it displays in realtime. I'd like a way to return all money if the donation target isn't met, however this isn't a requirement.Chipin Looks like a good alternative but had no news for a whilePledge Bank doesn't look as good but may be suitable.What else is there? | Donation/money pool online? | money | null |
_webmaster.47178 | I'm searching for a good looking colorpicker. I just found a screenshot: http://oi47.tinypic.com/2w6tees.jpgDo you know which plugin is it? | Do you know this colorpicker? | jquery;plugin | Here are some that might be it or look very similar:http://automattic.github.io/Iris/ -- I think it is this one, it doesn't have the Current Color or Default, but I think those are what the user would click on to bring up the color picker.http://bebraw.github.io/colorjoe/http://bgrins.github.io/spectrum/ |
_codereview.32868 | I have an enum like the following:enum MeasurementBandwidth{ Hz1 = 1, Hz3 = 3, Hz10 = 10, ...}But I do not like the Hz1, and 1Hz is not valid as it starts with a number.Does anyone have an idea how to solve this more elegant?Why I am doing this: I have an API, which offers a method like the following: public double MeasureInput(double frequency, MeasurementBandwidth bandwidth) { /*...*/ }And the bandwidth only has a few possible values which can be used and I want to make it as easy as possible for the user to choose a valid one. Using an enum was the best solution I came up with, as it is directly visible from the parameter type, what values are valid. | Alternative to starting enum values with a number | c#;enum | null |
_unix.387640 | It is written in the linux kernel Makefile thatclean - Remove most generated files but keep the config and enough build support to build external modulesmrproper - Remove all generated files + config + various backup filesAnd it is stated on the arch docs thatTo finalise the preparation, ensure that the kernel tree is absolutely clean;$ make clean && make mrproperSo if make mrproper does a more thorough remove, why is the make clean used? | Why both `make clean` and `make mrproper` are used? | linux;make;gnu | According to the Linux kernel Makefile, the mrproper target depends on the clean target (see line 1324).Executing make mrproper will therefore be enough as it would also remove the same things as what the clean target would do.The mrproper target was added in 1993 (Linux 0.97.7) and has always depended on the clean target. This means that it was never necessary to use both targets as in make clean && make mrproper.Reference: https://archive.org/details/git-history-of-linux |
_computergraphics.3775 | In a recent version of uTorrent , if you open the About Window, you will see an animated background , which is kind of waves that go on forever.How can this be achieved? Is this kind of a well-known algorithm/class of algorithms?Thanks. | What algorithm is used in the animation of the uTorrent 's About window? | algorithm;shader | As you discovered and mentioned in your self-answer, the pattern in the background appears to be a sum of sinusoidal gradients.However, the example linked to in your answer is more complicated than that used by Torrent. The background of the About window appears to be a static pattern, rather than the animated sinusoidal pattern used in the plasma post.Several sinusoidal gradients have been summed to give a single image, and the illusion of movement is given by simply cycling the colours in that one image, rather than generating a number of different images. This is most noticeable if you focus on the centre of one of the rings of colour. In the Torrent pattern you will notice that each ring stays in one place, and has colour flowing either into it or out of it. In contrast, the rings of colour in the fully animated pattern move around, occasionally dividing or merging.The simplified approach used by Torrent is reminiscent of animations used in the past when recalculating the sinusoidal patterns each frame was not realistic. |
_webmaster.60504 | I have seen many suggestions on various redirects, but none were simple and many had no accepted answer.I have a site I wish to completely remove from google and have only my homepage availableIn that homepage I have image css and js files so they of course should not be redirectedMy plan was to redirect all .html and all .php that are not the /index.html in root to the /index.html in rootOf course / should also be allowed.So /js, /css, /img and /images should be left aloneAny other php or html page I thought I wanted to have 301 to /index.htmlThis worked but as pointed out in a comment, does not tell Google that the content that it indexed is no longer supposed to be thereStackoverflow: how-to-redirect-all-pages-only-to-index-html-using-htaccess-file-and-not-redirectRewriteEngine onRewriteCond %{REQUEST_URI} !^/index.html$RewriteCond %{REQUEST_URI} !\.(gif|jpe?g|png|css|js)$RewriteRule .* /index.html [L,R=301]So my amended question is How to tell google my content is gone and redirect all requests for content (bookmarked pages for example or external links) made to my site to /index.html UpdateErrorDocument 410 /error-docs/error410.htmlRewriteEngine onRewriteCond %{REQUEST_URI} !^/error-docs/RewriteCond %{REQUEST_URI} !=/index.htmlRewriteCond %{REQUEST_URI} !=/RewriteCond %{REQUEST_URI} !\.(gif|jpe?g|png|css|js)$RewriteRule .* - [G]almost worksBut I want to return 410 on all files in 4 subfolders and whatever is under themI have /index.html/images//js//css//unwantedfolder/with/stuff/imagesandhtml/anotherunwantedfolder/with/stuff/imagesandhtmlI want to give 410 for now on all request to anywhere in the unwanted foldersIf I addRewriteRule ^unwantedfolder - [G]like thisErrorDocument 410 /error-docs/error410.htmlRewriteEngine onRewriteCond %{REQUEST_URI} !^/error-docs/RewriteCond %{REQUEST_URI} !=/index.htmlRewriteCond %{REQUEST_URI} !=/RewriteCond %{REQUEST_URI} !\.(gif|jpe?g|png|css|js)$RewriteRule .* - [G]RewriteRule ^unwantedfolder - [G]nothing happens to http://www.myserver.com/unwantedfolder/bla/images/someimage.pngIt shows without any redirection, likely due to the !\.(gif|jpe?g|png|css|js)$ earlierwhereas http://www.myserver.com/unwantedfolder/bla/somepage.html does get a error410 page | Remove all content not related to index.html from the web and google | htaccess;301 redirect | Following on from comments... since you are wanting to completely remove these pages from Google's index then simply redirecting (301) them (as requested in your original question) is not necessarily the correct thing to do. Redirection is saying that the page has moved. Yes, Google is likely to drop the original page from the index... eventually, but that could take some time. Trying to preserve PR by redirecting all pages to the homepage is unlikely to provide the SEO benefit you might hope for, and this is generally confusing for users.I would suggest serving a custom 410 (Gone) for these pages, with a prominent link to the homepage (if you wish) and not actually send the user to the homepage directly - unless your homepage is your 410!?Modifying your current .htaccess rules:ErrorDocument 410 /error-docs/e410.htmlRewriteEngine onRewriteCond %{REQUEST_URI} !^/error-docs/RewriteCond %{REQUEST_URI} !=/index.htmlRewriteCond %{REQUEST_URI} !\.(gif|jpe?g|png|css|js)$RewriteRule . - [G]The single hyphen (-) in the RewriteRule substitution passes the URL through unchanged. The G (GONE) flag returns a 410 status code and results in your custom 410 being served. An exception for the /error-docs/ folder is also required.CHANGE: Note, I've changed the RewriteRule pattern from .* (meaning anything) to simply . (single period) (meaning something). This is an alternative to specifying an additional RewriteCond directive for the root URL. So, the following is unnecessary:RewriteCond %{REQUEST_URI} !=/This should ensure that Google will remove these pages as-soon-as. You should also be able to see confirmation of this in terms of a crawl error report in GWT (yes, it is a crawl error, but it is intentional). This also provides a meaningful message to users and should encourage them to update/delete their bookmarks as required.UPDATE: As mentioned in comments, the above rules still permit all the gallery images to be accessed (in a sub folder). In order to prevent the gallery images, we can add another RewriteRule following the directives above:# (Above directives go here...)RewriteRule ^gallery\d - [G]This will block all URLs (including images) that start /gallery1, /gallery2, etc. (Note that the / prefix is intentionally omitted from the RewriteRule pattern.) However, the directives at the top will still allow all the other images, necessary to build your homepage.Note that this second RewriteRule is entirely separate from the previous RewriteRule and RewriteCond directives above. RewriteCond directives only apply to the single RewriteRule that follows them. So, the RewriteCond %{REQUEST_URI} !\.(gif|jpe?g|png|css|js)$ does not apply to this second RewriteRule.SummaryThe following is the complete set of rules:ErrorDocument 410 /error-docs/e410.htmlRewriteEngine on# Serve 410 to all files except:# error documents, /index.html, / (root) and imagesRewriteCond %{REQUEST_URI} !^/error-docs/RewriteCond %{REQUEST_URI} !=/index.htmlRewriteCond %{REQUEST_URI} !\.(gif|jpe?g|png|css|js)$RewriteRule . - [G]# Serve 410 to EVERYTHING within the /unwantedfolder# >>> including images <<<RewriteRule ^unwantedfolder - [G]# Serve 410 to EVERYTHING within the /anotherunwantedfolderRewriteRule ^anotherunwantedfolder - [G] |
_webapps.100911 | I've stumbled across an issue with one of my forms. You see the information from it does not show in the table.Seems to be the same issue when i try to customize the notification with fields from the form. They are not showing up.None such issues with my other forms.Can you please help me out? (pic below | Form entries not appearing | cognito forms | null |
_softwareengineering.345159 | I would like to compute a numeric value for strings containing only /[a-z0-9]/i (ignore case). Later, I want to use this value for sorting rows. For this post, I am ignoring number also.My thinking was, that I can define an alphabet like 0123456789a...z and compute a sortable value by summing up the indexes of each character found, like this (pseudo code but should work in ES6):const alpha = 'abcdefghijklmnopqrstuvwxzy'.split('');function easySort(myString) { myString = myString.toLowerCase(); let sortableValue = 0; for (let i = 0; i < myString.length; i++) { sortableValue += alpha.indexOf(myString.charAt(i)) + 1; // to avoid 0 } return sortableValue;};Simple example (assuming indexes a=1, b=2, ..):let arr = ['abc', 'ab', 'abd', 'aba'];let ordered = arr.sort((a, b) => easySort(a) - easySort(b));// ordered now is ['ab', 'aba', 'abc', 'abd']The question is, is this a good approach for strings from that alphabet? Are there cases when this would not work the intended way?I am not asking for improvements of the code but rather the algorithm and whether it may behave unexpected for certain values (by that I do not mean illegal values). | Simple algorithm for computing an orderable value from a string | sorting;strings;es6 | null |
_unix.323730 | My setup is the following:node A is where I startnode B is the gateway machinenode C is the destination.From Ato B I have setup SSH public key authentication but from B to C I am not allowed to.So from node A I use the following incantation which actually works from a different machine (Ubuntu 14.04):sshpass -p secretpass ssh -oProxyCommand=ssh -W %h:%p username@B username@C… however, when I try from a different location with another machine (Ubuntu 16.04 - though I doubt that's relevant), the invocation of sshpass promptly returns without any kind of output and an exit code (obtained with echo $?) of 6.More puzzling is the fact that if I do the steps separately, they succeed:A: $ ssh username@B (directly access B without being prompted for password)B: $ ssh username@C (prompted for password, provided 'secretpass')C: $ (reached my destination) | sshpass failing with exit code 6 | ssh | null |
_vi.6026 | Occasionally I want to override the default syntax highlighting colours and styles with my own preferences.I imagine the most appropriate way to do this would be to create my own colorscheme. However I have a couple of questions.If I want to set a highlight for a specific syntax group in a specific language, does this belong in my colorscheme, or would it be better to place it in after/syntax/[filetype].vim?highlight jsAssignExpIdent cterm=bold gui=boldIt seems a little odd to place obscure language-specific rules in the colorscheme, as they will be loaded whatever language I am working on, but it seems even worse to place highlight rules in the syntax file.Sometimes I create new syntax rules for a specific language, in after/syntax/[filetype].vim. In case other users want to employ these extensions, would it be appropriate for me to provide default highlight rules there which link to common default highlight groups? If another user wants to override that highlight colour, how should they do that?::::: after/syntax/asm.vim :::::syn match asmHexNumber /\(0x\|\$\)[0-9A-Fa-f]\+/highlight default link asmHexNumber Number | Where do custom highlighting rules belong? | syntax highlighting;highlight | First questionHighlight definitions belong to your colorscheme. The fact that they are loaded for every buffer, no matter what their language, shouldn't be a problem at all.If you don't want to edit your colorscheme, you can put those highlight definitions in plugin/myhighlights.vim:function! MyHighlights() highlight ... highlight ...endfunctionaugroup MyHighlights autocmd! autocmd ColorScheme * call MyHighlights()augroup ENDSecond questionYour sample is exactly how you should do and how every syntax script does. This method lets the plugin developer define sane default without forcing specific colors down their user's throat. |
_unix.235600 | I have a file with the below data in test1.txt:nnn 90vvv 80ttt 50sss 20I want to compare the second column value and remove that line. For example, if any of the second column value is less than 20, then delete that line entry. The output of test1.txt should look like:nnn 90vvv 80ttt 50I tried with sed and awk commands, but it's not working for me. | Comparing value and removing the lines of a file | text processing | null |
_webmaster.102763 | I recently started reading upon CDNs and how they can help optimize web requests by having a network of edge nodes which are much closer to the user. What kind of parameters do CDN Providers look upon to determine where the edge node should be placed? Will it be just a look up of how many requests come from each region and then place more servers there or are there other factors as well like, maybe Facebook has a lot more requests coming from a particular part of Europe. To help them optimize their requests, a lot of edge nodes may be placed near them?I realize this is a subjective question, but I am not sure where else I can ask this question! | How do CDNs determine where the edge nodes should be placed? | cdn | An Edge node is the server that delivers the content to the user. A CDN is typically spread throughout the globe having edge nodes at multiple continents and even multiple Internet Backbones.The edge node might be an application server, a caching server, or reverse proxy. When you query the CDN, it checks the Edge location which can get you the data with the minimum number of hops. While it optimizes for performance, it then tries to deploy popular data near the client who asked for it.Just because you're using a CDN will not mean that your data is replicated across each and every node. There are different caching mechanisms that are employed by different CDN networksYou can read more about it here: https://support.rackspace.com/how-to/what-is-a-cdn/ |
_unix.299265 | I edited ~/.Xmodmap to set keycode 118 to Control_L, so that I have the same functionality for CTRL on both sides of Space. I had to remove and add Control_L to control and it works fine now.keycode 127 = Insertremove control = Control_Lkeycode 118 = Control_Ladd control = Control_Lkeycode 135 = ISO_Level3_Shiftkeycode 108 = spaceremove mod1 = Alt_Lkeycode 94 = Alt_L ISO_Next_Group Alt_L ISO_Next_Groupadd mod1 = Alt_LNow Alt+Tab doesn't work, even though both Alts work the same way otherwise. Alt+Tab with the new Alt switches to 1 other program and then back to the first one. It doesn't show the task switcher menu at all.Output of xmodmap -pm:[hax@localhost ~]$ xmodmap -pmxmodmap: up to 4 keys per modifier, (keycodes in parentheses):shift Shift_L (0x32), Shift_R (0x3e)lock Caps_Lock (0x42)control Control_L (0x25), Control_R (0x69), Control_L (0x76)mod1 Alt_L (0x40), Alt_L (0x5e), Alt_L (0xcc), Meta_L (0xcd)mod2 Num_Lock (0x4d)mod3 mod4 Super_L (0x85), Super_R (0x86), Super_L (0xce), Hyper_L (0xcf)mod5 ISO_Level3_Shift (0x5c), space (0x6c), ISO_Level3_Shift (0x87), Mode_switch (0xcb)Output of xbindkeys -k for the old Alt:[hax@localhost ~]$ xbindkeys -kPress combination of keys or/and click under the window.You can use one of the two lines after NoCommandin $HOME/.xbindkeysrc to bind a key.NoCommand m:0x8 + c:64 Alt + Alt_LOutput of xbindkeys -k for the new Alt:[hax@localhost ~]$ xbindkeys -kPress combination of keys or/and click under the window.You can use one of the two lines after NoCommandin $HOME/.xbindkeysrc to bind a key.NoCommand m:0x8 + c:94 Alt + Alt_LOutput of xev for the old Alt:KeyPress event, serial 37, synthetic NO, window 0x3e00001, root 0x9b, subw 0x0, time 10657877, (328,658), root:(1612,798), state 0x0, keycode 64 (keysym 0xffe9, Alt_L), same_screen YES, XLookupString gives 0 bytes: XmbLookupString gives 0 bytes: XFilterEvent returns: FalseKeyRelease event, serial 40, synthetic NO, window 0x3e00001, root 0x9b, subw 0x0, time 10657981, (328,658), root:(1612,798), state 0x8, keycode 64 (keysym 0xffe9, Alt_L), same_screen YES, XLookupString gives 0 bytes: XFilterEvent returns: FalseOutput of xev for the new Alt:KeyPress event, serial 40, synthetic NO, window 0x3e00001, root 0x9b, subw 0x0, time 10659997, (328,658), root:(1612,798), state 0x0, keycode 94 (keysym 0xffe9, Alt_L), same_screen YES, XKeysymToKeycode returns keycode: 64 XLookupString gives 0 bytes: XmbLookupString gives 0 bytes: XFilterEvent returns: FalseKeyRelease event, serial 40, synthetic NO, window 0x3e00001, root 0x9b, subw 0x0, time 10660077, (328,658), root:(1612,798), state 0x8, keycode 94 (keysym 0xffe9, Alt_L), same_screen YES, XKeysymToKeycode returns keycode: 64 XLookupString gives 0 bytes: XFilterEvent returns: False | xmodmap Alt+Tab doesn't work with new Alt_L key | x11;keyboard layout;xmodmap | null |
_softwareengineering.166167 | After a recent heated debate over Scrum, I realized my problem is that I think of management as a quite unnecessary and redundant activity in a fully agile team. I believe a mature Agile team does not require management or any non-technical decision making process whatsoever. To my (apparently erring) eyes it is more than obvious that the only one suitable and capable of managing a mature development team is their coach (who is the most technically competent colleague with proper communication skills). I can't imagine how a Scrum master can contribute to such a team.I am having great difficulty realizing and understanding the value of such things in Scrum and the manager as someone who is not a veteran developer but is well skilled in planning the production cycles when a coach exists in the team. What does that even mean? How on earth can someone with no edge-skills of development manage a highly technical team? Perhaps management here means something else?I see management as a total waste of time and a by-product of immaturity. In my understanding a mature team is fully self-managing. Apparently I'm mistaken since many great people say the contrary but I can't convince myself. | Does a mature agile team requires any management? | agile;scrum;management;extreme programming | null |
_softwareengineering.334405 | So I wanted to know the differences between these two. I know software interrupts are sometimes referred to as exceptions, which makes the differences between the two somewhat confusing. Asking this entire question from a program level perspective; wouldn't an exception just be an illegal action whereas a software interrupt may not be?Firstly, am I understanding this much correctly and furthermore are there other differences that can be drawn between the two? | What are the differences between software interrupts/exceptions | exceptions;software | null |
_unix.12167 | top command shows the process cpu utilization, and it when we sum the cpu utilization of all the processes then it goes greater than 100%. And how can it shows the cpu utilization of each process( app. > 300 process) in very short span of time. There is a question about cpu usage by a processthat tells us to sleep for 1 second. And according to that solution Cpu usage by a process is different from top command output. so please tell me about right solution. My computer has the configuration Intel core2duo and ubuntu 10.10. | Queries about top command | linux;process;cpu;top | null |
_cs.75890 | It is pretty hard for me to understand, how binary representation of number may be context free. This language $L=\{bin(n)bin(n+1)^R : n \geq 0\}$ is context free.Here, at 1.b, is a PDA which describes this language, so it is context free. I've tried to construct a context free grammar for this one, but I have no idea when to even start. How can I express a CFG binary representation of a number? I would be very glad for any suggestions. | Context free grammar for $bin(n)bin(n+1)^R$ | formal languages;context free;formal grammars;pushdown automata | Here is one solution:$$\begin{align*}&S \to 01 \mid 1A1 \mid 1B1 \\&A \to 1A0 \mid 0 \\&B \to 1B1 \mid 0B0 \mid 0C1 \\&C \to 1C0 \mid \epsilon\end{align*}$$Explanation:$A$ generates $1^n 0^{n+1}$, and so $1A1$ generates $1^{n+1} 0^{n+1}1$, which handles numbers whose binary expansion is $1^{n+1}$.$C$ generates $1^n 0^n$, and so $0C1$ generates $01^n 0^n1$.$B$ generates $w01^n0^n1w^R$, and so $1B1$ generates $1w01^n0^n1w^R1$, which handles numbers whose binary expansion is $1w01^n$.Finally, $01$ handles $0$. |
_unix.247760 | I am having a log file where I need to grep based on yesterday date. How to get the yesterday date.The time stamp in the log file is formatted as:Wed Sep 23 for two digitWed Dec 1 for one digitNote that I'm on HP/UX where date is not GNU date. | How to get yesterday date and stored into one variable | shell;date;hp ux | null |
_unix.336822 | I need to accept job files from users, which would essentially consist of console interaction with a process I will be running for them. Naturally, the first idea that came to mind is to use expect scripts as job files:spawn processexpect readysend process DATAset timeout 100expect { done {send_user success} timeout {send_user failure}}However, since I'd like to accept jobs automatically, I want to prevent users from doing something stupid or dangerous, like spawning 10 sysbench processes, or writing random files to the disk, or trying to read /etc/passwd. I want to restrict them to STDIN/STDOUT interactions with the process I spawn for them.How would I go about this? So far my thoughts are:write my own expect lite. Sounds feasible but silly and time-consuming.sanitize expect job files. Sounds complex and error-prone.invent my own safe language and translate it to expect. Feasible, but I'll have to provide documentation and tutorials so users can learn it.restrict job process with quota and permissions. Not really an option, since I want my process to use a fair amount of CPU time and create tmp files (which I'm confident it will clean up).give users interactive access to process. Not an option since jobs may have to sit in a queue for some time.Is there something obvious I'm missing, like expect configuration parameter which restricts the scripts, or a similar tool I could use instead? | Restrict `expect` to stdin/stdout interaction only | scripting;security;expect | null |
_codereview.129114 | Note: Yes. It's big. I'm not expecting commensurately long/detailed answers (though if anyone wants to write one, you'll definitely be receiving a substantial bounty). This class is going to be used a lot in my VBA development so any reviews at all would be immensely helpful. Even if it's just a typo somewhere or an edge case that's not being checked or functionality you think should be added to it or even just a Gut-Check on coding smells, readability and the like.If you want a paste-able version of this code, please see this github repoI do a lot of data analysis with spreadsheets. VBA has no in-built array functions (sorting, filtering etc.). This is a problem.So, I took my accumulated collection of Array-manipulation methods, cleaned them up and turned them into a Class: CLS_2D_VarArray. It is also supposed to be paired with my collection of Standard Methods, in a Base_Standard_Methods Module, and with CLS_Comparison_Predicate which is used to pass logical expressions to functions.I would love to get peoples' thoughts on it.Class-Level stuff:Type of Array:I only use 2-D Variant Arrays, declared thus:Dim arr As VariantRedim arr(1 to 5, 1 to 5)Only declared that way for various reasons which I won't go into here.Only 2-Dimensional because that covers 95% of my use-cases, and supporting multi-dimensional operations would cause a lot of additional complexity.Properties:Private Type TVarArray varArray As Variant ColumnHeaderIndexes As Dictionary '/ Set when SetArray is called with hasHeaders = True PrintRange As Range '/ Set whenever Me.PrintToSheet is calledEnd TypePrivate This As TVarArrayBehaviour:All the functions are designed to be chain-able. So, with the exception of CopyArray(), which returns a copy of VarArray, or GetArray(), which returns VarArray itself, all functions return a new Class object.E.G. I can do the following:Set filteredArray = baseClass.RemoveIndexes().KeepHeaders().RemoveByPredicate()This allows me to Never have to worry about over-writing the original Array/DataPerform operations in sequence without having to keep re-inserting array outputs into new class objects.All inputs are checked/validated immediately upon calling a public method, before any business logic, and even if they will be checked again later on.For now, failed validations just Debug.Print, MsgBox and then Stop because this is strictly for internal use, I'm the only developer and it's a lot more useful to me to just Stop where the error is.Most of the public methods validate inputs and then call Internal... methods for the actual operations.Method ListSetArray, GetArrayCopyArray, CopyClass CheckTargetsIsAllocated, GetBounds, IsListArray, SetColumnHeaderIndexes InternalCopyArrayInternalCopyClassInternalRemoveIndexes InvertTargetIndexes RemoveIndexes, KeepIndexesRemoveByPredicate,KeepByPredicateRemoveHeaders, KeepHeaders ColumnIndexOfHeaderArrayListFromIndex AddDataMapHeadersToIndexesInsertIndex,FillIndex ReplaceValues SortRows PrintTosheet External Methods/Classes included for context:CLS_Comparison_Predicate External Methods Methods:SetArray, GetArrayNot properties because SetArray needs to know if the array has headers or not, and property Get/Set/Lets can't have multiple arguments.I had 2 options for headers. I could either assume that every array has headers, and ignore duplicate headers, or require a boolean declaration. I decided a declaration would be more annoying, but was preferable to ignoring duplicate-header collisions.Public Sub SetArray(ByRef inputArray As Variant, Optional ByVal hasHeaders As Boolean = False) If Not IsArray(inputArray) Then PrintErrorMessage Input is not an array Stop Else If Not DimensionCountOfArray(inputArray) = 2 Then PrintErrorMessage Input Array must be 2-dimensional Stop Else With This .varArray = inputArray If hasHeaders Then SetColumnHeaderIndexes Else Set .ColumnHeaderIndexes = Nothing End With End If End IfEnd SubPublic Function GetArray() As Variant GetArray = This.varArrayEnd FunctionCopyArray, CopyClassCopyArray also contains an argument for transposing the array.Public Function CopyClass(Optional ByVal copyTransposed As Boolean = False) As CLS_2D_VarArray Dim newClass As CLS_2D_VarArray Set newClass = InternalCopyClass() With newClass If copyTransposed Then .ArrayObject = Transpose2dArray(.ArrayObject) End With Set CopyClass = newClassEnd FunctionPublic Function CopyArray(Optional ByVal copyTransposed As Boolean) As Variant '/ Returns a new array object with identical contents to VarArray. CopyArray = InternalCopyArray If copyTransposed Then CopyArray = Transpose2dArray(CopyArray)End FunctionCheckTargetsWhich is a catch-all function for checking all possible inputs and should be called, in some form, from every public method (apart from the simple Get/Copy methods).Private Function CheckTargets(Optional ByVal checkDimension As Variant, Optional ByVal checkIndex As Variant, Optional ByRef checkIndexList As Variant) '/ Checks that VarArray is allocated '/ If supplied, checks that target Dimension/Indexes exist If Not IsAllocated Then PrintErrorMessage Array has not been allocated Stop End If Dim LB1 As Long, UB1 As Long Dim LB2 As Long, UB2 As Long GetBounds LB1, UB1, LB2, UB2 If Not IsMissing(checkDimension) Then If Not (checkDimension = 1 Or checkDimension = 2) Then PrintErrorMessage Target Dimension does not exist Stop End If End If If Not IsMissing(checkIndex) Then If Not ((checkDimension = 1 And checkIndex >= LB1 And checkIndex <= UB1) Or (checkDimension = 2 And checkIndex >= LB2 And checkIndex <= UB2)) Then PrintErrorMessage Target Index does not exist Stop End If End If If Not IsMissing(checkIndexList) Then If Not IsListArray(checkIndexList) <> 1 Then '/ Check that indexesToRemove is an arrayList PrintErrorMessage checkIndexList must be an arrayList Stop End If Dim listLB1 As Long, listUB1 As Long listLB1 = LBound(checkIndexList) listUB1 = UBound(checkIndexList) Dim ix As Long Dim testIndex As Long For ix = listLB1 To listUB1 testIndex = checkIndexList(ix) If Not ((checkDimension = 1 And testIndex >= LB1 And testIndex <= UB1) Or (checkDimension = 2 And testIndex >= LB2 And testIndex <= UB2)) Then PrintErrorMessage Target Index does not exist Stop End If Next ix End IfEnd FunctionIsAllocated, GetBounds, IsListArray, SetColumnHeaderIndexesSimple utility functions.Private Function IsAllocated() As Boolean On Error GoTo CleanFail: IsAllocated = IsArray(This.varArray) And Not IsError(LBound(This.varArray, 1)) And LBound(This.varArray, 1) <= UBound(This.varArray, 1) On Error GoTo 0CleanExit: Exit FunctionCleanFail: On Error GoTo 0 IsAllocated = False Resume CleanExitEnd FunctionPrivate Function IsListArray(ByRef checkVar As Variant) As Boolean Dim passedChecks As Boolean passedChecks = True If Not IsArray(checkVar) Then passedChecks = False PrintErrorMessage Input is not an array Stop End If If Not DimensionCountOfArray(checkVar) = 1 Then passedChecks = False PrintErrorMessage Input Array must be 1-dimensional Stop End If IsListArray = passedChecksEnd FunctionPrivate Sub SetColumnHeaderIndexes() Set This.ColumnHeaderIndexes = New Dictionary Dim LB1 As Long, LB2 As Long, UB2 As Long GetBounds LB1:=LB1, LB2:=LB2, UB2:=UB2 Dim header As Variant Dim columnIndex As Long Dim iy As Long For iy = LB2 To UB2 columnIndex = iy header = This.varArray(LB1, iy) This.ColumnHeaderIndexes.item(header) = columnIndex Next iyEnd Sub Private Sub GetBounds( _ Optional ByRef LB1 As Variant, Optional ByRef UB1 As Variant, _ Optional ByRef LB2 As Variant, Optional ByRef UB2 As Variant) '/ Assigns the L/U Bounds of the array for the specified dimension arguments If Not IsMissing(LB1) Then LB1 = LBound(This.varArray, 1) If Not IsMissing(UB1) Then UB1 = UBound(This.varArray, 1) If Not IsMissing(LB2) Then LB2 = LBound(This.varArray, 2) If Not IsMissing(UB2) Then UB2 = UBound(This.varArray, 2)End SubInternalCopyArrayThis is the core internal function. Used for copying the array and removing indexes.Private Function InternalCopyArray(Optional ByRef targetDimension As Variant, Optional ByRef indexesToIgnore As Variant) As Variant '/ Returns a new array object with identical contents to This.VarArray. '/ If target dimension & indexes are specified, will skip over them rather than copying, effectively removing them from the result. CheckTargets targetDimension, checkIndexList:=indexesToIgnore Dim targetsArePresent As Boolean targetsArePresent = (Not IsMissing(targetDimension)) And (Not IsMissing(indexesToIgnore)) Dim LB1 As Long, UB1 As Long Dim LB2 As Long, UB2 As Long GetBounds LB1, UB1, LB2, UB2 Dim newArray As Variant If targetsArePresent Then Select Case targetDimension Case 1 ReDim newArray(LB1 To UB1 - DimLength(indexesToIgnore, 1), LB2 To UB2) Case 2 ReDim newArray(LB1 To UB1, LB2 To UB2 - DimLength(indexesToIgnore, 1)) End Select Else ReDim newArray(LB1 To UB1, LB2 To UB2) End If Dim i As Long, j As Long Dim ignoreCounter As Long Dim ignoreIndex As Boolean Dim copyElement As Variant For i = LB1 To UB1 If targetsArePresent Then If targetDimension = 2 Then ignoreCounter = 0 '/ reset each row if targeting columns For j = LB2 To UB2 If IsObject(This.varArray(i, j)) Then Set copyElement = This.varArray(i, j) Else copyElement = This.varArray(i, j) If targetsArePresent Then ignoreIndex = False Select Case targetDimension Case 1 ignoreIndex = Not IsNull(IndexIn1DArray(indexesToIgnore, i)) Case 2 ignoreIndex = Not IsNull(IndexIn1DArray(indexesToIgnore, j)) End Select If ignoreIndex Then If targetDimension = 1 Then If j = LB2 Then ignoreCounter = ignoreCounter + 1 '/ only increment once per row if rows targeted Else ignoreCounter = ignoreCounter + 1 End If Else Select Case targetDimension Case 1 If IsObject(copyElement) Then Set newArray(i - ignoreCounter, j) = copyElement Else newArray(i - ignoreCounter, j) = copyElement Case 2 If IsObject(copyElement) Then Set newArray(i, j - ignoreCounter) = copyElement Else newArray(i, j - ignoreCounter) = copyElement End Select End If Else If IsObject(copyElement) Then Set newArray(i, j) = copyElement Else newArray(i, j) = copyElement End If Next j Next i InternalCopyArray = newArrayEnd FunctionInternalCopyClassUsed to produce the new Class Object outputs for each function.Private Function InternalCopyClass(Optional ByRef inputArray As Variant) As CLS_2D_VarArray CheckTargets Dim newCopy As CLS_2D_VarArray Set newCopy = New CLS_2D_VarArray Dim withHeaders As Boolean withHeaders = Not (This.ColumnHeaderIndexes Is Nothing) If IsMissing(inputArray) Then newCopy.SetArray Me.CopyArray(), withHeaders Else newCopy.SetArray inputArray, withHeaders End If Set newCopy.PrintRange = This.PrintRange Set InternalCopyClass = newCopyEnd FunctionInternalRemoveIndexesEffectively an abstraction layer between input methods and the core CopyArray function.Private Function InternalRemoveIndexes(ByVal targetDimension As Long, ByRef indexesToRemove As Variant) As CLS_2D_VarArray '/ Returns a new class object with identical array contents to This.VarArray. '/ Will skip over target Indexes rather than copying, effectively removing them from the result. Set InternalRemoveIndexes = InternalCopyClass(InternalCopyArray(targetDimension, indexesToRemove))End FunctionInvertTargetIndexesGiven a list of indexes in a target dimension, returns a list of all the other indexes in that dimension. E.G. given a list of indexes to keep, invert the list and suddenly it's a list of indexes *not* to keep.Whenever there is a Keep/Remove function, one will simply invert the target list and pass to the other.Private Function InvertTargetIndexes(ByVal targetDimension As Long, ByRef targetIndexes As Variant) As Variant '/ returns a listArray containing all the indexes NOT in targetIndexes. Dim LB1 As Long, UB1 As Long Dim LB2 As Long, UB2 As Long GetBounds LB1, UB1, LB2, UB2 Dim invertedIndexes As Variant ReDim invertedIndexes(1 To DimLength(This.varArray, targetDimension) - DimLength(targetIndexes, 1)) Dim startIndex As Long, endIndex As Long Select Case targetDimension Case 1 startIndex = LB1 endIndex = UB1 Case 2 startIndex = LB2 endIndex = UB2 End Select Dim matchCounter As Long Dim ix As Long For ix = startIndex To endIndex If IsNull(IndexIn1DArray(targetIndexes, ix)) Then '/ is not in indexes to keep matchCounter = matchCounter + 1 invertedIndexes(matchCounter) = ix End If Next ix InvertTargetIndexes = invertedIndexesEnd FunctionRemoveIndexes, KeepIndexesPublic Function RemoveIndexes(ByVal targetDimension As Long, ByRef indexesToRemove As Variant) As CLS_2D_VarArray '/ Returns a new class object with identical array contents to VarArray. '/ Will skip over target Indexes rather than copying, effectively removing them from the result. If (Not IsMissing(targetDimension)) And (Not IsMissing(indexesToRemove)) Then CheckTargets targetDimension, checkIndexList:=indexesToRemove Set KeepIndexes = InternalRemoveIndexes(targetDimension, indexesToRemove) Else PrintErrorMessage Both target Dimension and target Indexes must be supplied Stop End IfEnd FunctionPublic Function KeepIndexes(ByVal targetDimension As Long, ByRef indexesToKeep As Variant) As CLS_2D_VarArray '/ Returns a new class object with identical array contents to VarArray. '/ Will skip over non-target Indexes rather than copying, effectively removing them from the result. If (Not IsMissing(targetDimension)) And (Not IsMissing(indexesToKeep)) Then CheckTargets targetDimension, checkIndexList:=indexesToKeep Set KeepIndexes = InternalRemoveIndexes(targetDimension, InvertTargetIndexes(indexesToKeep)) Else PrintErrorMessage Both target Dimension and target Indexes must be supplied Stop End IfEnd FunctionRemoveByPredicate,KeepByPredicateFilter the array, based on values in a target index, using a logical predicate.Public Function RemoveByPredicate(ByVal targetDimension As Long, ByVal targetIndex As Long, ByRef predicate As CLS_Comparison_Predicate) As CLS_2D_VarArray '/ Use the predicate to build a list of indexes to remove, then pass to InternalRemoveIndexes '/ E.G. dimension 2, index 1, predicate(GreaterThan, 9000) will remove all rows where the value in column 1 is Greater Than 9,000 If predicate Is Nothing Then PrintErrorMessage Predicate must be set Stop End If CheckTargets targetDimension, targetIndex Dim arrayListAtIndex As Variant arrayListAtIndex = ArrayListFromIndex(targetDimension, targetIndex) Dim LB1 As Long, UB1 As Long AssignArrayBounds arrayListAtIndex, LB1, UB1 Dim removeCounter As Long Dim indexesToRemove As Variant ReDim indexesToRemove(1 To 1) Dim ix As Long For ix = LB1 To UB1 If predicate.Compare(arrayListAtIndex(ix)) Then removeCounter = removeCounter + 1 ReDim Preserve indexesToRemove(1 To removeCounter) indexesToRemove(removeCounter) = ix End If Next ix If removeCounter > 0 Then '/ Target Dimension for removal will be the opposite to the one we were comparing Select Case targetDimension Case 1 targetDimension = 2 Case 2 targetDimension = 1 End Select Set RemoveByPredicate = InternalRemoveIndexes(targetDimension, indexesToRemove) Else Set RemoveByPredicate = InternalCopyClass End IfEnd FunctionPublic Function KeepByPredicate(ByVal targetDimension As Long, ByVal targetIndex As Long, ByRef predicate As CLS_Comparison_Predicate) As CLS_2D_VarArray '/ Inverts the predicate, then passes to RemoveByPredicate If predicate Is Nothing Then PrintErrorMessage Predicate must be set Stop End If CheckTargets targetDimension, targetIndex Dim invertedPredicate As CLS_Comparison_Predicate Set invertedPredicate = predicate.Copy(copyInverted:=True) Set KeepByPredicate = Me.RemoveByPredicate(targetDimension, targetIndex, invertedPredicate)End FunctionRemoveHeaders, KeepHeadersPublic Function RemoveHeaders(ByVal headerList As Variant) As CLS_2D_VarArray '/ Use the headers to build a list of indexes to remove, then pass to InternalRemoveIndexes If Not IsListArray(headerList) Then PrintErrorMessage headerList must be a listArray Stop End If Const TARGET_DIMENSION As Long = 2 '/ Targeting columns Dim indexesOfHeaders As Variant indexesOfHeaders = GetIndexesOfHeaders(headerList) Set KeepHeaders = InternalRemoveIndexes(TARGET_DIMENSION, indexesOfHeaders)End FunctionPublic Function KeepHeaders(ByVal headerList As Variant) As CLS_2D_VarArray '/ Use the headers to build a list of indexes to remove, then pass to InternalRemoveIndexes If Not IsListArray(headerList) Then PrintErrorMessage headerList must be a listArray Stop End If Const TARGET_DIMENSION As Long = 2 '/ Targeting columns Dim indexesOfHeaders As Variant indexesOfHeaders = GetIndexesOfHeaders(headerList) Set KeepHeaders = InternalRemoveIndexes(TARGET_DIMENSION, InvertTargetIndexes(2, indexesOfHeaders))End FunctionColumnIndexOfHeaderPublic Function ColumnIndexOfHeader(ByVal header As Variant) As Variant '/ Returns NULL if header cannot be found in ColumnHeaderIndexes With This If .ColumnHeaderIndexes.Exists(header) Then ColumnIndexOfHeader = .ColumnHeaderIndexes.item(header) Else ColumnIndexOfHeader = Null End WithEnd FunctionArrayListFromIndexPublic Function ArrayListFromIndex(ByVal targetDimension As Long, ByVal targetIndex As Long) As Variant '/ Given a target index in VarArray, return a 1-D array of all the items in that index. '/ The returned array will still retain the same indexes as the original CheckTargets targetDimension, targetIndex Dim LB1 As Long, UB1 As Long Dim LB2 As Long, UB2 As Long GetBounds LB1, UB1, LB2, UB2 Dim arrayList As Variant Dim i As Long Select Case targetDimension Case 1 ReDim arrayList(LB2 To UB2) For i = LB2 To UB2 If IsObject(This.varArray(targetIndex, i)) Then Set arrayList(i) = This.varArray(targetIndex, i) Else arrayList(i) = This.varArray(targetIndex, i) Next i Case 2 ReDim arrayList(LB1 To UB1) For i = LB1 To UB1 If IsObject(This.varArray(i, targetIndex)) Then Set arrayList(i) = This.varArray(i, targetIndex) Else arrayList(i) = This.varArray(i, targetIndex) Next i End Select ArrayListFromIndex = arrayListEnd FunctionAddDataGiven some input array, find the corresponding headers in VarArray and copy the contents to new rows.Public Sub AddData(ByRef inputArray As CLS_2D_VarArray) '/ Takes the input array, determines that all headers exist in this array then writes all data to newlines CheckTargets If This.ColumnHeaderIndexes Is Nothing Then PrintErrorMessage Cannot match data as VarArray has no headers Stop End If Dim inputData As Variant inputData = inputArray.GetArray If IsEmpty(inputData) Then PrintErrorMessage Input array has no data Stop End If Dim mapHeaders As Dictionary Set mapHeaders = MapHeadersToIndexes(inputData) Dim inputLB1 As Long, inputUB1 As Long Dim inputLB2 As Long, inputUB2 As Long AssignArrayBounds inputData, inputLB1, inputUB1, inputLB2, inputUB2 Dim thisLB1 As Long, thisUB1 As Long Dim thisLB2 As Long, thisUB2 As Long GetBounds thisLB1, thisUB1, thisLB2, thisUB2 Dim thisArray As Variant thisArray = This.varArray thisArray = Transpose2dArray(thisArray) ReDim Preserve thisArray(thisLB2 To thisUB2, thisLB1 To thisUB1 + (DimLength(inputData, 1) - 1)) '/ -1 because not copying header row thisArray = Transpose2dArray(thisArray) Dim header As Variant Dim columnIndex As Long Dim copyElement As Variant Dim ix As Long, iy As Long '/ inputData indexes Dim thisRow As Long, thisCol As Long '/ thisArray indexes For iy = inputLB2 To inputUB2 header = inputData(inputLB1, iy) columnIndex = mapHeaders(header) thisCol = columnIndex For ix = inputLB1 + 1 To inputUB1 '/ +1 for ignoring headers thisRow = thisUB1 + (ix - (inputLB1 + 1) + 1) If IsObject(inputData(ix, iy)) Then Set thisArray(thisRow, thisCol) = inputData(ix, iy) Else thisArray(thisRow, thisCol) = inputData(ix, iy) Next ix Next iy Me.SetArray (thisArray)End SubMapHeadersToIndexesUsed to map headers for AddDataPrivate Function MapHeadersToIndexes(ByRef inputData As Variant) As Dictionary '/ For each header in inputData, finds the matching header in VarArray, adds the header/index to a dictionary '/ Throws an error if a header cannot be matched to VarArray Dim LB1 As Long Dim LB2 As Long, UB2 As Long AssignArrayBounds inputData, LB1, LB2:=LB2, UB2:=UB2 Dim mapHeaders As Dictionary Set mapHeaders = New Dictionary Dim header As Variant Dim columnIndex As Long Dim iy As Long For iy = LB2 To UB2 header = inputData(LB1, iy) If This.ColumnHeaderIndexes.Exists(header) Then columnIndex = This.ColumnHeaderIndexes.item(header) mapHeaders.Add header, columnIndex Else PrintErrorMessage Header & cstr(header) & does not exist in this array Stop End If Next iy Set MapHeadersToIndexes = mapHeadersEnd FunctionInsertIndex,FillIndexPublic Function InsertIndex(ByVal targetDimension As Long, ByVal targetIndex As Long, Optional ByVal header As Variant, Optional ByVal fillValue As Variant) As CLS_2D_VarArray '/ Returns a copy of VarArray with a new Row/Column by copying VarArray and leaving an extra gap at the specified index. CheckTargets targetDimension, targetIndex Dim LB1 As Long, UB1 As Long Dim LB2 As Long, UB2 As Long GetBounds LB1, UB1, LB2, UB2 Dim newArr As Variant If targetDimension = 1 Then ReDim newArr(LB1 To UB1 + 1, LB2 To UB2) If targetDimension = 2 Then ReDim newArr(LB1 To UB1, LB2 To UB2 + 1) Dim isAfterTarget As Boolean Dim sourceValue As Variant Dim ix As Long, iy As Long For ix = LB1 To UB1 For iy = LB2 To UB2 sourceValue = This.varArray(ix, iy) isAfterTarget = targetDimension = 1 And ix >= targetIndex Or targetDimension = 2 And iy >= targetIndex If isAfterTarget Then If targetDimension = 1 Then If IsObject(sourceValue) Then Set newArr(ix + 1, iy) = sourceValue Else newArr(ix + 1, iy) = sourceValue If targetDimension = 2 Then If IsObject(sourceValue) Then Set newArr(ix, iy + 1) = sourceValue Else newArr(ix, iy + 1) = sourceValue Else If IsObject(sourceValue) Then Set newArr(ix, iy) = sourceValue Else newArr(ix, iy) = sourceValue End If Next iy Next ix If Not (IsMissing(fillValue) And IsMissing(header)) Then FillIndex2D newArr, targetDimension, targetIndex, fillValue, header Set InsertIndex = InternalCopyClass(newArr)End FunctionPublic Function FillIndex(ByVal targetDimension As Long, ByVal targetIndex As Long, Optional ByVal fillValue As Variant, Optional ByVal header As Variant) As CLS_2D_VarArray '/ Fills every element of the index with fill value. If header is provided then the lower-bound of the index will contain the header value. CheckTargets targetDimension, targetIndex Dim LB1 As Long, UB1 As Long Dim LB2 As Long, UB2 As Long GetBounds LB1, UB1, LB2, UB2 Dim newArray As Variant newArray = InternalCopyArray Dim ix As Long, iy As Long Select Case targetDimension Case 1 If Not IsMissing(fillValue) Then For iy = LB2 To UB2 newArray(targetIndex, iy) = fillValue Next iy End If If Not IsMissing(header) Then This.varArray(targetIndex, LB2) = header Case 2 If Not IsMissing(fillValue) Then For ix = LB1 To UB1 newArray(ix, targetIndex) = fillValue Next ix End If If Not IsMissing(header) Then This.varArray(LB1, targetIndex) = header End Select Set FillIndex = InternalCopyClass(newArray)End FunctionReplaceValuesPublic Function ReplaceValues(ByVal findValue As Variant, ByVal replaceValue As Variant) As CLS_2D_VarArray '/ Replaces all *exact* occurences of the find value with the replace value. *exact* means the entirety of the array element must match. '/ Ignores objects. CheckTargets Dim newArray As Variant newArray = InternalCopyArray Dim LB1 As Long, UB1 As Long Dim LB2 As Long, UB2 As Long GetBounds LB1, UB1, LB2, UB2 Dim i As Long, j As Long For i = LB1 To UB1 For j = LB2 To UB2 If Not IsObject(newArray(i, j)) Then If newArray(i, j) = findValue Then newArray(i, j) = replaceValue Next j Next i Set ReplaceValues = InternalCopyClass(newArray)End FunctionSortRowsPublic Function SortRows(ByVal sortIndex As Long, Optional ByVal ignoreHeaders As Boolean = True, Optional ByVal sortOrder As XlSortOrder = xlAscending) As CLS_2D_VarArray '/ Simple Bubble sort - *Towards* the upper bound of the index - so xlAscending will result in the largest value being at the upper-bound of the index '/ Will fail if the index contains objects Const TARGET_DIMENSION As Long = 2 '/ sorting rows IN a column CheckTargets checkIndex:=sortIndex Dim LB1 As Long, UB1 As Long Dim LB2 As Long, UB2 As Long GetBounds LB1, UB1, LB2, UB2 If ignoreHeaders Then LB1 = LB1 + 1 Dim newArray As Variant newArray = InternalCopyArray Dim numIterations As Long numIterations = DimLength(newArray, 1) - 1 If ignoreHeaders Then numIterations = numIterations - 1 Dim swapValues As Boolean Dim currentItem As Variant, nextItem As Variant Dim currentIndex As Long, nextIndex As Long Dim ix As Long, iy As Long For ix = 1 To numIterations For currentIndex = LB1 To UB1 - 1 nextIndex = currentIndex + 1 currentItem = newArray(currentIndex, sortIndex) nextItem = newArray(nextIndex, sortIndex) swapValues = False If sortOrder = xlAscending Then swapValues = currentItem > nextItem Else swapValues = currentItem < nextItem End If If swapValues Then For iy = LB2 To UB2 '/ Sort column must have values, but the rest of the array could easily contain objects as well If IsObject(newArray(currentIndex, iy)) Then Set currentItem = newArray(currentIndex, iy) Else currentItem = newArray(currentIndex, iy) If IsObject(newArray(nextIndex, iy)) Then Set nextItem = newArray(nextIndex, iy) Else nextItem = newArray(nextIndex, iy) If IsObject(currentItem) Then Set newArray(nextIndex, iy) = currentItem Else newArray(nextIndex, iy) = currentItem If IsObject(nextItem) Then Set newArray(currentIndex, iy) = nextItem Else newArray(currentIndex, iy) = nextItem Next iy End If Next currentIndex Next ix Set SortRows = InternalCopyClass(newArray)End FunctionPrintToSheetPublic Sub PrintToSheet(ByRef targetSheet As Worksheet, Optional ByRef startCell As Range) CheckTargets If startCell Is Nothing Then Set startCell = targetSheet.Cells(1, 1) Dim rowCount As Long, colCount As Long rowCount = DimLength(This.varArray, 1) colCount = DimLength(This.varArray, 2) Dim PrintRange As Range With targetSheet Set PrintRange = .Range(startCell, .Cells(startCell.row + rowCount - 1, startCell.Column + colCount - 1)) End With PrintRange = This.varArray Set This.PrintRange = PrintRangeEnd SubExternal Methods/Classes included for context:CLS_Comparison_PredicateOption ExplicitPrivate Type TComparer Operator As ComparisonOperator RightValue As VariantEnd TypePrivate This As TComparerPrivate Const NULL_ERROR_TEXT As String = Invalid Compare input. Cannot compare against NullPrivate Const OBJECT_ERROR_TEXT As String = Invalid Compare input. Input must be a value, not an objectPrivate Const EMPTY_ERROR_TEXT As String = Invalid Compare Input. Input cannot be emptyPrivate Const ZLS_ERROR_TEXT As String = Invalid Compare Input. Input cannot be a Zero-Length-StringPublic Property Let Operator(ByVal inputOperator As ComparisonOperator) This.Operator = inputOperatorEnd PropertyPublic Property Let RightValue(ByVal inputValue As Variant) CheckInputValue inputValue This.RightValue = inputValueEnd PropertyPublic Function Copy(Optional ByVal copyInverted As Boolean = False) As CLS_Comparison_Predicate Dim newPredicate As CLS_Comparison_Predicate Set newPredicate = New CLS_Comparison_Predicate With newPredicate .RightValue = This.RightValue If Not copyInverted Then .Operator = This.Operator Else Select Case This.Operator Case NotEqualTo .Operator = EqualTo Case LessThan .Operator = GreaterThanOrEqualTo Case LessThanOrEqualTo .Operator = GreaterThan Case EqualTo .Operator = NotEqualTo Case GreaterThanOrEqualTo .Operator = LessThan Case GreaterThan .Operator = LessThanOrEqualTo Case Else '/ Should only happen if operator has not been set PrintErrorMessage operator has not been set Stop End Select End If End With Set Copy = newPredicateEnd FunctionPublic Function Compare(ByVal inputValue As Variant) As Boolean CheckInputValue inputValue With This Dim isTrue As Boolean Select Case .Operator Case NotEqualTo isTrue = (inputValue <> .RightValue) Case LessThan isTrue = (inputValue < .RightValue) Case LessThanOrEqualTo isTrue = (inputValue <= .RightValue) Case EqualTo isTrue = (inputValue = .RightValue) Case GreaterThanOrEqualTo isTrue = (inputValue >= .RightValue) Case GreaterThan isTrue = (inputValue > .RightValue) Case Else '/ Should only happen if operator has not been set PrintErrorMessage operator has not been set Stop End Select End With Compare = isTrueEnd FunctionPrivate Sub CheckInputValue(ByVal inputValue As Variant) '/ Check for NULL, Objects, Empty and ZLS If IsNull(inputValue) Then PrintErrorMessage NULL_ERROR_TEXT Stop End If If IsObject(inputValue) Then PrintErrorMessage OBJECT_ERROR_TEXT Stop End If If IsEmpty(inputValue) Then PrintErrorMessage EMPTY_ERROR_TEXT Stop End If On Error Resume Next If Len(inputValue) = 0 Then PrintErrorMessage ZLS_ERROR_TEXT Stop End If On Error GoTo 0End SubExternal MethodsPublic Sub AssignArrayBounds(ByRef targetArray As Variant, _ Optional ByRef LB1 As Variant, Optional ByRef UB1 As Variant, _ Optional ByRef LB2 As Variant, Optional ByRef UB2 As Variant, _ Optional ByRef LB3 As Variant, Optional ByRef UB3 As Variant, _ Optional ByRef LB4 As Variant, Optional ByRef UB4 As Variant, _ Optional ByRef LB5 As Variant, Optional ByRef UB5 As Variant) '/ Assigns the L/U Bounds of the array for the specified dimension arguments If Not IsMissing(LB1) Then LB1 = LBound(targetArray, 1) If Not IsMissing(UB1) Then UB1 = UBound(targetArray, 1) If Not IsMissing(LB2) Then LB2 = LBound(targetArray, 2) If Not IsMissing(UB2) Then UB2 = UBound(targetArray, 2) If Not IsMissing(LB3) Then LB3 = LBound(targetArray, 3) If Not IsMissing(UB3) Then UB3 = UBound(targetArray, 3) If Not IsMissing(LB4) Then LB4 = LBound(targetArray, 4) If Not IsMissing(UB4) Then UB4 = UBound(targetArray, 4) If Not IsMissing(LB5) Then LB5 = LBound(targetArray, 5) If Not IsMissing(UB5) Then UB5 = UBound(targetArray, 5)End SubPublic Function DimensionCountOfArray(ByRef targetArray As Variant) Dim maxDimension As Long Dim errCheck As Variant maxDimension = 0 Do While maxDimension <= 60000 On Error GoTo maxFound errCheck = LBound(targetArray, maxDimension + 1) On Error GoTo 0 maxDimension = maxDimension + 1 LoopmaxFound: On Error GoTo 0 DimensionCountOfArray = maxDimensionEnd FunctionPublic Function IndexIn1DArray(ByRef targetArray As Variant, ByVal searchItem As Variant, Optional ByVal startAtLowerBound As Boolean = True, Optional ByVal nthMatch As Long = 1, Optional ByRef matchWasFound As Boolean) As Variant '/ Returns the index of the Nth Match of a value in the target array. Returns Null if match not found. Dim LB1 As Long, UB1 As Long AssignArrayBounds targetArray, LB1, UB1 Dim startIndex As Long, endIndex As Long, stepValue As Long If startAtLowerBound Then startIndex = LB1 endIndex = UB1 stepValue = 1 Else startIndex = UB1 endIndex = LB1 stepValue = -1 End If Dim matchCounter As Long matchCounter = 0 Dim targetIndex As Variant targetIndex = Null Dim i As Long For i = startIndex To endIndex Step stepValue If targetArray(i) = searchItem Then matchCounter = matchCounter + 1 If matchCounter = nthMatch Then targetIndex = i Exit For End If Next i If Not IsNull(targetIndex) Then targetIndex = CLng(targetIndex) IndexIn1DArray = targetIndexEnd FunctionPublic Function Transpose2dArray(ByRef sourceArray As Variant) As Variant Dim LB1 As Long, UB1 As Long Dim LB2 As Long, UB2 As Long AssignArrayBounds sourceArray, LB1, UB1, LB2, UB2 Dim transposedArray() As Variant ReDim transposedArray(LB2 To UB2, LB1 To UB1) Dim i As Long, j As Long For i = LB1 To UB1 For j = LB2 To UB2 transposedArray(j, i) = sourceArray(i, j) Next j Next i Transpose2dArray = transposedArrayEnd Function | Class: 2D Variant Array | object oriented;vba;error handling;excel | null |
_webmaster.105464 | On my site I get the error :Uncaught TypeError: google.search.Search.apiary15400 is not a functionwhere the number changes on each page refresh.I've already checked here: https://productforums.google.com/forum/#!topic/customsearch/CYN9lFK46hk, but did not find any double cse references in my own code.Also, the ads that are being shown on the result page are somehow lightly grayed out.I tried adding the script code to the head of the googlesearch.aspx page and the cse tag in the body, but that results in the same error.How I inject the code:in head:<script type=text/javascript> (function () { var cx = '014868809914487598599:qtooouruo1q'; var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true; gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//www.google.com/cse/cse.js?cx=' + cx; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s); })();</script>in body:<gcse:searchresults-only></gcse:searchresults-only>`Why is this happening? | Google Custom Search: Uncaught TypeError: google.search.Search.apiary15400 is not a function | google custom search | You're loading the script twice, causing the function to run twice and produce this error. An example line that is doubled up:<script type=text/javascript async= src=https://www.google.com/cse/cse.js?cx=014868809914487598599:qtooouruo1q></script>It's not the only line that's doubled - perhaps check your code for duplicates. Or if it's being injected check your document write calls to see if they've been doubled up. |
_cstheory.18560 | I am solving a problem of blending sets of overlapping images. These sets can be represented by undirected weighted graph such as this one:Each node represents an image. Overlapping images are connected by an edge. Edge weight represents overlap area size (blending larger overlap sooner leads to better overall quality).The algorithm generally removes edges. It can do it sequentially or in parallel. However, when blending occurs, the nodes merge and the graph structure changes. So parallelization is possible only on connected components that are themselves not overlapping!Such non-overlapping components are D-B and F-E-G. We can run the blending algorithm on these components safely in parallel. The result is the following graph (merged nodes are displayed in green):Now there is no further parallelization possible because any two connected components are overlapping (they have an edge directly between them).The parallel version of the algorithm would look like this:1. Find connected components (no two are connected directly) and create task for each.2. Run the tasks in parallel.3. Update graph.4. Until single node remains, continue with 1.The tricky part is the first step: How to find best set of connected components?One way would be a greedy algorithm that simply finds the largest number of components at a given iteration.The greedy algorithm will maximize parallelization in the beginning but at the cost of many iterations later.The optimal solution may be bringing good amount of connected components in each iteration to maximize parallelization and minimize number of iterations at the same time (so there are two variables in the optimization).I can't think of any optimization algorithm other than backtracking, i.e. search space of all possible evolutions and choose the one with maximum parallelization.Edge weights can be ignored, but improved version of the algorithm may take it into account as larger areas takes more time to blend (e.g. area of size 200 will take roughly twice the time to blend than two areas of size 100). Taking weights into account may lead to better strategy on selecting components (faster overall running time of the algorithm).Do you have any clues for such optimization algorithm, that finds the best strategy of selecting parts of graph so that there is maximum parallelization and minimum number of iterations? | Finding optimal parallelization from general weighted undirected graph | ds.algorithms;graph theory;graph algorithms;directed acyclic graph;parallel | null |
_datascience.22254 | The authors of the original paper of Faster R-CNN when they refer to the positive anchors, they are labeled as 1. I guess they refer in binary classification. What happens in the case in a task we have more than two classes?I mean the purpose of the RPN is to generate just region proposals (there is an object or not, regardless the label) or it generates region proposals and the respective label as well? I guess it is the second case, since the positive anchors that participate in the training process need to have a ground truth label as well, i.e. (cat, dog, e.t.c).However, I might misunderstand things and interpret things in a wrong way. | Faster R-CNN: Labels regarding the positive anchors when there are many classes | machine learning;deep learning;image recognition;object recognition | null |
_unix.187465 | I transfer files through ssh, from one computer to another. Is there any way I receive a notification on my computer, when someone tries to transfer files via ssh? | Alert when transfering files using SSH? | ssh | null |
_softwareengineering.83948 | For our company needs, we need to sell one of our software on *nix-like system.How can we distribute and protect our software ? I know that almost every program on linux is open-source, so how can we protect source code ? Do we need distribute part of source code in object files ? Software written in C. | How to distribute our software on Linux without shipping source code | c;commercial | null |
_unix.35860 | I have encountered some malware on my Linux server, and am trying to remove it from many php files.I've tried endlessly with grep | sed and grep | tr and couldn't even erase a simple text string, getting different errors.When trying:grep -l '@error' * | xargs -0 sed -i 's/error/nothing/g' I receive an error message:can't read filename.phpUsing Terminal on Mac - maybe it's an OSX syntax problem?My final task is to delete a long string of code from all the files - one that includes some $,!,?,<,>,\, symbols - will I need to backslash them? | Removing a long string from php files - using grep and sed? | linux;grep;sed;php;tr | You should restore from backup or source control as @Mat suggested because otherwise you cannot be 100% sure you cleaned up everything.The problem with your command is the -0 flag for xargs, because that way xargs is expecting null-terminated arguments, which does not work with the output of grep -l. Just drop the -0 and it will work, as long as the file names don't have white spaces in them.grep -l '@error' * | xargs sed -i 's/error/nothing/g' |
_softwareengineering.260232 | Currently, I'm working on a system that enables users to add Tag's to available TagTypes on specific pages. For instance, we would have a TagType called Installer and the user wants his name associated with it (his name then would be the Tag). A requirement of this system is that administrators can add constraints to TagTypes. Once a Tag is created on an existing TagType, the containing constraint checks the Tag's value.Our wish is to make it as easy as possible to implement new types of constraints in the future. For instance, we would have a RegularExpression-constraint, a List-constraint (the value of a Tag should be one of the values in a list), an int-range constraint, etcetera. What would be the best way of facilitating this need? Not only does the constraint need checking once a Tag has been created (or edited), also, the back-end for administrators creating new constraints needs to be adjustable in an easy manner. We got to this point by implementing something bad:class TagTypeConstraint{}class TTConstraintList : TagTypeConstraint{}class TTConstraintIntRange : TagTypeConstraint{}class TTConstraintRegex : TagTypeConstraint{}This already has the problem, besides the awful maintainability, that abstract methods in TagTypeConstraint are becoming useless as the inheriting classes want other information passed to it (one wants a string, the other one wants two ints, the last one wants a string again). Maybe a future constraint will want a list of integers. I'm thinking there needs to be a good level of abstraction for our back-end to be easily extendable but how to achieve that when methods of inheriting classes will be asking for different parameters?Edit:I've made some progressions on how to tackle.My TagTypeConstraint class is now abstract, having abstract methods like + SetConstraint(object[] values) and + IsValid(object[] values) .These abstract methods get implemented by the inheriting classes and in those classes, the object[] variables are cast to appropriate types. If the casts fail, I will throw a ConstraintException. Also, I've added a static function to TagTypeConstraint that acts like a (simple) factory, removing the need to call the implementations of TagTypeConstraint in layers like the GUI. Any comments on this would be appreciated.Current (updated) structure:Tagstring _content;TagType _tagType;TagTypestring _name;TagTypeDataType _dataType;TagTypeDataTypestring _name;Constraint _constraint;abstract Constraintstatic Constraint CreateConstraint(ConstraintType type)abstract void SetConstraint(object[] values)abstract bool IsValid(object[] values)abstract ConstraintType GetConstraintType()StringListConstraintList _constraintValues;ConstraintType _constraintType;override void SetConstraint(object[] values)override bool IsValid(object[] values)override ConstraintType GetConstraintType() | Environment that enables variable constraint checking and creation | design patterns;maintainability;rules and constraints | null |
_unix.379947 | When running dd command to copy an ISO on Linux, I get a single progress print that stays open for a long time (many minutes). Then another at the end.The problem seems to be that a very large cache is being used which makes dd think sudo dd bs=4M if=my.iso of=/dev/sdc status=progressOutput (first line shows for a long time).1535115264 bytes (1.5 GB, 1.4 GiB) copied, 1.00065 s, 1.5 GB/s403+1 records in403+1 records out1692844032 bytes (1.7 GB, 1.6 GiB) copied, 561.902 s, 3.0 MB/sIs there a way to prevent this from happening so the progress output is meaningful? | How to prevent dd's progress from being meaningless on Linux? | dd | From the first line we can tell dd has read and written 1.5GB in one second. Even an SSD can't write that fast.What happened is that the /dev/sdc block device accepted it (writeback), but didn't send it to disk but buffered it and started writing to disk at the rate the disk can take it. Something like 3MiB/s.The system can't buffer data indefinitely like that, there's only so much data it will accept to hold in that non-committed dirty state. So after a while (in your case, after more than 1.5GB have been written but less than 2 seconds have passed (as progress lines are written every second)), dd's write() system call will block until the data has been flushed to the disk (during which it cannot write progress messages). When it gets through, dd can send the few extra missing megabytes, and that happens within less than a second, so you get only one extra progress line.To see a different behaviour, you could force the writes to be synchronous, that is not to return unless the data has been committed to disk. For instance by using oflag=sync or oflag=dsync or oflag=direct (not that I would advise doing that though). |
_webmaster.24488 | I've inherited a site built with a CMS I'm not familiar with. I've created new pages for the site and I can see they do appear in a html sitemap, but not the xml sitemap.Assuming I can't add the pages to the xml sitemap, should I delete the xml sitemap or leave it in place but with pages missing? | Sitemap with pages missing better than no sitemap at all? | sitemap | Leave it in place, but ideally figure out how to add the missing pages eventually, if only for the sake of completeness. Sitemaps are only informative. If something is missing from the map, it won't be interpreted as this isn't intended for crawling. As long as the pages are linked from somewhere, they'll get crawled.You didn't mention how long you've given this, but note that generating a sitemap might be computationally expensive if it's a large site, so there might be a delay in regenerating it, either just from the process running, or even because there's a scheduled task that handles it rather than it being done real-time. |
_softwareengineering.134064 | Sometimes I find in the source code files comments have quotation marks like these ,notice the ` :`help'``helpFor example, these are comments from GNU cat source code file, cat.c: /* Plain cat. Copies the file behind `input_desc' to STDOUT_FILENO. */> /* Select which version of `cat' to use. If any options (more than -u, --version, or --help) were specified, use `cat', otherwise use `simple_cat'. */>/* Suppress `used before initialized' warning. */While in other parts, is used : /* Determines how many consecutive newlines there have been in the input. 0 newlines makes NEWLINES -1, 1 newline makes NEWLINES 1, etc. Initially 0 to indicate that we are at the beginning of a new line. The state of the procedure is determined by NEWLINES. */What does ` mean? and what is it used for? | Is there a difference between the quotes in `help',``help, 'help' and help? | documentation;comments | It's the result (habit) of someone using LaTeX - it doesn't mean anything.E.g., in LaTeX, ``hello there'' would result in hello there.If, however, you see as part of a shell script, the command within the backticks () is performed. E.g., $ echo `whoami`awesome-linux-accountname |
_cs.1471 | I'm working on a ranking system that will rank entries based on votes that have been cast over a period of time. I'm looking for an algorithm that will calculate a score which is kinda like an average, however I would like it to favor newer scores over older ones. I was thinking of something along the line of: $$\frac{\mathrm{score}_1 +\ 2\cdot \mathrm{score}_2\ +\ \dots +\ n\cdot \mathrm{score}_n}{1 + 2 + \dots + n}$$I was wondering if there were other algorithms which are usually used for situations like this and if so, could you please explain them? | Looking for a ranking algorithm that favors newer entries | algorithms;data mining | You could use any function that gives a lower weight to older entries. For example, if data consists of scores, $s_1,\ldots,s_n$, where the index corresponds to the 'time of arrival' of the entry, that is, newer entries have larger indices, then you could use a weight function that increase as $i$ increases. So any 'increasing' function will do. Examples include:$f(x)=e^x$$f(x)=\log x$$f(x)=x$$f(x)=x^2$etc.Then your function will be$\dfrac{\sum_{i=1}^n s_i\cdot f(i)}{\sum_{i=1}^n f(i)}$.Actually, it makes more sense to give the newest entry the lowest index and make the weight function decreasing. This way you can tune it by setting the weighting that you want to give to the first element. Wikipedia has an entry on weight functions, some examples can be found on the page about weighted means. |
_codereview.97868 | I am learning how to implement Bootstrap modals in AngularJS. I can do it when the modal code (the actual popup window code) is on the main page, but I want to be able to display external files so that my SPA isn't super-cluttered. I am implementing this on a much larger scale, but for simplicity's sake I'll keep the code example to a minimum.<html> <head> <meta charset='utf-8'> <script src=js/angular.js></script> <script src=js/angular-ui-bootstrap-modal.js></script> <script src=js/app.js></script> <link rel=stylesheet href=css/bootstrap.css> </head> <body ng-app=MyApp ng-controller=MyCtrl> <button class=btn ng-click=open()>Open Modal</button> <!-- want this code to be an external.html file --> <div modal=showModal close=cancel()> <div class=modal-header> <h4>Modal Dialog</h4> </div> <div class=modal-body> <p>Example paragraph with some text.</p> </div> <div class=modal-footer> <button class=btn btn-success ng-click=ok()>Okay</button> <button class=btn ng-click=cancel()>Cancel</button> </div> </div> <!-- --> </body></html>app.jsvar app = angular.module(MyApp, [ui.bootstrap.modal]);app.controller(MyCtrl, function($scope) { $scope.open = function() { $scope.showModal = true; }; $scope.ok = function() { $scope.showModal = false; }; $scope.cancel = function() { $scope.showModal = false; };});I know that I need to add a templateUrl to my app.js, but don't know how I would bridge the gap between the three files (index.html, app.js, and external.html). | Bootstrap Modals | javascript;angular.js;twitter bootstrap | null |
_softwareengineering.314412 | I have a front/back applications that needs to be logged in to be used. When I log in (by means of the front-end app sending a request to the back end), what I do is not sending a cookie, but a JSON with a token in it. The latter will be stored by the front end app in a sessionstorage and each time it will interact with the back end it will send a request along with the token stored in the sessionstorage. The back end will verify the validity of the token.Do you think this solution is CSRF safe? Do you see any other vulnerabilities I'm not considering/ignoring? | Can I prevent CSRF attacks by using localstorage/sessionstorage? | login;sso | null |
_unix.190175 | Say I have a multi-line strings, but the entries on it are short; if I try to hexdump, then I get something like this:echo somethingisbeingwrittenhere | hexdump -C#00000000 73 6f 6d 65 74 68 69 6e 67 0a 69 73 0a 62 65 69 |something.is.bei|#00000010 6e 67 0a 77 72 69 74 74 65 6e 0a 68 65 72 65 0a |ng.written.here.|#00000020Most hex dump programs, including hexdump simply function as a 2D matrix (you can define how many bytes/column you're going to have per line); and so in this case, the entire output is compacted on two lines of dump.Is there a program that I can use, which would keep going as usual - except when it encounters a new line (0x0a - but possibly any other character, or seqence thereof), it would also start a new line? In this case, I'd imagine an output like:00000000 73 6f 6d 65 74 68 69 6e 67 0a |something.|0000000a 69 73 0a |is.|0000000d 62 65 69 6e 67 0a |being.|00000013 77 72 69 74 74 65 6e 0a |written.|0000001b 68 65 72 65 0a |here.|00000020 | Hexdump of a string starting at new lines? | text formatting;hexdump;hex | null |
_vi.10635 | I have @@ mapped to Space. This can be really convenient.Sometimes I want to combine a macro with another. So maybe I need to record q as @:/jump to run my last regex substitution and move to the next place I probably want to run it. Then @q and press Space until I'm happy.Unfortunately if you run @q, during the macro the @@ repeat will be set to @:. Is there a way to run @: without setting it to @@ while recording the macro for q?In this toy example, instead of combining macros I could copy the substitution into a register and paste it during the q recording, but that requires more foresight, and a bit of fiddling.Edit:I guess as far as combining @: goes, I can always use :%s/\v//gc... There are situations I've wanted to combine macros that have nothing to do with regex though. Only option I can think of so far to do what I want is remap Space to always be @q, instead of the last macro, which might be okay since that's 80% of the time what I mean. | Run a macro without having it set as last macro (@@) | macro | Is there a way to run @: without setting it to @@ while recording the macro for q?Yes:For normal 'character' registers::call feedkeys(@a): needs special handling::call feedkeys(':' . @: . \<CR>)If you use this often, you may want to map it: for @::noremap @- :<C-u>call feedkeys(':' . @: . <Bslash><lt>CR>)<CR> for normal char registers:noremap @_ :<C-u>call feedkeys(@)<Left> more complex version of the latter, improved to not need a final <CR>noremap @_ :<C-u>call FeedReg()<CR>function! FeedReg() echo 'Enter register name character:' let reg=nr2char(getchar()) call feedkeys(getreg(reg))endfunction |
_webmaster.28089 | I've been searching for hours now but can't get any tutorial on this.I have these thumbnails on my homepage which are the first images of their corresponding posts.What I want is that when I mouse-over a post on the homepage... the corresponding thumbnail should also show/rotate the other images of that particular post... bit like a sneak-peak image rotator...Does anyone know where I can get a tutorial regarding this? How's this called?It seems like I'm searching for the wrong keywords on google as I can't find anything. | Thumbnail preview rotator on mouse-over - what is it called? | images | null |
_scicomp.23503 | Given the advection equation for an incompressible flow field$$\frac{\partial c}{\partial t} + \mathrm{Pe} \frac{\partial c}{\partial x} = 0$$what would the best method be for discretizing this without introducing any numerical diffusion or oscillations? Specifically when we have step changes in boundary conditions, and time (and space) dependent velocity $v(x,t)$.The book Numerical Methods for Problems with Moving Fronts by Bruce A. Finlayson goes into great detail on this problem when you have step changes as boundary conditions.He recommends filtered leapfrog as the best finite difference method:$$c^{n+1}_i = \frac{\alpha}{2}\left(c_i^n + c_i^{n+2}\right) + (1-\alpha)c_i^{n-1} - \frac{\mathrm{Pe}\Delta t}{\Delta x}\left(c_{i+1}^n - c_{i-1}^n\right)$$ (filtered means $\alpha = 1$) and Taylor-Galerkin as the best finite element method:$$\frac{1}{6}\left(c_{i+1}^{n+1} - c_{i+1}^{n}\right) + \frac{2}{3}\left(c_{i}^{n+1} - c_{i}^{n}\right) + \frac{1}{6}\left(c_{i-1}^{n+1} - c_{i-1}^{n}\right) = -\frac{\mathrm{Pe}\Delta t}{\Delta x} \left(c^{n}_{i+1} - c^{n}_{i-1}\right) + \frac{\mathrm{Pe}^2\Delta t^2}{\Delta x^2}\left(c^{n}_{i+1} - 2c_i^n + c^{n}_{i-1}\right)$$but I was wondering what the consensus is today? I have tested the mentioned methods, and they both suffer from numerical and oscillation. But perhaps this can be managed by adjusting $\Delta t$ and $\Delta x$ in relation to the velocity?This answer to a related question regarding Crank-Nicholson and the advection equation states thatCrank-Nicolson is not necessarily the best method for the advection equation. It is second order accurate and unconditionally stable, which is fantastic. However it will generate (as with all centered difference stencils) spurious oscillation if you have very sharp peaked solutions or initial conditions.but gives no alternative methods. | Discretization method for advection equation without numerical diffusion | discretization;advection | null |
_codereview.146760 | This python code is for a homemade RC plane radio using the Raspberry Pi and a USB joystick. It sends values over serial to DSM2/X module for RC planes and other RC vehicles. This Python code is modified from codeforge's video CustomRC with raspberry and joystick usb with many improvements by me. feedback on the python code would be great as i rushed the modifications that add expo, channel reversing and channel offset.######################################################################################################################### This short code take input from a usb joystick ( I use microsoft sidewinder) and send it through serial# to a DSM2 module to control all kind of helicopter, multicopter or spektrum compatible devices. This code# must be run in raspbian with raspberry pi (I use a raspberry pi 2 B). You need to modified rPi speed as following:# 1 - remove all ttyAMA0 from /boot/cmdline.txt# 2 - add the following lines to the end of /boot/config.txt:# dtparam=i2c_arm=on# dtparam=i2c1=on# init_uart_clock=3255000# init_uart_baud=115200# dtparam=uart0_clkrate=3000000## 3 - reboot raspberry pi# 4 - install python modules pygame and pyserial# 5 - power on the spektrum receiver or spektrum device in BIND mode (led flashing)# 6 - run this code with root privileges: sudo python joystick.py# 7 - wait the binding complete and enjoy :)## PLEASE CONNECT DSM2 MODULE VCC (red or power) TO 3.3v AND NOT 5V OR YOU WILL BURN IT!# THEN CONNECT NEGATIVE TO NEGATIVE AND SIGNAL PIN OF DSM2 MODULE TO TX PIN ON RASPBERRY PI# NO NEED TO CONNECT RX PIN SO YOU NEED TO CONNECT JUCT 3 PIN OR CABLES## For any info contact me at [email protected]### Copyright (C) <2016> <Guido Berbacchi># Modified <10/11/16> <Ethan Johnston>## This program is free software: you can redistribute it and/or modify# it under the terms of the GNU General Public License as published by# the Free Software Foundation, either version 3 of the License, or# (at your option) any later version.## This program is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the# GNU General Public License for more details.## You should have received a copy of the GNU General Public License# along with this program. If not, see <http://www.gnu.org/licenses/>.########################################################################################################################import pygamefrom time import sleepimport serialser = serial.Serial('/dev/ttyAMA0', 115200)def sendDSM2(): # function to send data to dsm2/x module ser.write(DSM2_Header) ser.write(DSM2_Channel) sleep(0.014)def arduino_map(x, in_min, in_max, out_min, out_max): # map function as arduino map() return (x - in_min) * (out_max - out_min) // (in_max - in_min) + out_min def reverse_val(valinput, in_minval, in_maxval): return (in_maxval - valinput) + in_minvaldef apply_expo(axis_val, factor): factor = reverse_val(factor, 0, 100) factor = factor / 100 return (1 - factor) * axis_val * axis_val * axis_val + factor * axis_val# Global Variable and staticDSM2_Header = bytearray(b'\x98\x01') # header to bindDSM2_Channel = bytearray(b'\x18\x00\x05\xFF\x09\xFF\x0D\xFF\x10\xAA\x14\xAA')DSM2_CHANNELS = 6EPA = 300 #300EPAGAS = 180 #180fineBinding = 30i = 0val = 512BExit = 0#reverse channelsch0rev = False #throttlech1rev = True #rollch2rev = False #pitchch3rev = True #yawch4rev = False #gearch5rev = False #aux#epo for channelsch0expo = 0 #throttlech1expo = 20 #rollch2expo = 20 #pitchch3expo = 20 #yaw#Trimsch0offset = 0 #throttlech1offset = 0 #rollch2offset = 0 #pitchch3offset = 0 #yawch4offset = 0 #gearch5offset = 0 #auxprint (Binding)while fineBinding >= 0: sendDSM2() #print binding sleep(0.1) fineBinding = fineBinding - 1print (Binding end)sleep(1)# change header to send inputDSM2_Header[0] = '\x18';# pygame initialization to read joystick inputpygame.init()clock = pygame.time.Clock()pygame.joystick.init()joystick = pygame.joystick.Joystick(0)joystick.init()while BExit == 0: pygame.event.get() roll = joystick.get_axis(0) pitch = joystick.get_axis(1) yaw = joystick.get_axis(2) gas = joystick.get_axis(3) if ch0rev == True: gas = reverse_val(gas, -1, 1) if ch1rev == True: roll = reverse_val(roll, -1, 1) if ch2rev == True: pitch = reverse_val(pitch, -1, 1) if ch3rev == True: yaw = reverse_val(yaw, -1, 1) roll = apply_expo(roll, ch1expo) pitch = apply_expo(pitch, ch2expo) yaw = apply_expo(yaw, ch3expo) gas = apply_expo(gas, ch0expo) hat = joystick.get_hat(0) BLeft = joystick.get_button( 2 ) BRight = joystick.get_button( 3 ) if BLeft == 1: ch3offset -= 4 print(Yaw Trim: {}.format(ch3offset)) if BRight == 1: ch3offset += 4 print(Yaw Trim: {}.format(ch3offset)) if hat[1] == 1: ch2offset += 4 print(pitch Trim: {}.format(ch2offset)) if hat[1] == -1: ch2offset -= 4 print(pitch Trim: {}.format(ch2offset)) if hat[0] == 1: ch1offset += 4 print(roll Trim: {}.format(ch1offset)) if hat[0] == -1: ch1offset -= 4 print(roll Trim: {}.format(ch1offset)) BExit = 0 while (i < DSM2_CHANNELS): if i == 0: #throttle val = int(arduino_map(gas, -1.0, 1.0, 1023, 0+EPAGAS)) #723 - 300 val = val + ch0offset #print (gas,val) elif i == 1: #roll val = int(arduino_map(roll, -1.0, 1.0, 1023-EPA, 0+EPA)) #723 - 300 val = val + ch1offset #print (roll,val) elif i == 2: #pitch val = int(arduino_map(pitch, -1.0, 1.0, 1023-EPA, 0+EPA)) #723 - 300 val = val + ch2offset #print (pitch,val) elif i == 3: # yaw val = int(arduino_map(yaw, -1.0, 1.0, 1023-EPA, 0+EPA)) #723 - 300 val = val + ch3offset elif i == 4: val = 512 val = val + ch4offset elif i == 5: val = 512 val = val + ch5offset else: #the remaining channels set to half val = 512 if val > 1023: val = 1023 if val < 0: val = 0 (high, low) = (val // 0x100, val % 0x100) DSM2_Channel[i*2] = (i<<2) | high DSM2_Channel[i*2+1] = low i+=1 sendDSM2() clock.tick(135) i=0pygame.quit () | RC Plane Radio using the Raspberry Pi | python;python 2.7;serial port;raspberry pi | null |
_unix.157895 | The shellshock bug in bash works by way of environment variables. Honestly I was suprised by the fact that there is such a feature like:passing on of function definitions via env varsTherefore this question while maybe not perfectly formulated is to ask for an example or a case in which it would be necessary to have this feature?Bonus. Do other shells zsh, dash etc. also have this feature? | Why does bash even parse/run stuff put in the environment variable? | bash;environment variables;function;shellshock | When a script invokes another script, variables of the parent script can be exported, and then they'll be visible in the child script. Exporting functions is an obvious generalization: export the function from the parent, make it visible in the child.The environment is the only convenient way a process can pass arbitrary data to its children. The data has to be marshalled into strings that don't contain null bytes, which isn't a difficulty for shell functions. There are other potential methods, such as shared memory blocks or temporary files passed via file descriptors, but these could cause problems with intermediate programs that don't know what to do with them or would close them. Programs expect to run in an environment that contains variables that they don't know or care about, so they won't go overwriting or erasing them.The choice of using the function name as the name of the environment variable is a strange one. For one thing, it means that an exported variable clashes with an exported function of the same name.Exported functions are an old feature. Functions were added in the Bourne shell in SVR2, and exported functions in the Version 8 shell released the same year (1984). In that shell, variables and functions used the same namespace. I don't know how function export worked. The Heirloom shell is based on a Bourne variant which has functions but doesn't export them.ATT ksh supposedly supports exporting functions, but looking at the source or playing with it, I can't see that it does, as of ksh93u.env -i /usr/bin/ksh -c 'f=variable; f () { echo function; }; typeset -fx f; /usr/bin/env; ksh -c f'_=*25182*/usr/bin/envPWD=/home/gillesSHLVL=1A__z=*SHLVLksh: f: not foundKsh's public domain clones (pdksh, mksh), dash and zsh don't support exporting functions. |
_softwareengineering.267716 | I am writing a simple framework that I want to open source just for experience (and fun!). However, it has some cool ideas that could make it grow to a larger project and I want to be ready if that ever happens. I highly doubt that that will happen, but I want to use this as a learning experience on how to properly run an open source project.I want to dive right into the development. I'm not too worried about the actual code since it should be mostly simple. However, I'm not that experienced with Github. I mean, I know all the basics and such, but I don't really know how to use all of the tools to my advantage.How should I manage a workflow to best accommodate developers? I'm going to try to encourage the standard procedure:Fork the repositoryClone the repository to your Git clientMake a new branch for the workDo the actual workCommit your work (if multiple commits, rebase them to create one commit for easy history on the main repo)Submit a pull request with that one commitThen, obviously, I will choose if I want to pull it or not. Here's where I get stuck. How should I manage my branches?I drafted up this design:Proposed Workflow:Basically:The master branch is for stable releases. Individual pull requests are only sent to the master branch if it's a critical bug and needs an individual release ASAP.The beta branch is for the code for the next stable release. Bug fixes will be pulled to this branch.The alpha branch is where the feature requests are added.When a commit (not a pull request) is added to either the master or beta branch, the changes are cascading (i.e. a pull request is automatically created so that a commit to master will also be on beta and alpha; a commit on beta will be on alpha). I would do this with a simple script. Albeit it'd be somewhat ghetto, but it'd be automatic.For a standard release, the beta would be merged into the master and then the alpha into the beta branch.The reason for this is the feature requests aren't put into the next version so they're stable enough to be in the stable release.Is this dumb? A consolidated dev branch would be the easiest to manage, but I'm afraid that some bugs would still get through. I guess I'd have to stop accepting feature additions a little bit before I release a new version.EDIT: This question is extremely similar to my question: Is there an established or defined best practice for source control branching between development and production builds?. However, I'm looking at my proposed method vs. just not handling pull requests before a new release. Also, this is about open source software (so it might be harder to train new people on the system for this project). | How can I develop a productive Git(hub) branch workflow for an open source project? | open source;version control;github;branching | null |
_cstheory.32978 | In probability and statistics Orlicz norms are frequently used in concentration inequalities. For example, for Bernstein's inequality, we have versions for sub-exponential random variables using $\psi_1$-norm and for bounded random variables using variance. My first thought is that the $\psi_1$-norm version is more general, and includes the case of bounded random variables as a special case. However, an example of Bernoulli random variable with probability $1/n$ being $1$ and $1-1/n$ being $0$ suggests this is not true. For $n$ very large, the variance is roughly of the order $1/n$. However, its $\psi_1$-norm is roughly of the order ${1}/{\log n}$. This suggests that $\psi_1$-norm (or similarly, $\psi_2$-norm) is actually very loose for very biased Bernoulli random variables. Is there any other notions like $\psi_1$-norm that can accommodate biased Bernoulli random variables? | Orlicz norm of random variable and variance | pr.probability;chernoff bound | The Kearns-Saul inequality states that if $X\sim Ber(p)$ then$$ E[\exp(t(X-p))] = (1-p)e^{-tp}+pe^{t(1-p)} \le \exp\left(\frac{1-2p}{4\log((1-p)/p)}t^2\right).$$The subgaussian constant $\frac{1-2p}{4\log((1-p)/p)}$ is optimal.See http://ecp.ejpecp.org/article/view/2359 and especially the appendix in http://www.jmlr.org/papers/v16/berend15a.html for background and a slick proof.The K-S inequality is a considerable improvement over Hoeffding and Bernstein for very small/large $p$. |
_softwareengineering.299174 | I have to create UML documentation for my upcoming project. Now I have previously worked with Java which as an object orientated language is relativly easy to design UML class diagrams for. For my next project I will have to design an AngularJs Application. As some of you might know an Angular application consists of many things including Controllers Factories Services and many more.My question is when designing these using UML should Controllers / Factories / Services be seen as classes in a class diagram even though they are never defined as classes nor have any constructor but merely consists of variables and functions? | UML modeling angular controllers / factories and services | javascript;uml;angularjs | ** Short Quick Technical Answer **You can model Controllers, Factories, and Services as a class, with a stereotype.............................+--------------------+....| <<Controller>> |....| SomeController |....+--------------------+..............................+--------------------+....| <<Factory>> |....| SomeFactory |....+--------------------+..............................+--------------------+....| <<Service>> |....| SomeService |....+--------------------+............................** Long Boring Conceptual Answer **U.M.L. is a modeling tool, altought, was originally designed with Object Orientation, is not glued to it.You can still use U.M.L. for concepts that are not strictly objects. In a matter of fact, many Software Application Developers may design an object in U.M.L., that does not traslates exactly, as an object in an specific Programming Language.For example, the people that interact in a System, a.k.a. Actors, they are not specifically objects, yet some U.M.L. diagrams allow to use a class or object diagram for an Actor, instead of the Standard icon. |
_unix.350855 | I just installed Solaris 11.3 on my laptop. Unfortunately the internal card of this laptop (Broadcom BCM4312) is not supported by Solaris.And so my question is: Is there a list of USB wireless cards with the manufacturer that are supported by Solaris?I will go to the store and buy one and everything will be fine.Thank you. | Solaris 11 list of supported USB wireless cards | solaris | null |
_webmaster.11263 | What is the best way these days to make a visually interesting border around a div using images? CSS3's border-image would perfect, but it's CSS3. I don't want to rely on that yet. Is there a CSS2-compatible way to accomplish the same thing?My audience is mostly with-it, tech-savvy, not needing hacks for decrepit old browsers, but aren't necessarily all up on the cutting edge like CSS3 either.As an alternative to CSS for this, I tried some experiments with 3x3 tables using the images as cell background or cell content. The main content would go in the middle cell. I couldn't get the side images to stretch or repeat properly when the content varied. | CSS2 way of accomplishing what CSS3 border-image does? | css;images | I think the least kludgy solution would involve nesting two divs, and applying the border and a padding to the outer div.You may have to get creative with the application of the background, especially if it's anything more complicated than a tiling image, but it would avoid adding non-semantic tables to your markup. You should never use tables for layout. |
_webapps.78651 | My Google Spreadsheet does not preserve some formatting. Every time I set, for example font size to 12, for the whole sheet, newly copied data uses a smaller font size. This only started being an issue after an upgrade to New Sheets, some time in March.An example sheet that recreates the issue:Steps to reproduceCTRL + A twice to select the whole sheetSet font size to 12Copy & Paste clear text into column EExpected ResultsText in column E is in font size 12Actual ResultsText in column E is in smaller font sizeUPDATE:To recreate the date formatting issue I have created another sheet.Steps to ReproduceSet date formatting on column D to DD MMM YYY (like 1 Jun 2015)Insert some short test in a cell in column BResults ExpectedLMDT triggered on OnEdit event preserves the formatting: 1 Jun 2015Actual ResultsLMDT triggered on OnEdit event does not preserve the formatting: 01/06/2015 07:20:34time = Utilities.formatDate(time, UTC, dd-MM-yyyy **HH:mm:ss** );s.getRange(r.getRow(), LMDTCol).setValue(time);Yes, the formatting is set to dd-MM-yyyy HH:mm:ss but for last five years or so column formatting had higher priority than the formatting set in the script. | Cell formatting in Google Spreadsheets does not get preserved | google spreadsheets;formatting;conditional formatting | null |
_unix.385746 | Simple configuration with mail server with 993 imap port.Local IP is static natted at main router to public IP.I need to restrict access to 993 port by local lan and allow connection to imapl port by special myknown ports.Understand that source IP connecting to special ports are public.So I wonder can it be performed by local iptables or do I need to route special ports by other local host? What did I miss?iptables -A INPUT -p tcp --dport 33333 -j ACCEPTiptables -A INPUT -p tcp --dport 33334 -j ACCEPTiptables -A INPUT -p tcp -s 192.168.0.0/24 --dport 993 -j ACCEPTiptables -A PREROUTING -t nat -p tcp --dport 33333 -j REDIRECT --to-port 993iptables -A PREROUTING -t nat -p tcp --dport 33334 -j REDIRECT --to-port 993Update:I need to open ports 33333 and 33334 for internet and local lan and keep opened 993 port for local lan only.33333 and 33334 ports are forwarded to 993.Forwarding doesn't work in case 993 restricted: -s 192.168.0.0/24.Server has one ethernet interface. | How to restrict main port by iptables and allow service at other port | iptables;port forwarding | null |
_webapps.43824 | For some reason Google Spreadsheet insists on using the data I wish to have for my x-axis as my y-axis. Here I'll show what happens when I try to use my data to form a chart, and what happens when I use Google's example data for creating a line chart.Here is the image (my data is on the right, example data on the left): | Google Spreadsheets mixing up x- and y-axis on line chart, no option to change it | google spreadsheets;graph | null |
_datascience.18264 | I am studying neural networks. The smaller we make the learning rate, the longer the memory span over which the LMS algorithm remembers past data will be. (Section 3.5(page 103) of Simon Hykin's Neural Network and Learning Machines:)I don't understand why this is the case. Could someone explain? | Learning rate and memory of Least Mean Square algorithm | neural network;algorithms | null |
_unix.208761 | I'm trying to automate some tests on my RaspberryPi and I'm using python's pymouse to perform some emulated clicks. On my Debian it works fine, but when it comes to Raspbian it keeps failing with this error message when trying to import pymouse:pi@pi ~/ $ python test.pyTraceback (most recent call last): File test.py, line 2, in <module> from pymouse import PyMouse File /usr/local/lib/python2.7/dist-packages/pymouse/__init__.py, line 95, in <module> from unix import PyMouse, PyMouseEvent File /usr/local/lib/python2.7/dist-packages/pymouse/unix.py, line 53, in <module> class PyMouseEvent(PyMouseEventMeta): File /usr/local/lib/python2.7/dist-packages/pymouse/unix.py, line 54, in PyMouseEvent ctx = display2.record_create_context( File /usr/lib/pymodules/python2.7/Xlib/display.py, line 216, in __getattr__ raise AttributeError(attr)AttributeError: record_create_contextSo I did some research and found, that my issue might be caused by the missing record module in my x11 installation. I already created a default /etc/X11/xorg.conf and added the following lines:Section Module Load recordEndSectionAfter a restart I could not find any difference. I guess, the module is not installed so far in Raspbian? How can I install it?Update:I found someone else, who encountered a similar problem on fedora and he documented the fact, that his /usr/lib/xorg/modules/extensions/librecord.so was missing. This does not seem to be my problem, as the file is existant.I also tried to use Xorg -configure to create a new xorg.conf and restarted my Pi afterwards. Still no luck. :-(Here are some more information that might be helpful:pi@pi ~/ $ grep LoadModule /var/log/Xorg.0.log[169058.900] (II) LoadModule: fbturbo[169058.912] (II) LoadModule: fbdevAnd:pi@pi ~/ $ xdpyinfo name of display: :0.0 version number: 11.0 vendor string: AT&T Laboratories Cambridge vendor release number: 3332 [...] number of extensions: 7 BIG-REQUESTS MIT-SHM MIT-SUNDRY-NONSTANDARD SHAPE SYNC XC-MISC XTEST [...]This post was migrated from RaspberryPi.stackexchange.com. | How do I activate Xorg record module on Raspbian? | x11;xorg;python | null |
_reverseengineering.6896 | Can someone recommend any tutoial or books on how to analyze unknown network protocol. Basically given the dumps of network traffic, I need some guide/examples on reversing the protocol. | Books/tutorial on reversing protocol | protocol | The Malware Analysis Tutorial 1 on Dr Fu's Security Blog involves running a piece of malware inside a Windows VM and capturing its network traffic using wireshark in a Linux VM set up for the purpose. Among other things. That should cover the 'acquisition' part of your project nicely in case plain wireshark on its own should not be enough...As regards Ethereal/Wireshark as such, there's a series of tuts on Wikiversity and Google turns up a gazillion more.As regards the analysis portion I found these quite interesting:An Overview Of Protocol Reverse-EngineeringReverse Engineering Communication Protocols (netzob)Reverse Engineering of Protocols from Network Traces |
_unix.120704 | I have downloaded g2ipmsg from http://www.ipmsg.org/archive/g2ipmsg-0.9.6.tar.gzWhile installing this package, it is causing some error. checking for G2IPMSG... configure: error: Package requirements (libgnomeui-2.0 >= 2.14 gtk+-2.0 >= 2.4 glib-2.0 >= 2.8) were not met: No package 'libgnomeui-2.0' found Consider adjusting the PKG_CONFIG_PATH environment variable if you installed software in a non-standard prefix. Alternatively, you may set the environment variables G2IPMSG_CFLAGS and G2IPMSG_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details.How to resolve this error please let me know. | Installation causing error | centos;ip;wlan;messaging | Ensure that you have the package libgnomeui-2.0 mentionned into the error message correctly installed. Depending of your distribution, use apt-get or yum to install it.You may also need to install gtk+-2.0 and glib-2.0 (install first package and check the updated error message if any). |
_unix.381172 | I am trying to run a for loop which looks something like thiscat all_data | awk '{print $1 $2 $3}' | while read inst type serial ; do echo $inst if [ `echo ${inst} | cut -d '-' -f2` = H3 ]; then ssh -t username@hostname3 sudo ls elif [ `echo ${inst} | cut -d '-' -f2` = H2 ] ; then ssh -t username@hostname2 sudo ls elif [ `echo ${inst} | cut -d '-' -f2` = H1 ]; then ssh -t username@hostname1 sudo ls fi doneI am not able to run the ssh -t part,it says psuedo terminal will not be allocated becasued stdin is not a terminalsudo: no tty present and no askpass program specifiedI have tried with -t -t and -n, no luck.I cant edit the visudo file from the host i am running this command from.Edit$ cat all_dataABC-DIF2 DELL-800 60999ABC-DIF3 HP-DL340 J0777ABC-DIF4 DELL-800 P0087...The all_data contains 1000's of the similar entries.What i am trying to do it as follows.60999,J0777... are the entities on which i need to run commands on.So i am trying to read each line, split up and check what is the DIF number corresponding to the entity.eg If i read DIF2, it means that i need to ssh into hostname2 and run the command to get data on the 60999If if i read DIF3, it means for the entity J0777 can only be run from hostname3. | cannot remote command with ssh over for loop | ssh | null |
_webmaster.44698 | In June 2012 I added my website (a blog that I host on my own server) to Google-Analytics. In January 2013 I decided to use Piwik instead of Google-Analytics.So I removed my website from the Google Webmaster Tools page.I also removed the Google's script from the footer of my webpages.I checked several times that there are no links to any Google Tools (Google Fonts, Google Analytics) in my code.However Ghostery (Add-on for Firefox) shows that Google-Analytics still tracks my website. I checked the following pages on Google:The page www.google.com/dashboard/?pli=1 (Dashboard) lists my website (logically it shouldn't as I removed my website from it) but when I click on Manage my sites the page www.google.com/webmasters/tools/home?hl=en&authuser=0 (Webmaster Tools - Home) my website is not listed any more and there is only a form to add a new site.The page www.google.com/analytics/ invites me to sign up and then doesn't list any website and shows a form to add a website.Do you have any idea about what I should do to stop Google-Analytics to track my website for good?Thanks for your help.ps) this is my first message on Stack Exchange, I hope my English is not too bad.Thanks you all for making this big community exist. Keep up the good work.Update:Could the meta <meta name=google content=notranslate /> in my code be the reason of the tracking?Answer: no, it's not related. | Problem to stop Google-Analytics from tracking my website | google analytics | There is no Google analytics on your own site anymore, however your site iFrames content from vimeo.com, which contains google analytics tracking. <iframe src=http://player.vimeo.com/video/ webkitallowfullscreen= allowfullscreen= frameborder=0 height=315 width=560></iframe>This site has GA tracking, and your plugin is detecting the tracking from that site. So your site itself won't be tracked in Google analytics*, if you absolutely want to stop any reference to analytics from your site remove the iFrame'ed content.*The only exception being users who have a old copy of your page in their webbrowsers cache which still contains GA, this will still send a ping to the Google servers but as you disabled your site their it won't be tracked. |
_unix.216021 | I have a bash script set up on computer A (Mac OS X) set to run every five minutes via a cronjob. This script checks for new files on remote computer B (Gentoo Linux) then rsyncs any new files to computer A. Sometimes this sync (download) maxes out my connection at 3 MB/s, however sometimes, maybe 10% of the time, it will download at the extremely low rate of 10-50 KB/s. I'm 100% certain this isn't because my Internet connection is dying out/dipping so what could be at fault?The weird thing is that the rsync jobs that run slow, run slow the ~entire~ time. That is if it is rsyncing a 1 GB file it will sync/download at its extremely slow speed (10-50 KB/s) the entire life of the job until the 1 GB is fully downloaded. This leads me to believe it is not related to CPU load, or networking, but with either the script or something else.My script is below.# !/bin/sh# Check if rsync has been timestampped and exit if it hasecho Checking for local timestamp... >> /Users/localuser/log/rsync.logif [ -e /Users/localuser/scripts/.timestamp ]then echo Local timestamp already exists, exiting... >> /Users/localuser/log/rsync.log exitfi# Timestamp rsyncecho Local timestamp not found, continuing... >> /Users/localuser/log/rsync.logtouch /Users/localuser/scripts/.timestamp# Timestamp remote computer Becho Timestampping remote computer B >> /Users/localuser/log/rsync.logssh remoteuser@remotecomputerb touch /home/remoteuser/finished/.timestamp# Run rsyncecho Starting rsync at $(date) >> /Users/localuser/log/rsync.logrsync -avzPL -e ssh remoteuser@remotecomputerb:/home/remoteuser/finished /share --log-file /Users/localuser/log/rsync.log# Change permissionsecho Changing permissions >> /Users/localuser/log/rsync.logchmod -Rf 775 /share/usr/sbin/chown -Rf localuser:staff /share# Delete sym links that are older than the remote computer B timestampecho Deleting sym links on remote computer B >> /Users/localuser/log/rsync.logssh remoteuser@remotecomputerb find /home/remoteuser/finished \! -newer /home/remoteuser/finished/.timestamp -type -l -delete# Delete the rsync script timestampecho rsync finished at $(date) >> /Users/localuser/log/rsync.logrm /Users/localuser/scripts/.timestampexit 0 | rsync over SSH sometimes very slow--other times maxes out bandwidth | bash;ssh;osx;rsync;backup | That could be basically anything from link congestion to high CPU usage on the remote computer. In between, all the network devices can also screw up. Especially since you are bombing the ssh port. But buffering problems in the network devices can also be the culprits. One thing though: next time, double check that rsync is not running twice. Yes, you created workarounds in the script to avoid that, but one never knows... maybe the folder is read-only, maybe the filesystem behaves strangely...So, you understand it, we don't have enough information to answer correctly.However, I would recommend you to stop using rsync for this use case. This is inefficient as well as error prone. Since what you want is folder constant sync, have a look at syncthings. It should work better, without lag with the same amount of openness and security. (rsync is great for one-shots and for periodic backups, not for constantly syncing folders) |
_unix.187304 | A CentOS 7 web server has postfix, dovecot, and mailx installed. I have been able to make an IMAP connection to the server in order to read inbox mail using a remote Thunderbird client, but I am not able to make an SMTP connection to send email from Thunderbird. When I do forensics, I discover that the attempted SMTP connection times out. How can I resolve this problem of the connection timing out, so that I can send email from Thunderbird through the server? My forensics so far have resulted in: Typing hostname in the terminal at the server returns mydomain.com.nano /usr/lib/firewalld/services/smtp.xml indicates the smtp port is 25The smtp service is activated in the public zone because firewall-cmd --list-all results in: public (default, active) interfaces: enp3s0 sources: services: dhcpv6-client imaps openvpn smtp ports: masquerade: yes forward-ports: icmp-blocks: rich rules: But when I try to telnet from my devbox to the remote CentOS 7 server, I get the following results. Typing telnet mydomain.com 25 resulted in: Trying my.SERVER.ip.addr...telnet: connect to address my.SERVER.ip.addr: Connection timed outThen typing telnet smtp.mydomain.com 25 resulted in: Trying my.SERVER.ip.addr...telnet: connect to address my.SERVER.ip.addr: Connection timed outAlso, typing openssl s_client -CApath /etc/ssl/certs -starttls smtp -port 25 -host smtp.mydomain.com results in: socket: Connection timed outconnect:errno=110Similarly, typing openssl s_client -CApath /etc/ssl/certs -starttls smtp -port 25 -host mydomain.com also resulted in: socket: Connection timed outconnect:errno=110I typed nano /etc/postfix/main.cf to start to examine the config, but did not find anything related to ports. EDIT: As per FaheemMitha's advice, I tried telnet mydomain.com 587 from the client, and got No route to host in reply. I think this is because only port 25 is open in firewalld for smtp. I therefore thought to try telnet from within the remote server mydomain.com. When I logged on to my remote server via ssh and typed telnet localhost 25, the result was: Trying 127.0.0.1...Connected to localhost.Escape character is '^]'.220 mydomain.com ESMTP Postfix This causes me to suspect that postfix is running on port 25, but that somehow it is not able to accept outside connections. EDIT#2 As per @RedCricket's suggestion, I ran iptables -L. Since the results were verbose, I uploaded them to a file sharing site, which you can view by clicking on this link. I also tried iptables --flush followed by firewall-cmd --reload, and then repeated the telnet and thunderbird tests from above, but I am still getting the connection timed out error.What else can I try? I uploaded the entire /etc/postfix/main.cf to a file sharing site. You can read it by clicking on this link. EDIT#3 A valid email address someone.else@some_other_domain.com sends email to [email protected] without problems. Therefore, as a test, I had my remote Thunderbird client try to send email to that someone.else@some_other_domain.com as part of the work documented above in this OP. This morning, I received a return to sender message in my Thunderbird as a result of the test email. I interpret this returned message to mean that at least one of my test messages from Thunderbird got into the SMTP on mydomain.com, but that mydomain.com was not able to look up or otherwise connect to some_other_domain.com. Here is the message: This is the mail system at host mydomain.com.I'm sorry to have to someone.elserm you that your message could notbe delivered to one or more recipients. It's attached below.For further assistance, please send mail to postmaster.If you do so, please include this problem report. You candelete your own text from the attached returned message.The mail system<someone.else@some_other_domain.com>: Host or domain name not found. Name service error for name=some_other_domain.com type=MX: Host not found, try againReporting-MTA: dns; mydomain.comX-Postfix-Queue-ID: 2C915811BD1CX-Postfix-Sender: rfc822; [email protected]: Mon, 23 Feb 2015 16:46:34 -0500 (EST)Final-Recipient: rfc822; someone.else@some_other_domain.comAction: failedStatus: 4.4.3Diagnostic-Code: X-Postfix; Host or domain name not found. Name service error for name=some_other_domain.com type=MX: Host not found, try againForwardedMessage.emlSubject: key enclosedFrom: [email protected]: 02/23/2015 01:46 PMTo: someone.else@some_other_domain.comthis is the body of the email Thus, it seems that sometimes the connection from my remote devbox to mydomain.com is closed, and at other times, the connection from mydomain.com to the rest of the internet is closed. EDIT#4 Following @derobert's advice, I first tried the two telnet commands from the devbox to the server, then I tried to send an email from [email protected] using the Thunderbird client on my devbox, and then I ran the tcpdump command on both the devbox and on the server. Typing tcpdump port 25 in the devbox terminal resulted in the following: tcpdump: verbose output suppressed, use -v or -vv for full protocol decodelistening on tun0, link-type RAW (Raw IP), capture size 65535 bytes ^C 0 packets captured 0 packets received by filter 0 packets dropped by kernelNext, typing tcpdump on the server resulted in so much output that the results scrolled endlessly until I typed Ctrl-C. So I then typed tcpdump port 25 and got the following results: tcpdump: verbose output suppressed, use -v or -vv for full protocol decodelistening on tun0, link-type RAW (Raw IP), capture size 65535 bytes^C0 packets captured0 packets received by filter0 packets dropped by kernelAs a curiosity, I then typed tcpdump port 25 again on both the devbox and the server simultaneously and left it open without typing Ctrl-C, and I tried to manually send an email from [email protected] using Thunderbird client on my devbox. I still got the same Connection timeout failure, but there was no activity reported by the open tcpdump port 25 commands. And the totals also came up to zero when I typed Ctrl-C on both terminals afterwards. | postfix smtp connection timed out, why? | centos;email;postfix;openssl;ssl | After much troubleshooting, we determined that the ISP on the client side is blocking outgoing port 25 (SMTP). That was confirmed by using a random mail server test site on the Internet and finding that it could connect to the mail server fine. SMTP packets from the client machine did not arrive at all (confirmed via tcpdump).Solution is to reconfigure SMTP listener on a different port. 465 (SMTP over SSL) and 587 (mail submission, RFC6409) are common options. |
_codereview.146877 | This C++ Boggle board solver is intended to take in many boards one after another and score them. I would like comments on code style, whether there are C++ standard library features that I could use to streamline the code, appropriate division between public and private, etc.Download codeDownload dictionary fileBoggleBoggle is a board game with a 4x4 board of squares, each of which has a letter, in which you score points by finding words on the board. This is an example Boggle board:c a t ca t c at c a tc a t cThis board contains the words 'cat', 'act', 'tact', etc. The words must be made up of neighboring squares (left, right, up, down, and diagonal), and you can't use the same square twice in a word. Words don't need to be in a straight line.CodeBoggle classThe Boggle class stores the board. board stores the letters in a vector of structs, each of which stores a letter, the row and column, and a vector of indices for neighboring squares.Load loads a string into the board. Print prints the board. Score finds all words on the board and calculates how much they're worth.Words (private member function) finds all words starting at a given square on the board....#include <map>#include <string>#include <unordered_set>#include <vector>// Map word lengths to pointsstd::map<int, int> POINTS = {{3, 1}, {5, 2}, {6, 3}, {7, 5}, {8, 11}};// Boggle board classclass Boggle {private: struct square { std::string value; int row; int col; std::vector<int> neighbors; square(int row, int col); }; int size; std::vector<square> board; Dictionary dict; std::map<int, int> points; std::unordered_set<std::string> found_words; void Words(int position, std::string str = , std::unordered_set<int> visited = std::unordered_set<int>());public: Boggle(Dictionary dict, int size = 4, std::map<int, int> points = POINTS); ~Boggle(); void Load(std::string letters); void Print(); int Score();};// Boggle board constructorBoggle::Boggle(Dictionary dict, int size, std::map<int, int> points) { this->dict = dict; this->size = size; this->points = points; int row, col; // Add squares to the board for (int i = 0; i < size * size; i++) { row = i / size; col = i % size; board.push_back(square(row, col)); } // Add each square's neighbors std::vector<int> shift {-1, 0, 1}; for (square &sq : board) { for (int row_shift : shift) { for (int col_shift : shift) { row = sq.row + row_shift; col = sq.col + col_shift; if (row >= 0 & row < size & col >= 0 & col < size & !(row_shift == 0 & col_shift == 0)) { sq.neighbors.push_back(row * size + col); } } } }}Boggle::~Boggle() {}// Boggle square constructorBoggle::square::square(int row, int col) { this->row = row; this->col = col;}// Load a string of letters into the boardvoid Boggle::Load(std::string letters) { int i = 0; for (square &it : board) { it.value = letters[i]; i += 1; } // Clear any previously found words found_words.clear();}// Print the boardvoid Boggle::Print() { for (const square &sq : board) { std::cout << sq.value << ; if (sq.col == size - 1) { std::cout << std::endl; } }}// Find all words, then calculate the scoreint Boggle::Score() { int score = 0; // Find words for all squares on the board for (int i = 0; i < board.size(); i++) { Words(i); } // For each word, look up points and add to the score std::map<int, int>::iterator point; for (const std::string &word : found_words) { // Find the smallest point map key greater than word length, then move back one step // to get the largest key less than or equal to word length, e.g. 4->5->3 point = points.upper_bound(word.length()); --point; score += point->second; } return score;}// Find all words starting at a given positionvoid Boggle::Words(int position, std::string string, std::unordered_set<int> visited) { square &sq = board[position]; string = string + sq.value; visited.insert(position); // If the string is a word, add it to the found words if (dict.words.find(string) != dict.words.end()) { found_words.insert(string); } // If the string is a prefix, continue looking if (dict.prefixes.find(string) != dict.prefixes.end()) { for (const int &neighbor : sq.neighbors) { if (visited.find(neighbor) == visited.end()) { Words(neighbor, string, visited); } } }}Dictionary classThe Dictionary class reads in and stores the dictionary of words and word prefixes. The class constructor takes a path to the dictionary file. A Boggle object needs a Dictionary when the Boggle object is created....#include <fstream>#include <iostream>#include <unordered_set>class Dictionary {public: Dictionary(); Dictionary(std::string, int word_length = 3); ~Dictionary(); std::unordered_set<std::string> words; std::unordered_set<std::string> prefixes;};Dictionary::Dictionary() {};// Load the word dictionary and prefixes dictionary from a given fileDictionary::Dictionary(std::string path, int word_length) { std::string line; std::ifstream file(path); if (file.is_open()) { while (std::getline(file, line)) { if (line.length() >= word_length) { // Add to word dictionary this->words.insert(line); // Add to prefixes dictionary for (int i = 1; i < line.length(); i++) { this->prefixes.insert(line.substr(0, i)); } } } } file.close();}Dictionary::~Dictionary() {};Example programint main() { Dictionary dict(twl06.txt); Boggle b(dict); b.Load(serspatglinesers); b.Print(); std::cout << b.Score() << std::endl;}Output:s e r sp a t gl i n es e r s3692Thank you! | Boggle board solver in C++ | c++;beginner;game | About the constructor of BoggleFrom a stylistic point of view, instead of assigning member fields inside the constructor in java style, the C++ way is rather to use an initializer list.That is to say, instead of:Boggle::Boggle(Dictionary dict, int size, std::map<int, int> points) { this->dict = dict; this->size = size; this->points = points;You can write:Boggle::Boggle(Dictionary dict, int size, std::map<int, int> points): dict(dict), size(size), points(point){One big advantage of using an initializer list over assignments inside the constructor's body, is that you can now declare these variables as const, or even use a reference instead, which avoids the copy. Using references will save a lot of work, but you have to make sure that the referred-to object is not deleted before the end of the Boggle instance.PerformanceYour code is likely to be much slower than it could be. One source of slowness is the std::unordered_set<int> visited. Each call to the recursive Word function makes a copy of the set. There are two ideas that could improve this a lot.The first idea is to use a reference instead of a copy. That is to say, use std::unordered_set<int> &visited. With a reference, you also have to make sure that the set is restored to its initial state before quitting the function: add visited.erase(position); before returning.Another more important idea is that, instead of using a std::set, you could simply use an array of flags that indicate, for each possible position, whether it was visited or not. insert and erase operations on such a representation of a set will be considerably more efficient: it simply consists in setting an array element to true or false.Yet another performance idea: using a prefix-tree data structure might be a lot faster: https://en.wikipedia.org/wiki/Trie . But there is not such container in standard C++. |
_webmaster.79880 | Domestic SEO was much easier than expected. How does that impact international strategy?I accomplished what I thought is impossible for five pages on my site. We achieved page 1 and 2 ranks after launching a few months ago without creating any external links or social signals. One page's keywords has medium competition, but that page is getting a little link juice forwarded from it's previous domain. That site was not as well focused or well built for SEO, and never made it to page 2. The other four pages have low to low-medium competition and do not benefit from any legacy link juice.The keywords for each of the pages target a different but similar niche product made by well-kown major multi-national corporations. We sell a generic replacement for those niche products. Each of the products has true global consumer demand.Since launch the site has been tweaked to improve internal SEO and to enhance the ability to market internationally in preparation for an external SEO campaign. I was about to hire an SEO firm for link building, but now before doing so, I am rethinking my stratgey and hope to get some advice especially since this is my first foray into international SEO.For SEO on the default pages I still plan on a little link building, but substantially less. It seems like it will be relatively easy to achieve top 5 with each of the products. (Actually, one is already there.) Does that make sense? What about long-term SEO maintenance? Do you think it's worth much of an effort?We're using hreflang tags with xml site maps for the international URLs. The site maps for the first four new countries were just submitted to Google yesterday. The XML looks something like this:<url> <loc>http://www.example.com/en-us/product1</loc> <xhtml:link href=http://www.example.com/en-us/product1 hreflang=x-default rel=alternate /> <xhtml:link href=http://www.example.com/en-in/product1 hreflang=en-in rel=alternate /> <xhtml:link href=http://www.example.com/en-au/product1 hreflang=en-au rel=alternate /></url>For now, we are only targeting English speaking countries so the only substantive differences on the pages is the currency of the prices. We're using a CDN to ensure fast page loads from a close-by IP address. In each of these countries, the competition for the keywords is not as strong as the US. Do you think that we're likely to achieve similar organic SEO results by doing nothing? Do you think link-building will accelerate the ranking? | Domestic SEO was much easier than expected. How does that impact international strategy? | seo | null |
_codereview.52398 | I'm writing a bash script that has these goals: to build a node program from sourcesto install the built program on Ubuntu Linuxto allow the user to rebuilt from most recent sourcesto add a small CLI (it has none)to add a small GUI for support (like report-bug,fix common errors, etc.)So, it's pretty complete in my opinion, and the good thing is, it works well. But what concerns me is that the code seems chaotic and not optimized, even if it's entirely fine from a user's point-of-view.Here's the code's resume:#Part1 : VARIABLES11 variables I use for URLs, version number, log-files, etc.#Part 2 : FUNCTIONS9 functions.- 4 of them are quite simple and regular ones, for example error checking and exit if the user is root- 1 of them contains almost only text to write inside text-files- 4 of them call other function#part 3 : SCRIPT- a 'case' to watch options like -update- the list of 7 functions that I need to run everytime with or without the susmentionned 'options'Total = 409 lines (~150 without all the simple text to write somewhere or to display)Here's the full code. You can also watch what it does for the user on YouTube:#!/bin/bashinstalldir=/optversion=dev-0.3OfficialURL=http://get-popcorn.comgithubURL=https://github.com/popcorn-official/popcorn-appissueURL=https://github.com/popcorn-official/popcorn-app/issuesicon=https://github.com/popcorn-official/popcorn-app/raw/master/src/app/images/icon.pnglog=$HOME/popcorn-build.logbuildscriptURL=https://raw.githubusercontent.com/MrVaykadji/misc/master/Popcorn-Time/0.3.0/buildscript=build-popcorn[ $(arch) == x86_64 ] && arch=64 || arch=32buildtime=`date +%Y.%m.%d-%Hh%M`#FUNCTIONSfunc_apt() {for lock in synaptic update-manager software-center apt-get dpkg aptitudedo if ps -U root -u root u | grep $lock | grep -v grep > /dev/null; then echo Unexpected Error:=================Please close $lock then try again.; exit 1 fidone }func_root() {[ $EUID == 0 ] && echo Error. You need to run this without 'root' or 'sudo' privileges. && exit 2}func_error() {[ -n $error ] && return 0echo Unexpected Error:=================cat $logecho Please try again.exit 1 }func_clean() {case $1 in -save) sudo mkdir -p /tmp/popcorn-config sudo cp -r $HOME/.config/Popcorn-Time/data /tmp/popcorn-config/ &> /dev/null sudo rm -rf $HOME/.config/Popcorn-Time/* sudo cp -r /tmp/popcorn-config/data $HOME/.config/Popcorn-Time/ &> /dev/null && sudo chown -Rf $USER:$USER $HOME/.config/Popcorn-Time/data && sudo chmod -R 774 $HOME/.config/Popcorn-Time/data ;; -all) sudo rm -rf $installdir/Popcorn-Time /usr/share/pixmaps/popcorntime.png /usr/bin/popcorn-time $HOME/tmp $HOME/popcorn-app-$version $HOME/npm-debug.log $HOME/.npm $HOME/.cache/bower $HOME/.config/configstore/insight-bower.yml $HOME/.config/configstore/update-notifier-bower.yml $HOME/.local/share/bower $log $HOME/$version.zip ;; -package) sudo apt-get purge nodejs -y &> /dev/null && sudo apt-get autoremove -y &> /dev/null && sudo rm -rf /usr/bin/node && sudo add-apt-repository -yr ppa:chris-lea/node.js &> /dev/null && echo -e ... Done.\n ;; -building) sudo rm -rf $HOME/tmp $HOME/popcorn-app-$version $HOME/npm-debug.log $HOME/.npm $HOME/.cache/bower $HOME/.config/configstore/insight-bower.yml $HOME/.config/configstore/update-notifier-bower.yml $HOME/.local/share/bower $log && echo -e ... Done.\n ;;esac}func_ptexists() {if [ $1 == -update ] ; then func_clean -saveelse [ -e $installdir/Popcorn-Time ] && read -p WARNING: Popcorn-Time is already installed in '$installdir' and will be erased. Do you want to keep the configuration files (bookmarks, watched list, settings, ...) [y/n] ? if [ $REPLY == y ] ; then func_clean -save else sudo rm -rf $HOME/.config/Popcorn-Time/ fi sudo rm -rf /usr/share/applications/popcorn-time.desktopfifunc_clean -all}func_dependencies() {[[ -n `egrep -v '^#|^ *$' /etc/apt/sources.list /etc/apt/sources.list.d/* | grep chris-lea/node.js` ]] && nodeppa=1 || nodeppa=0if [ -n `dpkg-query -W -f='${Status}\n' nodejs wget unzip | grep not` ] || [ $nodeppa == 0 ] ; thenecho - Checking for dependencies 'nodejs', 'wget' and 'unzip'...sudo apt-add-repository -y ppa:chris-lea/node.js &> $log &&sudo apt-get update &> $log &&sudo apt-get install nodejs wget unzip -y &> $log && echo -e ...Ok ! || error=1func_errorfi#npm depif [ -e /usr/lib/node_modules/bower ] && [ -e /usr/lib/node_modules/grunt-cli ] ; then echo -e \n- Updating NPM 'grunt-cli' and 'bower'...else echo -e \n- Installing NPM 'grunt-cli' and 'bower'...fisudo npm install -g grunt-cli bower &> $log && echo -e ...Ok !\n || error=1func_error#repair broken nodejs symlink[ ! -e /usr/bin/node ] && sudo ln -s /usr/bin/nodejs /usr/bin/node #symlink libudev.so on 12.04[ `lsb_release -cs` == precise ] && [ ! -e /lib/$(arch)-linux-gnu/libudev.so.1 ] && sudo ln -s /lib/$(arch)-linux-gnu/libudev.so.0 /lib/$(arch)-linux-gnu/libudev.so.1 }func_build() {#get sourcesecho - Downloading '$version' sources from GitHub...cdwget $githubURL/archive/$version.zip -O $version.zip &> $log && unzip -o $version.zip &> $log && rm $version.zip && echo -e ...Ok !\n || error=1func_error#npmcd popcorn-app-$versionecho - Running 'npm install'...sudo chown -Rf $USER:$USER $HOME/popcorn-app-$version/ $HOME/tmpnpm install --yes &> $log && echo -e ...Ok !\n || error=1func_error#buildif [ $1 == -update ] ; then buildcommand=linux$archelse buildvar=0 echo -e You can build for this machine only (linux$arch) or for all plateforms, including : Mac, Windows, Linux 32-bits, Linux 64-bits.\n\nFor what platforms do you wish to build (for multiple builds, separate each platform with a comma) read -p [mac/win/linux32/linux64/all] : input IFS=',' read -a options <<< $input shopt -s extglob for option in ${options[@]}; do case $option in win|mac|linux32|linux64|all) buildcommand=${buildcommand:+$buildcommand,}$option buildvar=1;; *) printf 'Invalid option %s ignored.\n' $option;; esac done if (( !buildvar )); then echo Incorrect input. Default build 'linux$arch' selected. buildcommand=linux$arch fi [[ -n `echo $buildcommand | grep all` ]] && buildcommand=allfiecho -e \n- Building with 'grunt'...grunt build --platforms=$buildcommand &> $log && echo -e ...Ok !\n || error=1func_errorecho -e Popcorn-Time has been built in :\n $HOME/popcorn-app-$version/build/releases/Popcorn-Time/\n }func_install() {[ `echo $buildcommand | grep -v linux$arch` ] && exit 0if [ $1 != -update ] ; thenread -p Do you wish to install Popcorn-Time on this computer [y/n] ? [ $REPLY != y ] && exit 0fi sudo mkdir -p $installdirsudo cp -r $HOME/popcorn-app-$version/build/releases/Popcorn-Time/linux$arch/Popcorn-Time $installdirecho -e \n- Creating commandline launcher...echo #!/bin/bashecho \Popcorn Time============\[ \\$EUID\ == \0\ ] && echo \Error: You need to run this without 'root' or 'sudo' privileges.\ && exit 2helpsection() {echo \Version $version Built on $buildtime from $githubURLOfficial website : $OfficialURLOptions: -h, --help Display this help. -q,--quiet Launch Popcorn-Time without output. --flush Flush databases. --fix-node Fix the node-webkit 'blank' error. --uninstall Uninstall Popcorn-Time. --issue Report an issue. --build Build latest version from sources.\}flush_all() {echo \- Flushing databases...\sudo rm -rf $HOME/.config/Popcorn-Time}uninstall() {echo \- Uninstalling Popcorn-Time and removing configuration files...\sudo bash $installdir/Popcorn-Time/uninstall.sh}popcorntimequiet() {echo \Starting...\nohup $installdir/Popcorn-Time/Popcorn-Time &> /dev/null &exit 0}popcorntime() {$installdir/Popcorn-Time/Popcorn-Time}reportissue() {echo \Here is what a great bug report looks like:###############################Describe the problem hereVersion: $version for Linux $arch bits Built on $buildtimeDownloaded from: $githubURLOS: `lsb_release -si` `lsb_release -sr` `arch`Connection: X mbpsHow to reproduce: - Step 1 - Step 2 - Step 3Actual result: - X goes wrongExpected result: - X should go like that###############################\xdg-open $issueURL &> /dev/null}fix_node() {echo \Fixing node-webkit...\rm -rf $HOME/.config/node-webkit}build_pt() {cdecho \Building script fetched from GitHub...\wget -q $buildscriptURL$buildscriptbash $buildscript -update}case \$1 in -h|--help) helpsection ;; --uninstall) uninstall ;; --flush) flush_all ;; --fix-node) fix_node ;; --issue) reportissue ;; -q|--quiet) popcorntimequiet ;; --build) build_pt ;; *) popcorntime ;;esac | sudo tee /usr/bin/popcorn-time &> /dev/nullsudo chmod +x /usr/bin/popcorn-timeecho -e /usr/bin/popcorn-time\necho - Creating launcher... sudo wget $icon -qO /tmp/popcorntime.png && sudo cp /tmp/popcorntime.png /usr/share/pixmaps/echo [Desktop Entry]Comment=Watch movies in streaming with P2P.Comment[fr]=Regarder des films en streaming.Name=Popcorn TimeExec=/usr/bin/popcorn-timeStartupNotify=falseType=ApplicationIcon=popcorntimeActions=ForceClose;ReportIssue;FlushDB;FixNode;BuildUpdate;Keywords=P2P;streaming;movies;tv;series;shows;Keywords[fr]=P2P;streaming;films;sries;tlvision;tv;[Desktop Action ForceClose]Name=Force closeName[fr]=Forcer la fermetureExec=killall Popcorn-TimeOnlyShowIn=Unity;[Desktop Action ReportIssue]Name=Report IssueName[fr]=Rapporter un problmeExec=sh -c \popcorn-time --issue\OnlyShowIn=Unity;[Desktop Action FlushDB]Name=Flush databasesName[fr]=Vider les bases de donnesExec=sh -c \killall Popcorn-Time ; rm -rf $HOME/.config/Popcorn-Time ; /usr/bin/popcorn-time\OnlyShowIn=Unity;[Desktop Action FixNode]Name=Fix Node-WebkitName[fr]=Rparer Node-WebkitExec=sh -c \rm -rf $HOME/.config/node-webkit ; killall Popcorn-Time ; /usr/bin/popcorn-time\OnlyShowIn=Unity;[Desktop Action BuildUpdate]Name=Build latest versionName[fr]=Construire la dernire versionExec=sh -c 'killall Popcorn-Time ; xterm -fa monaco -fs 13 -bg black -fg white -title \Build latest Popcorn Time\ -e \popcorn-time --build\ ; /usr/bin/popcorn-time'OnlyShowIn=Unity; | sudo tee /usr/share/applications/popcorn-time.desktop &> /dev/nullsudo chmod +x /usr/share/applications/popcorn-time.desktopecho -e /usr/share/applications/popcorn-time.desktop\necho - Creating uninstall script...echo #!/bin/bash#uninstallation script for Popcorn-Time#clean directorysudo rm -rf $installdir/Popcorn-Time#clean configsudo rm -rf $HOME/.config/Popcorn-Time#clean iconsudo rm -rf /usr/share/pixmaps/popcorntime.png#clean launcherssudo rm -rf /usr/bin/popcorn-timesudo rm -rf /usr/share/applications/popcorn-time.desktop | sudo tee $installdir/Popcorn-Time/uninstall.sh &> /dev/nullsudo chmod +x $installdir/Popcorn-Time/uninstall.shecho -e $installdir/Popcorn-Time/uninstall.sh\n }func_end() {if [ $buildcommand == linux$arch ] ; then if [ $1 == -update ] ; then func_clean -building sudo rm -rf $0 else read -p Do you wish to remove all the building files [y/n] ? [ $REPLY == y ] && func_clean -building fifiif [ $nodeppa == 0 ] ; then read -p Do you wish to uninstall the packages installed for this build, they will be needed in case of new build [y/n] ? [ $REPLY == y ] && func_clean -packagefi }#SCRIPT#func_rootfunc_aptecho Popcorn-Time $version for Ubuntu-Linux=====================================Popcorn Time streams movies from Torrents.Downloading copyrighted material may be illegal in your country.!!! Use at your own risk !!!sudo test case $1 in -update) option=-update ;; *) [ -n $1 ] && echo -e \nUnauthorized option '$1' will be ignored. ;;esacfunc_ptexists $optionfunc_dependenciesfunc_build $optionfunc_install $optionfunc_end $optionecho =================================================Popcorn-Time is now installed !Type popcorn-time --help for more information.exit 0My questions concern some techniques that I use: I call functions from within other functions. Can I do that? Is 150 lines too long (without text to display and commentaries) for this kind of code?Should I split the code if I can? Leaving, for example, one script for the build that will download the installation script and the needed text-files, and another that will only be downloaded when the user wants to rebuild, ... these kinds of things.I would be grateful if you could skim through the code and give me an honest opinion about its globality. | Building/installing bash script | bash;installer | Working with the ecosystemIt important to know when not to write code. If you're going to work in the APT ecosystem, then you should work with other package management tools, rather than invent your own approach. There are at least two tools you should be leveraging:git-buildpackage is a suite of commands to create Debian packages based on Git repositories.grunt-debian-package is a command to create a Debian package from a grunt build.Consider the advantages of working with the ecosystem:Less code for you to maintain.The installation process works the way users expect it to. I, for one, don't like to run strangers' scripts as root, as I have no idea how they might be trashing my system. (And in my opinion, you are trashing my system, as I will discuss below.)Users get the benefits of package management, such as clean uninstallation and upgrades, dependency and conflict checking, standard filesystem paths, etc.You'll eventually need to package the product properly for release anyway, so you might as well start now.Maybe you think it's OK for Popcorn Time to do its own thing. But if every application did the same, it would be chaos.Building vs. installingYour script commingles the build and installation steps. I'd like to see them separated:The build process fetches the code from the Internet and generates installable packages. This step should be done without root privileges, as it runs a lot of complex programs, such as compilers.The installation process, in contrast, usually does require root privileges. It should therefore be restricted to simple, trustworthy tasks, namely unpacking the previously generated packages and maybe running some pre- and post-install scripts. I'd like to have the opportunity to inspect the packages and the pre-/post-install scripts before performing the installation.There should only be approximately one invocation of sudo that encompasses all of the installation process. After all, you shouldn't assume that /etc/sudoers contains a conveniently permissive entry for the user.Respecting the user's machineIt appears that the application installs primarily to /opt/Popcorn-Time, which is good (for an application that is not managed as a .deb package). Anything that you install outside of /opt/Popcorn-Time would be unexpected, and should deserve special mention, perhaps even confirmation, and ideally avoided altogether.You also write to/etc/apt/sources.list.d$HOME/.config/Popcorn-Time/usr/bin/node/lib/$(arch)-linux-gnu/libudev.so.1/usr/bin/popcorn-time/usr/share/pixmaps/popcorntime.png/usr/share/applications/popcorn-time.desktopYou do provide an uninstall script to clean up after the last three, but I would still consider it littering. The FHS requires non-package-managed files to go in /usr/local, I believe.In particular, the creation of symlinks /usr/bin/node /usr/bin/nodejs and /lib/$(arch)-linux-gnu/libudev.so.1 /lib/$(arch)-linux-gnu/libudev.so.0 is precisely the kind of secret shenanigans I fear most when running untrustworthy scripts as root. I expect every file in system directories such as /usr/bin and /lib to be either part of an installed Debian package or be managed by a post-install / pre-remove script of an installed Debian package in other words, fully managed by the package management system. Furthermore, an increment in the major version of a shared library indicates an API incompatibility. Library versioning is the Unix solution to DLL Hell, and by creating a symlink that spans major version numbers, you have trashed my system without so much as a courtesy notice! An executable that is properly built for the target OS should never need such a hack.Distinction between normal users and rootIs this meant to be a machine-wide installer? If so, then it has no business trying to manage per-user directories such as $HOME/.config/Popcorn-Time. Keep in mind that in a multi-user system, each user who has ever run the application could have his/her own $HOME/.config/Popcorn-Time directory. There's nothing special about the user who is running the uninstaller.Answers to your questionsCalling functions from other functions is perfectly fine. In fact, a defined function can be thought of as just another command (like ls or date) except that it's only available within your script.My concern is not the line count, but that you try to do too much.The script implements a build/installation process that doesn't play well with Ubuntu tools. You would be writing less code and making your users happier if you leveraged the appropriate tools for solving this kind of problem.Ideally, parts of the script, such as the popcorn-time.desktop file and the popcorn-time launch script, would be distributed in the Popcorn Time application's Git repository itself. Your build script would merely need to copy them into place, perhaps doing some string substitutions using sed.You misspelled platform. |
_unix.353615 | Gnome Shell 3.18.5 notified me some extensions needed updating. I went to: https://extensions.gnome.org/local/ in FireFox, updated the FF extension, and now I want to uninstall some of the Gnome extensions. E.g.**Removable Drive Menu by fmuellnerSystem extensionA status menu for accessing and unmounting removable devices.**System extension has a tooltip:System extension should be uninstalled using package manager. See about page for details.About page says: What is System extension? How to uninstall it? System extension is installed to system-wide location (usually /usr/share/gnome-shell/extensions). Such extension may be used by any PC user, however it can be uninstalled only by system administrator (root). To uninstall system extension use your distro's package manager or ask your system administrator. I looked through Synaptic but don't see this extension. How do I remove it?Here are the extensions I want to remove: 1 2 3 4 5Thanks in advance! | Can't uninstall Gnome Shell Extension | gnome;gnome3;gnome shell | Launch gnome-tweak-toolSearch Extensions in right menSelect the extension and click on Remove |
Subsets and Splits