id
stringlengths 5
27
| question
stringlengths 19
69.9k
| title
stringlengths 1
150
| tags
stringlengths 1
118
| accepted_answer
stringlengths 4
29.9k
⌀ |
---|---|---|---|---|
_unix.289599
|
Is php5.5 or php5.6 Available for CentOS 7?
|
PHP5.5 or PHP5.6 Availability for CentOS 7
|
centos;software installation;php5
| null |
_vi.7447
|
I noticed 3 problems with my Vim terminal setup on Ubuntu which can be illustrated by the following picture of my current Vim. I get the same look with a lot of airline-themes (e.g. molokai, jellybeans, dark, etc.)The first problem is that I'd like to have colors with my status bar which are clearly not appearing.Also I don't know if the symbols of the status bar are correct, because the arrows do not look like the ones shown below.Finally the upper bar indicating the buffers or the tabs clearly do not look like mine.Also, here are some potentially useful informationsI installed the powerline patched Mac OS font Monaco. This helped me to replace some weird symbols and get the ones shown above.The only airline theme that was different was base16.I tried changing the Vim colorscheme to different ones, but it didn't solve anything.Finally here is a copy of my .vimrcset encoding=utf8set rtp+=~/.vim/bundle/Vundle.vimlet g:ycm_global_ycm_extra_conf = '~/.vim/bundle/YouCompleteMe/third_party/ycmd/cpp/ycm/.ycm_extra_conf.py'call vundle#begin()Plugin 'gmarik/Vundle.vim'Plugin 'https://github.com/Valloric/YouCompleteMe.git'Plugin 'https://github.com/scrooloose/nerdtree.git'Plugin 'https://github.com/tpope/vim-surround.git'Plugin 'https://github.com/terryma/vim-multiple-cursors.git'Plugin 'dkprice/vim-easygrep'Plugin 'vim-airline/vim-airline'Plugin 'vim-airline/vim-airline-themes'Plugin 'MarcWeber/vim-addon-mw-utils'Plugin 'tomtom/tlib_vim'Plugin 'garbas/vim-snipmate' Optional:Plugin 'honza/vim-snippets'call vundle#end()filetype plugin indent onfiletype plugin onfiletype indent onsyntax on air-linelet g:airline_powerline_fonts = 1highlight Pmenu ctermfg=15 ctermbg=4 guifg=#ffffff guibg=#0000fflet g:ycm_show_diagnostics_ui = 1let g:ycm_enable_diagnostic_highlighting = 0set numberset autochdirset rulerset ts=4set expandtabset shiftwidth=4set cursorlineset showmatchset ignorecaseset showcmdset list listchars=tab:\ \ ,trail: set timeoutlen = 200set nofoldenableset wildmode=fullset laststatus=2set completeopt-=previewmap <Tab> <C-W>Wnnoremap <F5> :NERDTreeToggle<CR>:nmap <F3> :vimgrep //j ** <bar> copenIf more information is needed to solve these problems, I'll gladly provide it.UPDATE: I solved the first two problems by putting 'set t_Co=256' in my .vimrc, but the upper bar is still the same is it normal?
|
Problem with color, symbols and upper bar using airline with Vim in terminal
|
terminal;statusline;plugin vim airline
|
I solved the first two problems by putting the set t_Co=256 in my .vimrc and solved the missing upper bar problem by putting this in my .vimrc.let g:airline#extensions#tabline#enabled = 1 Show just the filenamelet g:airline#extensions#tabline#fnamemod = ':t'
|
_codereview.31007
|
I'm working on a project for an Intro to C/Python class and am looking to improve the efficiency of the program. The program is a lottery simulation where the user inputs the number of tickets they want to buy, then generates tickets, and finally outputs the total winnings and net gain (usually loss). This is my code (in Python, as required):def main(): numb_tickets = int(input(How many tickets would you like to buy?\n)) #Calculate Winnings winnings = 0 for i in range(numb_tickets): #For testing only, gives feedback progress of program print(i, ,winnings) #Creating winning ticket/your ticket, find number of matches win_tic = getRandomTicket(MAX_VALUE, TIX_SIZE) my_tic = getRandomTicket(MAX_VALUE, TIX_SIZE) numb_win = numMatches(win_tic, my_tic) #Add appropriate payout for number of matches if numb_win == 6: winnings += WIN_SIX elif numb_win == 5: winnings += WIN_FIVE elif numb_win == 4: winnings += WIN_FOUR elif numb_win == 3: winnings += WIN_THREE #Calculate cost of purchasing tickets cost_tics = numb_tickets * COST_TIC if winnings >= cost_tics: profit = winnings - cost_tics print(You won $,winnings,, for a net earnings of $,profit,., sep=) elif winnings < cost_tics: loss = cost_tics - winnings print(You won $,winnings,, for a net loss of $,loss,., sep=) main()Note: the getRandomTicket() and numMatches() functions were provided by the professor to generate a lottery ticket and check the number of matches it has, respectively.My program works fine for smaller numbers of tickets, but when testing the required 1,000,000 tickets, takes a massive amount of time. It makes sense that the time increases rapidly as the range of the loop increases, but I don't know of a better way to loop this yet. Any input or suggestions are greatly appreciated.
|
Improving Lottery Simulation
|
python;performance;simulation
| null |
_codereview.4043
|
There's another exercise from Thinking in C++. This time it asks this:Write a program that uses two nested for loops and the modulus operator (%) to detect and print prime numbers (integral numbers that are not evenly divisible by any other numbers except for themselves and 1).And this is what I think:// finds all prime numbers between 2 and a number given in input.#include <iostream>using namespace std;int main(int argc, char* argv[]) { cout << How many prime numbers do you want to print? ; int n; cin >> n; int i, j; bool flag = true; for(i = 2; i <= n; i++) { for(j = 2; j <= i; j++) { if((i % j) == 0) { if(i == j) flag = true; else { flag = false; break; } } } if(flag) cout << Prime: << i << endl; }}It works perfectly, but I'd know what do you think about. Thanks for the feedback!
|
Prime number finder
|
c++;primes
|
Forgive me, I'm a C# developer, I like descriptive terms :)As Alexandre mentioned, the sqrt is key to minimize computations. Great heuristic. Another heuristic you can use is every other number will not be prime, as it will be divisible by 2. Then to expand on this heuristic, you can say that no odd numbers are divisible by even numbers and therefore may skip every other number as your divisible test number.for(int mightBePrime = 3; mightBePrime <= upperLimitToCheck; mightBePrime += 2){ bool foundAPrime = true; for(int divisorToCheckPrime = 3; divisorToCheckPrime * divisorToCheckPrime <= mightBePrime ; divisorToCheckPrime += 2) { if(mightBePrime % divisorToCheckPrime == 0) { foundAPrime = false; break; } }}
|
_softwareengineering.158853
|
I was reading about Assemblies (modules, which Microsoft CLR works with). The Assembly contains so called Manifest, which by definition describes a set of files in the Assembly.I know that Android applications also contain a file called Manifest, which also describes a set of files contained in the application.Is this simply a coincidence? Or are there some commonly accepted rules in software development to name special files?
|
Coincidence or rule?
|
terminology;android;naming;clr
|
So you can mark this one as answered, these three comments accurately summarize things:Baqueta's comment:I'm pretty sure the terminology comes from the term shipping manifest, which wikipedia describes as: Manifest, a document listing the cargo, passengers, and crew of a ship, aircraft, or vehicle, for the use of customs and other officials.Joachim Sauer's comment:As far as I know Java was the first one to call it manifest (at least of the three that where mentioned). And since it's a fitting name (similar to a shipping manifest, it describes the content of a package), others just used the same term for similar files.MattDavey's comment:It's neither a coincidence nor a rule, just a good descriptive word to capture a concept.It's the same reason words like 'factory', 'facade', 'token', 'agent' are ubiquitous in software development.
|
_webmaster.4930
|
I'm currently building a website, and the specifications, which I am asked to look at with a critical eye, say that I should use url like these for a store locator page:www.mysite.com/store.html <--this page is a store listingwww.mysite.com/store/paris.html <-- this is a page for the store in ParisI think I should drop the .html part, but I am less sure about whether I should use plural for the first url (I mean www.mysite.com/stores instead of www.mysite.com/store ).Could you please advise?
|
Should I use plural or singular parts for my url when on a listing page
|
seo
|
I understand you wanna make friendly URLs. This is good.My preferred approach is face a website like a directories structure. This gives more semantic, and makes easier to power users to predict listing directories.In your case:www.mysite.com/ #rootwww.mysite.com/stores/ #stores listingwww.mysite.com/stores/paris #paris store detailsNote the predictable structure. Trailing slash let people and crawlers understand that it threats about a directory root.Power users that land in paris store for example, can be tempted to just delete paris from URL and expect to see the parent list or something like that (they tend to face URLs as breadcrumbs). This is why I think this approach is the more interesting.It also makes easier to code and make distribution (sitemaps) IMHO.
|
_webmaster.61148
|
I want to block search engines from crawling my websites. Atleast for Msn, Yahoo, Google, and Yandex. i dont really trust robot.txt. Because they can simply ignore it and continue crawling.I would use rails as my web framework.How can i do it, atleast to decrease the posibility destructive action they do by simply crawling a specific page.Is there any special mark or identifier on them while they are crawling a site ?This question marked as duplicate withRobots denied by domain is still listed in search resultsWich is i guess a mistake. Above questions is asking specifically why. I dont really care why google crawling my site. I just want to block it. Show 404 status.
|
How to force search engines not to crawl my site, is there any special mark on them?
|
search engines;web crawlers
| null |
_codereview.156088
|
I have created a script to check for failed logins and then trawl User .bash_history for keywords. There is also processing on the .bash_history files to convert epoch to human-readable timestamps.I've run my script through shellcheck.net and the only real thing that it's complaining about are my For loops. It's saying they should be while loops instead, and I'm struggling to convert them.Here's the script in its entirety:#! /bin/bash#printf \necho -e \e[93m*** Failed Login Checker ***\e[0msleep 2grep -E 'Failed password|invalid' /var/log/secure* | grep sshd\[ | uniqread -r -p Press [Enter] key to continue...printf \necho -e \e[93m*** BASH History Checker - script initiated ***\e[0msleep 2HOLDINGDIR=/root/check_historyif [ ! -d $HOLDINGDIR ];then mkdir $HOLDINGDIRfifor i in $( find /home -name .bash_history -type f );do cp $i $HOLDINGDIR/$( ls -la $i | awk '{print$3}' )_historydoneecho -e \e[93mAll BASH History files copied - now processing date format...\e[0mfor k in $( find $HOLDINGDIR -name '*_history' -type f );do echo Processing file: $k sed -i -E 's/^#([0-9]+).*$/date -d @\1/e' $k chmod 755 $kdoneprintf \necho -e \e[93mAll BASH History files timestamps converted\e[0mprintf \nread -r -e -p Enter search term: -i sudo su searchecho You typed: $searchsleep 3printf \nfor m in $( find $HOLDINGDIR -name '*_history' -type f );do printf \n FILENAME=$m echo ----------------------------------------------------------- echo History file for: $FILENAME | awk -F/ '{print$4}' echo ----------------------------------------------------------- grep -F -B1 -i $search $m read -r -p Press [Enter] key for next file...done
|
Script to check for failed logins and then trawl users' .bash_history for keywords
|
beginner;bash
|
Don't embed terminal escapes in your stringsYou don't know what terminal will be displaying your output - or even whether output will be going to a terminal. The standard tool to get the appropriate strings (if they exist) is tput. You'll want something like:sgr0=$(tput sgr0)sgr93=$(tput sgr 93)which you can then use in your stringsecho -e isn't portableSince you're using printf, you can conveniently use that when you don't want a newline:printf \n%s $sgr93*** Failed Login Checker ***$sgr0Pointless sleepingsleep 2read -r -p Press [Enter] key to continue...These server only two purposes - annoy the user, and make it harder to use in a pipeline.Unquoted variable expansionAlthough the value you've given $HOLDINGDIR is currently safe to expand without quotes, I recommend you quote its expansion anyway, to give you the freedom to change it later (for example, you might want its value to incorporate $HOME instead of hard-coding /root).No check that mkdir succeededIf $HOLDINGDIR already exists as a regular file, or its parent directory doesn't exist or can't be written, then it won't be created, and we don't check that it succeeded. The easy way to deal with this is to make any failed command abort the script:set -xUnbounded findDo you really mean to search recursively for .bash_history files? It probably makes more sense to look in each user's home directory only. And not all home directories are necessarily under /home. I'd be more inclined to iterate over awk -F: '{ print $6 /.bash_history }' /etc/passwd instead:awk -F: '{ print $1, $6 /.bash_history }' /etc/passwd \ | while read u f do if test -e $f then cp -v $f $HOLDINGDIR/${u}_history fi doneReplace copy+edit with a pipelineYou copy files and then process them with sed. It's much better to simply have sed take its input from the original file and send its output to the new file, so instead of the cp above we can just:sed -e 's/^#([0-9]+).*$/date -d @\1/e' $f >$HOLDINGDIR/${u}_historyand remove the following for loop.And drop the chmod 755: you don't really want to make the transformed history files executable and readable by everybody.Interactive reading of search termread -r -e -p Enter search term: -i sudo su searchAgain, this makes it hard to run from anything other than a terminal. And if you mistype it, you have to start right from the beginning, seeking out all the history files again. Instead, you could provide the terms as positional arguments, then you canfor search in $@do grep -FiH -B1 $search $HOLDINGDIR/*_historydoneEven better, you could search for all the search terms together, remembering that grep -F accepts a newline-separated list of search terms:grep -FiH -B1 $(printf '%s\n' $@) $HOLDINGDIR/*_historyModified program#!/bin/bashset -eif [ $# = 0 ]then echo No search terms specified! >&2 exit 1fiHOLDINGDIR=/root/check_historytest -d $HOLDINGDIR || mkdir $HOLDINGDIRawk -F: '{ print $1, $6 /.bash_history }' /etc/passwd \ | while read u f do if test -e $f then sed -e 's/^#([0-9]+).*$/date -d @\1 +#%c/e' $f >$HOLDINGDIR/${u}_history fi donegrep -FiH -B1 $(printf '%s\n' $@) $HOLDINGDIR/*_history
|
_cs.77810
|
I want to construct a 2-tape Turing Machine, which decides in linear time if the input string over $\Sigma^* := \{(, [, ], )\}$ is a valid bracket.I have not constructed too many TM's yet, this is why I need your help.
|
construct a TM decides in linear time, if valid bracket
|
turing machines;decision problem
|
If you are not allowed to use two or more tapes then as Yuval Filmus commented you cannot solve in linear time. Otherwise you can convert the following steps into TM instructions: Initially input on the tape 1, the tape 2 is empty. Machine reads input symbols stored on the tape 1, and tape 2 is used as stack (for push/pop operations). 1) x = Read a symbol. 2) If x is '[' or '(' Then 3) push x and go to 1) 4) Else If x is ')' Then 5) sym = pop() 6) If sym != '(' Then 7) Reject and Halt. 8) Else 9) go to 1) 10) Else If x is ']' Then 11 sym = pop() 12) If sym != '[' Then 13) Reject and Halt. 14) Else 15) go to 1) 16) Else If x is '$' Then (if end of input) 17) If stack is empty Then 18) Accept and Halt 19) Else 20) Reject and Halt 21) Else 22) Reject and HaltI think translation to a TM of this piece of code is quite tedious work. In computability theory if you want to prove existence of a TM then informal description (or just description using one of the high-level programming languages) is enough. You may use a single tape TM model or multitape model. However, when dealing with time complexity selection of a model matters.
|
_unix.224999
|
I am trying to build GTK+ using JHBuild. I ran into the following error:checking for GTK... noconfigure: error: Package requirements (gtk+-3.0 >= 3.12 gtk+-x11-3.0 >= 3.12) were not met:Requested 'gtk+-3.0 >= 3.12' but version of GTK+ is 3.10.8Requested 'gtk+-x11-3.0 >= 3.12' but version of GTK+ is 3.10.8Consider adjusting the PKG_CONFIG_PATH environment variable if youinstalled software in a non-standard prefix.Alternatively, you may set the environment variables GTK_CFLAGSand GTK_LIBS to avoid the need to call pkg-config.See the pkg-config man page for more details.*** Error during phase configure of gcr: ########## Error running ./configure --prefix /home/xiaolong/jhbuild/releases/gnome-apps-3.17.90/install --disable-static --disable-gtk-doc --disable-Werror *** [15/29]I am confused now. I want to build GTK+, so I need GTK+?! Why? Shouldn't that be independent from each other? How do I fix the issue?The command I used to start the build process:jhbuild -m ~/jhbuild/gnome-apps-3.17.90.modules build gtk+(I had to tell jhbuild where it could find the modules, since I couldn't find any documentation about where the modules directory is supposed to be and no directory I tried to put the modules in worked - it never found them, if I didn't specify.)
|
Why do I need GTK+ to build GTK+? And how to fix it
|
compiling;gtk;gtk3
| null |
_codereview.92761
|
Based on this: asymmetric encryption in C#I added some more functionality to make it even easier to use (I combined the keySize and the keys into one base64 string).My requirements are:I want a public and private string key A simple method to call to encrypt or decrypt another string.This works, and the following test case returns that all is good.[TestMethod]public void EncryptionRSATest(){ int keySize = 1024; var keys = EncryptorRSA.GenerateKeys(keySize); string text = text for encryption; string encrypted = EncryptorRSA.EncryptText(text, keys.PublicKey); string decrypted = EncryptorRSA.DecryptText(encrypted, keys.PrivateKey); Assert.IsTrue(text == decrypted);}So..Can anyone help make it even better? Are there any major flaws in this that makes it really easy to decrypt?Is it a horrible idea to add the keySize to the key?This is the class:using System;using System.Web;using System.Text;using System.Linq;using System.Collections.Generic;using System.Security.Cryptography;namespace JensB.Encryption{ [Serializable] public class EncryptorRSAKeys { public string PublicKey { get; set; } public string PrivateKey { get; set; } } public static class EncryptorRSA { private static bool _optimalAsymmetricEncryptionPadding = false; public static EncryptorRSAKeys GenerateKeys(int keySize) { if (keySize % 2 != 0 || keySize < 512) throw new Exception(Key should be multiple of two and greater than 512.); var response = new EncryptorRSAKeys(); using (var provider = new RSACryptoServiceProvider(keySize)) { var publicKey = provider.ToXmlString(false); var privateKey = provider.ToXmlString(true); var publicKeyWithSize= IncludeKeyInEncryptionString(publicKey, keySize); var privateKeyWithSize = IncludeKeyInEncryptionString(privateKey, keySize); response.PublicKey = publicKeyWithSize; response.PrivateKey = privateKeyWithSize; } return response; } public static string EncryptText(string text, string publicKey) { int keySize = 0; string publicKeyXml = ; GetKeyFromEncryptionString(publicKey, out keySize, out publicKeyXml); var encrypted = Encrypt(Encoding.UTF8.GetBytes(text), keySize, publicKeyXml); return Convert.ToBase64String(encrypted); } private static byte[] Encrypt(byte[] data, int keySize, string publicKeyXml) { if (data == null || data.Length == 0) throw new ArgumentException(Data are empty, data); int maxLength = GetMaxDataLength(keySize); if (data.Length > maxLength) throw new ArgumentException(String.Format(Maximum data length is {0}, maxLength), data); if (!IsKeySizeValid(keySize)) throw new ArgumentException(Key size is not valid, keySize); if (String.IsNullOrEmpty(publicKeyXml)) throw new ArgumentException(Key is null or empty, publicKeyXml); using (var provider = new RSACryptoServiceProvider(keySize)) { provider.FromXmlString(publicKeyXml); return provider.Encrypt(data, _optimalAsymmetricEncryptionPadding); } } public static string DecryptText(string text, string privateKey) { int keySize = 0; string publicAndPrivateKeyXml = ; GetKeyFromEncryptionString(privateKey, out keySize, out publicAndPrivateKeyXml); var decrypted = Decrypt(Convert.FromBase64String(text), keySize, publicAndPrivateKeyXml); return Encoding.UTF8.GetString(decrypted); } private static byte[] Decrypt(byte[] data, int keySize, string publicAndPrivateKeyXml) { if (data == null || data.Length == 0) throw new ArgumentException(Data are empty, data); if (!IsKeySizeValid(keySize)) throw new ArgumentException(Key size is not valid, keySize); if (String.IsNullOrEmpty(publicAndPrivateKeyXml)) throw new ArgumentException(Key is null or empty, publicAndPrivateKeyXml); using (var provider = new RSACryptoServiceProvider(keySize)) { provider.FromXmlString(publicAndPrivateKeyXml); return provider.Decrypt(data, _optimalAsymmetricEncryptionPadding); } } public static int GetMaxDataLength(int keySize) { if (_optimalAsymmetricEncryptionPadding) { return ((keySize - 384) / 8) + 7; } return ((keySize - 384) / 8) + 37; } public static bool IsKeySizeValid(int keySize) { return keySize >= 384 && keySize <= 16384 && keySize % 8 == 0; } private static string IncludeKeyInEncryptionString(string publicKey, int keySize) { return Convert.ToBase64String(Encoding.UTF8.GetBytes( keySize.ToString() + ! + publicKey)); } private static void GetKeyFromEncryptionString(string rawkey, out int keySize, out string xmlKey) { keySize = 0; xmlKey = ; if (rawkey != null && rawkey.Length > 0) { byte[] keyBytes = Convert.FromBase64String(rawkey); var stringKey = Encoding.UTF8.GetString(keyBytes); if (stringKey.Contains(!)) { var splittedValues = stringKey.Split(new char[] { '!' }, 2); try { keySize = int.Parse(splittedValues[0]); xmlKey = splittedValues[1]; } catch (Exception e) { } } } } }}
|
Very simple asymmetric RSA encryption in C#
|
c#;security;cryptography
| null |
_reverseengineering.12404
|
A typical PIN code snippet looks like this (taken from the official manual):// This function is called before every instruction is executed// and prints the IPVOID printip(VOID *ip) { fprintf(trace, %p\n, ip); }// Pin calls this function every time a new instruction is encounteredVOID Instruction(INS ins, VOID *v){ // Insert a call to printip before every instruction, and pass it the IP INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)printip, IARG_INST_PTR, IARG_END);}I just can't figure out how to access the ins object from within printip(VOID *p). The other way round seems easy, i.e. getting the IP from from the ins object:INS_Address (INS ins)(see here)I tried passing a INS *ins pointer to printip(VOID *ip, INS *ins) ins via IARG_PTR, &ins but this ended in either casting errors or Segmentation faults.How can I access the ins object (type INS) from inside an analysis function?Side note: I got to this problem when trying to call INS_Disassemble (INS ins) for every executed instruction.
|
Intel PIN: How to access the INS object from inside an analysis function?
|
c++;pintool
|
You may note that printip is a function pointer, it is lazily called internally by Pin; moreover ins is an automatic variable (it is passed into Instruction from the stack). Consequently, passing &ins into printip (through IARG_PTR), then using it will lead to segmentation faults.Pin declares INS by specializing the class template INDEX, as you can observe the following declaration in type_core.TLH:/*! @ingroup INS_BASIC_APIHandle for INS */ typedef class INDEX<6> INS;where constructors and assignment operators of class template INDEX are both default. So, in principle^^, we can always declare a persistent variable to share an object of INS between instrumentation and analysis functions, for example:static INS per_ins;...VOID Instruction(INS ins, VOID *v){ per_ins = ins; ...}...VOID printip(VOID *ip){ INS_Disassemble(per_ins);}This method does not work, unfortunately, this is an example for well-typed program still can go wrong in C/C++^^. Since Pin does not guarantee that internal variables, accessed by an object of type INS, are persistent in analysis time, the result of calling INS_Disassemble(per_ins) in an analysis function can be meaningless.For your case, you may not want to call INS_Disassemble(ins) each time ins executes. We don't need that, for example, if ins is in a loop then this function will be called multiple times (with the same ins) to get the same result.All static information of an instruction (e.g. the disassembled form of ins in this case) should be obtained in instrumentation time. Particularly, INS_Disassemble should be called single time only in some instrumentation function. One way to obtain the same effect as you want is:static std::unordered_map<ADDRINT, std::string> str_of_ins_at;VOID Instruction(INS ins, VOID *v){ str_of_ins_at[INS_Address(ins)] = INS_Disassemble(ins); ...}VOID printip(VOID *ip, ADDRINT addr) { std::string ins_str = str_of_ins_at[addr]; ...}
|
_webapps.65771
|
At the beginning of this week, I noticed that I can no longer properly copy and paste into or out of a Google Document. I find that if I highlight more than one paragraph and press Edit / Copy or ctrl / + c, it will not copy. Even when I select only one paragraph, it still will not copy.The only way I can get it to copy is when I leave off the first character in the paragraph, the last character in the paragraph, or both. Then I have to copy paragraph-by-paragraph out of the Google Doc.I've tried this on two different machines, both running Firefox. Does this happen for anyone else, and if so do you have a fix?
|
How do I fix copy/paste in Google Documents?
|
google documents;copy paste
| null |
_vi.9978
|
Inspired by Drew NEIL's course and the 'nested-folding' feature for Markdown files, I've installed the Vim-Markdown-Folding plugin, on my Vim (:version). The GitHub directory was copied into the ~/.vim/bundle directory (as required by the pathogen plugin) with:$ git clone https://github.com/msprev/vim-markdown-folding.gitThen I added the required let g:markdown_fold_style = 'nested'line into my .vimrc-file as described in the :help markdown-folding-configuration file and got this wired error:Error detected while processing BufEnter Auto commands for <buffer=1>:E117: Unknown function: mdfolding#foldtextupdatewhen opening, saving, or even jumping into the (Vim-)window of any markdown file. Otherwise everything seems to work fine. However, every time the error occurs I have to confirm the reading and I really would like to settle any other potential complications.
|
Vim-Markdown-Folding plugin error BufEnter E117
|
vimrc;folding;error;filetype markdown;plugin pathogen
|
A bit of investigationAfter finding the function in source file, with these lines preceding it:if !has('python') echo Error: Required vim compiled with +python finishendifAnd installing the plugin (my Vim is built without python), I can easily get the same error:Error detected while processing BufEnter Auto commands for <buffer=1>:E117: Unknown function: mdfolding#foldtextupdateSo :echo has('python') probably returns 0 for you, because your Vim either doesn't have python support at all or has only python3 support.By the way, the authors of the plugins should use :echoerr for such cases, or users might ignore important error messages.Plugin versionPlease do keep in mind that you did not install the original version of the plugin. What you installed is actually a fork of Drew Neil's plugin -- it seems to try to optimize performance of folding, but also requires Vim with python support.You can:use original version of the plugin, which doesn't require python (your link to documentation points to this repository, actually):git clone https://github.com/nelstrom/vim-markdown-folding.gitchange your Vim setup (if you really need this plugin)report upstream about the issue, maybe fixing it requires only adding check for python3 feature (e.g., if !has('python') && !has('python3')), the author should know better anyway
|
_datascience.6986
|
I found the following article on Hierarchical Clustering With Prototypesvia Minimax Linkage.It is stated in Property 6 that Minimax linkage cannot be written using LanceWilliams updates.A succint proof using a counter-example is given:Proof. Figure 9 shows a simple one-dimensional example that could not arise if minimax linkage followed Lance Williams updates. The upper and lower panels show two configurations of points for which the right side of (4) is identical but the left side differs; in particular, $d(G_1 \cup G_2,H) = 9$ for the upper panel, whereas $d(G_1 \cup G_2,H) = 8$ for the lower panel.But I do not understand their proof. For both cases (upper and lower panels), $d(G_1,H) = 16$, $d(G_2,H) = 7$, $d(G_1,G_2) = 5$.I cannot see any reasons that $\alpha(G_2)$ in the first case must equal to $\alpha(G_2)$ in the second case as, for instance, $G_2$ has not the same cardinal.
|
Is Minimax Linkage a Lance-Williams hierarchical clustering?
|
machine learning;clustering;algorithms
| null |
_cs.57644
|
I have to find the time complexity of the following program:function(int n){ for(int i=0;i<n;i++) //O(n) times for(int j=i;j<i*i;j++) //O(n^2) times if(j%i==0) { //O(n) times for(int k=0;k<j;k++) //O(n^2) times printf(8); }}I analysed this function as follows:i : O(n) : 1 2 3 4 5j : : 1 2..3 3..8 4..15 5..24 (values taken by j) O(n^2): 1 2 6 12 20 (Number of times executed)j%i==0 : 1 2 3,6 4,8,12 5,10,15,20 (Values for which the condition is true) O(n) : 1 1 2 3 4k : 1 2 3,6 4,8,12 5,10,15,20 (Number of times printf is executed) Total : 1 2 9 24 50 (Total)However I am unable to bring about any conclusions since I don't find any correlation between $i$ which is essentially $O(n)$ and Total of k (last line). In fact I don't understand if we should be looking at the time complexity in terms of number of times printf is executed since that will neglect $O(n^2)$ execution of j-for loop. The answer given was $O(n^5)$ which I presume is wrong but then whats correct?
|
Time complexity of nested for loop function involving mod to filter out the execution
|
algorithm analysis;runtime analysis;loops
| null |
_unix.309696
|
Sometimes when I try to suspend my laptop (using the sleep keyboard button), I get this popup from xfce4-power-manager: Are you sure you want to hibernate the system? An application is currently disabling the automatic sleep. Doing this action now may damage the working state of this application. I don't want to hibernate - I would like to know which application is disabling sleep, so that I can quit it and suspend the system normally. How can I find this out?I'm on Xubuntu 15.10.
|
How do I find out which application is disabling sleep?
|
xfce;power management;suspend;sleep
|
Under Freedesktop-compliant environments, including XFCE4, sleep inhibition is communicated via D-Bus on the org.freedesktop.PowerManagement bus. I can't find any documentation about this; the xfce4 code has a list of methods which includes one called GetInhibitors so this should work:dbus-send --print-reply --dest=org.freedesktop.PowerManagement /org/freedesktop/PowerManagement/Inhibit org.freedesktop.PowerManagement.Inhibit.GetInhibitors
|
_unix.164314
|
When using the nemo file browser in icon mode (compact view) the scroll turns to horizontal rather than vertical. For me this is very hard to work with. If the files are in list mode you can scroll vertical to see the next list of files. Hopefully there is a setting to allow this same type of scrolling in the alternate view.I have spent a lot of time in all the setting options and searching the Internet.Hopefully someone with experience can give me the setting option, or advise me that it doesn't exist and I can stop searching.
|
How to disable nemo's horizontal scroll
|
scrolling;nemo
|
I happen to be using nemo, and took a quick glance at nemo's settings and nemo's settings in dconf editor.There doesn't appear to be anything about changing the type of scrolling for compact view, so perhaps it was designed that way without an option to change it.I would say if you've already spent at least 30 minutes searching, it would probably be better to just keep to list view and save yourself the headache of searching any longer. Possibly request this feature as well?
|
_softwareengineering.345456
|
I know the purpose of it and everything. I see myself as a solo developer for a couple more years.I always see answers that it is contract. Yes I get it.But here's something on my mind:If a class did not provide what an Interface wants, it'll throw an error.Well, if a class really needs that method, it'll throw an error still if there's something that calls it and it's not there right?What's the difference?I can just actually implement it and go along with the norms but that will leave me hanging with the question why. I don't like blindly following something without understanding it.EDIT:I tried searching for answers about this question many times before and what I always find is something like So when someone else.... Haven't tried working with someone else before and I am not sure if that really is the reason on why use an Interface.I mean, because I do everything my own so I do know what something in my code needs right? And again, even if I forget to implement a method, I will still see an error that says a method is not defined.EDIT 2:The Dependency Injection is a very good answer. Implementing Interfaces on those helps in case you need to swap out dependency implementations. You are somehow confident that what you need is provided.It is a little more clear to me now that it is a Contract between components (maybe between developers too)
|
Another Why use Abstract/Interface question. But I'm a solo developer. Why use it?
|
object oriented;interfaces;abstract class
| null |
_softwareengineering.124976
|
ORMs and persistence ignorance make perfect sense: if I am programming in a language, then I want to use the language's native implementation of objects and data structures to drive my program. I shouldn't need to worry about SQL or a database, and I always thought that inline SQL strings in a program was very cumbersome.Why is SQL still used as a backend? Why doesn't the ORM just persist objects to XML or a binary file(s) and avoid all the overheads and difficulties of administering a database server?
|
Why are SQL databases still used with ORM?
|
database;orm
| null |
_softwareengineering.40255
|
Recently I heard of a company that, for interviews, asks potential employees to stand up and write out code on a whiteboard. Apparently that freaked alot of interviewees out. This got me thinking and even though I consider myself a reasonable programmer, I would be hard pressed to write lengthy code out without referring to previous code I had written or doing a quick Google search. How many programmers could safely say Yes I could write all my code out just like I was writing an email?
|
How important is to be able to write code like you would write prose
|
interview
|
As an interviewer asking for white board coding, I wasn't looking for perfect syntax and I was asking questions about basic algorithms using arrays or strings. I was looking for the kind of knowledge a college kid should have after watching a professor write code on a chalkboard. Not that most professors do that any more, since they all use PowerPoint, but back in the day I promise they did.Whiteboarding code did seem to freak some of my interviewees out, but in that case I tended to try and talk them through it. All I wanted to see was that they could write code. Since my company didn't take code samples, and since I wasn't the hiring manager dictating how the interview went, this was my best bet for getting that information. As an interviewee I was interviewed by a Very Big Company whose technical interviews are all whiteboard. I had read on blogs and in articles that for this Very Big Company you had to start off with a moderately optimized answer as opposed to the brute force attack and you had to have perfect syntax. The people writing this on the internet must have gotten the though interviewers and I must have gotten the easy ones, because my experience was that the whiteboard coding was viewed as a thinking tool in the interviews just as it would be in real brainstorming with your team.Perhaps there are interviewers out there who demand perfect and at least somewhat optimized code on the whiteboard as if it was flowing straight from your stream of consciousness. Really, though, if a person is demanding such things do you want him or her as your co-worker? If so, great. If not, perhaps it isn't so bad if you can't write code like prose.I wouldn't freak out about writing code on a whiteboard in an interview, though. Just do your best to solve the problem with the tools you have. Interviewers like me are rooting for you to solve the problem as much as you are.
|
_scicomp.4744
|
So the Cholesky decomposition theorem states that that any real symmetric positive-definite matrix $M$ has a Cholesky decomposition $M= LL^\top$ where $L$ is a lower triangular matrix. Given $M$, we already know there are fast algorithms to calculate its Cholesky factor $L$.Now, suppose I was given a rectangular $m\times n$ matrix $A$, and I knew that $A^\top A$ was positive definite. Is there a way to calculate the Cholesky factor $L$ of $A^\top A$ without computing $A^\top A$ explicitly and then applying Cholesky factorization algorithms?If $A$ is a very large rectangular matrix performing $A^\top A$ explicitly seems very expensive and hence the question.
|
Computation of Cholesky factor
|
linear algebra;algorithms
|
Yes, you can obtain the factor (up to the signs of entries) using QR decomposition; see this answer. Note that if all you're interested in is solving the least squares problem that lead to the normal equations involving $A^T A$, you can use the QR decomposition directly.
|
_unix.167668
|
A shebang (#!/bin/sh) is placed on the first line of a bash script, and it's usually followed on the second line by a comment describing what action the script performs. What if, for no particular reason, you decided to place the first command far beneath the shebang and the comment by, say, 10000 lines. Would that slow the execution of the script?
|
Distance of a command from a shebang?
|
shell script;shebang
|
To find out, I created two shell files. Each starts with a shebang line and ends with the sole command date. long.sh has 10,000 comment lines while short.sh has none. Here are the results:$ time short.sh Wed Nov 12 18:06:02 PST 2014real 0m0.007suser 0m0.000ssys 0m0.004s$ time long.shWed Nov 12 18:06:05 PST 2014real 0m0.013suser 0m0.004ssys 0m0.004sThe difference is non-zero but not enough for you to notice.Let's get more extreme. I created very_long.sh with 1 million comment lines:$ time very_long.shWed Nov 12 18:14:45 PST 2014real 0m1.019suser 0m0.928ssys 0m0.088sThis has a noticeable delay.Conclusion10,000 comment lines has a small effect. A million comment lines cause a significant delay.How to create long.sh and very_long.shTo create the script long.sh, I used the following awk command:echo date | awk 'BEGIN{print #!/bin/bash} {for (i=1;i<=10000;i++) print #,i} 1' >long.shTo create very_long.sh, I only needed to modify the above code slightly:echo date | awk 'BEGIN{print #!/bin/bash} {for (i=1;i<=1000000;i++) print #,i} 1' >very_long.sh
|
_webmaster.82482
|
I read through the comments and answers to both How bad is it to use display: none in CSS? and Is hidden content (display: none;) -indexed- by search engines?, but I couldn't see anything related to links.If I have a menu load up as Display:None and then show it via JavaScript later will those links in the menu get crawled? Is there an impact on PageRank?It seems as if the answer is yes, it sees them and crawls them and there is no effect on rank flowing through the hidden links... I just can't seem to find a definitive answer.
|
Do links hidden by display:none still pass PageRank
|
seo
|
More than likely these links will get crawled and be treated like other links on your site (assuming that you don't nofollow them). However, be sure you are are clear on Google's guidelines around hidden text (see https://support.google.com/webmasters/answer/66353). One thing I've learned the hard way related to this is that you you want to make sure Google can access your CSS and JavaScript files (don't block those files via your robots.txt).Now, all that said, I wouldn't count on Google finding all the pages on your site just because they are in the menu (this is true whether the menu has display:none or not). Make sure the pages are available via links elsewhere on the site, including in the XML sitemap. That way if Google for some reason does not see the display:none links (or, if Google chooses to ignore those links), those pages will still get crawled and indexed (assuming all else being okay with your site of course).
|
_unix.55517
|
Is it possible to get input from both file and the terminal?I wish to ask the user something in the END portion of the awk script.That input should be typed in by the user and not read from the file which had the data to be processed.END { getline choice if(choice == Y) print OK}But choice is read off the input file.
|
awk - get input from both file and STDIN?
|
awk;input
|
You can read from /dev/tty or from /dev/stdin.getline choice < /dev/tty/dev/tty is pretty ubiquitous (even one the very few, along with /dev/null and /dev/console to be required by POSIX), /dev/stdin is less common, but at least GNU awk would recognize it as meaning stdin even if the system doesn't have such a device/special file.
|
_webapps.100945
|
I would like to export a simple textual conversation with another user on Google through Google Hangouts.I am using a Google Apps account, however, and Google Takeout is disabled. Are there any (dirty or not) workarounds to export the chat data (for example tying an IMAP client to it and reading the Chats folder, though I tried that and it does not work)
|
Export Google Hangouts chat without using Google Takeout
|
google hangouts
| null |
_webapps.16872
|
I want to build a website which will allow people to migrate from a Yahoo Group, but interaction with the group must still be possible. To this end I want to have peoples interaction with the group done by the website.The group emails have the reply to address as the users personal email address, not the group address.So the website will need to post users entries to the group with a unique reply to address and then recieve replies to that address so that they can marked as replies to the user that sent them.Is there a way that I can do this? I considered having a single user on the group for the website and then modifying the reply to address so that it was something like website+<userid>@website.email.com but I'm not sure if the groups can be configured to allow this as a reply to address. Or perhaps to allow all posts from a particular subdomain so that the reply could be <userid>@website.email.com and all posts from *@website.email.com are allowed. Can I create users of the group programmatically to support this?
|
Can I manage Yahoo Groups on behalf of many people?
|
yahoo
| null |
_webmaster.15699
|
I'm curious if anyone has any insight into something: Google seems to have recently changed their algorithm, and now Github repos have basically disappeared from the search results. If I want to try and get a repo to show up on Google again, does anyone have any suggestions for how I might optimize my repo's home page?
|
Page Rank / Github
|
seo;google;ranking
| null |
_unix.199669
|
Firstly, any advice on improving the title appreciated!I want a webpage to reflect a log file. I have a bash script that converts the log to html. Currently this runs periodically via crontab, which works, but obviously executions are redundant when the webpage isn't viewed. I'd like to implement a system so the bash script runs only called when the webpage is called.I gather an index.php script along the lines:<?php$message=shell_exec(. /path/script.sh);?>.. should generate the index.html file ok. But is there an easy way to get index.php/Apache to serve that file to the client browser? Advice much appreciated.
|
Implementing index.php that serves index.html
|
apache httpd;php
| null |
_unix.220425
|
I have a laptop with Linux Slackware. When it's working on battery saving a file to hard drive takes around a second. When I'm writing code I waste a lot of time saving the files.I have about 2 GB of free RAM, so I can use 1 GB as a temporary buffer. And work like this:Load the file into the RAM buffer.Work with the file and save it there.At the end of work the file is moved to the HDD.The problem is that the file is a php script, used by Apache. So, I must somehow make the buffer transparent for it and make it use the RAM file when it's applying to the original file.
|
How to keep the file in RAM
|
files;ramdisk
|
I think what you want to do is a bad idea, because in the case of a system crash you'll lose your work. Anyway, you can use a subdir of /dev/shm to store your files; it's a tmpfs file system, which means it's kept in RAM.
|
_codereview.123828
|
In preparing this answer, one of the components was an algorithm to rearrange a sorted array in a particular way. To put it succinctly, here's the problem description:Given an array \$A\$ with \$n\$ elements \$A = \{ A_1, A_2, A_3, \dots , A_{n-2}, A_{n-1}, A_{n} \}\$ rearrange the contents such that the resulting array is \$A' = \{ A_1, A_n, A_2, A_{n-1}, A_3, A_{n-2}, \dots \}\$I decided to create a templated function modeled on std::reverse that only uses two bidirectional iterators. Here's the templated function:#include <algorithm> template<class BidirIt>void weave(BidirIt first, BidirIt last) { if ((last - first) < 3) { return; } for (++first; first != last; ++first) { std::reverse(first, last); }}This is the code in context with a short test program.testweave.cpp#include <utility>#include <algorithm>#include <iostream>#include <vector>std::ostream& operator<<(std::ostream& out, const std::vector<int>& v) { if (v.begin() == v.end()) { return out << {}; } out << { << *v.begin(); for (auto it = v.begin()+1; it != v.end(); ++it) { out << , << *it; } return out << };}#define SHOW(x) std::cout << # x = << x << '\n'template<class BidirIt>void weave(BidirIt first, BidirIt last) { if ((last - first) < 3) { return; } for (++first; first != last; ++first) { std::reverse(first, last); }}int main(){ std::vector<int> v; for (int i=0; i < 10; ++i) { std::cout << '\n'; SHOW(v.size()); SHOW(v); weave(v.begin(), v.end()); SHOW(v); v.push_back(i); std::sort(v.begin(), v.end()); }}I'm particularly interested in whether there is a more efficient algorithm for this.
|
Weaving an array
|
c++;algorithm;c++11;array
|
Just glancing at it, this:template<class BidirIt>void weave(BidirIt first, BidirIt last) { if ((last - first) < 3) { return; }...jumped out--although the template parameter seems to imply that you want this to work for bidirectional iterators, the subtraction will only work for a random access iterator. To work for bidirectional iterators, you'll want to use std::distance instead.Although it's only in the test code:std::ostream& operator<<(std::ostream& out, const std::vector<int>& v) { if (v.begin() == v.end()) { return out << {}; }...I'd prefer if (v.empty()) {As far as the algorithm goes, yes, there's better. In particular, it looks like your current algorithm is \$O(N^2)\$, but it's possible to do the job in \$O(N)\$ (as you probably expected).The first step would be to reverse the entire second half of your input. From there you can use an in-place shuffle algorithm. Also see an old answer on SO.
|
_codereview.46172
|
I have a completed application which I'm trying to write unit tests for (Yeah I know, talk about bad practices)I have the following class herepublic class UserManagementService : IUserManagementService{ private static readonly IUserDao userDao = DataAccess.UserDao; private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public LoginResponse Login(LoginRequest request) { var response = new LoginResponse(request.RequestId); try { var user = userDao.GetByUserId(request.UserId); if (user != null) { if (request.Password != ) { if (Authenticate(user, request.Password)) { return response; } response.ErrorCode = IncorrectPassword; } else { response.ErrorCode = PasswordNotFound; } } else { response.ErrorCode = UserNotFound; } response.Acknowledge = AcknowledgeType.Failure; return response; } catch (Exception ex) { Log.Error(ex); response.Acknowledge = AcknowledgeType.Failure; response.ErrorCode = Exception; return response; } } public bool Authenticate(User user, string password) { if (user == null) return false; using (var deriveBytes = new Rfc2898DeriveBytes(password, user.Salt)) { var derivedPassword = deriveBytes.GetBytes(20); if (!derivedPassword.SequenceEqual(user.Password)) return false; } return true; } }userDao follows the singleton pattern and this userDao.GetByUserId(request.UserId); basically makes a call to my DBI have written the following test, which will definitely give rise to some issues because I haven't figured how to Mock the userDao, and the Log[Theory][InlineData(manager, manager)]public void LoginTest(string userId, string password){ // Arrange // System under test IUserManagementService userService = new UserManagementService(); var request = new LoginRequest().Prepare(); request.UserId = userId; request.Password = password; var expectedResponse = new LoginResponse(request.RequestId) { Acknowledge = AcknowledgeType.Success }; //Act var actualResponse = userService.Login(request); //Assert Assert.AreEqual(actualResponse.Acknowledge, expectedResponse.Acknowledge); }How can I refactor my Login method, and UserManagementService class without breaking too much of its structure to support unit testing so I can inject userDao and Log?Any help would be great to help me kickstart what is going to be a long tedious process of refactoring the rest of my classes.EDIT: This is a WCF service which follows the facade pattern. I have removed the 10 other static DAO similar to userDao to lessen the code clutter for this example.
|
Refactoring method to make it unit testing friendly
|
c#;unit testing;dependency injection
|
Following on what Magnus said in comments can you not inject the necessary dependencies.For example:public class UserManagementService : IUserManagementService{ private readonly IUserDao userDao ; private readonly ILog log; public UserManagementService(IUserDao userDao, ILog logger) { this.userDao = userDao; this.log = logger; } public LoginResponse Login(LoginRequest request) { // etc } }Now the class has no dependencies on concrete implementations and you can mock the interfaces however you feel. For example, the ILog interface you might want to mock so it logs to the console only. The IUserDao interface might be mocked to a internal list implementation or you might use a mocking framework such as Moq.
|
_softwareengineering.110595
|
I've been a programmer now for over 11 years, and am just starting to get into version control for real. The places I've worked at have never really used version control (one committed at the end of each day, the others simply haven't bothered). I am not happy with the way that I've been taught to version control (programme.js, programme.js.bak, programme.js.bak.20110901 etc) and so have been teaching myself to use git.I currently use it along with github to keep my .vimrc file current across 4 machines, but I'm never sure when I should consider a change a commit, and when it's just a change which should be included along with another commit. I have started to use it for javascript development too and find it awesomely useful :)My question is: At what point do changes become a commit? As I said, the only company I've worked for who used version control did it at the end of the day - this doesn't seem sensible to me. I feel that they should be more atomic. But my question is how atomic?Is a bug fix for a function enough for a commit? Should I fix three (unrelated) functions and commit them all at once? Should I commit after changing the condition in an if statement? On personal projects, I commit after any change. I personally find that useful, but I don't know if it's bad practice or annoying. How do you do it, how does the industry do it, and what are best practices?(I'm a web developer so work on short projects - perhaps a month long)
|
git / other VCS - how often to commit?
|
version control;git;svn;github;tracking
|
Each individual change should be one commit. A few things to consider:Having stuff committed means that you can roll back. Assume you have a bigger task to be done. You're 50% done, that part looks good so far. Then you continue and break something massively by some mistake. Having the commit in between means you can go back there and didn't loose all of the work.Version control is not a place to dump data and forget. Version control provides a history. Lateron you can use the history, including my favorite annotate feature, to figure out why a change was made (and who is responsible) this often helps. But to work properly the change should be small and self contained.When working in teams it's great to have people reviewing it (actually even when working alone this would be great ;-) ), for a review it's good to have small parts which can be reviewed without being mixed in between unrelated changes.Looking at git specifically: git allows local commits, which don't hurt other, so it can even be acceptable to commit broken code locally and fixing that with a later commit before pushing. The git developers are proud how fast the commit operation works, so just committing locally doesn't really interrupt the development process. Git also allows rewriting commits, so these two (or more) commits might be rewritten into one before being pushed, which might ease review - while rewrites are dangerous and should be done with care (don't rewrite after push etc.)
|
_unix.388134
|
I recently installed a new Debian9 (stretch) machine.Initally it had 2 drives. I configured them as RAID1 using the Debian installer, and it gave me a /dev/md0 with /etc/mdadm/mdadm.conf (extract):# definitions of existing MD arraysARRAY /dev/md/0 metadata=1.2 UUID=3d21d0e0:2758c58e:962b5191:98e225c1 name=MYHOSTNAME:0and /proc/mdstat showing:md0 : active raid1 sda1[0] sdb1[1] 488253440 blocks super 1.2 [2/2] [UU] bitmap: 0/4 pages [0KB], 65536KB chunk(and that device formatted as ext4 and mounted by UUID as '/' in /etc/fstab). All works fine, as expected.Later I added a couple more even bigger drives, partitioned them (with a small swap parition on each first) and configured them using mdadm -C -n 2 -l raid1 /dev/md1 /dev/sdc2 /dev/sdd2 (that's definitely what I did because it's still in my root's shell history, along with a couple of subsequent mdadm --examine /dev/md1 and mdadm --detail --verbose /dev/md1). I also added a line to /etc/mdadm/mdadm.conf (just following the pattern for the initial device):ARRAY /dev/md/1 metadata=1.2 UUID=47492bd7:08d1fd1c:418dad41:2aa7d77f name=MYHOSTNAME:1And of course I ext4-formatted the device and added a UUID-based entry to /etc/fstab to mount this at my chosen /data mount point.That all seems to be working fine, and after multiple reboots of the machine too, and I have happily been doing huge rsyncs to the new disks. However today I happened to glance at etc/mtab and /proc/mdstat and I notice my /dev/md1 seems to have disappeared and morphed into a /dev/md127 (in /proc/mdstat) and/or a /dev/md127p1 in /etc/mtab:/proc/mdstat:md127 : active raid1 sdc2[0] sdd2[1] 3904788480 blocks super 1.2 [2/2] [UU] bitmap: 2/30 pages [8KB], 65536KB chunkmd0 : active raid1 sda1[0] sdb1[1] 488253440 blocks super 1.2 [2/2] [UU] bitmap: 0/4 pages [0KB], 65536KB chunk/etc/mtab (selected lines):/dev/md0 / ext4 rw,relatime,errors=remount-ro,data=ordered 0 0/dev/md127p1 /data ext4 rw,relatime,errors=remount-ro,data=ordered 0 0It all still seems to be working fine, but what the heck happened there? I've configured RAID1 in much the same way on a couple of other machines before (admittedly many years ago) and there the raid arrays just ended up called /dev/md0 and /dev/md1. Where did this 127 come from and what's the difference between /dev/md127 and /dev/md127p1? Is there some way I can rename them (both?) to /dev/md1, or is this something I'm stuck with?
|
Why is what was /dev/md1 when I created it now apparently called /dev/md127 or /dev/md127p1?
|
debian;raid;software raid
| null |
_unix.293966
|
My log files are getting dumped with following message while running shell scripts using some underlying MySQL commands.Here is the message:Warning: Using a password on the command line interface can be insecure.To stop these messages, I am using the following job definition.Example:run_wrapper.sh |grep -v Warning: Using a password > output.log 2>&1This worked but the MySQL errors are not being logged to output.log.If I change the definition like the following, then MySQL errors start appearing if anyrun_wrapper.sh > output.log 2>&1So the question is how to suppress the warning messages and also report SQL errors in log files using only the cron definition?
|
Suppress warning messages from MySQL in shell script but allow errors
|
shell script;logs;io redirection;mysql
| null |
_webmaster.35103
|
Preferably using .htaccess files, though .conf files are an option, is there any way to stop Apache serving certain filetypes? For example, .db shouldn't be served for obvious reason (privacy and whatnot, etc.), so could I make them show as a 404 but still have them available for my CGI scripts?Putting these sensitive files in a directory other than /public_HTML/ is also an option, though I like having them in the same directory as the scripts for ease of use.Cheers
|
Stop Apache serving filetypes
|
apache;htaccess;webserver;httpd.conf
|
I would have said that placing these sensitive files above the document root would be preferable. And perhaps easier to manage if they are all contained in a particular directory, however...Using .htaccess to prevent access to all .db and .exe files and return a 403 - Forbidden.<Files ~ \.(db|exe)$>Deny from all</Files>Unless you have a specific requirement, I would have thought a 403 would be better than a 404 in this instance, and this would seem more natural for Apache. To return a 404 here would require additional code.
|
_softwareengineering.347297
|
Specifically for ReactJS and responsive frameworks that show/hide elements based on width like Bootstrap.Because ReactJS has a virtual DOM I am presuming doing the DOM manipulation is faster and in the end a bit easier to debug because you are not trying to think which parts are display:none and there are less elements to debug. It was also easier to me to think that way because of my programming background rather than CSS.I haven't dealt with too much performance testing yet on ReactJS (that's a few chapters down) but what is better from an engineering standpoint.Code wise it looks like this...constructor(props) { super(props) this.updateStatesBasedOnWindowSize = this.updateStatesBasedOnWindowSize.bind(this) this.state = { smallDeviceNavigation: false, sideNavVisible: false, }}componentWillMount() { this.updateStatesBasedOnWindowSize()}componentDidMount() { window.addEventListener(resize, this.updateStatesBasedOnWindowSize)}componentWillUnmount() { window.removeEventListener(resize, this.updateStatesBasedOnWindowSize)}/** * This will trigger a state change based on the device size. */updateStatesBasedOnWindowSize() { const w = window, d = document, documentElement = d.documentElement, body = d.getElementsByTagName('body')[0], width = w.innerWidth || documentElement.clientWidth || body.clientWidth if (width >= 576) { if (this.state.smallDeviceNavigation) { this.setState({ smallDeviceNavigation: false }) } if (!this.state.sideNavVisible) { this.setState({ sideNavVisible: true }) } } else { if (!this.state.smallDeviceNavigation) { // Force hide the side // nav if the smallDeviceNavigation was false before. this.setState({ sideNavVisible: false }) } if (!this.state.smallDeviceNavigation) { this.setState({ smallDeviceNavigation: true }) } }}Then in the components I just check this.state accordingly. I get the advantage that I am dealing with the state based on a logical name rather than physical widths and breakpoints I am not dealing with.Mind you this is for show/hide hence I emphasized it earlier. Layouts based on CSS I just left alone and let bootstrap grid deal with it. But menus and navs I did the DOM manipulation.
|
React DOM manipulation vs CSS for responsive breakpoints?
|
css;reactjs;dom
| null |
_unix.367884
|
I have had a couple of directories mounted remotely from a Debian Jessie in a Windows share for a few months.In the last weeks, I been having complaints of random disconnects from the mount, and had to do asudo mount -ato regain the mount connectivity a couple of times (the server is used once or twice a week).e.g. the mounts are not recovering often after some period without being used.The Windows administrator also told me the Windows server has not been rebooted for a while.Today, coincidentally when doing mount -a again, it only worked in the 2nd try, while the first try gave the following error:sudo mount -amount error(104): Connection reset by peerRefer to the mount.cifs(8) manual page (e.g. man mount.cifs)mount error(112): Host is downRefer to the mount.cifs(8) manual page (e.g. man mount.cifs)The directories are mounted from /etc/fstab as such://10.2.1.2/XX/ZZ/YY /mnt/mount_point cifs credentials=/root/.smbcredentials,iocharset=utf8,file_mode=0770,dir_mode=0770,uid=1001,gid=1001 0 0When doing a mount command, you can also see the option echo_interval is activated by default at 60 minutes.$mount//10.2.1.2/XX/ZZ/YY on /mnt/mount_point type cifs (rw,relatime,vers=1.0,cache=strict,username=someusername,domain=XXX,uid=1001,forceuid,gid=1001,forcegid,addr=10.2.1.2,file_mode=0770,dir_mode=0770,nounix,serverino,mapposix,rsize=61440,wsize=65536,echo_interval=60,actimeo=1)What to do?
|
CIFS randomly losing connection to Windows share
|
debian;cifs
|
I found an interesting related post here cifs mounted folder keeps disconnecting (ubuntu server) talking of a similar problem (same error, Samba shares).The relevant tidbit here for following the rest of the answer is that CIFS mounts use the SMBv1.0 protocol by default, as can be verified issuing the mountcommand, and paying attention to the vers=1.0 field.$mount//10.2.1.2/XX/ZZ/YY on /mnt/mount_point type cifs (rw,relatime,vers=1.0,cache=strict,username=someusername,domain=XXX,uid=1001,forceuid,gid=1001,forcegid,addr=10.2.1.2,file_mode=0770,dir_mode=0770,nounix,serverino,mapposix,rsize=61440,wsize=65536,echo_interval=60,actimeo=1)I also found in Stack Overflow the post Mount CIFS Host is downThis could be also because of protocol mismatch. In 2017 Microsoft patched Windows Servers and advised to disable the SMB1 protocol.From now on, mount.cifs might have problems with protocol negotiation.The error displayed is Host is down. but when you do debug with:smbclient -L <server_ip> -U <username> -d 256 you will get the error: protocol negotiation failed: NT_STATUS_CONNECTION_RESETThe posts mentions that Windows patches to the protocol/Wannacry and others, are messing up with/or more exactly, some people disabled v1 CIFS requests funcionality; similar problems have been happening on the Windows front, and, given the timings, it makes me suspect the problem must be related. We have not disabled v1 CIFS in this specific server, AFAIK (and testing confirms this), however the MS bulletins suggest the default SMBv1 behaviour was (slightly) changed.I ended up following the general idea suggested in the mentioned Samba question. From man mounts.cifs:vers= SMB protocol version. Allowed values are: 1.0 - The classic CIFS/SMBv1 protocol. This is the default. 2.0 - The SMBv2.002 protocol. This was initially introduced in Windows Vista Service Pack 1, and Windows Server 2008. Note thatthe initial release version of Windows Vista spoke a slightly different dialect (2.000) that is not supported. 2.1 - The SMBv2.1 protocol that was introduced in Microsoft Windows 7 and Windows Server 2008R2. 3.0 - The SMBv3.0 protocol that was introduced in Microsoft Windows 8 and Windows Server 2012. Note too that while this option governs the protocol version used, not all features of each version are available.--verbose Print additional debugging information for the mount. Note that this parameter must be specified before the -o. For example: mount -t cifs //server/share /mnt --verbose -o user=usernameAs seen by the manual, in recent Windows versions after Windows 8 using at least vers=2.0 may make more sense; the alternative syntax in the command line with the --verbose option that is mentioned is also be useful to further debug any complication that may arise.As such, as the Windows server which I am mounting stuff from on this question is a Windows server 2008 R2, I put in /etc/fstab://10.2.1.2/XX/ZZ/YY /mnt/mount_point cifs credentials=/root/.smbcredentials,iocharset=utf8,file_mode=0770,dir_mode=0770,uid=1001,gid=1001,vers=2.1 0 0Then remounted it for the option to take effect:sudo mount -o remount /mnt/mount_pointNow we verify with mount again to confirm the negotiated protocol:$mount//10.2.1.2/XX/ZZ/YY on /mnt/mount_point type cifs (rw,relatime,vers=2.1,cache=strict,username=someusername,domain=XXX,uid=1001,forceuid,gid=1001,forcegid,addr=10.2.1.2,file_mode=0770,dir_mode=0770,nounix,serverino,mapposix,rsize=61440,wsize=65536,echo_interval=60,actimeo=1)And we can confirm we modified successfully the SMB protocol being used.See also MS Developer Network - [MS-SMB2]: Versioning and Capability Negotiation - 1.7 Versioning and Capability NegotiationIt should also be noted CIFS v1.0 besides obsolete is extremely inefficient and insecure compared to newer versions of the protocol.From MS blogs - Stop using SMB1SMB1 isnt modern or efficient When you use SMB1, you lose key performance and productivity optimizations for end users.Larger reads and writes (2.02+)- more efficient use of faster networks or higher latency WANs. Large MTU support. Peer caching of folder and file properties (2.02+) clients keep local copies of folders and files via BranchCache Durable handles (2.02, 2.1) allow for connection to transparently reconnect to the server if there is a temporary disconnection Client oplock leasing model (2.02+) limits the data transferred between the client and server, improving performance on high-latency networks and increasing SMB server scalability Multichannel & SMB Direct (3.0+) aggregation of network bandwidth and fault tolerance if multiple paths are available between client and server, plus usage of modern ultra-high throughout RDMA infrastructure Directory Leasing (3.0+) Improves application response times in branch offices through cachingInterestingly enough, this last articles suggests the disconnections problems are less likely to appear after a disconnection (Durable handles) if using a protocol >= 2.01, so I would stress again to not continue using CIFS v1.0. ( e.g while in 1.0 echo_interval=60 does keep it connected, if there is a network glitch or some other server interruption the mount wont recover itself without manual intervention while using the CIFS v1.0, I suspect)As a last piece of advice, avoid doing sudo mount -a and start doing:sudo mount -o remount -aSee my question also CIFS mounting multiple copies of the same share on the same mount point
|
_vi.5624
|
I just learned about tabs, meaning I can open them via:tabe some/file:tabe yet/another/file:tabe fooand circle them via gt (activate right one) and gT (activate left one).Yet when I close my vim instance via quit-all :qa, all my tabs are gone. How can I restore them all when entering vim again?
|
How do I restore a group of tabs?
|
sessions
| null |
_webmaster.61609
|
From an SEO point-of-view, which version is better:<input type=text name=q value=search />or<input type=text name=query value=search />Here's another example:<input type=text name=e value=email />or<input type=text name=email value=email />In other words: Does Google use the HTML input name attribute?
|
Using the HTML input name attribute and SEO
|
seo;google;html
|
There is no SEO value in this. This is not content. Use form names that makes the server side programming cleaner and easier to manage. This is way over-thinking SEO.
|
_softwareengineering.150699
|
According to section 11.2 of the App Store Review Guidelines,Apps utilizing a system other than the In App Purchase API (IAP) to purchase content, functionality, or services in an app will be rejected.Various apps like JetSetter, Gilt, and Kayak include in-app purchasing flows that either collect credit card information directly, or use a UIWebView to direct the user to a third-party website to purchase goods and services.What provision allows apps to do this, and what are the limitations to purchasing physical goods and services in an iPhone app without using IAP?
|
How do certain iPhone apps allow purchases without IAP?
|
iphone
|
It's all spelled out pretty clearly in the developer agreement, I think. If I remember correctly, you must use IAP to purchase content for your app, and you must not use IAP to purchase real-world goods and services. I haven't looked at the apps you mention, but a service like Kayak is surely selling real-world services (flights, hotel stays, etc.) rather than app content.
|
_softwareengineering.337132
|
OutlineI have an application that loads data from a database. I'm not talking about client data here though, I'm talking about application configuration. The database will therefore come with some default setup, which I want to remain unchanged so that future updates can just be imported and overwrite that setup.I would like for the client to be able to overwrite certain parts of that setup and/or add to it and/or remove from it (which probably won't actually be removed, just marked as deleted/disable). But I'd like a department and a user to also be able to do this and I'd also like for the most relevant changes to be loaded from the database.Essential RequirementsThe database contains standard application setup that cannot (or will not) be changed.The database stores changes based on company, department or user that provide modifications to the standard setup. These might be added configuration, or modifications to existing configuration or the disabling of standard configuration.My best effortA table with a combined primary key from two columns: [Id] and [Scope]. [Scope] determines whether or not it is the default setup, a company record, a department code or a user code. The [Id] can therefore be the same for each allowing each level of the client to have their own configuration of that same record. For example:Id | Scope | Name | Other columns...============================== 1 | -1 | MyApp | ... <- Default record 1 | 0 | Company Name | ... <- Company record 1 | 1 | Department X | ... <- Department record 1 | 101 | User X | ... <- User recordI really don't like this approach, I have to create a view that groups all the same Ids and then picks the most relevant record based on the type (i.e. if there is no user record, then use the department record, if no department then use the company and if no company then use the default).A lot of the information doesn't really change within the record either, maybe one or two columns (sometimes more though) and it seems wasteful to store the same data over and over again.RequestI'm really looking for ideas from people about how better to store and organise this kind of setup please?
|
How to set up a sql database to cater for user records, group records and default records?
|
design;design patterns;database design;sql server
| null |
_webapps.41863
|
While in Basecamp classic you were able to mark todo-lists or messages as private (only visible by your company), it seems that there's no such feature in the all-new version of Basecamp.I know that you can set permissions for whole projects in way that only your company is able to access the project and that you can move whole todo-lists to another project. But that's an annoying and complicated workflow.Is there another easy workflow which simulates the Private Items feature from Basecamp classic?
|
Is there something like private items in Basecamp?
|
privacy;collaboration;basecamp
|
Note: This has been implemented to the new basecamp a while ago (in 2013).
|
_unix.189930
|
I have upgraded my Ubuntu VM from 13.10 to 14.04.2 LTS. When I log in, it keeps telling me that a new release 14.04.2 LTS is available:Welcome to Ubuntu 14.04.2 LTS (GNU/Linux 3.11.0-18-generic x86_64) * Documentation: https://help.ubuntu.com/Your Ubuntu release is not supported anymore.For upgrade information, please visit:http://www.ubuntu.com/releaseendoflifeNew release '14.04.2 LTS' available.Run 'do-release-upgrade' to upgrade to it.I used do-release-upgrade to upgrade.How do I get rid of this message?Also, I was connected via SSH and after the installation it said it completed, but with errors, allthough I couldn't find any in the buffer of the PuTTY terminal. Where can I find the logs of the installation?
|
Ubuntu 14.04.2 LTS keeps telling that a new release is available
|
upgrade
| null |
_datascience.11531
|
I have a problem with using neurolab python library: I'm trying to predict some time-series with help of Elman recurrent neural network:import neurolab as nlimport numpy as np# Create train samples# x = np.linspace(-7, 7, 20)x = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 4, 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9, 5, 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 5.7, 5.8, 5.9, 6, 6.1, 6.2, 6.3, 6.4, 6.5, 6.6, 6.7, 6.8, 6.9, 7, 7.1, 7.2, 7.3, 7.4, 7.5, 7.6, 7.7, 7.8, 7.9, 8, 8.1, 8.2, 8.3, 8.4, 8.5, 8.6, 8.7, 8.8, 8.9, 9, 9.1, 9.2, 9.3, 9.4, 9.5, 9.6, 9.7, 9.8, 9.9, 10, 10.1, 10.2, 10.3, 10.4, 10.5, 10.6, 10.7, 10.8, 10.9, 11, 11.1, 11.2, 11.3, 11.4, 11.5, 11.6, 11.7, 11.8, 11.9, 12, 12.1, 12.2, 12.3, 12.4, 12.5, 12.6, 12.7, 12.8, 12.9, 13, 13.1, 13.2, 13.3, 13.4, 13.5, 13.6, 13.7, 13.8, 13.9, 14, 14.1, 14.2, 14.3, 14.4, 14.5, 14.6, 14.7, 14.8, 14.9, 15, 15.1, 15.2, 15.3, 15.4, 15.5, 15.6, 15.7, 15.8, 15.9, 16, 16.1, 16.2, 16.3, 16.4, 16.5, 16.6, 16.7, 16.8, 16.9, 17, 17.1, 17.2, 17.3, 17.4, 17.5, 17.6, 17.7, 17.8, 17.9, 18, 18.1, 18.2, 18.3, 18.4, 18.5, 18.6, 18.7, 18.8, 18.9, 19, 19.1, 19.2, 19.3, 19.4, 19.5, 19.6, 19.7, 19.8, 19.9]x=np.asarray(x)y = [0.000, 0.296, 0.407, 0.488, 0.552, 0.607, 0.655, 0.697, 0.734, 0.769, 0.800, 0.829, 0.855, 0.880, 0.903, 0.925, 0.945, 0.964, 0.982, 0.998, 1.014, 1.029, 1.043, 1.057, 1.069, 1.081, 1.092, 1.103, 1.113, 1.123, 1.132, 1.141, 1.149, 1.157, 1.164, 1.171, 1.177, 1.184, 1.189, 1.195, 1.200, 1.205, 1.209, 1.214, 1.218, 1.221, 1.225, 1.228, 1.231, 1.234, 1.236, 1.238, 1.240, 1.242, 1.244, 1.245, 1.246, 1.247, 1.248, 1.249, 1.249, 1.250, 1.250, 1.250, 1.250, 1.250, 1.249, 1.248, 1.248, 1.247, 1.246, 1.245, 1.243, 1.242, 1.240, 1.239, 1.237, 1.235, 1.233, 1.231, 1.228, 1.226, 1.224, 1.221, 1.218, 1.215, 1.213, 1.210, 1.206, 1.203, 1.200, 1.197, 1.193, 1.190, 1.186, 1.182, 1.178, 1.174, 1.170, 1.166, 1.162, 1.158, 1.154, 1.149, 1.145, 1.140, 1.136, 1.131, 1.126, 1.122, 1.117, 1.112, 1.107, 1.102, 1.096, 1.091, 1.086, 1.081, 1.075, 1.070, 1.064, 1.059, 1.053, 1.047, 1.041, 1.036, 1.030, 1.024, 1.018, 1.012, 1.006, 0.999, 0.993, 0.987, 0.981, 0.974, 0.968, 0.961, 0.955, 0.948, 0.942, 0.935, 0.928, 0.922, 0.915, 0.908, 0.901, 0.894, 0.887, 0.880, 0.873, 0.866, 0.859, 0.852, 0.844, 0.837, 0.830, 0.822, 0.815, 0.807, 0.800, 0.792, 0.785, 0.777, 0.770, 0.762, 0.754, 0.747, 0.739, 0.731, 0.723, 0.715, 0.707, 0.699, 0.691, 0.683, 0.675, 0.667, 0.659, 0.651, 0.643, 0.634, 0.626, 0.618, 0.610, 0.601, 0.593, 0.584, 0.576, 0.567, 0.559, 0.550, 0.542, 0.533, 0.525, 0.516, 0.507, 0.498, 0.490, 0.481]y=np.asarray(y)sample = [20, 20.1, 20.2, 20.3, 20.4, 20.5, 20.6, 20.7, 20.8, 20.9, 21, 21.1, 21.2, 21.3, 21.4]sample=np.asarray(sample)size = len(x)inp = x.reshape(size,1)tar = y.reshape(size,1)smp = sample.reshape(len(sample),1)#print(inp)print(tar)# Create network with 2 layers and random initialized#net = nl.net.newelm([[min(x), max(y)]],[5, 1]) # neurolab.net.newff(minmax, size, transf=None)net = nl.net.newelm([[min(x), max(y)]], [16, 1], [nl.trans.TanSig(), nl.trans.PureLin()])# Set initialized functions and initnet.layers[0].initf = nl.init.InitRand([-0.1, 0.1], 'wb')net.layers[1].initf = nl.init.InitRand([-0.1, 0.1], 'wb')net.init()# Train networkerror = net.train(inp, tar, epochs=1900, show=100, goal=0.0001)# Simulate networkout = net.sim(smp)print(out)It works fine with only one input time series (input vector). But I need more than one, in fact, I do need five input vectors.Example:I'm going to predict 6 rows of to_be_predicted column. The data: pastebin.com/7z1DeikJ. So columns usd, euro, GDP_bln, inflation, CPI are the inputs and to_be_predicted is a target in my case.Does anybody know how to solve this issue? Thanks for your help!
|
Is there any ability to use two ore more inputs for Elman recurrent neural network?
|
python;neural network;time series
| null |
_webmaster.49766
|
If I purchase a domain, I'm usually required to enter an address. Usually, the address can be accessed publicly by any sort of WHOIS lookup. I'm uncomfortable publishing my real home address; what do people usually do? Lie? Purchase a P.O box?
|
Concerns regarding registering a domain name with a home address
|
domains;domain registration;domain registrar
|
Not disclosing your personal contact information is a common concern, since as you state, it's otherwise publicly available at domain registrars, and any site that implements WHOIS lookups.There are Domain Privacy options available at most domain registrars however, for example: Private RegistrationThese will prevent the public from seeing your home address and contact information (including email address), while staying within ICANN guidelines since the registrar will act as the administrative contact and forward important emails regarding the domain to you.It's not a wise choice to provide false information during domain registrations because if there's ever a challenge for your domain name (UDRP) you'll lose the decision due to violating their terms requiring that all registrants provide valid information at the time of registration, as well as maintaining valid contact information throughout ownership.Additionally, the registrar may seize, or even delete the domain, if notices from them are not properly delivered. For example, some registrars confirm if addresses are valid on a periodic basis, and request that you update them if not. So if you don't receive these notices, you might have a serious issue with your domain...You can use a P.O. Box, however, that's more expensive on a monthly basis than just adding a privacy option for a year during registration and renewals (and all your other contact info will be blocked too).Tip: If you do opt for the privacy option during registration, look for discount codes so they're more affordable for the first year.
|
_vi.6870
|
I have this mapping in my vimrc:nnoremap <F3> :%s//\\{a}/g<CR> :%s//\\{o}/g<CR> :%s//\\{u}/g<CR> :%s//\ss{}/g<CR>after executing it, an 'R' is inserted above the current line, which of course doesn't make sense at all.the same applies tonnoremap <F3> :%s//\\{a}/g<CR> How can I debug this? Is this mapping even possible?EDIT my vim config
|
mapping with multiple substitutes inserts just a newline with 'R'
|
key bindings;substitute
| null |
_softwareengineering.244485
|
I'm trying to add data from a webhook (from a web cart) to a local Microsoft SQL Server. It seems like the best route for me is to use a PHP script to listen for new data (POST as json), parse it, then query to add to MSSQL.I'm not familiar with security concerning the connection between the PHP script (which would sit on a shared-host website) and the local MSSQL database. I would just keep the PHP script running on the same localhost (have Apache running on Windows), but the URI for the webhook needs to be publicly accessible.Alternately, I assume that I could just schedule a script from the localhost to check periodically for updates through the web carts API, though the webhooks seem to be more fool-proof for an amateur programmer like myself.What steps can I take to ensure security when using a PHP on a remote, shared-host to connect to MSSQL on my local machine?
|
Securely sending data from shared hosted PHP script to local MSSQL
|
php;security;sql server;server;server security
| null |
_cs.60020
|
I came across a question which asked how sorting would help in searching for counterexamples to the conjecture that $$u^6 + v^6 + w^6 + x^6 + y^6 = z^6$$ has no non trivial solutions in integers.The answer said to make two files containing values of $u^6 + v^6 + w^6 \pmod W$ and $z^6 - y^6 - x^6 \pmod W$. $W$ is the word size of the computer. Sort these, search for duplicates and go for further steps.Can someone explain what these further steps would be in detail ?
|
Use of sorting in counterexamples for equations
|
sorting;number theory
| null |
_unix.170677
|
I wrote a simple backup script which back ups my stuff on a remote server, everything is working great but I'd like to have some sort of report like backup successful or not.this is my script # backup CHECKdate1=`date +%d.%m.%y - %H.%M`host=`hostname`twdate=`date +%d.%m`performtw=`ls -la|grep tw|grep $twdate > tmp1.txt`echo $performtwifcat tmp1.txt|grep twthenecho backup successfullprintf tw backup success! | mail -s tw backup check $date1 repor$rm tmp1.txtelseecho backup failureprintf sitename backup failure! | mail -s site backup check $date1 repor$rm tmp1.txtfiexitBut this isn't working really well and I ask you if there's some simpler and more powerful way to do it? Basically it just needs to check if file exists with the name starting xyz and was created at date xyz.
|
Shell script check if file exists?
|
shell script;files;timestamps
| null |
_cogsci.4801
|
Petty is a word that is pretty clearly defined:Not very important or seriousRelating to things that are not very important or seriousI'm interested in measuring the degree that someone is likely to be focused on, or taking issue with things that most would consider to be trivial, unimportant or nonsensical. For instance, when interviewing a candidate for a position, how could I determine how likely this person is to latch onto issues that most would forget about within minutes of them occurring?To better illustrate what I'm trying to measure, suppose someone was exposed to the following bits of information in a day:The company lost over 14 billion in revenue due to gum-chewingThe city government outlawed all use of purple on WednesdaysWe realized that alien civilizations exist on Mars and have been emulating us by what they pick up from our radio emissions, and formed boy bandsA co-worker wasn't wearing the exact color socks specified in the employee handbookDespite the magnificence of events 1 - 3, the type of person very likely to place an inordinate amount of focus on all things petty can only dwell on number 4. Is there a term for this and, moreover, a test to determine the degree of it in an individual's personality?
|
Is it possible to quantify 'pettiness' in a personality?
|
measurement;personality
| null |
_webapps.11204
|
Is there a service that allows the simultaneous translation to multiple languages?For example I would type in a word and get it translated to the 20 most common languages.
|
Translate to multiple languages
|
translation
|
Nice Translator do just that.50+ langages available.
|
_scicomp.953
|
I'm talking about the vanilla sudoku game, with 9x9 grids equally split into 9 regions.I've tried a few approaches to estimate the probability that a specific number is in a specific location, but I can't seem to find the right pattern about it.Suppose I have this (partial) grid:What kind of calculation or method would help me find the probabilities of having a 8 in any of the free locations?Intuitively, I'd think there is a 50% chance of there being an 8 in any of the free locations of the two leftmost squares, but I'm not too sure what to think anymore with that rightmost almost-empty square.(I do realize that this specific example has multiple solutions; I couldn't come up with one that had just one solution but wasn't trivially easy to solve.)EDIT I also realize that since 'good' sudokus only have one solution, as Thomas Andrews noted, the probability that a certain location contains an 8 is either 0 or 1.Therefore, let's assume that I can determine the value of a square with 100% certainty if and only if it can be found through the naked single or hidden single techniques (that is, the number is either the only possible option for a square, or there is no other place where the number can be). Those two techniques are only enough to solve the most basic sudokus.If I chose to observe the grid with those two techniques only, even though I'd get stuck at some state, it would still be possible to enumerate several successor states that would seem legal at first, and very obviously, many of them would have overlapping results. For instance, taking the partial grid above, several successor states would have an 8 in the second square. And by counting every single occurrence of the 8 value in the second square, divided by the number of seemingly legal successor states, I would get what I call the probability of an 8 being there.The problem is that, even for a computer, counting those is sloooow. So I am wondering what kind of maths I could use the get the right answer, without resorting to the manual count, just knowing the constraints.
|
What is the probabilistic model behind sudoku grids?
|
combinatorics;constraints
| null |
_unix.176975
|
I appear to be having unexplainable issues with scripts run from within a subscript. I've been unable to acquire a solution so I will give you what I can to help me solve it.Problem: when a script is run from within a script, particular glitches occur that do not when running the script from the main shell, e.g. # ./userThe glitches that occur are that all 'echo' statement prints onto the same line, even given \n with '-e', '-n', or nothing at all. The other main glitch is that the 'read' statement in the code actually gets run before everything else, when it's one of the last things run in the debug code, from within the subscript.Below is the code being executed from within the main script. #!/bin/bash#Frame. /uhost/admin/uhost_files/UHU_FRAME.source. /uhost/admin/uhost_files/UHU_DIR_EXECUTE.sourcearr_uhu_arg=($@)command_get=$1function Help () { echo -e -n Allows creation, edition, and locking of user accounts stored on the UH2 system.\n echo -e -n Takes the following arguments: ${lblue} add lock del${nc}\n echo -e -n Can add, lock, and delete UNIX user accounts from the UH2 system.\n}function Start () { if [[ ${arr_uhu_arg[*]} == * add * ]]; then echo ===== USER ADD ===== echo Username: read uhost_username fi}if [[ $command_get == init_help ]]; then Help # Runs Help function when used by the help commandelse Start # Runs the main command's functionfiThe scripts are called via the line in the main script:echo `/bin/bash ${UHU_DIR_EXECUTE}/com/$uhu_sepcommand $uhu_sepcommand_arg1 $uhu_sepcommand_arg2`'$uhu_sepcommand' is the script file, followed by arguments.The partif [[ ${arr_uhu_arg[*]} == * add * ]]; then echo ===== USER ADD ===== echo Username: read uhost_username fiBoth 'echo' statements appear on one line, and the 'read' statement seems to execute before everything else.The glitches ONLY occur when executing the script from within the main script.Using GNU bash, version 4.2.37(1)-release (i486-pc-linux-gnu)Debian GNU/Linux 7.7EDIT #1The comment by Gilles actually answers my problem. The subscript was being accumulated all together and output as one 'lump'. To clarify, the glitch was output coming out inconsistently and incorrectly to what was written.Changing echo `/bin/bash ${UHU_DIR_EXECUTE}/com/$uhu_sepcommand $uhu_sepcommand_arg1 $uhu_sepcommand_arg2`to/bin/bash ${UHU_DIR_EXECUTE}/com/$uhu_sepcommand $uhu_sepcommand_arg1 $uhu_sepcommand_arg2solves the problem.
|
Bash Executing Script from within Script Causes Echo and Read Issues
|
bash;scripting
| null |
_softwareengineering.355999
|
This question might have been asked before, but I am unable to find it.So here goes:I am writing a program which connects to several databases (one at a time). It is using OleDbConnection at the moment, but will be changed to SqlConnection at some point.Should I create, and open a new connection every time, or simply close the existing connection, assign a new connectionstring, and reopen it.I know both solutions work, but why would I prefer one over other.For completeness sake, here is the implementation:Code executed when changing database.var connection = new OleDbConnection(connectionString);HasConnection = true;ConnectionEstablished(this, new ConnectionArgs<OleDbConnection>(connection));Code acting on that changepublic async Task ExecuteAsync(string query, Func<IDataReader, Task> onExecute, params DataParameter[] parameters){ using(var command = builder.BuildCommand(query)) { foreach(var parameter in parameters) command.AddParameter(parameter); if(!connection.IsOpen) connection.Open(); await command.ExecuteAsync(onExecute); }}private void OnConnectionEstablished(object sender, ConnectionArgs<IConnection> e){ this.connection = e.Connection;}This there a way to use the using statement, and still preserve this structure?
|
New connection vs new connectionstring
|
c#;database
|
The recommended approach is to open a new connection each time with the using statement.using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // Do work here; connection closed on following line. }The reason to prefer this approach is that it guarantees the connection will be closed after use.However, this would seem to be non-performant, except that there is a feature of the SqlConnection object called 'Connection Pooling'.To deploy high-performance applications, you must use connection pooling. When you use the .NET Framework Data Provider for SQL Server, you do not have to enable connection pooling because the provider manages this automatically, although you can modify some settings. For more information, see SQL Server Connection Pooling (ADO.NET).https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection(v=vs.110).aspxConnection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool.https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-connection-poolingIt looks like the ODBCConnection is slightly different, but still has a connection pooling option.Re:Updated questionSo there is the obvious way of just using the connection string from the passed in connection to make 'new' connections with using. But it would probably be best to refactor.Your current code has a race condition on the open statement and no close is shown.However, is connection pooling used? not sure. You only call open once, so I think everything will run on the same db connection with no requirement for the pooling code to do anything.This eliminates the race condition on Open, ensures commands can complete without the underlying connection closing or changing on them and ensures that all connections are closed;public async Task ExecuteAsync(string query, Func<IDataReader, Task> onExecute, params DataParameter[] parameters){ using(var conn = new SqlConnection(this.connstr)) using(var command = builder.BuildCommand(query, conn)) { conn.Open(); foreach(var parameter in parameters) { command.AddParameter(parameter); } await command.ExecuteAsync(onExecute); }}private void OnConnectionEstablished(object sender, ConnectionArgs<IConnection> e){ this.connstr = e.Connection.ConnectionString ;}
|
_softwareengineering.252419
|
I see a lot of code with variables declared right after the function, but when I post something like that people end up mad and say it is better to declare them when they are used.I assume this all compiles to the same executable, so it is simply a matter of style. As far as I can tell, pretty much all C code (99.9% that I've seen) declares them near the beginning and this is how it has been done for many years.So why do people keep suggesting that they are declared closer to the block that uses them?
|
Where are C variables declared
|
coding style;declarations
| null |
_opensource.2648
|
At the Philosophy of the GNU Project, there is one page Why we must insist on free software which states the importance/significance and advantages of free software.So, I want to know what OSI states/shows the importance & advantages of open source?I can see at the mission statement at about page:Open source is a development method for software that harnesses the power of distributed peer review and transparency of process. The promise of open source is higher quality, better reliability, greater flexibility, lower cost, and an end to predatory vendor lock-in.But I'm looking for the (demonstrating) topics like:How open source is better?How open-sourcing is important? or Why open source?
|
What significance & advantages does the OSI say about open source?
|
osi;fsf
| null |
_cogsci.12349
|
I've long been interested in the concept of states of mind, which influence the perception of the outside world and outlook on past, present and future. They can be thought of as colored lenses through which the world is perceived. Each state has a certain trigger. Some example states are:Anxiety - world is a terrible place full of dangerSexual arousal - brain notices sexual stimuli more and reduces inhibitionsCreative inspiration - ideas fly and there's a drive to createToday I've read about an experiment to replicate a part of a rat brain in supercomputer. The following quote jumped at me as rather significant:The researchers wrote, that the slow synchronous waves of neuronal activity, which have been found in the brain during sleep, were triggered during the simulations, suggesting that neural circuits may have the unique ability to able to switch into different modes that could explain critical behaviours.An analogy would be a computer processer that can reconfigure to focus on certain tasks. The experiments suggest the existence of a spectrum of states, so this raises new types of questions, such as what if youre stuck in the wrong state? said Markram.I read that the project is criticized due to it's complexity, seems like they are working from the bottom up, which makes me ask:Are there projects out there that attempt to model the brain from the higher levels of abstraction (discrete states and their triggers) down to more detail?To use a computer analogy - instead of writing very low level binary code, I can take a high level programming library and work with that. Is there research in this direction?This image is an example of a state machine - a system is modelled in terms of discrete states and their interactions. The author does not concern themselves with interaction of individual neurons, instead with higher level states:
|
Can a brain be modeled as a simplified interaction of different states and their triggers?
|
cognitive psychology;cognitive neuroscience;cognitive modeling;behavior
|
My answer is probably a weird hodgepodge of sometimes poorly explained stuff, but hopefully it's coherent enough :PFor many decades in psychology, we've had a mechanistic stimulus-organism-response understanding of the brain. That is, a stimulus triggers an internal psychological process, which produces some behavioral response. One of the major limitations of this kind of thinking is that it assumes that the mind is at rest until it's stimulated by something in the environment (even if we add a recursive component to it). However, this is fundamentally untrue. Instead, the brain is a predictive organ (e.g., Clark, 2013). It's loaded with prior knowledge about past experiences, which is constantly used to predict incoming sensory information. If there is a discrepancy between incoming information and past experience (i.e., prediction error), then our knowledge is updated. This is most clearly seen in the literature on vision, which shows how top-down expectations and prior knowledge robustly bias early visual activity, even in the absence of a visual stimulus (Summerfield & de Lange, 2014). The trigger-state model could not easily account for this.Moreover, dividing up the brain into mental states may not actually represent how the brain functions. The brain isn't really faithful to the kinds of distinctions we make between cognition and emotion, for example (e.g., Barrett, 2009; Pessoa, 2008). And not only that, those higher order states like anxiety and sexual arousal can be represented in the brain in many different ways. Indeed, there is no dedicated mechanism in the brain or body for producing states like anxiety or creative inspiration (e.g., Wager et al., 2015). They're merely concepts for organizing and communicating our experience. And even then, our brain may not really have concepts (see Laurence Barsalou's work; but see also Blouw, Solodkin, Thagard, & Eliasmith, 2015), although it may have a conceptual system that allows us to conceptualize (e.g., Barsalou, 2005).So I guess what I'm getting at is that brain function is nonlinear, spatiotemporally dynamic, and doesn't adhere to folk psychological categories. Thus, it would probably be difficult to understand the brain by attempting to reduce linear trigger-state relationships to the level of networks, regions, and cells. However, maybe (probably) someone has a better informed, more balanced answer than me! :)
|
_unix.179134
|
I am trying to set up networking on my development server running Arch Linux, but something is amiss. I have enabled dhcpcd on all interfaces, and ping now works (including dns resolution), but curl/other TCP programs do not. Does anyone have any ideas for how to go about debugging this? Thank you in advance.
|
ping works but curl does not
|
networking;arch linux
| null |
_cs.71374
|
A language $L$ is definite if there is some $k> 0$ such that for any string $w$, whether $w \in L$ depends on the last $k$ symbols of $w$. How can I prove that every definite language is accepted by a finite automaton?
|
Show that every definite language is accepted by a finite automaton
|
finite automata
|
This is true as a consequence of the Myhill Nerode theorem. For any fixed $k\gt 0$, the number of possible combinations of the last $k$ symbols of any string $w\in L$ is $|\Sigma|^k$, where $\Sigma$ is the alphabet.Any two strings that have the last $k$ symbols identical will always be both accepted or both rejected by $L$, for any string appended to them, i.e., no string in $\Sigma^*$ will distinguish such strings. Thus, such strings lie in the same equivalence class of $L$.Strings with differences in their last $k$ symbols will either lie in different equivalence classes or will cause the classes demarcated in the previous step to collapse together into a single class.Thus, the equivalence classes of $L$ are determined by the last $k$ symbols of $L$.As the possible combinations of the last $k$ symbols is finite, the number of equivalence classes is finite. Thus, by the Myhill Nerode theorem, the language $L$ is regular. Hence, there exists a DFA that accepts $L$.
|
_unix.249024
|
I have a hard drive that got corrupted after a doing an MTP mounting of a cell phone. It was created under Fedora Core 20 using defaults. Originally, I thought I did it as an ext4 partition. I tried mounting it as an ext4 it couldn't and fsck reported corrupt superblocks. The TestDisk program couldn't determine what the partition was either. Out of desperation, I created new superblocks as follows:mke2fs -n -b 2048 /dev/sdb3The partition could still not be mounted. Later saw from a grub.cfg file the following linelinuxefi /vmlinuz-3.19.8-100.fc20.x86_64 root=/dev/mapper/fedora_dfl-root ro rd.lvm.lv=fedora_dfl/swap vconsole.font=latarcyrheb-sun16 rd.lvm.lv=fedora_dfl/root rd.luks.uuid=luks-a0d2613e-ce2a-4a6b-96cf-b999b3a36ab8 rhgb quiet LANG=en_US.UTF-8My guess is that I created an encrypted volume and forgot that I did so. Fortunately, I only use a few passwords so guessing which one I used shouldn't be too hard. In a perfect world, I'd love to have the full volume back. However, I hope to get back a couple of files.
|
Decrypt a portion of a corrupted drive
|
partition;encryption;ext4;luks
| null |
_cs.50525
|
Let $X = \{x_1, x_2, ..., x_n\} \subset \mathbb{R}^m$ be a finite set of points. Smallest enclosing ball is a well-known problem that asks for the $m$-ball that covers all $x_i \in X$, while having the smallest radius possible.I am interested in solving a related, more constrained problem. Namely, in my version, the enclosing $m$-ball's center can not be chosen freely, but is constrained to be one of the points in $X$. In other words, I would like to find the point $x_j \in X$ such that the maximum distance (i.e. the enclosing radius)$$\max_{x \text{ } \in \text{ } X} \; \lVert x - x_j \rVert$$is minimized.Obviously, one can simply compute all distances in $O(m n^2)$ time, and find the desired point. A less naive way to tackle the problem would be to generate a space-subdividing acceleration structure, say a kd-tree. We can do this in $O(m n \log n)$. Then, per-node maximum distances can be computed in $O(f(m, n))$ time, and we can pick the node having the minimum-maximum distance. This method would have a complexity of $O(n (f(m, n) + m \log n))$. Here, $f(m, n)$ is a function that stands for the query complexity of the kd-tree. Therefore, $f(m, n)$ looks like $m \log n$ for small $m$, but $m n$ for large $m$.All in all, we would still be making many repeated (and unnecessary) distance computations. Also, because of how $f(m, n)$ behaves, the latter method degrades to the former for big $m$. Therefore, even the latter solution is not very satisfactory.Can we do better? What is the best (in terms of time complexity and practical performance) known algorithm to tackle this problem?
|
Constrained Smallest Enclosing Ball Problem
|
algorithms;computational geometry
| null |
_unix.46289
|
I would like to apply the Toogle Invert Effect when I start my system.So, I need to know how to call this KWin effect using the terminal.OBS.: I'd tried xte keydown Meta_L key i keyup Meta_L, but didn't work.
|
How to emulate a KWin effect by command line?
|
command line;scripting;kde;window;kwin
| null |
_vi.11155
|
I like the functionality of gf but for certain files I would like to run some (non-Vim) code on the file prior to displaying it in my window. Is there a way to capture the filename under the cursor so it can be used in a shortcut?For example, I want to create a shortcut that would run <custom_unix_script> <file> (where is under the cursor) and display those results in a new buffer or tab.
|
How do I run a command on the file name under the cursor
|
vimscript
|
In addition to @Luc Hermitte's answer of using expand(<cfile>), you can also use the :! command to run a shell command. You could do something like the following:nnoremap gf :execute !<custom_unix_script> . expand(<cfile>)nnoremap: Creates a normal mode non-recursive mapping:execute: Allows us to build the command on the fly:!...: Runs the following command in your shellexpand(<cfile>): Uses the file-like word under your cursorNote that this will do this for ALL files. If you want to filter by certain files you'll need to get a little bit more fancy. I'd recommend calling a function and doing a conditional on the output of expand(<cfile>).See :h expand, :h <cword>, :h execute, and :h !cmd for more info.
|
_webmaster.24077
|
I'm writing a big index of documents and I'm dealing with URLsas example I will use the car industry:somesite.com/manifacturer-mazda_model-miata_engine-1600cc_gas_color-red_hard-top-spider_[[A LOT MORE]].htmthis url points to a generated content that can't be identified as a single resource (in practice, every keyword is a filter and the page result is generated by a database search)at Google's eyes an URL like this looks spammy or I can use this solution with freedom?using querystring instead of URL rewriting can fix risks? and, in this case, keywords will be considered as keyword for SERPs?thank you in advance,feel free to correct my English!
|
how to deal with URLs containing lot of spammy keywords?
|
google;url;seo;query string
|
If you have enough different content for each result page that should be ok. Google is intelligent enough to know that keywords in URL and in query string is the same (but by using Google Webmaster Tools, you can filter query string only).In your case, those are categorized pages, so that's ok.About keywords in URL (or as query string): IMHO we don't need them. Google recognises them, but if we put them in a meta tag, Google recognises them, too, and we don't need to put all in URL, just 3-4 are ok.
|
_softwareengineering.202704
|
What values in an application should be configurable, or otherwise not hard coded? Does this differ based on application type (batch vs UI) and are there any published standards or guidance on this topic (IEEE, ACM, vendor, etc)?
|
What values in an application should be configurable?
|
design;coding standards;configuration
| null |
_softwareengineering.213963
|
In a team that I used to work for, there was a policy that if you introduced a memory or other resource leak, you got a 'dummy of shame' hung on your door until you found the next resource leak.While it was effective at finding resource leaks, I felt like it placed more emphasis on blaming others rather than working together to solve problems as a team.Am I being unreasonable in thinking that this policy contributed to a lower sense of team cohesion? Am I also being unreasonable in thinking that we should have rewarded those people who found and fixed the issue?
|
Assigning Blame for Bugs versus Giving Rewards for Fixes
|
development process;teamwork
| null |
_webmaster.43507
|
I'm already hosting my site, and looking for another host. So I need to know how much bandwidth my website is using.On my current host I can see only following bandwidth related data:Outbound traffic (24 hours)Maximum 801kb/sAverage 398kb/sI want to know how many Gb/month I need.
|
How to calculate Website Bandwidth?
|
web hosting;bandwidth
|
398 (kb/sec) * 60 (sec/min) * 60 (min/hour) * 24 (hours/day) * 30 (days/month) / (8 (bits/byte)) / (1024 KB/MB) / (1024 MB/GB) = 123 GB/Month
|
_webmaster.58330
|
We build websites, and some that accept user data and/or allow creation of accounts with personal information. What's the worst that could happen if you don't have a Privacy Policy on your website? I know that the site needs one.Also, whats the worst a consumer or parent can do when he/she encounters a site (for adults or children) without a Privacy Policy, apart from complaining to some court or legal authority? Is there a central place for this in the US and other countries?
|
What's the worst that could happen with no Privacy Policy
|
legal;privacy;privacy policy
|
In the U.S.? Nothing. Sorta. A privacy policy is a good idea and helps trust organizations such as eTrust evaluate your site for trust. It also helps the site user. I always read the privacy policy when any account or PII (personally identifiable information) is taken.The exception is where a site engages in marketing and serving to children 13 and under. There are legalities involved and a privacy policy is required. http://en.wikipedia.org/wiki/Children%27s_Online_Privacy_Protection_ActIf your site is clearly not for children, then it is just good business even for sites that do not have account registrations but do capture usage information, uses cookies, or uses a 3rd party tool that may do the same such as Google Analytics and Adsence.If your site is purely informational and you do nothing else but evaluate site logs, then I would not worry about it unless you want a trust organization to give a better score.The Wikipedia page on this is very good. http://en.wikipedia.org/wiki/Privacy_policy Here you will see as much information as there probably is with good links on the subject.
|
_codereview.68219
|
I'm trying to write a program where you can insert and display some books (without using a database).For doing this, I use three classes:Book - is the base class.TehnicBook and Literature - that will inherit some properties from Book.#include <iostream>#include <string>#include <stdlib.h>using namespace std;class Book {public: string author, title; bool rented; Book(string &author, string &title, bool rented) { this -> author = author; this -> title = title; this -> rented = rented; }; void display(void);};class TehnicBook:public Book { int amount, RlYear; string language; TehnicBook *head, *next;public: TehnicBook(string &author, string &title, bool rented, int amount, string &language, int RlYear):Book(author, title, rented) { head = NULL; this -> language = language; this -> amount = amount; this -> RlYear = RlYear; }; ~TehnicBook(void) { delete head; }; void display(void); void add(void); void dellete(string&);};class Literature:public Book { string bookType; Literature *head, *next;public: Literature(string &author, string &title, bool rented, string &bookType):Book(author, title, rented) { head = NULL; this -> bookType = bookType; }; ~Literature(void) { delete head; }; void display(void); void add(void);};void TehnicBook::add(void) { string author, title, language; int year, amount; bool rented; cout << endl << Author: , cin >> author; cout << Title: , cin >> title; cout << Rented? (0/1): , cin >> rented; cout << The amount of books: , cin >> amount; cout << Language: , cin >> language; cout << Release year: , cin >> year; TehnicBook *p = new TehnicBook(author, title, rented, amount, language, year); p -> next = head; head = p;}void TehnicBook::display(void) { TehnicBook *p = head; while(p) { cout << -----------------------------\n; cout << Author: << p -> author << endl; cout << Title: << p -> title << endl; cout << Is << ((p -> rented) ? : not ) << rented << endl; cout << Amount of books: << p -> amount << endl; cout << Language: << p -> language << endl; cout << Release year: << p -> RlYear << endl; cout << endl; p = p -> next; }}void Literature::add(void) { string author, title, bookType; bool rented; cout << \nAuthor: , cin >> author; cout << Title: , cin >> title; cout << Is rented? , cin >> rented; cout << Book type (hardcover/...: , cin >> bookType; Literature *p = new Literature(author, title, rented, bookType); p -> next = head; head = p;}void Literature::display(void) { Literature *p = head; while(p) { cout << \n-----------------------------\n; cout << Author: << p -> author << endl; cout << Title: << p -> title << endl; cout << Is rented? << ((p -> rented) ? yes : no) << endl; cout << Book type: << p -> bookType << endl << endl; p = p -> next; }}int main(int argc, char const **argv) { string blank = ; TehnicBook *tehnicB = new TehnicBook(blank, blank, false, 0, blank, 0); Literature *litB = new Literature(blank, blank, false, blank); int opt; for(;;) { cout << \n\n1) Add a tehnic book.\n; cout << 2) Display all tehnic books.\n; cout << 3) Add a literature book.\n; cout << 4) Display all literature books.\n; cout << 5) Exit.\n\n; cout << Your option: , cin >> opt; switch(opt) { case 1: tehnicB -> add(); break; case 2: tehnicB -> display(); break; case 3: litB -> add(); break; case 4: litB -> display(); break; case 5: exit(0); default: continue; } } return 0;}Am I doing this right? Any better ideas?
|
Inserting and displaying books
|
c++;beginner;inheritance;polymorphism
|
Major bug: Book::~Book is not virtual. This means you have a memory leak in the following case:TehnicBook *tb = new TehnicBook(...);tb->add(...);Book *b = tb;delete tb; //<- tb->head is leakedIf you have C++11 I recommend that every class either has a virtual destructor or is declared final such as class Book final{...}.Major design issue: You are combining TehnicBook with a linked list. A class should have only one responsibility: Either manage a book or manage memory, not both. At least use std::list or better std::vector. Better remove add from TehnicBook and Literature and put a vector<Book> into main to seperate storage and functionality.Similarly add should not use cin and cout. You are mixing user interface and class functionality. It should simply take a TehnicBook *. You can make a free standing function that conveniently does this, but it should not be part of TehnicBook.Similarly display should not use cout. Either make it return a string which you then give to cout or teach cout how to print books such as this:ostream &operator <<(ostream &os, TehnicBook &t){ os << os << -----------------------------\n; os << Author: << p->author << endl; os << Title: << p->title << endl; os << Is << ((p->rented) ? : not ) << rented << endl; os << Amount of books: << p->amount << endl; os << Language: << p->language << endl; os << Release year: << p->RlYear << endl; os << endl; return os;}Now you can do TehnicBook book(...); cout << book;, which is pretty neat, but more importantly you can do things like ofstream file(test.txt); file << book;, so we got printing a book to a file and TCP-streams and so on for free.I see void dellete(string&); inside TehnicBook, but no implementation. I guess you meant to add the functionality to remove books from the list. Remove this function, it does not belong to a TehnicBook.Is TehnicBook supposed to be TechnicBook or TechnicalBook?This may be a bit over your head, but I want to at least mention it: Do not use new and delete. Ever. Instead use make_unique.TehnicBook *tehnicB = new TehnicBook(blank, blank, false, 0, blank, 0);becomesauto tehnicB = make_unique<TehnicBook>(blank, blank, false, 0, blank, 0);The point is that now you do not need to manage memory. Managing memory is very difficult and error prone and unnecessary. For example you forgot to clean up tehnicB and litB inside main. This automatically gets fixed without thinking about it with modern C++.
|
_unix.313744
|
When i run this find command:find /html/car_images/inventory/ -type f -iname \*.jpg -mtime -4i get output like this:/html/car_images/inventory/16031/16031_06.jpg/html/car_images/inventory/16117/16117_01.jpg/html/car_images/inventory/16126/16126_01.jpg/html/car_images/inventory/16115/16115_01.jpg/html/car_images/inventory/16128/16128_02.jpg/html/car_images/inventory/16128/16128_03.jpg/html/car_images/inventory/16128/16128_04.jpgMy goal is to delete a thumbnail folder that exists in each of these directories (ie delete this folder: /html/car_images/inventory/16128/thumbnails/ and also delete /html/car_images/inventory/16115/thumbnails/I'm thinking perhaps of a script that takes each line of output from the above find command, then replaces *.jpg with thumbnails and adds as a prefix rm -fr such that i end up with this:rm -fr /var/www/html/car_images/inventory/16115/thumbnails/rm -fr /var/www/html/car_images/inventory/16128/thumbnails/and so on...Any ideas on how to do this? (maybe using the -exec option of find and sed or cut?)(another way to phrase my entire goal is, if a folder contains a .jpg file that is younger than X days, than delete the thumbnails folder, in its folder)
|
Use output from find command to then remove a specific directory
|
command line;find;rm;command substitution
|
Assuming you don't have filenames with newline(s):find /html/car_images/inventory/ -type f -iname \*.jpg -mtime -4 \ -exec sh -c 'echo ${1%/*}' _ {} \; | sort -u | \ xargs -d $'\n' -I{} rm -r {}/thumbnailsThe parameter expansion, ${1%/*} extracts the portion without the filename from each found entrysort -u sorts and then make the entries unique so that we don't have any duplicatexargs -I{} rm -r {}/thumbnails adds thumbnails at the end, and then remove the resultant directory
|
_webmaster.61281
|
I have installed Nginx webserver on my system. I just need to know the IP adress of the server which am running. I have Googled many times but I didn't get a good answer.
|
How do I find my home servers IP address?
|
server;ip address
|
If you are on Windows, use the command line and enter ipconfig.If on Linux, enter ifconfig from the terminal to find out your ip address. I believe it's ifconfig on Mac too.
|
_unix.50644
|
I have a virtual machine that I am trying to use. It doesn't seem to have dpkg or apt-get, so I downloaded the source from http://packages.debian.org/sid/dpkg-dev.If I run ./configure followed by make I get$ makemake all-recursivemake[1]: Entering directory `/home/dbadmin/temp/dpkg-1.16.8'Making all in libmake[2]: Entering directory `/home/dbadmin/temp/dpkg-1.16.8/lib'Making all in compatmake[3]: Entering directory `/home/dbadmin/temp/dpkg-1.16.8/lib/compat' CC empty.occ1: error: unrecognized command line option -Wvlamake[3]: *** [empty.o] Error 1make[3]: Leaving directory `/home/dbadmin/temp/dpkg-1.16.8/lib/compat'make[2]: *** [all-recursive] Error 1make[2]: Leaving directory `/home/dbadmin/temp/dpkg-1.16.8/lib'make[1]: *** [all-recursive] Error 1make[1]: Leaving directory `/home/dbadmin/temp/dpkg-1.16.8'make: *** [all] Error 2I tried $ ./configure --disable-compiler-warnings$ maketo get ... CC trigproc.o CC update.o CCLD dpkgarchives.o: In function `tar_writeback_barrier':/home/dbadmin/temp/dpkg-1.16.8/src/archives.c:1139: undefined reference to `sync_file_range'archives.o: In function `fd_writeback_init':/home/dbadmin/temp/dpkg-1.16.8/src/archives.c:77: undefined reference to `sync_file_range'collect2: ld returned 1 exit statusmake[2]: *** [dpkg] Error 1make[2]: Leaving directory `/home/dbadmin/temp/dpkg-1.16.8/src'make[1]: *** [all-recursive] Error 1make[1]: Leaving directory `/home/dbadmin/temp/dpkg-1.16.8'make: *** [all] Error 2This is my machine$ uname -aLinux server.name.domain.tld 2.6.18-194.26.1.el5xen #1 SMP Fri Oct 29 14:30:03 EDT 2010 x86_64 x86_64 x86_64 GNU/LinuxHow should I go about getting a functional package manager on this?Update:$ gcc --versiongcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-51)
|
Can't install dpkg on Linux 2.6.18
|
linux;software installation;dpkg
|
Dpkg is designed to work on Debian and Debian-like distributions. It can be difficult to compile on other systems, and you wouldn't be able to use it effectively anyway. Also, a kernel version of 2.6.18 is ancient (I smell CentOS 5), only an older version of dpkg has a chance of working.gcc --version gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-51)So you have a Red Hat distribution: RHEL or a repackaging thereof such as CentOS. The basic package manipulation tool (the equivalent of dpkg) on Red Hat distributions is rpm. The high-level package manipulation tool (the equivalent of apt-get) is yum.For more systematic ways of determining which distribution a Linux machine is running, see How to write a script that effectively determines distro name?. If you're lucky, lsb-release -si will give you the answer. Otherwise, look for indicative files such as /etc/*release* or /etc/*version*.
|
_unix.13801
|
Suppose a photograph with text and numbers. I want to manage it in my editor with tools such as grep, standard text-processing things such as Vim's block-highlighting and also more advanced things such as Gimp's magic-wand-style pattern highlighting. How?Analysis This puzzle breaks down at least to partsOCR -- character recognizationDSP -- proximity -algos, all puzzles not yet knownAscii-art -- creating fillers and decorators (not technical term)For the sake of simplicity, suppose the writing is line-wise so you do not need to consider reprocessing multiple-lined documents. There is some working-prototype that does pretty good job in small scale with LaTex here, the multiple lined problem follows later.
|
Image (having text-and-numbers) to text-file matching [:alnum:] nicely with some Unix -tool?
|
image manipulation;ascii;ocr;dsp
| null |
_unix.251303
|
I was trying to set compression for jboss log files. The log files I want to compress are console.log and server.log. Compression for console.log is working fine, but server.log I am seeing issues. I am using logrotate for using compression . Please find my rules below . $cat /etc/logrotate.d/jboss /data/logs/*/console.log /data/logs/*/server.log { daily rotate 14 copytruncate compress missingok postrotate # Service restarts go here. endscript}log files are named as follows-rw-rw-r-- 1 jboss logs 139 Dec 21 03:23 console.log-20151221.gz-rw-rw-r-- 1 jboss logs 12195934 Dec 21 23:59 server.log.2015-12-21-rw-rw-r-- 1 jboss logs 1383 Dec 22 03:40 console.log-20151222.gz-rw-rw-r-- 1 jboss logs 12157917 Dec 22 23:59 server.log.2015-12-22-rw-rw-r-- 1 jboss logs 1037 Dec 23 03:32 console.log-20151223.gz-rw-rw-r-- 1 jboss logs 11966496 Dec 23 23:59 server.log.2015-12-23-rw-rw-r-- 1 jboss logs 142 Dec 24 03:10 console.log-20151224.gz-rw-rw-r--. 1 jboss logs 113 Dec 24 12:27 console.log-rw-rw-r-- 1 jboss logs 8730030 Dec 24 17:35 server.logPlease suggest .
|
log compression using logrotate
|
logs;compression;logrotate;jboss
| null |
_scicomp.5366
|
For your information, the original equation comes from here. Note: You DON'T have to read the paper. I will make the question as self-contained as possible.The central equation to solve is equation (16), which is of the form (my question extends to other system of PDE with similar form):$\dfrac{\partial f_n(x;\tau)}{\partial \tau}=\left[[-(n-6)+\dot{\bar{A}}x]\dfrac{\partial}{\partial x}+2\dot{\bar{A}}-(c_++c_-)n\right]f_n(x;\tau)+c_+(n-1)f_{n-1}(x;\tau)+c_-(n+1)f_{n+1}(x;\tau)$$x$ is continuous and positive, $\tau$ is basically time, $n$ is positive integer number and $f_n(x;t)$ goes to zero very quickly as $x\rightarrow\infty$ so that we can have a cutoff $x_{max}$. The boundary conditions used by the paper is called used open boundary conditions, i.e., probability ($f_n(x;\tau)$ is proportional to probability density) could flow out of the system across the cutoffs, but no probability could flow into the system, since $f_n(x)$vanished beyond the cutoffs.additional clarifications for the symbols: $\dot{\bar{A}}=\sum_{k=0}^5(6-k)f_k(0;\tau)$, $c_+=(1/6)f_5(0;\tau)$ and $c_-=(1/6)\sum_{k=0}^5(6-k)f_k(0;\tau)$.My understanding of the above description is that the BC looks like some kind of absorbing boundary conditions. The mass of $f_n$ can flow outside the interval $[0,x_{max}]$ but nothing outside can flow into the interval, such that the integral of $f_n(x;\tau)$ over the interval will decrease with time.If we discretize $x$, it's not very difficult to write a program for explicit scheme according to the above description, but the implicit scheme would be difficult (there are two index $x$ and $n$). So my question is: how to write down the mathematical statement (for continuous $x$) for such boundary conditions? The motivation for writing down a mathematical statement instead of directly writing down the BC for discretized $x$ is that I can let software such as Mathematica. Then why don't I ask the question in Mathematica exchange? Yes, I did. But the folks there seemingly thinks that I should figure out the mathematical statement first.
|
mathematical statement of open boundary condition
|
pde;hyperbolic pde;boundary conditions
| null |
_webapps.56538
|
I didn't get a Facebook look back movie. I've been on Facebook since it was thefacebook in 2005 and I've shared my little heart out. Anybody know if the automated video is linked to security settings or other things that might be locking me out? I get the lame collage of 6 pictures that were all posted in the last week. No, thanks. I'd rather have a movie.
|
Collage of six photos, not Facebook Lookback movie
|
facebook;facebook lookback
| null |
_scicomp.11627
|
Is there a C++/C implementation of the Appell series? GSL and Boost do not seem to have this function.
|
Appell function implementation in C++?
|
c;special functions
| null |
_webapps.70699
|
When I get an email from someone in Gmail, there's a list of names of other people at the top who also received this email. My name is always listed as, me instead of my email name. Is there any way I can change this to my email name?
|
Show actual name instead of me in Gmail received emails
|
gmail
| null |
_unix.60261
|
When using grep -r you could search in all files with either * or .and it seems to return the same thing but is it really the same?Let's say I search for foo, then I could write grep -r foo *orgrep -r foo .Would anyone try to explain the difference between . and *?
|
grep -r foo * vs grep -r foo .
|
grep;wildcards
|
grep -r foo * doesn't look for matches in hidden files or directories,also * is expanded by the shell so you might end up with an Argument list too long error when there are a lot of entries in the current directory, or some other errors or misbehaviour if the name of some of the files or directories starts with a dash character. Invocation grep -r foo . doesn't have the above flawsUpdated:Another difference: grep's man page (@fedora17) says: -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. ...There will be also a difference when you execute this command in an empty directory:$ grep -r foo *; echo $?grep: *: No such file or directory2$ grep -r foo .; echo $?1$
|
_codereview.163019
|
I need to learn more about Entity Framework, so I created a database to store notes. The database definition is as follows:public class User{ [Key] public int UserId { get; set; } [MaxLength(20)] public string UserName { get; set; } public virtual List<Note> Notes { get; set; }}public class Note{ [Key] public int NoteId { get; set; } [MaxLength(30)] public string Title { get; set; } [MaxLength(200)] public string Content { get; set; } public int UserId { get; set; } public virtual User User { get; set; }}public class NotesContext : DbContext{ public DbSet<User> Users { get; set; } public DbSet<Note> Notes { get; set; }}I wrote the following helper functions (I'm working off a Console Application for now):class Program{ private static void AddUser(string userName) { using (var db = new NotesContext()) { db.Users.Add(new User { UserName = userName }); db.SaveChanges(); } } private static void RemoveUser(int userId) { using (var db = new NotesContext()) { var user = db.Users.FirstOrDefault(u => u.UserId == userId); if (user != null) { db.Users.Remove(user); db.SaveChanges(); } } } private static void ClearUsers() { using (var db = new NotesContext()) { db.Users.RemoveRange(db.Users); db.SaveChanges(); } } private static void AddNote(int userId, string title, string content) { using (var db = new NotesContext()) { db.Notes.Add(new Note { UserId = userId, Title = title, Content = content }); db.SaveChanges(); } } private static void RemoveNote(int noteId) { using (var db = new NotesContext()) { var note = db.Notes.FirstOrDefault(u => u.NoteId == noteId); if (note != null) { db.Notes.Remove(note); db.SaveChanges(); } } } private static void ClearNotes() { using (var db = new NotesContext()) { db.Notes.RemoveRange(db.Notes); db.SaveChanges(); } }}Other than the fact that it would be somewhat expensive to add or remove a set of users using these extensions, rather than getting one DB instance, updating it, and running SaveChanges() once, is there anything I should be doing differently?
|
Code-First Notes Database
|
c#;entity framework
| null |
_unix.294562
|
If you have a series of sub folders (like from a to z) and want to run a command on each one of them (like dsmmigrate * & ) how do you do that? The manual approach would be,cd a dsmmigrate * &cd ../bThat seems too complicated, so I believe there must be an easier approach.
|
How to Run a command on all subfolders
|
shell;files;wildcards
| null |
_unix.251174
|
Using Cygwin, I installed Environment Modules by downloading source code, running configure, make, and make install. Every time I run a module command, I get:init.c(718):WARN:165: Cannot set TCL variable '!::'I've traced this down to the fact that Cygwin has the following environment variable set:$ env | grep ::!::=::\Does anyone know what this is, where it is set, why it might be necessary, or how to get rid of it?I might add that it's exceedingly difficult to Google, or even get to display correctly in Markdown.From the comments:$ unset '!::' -bash: unset: `!::': not a valid identifier
|
Strange environment variable !::=::\ in Cygwin
|
environment variables;cygwin
|
This is nothing to do with Unix or Linux. It's entirely Win32 and Cygwin.As first discussed in the Microsoft doco for Win32 and various Win32 programmers guides almost a quarter of a century ago, the Windows NT kernel doesn't have a notion of multiple drives each with their own individual working directories. This MS-DOS paradigm is emulated in Win32 using environment variables, not normally displayed by Win32 command interpreters' set commands (but fairly easily accessible programmatically), with names in the form =D: (where D is a drive letter). This pretense of multiple working directories, just like good old MS-DOS, is a shared fiction consulted and maintained by the Win32 API, Microsoft's command interpreter cmd, and the runtime libraries for various languages including some C and C++ compilers.When a Cygwin process starts up, it converts the Win32 environment block into a more UNIX-y form. It has a whole set of hardwired special conversion rules for various specific variables, such as PATH. It's not in the Cygwin doco, but it also likewise deals with the =D:=D:\path environment strings by converting the leading = into a !. This yields environment strings, as Cygwin program execution sees them, of the form !D:=D:\path. It reverses this conversion when it needs to generate a new Win32 environment for whatever reason, such as spawning a new process, turning the ! back into a =.To get Microsoft's command interpreter to display these environment variables, one simply runs set whereupon one will see output beginning something like =C:=C:\Users\Jim…Sometimes, an extra one of these environment variables crops up, with : as the drive letter. Running the same set command as above yields output beginning =::=::\=C:=C:\Users\Jim…After this has been made more UNIX-y by Cygwin, this is of course the very !::=::\ that you are seeing.Because these are a mechanism that is embedded within Win32 applications (within Microsoft's command interpreter most especially) and that is partly entangled in the Win32 API itself, it's not exactly trivial to prevent their existence.Further readingCreateProcess(). Microsoft Win32 Programmer's Reference: Functions, A–G. Microsoft Press. 1993. ISBN 9781556155178. p. 213.Jeffrey Richter (1995). Advanced Windows: The Developer's Guide to the Win32 API for Windows NT 3.5 and Windows 95. Microsoft Press. ISBN 9781556156779. pp. 26–27.
|
_unix.333854
|
I have fedora 25 running with dual head, and I have named each screen/monitor/device in xorg.conf, yet in the display settings they show up as 'Unknown Display'.Is there a way to force Fedora to use the xorg.conf names? Or perhaps rename them in Fedora?
|
Naming displays in Fedora 25's settings
|
fedora;xorg;graphics;dual monitor
| null |
_unix.211629
|
how is this possible: [root@oda001-d0 .ACFS]# pwd/OVS/Repositories/repo1/.ACFS[root@oda001-d0 .ACFS]# ls -la ..total 148drwxr-xr-x 8 root root 4096 Jun 23 11:45 .drwxr-xr-x 5 root root 4096 Jun 23 14:18 ..drwxr-xr-x 6 root root 8192 Jun 23 17:13 Locksdrwx------ 2 root root 65536 Jun 23 11:45 lost+found-rw-r--r-- 1 root root 8316 Jun 23 17:11 oakres.xmldrwxr-xr-x 2 root root 8192 Jun 23 11:45 Templatesdrwxr-xr-x 2 root root 8192 Jun 23 11:45 VirtualDisksdrwxr-xr-x 2 root root 8192 Jun 23 11:45 VirtualMachines[root@oda001-d0 .ACFS]#You see, the directory we currently are in is not listed in the parent directory. This directory must be hidden in a way that it cannot be found with ls -la, but I have no idea how. Even find does not find this folder. What kind of sorcery it this? Directory /OVS/Repositories/repo1 is imported via NFS:192.168.16.10:/u01/app/sharedrepo/repo1 on /OVS/Repositories/repo1 type nfs (rw,bg,hard,nointr,rsize=32768,wsize=32768,tcp,actimeo=0,nfsvers=3,timeo=600,addr=192.168.16.10)It's an acfs on NFS-server-side:/dev/asm/repo1-399 on /u01/app/sharedrepo/repo1 type acfs (rw)Is this some special ACFS-magic? But if yes, how does this get through NFS?...and do developers at Oracle sit there, laughing, thinking of people actually searching files in this directory? As I am told to by their docs?
|
Completely hidden directory on ACFS imported via NFS
|
filesystems;ls
| null |
_unix.248291
|
I'm trying to apply SHA256 and then Base64 encode a string inside a shell script. Got it working with PHP:php -r 'echo base64_encode(hash(sha256, asdasd, false));'. But I'm trying to get rid of the PHP dependency.Got this line that works well in the terminal (using the fish shell):$ echo -n asdasd | shasum -a 256 | cut -d -f 1 | xxd -r -p | base64X9kkYl9qsWoZzJgHx8UGrhgTSQ5LpnX4Q9WhDguqzbg=But when I put it inside a shell script, the result differs:$ cat foo.sh#!/bin/shecho -n asdasd | shasum -a 256 | cut -d -f 1 | xxd -r -p | base64$ ./foo.shIzoDcfWvzNTZi62OfVm7DBfYrU9WiSdNyZIQhb7vZ0w=How can I make it produce expected result? My guess is that it's because of how binary strings are handled?
|
Apply SHA256 and Base64 to string in script
|
shell script;scripting;binary;hashsum;base64
|
The problem is that you are using different shells. The echo command is a shell builtin for most shells and each implementation behaves differently. Now, you said your default shell is fish. So, when you run this command:~> echo -n asdasd | shasum -a 256 | cut -d -f 1 | xxd -r -p | base64X9kkYl9qsWoZzJgHx8UGrhgTSQ5LpnX4Q9WhDguqzbg=you will get the output shown above. This is because the echo of fish supports -n. Apparently, on your system, /bin/sh is a shell whose echo doesn't support -n. If the echo doesn't understand -n, what is actually being printed is -n asdasd\n. To illustrate, lets use printf to print exactly that:$ printf -- -n asdasd\n -n asdasdNow, if we pass that through your pipeline:$ printf -- -n asdasd\n | shasum -a 256 | cut -d -f 1 | xxd -r -p | base64IzoDcfWvzNTZi62OfVm7DBfYrU9WiSdNyZIQhb7vZ0w=Thats the output you get from your script. So, what happens is that echo -n asdasd is actually printing the -n and a trailing newline. A simple solution is to use printf instead of echo:$ printf asdasd | shasum -a 256 | cut -d -f 1 | xxd -r -p | base64X9kkYl9qsWoZzJgHx8UGrhgTSQ5LpnX4Q9WhDguqzbg=The above will work the same on the commandline and in your script and should do so with any shell you care to try. Yet another reason why printf is better than echo.
|
_unix.152219
|
I have a linux user thomas and 2 domain names domain1.com and domain2.com. I have followed steps to have two virtual mail boxes /var/mail/vhosts/domain[12].com/When I test and send an email to [email protected], it lands in /var/mail/vhosts/domain2.com/thomas/...When I send it to [email protected], it lands in /var/mail/thomas. However, dovecot looks into /var/mail/vhosts/%d/%n. How can I fix that ?
|
Postfix favors non virtual to virtual host
|
postfix;dovecot
| null |
_codereview.154208
|
I have coded a prize system in where I add a prize in the database and it calls the CheckPrizes(player) every time a player logs in to the application. I won't go in to detail of how they log in but thats the basics of it.PrizeManager.cs:using System;using System.Collections.Concurrent;using System.Collections.Generic;using System.Data;using System.Linq;using Sahara.Base.Game.Players;namespace Sahara.Base.Game.Prizes{ internal sealed class PrizeManager { private readonly ConcurrentDictionary<int, Prize> _prizes; private readonly ConcurrentDictionary<int, List<int>> _prizeLogs; public PrizeManager() { _prizes = new ConcurrentDictionary<int, Prize>(); _prizeLogs = new ConcurrentDictionary<int, List<int>>(); LoadPrizes(false); } private void LoadPrizes(bool clearBefore) { if (clearBefore && _prizes.Count > 0) { _prizes.Clear(); } using (var mysqlConnection = Sahara.GetServer().GetMySql().GetConnection()) { mysqlConnection.OpenConnection(); mysqlConnection.SetQuery(SELECT * FROM `server_rewards` WHERE `enabled` = @enabled); mysqlConnection.AddParameter(enabled, 1); var dataTable = mysqlConnection.GetTable(); if (dataTable == null) { return; } foreach (DataRow prizeRow in dataTable.Rows) { _prizes.TryAdd(Convert.ToInt32(prizeRow[id]), new Prize(Convert.ToInt32(prizeRow[id]), Convert.ToInt32(prizeRow[reward_start]), Convert.ToInt32(prizeRow[reward_end]), Sahara.GetServer().GetUtility().GetPrizeTypeFromString(Convert.ToString(prizeRow[reward_type])), Convert.ToString(prizeRow[reward_data]), Convert.ToString(prizeRow[message]))); } mysqlConnection.CloseConnection(); } } public void CheckPrizes(Player player) { if (player?.GetPlayerData() == null) { return; } foreach (var prizeEntry in _prizes.Where(prizeEntry => !ReceivedPrize(player.GetPlayerData().PlayerId, prizeEntry.Key)).Where(prizeEntry => prizeEntry.Value.Ready())) { prizeEntry.Value.OnReceive(player); } } public void LogReceivedPrize(int playerId, int prizeId) { if (!_prizeLogs.ContainsKey(playerId)) { _prizeLogs.TryAdd(playerId, new List<int>()); } if (!_prizeLogs[playerId].Contains(prizeId)) { _prizeLogs[playerId].Add(prizeId); } using (var mysqlConnection = Sahara.GetServer().GetMySql().GetConnection()) { mysqlConnection.OpenConnection(); mysqlConnection.SetQuery(INSERT INTO `server_reward_logs` VALUES (@playerId, @prizeId)); mysqlConnection.AddParameter(playerId, playerId); mysqlConnection.AddParameter(prizeId, prizeId); mysqlConnection.RunQuery(); mysqlConnection.CloseConnection(); } } private bool ReceivedPrize(int playerId, int prizeId) => _prizeLogs.ContainsKey(playerId) && _prizeLogs[playerId].Contains(prizeId); }}Prize.cs:using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using Sahara.Base.Game.Players;using Sahara.Core.Net.Messages.Outgoing.Packets.Inventory.Purse;namespace Sahara.Base.Game.Prizes{ internal sealed class Prize : IPrize { private readonly int _prizeId; private readonly int _prizeStart; private readonly int _prizeEnd; private readonly PrizeType _prizeType; private readonly string _prizeData; private readonly string _prizeMessage; public Prize(int prizeId, int prizeStart, int prizeEnd, PrizeType prizeType, string prizeData, string prizeMessage) { _prizeId = prizeId; _prizeStart = prizeStart; _prizeEnd = prizeEnd; _prizeType = prizeType; _prizeData = prizeData; _prizeMessage = prizeMessage; } public bool Ready() { var now = Sahara.GetServer().GetUtility().GetUnixNow(); return (now >= _prizeStart && now <= _prizeEnd); } public void OnReceive(Player player) { switch (_prizeType) { case PrizeType.None: return; case PrizeType.Badge: if (!player.GetPlayerData().GetBadgeManagement().HasBadge(_prizeData)) { player.GetPlayerData().GetBadgeManagement().GiveBadge(_prizeData, true); } break; case PrizeType.Credits: player.GetPlayerData().Credits += Convert.ToInt32(_prizeData); player.SendMessage(new CreditBalanceMessageComposer(player.GetPlayerData().Credits)); break; case PrizeType.Duckets: player.GetPlayerData().Duckets += Convert.ToInt32(_prizeData); player.SendMessage(new HabboActivityPointNotificationMessageComposer(player.GetPlayerData().Duckets, Convert.ToInt32(_prizeData))); break; case PrizeType.Diamonds: player.GetPlayerData().Diamonds += Convert.ToInt32(_prizeData); player.SendMessage(new HabboActivityPointNotificationMessageComposer(player.GetPlayerData().Diamonds, Convert.ToInt32(_prizeData))); break; default: throw new ArgumentOutOfRangeException(); } } }}PrizeType.csusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Sahara.Base.Game.Prizes{ internal enum PrizeType { Credits, Badge, Duckets, Diamonds, None, } }GetUnixNow method:public double GetUnixNow(){ var ts = (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0)); return ts.TotalSeconds;}}
|
Player prize system
|
c#
| null |
_unix.178925
|
I am playing around with -exec flag of find command. I am trying to use the flag to print the extension name of files, using a fairly new Linux distribution release.Starting simple, this works:find . -type f -exec echo {} \;An attempt to use convenient Bash string feature fails:find . -type f -exec echo ${{}##*.} \; (bad substitution)So what should be the correct way to do it?
|
Print file name extension using -exec in find
|
shell;find;filenames;parameter;variable substitution
|
If you want to use shell parameter expansion then run some shell with exec:find . -type f -exec sh -c 'echo ${0##*.}' {} \;
|
_unix.278194
|
gcc version 5.3.0 20151204 (Ubuntu 5.3.0-3ubuntu1~14.04) I have a problem with g++ When I search for g++ I find nothing!So I tried to install it; it seems like g++ is already installed and it's the newest one!arubu@CQ56-LinuxMachine:~$ which g++arubu@CQ56-LinuxMachine:~$ sudo apt-get install g++[sudo] password for arubu: Reading package lists... DoneBuilding dependency tree Reading state information... Doneg++ is already the newest version.g++ set to manually installed.The following packages were automatically installed and are no longer required: libgranite-common libgranite1 libkeybinder-3.0-0Use 'apt-get autoremove' to remove them.0 upgraded, 0 newly installed, 0 to remove and 8 not upgraded.arubu@CQ56-LinuxMachine:~$ g++ -vThe program 'g++' is currently not installed. You can install it by typing:sudo apt-get install g++
|
problem finding g++ program, despite it being installed
|
software installation;g++
|
You should force the re-installation of the g++ package; this will restore the appropriate symbolic links:sudo apt-get --reinstall install g++Once this is done you should find that /usr/bin/g++ exists once again and is a symbolic link to g++-5.
|
_webapps.79848
|
I have written the following codefunction myFunction(e){ var options={cc: '[email protected]'}; MailApp.sendEmail(e.values[2], New SMS Blast request, A new SMS blast request has been entered, the particulars are:+ \n\n SMS Blast city:+e.values[3]+ \n\n SMS Blast Date:+e.values[7]+ \n\n SMS Blast time:+e.values[8]+ \n\n SMS Blast objective:+e.values[4]+ \n\n SMS Blast Base:+e.values[5]+ \n\n SMS content:+e.values[10]+ \n\n To approve or deny the request, kindly go to the following link:+ \n\n xxxxxx+ \n\n Data team, kindly share the SMS base once the request has been approved and enter the SMS base volume in the tracker+ \n\n SMS Team, kindly send the SMS once the data has been shared, options) var ss = SpreadsheetApp.getActiveSpreadsheet(); var requestSheet= ss.getSheetByName(SMS Blast Request); var column = requestSheet.getRange('K:K'); var columnValues= column.getValues(); var row = 1; while ( columnValues[row-1][0] != ) { row++; } if(e.values[6]==One Time){ requestSheet.getRange(row, 1).setValue(e.values[3]); requestSheet.getRange(row, 2).setValue(e.values[7]); requestSheet.getRange(row, 3).setValue(e.values[8]); requestSheet.getRange(row, 4).setValue(e.values[4]); requestSheet.getRange(row, 5).setValue(e.values[5]); requestSheet.getRange(row, 7).setValue(e.values[9]); requestSheet.getRange(row, 8).setValue(e.values[10]); requestSheet.getRange(row, 11).setValue(1); } else{ var campaignDuration=e.values[14]-e.values[13]+1; var numOfSMS; var SMSInterval; if(e.values[15]==Daily){ numOfSMS=campaignDuration; SMSInterval=1; } else if(e.values[15]==Weekly){ numOfSMS=campaignDuration/7; SMSInterval=7; } else{ numOfSMS=campaignDuration/2; SMSInterval=2; }for(var i=0;i<numOfSMS;i++){ requestSheet.getRange(row, 1).setValue(e.values[3]); requestSheet.getRange(row, 2).setValue(e.values[11]+SMSInterval*i); requestSheet.getRange(row, 3).setValue(e.values[14]); requestSheet.getRange(row, 4).setValue(e.values[4]); requestSheet.getRange(row, 5).setValue(e.values[5]); requestSheet.getRange(row, 7).setValue(e.values[15]); requestSheet.getRange(row, 8).setValue(e.values[16]); requestSheet.getRange(row, 11).setValue(1); row=row+1; } }}The above code basically takes the input of a form and then populates a google spreadsheet according to the responses of the form.I selected the SMS type(e.values[6]): One Time and filled in the following valuesCity: NYCDate:1/1/2015Time:1:00:00 AMObjective: AttachmentBase: UberContent: TestAs written in the code, I received a mail with all the values written correctly. However, in the spreadsheet, where the code is supposed to set the values, only city, objective and base are getting set correctly. The date column is getting the value 0 and the rest of the columns are blank.I have tried many different things to solve this issue: I have tried setting the values using e.namedVAlues[] instead of e.values. I have also tried changing the array indices of e.values inside the setValue() bracket. However, even after changing the index, the function is populating the same values. I have checked both logs and execution transcripts and found the all the elements of e.values[] array are getting correct values. This has led me to believe that the problem lies only with the setValue function and it is not able to set some of these values for some reason.Can anybody please explain me what is the solution to this problem or what is wrong with the code?
|
Google Script: setValue function on form submit
|
google apps script;google forms
| null |
_unix.191004
|
The idea of my PS1 configuration is to show some extended info like Mercurial or Git repo status, command execution time, etc. The prompt is split by two lines because it produces too many characters to fit into a single line. Here is my PS1 in my .bashrc (not sure if the entire source code is necessary here, hope it helps):function prompt_status { local color_app=\e[1;38;5;214m local color_branch=\e[1;38;5;32m local color_revision=\e[0;38;5;64m if git rev-parse --is-inside-work-tree &> /dev/null; then local branch=$(git rev-parse --abbrev-ref HEAD | tr -d '\n') local revision=$(git rev-parse HEAD | tr -d '\n') echo -ne $color_appgit $color_branch$branch $color_revision($revision) elif hg status &> /dev/null; then local branch=$(hg branch | tr -d '\n') local revision_number=$(hg identify -n | tr -d '\n') local revision=$(hg parent --template '{node}' | tr -d '\n') echo -ne $color_apphg $color_branch$branch $color_revision($revision_number:$revision) else return fi echo -e \e[0m}function prompt_return_value { RET=$? if [[ $RET -eq 0 ]]; then echo -ne #echo -ne \e[32m$RET\e[0m else echo -ne \e[1;37;41m$RET\e[0m fi}function timer_start { timer=${timer:-$SECONDS}}function timer_stop { seconds_elapsed=$(($SECONDS - $timer)) unset timer}function prompt_seconds_elapsed { local c; local t=${seconds_elapsed}s if [ $seconds_elapsed -ge 60 ]; then c=196 t=$(format_seconds $seconds_elapsed) elif [ $seconds_elapsed -ge 20 ]; then c=214 elif [ $seconds_elapsed -ge 10 ]; then c=100 elif [ $seconds_elapsed -ge 5 ]; then c=34 elif [ $seconds_elapsed -ge 1 ]; then c=22 else return fi echo -ne \e[0;38;5;${c}m${t} \e[0m}function format_seconds { ((h=${1}/3600)) ((m=(${1}%3600)/60)) ((s=${1}%60)) printf %02d:%02d:%02d\n $h $m $s}trap 'timer_start' DEBUGPROMPT_COMMAND=timer_stopexport PS1=\n\e[1;38;5;106m\u@\h \e[0;38;5;136m\w\[\e[0m\]\n\$(prompt_return_value)\$(prompt_seconds_elapsed)\$(prompt_status)\$ The problem is that the prompt looks broken when a terminal window has small width. This is what I get for 80 columns:username@some-very-long-hostname ~/tmp/d06a14b06cac) $ 9866c9d0d26d2b27063a89ee1c330It's like wrapped at the 2nd line causing total mess (see the $ sign in the middle). It works almost perfectly for a larger terminal column number, say 120:username@some-very-long-hostname ~/tmp/dhg default (0:69866c9d0d26d2b27063a89ee1c3306a14b06cac) $Also I noticed that add more text to the end of the terminal line causes an issue that's very similar to the effects described for 80 columns above. The question is: does bash handle new lines or too long incorrectly for PS1?Thanks.UPDATEThis question is not an exact duplicate of Why is my bash prompt getting bugged when I browse the history? . After some discussion with @AdamKatz, it seems that zero-length output escapes \[ and '] work only when they are literally put in the PS1 string, but they does not seem to work when returned from a function causing to appear unescaped on terminal.
|
bash: The prompt gets visually broken
|
bash;prompt
|
For multi-line prompts (including when it wraps, including from your commands), you need to enclose your color codes in escaped square brackets (like \[$color\]).This example is green, has user@hostname:workingdir $ and then reverts back to uncolored:PS1='\[\e[1;32m\]\u@\h:\w \$\[\e[0;0m\]'
|
_unix.209086
|
Pseudocode which is a continuation from this answergsed 's/|/1)/g' 's/|/2)/2g' 's/|/3)/3g' 's/|/5)/4g' 's/|/5)/5g' <input.csv >output.csvwhich is of course not working. I am interested in how gsed can manage such an looping. How does gsed extend to such looping?
|
Replace 1st with 1), 2nd with 2), ... in GNU Sed
|
text processing;sed
|
For the case above, you can do it like this:gsed 's/|/1)/; s/|/2)/; s/|/3)/; s/|/4)/; s/|/5)/'Example:$ echo '| | | | |' | sed 's/|/1)/; s/|/2)/; s/|/3)/; s/|/4)/; s/|/5)/'1) 2) 3) 4) 5)This works if you can estimate in advance the maximum number of | on a line, and add s/|/N)/ accordingly.If you can't estimate the maximum number of | on a line it can still be done with gsed, using a counter in the hold buffer, and incrementing it with this clever device by Bruno Haible. The actual implementation is a little tricky though, and thus I'll leave it to the masochisticastute reader.The easy way is, of course, to just use awk:awk '{ cnt = 0; while(sub(/\|/, ++cnt ))); print }'Proof:$ echo '| | | | |' | awk '{ cnt = 0; while(sub(/\|/, ++cnt ))); print }'1) 2) 3) 4) 5)
|
_codereview.43635
|
I need to take data from a MySQL database and message it into a format expected by the front end of an application - I can not change the front end as other services provide it data in this same format.The database is structured as follows:id type value label optgroup1 car ix5 Ford Taurus Ford2 car ix6 Ford Focus Ford3 car ix9 Cobalt Chevy4 planet ix8 Earth DefaultThe output from this code must do the following: for types with optgroups, records must be categorized by optgroup; if there is only one optgroup, then it should be ignored. The real data has hundreds to thousands of rows per type. The finally array output from this data would be:$data = [ 'car' => [ 'chevy' => [ 'ix9' => 'Cobalt' ], 'ford' => [ 'ix5' => 'Ford Taurus', 'ix6' => 'Ford Focus' ] ], 'planet' => [ 'ix8' => 'earth' ]];The code I have doing this currently works, but is a bit slow, and I am looking for a possible improvement. Here's the functioning code, where $STH->result() is the database result as an array of rows:protected function _format($STH){ $data = []; foreach ($STH->result() as $row) { if ( ! $row->optgroup) $data[ $row->type ][ $row->value ] = $row->label; else $data[ $row->type ][ $row->optgroup ][ $row->value ] = $row->label; } // selects with a single optgroup can have that optgroup removed foreach ($data as $menutype => $optorkey) { if (is_array($optorkey) && count($optorkey) == 1) $data[$menutype] = current($optorkey); } return $data;}EDITThe original query generating the data is very simple, as follows:SELECT type, value, label, optgroup FROM ####.options ORDER BY type, optgroup, label ASCThe data in this table is updated frequently by automated processes.
|
How can I optimize this database to array structure code?
|
php;optimization
| null |
_unix.164630
|
I chose the default installation of OpenBSD 5.5. My monitor's brand is Samsung 27-inch 850 series LED. It's in full high-definition, 1920x1080.After I type my login username and password, I am presented with a window and whatever I type into it appears tiny, that is, the on-screen fonts are too small for me to read.How do I make the on-screen fonts and icons on the desktop larger for me to see clearly? (I believe the default window manager is FVWM)
|
On-screen fonts appear tiny on OpenBSD 5.5
|
x11;fonts;openbsd;fvwm
| null |
_unix.118244
|
I've got 10k+ files totaling over 20GB that I need to concatenate into one file.Is there a faster way thancat input_file* >> out?The preferred way would be a bash command, Python is acceptable too if not considerably slower.
|
Fastest way to concatenate files
|
bash;shell script;files;cat
|
Nope, cat is surely the best way to do this. Why use python when there is a program already written in C for this purpose? However, you might however want to consider using xargs in case the command line length exceeds ARG_MAX and you need more than one cat. Using GNU tools, this is equivalent to what you already have:find . -maxdepth 1 -type f -name 'input_file*' -print0 | sort -z | xargs -0 cat -- >>out
|
_cs.24307
|
This circuit should be reasonably efficient in size and depth, but with priority on depth. If depth was not a concern, then I guess I could make a specialized adder for the least significant bit and then modelled the rest of the circuit as a ripple adder with only that initial, possible carry. The carry has to ripple through the first sequence of consecutive bits set to 1. For example:$inc(0111) = 1000$$inc(0001) = 0010$$inc(0100) = 0101$ (no ripple)But this takes linear time, in the worst case (binary string is $1...1$). How do you optimize for depth? Does the optimal circuit have a $log_2(n)$ depth? Is perhaps the best strategy to use a parallel prefix circuit? If so, I guess one would make a specialized adder for the least significant bit. Then you have the result of the least significant bit, which is 0 if a carry was generated, 1 otherwise. If a carry was generated, then you need to efficiently ripple it through all the adjacent, consecutive 1-bits. If one is to use a prefix sum, then you need an associative binary operator. It also needs to preserve the value of the bits that are not part of the initial, consecutive 1-bits (from right to left). This might mean that you pass in the carry bit that was (possibly) generated after the increment on the least significant bit, while the rest of the operators gets fed predefined bits which preserve the values of the relevant bits of the number (bit vector). At this point, I'm stuck.
|
Create a shallow logic circuit that increments a binary number
|
logic;circuits
| null |
_webmaster.58577
|
I'm quite new to SEO, I have a website that focuses on things to do in a city.We have lots of articles like Top 10 / 20 restaurants etc.We just opened a new section which uses Google Maps and has map points for all the individual things to do in the city. I would like to use snippets of text from the larger articles and create new articles with them.For example: I would like to take the text for each of the restaurants on the Top 10 article and create 10 new articles with those pieces of text and link each one to a point on the map. The titles and URLs will all be unique and the focused keywords will be different too.I'm also going to be linking to the big Top 10 article from each of these small article pages too.I'm worried about it being seen as duplicate content by Google and would like some advice on best practices.
|
SEO Advice Needed! Can you use a snippet from a big article as a new small article?
|
seo;duplicate content
| null |
_unix.261518
|
When I run my grep command:grep -rc 'PATTERN' .it prints out the number of lines that the pattern occurs, but it looks like this:./hotel_232424.dat:234and so on...How would I remove the ./hotel_232424.dat: part and just print out the number?
|
Remove file name when recursively counting number of occurrences of a pattern
|
bash;shell script;sed;grep
| null |
_webapps.16
|
I like Facebook to connect with friends, but I don't like the way their favorite games spam me.They just keep giving me Mafia Wars updates!Is there any way to block a friend's Mafia Wars update? Or any other Facebook game for that matter.
|
How do I make Facebook block a friends Mafia Wars updates?
|
facebook
|
You can open the game at http://apps.facebook.com/inthemafia/. Find the Block Application link and follow the instructions. Further updates from Mafia Wars will not be seen on your account. If you're interested in just blocking a particular user's updates, you can block the person by visiting their profile and doing the same thing on that page, however you will effectively be blocking ALL of their updates and not just their Mafia Wars updates.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.