Posts

Showing posts from July, 2010

dependency injection - DI container for Java without @Inject -

i'd know if there di container java world behaves close .net ones, namely, want these 2 features: main requirement - should work without @inject annotation. so, if @inject not specified anywhere, , class has single constructor container should use constructor. know, @inject annotation standard, don't it. 2nd requirement (not necessary @ all) - way auto-configure (by naming conventions etc.) it looks swing , guice require @inject, happy, if i'm wrong. pico satisfies 1st requirement. 2nd requirement can more or less done org.reflections library , this answer

bash - How to avoid 'are the same file' warning message when using cp in Linux? -

i'm trying copy files 1 directory another. using command find "$home" -name '*.txt' -type f -print0 | xargs -0 cp -t $home/newdir i warning message saying cp: '/home/me/newdir/logfile.txt' , '/home/me/newdir/logfile.txt' same file how avoid warning message? the problem try copy file itself. can avoid excluding destination directory results of find command this: find "$home" -name '*.txt' -type f -not -path "$home/newdir/*" -print0 | xargs -0 cp -t "$home/newdir"

osx - Retina issue (OS X) -

i creating cocoa app, , when import @2x images project, no image shows in app @ all. using non-retina macbook pro. if have image, such image.png, shows correctly. when import image@2x.png project, no image shows when app run (even normal image). when change image@2x.png image@2xx.png (or other name), image shows again. however, can't show image on retina device. am not handling retina images correctly? you need include image.png , image@2x.png in project. make sure when load files not include .png extension.

Django - MultipleCheckBoxSelector with m2m field - How to add object instead of save_m2m() -

Image
i use inlineformset_factory custom form option in order change queryset , widget of m2m field, ie: ezmap . want form give user option add or remove current selected_map m2m field checkboxselectmultiple widget. however, dont want give user ability remove other objects there. problem when save formset formset.save_m2m() , overides field , erase objects saved. how add new object without erasing others? models: (some of unecessary fields removed) class shapefile(models.model): filename = models.charfield(max_length=255) class ezmap(models.model): map_name = models.slugfield(max_length=50) layers = models.manytomanyfield(shapefile, verbose_name='layers display', null=true, blank=true) class layerstyle(models.model): stylename = models.slugfield(max_length=50) layer = models.foreignkey(shapefile) ezmap = models.manytomanyfield(ezmap) forms: class polygonlayerstyleformset(forms.modelform): add_to_map = forms.booleanfield(required=false)...

How to swap a double in Objective-C -

i'm trying read double file. need swap it. nsswaplittledoubletohost(nsswappeddouble x) requires nsswappeddouble . nsswapdouble() requires nsswappeddouble well. nsswappeddouble doubleswap = normaldouble; doesnt work. how convert double nsswappeddouble? to convert double nsswappeddouble can use nsconverthostdoubletoswapped per documentation . however, if want swap double can call nsswaphostdoubletobig or nsswaphostdoubletolittle directly (both take double parameter).

png - matplotlib subplot with image background -

how can create subplot, background created fully, without gray boundry, png image file.png i have tried: import matplotlib.pyplot plt im = plt.imread('map.gif') implot = plt.imshow(im,aspect='auto',origin='lower') fig0=implot.figure.tight_layout(pad=0.5) implot.axes.set_axis_off() fig1=implot.figure ax1=fig1.add_subplot(2,2,1) ax1.plot(range(10)) ax2=fig1.add_subplot(2,2,2) ax2.plot(range(9,-1,-1)) plt.show() i cannot image span whole graphics window thanks ilan

php get the max(accNumber) and then increment by 1 -

i'm trying highest number , increment 1. blank page, here code $query = $pdo->prepare("select max(accnum) accounts"); $query->execute(); while($num = $query->fetchall()){ if($num[1] == null){ $accnumber = "100001"; }else{ $accnumber = $num[1]++; } echo $accnumber; } what doing wrong here. thanks $query = $pdo->prepare("select max(accnum) accounts"); $query->execute(); while($num = $query->fetchall()){ if($num[0] == null){ $accnumber = "100001"; }else{ $accnumber = $num[0]++; } echo $accnumber; }

rest - ServiceStack deserialization of JSON content in multipart/form-data request -

i'm creating restful service using servicestack should consume post multipart/form-data content. content in json format, when send post, object not deserialized correctly (all properties null/default values). if try sending object regular post (without multipart/form-data), deserializes fine. i poked around in servicestack code try figure out going on, , current understanding: httplistenerrequestwrapper::loadmultipart() loading multipart request , saving (non-file) parts "formdata", maps name of part contents. however, appears content-type (which correctly written httpmultipart::element individual sections being parsed) lost because isn't stored in anywhere. some time later in control-flow, endpointhandlerbase::deserializehttprequest() calls keyvaluedatacontractdeserializer.instance.parse() formdata , type deserialize to. if first time kind of object being deserialized, stringmaptypedeserializer created type , cached typestringmapserializermap. each pro...

ruby on rails - has_many :through with class_name and foreign_key -

i'm working straightforward has_many through: situation can make class_name/foreign_key parameters work in 1 direction not other. perhaps can me out. (p.s. i'm using rails 4 if makes diff): english: user manages many listings through listingmanager, , listing managed many users through listingmanager. listing manager has data fields, not germane question, edited them out in below code here's simple part works: class user < activerecord::base has_many :listing_managers has_many :listings, through: :listing_managers end class listing < activerecord::base has_many :listing_managers has_many :managers, through: :listing_managers, class_name: "user", foreign_key: "manager_id" end class listingmanager < activerecord::base belongs_to :listing belongs_to :manager, class_name:"user" attr_accessible :listing_id, :manager_id end as can guess above listingmanager table looks like: create_table "listing_managers...

r - Making a cumsum created vector correspond to the data from which it was created. -

i using cumsum calculate accumulation of thermal units (tu). each day has multiple thermal units, end vector has length of on 3000, want column in dataframe tells me how many accumulated thermal units have each day. here example dataframe: doy tu 1 5 2 10 3 5 4 5 5 10 6 5 and want like: doy tu cumtu 1 5 5 2 10 15 3 5 20 4 5 25 5 10 35 6 5 40 i have been using cumsum(df$tu) , not sure how use cumsum in context of df.

c# - ASP.NET Application - Accessing details about a drop down list's DataSource -

i have following markup: <td> <asp:dropdownlist runat="server" id="ddlextroutebusyid" style="width: 320px;" /> </td> and code behind executes on page load: //bind route busy drop down list: datatable dr = /*[some datatable returned wrapper rdbms*/; this.ddlextroutebusyid.datasource = dt; this.ddlextroutebusyid.datatextfield = "description"; this.ddlextroutebusyid.datavaluefield = "id"; this.ddlextroutebusyid.databind(); i cannot seem access description , id data based upon value of selecteditem/value. example if select second list item, selectedindex 1, description might "server2" , id might 1118. how can pull description , id values? thanks. you can use following text , value: ddlextroutebusyid.selecteditem.text ddlextreoutebusyid.selecteditem.value if doesn't work there may other problem page doing, since verified these worked me.

websphere - Deploy an ear file to remote WAS 8 using Maven 3 -

is there way deploy ear file remote 8 using maven i found 6 plugin work 8 you write ant script deployment. you can call ant tasks maven.

Changing the Resolution of "time" Command in Linux -

is there way change resolution (accuracy) of reported execution time "time" command in linux? reports execution time in milli seconds. thanks looks me 3 digits after 0 maximum resolution. if want better resolution, suggest write wrapper in c , use utime see man -s2 utime if using bash, output format of time command (a builtin function) can set using timeformat environment variable. see man bash , search timeformat if using gnu time utility, can set format using time --format= check man time . in both cases, don't see option higher resolution.

c# - convert string to int with losing everything but digits -

i have string string = "234234324\r\n"; i want parse string integer losing \r\n part, int should contain digits string int b = 234234324 ; p.s. string not contain \r\n part, point want use digits string. i tried convert.toint32(a) have error. int b = int.parse(new string(a.where(char.isdigit).toarray()));

javascript - OnHover HTML5 audio on Safari -

i created simple nav bar on-hover mp3/ogg audio playback. works on browsers except safari on windows, judging autor should work on too. can take on mac , let me know working http://goo.gl/h2k6pn <audio id="aruba" controls preload="auto"> <source src="audio/aruba.mp3"></source> <source src="audio/aruba.ogg"></source> </audio> <ul class="top-level"> <li><a href="#" class="palm-tree" id="arubaplay">link</a></li> </ul> js window.onload=function(){ // collecting audio files var aruba = document.getelementbyid('aruba'); var arubaplay=document.getelementbyid('arubaplay'); arubaplay.onmouseover=function(){ aruba.play(); return false; }; windows safari not support html audio tags without quicktime installed. link works on os x safari.

c# - Layering Image over Flash XAML -

i have flash ui, , image. place image on flash object, can't seem working when using panel.zindex. here code <my1:wpfflashui name="mflashui" margin="0,0,0,6" horizontalalignment="stretch" panel.zindex="2" /> <image name="img2" source="http://www.donkersct.nl/wordpress/wp-content/uploads/2012/07/stackoverflow.png" height="217" width="363" margin="560,199,-45,6" panel.zindex="1" /> can see why isn't working, or suggest better way? have tried swapping zvalues around.

sql - How to do multiple INNER JOIN dynamically in php -

this first i've made code using multiple inner join s relationship table. this i'm doing: $table = $_post['tabla']; $campos = $_post['campos']; $camporelacion = $_post['campo_relacion']; **//code forget put** *// create array contain fields $ field = array (); //walk array of fields , assigned array //that created foreach ($ fields $ val) { $ field [] = "". $ val. ""; } //we separate fields in array commas $ field = join (',', $ field);* $maintable = $table[0]; $sql = 'select '.$field.' '.$maintable.' '; ($i = 1; $i<count($table); $i++) { $curtable = $table[$i]; $joinfield = $camporelacion[$i-1]; $sql.= 'inner join '.$curtable.' on '.$maintable.'.'.$joinfield.' = '.$curtable.'.'.$joinfield.' '; } the output of depending on data send: select slip_plantillas.nombre...

css - How to keep html table on same line without specifying a width? -

i can't seem keep (dynamic width) table on same line previous element , have extend it's parent container without exceeding , overflowing. don't want horizontal scrollbar table should break lines and/or words make more narrow. however, it's not doing that. jsfiddle in fiddle, table overflows , extends beyond it's parent container's width. parent container using white-space: nowrap keep on same line content next it. why not sizing it's width correctly? if set fixed width on table, works , sizes width correctly, need width of table dynamic. outermost containing div fixed. any ideas? if add .listinfotbl { [...] max-width: 142px; [...] } then you'll see working. may wonder why that? the answer set width div.listpropertydiv therefore won't grow beyond , additionally there's padding take formula: innerwidth(.listpropertydiv) = innerwidth(#left) - border(.listpropertydiv) - padding(.listpropertydiv) - margin(.listproper...

html5 - Bootstrap 3 RC1 responsive fluid grid system breakpoint issues -

i have designed website testing bootstrap 3 rc1. have 4 grid in row(12 grid / 4 =col-3) , when tried minimize small-display area of grids-row not going second line has scaling-up same row. my site : http://goo.gl/zcn8ri for example below code, have used class="col-2 col-sm-1 col-lg-3", need in large display grid should display '3-col' , small display should 2 col(line-break) not happening ... <div class="row"> <div class="col-2 col-sm-1 col-lg-3"> <div class="pc-area"> <center> <a href="#"><span class="area-positions"><img src="images/pc-laptop.png" alt="pc laptop"></span></a> </center> </div> </div> <div class="col-2 col-sm-1 col-lg-3"> <div class="mac-area"> <center> <a href="#"><span c...

node.js - Acitvate express/node error handler on user code exception -

i have code follows: app.js app.use(app.router) app.use(function(err, req, res, next) { res.render(errorpage) }) app.get('/', function(req,res,next) { module1.throwexception(function{ ... }); }); module1.js exports.thowexception = function(callback) { // throws typeerror exception. // follwoing 2 lines getting executed async // simplicity removed async code var myvar = undefined; myvar['a'] = 'b' callback() } with exception in module1.js, node prcoess dies. instead wanted render error page. i tried try ... catch in app.get(..), did not help. how can this?? you can't use try ... catch asynchronous code. in post can find basic principles error handling in node.js. in situation should return error first parameter of callback module instead of throwing , next call error handler. because error handling function after app.route handler, should check not found error if of route doesn't ...

Titanium AudioPlayer access iOS remote controls -

i have audioplayer playing music url. var streamer = ti.media.createaudioplayer({ url : '8..' }); and have fixed can play music in background ios. problem can´t access system buttons, example if lock iphone , press home button twice backward, pause/play , forward button , if iphone unlocked , press home button twice , swipe bottom bar right have system controls. i saw comment in thread @ appcelerators q/a: check comment dustin hume http://developer.appcelerator.com/question/47291/background-audio-in-14 i did steps , able run audioplater not able use remote buttons. have checked api documentation , not this. have clue? a year ago tried accomplish same thing. new titanium , app development in general found module on titaniums marketplace did thing. https://marketplace.appcelerator.com/apps/5573?1192373639

objective c - Using "tableView didSelectRowAtIndexPath" in tandem with prepareForSegue -

i have project utilizing storyboards uses uitableview in tandem navigation controller. layout similar apple's ios address book there table of objects, , clicking on cell pushes view onto navcontroller objects's details (properties). having trouble using prepareforsegue method in harmony table view's didselectrowatindex. need way prepareforsegue know row passed in didselectrowatindex can pass it's properties detail view controller being pushed since prepareforsegue gets called before didselectrowatindex does. if possible still use storyboard segue if there isn't way can progamatically push/pop. there question similar on stackoverflow never answered, kind of rambled on. if know work-around please let me know, thank you ! you can not use didselectrowatindexpath: @ all. can index path in prepareforsegue: this: uitableviewcell *cell = (uitableviewcell*) sender; nsindexpath *indexpath = [self.tableview indexpathforcell:cell];

osx - Sublime: Change Python version used by plugins -

could tell me doing wrong in selecting different version of python sublime text 2 (running on mac)? want sublime use python 3.2 not python 2.6 default version on mac. i want sublime use python 3.2 plugins write. i followed steps mentioned in answer this question . this not working. know not working have written simple plugin print version , prints 2.6.7 my python.sublime-build { //default //"cmd": ["python", "-u", "$file"], "cmd": ["/library/frameworks/python.framework/versions/3.2/bin/python3.2", "-u", "$file"], "file_regex": "^[ ]*file \"(...*?)\", line ([0-9]*)", "selector": "source.python" } plugins use internal version of python included sublime text 2, not python installed on system. from official plugin porting guide sublime text 3 (which in beta): sublime text 3 uses python 3.3, while sublime text...

Emacs key binding for isearch-forward -

i'm using emacs v24.3 on windows 7. i'm trying learn how remap key bindings. i've created .emacs file in home directory , contains 1 line: (global-set-key (kbd "c-f") 'isearch-forward) i start emacs runemacs.exe. find non-existant file, type words (click @ start of text) , type c-f find. i-search: prompt displays , can incrementally search text. far go. the problem is, if behavior suppose same default isearch-forward keystroke, c-s , isn't. when type c-f second time search next occurance of string, thing happens i-search prompt appears in minibuffer. i'm not able search next occurance of string. additionally, del key suppose repeate search in reverse direction. not happen me when search using c-f (though when search using c-s .). so single key mapping seems break 2 things. mapping wrong? or these bugs? if i'm mapping wrong, how map c-f isearch-forward command? along 1 line, add: (define-key isearch-mode-map ...

Rails 4 Routing conflict -

i rewritting rails app did 5 years ago using rails 1.something. when try browse localhost/companies/search_updates/ error... know routing error because when remove resources :companies router.rb thing works fine... how can fixed? , need manually add routes every action create? error when try access localhost/companies/search_updates/ the action 'show' not found companiescontroller controler class companiescontroller < applicationcontroller def index @companies = company.all end def search_updates # execute code search updates # redirect results end end routes resources :accounts resources :companies 'companies/search_updates' => 'companies#search_updates' search_updates.html.erb hello updates! the action 'show' not found companiescontroller rails routes matched in order specified, if have resources :companies above 'companies/search_updates' show action's route resources line m...

security - Is HWND unique among a window station? -

assume created 2 desktops d1 , d2 in winsta0, , d2 has window b. my question is: can thread belonging d1 window b's caption text through getwindowtext(hwnd b, ....)? the hierarchy session => window station => desktop => thread => window. session important when work service, run in isolated session 0. every session has @ least winsta0 interactive window station. session 0 has additional ones services. a window station has multiple desktops, @ least default desktop interact , winlogon desktop, secure 1 that's used login , screen savers. plus additional ones create, d2 desktop. a desktop has single desktop heap window objects stored. every hwnd unique in heap. you'll need getthreaddesktop() hop in hierarchy , go known thread desktop on creates windows. enumdesktopwindows() toplevel windows owned desktop. getting thread id obstacle, you'll need @ least know process. can enumerate threads owned process with, say, createtoolhelp32s...

multithreading - Java Program output printed in random position in Eclipse console -

i have junit class in eclipse project. following: import org.slf4j.logger; import org.slf4j.loggerfactory; /*some other imports*/ public class _junittests{ final logger logger = loggerfactory.getlogger(_junittests.class); public void test(int num){ logger.info("**** tests no."+num+" ***"); /* code */ } @test public static void test1() { test(1); } @test public static void test2() { test(2); } @test public static void test3() { test(3); } @test public static void test1() { test(1); } } when run tests, expecting output such as[class information of info ignored] **** tests no.1 *** /* somethings */ **** tests no.2 *** /* somethings */ **** tests no.3 *** /* somethings */ however, result shown in console messed like: **** tests no.1 *** **** tests no.2 *** **** tests /* somethings */ no.3 *** /* somethings */ /*...

javascript - Vertically centering div caption over responsive image -

i'm trying vertically center absolutely positioned caption on image has flexible height (max-width: 100%;) , having trouble. know need use js detect height of div , adjust top positioning of caption div, i'm having trouble. http://jsfiddle.net/a69xr/ <div id="nav">navigation</div> <div id="slider"> <img src="http://codeword.org/wp-content/uploads/2011/07/aspen_colorado.jpg"> <div class="caption"> <div class="wrap"> <h1>title</h1> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed eiusmod tempor incididunt ut labore et dolore magna aliqua. </div> </div> </div> if know width , height of caption accomplish in css: say caption 400px wide , 90px tall #slider { position:relative; } .caption { position:absolute; margin-left:-200px; margin-top:-45px; top:50%; l...

Set an array value equal to a variable in a dynamically loaded class in Java -

i have seemingly simple question have not been able find solution in week of searching, thought i'd ask. want take array value, anarray[1] , set equal variable in class... otherclass.variableone this easy do, want able use variable name of class want variable from. instead of "otherclass.variableone" want like: string classvar = "otherclass"; anarray[1]=classvar.variableone; i'm not sure whether need set classvar equal like... classname(otherclass) or that. quite new java , i'm having great difficulty. i know seems dumb necessary want do. have looked reflection doesn't seem able need. question is: string classvar = "otherclass"; anarray[1]=classvar.variableone how make work classvar variable refers class contains public static int variableone? please excuse limited programming experience. appreciated. in advance. you need use the reflection api . can use obtain class variable representing "otherclass...

wordpress - Display all Archives -

i have create few posts in latest news section(cpt) , want show posts archive of custom post type ,its showing of july month archives have published few posts in dates (like have posted in may months) archives getting of july month. how archives of may months when click on may(2013) should shows posts of may-2013? and how make sure not using category, should archive only? here function using show archive: <?php wp_get_archives( array( 'type' => 'monthly', 'limit' => 12 ) ); ?> you showing monthly, need try yearly if want show more months. <?php wp_get_archives( array( 'type' => 'yearly') ); ?> there more options run on wp_get_archives(); such postbypost can try. <?php wp_get_archives( array( 'type' => 'postbypost') ); ?> look @ codex see these other parameters can you. http://codex.wordpress.org/function_reference/wp_get_archives please notice removing limit paramet...

android - Text color changes of Row in List View when selected -

i facing problem while selecting items in list view. doing here is, when user selects item list view, color of item(here text) changes cyan (default black). but, when scroll list view, items not selected user, color changes. tried resolved it, have not find solution. below code.. first.xml <listview android:id="@+id/list1" android:layout_width="220dp" android:layout_height="300dp" android:layout_marginleft="45dp" android:layout_margintop="80dp" android:cachecolorhint="#00000000" android:fastscrollenabled="true" > </listview> second.xml <checkedtextview android:id="@+id/txt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentleft="true" android:layout_alignparenttop="true" android:text="" android:te...

html5 - How to make Visual Studio 2010 render HTML with respect to carriage return -

i have put in master page : <!doctype html> <html lang="en"> <head runat="server"> <meta charset="utf-8" /> <title></title> <link href="~/styles/site.css" rel="stylesheet" type="text/css" /> <asp:contentplaceholder id="headcontent" runat="server"> </asp:contentplaceholder> </head> in browser source got html doesn't respect carriage return of masterpage between <meta> , <title> , not formatted beautifully : <!doctype html> <html lang="en"> <head><meta charset="utf-8" /><title> home page </title><link href="styles/site.css" rel="stylesheet" type="text/css" /> </head> how make visual studio 2010 render html respect carriage return

css - Bootstrap Navbar not collapsing. B3 -

i'm trying use bootstrap navbar in project. it's not working well. here link; http://www.uzuntweet.net/uzuntweet/twitter_api_istek_asimi . how can solve problem? you may looking usage of navbar collapse make sure have bootstrap3 <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <button data-target=".nav-collapse" data-toggle="collapse" class="navbar-toggle" type="button"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="#" class="navbar-brand">logo</a> <div class="nav-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="#">home</a></li> <...

ruby on rails - Moving javascript data series to html data attribute breaks Highchart -

i'm trying add highcharts chart rails app, following example http://www.highcharts.com/demo/column-stacked everything works fine when use javascript configure chart, content dynamic want move series data onto data attribute. i've modified 1 line in function (see view options @ link above) series: $('#container').data('chart') and in view <div id="container" style="width:100%;height:172px;" data-chart='<%= @data %>' ></div> in controller @data = [{ name: 'john', data: [5, 3, 4, 7, 2] }, { name: 'jane', data: [2, 2, 3, 2, 1] }, { name: 'joe', data: [3, 4, 4, 2, 5] }] now instead of displaying correct chart in example, have messy chart around 100 data series. is there difference in way data array handled under javascript , ruby cause discrepan...

c++ - Read image file, for compression -

so trying out c++, , start something, , guess, compressing images should simple. and code is: void main(){ struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); file* outfile = fopen("/tmp/test.jpeg", "wb"); jpeg_stdio_dest(&cinfo, outfile); //cinfo.image_width = xinfo.width; //cinfo.image_height = xinfo.height; //cinfo.input_components = 3; //cinfo.in_color_space = jcs_rgb; jpeg_set_defaults(&cinfo); /*set quality [0..100] */ jpeg_set_quality (&cinfo, 75, true); jpeg_start_compress(&cinfo, true); jpeg_finish_compress(&cinfo); } which took , changed bit form site. though can see, xinfo doesn´t exist, , in example found, screenshot library or something. so want feed image got on harddrive , compress it. don´t want make harder necessary. http://www.andrewewhite.net/wordpress/2008...

Disable latex symbol conversion in vim -

Image
the vim editor on kubuntu 13.04 laptop seems have advance feature latex edting, i.e. can convert latex symbols unicode chars on fly , hide source code when cursor not on line. this may great function people, find bit annoying. not sure whether built-in or provided extension, hope can find out way disable it. my vim version 7.4b, list of extensions installed: clang_complete emmet-vim html-autoclosetag neocomplete.vim neosnippet tabular tagbar tlib_vim unite.vim vim-addon-mw-utils vim-airline vim-colorschemes vim-colors-solarized vim-commentary vim-easymotion vim-eunuch vim-fugitive vim-repeat vimrepress vim-r-plugin vim-snippets vim-surround vim-table-mode vim-unimpaired vundle this functionality provided vim's "conceal" feature. vim's tex plugin takes advantage of "conceal" if have set 'conceallevel' 2. see :h ft-tex-syntax . leave 'conceallevel' @ default value of 0 disable concealing. alternatively, put foll...

javascript - Select2 - use JSON as local data -

Image
i can work... var options = [{id: 1, text: 'adair, charles'}] $('#names').select2({ data: options, }) but cant work out how here... alert(json.stringify(request.names)) gives me... [{"id":"1","name":"adair,james"}, {"id":"2","name":"anderson,peter"}, {"id":"3","name":"armstrong,ryan"}] to select2 accept local data load data local array the webpage of jquery-select2 examples contains demo use select2 with local data (an array) . the html <input type="hidden" id="e10" style="width:300px"/> the javascript $(document).ready(function() { var samplearray = [{id:0,text:'enhancement'}, {id:1,text:'bug'} ,{id:2,text:'duplicate'},{id:3,text:'invalid'} ,{id:4,text:'wontfix'}]; $("#e10...

mysql uses primary key instead of index -

i have pretty large table few million rows: id (primary) countrycode status flag_cc i tried following sql statement, quite slow: select id, countrycode, status, flag_cc table id>=200000 , countrycode=3 , status=1 , flag_cc=0 so thought idea add index fasten query up: add index myindex(id, countrycode, status, flag_cc) then queried: explain select id, countrycode, status, flag_cc table id>=200000 , countrycode=3 , status=1 , flag_cc=0 but mysql wants use primary key instead of key. used force index , compared primary key key.. sadly primary key lot faster. how be? , ever possible optimize query if primary key slow? your question "what index?". might want consider reading on them in mysql documentation, here on stackoverflow , using search engine. consider index index in big encyclopedia. there lot of topics defined, index helps find you're looking little faster. but should in index? category (science, entertainment, people, ...)? wh...

Post increment in Java -

this question has answer here: post increment operator not incrementing in loop 4 answers in code segment, [1]int i=0; [2]i = i++; [3]system.out.println(i); in line 2, executed expression first (which assigned 0 i) , should increment value 1. in system.out.println(i) , getting answer 0 instead of 1.can explain reason this? i++ not yield variable, value. i++ yields 0. then incremented 1. then 0 assigned i. summary: precedence of operators maybe not expected. or @ least might've misunderstood actual increment of happening. it's normal show people use of i++ can split 2 lines line after doing incrementation - that's not correct. happens before assignment operator.

how to change the size property of a form text input? -

1) didn't find in css files in relation width of form input. 2) tried : array( 'spec' => array( 'name' => 'name', 'options' => array( 'label' => 'your name', 'size' => '14', <---this doesn't work! ), 'type' => 'text', ), ), without result! so, possible change width (size property) of form text input in zf2 ? thanks put size in attributes instead of options array( 'spec' => array( 'name' => 'name', 'options' => array( 'label' => 'your name', ), 'attributes' => array( 'size' => 14, ), 'type' => 'text', ), ),

iphone - NSString to NSDate issue IOS7 -

i'm using following code convert nsstring nsdate : nsdate *date = [nsdate convertstringtodate:strdate andformatter:@"mm dd"]; + (nsdate *)convertstringtodate:(nsstring *)datestring andformatter:(nsstring *)formatter { nsdateformatter *dateformatter = [[nsdateformatter alloc] init]; // imporant - set our input date format match our input string // if format doesn't match you'll nil string, careful [dateformatter setdateformat:formatter]; dateformatter.timezone = [nstimezone systemtimezone]; return [dateformatter datefromstring:datestring]; } nsstring @"07 15" . nsdate nil . on simulator fine on device ios7 nil. do have suggestions it? if code works in ios 6, may bug in ios 7. sure file bug report if think that's case. if doesn't work in ios 6, may month , day aren't sufficient specify date. try adding year , see if valid date way. note questions ios 7 should posted apple's developer forum...

c# - Can I use LINQ to compare what is missing, added or updated between two collections -

i have following class. make compare added equals method: public objectivedetail() public int objectivedetailid { get; set; } public int number { get; set; } public string text { get; set; } public override bool equals(object obj) { return this.equals(obj objectivedetail); } public bool equals(objectivedetail other) { if (other == null) return false; return this.number.equals(other.number) && ( this.text == other.text || this.text != null && this.text.equals(other.text) ); } } i have 2 icollection collections: icollection<objectivedetail> _obj1; // reference icollection<objectivedetail> _obj2; // may have more, less or different objectdetails reference. the common tfield collections objectivedetailid. there way can use 3 linq expressions create: a collection of rows in _obj2 , not _obj1 a collectio...

How many times should I tell ios app user he is on Carrier network? -

according apple (9.3 , 9.9 https://developer.apple.com/appstore/resources/approval/guidelines.html ) need tell ( doesn´t explicitly understanding ) user of app not on wifi network , if streams content of app cost him lots of money. what can't find out is : have give user constant warnings e.g for every link clicks or enough give him warning one time while in app ? mean in app hours (hopefully :-)). edit: after rereading https://developer.apple.com/appstore/resources/approval/guidelines.html see have not totally understood guideline. it says : 9.3 audio streaming content on cellular network may not use more 5mb on 5 minutes 9.9 video streaming content on cellular network longer 10 minutes must use http live streaming , include baseline 64 kbps audio-only http live stream so understanding need tell user usage after 10 minutes or after 5mb download after 5 minutest ? no can´t be! can it? my program container around youtube streaming video them.

mysql - Is it possible to embed PHP in Qt (Symbian)? -

since qt sdk symbian not support mysql driver (spent 5 days trying create 1 no success), possible embed php code in c++/qt ? i.e. able put in symbian app php code connect remote db , insert data tables ... $mysqli = new mysqli("localhost", "username", "pass", "db"); if ($mysqli->connect_errno) { echo "failed connect: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; } and after insert statement ... do know if it's feasible ? it bad design - if don't want store data locally (you can use sqlite 3 driver symbian), shouldn't have local php server on phone, should rather have remote php server database resides , create api communicate phone.

java - Assert package call directions with AspectJ -

Image
let's assume have following package structure some.package |-aaa.private |-aaa.public |-bbb.private |-bbb.public my architecture demand, make calls some.package.aaa..* some.package.bbb.public..* , vice versa, calls some.package.bbb..* some.package.aaa.public..* . in other words, if traverse "major" package border (e.g. aaa bbb), want allow calls public package in root of other major package. is possible define aspectj pointcut, selects joinpoints violate rule? i.e. if want write declare error: insomemajorpackage() && callingnonpublicpackageofothermajorpackage() : "please make calls public interfaces of other major packages"; is there way define 2 pointcuts, such enforce rule? attention: lengthy answer because of code samples. i created sample project can downloaded scrum-master.de . package structure follows: as can see, below main application package de.scrum_master there 3 "major" packages...

php - Secure admin system with hiding admin URLs -

is idea hide admin urls in order prevent being damaged hackers? how can hacker enters admin area without knowing url if hacker have username , password? what mean security through obscurity , very bad idea...

c# - Importing existing class and use it's form visual studio -

i'm using visual studio 2010 express c# project. partner , divided work, each of worked on different machine. how merge projects in one? when run imported clases lot of errors, of them seem because cant use form created on machine. how import these windows form well?? thanks i suggest using sort of revision control system. there's online services github can that. in meantime, you'll have manually merge changes. alternatively, could create new project, check revision control, check out in 2 places, copy changes each have made over-top, , try merging... ymmv.

spring - Storing trailing zeroes in database with JPA and Oracle -

i need store prices in database. i'm using jpa, i've got model this: @entity @table(name="products") public class product { @id @generatedvalue(strategy=generationtype.identity) private long id; @column(name="price") private float price; } the problem when fill price form inputs values "4.20", on oracle database "4.2", losing trailing zero. how can solve problem? edit: since i'm using jpa, have avoid writing queries in native oracle dialect. store products (with prices) write em.persist(product) , em entitymanager you can't solve it, , i'd suggest it's not problem. that's how oracle stores number values: least precision needed. if entered price 4.00 stored 4 . note java won't default 2 decimals either when displaying value. need specify number of decimal places. and, if possible, i'd use bigdecimal instead of float price. float type isn't precise. alte...

ios - Run UIViewController inside UINavigationController as a second view of UISplitViewController -

i have problem trying access navigation controller of view controller it, returns nill me, though shown within navigation controller. here have (i have split view controller, presented tab controller master , viewcontroller (inside navigation controller) detail): firstdetailviewcontroller *fdvc = [[firstdetailviewcontroller alloc] initwithnibname:@"firstdetailviewcontroller" bundle:nil]; uinavigationcontroller *fdvcnav = [[uinavigationcontroller alloc] initwithrootviewcontroller:fdvc]; nsarray *ipadvcs = [[nsarray alloc] initwithobjects:tabcontroller, fdvcnav, nil]; uisplitviewcontroller *splitvc = [[uisplitviewcontroller alloc] initwithnibname:nil bundle:nil]; [splitvc setviewcontrollers:ipadvcs]; [[splitvc view] setbackgroundcolor:[uicolor colorwithpatternimage:[uiimage imagenamed:@"splitviewcontrollerbg"]]]; [splitvc setdelegate:fdvc]; [[self window] setrootviewcontroller:splitvc]; [[self window] makekeyandvisible]; but when i'm trying access navig...

javascript - Ace Editor and meteor for collaborative code editing: Observe hangs app -

i trying make basic collaborative code editor in meteor using ace editor. javascript follows: var file meteor.startup(function(){ session.set("file", "fileid"); var query = files.find({_id : session.get("fileid")}); var handle = query.observe({ changed : function(newdoc, olddoc) { if(editor !== undefined){ console.log("doc changed ", olddoc.contents, "to ", newdoc.contents); editor.setvalue(newdoc.contents); } handle.stop(); } }); editor.getsession().on('change', function(e) { // update file collection if(session.get('file')) { files.update({_id: session.get("file")}, { $set : { contents : editor.getvalue() } }); } }); }); the ed...

php - Joomla 3 using Wright - How to find CSS? -

i've got joomla 3 website using wright framework. when try inspecting element frontend, says css coming http://example.com/templates/template/wright/css/template.css.php but when go there, there's no css. , coming template.css.php when inspect frontend. what or should look? thanks! according documentation on template structure (getting started wright) the css folder has several files start # file.css. css files prefixed # automatically loaded wright, in numerical order. so files looking for, should in css folder.

java - image corrupted by FileUpload -

i need make http server recieving , sending images , text(less 100 characters) client. planning use json or google protocol buffer. i studied "httpuploadserver" example in netty 4.0.6 package. then, deleted in handler except things dealing multipart post requests. here's part struggling with. private void writehttpdata(interfacehttpdata data) { fileupload fileupload = (fileupload)data; try { file file = fileupload.getfile(); file.renameto(new file("c:\\savedfiles\\"+file.getname())); } catch (ioexception e) { e.printstacktrace(); } } when call getfile(), gives me corrupted file. i've tested zip files, , images(png, jpeg). (btw. using postman add-on test server, wrong headers not problem) is there way make right? found answer on github change private static final httpdatafactory factory = new defaulthttpdatafactory(defaulthttpdatafactory.minsize); to private static final httpdatafactory...

ios - Draw circle arc with GL_TRIANGLE_STRIP -

Image
i trying write method draw arc start angle end angle using gl_triangle_strip. i've written following code have following problems: i can't seem proper angles working. seem offset should odd amount (not 90/45/180). if total angle between 2 more 180 degrees arc draw smaller angle on circle between two. i.e if total angle 200 degrees draw arc 160 degrees on other part of circle. i've spent way time trying right , figured helpful have pair of eyes looking @ code. image below shows triangle strips trying create between angles. i'll applying texture after figure part out. help! -(void) drawarcfrom:(cgfloat)startangle to:(cgfloat)endangle position:(cgfloat)position radius:(cgpoint)radius { cgfloat segmentwidth = 10.0; cgfloat increment = fabsf(endangle - startangle) / segmentwidth; int numsegs = fabsf(endangle - startangle) / segmentwidth; int direction = (endangle - startangle > 0) ? 1 : -1; ccvertex2f vertices[numsegs * 2]; (int =...

file storage - Store class instance - Windows store application -

i'm bit new programing windows store app.so question how can save instance of class in xml or binary file.i tried code isn't working. hope 1 can steer me in right direction . you can serialize instance using code /// <summary> /// deserializes xml. /// </summary> /// <typeparam name="t"></typeparam> /// <param name="xml">the xml.</param> /// <returns>the instance</returns> public static t deserializexml<t>(this string xml) { var bytes = encoding.utf8.getbytes(xml); using (var stream = new memorystream(bytes)) { var serializer = new datacontractserializer(typeof(t)); return (t)serializer.readobject(stream); } } /// <summary> /// serializes specified instance. /// </summary> /// <param name="instance">the instance.</param> /// <returns>xml...

ember.js - how to really find out only once if Ember finishes its ajax request and DS.RecordArray is completely filled -

i have tried gazillion ways , nothing efficient. last attempt - works little ugly tradeoff this: app.usersroute = em.route.extend({ model: function() { return app.user.find({}).then(function(response) { return response; }); } }); the problem - i'd love know making synchronous call. html/dom won't finish loading until returns. another thing i'd love know if omit empty object {} find - promise function gets called immediately. promise! now other methods i've tried following have flaws: observing content.lastobject.isloaded on controller implementing arraycontentdidchange ember.arraycontroller - gets triggerd multiple times array getting filled. - i have tried gazillion ways , nothing efficient. i don't know if tried hooking aftermodel function of route addition added not long ago , available in rc6: app.usersroute = em.route.extend({ aftermodel: function(users, transition) { console.log(users.get('length...