Posts

Showing posts from July, 2013

ruby on rails - How can I allow the user to download spreadsheets created using axlsx gem -

in controller have code create add content workbook def report p = axlsx::package.new wb = p.workbook wb.add_wordsheet(:name => "viewer summary") |sheet| sheed.add_row["lol"] end end my sheet has lot more stuff added sheet not think necessary type out. in view have button calls above report method in controller. when user clicks button want users browser download spreadsheet. possible axlsx gem? i think method looking send_data http://apidock.com/rails/actioncontroller/streaming/send_data basically this, although i'd consider removing creation , adding data wb own class. def report p = axlsx::package.new wb = p.workbook wb.add_wordsheet(:name => "viewer summary") |sheet| sheet.add_row["lol"] format.xlsx { send_data(wb) } #something similar that. end end

javascript - Angular js ng-repeat not working for server response -

i have response object server this $scope.new = {"module":"a","link":"b"} how use ng-repeat display 2 items? <div ng-repeat="item in new"> {{item}} -- {{item.module}} -- {{item.link}} </div> here's how iterate through each property within object: <div ng-repeat="(key,item) in new"> {{ key }}: {{ item }} </div> note we're using (key,item) instead of item have access key of property. plunker

Java Synchronization callstack -

suppose there synchronized method in turn calls other ordinary methods shown below: public static synchronized void dosomething(){ doit1(); } public doit1(){ doit2(); } my question is, when have above code , call dosomething(), synchronized method, method synchronized, or subsequent methods called, doit1 & doit2, synchronized? my question is, when have above code , when call dosomething() synchronized method method synchronized or subsequent methods call doit1 & doit2 synchronized ? only calls dosomething() synchronized; direct calls doit1() or others not, unless those calls use locking of kind. that is, if call doit1() , jvm won't @ call sites method , see "oh, there synchronized call site method synchronize accesses method well". in short: jvm assumes know doing.

javascript - Angular Uncaught object adding urlRouterProvider -

on config function when pass param ".config(function($urlrouterprovider)" got error uncaught object angular.min.js:6 (anonymous function) angular.min.js:6 (anonymous function) angular.min.js:34 q angular.min.js:7 f angular.min.js:33 cb angular.min.js:37 d angular.min.js:18 fc angular.min.js:18 id angular.min.js:17 (anonymous function) angular.min.js:217 angular.min.js:146 (anonymous function) angular.min.js:31 q angular.min.js:7 de.c angular.min.js:31 i've downloaded lastest version of angular , route module. i think might have forgotten include ng-route module in app. var app = angular.module('yourapp',['ngroute']);

java - Serving different CSS based on user ID - spring mvc -

i have web app developed spring-mvc. every company have admin able edit backgrounds, fonts , colors. app should store color settings( in database or in css file ?) , should use preferred css users belonging same company. different companies see different css. what best approach achieve that: serving different css based on user id. you can try code csscontroller mapping method serving css @requestmapping(value = "/mycustom.css") public @responsebody byte[] getmessages(final httpsession session, final principal principal) { stringbuffer sb = new stringbuffer(""); sb.append("/* css*/"); return sb.tostring().getbytes(charset.forname("iso-8859-1")); } and optionnaly @cacheable if need access db build css.to not have fetch data on every page. and include : <link href="/mycustom.css" rel="stylesheet">

c++ - Practical use of pointer to const -

i understand use of pointer constant strlen implementation. size_t strlen ( const char * str ); can suggest other reasons or provide scenarios 'pointer const value' useful in practice. think of way. want me @ value of variable don't want me alter variable in way, pass me constant. when use function , see parameter constant know there contract between , says should not change value of variable nor can directly. when write code don't know use functions. practice protect code. protects yourself, compiler errors moment tr change value of variable. a side note: true in c can still change value though parameter says const , take pointer alter content of variable in memory. try compiling code , notice how compiler protects making mistake. const char *cookies(const char *s) { return ('\0' == *s)? s: s + 1; } it won't let compile, why? because trying change const variable. another post same question here: const usage pointers in c

python - Django, ModelManager with a query based on model property -

i have models.py: class piecemanager(models.manager): def top_ten(self): # return self.get_queryset().order_by(total_likes) # how can first n-items ordered property total_likes? class piece(models.model): name = models.charfield(max_length=250) description = models.textfield(blank=true, null=true) museum = models.foreignkey(museum, blank=true, null=true) objects = piecemanager() @property def total_likes(self): return self.likes.count() class like(models.model): created_at = models.datetimefield(auto_now_add=true, blank=true, null=true) piece = models.foreignkey(piece, blank=true, null=true, related_name="likes") how can first -items ordered total_likes property? right way that? there better way? thanks. as simple search have shown, can't sort result of property or method. however in case don't need to, since can better , more efficiently aggregation: from django.db.models import

c - Can't find the error in this code. (SIGSEGV) -

i writing method (c - language) should create new node linked list. crashes @ line after first if (sigsegv signal) i debugging method there more errors in subsequent lines, moment appreciate observations regarding particular line. //create new tequivalencenode tequivalencenode* createnewequivalencenode(twordequivalence e){ //create new equivalence node tequivalencenode* node = null; node = (tequivalencenode*) malloc(sizeof(tequivalencenode)); //allocate memory both srcword , dstword twordinfo* destiny = null; twordinfo* source = null; destiny = (twordinfo*) malloc(sizeof(twordinfo)); source = (twordinfo*) malloc(sizeof(twordinfo)); if((node != null)&&(destiny != null) && (source != null)){ node->elem->dstword = destiny; //crashes @ line node->elem->srcword = source; //copy information destiny word in new node node->elem->dstword->languageid = e.dstword->languageid;

CakePHP 2.4.9: using data from two databases from controller -

i have 2 databases identical tables (one regular use, 1 update purposes). want able access data both of them. code i'm using: $this->channel->usedbconfig = 'default'; debug($this->channel->find('count')); // output: 641939, correct! $this->channel->usedbconfig = 'update'; debug($this->channel->find('count')); // output: 641939, wrong, should 641938 the second usedbconfig isn't working. it's still manipulating data default datasource instead of update datasource. guess has default datasource being used right before it. how can access update database immediately after using default one?

javascript - XMLDOM "undefined is not a function" alert Chrome -

i tried open xml file chrome gives me alert saying "undefined not function" , nothing more. don't know problem. can please tell me problem , how can solve it? my code: <!doctype html> <html> <head> </head> <body> <script> function loadxmldoc(dname) { try //internet explorer { xmldoc=new activexobject("microsoft.xmldom"); } catch(e) { try //firefox, mozilla, opera, etc. { xmldoc=document.implementation.createdocument("","",null); } catch(e) {alert(e.message)} } try { xmldoc.async=false; xmldoc.load(dname); return(xmldoc); } catch(e) {alert(e.message)} return(null); } var xmldoc= loadxmldoc('skoly.xml'); </script> </body> </html> your document.implementation.createdocument invalid. here documentation on it: https://developer.mozilla.org/en-us/docs/web/api/domimplementation.createdocument

text_field disabled in Ruby on Rails -

i have following code disable text_field when user not admin , working fine: <div class="form-group"> <%= f.label :nome, "genero" %> <%= f.text_field :nome, class: "form-control", disabled: true if not is_admin? %> </div> but when user admin text_field disappears. know why happening , have do? assuming is_admin? returns true or false , can do <%= f.text_field :nome, class: "form-control", disabled: !is_admin? %> currently, if condition i.e., if not is_admin? applied on entire text field, results in text field disappearance when is_admin? returns true , when condition returns false text field displayed.

jquery - Javascript handle 2 data attribute -

i need use data attribute in html <div id="userlist" data-user="a.a.m"></div> need alert data-user used var userlist = document.getelementbyid("userlist"); var show = userlist.getattribute("data-user"); alert(show); my question how handle many data-user in html like <div id="userlist" data-user="a.a.m"></div> <div id="userlist2" data-user="a.a.m2"></div> alert a.a.m , a.a.m2 thanks in advance , sorry bad english. you know how alert 1, alert 2: alert @ same time: var data1 = document.getelementbyid("userlist").getattribute("data-user"); var data2 = document.getelementbyid("userlist2").getattribute("data-user"); var data = data1 +"\n" + data2; //"\n" can other separators alert(data) if have many of them, can use jquery: add in , before other js code. <script src="ht

java - Exception because of stale OneToMany relation when merging -

my entities like: class parent { @id long id; @onetomany(fetch=fetchtype.eager) @joincolumn(name="childid", insertable=false, updatable=false) set<child> children = new hashset<child>(); } class child { @id long id; } i have parent entity child loaded in thread a. in thread b, code deletes child belongs parent entity in thread a. result, thread encounter javax.persistence.entitynotfoundexception when calling entitymanager.merge() because field children contains stale data has been deleted. how should handle concurrent situation?

server sent events - Notification using jersey 2.8 - To notify to specific group of users -

we using jersey 2.8 implementing restful webservice in our application. so same using serversentevent (sse) notify user occurrence of event in server side. we found there 2 ways of implementing same. 1. notification. 2. broadcast. for both type registered user gets notification. notification: user registers specific event same new thread created , client notified in thread. problem using notification approach: in case of notification, have keep on waiting event occur(by polling occurrence of event in thread infinitely). broadcast: in order rid infinitely polling event used broadcast. here, user registers specific event, , event occurs can published client. problem broadcast approach: in case if want notify specific group of users not getting how should implemented. for instance: in case of facebook notification, person x posts status, there following categories of persons, y - has liked post. z - has commented on post. q - friend of x has neither commented nor like

objective c - Post plain text on facebook wall from iOS application -

yet, it's rather popular question , fb's doc clear, stuck following situation: want user post ios app facebook wall article,that wants share friends(but article on website available subscribed users, can't post link article need post full article's text @ once) nsmutabledictionary *params = [nsmutabledictionary dictionarywithobjectsandkeys: _title, @"name", _htmlbody, @"description", nil]; [fbwebdialogs presentfeeddialogmodallywithsession:nil parameters:params handler:handler]; as can see, parameter "link" missed in params, , causes, post on wall empty!is there workaround how post on wall plain text without link, photo, etc.? note: when add working link in params, can see post on wall, but, anyway description cut, several lines article seen.(i think because param "description" allows have particular size,

java - Display a text letter by letter in Android / Runnables are too slow -

i searched didn't found answer, hope can me. want write text letter letter h he , hel , on. did runnables: private void text001(final string finishedtext) { ... ... final string text = getresources().getstring(r.string.first_start_001); new handler().postdelayed(new runnable() { public void run() { professortext.settext(finishedtext + text.charat(finishedtext.length())); string finishedtextextra = finishedtext + text.charat(finishedtext.length()); text001(finishedtextextra); log.i("actual text speed", textspeed + ""); } }, textspeed); ... ... } but seems runnables slow. if set textspeed 50ms text appears not faster if set textspeed 100ms. thought maybe have different, found no other way. helping.

How to add height and width in a PHP script? -

i have following line. works fine want add height , width image. how? echo "<td>" . "<img src='img/" .$row['foto'] . "'>" . "</td>"; you can use style attribute : echo "<td>" . "<img style = 'width:?;height:?' src = 'img/" .$row['foto'] . "'>" . "</td>"; or width , height attributes : echo "<td>" . "<img width = '?' height = '?' src = 'img/" .$row['foto'] . "'>" . "</td>";

javascript - Typeahead always shows only 5 suggestions maximum -

i have below code using typeahead.js suggestions. have no major issues on code works fine. the minor issue face given time, see 5 suggestions though there more 5 suggestions remote url. var isearch = new bloodhound({ datumtokenizer: function(d) { return bloodhound.tokenizers.whitespace(d.value); }, querytokenizer: bloodhound.tokenizers.whitespace, remote: "http://localhost/search/get-data/%query" }); isearch.initialize(); $("#search_box .typeahead").typeahead(null,{ name: "isearch", displaykey: "value", source: isearch.ttadapter(), templates: { suggestion: handlebars.compile("{{value}}") } }); what expect there more suggestions, there should scroll bar users see. this answer typeahead version 0.10.4. the bloodhound suggestion engine has default value of 5 "limit" option (i.e. the max number of suggestions return bloodhound#get ) you can increase lim

html - Making span inherit sibling width -

i have div header element , span . how can prevent span making parent div larger? i.e. lets span 's width width of sibling heading. example: <div class="media-body"> <h4 class="media-heading"> lauren ipsum <small>@ipsum - 2014-06-01t18:40:35.000z</small> </h4> <span> lorem ipsum.. </span> </div> the span should not make div , wider if wasn't there. example: fiddle if understand question, want span element remain size of parent. from looking @ code appears haven't specified maximum width of parent, span assumes keep flowing until reaches border of container. given it's not set, text keeps going until hits browser window. your options limited 1) setting maximum width of parent, , setting span display: block; or 2) setting max width on span .

ios - SpriteKit - Stop Clicks on Sprite From Acting Upon Children -

i use following create button text using spritekit: sklabelnode *startbuttontext = [sklabelnode labelnodewithfontnamed:@"verdana-bold"]; startbuttontext.text = @"start"; startbuttontext.fontcolor = [skcolor colorwithred:1 green:1 blue:1 alpha:1]; startbuttontext.fontsize = 24; startbuttontext.position = cgpointmake(self.size.width/2, self.size.height/2-10); startbuttontext.name=@"startbutton"; skshapenode *startbutton = [[skshapenode alloc] init]; startbutton.path = [uibezierpath bezierpathwithrect:cgrectmake(center.x-65.0 , center.y-20.0, 130.0, 40.0)].cgpath; startbutton.fillcolor = [skcolor colorwithred:0.188 green:0.196 blue:0.161 alpha:1]; startbutton.strokecolor = nill; startbuttontext.name=@"startbutton"; [startbutton addchild:startbuttontext]; [self addchild:startbutton]; my goal make when screen touched, touch registers startbutton not start startbuttontext via: - (void)touchesbegan:(nsset *)touches withevent:(uievent *)event

javascript - jQuery Mobile 1.4.2 + Photoswipe 1.0.11 -

i trying implement latest version of photoswipe latest version of jquery mobile. use made examples included photoswipe download file , updating jquery & jquery mobile latest versions. after doing that, gallery not work. have managed make work? if impossible, alternative works latest jquery mobile? best, just keep using photoswipe. problem version mismatch. original developer stopped working on framework few weeks ago , developer overtook project. not known second developer forked project long time ago , there 2 separate versions of plugin. original 1 stopped working jquery mobile ago. second implementation holds version: 3.0.5. unfortunately version no longer available. knowledge second developer working on merging 2 projects together. thankfully have available version 3.0.4 working example: http://jsfiddle.net/gajotres/pfqvs/ html: <!doctype html> <html> <head> <title>jqm complex demo</title> <meta htt

JavaScript regex \G + offset equivalent -

is there equivalent of \g in javascript regular expressions? need match pattern @ exact offset. setting g flag , .lastindex searches forward given index, won't match @ offset exactly. xregexp has y modifier might i'm looking for, doesn't appear work in node/v8. i think thing can set .lastindex starting point, try match .exec() , , if match check updated value of .lastindex . if it's equal starting position plus length of match result, match began wanted. so: var re = /banana/g; re.lastindex = 6; var mr = re.exec("hello banana"); if (mr[0].length + 6 === re.lastindex) alert("good banana"); i never claim "good" way of doing things, it's possibility know of.

php - codeigniter form validation doesn't call callback function -

by reason form validation doesn't call callback function set in rules. it rules sets if( ! empty($_post)) { ci()->form_validation->set_rules('login', 'username', 'trim|required'); ci()->form_validation->set_rules('email', 'email', 'trim|required|valid_email|callback_check_email'); if (ci()->form_validation->run() == true) { } } and function public function check_email($str) { ci()->load->model(array('secure_model', 'admin/members_model')); $o['username'] = ci()->input->post('login'); $o['email'] = ci()->input->post('email'); $m = $this->_model->get_row($o); if ( ! $m) { $this->form_validation->set_message('check_email', lang('unlock_incorrect_login')); return false; } else {

php - API response: Access member with hyphen in name -

i in absurd situation. using api returns me [winner-id] => 15404899 the way select elements api's return is: $matches->returnelement; the problem can't winner-id's value cause when type $matches->winner-id; it's invalid variable because of (-) sign. give me advice? try this: $matches->{'winner-id'};

javascript - extjs grid hide and show changes width -

i have extjs grid simple stuff within div. hide , show container clicking button. after hiding container, if resize window, , again show container, grid gets width of 100px. expect make use of width:100% .container{ border:1px solid gold; } .row{ padding:20px; } .col4{ width:30%; float:left; padding:20px; font-size:20px; background-color:red; color:#fff; } </style> <script> $(document).ready(function(){ $(".btn").click(function(){ $(".container .thrd-row").css("display","none"); }); $(window).resize(function(){ $(".container .thrd-row").removeattr("style"); }); }); </script> //use html <div class="container"> <div class="row firs-row"> <div class="col4">1</div> <div class="col4">1</div> <div class="col4">1</div> </d

c# - Vertical Grouping - WPF DataGrid or ListView -

Image
how can have below view using wpf or creating custom control? as need use data templates , cell values might object instances, cannot use winforms use old structure. (not mention if wouldn't!) grouping level can 1 (like picture) or more. 4 steps satisfactory here. any other solutions appreciated. here go i defined itemscontrol bound items (your data) , defined group style show data expectation. <itemscontrol itemssource="{binding items}"> <itemscontrol.groupstyle> <groupstyle> <groupstyle.containerstyle> <style targettype="{x:type groupitem}"> <setter property="template"> <setter.value> <controltemplate targettype="{x:type groupitem}"> <grid> <gr

ajax - How to replace the Data Array in jQuery DataTables -

i have datatables table filled json array (directly written html asp.net). want refresh data ajax data won't added. want use own method, not datatables' internal ajax method. (using datatables 1.10.0). $.getjson("?ajax=1", null, function(json, status, xhr) { var table = $("#" + protableid).datatable(); osettings = table.settings(); //table.clear(); table.rows().remove(); var data = table.data(); (var = 0; < json.length; i++) { data.push(json[i]); } table.draw(); }); the json result correct after call datatable empty. how replace data inside datatables object , preferably keep sorting , filtering? for adding data data table, have access property row of data table object, , call add method. finally, update table calling draw method. as can seen on data table documentation . have this: for(var i= 0; < json.length; i++){ table.row.add([ json[i].firstproperty, json[i].secon

angularjs - Decoupling between service and controller e.g. not using $http -

i'm quite new angularjs , i'm trying find nice way implement controller-service communication simple rest client i'm writing. on web find lot of examples controller delegates $http requests service still rely on $http object perform success/error handling. imho not thoroughly decoupled, $http object "leaked" controller layer. controller should ignorant of how data retrieved -- should ask service layer "give me/do this/etc." i have java background typically decouple controller-service using pojo's can anti-pattern i've heard. what best practice? i returning promises services . here's example: controller: $scope.removetask = function(task) { boardservice.removetask({task_id: task.id}).then(function() { // task removed }); } service: this.removetask = function(data) { return $http.post($rootscope.serverroot + '/task/delete', data); } doing way not require inject $

android - Popup showAtLocation is not working -

i'm using pop-window show text-view while clicking edit-text . pop-window not showing @ particular location ,it showing @ left top corner , here code ,what wrong in private void showpopup(context context,final linearlayout parent) { layoutinflater layoutinflater = (layoutinflater)context .getsystemservice(context.layout_inflater_service); layout = layoutinflater.inflate(r.layout.popup,mainactivity.parent,true); // creating popupwindow final popupwindow popupwindow = new popupwindow( layout,700,700); popupwindow.setcontentview(layout); popupwindow.setheight(500); new runnable(){ @override public void run() { popupwindow.showatlocation(layout, gravity.center,300,150); } }; } try following code: public static rect locateview(view v) { int[] loc_int = new int[2]; if (v == null) return null; try { v.getlocationonscreen(loc_int); } catch

javascript - How can I rotate two divs to form an X when I click the container div? -

here's have now: code this html <div id="box"> <div id="line1" class="line"></div> <div id="line2" class="line"></div> <div id="line3" class="line"></div> </div> i use jquery rotate line1 , line3 form x , make line2 disappear when click container div (#box). idea of jquery because of animation, other ideas welcome. you can this .rotatel{ transform:rotate(45deg) translatex(10px); -webkit-transform:rotate(45deg) translatex(10px); transform-origin:30%; -webkit-transform-origin:30%; } .rotater{ transform:rotate(-45deg) translatey(10px); -webkit-transform:rotate(-45deg) translatey(10px); transform-origin:22%; -webkit-transform-origin:22%; }

java - Change Jackson date formatting setting in spring data rest webmvc -

lightadmin timestamp fields such as: @temporal(temporaltype.timestamp) @column(name="started_at") date startedat; does not format them shows them number of milliseconds since epoch, e.g. 1398940456150 . when enter lightadmin edit page e.g. http://localhost:8080/admin/domain/user/1/edit values form populated received in request - http://localhost:8080/admin/rest/user/1/unit/formview?_=1401699535260 , returns json with: ... "startedat" : { "name" : "startedat", "title" : "started @ timestamp", "value" : 1398940456150, "type" : "date", "persistable" : true, "primarykey" : false } ... the task change 1398940456150 e.g. 01.05.2014 10:34:16 . according investigation, org.lightadmin.core.rest.dynamicrepositoryrestcontroller.entity() entry point of such requests, code responsible generating json inside: org.springframework.data.rest.webmvc.rep

Google visualization code is throwing a crypic error -

i'm getting data google analytics , trying display in table. code throwing error "this.zf[a].c undefined". don't see wrong code. /*table */ google.load('visualization', '1.0', {packages:['table']}); // set callback run when google visualization api loaded. google.setonloadcallback(drawnewtable); function drawnewtable() { var json = {cols: [{id:'campaign',label:'campaign',type:'string'},{id:'source',label:'source',type:'string'},{id:'medium',label:'medium',type:'string'},{id:'sessions',label:'sessions',type:'number'}],rows:[["fac 2005-74 addresses contractor past performance reporting, contractor compensation","todays_acquisition_news_05302014","email",8.0],["gao sustains protest, finding agency revised requirements","todays_acquisition_news_05292014","email",8.0],["gsa announces o

logging - php - different design of webpage for logged in users -

i have 1 question. looked through 1 book , internet , unfortunately didn't find concrete answer. so... have webpage user can log in. if user logged in bar @ top of webpage different(user sees own photo, name etc.). know how use sessions&databases in case, don't know how make 2 different websites. mean.... in home site of whole webpage can write sth (in php): if(isset($_session["user"])) ..... . but then? should somehow hide html unlogged user in "else" , part logged user in "if" or should create whole new site logged in users , redirect site if user logged...? please, me. it seems need spend little time looking php deeper. advice learn including php files in order create template system (so have base php file html/php on every page (like master page) include code: if(isset($_session["user"])) { // code logged in user... } else { // code generic user... } although rudimentary example, have glo

c# - How to update the item of the listbox as well as in the iso store local database -

as working on how update data in local database in windows phone app problem facing item want edit not edited , second item created in database due code want edit , update same data item without creating second item in database. please me how update item in database.. my view model: public void getpersonallist() { try { personaldatacontext addreminder = new personaldatacontext(personaldatacontext.dbconnectionstring); if (addreminder.personal.count() > 0) { this.personallist.clear(); personalreminderdata reminderdata = new personalreminderdata(); list<personaltable> personals = reminderdata.getreminderdata(); foreach (var personalitem in personals) { this.personallist.add(new personalmodel { id = personalitem.id, title = personalitem.title, description = personalitem.description, date = personalitem.date,

initialization - How to initialize all members of an array to the same value in Swift? -

i have large array in swift. want initialize members same value (i.e. 0 or other value). best approach? actually, it's quite simple swift. mentioned in apple's doc , can initialize array same repeated value this: with old swift version : var threedoubles = [double](count: 3, repeatedvalue: 0.0) since swift 3.0 : var threedoubles = [double](repeating: 0.0, count: 3) which give: [0.0, 0.0, 0.0]

numpy - Use Python SciPy to solve ODE -

now face problem when use scipy.integrate.ode. i want use spectral method (fourier transform) solve pde including dispersive , convection term, such du/dt = * d^3 u / dx^3 + c * du/dx then fourier transform pde convert set of odes in complex space (uk complex vector) duk/dt = (a * coeff^3 + c * coeff) * uk coeff = (2 * pi * * k) / l k wavenumber, (e.g.. k = 0, 1, 2, 3, -4, -3, -2, -1) i^2 = -1, l length of domain. when use r = ode(uode).set_integrator('zvode', method='adams') , python warn like: c zvode-- @ current t (=r1), mxstep (=i1) steps taken on call before reaching tout in above message, i1 = 500 in above message, r1 = 0.2191432098050d+00 i feel because time step chosen large, cannot decrease time step every step time consuming real problem. have other way resolve problem? did consider solving odes symbolically? sympy can type import sympy sy sy.init_printing() # use ipython better res

c# - Replacing all occurrences of alphanumeric characters in a string -

i'm trying replace alphanumeric characters in string character "-" using regex. if input "dune" should "----". though i'm getting single "-"; string s = "^[a-za-z0-9]*$"; regex rgx = new regex(s); string s = "dune"; string result = rgx.replace(s, "-"); console.writeline(result); console.read(); right know looking string "dune" rather letters "d" "u" "n" "e". can find class work. your regex greedy, remove * , start end string matches. should be string s = "[a-za-z0-9]"; this match 1 character anywhere in string rather all. @ shorthand alphanumeric string s= "\w";

java - Swing timer synchronization -

Image
i'm confused how swing timer work. in code below, want display 0~9 every 400ms in first text field when press start (once). after second text field display "finished". public class main extends jpanel{ private static final long serialversionuid = 1l; private jbutton bstart; private jtextfield ttest; private jtextfield tnumber; main(){ bstart = new jbutton("start"); bstart.addactionlistener(new actionlistener(){ @override public void actionperformed(actionevent arg0) { // todo auto-generated method stub displaynumbers(); } }); ttest = new jtextfield(null, 30); tnumber = new jtextfield(" ", 30); tnumber.seteditable(false); this.setsize(300, 100); this.add(bstart); this.add(tnumber); this.add(ttest); } public void displaynumbers(){ new timer(400, new actionlistener() { int = 0; public void actionperformed(actionevent evt) {

php - Return array key and value from ordered number -

i want return both key , value of array item, knowing numerically ordered number. is there better method using these 2 functions? $num = '3'; $array = [ 'fish' => 'blue', 'monkey' => 'green', 'pig' => 'blue', 'cat' => 'yellow', ]; echo array_values($array)[$num]; // yellow echo array_keys($array)[$num]; // cat sure, array_slice() $num = '3'; $array = [ 'fish' => 'blue', 'monkey' => 'green', 'pig' => 'blue', 'cat' => 'yellow', ]; $newarray = array_slice($array, $num, 1); var_dump($newarray); works associative arrays

sql - Achieve sequence number in concurrency -

i new transaction isolation levels. beginner sql well. have 2 stored procedures below. create procedure [dbo].[spupdaterecordinfintab] @ids bigint begin begin try begin transaction declare @id bigint set @id = (select [seedno] [dbo].[seedno] [type] = 'abc')+1 declare @inum nvarchar(50) set @inum = 'abc'+ cast(@id nvarchar(20)) update [dbo].[exchtab] set [inumber] = @inum [id] = @ids update [dbo].[seedno] set [seedno] = @id [type] = 'inv' exec spnewroecordintofintab @ids commit end try begin catch rollback transaction end catch end create procedure [dbo].spnewroecordintofintab @ids bigint begin declare @id bigint set @id = (select [seedno] [dbo].[seedno] [type] = 'abc')+1 declare @inum nvarchar(50) set @inum = 'abc'+ cast(@id nvarchar(20)) insert [dbo].[exchtab] values( @inum,123.78,1) update [dbo].[seedno] set [seedno] = @id [type] = 'inv' en

javascript - How to transfer onclick with a jsp variable and direct to other page -

do know how transfer variable button other page. creating update , delete site. database query data, , there edit button, if press edit, direct second site. site show data information update. source code below. used below source code, when enter edit, will not direct page(edit_delete.jsp) can 1 plem me, whay wrong code please see bold in source code mark, might problem. -----------------------------------------source code----------------------------------------------------------- <script language="javascript"> function editrecord(no){ var f=document.form1; alert(no); f.method="post"; **f.action='edit_delete.jsp?id='+no;** f.submit(); } </script> class.forname("com.mysql.jdbc.driver").newinstance(); con = drivermanager.getconnection("jdbc:mysql://localhost:3306/webapp?user=root&useunicode=true&characterencoding=big5"); stmt=con.preparestatement("select id, no, name, class, test"); rs

javascript - Switch statement automatically performing cases without meeting case requirements? -

i made switch statement , begun work until began adding more code it.. take look: var txt; var begin = 'some text'; var briefbegin = 'some text'; var started = false; var input = function () { switch (true) { case 'start' && !started: txt = begin; started = true; break; case 'start brief' && !started: txt = bbegin; started = true; break; default: txt = "some text." } $('.output1').text(txt); }; i called down here... var teext; $(".submit").click(function() { teext = $('.inputt').val(); input(teext); console.log(teext); }); $(".inputt").keyup(function(event){ if(event.keycode == 13){ $(".submit").click(); } }); so whenever type in input field (under class ".inputt") whether fits case or not, automatically prints every case top bottom. appreciated :d tha

java - executorservice to read data from database in chuncks and run process on them -

i'm trying write process read data database , upload onto cloud datastore. how can decide partition strategy of data? want query table in chunks , process each chunk in 10 threads. each thread send data individual node on 10 node cluster on cloud.. where in below multi threading code dataquery extract , send 10 concurrent requests uploading data cloud be? important not loose cursor database query has processed far incase of failure, in database once batch of 100 records have been processed example, should update record statuses pending done in database column record. job run every 10 min pull data source database. public class caller { public static void main(string[] args) { executorservice executor = executors.newfixedthreadpool(10); (int = 0; < 10; i++) { runnable worker = new domaincdcprocessor(i); executor.execute(worker); } executor.shutdown(); while (!executor.istermina

ubuntu - CouchDB crashes when bound to public ip -

i have couchdb server running on amazon ec2 instance, when start bound 127.0.0.1 it works fine, when bind_address = my.public.ip it crashes on start error failure start mochiweb: eaddrnotavail this error occurs when address invalid, though multiple checks verify in fact valid, , when bind_address = 0.0.0.0 it works fine. eaddrnotavail means port not available,you have edit /etc/couchdb/couch.ini file , change port setting available port.

firebird - What is the Clad Genius database structure in cafw.fdb? -

clad genius internally uses firebird sql database (cafw.fdb). can connect using linux firebird client, these tables: sql> show tables; bp_adcat bp_adreg bp_cat bp_catv bp_ema bp_post bp_reg ca_ad ca_adimg ca_campaign ca_proxy ca_reg ca_tpreg cl_act cl_adcat cl_adreg cl_cat cl_ema cl_post cl_reg gr_app gr_cc gr_chlog gr_fb gr_hint gr_htde gr_htds

jquery - how to read nested array in JSON from javascript? -

i have json array below. [ [ "{"category_id":1,"category_name":"cake","image_id":0}", "{"category_id":2,"category_name":"briyani","image_id":6}", "{"category_id":3,"category_name":"indian breads","image_id":0}", "{"category_id":4,"category_name":"tandoori","image_id":5}", "{"category_id":5,"category_name":"seafood delight","image_id":10}", "{"category_id":6,"category_name":"vegetarian","image_id":0}", "{"category_id":7,"category_name":"curry","image_id":0}", "{"category_id":8,"category_name":"biryani","image_id":0}", "{"category_id":9,"category_name":"desser

performance - Drawing lags in Android drawing application with canvas -

i building drawing application in android using canvas. i'm directly painting on canvas without using offline bitmap/canvas. works fine on 512m memory device on slower devices, application lags after few strokes. application allows user put cliparts, background , flood fill, too. for different objects using arraylist bean class store each paint object, style , bitmap. in ondraw(), each time iterating on arraylist , draw stored in arraylist. providing undo , redo cannot use drawingcache. in short, need improve overall performance of application. how can achieve that? application structure proper or should change? can post code if needed. thanks in advance.

gruntjs - Run all Grunt SubTasks except one -

i've bunch of subtasks grunt watch (e.g. grunt watch:styles, grunt watch:sprites, etc). many other tasks run grunt watch . exclude 1 task. there way specify that? run grunt watch subtasks except grunt watch:dist . i know create task , specify subtasks i'm interested on, however, if add subtask later, means i've add it, rather not way. thanks there might better way, doing trick now: grunt.registertask('watch:basic', function () { delete grunt.config.data.watch.dist; grunt.task.run('watch'); }); fortunately, in case, don't have other tasks might run grunt watch:dist , it's safe remove config, can think of other cases approach create conflicts.

c# - WPF Binding in ComboBox with UserControl list -

in 2 combobox , b. a's itemssource custom list. , b's itemssource usercontrol list. when manually setting selecteditem, combobox works well, b combobox ui not show selected item. (in debugging, selecteditem's value mapping right, combobox b's ui not changed.) other structure same between , b. reason? mainwindow.xaml ... <combobox itemssource="{binding fruitlist}" selecteditem="{binding selectedfruit}" displaymemberpath="fruitname" /> <button content="button" horizontalalignment="left" verticalalignment="top" width="75" click="button_click"/> <combobox itemssource="{binding usercontrollist}" selecteditem="{binding selectedusercontrol}" displaymemberpath="itemname" /> <button content="button" horizontalalignment="left" verticalalignment="top" width="75" click="button_click2"

Unable to grant file permission using exec-maven-plugin -

i'm trying grant file permission using next exec-maven-plugin config: <plugin> <groupid>org.codehaus.mojo</groupid> <artifactid>exec-maven-plugin</artifactid> <version>1.2.1</version> <executions> <execution> <id>grant-permissions</id> <phase>validate</phase> <goals> <goal>exec</goal> </goals> <configuration> <executable>chmod</executable> <arguments> <argument>+x</argument> <argument>${somepath}/*.sh</argument> </arguments> </configuration> </execution> it prints chmod: can

jdbc - Strange error when installing sonarqube 4.3 -

im trying install sonarqube , steps have taken: downloaded sonarqube version 4.3 unpacked sonarqube-4.3.zip c:\sonarqube start sonarqube running: c:\sonarqube\bin\windows-x86-64\startsonar.bat server running testet access server on http://localhost:9000 comment out following line in c:\sonarqube\conf\sonar.properties sonar.jdbc.url=jdbc:h2:tcp://localhost:9092/sonar edit following lines in c:\sonarqube\conf\sonar.properties sonar.jdbc.username=sonar sonar.jdbc.username=username sonar.jdbc.password=sonar sonar.jdbc.password=password #sonar.jdbc.url=jdbc:oracle:thin:@host/xe sonar.jdbc.url=jdbc:oracle:thin:@host:port/db download ojdbc6.jar copy ojdbc6.jar c:\sonarqube\extensions\jdbc-driver\oracle\ stop server start server starting server fails i in log: any or pointers appreciated 2014.06.03 11:13:55 info [o.s.a.connectors] http connector enabled on port 9000 2014.06.03 11:13:56 info [o.a.c.h.http11protocol] initializing protocolhandler ["http-bio-0

css - Max width with twitter bootstrap label -

Image
i trying achieve similar thing tags. it looks great , problem want have maximum width of each tag, if length of the tag, big, truncated. i can achieve with: .label{ width: 50px; float: left; overflow: hidden; } ok, works, when this, number not on same line label . how can achieve same effect on first fiddle, maximum width. this should trick: .label { display: inline-block; max-width: 100px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: middle; } jsfiddle demo . what i've done here dropped float: left , replaced display: inline-block . i've given ellipsis text-overflow property make nicer, , set vertical-align middle in line .multiple element. oh, , i've replaced width max-width stop smaller tags being same size. example usage here example multiple tags (each on new line intentionally): jsfiddle . obviously can adjust max-width accordingly.

xml - How to check for text node of an element in xmltype oracle -

using following query, select * sampletable xmlexists('/books/book[@max="30"]' passing xmlcolumn); but want know , how check plain text content of element, like select * sampletable xmlexists('/books/book="content"' passing xmlcolumn); to check if there book node text node equals content (from xpath terms return book nodes), do: select * sampletable xmlexists('/books/book[.="content"]'; to check if there books nodes child node equals content (from xpath terms return books nodes), do: select * sampletable xmlexists('/books[book="content"]';

Zend Translation and View Scripts -

form labels , error messages translated automatically. strings in view scripts not. have use $this->translate("text transfer"); in each , every phtml files.i don't want use $this->translate("text transfer"); method.how can automatically translate view scripts in case of forms.my code protected function _inittranslation() { $langnamespace = new zend_session_namespace('language_sess'); $lang = $langnamespace->lang; $registry = zend_registry::getinstance(); $tr = new zend_translate( array( 'adapter' => 'array', 'content' => application_path . "/languages/$lang/$lang.php", 'locale' => "ar", 'scan' => zend_translate::locale_directory ) ); $registry->set('zend_translate', $tr); return $registry; } ok, make clear, need understand few things: zend_t