Search Results

Search found 382 results on 16 pages for 'rep movsd'.

Page 1/16 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • VoteCounts: bookmarklet to display up/down votes even for rep<1k

    - by SztupY
    Screenshot / Code Snippet About This small bookmarklet will allow anyone to use the "vulnerability" of the API that it allows you to check the up/down vote count - a feat you could normally achieve by being a 1k+rep user. Mainly useful for sites where you don't have this amount of rep, but want to check the stats of the more controversial questions (usually on meta) No API key is actually used here, but it's trivial to add one. License I don't think a code like this deserves anything other than WTFPL Download It's the following line (javascript - 375 bytes): javascript:(function(){a='jsonp';c=' .vote-count-post';d='up_vote_count';e='down_vote_count';$.ajax({url:document.location.href.replace(/(http:\/\/)(.*)(\/questions\/.*)\/.*/,'$1api.$2/1.0$3'),dataType:a,jsonp:a,success:function(x){b=x.questions[0];$('#question'+c).html(b[d]+"-"+b[e]);$.each(b.answers,function(z,y){$('#answer-'+y.answer_id+c).html(y[d]+"-"+y[e])})}})})() EDIT: This is longer, but it will make the result look like exactly on SO. Took a while to make it exactly 508 chars, so it works with IE too. javascript:(function(){w=function(t,q){l='_vote_count';h='up'+l;j='down'+l;k='</div>';s='<div style="color:';$(t).html(s+'green">'+(q[h]?'+':'')+q[h]+k+'<div class="vote-count-separator">'+k+s+'maroon">'+(q[j]==0?'':'-')+q[j]+k)};a='jsonp';c=' .vote-count-post';$.ajax({url:document.location.href.replace(/(http:\/\/)(.*)(\/questions\/.*)\/.*/,'$1api.$2/1.0$3'),dataType:a,jsonp:a,success:function(x){b=x.questions[0];w('#question'+c,b);$.each(b.answers,function(z,y){w('#answer-'+y.answer_id+c,y)})}})})() Platform For any jquery/bookmarklets compatible browser. Tested with Chrome, FF3.6 and IE8 for SU,SO,MSO Contact sztupy.hu Code It was written in notepad already in minified form. Used firebug to debug. Code is above. Contribute(=decrease code size or make the output nicer) any way you want. I'd be great if you'd do the second code shorter than 508 bytes. Known bugs If a question has more than 30 answers then some of the answers won't be resolved. This can be solved easily for <=100 answers, but for questions with more than 100 answers this is more difficult EDIT: updated to API version 1.0. Answers doesn't work yet.

    Read the article

  • Make compiler copy characters using movsd

    - by Suma
    I would like to copy a relatively short sequence of memory (less than 1 KB, typically 2-200 bytes) in a time critical function. The best code for this on CPU side seems to be rep movsd. However I somehow cannot make my compiler to generate this code. I hoped (and I vaguely remember seeing so) using memcpy would do this using compiler built-in instrinsic, but based on disassembly and debugging it seems compiler is using call to memcpy/memmove library implementation instead. I also hoped the compiler might be smart enough to recognize following loop and use rep movsd on its own, but it seems it does not. char *dst; const char *src; // ... for (int r=size; --r>=0; ) *dst++ = *src++; Is there some way to make the Visual Studio compiler to generate rep movsd sequence other than using inline assembly?

    Read the article

  • Error: (subscript) logical subscript too long

    - by frespider
    Can some one let me know why I am getting this error and how I can fix it? Here is the code What I am trying to do is remove the rows that associated 1's if the column of that one's less than 10 a0=rep(1,40) a=rep(0:1,20) b=c(rep(1,20),rep(0,20)) c0=c(rep(0,12),rep(1,28)) c1=c(rep(1,5),rep(0,35)) c2=c(rep(1,8),rep(0,32)) c3=c(rep(1,23),rep(0,17)) c4=c(rep(1,6),rep(0,34)) x=matrix(cbind(a0,a,b,c0,c1,c2,c3,c4),nrow=40,ncol=8) nam <- paste("V",2:9,sep="") colnames(x)<-nam dat <- cbind(y=rnorm(40,50,7),x) #=================================== toSum <- colSums(dat) Col <- Val <- NULL for(i in 1:length(toSum)){ if(toSum[i]<10){ Col <- c(Col,colnames(dat)[i]) Val <- c(Val,toSum[i])} } cs <- colSums(dat) < 10 indx <- dat[,which(cs)]==0 for(i in 1:dim(indx)[2]){ datnw <- dat[indx[,i],] dat <- datnw} datnw2 <- dat[, -which(cs)] Thanks

    Read the article

  • share git rep access on unix machine with ssh

    - by Daniel
    at my school we have a student unix server with our accounts. i have installed git on my account, created a repository, and created the acl permissions on the folder repository so other users can access the repository # file: tp1 # owner: my_account # group: groupxxx user::rwx user:friend_account:rwx group::--- mask::rwx other::--- default:user::rwx default:user:friend_account:rwx default:group::--- default:mask::rwx default:other::--- but friend_account cant even cd to my tp1 directory (permission denied), so i think the problem should be in unix acl permissions..

    Read the article

  • ANOVA with 3 fixed factors in R

    - by TKBell
    Im trying to run a model with a response variable p and 3 fixed factors to get ANOVA. this is how my code looks like : #run it as 3 fixed factor model p1=c(37,38,37,41,41,40,41,42,41) p2=c(42,41,43,42,42,42,43,42,43) p3=c(30,31,31,31,31,31,29,30,28) p4=c(42,43,42,43,43,43,42,42,42) p5=c(28,30,29,29,30,29,31,29,29) p6=c(42,42,43,45,45,45,44,46,45) p7=c(25,26,27,28,28,30,29,27,27) p8=c(40,40,40,43,42,42,43,43,41) p9=c(37,38,37,41,41,40,41,42,41) p10=c(35,34,34,35,35,34,35,34,35) p = cbind(p1,p2,p3,p4,p5,p6,p7,p8,p9,p10) partnumber=c(rep(1,9),rep(2,9),rep(3,9),rep(4,9),rep(5,9),rep(6,9),rep(7,9),rep(8,9),rep(9,9),rep(10,9)) test=c(rep(c(rep(1:3,3)),10)) inspector = rep(c(rep(1,3),rep(2,3),rep(3,3)),10) fpartnumber = factor(partnumber) ftest = factor(test) finspector = factor(inspector) model=lm(p~fpartnumber*ftest*finspector) summary(model) anova(model) but when I run it I get this error : it says my variable length for fpartnumber is different , but when I checked the length of each variable and is 90. What is going on ? model=lm(y~fpartnumber*ftest*finspector) Error in model.frame.default(formula = yang ~ fpartnumber * ftest * finspector, : variable lengths differ (found for 'fpartnumber')

    Read the article

  • Why does Maven have such a bad rep?

    - by Dan
    There is a lot of talk on the internet about how Maven is bad. I have been using some features of Maven for a few years now and the most important benefit in my view is the dependency management. Maven documentation is less than adequate, but generally when I need to accomplish something I figure it once and than it works (for example, I remember when I implemented signing the jars.) I don’t think that Maven is great, but it does solve some problems that without it would be a genuine pain. So, why does Maven has such a bad rep and what problems with Maven can I expect in the future? Maybe there are much better alternatives that I don't know about? (For example, I never looked Ivy in detail.) NOTE: This is not an attempt to cause an argument. It is an attempt to clear the FUD.

    Read the article

  • ZeroMQ REQ/REP on ipc:// and concurrency

    - by Metiu
    I implemented a JSON-RPC server using a REQ/REP 0MQ ipc:// socket and I'm experiencing strange behavior which I suspect is due to the fact that the ipc:// underlying unix socket is not a real socket, but rather a single pipe. From the documentation, one has to enforce strict zmq_send()/zmq_recv() alternation, otherwise the out-of-order zmq_send() will return an error. However, I expected the enforcement to be per-client, not per-socket. Of course with a Unix socket there is just one pipeline from multiple clients to the server, so the server won't know who it is talking with. Two clients could zmq_send() simultaneously and the server would see this as an alternation violation. The sequence could be: ClientA: zmq_send() ClientB: zmq_send() : will it block until the other send/receive completes? will it return -1? (I suspect it will with ipc:// due to inherent low-level problems, but with TCP it could distinguish the two clients) ClientA: zmq_recv() ClientB: zmq_recv() so what about tcp:// sockets? Will it work concurrently? Should I use some other locking mechanism to work around this?

    Read the article

  • Eclipse - Import existing mult-rep CVS project folder

    - by iQ
    Hey guys, Wondering if anyone can help me out with eclipse in terms of importing an existing CVS managed project. I am currently trying to shift my work on to the eclipse IDE. Some details about my project and environment below. I'm working in Linux Ubuntu, the project folder is located on a mounted shared network drive, I have installed the "Eclipse CVS Client" plug-in for my version of eclipse (helios). I've tried many ways for eclipse to use my existing folder as a project and recognize the CVS data in the CVS folders. I have done the following options: Created a new project, selected existing source, located my project folder and clicked OK to finish creating. In the end the CVS files weren't automatically read. Did the same as above and after project creation I wen to the option "project menu-team-share project", it asks me to choose a repository and doesn't automatically find the CVS information in the subfolders. If your wondering I have set-up both repositories in my eclipse and can browse the repositories through the CVS browser. My project directory layout is like this: +-Project Folder (no CVS folder at this level) +---Repo A folder +-----CVS meta-info folder is INSIDE, along with all checked out files from Repo A + +---Repo B folder +-----CVS meta-info folder is INSIDE, along with all checked out files from Repo B + +-(couple of random files, not in CVS) Thanks for the help

    Read the article

  • Subversion post-commit hook to sync rep with FTP server ( for a website )

    - by Brett
    I've installed a repository on my computer locally. What I'm trying to do is be able to work on a website locally on my computer and see changes using something like MAMP. When I commit a change though I'd like it to sync my repo with the live website source files on a remote FTP server. I've done a bit of digging and I know that people keep saying to use a post-commit hook but I'm not sure how to configure it or even how to install it locally. Also i'm not sure if it's possible to do from my computer to an FTP. Could someone be a huge help and walk me through how to do this I've been trying for hours to figure out how to do it. thanks so much.

    Read the article

  • How to include multiple tables programmaticaly into a Sweave document using R

    - by PaulHurleyuk
    Hello, I want to have a sweave document that will include a variable number of tables in. I thought the example below would work, but it doesn't. I want to loop over the list foo and print each element as it's own table. % \documentclass[a4paper]{article} \usepackage[OT1]{fontenc} \usepackage{longtable} \usepackage{geometry} \usepackage{Sweave} \geometry{left=1.25in, right=1.25in, top=1in, bottom=1in} \listfiles \begin{document} <<label=start, echo=FALSE, include=FALSE>>= startt<-proc.time()[3] library(RODBC) library(psych) library(xtable) library(plyr) library(ggplot2) options(width=80) #Produce some example data, here I'm creating some dummy dataframes and putting them in a list foo<-list() foo[[1]]<-data.frame(GRP=c(rep("AA",10), rep("Aa",10), rep("aa",10)), X1=rnorm(30), X2=rnorm(30,5,2)) foo[[2]]<-data.frame(GRP=c(rep("BB",10), rep("bB",10), rep("BB",10)), X1=rnorm(30), X2=rnorm(30,5,2)) foo[[3]]<-data.frame(GRP=c(rep("CC",12), rep("cc",18)), X1=rnorm(30), X2=rnorm(30,5,2)) foo[[4]]<-data.frame(GRP=c(rep("DD",10), rep("Dd",10), rep("dd",10)), X1=rnorm(30), X2=rnorm(30,5,2)) @ \title{Docuemnt to test putting a variable number of tables into a sweave Document} \author{"Paul Hurley"} \maketitle \section{Text} This document was created on \today, with \Sexpr{print(version$version.string)} running on a \Sexpr{print(version$platform)} platform. It took approx \input{time} sec to process. <<label=test, echo=FALSE, results=tex>>= cat("Foo") @ that was a test, so is this <<label=table1test, echo=FALSE, results=tex>>= print(xtable(foo[[1]])) @ \newpage \subsection{Tables} <<label=Tables, echo=FALSE, results=tex>>= for(i in seq(foo)){ cat("\n") cat(paste("Table_",i,sep="")) cat("\n") print(xtable(foo[[i]])) cat("\n") } #cat("<<label=endofTables>>= ") @ <<label=bye, include=FALSE, echo=FALSE>>= endt<-proc.time()[3] elapsedtime<-as.numeric(endt-startt) @ <<label=elapsed, include=FALSE, echo=FALSE>>= fileConn<-file("time.tex", "wt") writeLines(as.character(elapsedtime), fileConn) close(fileConn) @ \end{document} Here, the table1test chunk works as expected, and produced a table based on the dataframe in foo[[1]], however the loop only produces Table(underscore)1.... Any ideas what I'm doing wrong ?

    Read the article

  • How to create a column containing a string of stars to inidcate levels of a factor in a data frame i

    - by PaulHurleyuk
    (second question today - must be a bad day) I have a dataframe with various columns, inculding a concentration column (numeric), a flag highlighting invalid results (boolean) and a description of the problem (character) dput(df) structure(list(x = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), rawconc = c(77.4, 52.6, 86.5, 44.5, 167, 16.2, 59.3, 123, 1.95, 181), reason = structure(c(NA, NA, 2L, NA, NA, NA, 2L, 1L, NA, NA), .Label = c("Fails Acceptance Criteria", "Poor Injection"), class = "factor"), flag = c("False", "False", "True", "False", "False", "False", "True", "True", "False", "False" )), .Names = c("x", "rawconc", "reason", "flag"), row.names = c(NA, -10L), class = "data.frame") I can create a column with the numeric level of the reason column df$level<-as.numeric(df$reason) df x rawconc reason flag level 1 1 77.40 <NA> False NA 2 2 52.60 <NA> False NA 3 3 86.50 Poor Injection True 2 4 4 44.50 <NA> False NA 5 5 167.00 <NA> False NA 6 6 16.20 <NA> False NA 7 7 59.30 Poor Injection True 2 8 8 123.00 Fails Acceptance Criteria True 1 9 9 1.95 <NA> False NA 10 10 181.00 <NA> False NA and here's what I want to do to create a column with 'level' many stars, but it fails df$stars<-paste(rep("*",df$level)sep="",collapse="") Error: unexpected symbol in "df$stars<-paste(rep("*",df$level)sep" df$stars<-paste(rep("*",df$level),sep="",collapse="") Error in rep("*", df$level) : invalid 'times' argument rep("*",df$level) Error in rep("*", df$level) : invalid 'times' argument df$stars<-paste(rep("*",pmax(df$level,0,na.rm=TRUE)),sep="",collapse="") Error in rep("*", pmax(df$level, 0, na.rm = TRUE)) : invalid 'times' argument It seems that rep needs to be fed one value at a time. I feel that this should be possible (and my gut says 'use lapply' but my apply fu is v. poor) ANy one want to try ?

    Read the article

  • Is it possible to link directories in git?

    - by Andreas Selenwall
    I will start with a simplified example describing my intent. I have a repository my-rep.git containing two directories, src and deploy. In src I have my source code (NodeJS code, but that doesn't matter), and in deploy I want to keep my deploy configuration. So for example if I have a project, projectA, then the structure should look like this, my-rep.git/src/projectA my-rep.git/deploy/projectA/dotcloud.yml my-rep.git/deploy/projectA/src Now to my question. I want the source code in projectA to be available in the deploy directory for dotcloud. Is there any way I can make my-rep.git/deploy/projectA/src point to my-rep.git/src/projectA, that is, so when I do a git pull in deploy it will automatically pull the my-rep.git/deploy/projectA/src. It must be supported in git, symbolic linux links won't work as some developers in my team work in Windows.

    Read the article

  • R ggplot2: Arrange facet_grid by non-facet column (and labels using non-facet column)

    - by tommy-o-dell
    I have a couple of questions regarding facetting in ggplot2... Let's say I have a query that returns data that looks like this: (note that it's ordered by Rank asc, Alarm asc and two Alarms have a Rank of 3 because their Totals = 1798 for Week 4, and Rank is set according to Total for Week 4) Rank Week Alarm Total 1 1 BELTWEIGHER HIGH HIGH 1000 1 2 BELTWEIGHER HIGH HIGH 1050 1 3 BELTWEIGHER HIGH HIGH 900 1 4 BELTWEIGHER HIGH HIGH 1800 2 1 MICROWAVE LHS 200 2 2 MICROWAVE LHS 1200 2 3 MICROWAVE LHS 400 2 4 MICROWAVE LHS 1799 3 1 HI PRESS FILTER 2 CLOG SW 1250 3 2 HI PRESS FILTER 2 CLOG SW 1640 3 3 HI PRESS FILTER 2 CLOG SW 1000 3 4 HI PRESS FILTER 2 CLOG SW 1798 3 1 LOW PRESS FILTER 2 CLOG SW 800 3 2 LOW PRESS FILTER 2 CLOG SW 1200 3 3 LOW PRESS FILTER 2 CLOG SW 800 3 4 LOW PRESS FILTER 2 CLOG SW 1798 (duplication code below) Rank = c(rep(1,4),rep(2,4),rep(3,8)) Week = c(rep(1:4,4)) Total = c( 1000,1050,900,1800, 200,1200,400,1799, 1250,1640,1000,1798, 800,1200,800,1798) Alarm = c(rep("BELTWEIGHER HIGH HIGH",4), rep("MICROWAVE LHS",4), rep("HI PRESS FILTER 2 CLOG SW",4), rep("LOW PRESS FILTER 2 CLOG SW",4)) spark <- data.frame(Rank, Week, Alarm, Total) Now when I do this... s <- ggplot(spark, aes(Week, Total)) + opts( panel.background = theme_rect(size = 1, colour = "lightgray"), panel.grid.major = theme_blank(), panel.grid.minor = theme_blank(), axis.line = theme_blank(), axis.text.x = theme_blank(), axis.text.y = theme_blank(), axis.title.x = theme_blank(), axis.title.y = theme_blank(), axis.ticks = theme_blank(), strip.background = theme_blank(), strip.text.y = theme_text(size = 7, colour = "red", angle = 0) ) s + facet_grid(Alarm ~ .) + geom_line() I get this.... Notice that it's facetted according to Alarm and that the facets are arranged alphabetically. Two Questions: How can I can I keep it facetted by alarm but displayed in the correct order? (Rank asc, Alarm asc). Also, how can I keep it facetted by alarm but show labels from Rank instead of Alarm? Note that I can't just facet on Rank because ggplot2 would see only 3 facets to plot where there are really 4 different alarms. Thanks kindly for the help! Tommy

    Read the article

  • [R] Merge multiple data frames - Error in match.names(clabs, names(xi)) : names do not match previou

    - by Jasmine
    Hi all- I'm getting some really bizarre stuff while trying to merge multiple data frames. Help! I need to merge a bunch of data frames by the columns 'RID' and 'VISCODE'. Here is an example of what it looks like: d1 = data.frame(ID = sample(9, 1:100), RID = c(2, 5, 7, 9, 12), VISCODE = rep('bl', 5), value1 = rep(16, 5)) d2 = data.frame(ID = sample(9, 1:100), RID = c(2, 2, 2, 5, 5, 5, 7, 7, 7), VISCODE = rep(c('bl', 'm06', 'm12'), 3), value2 = rep(100, 9)) d3 = data.frame(ID = sample(9, 1:100), RID = c(2, 2, 2, 5, 5, 5, 9,9,9), VISCODE = rep(c('bl', 'm06', 'm12'), 3), value3 = rep("a", 9), values3.5 = rep("c", 9)) d4 = data.frame(ID =sample(8, 1:100), RID = c(2, 2, 5, 5, 5, 7, 7, 7, 9), VISCODE = c(c('bl', 'm12'), rep(c('bl', 'm06', 'm12'), 2), 'bl'), value4 = rep("b", 9)) dataList = list(d1, d2, d3, d4) I looked at the answers to the question titled "Merge several data.frames into one data.frame with a loop." I used the reduce method suggested there as well as a loop I wrote: try1 = mymerge(dataList) try2 <- Reduce(function(x, y) merge(x, y, all= TRUE, by=c("RID", "VISCODE")), dataList, accumulate=F) where dataList is a list of data frames and mymerge is: mymerge = function(dataList){ L = length(dataList) mdat = dataList[[1]] for(i in 2:L){ mdat = merge(mdat, dataList[[i]], by.x = c("RID", "VISCODE"), by.y = c("RID", "VISCODE"), all = TRUE) } mdat } For my test data and subsets of my real data, both of these work fine and produce exactly the same results. However, when I use larger subsets of my data, they both break down and give me the following error: Error in match.names(clabs, names(xi)) : names do not match previous names. The really weird thing is that using this works: dataList = list(demog[1:50,], neurobat[1:50,], apoe[1:50,], mmse[1:50,], faq[1:47, ]) And using this fails: dataList = list(demog[1:50,], neurobat[1:50,], apoe[1:50,], mmse[1:50,], faq[1:48, ]) As far as I can tell, there is nothing special about row 48 of faq. Likewise, using this works: dataList = list(demog[1:50,], neurobat[1:50,], apoe[1:50,], mmse[1:50,], pdx[1:47, ]) And using this fails: dataList = list(demog[1:50,], neurobat[1:50,], apoe[1:50,], mmse[1:50,], pdx[1:48, ]) Row 48 in faq and row 48 in pdx have the same values for RID and VISCODE, the same value for EXAMDATE (something I'm not matching on) and different values for ID (another thing I'm not matching on). Besides the matching RID and VISCODE, I see anything special about them. They don't share any other variable names. This same scenario occurs elsewhere in the data without problems. To add icing on the complication cake, this doesn't even work: dataList = list(demog[1:50,], neurobat[1:50,], apoe[1:50,], mmse[1:50,], faq[1:48, 2:3]) where columns 2 and 3 are "RID" and "VISCODE". 48 isn't even the magic number because this works: dataList = list(demog[1:500,], neurobat[1:500,], apoe[1:500,], mmse[1:457,]) while using mmse[1:458, ] fails. I can't seem to come up with test data that causes the problem. Has anyone had this problem before? Any better ideas on how to merge? Thanks for your help! Jasmine

    Read the article

  • Blackjack game reshuffling problem-edited

    - by Jam
    I am trying to make a blackjack game where before each new round, the program checks to make sure that the deck has 7 cards per player. And if it doesn't, the deck clears, repopulates, and reshuffles. I have most of the problem down, but for some reason at the start of every deal it reshuffles the deck more than once, and I can't figure out why. Help, please. Here's what I have so far: (P.S. the imported cards and games modules aren't part of the problem, I'm fairly sure my problem lies in the deal() function of my BJ_Deck class.) import cards, games class BJ_Card(cards.Card): """ A Blackjack Card. """ ACE_VALUE = 1 def get_value(self): if self.is_face_up: value = BJ_Card.RANKS.index(self.rank) + 1 if value > 10: value = 10 else: value = None return value value = property(get_value) class BJ_Deck(cards.Deck): """ A Blackjack Deck. """ def populate(self): for suit in BJ_Card.SUITS: for rank in BJ_Card.RANKS: self.cards.append(BJ_Card(rank, suit)) def deal(self, hands, per_hand=1): for rounds in range(per_hand): if len(self.cards)>=7*(len(hands)): print "Reshuffling the deck." self.cards=[] self.populate() self.shuffle() for hand in hands: top_card=self.cards[0] self.give(top_card, hand) class BJ_Hand(cards.Hand): """ A Blackjack Hand. """ def __init__(self, name): super(BJ_Hand, self).__init__() self.name = name def __str__(self): rep = self.name + ":\t" + super(BJ_Hand, self).__str__() if self.total: rep += "(" + str(self.total) + ")" return rep def get_total(self): # if a card in the hand has value of None, then total is None for card in self.cards: if not card.value: return None # add up card values, treat each Ace as 1 total = 0 for card in self.cards: total += card.value # determine if hand contains an Ace contains_ace = False for card in self.cards: if card.value == BJ_Card.ACE_VALUE: contains_ace = True # if hand contains Ace and total is low enough, treat Ace as 11 if contains_ace and total <= 11: # add only 10 since we've already added 1 for the Ace total += 10 return total total = property(get_total) def is_busted(self): return self.total > 21 class BJ_Player(BJ_Hand): """ A Blackjack Player. """ def is_hitting(self): response = games.ask_yes_no("\n" + self.name + ", do you want a hit? (Y/N): ") return response == "y" def bust(self): print self.name, "busts." self.lose() def lose(self): print self.name, "loses." def win(self): print self.name, "wins." def push(self): print self.name, "pushes." class BJ_Dealer(BJ_Hand): """ A Blackjack Dealer. """ def is_hitting(self): return self.total < 17 def bust(self): print self.name, "busts." def flip_first_card(self): first_card = self.cards[0] first_card.flip() class BJ_Game(object): """ A Blackjack Game. """ def __init__(self, names): self.players = [] for name in names: player = BJ_Player(name) self.players.append(player) self.dealer = BJ_Dealer("Dealer") self.deck = BJ_Deck() self.deck.populate() self.deck.shuffle() def get_still_playing(self): remaining = [] for player in self.players: if not player.is_busted(): remaining.append(player) return remaining # list of players still playing (not busted) this round still_playing = property(get_still_playing) def __additional_cards(self, player): while not player.is_busted() and player.is_hitting(): self.deck.deal([player]) print player if player.is_busted(): player.bust() def play(self): # deal initial 2 cards to everyone self.deck.deal(self.players + [self.dealer], per_hand = 2) self.dealer.flip_first_card() # hide dealer's first card for player in self.players: print player print self.dealer # deal additional cards to players for player in self.players: self.__additional_cards(player) self.dealer.flip_first_card() # reveal dealer's first if not self.still_playing: # since all players have busted, just show the dealer's hand print self.dealer else: # deal additional cards to dealer print self.dealer self.__additional_cards(self.dealer) if self.dealer.is_busted(): # everyone still playing wins for player in self.still_playing: player.win() else: # compare each player still playing to dealer for player in self.still_playing: if player.total > self.dealer.total: player.win() elif player.total < self.dealer.total: player.lose() else: player.push() # remove everyone's cards for player in self.players: player.clear() self.dealer.clear() def main(): print "\t\tWelcome to Blackjack!\n" names = [] number = games.ask_number("How many players? (1 - 7): ", low = 1, high = 8) for i in range(number): name = raw_input("Enter player name: ") names.append(name) print game = BJ_Game(names) again = None while again != "n": game.play() again = games.ask_yes_no("\nDo you want to play again?: ") main() raw_input("\n\nPress the enter key to exit.") Since someone decided to call this 'psychic-debugging', I'll go ahead and tell you what the modules are then. Here's the cards module: class Card(object): """ A playing card. """ RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"] SUITS = ["c", "d", "h", "s"] def __init__(self, rank, suit, face_up = True): self.rank = rank self.suit = suit self.is_face_up = face_up def __str__(self): if self.is_face_up: rep = self.rank + self.suit else: rep = "XX" return rep def flip(self): self.is_face_up = not self.is_face_up class Hand(object): """ A hand of playing cards. """ def init(self): self.cards = [] def __str__(self): if self.cards: rep = "" for card in self.cards: rep += str(card) + "\t" else: rep = "<empty>" return rep def clear(self): self.cards = [] def add(self, card): self.cards.append(card) def give(self, card, other_hand): self.cards.remove(card) other_hand.add(card) class Deck(Hand): """ A deck of playing cards. """ def populate(self): for suit in Card.SUITS: for rank in Card.RANKS: self.add(Card(rank, suit)) def shuffle(self): import random random.shuffle(self.cards) def deal(self, hands, per_hand = 1): for rounds in range(per_hand): for hand in hands: if self.cards: top_card = self.cards[0] self.give(top_card, hand) else: print "Can't continue deal. Out of cards!" if name == "main": print "This is a module with classes for playing cards." raw_input("\n\nPress the enter key to exit.") And here's the games module: class Player(object): """ A player for a game. """ def __init__(self, name, score = 0): self.name = name self.score = score def __str__(self): rep = self.name + ":\t" + str(self.score) return rep def ask_yes_no(question): """Ask a yes or no question.""" response = None while response not in ("y", "n"): response = raw_input(question).lower() return response def ask_number(question, low, high): """Ask for a number within a range.""" response = None while response not in range(low, high): response = int(raw_input(question)) return response if name == "main": print "You ran this module directly (and did not 'import' it)." raw_input("\n\nPress the enter key to exit.")

    Read the article

  • Writing reports with Perl

    - by georgemp
    Hi, I am trying to write out multiple report files using perl. Each file has the same structure, but with different data. So, my basic code looks something like #begin code our $log_fh; open %log_fh, ">" . $logfile our $rep; if (multipleReports) { while (@reports) { printReport($report[0]); } } sub printReports { open $rep, ">" . $[0]; printHeaders(); printBody(); close $rep; } sub printHeader() { format HDR = @>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> $generatedLine . format HDR_TOP = . $rep->format_name("HDR"); $rep->format_top_name("HDR_TOP"); $generatedLine = "test"; write($rep); $generatedLine = "next item"; write($rep); $generatedLine = "last header item"; write($rep); } sub printBody #There are multiple such sections in my code. For simplicity, I have just shown 1 here { #declare own header and header top. Set report to use these and print items to $rep } #end code The above is just a high level of the code I am using and I hope I have captured all the salient points. However, for some reason, I get the first report file output correctly. The second file instead of having in the first section test next item last item reads last item last item last item I have tried a whole lot of options primarily around autoflush, but, for the life of me can't figure out why it is doing this. I am using Perl 5.8.2. Any help/pointers much appreciated. Thanks George

    Read the article

  • Can one instance of a WCF service pass work on to another instance where this 2nd instance would rep

    - by Matt
    Let's say I have 2 instances of the same web services. Is there a way that I can have the second instance of the web service perform a task at the behest of the first instance of the WCF service and reply directly to the original requester? I could code this and include logic in WCF-A to contact WCF-B under the right conditions and then passback the result, but returning to the requester directly from WCF-B would be easier. Also, I made a handy dandy chart.

    Read the article

  • How to obtain a random sub-datatable from another data table

    - by developerit
    Introduction In this article, I’ll show how to get a random subset of data from a DataTable. This is useful when you already have queries that are filtered correctly but returns all the rows. Analysis I came across this situation when I wanted to display a random tag cloud. I already had the query to get the keywords ordered by number of clicks and I wanted to created a tag cloud. Tags that are the most popular should have more chance to get picked and should be displayed larger than less popular ones. Implementation In this code snippet, there is everything you need. ' Min size, in pixel for the tag Private Const MIN_FONT_SIZE As Integer = 9 ' Max size, in pixel for the tag Private Const MAX_FONT_SIZE As Integer = 14 ' Basic function that retreives Tags from a DataBase Public Shared Function GetTags() As MediasTagsDataTable ' Simple call to the TableAdapter, to get the Tags ordered by number of clicks Dim dt As MediasTagsDataTable = taMediasTags.GetDataValide ' If the query returned no result, return an empty DataTable If dt Is Nothing OrElse dt.Rows.Count < 1 Then Return New MediasTagsDataTable End If ' Set the font-size of the group of data ' We are dividing our results into sub set, according to their number of clicks ' Example: 10 results -> [0,2] will get font size 9, [3,5] will get font size 10, [6,8] wil get 11, ... ' This is the number of elements in one group Dim groupLenth As Integer = CType(Math.Floor(dt.Rows.Count / (MAX_FONT_SIZE - MIN_FONT_SIZE)), Integer) ' Counter of elements in the same group Dim counter As Integer = 0 ' Counter of groups Dim groupCounter As Integer = 0 ' Loop througt the list For Each row As MediasTagsRow In dt ' Set the font-size in a custom column row.c_FontSize = MIN_FONT_SIZE + groupCounter ' Increment the counter counter += 1 ' If the group counter is less than the counter If groupLenth <= counter Then ' Start a new group counter = 0 groupCounter += 1 End If Next ' Return the new DataTable with font-size Return dt End Function ' Function that generate the random sub set Public Shared Function GetRandomSampleTags(ByVal KeyCount As Integer) As MediasTagsDataTable ' Get the data Dim dt As MediasTagsDataTable = GetTags() ' Create a new DataTable that will contains the random set Dim rep As MediasTagsDataTable = New MediasTagsDataTable ' Count the number of row in the new DataTable Dim count As Integer = 0 ' Random number generator Dim rand As New Random() While count < KeyCount Randomize() ' Pick a random row Dim r As Integer = rand.Next(0, dt.Rows.Count - 1) Dim tmpRow As MediasTagsRow = dt(r) ' Import it into the new DataTable rep.ImportRow(tmpRow) ' Remove it from the old one, to be sure not to pick it again dt.Rows.RemoveAt(r) ' Increment the counter count += 1 End While ' Return the new sub set Return rep End Function Pro’s This method is good because it doesn’t require much work to get it work fast. It is a good concept when you are working with small tables, let says less than 100 records. Con’s If you have more than 100 records, out of memory exception may occur since we are coping and duplicating rows. I would consider using a stored procedure instead.

    Read the article

  • Crystal Report with Error : A number range is required here.

    - by gofor.net
    Hi Everyone, I am using the crystal report, in that i am using code like below to show the SQL data into the crystal report, string req = "{View_EODPumpTest.ROId} IN " + str + " AND " + "({View_EODPumpTest.RecordCreatedDate}>=date(" + fromDate.Year + " , " + fromDate.Month + " , " + fromDate.Day + ")" + "AND" + "{View_EODPumpTest.RecordCreatedDate}<=date(" + toDate.Year + " , " + toDate.Month + " ," + toDate.Day + " ))"; ReportDocument rep = new ReportDocument(); rep.Load(Server.MapPath("PumpTestReport.rpt")); DateTime fromDate = DateTime.Parse(Request.QueryString["fDate"].ToString()); DateTime toDate = DateTime.Parse(Request.QueryString["tDate"].ToString()); CrystalReportViewer_PumpTest.ReportSource = rep; //CrystalReportViewer1.SelectionFormula = str; rep.RecordSelectionFormula = str; CrystalDecisions.CrystalReports.Engine.TextObject from = ((CrystalDecisions.CrystalReports.Engine.TextObject)rep.ReportDefinition.ReportObjects["txtFrom"]); from.Text = fromDate.ToShortDateString(); CrystalDecisions.CrystalReports.Engine.TextObject to = ((CrystalDecisions.CrystalReports.Engine.TextObject)rep.ReportDefinition.ReportObjects["txtTO"]); to.Text = toDate.ToShortDateString(); //Session["Repo"] = rep; CrystalReportViewer_PumpTest.RefreshReport(); after running my application it executes fine with no exception but such error i am getting, A number range is required here. Error in File C:\DOCUME~1\Delmon\LOCALS~1\Temp\PumpTestReport {14E557A7-51B3-4791-9C78-B6FBAFFBD87C}.rpt: Error in formula . '{View_EODPumpTest.ROId} IN ['15739410','13465410'] AND ({View_EODPumpTest.RecordCreatedDate}>=date(2010 , 12 , 1)AND{View_EODPumpTest.RecordCreatedDate}<=date(2010 , 12 ,25 ))' A number range is required here. error. what i will do for this? Please help, Thanks in advance

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >