Posts

Showing posts from May, 2013

sql - How to use a psql variable in the middle of other characters? -

i wondering if possible use variable in middle of other characters in sql statement psql. for example: psql -v x=apple -f "example.sql" with example.sql being: select * :x; works fine. it's executed as: select * apple; but how handle situation example.sql like: select * red_:x_pie; i want psql read "red_apple_pie" syntax error on ":" instead. thanks. you'll have use string concatenation: declare x text; begin x = 'apple'; select * "food" "name" = 'red_' || x || '_pie'; i used example because it's simpler understand (table names have enclosed in quotes).

sql server - Average of Most Recent 100 SQL Database Entries -

select dc_grp.dc_grp, dc_grpx.reqt_id, avg(results.[var]) average, stdev(results.[var]) stddev results inner join... currently pulling of var fields out of results, need recent 100. how can call recent 100 within avg( ) call? assuming have column define recent, can subquery: select dc_grp.dc_grp, dc_grpx.reqt_id, avg(r.[var]) average, stdev(r.[var]) stddev (select top 100 * results order createdat desc) r inner join... this example assumes name of column createdat .

ubuntu - MySQL Replication was working, now broken -

so month+ ago setup replication 1 of web servers m local lan servers. had 2 local lan servers slaves (quad , hex) master web server (falcon). weeks replication worked without issue. then noticed earlier week i/o thread wasn't running on either quad or hex. restarted them on , on , on again because every run normally, @ least 1 of slave, several minutes. i/o thread stop working again. have attempted reconfigure master on both lan machines via phpmyadmin , phpmyadmin reports slave connected master. phpmyadmin gives me option (that wasn't yesterday) of synchronizing slave dbs master's. run , in few seconds page stops loading no response (error or otherwise) given. all of machines involved running lamp stack on ubuntu 12.04. web server 12.04 server while lan machines both 12.04 desktop. suspected had run apt-get update/upgrade on lan machines while neglecting on falcon. ran on 3 machines morning. still i/o thread won't run. the sql thread running. occasionally, ma

r - Diagonal Label layout -

i'm sending 3 graphs pdf file on same page. x axis labels, despite having same y coordinates in code, @ different heights. how fix it? here example: pdf("data_output.pdf", height = 8.5, width = 14) graph.frame <- cbind(c(1,2,3,4),c(5,6,7,8),c(9,10,2,2)) par(mfrow = c(1,3), mar = c(7.6, 4.1, 6.1, 2.1)) colnames(graph.frame) <- c("oneoneone", "twotwotwo", "threethreethree") labels <- colnames(graph.frame) temp1 <- barplot(graph.frame[1,], ylab = "aaa", col = terrain.colors(3), xaxt = "n") temp2 <- temp1[1:length(labels)] text(temp2, par("usr")[3] - 0.35, srt = 45, adj = 1, labels = labels, xpd = true) box() temp1 <- barplot(graph.frame[2,], main = "title", ylab = "bbb", col = terrain.colors(3), xaxt = "n") temp2 <- temp1[1:length(labels)] text(temp2, par("usr")[3] - 0.35, srt = 45, adj = 1, labels = labels, xpd = true)

c - Run 3 parallel threads in a single core machine -

i have question ask. have program (process 1) has 3 threads: thread 1 runs continuously, receives packets lock socket (af_unix, non_block) , copies them buffer. thread 2 reads buffer , writes information received file (disk). thread 3 compresses file if file grows larger 5 mb there process (process 2) continuously sending packets local socket read process 1. number of packets (of around 100 bytes) sent per second can high 3000-5000 packets per second. setup runs on embedded hardware arm v9 controller. i have ensure none of packets lost , of them written disk. current implementation, receive sending errors @ process 2 "sendto" (resource unavailable) every , then. i disable locks , mutexes avoiding race conditions (remove checks prevent write while read , vice-versa), sending errors "sendto". then in second step, disable writing disk. now, thread 1 of process 1 can read fast possible local socket , there no sending error. guess since threads running

Facebook Graph API & django-facebook - posting links and photos to page feeds -

@facebook_required_lazy(scope=['manage_pages', 'publish_stream', 'photo_upload']) def index(request): if request.method == 'post': form = cpyposterform(request.post) if form.is_valid(): fb = require_persistent_graph(request) msg = form.cleaned_data['msg'] pages = form.cleaned_data['pages'] res = dict() p in pages: try: key = page_choices[p] except keyerror: key = p res[key] = fb.set('{page_id}/feed'.format(page_id=p), message=msg) i'm trying post feeds of multiple pages. when post simple text, no problem. however, when attempt upload photo or link, item posted feed, it's "recent posts others" section , not page feed itself. it gets posted me , not page. there need special post item in pages feed (as page) link and/or photo? faceb

java - Cant understand why this doesn't print to the text file -

im coding hotel reservation program , im using gui input guests info textfields. have array these input values should go straight (maybe thats problem, donno how fix it). after want values in array print text file had created. heres code: guests[] garr = new guests[1000]; public static dateformat dateformat = new simpledateformat("dd/mm/yyyy hh:mm"); public int cnt = 1; int count = 0; string firstname ; string lastname; string country ; string idtype; string passportno ; string idno ; string addr1; string addr2 ; int areacode ; string telno ; string cellno ; string email ; first have declared these variables global (these variables in object class guests ) put them again in jframe class called home . after have made these variables take value of textfields have text input them. within method checks see if fields blank: public collection<string> getnonblankfields() { this.firstname = namef.gettext(); this.l

python - Constrain wxPython MultiSplitterWindow panes -

edit: i'm leaving question open is, it's still question , answer may useful others. however, i'll note found actual solution my issue using different approach auimanager ; see answer below. i'm working on multisplitterwindow setup (after spending deal of time struggling against sashlayoutwindow layout quirks). unfortunately, when create multisplitterwindow , see unexpected behavior when dragging sashes around: sashes can dragged outside containing window in direction of layout. least, behavior i'd avoid. here basic setup (you can confirm behavior below in wxpython demo, substituting leftwin panel1 , etc., see below example app). have rootpanel/boxsizer , there panel (or frame , or whatever kind of container element like) boxsizer multisplitterwindow added – again, in demo. +--------------------------------+ | rootpanel/boxsizer | |+------------------------------+| || multisplitterwindow || ||+--------++--------++--------+|| |||

Storing Pandas objects along with regular Python objects in HDF5 -

pandas has nice interface facilitates storing things dataframes , series in hdf5: random_matrix = np.random.random_integers(0,10, m_size) my_dataframe = pd.dataframe(random_matrix) store = pd.hdfstore('some_file.h5',complevel=9, complib='bzip2') store['my_dataframe'] = my_dataframe store.close() but if try save other regular python objects in same file, complains: my_dictionary = dict() my_dictionary['a'] = 2 # <--- error my_dictionary['b'] = [2,3,4] store['my_dictionary'] = my_dictionary store.close() with typeerror: cannot create storer for: [_type_map] [group->/par ameters (group) u'',value-><type 'dict'>,table->none,append->false,kwargs- >{}] how can store regular python data structures in same hdf5 store other pandas objects ? here's example cookbook: http://pandas.pydata.org/pandas-do

ios - ModalUIview, not dismiss but transition / fade into ViewController -

i have uiview display modally, view hosts imageview , trying create vehavior when user clicks on button ( select ) instead of dimissing modal window fade in ( transition ) modal window viewcontroller , , make image background of parent viewcontroller , couldn't find quite behavior online. any ideas? set custom hide , show methods view. this: - (void)show:(bool)animated { if (animated) { __weak storymetadataview * blockself = self; [uiview animatewithduration:kshowhideduration animations:^{ blockself.alpha = 1.0; } completion:^(bool finished) { }]; } else { self.alpha = 1.0; } } - (void)hide:(bool)animated { if (animated) { __weak storymetadataview * blockself = self; [uiview animatewithduration:kshowhideduration animations:^{ blockself.alpha = 0.0; } completion:^(bool finished) { [blockself removefromsuperview]; }]; } else {

Is there a way to create a constraint that prevents updates in a SQL Server 2012 database table? -

i creating application track hours employees. ideally, hr has asked tables not modified once data commited. done enough front-end , stored procedures. however, great able prevent server through constraints folks have access back-end data can't change values in selected tables (unless sneaky enough know how disable constraints). if trust sql server admins it’s possible. have admin create users don’t have datawriter permissions tables or schema. so, application write data database , users have access tables able read data. if don’t want admins have ability modify data that’s not possible. there no way prevent there way detect if happens. check out this article details on details how done in third party application , see if helps.

Git diff doesn't ignore specified files in .gitignore -

i'm new git , have no idea i'm doing wrong. want run git diff --name-only want exclude files ending in .test meaning if these haves have changed, don't want git diff output it's changed. tried add these file .gitignore files did include .gitignore when run git diff command! what doing wrong , how exclude files when run git diff? okay, did wrong. git continue track files because started tracking them earlier in project. @ point earlier did run initial commit looked like: git add . # added tracking system including .test files git commit -a -m 'i committed in project .test files included' putting things gitignore file keep future files create end in .test entering project, need remove .test files told git track git's memory. putting things in gitignore not preform action tracked files. need this: option 1: # can remove files gits tracking system , put them # when go put them git have no memory of tracking these # , consider future e

javascript - In .md file: How to add background color to a text? or Put text in a colored box? -

i want add background color text below in .md file. how can that? like randomw text you. randomw text you. randomw text you.like randomw text you. i believe backticks produce inline <code> (or <pre> maybe) tag when compiled. style particular tag.

performance - Issue with EF 4.1 Pre-Compiled View Generation -

Image
i have entity framework 4.1 dbcontext based model. using pocomodelgenerator.tt file generate entities. found querying 20,000 row sql table takes around 5 seconds code locally. takes less second when done directly in sql. in order boost performance, followed approach in link below generate pre-compiled views: http://blogs.msdn.com/b/adonet/archive/2008/06/20/how-to-use-a-t4-template-for-view-generation.aspx but performance didn't improve @ all. it's tad bit slower when running 2nd or 3rd time. here's project structure have: here properties generated materialsmodel.views.cs file: i have following questions: any idea can issue here? how check generated materialsmodel.views.cs being compiled output assembly. how check generated views indeed being used code? are properties setup correctly? well answer 3rd simple: edit view class , comment call methods. run code, should through exception.

unit testing - Fluent NHibernate PersistenceSpecification not-null property references a null or transient value error -

i've been struggling mess days now, trying figure out exact reason error. 1 word, failure! have been trying unit test classmap i've written reference references reference . [testmethod] public void issuereturnregistermap_create_success() { var maxdifference = timespan.frommilliseconds(990); booksize sz = new booksize() { id = "1", name = "a" }; department dpt = new department() { id = "1", name = "philosophy" }; author auth = new author() { id = "2", firstname = "wise", lastname = "person" }; publisher pub = new publisher() { id = "1", name = "pub1", address = "address 1" }; language lang = new language() { id = "1", name = "lang1" }; patron ptrn = new patron() { id = "1", firstname = "first", lastname = "last",

html - How to align a speech bubble with an image -

i'm trying align speech bubble image looks if character trying something. i understand won't perfect fluid , not absolute looks kind of same on big screen monitors , laptop monitors well. i've added margin-left: 205px; doesn't seem cut it.. example: http://jsfiddle.net/fuway/1/ you might better off setting speech bubble display: relative; , controlling top , left properties position bubble want on image: <blockquote class="oval-thought" style="position: relative; top: 250px; left: 150px;"><p>yay</p></blockquote> <img src="http://th00.deviantart.net/fs70/pre/f/2010/310/7/4/super_sonic_sa2_by_mephilez-d329bcu.png" height="600" width="400"/>

ruby on rails 3.2 - bootstrap nav tabs with will_paginate pagination in each tab -

when put will_paginate paginated lists twitter bootstrap tabs. lists them way out pagination links in between. i'm using will_paginate-bootstrap style pagination. i tried without making tabs work: taking out pagination styling removing pagination blocks if remove ruby tabs work, they're working independently <div class="tabbable"> <ul class="nav nav-tabs"> <li class="active"><a href="#a" data-toggle="tab">newest</a></li> <li><a href="#b" data-toggle="tab">activity</a></li> </ul> <div class="tab-content"> <div class="tab-pane active" id="a"> <%= render partial: "posts/post", collection: @posts, as: :post %> <%= will_paginate @posts, renderer: bootstrappagination::rails %> </div> <div class="tab-pane" id="b&

postgresql - How do I minimize round-trips to SQL with user-based authorization? -

context: mvc web service backed sql db. have user relation in database, , set of relations reference through chain of fks. example let's have table: sales_people car_dealership cars where sales person belongs car dealership, , cars. sales people should able see cars belong specific dealership. have few options here: i can bake authorization business logic sql query itself: select * cars c, sales_people sp, car_dealerships cd where c.dealership_id = cd.id , sp.dealership_id = cd.id , sp.id = ? , c.id = ? assuming caller has verified sales_people id legit , prevents trivial spoofing of id, query above prevent user getting hold of cars aren't his. extended arbitrary # of tables long join isn't massive. upside? 1 single db call. downside? the authorization business logic here basic. user referenced 1 of tables? sure, can pass. let's have have more complex access rules. it's might not doable 1 simple query. it's hard tell if user requested unaut

ggplot2 - How to Specify Columns when a user chooses a file to upload in R? -

i writing r file prompts user upload file , plots data in file user uploads. not know how reference columns (i trying use ggplot2) in code. the data user upload csv file like, can vary: january february march april may burgers 4 5 3 5 2 i stuck @ ggplot2 part need reference column names. server.r library(shiny) library(datasets) library(ggplot2) x <- read.csv(file.choose()) # define server logic required summarize , view selected dataset shinyserver(function(input, output) { # generate summary of dataset output$summary <- renderprint({ dataset <- x summary(dataset) }) # show first "n" observations output$view <- rendertable({ head(x, n = input$obs) }) # create line plot (i took https://gist.github.com/pssguy/4171750) output$plot <- reactiveplot(function() { print(ggplot(x, aes(x=date,y=count,group=name,colour=name))+ geom_line()+ylab("")+xlab("&quo

fortran - How to control lapack solver presion -

i'm trying use lapack zhesv subroutine in fortran solve linear system, precision seems not good. here code: program main implicit none integer,parameter::n=4 integer::lda=n,ipiv(n),ldb=n,lwork=n*n,info,i complex*16::a(n,n),b(n),work(n,n),x(n) a=reshape( (/(1.,0.),(0.,0.),(0.,-6.94908e-13),(0.,-6.94908e-13),& &(0.,0.),(1.,0.0352595),(0.,-4.51893e-11),(0.,-4.51893e-11),& &(0.,-6.94908e-13),(0.,-4.51893e-11),(1.,0.0376938),(0.,0.),& &(0.,-6.94908e-13),(0.,-4.51893e-11),(0.,0.),(1.,0.0378932)/),shape(a)) a=transpose(a) b=(/(1.,0.),(0.,0.),(0.,6.94908e-13),(0.,6.94908e-13)/) x=b write(*,*) "--------------b----------------" write(*,99999) b call zhesv('upper',n,1,a,lda,ipiv,x,n,work,lwork,info) write(*,*) "--------------x----------------" write(*,99999) x write(*,*) "-------------info--------------" write(*,*) info write(*,*) "-------------error-------------" write(*,9

Python adding an exception (edited) -

this simple program working on learn python because beginner. how add exception if user types other y,y,n,n. have searched everywhere can't seem find exception use? everyone's help. edit:i adjusted code. thing not working if(welcomestring.strip().lower() != 'n' or 'y'): welcomestring = input('not valid choice\nwould reverse string?(y/n):'). not realize user types in y or n. works other letters though. edit2: working expected until user types in invalid input second time. first time "not valid choice", second time, program exit out. import sys welcomestring = input('welcome string reverser\nwould reverse string?(y/n)') if not welcomestring.strip().lower() in ['n','y']: welcomestring = input('not valid choice\nwould reverse string?(y/n):') if welcomestring.strip().lower() == 'n': print("thanks using string reverser") while welcomestring.strip().lower() == 'y':

c# - get treenode under cursor -

basically have treeview populated numerous image files. trying make nodemousehover event bring little preview of image. need find out node mouse over, cannot work, unable find tree node @ cursor position. here simplified version code private void treebroswer_nodemousehover(object sender, treenodemousehovereventargs e) { string filepath; picturebox preview; treenode test = treebroswer.getnodeat(cursor.position.x, cursor.position.y); //also tried mouseposition.x,mouseposition.y if (test == null) { messagebox.show("no tree node"); } else { filepath = test.fullpath; preview = new picturebox(); preview.imagelocation = @filepath; // display preview } } it fails tree node no matter mouse is. not sure if getting mouse position wrong or i'm using getnodeat wrong, or both. the parameter event - treenodemousehove

ruby on rails - Heroku and Emberjs Rails4 deployment -

the case pretty simple describe. gem file gem 'ember-rails' gem 'ember-source', '1.0.0.rc6.2' gem 'handlebars-source', '~> 1.0.12' this application.js file //= require jquery //= require jquery_ujs //= require foundation //= require handlebars //= require ember //= require ember-data //= require_self //= require q this have in development.rb , production.rb config.ember.variant = :development config.ember.variant = :production i tested in production environment locally, worked fine. when push heroku, have following error, can't figure out problem -----> preparing app rails asset pipeline running: rake assets:precompile rake aborted! couldn't find file 'handlebars' (in /tmp/build_2ddhwlktd9evz/app/assets/javascripts/application.js:17) i forgot mention using rails4 try following in gemfile: gem 'ember-rails' gem 'ember-source', '1.0.0.rc6' gem 'handlebar

javascript - jQuery animate table-cell -

i trying animate a tag, has css property of table-cell effect looking for. looking animate when clicks on using jquery, isn't working, , think because of table-cell removing table-cell breaks layout. here page working with . here fiddle: http://jsfiddle.net/neryb/ .clip{ background-color: #373938; min-height: 100%; height: 100%; width: 300px; background-position: center center; background-size: auto 100%; background-repeat: no-repeat; display: table-cell; box-shadow: -2px 0 5px rgba(0,0,0,.2), -2px -2px 5px rgba(0,0,0,.2), -2px 2px 5px rgba(0,0,0,.2); text-align: center; filter: grayscale(100%); filter: url(/media/images/new/filters.svg#grayscale); filter: gray; -webkit-filter: grayscale(1); position: relative; } here jquery: $(document).on("click", "a.clip", function(e){ e.preventdefault(); window.history.pushstate("gallery", "gallery", $(this).attr("hre

c# - CheckedListBox throwing argument out of range when it shouldn't -

this .net 3.5 winforms project. i'm having weird error trying programmatically check checkboxes in checkboxlist. for (int = 0; < 5; i++) { cblistforming.items.add((i + 1).tostring()); cblistforming.setitemchecked(i, true); } so adds 5 items, 1 5, , have added checkboxes checked default. nothing surprising. on first iteration of loop, works fine on second iteration (i == 1), setitemchecked throws exception. system.argumentoutofrange {"index out of range. must non-negative , less size of collection.\r\nparameter name: index"} i can see first checkbox checked visually well. rest of them aren't because of above exception. this pretty baffling. testing purposes, tried add items first, , programmatically check them later second loop, still same issue happens, even though count of checkbox 5. i tried using setitemcheckstate instead. again, same issue. i think might've broken checkedlistbox component itself, or weird framework bug

.net - Can webapp in virtual machine access a cache role in azure? -

the question simple. i've got website deployed on azure's virtual machine, there's dedicated cache role deployed on cloud service. question is, how can make website in virtual machine access dedicated cache role? please give me instructions go or advice articles. thx lot! you can't. viable solution accessing caching same cloud service (same role or role). question why using vm deploy web application in azure?

sqlite - Phonegap/Cordova 3 Storage questions -

i've finished reading documentation here: http://docs.phonegap.com/en/edge/cordova_storage_storage.md.html#storage , and have numerous questions can't find answers to: what, if any, size limits creating new sql lite database? (ios , android in particular) where database stored on local machine while i'm developing? how 1 destroy database if it's no longer needed? what, if any, advantages using localstorage on sql lite database? if out i'd obliged! question 2 if you're using mac , simulator through xcode, localstorage / sqlite database stored here; /users/{your name}/library/application support/iphone simulator/{version}/applications/{app id}/library/webkit/localstorage/file__0/0000000000000001.db i recommend sqlite professional through app store - read-only version free. in windows using chrome, databases stored in; c:\users{your name}\appdata\local\google\chrome\user data\default\databases\ c:\documents , sett

How can I do "presets" in Django models -

i create store of products. class product(models.model): name = models.charfield(verbose_name=_(u'name'), max_length=200) quantity = models.integerfield(verbose_name=_(u'quantity')) >>> product.objects.create(name="egg", quantity="100") >>> product.objects.create(name="ham", quantity="10") now want create recipes, like: scrambled eggs 3 eggs , 1 piece of ham. tried describe like: class recipe(models.model): name = models.charfield(verbose_name=_(u'name'), max_length=200) items = models.manytomanyfield('product', related_name='recipe_sets') but stuck in description number of required products 1 recipe . should put quantity in other model? how can calculate number of servings (depending on quantity of product)? there elegant way or application deduction of products (as result of cooking 1 dish)? you're going need table. manytomany create intermed

.net - Problems w/Crystal Reports and 64 Bit machines -

i'm aware question may have been asked before, still haven't found solution. i have .net application (.net 2005) few reports done crystal reports. problem these crystal report print dialogue not pop in 64 bit machines. i have found this link problem not write code pop dialogue box cannot set useexdialog true. have tried service pack , many solutions proposed @ internet still no luck. pl note windows based application. this link suggests installing crystal reports xir2 (or higher) + service packs: http://community.spiceworks.com/topic/130438-windows-7-and-crystal-report-viewer-xi-r2 other links/other suggestions: printdialog.showdialog(); not showing print dialog in windows 7 64 bit print dialog not show in crystal report viewer on 64 bit machine

textbox - asp.net "compare validator" validation -

i trying validate fromdate & todate textboxes in asp.net using compare validator script is: <table><tr><td> <asp:scriptmanager id="scriptmanager1" runat="server"> </asp:scriptmanager> <asp:label id="label1" runat="server" text="fromdate:"> </asp:label> <asp:textbox id="fromdatetxt" runat="server" height="21px" width="103px" ></asp:textbox> <ajaxtoolkit:calendarextender id="fromdatetxt_calendarextender" runat="server" enabled="true" targetcontrolid="fromdatetxt"> </ajaxtoolkit:calendarextender> </td> <td> <asp:label id="label2" runat="server" text="todate:"></asp:label> <asp:textbox id="todatetxt" runat="server" height="2

php - Unable to upload JPEG file in the server -

i trying upload images in php server using html form. have written following code. not creating problem when upload 'png' file, when upload 'jpeg' images says 'invalid file'. kindly check , guid me. thanks <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>untitled document</title> </head> <body> <form action="file_upload_test2.php" method="post" enctype="multipart/form-data"> <label for="file">filename:</label> <input type="file" name="file" id="file"><br> <input type="submit" name="submit" value="submit"> </form> </body> </html> <?php $allowedexts = array("gif", "jpeg", "jpg", "png"); $extension = end(explode(".", $_files["file"]["name"

href - commandlink in JSF not generating the intented HTML tag -

i'm trying call managed bean h:commandlink in jsf. don't see href attribute in rendered html a tag. am missing ? there managedbean called accountsetupcontroller signup method in it. this tag used in jsf: <h:form prependid="false"> <h:commandlink action="#{accountsetupcontroller.signup()}" value="#{msg['homepage.createaccount']}" styleclass="button large"> </h:commandlink> </h:form> this rendered tag. see there nothing in href attribute. <a href="#" onclick="mojarra.jsfcljs(document.getelementbyid('j_idt15'), {'j_idt33':'j_idt33'},'');return false" class="button large">create account</a> this form tag generated <form id="j_idt15" name="j_idt15" method="post" action="/myproject/faces/homepage/homepage.xhtml" enctype="appl

performance - Android APk is not visible in google play -

i first time uploading apk google play, in manifest declared min sdk 14 , targeted version 17. when search apk version 4.0.3 not visible. same app visible other devices. can guide me on why happen. try install app web browser under phone's google account. show reason, why application cannot installed.

How to set datepickerOptions in daterangepicker to set default date -

i want set default date in regional format daterangepicker . having trouble in settting it. click on given link , read it's documentation carefully. http://glad.github.io/gldatepicker/#examples hopefully, able resolve.

ruby - i'm getting error in running rake db:migrate -

i had typed in cmd of ruby on rails command rails generate controller user name:string email:string once created when type in rake db:migrate shows error this: c:\sites\twinkle>rake db:migrate (in c:/sites/twinkle) == createmembers: migrating ================================================== -- create_table(:members) rake aborted! error has occurred, , later migrations canceled: sqlite3::sqlexception: table "members" exists: create table "members" (" id" integer primary key autoincrement not null, "name" varchar(255), "email" var char(255), "created_at" datetime, "updated_at" datetime) what should do? this error means have table called 'members' in database. remove members table , try again. rails can't 'overwrite' table have make new one. you can drop table this: $rails console activerecord::migration.drop_table(:members) now can run ra

javascript - parseFloat.toPreceision just adds zeros -

i'm sending number/string 0.001 function below: significantfigures = 4; function limitnumberofdigits(num) { var tempstr = ""; if (isnan(num)) return "\xd8"; else{ if (parsefloat(num) === 0 || (num.tostring().indexof('.') === -1 && parseint(num) < 9999) || num.tostring().length <= 4) { return num; } tempstr = parsefloat(num).toprecision(significantfigures); if (tempstr.indexof("e") > -1) { var starte = tempstr.indexof("e"); var ende = 0; (var = starte +2 ; < tempstr.length; i++ ) { // + ignore e , sign (+ or - ) if(parseint(tempstr[i], 10) > 0) { ende = i; }else { break; } } if (starte + 2 === ende) { var pow = tempstr[ende]; } else { var pow = tempstr.sub

java - gzip a folder and its subfolders on the fly -

i have big folder want send zipped version of while saving on sub-folders hierarchy. currently i'm doing creating large zip file , sending it. i'm looking way write folder content outputstream redirected socket output stream. my motivation avoid keeping large files in machine on run time i know how single file, have no idea how process folder many sub folders , save inner hierarchy... thanks! it's little unclear you're after, since gzip has no notion of files - bytes compressed - need archive format tar combine bunch of files , directories single stream, , can gzip that. if want compressed archive format, jdk's zipoutputstream let use zip compression. if need gzip format, there number of implementstions of tar output streams out there - use 1 of , pipeline jdk's gzip output stream .

Android Facebook Login erorr in fb sdk3.0 -

when login click on myfblogin avtivity 07-24 13:52:35.960: e/androidruntime(28252): caused by: com.facebook.facebookexception: cannot call loginactivity null calling package. can occur if launchmode of caller singleinstance. how can resolve this. your log shows problem, change launchmode in activity singletop

.htaccess - Duplicate URLs and solution in htaccess -

after years discovered bug in duplication urls try fix (author gone) despite htaccess rule thought should force it. issue: have same content under 2 urls, ex: http://www.wrock.pl/news-23069/depeche_mode_party_w_klubie_liverpool_/ www.wrock.pl/index.php?s=news&d=23069&nazwa=depeche_mode_party_w_klubie_liverpool_ or shorter www.wrock.pl/index.php?s=news&d=23069 another example menu pages: http://www.wrock.pl/koncerty/ www.wrock.pl/index.php?s=koncerty i thought "index.php" version should hidden or redirected friendly url version, meanwhile both show 200/ok index.php gets redirected ok: www.wrock.pl/index.php aim: able show friendly url version (redirect index.php version). google stopped indexing them may issue (one of many reasons). here htaccess responsible presented examples: rewriteengine on rewritecond %{http_host} ^wrock.pl(.*) [nc] rewriterule ^(.*)$ http://www.wrock.pl/$1 [r=301,l] # redirect index.php / rewritecond %{the_request}

how to import dll in c# -

i have .dll , .xml(e.g. farsilibrary.resources.dll ,farsilibrary.resources.xml) use persian calender . how import in project. note: i'm using visual studio 2012. "right click on project -> add reference -> browse..." dll. add existing file xml.

asp.net - Gridview fields values does not change on update -

i have gridview , want modify fields on gridview.this fields value not change when click on update button.i tried use postback control problem keep going.how can solve problem? aspx code <asp:gridview id="gview" runat="server" autogeneratecolumns="false" enablemodelvalidation="true" gridlines="horizontal" onrowdatabound="gview_rowdatabound" onrowediting="gview_rowediting" onrowupdating="gview_rowupdating" onrowcancelingedit="gview_rowcancelingedit"> <columns> <asp:boundfield datafield="subcategoryid" headertext="id" insertvisible="false" readonly="true" sortexpression="subcategoryid" /> <asp:templatefield headertext="category"> <itemtemplate> <asp:label id="lblcategory" runat="server"></asp:label> &

c# - Fit Label size to drawn text -

i'm using label display progress user. occurs many times , partly user-defined text changes every time. problem: should know if drawn text bigger label's size. i tried approach: using (graphics g = lbl.creategraphics()) { sizef size = g.measurestring(lbl.text, lbl.font); // change size of label if small } but slow , uses lot resources when calling @ every update. so there way find out when drawn text bigger label? edit: stated hans passant, autosize it. sorry, didn't other controls below label has move then. it seems there no other way it. have use above solution: using (graphics g = lbl.creategraphics()) { sizef size = g.measurestring(lbl.text, lbl.font); // change size of label if small }

java - how can I get View from another view -

here xml file <framelayout android:layout_alignparentright="true" android:layout_alignparentbottom="true" android:layout_width="wrap_content" android:layout_height="wrap_content" > <button android:id="@+id/button1" style="?android:attr/buttonstylesmall" android:layout_width="50dp" android:layout_height="30dp" android:text="@string/productbutton_download" android:onclick="testgetview" /> <progressbar style="?android:attr/progressbarstylehorizontal" android:layout_width="50dp" android:layout_height="30dp"

indexing - Duplicate key error with mongodb 2dsphere unique index -

i try inserts geo points mongodb 2dsphere unique index, raises many duplicate key error. a simple reproduce demo: > version() 2.4.5 > use geo > db.test.ensureindex( { loc : "2dsphere" }, unique=true ) > db.test.insert({"loc" : { "type" : "point", "coordinates" : [ 113.3736642, 23.04469194 ] }}) > db.test.insert({"loc" : { "type" : "point", "coordinates" : [ 113.3734775, 23.04609556 ] }}) e11000 duplicate key error index: geo.test.$loc_2dsphere dup key: { : "1f22000102222113" } why these totally different points raise duplicate key error? update: i tried other tests, seems have accuracy. > db.test.ensureindex( { loc : "2dsphere" }, unique=true ) > db.test.insert({"loc" : { "type" : "point", "coordinates" : [ 113.373, 23.044 ] }}) > db.test.insert({"loc" : { "type" : "