id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_webmaster.87915
I've been working with the event capture in dhis2 and looks like it is far less polished than the data entry part. Right now in the data entry if you choose to use a data element of type file a button to upload the file appears there.When you use a data element of type file on event capture a text field appears instead (and looks like it expects the id of the file to be put there), but no way to upload the file first. The only way I've seen to do this is to first upload the file inside the form using the dhis api, retrieve the id and put it automatically on the field (but still quite not sure about how this could be done).I was wondering if there was an easier way or if someone faced the same problem or if there is an easier way that I missed to do this. (seems like quite a complex way to just upload a file)Thanks for your time!
DHIS2 - How to attach files in event captures?
dhis2
null
_vi.2906
Vim has some fancy pants indentation stuff. When it works right it's a pleasure to have, but sometimes it just drives me nuts. One that I've never been able to solve has to do with LaTeX syntax.Lets say you have this file:This is a test paragraph. Most of it is innocuous, but the \textit{inline markup code happens to fall over a line break} which is a problem.% vim: autoindent textwidth=79 ft=texIf you put your cursor in the first line and hit gqip to reformat the paragraph, it will format it like this:This is a test paragraph. Most of it is innocuous, but the \textit{inline markup code happens to fall over a line break} which is a problem.But what I would like is this:This is a test paragraph. Most of it is innocuous, but the \textit{inlinemarkup code happens to fall over a line break} which is a problem.Of course I still do want it to auto-indent when I hit enter on a line ending in { (or {%. I also want to follow the indent of the previous line, so if I reformat: This is a test paragraph. Most of it is innocuous, but the \textit{inline markup code happens to fall over a line break} which is a problem.I would like: This is a test paragraph. Most of it is innocuous, but the \textit{inline markup code happens to fall over a line break} which is a problem.Is there a way I can correct only the use case behavior of formatting paragraphs that have inline markup without affecting other usage scenarios?
How can I fix the auto indentation in LaTeX?
indentation;plugin atp
null
_codereview.158771
I just started watching some regex tutorials on Plural Sight just to learn how to write a proper regex expression. So far so good, it's been alright and I decided to test my knowledge on Hackerrank. Although, the tutorial explains how to use PCRE (Perl Compatible Regular Expressions) and ECMAScript engines but I'm comfortable using PCRE at the moment so hence my code is running on PHP.A brief overview of the question is:TaskYou have a test string S. Your task is to match the pattern XXxXXxXX Here, x denotes whitespace characters, and X denotes non-white space characters.NoteThis is a regex only challenge. You are not required to write code. You have to fill the regex pattern in the blank (_________).$handle = fopen (php://stdin,r);$Test_String = fgets($handle);if(preg_match($Regex_Pattern, $Test_String, $output_array)){ print (true);} else { print (false);}fclose($handle);?>I don't really know much about PHP, all I had to do was fill in the blank so I wrote 2 test cases to see how my regex was doing so far in regex 101 e.g AA AA AA, BB BB BC.$Regex_Pattern = /\S{2}\s{1}\S{2}\s{1}\S{2}/; //Do not delete '/'. Replace __________ with your regex.Final thoughts: I'm fully aware the example isn't meant to be complicated as it's meant to show how to use \S and \s. I attempted using [\S\s]+\S{2}$ but that wasn't greedy enough as it permits multiple spacing.Are there more refined ways to do this without using \S & \s and if S &\s can be used differently to achieve the same results?
Matching whitespace and non-whitespace characters with RegEx
php;programming challenge;regex
null
_unix.295245
Is there any way, in Python 3, to find out the language used by the system?Even a tricky one though, like: reading from a file in a sneaky directory, and finding the string 'ENG' or 'FRE' within the file's content
How to find system language within Python?
locale;python3;system information
Unix systems don't really have a system language. Unix is a multiuser system and each user is free to pick their preferred language. The closest thing to a system language is the default language that users get if they don't configure their account. The location of that setting varies from distribution to distribution; it's picked up at some point during the login process.In most cases, what is relevant is not the system language anyway, but the language that the user wants the application to use. Language preferences are expressed through locale settings. The setting that determines the language that applications should use in their user interface is LC_MESSAGES. There are also settings for the date, currency, etc. These settings are conveyed through environment variables which are usually set when the user logs in from some system- and user-dependent file.Finding a locale setting is a bit more complicated than reading the LC_MESSAGES variable as several variables come into play (see What should I set my locale to and what are the implications of doing so?). There's a standard library function for that. In Python, use locale.getlocale. You first need to call setlocale to turn on locale awareness.import localelocale.setlocale(locale.LC_ALL, )message_language = locale.getlocale(locale.LC_MESSAGES)[0]
_unix.185905
I do not have programming experience, but I understand how a shell script works theoretically. There are only two steps important to make a script executable, I have to tell the shell how to interpret the contents of thescript by writing a #!/path/to/interpreter,I have to give the permission to execute the file by chmod+x filename.So far, I can understand it, but how do real programs that contain many files and are zipped in a .tar.gz package differ from this kind of installation, what are important steps the Linux needs to do behind the curtain in order to make the program executable? Or in short: What is the very meaning of installing in Linux ?
What does the term 'installation' or 'install' mean when used in connection with Linux software?
linux;software installation
The installation of a Unix program consists of roughly two parts.1) Putting the files in suitable locations2) Setting file permissions and ownerships suitablyWith regard to the first, the Linux File Hierarchy Standard is relevant. This is Linux specific, but largely follows historically codified Unix rules. Specifically, binaries intended to be run by the user are placed in /usr/bin, system level binaries for adminstration etc. are placed in /bin, locally installed binaries are typically places in /usr/local/bin, etc. These are places that the system looks where to look at runtime, based on the PATH, variable, which on Debian is /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin. Similarly, libraries are placed in specific locations, /usr/lib, /lib, /usr/local/bin etc. following similar rules. Again, by default, the system is designed to look in these directories at runtime.There are other specified locations for placing documentation (including man pages) and data files, but these are not so critical to system functioning.As regards the second, files in the different parts of the system have different ownerships and permissions. While most files are owned by root, the associated group varies.The actual machinery of an installation varies, but is usually handled by the install target of a build system. The most common build systems for free Unix-like systems like the Linux-based systems are Autotools and Cmake.There is also usually an extra layer. Normally Linux systems have a binary package manager. These packages are usually built by invoking the installation target, but instead of installing the files into the system, they are installed into a temporary directory as part of the process of building the binary package.For Debian, this is usually the debian/tmp subdirectory of the source directory.Installing a binary package into the system has numerous advantages over a local installation, notably tracking which files belong to which package/software, and also handling package/software removals in a clean and reliable way. While build systems may have an uninstall target, this is not such a reliable way of handling uninstalls.
_unix.345856
After hitting the sleep or hibernate buttons (equivalent of xfce4-session-logout -s), my screen doesn't switch on when I'm trying to wake my computer up. The computer seems to run correctly since I can heard the sound of the video I was playing before I put the computer into standby mode.I thought it was a screen luminosity problem but I see the screen when I switch between tty.I have to logout through keyboard shortcut (ctrl+alt+del in arch-linux) or hard-reboot on order to be able to use my computerI have found a hack which seems to solve this problem, in order to sleep my computer I can use sudo echo mem > /sys/power/state as it's explained in kernel's power-state documentation.But since it's not the equivalent of the previous sleep method, I'm wondering what is the problem.You will find the logs associated to the both previous commands exported through journalctl --since xx command, as a gist here.Note: I used a different user for those two sleep methods (root for echo mem > ... and the current user (aldo) for the classic one. But executing xfce4-session-logout -s as sudoer didn't change anything) computer specs:$ cat /etc/*-releaseArch Linux releaseLSB_VERSION=1.4DISTRIB_ID=ArchDISTRIB_RELEASE=rollingDISTRIB_DESCRIPTION=Arch LinuxNAME=Antergos LinuxVERSION=16.11-Minimal-ISO-Rolling$ echo $DESKTOP_SESSIONxfce$ lspci -vnn | grep VGA -A 1200:02.0 VGA compatible controller [0300]: Intel Corporation Atom Processor Z36xxx/Z37xxx Series Graphics & Display [8086:0f31] (rev 0c) (prog-if 00 [VGA controller]) Subsystem: ASUSTeK Computer Inc. Device [1043:15bd] Flags: bus master, fast devsel, latency 0, IRQ 91 Memory at d0000000 (32-bit, non-prefetchable) [size=4M] Memory at c0000000 (32-bit, prefetchable) [size=256M] I/O ports at f080 [size=8] [virtual] Expansion ROM at 000c0000 [disabled] [size=128K] Capabilities: [d0] Power Management version 2 Capabilities: [90] MSI: Enable+ Count=1/1 Maskable- 64bit- Capabilities: [b0] Vendor Specific Information: Len=07 <?> Kernel driver in use: i915 Kernel modules: i915
Computer's screen doesn't switch on after waking up
arch linux;xfce
null
_webmaster.6022
I haven't done this before so I gotta ask.I'm doing a site for a client. The current site is done in PHP, and I'll do it in ASP.NET.Now, the current hosting service does not support ASP.NET code, so I'll have to change the hosting provider, and that's fine, BUT, the client SPECIFICALLY asked that the email adresses stay the same.Is this doable and if yes, how?So only the hosting provider changes, the domain name stays the same.Tnx for your time!Andrej
Change host / keep emails
web hosting;email
1) Create the email accounts on the new server2) Have the customer download any emails they wish to keep off of the old server (if they haven't done so already)3) After business hours change the DNS records to reflect the new host's nameservers (and by extensions MX records)4) If the mail settings have changed, have the customer update their email client to connect to the new mail server.5) Some emails may still get routed to the old server. Have the customer check this by either using webmail (if available) or using their old IP address for the mail server.
_unix.387538
I have been working on getting a new Debian (Stretch) install working satisfactorily on my new computer (Lenovo X270), including setting up xmonad/xmobar. Since I am studying Japanese, I wanted to set up an IME, which I managed to do using fcitx/fcitx-mozc. However, I wanted to include a plugin in my xmobar setup that indicates whether the current input method (according to fcitx) is japanese or not. The Kbd plugin doesn't seem to do this, since fcitx doesn't directly interface with XKB (as far as I can tell), so it shows us all the time. I also haven't been able to find out any way of querying the current fcitx IM from a terminal. Is there any way to do this (as if this is possible, I might be able to hack together an xmobar indicator), or is it far more trouble than it is worth?[For the record, I tried setting up ibus, but I had trouble with it, so I switched over to fcitx.]If necessary, I am more than happy to provide more details about my setup.
Query current input method in fcitx [for xmobar]
debian;xmonad;input method;fcitx
Hint: you can query DBus, e.g. by qdbus console tool, so:$ qdbus org.fcitx.Fcitx /inputmethod GetCurrentIMAnother approach with xkb-switch: xkb-switch -p
_unix.224354
I'm new on Fedora and I would like to know how to install the little applet named indicator-cpufreq on my Fedora laptop cause my i7 4700HQ burn over 90C after few seconds when the average cpu charge is over 80%. I just would like to lower the CPU frequency to limit the temperature.For information, I already tried dnf install indicator-cpufreq but that didn't find the package and i don't find any help on other forums, do I need to add sources? How can I do that on Fedora?
How to install indicator-cpufreq on fedora 22?
fedora;gnome;burning
null
_unix.165578
I've been told it's possible to use dd to reformat a portion of a Windows share drive from NTFS to ext3. I'd like to do this to be able to preserve permissions when using rsync for backups, but I cannot get it to work. I'm trying, from Unbuntu 12.04 and from Mac OS X.8.5, variants ofdd if=/dev/zero of=smb://WIN;username@IPaddress/path.ext3 bs=1024 count=1048576All of the variants of quotation mark presence/absence, single/double, and position I've tried all result in dd: smb://WIN: No such file or directorySmb to the remote directory works fine.
dd over smb to reformat ntfs as ext3
dd;smb
null
_datascience.8694
I frequently use Random Forest, Regularized Random Forest, Guided Random Forest, and similar tree models.The size of the data that I'm dealing with has grown beyond what I can work around using HPC and parallelism. It's typically large due to row length (observations) not columns (features). The data is also often not normally distributed.I have to make a choice between: Running a small number of trees (i.e. 50 or less) with either complete data or a relatively large and comparative sampleRunning several times the number of trees, but with a correspondingly scaled down sample sizeThere are work-arounds and for any 1 case -- for instance, I can do some ad hoc tests to see which I think will work better, but what I'm wondering is if there is a good theoretical (or robust empirical) reasoning to either guide the choice of approach over the other or to describe the tradeoff being made?In other words, I'm hoping that someone more comfortable with the math, statistics, and theory underlying this (type of) algorithm can offer some generalizable insight.
Random Forests with Big Data - number of trees v. number of observations
bigdata;random forest
I would recommend using a combination of both options #1 and #2.You could first try tuning your hyper-parameters to find out till what extent could you reduce the number of trees to a point where the random forest model's prediction starts deteriorating on the test set.This is because changing the value of mtry, the randomly selected number of features for a new tree, is the only meaningful hyper-parameter that should impact accuracy of the model. Since averaging converges as the no. of trees increases, the no. of trees could be reduced to a point where its performance is not impacted as much. Hence, you need to iterate and choose a a limit beyond which very small number of trees may not produce a strong enough ensemble. A random forest needs works best by using more base learners for reducing the variance by averaging each individual tree's output.It is not clear from your case whether you're using the Random Forest for a a classification or a regression problem. In case this is a classification problem, and if your data-set is imbalanced in terms of ratio of positive vs. negative classes; then you could reduce the size of the training set by under-sampling the majority class to bring it nearer to a 1:1 ratio. Since you have a large number of records, such class based sampling could improve accuracy as well as reduce data size for training.Additionally, if you've got a fine tuned Random Forest with good performance, then you could also evaluate dropping features that are least important as determined by the algorithm on OOB samples. This would reduce the time taken to train the model.
_unix.56550
This is hardly a theoretical question as many have done this, albeit there's very little information on the underlying processes.I'm developing a custom MIPS-based processor on which I would like to run Ubuntu. I'm quite baffled as to what to do next after you've designed the instruction set and the computer architecture itself. I need to be able to run a kernel and OS but how does it all tie in?At the moment I'm researching into designing a compiler for the Linux kernel to generate the appropriate assembly language. Is that a good way to go? What do I need to do after that?
Running the linux kernel and Ubuntu on custom processor
linux;kernel;development;mips;assembly
On the architecture side, you need more than an instruction set and a computer architecture. You also need to have:A CPU in some form (emulator, FPGA, silicon).A way of booting that processor: a way of getting the operating system into the memory that the processor runs at boot time. Most processors boot to code stored in ROM which either switches on some kind of flash memory and branches to it, or which loads some code from some storage media into RAM and branches to it. The next stage is an OS bootloader.Some peripherals at a minimum, RAM, some kind of storage controller, and some input/output devices.On the software side, you will need:A compiler. Since you're using the MIPS architecture, any existing compiler targetting MIPS should be sufficient. If your instruction set extends the basic MIPS instruction set (e.g. with extra registers), you may need to extend the assembler accordingly.A kernel. Linux for MIPS already exists. You'll have to add support for what you customized in your architecture: boot, MMU, Drivers. You'll need to write drivers for all the pieces of computer architecture that you didn't take off-the-shelf.A bootloader. There are usually things in the bootloader that are very architecture-specific, but you can probably add the requisite support to an existing bootloader, e.g. by adding a machine definition to U-Boot.And that's about all. Once you have a kernel and bootloader, userland programs should just work. Patch the kernel and bootloader from an existing distribution, cross-compile it on your PC, and install. Ubuntu doesn't support MIPS, but Debian does (mips or mipsel depending on endianness).
_softwareengineering.169854
Can someone clarify the following things for me ?Let's say I want to build a website and add publicity to it so I can make money out of my work.I would use Html5 for the interface and C# with ASP.NET for the background programming.I would use Visual Studio as my IDE and SQL server as a database.This is just an example on the top of my head but I don't know where to start for the licenses.Do I need one :For VisualStudio and SQLServer only ?For VisualStudio, SQLServer and pay some kind of rights for Asp.net ?The whole package.. Both VisualStudio, SQlServer plus rights for Asp.net AND C# ?I know this question is a little vague but I really don't know where to start and the opinion of someone with experience int this might give me just the help I need to get started.
Licensing a project
licensing;copyright
You can write .NET and T-SQL software in notepad and sell the result, same goes if you use IDEs. There are no licensing fee's for software based on the tools in .NET to create it, there may be if you try to release your software with third party assemblies that do not have free redistribution, but all the MS .NET and ASP.NET components are free to redistribute with appropriate license docs attached, not that you need to buy them.Also you obviously need buy licenses for any tools if you want to use them, like hosting it yourself using mssql means you need the license for the server you're running, but you don't need another license to sell the database file from your app.
_unix.257209
I have a directory (currdir) with 24000 images on a centos/cpanel server.I want to split this directory by moving images from this directory into other directories (or sub-directories inside currdir) based on image dates.How to make it happen?
How to move (image) files to other directories based on files' dates
files;date;move
null
_softwareengineering.193432
I'm working on a translator in C++. Basically I want to parse the file with translations and store it in my program, so I can perform search through the words and simply access the corresponding word. My file will look like that:word|translationsecond word|second translationetc. It doesn't have to be | as delimiter and the word can contain spaces. So after I store it in my program I want to search for a word and get the corresponding word easily.The question is, what is 'the best' way to store this dictionary? Should I use dynamic structures and link them? Maybe vectors? Or should I use two-dimensional array to store the 2 strings? Could you please propose to me how the structure will look like?
The best way to store dictionary from file
c++;data structures
Since you're going to search by the first word, I'd suggest using a Hashmap.A Hashmap is designed to solve exactly this issue: Search for a complicated key; It's also sometimes referred to as Dictionary, so you know it's about this.It works by defining a function (Which is called hash function) from the key-domain (word in your dictionary) to int, and then use these ints as the position in an array, where it stores both original key and value (word and translation).If your input is identical to some key, then the result of the hash function will give you the right int key, and you can complete your search very fast.For more information: http://en.wikipedia.org/wiki/HashmapGood luck :)
_softwareengineering.335799
TL;DRWhat procedure is followed when selecting bytes to represent opcodes? Are byte(s) for opcodes just randomly chosen, and them mapped to mnemonics?I recently learned from this answer that bytecode usually consists of instructions which have one opcode, which consists of a fixed number of bytes, and operands. Specifically this snippet from ratchet freak's answer:The bytecode itself is very often a very simple syntax. Where the first few bytes indicate what operation has to be performed and what operands are needed. The bytecode will be designed so that when reading byte per byte there is a unambiguous interpretation of the instructions.I took that advice and began designing my bytecode instruction set. But I soon came to a problem. Before I asked this question, I had tried to create opcodes using methods such as:# pseudo codeopcodes = { 'PUSH': convertToBytes(5), 'POP': convertToBytes(10), 'ADD': converToBytes(15), etc...}As you can probably tell, in the above example I used integers that were multiples of five, and converted them to byte form. I was trying to create a way in which I could orderly map my opcodes, to something such as integers. This of course did not work because as each integer became larger, So did the number of bytes relative to each integer. Which meant that my opcodes would've been variable lengths.I then began to wonder if I was going about this the wrong way. I did some research to see how other languages design there opcodes. I found this webpage about CPU opcodes that said:The x86 CPU has a set of 8-16 bit codes that it recognizes and responds to. Each different code causes a different operation to take place inside the registers of the CPU or on the buses of the system board.Here are three examples showing the bit patterns of three actual x86 opcodes, each followed by their one or more bytes of operands:And proceed to give an example: Bit Pattern ; operation performed by CPU ----------- -------------------------------------------------------1. 10111000 ; MOVe the next two bytes into 16-bit register AX2. 00000101 ; ...the LSB of the number (goes in AL)3. 00000000 ; ...the MSB of the number (goes in AH)1. 00000001 ; ADD to the BX register2. 11000011 ; ...the contents of the AX register1. 10001001 ; (2-byte opcode!) MOVe the contents of BX to2. 00011110 ; ...the memory location pointed to3. 00100000 ; ...by these last4. 00000001 ; ...two bytesThis leads me to my question: What procedure is followed when selecting bytes to represent opcodes?. As in the above example, each instruction consists of one byte. How though, was that specific pattern of a byte picked?. Are byte(s) for opcodes just randomly chosen, and them mapped to mnemonics? eg:# pseudo codeopcodes = { 'PUSH': selectRandomByte(), 'POP': selectRandomByte(), 'ADD': selectRandomByte(), etc...}Note: Let me clarify: When I say opcode, I am referring to the opcodes found in Virtual Machine bytecode, not CPU's. I apologize if this was not clear before. The example I gave with the CPU opcodes was only for illustration purposes only.Sourcesteaching.idallen.comHow exactly is bytecode parsed?
What is the procedure(if any) to select bytes to represent opcodes?
programming practices;language agnostic;language design;byte;bytecode
It's not random, but it may not be immediately apparent. And it may have evolved over time: the x86, architecture, for example, has been with us for nearly 40 years (1977), and has evolved from 16-bits to 32, to 64, with additional operations (such as MMX and SSE) added in that time.Architectures that have been around for a long time generally have some relationship between opcodes and the actual electrical signals used to control the CPU.In some architectures, such as the PDP-11, there is a clear plan to the opcodes. All opcodes fit into a 16-bit word, generally divided into 3-bit octal digits, with the following general usage:Bit 15: 1 for a byte operation, 0 for a word operatonBits 14-12: 0 indicates an instruction that takes a single operand, 1-6 indicates an instruction that takes two operands, 7 is for operations that don't follow the standard operand encoding.Bits 11-6: source operand for two-operand instructions, otherwise denotes the specific single-operand instruction.Bits 5-0: destination operand for two-operand instructions, otherwise the sole operand for single-operand instructions.In the case of Java bytecode, there's no underlying electrical architecture, and no real reason to put intelligence inside the structure of the bytecode, so related operations are grouped together and assigned sequential numbers. So while there's a reason that iconst_0 and iconst_1 have adjacent opcodes, there's (probably) no reason why those appear before the integer math opcodes.
_unix.31593
My USB TV tuner (an ENUTV-2) just stopped working and now I have to buy a new one. While I was browsing options, I realized my biggest priority was to get one that had Linux drivers (lack of them was my biggest annoyance with the old tuner).Can anyone recommend a TV tuner that has Linux drivers? It could be either PCI-E card or a USB box, my priority is Linux support.
Linux friendly TV tuner/receiver
drivers
The video4linux project keeps lists of supported cards, for example, analog PCI-e cards and analog USB devices. linux (the kernel) itself has a list of supported tuners under /Documentation/video4linux/CARDLIST.tuner.
_cogsci.102
Both disciplines have historically been at each other's throats, and Radical Behaviorists like B.F. Skinner often completely reject cognitive psychology at a philosophical level.It seems that today Behaviorism has largely fallen by the wayside but certain principles like Operant Conditioning remain entirely valid. Are these two philosophies/schools of thought incompatible or part of a greater whole? Is Behaviorism still relevant?
Is Behaviorism incompatible with Cognitive Psychology?
cognitive psychology;behaviorism
I think cognitive scientists would say that these views are compatible, insofar as cogsci admits results from behaviorism as valid results to be explained by understanding the cognitive constructs underlying them. Obviously (they would say) we have minds, our minds arise from physical processes in our brains, and as such have internal states that sometimes explicitly manifest in behavior, but other times do not manifest in any way that is perceivable. This is not a problem for non-behaviorist cognitive scientists.Hardcore behaviorists, however, cannot be so accommodating. Internal and non-manifest mental states are not admissible in their theoretical universe, and so what most cognitive scientists would have no difficulty in describing as a state change in some internal mental edifice, behaviorists must reframe as some kind of 'mental behavior' in the same way they tried to do with 'verbal behavior.' Of course, if one is very rigorous, and pushes very hard on this behaviorist view, it is either rendered nonsensical, or becomes an excessively ornate re-statement of normative cognitive science in behaviorist language. What this accomplishes I have no idea, although, to be honest, this seems to be nearly a straw man at this point. Hardcore behaviorists are increasingly hard to spot in the wild.
_unix.231022
I tried Fedora the other day and one thing which really annoyed me is how the title bar on windows disappears when I maximize them. I am using the Cinnamon desktop.How can I make it so the title bar does not disappear? I have found some answers for Gnome but not for Cinnamon.
How can I keep the title bar showing in Fedora (Cinnamon desktop) when a window is maximized?
fedora;cinnamon
null
_unix.243678
In a parent directory, I have several sub-directories, each of them contain one or more space-delimited text files.I have the following command that outputs what I want, but only for an individual file INPUTFILE.txtawk '{if (NF>4){print $1, $2, $3 , 0 } else {print $0}}' INPUTFILE.txtConsidering the fact that I have thousands sub-directories, and the file names will vary, how can I apply this command to all sub-directories; from the parent directory?
Apply a command to all subdirectories/files
bash;directory;command
First, cd to your desired parent directory.Then, make use of the find to run your awk command:find -type f -exec awk '{if (NF>4){print $1, $2, $3 , 0 } else {print $0}}' {} +Explanationit is already recursive by default so it will carry this out for all sub-directories-type f will limit to finding files , instead of both files and directoriesthe -exec somecommand {} + syntax runs a command, and puts the file paths found where you write {}the + option has been said to be more efficient because it only runs one instance of awk while putting the find results as arguments in {} whereas the other way of running it (not shown here) would run awk once per each file name and is said to be less efficient
_unix.73393
Suppose you tried something like this:$ paste ../data/file-{A,B,C}.datand realize that you want to sort each file (numerically, let's suppose) before pasting. Then, using process substitution, you need to write something like this:$ paste <(sort -n ../data/file-A.dat) \ <(sort -n ../data/file-B.dat) \ <(sort -n ../data/file-C.dat)Here you see a lot of duplication, which is not a good thing. Because each process substitution is isolated from one another, you cannot use any brace expansion or pathname expansion (wildcards) that spans multiple process substitution.Is there a tool that allows you to write this in a compact way (e.g. by giving sort -n and ../data/file-{A,B,C}.dat separately) and composes the entire command line for you?
Combining multiple process substitution
bash;command line;process substitution
Please see here, why eval can be dangerous to use. As you'll notice, it is a very powerful tool, but at the same time can cause a lot of damage.The following script will do what you want - safely.sort_ps () { local cmd=$1 p=() shift; for f in $@; do p+=(<(sort -n $f)); done $cmd ${p[@]}}EDIT: Mr. Chazelas is right. I fixed my solution, so you can now use sort_ps paste file1.txt file2.txt file2.txt ... fileN.txt instead. Thank you Stephane for reviewing my answer.Sample output:rany$ sort_ps sprunge foo1.txt foo.txt http://sprunge.us/EBZf?/dev/fd/62http://sprunge.us/TQGC?/dev/fd/62
_unix.382339
I use sshfs to mount a folder from a synology NAS (DS216+) locally to my Ubuntu machine. The command I use issshfs -o uid=1234,gid=1234,allow_other,default_permissions mysynology.box.com: /mnt/local.folderThe mount is (initially) succesful, in the sense that I can cd to the mounted folder from my ubuntu box, create files, etc.However, when I try to use the mount for something actually useful, like to create/move/copy larger files in batch, or create/manipulate a git repo, the sshfs mount is reset, and I get a failed: Transport endpoint is not connected (107) error when I try to use the mount point from then on.Note that, I have used the same command to mount folders by sshfs from two other, different unix boxes, other than the Synology box, with absolutely no problem.What could be the cause / remedy to this problem?
Using sshfs with Synology NAS results in connection reset
mount;sshfs;nas;synology
null
_webapps.104263
How can I see what profiles my page has viewed? I found how to see what videos were viewed, but would like to see the profiles.
I want to see what profiles my page has viewed in the past
facebook
null
_softwareengineering.305961
I have a Product class which has among others an attribute Ean13 that encapsulates an EAN13 code. Here is a prototype of the Product class:@Entity@Table(name = tb_produtos)public class Product implements Serializable { public Product() { } @Id @GeneratedValue private Integer id; @ManyToOne @JoinColumn(name = ID_FABRICANTE) private Manufacturer manufacturer; @Column(name = DESCRICAO) private String description; @Column(name = URL) private String url; @Embedded private Ean13 ean; @Transient private Keywords keywords; ... getters and setters.}At first, I implement the EAN class as follows:@Embeddablepublic class Ean13 { private static final RuntimeException notValidEanException = new RuntimeException(NOT VALID EAN CODE); @Column(name = ean_code, nullable = true, length = 13) private String code; public Ean13() { } public Ean13(String code) { validate(code); this.code = code; } private void validate(String code) { if (code == null || code.length() != 13) { throw notValidEanException; } if (!CharMatcher.DIGIT.matchesAllOf(code)) { throw notValidEanException; } String codeWithoutVd = code.substring(0, 12); int pretendVd = Integer.valueOf(code.substring(12, 13)); int e = sumEven(codeWithoutVd); int o = sumOdd(codeWithoutVd); int me = o * 3; int s = me + e; int dv = getEanVd(s); if (!(pretendVd == dv)) { throw notValidEanException; } } private int getEanVd(int s) { return 10 - (s % 10); } //mover estes metodos para outra classe. //TODO: Java 8. private int sumEven(String code) { int sum = 0; for (int i = 0; i < code.length(); i++) { if (isEven(i)) { sum += Character.getNumericValue(code.charAt(i)); } } return sum; } private int sumOdd(String code) { int sum = 0; for (int i = 0; i < code.length(); i++) { if (!isEven(i)) { sum += Character.getNumericValue(code.charAt(i)); } } return sum; } private boolean isEven(int i) { return i % 2 == 0; } @Override public String toString() { return code; }}As you can see, the way I implement the constructor throws a RuntimeException when the object is instantiated with an invalid code.An explanation about the Product class:In this particular case I will use this class to hold information about products in a crawler application, that crawl few web sites and collect information about these products. One of this information is the EAN code. In this case the product and EAN object will by instantiate in a service class. Some EAN codes the application grabs from the web site are not valid EAN codes (can be another code, or some other string). At first I want to save this products without any code until I created a way to store it. So at first I have to validate this EAN code before persist it. As you can see in the code above, I implement the validation in the method 'validate' that is called by constructor. In the way it is implemented, the validation will work more or less as follow:Product p = new Product ();try { Ean13 e = new Ean13(somecode); p.setEan13 (e);} catch (InvalidEanCodeRuntimeException e) { //Log invalid ean code and product information. }persist(p);But there would be other ways to validate it. I can make implement a public method in the Ean13 class as follow:Product p = new Product ();Ean13 ean = new Ean13 (somecode);if (ean.isValidEan ()){ p.setEan13(ean);}or it could still be done as follows, putting the validation in an external util class:Product p = new Product ();String somecode = somecode;if (CodeUtil.isValidEan13 (somecode)){ p.setEan13(new Ean13(somecode));}Certainly there are many other ways to implement it would work. But I would like to implement this validation in the most correct way, clean and elegant as possible and / or promote a discussion on ways to implement this kind of validation.
When a class represents a property that might be invalid, how should the validation be done?
java;programming practices;domain driven design;domain model
It depends on what your program is going to do with those objects. For example, if you are implementing a bar code scanner program, and in case of a scan error, the requirement is to write the (invalid!) code the scanner has detected into a log file, or display it to the user, I can imagine a scenario where is makes sense to construct and process Ean object even if it is invalid. If that is your case, it should be obvious you need an isValid method for something along the lines of: Ean eanCode; while(true) { eanCode = new Ean(ScanCode()); if(eanCode.isValid()) break; LogScanError(eanCode); }However, if your program always expects Ean objects to be valid, and there is absolutely no need for invalid objects, do the validation in the constructor, and throw an exception in case it fails. The example above might be implemented like Ean eanCode; bool scanOk=false; while(!scanOk) { String code = ScanCode(); try { eanCode = new Ean(code); scanOk=true; } catch(ValidationException ex) { LogScanError(code); } }This second variant has IMHO a light code smell, since it uses exceptions for control of flow, which is often seen as a bad practice.Thus I would prefer the isValid variant if you need the invalid Ean codes in more than one place in your program in a sensible manner, and the constructor variant if invalid Ean codes are a rare exception and their usage can be can be circumvented by implementing some code like above.
_cstheory.27298
I'm looking through some lectures and books to understand the PCP verifier constructed by Hastad. I noticed that the subtle difference of an adaptive or non-adaptive PCP verifier seems to correspond to verifier with perfect or non-perfect completeness.In A tight characterization of NP with 3 query PCPs the authors point out that there are (due to Trevisan and Zwick) strong restrictions using non-adaptive PCPs, e.g.$$P = PCP_{1, \frac{5}{8} + \epsilon}(log(n), 3)$$and they construct an adaptive PCP finally showing that $NP = PCP_{1, \frac{1}{2}+\epsilon}(log (n), 3)$.Then again the definition in the textbook from Arora, Barak (and in other lectures) uses explicitly non-adaptive verifiers with perfect completeness (well, with soundness $\frac{1}{2}$). Could someone give further explanations on this? Are different definitions with soundness paramter $\frac{1}{2}$ equivalent?And one further question: Is it possible to construct a linear dictatorship test (as basis of the Hastad Verifier) which is complete AND non-adaptive?
Adaptive vs. non-adaptive PCP verifiers
adaptive
null
_unix.85524
First, I'm not sure what window manager is running on my Mint installation. The Control Center yields no clues. Nevertheless - whatever I have is grabbing the emacs meta key (the option key on my Mac) and dropping down a window menu.Being a Mac person, I could do without any of those option key shortcuts into the menus. Is there a way to turn them off completely? Barring that, is there a way to at least tell the manager to listen for some obscure key, so that I can get my meta keystrokes into emacs?
emacs meta key and Mint window manager
linux mint;window manager;key mapping
null
_datascience.5458
I have around 1,000 job ads in the filed of IT (in excel file). I want to find the skills which are mentioned in each of ads. and then find the similar jobs based on skills.My method: I created 12 categories Such as programming skills, testing skills, communication skills, network skills, ... . Each advertisement may belong to 3-4 categories. In this case, some said multi-variate classification or Multi label classification is useful. But I don't know how to do this kind of classification in RapidMiner.1- Does anyone know how to do multi-variate classification or Multi label classification in RapidMiner? or is there another way?2- Do you recommend classification in order to analysis required job skills? or another technique? 3- Is there any better way to classify the skills which are stated in job ads?I'm new in the field of text mining. Please let me know if you have any idea. Thanks
Classification of skills based on job ads
machine learning;classification;nlp;text mining
null
_webapps.22186
I am using Google Blogger and would like to highlight the code. I tried a couple of ways, but not satisfied with the results. Can anyone share how they have done it?
How to highlight code in Blogger?
blogger;code
Alex Gorbatchev's SyntaxHighlighter is one of the most commonly used by software-related blogs for code highlighting. It lists several blogs that provide steps how to integrate it with the Blogger service.
_unix.200306
I have a peculiar problem - as soon as Dummynet Kernel module is loaded and appropriate ipfw add pipe 1 from localhost to localhost command is issued, I no longer can ping localhost - I receive the ping: sendto: No buffer space available error.Has anyone dealt with this issue? Thank you in advance for your proposed solutions!
No buffer space available when using Dummynet in FreeBSD 9.3
freebsd;ping;ipfw
null
_softwareengineering.136684
I have some confusion understanding the OpenUp/Basic process. It is described as an iterative process consisting of four phases:Inception,Elaboration,Construction, andTransition. I am not clear if a single iteration consists of all these phases or if we make several iterations within a single phase and then move to next phase. In the later case, it seems to be impractical but in former case feasibility of project can not be identified. Is there anyone who has experience implmenting it in the organisation?
OpenUp/Basic In Practice
agile
Open Up is a modified version of Rational Unified Process.[RUP][ R is for Rational]. It is customizable software developemnet process [ Infact you should always customize it to your own needs...You should have AUP where A stands for Anergy :-) ]At RUP,OpenUP [and probably in your AUP] there are 4 phases.Each phase cosist of n iterations. Each iteration ends with executable software. But there may exception for this at Inception. At Inception you basically check/investigate business-technological feasibility of software...You ask yourself should we do this, and if we want to do can we able to do it? For some large projects in order to answer those questions you may have to write some software...But this is so rare case...At Elaboration basically you take most risky-hard parts of the system and code it iteratively...So at the end of this phase you will had a solid architecture which is proven by most risky-hard part of the system features/requirements...You have executable architecture- not architecture stay just on document...Then comes Construction in which you code relatively lower risk parts iteratively...This takes more time than the other phases generally...Then Transition....bla bla bla....Shortly Each phase in RUP/OpenUP consiste of several[n] iterations...Each iteration generally result with executable code..At each iteration you basically do Requirement analysis-Implementation- Test - and produce small version of system whichcan be exceuted tested..At each iteration you incerement software...add some feature-valueRUP is iterative and incremental software developement process...To get more undestanding i advice you to read/watch those :Kruchten, What Is the Rational Unified Process? LinkKruchten, A Software Development Process for a Team of One LinkLarman,Kruchten,Bittner, How to Fail with the Rational Unified ProcessLinkIJI Consulting, Why Iterate? Understanding the Essentials ofIterative Development Watch at YoutubeIJI Consulting, Are you ready for Iterative Development Watch at youtube
_codereview.61101
After a lot of back and forth on various sites, reading articles, watching videos etc i still can not figure out the best way to secure my admin section.The session id is regenerated every page reload / action to make session hijacking / fixation more difficult.Let me know in the comments if you need any more details.My Goal:Securely log the user inSet a session / cookieAuthenticate the userDo this without HTTPSThe following code attempts to deal with authenticating the user / allowing use of the various admin pages / functions if successfully logged in, what am i missing?Config.php<?php session_name('wcx');session_start();session_regenerate_id(true);define( 'DB_HOST', '' ); // set database hostdefine( 'DB_USER', '' ); // set database userdefine( 'DB_PASS', '' ); // set database passworddefine( 'DB_NAME', '' ); // set database namespl_autoload_register(function ($class) { require_once 'classes/class.'. $class .'.php';});$backend = new backend();?>Index.php<?phpdefine('WCX', TRUE);require_once('config.php');$pagearray = array('dashboard');if(isset($_COOKIE['wcxadmin'], $_SESSION['loggedin'], $_SESSION['session']) && $backend->isLoggedIn()===true) { if(isset($_GET['page']) && !empty($_GET['page'])) { $page = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_STRING); } else { $page = 'dashboard'; } include_once('includes/header.php'); if(in_array($page, $pagearray, TRUE) && file_exists('includes/'.$page.'.php')) { include_once('includes/'.$page.'.php'); } else { include_once('includes/404.php'); } include_once('includes/footer.php');}else { include_once('login.php');}?>Login.php<?phpif(!defined('WCX')) { die('Direct access not permitted');}require_once(config.php);?><!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Transitional//EN http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd><html xmlns=http://www.w3.org/1999/xhtml><head><meta http-equiv=Content-Type content=text/html; charset=utf-8 /><link href=css/login.css rel=stylesheet type=text/css /><title>WebCodex - Please Login</title></head><body> <div id=loginwrapper><h2>WCX LOGIN</h2> <div id=loginformwrap> <div id=loginformwrapper> <form name=loginform method=post action=<?php $_SERVER['PHP_SELF']; ?>> <table class=adminlogin> <tr> <td valign=top> <input type=text class=default required=required name=username value= placeholder=Username id=adminusername maxlength=80 style=text-align: center; width:280px; color: #333; onblur=this.style.color='#333' onfocus=this.style.color='#000'/> </td> </tr> <tr> <td valign=top> <input type=password class=default required=required name=password value= placeholder=Password id=adminpassword maxlength=80 style=text-align: center; width:280px; color: #333; onblur=this.style.color='#333' onfocus=this.style.color='#000'/> </td> </tr> <tr> <td colspan=2> <input id=adminloginbutton type=submit name=login value=LOGIN /> </td> </tr> </table> </form> </div> <?php // SESSION ERRORS ARE SHOWN HERE if(isset($_SESSION['errors'])) { echo '<div class=loginerror>'.$_SESSION['errors'].'</div>'; // CLEAR THE SESSION ERRORS AFTER DISPLAYING THEM $_SESSION['errors'] = ''; } ?></div></div></body></html><?php // IF LOGIN BUTTON PRESSED / FORM SUBMITTED if (isset($_POST['login'])) { $bits = 32; $usercookie = 'Admin-'.bin2hex(openssl_random_pseudo_bytes($bits)); // SET THE LASTLOGIN AND SESSION VARIABLES //$lastlogin = date('d / m / y - H:ia'); $session = bin2hex(openssl_random_pseudo_bytes($bits)); $active = 1; // GRAB THE USERS INPUT $username = $_POST['username']; $password = $_POST['password']; //SELECT PASSWORD WHERE USERNAME = $username using a Prepared Statement $query = 'SELECT password FROM wcx_admin WHERE username = :username'; // PREPARE, BIND, EXECUTE, BIND THE RESULT TO A VAR $dbpass, FETCH, CLOSE $stmt = $backend->queryIt($query); $stmt = $backend->bind(':username', $username); $stmt = $backend->execute(); $dbpass = $backend->getColumn(); // VERIFY USER INPUTTED PASSWORD WITH DB PASSWORD USING PHP FUNCTION password_verify() if(password_verify($password, $dbpass)) { // UPDATE ACTIVE AND LASTLOGIN WHERE USERNAME = $username $query = 'UPDATE wcx_admin SET lastlogin = CURRENT_TIMESTAMP, session = :session WHERE username = :username'; // PREPARE, BIND, EXECUTE, CLOSE $stmt = $backend->queryIt($query); $stmt = $backend->bind(':session', $session); $stmt = $backend->bind(':username', $username); // IF THE ABOVE WENT WELL if($backend->execute()) { // SET THE SESSION $_SESSION['username'] = $backend->cipher($username, 1); $_SESSION['loggedin'] = 1; $_SESSION['session'] = $session; // A 1 HOUR LOGIN COOKIE setcookie( 'wcxadmin', $usercookie, time()+3600); header('Location: index.php'); } } else { // IF ERRORS SET AN ERROR SESSION w/GENERIC ERROR MESSAGE / DO NOT GIVE TOO MUCH AWAY $_SESSION['errors'] = 'Incorrect Username or Password'; // REFRESH THE PAGE TO SHOW THE ERROR header('Location: index.php'); } } ?>isLoggedIn Function// Is the User Logged In?public function isLoggedIn() { if($_SESSION['loggedin'] === 1) { return true; } else { return false; }}Logged in check on every page// Check for cookie and sessions / isLoggedIn booleanif(isset($_COOKIE['wcxadmin'], $_SESSION['loggedin'], $_SESSION['session']) && $backend->isLoggedIn()===true) { //Do Something Here}Logout.php<?php require_once('config.php');if(isset($_COOKIE['wcxadmin'], $_SESSION['loggedin'], $_SESSION['session']) && $backend->isLoggedIn()===true) { $session = $_SESSION['session']; $query = 'UPDATE wcx_admin SET session = :sess WHERE session = :session '; $stmt = $backend->queryIt($query); $stmt = $backend->bind(':sess', $sess=''); $stmt = $backend->bind(':session', $session); $logout = $backend->execute(); if($logout) { $params = session_get_cookie_params(); setcookie(session_name(), '', 0, $params['path'], $params['domain'], $params['secure'], isset($params['httponly'])); setcookie('wcxadmin', '', time()-3600); session_unset(); session_destroy(); header('Location: index.php'); }}else { header('Location: index.php'); }?>
Admin section - Secure login and authentication
php;pdo;authentication
SecurityYou have a lot of things covered. You use prepared statements and only include files that are defined in a white-list, that's good. I just have these smaller points:don't store your password in the php source file, but in a configuration file (outside the web root). It's not too dangerous, but it's better to be save.action=<?php $_SERVER['PHP_SELF']; ?>: this would be vulnerable to XSS attacks if it were working. As you are not echoing, the action will always be . Either set the action to a hard-coded , or echo an escaped php self. Do not leave it as it is, in case someone will fix it.you are not filtering $_SESSION['errors'] when outputting it to the user. Right now, this is not a problem (it only contains a hard-coded string). But if you at some point change your code that this does depend on user input, this will cause problems (for example: You tried to access /cool-site/<script>alert('xss');</script>. We are sorry, but you do not have the right to access it. I would just filter it now to be sure.enable HttpOnly cookies (for your cookie as well as the session cookie). I would do this in the PHP code as well as in the server settings, because you newer know if others remember to set the server settings. This mitigates the risks of XSS (although there are still risks).Secure login and Do this without HTTPS: these do not go together. If you want to prevent man in the middle attacks, you will need HTTPS.(I didn't find anything else, but that doesn't mean that there is nothing else to find.)Apart from the security aspects, your code seems fine. Sometimes, the indentation is a bit of, and your HTML doesn't validate 100%, but I didn't see any major problems.
_webmaster.21855
I would like to buy Google maps premier license. I tried to contact Google maps through their web site (online inquiry form). No one got back to me. I would appreciate if someone can help me with this.
Google maps premier license
google maps
null
_unix.250022
I have a Yubikey 4 and I want to use my GPG keys stored on this to authenticate to SSH servers.I want to use GitHub for a start. I have already added my GPG authentication key to GitHub.My problem is that when I ssh, my agent doesn't use this key. I've checked by trying to connect to my VPS with ssh -v but it skips my GPG key. My Yubikey is plugged in and gpg2 --card-status shows all the details. I am able to sign and decrypt fine as well as use the other features of the Yubikey.The ssh ouputdebug1: Authentications that can continue: publickeydebug1: Next authentication method: publickeydebug1: Trying private key: /home/wilhelm/.ssh/id_rsadebug1: Trying private key: /home/wilhelm/.ssh/id_dsadebug1: Trying private key: /home/wilhelm/.ssh/id_ecdsadebug1: Trying private key: /home/wilhelm/.ssh/id_ed25519debug1: No more authentication methods to try.Permission denied (publickey).I have disabled gnome password manager.I've looked at Connecting SSH and Git to gpg-agent and followed the suggestion, but it doesn't seem to be working. ssh-add -lCould not open a connection to your authentication agent. ps aux | grep gpg-agentwilhelm 26079 0.0 0.0 20268 980 ? Ss 20:57 0:00 gpg-agent --daemon --enable-ssh-support --shwilhelm 31559 0.0 0.0 12724 2184 pts/1 S+ 22:49 0:00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn gpg-agent
gpg-agent instead of ssh-agent
ssh;gpg;gpg agent
ssh can't open connection to your gpg-agent if you will not give it the way to do so.When you start your gpg-agent with --enable-ssh-support option, it prints out environmental variables that needs to be available in the shell where from you will be using your ssh. There are few possibilities how to get them:Stop your gpg-agent and start it once more in like this in the shell where from you are using your ssh (this should be the easiest way to test it):eval $(gpg-agent --daemon --enable-ssh-support --sh)Find the location of authentication socket and set up the environment variable SSH_AUTH_SOCK by handLater on, when you will know that it works, you should set up the agent start according to the manual page for gpg-agent(1), so probably in ~/.xsession to let it start automatically.
_softwareengineering.237273
I have a few projects that use various webservices e.g. DropBox, AWS. For managing private information I use bash_profile which works great with heroku that uses env variables to manages secret informations. The problem is my bash_profile is growing significantly (HEROKU_ADD_ON_1 HEROKU_ADD_ON_2 etc.) and it bit me today.What's the better way?
how do you manage api keys?
configuration;environment;heroku
null
_webmaster.7958
Is this possible?A third party site is running my Drupal moduleAn end user clicks on a link which will:Open up a new window www.mysite.com/redirect.phpand POST certain data to this page www.mysite.com/redirect.phpI've seen the user's browser being redirected, but am not clear on how to do the above.
Can I POST to a new window that I want to open up?
html;redirects;drupal;post
If you just want a link that opens a POST-requested page in a new window here are some ideas. However, be aware a POST request can't be bookmarked.You can make a button that opens a POST-requested page in a new window.<form method=post action=http://example.com/example.php target=_blank><input type=hidden name=name1 value=value1><input type=hidden name=name2 value=value2><input type=submit value=Open results in a new window> </form>If you want it to look like a link, you can make a link with an onClick attribute that submits the form.<form name=myform method=post action=http://example.com/example.php target=_blank><input type=hidden name=name1 value=value1><input type=hidden name=name2 value=value2></form><a href=http://example.com/example.php onClick=document.forms['myform'].submit(); return false;>Open results in a new window</a>The onClick part submits the form, which opens the POST-requested page in a new window. The return false prevents the browser from also going to the href address in the current window at the same time. If Javascript is disabled or the link is bookmarked, the href address is used as a fallback, but the resulting page won't receive any POST values. This might be confusing or unfriendly for your users if they bookmark the link.If you want the link to be bookmarkable, investigate if your page can accept GET parameters. If so, then you can make a bookmarkable link. <a href=http://example.com/example.php?name1=value1&name2=value2 target=_blank>Open results in a new window</a>
_codereview.106853
I'm using VB.Net, MVC 5, EF 6, and Linq. I have a list of Integers (category attribute IDs). I need to create a second list of String (values). There will be one string for each integer.I am currently accomplishing my task like this:Function getValues(catAttIDs As List(Of Integer), itemID As Integer) As List(Of String) Dim db As New Model1 Dim values = New List(Of String) For i As Integer = 0 To catAttIDs.Count - 1 Dim catAttID = catAttIDs(i) Dim currentValue = (From row In db.tblEquipment_Attributes Where row.Category_Attribute_Identifier = catAttID _ And row.Unique_Item_ID = itemID Select row.Value).SingleOrDefault() values.Add(currentValue) Next Return valuesEnd FunctionI have a strong feeling that there is a better way to do this, but I have not been able to find the information I'm looking for.I'm particularly interested in changing this code so that the database is called once for the list, instead of calling the database 5 or 6 times as I work my way through the list.
Retrieving a list, by iterating through a list
linq;vb.net
You're looking for the LINQ-equivalent of an IN clause in SQL. So something like this:SELECT value FROM tblEquipment_Attributes WHERE Category_Attribute_Identifier IN (<list of integers>) AND Unique_Item_ID = itemID;So what you could do is write your LINQ statement to see if the Category_Attribute_Identifier is in the list. Then your function will look something like this:Function getValues(catAttIDs As List(Of Integer), itemID As Integer) As List(Of String) Dim db As New Model1 Dim currentValues as List(Of String) = (From row In db.tblEquipment_Attributes Where catAttIDs.Contains(row.Category_Attribute_Identifier) _ And row.Unique_Item_ID = itemID Select row.Value).ToList() Return currentValuesEnd FunctionNote that ToList will create a List<T>, where T is the type of the elements. As long as Value in your db is a varchar, it'll be a List.
_codereview.33427
I wrote an FAQ on a third-party website which pertains to thread-protecting objects in Delphi. What I'd like to know is if this thread-protection approach is accurate, or if I should change anything about it. I don't intend to ask about the FAQ in general, just the aim at the actual topic of multi-threading.This code comes from common practices of mine, and I'm starting to wonder if these practices are good or bad. I've used this TLocker object for a long time, and would like to know if there's anything wrong with any of this approach.The FAQ content:There are many ways to thread-protect objects, but this is the most commonly used method. The reason you need to thread-protect objects in general is because if you have more than one thread which needs to interact with the same object, you need to prevent a deadlock from occuring. Deadlocks cause applications to freeze and lock up. In general, a deadlock is when two different threads try to access the same block of memory at the same time, each one keeps repeatedly blocking the other one, and it becomes a back and forth fight over access.Protection of any object(s) begins with the creation of a Critical Section. In Delphi, this is TRTLCriticalSection in the Windows unit. A Critical Section can be used as a lock around virtually anything, which when locked, no other threads are able to access it until it's unlocked. This ensures that only one thread is able to access that block of memory at a time, all other threads are blocked out until it's unlocked.It's basically like a phone booth with a line of people waiting outside. The phone its self is the object you need to protect, the phone booth is the thread protection, and the door is the critical section. While one person is using the phone with the door closed, the line of people has to wait. Once that person is done, they open the door and leave and the next comes in and closes the door. If someone tried to get in the phone booth while someone's using the phone, well, it's obvious that would lead to a fight. That fight would be a deadlock.It is still a risk to cause a deadlock even when using this method, for example, someone trying to use the phone when someone else is using it. If for any reason a thread attempts to access the object without locking it, and while another thread is accessing it, you will still run into issues. So, you need to use this protection EVERYWHERE that could possibly need to access it. Remember, when you lock this, nothing else is able to lock it again (under the promise that all other attempts would also be using this same Critical Section). The locking thread must unlock it before it can be locked again.Okay, so into the code. The four calls you will need to know are:InitializeCriticalSection() - Creates an instance of a Critical SectionEnterCriticalSection() - Engages the lockLeaveCriticalSection() - Releases the lock DeleteCriticalSection() - Destroys an instance of a Critical SectionFirst, you need to declare a Critical Section somewhere. It's usually something that would be instantiated for the entire duration of the application, so I'll assume in the main form. TForm1 = class(TForm) private FLock: TRTLCriticalSection;Then, you need to initialize (create) your critical section (presumably in your form's constructor or create event)...InitializeCriticalSection(FLock);Now you're ready to use it as a lock. When you need to access the object it's protecting, you enter the critical section (locking it)...EnterCriticalSection(FLock);Once you have done this, it is locked. No other thread other than the calling thread is able to access this lock. Remember, technically other threads are able to access the object (but would potentially cause a deadlock), so make sure all other threads are also first trying to lock it. That's the goal of this lock.Once you have done everything you need in this thread, you leave the critical section (unlocking it)...LeaveCriticalSection(FLock);Now, it is unlocked and the next thread which may have attempted a lock is now able to completely lock it. That's right, while a critical section is locked, it remembers any other lock attempt, and once the calling thread unlocks it, the next one in the queue automatically acquires this lock. Same concept as a line of people waiting outside a phone booth.When you're all finished with the object, make sure you dispose of this critical section (presumably in your form's destructor or destroy event)...DeleteCriticalSection(FLock);And those are the fundamentals. But we're not done yet.It's highly advised that you should always use a try..finally block when entering/leaving a critical section. This is to ensure that it gets unlocked, in case of any unhandled exceptions. So, your code should look something like this:EnterCriticalSection(FLock);try DoSomethingWithTheProtectedObject;finally LeaveCriticalSection(FLock);end;Now, the last thing you may wish to do is wrap this up in a nice simple class to do the work for you. This way, you don't have to worry about all the long procedure names whenever you use this lock. This object is called TLocker, which protects an object instance for you. You would need to create an instance of this for every object instance you need to protect. So, instead of declaring something like FMyObject: TMyObject; you would do it like FMyObject: TLocker; and then give the object instance to it upon its creation.type TObjectClass = class of TObject; TLocker = class(TObject) private FLock: TRTLCriticalSection; FObject: TObject; public constructor Create(AObjectClass: TObjectClass); overload; constructor Create(AObject: TObject); overload; destructor Destroy; function Lock: TObject; procedure Unlock; end;constructor TLocker.Create(AObjectClass: TObjectClass);begin InitializeCriticalSection(FLock); FObject:= AObjectClass.Create;end;constructor TLocker.Create(AObject: TObject);begin InitializeCriticalSection(FLock); FObject:= AObject;end;destructor TLocker.Destroy;begin FObject.Free; DeleteCriticalSection(FLock);end;function TLocker.Lock: TObject;begin EnterCriticalSection(FLock); Result:= FObject; //Note how this is called AFTER the lock is engagedend;procedure TLocker.Unlock;begin LeaveCriticalSection(FLock);end;The first constructor TLocker.Create(AObjectClass: TObjectClass); expects a class type to be specified (such as TMyObject).The other constructor TLocker.Create(AObject: TObject); expects an instance of an object already created. Bear in mind that if you do use this constructor, you should no longer refer directly to that object after passing it into this constructor.In both of these cases, your object which is being protected will be automatically free'd when the TLocker is free'd. Let's assume the second constructor of the two. Once you've created an instance of this class with your initial actual object reference, never reference to the actual object again. Instead, whenever you need to use that object, pull it out of the TLocker instance by locking it. Using a try..finally block, make sure you also unlock it once you're done, or else the lock is stuck.So, using the class above, you can access an object like this:procedure TForm1.FormCreate(Sender: TObject);var O: TMyObject;begin O:= TMyObject.Create; FMyObjectLocker:= TLocker.Create(O);end;procedure TForm1.FormDestroy(Sender: TObject);begin FMyObjectLocker.Free; //Your original object will be free'd automaticallyend;procedure TForm1.DoSomething;var O: TMyObject;begin O:= TMyObject(FMyObjectLocker.Lock); try O.DoSomething; //etc... finally FMyObjectLocker.Unlock; end;end;As you see, I acquire the object at the same time as locking it. This should be the only possible way to access this object. Just make sure you always unlock it when you're done. Notice also how I also don't define the actual protected object in the class - to prevent accidental direct calls to the object.
Is this the right way to thread-protect an object?
multithreading;thread safety;delphi
null
_softwareengineering.173452
I am having a mobile app created for ios. The developers built the app in php. The app requires an algorithm so I found another programmer to develop it. The algorithm programmer built the algorithm in python. The developers refuse to finish the app because they say it won't work with python, while the programmer insist it will. The programmer says put the algorithm in its on server and connect then over http. Will this work and I'd so how risky is it to future problems?
Can python and php work together?
php;python;ios;iphone;app
null
_unix.304890
Updating my Linux server is mostly a stressed part for me. Like today. With yum update i see a new version of NodeJS, but from what i can remember nodejs has been used by a program which needs to be carefully altered.So i thought, there should be a command how to find out which program is using NodeJS, but unfortunately I can't find such command.Is there a yum command which tells me who is using NodeJS on my system? So i can check if it is ok to update?
Which program uses which package?
files;yum;monitoring;dependencies
null
_softwareengineering.302363
I've been writing a program to pick random words from my list. However, to do that I had to imitate some solutions on the internet, and I succeeded. Unfortunately, there is something that I can't understand in my work.def repeat(pic_word, n): for i in range(n): pic_word()My question is what is the meaning of i in for i in range?
What i and n stand for in python?
python;python 3.x;ironpython
null
_unix.247587
I can boot from USB drive to Kali Linux, but when I reboot the system, all previous updates and files saved just vanish.I have done almost everything the Kali Linux official documents tell me to do, except that after I dd the ISO to my USB drive, I used the parted command to create a new partition named 'work' and created the persistence.conf file in my Ubuntu system, instead of rebooting into Kali Linux live from the USB drive to create the partition and so on.While I searched the Internet for things like Kali Linux live boot from USB, I encountered many tutorials for installing Kali Linux live usb. These tutorials provide quite similar instructions as the official documents.I also noticed this question (Kali Linux live usb persistance) on Unix&Linux. I don't quite understand this --that partition will be 'merged' with / as specified in persistence.conf.Please help me sort things out.EDIT 1:I made a post(at #2) at Kali Linux Forums yesterday to describe my problem in more detail.
Kali Linux 2.0 live USB updates not working
kali linux;live usb;persistence
null
_codereview.156965
I have an assignment to create a method to retrieve the proper day of the week for any given date, without using the Java calendar. After countless hours of trying to implement the algorithm in the outline, I've finally finished it and it appears to work! I feel like it's really sloppy. Any tips on how to clean it up or remove any dead code you see?Here's the algorithm I had to implement:Only look at the last two digits of the year and determine how many 12s fit in itLook at the remainder of this divisionHow many 4s fit into that remainderAdd the day of the monthAdd the month code:Jan = 1Feb = 4Mar = 4Apr = 0May = 2Jun = 5Jul = 0Aug = 3Sep = 6Oct = 1Nov = 4Dec = 6Add your numbers, then mod by 7Some dates require special offsets:January and February dates in leap years: subtract 1 from step 5Dates in the 1600s: add 6 to step 5Dates in the 1700s: add 4 to step 5Dates in the 1800s: add 2 to step 5Dates in the 2000s: add 6 to step 5Dates in the 2100s: add 4 to step 5public String getDayOfTheWeek(){ int shortYear = yearNumber % ONE_HUND_MOD; /* gives the last two digits of the four digit year */ int anotherShortYear = yearNumber % ONE_HUND_MOD; /* gives the last two digits of the four digit year to another variable */ int twelvesFirstStep = (shortYear / TWELVE_DIVIDE); /* gives the number of 12s that fit in the last two digits of the year(step1) */ int secondStepRemainder = anotherShortYear % TWELVE; /* gives the remainder of whats left from dividing the last two digits of year by 12(step 2) */ int thirdStepRemainder = secondStepRemainder / FOUR; /* gives the division by 4 of the remainder of the previous step (step 3) */ int numericalDay = 0; int temp = twelvesFirstStep + secondStepRemainder + thirdStepRemainder + dayNumber +getMonthCode(); // all variables combined if (monthNumber ==JANUARY || monthNumber == FEBRUARY && isLeapYear() == true) { temp--; } else { temp = temp; } if (yearNumber >= CENTURY_SIXTEEN && yearNumber < CENTURY_SEVENTEEN || yearNumber >= CENTURY_TWENTY && yearNumber < CENTURY_TWENTY_ONE) { numericalDay = (SIX+temp) % MOD_BY_SEVEN; } else if(yearNumber >=CENTURY_SEVENTEEN && yearNumber < CENTURY_EIGHTEEN || yearNumber >= CENTURY_TWENTY_ONE && yearNumber <CENTURY_TWENTY_TWO) { numericalDay = (FOUR+temp) % MOD_BY_SEVEN; } else if(yearNumber >=CENTURY_EIGHTEEN && yearNumber < CENTURY_NINETEEN) { numericalDay =(TWO+temp) % MOD_BY_SEVEN; } else { numericalDay = temp % MOD_BY_SEVEN; } if(numericalDay == TRANSLATED_DAY_SAT) { return SATURDAY_STRING; } else if(numericalDay == TRANSLATED_DAY_SUN) { return SUNDAY_STRING; } else if(numericalDay ==TRANSLATED_DAY_MON) { return MONDAY_STRING; } else if(numericalDay == TRANSLATED_DAY_TUES) { return TUESDAY_STRING; } else if(numericalDay == TRANSLATED_DAY_WED) { return WEDNSEDAY_STRING; } else if(numericalDay ==TRANSLATED_DAY_THU) { return THURSDAY_STRING; } else { return FRIDAY_STRING; }}
getDayOfTheWeek function, without using built-in date libraries
java;datetime;homework
null
_unix.141362
I'm looking to disable USB via the kernel for a high-performance server.How can I effectively administer the server, if problems occurs if USB isn't enabled? Without USB, keyboards and mice devices won't be able to function. I could do it through ILO through the network but I have the possibility of the NIC failing on me or the IP address changing via DHCP. Are there best practices on this?
How can I administer a server if USB disabled?
usb;administration
Typically you can set the BIOS to handle USB support, which will work with whatever boot-loader from there. At that point you can have a separate image available to load with USB support for those times that everything goes to pot. This may not work as some USB devices aren't supported by some boot-loaders.Two notes:1) I haven't tried this, though the theory should be sound (the crowd can shoot me down if I'm not.2) I'm also not sure that the USB module is that heavy. You could JUST leave in the specific model you have to make it lighter and still have a keyboard available.
_webmaster.53572
Similar to question posted here (but not related to sub directories):.htaccess redirect of domain name alias to main domain but must show up as the alias domainI am trying to direct traffic from an alias domain I have to my site that is on the same server, while also keeping the alias domain in the browser address bar. This is my original htaccess content which correctly redirects the user, but xyz.com appears in the browser which I do not want.rewritecond %{HTTP_HOST} ^(www\.)?abc\.com$ [NC]rewriterule ^ http://xyz.com/?foo [R=301,QSA,L]This is my attempt to not only bring abc.com visitors to xyz.com but also have abc.com appear in the browser. This doesn't even load the site. Any ideas on a fix? rewritecond %{HTTP_HOST} ^(www\.)?abc\.com$RewriteRule ^$ /index.html [L]
Require domain alias to show in browser address bar
domains;htaccess;apache;redirects;url rewriting
null
_unix.218375
I'm trying to configure alpm to max_perfomance on my system disk, medium_power on my data disks and min_power for backup disks. I tried various variations in tuned.conf but the result is that the last setting is set for all my disks.My tuned.conf file goes like this:[systemdisk]devices=sdbtype=diskalpm=max_performance[datadisk]devices=sda, sdd,!sdbtype=diskalpm=medium_power[backupdisk]type=diskdevices=sdc, sdealpm=min_powerand the result is that all my disks are set to min_power. If I comment the [backupdisk] section, all my disks are set to medium_power. How can I configure different alpm values for different disks?
tuned on fedora 22 - setting different alpm policies for specific devices
linux;fedora;power management;tuned
I got an official reply to the bug I opened:https://bugzilla.redhat.com/show_bug.cgi?id=1246992Unfortunately, the reply is that setting different alpm policies for different devices is not supported. It may be supported in the future for devices on different controllers, but not as a specific setting for different drives.
_unix.25361
Why is a signed integer used to represent timestamps? There is a clearly defined start at 1970 that's represented as 0, so why would we need numbers before that? Are negative timestamps used anywhere?
Why does Unix store timestamps in a signed integer?
timestamps
Early versions of C didn't have unsigned integers. (Some programmers used pointers when they needed unsigned arithmetic.) I don't know which came first, the time() function or unsigned types, but I suspect the representation was established before unsigned types were universally available. And 2038 was far enough in the future that it probably wasn't worth worrying about. I doubt that many people thought Unix would still exist by then.Another advantage of a signed time_t is that extending it to 64 bits (which is already happening on some systems) lets you represent times several hundred billion years into the future without losing the ability to represent times before 1970. (That's why I oppose switching to a 32-bit unsigned time_t; we have enough time to transition to 64 bits.)
_codereview.161522
Since I am new to R, I have pulled this code together in kind of a rag-tag way, but I am wondering, is there something similar to list comprehensions (in Python) I can use in R to make this simpler? Or a better way of doing this? I am trying to fetch the total amount of reputation a user has accumulated on Stack Exchange. I am ideally looking for a way to remove the for loop and use the sum function on a subset of items (from the API response).library(httr)s = 0for(i in content(GET(paste(http://api.stackexchange.com/users/,readline(),/associated,sep=)))$items) { q=i$reputation if (q>101) s=s+q}print(s)Sample input would be a user's id, like 10400443.
Fetching the total amount of SE reputation accumulated
r;stackexchange
R does not offer list comprehensions like Python, but a similar thing called the apply family of functions. In addition, there is packages called purrr that offers similar functionality with a more user-friendly interface. Below is an example how to compute the sum using these tools.library('httr')user_url <- paste0(http://api.stackexchange.com/users/, readline(), /associated)dat <- content(GET(user_url))$itemssum(vapply(dat, function(x) ifelse(x$reputation > 101, x$reputation, 0), 1))library('purrr')sum(map_dbl(dat, ~ifelse(.x$reputation > 101, .x$reputation, 0)))
_cs.7373
Possible Duplicate:Every simple undirected graph with more than $(n-1)(n-2)/2$ edges is connected At lesson my teacher said that a graph with $n$ vertices to be certainly connected should have$ {\frac{n(n-1)}{2}+1 \space }$ edges showing that (the follow is taken from the web but says the same thing):The non-connected graph on n vertices with the most edges is a complete graph on $n-1$ vertices and one isolated vertex. So you must have $ 1+{\frac{n(n-1)}{2} \space}$ edges to guarantee connectedness. My idea: a complete graph $K_{n-1}$ with $n-1$ vertices has ${n-1 \choose 2}$edges, so ${\frac{(n-1)*(n-2)}{2}}$ edges, added to the edge to connect the complete graph to the isolate vertex,so shouldn't be ${\frac{(n-1)*(n-2)}{2}}+1$ edges?What am I doing wrong?Thanks.
How many edges must a graph with N vertices have in order to guarantee that it is connected?
graph theory;graphs
Don't know why I didn't just give an answer, rather than a comment, but for posterity:Your reasoning is correct, the $n$ vertex graph with the maximal number of edges that is still disconnected is a $K_{n-1}$ with an additional isolated vertex. Hence, as you correctly calculate, there are $\binom{n}{2} = \frac{(n-1)(n-2)}{2}$ edges.Adding any possible edge must connect the graph, so the minimum number of edges needed to guarantee connectivity for an $n$ vertex graph is $\frac{(n-1)(n-2)}{2}+1$.Contrary to what your teacher thinks, it's not possible for a simple, undirected graph to even have $\frac{n(n-1)}{2}+1$ edges (there can only be at most $\binom{n}{2} = \frac{n(n-1)}{2}$ edges).The meta-lesson is that teachers can also make mistakes, or worse, be lazy and copy things from a website.For an extension exercise if you want to show off when you tell the teacher they're wrong, how many edges do you need to guarantee connectivity (and what's the maximum number of edges) in aSimple, directed graph?A directed graph that allows self loops?
_softwareengineering.294410
I have a Node.js Express RESTful HTTP server I will call server A and an Express socket.io server I will call server B.Server A responds to all HTTP requests by clients and server B listens to the MongoDB oplog and sends database updates currently to all clients.I don't want to send all DB updates to all the clients -I want to optimize the system so that server B and the connected clients experience less load by partitioning server B so that only certain/relevant DB updates are sent to certain clients...In this way server B could send just a fraction of the messages it would have before, and each client wouldn't have to handle all the updates.I have read a little bit about socket.io rooms and how clients can join a namespace.In the past I have appended the user id to all MongoDB collections that pertain to a certain user, so I could have each client join the namespace denoted by their user id. This might mean that each client only gets the updates corresponding to their namespace on the server + a few universal updates that pertain to all users.My question is how to best design this so that all users get the updates they need while minimizing the load on the server and the clients.Does anyone have any advice on how to best do this with MongoDB, the MongoDB oplog and a separate socket.io server?
Design pattern for socket.io and Express
node.js;http;sockets;websockets
null
_bioinformatics.230
As enrichment analysis a usual step is to infer the pathways enriched in a list of genes. However I can't find a discussion about which database is better. Two of the most popular (in my particular environment) are Reactome and KEGG (Maybe because there are tools using them in Bioconductor).KEGG requires a subscription for ftp access, and for my research I would need to download huge amounts of KGML files I am now leaning towards ReactomeWhich is the one with more genes associated to pathways ? Which is more completely annotated ?Is there any paper comparing them ?
What are the advantages and disadvantages between using KEGG or Reactome?
database
One big downside of KEGG is the licensing issue. One big advantage of Reacome are various crosslinks to other databases and data.ad 1, This depends on which pathway, they are both primary databases. Sometimes other databases that for instance combine data of primary databases have better annotation of pathways (there is an example in the review paper bellow)ad 3, There is very extensive relatively new (2015) review on this topic focused on human pathways: Comparison of human cell signaling pathway databasesevolution, drawbacks and challenges. However I could not find there which one is more complete ...
_cs.48899
I am thinking of the classical paper, https://www.cs.sfu.ca/~kabanets/Research/poly.htmlCan someome link to some papers/reviews that give a sampling of what are the recent thoughts in this direction? I am equally happy to know of what are the recent directions in the topic of pseudorandomness and derandomization.
What are the recent research directions in the topic of circuit lower bounds from derandomization?
reference request;circuits;randomness;pseudo random generators
null
_vi.6777
I have the ruler shown, but as soon as I drop into insert mode, it disappears and reappears upon entering normal mode. This is very annoying when trying to insert a certain number of spaces to have the cursor at column x.MacVim shows no such behaviour.How can I show the ruler in insert mode?
Why is ruler not shown in insert mode?
insert mode;normal mode
null
_unix.74385
I use the highlight mode in vim to copy a few characters. I then want to paste more than once. My current technique does not work well.Sample text: Linux Solaris Irix HP-UXSuppose I want to copy the word Linux, then paste over Solaris and Irix.Place cursor at L in LinuxCommand v (for visual hilite), then e (for end-of-word), then y (for yank/copy)Now Linux is on my vim clipboardMove cursor to S in Solaris (first instance)Command v (for visual hilite), then e (for end-of-word), then p (for paste)Text is now: Linux Linux Irix HP-UX, but now Solaris is on my vim clipboardMove cursor to I in Irix (second instance)Command v (for visual hilite), then e (for end-of-word), then p (for paste)Text is now: Linux Linux Solaris HP-UX which is not what I expected.I resort to using highlite/paste with the mouse (via X Terminal). Surely, I can do this better. How?
Vim: copy, then paste more than once
vim
null
_codereview.79569
Last weekend my teacher asked me to create code to solve a problem:Giving a dynamic array, we want to pass the array elements from a file. The first number in the file N gives us the array length. They follow N numbers, the actual elements of the array. Three brothers are going to work in the shop of their father for a time. The shop is doing well and every day generates profit which the three brothers may provide. The brothers agreed that they would divide the total time in three successive parts, not necessarily equal duration, and that each one will be working in the shop during one of these parts and collects the corresponding profit on his behalf. But they want to make a deal fairly, so that one received from three more profit someone else. Specifically, they want to minimize the profit the most favored of the three will receive.Now assume that we have the following array elements:5 6 1 4 9 3 1 2The procedure we should make appears in the following diagram:We want every time to keep the lowest value of weight and in the end to generate a result.I created the code and it works for all inputs. Is there any way to reduce the complexity from \$\mathcal{O}(n^3)\$ to \$\mathcal{O}(N)\$ if we can keep in mind that this isn't tidied up and probably needs to be.#include <stdio.h>#include <stdlib.h>#include <limits.h>int sum_array(int* array, int cnt){ int res = 0; int i; for ( i = 0; i < cnt ; ++i) res += array[i]; return res;}int main(){ FILE* input = fopen(share.in,r); int N = 0; fscanf(input,%d,&N); int *array = (int*)malloc(N * sizeof(int)); for (int i = 0; i < N; i++) fscanf(input,%d,&array[i]); fclose(input); int Min = 0; int bestA = 0, bestB = 0, bestMin = INT_MAX; int A, B; int i; for ( A = 0; A < N - 2; ++A) { for ( B = A + 1; B < N - 1; ++B) { int ProfitA = sum_array(array, A + 1); int ProfitB = sum_array(array + A + 1, B - A ); int ProfitC = sum_array(array + B + 1, N - 1 - B ); //here the values are current - valid Min = (ProfitA > ProfitB) ? ProfitA : ProfitB; Min = (ProfitC > Min) ? ProfitC : Min; if( Min < bestMin ) bestA = A, bestB = B, bestMin = Min; } } printf(%d\n, bestMin); free(array); return 0;}
Reading, processing and counting an array setting limits
algorithm;c;mathematics;dynamic programming
Here are some things that may help you improve your code.Eliminate unused variablesWithin main, the variables i, BestA and BestB are declared and some of them set, but they are otherwise unused. They should be omitted from the program.Don't abuse the comma operatorThis line doesn't really need a comma operator:bestA = A, bestB = B, bestMin = Min;It should instead be three separate statements, or (if you follow the previous advice) reduced to a single one involving bestMin.Don't cast the return from mallocThe return value from malloc or calloc is a void * and does not need an explicit cast. See this question for a thorough discussion of the reasons not to, but for me the most compelling reason is that it's simply not needed.Use const where practicalIn your sum_array routine, the values in the array are never altered, which is just as it should be. You should indicate that fact by declaring it like this:int sum_array(const int* array, int cnt)Use pointers rather than indexing for speedPointers are generally a faster way to access elements than using index variables. Speed may not a particular goal in this program but it's useful to know anyway. For example, your sum_array routine could be written like this:int sum_array(const int* array, int cnt){ int res; for ( res = 0; cnt; --cnt) res += *array++; return res;}Check return values for errorsThe calls fopen, fscanf and malloc can each fail. You must check the return values to make sure they haven't or your program may crash (or worse) when given malformed input or due to low system resources. Rigorous error handling is the difference between mostly working versus bug-free software. You should strive for the latter.Consider separating I/O from the algorithmThe I/O is done first, and then the input values are processed to find the answer. Consider separating those into to separate functions which would both make your program cleaner and also allow for better automated testing (such as automatically generating random values and then checking that the algorithm does the right things).Reconsider your algorithmRight now, the sums are recalculated many times, but this isn't strictly necessary. As you iterate through the combinations, the partitioning only moves by one value. So what you could do instead would be to keep the three sums ProfitA, ProfitB and ProfitC and then just add and subtract the particular value that moves from one brother to another.I've done some reading and it appears to me that the best you can do for complexity is \$\mathcal{O}(N^3)\$See this question and the many links from it to explain that.Think about negative numbersWhile the problem states that the shop generates profit each day, it doesn't necesarily mean that every time period is profitable. This suggests that some of the time periods could be associated with negative numbers. If we use this input:8-5 6 1 4 -9 3 1 2the program reports a max value of 1, which is correct, but you should verify that it is correct for any possible set of numbers. Consider adding an early bailoutIf it ever occurs that ProfitA == ProfitB == ProfitC (as with the values in the previous point) this must be the answer (do you see why?) so the program could exit early with that correct answer.Eliminate return 0You don't need to explicitly provide a return 0; at the end of main -- it's created implicitly by the compiler.
_softwareengineering.296594
I have too many write requests to database. Currently my app implementation is such that it makes pull call to server every 5 seconds to update the changed data. If I implement push through web sockets, does it increase the server load(mainly number of queries getting fired on mysql)? Because now on change of data (which is every second) it will send push to every client, thus every second it will now run sql query for every client and increases load on my db server ? I am using mysql, php in backend.
Does push via web sockets increases server load if I have too many write requests?
performance;websockets;client server
null
_unix.123226
In Okular, I add inline notes to a pdf file. I change the default settings forinline notes:from default font Ubuntu 13 to Ubuntu 6, and from default opacity 100% to opacity 0%. But I have to change the settings for every inline note. I wonder ifit is possible to change the settings and save the change for thefollowing inline notes?Also how can I create a inline note without the box-line boundary?How can I move a existing inline note to another place?Thanks!
Change and save pdf annotation setting in Okular?
pdf;okular
null
_unix.195380
I want to show keyboard layout and selection of language at login screen in RHEL 7.I have modified the language menu to show show keyboard layout and Region & Language settings.On clicking above menu items, applications are launched but they are not visible at login screen.I check the programs are running by taking a remote session.**gkbd-keyboard-display -l usgnome-control-center region**above two applications are executing but none is displaying at login screen(gdm).How can I bring the applications at top of display manager(gdm).I have tried raise_top() function in gnome js, but it is not working.
How do I run a application on top, in a display manager like GDM.(RHEL 7, Gnome 3.8.4)
rhel;gnome3;gdm3
null
_unix.254439
I need to find files in a given directory that have been modified in the last N days, where N is the second argument of the script. Basically, I need to give the command with 2 numbers (arguments) and run a script which would do this.Is this line of code right in order to find the files?find . -type f -mtime $2 -exec ls -l {} \;
Finding files that have been modified using a script?
scripting;find
Sort of. You don't need -exec ls -l {} \;, the find command already lists the files. If you want to list them with more details, you can use find -ls. There's nothing wrong with -exec ls ... either, it's fine if you prefer that, just not needed. The -mtime N will find files that were modified exactly N days ago. The details are in man find: +n for greater than n, -n for less than n, n for exactly n.So, to find the files modified in the last 2 days, you would runfind /target/path -mtime -2 -lsNote that find . will search in the current directory. To search in a specific directory, use a path like find /path/to/dir. If the 1st argument is the target directory, use (remember to always quote your variables):find $1 -mtime -$2 -lsAlso, note that -mtime only deals with 24 hour periods, days. You'll need to take that into account when writing your command. As explained in man find (this is for -atime but the same applies to -mtime):File was last accessed n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago.
_webmaster.100752
Question: Does the registered on date carry over to new owners of a domain name?Scenario:I was recently contacted by a very credible non-profit that had lost their domain name because they failed to renew. As I was researching the history of their site, I noticed something I didn't expect in the Whois. They first registered their domain name in 2006. The new owners picked it up in the last few months. Yet the Registered On date is 2006.
Domain name registered on date
domains;whois
First of all, it's important to note that there is no standard in how the registries stores or expose the information.Most ICANN-regulated TLDs follow the same rules, but generally speaking each registry can store and manipulate most of the registration information independently than other registries.That said, the registered on generally represents the initial registration of a domain name, regardless the ownership.Let's say A registers the domain on Jan 2006. On Mar 2010 the domain is transferred to B. The registration date will still be Jan 2006.The registration date will not change if the domain keeps being renewed, it is transferred to another owner or to another registrar.However, there is also a second scenario: the domain is registered on Jan 2006, then at some point the domain is not renewed and it expires (let's say on Dec 2010). On May 2011 the domain is then re-registered (it doesn't really matter by whom). At this point, the registration date will be May 2011.In other words, the registration date reflects the latest registration, it doesn't reflect the date the domain was registered the first time (if it was registered and then expired).
_datascience.10489
I have a classification task for people with 3 categories. I want to apply machine learning for that. I have 10 sources of data, which have the same fields (say 4: age, job title, a number of organizations, a number of followers). Data is incomplete, some fields can be missing in some profiles. The training set is limited (say, 300 examples).I have two strategies for feature engineering, and I don't know which one to use.Expand features: take 40 features (Profile 1 age, Profile 1 job title, ..., Profile 10 age, Profile 10 job title).Compact features: take 4 features, and apply some heuristics to merge the values from different profiles. Say, take age and job title which occur most frequently, take a maximum number of organizations, take a sum of numbers of followers.What strategy is generally used to give best results and why?
Expand or compact features?
machine learning;classification;feature selection
The way I see it is that your 10 sources of data, they all refer to the same set of people. Depending on the attributes, some can be expanded, some can be merged ...Attributes such as age should be unique, so it doesn't make sense to expand it to Profile 1 age, profile 2 age ... One simple way is merge them is by using the average or use max. Expanding age only add redundant data to your feature matrix, and increase its dimensionality, in most cases, this doesn't help generalization performance of your model. On the other hand, number of followers can be expanded. Depending on the data source, a guy has 10 followers on Twitter but 1000 followers on Google+ might simply mean that he barely uses Twitter. That being said, the way you pick your features or engineer new features should increase your model performance, so if expanding number of followers actually decrease Cross Validation or Test performance, compared to the one using sum of followers then you can simply use sum of followers.
_webapps.6542
In a Google Docs document, I would like to be able to specify the page margins (File Page Setup) in millimeters instead of inches. Is it possible to switch between imperial and metric units?
How to change measuring units in Google Docs?
google documents
Go to Settings Document Settings on the top right of the page and change the language to English (UK). Rulers and margins will now both be in centimetres (cm).You may need to log out and sign back in before you see the changes take effect.
_webmaster.33245
I am trying to display the files in my folder, Amir, but my table keeps displaying all of the files, . and ... How can I prevent my table from displaying .. or .? I have placed the code and a picture below.<?phpecho '<table border=1><tr> <th>Name</th> </tr>';if ($handle = opendir(amir)) { //echo Directory handle: $handle\n; //echo Entries:\n; /* This is the correct way to loop over the directory. */ while (false !== ($entry = readdir($handle))) { // echo $entry\n; echo' <tr> <td><a href='. $entry . '>'. $entry. '</a></td> </tr>'; } /* This is the WRONG way to loop over the directory. */ while ($entry = readdir($handle)) { //echo $entry\n; } closedir($handle);}echo'</table>';?>
Prevent file table from showing navigation links
php;html;directory;table
Edit: Try this. (slightly simplified from [here])<?php// open this directory $myDirectory = opendir(./);// get each entrywhile($entryName = readdir($myDirectory)) { $dirArray[] = $entryName;}// close directoryclosedir($myDirectory);//count num files$indexCount = count($dirArray);Print ($indexCount files<br>\n);//sort by namesort($dirArray);//print filesprint(<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks>\n);print(<TR><th>Filename</th><th>Filesize</th></TR>\n);// loop through the array of files and print them allfor($index=0; $index < $indexCount; $index++) { if (substr($dirArray[$index], 0, 1) != .){ // don't list hidden files print(<TR><TD><a href=\$dirArray[$index]\>$dirArray[$index]</a></td>); print(<td>); print(filesize($dirArray[$index])); print(</td>); print(</TR>\n); }}print(</TABLE>\n);?>
_unix.198561
I have installed google-chrome-stable 64 bit. But it is not opening. My system is Elementary OS Freya 64 bit.Here is the error code that generate in the terminal.[1:1:0425/175043:ERROR:image_metadata_extractor.cc(111)] Couldn't load libexif.[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: pixmap,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: pixmap,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: pixmap,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: pixmap,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: pixmap,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,[6234:6234:0425/175043:ERROR:browser_main_loop.cc(199)] GTK theme error: Unable to locate theme engine in module_path: murrine,Gtk-Message: Failed to load module canberra-gtk-moduleAborted (core dumped)I have tried to install murrine but the system showed me that this is already in newest version.
Can not open google chrome stable on elementary os freya
chrome;elementary os
null
_codereview.73887
I was wondering if someone could tell me things I could improve in this code. This is one of my first Python projects. This program gets the script of a movie (in this case Interstellar) and then finds the occurrences of all words and prints out the 20 most common words in the script.from bs4 import BeautifulSoupimport requestsfrom collections import Counter import operatorimport reclass MovieScript(object): def __init__(self, movie): self.movie = movie self.url = http://www.springfieldspringfield.co.uk/movie_script.php?movie={0}.format(movie.replace( , -)) def get_movie(self): return self.movie def get_text(self): r = requests.get(self.url) soup = BeautifulSoup(r.text) return soup def parse_text(self): text = self.get_text().findAll('div', {class:scrolling-script-container})[0].text.lower() text = re.sub(r'\W+', ' ', text) #remove puncation from the text return text.split() def find_all_occurences(self): return Counter(self.parse_text()) def get_all_occurences(self): sorted_occurences = sorted(self.find_all_occurences().items(), key=operator.itemgetter(1)) return sorted_occurencesdef Main(): db = MovieScript(interstellar) print The Movie: + db.get_movie() all_occurences = db.get_all_occurences() for i in range(-1, -21, -1): print str(-i) + . + str(all_occurences[i][0]) + -> + str(all_occurences[i][1])if __name__ == __main__: Main()
Finding the occurrences of all words in movie scripts
python;python 2.7;web scraping;beautifulsoup
null
_bioinformatics.860
We can calculate the distance between residues in a PDB file regarding different parameters like closest atoms, alpha carbon, beta carbon, centroid and etc. Which one of these parameters are better to show physical interaction between residues in a PDB file?
Best distance parameter for estimating physical interaction between residues in a PDB file
protein structure;pdb
Use a distance cutoff of 12 between C atoms.
_unix.16790
Suddenly ifconfig -a doesn't prints out the wlan0 on my Fedora14 notebook..WHY? (it worked before..)Infos:# dmesg | egrep -i wireless|wifi|broadcom|bcm4312|10:00.0[ 0.219841] pci 0000:10:00.0: reg 10: [mem 0xe8000000-0xe8003fff 64bit][ 0.220074] pci 0000:10:00.0: supports D1 D2[ 1.539203] ata1.00: ACPI cmd c6/00:10:00:00:00:a0 (SET MULTIPLE MODE) succeeded[ 1.543355] ata1.00: ACPI cmd c6/00:10:00:00:00:a0 (SET MULTIPLE MODE) succeeded# lspci | fgrep -i network10:00.0 Network controller: Broadcom Corporation BCM4312 802.11b/g LP-PHY (rev 01)# rpm -qa | fgrep -i broadcom-wlbroadcom-wl-5.100.82.38-1.fc14.noarch# lsmod | fgrep -i br## ifconfig -aeth0 ...lo ...# # uname -aLinux localhost.localdomain 2.6.35.13-92.fc14.i686 #1 SMP Sat May 21 17:39:42 UTC 2011 i686 i686 i386 GNU/Linux# lsb_release -aLSB Version: :core-4.0-ia32:core-4.0-noarchDistributor ID: FedoraDescription: Fedora release 14 (Laughlin)Release: 14Codename: Laughlin# # vi /var/log/messages:Jul 16 14:21:40 localhost NetworkManager[1173]: <info> found WiFi radio killswitch rfkill0 (at /sys/devices/platform/hp-wmi/rfkill/rfkill0) (driver hp-wmi)Jul 16 14:21:40 localhost NetworkManager[1173]: <info> WiFi disabled by radio killswitch; enabled by state fileJul 16 14:22:12 localhost NetworkManager[1173]: <info> WiFi now enabled by radio killswitchJul 16 14:24:05 localhost NetworkManager[1215]: <info> found WiFi radio killswitch rfkill0 (at /sys/devices/platform/hp-wmi/rfkill/rfkill0) (driver hp-wmi)Jul 16 14:24:05 localhost NetworkManager[1215]: <info> WiFi enabled by radio killswitch; enabled by state fileJul 16 14:24:32 localhost NetworkManager[1215]: <info> WiFi now disabled by radio killswitchJul 16 14:24:37 localhost NetworkManager[1215]: <info> WiFi now enabled by radio killswitch#
BCM4312 802.11b/g under Fedora 14 - suddenly not working
fedora;wifi
null
_scicomp.24613
The scheme is given by$$\frac{v_m^{n+1}-v_m^{n-1}}{2k} + b\frac{v_m^{n+1}+v_m^{n-1}-v_{m-1}^n-v_{m+1}^n}{h^2} = 0$$where $v_m^n$ is the numerical solution at the $m^\text{th}$ spatial coordinate and $n^\text{th}$ time step. It approximates a solution to$$\frac{\partial u}{\partial t} - b\frac{\partial^2 u}{\partial x^2} = 0$$I need to find a bound for the local truncation error. Is there a relatively quick way of doing this? I need to do this sort of thing on an exam, and I don't want to take too long, or rush it and make a mistake, possibly taking even longer.
Local truncation error of Dufort Frankel Scheme
numerical analysis
null
_codereview.41998
The function itself is just returning as void. But, the point of the posted code is not about what the function is returning. It is the code related to using T-SQL and C# to return data from a SQL database that I would like reviewed. Especially the way the using statements are structured. public void GetOffice(int syncID) { string strQry = @Select so.SyncID, so.titleFrom Offices oLeft Outer Join SyncOffices so On so.id = o.SyncIDWhere o.SyncID = @syncID; using (SqlConnection conn = new SqlConnection(Settings.ConnectionString)) { using (SqlCommand objCommand = new SqlCommand(strQry, conn)) { objCommand.CommandType = CommandType.Text; objCommand.Parameters.AddWithValue(@syncID, syncID); conn.Open(); SqlDataReader rdr = objCommand.ExecuteReader(); if (rdr.Read()) { this.OfficeName= rdr.GetString(1); } rdr.Close(); } } }
Return office details from multiple tables
c#;sql server;ado.net
First of all, kudos for using a Parameter and not concatenating the value into your T-SQL string.You're not disposing all IDisposable objects. SqlDataReader should be disposed as well. Now this makes it quite a bunch of nested using scopes, which you could rework like this: using (var connection = new SqlConnection(Settings.ConnectionString)) using (var command = new SqlCommand(sql, connection)) { command.CommandType = CommandType.Text; command.Parameters.AddWithValue(@syncID, syncId); connection.Open(); using (var reader = command.ExecuteReader()) { if (reader.Read()) { this.OfficeName = reader.GetString(1); } } }Note:Usage of var for implicit typing makes the code easier to read (IMO), if you're using C# 3.0+Disemvoweling is bad. There's no reason to call a variable rdr over reader. Use meaningful names, always.Hungarian notation is evil. There's no reason to prefix a string with str.Stick to camelCasing for locals - that includes parameters, so syncID becomes syncId.The code assumes the query only returns 1 row, but the query isn't written to explicitly select a single row. This could lead to unexpected results.Given some IList<string> results = new List<string>();: using (var reader = command.ExecuteReader()) { while (reader.Read()) { results.Add(reader.GetString(1)); } }You could then do this.OfficeName = results.Single(); (which would blow up if no rows were returned). One thing that strikes me, is that you're selecting 2 fields, but only using 1, which makes this reader.GetString(1) statement look surprising. If you don't need to select the SyncID field, remove it from your query and do reader.GetString(0) instead.Finally, the T-SQL itself:Select so.SyncID, so.titleFrom Offices oLeft Outer Join SyncOffices so On so.id = o.SyncIDWhere o.SyncID = @syncIDCould look like this:SELECT so.TitleFROM Offices oLEFT JOIN SyncOffices so ON so.id = o.SyncIDWHERE o.SyncID = @syncIDOr, in a string:var sql = SELECT so.Title FROM Offices o LEFT JOIN SyncOffices so ON so.Id = o.SyncId WHERE o.SyncId = @syncId;The line breaks make it look weird, and since it's not too long of a query, I think it would make the code better to have it on a single line.
_unix.315865
The postfix daemon has only the name master if I use netsat like this:root@myhost# netstat -tulpen| grep mastertcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 0 53191445 13640/master If I use ps I get a more verbose name:root@myhost# ps aux| grep 13640root 13640 0.0 0.0 25036 1500 11:35 0:00 /usr/lib/postfix/masterIs there a way to tell netstat to output the long name? In this case it would be /usr/lib/postfix/master.UpdateIt seems that netstat can't do it. If you know how to do this with an other tool, then this is valid question, too. (But netstat based solutions are still prefered).Update2All answers work. Thank you very much for showing your unix knowledge. But up to now the answers are far too long/complicated. Is there no easy solution? I can install any tool which is needed, but I want the usage to be simple to use.I can't give the bounty to all of you ...There are several answers which to post processing to get the needed information. Each answer uses a different way and I don't see that one solution is better than an other.Unfortunately there seems to be no unix/linux which can do this out of the box. But that's not the fault of you, who tried to help me.Unfortunately I can't give the bounty to all answers :-)I gave the bounty to the user with the least reputation points.
netstat: See process name like in `ps aux`
ps;netstat
null
_unix.96459
I have a package with several dependencies. I updated my repo with the given package and his dependencies but when I'm updating the package dependencies are not updated since the required versions are already installed. How could I force those dependencies to be updated? Here's an example to clarify it:I have installedRPM_A_1.0Who have in dependencies :RPM_B version 2.1RPM_C version 1.1Now I updated my repo so I have the following versions:RPM_A_2.0RPM_B version 2.1-12RPM_C version 1.1-12When I call yum update RPM_A the others RPMs are not updated and I would like to force those updates
Yum, force the update of dependencies
centos;yum
There's no easy way to do this with your current set up. Puppet only checks to see if RPM_A version 2.0 is installed. If it sees it is installed and at the desired version, its job is pretty much down. As for when puppet/yum updates the package RPM_A from 1.0 to 2.0, unless there's a specific dependency in RPM_A that says it needs specific newer versions of RPM_B and RPM_C, yum will not go out and fetch the new versions of RPM_B and RPM_C. It will see the packages as already installed and since you're only wanting to update RPM_A, there's no need to get the new versions of RPM_B and RPM_C.There's a few ways to do what you want:If you're the person who is compiling RPM_A, you can put the specific version requirements for RPM_B and RPM_C in the spec file so yum will go fetch them when RPM_A is updated.You can make package types for RPM_B and RPM_C and put them in your manifest and make RPM_A depend on them.Create some meta package that only exists to list the specific verions of RPM_A, RPM_B, and RPM_C that you need installed. This option is kind of dumb since it is basically the same thing as option 2 but you're doing the same work in a spec file instead of a puppet manifest.
_codereview.173874
I'm trying to solve this Play With Numbers. I have passed the test cases but, I kept getting time limit exceeded.Can someone help me improve its performance in order to pass the time limit, please?ProblemYou are given an array of n numbers and q queries. For each query you have to print the floor of the expected value(mean) of the subarray from L to R.InputFirst line contains two integers N and Q denoting number of array elements and number of queries. Next line contains N space seperated integers denoting array elements.Next Q lines contain two integers L and R(indices of the array).Outputprint a single integer denoting the answer.Time Limit:1.5 sec(s) for each input file.Result Time:Input 1: 1.999309Input 2: 1.998019#include <iostream>#include <vector>#include <math.h>using namespace std;int main() {ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);int n = 0, q = 0;cin >> n >> q;vector<int> nums(n);for (size_t i = 0; i < n; i++){ cin >> nums[i];}for (size_t i = 0; i < q; i++){ float ans = 0.0f; int leftIndex = 0, rightIndex = 0; cin >> leftIndex >> rightIndex; leftIndex = leftIndex - 1; rightIndex = rightIndex - 1; for (size_t i = leftIndex; i <= rightIndex; i++) { ans = ans + nums[i]; } ans = ans / (rightIndex - leftIndex) + 1; cout << floor(ans) << \n; } system(pause); }
Play With Numbers Programming Challenge (mean value of subarrays)
c++;programming challenge;time limit exceeded;statistics
You are running this O(R - L) loop for each query:for (size_t i = leftIndex; i <= rightIndex; i++){ ans = ans + nums[i];}You could obtain each sum in O(1) time if you stored the array as cumulative sums instead.$$\begin{align}S_1 =&\ A_1 \\S_2 =&\ S_1 + A_2 \\S_3 =&\ S_2 + A_3 \\ \vdots& \\S_N =& S_{N-1} + A_N\end{align}$$The tricky part is that \$S_N\$ could be as large as \$10^{15}\$, which requires more than 32 bits.
_unix.334155
I have a file in the following format, where, columns 6 and 7 are allele A and B. All I need to do is make changes in column 9 and onwards based on the alleles in columns 6 and 7. If column 9 field value is 0 then replace it with column 6 and if it is 2 replace it with column 7. If it is -1 then it should be left as such and 1 should be marked as col 6/col 7. This I have to do repeatedly for all the fields in each until the end of each row. Below are a few such rows pasted for your reference. Each row has some 130 fields. Probe Set ID Affy SNP ID Chromosome Physical Position Flank Allele A Allele B probeset_id SunOleic97R NC94022 S1 S2 S3 S4 S9 S11 S14 AX-147208720 Affx-152069361 Aradu.A01 5066618 TTTCTTGGCGGCATTGCTGATTTCTTATCATCCAA[A/G]CCATTCTTCTTTGTGTCAGGGTGGAATCTAAAATT A G AX-147208720 0 2 0 0 2AX-147209428 Affx-152065184 Aradu.A01 9154456 TAGCTGTTGACATGTCAATTGCTAAGGGAGAGTCC[C/T]TTGGAAAGCCCTACATCATTCATCAAATCATTCTC T C AX-147209428 2 0 2 0 0AX-147209429 Affx-152069061 Aradu.A01 9155638 TCAGCAAATGAACCTCTTAAGAAACCAATTCGGTC[A/G]TTGCTTATCACTAAGCTTTCAATCCCTTTCACTGG A G AX-147209429 2 0 2 0 0AX-147209430 Affx-152031763 Aradu.A01 9157305 CGGCGCTCTAAAATCCAGATAACAACTCCAACAAC[C/T]AAGAAAAAGGTTGCTGTGACAAACCACATCATTGG T C AX-147209430 2 0 2 0 0AX-147209432 Affx-152067683 Aradu.A01 9205209 CCCTTAATTGGGGAAGAGAGTTGTTCCACTGTGAG[A/G]ATTGATGTTAGGCTTGCAATGTAGCTTGAATTCAG A G AX-147209432 2 0 2 0 0AX-147209600 Affx-152035192 Aradu.A01 9873259 CTCCTTCTCTCGGTTTCCAAGACAAAAGAAAGACA[A/G]ATATCTTTTAAGATCTTCCTCAGTTTTGTTCTCCC A G AX-147209600 2 0 0 0 0AX-147209601 Affx-152067325 Aradu.A01 9873427 TGGCCACATTGGAACCACAACATACACAGTGAAGT[C/T]TTGCTTAGCTTTAATCTTGCTAACAATTTTAAGTG T C AX-147209601 2 0 0 0 0AX-147209615 Affx-152066978 Aradu.A01 9974460 AAAACTCACAATTCTTCTTTGATGATCTGAGTCCT[C/T]TCCATTTGACAATTTAGCATCCACCACCACAATCT T C AX-147209615 0 2 2 2 2I initially tried to replace the value of field in column 9 based on its values using:awk '{if ($9 == 0) print $9 == $6}; 1' file.txt |less -S It did not do any change to the original file.Can anyone please help me!
replace values of fields in each row with values in previous fields until the end of each row
awk
null
_webapps.13737
I was operating a web site profile using Analytics.When I changed my site domain, I add new profile and deleted old one.I want to restore the old one now. No way?
Can I restore Google Analytics website profile which has been removed?
google;google analytics
Once you delete it, it's gone.
_cstheory.25907
I've been interested in looking into the area of de-amortization recently (i.e. finding data structures with matching worst-case and amortized running time bounds, or exhibiting lower bounds against matching the amortized complexity of certain operations with a worst-case bound). The only reference I've been able to find so far is a survey from COCOON by S.R. Kosaraju and M. Pop.Are there any other good surveys or set of papers to read regarding de-amortization?
References for de-amortization
reference request;ds.data structures;lower bounds;amortized analysis
null
_webmaster.59450
I found in a video zz.zz.zz.zzz.com being as a URL and streaming the content from this. attached is the URL fro information. My question is: is there some URL like this zz...? Is this a localhost / a domain hostname ?
Is zz.zz.zz.zzz a local host or a domain Hostname?
domains;web hosting;url
null
_codereview.52495
The following program is a demonstration of variant and double visitation used to obtain double dispatch between the elements of two inhomogeneous containers. Most of the work is done at compile time. What do you think about it compared to the dynamic version in explained in Wikipedia?boost::variant does not employ variadic templates and has a hand coded limit to 20 different types which can be easily extended to 50 but not beyond. Is it a crazy idea to use this pattern (with an appropriate variant implementation) with more than 50 types, say 100 spaceships and 10 different asteroids or so?#include <iostream>#include <vector>#include boost/variant.hppusing std::cout;using std::endl;////////// some basic objectsclass SpaceShip {};class ApolloSpacecraft : public SpaceShip {};class Asteroid {public: void CollideWith(SpaceShip&) { cout << Asteroid hit a SpaceShip << endl; } void CollideWith(ApolloSpacecraft&) { cout << Asteroid hit an ApolloSpacecraft << endl; }};class ExplodingAsteroid : public Asteroid {public: void CollideWith(SpaceShip&) { cout << ExplodingAsteroid hit a SpaceShip << endl; } void CollideWith(ApolloSpacecraft&) { cout << ExplodingAsteroid hit an ApolloSpacecraft << endl; }};////////// visitorstruct CollideVisitor : public boost::static_visitor<void> { template <typename A, typename S> void operator()( A & a, S & s) const { a.CollideWith(s);}};////////// demoint main() { std::vector<boost::variant<Asteroid,ExplodingAsteroid>> asteroids; asteroids.emplace_back(Asteroid()); asteroids.emplace_back(ExplodingAsteroid()); std::vector<boost::variant<SpaceShip,ApolloSpacecraft>> spaceships; spaceships.emplace_back(SpaceShip()); spaceships.emplace_back(ApolloSpacecraft()); for (auto & a : asteroids) { for (auto & s : spaceships) { boost::apply_visitor(CollideVisitor(), a, s); } } return 0;}
Multiple dispatch with variant and multi visitation in C++
c++;c++11;template;boost;variant type
null
_softwareengineering.155168
I bury a good deal of my ideas for fear that I don't know enough about scaling web applications and high-traffic websites. That said, I'd like to know of any general topics to research in order to ensure that your web app doesn't break / slow down when you start getting to Twitter-level traffic.I'm looking for research topics with, preferably, additional resources.For example: Make sure you optimize SQL queries (see High Performance MySQL Optimization)
Research topics for starting and optimizing a high-traffic website
optimization;research
Likely SuspectsMost likely, the things you want to pay attention to are:your caching tier,your database tier,your general architecture's design (if it's not designed to scale, it just won't).Further ReadingWords of caution about the resources below:Some are generic resources, others are specific to one stack or language but still provide insight on the types of issues to deal with and how to (try to) address or mitigate them.Some provide general information of scalability.Some give only hints on basic pipeline and programming optimizations.Some are sponsored or hosted by industry-actors, in which case conclusions and comparisons may or may not be accurate and/or impartial.Research papersSome papers' links may be unaccessible for you if you don't have a subscription to some publication networks.Dynamic Load-Balancing on Web-Server Systems [PDF]Web-Search for a Planet: the Google Architecture [PDF]High-Performance Site Design Techniques [PDF]Scalability Issues for High-Performance Digital Libraries on the Web [PDF]Improving Performance on the Internet [PDF]Web Server Farm in the Cloud [PDF]Observations on Tuning a Java Application for Performance and ScalabilityThe Akamai Network: A Platform for High-Performance Web-Applications [PDF]BooksBuilding Scalable WebSites (Henderson, 2006)Building Scalable and High-Performance Java Web-Applications (Barish, 2002)Handbook of Cloud Computing (Furht, Escalante, 2010)High-Performance WebSites: Essential Knowledge for Front-End Engineers (Souders, 2007)Architecture of Reliable Web-Applications Software (Radaideh, Al-Ameed, 2007)Articles, Blogs and Web ResourcesPerformance Tuning and Optimization of High-Traffic WebSitesThe Ultimate Guide to Web Optimization (Tips and Best Practices)A herd of resources on Google's Make The Web Faster effortlike these tutorialsScaling Python for High-Load WebSitesHandling Web-Servers of High-Traffic WebSitesHow to Scale PHP ApplicationsTYPO3 Scalability for High-Traffic WebSitesScaling Twitter: Making Twitter 10,000 Percent FasterScaling a High-Traffic Application: Our Journey From Java to PHPNotes on the Google Talk ArchitectureFamous Last WordsWhile I can understand your original intuition that you should bury some projects out of fear that they won't adapt well and survive, I think that's the wrong approach. While the build it and they will come approach can be wrong, the build it only once it's perfect counter-part can be just as wrong.You don't know if your projects will reach the critical mass where they actually need to care about these issues, so why not build them anyways?Maybe you'll fail at first, but then you'll have learned and your next product will fare better. It's better to try it this way than to one day really have to dive in the deep end of the pool without a net, for a real product. So go ahead and give these ideas a chance.While it's true that it's hard to make an application scalable when it hasn't been originalyl designed to be, at least you'll have an application that needs to be modified for scalability. In my book it's better than no application at all.
_unix.77296
When handling log files, some end up as gzipped files thanks to logrotate and others not. So when you try something like this:$ zcat *you end up with a command line like zcat xyz.log xyz.log.1 xyz.log.2.gz xyz.log.3.gz and then with:gzip: xyz.log: not in gzip formatIs there a tool that will take the magic bytes, similar to how file works, and use zcat or cat depending on the outcome so that I can pipe the output to grep for example?NB: I know I can script it, but I am asking whether there is a tool out there already.
Is there a tool that combines zcat and cat transparently?
text processing;cat;gzip
zlessIt seems a pity about zcat, as libz has an API that supports reading from both compressed and uncompressed files transparently. But the manpage does say that zcat is equivalent to gunzip -c.
_webapps.4946
Weekly, I tend to browse the Explore section or sometimes basic searches to see if I can reproduce any shots. To keep things realistic, I do not own a DSLR so a lot of shots are ignored. Is it possible to filter searches so that I can only get a certain camera type.Where the camera type is displayed in the Additional information section. I know there is the Camera Finder Setup (e.g. photos with iPhone ) How about the reverse ? Searching photos then applying the filter ? The reason for this is that say I wanted to check only Creative Commons-licensed content , I would select this in advanced search... but then I lose the camera filter. (maybe I am missing a step)
Is there a way to search Flickr photos by camera type?
flickr
The advanced search does seem to lose the camera finder filter. If you copy the URL argument for the camera type;&cm=apple%2Fiphone_3gsand paste it in at the end of your CC licensed software searchhttp://www.flickr.com/search/?q=tree&l=cc&ss=0&ct=0&mt=all&w=all&adv=1&cm=apple%2Fiphone_3gsYou can get the results you require. A bit hacky but it does work.Hope this helps.
_webmaster.104631
Some days ago I used some traffic generator sites to increase traffic for my site. But after doing log out from this sites. The traffic which is coming to my site from these sites should stop, but still, traffic is coming and this traffic showing as organic traffic in analytics under not provided keywords. I also read about how to identify fake traffic. The answer is if your getting it from the same location again n again or having high bounce rate so it may be fake traffic. But there is no high bounce rate also getting traffic from a different location but most traffic is from the USA. For reference, i'm attaching my GA audience overview of today. In blogger dashboard under traffic sources Referring URLs and Referring sites are showing from google.com. Really not getting is it fake traffic or real traffic. Also checked Exclude all hits from known bots and spiders in analytics setting. I heard about captcha setting so can I add CAPTCHA before entering my site? So it will avoid bots. Please any solution as soon as possible I want to avoid it.
Getting too much organic traffic? how to identify is it real or fake?
seo;google analytics
The best way to check weather organic traffic is real or fake, I use mostly Google search console, why? Because it is not normal analytics like Google analytics which track something when someone land in your website (including spam bot) or using http headers(Which is easy to spoof for many spammer).To make it fake search console analytics report, your competitor or any third party tool have to search that phrase in search and also have to click on search result, which is not easy and required more CPU resource. At this time there are some tool which track keyword position, but they just check the position, and does not click on search result pages. So you will get better assumption with number of impression and number of clicks from search analytic report.To see your search analytics report go to your search console, click on search traffic and finally click on search analytics. Or simply click here and choose your web properties. Hope you have already added your website on search console.
_cs.60152
I'm encountering a dynamic modelling problem. I've tried a lot of methods but it seems that all of them are of time complexity O(MNK), like the basic algorithm. I wonder if any guys can make some suggestions about any possible improvement of my time complexity?A dynamic model is defined as follows: State(n,m,t) is the state of the node (n,m) at time t. This value is either 0 or 1. A neighbourhood of node (n,m) consists of 8 nodes around it. Denote LifeAround(n,m,t) as the number of nodes in the neighbourhood of (n,m) at time t that are in state 1. Evolution: If state(n,m,t)=0 (dead) then state(n,m,t+1)=1 (alive) iff LifeAround(n,m,t)=3 If state(n,m,t)=1 (alive) then state(n,m,t+1)=0 (dead) iff LifeAround(n,m,t)<2 or LifeAround(n,m,t)>3a. Write a function that starts with the given state and develops the model through k steps on a fixed grid with zeros outside the boundary. b. Write a similar function that has no boundary.
Dynamic Modelling improvement suggestions
arrays
null
_cs.53274
This is what I have so far1 1 0 0Switch values by 2s Complement0 0 1 1+ 10 1 0 0
Is it possible to compute -12 (decimal) in 4 bits binary
computer architecture;arithmetic
No, it's not possible, at least using the standard representations. An unsigned $n$-bit number can represent any integer in the interval $[0, 2^{n} - 1]$. A signed $n$-bit number using two's complement can represent integers in the interval $[-2^{n - 1}, 2^{n - 1} - 1]$. With $n = 4$, that gives an interval of $[-8, 7]$, which obviously doesn't include $12$. One's complement can use $n$ bits to represent the interval $[-(2^{n - 1} - 1), 2^{n - 1} - 1]$, giving the interval $[-7, 7]$ for four bits, which also doesn't work. You'd have to contrive a nonstandard representation to represent $-12$ in four bits.
_webmaster.11961
I am trying to layout a list vertically that has a checkbox, image and description....see here for an example...http://www.sk8loc8.com/deposit/list.jpgAs you can see the images look a bit too high and i would like them to 'sink' a little to line up with the text and checkbox. i put them in a table to get around the issue, but it acts just the same as an unordered list and the image sits higher.i tried using valign=top for the text and checkbox but this doesnt seem to work, neither does adding a bottom-margin to the text, or adding a top-margin to the image.does anyone have any advice? here is the markup...<table id=mapLegend class=mapLegendTable border=1 cellpadding=5px> <tr title=A skatepark we know exists> <td valign=top><input type=checkbox /></td> <td><img src=assets/images/gIconRedDot.png alt=Skatepark /></td> <td valign=top>Park</td> </tr> <tr title=A skatepark we strongly recommend> <td valign=top><input type=checkbox /></td> <td><img src=assets/images/gIconYellowStar.png alt=Recommended Skatepark /></td> <td valign=top>Recommended Park</td> </tr> <tr title=A Skater Owned Shop> <td valign=top><input type=checkbox /></td> <td><img src=assets/images/gIconSkateshop.png alt=Skate Shop /></td> <td valign=top>Skate Shop</td> </tr> <tr title=A skatepark we do not know anything about. It MAY exist but we do not know for sure> <td valign=top><input type=checkbox /></td> <td><img src=assets/images/gIconUnconfirmedSpot.png alt=Unconfirmed Skatepark /></td> <td valign=top>Unconfirmed Park</td> </tr> </table>and the old code, as an unordered list...<ul id=mapLegend> <li id=parkIcon title=A skatepark we know exists> <img src=assets/images/gIconRedDot.png alt=Skatepark /><span>Park</span></li> <li id=recommendedParkIcon title=A skatepark we recommend> <img src=assets/images/gIconYellowStar.png alt=Skatepark />Recommended Park</li> <li id=shopIcon title=A Skater Owned Shop> <img src=assets/images/gIconSkateshop.png alt=Skatepark />Skate Shop</li> <li id=unconfirmedParkIcon title=A skatepark we do not know anything about. It MAY exist but we do not know for sure> <img src=assets/images/gIconUnconfirmedSpot.png alt=Skatepark />Unconfirmed Park</li> </ul>
Aligning Images in Tables and Lists
html;images;table
The list will do. You need to apply the 'vertical-align:top' style to the images. I usually use 'middle' for this which looks a little better for one-liners.This can be done in your image direction, as in:<img src=assets/images/gIconRedDot.png alt=Skatepark style=vertical-align:top/>Or by CSS:#mapLegend li img {vertical-align:top;}
_codereview.20129
public class NANDFunction : FunctionInfo{ public override string Name { get { return NAND; } } public override int MinArgs { get { return 2; } } public override int MaxArgs { get { return 2; } } public override object Evaluate(object[] args) { bool arg0 = CalcConvert.ToBool(args[0]); bool arg1 = CalcConvert.ToBool(args[1]); return ((arg0 != arg1) || (!arg0 && !arg1)); }}What do you think of this code?
Possible issues and best practices for this piece of code
c#
You may want to add some additional validation around how many arguments you're expecting (since you know via MinArgs and MaxArgs). You can also eliminate having to create an object array explicitly in the caller by using the params keyword (make sure you do it in the declaration in FunctionInfo as well). Lastly, if this class is intended to be non-inheritable (unlike FunctionInfo), mark it as sealed:public sealed class NANDFunction : FunctionInfo{ public override string Name { get { return NAND; } } public override int MinArgs { get { return 2; } } public override int MaxArgs { get { return 2; } } public override object Evaluate(params object[] args) { if ((args.Length < this.MinArgs) || (args.Length > this.MaxArgs)) { throw new ArgumentException(An insufficient number of arguments were passed.); } bool arg0 = CalcConvert.ToBool(args[0]); bool arg1 = CalcConvert.ToBool(args[1]); return (arg0 != arg1) || (!arg0 && !arg1); } }
_softwareengineering.343734
We have a Java application that uses a live 3rd party data feed. There are several steps in our application and in each step the application reaches out to the 3rd party data feed with the current state of the user flow and received back the data for the current step.Recently, we have noticed that there have been problems with the data in the feed. Because of this our application barfs and users cannot proceed. Even though the application handles the error, our priority is to let user complete the flow.In order to do that I have been thinking of starting to take snapshots of the feed and version them, so that in case the external party feed has problem we can switch to our internal snapshot till the external feed is fixed.Does this makes sense? I am wondering if this is a good strategy or there can be something else we can do. Also, are there any tools that lets you keep snapshots of data?
How to mitigate third party data feed issues?
java;data;3rd party
null
_unix.317175
Why root lose permission to run 1st level symlink /bin/planet and 2nd level symlink /tmp/earth, except symlink target /tmp/sun at the end ? Instead ordinary user no problem to run 3 of them:xiaobai@dnxb:~/note$ echo -e '#!/bin/bash\necho hack the planet' > /tmp/earthxiaobai@dnxb:~/note$ chmod +x /tmp/earthxiaobai@dnxb:~/note$ sudo ln -s /tmp/earth /bin/planetxiaobai@dnxb:~/note$ sudo file /bin/planet/bin/planet: symbolic link to /tmp/earthxiaobai@dnxb:~/note$ sudo ls -la /bin/planetlrwxrwxrwx 1 root root 10 Oct 18 18:55 /bin/planet -> /tmp/earthxiaobai@dnxb:~/note$ planethack the planetxiaobai@dnxb:~/note$ echo -e '#!/bin/bash\necho crack the planet' > /tmp/sunxiaobai@dnxb:~/note$ chmod +x /tmp/sunxiaobai@dnxb:~/note$ rm /tmp/earthxiaobai@dnxb:~/note$ ln -s /tmp/sun /tmp/earthxiaobai@dnxb:~/note$ ls -la /bin/planet lrwxrwxrwx 1 root root 10 Oct 18 18:55 /bin/planet -> /tmp/earthxiaobai@dnxb:~/note$ sudo ls -la /bin/planet lrwxrwxrwx 1 root root 10 Oct 18 18:55 /bin/planet -> /tmp/earthxiaobai@dnxb:~/note$ file /bin/planet /bin/planet: symbolic link to /tmp/earthxiaobai@dnxb:~/note$ sudo file /bin/planet /bin/planet: broken symbolic link to /tmp/earthxiaobai@dnxb:~/note$ planetcrack the planetxiaobai@dnxb:~/note$ sudo planetsudo: unable to execute /bin/planet: Permission deniedxiaobai@dnxb:~/note$xiaobai@dnxb:~/note$ sudo /tmp/earth sudo: unable to execute /tmp/earth: Permission deniedxiaobai@dnxb:~/note$ sudo /tmp/sun crack the planetxiaobai@dnxb:~/note$ /tmp/suncrack the planetxiaobai@dnxb:~/note$ /tmp/earth crack the planetxiaobai@dnxb:~/note$ stat /tmp/earth File: '/tmp/earth' -> '/tmp/sun' Size: 8 Blocks: 0 IO Block: 4096 symbolic link Device: 807h/2055d Inode: 29 Links: 1 Access: (0777/lrwxrwxrwx) Uid: ( 1000/ xiaobai) Gid: ( 1000/ xiaobai)Access: 2016-10-18 18:59:15.949297618 +0800Modify: 2016-10-18 18:56:56.849295531 +0800Change: 2016-10-18 18:56:56.849295531 +0800 Birth: -xiaobai@dnxb:~/note$ stat /tmp/sun File: '/tmp/sun' Size: 34 Blocks: 8 IO Block: 4096 regular fileDevice: 807h/2055d Inode: 30 Links: 1Access: (0755/-rwxr-xr-x) Uid: ( 1000/ xiaobai) Gid: ( 1000/ xiaobai)Access: 2016-10-18 18:59:36.489297926 +0800Modify: 2016-10-18 18:56:45.253295357 +0800Change: 2016-10-18 18:56:49.377295419 +0800 Birth: -xiaobai@dnxb:~/note$ The only difference from stat output is l, but it's normal because it's a symlink. So what's the real reason root lose the permissions except final symlink target ? Another weird thing is sudo file /bin/planet said it's a broken symlink but file /bin/planet (ordinary user) said it's a symbolic link to /tmp/earth.[UPDATE]After i do sudo sysctl -w fs.protected_symlinks=0, no such problem anymore.
Why root lose permission of 1st and 2nd level symlink?
permissions;root;symlink;tmp;ln
null
_opensource.4682
I'm working on building a proprietary application that I would like to release as PGP-signed Debian packages.I heard I might be forced to release the source to my proprietary application simply due to the fact that it would be signed by GnuPG, which is covered under GPLv3 containing the Tivoization clause.Is this true? It is my understanding that the license for GnuPG would enforce disclosing any modifications to GnuPG itself, not the use of GnuPG to apply a signature to an arbitrary object. Saying that the object I'm signing with GnuPG is now also open source makes no sense to me.Can someone clarify?Thank you!
Is GPLv3 violated by releasing proprietary code as a GnuPG-signed package?
licensing;gpl 3;proprietary code;intellectual property
In general, the GPL does not affect the output of a GPL-licensed program. From the GPL FAQ:Is there some way that I can GPL the output people get from use of my program?For example, if my program is used to develop hardware designs, can I require that these designs must be free?In general this is legally impossible; copyright law does not give you any say in the use of the output people make from their data using your program. If the user uses your program to enter or convert her own data, the copyright on the output belongs to her, not you. More generally, when a program translates its input into some other form, the copyright status of the output inherits that of the input it was generated from.That is sufficient to show that the output of GnuPG is not automatically licensed under the GPL, so distributing such output within another work does not impose GPL requirements.In your case, there is a further reason that a signature would not impose GPL requirements: I sincerely doubt that copyright law could ever recognize a cryptographic signature as a creative or derivative work. Cryptographic signing (which, as one of its steps, includes hashing) is a massively lossy transformation that completely destroys the original content of the work and is not designed to be reversed. As such, even if the GPL applied to the output of a GPL signing program (and again, it does not, per the FAQ item above), the output would not be eligible for copyright, so any copyright license such as the GPL would have no effect.Finally, tivoization only applies ifyou are distributing a GPLv3-licensed program, andthe program is intended to run on a specific hardware device, andthe hardware of that device refuses to run an incorrectly signed executable.As far as you've described your situation, absolutely none of those criteria apply to your case.
_unix.369406
I'm trying for many hours to clean my csv file using (AWK or SED)here is how looks the csv file:id,name,contact-type,contact1,toto corp,tel,+1234567891,toto corp,fax,+1987654321,toto corp,site,totocorp.com2,Namek corp,tel,+143776785632,Namek corp,fax,+198673345652,Namek corp,site,Namekcorp.comand I would like to have this output:id,name,tel,fax,site1,toto corp,+123456789,+198765432,totocorp.com2,Namek corp,+14377678563,+19867334565,Namekcorp.comThank you for the hand guys!
Parsing CSV using AWK or SED
text processing;awk;sed;cvs
null
_cs.33493
Let $W = \{w_1,w_2,...w_n\}$ be a set of integer weights. Let $B = \{b_1,b_2,...b_m\}$ be a set of buckets, with $m \leq n$. Let $T(b_j)$ represent the total weight present in bucket $b_j$, which is the sum of all the weights present in $b_j$.What is the optimal way to distribute all the weights $w_i$ into the buckets $b_j$ to minimize the metric $\max T(b_j) - \min T(b_k)$ for some $j,k \leq n$?I know that this seems to be a variant of the bin packing problem and I have found some heuristics such as the ones described here.But is this problem really equivalent to the one in the link? My problem does not have an upper limit on the capacity of each bucket, which makes it quite different from the routine bin-packing problem.If anyone has an optimal solution and if it's NP-hard, an approximation algorithm, I'd love to hear it.
Balanced Weight Distribution in Bins/Buckets
algorithms;approximation;knapsack problems
null
_cs.43088
Find the 10 top most occurring strings in a huge array of Strings.Since the array is huge, it is not possible to load it in memory completely.My idea is to parse the arrays one by one and put the strings in a hash table with string as key and occurrence count as value. But this would take too much memory.Is there any other optimized solution? Given that we only care about top 10 keys.
Find the 10 top most occurring strings in a huge array of objects
algorithms;space complexity;streaming algorithm
null
_webapps.108786
On their website they announce a free machine:However, when I try to get it, it is not free: So, how can I get this free machine?
How to get Google Compute Engine free tier?
google cloud
null
_unix.213707
This is related to my previous question.Given that I can find the statistics of IPC channels in my Linux system (e.g. sys V IPC), how can I find which processes are using certain IPC channel (sending via channel; receivers are usually mentioned in command outputs). For example, ipcs gives me a list of shared mem id's on the machine. How can I find which processes are using that shared memory ?The other IPC's I am interested in (these are the commands I used to find the statistics):Pipes: lsof | grep pipeUNIX Domain sockets: netstat -n
Linux - check processes using IPC channels
ipc
null
_webmaster.53090
On a search results page, I want to show related search links. These links are generated by user searches, that aren't already part of the site's regular links. This, in effect was to increase the number of links on the site.I had created a small widget that showed ten related search links. The site took a negative hit, and I'm guessing this was because on each page, ten new links would appear, and essentially creating thousands of new pages. I want to be able to dynamically add some user-generated searches to the site without taking an SEO hit. Obviously I can no-follow those links, but that then defeats the purpose.What's the best way to go about this?
How to properly use related search links on sites without taking a negative SEO hit?
seo;negative seo
null
_softwareengineering.252884
I'm writing a huffman encoding program in C. I'm trying to include the least amount of information in the header as possible, I know the simplest way to decompress the file in the header would be to store the frequencies of each character in the file, but for a large file with 256 characters it would take 2304 bytes ((1 byte for character + 8 bytes for long frequency) * 256), which I don't think is optimal. I know I can reconstruct a tree from a preorder scan and an inorder scan of it, but that requires having no duplicate values. That is bad because I now have to store each node in the tree (in a huffman tree: n*2 - 1 with n being the number of unique characters), twice, having each node be a long value (which could take ((256*2 - 1) * 2) * 8 = 8176 bytes.Is there a way I'm missing here, or are those my only options?Thanks.
Reconstructing a huffman tree using minimal information in the header
c;huffman encoding
There are 2 separate problems, store the topography and assign the leaf nodesAssigning the leaf nodes can be done by storing the characters in in a predefined order so it can be extracted as needed.Storing topography can be done by having a bit vector with 2 bits per parent node in the previous layer where 1 represents a compound node and 0 represents a leaf nodeso first there is 1 bit for the root which is 1 and the next 2 bits will represent the next level downto build the tree using the node{char value; node* left, right;} setup will be:char[] chars;//prefill with the other arrayint charIndex = 0;node root;vector<node*> toBuild(root);while(!toBuild.empty()){ node n = toBuild.popFront(); bool bit = grabBit(); if(bit){ n.left = new node; toBuild.pushBack(n.left); }else n.value = chars[charIndex++]; bit = grabBit(); if(bit){ n.right = new node; toBuild.pushBack(n.left); }else n.value = chars[charIndex++];}return root;This is 2*n bits in the topography plus the permutation which is O(log n!) at the minimum.
_unix.169598
I use VIM's dictionary completion feature very frequently, yet have found it unhelpful when it comes to 'specialized' terminology, in my case German philosophical terms. I would now like to create my own dictionary file filled with philosophical terms that I can feed VIM with. How could one create such a file? I was thinking Wikipedia would be a good place to start? Or extracting all <h3> headers from this site?Looking forward to any suggestions!
Creating specialised dictionary file for VIM (from Wikipedia?)
vim;dictionary
For now I've started a GitHub project for anyone interested.
_cs.3098
How can I prove that a set is complete for $\Pi_2$ complete? Can you give me an example proof? Say for $All_{TM}$ = Turing machines whose accepted language is all strings?
How to show a set is $\Pi_2$ complete
computability
null
_unix.357890
I tried several ways to get logged into freelancer.comI am trying to achieve this using cURL but it is not saving the cookie but from the output:[root@lnc free]# sudo bash free.sh Warning: /root/.curlrc:1: warning: '--' had unsupported trailing garbage* About to connect() to www.freelancer.com port 443 (#0)* Trying 54.225.216.189...* Connected to www.freelancer.com (54.225.216.189) port 443 (#0)* Initializing NSS with certpath: sql:/etc/pki/nssdb* CAfile: /etc/pki/tls/certs/ca-bundle.crt CApath: none* SSL connection using TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256* Server certificate:* subject: CN=*.freelancer.com,OU=Domain Control Validated - RapidSSL(R),OU=See www.rapidssl.com/resources/cps (c)15,OU=GT15355554* start date: May 10 07:58:28 2015 GMT* expire date: May 11 14:18:43 2017 GMT* common name: *.freelancer.com* issuer: CN=RapidSSL SHA256 CA - G3,O=GeoTrust Inc.,C=US* Server auth using Basic with user 'potato'> GET /login HTTP/1.1> Authorization: Basic bWFydGluccAwccpccccpccMccA==> User-Agent: curl/7.29.0> Host: www.freelancer.com> Accept: */*> < HTTP/1.1 200 OK< Server: nginx< Date: Sun, 09 Apr 2017 04:19:52 GMT< Content-Type: text/html; charset=UTF-8< Transfer-Encoding: chunked< Connection: keep-alive< Vary: Accept-Encoding< Age: 0< X-Cache: MISS< Accept-Ranges: bytes< Strict-Transport-Security: max-age=172800< X-Frame-Options: SAMEORIGIN< { [data not shown]* Connection #0 to host www.freelancer.com left intactfree.shcurl -s -v -L -u potato:fried 'https://www.freelancer.com/login' >> /home/free/file.htmlI am trying to get logged in then go to my dashboard and collect some data.But it does not redirect me neither..
Login with curl from a bash script is not saving cookies
login;curl;ssl
null
_unix.97796
After posting my question here, Add xinput to the start up secuence of LXDEI got no answer so here it is. I have these 2 commands:xinput --set-prop Razer Razer DeathAdder Device Accel Constant Deceleration 4 xinput --set-prop Razer Razer DeathAdder Device Accel Velocity Scaling 1 Which I want to run on start up. I am using zsh shell.I tried putting these 2 commands /etc/rc.local, .zshrc, .zlogin, also in /etc/xdg/lxsession/Lubuntu/autostart , also in /.xinitrc and /etc/X11/xinit/xinitrc but nothing seems to happen. Could somebody let me know what is going on please, and why none of these is working?Here is my current /etc/X11/xinit/xinitrc file (ignore the numbers (vim)): 1 #!/bin/sh 2 3 # /etc/X11/xinit/xinitrc 4 # 5 # global xinitrc file, used by all X sessions started by xinit (startx) 6 7 # invoke global X session script 8 . /etc/X11/Xsession 9 10 /usr/bin/xinput --set-prop Razer Razer DeathAdder Device Accel Constant Deceleration 4 11 /usr/bin/xinput --set-prop Razer Razer DeathAdder Device Accel Velocity Scaling 1 Could somebody explain to me what is goign on ? Why nothing is happening?I tried everything, rebooted, and the $%^&* commands will just not run.Any help please?
Start up commads in Lubuntu 2
ubuntu;zsh;oh my zsh;lubuntu
null
_webapps.76037
I am creating a form to sign up members to a summer camp. I have set up a repeating section, so if parents have more then one child attending they don't have to start from scratch. My problem is that it cost $60 for the first kid and $30 for each additional kid. I know I can do a drop down menu to ask the cost for each kid, but I rather it automatically calculate the costs to eliminate errors. I can't figure how to do a conditional to know that camper 1 has been added ($60) and to only charge $30 each for additional camper ie camper 2 , camper 3 etc.The cost should be $120 for three campers.Thanks.
Repeating Section Cognito Forms with variable costs
cognito forms
null
_unix.273108
Compare the following two commands:mysqldump database_name --hex-blob -uuser_name -p | tee database_name_tee.sqlmysqldump database_name --hex-blob -uuser_name -p > database_name_out.sqlIf I run the first, on completion I see the following on my terminal:$ 62;c62;c62;c62;cWhere does this come from? Does it suggest that something has gone wrong somewhere in the process? Are these control characters which are being output for some reason?U+0C62 is Telugu Vowel Sign Vocalic L, which Im pretty sure is not part of my data, so I dont think this is Unicode. Anyway, the sequence seems to be not c62 but 62;c. This could be a control character of some kind. And whatever is causing it is included in the output file. If I later cat either database_name_tee.sql or database_name_out.sql, I again see this sequence once the cat is complete.tail database.sql -n200 does not produce this output; -n300 produces just $ 62;c62;c; and -n400 produces $ 62;c62;c62;c62;c. So whatever is causing this is distributed throughout the file.Mucking around with head and tail, I found one of the culprits: a single line which, when saved to a separate file and printed with cat, produces $ 62;c62;c. My problem is that this single line is 1043108 bytes.(The generated SQL file is perfectly fine, and runs without errors. I dont think that this has anything to do with MySQL per se.)Im running the initial mysqldump on a CentOS server, and am seeing the same effects from cat on both the server itself and my Ubuntu desktop, so this seems to be a general Bash thing.od -c problem_line produces 65174 lines of output, so I cut it down to a smaller section which demonstrates the same output (also available as a plain hexdump).
What does it mean when characters appear on the prompt after an operation?
bash;escape characters
null