id
stringlengths
5
27
question
stringlengths
19
69.9k
title
stringlengths
1
150
tags
stringlengths
1
118
accepted_answer
stringlengths
4
29.9k
_cstheory.31652
I'm reading Ankur Moitra's excellent lectures notes at http://people.csail.mit.edu/moitra/docs/bookex.pdf .In Chapter4, the notes claim that a certain circulant matrix of fourier coefficients is invertible [left as exercise to reader, and I can't find the footnote]. I can not prove it. I'm also not convinced it's true. The pages are attached. Any pointers as to what I should read up on would be helpful.Thanks!EDIT: Images are high resolution. Click open image in new tab.
Inverting Matrix in Prony's Algorithm
linear algebra
null
_unix.293191
I'm writing a small script that will help me debug some permission problems. I am passing the parent folder I wish to examine and am able to specify any sub-folders which I want to ignore.I'm having a problem passing the constructed parameter string to find because some parts of it (the are being escaped. I can't seem to figure out how to provide the wildcard into the command in such a way that find accepts it properly. With the wildcard in place, that portion of the path string is qualified using single quotes that are escaped using '\'' and are confusing me (as I can't figure out how to control the transformation) and find (which is essentially ignoring my excludes)I've been reading all about single and double quotes as well as escaping characters, but I haven't found an example similar to mine.#!/bin/bash -f# output permissions and ownership with path relative to specified parent.Usage=$0 <parent path> <excluded child folder> ....if [ $# -lt 1 ]then (>&2 echo -e $Usage) exit 1else parent=$1 shift if [ $# -gt 0 ] then excludes= ( for folder in $@ do thisLine= ! -path $parent$folder ! -path '$parent$folder/*' <=== the '*' wildcard is causing the problem I think. excludes=$excludes$thisLine done excludes=$excludes ) fi (>&2 echo => find $parent $excludes -ls | awk '{print '$3|$5|$6|$11}'') (>&2 echo )set -vx find $parent $excludes -ls | awk '{print $3|$5|$6|$11}'fiThe branch of the tree that I'm working with is /home/user/catkin_ws/src/clfsm which has three sub-folders, two of which I wish to exclude; cmake & include. The output below is in two parts: Top is the current output, which does not filter the folders I wish to exclude. The bottom part is correct, using the echoed command line from my code above.The command to call the above script is:~/myScripts/show_permissions.sh /media/nap/U14041/home/nap/catkin_ws/src/clfsm /cmake /include. Note that Stephen's solution requires that the sub-folders to be excluded be specified without a leading /.user@rMBP-Ubuntu:[12:29]:/home/user/catkin_ws/src/clfsm$ ~/myScripts/show_permissions.sh /home/user/catkin_ws/src/clfsm /cmake /include=> find /home/user/catkin_ws/src/clfsm ( ! -path /home/user/catkin_ws/src/clfsm/cmake ! -path '/home/user/catkin_ws/src/clfsm/cmake/*' ! -path /home/user/catkin_ws/src/clfsm/include ! -path '/home/user/catkin_ws/src/clfsm/include/*' ) -ls | awk '{print $3|$5|$6|$11}'++ find /home/user/catkin_ws/src/clfsm '(' '!' -path /home/user/catkin_ws/src/clfsm/cmake '!' -path ''\''/home/user/catkin_ws/src/clfsm/cmake/*'\''' '!' -path /home/user/catkin_ws/src/clfsm/include '!' -path ''\''/home/user/catkin_ws/src/clfsm/include/*'\''' ')' -ls++ awk '{print $3|$5|$6|$11}'drwxrwxr-x|user|user|/home/user/catkin_ws/src/clfsm-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/clfsm.layoutdrwxrwxr-x|user|user|/home/user/catkin_ws/src/clfsm/src-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/src/clfsm_visitorsupport.cc-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/src/clfsm_machine.cc-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/src/clfsm_visitors.cc-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/src/clfsm_main.cc-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/src/clfsm_cc.cc-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/cmake/FindLibDispatch.cmake-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/CMakeLists.txt-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/clfsm_vector_factory.hdrwxrwxr-x|user|user|/home/user/catkin_ws/src/clfsm/include/typeClassDefs-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/typeClassDefs/FSMControlStatus.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/typeClassDefs/FSM_Control.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/typeClassDefs/wb_fsm_control_status.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/typeClassDefs/wb_fsm_state_status.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/CLActionAction.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMWBQueryPredicate.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMSuspensibleMachine.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMWBSubMachine.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/gu_util.h~-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/CLTransitionExpression.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMWBContext.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMState.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMAction.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMExpression.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/clfsm_cc.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMTransition.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/clfsm_visitorsupport.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/stringConstants.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/clfsm_factory.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMFactory.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMachineVector.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMActivity.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/clfsm_visitors.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMachine.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/clfsm_cc_delegate.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/clfsm_machine.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/gu_util.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSMWBPredicate.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/clfsm_wb_vector_factory.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/include/FSM.h-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/package.xml-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/clfsm.cbpuser@rMBP-Ubuntu:[12:34]:/home/user/catkin_ws/src/clfsm$ find /home/user/catkin_ws/src/clfsm \( ! -path /home/user/catkin_ws/src/clfsm/cmake ! -path '/home/user/catkin_ws/src/clfsm/cmake/*' ! -path /home/user/catkin_ws/src/clfsm/include ! -path '/home/user/catkin_ws/src/clfsm/include/*' \) -ls | awk '{print $3|$5|$6|$11}'drwxrwxr-x|user|user|/home/user/catkin_ws/src/clfsm-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/clfsm.layoutdrwxrwxr-x|user|user|/home/user/catkin_ws/src/clfsm/src-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/src/clfsm_visitorsupport.cc-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/src/clfsm_machine.cc-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/src/clfsm_visitors.cc-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/src/clfsm_main.cc-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/src/clfsm_cc.cc-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/CMakeLists.txt-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/package.xml-rw-rw-r--|user|user|/home/user/catkin_ws/src/clfsm/clfsm.cbpuser@rMBP-Ubuntu:[12:35]:/home/user/catkin_ws/src/clfsm$
How to pass string with special characters to shell command in a script?
bash;text processing
If I understand the requirement properly you should be using -path ... -prune to stop descending into trees.Something like:#!/bin/bash -f# output permissions and ownership with path relative to specified parent.Usage=$0 <parent path> <excluded child folder> ....if [ $# -lt 1 ]then (>&2 echo -e $Usage) exit 1else parent=$1 shift if [ $# -gt 0 ] then for folder in $@ do thisLine= ( -path $parent/$folder -prune ) -o excludes=$excludes$thisLine done fiset -vx find $parent $excludes -ls | awk '{print $3|$5|$6|$11}'fiThe idea is to build out a string similar tofind /tmp/A \( -path /tmp/A/skip1 -prune \) -o -ls
_unix.161958
I am trying to figure out a solution for this question. My approach to this problem so far is as below. Append all the characters together to make it a long string.After the above step, remove all the white spaces or tab spaces so that we will just have one big string.I was able to establish the above steps with the below command. column -s '\t' inputfile | tr -d '[:space:]'So for an input file like this,1 0 0 0 0 00 1 1 1 0 0After applying the above command I have the values as,100000011100Now in this big string I am trying to apply an approach as below. Extract every 6th character (as the original OP wants), and append it to an array element till the end of the string. So basically, with the above step, I am trying to create the array elements as,10 (1st and 7th character), 01 (2nd and 8th character), 01 (3rd and 9th character), 01 (4th and 10th character), 00 (5th and 11th character), 00 (6th and 12th character).So my question is, how could I extract every nth character so that I could add them to an array to proceed further? (n=6, in this case).
extract every nth character from a string
shell;shell script;string
Two linesHere is a pure-bash solution that produces a bash array:s=100000011100array=($( for ((i=0; i<${#s}-6; i++)) do echo ${s:$i:1}${s:$((i+6)):1} done ))echo ${array[@]}This produces the same output as shown in the question:10 01 01 01 00 00The key element here is the use of bash's substring expansion. Bash allows the extraction substrings from a variable, say parameter, via ${parameter:offset:length}. In our case, the offset is determined by the loop variable i and the length is always 1.General Solution For Any Number of LinesSuppose, for example, that our original string has 18 characters and we want to extract the i-th, the i+6-th, and the i+12-th characters for i from 0 to 5. Then:s=100000011100234567array=($( for ((i=0; i<6; i++)) do new=${s:$i:1} for ((j=i+6; j<${#s}; j=j+6)) do new=$new${s:$j:1} done echo $new done ))echo ${array[@]}This produces the output:102 013 014 015 006 007This same code extends to an arbitrary number of 6-character lines. For example, if s has three lines (18 characters):s=100000011100234567abcdefThen, the output becomes:102a 013b 014c 015d 006e 007f
_webapps.5070
Answers so far (and what these services ought to deliver):Disqus Profile (full ownership on Disqus enabled sites, claiming authorship on others)Intense Debate] (for blog publishers: tightly integrated into the WordPress blogging platform)BackType Connect Plugin (for blog publishers: copies comments (that link to one of your posts) to your blog, no matter where they are on the web)Gravatar (self-promotion, better visibility)Google Sidewiki (adds another layer)become a blog publisherIn addition, here are some other services:co.mment (conversation tracker)coComment (conversation tracker - still alive and kicking?)Google Reader: Like item action (appreciation feedback)Convenient solutions for ordinary netizens preferred.For your reading pleasure: Comment ownership is a complex problem. The commenter writes the comment, but the blog owner hosts it. So of course, the blog owner has the right to decide what he agrees to host or not. But the person who wrote the comment might also want to claim some right to his writing once its published. (Who Owns Your Comments? by Stephanie Booth)
How do you take ownership of your comments?
sharing;comments;follow;communication
Disqus is one of the solutions.
_cs.72196
Let $M$ be a variant of Turing machine with no working tape but with several heads on input word. Prove that these machines accept exactly the languages in $L$.Please hint me how to start.
Variant of offline Turing machine
complexity theory;computability;turing machines
null
_unix.192331
I have a file with the following content:list:blue,nonered,noneorange,plot baseball , noneuniversity,noneschool,nonedesk,plotmonitor,noneearphone,noneI need to read this file, remove spaces and store each column in a different array.script:output_names=()output_plots=()while read line do item=$(echo -e ${line} | tr -d '[[:space:]]') item=$(echo $item | tr , \n) output_names+=(${item[0]}); output_plots+=(${item[1]});done <listecho ** output_names:;for item in ${output_names[*]}do echo $itemdoneecho ** output_plots:;for item in ${output_plots[*]}do echo $itemdoneHowever it does not work as I expect. What is wrong? and how to fix this code?NoteIf somebody has a solution to store the data in a single array with different keys output['names'][*] and output['plots'][*], that would be highly appreciated as I do not know how to do it.Outputs:** output_names:bluenonerednoneorangeplotbaseballnoneuniversitynoneschoolnonedeskplotmonitornoneearphonenone** output_plots:
Read file remove spaces and store in array
shell script;string;array
This returns a string with spaces:item=$(echo $item | tr , \n)change it like this to have an array:item=($(echo $item | tr , \n))output:** output_names:blueredorangebaseballuniversityschooldeskmonitorearphone** output_plots:nonenoneplotnonenonenoneplotnonenoneThere may be better ways to achieve your task tough
_codereview.93398
The code below works fine for me. Is there any way that I can improve this code more? Note: delimiter is single whitespace only for email address.getmail.py#!/usr/bin/pythonimport rehandleone = open(scratchmail.txt, r)f1 = handleone.readlines()handletwo = open(mailout.txt, a+)match_list = [ ] for ArrayItem in f1: match_list = re.findall(r'[\w\.-]+@[\w\.-]+', ArrayItem) if(len(match_list)>0): handletwo.write(match_list[0]+\r\n) Input file scratchmail.txt:tickets.cgi:5141|5141Z4063442957942364067088508|1219588377|1219588377||PND||abc@AABBCC.com|Mjpqafml|JgALKGXCuasMph|tickets.cgi:358236|358236Z24989798132452492828304439|1433071308|1433071308||PND||xyz.abc@example.com|Edison|CpwxPARuQaqPR|tickets.cgi:86805|86805Z25422507290694218605033173|1232345784|1232345784||PND||pytest@test.com|Agfaodki|jPdSNVlbXi|Output file mailout.txt:abc@AABBCC.comxyz.abc@example.compytest@test.com
Extracting emails from a file and writing them to another file
python;regex;csv;linux;email
Working with file handlesYou should always close the file handles that you open.You didn't close any of them.In addition,you should use with open(...) as ... syntax when working with files,so that they will be automatically closed when leaving the scope.Checking if a list is emptyThere is a much simpler way to check if a list is empty, instead of this:if(len(match_list)>0):The Pythonic way to write is simply this:if match_list:Unnecessary initializations and data storageThere's no need to initialize match_list before the loops.You reassign it anyway inside.You don't need to store all the lines from the first file into a list.You can process the input line by line and write output line by line.That can save a lot of memory, as you only need to keep one line in memory at a time,not the entire input file.Poor namingThe file handles are very poorly named.handleone and handletwo don't convey that one is for input the other is for output.ArrayItem doesn't follow the recommended naming convention of snake_case (see PEP8),and it doesn't describe what it really is.But f1 wins the trophy of worst name in the posted code.lines would have been better.Minor optimizationInstead of re-evaluating regular expressions in every loop,I use re.compile to compile them first, to make all uses efficient.However, this might not be necessary,as it seems recent versions of Python have a caching mechanism.Suggested implementationWith the above suggestions applied, the code becomes simpler and cleaner:import rere_pattern = re.compile(r'[\w\.-]+@[\w\.-]+')with open(input.txt) as fh_in: with open(mailout.txt, a+) as fh_out: for line in fh_in: match_list = re_pattern.findall(line) if match_list: fh_out.write(match_list[0]+\r\n)
_webapps.78310
I've set up an alias for automated e-mail delivery from a Linux box. When an e-mail is sent from me@mydomain.com (using my Google Apps credentials) to my_alias@mydomain.com I can see it on my sent mail folder and not in inbox, where I expected it to be.How can I change that so I'd be able to receive the automated e-mails?
Can't see e-mails sent from me to my alias in google apps
google apps email;google apps for work
null
_unix.290112
So there's this rename(1) Perl thing. It suits my task precisely, except that I need it to basically cp files instead of mv.How to achieve that? I have quite a few rules of renaming, all expressed compactly in s|/foodir/|/|;s|/bardir/|/| form, and then a few lines of file patterns which I need to move copy.It looks somewhat like this:rename -v 's|/pars/|/|; s|/fts/|/|; s|innobase/include|include|' \ storage/{innobase,xtradb}/pars/{pars0grm.cc,pars0grm.y,pars0lex.l,lexyy.cc} \ storage/{innobase,xtradb}/fts/{fts0blex.cc,fts0blex.l,fts0pars.cc,fts0pars.y,fts0tlex.cc,fts0tlex.l} \ storage/innobase/include/fts0[bt]lex.hI suspect that a short Perl snippet would shine at this but I don't speak Perl much.Any help?
rename(1)-like script in Perl, but for copying files?
scripting;perl;file copy
null
_scicomp.27383
I have a Boundary Value Problem for a system of ODEs as an approach of quasi-steady one dimensional flow in a rocket combustion chamber. The equations have the following shape:\begin{equation}\dfrac{d (\rho u A_{p})}{dx} = \chi(x) \end{equation}\begin{equation}\dfrac{d ((\rho u^{2} +p) A_{p})}{dx} -p \dfrac{A_p}{dx}= \psi(x, \rho, u)\end{equation}\begin{equation}\dfrac{d (p \dfrac{\gamma }{\gamma - 1}+\rho u^2 )A_{p} u}{dx} = \chi(x) h(\rho) \end{equation}The gas state equation closes the system\begin{equation}p = \rho R_g T\end{equation}The BC's are:At the beginning of the domain as Initial Values:T(0) = value; u(0) = 0, aprox.And at the end of the domain as closure, the mass flow provides the condition:\begin{equation}\rho u A_p = p(1+\dfrac{\gamma -1}2 M(u,T)^2)^\frac{\gamma}{\gamma -1} kte \end{equation}Must be assumed the values which are not the flow magnitudes $(\rho, p, T, u)$, known.$A_p$ and its variation can be considered a known function related to $x$, $A_p (x)$I am currently applying a finite differences approach with an Explicit Euler's for the ODEs. I have a lot of problems to choose the best method for this problem. I have tried with different ideas, the most recent was the Shooting Method with the secant method for the nonlinearity.I am very lost with this problem and it is the main part of my Bachelors Degree Thesis, so I would appreciate any help.
Boundary Value Problem for CFD Case
pde;fluid dynamics;boundary conditions;nonlinear equations;navier stokes
null
_codereview.111597
I'm developing backend for my mobile app by using gin-gonic and gorm ORM (mysql). But I'm not sure api and db handle huge amount requests if clients increased. for example I'm using my db struct as parameter, is this a problem for concurrency ? Here is my implementation:main.go:var i Implfunc main() { // #GIN# // r := gin.New() r.Use(gin.Logger()) r.Use(gin.Recovery()) // #GIN# // // #DB# // i.InitDB() // #DB# // // #TWITTER# // t := Twitter{} t.InitTwitter() // #TWITTER# // r.GET(/someEndpoint, func(c *gin.Context) { i.InsertUser(&user) go t.Ping(&i) c.JSON(200, gin.H{status: true}) }) r.Run(:5000)}twitter.go:// InitAPI TO-DOfunc (t *Twitter) InitAPI(token string, tokenSecret string) { t.API = anaconda.NewTwitterApi(token, tokenSecret) t.UserID = strings.Split(token, -)[0]}// Ping TO-DOfunc (t *Twitter) Ping(i *Impl) { t.GetHomeTimeLine(i) t.GetUsersFriends(i)}// GetHomeTimeLine TO-DOfunc (t *Twitter) GetHomeTimeLine(i *Impl) { v := url.Values{} v.Set(count, 200) v.Set(exclude_replies, true) results, err := t.API.GetHomeTimeline(v) if err != nil { log.Println(err.Error()) return } tweets := convertTweets(results, t.UserID) go i.CreateOrUpdateTimeline(tweets)}// GetUsersFriends TO-DOfunc (t *Twitter) GetUsersFriends(i *Impl) { v := url.Values{} v.Set(count, 200) v.Set(skip_status, true) friendsChannel := t.API.GetFriendsListAll(v) for { _friends, more := <-friendsChannel if _friends.Error != nil { log.Println(_friends.Error.Error()) break } friends := convertFriends(_friends.Friends, t.UserID) go i.CreateOrUpdateFriends(friends) if !more { break } }}db.go:// Impl TO-DOtype Impl struct { DB gorm.DB}// InitDB TO-DOfunc (i *Impl) InitDB() { var err error i.DB, err = gorm.Open(mysql, connection string) if err != nil { log.Fatalf(Got error when connect database, the error is '%v', err) } i.DB.LogMode(false) i.DB.DB().SetMaxIdleConns(10) i.DB.DB().SetMaxOpenConns(100)}// InsertUser TO-DOfunc (i *Impl) InsertUser(user *User) bool { if err := i.DB.Create(&user).Error; err != nil { log.Fatalf(InsertError: %s, err.Error()) return false } return true}
Mobile app backend using Gin and Gorm ORM
mysql;go;web services;twitter;rest
null
_codereview.156719
I have 2 groovy sql resultset, I need to combine the result set so that project_no should be unique and case_no can have multiple elements if there is a duplicate project_noBelow are the 2 groovy sql resultset[[project_no:0-10001,case_no:00492268],[project_no:0-10160,case_no:01957580],[project_no:1-10014,case_no:02022686]][[project_no:0-10160,case_no:01957590],[project_no:1-10014,case_no:019126],[project_no:1-2896337,case_no:02039596]]Desired List[[project_no:0-10001,case_nos:[00492268]], [project_no:0-10160,case_nos:[01957580,01957590]] ,[project_no:1-10014,case_nos:[02022686,019126]], [project_no:1-2896337,case_nos:[02039596]]]This is what I have triedcaseResultForAnalysis.each { ca -> def ptmp = [:], caseList = [] tempPrList.add(ca[project_no]) ptmp[project_no] = ca[project_no] caseList.add(ca[case_no]) if (caseList.size() > 0) { ptmp[case_nos] = caseList mergedCaseResult.push(ptmp) }}mergedCaseResult.each { ma -> def ptmp = [:], caseList = [] caseResultForUploads.each { cp -> if (!tempPrList.contains(cp[project_no])) { ptmp[project_no] = ma[project_no] caseList.add(cp[case_no]) } else if (ma[project_no] == cp[project_no]) { //if (!ma[case_nos].contains(cp[case_no])) List tmp = ma[case_nos] if (!tmp.contains(cp[case_no])) ma[case_nos].add(cp[case_no]) } } if (caseList.size() > 0) { ptmp[case_nos] = caseList mergedCaseResult.push(ptmp) }}//1st list caseResultForAnalysis//2nd List caseResultForUploads//desired List mergedCaseResultIs there a better way to do this, for better readability and less resource consumption?
Combine lists of objects with no duplicates
groovy
null
_unix.192464
for i in {1..40}do echo $idoneI got{1..40}and I would like to have something like123and so onso I can use the variable i inside a command's parameter.
Brace expansion not working in a script
bash;shell;shell script;brace expansion
In bash 3.0+ (as well as zsh and ksh93), {1..40} will expand to the numbers from 1-40 (inclusive). In a POSIX shell like dash (which is typical of /bin/sh in e.g. Ubuntu), it will not work (we call this issue a bashism).On systems with the GNU utilities, you can use seq to accomplish this:for i in $(seq 1 40)do echo $idoneTo be more portable, you'll have to manually increment $i in a while loop:i=1while [ $i -le 40 ]do echo $i i=$((i+1))doneThis portable version is also very slightly faster since it lacks the external command.
_webmaster.11532
I'm in the process of improving the SEO in one of our client's multilingual sites. Currently the site passes a user the site in their preferred language by checking for a language cookie set by the system last time it was visited. If the cookie does not exist it looks for an Accept-Language header from the browser and checks for a language supported by the site. If that fails it defaults to a language based on some preset defaults for GEO-Location. Once we have a language determined the site will return the page in the language determined with no change to the URL and with all the proper meta tags for that language. So if a Spanish speaking user requests domain.com/venue/access/ then they we'll see Spanish while an English speaker would see English. Of course if the user clicks a language select link with a query string including lang=?? (?? would be es,en, ect.) their cookie will be changed to that language and they'll get that language from that point forward.The problem with this approach is, while usually great for a person, crawlers (currently) don't pass an Accept-Language header when they request a page. This means that a result shown for people using Google, Bing, ect. will usually be in the default language or sometimes a completely different language depending on the path the crawler has taken to a page and how it decided to index it. This is killing our SEO and click-though outside of the default language.We're working with two ideas for how we're going to change handling of user language.Version 1 - All languages have a sub-directoryIf a user hits a URL without a language directory we'll check for the users language by following the following steps in order until we get a match.User has cookie for language preference. Check the browser headers for a supported languageFallback to a site default language based on GEO-Location.Once a language has been determined the system will set a cookie, do a 301 direct and add the language sub-directory to the URL which will be parsed by mod-rewrite and passed as a query string parameter.Version 2 - All NEW languages have a sub-directoryThe first time a user hits the site if they hit a URL without a language directory we'll check for the users language by following the following steps in order until we get a match.User has cookie for language preference. Check the browser headers for a supported languageIf a supported language has been detected the system will set a cookie. If the language is not the default language the system will do a 301 direct and add the language sub-directory to the URL if the language is not the default site language which will be parsed by mod-rewrite and passed as a query string parameter.Any input on the better option?How should we deal with Canonical URL's depending on which option we choose, should canonical URL's point to the main URL without the language sub-directory or should they point to the version for the current language sub-directory? The client would like, if possible, to have counters for social networking reflect the totals for a page in all languages and we're assuming having separate sub-directories for language will prevent this, unless we use a canonical to a single URL which will probably screw up crawlers and negate the whole point of the language changes.Is there an ideal solution I might be missing?
Multilingual sites SEO and canonical
seo;canonical url;multilingual
I do not know the capabilities of the CMS you are using but this is what I would suggest.First of all, try avoiding URL parameters and go for a clear URL scheme. For a Contact page this could look like this:English version: http://domain.com/en/contactPolish version: http://domain.com/pl/kontaktOr:English version: http://en.domain.com/contactPolish version: http://pl.domain.com/kontaktThis way the URL is always easy to understand for the user. Do not use English URLs for non-English pages, so for a Polish page use kontakt instead of contact. After all, if an URL is to be comprehensible for a visitor, it needs to be in the language he or she has chosen to use.If you want to inform search engines about the language of the current page, you have three options that you can use in tandem:Send the HTTP header Content-Language: xx.Use the HTML META section: <meta http-equiv=Content-Language content=xx />. Remember that this is obsolete in HTML5.Use the 'lang attribute in the HTML element. <html lang=xx>Hope this helps!
_codereview.135192
I have the following piece of code which hides an element when a specified date was reached. I would like to get some tips about do's and don'ts.Specifically, I'm interested in:improvements brought to this codeavoid bad practicesAnd whatever you guys consider I should be careful about.var Timer = (function(){ var $el = $('#element'); function count() { setInterval(function() { check(); }, 1000); } function hide() { $el.hide(); } function check() { var currentDate = new Date(); var endingDate = new Date(July 25, 2016 11:06:00); if (currentDate.getTime() >= endingDate.getTime()) { hide(); } } return { count: count };})();Timer.count();
Countdown module that hides an element when a specified date is reached
javascript;jquery;timer;revealing module pattern
null
_datascience.5023
With respect to ROC can anyone please tell me what the phrase discrimination threshold of binary classifier system means? I know what a binary classifier is.
What is a discrimination threshold of binary classifier?
classification;graphs
Just to add a bit.Like it was mentioned before, if you have a classifier (probabilistic) your output is a probability (a number between 0 and 1), ideally you want to say that everything larger than 0.5 is part of one class and anything less than 0.5 is the other class.But if you are classifying cancer rates, you are deeply concerned with false negatives (telling some he does not have cancer, when he does) while a false positive (telling someone he does have cancer when he doesn't) is not as critical (IDK - being told you've cancer coudl be psychologically very costly). So you might artificially move that threshold from 0.5 to higher or lower values, to change the sensitivity of the model in general.By doing this, you can generate the ROC plot for different thresholds.
_softwareengineering.237435
I was reading this blog post about Hexagonal architecture and at the bottom it says:The Loopback pattern is an explicit pattern for creating an internal replacement for an external device.When I google for Loopback pattern I don't find any details about it. Does anyone know what the author is referring to? For curiosity's sake, I'd like to know how to implement this.
What is the Loopback Pattern?
design patterns;architecture
As an example, I recently had a dependency on a remote Authorization service to validate user access tokens. But then I wrote a service that didn't need Authorization -- it just made calculations. So I implemented the AuthorizationService interface (name changed to protect innocent services) with a NoAuthorizationService that just returned true for validate(token).I could use that same stub interface to stub out calls to the actual Authorization service. But I considered it a production artifact rather than a test artifact, because I could use that for a live service to plug into if I didn't want to otherwise disable calls to that service.Think of 127.0.0.1, the loopback IP -- it just goes to localhost. It's a similar idea in a hexagonal architecture, where calls to a remote service are just looping back to the local service instead....In the more common Gang Of Four lingo, this would be the Null Object pattern. Or else a sentinel object that takes the place of the real thing but doesn't do anything.
_codereview.74375
I finally managed to work with socket.io namespace stuff which I'm using for building a chat module. Here, employees of multiple organizations can join and vhat with other employees of the respective organization. What I'm doing at here is creating separate namespaces for each organization. So, it'll be easier for me to manage all employees of different organizations.Here is my server side code:var express = require('express'), http = require('http'),app = express(),server = http.createServer(app),io = require('socket.io').listen(server);var nsp_1005 = io.of('/nsp_bucket_1005');nsp_1005.on('connection', function(socket){ console.log('someone connected to namespace bucket 1005'); socket.on('addEmp', function(login_org_id, login_emp_id, login_emp_name){ console.log('addEmp - Org_Id : '+login_org_id); console.log('addEmp - Emp_Id : '+login_emp_id); console.log('addEmp - Emp_Name : '+login_emp_name); }); socket.on('disconnect', function(){ console.log('Someone disconnected from namespace bucket 1005.'); });});var nsp_1010 = io.of('/nsp_bucket_1010');nsp_1010.on('connection', function(socket){ console.log('someone connected to namespace bucket 1010'); socket.on('addEmp', function(login_org_id, login_emp_id, login_emp_name){ console.log('addEmp - Org_Id : '+login_org_id); console.log('addEmp - Emp_Id : '+login_emp_id); console.log('addEmp - Emp_Name : '+login_emp_name); }); socket.on('disconnect', function(){ console.log('Someone disconnected from namespace bucket 1010.'); });});Those 1005, 1010 codes are Organization IDs. Sorry for the wired naming scheme. But, one thing right now I'm feeling the way I've made this code is not so good. Because I'm duplicating the code at the time of creating namespace for each organization. Can anyone suggest a better way to arrange this code?
Socket namespace for a chat module
javascript;node.js;chat;namespaces;socket.io
Extract the common logic to a function,where the varying parts are parameters.Unless I'm missing something, this looks trivially easy to do:function setup_namespace(org_id) { var nsp = io.of('/nsp_bucket_' + org_id); nsp.on('connection', function(socket){ console.log('someone connected to namespace bucket ' + org_id); socket.on('addEmp', function(login_org_id, login_emp_id, login_emp_name){ console.log('addEmp - Org_Id : ' + login_org_id); console.log('addEmp - Emp_Id : ' + login_emp_id); console.log('addEmp - Emp_Name : ' + login_emp_name); }); socket.on('disconnect', function() { console.log('Someone disconnected from namespace bucket ' + org_id); }); }); return nsp;}var nsp_1005 = setup_namespace(1005);var nsp_1010 = setup_namespace(1010);If you don't need to retain those variables,then you could remove the variables and just leave the calls:setup_namespace(1005);setup_namespace(1010);
_unix.233330
I have the following problem:My home directory lies on the network and is mounted locally on home/<my username>.I can access it with my normal user account <my username>, but as root, I cannot.I do know about this question:https://serverfault.com/questions/571073/root-cannot-access-users-home-folder-shared-via-nfsHowever, this, from my limited understanding of linux systems etc., seems to be some server-side-solution, if it's even applicable in this case. But I need a client-side solution, since the admins won't change this for the time being.So I was wondering if there was some sort of option to make the superuser automatically act like user <my username> inside the sub-directory-tree /home/<my username>, whenever the superuser needs access there.As of now, the superuser can't even cd into my home directory.Please note, the solution should work for sudo and in case I choose to sudo su.
Make superuser act like some other user in certain directory tree
permissions;sudo;nfs;su
null
_scicomp.8308
I hope this is not too off-topic here -- I've asked it on SO but I'm hoping I'll get better answers here!I'm a little bit confused about when I should call MPI_Wait (or other variants such as: MPI_Waitall, MPII_Waitsome, etc). Consider the following situations: (Note: pseudo code)Case (1)MPI_Isend (send_buffer, send_req); // Do local workMPI_Probe (recv_msg);MPI_Irecv (recv_buffer, recv_req);// wait for msgs to finishMPI_Wait (recv_req); // <--- Is this needed?MPI_Wait (send_req); // <--- How about this?So my confusion stems from MPI_Probe in this case. Since this is a blocking call, wouldn't that essentially mean it blocks the caller until message is received? If this is the case, then I think MPI_Waits are unnecessary here.How about the following case?Case (2)MPI_Isend (send_buffer, send_req); // Do local workMPI_Probe (recv_msg);MPI_Recv (recv_buffer);// wait for msgs to finishMPI_Wait (send_req); // <--- Is this necessary?Similar to the first case but MPI_Irecv is replaced with its blocking version. In this case, the message is definitely received by the time MPI_Wait is called which means MPI_Isend must have been finished ... Also as a separate question, what do we mean when we say MPI_Probe is blocking? Does it block until all of the message is received by the process or does it only block until meta-data (such as msg size, sender rank, etc) is received? In other words is MPI_Probe + MPI_Irecv any better than MPI_Probe + MPI_Recv ?
When is MPI_Wait necessary for non-blocking calls?
parallel computing;mpi;c
Bill answered the first part, so I'll only answer the second question. An MPI send is blocking if it does not return until it is safe to modify the send buffer and a receive is blocking if it does not return until the receive buffer contains the newly-received message. In practice, outside of buffered sends (thanks, Hristo Iliev), this implies that communication may be required before returning. For example, MPI_Send is blocking because it cannot complete before the message has been buffered or sent. Implementations will usually eagerly buffer short messages, in which case MPI_Send appears to return immediately. This means that code looks like:MPI_Send(&x,count,MPI_INT,(rank+1)%size,1,comm);MPI_Recv(&y,count,MPI_INT,(size+rank-1)%size,1,comm,MPI_STATUS_IGNORE);is expected to deadlock for large messages, although it will likely succeed for small enough messages. Nonblocking sends and receives return MPI_Requests that must be completed before buffers are accessed/modified.Some operations are a bit different from sends and receives. MPI_Probe is blocking because it does not return until a message has been found, although the message need not have been received yet. MPI_Iprobe is non-blocking in that it always returns even if there is no message.
_unix.282276
I have a Server that runs haproxy to redirect incoming traffic to the correct process based on the subdomain. haproxy is configured to use different SSL certificates depending on the subdomain.The configuration works, however sometimes (quite often though), haproxy serves the wrong certificate (it serves the certificate of another subdomain). I have to refresh the page multiple times in order to get the correct one.Here is my haproxy configuration:haproxy.conf
haproxy serving wrong SSL certificate for a subdomain
ssl;certificates;haproxy
null
_unix.351468
Using pipes, one can create files with simple shell built-ins.{ echo #!/bin/bash \ echo echo Hello, World! \} > helloworld.shWith chmod these can then be made executable.$ chmod 755 helloworld.sh$ ./helloworld.shHello, World!I wonder whether it is possible to save the chmod step. Already, I found that umask cannot do the job. But perhaps someone knows an environment variable, bash trick, program to pipe through or other neat way to do it.Is it possible to have the file created with the executable bit already set?
create executable files via piping
shell script;permissions;executable
It is not possible to create an executable file solely with a shell redirection operator. There is no portable way, and there is no way in bash either (in the source code, you can see that redirection calls do_redirection_internal which calls redir_open with the parameter mode set to 0666, and this in turn calls open with this mode).You're calling a shell command anyway, so add ; chmod +x somewhere in it. There's absolutely nothing wrong with that. One more line of code is not a problem. You need to do three things (create a file with some given content, make the file executable, execute it), so write three lines.There is a relatively obscure shell command that can create an executable file with some specified content: uudecode. But I would not recommend using it: it requires the input to be passed in a non-readable format, it bypasses the user's umask, and it's obscure.A sane alternative is to call bash /the/script instead of chmod +x /the/script && chmod +x, if you know what interpreter to execute the file with.
_unix.327647
I am trying to prioritize TCP traffic using ToS field in IP header.I am saturating the interface(ethernet) by sending 1GB data through iperf with ToS field set to 0x10 (Minimize-Delay).I then start another TCP client with default ToS (0).Expectation :My TCP client should not send data till iperf completes sending its data.Result:The data from my client is sent even tough iperf is sending packets with higher priority.I also tried to create the same scenario by creating 2 separate clients and allocating 0x10 and 0x08 ToS to respective clients using iptables.I used :iptables -A PREROUTING -t mangle -p tcp --sport 5000 -j TOS --set-tos Minimize-DelayI am still not able to prioritize one client over other. Altough I can see the packets marked with ToS in wireshark.I am using Ubuntu (14.04) with iptables version 1.4.21Can someone kindly help me solve the issue?ThanksVarun
Why am I unable to prioritize TCP traffic using ToS fields?
iptables;tcp;qos
null
_cs.22316
I have a cost function $f(X)=\|\hat{X}-X\|_2$ to minimize which depends on a $s\times s$ matrix $X$ where $\hat{X}$ is given and $\|X\|_2=\big(\sum_{i,j}x_{ij}^2\big)^{1/2} $. This matrix $X$ is generated by selecting only $s$ different rows from a matrix $B$ of dimension $n\times s$. At the end, we are going to choose one matrix $X$ that generates the least cost $f(X)$ within all possible $n\choose s$ submatrices of B. And so, this is a combinatorial problem that becomes complicated mostly when $n$ is big. So my question is can we find a suboptimal solution without going through all possible $n\choose s$ submatrices and what kind of algorithm that I can apply to find such solution.My second question is can we apply a feature selection algorithm to find a suboptimal solution for a combinatorial problem.
Suboptimal Solution for a combinatorial problem
optimization;combinatorics;parallel computing
Mixed-integer quadratic programmingGiven your updated question, this can be formulated as a mixed-integer quadratic programming problem.Let $y_1,\dots,y_n$ be $n$ zero-or-one integer variables, subject to the constraint $y_1+\dots+y_n=s$, with the intent that if $y_i=1$ then we are selecting the $i$th row from $B$. Then for each $i,j$, the entry $(\hat{X}-X)_{i,j}$ can be expressed as a linear function of $y_1,\dots,y_n$. We are asking to minimize the objective function $\sum_i,j (\hat{X}-X)_{i,j}^2$, which is a quadratic objective function. Therefore, this can be expressed as a mixed-integer quadratic programming problem.So, you could try throwing an off-the-shelf solver for mixed-integer quadratic programming at this and see how it does.Closest vector problemIf everything in sight is an integer, I think this problem could also be approached as the problem of finding the closest point in a lattice to a given vector, the closest vector problem (CVP).Consider the following lattice over a $n+s^2$-dimensional space. For each $i$, we have a basis vector of the form$$(0,\dots,0,K,0,\dots,0,B_i,0,\dots,0),$$where $K$ is a large constant (to be chosen later) and in the above, $K$ appears in the $i$th column, and $B_i$ is the $i$th row of $B$ and it appears starting in the $n+(i-1)s+1$th column. This gives us $n$ basis vectors, which form a basis for the lattice. Now we want to find the lattice point that is closest to the vector$$(0,\dots,0,\hat{X}_1,\hat{X}_2,\dots,\hat{X}_s),$$where the first $n$ columns of this vector are zero and $\hat{X}_i$ is the $i$th row of $\hat{X}$. If we choose $K$ appropriately, the closest lattice point has a good chance of being a sum of just $s$ of the basis vectors and thus forming a solution to this problem.Now you could try to see if you can find any off-the-shelf CVP solvers, and see if they are effective at this problem. This is only going to work if everything is an integer: if you've got real numbers, I don't think this will work.
_unix.275014
I have a tar file that ends with .b and I don't know how to open it. Neither in windows, neither Linux I've been successful to open it.data.ext4.tar.bAnother tar that ends with .a could easily be opened in Windowsdata.ext4.tar.aWhat's is the difference? How can I possibly open the .b tar?This is from an Android OS image - a nandroid backup. .a consists of all the apps and hopefully .b consists of pictures
Open tar-file that ends with .b
linux;tar
null
_webmaster.32816
I'm quitely new to SEO and I don't know how to handle foreign content on a blog.I am writing content for two different blogs. The subjects of these blogs intersect partially, so there are sometimes situations in which I like to post exactly the same entry on both blogs. On the other hand I often see blogposts with a note like this post was first published on www.xyz.com.I thought to avoid the problem with double content I could use a canonical link in both cases. But all I read about using it cross-domain supposes to still have the same website.So what is the best practice to handle this, by avoidingthat the original site doesn't benefit from being the first-posted andthat the second site has disadvantages because of containing double content?edit: I assume the fact that google tries to serve different contents for given keywords. Sites which doesn't seem to be the original one of multiple found content are ranked down, based on the presumption the content was stolen or something else (this correct?). How to prevent this behaviour if content is legally doubled? Would the canonical-link be the right way or isn't there any, bercause it'd be against googles aims?
how to handle foreign content on a blog (double content)
seo;google;canonical url;best practices
null
_cs.77138
While Going through Exercise problem of Computer Networking A Top-Down Approach by Kurose and Ross, i encountered this problem.I am giving my approach and the point where i am stuck at.QuestionSuppose Host A sends 5 data segments to Host B, and the 2nd segment (sent from A) is lost. In the end, all 5 data segments have been correctly received by Host B.How many segments has Host A sent in total and how many ACKs has Host B sent in total for Go Back NGiven AnswerGoBackN: $A$ sends $9$ segments in total. They are initially sent segments $1, 2, 3, 4, 5 $and later resent segments $2, 3, 4, $and $5$. $B$ sends $8$ ACKs. They are $4$ ACKS with sequence number $1,$ and $4$ ACKS with sequence numbers $2, 3, 4,$ and $5.$My Approach /DoubtI agree with the number of transmission of data segment by Host $A$.But i have doubt regarding the Acknowledgement by Host $B$.Why?We know that GBN has sender side window size=$N$ while reciever side as only$1$ which is the reason that it cannot recieve Out of order packet.Now When Host $A$ sends entire packet $1,2,3,4,5$ where $2^{nd}$ gets lost then Host $B$ which is expecting Sequence number $1$.On recieving sequence number $1$, it will send ack as $2$i.e expecting sequence number $2$.As Sequence number gets lost , host $B$ will recieve sequence $3,4,5$ for which it will discard the packet as it is not the packet it is expecting.On recieving again sequence number $2,3,4,5$(retransmitted packet), Host $B$ will send the Acknowledgement.Total Acknowledgement i am getting is $5$ i.e ACk no for sequence number $1,2,3,4,5$ not $8$.Please help me out where i am wrong ??Thanks
Number of Retransmission in case of Go Back N
computer networks
GBN is resending ACK's for the discarded packets .Excerpt from what I can find:The receiver's actions in GBN are also simple. If a packet with sequence number n is received correctly and is in-order (i.e., the data last delivered to the upper layer came from a packet with sequence number n-1), the receiver sends an ACK for packet n and delivers the data portion of the packet to the upper layer. In all other cases, the receiver discards the packet and resends an ACK for the most recently received in-order packet. Note that since packets are delivered one-at-a-time to the upper layer, if packet k has been received and delivered, then all packets with a sequence number lower than k have also been delivered. Thus, the use of cumulative acknowledgements is a natural choice for GBN.
_unix.180207
In my ssh_config file there are multiple entries for sites on the same server such as:Host site1 HostName 123.1.1.1 User myuser Port 13245 GSSAPIAuthentication no IdentityFile /home/myuser/.ssh/id_dsaHost site2...I use a passphrase protected key in order to log in to the remote server and this works fine. However, I'm attempting to create some bash scripts that synchronize files using rsync and would like for the script to to prompt me for the passphrase and then execute the rsync command. ssh-agent seems to be what I want to use but I'm having difficulty figuring it out. I'm looking for something like...HOST=site1:SRC=/var/fooDEST=/home/barSYNC=(rsync $SRC $HOST$DEST...)# rsync /var/foo site1:/home/bar...read -r -p Are you sure? [y/N] responseresponse=${response,,}if [[ $response =~ ^(yes|y)$ ]]then #check to see if the passphrase exists from prior execution of this script. if [ no ];then #use ssh-add to prompt for passphrase ssh-add #? ; #then execute rsync command ${SYNC[@]} else #execute rsync command ${SYNC[@]} fielse echo Operation aborted!fiThe only examples I've been able to find either suggest code be placed in .bashrc or .profile which forces me to enter a passphrase each time I start a shell or create an expect file which stores the passphrase, neither of which I desire to do. How can I achieve a prompt for the passphrase only once when I start my rsync script so that I can switch hosts and rerun the script as in my example.
How can I invoke a prompt for an ssh key passphrase during the execution of a script?
bash;shell script;ssh;rsync;prompt
First you may check whether ssh-agent is running and start it if not:if ! [ -n $SSH_AUTH_SOCK ] || ! { ssh-add -l &>/dev/null; rc=$?; [ $rc -eq 0 ] || [ $rc -eq 1 ];}; then echo Starting agent... eval $(ssh-agent -s)fissh-add -l exits with code 1 if there are no identities and with code 2 if it cannot connect to ssh-agent.Then you add the passphrase for the key you need.ssh-add ~/path/to/keyfile
_unix.9221
I'm running wget like this:wget --mirror --adjust-extension --convert-links --no-cookies http://tshepang.net -o log-mainI get a bunch of these messages:Last-modified header missing -- time-stamps turned off.I suppose that means that pages keep getting re-downloaded, even though I have them locally.NOTE: I want this so that I don't have to re-download existing files each time I run the command mirror.
How to work around missing 'last-modified' headers?
wget;web
Did you try adding the -c parameter?Excerpt from wget manual:-c --continueBeginning with Wget 1.7, if you use -c on a non-empty file, and it turns out that the server does not support continued downloading, Wget will refuse to start the download from scratch, which would effectively ruin existing contents. If you really want the download to start from scratch, remove the file.Also beginning with Wget 1.7, if you use -c on a file which is of equal size as the one on the server, Wget will refuse to download the file and print an explanatory message. The same happens when the file is smaller on the server than locally (presumably because it was changed on the server since your last download attempt)---because ''continuing'' is not meaningful, no download occurs.On the other side of the coin, while using -c, any file that's bigger on the server than locally will be considered an incomplete download and only (length(remote) - length(local)) bytes will be downloaded and tacked onto the end of the local file. This behavior can be desirable in certain cases---for instance, you can use wget -c to download just the new portion that's been appended to a data collection or log file.To my knowledge it should skip files that are already downloaded and of the same size.
_codereview.144492
Have some ideas to improve code from this discussion (Find valid triples for a sorted list of integers), and post new code in a new post.The new idea is, trying to remember where low bound searched last time, and when doing the search, only search from the lower bound where last search is satisfied, since with j increase each time, the 3rd dimension of satisfied triple could only increase. More specifically, these two lines, #upperBoundIndex = findSum(numbers, j+1, numbers[i]+numbers[j]) # previous code upperBoundIndex = findSum(numbers, upperBoundIndex, numbers[i] + numbers[j]) I'm working on a problem in which I have an input array, sorted positive unique integers, and have to try to find all possible triples \$(x,y,z)\$ which satisfy \$x+y>z\$ and \$x<y<z\$. For example, \$(1,2,3)\$ is not a valid triple since \$1+2\$ is not \$> 3\$, and \$(3,4,5)\$ is a valid triple since \$3<4<5\$ and \$3+4>5\$.This code leverages binary search, and I'm wondering if this can be improved in terms of time complexity. Please also help to point out any code issues/bugs or improvement areas.BTW, I am not using enumeration feature of Python since I want to keep j greater than i, and leverage the feature in my logics.from __future__ import divisiondef findSum(numbers, startIndex, value): find index whose value is less than input parameter value (as upper bound) ,and the greatest possible value possible :param numbers: sorted value to search, may contains duplicates :param startIndex: where to search from, inclusive :param value: upper bound to search :return: the index whose value is less than upper bound value low = startIndex high = len(numbers) - 1 while low <= high: mid = (low + high) // 2 if numbers[mid] == value: while mid >= low and numbers[mid] == value: mid -= 1 return mid if mid >= low else -1 elif numbers[mid] > value: high = mid - 1 else: low = mid + 1 # while return low-1 if (low-1) >= startIndex else -1def findTriagles(numbers): :param numbers: could contains duplicate number, assume numbers are sorted :return: unique triples results = set() for i in range(0, len(numbers)-2): upperBoundIndex=min(i+2, len(numbers)-1) for j in range(i+1, len(numbers)-1): #upperBoundIndex = findSum(numbers, j+1, numbers[i]+numbers[j]) # previous code upperBoundIndex = findSum(numbers, upperBoundIndex, numbers[i] + numbers[j]) if upperBoundIndex != -1: for k in range(j+1, upperBoundIndex+1): results.add((numbers[i],numbers[j],numbers[k])) return resultsif __name__ == __main__: #print findTriagles([4,5,6,7]) # output, set([(4, 6, 7), (4, 5, 7), (4, 5, 6), (5, 6, 7)]) print findTriagles([4, 4, 6, 7]) # output, set([(4, 4, 6), (4, 4, 7), (4, 6, 7)])
Find valid triples for a sorted list of integers (part 2)
python;algorithm;python 2.7;sorting;binary search
null
_unix.21378
I would love to get the mappings to work for keyboard shortcuts shown here http://ascii-table.com/ansi-escape-sequences.php I have the hang of color but for some reason nothing else seems to work!
Non printing characters
bash;terminal
Those codes are primarily for ANSI.SYS, a DOS extension. The equivalent for BASH is to rebind the keys via readline. See the bash(1) man page, READLINE section.
_codereview.135259
I have a to write a simple utility function that given a time in CST and a date in PST, tells if the date is today and if the current time is less than the cutoff (post converting cutoff to PST).This is my attempt (highly childish but I seriously don't get Java date-time at all). If anyone could help me improve this code, I would be highly grateful. /** * Returns true if: * - availableDate is today * - currentTime is less than cutoff time * False otherwise * * @param cutoffTimeStr HH:mm format, CST timezone * @param availableDate YYYYMMDD format, PST timezone * @return true/false */ public Boolean test(String cutoffTimeStr, String availableDate) throws ParseException{ DateFormat availableDateFormat = new SimpleDateFormat(YYYYMMDD, Locale.ENGLISH); Date avlDate = availableDateFormat.parse(availableDate); avlDate.setHours(new Date().getHours()); avlDate.setMinutes(new Date().getMinutes()); //Compose current time with the given date DateFormat cutOffFormat = new SimpleDateFormat(HH:mm); cutOffFormat.setTimeZone(TimeZone.getTimeZone(CST)); Time cutOffTime = new java.sql.Time(cutOffFormat.parse(cutoffTimeStr).getTime()); //cutOffTime is PST version of given CST time Date currentDateWithCutoffTime = new Date(); currentDateWithCutoffTime.setHours(cutOffTime.getHours()); currentDateWithCutoffTime.setMinutes(cutOffTime.getMinutes()); //Today's date with time as cutoff if(avlDate.before(currentDateWithCutoffTime)){ return true; } else{ return false; } }I have assumed that the availableDate will always be today or greater than today and thus, if its before the currentDateWithCutoffTime, we can return true.
Java util to compare if time beyond cutoff
java;datetime
null
_cs.44816
Could you please resolve a confusion with Schaefer's theorem for me? Namely, why does it not imply many problems in P are NP-complete? For example, primality testing surely cannot be reduced to one of the six classes in the theorem, so why does that not imply it's NP-complete?
Shaefer's Dichotomy Theorem
complexity theory;np complete;satisfiability
null
_softwareengineering.87460
What is the best strategy to go about understanding some one else's code for a medium sized project, if the code is not well documented and does not adhere to many coding standards?
Deciphering foreign code
maintenance;comments;knowledge transfer
My approach:Play with the app (use it)Check the code organization (layers/entities etc.)Generate references diagram (i.e. using NDepend for .NET)Look for some code patterns in code (this will give you some ideas what the author(s) tried to implement)Don't dig into details too deep at start.Focus on understanding the dataflow (i.e. how are lists populated, how is data saved, for example: UI->BusinessLayer->DataAccessLayer->SLQ Stored Procedure)
_cstheory.10362
I am a computer science research student working in application of Machine Learning to solve Computer Vision problems.Since, lot of linear algebra(eigen-values, SVD etc.) comes up when reading Machine Learning/Vision literature, I decided to take a linear algebra course this semester. Much to my surprise, the course didn't look at all like Gilbert Strang's Applied Linear algebra(on OCW) I had started taking earlier. The course textbook is Linear Algebra by Hoffman and Kunze. We started with concepts of Abstract algebra like groups, fields, rings, isomorphism, quotient groups etc. And then moved on to study theoretical linear algebra over finite fields, where we cover proofs for important theorms/lemmas in the following topics:Vector spaces, linear span, linear independence, existence of basis. Linear transformations. Solutions of linear equations, row reduced echelon form, complete echelon form,rank. Minimal polynomial of a linear transformation. Jordan canonical form. Determinants. Characteristic polynomial, eigenvalues and eigenvectors. Inner product space. Gram Schmidt orthoganalization. Unitary and Hermitian transformations. Diagonalization of Hermitian transformations.I wanted to understand if there is any significance/application of understanding these proofs in machine learning/computer vision research or should I be better off focusing on the applied Linear Algebra?
What is the significance of abstract linear algebra in machine learning/computer vision research?
machine learning;linear algebra;cv.computer vision
In my experience (YMMV) linear algebra is very much used as a tool in Machine Learning and Computer Vision, with little interest in the underlying mathematics.That said, you'll need a more mathematical understanding than, say, a games programmer or a basic researcher in the natural sciences. Basically you'll need to know enough to take a method like PCA apart and put it back together again, but you don't need to worry about your matrices containing anything other than real values. It sounds like this course is starting off deeper and more general than you want, but the list of topics suggests that you are moving in the right direction. So long as some attention is given to how to translate the mathematical methods into the computer. It's one thing to suggest that an SVD decomposition exists, and another to actually compute it.The deep mathematical understanding won't hurt, but there's no guarantee that all of it will be useful to you.
_unix.28853
I've used NEdit since about 2003. NEdit's whitespace highlighting is subtle and I prefer it to the dot other editors put in whitespace. NEdit's background normally is light grey and whitespace is rendered as white without a dot (and tabs in a darker gray).However, NEdit doesn't support UTF-8 encoding, so I don't intend to use NEdit for much longer. I've (reluctantly) determined that gedit is the presently available editor that is closest to what I want.I am trying to replicate NEdit's look in gedit without success. I can change the style of the spaces shown with the Draw Spaces plugin by adding the following to the gedit style file:<style name=draw-spaces foreground=color/>The foreground property only changes the color of the dot. There does not appear to be a corresponding background property to change the background. I thought if I made foreground and background the same color then I could replicate NEdit's look.How can I change the background color of the whitespace highlighting in gedit without also changing the background color of the remainder of the text?
Changing background color of gedit's whitespace highlighting
gedit
null
_cstheory.27104
I was wondering, is the bitonic sort algorithm stable? I searched the original paper, wikipedia and some tutorials, could not find it.It seems to me that it should be, as it is composed of merge / sort steps, however was unable to find answer anywhere.The reason why I'm asking - I was comparing this particular implementation of bitonic sort to the sort implemented in the C++ standard library, for array length 9 it requires 28 comparison / swap operations, while the standard library sort (which is unstable) requires 25. The three extra cswaps do not seem enough to make the sort stable.
Is the bitonic sort algorithm stable?
sorting;sorting network;stable
No, bitonic sort is not stable.For this post I will denote numbers as 2;0 where only the part before the ; is used for comparison and the part behind ; to mark the initial position.Comparison-exchanges are denoted by arrows where the head points at the desired location of the greater value.As written in the link that @JukkaSuomela posted a stable sorting network needs to avoid swaps of equal values.When swapping equal values, the bitonic sorter for two values is already unstable:0;0 ----- 0;1 | v0;1 ----- 0;0Of course, this can be fixed when we don't swap equal values:0;0 ----- 0;0 | v0;1 ----- 0;1However, it could happen that the order of two equal elements is swapped without them being compared to each other.This is exactly the case in this example of a bitonic sorter for 4 values:1;0 ------ 1;0 ------ 0;2 ------ 0;2 ^ | | | | v1;1 ------ 1;1 --|--- 1;1 ------ 1;1 || v|0;2 ------ 0;2 ---|-- 1;0 ------ 1;0 | | | v v v2;3 ------ 2;3 ------ 2;3 ------ 2;3Although we were careful not to swap elements that compared equal (upper left comparison), the merging pass swapped the order of 1;1 and 1;0 which cannot be corrected later on.This counterexample proves that bitonic sort cannot be stable.
_unix.235489
What does . /path/to/a/shell-script-filedo exactly? I mean obviously it executes that shell script but why put that . followed by a space before the path/name of the script file?
. /path/to/a/shell-script-file ? (within a shell script)
bash;shell
null
_webapps.51728
I have one problem to bring to your kind attention and I hope that you'll know the answer and thus help me. Well, it is about WiseStamp, I have been used it in the past, so I am quite familiar to it. Only that I have been using it intermittently. I remember that it used to work excellent on all of my email accounts be it Yahoo or Google.But now I have installed it is again on all of my browsers, and although it seem to work fine in Gmail, it has a problem with Yahoo - the WiseStamp signature doesn't appear at all and I can't insert it either. I must say that, when I sign into my WiseStamp account and I edit my signature, I do can see it, but only in my preview signature. Otherwise, I can only see it in my Gmail, as I have already told. I have to mention that, in order to solve this situation, I have followed the advices from the official site. But, unfortunately, those advices did not helped much. Practically, they ask me to reinstall the add-on. I did that three times, but with no result. I did a Google search over it but it seem that I have no luck in it. All I could find was an article apparently suggesting that the new changes of Yahoo mail can affect some codes, or something like that. and it occurred to me that this might be the cause of the unusual behaviour of the add-on.Even so, this must have a solution, and if you know how to fix this and make the WiseStamp signature reappear in Yahoo mail, please, tell me!Thank you in advance for your help!
How can I fix a WiseStamp signature who disappears from Yahoo mail?
yahoo mail;email signature
null
_codereview.123571
This code calls the iControl REST API provided by BIG-IP LTM. Trying to get the list of the pools, it's current status and the pool members associated with the pool.My code works like this, based on three calls:Get the pool names (/mgmt/tm/ltm/pool)Based on the pool names (path), get its status (mgmt/tm/ltm/pool/~pool~name/stats)Based on the pool names (path), get its pool members (/mgmt/tm/ltm/pool/~pool~names/members)If I do only the first call, I get the output within milliseconds. After adding the second call, it becomes worse. With a third call, it takes good amount of time (more than 6 minutes) to get all the output for about 400 pools.How can I optimize this code?import requestsfrom requests.auth import HTTPBasicAuthBASE_URL = https://localhost/mgmt/tmusername = adminpassword = admindef makeRequest(username, password, url): response_data = requests.get(url, auth = HTTPBasicAuth(username, password), verify = False) return response_data.json()pool_data = makeRequest(username, password, BASE_URL + /ltm/pool)for pools in pool_data['items']: print pools['name'] tildPath = pools['fullPath'].replace('/','~') #GET the Pool stats pool_stats = makeRequest(username, password, BASE_URL + /ltm/pool/ + tildPath + /stats) print pool_stats['entries']['status.availabilityState']['description'] #GET the Pool Members pool_members = makeRequest(username, password, BASE_URL + /ltm/pool/ + tildPath + /members) for members in pool_members['items']: print members['name'] + + members['address'] + + members['state']
REST API calls to BIG-IP LTM to get the status of pool members
python;performance;rest;status monitoring
null
_codereview.95262
HTTP request is made, and a JSON string is returned, which needs to be parsed.Example response:{urlkey: com,practicingruby)/, timestamp: 20150420004437, status: 200, url: https://practicingruby.com/, filename: common-crawl/crawl-data/CC-MAIN-2015-18/segments/1429246644200.21/warc/CC-MAIN-20150417045724-00242-ip-10-235-10-82.ec2.internal.warc.gz, length: 9219, mime: text/html, offset: 986953615, digest: DOGJXRGCHRUNDTKKJMLYW2UY2BSWCSHX}{urlkey: com,practicingruby)/, timestamp: 20150425001851, status: 200, url: https://practicingruby.com/, filename: common-crawl/crawl-data/CC-MAIN-2015-18/segments/1429246645538.5/warc/CC-MAIN-20150417045725-00242-ip-10-235-10-82.ec2.internal.warc.gz, length: 9218, mime: text/html, offset: 935932558, digest: LJKP47MYZ2KEEAYWZ4HICSVIHDG7CARQ}{urlkey: com,practicingruby)/articles/ant-colony-simulation?u=5c7a967f21, timestamp: 20150421081357, status: 200, url: https://practicingruby.com/articles/ant-colony-simulation?u=5c7a967f21, filename: common-crawl/crawl-data/CC-MAIN-2015-18/segments/1429246641054.14/warc/CC-MAIN-20150417045721-00029-ip-10-235-10-82.ec2.internal.warc.gz, length: 10013, mime: text/html, offset: 966385301, digest: AWIR7EJQJCGJYUBWCQBC5UFHCJ2ZNWPQ}My code:result = Net::HTTP.get(URI(http://index.commoncrawl.org/CC-MAIN-2015-18-index?url=#{url}&output=json)).split(})result.each do |res| break if res == \n #need to add back braces because we used it to split the various json hashes from the http request res << } to_crawl = JSON.parse(res) puts to_crawlendIt works, but I'm sure there is a much better way to do it, or at least a better way to write the code.
Parsing JSON string from HTTP request
ruby;json;http
This body.split('{'}) is doing you a disservice, as it destroys the structure of the response. Split it by lines instead:body = Net::HTTP.get(...)data = body.lines.map { |line| JSON.parse(line) }
_cs.77390
The order of the classes of three does not matter. Example: 1,2,3 and 3,2,1 would be considered one class. I am trying to do fisher discriminant analysis on a set of data and want to begin reducing the parameters to better help with classification. As of now I cannot tell which parameters are the most pertinent, so looping every combination through and then having MATLAB take out the LDA analysis with the MisIDs on the lower end in my algorithm will help to isolate the parameters. Can someone refresh me on the math behind this/suggest a way to code this in MATLAB?
Data Analysis: Have 70 data parameters, how many different classes of 3 are possible?
combinatorics
null
_unix.122992
I have installed Debian 7.4 on my Iomega ix2-200 NAS, following this blog. The ix2-200 is running an ARM Marvel CPU and has a 128 MB NAND flash memory. The flash contains an initramfs image (uInitrd) and a kernel image (uImage) to boot the system.Sometimes, a new package (like cryptsetup) requieres to update the kernel and fails (Unsupported platform). I manually need to flash the new initramfs initrd.img-3.2.0-4-kirkwood and kernel vmlinuz via mkimage, which works fine.The (anoying) issue: everytime I run apt-get upgrade the system is showing up those unfinished packages. How can I tell my system that everything is fine?I have tried Google and StackExchange, but most of the posts are dealing with how to remove those unfinished/incomplete packages. I want to keep it!Please see attached code snapshot:#> apt-get install cryptsetupReading package lists... DoneBuilding dependency treeReading state information... DoneThe following extra packages will be installed: console-setup console-setup-linux cryptsetup-bin kbd keyboard-configuration libcryptsetup4 xkb-dataSuggested packages: dosfstoolsThe following NEW packages will be installed: console-setup console-setup-linux cryptsetup cryptsetup-bin kbd keyboard-configuration libcryptsetup4 xkb-data0 upgraded, 8 newly installed, 0 to remove and 0 not upgraded.Need to get 3,179 kB of archives.After this operation, 11.8 MB of additional disk space will be used.Do you want to continue [Y/n]? y...Processing triggers for initramfs-tools ...update-initramfs: Generating /boot/initrd.img-3.2.0-4-kirkwoodUnsupported platform.run-parts: /etc/initramfs/post-update.d//flash-kernel exited with return code 1dpkg: error processing initramfs-tools (--configure): subprocess installed post-installation script returned error exit status 1Errors were encountered while processing: initramfs-toolsE: Sub-process /usr/bin/dpkg returned an error code (1)#> apt-get upgradeReading package lists... DoneBuilding dependency treeReading state information... Done0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.1 not fully installed or removed.After this operation, 0 B of additional disk space will be used.Do you want to continue [Y/n]?
How to mark not fully installed apt-get package as successfully installed
debian;apt;initramfs
You should fix /etc/initramfs/post-update.d/flash-kernel so that it successfully flashes your kernel & initrd. It's in /etc, so you're free to edit it to make it work on your board.If you can't edit it to make it work (e.g., flashing is done with JTAG), then you ought to have it print out a big warning reminding you to flash it, and exit 0.Once you've fixed it, then you can run dpkg --configure -a.
_unix.92158
I have a xml called Det.xml like this :<?xml version=1.0 encoding=UTF-8?> <S:Envelope xmlns:S=http://schemas.xmlsoap.org/soap/envelope/> <S:Body> <ns4:grtHgetRed xmlns:ns2=http://object xmlns:ns3=http://object xmlns:ns4=http://object> <RequestId>lol</RequestId> <MessageDateTime>54.009</MessageDateTime> <SenderId>UH</SenderId> <ReceiverId>GER</ReceiverId> <TrackingNumber>45</TrackingNumber> <ServerName>trewds</ServerName> <ResponseType>success</ResponseType> <StatusInfo> <Status>success</Status> <SystemMessage>Hagert</SystemMessage> <UserMessage>Hgert</UserMessage> <Origination>htref</Origination> </StatusInfo> </ns4:grtHgetRed> </S:Body> </S:Envelope>I am trying to get the ResponseType node value success from it using xmllint in Unix shell script and so i tried the following :echo cat //*[local-name()='S:Envelope'/*[local-name()='S:Body']/*[local-name()='ns4:grtHgetRed']/*[local-name()='ResponseType'] | xmllint --shell Det.xml | sed '/^\/ >/d' | sed 's/<[^>]*.//g'But it's not working . Also i don't have xpath in my unix environment . Can any one tell me what am i doing wrong here ?I also tried using statusMSG==$(echo cat /Envelope/Body/grtHgetRed/ResponseType/text() | xmllint --nocdata --shell response.xml | sed '1d;$d'), then echo $statusMSG, but this gives an empty echo. Is this because of namespace problem ?
Get Node value from a XML using xmllint
xmllint
If your Det.xml is always going to look like that (e.g. won't have any extra ResponseType nodes), you can simply use this:xmllint --xpath 'string(//ResponseType)' Det.xmlAnd it will spit out: successIf your xmllint doesn't have xpath for some reason, you can always fall back to regular expressions for this sort of thing:grep -Po '(?<=<ResponseType>)\w+(?=</ResponseType>)' Det.xmlIt uses Perl regular expressions to allow for the positive look aheads / look behinds and only shows the matched part (not the whole line). This will output the same as above without using xmllint / xpath at all.
_webmaster.64791
I'm trying to understand if/how I can benefit from people linking to pages on my site which are with pages that have a noindex meta tag. 2 actions I'm considering to perform:Remove the robots.txt disallow to these pages, to make sure inner links get the propagated link juice.Adding a canonical tag to the most similar page that doesn't have a noindex meta tagAre these valid approaches that might help? Any others I should consider?
Can I benefit from links to pages on my site which have a `noindex` meta tag?
seo;canonical url;noindex
null
_webapps.82378
I have the following table.What I want to do is as follows.User selects either Minor, Medium, or Major and that specifies which column is used. User then inputs a number 1-100 and the chart then looks to find where the value follows and returns the text in the far right column.So if the user selects Minor and inputs 9 it would return Weapons but if they selected Medium and input 9 it would return Armor and Shields.I thought of one way to do this would be nested if statements with a unique VLookup in each(Example below) but I would prefer a much cleaner way to right this but I can't think of anyway.If (A1=Minor,Vlookup(A2, B2:E11,4),if(A2=Medium,Vlookup(A2, C2:E11,3)ECT...)
How to perform a Vlookup with search column dynamic depending on input in another cell
google spreadsheets
By default, vlookup assumes the data is sorted, and finds the largest element that is less than or equal to the search key. Therefore, you should fill the table with the lower bound for each range: +-------+--------+-------+---------+| Minor | Normal | Major | Item || 1 | 1 | 1 | Arrow || 5 | 11 | 11 | Weapons || 10 | 21 | 21 | Potion || 45 | 32 | 26 | Ring |+-------+--------+-------+---------+Let's say the above is your range B2:E6. The first step is to filter the columns, so that only two are left: one of the first three, and the last one. For this I would use filter based on regexmatch: =filter(B2:E6, regexmatch(B2:E2, ^(&A1&|Item)$))For example, if A1 has Normal (my favorite mode) then the regular expression is ^(Normal|Item)$ which matches either of two words, and nothing else. So, if we don't do anything else, the result is +--------+---------+| Normal | Item || 1 | Arrow || 11 | Weapons || 21 | Potion || 32 | Ring |+--------+---------+But of course we don't stop here: the filtered columns should be fed into vlookup: =vlookup(A2, filter(B2:E6, regexmatch(B2:E2, ^(&A1&|Item)$)), 2)And that is the formula you want. For example, if A2 is 15, then the largest entry that is <=A2 is 11, so the returned value is Weapons.
_codereview.77610
Given my IUnitOfWork interface using System;public interface IUnitOfWork : IDisposable{ void Commit();}I then create an abstract factory interface called IUnitOfWorkFactoryusing System.Transactions;public interface IUnitOfWorkFactory{ IUnitOfWork GetUnitOfWork(IsolationLevel isolationLevel);}I then create a default implementation of my IUnitOfWork called TransactionScopeUnitOfWorkusing System;using System.Transactions;public class TransactionScopeUnitOfWork : IUnitOfWork{ private bool disposed = false; private readonly TransactionScope transactionScope; public TransactionScopeUnitOfWork(IsolationLevel isolationLevel) { this.transactionScope = new TransactionScope( TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = isolationLevel, Timeout = TransactionManager.MaximumTimeout }); } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { this.transactionScope.Dispose(); } disposed = true; } } public void Commit() { this.transactionScope.Complete(); }}I then create the factory to return that implementation called TransactionScopeUnitOfWorkFactoryusing System.Transactions;public class TransactionScopeUnitOfWorkFactory : IUnitOfWorkFactory{ public IUnitOfWork GetUnitOfWork(IsolationLevel isolationLevel) { return new TransactionScopeUnitOfWork(isolationLevel); }}The reason for creating the factory is to allow DI (Dependency Injection) frameworks to use different unit of work implementations depending on configuration.If TransactionScopeUnitOfWorkFactory was mapped to IUnitOfWorkFactory in a DI container, some sample code for using it in an application could be:public class Test{ private readonly IUnitOfWorkFactory unitOfWorkFactory; private readonly IRepository testRepository; public Test( IRepository testRepository, IUnitOfWorkFactory unitOfWorkFactory) { this.testRepository = testRepository; this.unitOfWorkFactory = unitOfWorkFactory; using (IUnitOfWork unitOfWork = this.unitOfWorkFactory.GetUnitOfWork(IsolationLevel.Serializable)) { this.testRepository.Delete(1); // Some valid CRUD unitOfWork.Commit(); } }I am asking if this seems like a good implementation. Am I missing anything?I want an IUnitOfWork interface that I can use across applications and not worry about maintaining later on. Any opinions?
Reusable Unit Of Work Interface / Factory
c#;design patterns;.net;repository
null
_codereview.80439
Here is the story.We have the BankTerminalSettings class. It has many properties:public class BankTerminalSettings { public bool IsEnabled { get; set; } public string IPAddress {get; set;} public ushort TcpPort {get; set; } public List<string> Zombies {get; set;} //and many other properties}And we have a class which takes BankTerminalSettings as a parameter of it's constructor.public class BankTerminal { public BankTerminal(BankTerminalSettings terminal, int clientId) { ValidateBankTerminalSettings(terminal); terminalSettings = terminal; this.clientId = clientId; }}The thing is that the BankTerminal uses only three of all those properties in that domain config class named BankTerminalSettings.It's a temptation just to pass the whole instace of the BankTerminalSettings, but the caller can incidentally change those properties which are relevant for the BankTerminal. That can cause very subtle bugs.What would you recommend?To replicate the BankTerminalSettings before passing it's instance?To replicate the BankTerminalSettings in the constructor of the BankTerminal?To pass only those parameters which are truely needed by the BankTerminal?
Initializing object by settings implemented as a class
c#;.net;constructor
It depends on whether you want to handle config updates or not. In your case I guess you just want to work with data at constructing point. There are few options to do this:Make copy of your settings before they are passed and use BankTerminalSettings inside the BankTerminal (as was considered). But personally I dont like the idea there are different BankTerminalSettings passing around.Better approach would be just to inialize your internal fields with config settings, i.e. to copy settings of BankTerminalSettings to BankTerminalAlso I'm worried with the fact BankTerminalSettings contain more properties than is needed for BankTerminal. Maybe BankTerminalSettings should get another name? Anyway, I would create interface IBankTerminalSettings that contain only properties needed by BankTerminal and pass it to BankTerminal constructor
_unix.305013
I am trying access a USB device using libFtd2xx (Version : libftd2xx.so.1.3.6)driver. Driver Link : http://www.ftdichip.com/Drivers/D2XX/Linux/ReadMe-linux.txt ...To test device functionality used Simple from example directory and mentioned below are the output during execution.Under ROOTvenkat:/opt# ./simple-dynamicDevice 0 Serial Number - 12Z9UXGVDevice 1 Serial Number -Opened device 12Z9UXGVUnder NON_Privilaged Uservenkat@venkat:/opt$ ./simple-dynamicError: FT_ListDevices(2)Under ROOT User : Device accessing worked as expected. However, when tried executing it under normal user the device was not accessible.I believe it is somewhere related to some permission . But not able to get through this.Strace Diff ROOT open(/dev/bus/usb/001/005, O_RDWR) = 10Normal user open(/dev/bus/usb/001/005, O_RDWR) = -1 EACCES (Permission denied)Thing I made sure before running this application: 1. rmmod ftdi_sio (as super user) 2. chmod 0755 /usr/local/lib/libftd2xx.so.1.3.6 3. ln -sf /usr/local/lib/libftd2xx.so.1.3.6 /usr/local/lib/libftd2xx.soTried adding permission to UDEV too:ACTION==add, SUBSYSTEMS==usb, ATTRS{idVendor}==0403, ATTRS{idProduct}==6014, MODE=0755Request some guidance in addressing this issue.Source Sample:/* Simple example to open a maximum of 4 devices - write some data then read it back. Shows one method of using list devices also. Assumes the devices have a loopback connector on them and they also have a serial number*//*To build use the following gcc statement (assuming you have the d2xx library in the /usr/local/lib directory).gcc -o simple main.c -L. -lftd2xx -Wl,-rpath /usr/local/lib*/#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include ../ftd2xx.h#define BUF_SIZE 0x10#define MAX_DEVICES 5static void dumpBuffer(unsigned char *buffer, int elements){ int j; printf( [); for (j = 0; j < elements; j++) { if (j > 0) printf(, ); printf(0x%02X, (unsigned int)buffer[j]); } printf(]\n);}int main(){ unsigned char cBufWrite[BUF_SIZE]; unsigned char * pcBufRead = NULL; char * pcBufLD[MAX_DEVICES + 1]; char cBufLD[MAX_DEVICES][64]; DWORD dwRxSize = 0; DWORD dwBytesWritten, dwBytesRead; FT_STATUS ftStatus; FT_HANDLE ftHandle[MAX_DEVICES]; int iNumDevs = 0; int i, j; int iDevicesOpen; for(i = 0; i < MAX_DEVICES; i++) { pcBufLD[i] = cBufLD[i]; } pcBufLD[MAX_DEVICES] = NULL; ftStatus = FT_ListDevices(pcBufLD, &iNumDevs, FT_LIST_ALL | FT_OPEN_BY_SERIAL_NUMBER); if(ftStatus != FT_OK) { printf(Error: FT_ListDevices(%d)\n, (int)ftStatus); return 1; } for(i = 0; ( (i <MAX_DEVICES) && (i < iNumDevs) ); i++) { printf(Device %d Serial Number - %s\n, i, cBufLD[i]); } for(j = 0; j < BUF_SIZE; j++) { cBufWrite[j] = j; } for(i = 0; ( (i <MAX_DEVICES) && (i < iNumDevs) ) ; i++) { /* Setup */ if((ftStatus = FT_OpenEx(cBufLD[i], FT_OPEN_BY_SERIAL_NUMBER, &ftHandle[i])) != FT_OK){ /* This can fail if the ftdi_sio driver is loaded use lsmod to check this and rmmod ftdi_sio to remove also rmmod usbserial */ printf(Error FT_OpenEx(%d), device %d\n, (int)ftStatus, i); printf(Use lsmod to check if ftdi_sio (and usbserial) are present.\n); printf(If so, unload them using rmmod, as they conflict with ftd2xx.\n); return 1; } printf(Opened device %s\n, cBufLD[i]); iDevicesOpen++; if((ftStatus = FT_SetBaudRate(ftHandle[i], 9600)) != FT_OK) { printf(Error FT_SetBaudRate(%d), cBufLD[i] = %s\n, (int)ftStatus, cBufLD[i]); break; } printf(Calling FT_Write with this write-buffer:\n); dumpBuffer(cBufWrite, BUF_SIZE); /* Write */ ftStatus = FT_Write(ftHandle[i], cBufWrite, BUF_SIZE, &dwBytesWritten); if (ftStatus != FT_OK) { printf(Error FT_Write(%d)\n, (int)ftStatus); break; } if (dwBytesWritten != (DWORD)BUF_SIZE) { printf(FT_Write only wrote %d (of %d) bytes\n, (int)dwBytesWritten, BUF_SIZE); break; } sleep(1); /* Read */ dwRxSize = 0; while ((dwRxSize < BUF_SIZE) && (ftStatus == FT_OK)) { ftStatus = FT_GetQueueStatus(ftHandle[i], &dwRxSize); } if(ftStatus == FT_OK) { pcBufRead = realloc(pcBufRead, dwRxSize); memset(pcBufRead, 0xFF, dwRxSize); printf(Calling FT_Read with this read-buffer:\n); dumpBuffer(pcBufRead, dwRxSize); ftStatus = FT_Read(ftHandle[i], pcBufRead, dwRxSize, &dwBytesRead); if (ftStatus != FT_OK) { printf(Error FT_Read(%d)\n, (int)ftStatus); break; } if (dwBytesRead != dwRxSize) { printf(FT_Read only read %d (of %d) bytes\n, (int)dwBytesRead, (int)dwRxSize); break; } printf(FT_Read read %d bytes. Read-buffer is now:\n, (int)dwBytesRead); dumpBuffer(pcBufRead, (int)dwBytesRead); if (0 != memcmp(cBufWrite, pcBufRead, BUF_SIZE)) { printf(Error: read-buffer does not match write-buffer.\n); break; } printf(%s test passed.\n, cBufLD[i]); } else { printf(Error FT_GetQueueStatus(%d)\n, (int)ftStatus); } } iDevicesOpen = i; /* Cleanup */ for(i = 0; i < iDevicesOpen; i++) { FT_Close(ftHandle[i]); printf(Closed device %s\n, cBufLD[i]); } if(pcBufRead) free(pcBufRead); return 0;}
Accessing a USB device under Non - Privilaged user with FTDI2XX Driver
linux;debian;drivers;usb;devices
null
_webapps.30971
Is there a way to convert your Facebook friends to subscribers? I have read that some people did it, but I can't find any info about it.
Convert friends to subscribers in Facebook
facebook
null
_webapps.105037
Why can't I remove a device off my Google account activity that is not one of my devices?
Remove access for unknown devices in account activity
google account;security;account management
null
_cs.53450
If I'm given 2 unsorted arrays A and B of n distinct integers and an integer z, how can I determine if there exists an integer in A and an integer in B that add up to z with an expected run time of O(n)? I'm pretty sure that I would have to use a hash table(s) of some sort since I'm dealing with expected run time but I'm not sure how the algorithm would work.Any help would be really appreciated! Thanks!
Determine if there are 2 integers in 2 separate arrays add up to a given number
algorithms;hash tables
Insert the elements of the first array into a hashset S by subtracting from z. I.e., if 3 is an element of the first array, instert z - 3 into S. Then for each element in the second array, check if z - element is already in S. This procedure is O(n).
_unix.385781
I am running the i3 window manager with Debian 9 Stretch on a laptop with a trackpad.I have run into the problem that whenever I type, the mouse is disabled. Is this normal behavior or a bug?nonfree repos have been enabled and linux-firmware-nonfree has been installed. The bug does not show up on other distributions.This does not happen with a USB mousexinput outputVirtual core pointer id=2 [master pointer (3)]Virtual core XTEST pointer id=4 [slave pointer (2)]ETPS/2 Elantech Touchpad id=11 [slave pointer (2)]Virtual core keyboard id=3 [master keyboard (2)]Virtual core XTEST keyboard id=5 [slave keyboard (3)]Video Bus id=7 [slave keyboard (3)]Power Button id=8 [slave keyboard (3)]HP TrueVision HD id=9 [slave keyboard (3)]AT Translated Set 2 keyboard id=10 [slave keyboard (3)]HP Wireless hotkeys id=12 [slave keyboard (3)]HP WMI hotkeys id=13 [slave keyboard (3)]Power Button id=6 [slave keyboard (3)]Touchpad PropertiesDevice 'ETPS/2 Elantech Touchpad': Device Enabled (142): 1 Coordinate Transformation Matrix (144): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000 libinput Tapping Enabled (277): 0 libinput Tapping Enabled Default (278): 0 libinput Tapping Drag Enabled (279): 1 libinput Tapping Drag Enabled Default (280): 1 libinput Tapping Drag Lock Enabled (281): 0 libinput Tapping Drag Lock Enabled Default (282): 0 libinput Tapping Button Mapping Enabled (283): 1, 0 libinput Tapping Button Mapping Default (284): 1, 0 libinput Accel Speed (285): 0.000000 libinput Accel Speed Default (286): 0.000000 libinput Natural Scrolling Enabled (287): 0 libinput Natural Scrolling Enabled Default (288): 0 libinput Send Events Modes Available (262): 1, 1 libinput Send Events Mode Enabled (263): 0, 0 libinput Send Events Mode Enabled Default (264): 0, 0 libinput Left Handed Enabled (289): 0 libinput Left Handed Enabled Default (290): 0 libinput Scroll Methods Available (291): 1, 1, 0 libinput Scroll Method Enabled (292): 1, 0, 0 libinput Scroll Method Enabled Default (293): 1, 0, 0 libinput Disable While Typing Enabled (294): 1 libinput Disable While Typing Enabled Default (295): 1 Device Node (265): /dev/input/event1 Device Product ID (266): 2, 14 libinput Drag Lock Buttons (296): <no items> libinput Horizontal Scroll Enabled (297): 1
Mouse and keyboard don't work when used at the same time
debian;i3;laptop
null
_unix.38498
If I change my system time on Debian which files would be modified?Would it be /etc/default/rcS?Also, is default time on Debian Dec 31 1969?
Debian and system clock change?
linux;debian;time
null
_softwareengineering.351465
I want to know how does a file system write to and read from a storage device.I think this is how it works:A file system doesn't access the storage device directly, but rather the storage device is presented (by the device driver of the storage device) to the file system as a (very large) byte array.For example, if the file system wants to access a hard disk, it will simply access the byte array representing the hard disk.This way a file system can work with any type of storage device (traditional hard disk, SSD, USB flash drive, etc.), and only the device driver for the storage device is changed.This image shows what I have just explained:Am I correct in my understanding?
Does a file system see the storage device as a (very large) byte array?
operating systems;file systems
null
_computergraphics.4272
I have a cylinder that has rectangular box regions to mark leakage problems. The location of a rectangular box is determined by its initial position in the longitudinal axis and its initial position in the circumferential axis in degree. The length and width (in degrees, from 0 to 360) of the boxes are also available.How can I convert this cylinder to a plane surface so that I can find the location of the rectangular boxes in the 2D plane?Here I have three rectangles on the surface.
Mapping of cylinder to 2D plane
computational geometry
You already have a 2D parametrisation, don't you? One of the dimensions is the longitudal axis (in mm?) and the other is the circumferential axis (in degrees). The only problem I see is when you have rectangles wrapping around the 0/360-degree boundary. One workaround for that would be to duplicate each rectangle (or just the ones on the boundary) so that you get one copy on each side of the boundary. Does that help? And if you need to have a distance, and not an angle, for the circular dimension, that is readily available as $l = r a \pi/180$, where $r$ is the radius and $a$ is the angle in degrees.
_softwareengineering.312468
Sorry in advance if this is a little confusing, it's difficult how to phrase this.I am currently using Spring MVC with some RESTful services mixed in for some AJAX client side logic. I am looking to move towards a more SOA style of coding our views. Since the MVC and the REST service would live in the same application, is there a need to use Spring RestTemplate in the code when I need to populate objects into a Model?Right now to GET User and display in the view, the Spring MVC talks to a DAO and then adds the User into Model. After reading a few things here on SO and Spring's Site it seems like RestTemplate could be used to get the data from a REST service and then insert into the model (if it came from a 3rd party).Is there any reason why code should (or shouldn't) move to using the RestTemplate for internal REST calls instead of just using the DOA and such? I assume going towards SOA means moving into this style, but it seems a little clunky for calling a service that is within the same application. But I also see the value add of having the service exist once and using it multiple times, updating in one spot instead of all over so any front end web code would be automatically updated with any changes to the service layer.Example:@RequestMapping(value={showUserTable},method={RequestMethod.GET})public String showUserTable(Model model){ List<User> users = User.getAll(); //DAO nonsense here, assume List exists model.addAttribute(users, users); return userTable; // returns a jsp simply looping through the list and displaying.}Is there any reason to go towards complicating these to use the internal REST Service in favor of the encapsulation I gain of SOA, or is there a cleaner way to consume these services?@RequestMapping(value={showUserTable},method={RequestMethod.GET})public String showUserTable(Model model){ List<User> users = restTemplate.getForObject(http://example.com/users, User.class); // or however I use restTemplates, havent done it yet so still fuzzy but shouldnt be too tricky. model.addAttribute(users, users); return userTable; // returns a jsp simply looping through the list and displaying.}
Spring Consuming Internal REST WS for MVC
java;spring;rest;spring mvc
null
_webmaster.9937
FB share currently pulls the page title tag and first body text by default.However our title tags are optimised for SEO and we want to customise what people see when the website is shared.I thought this might be a solution:<meta name=title content=title /><meta name=description content=description /><link rel=image_src href=thumbnail_image / >But have been told this will still conflict with the SEO? Can anyone help?
How do we customise FB share function without affecting SEO?
facebook;seo
null
_softwareengineering.305746
I wrote up a site using Mustache to template it. Right now though, the template is embedded in the page, which defeats the purpose of using the template since I'll need to copy it to any other pages that need it.I read that it's possible to store the template in an external page, then use Ajax to load the template when needed, but this is for a school project, and I'm not yet at the point where they want us using Ajax.Is it possible to have the template externalized without the use of Ajax?Ideally, I'd like to have the following setup:...PageUsingTemnplate.htmlAnotherPageUsingTemplate.html...Template.html
Can I use an external Mustache template without Ajax?
ajax;templates
You can use PartialsPartials begin with a greater than sign, like {{> box}}.For example, this template and partial:base.mustache:<h2>Names</h2>{{#names}} {{> user}}{{/names}}user.mustache:<strong>{{name}}</strong>Can be thought of as a single, expanded template:<h2>Names</h2>{{#names}} <strong>{{name}}</strong>{{/names}}
_softwareengineering.298710
I'm writing a PHP application where a block/module of domain logic is subject to frequent, significant changes over time.The complication is the application needs to be able to use not just the latest version of the module, but any version that it has previously used, so it can reproduce the results of data that that version would have made.I would use a facade and/or adapters or similar so the application's main code can switch between which versions of the module it uses without too much trouble.As for the module, I was planning to use namespacing for each major revision (where the domain logic produces different results); duplicating all the classes in that domain logic module. I.e. effectively copy-and-paste the entire thing, including classes within the module that haven't changed.This is a pungent code smell and I can't think of any way round it, let alone a simple way, given that the module may also undergo complete restructuring.Any ideas?
OO Pattern for making multiple versions of domain logic available to the client
versioning
null
_unix.328594
I was trying to develop a twitter streaming application on my AWS EC2 machine. The OS platform is Ubuntu 16.04.1 LTS and I have downgraded the PHP version to 5.6.28-1+deb.sury.org~xenial+1When I run the twitter streaming application on this server, I am getting the following errors.Warning: fsockopen(): Peer certificate CN=`stream.twitter.com' did not match expected CN=`199.16.156.217' in /var/www/html/myapp/streamer/twitterstreamer.php on line 620Warning: fsockopen(): Failed to enable crypto in /var/www/html/myapp/streamer/twitterstreamer.php on line 620 Warning: fsockopen(): unable to connect to ssl://199.16.156.217:443 (Unknown error) in /var/www/html/myapp/streamer/twitterstreamer.php on line 620The same code is running without any issues in another two machines (one is AWS EC2 and the another is a godaddy server).All the ports in the current EC2 machine is open now and the SSL version is OpenSSL/1.0.2g the openssl section is having the following value.Can someone help me to find where the exact issue is ?
openssl issue in Ubuntu 16.04.1 LTS and php 5.6.28-1+deb.sury.org~xenial+1
ubuntu;php;openssl
null
_cs.19663
Given this set of question-answer pairs, what program will derive the underlying algorithm and provide the correct answer for any question of the same format.Question-Answer Pairs (training set):B:BABA:BBBB:BAABAA:BABBAB:BBABBA:BBBBBB:BAAABAAA:BAABBAAB:BABAThose familiar with binary may notice that the training set is binary numbers with A and B substituted for 0 and 1. The answer to each question is the next binary number (using A and B). After processing the training set, the program should be able to answer questions such as the following using the algorithm it derived:BABA:?BABB:?BBBBAAA:?BAABBAAABBABA:?Constraints:The program must derive the counting algorithm only by manipulating the data given in the training set. It must not use hard coded knowledge of binary counting.Many algorithms may produce the correct answers. Therefore, the simplest algorithm is preferred. The program should assume that each answer is a transformation of the question.All questions will be in the binary format seen above, but they may be of arbitrary size.Can any existing machine learning programs/algorithms solve this? If so, how?If you believe this is unsolvable, please explain why.This update contains background to the question, explanation of the problem space, a new constraint, a proposed solution, and further questions.This problem is relevant to general machine learning where the machine must learn by observation and feedback the algorithms that govern the world around it.Based on Kolmogorov complexity, there is at least one program that can produce the correct mappings:if B, then BAif BA, then BB(etc. for all pairs in training set)This will work for every pair in the training set and nothing else. This will be the shortest program if the training set is completely random. The good news is that this is an upper bound. For any training set that is not random, there will be a smaller program that will work. Also, the number of programs smaller than upper bound is finite. A unfortunate result of Kolmogorov complexity is that it cannot be calculated. This is due to the halting problem. We can't know if any program will stop until it does.If the question is Write pi, then the program that produces the correct answer would never halt because pi has infinite digits. An answer infinitely long is never desirable so I think the best way to deal with this is to put an arbitrary limit on the length of the answer.With that additional constraint, here is an (inefficient) program that will generate a correct solution program shorter than the upper bound if one exists. (sorry of this is confusing, but these steps outline a program that generates programs that implement an algorithm to map questions to answers in a training set):Create the upper bound program. One that maps each input in the training set directly to its output.Generate every possible program that is shorter than the upper bound and list them from shortest to longest.Starting with the shortest program, run the first step of every program. Stop when a correct program is found.Eliminate programs that stop without a correct answer or produce an answer longer than the arbitrary limit.Repeat steps 3-5 running the second step, third step, etc. of the programs.This program has the following benefits:It limits the number of programs to those smaller than the upper bound program.It avoids the halting problem byincorporating an arbitrary limit to the length of the answer and executing step x in all programs before moving on to step x+1 so that the solution will be found before looping infinity.The main disadvantage is that it is terribly slow. It takes millions of years to crack a 128 bit password and I think this program could have comparable performance.Now, the questions:Do you see any significant flaws in this solution?Can this program's performance be improved in any significant waywithout introducing onerous constraints?
What program will derive the underlying algorithm in these question-answer pairs (updated)?
machine learning;artificial intelligence
The same answers you got the last time you asked this question apply. There are infinitely many possible mappings $\{A,B\}^* \to \{A,B\}^*$ and none is preferable to any other.Let's try to formalize your problem more clearly. I suspect you want an algorithm to solve the following problem:Given a training set as input (i.e., a set of mappings $x \mapsto y$, where $x,y$ are strings), output the shortest algorithm $A$ with the property that $A(x)=y$ for every $x,y$ in the training set.The bad news is that this problem is not solvable. In particular, the problem is undecidable, so you should not expect any general algorithm to solve this problem. To do better, you will need some structure on the set of hypotheses (e.g., a distribution on possible mappings or something like that).Why is this undecidable? Because it is basically the problem of computing the Kolmogorov complexity of the training set, and computing the Kolmogorov complexity is known to be undecidable.You might be wondering how standard methods for machine learning get around this barrier. The answer is that they avoid this barrier by changing the problem statement. Machine learning methods generally involve a more restricted space of hypotheses (instead of allowing all possible algorithms, we only consider a restricted subset, such as those that are linear or that have some other nice properties) or else involve specifying a probability distribution on the set of possible mappings. I recommend you spend some time studying machine learning.What is the context and motivation for your question? What's the specific real-world situation where you encountered this? To make progress I suspect you'll need to step back and look at the real requirements from your application, and be open to other ways to meet your needs.
_unix.228915
I need to find and replace either one or two numerical characters in strings in a file. The strings are IP addresses of the form: 10.xx.y.z Where xx can be one or two characters. I want to replace the xx with the single character 0, so I have10.0.y.z preserving the values of y and z. The string may appear multiple times in the file. What is the sed invocation to do this?
Replace arbitrary characters in the middle of an IP address string with sed
text processing;sed
null
_reverseengineering.9402
I was trying to reverse engineer an Android Malware sample and I find the following sample when decompiling the jar file I obtained by running dex2jar. if (i >= paramBundle.length()) { ((TextView)findViewById(2131034112)).setText(((StringBuilder)localObject).toString()); return; }How can I find the string that 2131034112 refers to?
Android malware reversing : constant values
android
null
_cstheory.1948
I'm interested in an explicit Boolean function $f \colon \\{0,1\\}^n \rightarrow \\{0,1\\}$ with the following property: if $f$ is constant on some affine subspace of $\\{0,1\\}^n$, then the dimension of this subspace is $o(n)$. It is not difficult to show that a symmetric function does not satisfy this propertyby considering a subspace $A=\\{x \in \\{0,1\\}^n \mid x_1 \oplus x_2=1, x_3 \oplus x_4=1, \dots, x_{n-1} \oplus x_n=1\\}$. Any $x \in A$ has exactly $n/2$ $1$'s and hence $f$ is constant the subspace $A$ of dimension $n/2$.Cross-post: https://mathoverflow.net/questions/41129/a-boolean-function-that-is-not-constant-on-affine-subspaces-of-large-enough-dimen
A Boolean function that is not constant on affine subspaces of large enough dimension
cc.complexity theory;circuit complexity;derandomization;linear algebra
The objects you are searching for are called seedless affine dispersers with one output bit. More generally, a seedless disperser with one output bit for a family $\mathcal{F}$ of subsets of $\{0,1\}^n$ is a function $f : \{0,1\}^n \to \{0,1\}$ such that on any subset $S \in \mathcal{F}$, the function $f$ is not constant. Here, you are interested in $\mathcal{F}$ being the family of affine subspacesBen-Sasson and Kopparty in Affine Dispersers from Subspace Polynomials explicitly construct seedless affine dispersers for subspaces of dimension at least $6n^{4/5}$. The full details of the disperser are a bit too complicated to describe here. A simpler case also discussed in the paper is when we want an affine disperser for subspaces of dimension $2n/5+10$. Then, their construction views ${\mathbb{F}}_2^n$ as ${\mathbb{F}}_{2^n}$ and specifies the disperser to be $f(x) = Tr(x^7)$, where $Tr: {\mathbb{F}}_{2^n} \to {\mathbb{F}}_2$ denotes the trace map: $Tr(x) = \sum_{i=0}^{n-1} x^{2^i}$. A key property of the trace map is that $Tr(x+y) = Tr(x) + Tr(y)$.
_unix.166502
Wow, I could not think of a good way to title this question. Basically I have a file called attendance with data like this:11/06/2014 101.11.001.01 FirstName LastName11/06/2014 101.11.001.01 FirstName LastName11/06/2014 101.11.001.01 FirstName LastName11/06/2014 101.11.001.01 FirstName LastNameBasically it's the date, IP address, First name, and Last name. The above is how it is formatted in the attendance file. I have created an html page with text boxes and a submit button where a user can either: A.) Enter a FN/LN and receive a list of dates that person logged in, OR B.) Type in a date and receive a list of users who logged in on that date. I'm getting the results I want, but the result of the grep displayed in the browser is all on one line, like this:11/06/2014 101.11.001.01 FirstName LastName 11/06/2014 101.11.001.01 FirstName LastName 11/06/2014 101.11.001.01 FirstName LastName 11/06/2014 101.11.001.01 FirstName LastNameObviously this is sub-optimal. I need the grep results to appear on separate lines. Below is my .cgi file. getvars is just a script the professor made for converting variable types. Also, I'm cutting corners by only grepping last name, because nobody has the same last name:#!/bin/bash. ~/bin/getvarsif [ ! -z $LN ]; thencat attendance | grep $LNelif [ ! -z $DATE ]; thencat attendance | grep $DATEelse echo No Records FoundfiI've tried to be as concise as possible and I apologize is anything doesn't make sense. My only question is: How do I get the grep results on separate lines?
How to format grep results?
bash;grep
Presumably, your browser is interpreting whatever file you're pointing it to as HTML. In HTML a newline is not \n but the <br> tag, so you would need to add that. For example:#!/usr/bin/env bash. ~/bin/getvarsif [ ! -z $LN ]; then grep $LN attendance | sed 's/$/<br>/'elif [ ! -z $DATE ]; then grep $DATE attendance | sed 's/$/<br>/'else echo No Records FoundfiOn my Debian, firefox interprets \n as line breaks if the file has no .html extension (I tried with no extension and .txt) so that might be a workaround but I have no idea how portable that would be. A better alternative would be to make it a proper HTML page, use <pre> tags and replace all < and > with their HTML equivalents:#!/usr/bin/env bash. ~/bin/getvarsecho <HTML><BODY><pre>if [ ! -z $LN ]; then grep $LN attendance | sed 's/>/\&gt;/g;s/</\&lt;/g;'elif [ ! -z $DATE ]; then grep $DATE attendance | sed 's/>/\&gt;/g;s/</\&lt;/g;'else echo No Records Foundfiecho </pre></BODY></HTML>
_cs.74569
My Computer Architecture gives me this example but I cant for the life of me understand how it solved the problem.How many bubbles must be placed between the pair of SRC instructions in the presence and in the absence of data forwarding to resolve dependence?ld r2, (r4)add r6,r4,r2SolutionStaller = ldStallee = addHazard Register = r2Bubbles without/with forwarding = 3/1How does it know there is a stall?How does it know the hazard register?How did it calculate the number of bubbles?I really need help understanding this concept to do my homework. Much appreciated.
Need Help Understanding Pipeline Bubbles Problem
computer architecture
null
_unix.259124
This happens to be a new problem because I was able to run MATLAB on the shell until today. I didn't install or update it or anything of that sort, but now I am unable run matlab in the sell. It tells me:user~ $ matlabbash: matlab: command not foundthis seems weird to me.The solution that I have tried is adding the MATLAB binaries to path. So I did:PATH=$PATH:/Applications/MATLAB_R2015a.appwhere /Applications/MATLAB_R2015a.app is the path returned by matlabroot matlab command from the GUI. I tried this but as a no surprise, it didn't work, I still can't add the MATLAB binaries to my path. How does one find the MATLAB binaries location in my system? Even if I find them, is it advised to just manually add it to my path? I also restarted my computer (OS X) but that did not work either. Any advice how to solve the issue? Re-install MATLAB?
Why can't my Unix terminal not find my matlab binaries and making Unix find them again?
shell;matlab
null
_codereview.121633
ContextI have a bunch of data points that look roughly like this:(defn rand-key [] (into [] (repeatedly 3 #(- (rand-int 19) 9))))(defn rand-val [] (rand-nth [:foo :bar :baz :qux]))(def data (into {} (repeatedly 10 (fn [] [(rand-key) (rand-val)]))))Obviously the actual coordinates would have a much greater range, the actual values would hold some sort of information, and the actual number of data points would be far greater, but you get the idea.This data structure is going to be evolving over time (so I'll probably store it in an atom or something like that), and as it evolves, I want to be able to quickly find the bounding box for the points it contains in its current state.The easiest way to do that for an n-dimensional dataset is to keep n independent sets of its keys, each one sorted in one dimension. Since I can't be bothered to write a proper comparator in Clojure, though, I'm going to replace each of those sets with a sorted map from a coordinate in a particular dimension to the number of data points that have that coordinate in that dimension:(def keymaps (mapv (fn [dimension] (->> (keys data) (map #(get % dimension)) frequencies (into (sorted-map)))) (range 3)))With this, it's trivial to find the bounding box of the dataset:(def bounds (mapv (juxt (comp key first) (comp key first rseq)) keymaps))ProblemNow, no matter what I do, I have to update my data and my keymaps together. Maybe, like I suggested above, I have an atom that stores some current state, and in that case that atom would look like this:(def state (atom {:data data :keymaps keymaps}))Any time I update state, I can't just use the built-in Clojure functions to update the :data because that would cause the :keymaps to become outdated. I could write my own functions to replace assoc and dissoc that would keep the two in sync, but then I wouldn't be able to make use of all the great higher-level functions (such as merge) that are built on top of the original, polymorphic assoc and dissoc.SolutionSo I decided to take the most painful approach possible: build a custom map type that allows efficient bounding box queries using the scheme detailed above. First things first, some protocols:(defprotocol Space (dimension [this]))(defprotocol Bounded (bounds [this]))Since I need to store extra data alongside an existing map, I can't just use extend-type on the PersistentHashMap class. No, I need a far more powerful tool: deftype! I'll have one field for the underlying data map and another for the vector of keymaps.In most cases, I could get away with just implementing the map abstraction directly, but I don't want to tie myself to a particular implementation for the wrapped map. What if later I decide that I want to use a quadtree or an octree for the underlying map, to allow for efficient queries of subspaces? To prevent myself from having to extend more protocols to my bounded map type than I need to, I'll just provide a way to get the wrapped map and query that:(defprotocol Wrapper (wrapped [this]))And here's the deftype itself. Prepare for boilerplate:(import (clojure.lang Associative Counted ILookup IPersistentCollection IPersistentMap Seqable))(declare ->BoundedMap)(deftype BoundedMap [m keymaps] Seqable (seq [_] (seq m)) IPersistentCollection (cons [this [k v]] (assoc this k v)) (empty [_] (->BoundedMap (empty m) (mapv empty keymaps))) (equiv [_ x] (= m x)) ILookup (valAt [_ k] (get m k)) (valAt [_ k not-found] (get m k not-found)) Associative (containsKey [_ k] (contains? m k)) (entryAt [_ k] (find m k)) Counted (count [_] (count m)) IPersistentMap (assoc [_ k v] (->BoundedMap (assoc m k v) (if (contains? m k) keymaps (mapv #(update %1 %2 (fnil inc 0)) keymaps k)))) (without [_ k] (->BoundedMap (dissoc m k) (if (contains? m k) (mapv #(if (< 1 (get %1 %2)) (update %1 %2 dec) (dissoc %1 %2)) keymaps k) keymaps))) Wrapper (wrapped [_] m) Space (dimension [_] (count keymaps)) Bounded (bounds [_] (mapv (fn [keymap] (mapv #(key (first (% keymap))) [seq rseq])) keymaps)))And of course, what data structure would be complete without a nifty little constructor function?(defn bounded-map [dimension m] (->> (keys m) (iterate (partial map rest)) (take dimension) (mapv #(into (sorted-map) (frequencies (map first %)))) (->BoundedMap m)))Now I can define my atom like this instead of what I had before:(def state (atom (bounded-map 3 data)))Pretty much all of the Clojure tools for maps will work properly, I can get bounding boxes at my leisure, and if I ever switch to a more featured map implementation for the data itself, I can always compose those extra functions with wrapped.QuestionsIs this the right approach?Is there a way to make = work properly without implementing java.util.Map (yuck)?Can this code be improved in any other way?
Tracking the bounding box of a map
clojure;coordinate system
null
_webapps.3120
Is it possible to change your username on Delicious? I have an old account with all my bookmarks and I would like to change my username.Is the only solution exporting your existing bookmarks from your old account and importing them in your new account? Anyone has experience with this?
Changing your username on Delicious
delicious;username
You can't, but you can create a new account and import your exported bookmarks from your old account.From the Delicious FAQ:How do I change my username? There's no easy way to do this right now, but you can use the export and import features in your settings to change to a new account while preserving your current bookmarks. First, visit your Settings (accessible from the top right of every page on Delicious) and select export/backup from that page. Follow the directions to export your bookmarks. Then, register or log into your new account, go to settings, and select import/upload. After importing your bookmarks into your new account, you can log out of it and log back into your old account to delete that one. To do this, go to Settings and choose delete account.
_codereview.103820
How can I improve this code?public virtual HttpResponseMessage Get(int pageNo, int pageSize){ pageNo = pageNo > 0 ? pageNo - 1 : 0; pageSize = pageSize > 0 ? pageSize : 0; int total = repository.Table.Count(); int pageCount = total > 0 ? (int)Math.Ceiling(total / (double)pageSize) : 0; var entity = repository.Table.OrderBy(c => c.ID).Skip(pageNo * pageSize).Take(pageSize); if (entity.Count() == 0 || entity == null) { var message = string.Format({0}: No content, GenericTypeName); return ErrorMsg(HttpStatusCode.NotFound, message); } var response = Request.CreateResponse(HttpStatusCode.OK, entity); response.Headers.Add(X-Paging-PageNo, (pageNo + 1).ToString()); response.Headers.Add(X-Paging-PageSize, pageSize.ToString()); response.Headers.Add(X-Paging-PageCount, pageCount.ToString()); response.Headers.Add(X-Paging-TotalRecordCount, total.ToString()); return response;}
WebApi Get with paging
c#;pagination;asp.net web api
Let's start with the BUG. if (entity.Count() == 0 || entity == null)If entity is null, then you'll get a NullReferenceException when Count is called, so there's currently no possible way the second half of this statement will ever be called. I think you meant to do this. if (entity == null || entity.Count == 0)Which works, but isn't great. I would prefer not Any here. I find it's good practice to get into the habit of using Any. It's just more readable IMO. if ( entity == null || !entity.Any() )To clarify. Any() returns as soon it finds an element, whereas Count has to iterate over the entire Enumerable before it returns. Note that this isn't true for List. Any() still returns early when called on a List, but so will Count because a list keeps track of how many items it has as they're added/removed. Enumerables do not already know how big they are. They must be iterated to get a count. Now let's back up a bit and stop your Linq from scrolling off the screen. var entity = repository.Table .OrderBy(c => c.ID) .Skip(pageNo * pageSize) .Take(pageSize);Maybe it's because I grew up with a language where everything is passed ByRef by default (.Net passes ByVal by default), but I don't like assigning values to arguments. public virtual HttpResponseMessage Get(int pageNo, int pageSize){ pageNo = pageNo > 0 ? pageNo - 1 : 0; pageSize = pageSize > 0 ? pageSize : 0;I'd introduce another variable, but I'm having a hard time thinking of good names at the moment. I'd also consider extracting the logic into private methods to clarify the intent. It doesn't matter that you're unlikely to ever call them from anywhere else, some well named methods can really clarify what code is doing. You can always look inside them if you're interested in the implementation, but at this level, I don't care how we're calculating these numbers, I just care that we are. public virtual HttpResponseMessage Get(int pageNo, int pageSize){ pageNo = NormalizePageNo(pageNo); pageSize = NormalizePageSize(PageSize);Here's another great opportunity to give logic a name. int pageCount = total > 0 ? (int)Math.Ceiling(total / (double)pageSize) : 0;Mmmm hmmm... Now what is that doing exactly? If the total number of records is greater than zero, Then return the percentage of total divided by page size, rounded up Else return Zero. Again, these are implementation details. At the current level of abstraction, we just want to knowint pageCount = CalculatePageCount(total, pageSize);
_codereview.80515
I've just started delving into JavaFX, and the following is essentially my Hello World. Although it's simple, I question the code formatting and wonder if I'm breaking any conventions, especially if explicitly concerning the library.I also find myself concerned with what best promotes readability. Unfamiliarity brought many an alteration between styles. e.g. for statements, whether it is preferable to instantiate, modify and add an object all at once or simply pairing similar things together and modifying them wherever necessary and adding them at the end -- my final code here is an amalgamation of both styles.This last bit may be delving a bit into SO/Programmers territory, but I'm curious. I found myself using anonymous inner classes as it made methods easily transportable; I've hitherto not used it more than once in a program, is this bad form? If so, why?import javafx.application.Application;import javafx.beans.value.ObservableValue;import javafx.scene.Group;import javafx.scene.Scene;import javafx.scene.control.Slider;import javafx.scene.paint.Color;import javafx.scene.shape.Line;import javafx.scene.shape.StrokeLineCap;import javafx.scene.text.Text;import javafx.stage.Stage;public class DrawingLines extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { primaryStage.setTitle(Legato's Lines); Group root = new Group(); Scene scene = new Scene(root, 300, 150, Color.GRAY); Line redLine = new Line(10, 10, 200, 10) { { setStroke(Color.RED); setStrokeWidth(3); getStrokeDashArray().addAll(10d, 5d, 15d, 5d, 20d); setStrokeDashOffset(0); } }; Line whiteLine = new Line(10, 30, 200, 30) { { setStroke(Color.WHITE); setStrokeLineCap(StrokeLineCap.ROUND); setStrokeWidth(10); } }; Line blueLine = new Line(10, 50, 200, 50) { { setStroke(Color.BLUE); setStrokeLineCap(StrokeLineCap.BUTT); setStrokeWidth(5); } }; Slider slider = new Slider(0, 100, 0) { { setLayoutX(10); setLayoutY(95); } }; Text offsetText = new Text(Stroke Dash Offset: 0) { { setX(10); setY(80); setStroke(Color.WHITE); } }; slider.valueProperty().addListener( (ov, curVal, newVal) -> offsetText.setText( Stroke Dash Offset: + Math.round(slider.getValue())) ); redLine.strokeDashOffsetProperty().bind(slider.valueProperty()); root.getChildren().add(redLine); root.getChildren().add(whiteLine); root.getChildren().add(blueLine); root.getChildren().add(slider); root.getChildren().add(offsetText); primaryStage.setScene(scene); primaryStage.show(); }}
Whose line is it anyway?
java;beginner;gui;javafx
It's hard to pick on such simple and straightforward code.The one thing that stands out to me is the distance between the line where you declare the root variable, and the lines where you actually use it.Let me quote an interesting paragraph from Code Complete:The code between references to a variable is a window of vulnerability. In the window, new code might be added, inadvertently altering the variable, or someone reading the code might forget the value the variable is supposed to contain. Its always a good idea to localize references to variables by keeping them close together.Indicators of this window of vulnerability are the measurements of variable span and live time:Variable span: the number of lines between references to a variable. When a variable is referenced multiple times, the average span is computed by averaging all the individual spans. The smaller the better.Variable live time: the total number of statements over which a variable is live. This is a count of lines between the first reference and the last. Again, the smaller the better.By declaring root and scene at the top and using only at the button,you have a large window of vulnerability,and high average spans and life times.You can reduce these negative indicators by pushing these declarations down in your method to where the variables are actually used.
_codereview.163586
The problem statement is as follows:The four adjacent digits in the 1000-digit number that have the greatest product are 9 9 8 9 = 5832.73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?My code below solves the problem.I know this enters into the realm of preference but is it taboo to merge the 100 digit number onto a single line as I initially did but commented out, or is the method utilizing StringBuilder for readability better?public class Program{ public static void Main(string[] args) { //string numbers = 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450; string numbers = Get100DigitNumber(); Console.WriteLine(MaxProductNumericStringOfLength(numbers,13)); } static long ProductOfNumericString(string number) { long product = 1; for (int digit = 0; digit<number.Length ; digit++) { product *= int.Parse(number[digit].ToString()); } return product; } static long MaxProductNumericStringOfLength(string numberString, int length) { long maxSubstring=0; long possibleMaxSubstring; for (int position = 0; position < numberString.Length-length ; position++) { possibleMaxSubstring = ProductOfNumericString(numberString.Substring(position,length)); if (possibleMaxSubstring > maxSubstring) maxSubstring=possibleMaxSubstring; } return maxSubstring; } static string Get100DigitNumber() { StringBuilder sb = new StringBuilder(); sb.Append(73167176531330624919225119674426574742355349194934); sb.Append(96983520312774506326239578318016984801869478851843); sb.Append(85861560789112949495459501737958331952853208805511); sb.Append(12540698747158523863050715693290963295227443043557); sb.Append(66896648950445244523161731856403098711121722383113); sb.Append(62229893423380308135336276614282806444486645238749); sb.Append(30358907296290491560440772390713810515859307960866); sb.Append(70172427121883998797908792274921901699720888093776); sb.Append(65727333001053367881220235421809751254540594752243); sb.Append(52584907711670556013604839586446706324415722155397); sb.Append(53697817977846174064955149290862569321978468622482); sb.Append(83972241375657056057490261407972968652414535100474); sb.Append(82166370484403199890008895243450658541227588666881); sb.Append(16427171479924442928230863465674813919123162824586); sb.Append(17866458359124566529476545682848912883142607690042); sb.Append(24219022671055626321111109370544217506941658960408); sb.Append(07198403850962455444362981230987879927244284909188); sb.Append(84580156166097919133875499200524063689912560717606); sb.Append(05886116467109405077541002256983155200055935729725); sb.Append(71636269561882670428252483600823257530420752963450); return sb.ToString(); }}
Project Euler Problem 8: Largest product in a series
c#;beginner;programming challenge
null
_webapps.107754
It seems that if you insert a table into a document, there is always a new line after it. This can be quite frustrating if the table is tall, as it keeps adding a blank page that is not required beneath the table.Is there some special way of removing that line?
Line After Table
google documents
null
_webmaster.59146
I have paging URLs below and the page uses AJAX to do paging. Do I need to add _escaped_fragment_= to the URL below or are those URLs fine?<link rel=prev href=http://example.com/youth-basketball-tournaments/kansas?page=4 /><link rel=prev href=http://example.com/youth-basketball-tournaments/kansas?page=5 />
Paging next/previous links with Google escape fragment
seo;google;ajax;pagination
null
_cs.57515
I'm trying to figure out how to compute an amortized complexity/ or complexity of this algorithm. We have a Graph which is oriented. And we are going to run Dijkstra's algorithm for finding a shortest path between vertices, but it has to start only in those vertices, which has no input edge going to this vertex (the vertices with red color).So Dijkstra would be runned only from red vertices. If we run Dijkstra on all vertices, we could assume that complexity is |V|*Dijkstra but in this case we do not need such big complexity. As is one Dijkstra big, another Dijkstra from another vertex would be runned on less vertices. The more Dijkstras we run, the less vertices could be visited.Dijkstra from all vertices should have |V|(|E|+|V|*log|V|) complexity. This complexity should be much lower but I can't figure out where to compute.
How to compute amortized complexity of n runs of Dijkstra's algorithm?
graph theory;graphs;time complexity;amortized analysis
null
_codereview.41748
This one time pad encryption program I have written (basically just an XOR encryption program) seems to be working fine, compiling nicely (gcc -o ./OTP.c), and doing what it's supposed to. However I would like to improve it as much as possible which is why I am posting this.I am particularly insecure about the memory allocation. Any suggestions regarding improvements are more than welcome!The code in its entirety is found below and can also be found on Github: PrivacyProject/OTP-Encryption.#include <stdio.h>#include <stdlib.h>#include <sys/stat.h>#include <sys/mman.h>int main(int argc, char **argv){struct stat statbuf;struct stat keybuf;char buffer [20];int key;int data;int output;int count;char ans;int * buf;FILE * keyfile;FILE * sourcefile;FILE * destfile;if(geteuid() !=0){printf(Root access is required to run this program\n\n);exit(0);}if(argc<4){printf(\n);printf( OTP 1.0 \n\n);printf( This program encrypts a file using a random key\n);printf( and generates an output file with the resulting\n);printf( cipher. Decryption is achieved by running the\n);printf( output file as source file with the same key.\n\n);printf( WARNING: The security of the encryption provided\n);printf( by this program is entirely dependent on the key\n);printf( file. The keyfile should meet the requirements\n);printf( below:\n);printf( - Be of the same size or larger than the\n);printf( source file.\n);printf( - Be completely random, preferably generated by \n);printf( a Hardware Random Number Generator.\n); printf( - NEVER be reused!\n\n);printf( The author takes no responsibility for use of\n);printf( this program. Available under GNU General Public\n);printf( Licence v.2\n\n);printf( USAGE: OTP <source file> <output file> <keyfile>\n\n);return (0);}/* Check number of arguments. */if(argc>4){printf(Too many arguments.\n);printf(USAGE: OTP <source file> <output file> <keyfile>\n);exit(1);}/* Allocate memory required by processes */buf = (int*) malloc (sizeof(int));if (buf == NULL){perror(Error);exit(1);}/* Lock down pages mapped to processes */printf(Locking down processes...\n\n);if(mlockall (MCL_CURRENT | MCL_FUTURE) < 0){perror(mlockall);exit (1);}/* Check if sourcefile can be opened. */if((sourcefile = fopen(argv[1], rb))== NULL){printf(Can't open source file\n);perror(Error);printf(USAGE: OTP <source file> <output file> <keyfile>\n);exit (1);}/* Get size of sourcefile */fstat(fileno(sourcefile), &statbuf); /* Check if keyfile can be opened. */if((keyfile = fopen(argv[3], rb))== NULL){printf(Can't open keyfile.\n);perror(Error);printf(USAGE: OTP <source file> <output file> <keyfile>\n);exit(1);} /* Get size of keyfile */fstat(fileno(keyfile), &keybuf);/* Check if keyfile is the same size as, or bigger than the sourcefile */if((keybuf.st_size) < (statbuf.st_size)){printf(Source file is larger than keyfile.\n);printf(This significantly reduces cryptographic strength.\n);printf(Do you wish to continue? (Y/N)\n);fgets(buffer, 20, stdin);sscanf(buffer, %c, &ans);if(ans == 'n' || ans == 'N'){exit (1);}if(ans == 'y' || ans == 'Y'){ printf(Proceeding with Encryption/Decryption.\n); }else{printf(No option selected. Exiting...\n);exit (1);}} /* Check if destfile can be opened. */if((destfile = fopen(argv[2], wb))== NULL){printf(Can't open output file.\n);perror(Error);exit(1); } /* Encrypt/Decrypt and write to output file. */while(count < (statbuf.st_size)){key=fgetc(keyfile);data=fgetc(sourcefile);output=(key^data);fputc(output,destfile);count++;}/* Close files. */fclose(keyfile);fclose(sourcefile);fclose(destfile);printf(Encryption/Decryption Complete.\n\n);/* delete Source file option. */printf(Do you wish to delete the source file? (Y/N)\n);fgets(buffer, 20, stdin);sscanf(buffer, %c, &ans);if(ans == 'y' || ans == 'Y'){ if ( remove(argv[1]) == 0) { printf(File deleted successfully.\n); } else { printf(Unable to delete the file.\n); perror(Error); exit(1); }}/* delete keyfile option. */printf(Do you wish to delete the keyfile? (Y/N)\n);fgets(buffer, 20, stdin);sscanf(buffer, %c, &ans);if(ans == 'y' || ans == 'Y'){ if ( remove(argv[3]) == 0) { printf(File deleted successfully.\n); } else { printf(Unable to delete the file.\n); perror(Error); exit(1); }}/* cleanup */printf(Releasing memory.\n);free (buf);return(0);}
Small one time pad encryption program
c;beginner;memory management;cryptography
Things you did well on:You make good use of comments.You try to make the user experience as smooth as possible, printing out a lot of useful information.Things you could improve:A few notes that others haven't covered:Running your program through Valgrind, I didn't see any memory leaks besides where your if conditions fail and you exit main(). if((sourcefile = fopen(argv[1], rb)) == NULL) { printf(Can't open source file\n); perror(Error); printf(USAGE: OTP <source file> <output file> <keyfile>\n); exit(1); }The majority of modern (and all major) operating systems will free memory not freed by the program when it ends. However, relying on this is bad practice and it is better to free it explicitly. Relying on the operating system also makes the code less portable.if((sourcefile = fopen(argv[1], rb)) == NULL){ puts(Can't open source file.); perror(Error); free(buf) return -5;}Your encryption method is secure, banking on the fact that the all of the conditions for your program are met.But I always think worst case scenario, where the user doesn't follow your program's optimal conditions. If you want to use secure encryption techniques, you can benefit from a cryptography expert's work. This means you will have to implement an external library (such as OpenSSL). Here is an example if you want to go that route.You have an implicit declaration of function geteuid(), which is invalid in the C99 standard.#include <unistd.h>fopen(), a widely-used file I/O functions that you are using, got a facelift in C11. It now supports a new exclusive create-and-open mode (...x). The new mode behaves like O_CREAT|O_EXCL in POSIX and is commonly used for lock files. The ...x family of modes includes the following options:wx create text file for writing with exclusive access.wbx create binary file for writing with exclusive access.w+x create text file for update with exclusive access.w+bx or wb+x create binary file for update with exclusive access.Opening a file with any of the exclusive modes above fails if the file already exists or cannot be created. Otherwise, the file is created with exclusive (non-shared) access. Additionally, a safer version of fopen() called fopen_s() is also available. That is what I would use in your code if I were you, but I'll leave that up for you to decide and change.You can cut down on a few lines of code by initializing similar types on one line. This will keep you more organized. struct stat statbuf; struct stat keybuf; char buffer [20]; int key; int data; int output; int count; char ans; int * buf; FILE * keyfile; FILE * sourcefile; FILE * destfile;Also, initialize your int values when you declare them. Pointer values will default to NULL.struct stat statbuf, keybuf;char buffer [20];char ans;int key = 0, data = 0, output = 0, count = 0;int *buf;FILE *keyfile, *sourcefile, *destfile;You check if argc is greater or less than 4.if(argc<4){ // huge printf() block return (0);}// ...if(argc>4){ printf(Too many arguments.\n); printf(USAGE: OTP <source file> <output file> <keyfile>\n); exit(1);}Just check for the inequality of 4 and print the block statement.if (argc != 4){ // printf() block return 0;}I would have extracted all of the encryption to one method and all of the file validation in another method, but I'll leave that for you to implement. You can remove the != 0 for maximum C-ness, but this is to your discretion and tastes. if(geteuid() != 0)It is more common to return 0; rather than to exit(0). Both will call the registered atexit handlers and will cause program termination though. You have both spread throughout your code. Choose one to be consistent. Also, you should return different values for different errors, so you can pinpoint where something goes wrong in the future.Use puts() instead of printf() with a bunch of '\n' characters. printf( and generates an output file with the resulting\n);puts( and generates an output file with the resulting);You compare some pointers to NULL in some test conditions. if (buf == NULL)You can simplify them.if (!buf)Your perror() messages could be more descriptive.You compare some input to the uppercase and lowercase versions of characters. if (ans == 'n' || ans == 'N')You could use the tolower() function in <ctype.h> to simplify it a bit.if (tolower(ans) == 'n')Already mentioned, but please indent your code properly. It will make your code a lot easier to read and maintain. You can find IDE's out there that will do it automatically for you when told.Final code (with my changes implemented):#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <ctype.h>#include <sys/stat.h>#include <sys/mman.h>int main(int argc, char **argv){ struct stat statbuf, keybuf; char buffer[20]; char ans; int key = 0, data = 0, output = 0, count = 0; int *buf; FILE *keyfile, *sourcefile, *destfile; if(geteuid() != 0) { puts(Root access is required to run this program.); return -1; } if(argc != 4) { puts(OTP 1.0 \n); puts(This program encrypts a file using a random key); puts(and generates an output file with the resulting); puts(cipher. Decryption is achieved by running the); puts(output file as source file with the same key.\n); puts(WARNING: The security of the encryption provided); puts(by this program is entirely dependent on the key); puts(file. The keyfile should meet the requirements); puts(below:); puts( - Be of the same size or larger than the); puts( source file.); puts( - Be completely random, preferably generated by); puts( a Hardware Random Number Generator.); puts( - NEVER be reused!\n); puts(The author takes no responsibility for use of); puts(this program. Available under GNU General Public); puts(Licence v.2\n); puts(usage: OTP <source file> <output file> <keyfile>); return 0; } /* Allocate memory required by processes */ buf = (int*) malloc (sizeof(int)); if (!buf) { perror(Error); free(buf); return -3; } /* Lock down pages mapped to processes */ puts(Locking down processes...); if(mlockall (MCL_CURRENT | MCL_FUTURE) < 0) { perror(mlockall); free(buf); return -4; } /* Check if sourcefile can be opened. */ if((sourcefile = fopen(argv[1], rb)) == NULL) { puts(Can't open source file.); perror(Error); free(buf); return -5; } /* Get size of sourcefile */ fstat(fileno(sourcefile), &statbuf); /* Check if keyfile can be opened. */ if((keyfile = fopen(argv[3], rb)) == NULL) { puts(Can't open keyfile.); perror(Error); free(buf); return -6; } /* Get size of keyfile */ fstat(fileno(keyfile), &keybuf); /* Check if keyfile is the same size as, or bigger than the sourcefile */ if((keybuf.st_size) < (statbuf.st_size)) { puts(Source file is larger than keyfile.); puts(This significantly reduces cryptographic strength.); puts(Do you wish to continue? (Y/N)); fgets(buffer, 20, stdin); sscanf(buffer, %c, &ans); if (tolower(ans) == 'n') { free(buf); return 0; } else if (tolower(ans) == 'y') puts(Proceeding with Encryption/Decryption.); else { puts(No option selected. Exiting...); free(buf); return -7; } } /* Check if destfile can be opened. */ if ((destfile = fopen(argv[2], wb)) == NULL) { puts(Can't open output file.); perror(Error); free(buf); return -8; } /* Encrypt/Decrypt and write to output file. */ while (count < (statbuf.st_size)) { key=fgetc(keyfile); data=fgetc(sourcefile); output=(key^data); fputc(output,destfile); count++; } /* Close files. */ fclose(keyfile); fclose(sourcefile); fclose(destfile); puts(Encryption/Decryption Complete.); /* delete Source file option. */ puts(Do you wish to delete the source file? (Y/N)); fgets(buffer, 20, stdin); sscanf(buffer, %c, &ans); if (tolower(ans) == 'y') { if (remove(argv[1]) == 0) puts(File deleted successfully.); else { puts(Unable to delete the file.); perror(Error); free(buf); return -9; } } /* delete keyfile option. */ puts(Do you wish to delete the keyfile? (Y/N)); fgets(buffer, 20, stdin); sscanf(buffer, %c, &ans); if(tolower(ans) == 'y') { if (remove(argv[3]) == 0) puts(File deleted successfully.); else { puts(Unable to delete the file.); perror(Error); free(buf); return -10; } } /* cleanup */ puts(Releasing memory.); free (buf); return(0);}
_webapps.13692
Is there a automagical way that I can copy my favorites from Pandora to Last.FM?
Copy favorite songs and artists from Pandora to Last.fm?
music;pandora;last.fm
null
_unix.140946
I have a problem with switching layouts in Chromium. If I switch keyboard layout it changes successfully, but I can't still type Cyrillic (or other) symbols in Chromium. I found out that actually keyboard layout is changed in Chromium, because symbols like ?, and are on the different places (they are in placesion which they should be in the current layout), but I can't type letters from the current layout.So for example I'm in English layout - I can type any letters etc. without any problems. Then I switch my layout to Russian (for example), after that I can't type any Cyrillic letters at all, I still can type only Latin letters.
Keyboard layout isn't changed in Chromium under Debian
debian;keyboard layout;chrome
null
_codereview.48002
I am building a new system that is using some tables from an old system.For each user on this new system, I need to go to the old system and total up their sales. Currently it takes between 2-5 minutes to load.public static List<DailyTeamGoal> GetListDailyTeamGoals(int teamId){ string teamGoal = ; List<ProPit_User> lstProPit_User = new List<ProPit_User>(); using (ProsPitEntities db = new ProsPitEntities()) { // Find the team Team team = db.Teams.Where(x => x.teamID == teamId).FirstOrDefault(); if (team != null) { // Grab team goal teamGoal = Convert.ToString(team.goal); } // Make a list of all users who are on the team lstProPit_User = db.ProPit_User.Where(x => x.teamID == teamId).ToList(); } List<DailyTeamGoal> lstDailyTeamGoal = new List<DailyTeamGoal>(); using (TEntities db = new TEntities()) { //have to get every day of the month DateTime dt = DateTime.Now; int days = DateTime.DaysInMonth(dt.Year, dt.Month); decimal orderTotal = 0m; for (int day = 1; day <= days; day++) { // For every day in the month total the sales DailyTeamGoal dtg = new DailyTeamGoal(); dtg.Date = day.ToString(); //dt.Month + / + day; + / + dt.Year; dtg.TeamGoal = teamGoal; decimal orderTotalRep = 0m; foreach (var propit_User in lstProPit_User) { DateTime dtStartDate = Convert.ToDateTime(dt.Month + / + day + / + dt.Year); DateTime dtEndDate = dtStartDate.AddDays(1); var lstorderTotalRep = (from o in db.Orders where o.DateCompleted >= dtStartDate where o.DateCompleted <= dtEndDate where (o.Status == 1 || o.Status == 2) where o.Kiosk != 0 where o.SalesRepID == propit_User.SalesRepID orderby o.OrderTotal descending select o.OrderTotal).ToList(); foreach (var item in lstorderTotalRep) { //orderTotalRep =+ item; orderTotalRep += item; } } orderTotal += orderTotalRep; dtg.DailyTotal = orderTotal; lstDailyTeamGoal.Add(dtg); } } return lstDailyTeamGoal;}The above code will use my site to find the teamID the logged in person is on. It will then find all members who are on that team. For each member it finds it will calculate the total sales and then spit me back a list. Any way to speed this up?
Calculating total sales from each member
c#;performance;linq;entity framework;asp.net mvc 4
I won't comment about the fact that this is a static method in what's possibly a static helper class and that it would be much prettier in a service class instance... but I just did.The method is doing way too many things.Thing one:// Make a list of all users who are on the teamThat's one method. But there's a twist: you not only need all users on the team, but also the teamGoal figure. I'd encapsulate that in its own class:public class TeamGoalAndUsersResult // todo: rename this class{ public IEnumerable<ProPit_User> Users { get; private set; } public string Goal { get; private set; } public TeamGoalAndUsersResult(string goal, IEnumerable<ProPit_User> users) { Users = users; Goal = goal; }}And then you can write a method/function that will return that type:private TeamGoalAndUsersResult GetTeamGoalAndUsers(int teamId){ using (ProsPitEntities db = new ProsPitEntities()) { var goal = string.Empty; var team = db.Teams.SingleOrDefault(x => x.teamID == teamId); if (team != null) { goal = Convert.ToString(team.goal); } var users = db.ProPit_User.Where(x => x.teamID == teamId).ToList(); return new TeamGoalAndUsersResult(goal, users); }}Performance Issue: var lstorderTotalRep = (from o in db.Orders where o.DateCompleted >= dtStartDate where o.DateCompleted <= dtEndDate where (o.Status == 1 || o.Status == 2) where o.Kiosk != 0 where o.SalesRepID == propit_User.SalesRepID orderby o.OrderTotal descending select o.OrderTotal).ToList(); foreach (var item in lstorderTotalRep) { //orderTotalRep =+ item; orderTotalRep += item; }You're doing all the computation on the client. I'd take a wild guess and say that this is where your bottleneck is. Do you really need to select, sort and materialize all orders just to sum up OrderTotal?var total = db.Orders.Where(o => o.DateCompleted >= dtStartDate && o.DateCompleted <= dtEndDate && (o.Status == 1 || o.Status == 2) && o.Kiosk != 0 && o.SalesRepID == user.SalesRepID) .Sum(o => o.OrderTotal);orderTotal += total;dtg.DailyTotal = orderTotal;dailyTeamGoals.Add(dtg);The above doesn't sort anything, has the same criterion and performs everything on the server side, without materializing every order in the way. Also I believe if the table has all the fields used in the WHERE, in an index (guts tell me especially DateCompleted), that would further help the server-side processing, but that's something you're probably better off finding out with a profiler.
_unix.251375
I ran this command on RHEL 6.3:# mount /dev/cdrom /mntEverything is okay, but after a restart the mounted dir, /mnt disappears...I don't know where is it going.
Mounted dir disappears after restart
rhel;mount
null
_softwareengineering.133935
I'm writing a Java framework to manipulate a large amount of data in-memory, where many cells that are near each other will have the same value.I'm looking for algorithms and/or techniques specially designed to eliminate those duplication while maintaining fast in-memory read access speed. That is, techniques that keeps an O(1) read-access speed.My data is store in immutable objects, to allow fast multi-threading. The data itself can be anything, from 4 bits-per-cell to doubles to arrays of beans, etc.
Where can I find good example of techniques to compact data in-memory?
java;performance;compression
If there is a lot of repetition of values then some form of run length encoding might work for the compression side, the tricky part would be maintaining O(1) lookup (or if we relax that constraint slightly, fast lookup)you could get log m lookup relatively easily (where m is the number of runs , not the number of values) by instead of storing the length with each value store the indexe.g. using the wikipedia example of WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWWinstead of storing the lengths with each value for a run (added parens for clarity)(12 W)(1 B)(12 W)(3 B)(24 W)(1 B)(14 W)we could store the indexes at which we change value (pluss an ending value if necessary)(0 W)(12 B)(13 W)(25 B)(28 W)(52 B)(53 W)(67 null) we can then use a binary search on the index to find the value for any index in log(m) which may be quick enough?
_unix.185144
I am a bit of a newbie when it comes to migrations. I had an old machine whose PSU crapped out. So I took whatever I could salvage (i.e. RAM, gfx card and the HDD which still had my arch installation) and merged it into a new machine. When I try to boot up the machine, it says cannot find root device with UUID-xxxxxx and it drops me into a recovery shell. After a bit of fiddling around I found out that the machine does boot into the fallback image and everything works perfectly. But when I reboot and try to boot into the normal image it says the same thing again. I am a bit lost as to what is going on. Could someone explain to me what went wrong and how I can go about fixing this? Also, I am writing this from the new machine in the fallback image.Cheers!Edits :/etc/fstab# UUID=2932dc14-2339-4509-aa13-4131764a9bfe/dev/sda5 / ext4 rw,relatime,data=ordered 0 1# UUID=ed251836-86aa-40ab-bd1f-b6f40937cb72/dev/sda1 /boot ext2 rw,relatime 0 2# UUID=c2a8e803-2197-4130-99f3-6a43cfb43e73/dev/sda7 /home ext4 rw,relatime,data=ordered 0 2#aravind@husker:/home/aravind/Work/ /home/aravind/Work fuse.sshfs noauto,x-systemd.automount,_netdev,users,IdentityFile=/home/aravind/.ssh/id_rsa,allow_other,reconnect,workaround=all 0 0/var/log/dmesg.logThere is no dmesg.log or boot.log in /var/log/BootloaderGrubBootloader - config /boot/grub/grub.cfg## DO NOT EDIT THIS FILE## It is automatically generated by grub-mkconfig using templates# from /etc/grub.d and settings from /etc/default/grub#### BEGIN /etc/grub.d/00_header ###insmod part_gptinsmod part_msdosif [ -s $prefix/grubenv ]; then load_envfiif [ ${next_entry} ] ; then set default=${next_entry} set next_entry= save_env next_entry set boot_once=trueelse set default=0fiif [ x${feature_menuentry_id} = xy ]; then menuentry_id_option=--idelse menuentry_id_option=fiexport menuentry_id_optionif [ ${prev_saved_entry} ]; then set saved_entry=${prev_saved_entry} save_env saved_entry set prev_saved_entry= save_env prev_saved_entry set boot_once=truefifunction savedefault { if [ -z ${boot_once} ]; then saved_entry=${chosen} save_env saved_entry fi}function load_video { if [ x$feature_all_video_module = xy ]; then insmod all_video else insmod efi_gop insmod efi_uga insmod ieee1275_fb insmod vbe insmod vga insmod video_bochs insmod video_cirrus fi}if [ x$feature_default_font_path = xy ] ; then font=unicodeelseinsmod part_msdosinsmod ext2set root='hd0,msdos5'if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos5 --hint-efi=hd0,msdos5 --hint-baremetal=ahci0,msdos5 2932dc14-2339-4509-aa13-4131764a9bfeelse search --no-floppy --fs-uuid --set=root 2932dc14-2339-4509-aa13-4131764a9bfefi font=/usr/share/grub/unicode.pf2fiif loadfont $font ; then set gfxmode=auto load_video insmod gfxtermfiterminal_input consoleterminal_output gfxtermset timeout=5### END /etc/grub.d/00_header ###### BEGIN /etc/grub.d/10_linux ###menuentry 'Arch Linux, with Linux core repo kernel' --class arch --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-core repo kernel-true-2932dc14-2339-4509-aa13-4131764a9bfe' { load_video set gfxpayload=keep insmod gzio insmod part_msdos insmod ext2 set root='hd0,msdos1' if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos1 --hint-efi=hd0,msdos1 --hint-baremetal=ahci0,msdos1 ed251836-86aa-40ab-bd1f-b6f40937cb72 else search --no-floppy --fs-uuid --set=root ed251836-86aa-40ab-bd1f-b6f40937cb72 fi echo 'Loading Linux core repo kernel ...' linux /vmlinuz-linux root=UUID=2932dc14-2339-4509-aa13-4131764a9bfe ro quiet echo 'Loading initial ramdisk ...' initrd /initramfs-linux.img}menuentry 'Arch Linux, with Linux core repo kernel (Fallback initramfs)' --class arch --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-core repo kernel-fallback-2932dc14-2339-4509-aa13-4131764a9bfe' { load_video set gfxpayload=keep insmod gzio insmod part_msdos insmod ext2 set root='hd0,msdos1' if [ x$feature_platform_search_hint = xy ]; then search --no-floppy --fs-uuid --set=root --hint-bios=hd0,msdos1 --hint-efi=hd0,msdos1 --hint-baremetal=ahci0,msdos1 ed251836-86aa-40ab-bd1f-b6f40937cb72 else search --no-floppy --fs-uuid --set=root ed251836-86aa-40ab-bd1f-b6f40937cb72 fi echo 'Loading Linux core repo kernel ...' linux /vmlinuz-linux root=UUID=2932dc14-2339-4509-aa13-4131764a9bfe ro quiet echo 'Loading initial ramdisk ...' initrd /initramfs-linux-fallback.img}### END /etc/grub.d/10_linux ###### BEGIN /etc/grub.d/20_linux_xen ###### END /etc/grub.d/20_linux_xen ###### BEGIN /etc/grub.d/30_os-prober ###### END /etc/grub.d/30_os-prober ###### BEGIN /etc/grub.d/40_custom #### This file provides an easy way to add custom menu entries. Simply type the# menu entries you want to add after this comment. Be careful not to change# the 'exec tail' line above.### END /etc/grub.d/40_custom ###### BEGIN /etc/grub.d/41_custom ###if [ -f ${config_directory}/custom.cfg ]; then source ${config_directory}/custom.cfgelif [ -z ${config_directory} -a -f $prefix/custom.cfg ]; then source $prefix/custom.cfg;fi### END /etc/grub.d/41_custom ###### BEGIN /etc/grub.d/60_memtest86+ ###### END /etc/grub.d/60_memtest86+ ###
Old HDD with arch linux on new machine won't boot
arch linux;fstab;migration
null
_softwareengineering.274118
Not sure exactly how to phrase the question succinctly for the title.I have a collection class that extends another collection class.The parent collection-class has a method addMember(someClass $obj) that adds an object to the collection.The child collection-class groups objects of the child class of someclass, someClassChild. I thought that a child class's method's signature would pass muster as long as the signature was the same or required children of the classes the parent required.E.g. addMember(someClassChild $obj)But I tried it and I'm getting a warning about strict standards.So then, how to I implement a collection class as a child of another collection class to provide functionality for parent/child base objects?
PHP extended class method requires same signature including object class requirement?
object oriented;php
null
_codereview.127606
I have a WinForms MVC application that uses Ninject for it's Dependency Injection (DI) / IoC Container. I have build quite a nice framework that allows the main shell (which uses a Docking Container to house an manipulate windows - like Visual Studio), to manipulate IDocument types (actual documents .txt, .xlsx etc.) and ITool types (my utilities, like file system explorer tree view, Command Window etc.). I communicate from the views (which are blind and deaf to the fact the controllers exist) to their controllers via event handlers. So the architecture is like this: IView.cs:public interface IView{ string DisplayName { get; set; }}IController.cs:public interface IController{ bool IsDirty { get; set; } IView View { get; }}IDocumentView.cs:public interface IDocumentView : IView, IActivate, IDeactivate{ bool StatusBarVisible { get; set; }}IDocumentController.cs:public interface IDocumentController : IController{ bool Handles(string path); DocumentView New(string fileName); DocumentView Open(string path); void Save(); string FilePath { get; set; } IEnumerable<DocumentFileType> FileTypes { get; }}I then have an abstract DocumentView class that handles so common behaviors of all IDocument types.DocumentController.cs:public abstract class DocumentController : IDocumentController, IClose, IGuardClose, IDisposable{ // Lots of stuff...}IGuardClose.cs:public interface IGuardClose{ void CanClose(Action<bool> callback);}IClose.cs:public interface IClose{ bool TryClose(object sender, FormClosingEventArgs e);}DocumentView.cs: [TypeDescriptionProvider(typeof(AbstractControlDescriptionProvider))] public abstract class DocumentView : DockContent, IDocumentView, IViewManagment { public virtual EventHandler OnViewLoaded { get; set; } public virtual EventHandler OnViewClosing { get; set; } public virtual EventHandler<EventArgs> ViewActivated { get; set; } public virtual EventHandler<EventArgs> ViewDeactivate { get; set; } public abstract string DisplayName { get; set; } public virtual bool StatusBarVisible { get; set; }}IViewManagement.cs:public interface IViewManagment{ EventHandler OnViewLoaded { get; set; } EventHandler<FormClosingEventArgs> OnViewClosing { get; set; }}They allow me to wire my controller up to listen for the loaded and losing events triggered from the view without the view knowing anything about it, but herein lies my problem.For my actual IDocumentViews and IDocumentControllers, I inherit from DocumentView and DocumentController respectively. This works well and all is fine, I can open new documents, open from files system you name it. My issue, is to do with closure. If I click the views X button to close the view, I need (and do) let the controller clean up some resources it is using (a FileSystemWatcher for the opened file etc.), but I also need to be able to close the view from the controller, so the TryClose method cannot merely do View.Close() for all calls as clearly this will envolve a stack overflow, as the View.Close() request would lead to another call to the controller TryClose etc. My questions:How can I best implement Controller.TryClose() so it can be used from both the controller and the view, should I have two methods in IClose, CleanUp(), let the controller clean its business and Close() actually close the view as well as clean up?Sometimes the user will close the main shell. Here I can to loop through all open documents and check CanClose() of IGuardClose. Assuming I can easily access the controllers from the main shell in a for loop/foreach loop, how best could I implement a close all (with safety - some documents are unsaved do you want to save now?)?
Supporting all closure options in WinForms MVC application
c#;winforms;dependency injection
null
_codereview.82261
Since I am fairly new to Python I was wondering whether anyone can help me by making the code more efficient. I know the output stinks; I will be using Pandas to make this a little nicer.from xlrd import *def main(): '''This Proram reads input (A:clone name, B:sequence, C:elisa) from an Excel file and makes a cross comparison of each sequence pair''' book = open_workbook(mtask.xlsx) Input = book.sheet_by_index(0) # naming of input data a = (Input.col_values(0,0)) b = (Input.col_values(1,0)) c = (Input.col_values(2,0)) # make dictionary: keys are seq numbers; values are residues y = {} for i in range(Input.nrows): x = [] for j in b[i]: x.append(j) y[a[i]] = x # comparison of sequences and extraction of mutations for each sequence pair List = [] for shit in range(Input.nrows): for seq in range(Input.nrows): seq12 = [] z = 0 for i in y[a[seq]]: try: for j in y[a[shit]][z]: if i == j: seq12.append(i.lower()+j.lower()) else: seq12.append(i+j) z = z+1 except IndexError: print(oops) lib = [a[seq],a[shit],c[seq],c[shit]] for position, item in enumerate(seq12): if item.isupper(): x = (str(item[0])+str(position+1)+str(item[1])) lib.append(x) List.append(lib) # comparison of sequences and extraction of mutations for each sequence pair dic = {} for i in range(Input.nrows*Input.nrows): x = [] for j in List[i]: x.append(j) dic[i] = x # sort a = [] for i in dic.values(): a.append(i) # collect number of mutations in data files import csv null = [] one = [] two = [] three = [] four = [] five = [] six = [] seven = [] eight = [] nine = [] ten = [] for i in range(Input.nrows*Input.nrows): if len(a[i]) <= 4: null.append(a[i]) with open(no_mut.csv, w, newline=) as f: writer = csv.writer(f) writer.writerows(null) elif len(a[i]) == 5: one.append(a[i]) with open(one.csv, w, newline=) as f: writer = csv.writer(f) writer.writerows(one) elif len(a[i]) == 6: two.append(a[i]) with open(two.csv, w, newline=) as f: writer = csv.writer(f) writer.writerows(two) elif len(a[i]) == 7: three.append(a[i]) with open(three.csv, w, newline=) as f: writer = csv.writer(f) writer.writerows(three) elif len(a[i]) == 8: four.append(a[i]) with open(four.csv, w, newline=) as f: writer = csv.writer(f) writer.writerows(four) elif len(a[i]) == 9: five.append(a[i]) with open(five.csv, w, newline=) as f: writer = csv.writer(f) writer.writerows(five) elif len(a[i]) == 10: six.append(a[i]) with open(six.csv, w, newline=) as f: writer = csv.writer(f) writer.writerows(six) elif len(a[i]) == 11: seven.append(a[i]) with open(seven.csv, w, newline=) as f: writer = csv.writer(f) writer.writerows(seven) elif len(a[i]) == 12: eight.append(a[i]) with open(eight.csv, w, newline=) as f: writer = csv.writer(f) writer.writerows(eight) elif len(a[i]) == 13: nine.append(a[i]) with open(nine.csv, w, newline=) as f: writer = csv.writer(f) writer.writerows(nine) elif len(a[i]) == 14: ten.append(a[i]) with open(ten.csv, w, newline=) as f: writer = csv.writer(f) writer.writerows(ten)main()
Reading an Excel file and comparing the amino acid sequence of each data pair
python;beginner;excel;bioinformatics;pandas
null
_codereview.19799
I need to write a jQuery plugin that doesn't take an element to work.Example call:$.funkyTown();... not called like this:$('#foo').funkyTown();...in other words, I need this plugin to act more like a utility plugin (vs. apply itself directly to a matched element(s)).Here's what I have written so far:;(function($, window, document, undefined) { var console = this.console || { log : $.noop, warn: $.noop }, // http://api.jquery.com/jQuery.noop/ defaults = { foo : 'bar', // Callbacks: onInit : $.noop, // After plugin data initialized. onAfterInit : $.noop // After plugin initialization. // Using $.noop shorter than function() {} and slightly better for memory. }, settings = {}, methods = { // Initialize! // Example call: // $.funkyTown({ foo : 'baz' }); // @constructor init : function(options) { settings = $.extend({}, defaults, options); settings.onInit.call(this, 'that'); console.log('1. init:', settings.foo, _foo_private_method(), methods.foo_public_method()); console.warn('2. I\'m a warning!'); settings.onAfterInit.call(this); return this; // Is this needed for chaining? }, // Example call: // console.log($.funkyTown('foo_public_method', 'Wha?')); foo_public_method : function(arg1) { arg1 = (typeof arg1 !== 'undefined') ? arg1 : 'Boo!'; return 'foo_public_method(), arg1: ' + arg1; }, // Might need to give users the option to destroy what this plugin created: destroy : function() { // Undo things here. } }, // The _ (underscore) is a naming convention for private members. _foo_private_method = function() { return '_foo_private_method(), settings.foo: ' + settings.foo; }; // Method calling logic/boilerplate: $.funkyTown = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if ((typeof method === 'object') || ( ! method)) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.funkyTown.'); } };}(jQuery, window, document));The above is called like so:$(document).ready(function() { // Calls init and modifies default options: $.funkyTown({ foo : 'baz' }); // Access to public method: console.log($.funkyTown('foo_public_method', 'Wha?'));});My questions:Do you see anything out of the ordinary with my above plugin template? If so, how could it be improved?Related to #1 above: As you can probably see, I'm trying to account for the various needs like passing options, private and public methods and console handling... What am I missing in terms of useful features? This line $.funkyTown = function(method) { makes the javascript linter throw a warning: warning: anonymous function does not always return a value; is there anyway for me to fix this? Could I just add return false to the end (right before the closing };? Update: Looks like I just needed to use a different tool.Because I'm writing a utility plugin (one that will never be used directly on an element) do I still need to return this in my public methods in order to make things chainable (see the return this; // Is this needed for chaining? line of code above)? Should I even worry about chaining for this type of plugin?Could you provide any other feedback to help me improve my code?What's the easiest/best way to pass settings from init to other private and public functions? Normally, I'd use .data() on $(this) to store settings and other stateful vars... Because there's not element, should I just pass settings as an argument to the other methods? Update: Doi! This was an easy one! I simply needed to initialize my settings outside of my public methods object.UPDATE 1:I've updated my code (above) to reflect the things I've learned (i.e. the strike-through lines in numeric list above) since posting this question.I've also added a new feature:;(function($, window, document, undefined) {// ...}(jQuery, window, document));I found that I needed access to window a few times already in my real script... After some Googling, I found this awesome resource:JavaScript Patterns Collection... which led me to here:Lightweight - perfect as a generic template for beginners and above... specifically:// the semi-colon before the function invocation is a safety// net against concatenated scripts and/or other plugins// that are not closed properly.;(function ( $, window, document, undefined ) { // undefined is used here as the undefined global // variable in ECMAScript 3 and is mutable (i.e. it can // be changed by someone else). undefined isn't really // being passed in so we can ensure that its value is // truly undefined. In ES5, undefined can no longer be // modified. // window and document are passed through as local // variables rather than as globals, because this (slightly) // quickens the resolution process and can be more // efficiently minified (especially when both are // regularly referenced in your plugin).})( jQuery, window, document );Update 2:I've added callbacks. I've also decided to use $.noop in place of function() {}:... typing $.noop is 6 chars shorter than function(){}. Also if you use this everywhere instead of creating new, anonymous, empty functions, you'll slightly cut down on memory. MarcoNow I'm wondering what my callbacks should return in a utility plugin? Sending this doesn't seem that useful.
A jQuery utility plugin template
javascript;jquery
What I suggest is read the jQuery source. Check out how they do it. In their init method they return this for certain cases, but not for others.Like when there is no selector:if ( !selector ) { return this;}But if you check out other utility plugins in their source like $.mapmap: function( elems, callback, arg ) {var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret );},Here they don't return the jQuery object, since this utility is for arrays. My point here is that there's no one shoe fits all. It depends on what you're trying to get from your plugin. Also chaining is expected but not on something like $.map(). Also keep in mind, in your callbacks this should refer to the element in question (ie. in a click callback this refers to the clicked element). If you're not playing with an element, this should refer to the global(window) object.
_codereview.88060
First Python script, so my code is pretty laughable. Sensitive information has been redacted. One thing that I'd like to point out is that there is an inconsistent use of '' and . This is an old habit that I really need to break. import sys, osimport prawimport timeimport sqlite3import reimport requestsimport jsonfrom datetime import datetime,timedeltaUSERNAME = PASSWORD = time_zone = updateTime = datetime.utcnow() - timedelta(hours=7)time_stamp = updateTime.strftime(%m-%d-%y %I:%M:%S %p PST :: )sql = sqlite3.connect((os.path.join(sys.path[0],'redacted-sql.db')))cur.execute('CREATE TABLE IF NOT EXISTS oldmentions(ID TEXT)')sql.commit()r = praw.Reddit()r.login(USERNAME, PASSWORD) def stats(): mentions = list(r.get_mentions(limit=None)) unreads = list(r.get_unread(limit=None)) for mention in mentions: mid = mention.id try: pauthor = mention.author.name except AttributeError: #author is deleted continue cur.execute('SELECT * FROM oldmentions WHERE ID=?', [mid]) if cur.fetchone(): #post already in database continue pbody = mention.body.lower().replace('\n', ' ').encode('utf-8') pbody_strip_1 = re.sub(r'[^A-Za-z0-9 ]+', '', str(pbody_strip_0)) pbody_words = pbody_strip_1.split(' ') pbody_words_1 = filter(None, pbody_words) try: if pbody_words_1[pbody_words_1.index('redactedbot')-1] == u: charname = pbody_words_1[pbody_words_1.index('redactedbot')+1] else: cur.execute('INSERT INTO oldmentions VALUES(?)', [mid]) sql.commit() mention.mark_as_read() continue except (IndexError, KeyError, ValueError): cur.execute('INSERT INTO oldmentions VALUES(?)', [mid]) sql.commit() mention.mark_as_read() continue cns_char_dic = json.loads(cns_char_j) char_exist = cns_char_dic['returned'] if char_exist != 1: cur.execute('INSERT INTO oldmentions VALUES(?)', [mid]) sql.commit() mention.mark_as_read() continue char_case = cns_char_dic['person_list'][0]['name']['first'] char_id = cns_char_dic['person_list'][0]['person_id'] char_creation = time.strftime(time_format, time.localtime(float(cns_char_dic['person_list'][0]['times']['creation']))) char_login = time.strftime(time_format, time.localtime(float(cns_char_dic['person_list'][0]['times']['last_login']))) char_login_count = int(float(cns_char_dic['person_list'][0]['times']['login_count'])) char_h, char_m = divmod(int(cns_char_dic['person_list'][0]['times']['minutes_played']), 60) if char_h == 1: hours = hour else: hours = hours if char_login_count == 1: logins = login) else: logins = logins) char_rank = cns_char_dic['person_list'][0]['battle_rank']['value'] post_reply_rank = Battle rank: + char_rank if char_rank_next != 0: post_reply_rank += ( + char_rank_next + % to next) char_faction = cns_char_dic['person_list'][0]['faction'] char_world_id = cns_char_dic['person_list'][0]['world_id'] try: char_outfit = cns_char_dic['person_list'][0]['outfit_member'] if char_outfit['member_count'] != 1: post_reply_outfit = Outfit: [ + str(char_outfit['alias']) + ] + str(char_outfit['name']) + ( + {:,}.format(int(char_outfit['member_count'])) + members) else: post_reply_outfit = Outfit: [ + char_outfit['alias'] + ] + char_outfit['name'] + ( + char_outfit['member_count'] + member) except KeyError: post_reply_outfit = Outfit: None try: char_kills = cns_char_dic['person_list'][0]['stats']['stat_history'][5]['all_time'] char_deaths = cns_char_dic['person_list'][0]['stats']['stat_history'][2]['all_time'] cns_stat_j = cns_stat.text cns_stat_dic = json.loads(cns_stat_j) char_stat = cns_stat_dic['persons_stat_list'] if pauthor.lower() != USERNAME.lower(): try: mention.reply(post_reply) mention.mark_as_read() except APIException: pass cur.execute('INSERT INTO oldmentions VALUES(?)', [mid]) sql.commit() else: print(time_stamp + 'Will not reply to myself') cur.execute('INSERT INTO oldmentions VALUES(?)', [mid]) sql.commit() mention.mark_as_read()
Uses game API to post stats about user when requested
python;json;api
null
_webapps.44710
I have a problem with Dropbox Camera Upload: I have an iPad, an iPhone and a Samsung Galaxy Camera, all uploading photos to Dropbox. I would like to create different folders for each one of them: uploads from iPad, uploads from iPhone, uploads from Samsung, to divide the photos from each device. Is this possible?
Using Dropbox with multiple cameras
dropbox
null
_cs.79305
The halting-after-$n$ steps problem may be defined as the question if a given turing machine halts after a maximum of $n\in\mathbb{N}$ steps. Is it theoretically possible to solve this problem in general in less than $n$ execution steps (just execution the program) or can't this be done? If not, why not?Thank you
Is it possible to solve the halting-after-$n$ steps problem more efficient than just execute $n$ steps?
turing machines;halting problem
The time hierarchy theorem, or rather its proof, gives some answer to this question. If you look at the proof, you should get a lower bound of $\Omega(n/\log n)$.In more detail, consider the language $L$ of all triples $\langle M,x,1^t \rangle$ such that $M$ halts on $x$ after at most $t$ steps. Suppose that this can be solved in time $f(n)$, where $n$ is the input length (which is $t + |M| + |x|$). Then you can construct a Turing machine which on input $\langle x,1^t \rangle$ determines whether $\langle x,x,1^t \rangle \in L$, if so runs into an infinite loop, otherwise halts. When run on itself as input, this machine either halts in time $f(t + O(1)) + O(1)$ or never halts. Hence if $f(t + O(1)) + O(1) \leq t$, we reach a contradiction. This shows that $f$ has to essentially be at list linear.
_unix.197057
Using grep val index.php I get the list<td class=val> 7.6</td><td class=val> 58</td><td class=val>1013.8 </td><td class=val> 1020 </td><td class=val> 0.2</td><td class=val> 2.4</td>I'd like to filter and get only the value of the first td, that is, 7.6 and save it to use later with echo.That value could change, so grep 7.6 is not good.(!) The line in php containing that tag is line 42. A solution without this information could be better since the line number could change. But for a while, using its number can be a temporary solution.I searched for a solution but I only found complex ones.
Filter grep output
scripting;grep
null
_cs.50505
I'm learning how to convert NFAs to DFAs and I want to make sure I'm doing it right. Obviously, going back in the other direction isn't a thing. Does anyone know of an algorithm to check that a DFA is equivalent to a NFA?
How do I verify that a DFA is equivalent to a NFA?
automata;finite automata;proof techniques;nondeterminism
This is a problematic question. There is a way to check equivalence of automata, which I'll now explain, but I'm afraid it won't help you, as you will see at the end.Recall that two sets $A$ and $B$ are equal iff $A\subseteq B$ and $B\subseteq A$ (this is the definition of set equality).Thus, it is enough for you to verify that $L(D)\subseteq L(N)$ and $L(N)\subseteq L(D)$, where $D$ and $N$ are your DFA and NFA, respectively.But how do you check containment of languages, you might ask. Well, now observe that $A\subseteq B$ iff $A\cap \overline{B}=\emptyset$ (where $\overline{B}$ is the complement of $B$).Let's consider first checking whether $L(N)\subseteq L(D)$. To do this, you need to complement $D$ (very easy - swap the accepting an rejecting states), then construct the intersection automaton (e.g. with the product construction) with $N$, and check for emptiness, by finding a path to an accepting state.The converse direction, however, will show why this doesn't help you. In order to check whether $L(D)\subseteq L(N)$, you need to complement $N$. But in order to complement an NFA, you first need to convert it to a DFA, rendering the whole idea pointless.Essentially, the problem with your question is much deeper: you want to verify that you (an undefined computational model) executed a well-defined algorithm properly. So this is not really a computer-science problem.I will say this: following the constructions I suggested, it is not hard to conclude that $L(D)\neq L(N)$ iff there is a word of length at most $2^{2n}$ ($n$ being the number of states of $N$) that is accepted by one and not by the other. So you can try all words up to this length.
_cseducators.728
These days, we've got all this fancy, new-fangled technology. We've got live coding, we've got presentations, we've got remote desktop adapted for classroom use. There seems to be a tool for every teaching problem. But when should we ignore the KnowledgeInjector2000TM and instead use the good old blackboard?More specifically, which concepts are easier to explain with a blackboard and how would you use a blackboard to explain them?
When should I scrap my projector for a blackboard?
lecture tools
null
_softwareengineering.318549
When I have some object with boolean state that can be changed (like a checkbox's checkedness), there are several ways I can expose it.Getter property, Setter methodbool IsChecked { get { ... } }void SetChecked(bool checked) { ... }Getter property, Set true method, Set false methodbool IsChecked { get { ... } }void Check() { ... }void Uncheck() { ... }Getter, setter propertybool IsChecked { get { ... } set { ... } } Is there a good design or logical reason to use one of these ways in particular? (I apologize if this question is too opinion-based/open-ended)
How should I represent mutable boolean state?
c#;design patterns
null
_unix.134010
I'm writing a script to build a software from sources, and there's a --platforms option. I would like to allow the user to select multiple items, but I don't know how to prevent them from making a mistake.Example:read -p For what platforms do you wish to build [mac/win/linux32/linux64/all] ? if [[ -n `echo $REPLY | grep 'win\|mac\|linux32\|linux64\|all` ]] ; then echo okelse echo not okfiIf the user answers linux32, it should be OK (and it is)If the user answers linux32,mac, it should be OK (and it is)If the user answers lulz, it should NOT be OK (and it is not)If the user answers linux32,lulz, it should NOT be OK (and it is, that's my issue)I was wondering if you knew a way to allow the user to input whatever they want separated by commas, but only if it's one of the options the script is offering, so in this case linux32 linux64 mac win all. Maybe with case there is a way to allow multiple inputs, or maybe add an elif $REPLY contains anything else than what we want. Another idea, could awk be used? I can't figure out myself how to do that.
Check if a variable contains only what I want, and nothing else
bash;grep
A simplified/improved version of arnefm's answer:read -p 'Enter a comma-separated list of platforms to build for [win/mac/linux32/linux64/all]: ' inputIFS=',' read -a options <<< $inputshopt -s extglobfor option in ${options[@]}; do case $option in win|mac|linux@(32|64)|all) buildcommand=${buildcommand:+$buildcommand,}$option buildvar=1;; *) printf 'Invalid option %s ignored.\n' $option >&2;; esacdoneIFS=',' read -a options <<< $buildcommandfor option in ${options[@]}; do if [[ $option == 'all' ]]; then buildcommand='all' break fidoneif (( !buildvar )); then echo 'Incorrect input. Default build selected.' >&2 buildcommand='default'fi
_cs.68861
The question is to show that there are $(n-1)!/2$ distinct tours for a Euclidean traveling salesman problem (ETSP) on $n$ points.My attempt was using induction. So I start by:If $n=3$, then we have a triangle and there is only one tour.Assume that there are $(n-1)!/2$ distinct tours for a ETSP on $n$ points. Prove that there are $n!/2$ distinct tours for a ETSP on $n+1$ points?Here I proceed like this: for each tour $t$ from the $(n-1)!/2$ distinct tours do: add one point $n+1$.for each edge $e=\{v_i, v_j\}$ in $t$ do: remove $e$ and create two edges $e_1=\{n+1,v_i\}$ and $e_2=\{n+1, v_j\}$. We have a new tour and in total we can create $n$ distinct tours.Since there are $(n-1)!/2$ distinct tours, we will have $n(n-1)!/2=n!/2$ distinct tours.This gives the desired result but somehow long and complicated.
Show that there are $(n-1)!/2$ distinct tours for a Euclidean traveling salesman problem on $n$ points?
traveling salesman
We may reason in a combinatorial way.There are $n!$ permutations of $n$ nodes, but that overcounts the number of tours in two different ways. Since tours are closed, we may start indifferently on any of the $n$ nodes, and we may choose the direction in $2$ ways. Therefore, each tour was counted a total of $2n$ times.This yields the desired result.
_unix.19829
I've got a slight problem with a very stubborn error during an rsync. It's caused by a file with a special character in its filename. There's been others but I could sort that out by doing some conversion in the encoding of the filename. However this one file I can't even find.So here's what rsync says:../.\#033OA.tex.pyD0MB failed: No such file or directory (2)First thing one notices is that the character code can't be hex or octal so I've googled it and only found this. So it may be a CURSOR UP character (or not). I've triedls -la *`printf '\033OA'`*to no avail. I've also tried piping the output of ls of that directory to od to no avail.What else can I do? Or what character am I looking for anyway?Thanks
special character in filename (\#033OA)
filenames;character encoding;special characters
You can use the -b option to ls, which shows non graphical characters as C-style escape sequences.
_unix.302280
I'm a little lost and hope someone can point me into the right direction to solve my problem. I have a server running with a Debian distribution and I'm using UFW as firewall. The configuration and setup was pretty easy and I started the firewall as documented with:manly@server:~$ sudo ufw enableCommand may disrupt existing ssh connections. Proceed with operation (y|n)? yFirewall is active and enabled on system startupIf I check, if ufw is running I receive (correctly):manly@server:~$ sudo ufw statusStatus: activeTo Action From-- ------ ----22 ALLOW Anywhere80/tcp ALLOW Anywhere22 ALLOW Anywhere (v6)80/tcp ALLOW Anywhere (v6)After some time (I check daily), the firewall turns inactive - even without any restart in between -, i.e., status returns inactive:manly@server:~$ sudo ufw statusStatus: inactiveI have no idea why. What can I check to figure out the reasons behind that weird behavior. I'm thankful for any advice!Update:I noticed something, which may help to find a solution. So I start the ufw with the sudo ufw enable in an ssh session. It seems like, that if I keep the ssh session open, the firewall is enabled. If I close the ssh session (exit), the ufw status will be set to inactive after some time. Do I have to start the ufw in any special manner?
UFW (Uncomplicated Firewall) turns off (inactive) after a while
linux;debian;firewall;ufw
So after some digging and talking to the support, we finally figured out, what stops UFW. The system also had APF (Advanced Policy Firewall - R-fx Networks) configured, which adds a cron-job to the system. The job removes all rules on midnight and resets the rules defined for APF.
_webapps.74578
I would like to create 20-30 shortened URLs to Google Documents using Google own URL shortener Goo.gl. Does anybody know if this is possible or do I need to enter them one by one?
Batch creation of shortened URLs with Goo.gl
goo.gl
my thoughts :use the goo.gl url shortener APIwrite code to loop through all the links and shorten them.get short linkswant me to write the code?
_webmaster.78152
Back in the day when I was updating my website and had errors, Google Webmaster Tools took note of it and gave my sitemap files warnings.Now I decided to start over new again by uploading brand new sitemaps with today's date stamped on them, and yet I still get the same warnings dated from weeks ago as follows:When we tested a sample of the URLs from your Sitemap, we found that some of the URLs were unreachable. Please check your webserver for possible misconfiguration, as these errors may be caused by a server error (such as a 5xx error) or a network error between Googlebot and your server. All reachable URLs will still be submitted.Some URLs in the Sitemap have a high response time. Some URLs listed in this Sitemap have a high response time. This may indicate a problem with your server or with the content of the page.I have fixed these issues now, but I don't know how to delete the warnings and make Google re-evaluate my website again. Anyone have any ideas?
Resetting sitemap warnings in Webmaster Tools
google;google search console;sitemap;crawl errors;link submission
null