Posts

Showing posts from May, 2014

wpf - C#.Net Unspecified String to Color Converter -

in situation have list of customers represent colors. how make converter generate color based off customer name, or portion of name? public class customer { public string customername {get; set;} //other properties unrelated question.... } then in xaml somewhere able following: <textblock text="{binding customername}" foreground="{binding customername, converter={staticresource mystringtocolorconverter}}"/> i don't need whole converter written out, ideas on how convert unspecified string color. you take binary values of first 3 characters of name , convert red, green, , blue values. thing though regular names begin (assuming upper case characters) 26 of 256 possible binary values you'll need adding , multiplying in 0-1 range. if want more 26 discrete values each of red, green, , blue consider aggregating value multiple letters. once have number in 0-1 range, next thing want normalize values avoid ...

javascript - How to detect any click on the page? -

i want catch click event on elements of page. can not catch click on specific page elements. see example https://jsfiddle.net/rdnf5m1f/ $(function() { $(".profile").on( "click","a", function() { console.log(1); return false; }); // below not work $("body").on( "click","*", function() { console.log(2); }); $("body").click(function() { console.log(2); }); $(window).click(function() { console.log(2); }); }); why? following need "capture all, except some". add class 'nocapture' elements don't want capture, , use script: jquery('*:not(.nocapture)').on('click', function(e){ e.stoppropagation(); console.log('element clicked', this); })

jodatime - Are time zones lost when passing them via DateTimeFormatter to DateTimeFormatterBuilder? -

i need parse date using couple of date formats assuming particular time zone , output in time zone (i.e. utc). hoping datetimeformatterbuilder appears time zone information attached parsers , printers lost/ignored? see test , output: import org.joda.time.datetime; import org.joda.time.datetimezone; import org.joda.time.format.datetimeformat; import org.joda.time.format.datetimeformatter; import org.joda.time.format.datetimeformatterbuilder; import org.joda.time.format.datetimeparser; import org.junit.test; public class jodabuildertest { @test public void atestoftimezoneretentionofformatterspassedtobuilder() throws exception { string [] parsepatterns = new string [] { "mm/dd/yyyy hh:mm:ss", "mm/dd/yyyy" }; string printpattern = "yyyy-mm-dd't'hh:mm:ss.ssszz"; string inputstring = "08/03/2015 01:01:01"; datetimezone tz = datetimezone.foroffsethours(-3); datetimeparser[] parsers = new datetimeparser[...

Matlab bsxfun(@times,...,...) equivalent in R -

has r got equivalent of matlab bsxfun(@times,a,b) ? suppose 1 perform element wise multiplication on matrix a,b : matlab: a=[1 0 3 -4]; b=[0 1 5 7; 2 9 -3 4]; bsxfun(@times,a,b) = [0 0 15 -28; 2 0 -9 -16] r: a<-c(1,0,3,-4) b<-matrix(c(0,2,1,9,5,-3,7,4),nrow = 2,ncol = 4) * b = matrix(c(0,0,3,-36,5,0,21,-16),nrow = 2,ncol = 4) any idea on way r gets results of above of a*b , expecting identical matlab bsxfun(@times,a,b) edit: bsxfun("*",repmat(a,2,1),b) # using r {pracma} best do column major matrices, since r-convention: > b<-matrix(c(0,2,1,9,5,-3,7,4),nrow = 4,ncol = 2) > a*b [,1] [,2] [1,] 0 5 [2,] 0 0 [3,] 3 21 [4,] -36 -16 if take original construction of b bit of unpleasant surprise when try use sweep : > b2<-matrix(c(0,2,1,9,5,-3,7,4),nrow = 2,ncol = 4) > sweep(b2, 2, a, '*') [,1] [,2] [,3] [,4] [1,] 0 0 15 -28 [2,] 2 0 -9 -16 since matrix functio...

c# - UDP multicasting with IPAddress.Any -

Image
good day all i going through msdn website try familiarize mystelf multicasting , how works. i'm wondering: when 1 use ipaddress.any it refers commented out line this link //ipaddress localip = ipaddress.any; i have seen on multiple occasions, ipaddress.any mean? update a quick googling reveals: what's ipaddress.any - msdn forums : ipaddress.any listen on ip addresses assigned pc. example, if connected network via wireless , wired, there 2 ip addresses assigned. means listen requests on both ip addresses. if take ip of wired receive requests nic. as can see, specifying address listen on ( effectively, equivalent ipaddress.parse("0.0.0.0") ) , not specific multicasting. see how udp multicast across local network in c#? example of latter's implementation.

c# - Convert Docx to html using OpenXml power tools without formatting -

i'm using openxml power tools in project convert document (docx) html, using code provided sdk produces elegant duplicate in html form.(github link : https://github.com/officedev/open-xml-powertools/blob/vnext/openxmlpowertoolsexamples/htmlconverter01/htmlconverter01.cs ) however looking @ html markup, html has embedded styling. is there way of turning off , using plain , simple <h1> , <p> tags ? i know embedded styling formatting taken care of bootstrap. the embedded styling follows : <p dir="ltr" style="font-family: calibri;font-size: 11pt;line-height: 115.0%;margin-bottom: 0;margin-left: 0;margin-right: 0;margin-top: 0;"> <span xml:space="preserve" style="font-size: 11pt;font-style: normal;font-weight: normal;margin: 0;padding: 0;"> </span> </p> this can see fine if want direct copy, not if want control style yourself. in c# code have made following ajustments : additionalcss ...

haskell - Basic Yesod Hello World! giving me parse error -

i beginning learn yesod through book developing web applications haskell , yesod. first thing book has after installing few requirements write hello world! despite copying program verbatim book, getting parse error. bit of background, have no experience in web development, , knowledge of haskell pretty contained learn haskell, quite lost. here said code: -- hello world yesod {-# language templatehaskell, typefamilies, quasiquotes, multiparamtypeclasses, overloadedstrings #-} import yesod data helloworld = helloworld mkyesod "helloworld" [parseroutes | / homer |] instance yesod helloworld gethomer :: handler rephtml gethomer = defaultlayout [whamlet | hello world! |] main :: io() main = warpdebug 3000 helloworld the compiler telling me this: c:\haskell\yesod>runhaskell helloworld.hs helloworld.hs:11:1: parse error (possibly incorrect indentation or mismatched brackets) i got file load (with warnings) deleting spaces before pipes in quas...

r - Using a reactive expression in an if statement in shiny -

i writing shiny app output should depend on value of variable calculated in reactive expression in shiny. instead of reproducing actual app believe have recreated problem following simple app: ui.r file: library(shiny) shinyui(pagewithsidebar( headerpanel("illustrating problem"), sidebarpanel( numericinput('id1', 'numeric input, labeled id1', 0, min = 0, max = 100, step =5) ), mainpanel( h4('you entered'), verbatimtextoutput("oid1"), verbatimtextoutput("odic") ) )) server.r file library(shiny) shinyserver( function(input, output) { output$oid1 <- renderprint({input$id1}) x<-reactive({5*input$id1}) if (x()>50) output$oid2<-renderprint({"you entered number greater 10"}) else output$oid2<-renderprint({"you entered number less or equal 10"}) } ) if run error: error in .getreactiveenvironment()$currentcontext() :...

bash - Change part of script file by sed or awk -

i'm trying write sed command change script automatically. script using apply sql patches database based on provided version of application. better understandings simplify script , source looks like # before if [ "$branch" = "trunk" ] apply_patch.sh 1.0 apply_patch.sh 2.0 apply_patch.sh trunk elif [ "$branch" = "2.0" ] apply_patch.sh 1.0 apply_patch.sh 2.0 elif [ "$branch" = "1.0" ] apply_patch.sh 1.0 fi # after based on 2 input arguments (current version , next version) need change script following # before if [ "$branch" = "trunk" ] apply_patch.sh 1.0 apply_patch.sh 2.0 apply_patch.sh 2.1 apply_patch.sh trunk elif [ "$branch" = "2.1" ] apply_patch.sh 1.0 apply_patch.sh 2.0 apply_patch.sh 2.1 elif [ "$branch" = "2.0" ] apply_patch.sh 1.0 apply_patch.sh 2.0 elif [ "$branch" = "1.0...

how to break database backup file? -

i created backup of database, , trying upload says database file big, , because of can't upload it. so there way break down sql, database backup file, pieces or tables, can upload them separately. or there other way it. thanks this sounds using phpmyadmin this, correct? in case, have 2 choices: 1.) make smaller backups selecting few tables @ time but can complicated when comes managing indexes, etc. abetter option to: 2.) use database gui tool such sqlyog restore backup. this, need make sure have remote access database - depend on hosting situation, shared hosts allow through remotesql in cpanel. to accurate, need more details.

django - Serialize Timezone Object -

i have model has timezone field using django-timezone-field . stores pytz object in field. receive in response object's zone instance.timezone_field.zone . with field i'm using readonlymodelviewset , when issuing request, error <dsttzinfo 'us/arizona' lmt-1 day, 16:32:00 std> not json serializable . it makes sense why i'm getting error, object not json serializable. how serialize use zone subfield? to show structure of object field, in shell can zone by: obj = mymodel.objects.get(id=1) obj.timezone.zone "us/pacific" i ended making custom serializer field , using zone field on timezone object. class timezonefield(field): "take timezone object , make json serializable" def to_representation(self, obj): return obj.zone def to_internal_value(self, data): return data class appsettingsserializer(modelserializer): timezone = timezonefield() class meta: model = userappsettings ...

c# - WPF container artifacts when content is more than container -

Image
i'm creating styles control , faced strange problem. just compare: the normal slider: what when decrease image container: what is? that's not border, i'm not use borders or that. affect's not images. it's example. how avoid behavior? the code when decreased container(thumb) size: <track.thumb> <thumb x:name="thumb" height="15" width="15"> <thumb.template> <controltemplate targettype="thumb"> <image source="../images/player/slider_thumb.png" height="17" width="17" /> </controltemplate> </thumb.template> </thumb> </track.thumb>

generate machine code directly via LLVM API -

with following code, can generate llvm bitcode file module: llvm::module * module; // fill module code module = ...; std::error_code ec; llvm::raw_fd_ostream out("anonymous.bc", ec, llvm::sys::fs::f_none); llvm::writebitcodetofile(module, out); i can use bitcode file generate executable machine code file, e.g.: clang -o anonymous anonymous.bc alternatively: llc anonymous.bc gcc -o anonymous anonymous.s my question is: can generate machine code directly in c++ llvm api without first needing write bitcode file? i looking either a code example or @ least starting points in llvm api, e.g. classes use, nudging me in right direction might enough. take @ llc tool source , spcifically compilemodule() function. in short, creates target , sets options via targetoptions , uses addpassestoemitfile() , asks passmanager perform planned tasks.

javascript - Is it possible to use promises for this example? -

i trying write basic program work this: enter name: _ enter age: _ name <name> , age <age>. i've been trying figure out how in node without using prompt npm module. my attempt @ was: import readline 'readline' const rl = readline.createinterface({ input: process.stdin, output: process.stdout }) rl.question('what name? ', (name) => { rl.question('what age? ', (age) => { console.log(`your name ${name} , age ${age}`) }) }) however, nested way of doing seems weird, there anyway can without making nested right order? zangw's answer sufficient, think can make clearer: import readline 'readline' const rl = readline.createinterface({ input: process.stdin, output: process.stdout }) function askname() { return new promise((resolve) => { rl.question('what name? ', (name) => { resolve(name) }) }) } function askage(name) { return new promise((resolve) => { rl.ques...

c# - ListView SelectedItems binding: why the list is always null -

i'm developing uwp app, mvvm light , behaviours sdk. defined multi selectable listview: <listview x:name="memberstoinvitelist" ismultiselectcheckboxenabled="true" selectionmode="multiple" itemssource="{binding contacts}" itemtemplate="{staticresource membertemplate}"> </listview> i'd like, button binded mvvm-light relaycommand , obtain list selected items: <button command="{binding addmemberstoevent}" commandparameter="{binding elementname=memberstoinvitelist, path=selecteditems}" content="ok"/> the relaycommand (of mvvm-light framework): private relaycommand<object> _addmemberstoevent; public relaycommand<object> addmemberstoevent { { return _addmemberstoevent ?? (_addmemberstoevent = new relaycommand<object>( (selectedmembers) => { // t...

python - Pivot Pandas Dataframe and calculate 'columns' parameter -

say have following dataframe: import pandas pd df = pd.dataframe() df['id'] = [1, 1, 1, 2, 2] df['type'] = ['a', 'b', 'q', 'b', 'r'] df['status'] = [0, 0, 1, 0, 1] >>> df id type status 0 1 0 1 1 b 0 2 1 q 1 3 2 b 0 4 2 r 1 >>> i want group dataframe 'id' , reshape have "type" variable , "status" variable each item within group. see below: type1 type2 type3 status1 status2 status3 id 1 b q 0 0 1 2 b r nan 0 1 nan the number of rows in output dataframe depend on max number of records in 1 group of ids. i believe pivot function want use here. however, calls "columns" parameter believe should id of each item within each group. have clunky way of calculating this, appreciate advice on...

algorithm - What is wrong with this reasoning to determine the upper bound? -

i given question in algorithm class is 2^{2n} upper bounded o(3^n)? now clear 2^2n 4^n, , 4^n can't upper bounded 3^n. however if take log on both sides on lhs 2n on rhs kn (where k constant) 2n can upper bounded kn, contradicting of more obvious claim above. doing wrong in reasoning? essentially, reasoning boils down statement: if log f(n) ≤ c log g(n) constant c, f(n) = o(g(n)). this statement isn't in general true statement, though. 1 way see find counterexamples: if f(n) = n 4 , g(n) = n, log f(n) = 4 log n , log g(n) = log n. it's true there's multiple of log n that's bigger 4 log n, n 4 ≠ o(n). if f(n) = 4 n , g(n) = 2 n , log f(n) = 2n , log g(n) = n. there's multiple of n makes bigger 2n, 4 n ≠ o(2 n ). to @ why doesn't work, notice c log g(n) = log g(n) c , multiplying log constant equivalent raising original function large power. can reason big-o of function multiplying constant, can't reason raising p...

OAuth Spec: why do some implementations return an access_token + access_token_secret and others just an access token? -

case in point: the facebook https://graph.facebook.com/oauth/access_token endpoint, in handing off code access token, returns access_token , expires . instagram seems same. on other hand, twitter https://api.twitter.com/oauth/access_token returns both access_token , access_token secret . subsequently, when accessing facebook api endpoints, send access_token request. on other hand, accessing twitter endpoints requires signing request secret well. the reason ask: i'm implementing own oauth web app api, , make sure conform standards. designed act twitter, don't understand why facebook & instagram act in way do. facebook , instagram use oauth 2.0 protocol whereas twitter uses oauth 1.0a protocol. posts here , here may understand differences.

php - Echo string with background color -

i creating local chat echo message in strings. want put background color on strings fb messenger. problem when type background: red; have red background. when put background:#0612e; not effect. how solve problem? echo '<div style="border: 1px solid; background:#0612e; border-radius:4px; height: auto; padding-right:8px; text-align:right; font-size:0.9em;">' . '<div style="color:#01541d;">' . $messages->username . "</div> message: " . $messages->msg . '</div>' . "<br/>"; } when see #0c0c0c, see hexadecimal representation of rgb integers. each color value made of 2 characters, totaling between 0 , 255. example, #00ff00 0 red, 255 green, , 0 blue. particular problem hex code in question is 5 characters long, , needs character.

ios - How to reverse an AAC audio file? -

i able record , playback in reverse (thanks couple examples), give user ability select recorded .aac file table view , reverse it. have tried changing input file url url of user's file, either static or audio file 0.0 duration. type of reversal possible aac files? if so, how correct settings accept it? recordedaudiourl = [nsurl urlwithstring:[savedurl stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]]; nslog( @"url %@", [recordedaudiourl absolutestring]); flippedaudiourl = [nsurl urlwithstring:[reverseurl stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]]; nslog( @"url %@", [flippedaudiourl absolutestring]); audiofileid outputaudiofile; audiostreambasicdescription mypcmformat; mypcmformat.msamplerate = 16000.00; mypcmformat.mformatid = kaudioformatlinearpcm ; mypcmformat.mformatflags = kaudioformatflagscanonical; mypcmformat.mchannelsperframe = 1; mypcmformat.mframesperpacket = 1; mypcmformat.mbitsperchannel = 16; mypcmform...

facebook can_upload is false except for one album -

if query "me/albums?fields=can_upload,name" graph explorer can_upload true 1 album (from total of 13 albums) my permissions (from access token debugger): create_note photo_upload publish_actions publish_stream share_item status_update user_photos video_upload what missing? damn, got solution. i've set permission post visibility app me. the album can_upload true visible me, too.

php - how to auto decrement a column in the database daily -

i have column name remainingdays. counts remaining days since last donation of user. how can auto decrement column daily. example column has value of 90 tommorow becomes 99. automatically updates database without users interaction. i add date field database. each time donation made, update date , reset counter. then whenever need check or current value of counter, change select using to_days function in mysql converts date number-of-days value. select current_count - to_days(now())-to_days(date(last_donation)) result so if last update made yesterday, counter value reset beginning , yesterdays date have been recorded. if value set 100, today when select return 99 , in ten days return 90. this how i'd anyway , assumes mysql i'm sure type of functionality available in sql database sever environments.

javascript - camera js thumbanil issue -

i'm using camera js main slider, , works fine, except im trying use thumbnail functions better look, doesn't seem working. http://www.pixedelic.com/plugins/camera/ the camera js document suggests need have option 'thumbnails:true' , insert data-src="images/main_image.jpg" yet doesn't seem work yet. what did miss? here code: <div class="slider"> <div data-thumb="images/main_image.jpg" data-src="images/main_image.jpg" style="background-size:cover;"></div> <div data-src="images/main_image.jpg" style="background-size:cover;"></div> <div data-src="images/main_image.jpg" style="background-size:cover;"></div> jquery(document).ready(function($) { jquery('.slider').camera({ //here declared settings, height , presence of thumbnails pagination: true, navigation: true, fx: 'scrollleft', height:'960px...

javascript - Display ReportViewer (ReportViewer1.ServerReport.ReportServerCredentials) in a separate, dragable window -

i have ssrs report displaying fine in .aspx page, except needs display in own window. now, can form url report server , open this, not need in case. string url = "http://testserver/reportserver/pages/reportviewer.aspx? %2fsqlreports%2ftestreport&rc:parameters=collapsed&id=" + id.tostring() + ""; string script = "window.open('" + url + "','')"; if (!clientscript.isclientscriptblockregistered("newwindow")) { scriptmanager.registerclientscriptblock(this, this.gettype(), "newwindow", script, true); } what need code-behind, open way forming reportview on aspx page having it's parameters passed along it: (reportviewer1.serverreport.reportservercredentials) i have researched quite time , cannot seem find definitive answer solution this. i've tried following: ajaxtoolkit:modalpopupextender (there way make draggable breaks in ie10 due known bug). pa...

finding xpath for elements in applications built on angularjs -

the application under test built on angular because of xpaths failing locate element . using selenium web diver automating tests , google chrome browser. can kindly specify how break down angularjs components basic html elements while creating xpath or other way can adapt find exact element on page. any link or path or tips follow. i have searched lot no luck till now. starting covering general concerns. when testing angularjs applications, timing issues common - partially why have tools protractor built test angularjs applications. makes unique works in sync angular, knowing when ready interacted with. provide angularjs specific locators makes locating elements easier, samples: element.all(by.repeater("item in items")); element(by.binding("mybinding")); element(by.model("mymodel")); if can, should consider switching protractor - test flow natural - no explicit waits, lot of convenient syntactic sugar , more element-locating opti...

c# - Application copy protection using encrypted files -

i developing desktop app , want start selling @ point, start put license data (ex: start date, license duration, etc...) in encrypted file, during runtime of app decrypt file , license data check it. the question is method enough copy protection ? this question broad short answer is: depends on threat model. since application have decrypt file check contents, file have on client machine (along decryption key) if wants crack it, they'll have field day it. (they can attach debugger process , trace through code deals protection , either patch executable or figure out how generate valid license file. among other possible approaches didn't think of.) if you're serious protecting software and think program popular many, many users try pirate it, buy professional solution - you'll professional advice on setting , protection have been tested in other products. if that's expensive, re-evaluate whether need copy protection or not. home-brewed schemes can c...

smack - XMPP Muc Queries -

i using session resumption large resumption time - 24 hours - http://xmpp.org/extensions/xep-0198.html . have doubt muc, if in group , client rejoin, need leave , rejoin group new messages. non muc stanzas, kept in offline storage , delivered reconnect. not sure muc. if not case don't think there advantage of being online - except fetch occupants list. again not sure if occupant joined event if client offline.

excel - I need to find a particular cell based on 3 factors: Age, $ amount -

i need able enter age , coverage amount , want able go corresponding cell , tell me price product. the pricing sheet have age on y axis , coverage on x axis. example: have 50 year old wants 20,000 in coverage. go down y axis , find 50 , on over x axis 20,000. i want tell me amount @ particular cell. if not clear enough on mean let me know , try , further explain. i not have code of yet because i'm not sure start. in advance. if x axis in sorted order (which seems given values increasing in coverage) use match function axis. y axis, same scenario on age. question becomes whether want exact matching or nearest ceiling/floor. index( <full table range $a$1:$abc1000>, match( $agesource, <full axis $a$1:$a1000>), match( $coverage, <full axis $a$1:$abc1> ) )

php - Apache doesn't work after updating to php7 on osx 10.11 -

after updating php7 on osx, php -v returns this: dyld: library not loaded: /usr/local/opt/libxml2/lib/libxml2.2.dylib referenced from: /usr/local/bin/php reason: incompatible library version: php requires version 12.0.0 or later, libxml2.2.dylib provides version 10.0.0 trace/bpt trap: 5 also localhost receives: you don't have permission access / on server. additionally, 403 forbidden error encountered while trying use errordocument handle request.

javascript - How to convert string of objects to JSON object in angular transformRequest -

so i'm receiving string: {"id":"0-worfebvjyyvqjjor","size":17,"price":921,"face":"( .-.)","date":"mon jan 04 2016 22:55:30 gmt+0000 (gmt standard time)"} {"id":"1-ifma3yxxccgzaor","size":19,"price":98,"face":"( .o.)","date":"fri jan 08 2016 16:11:25 gmt+0000 (gmt standard time)"} {"id":"2-sa3iurvt4hv0lik9","size":14,"price":659,"face":"( `·´ )","date":"sun jan 03 2016 06:20:28 gmt+0000 (gmt standard time)"} {"id":"3-bc3tf55q9vx11yvi","size":33,"price":361,"face":"( ° ͜ Ê– °)","date":"fri jan 01 2016 22:49:22 gmt+0000 (gmt standard time)"} here in console.log(data): var warehouseresource = $resource('/api/products?limit=10', {}, { query: { ...

babeljs - Using react-router w/ brunch/babel -

i'm attempting use react-router in brunch/babel setup. in app.js have: import react "react" import reactdom "react-dom" import { router, route, link } "react-router" this gives me: uncaught error: cannot find module "history/lib/createhashhistory" "react-router/router" when looking @ referenced line see: var _historylibcreatehashhistory = require('history/lib/createhashhistory'); when inspecting app.js that's generated via brunch see: require.register('history/createbrowserhistory', function(exports,req,module) { ... }); how go fixing createbrowserhistory gets imported properly? the module history listed peer dependency react-router , means need install through command npm install history --save .

javascript - Code won't run because I can't output more than one variable in document.write -

my code won't run when try display more 1 variable in document.write section of code. i'm pretty sure doing right. <script type="text/javascript"> var name = prompt("welcome fruity store. name?",""); var product = prompt("what name of product like?",""); var price = 1*prompt("how cost?",""); var quantity = 1*prompt("how many of fruit like?",""); var discount = 1*prompt("what discount of product in decimal form?",""); var costoforder = (price*quantity); var discounted = (price*quantity*discount); var totalorder = (costoforder - discounted); document.write("thank placing order " +name ) document.write("<p>the cost of buying " +quantity "of " +product "is " +costoforder </p>) document.write("<p>the discount purchase " +discounted </p>) document.write("<p>with discount,...

java - How to store a splitted string into an array? -

the problem here that, don't know how insert array, given for-each loop. wanted that, for-each string splitted, splitted string gets stored in array, instead of printing out. system.out.println("input string: "); scanner s = new scanner(system.in); string input = s.nextline(); string[] longstr = input.split("(?<=\\.\\s)"); system.out.println("output:\n"); for(string shortstr : longstr){ system.out.println(shortstr); } input string: imagine me , you, do. think day , night. it's right. output imagine me , you, do. i think day , night. it's right. proposed code output for(string shortstr : longstr){ //store shortstr in array } //call arrays of shortstr same output dictated above is possible? arraylist<string> result = new arraylist<>(); for(string shortstr : longstr){ //system.out.println(shortstr...

Swift crashing when casting NSObject subclass to a non-objc protocol -

i've spent time figuring out. code crashes: public protocol fourleggedanimal: anyobject { } public class animal: nsobject { } public class dog: animal, fourleggedanimal { } public class animalproperty<kind: animal>: nsobject { let animal: kind public init(animal: kind) { self.animal = animal } } public class fourleggedanimalproperty<kind: animal>: animalproperty<kind>, nstextfielddelegate { public override init(animal: kind) { /// since cannot express in swift kind should animal /// subclass confirming particular protocol, use force-cast /// not pretty solution, there aren't options. /// , crashes. let fourleggedanimal = animal as! fourleggedanimal print(fourleggedanimal) super.init(animal: animal) } } let dog = dog() let property = fourleggedanimalproperty(animal: dog) the code crashes in swift's library's getgenericpattern() function when att...

javascript - AngularJS ng-repeat does not render -

i practicing angularjs. my problem : ng-repeat not repeat array. index.html: <!doctype html> <html ng-app="store"> <head> <link rel="stylesheet" type="text/css" href="node_modules/bootstrap/dist/css/bootstrap.min.css" /> </head> <body ng-controller="storecontroller store"> <div ng-repeat="product in store.products"> <h1> {{product.name}}</h1> <h2> ${{product.price}}</h2> <p> {{product.description}} </p> <button ng-show="product.canpurchase">add cart</button> </div> <script type="text/javascript" src="node_modules/angular/angular.min.js"></script> <script type="text/javascript" src="app.js"></script> </body> </html> app.js: (function(){ var app = angular.module('store'...

flex error "start-condition stack underflow" with "%option full" on parsing files with chinese character -

i have flex scanner run correctly long time, on files chinese characters. want make faster, , add "%option full", indeed 3x faster. may fail on files comments contain chinese characters. the error message "start-condition stack underflow". i add printing statement lex source code, , find scanner print error in start condiiton sc, have not run code segment contain "yy_push_state(sc)". think there may overflow in flex buffer. so do? for historical reasons (or something), if use %option full or %option fast , flex default producing 7-bit scanner (i.e. %option 7bit ). that's unsafe, since 7-bit scanner not attempt verify scanned text consists of 7-bit ("ascii") characters, , behaviour in case encounters character high-order bit set undefined. happen if input utf-8 or multibyte. so need specify %option 8bit full . increase size of scanner tables, these days might not matter much. might want try %option 8bit full ecs interm...

c# - Which is the best way to Prevent Bad word entry in Discussion module in my site -

in web site hackers entering bad words. best way prevent this? i using asp.net, c# , sql server resources. check bad words in form backend ? check bad words in javascript? check bad words in stored procedure before insert? i think first method best. please tell optimized code check now using method var filterwords = ["fool", "dumb", "couch potato"]; // "i" ignore case , "g" global var rgx = new regexp(filterwords.join(""), "gi"); function wordfilter(str) { return str.replace(rgx, "****"); } // call function document.write("original string - "); document.writeln("you fool. why dumb <br/>"); document.write("replaced string - "); document.writeln(wordfilter("you fool. why dumb")); reality can’t prevent 100% of bad words. i’d go two-step verification ...

After updating to canary preview 5, android studio does not work -

Image
after updating canary preview 5, android studio not work. it show image , nothing happens i searched solution no avail what wrong it? thanks in advance i have same problem android studio version 2 preview 4 asked question here in after find solution on answer question here this did this answer question, after trying many methods works fine. how resolved problem by: updating android sdk tools , latest sdk platform removing android studio cache folder situated in c:\users\<username>\.androidstudiopreview2.0 running android studio again give try , luck!

php - can i reduce load time while creating pdf? -

i have created pdf file tcpdf. for less data works fine , not taking time load, if write more data takes 1 or 2 minutes load. is there solution? my file contains text, colors on text , few images - nothing else. still takes more time load. i doing this: $pdf->writehtmlcell($w=0, $h=0, $x='', $y='', $html, $border=0, $ln=1, $fill=0, $reseth=true, $align='', $autopadding=true); $pdf->output(); exit(); i found http://www.tcpdf.org/performances.php - maybe have implement xcache? i had problem , didn't have code. running ubuntu linux, 32 bit version of operating system. i reinstalled , switched 64 bit version , generation time went 1 2 minutes down 5 10 seconds. huge difference.

javascript - Edit a page with content editable and save it using php -

i trying wrap head around project work on attempt more familiar programming in php. i want create website that's easy update without full blown cms. thinking of using html5 contenteditable widget. what envision following: user logs in , session started allow php echo content editable tag it's visible when user authenticated. once logged in, user can make changes file , click save button , file updated. need help is possible update php file on? if is, involve ajax or pure php? how pass content within contenteditable widget saved on server? don't want use ftp i'm assuming have learn how ajax? hate ask if have example code awesome! lastly, super major security risk? thanks in advance! atlante i did that. considering have built <form> has textbox , submit button: <form action="update.php" method="post"> <div><label for="textarea">your message</label></div> <div>...

mongoose - MongoDB $pull efficiency -

let's assume following schema var schema = new mongoose.schema({ data: { type: [number] } }); schema.index({ _id: 1, data: 1 }); var model = mongoose.model('test', schema); how efficient $pull operator when removing entries doc.data ? model.update({ _id: someid }, { $pull: { data: { $lte: 123 } } }).exec(); will use index , run in o(log n + m) complexity, n number of elements in data , m number of removed elements? or have scan whole array? and what's complexity of removing element after mongo finds it? o(1), o(log n) or o(n) has shift other items? the collection's indexes used doc finding part of update, not update itself. so built-in index on _id used find document, $pull update require whole data array read , scanned against {$lte: 123} query: o(n). the index added on { _id: 1, data: 1 } used if included data in actual query as: model.update({_id: someid, data: {$lte: 123}}, {$pull: {data: {$lte: 123}}}).exec(); but pro...

filter number from Phone book by replacing all special characters in Android? -

i working contacts fetched default phone book in android. when fetch contacts phone book, sometime getting "-", "(" etc characters. if characters known can remove them relpace() method client complaint times got see % symbols in number fetch phone book. please suggest me, how can filter numbers fetch phone book, can have only , digits in text field , no else characters. currently using string.replace("-",""); removing '-' contact number. you can use phonenumberutils.stripseparators(string) (available in api 1+). edited or can use regular expression‌ ​: filternum = filternum.replaceall("[^0-9]+", ""); — remove characters not in range 0...9 . think easier. here's the documentation .

haskell - hspec failing to import (private) code dependency despite CPP override -

let's have src file so: {-# language cpp #-} module alphabet ( #ifdef test alphabet #endif ) alphabet :: [char] alphabet = "abcdefghijklmnopqrstuvwxyz" a .cabal file so: name: alphabet version: 0.1.0.0 library build-depends: base >=4.8 && <4.9, containers >=0.5 && <0.6, split >=0.2 && <0.3 hs-source-dirs: src exposed-modules: alphabet default-language: haskell2010 test-suite alphabet-test ghc-options: -wall -werror cpp-options: -dtest default-extensions: overloadedstrings type: exitcode-stdio-1.0 main-is: spec.hs hs-source-dirs: tests build-depends: alphabet, base >= 4.8 && < 4.9, containers >= 0.5 && <0.6, split >= 0.2 && < 0.3, hspec, quickcheck default-language: haskell2010 a master test file so: {-# options_ghc -f -pgmf hspec-discover #-} ...

Dart Server Side: Where are the advantage of using Shelf rather than IO as a Web Server? -

i want use rpc library develop dart server side restful. in library repository, bring 2 exemples how use ( https://github.com/dart-lang/rpc-examples/tree/master/bin ): shelf , io. i understand better differences between shelf , io. advantage of using shelf rather io web server? shelf modular framework server application. shelf built on top of dart:io . there quite few packages available shelf (from dart team , 3rd-party) make quite easy build complex server applications. if prefer build own solution use dart:io directly.

r - How to make a chart with multi histograms -

Image
i have mess making chart multy histograms in r (try use ggplot2). example of need generated in excel chart (see link): the initial dataset below: attribute dev_share current_qty_share 1 0,04999641 0,115217086 2 0,050001729 0,076647464 3 0,04999641 0,074048054 4 0,050001729 0,071905297 5 0,049999069 0,067865674 6 0,049999069 0,059962063 7 0,049999069 0,054130954 8 0,049999069 0,052725868 9 0,049999069 0,047421666 10 0,049999069 0,036040466 11 0,049999069 0,033370802 12 0,049999069 0,029085289 13 0,049999069 0,027047913 14 0,04999641 0,034354363 15 0,050001729 0,036567374 16 0,049999069 0,039728818 17 0,049999069 0,042222847 18 0,049999069 0,036532247 19 0,049999069 0,02511592 20 0,050017684 0,040009836 for each attribute (#1,2,3...) correspond 2 variables ('dev_share' - blue...

openerp - How to update automatically other fields when quantity on hand get increase or decrease odoo? -

i need update automatically field(qty_available_onhand) either when quantity on hand increase or decrease below have mentioned code. current below code working when fill field(squ_meter) i'm entering in field multiplied field(qty_avl) qty_avl nothing quantity on hand. answer appreciated class product_template(osv.osv): _name = "product.template" _inherit = "product.template" _columns = { 'squ_meter':fields.float('square meter'), 'qty_available_onhand': fields.float( 'qty sqm available', compute='_compute_qty_available_onhand', require = true ), 'qty_avl':fields.related( 'virtual_available', relation='product.product', string='quantity on hand' ), } @api.depends('qty_avl', 'squ_meter') def _compute_qty_available_onhand(se...

jenkins - Continuous Integration Workflow & SVN -

ok may long one. i'm trying standardize , professionalize setup have @ workplace doing live updates our software. currently, manual; have opportunity start scratch. i have installed jenkins, have repositories work with, have job template (based on http://jenkins-php.org ) , have current workflow in mind: main repository, 'trunk' sat on development server in own virtual host each developer creates branch specific bug/enhancement/addition, own virtual host 1) first question: @ stage, recommended practice run jenkins job/build once developer commits branch? run unit tests , other stuff (as per template linked above) once developer branch has been tested, approved, etc - lead developer merge of branch trunk 2) @ stage, jenkins job re-run again once merge complete. possible, , correct way this? once merge process has been tested , approved, deployment (im guessing can added task/target deploy job occurs automatically upon tests being passed in step above?...

android - facebook Login button customization -

Image
using facebook sdk 4.6.0 trying use facebook login integration in android app. com.facebook.login.widget.loginbutton shows following button i want change text "login facebook" "facebook" only i have tried solutions provided previously, none of them worked me. probable reason think of answered question facebook sdk 3.0 seems fails facebook sdk 4.6.0 i tried: modifying loginbutton class locked xmlns:facebook="http://schemas.android.com/apk/res-auto" using schema in loginbutton , changing text using facbook:login_text="login", facebook:com_facebook_login_text="login" both failed work this dependencies facebook sdk compile 'com.facebook.android:facebook-android-sdk:4.6.0' this loginbutton xml <com.facebook.login.widget.loginbutton android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/buttonregisterfacebook" android:padding=...

R: Plot: Re-arranging the order of variables -

i want create barplot in r. however, re-arrange variables on x-axis, not frequency 'meaning'. imagine have following data set: df<-data.frame(read.table(header=true, text=" id radio 1 2 b 3 4 c 5 d 6 d 7 e 8 e 9 10 b 11 c 12 e 13 c 14 15 d 16 17 c 18 19 20 f 21 22 c 23 c 24 25 b 26 27 c 28 29 b 30 c")) i want use plot depict frequencies. plot(df$radio) obviously, r create barplot, ordered levels of factor df$radio (i.e. a b c d e f ). let us, however, assume, order should be: c e b a d f . (in real-case case behind scenario variable dr$radio stands the last time respondent has been using radio. c stands 'today', e 'last week' etc.) i not sure re-arrange order in barplot. tried re-arrange order of levels of df$radio. however, messed factor variable. also, tried solve problem using `order' in plot-code no avail, too. ideas? appreciated! we can use factor levels speci...

ruby on rails - Render only One Row in link_to_add_association using cocoon gem -

i have homebannerslider model has has_many relation wih image . used cocoon gem add multiple association to render images used following code in y form = f.simple_fields_for :images |image| = render 'image_fields', f: image .links = link_to_add_association 'add image', f, :images in image field used following code div.col-lg-12.nested-fields div.sub_box.col-lg-12 .form-group.col-md-3 = f.input :title, input_html: {class: "form-control"} .form-group.col-md-3 = f.input :description, input_html: {class: "form-control"} .form-group.col-md-3 = f.input :image, as: :file, input_html: {class: "form-control"} .form-group.col-md-3 = image_tag f.object.image.url(:thumb) if f.object.image.present? = link_to_remove_association "remove image", f my problem whenever click on link_to_add_association build , renders three new records...

How can I pick only existing JSON branches in Play 2.4 (Scala)? -

edited question (simplified) i input json object via rest api , want transform new validated json object. properties/branches optional. my play 2.4 action far: import play.api.mvc._ import play.api.libs.json._ import play.api.libs.json.reads._ import play.api.libs.functional.syntax._ // [...] def updateuser(id: string) = action(parse.json) { request => /** name validaton */ val namereads: reads[jsstring] = reads.of[jsstring] keepand reads.minlength[string](2) keepand reads.maxlength[string](20) keepand reads.pattern("""[a-z]*""".r) /** age validaton */ val agereads: reads[jsnumber] = reads.of[jsnumber] keepand reads.min(18) keepand reads.max(128) /** transformer */ val transformuser: reads[jsobject] = ( (__ \ 'name).json.pickbranch(namereads) , (__ \ 'age).json.pickbranch(agereads) ).reduce // guess i'd have this: // val transformuser: ...

How to get invocation list of an explicit event in C# -

i can define event following: public event msg_callback event_pingmessage; and invocation list of event following: multicastdelegate event_delegate = (multicastdelegate)this.gettype().getfield(event_name, bindingflags.instance | bindingflags.nonpublic | bindingflags.getfield).getvalue(this); foreach (var handler in event_delegate.getinvocationlist()) { // use handler() here } but, if define event_pingmessage explicit event, like: private msg_callback explicitevent; public event msg_callback event_pingmessage { add { explicitevent += value; int = 0; } remove { explicitevent -= value; } } the multicastdelegate event_delegate = ... line throws exception: object reference not set instance of object. how can .getinvocationlist() explicit events? you can use explicitevent.getinvocationlist() . explicitevent equivalent of...

android - Many app store apps, one start screen -

i want users download different apps within suite, think ms office, have 1 main screen pick each app from. users can add (or remove) apps downloading them google, etc. i don't want users have have multiple copies of same start screen, 1 in each app, if possible, because want minimize internal or external memory storage use. alternately, if download , instal 1 app suite, can use install 2 apps, useful app , second mainscreen app wont installed if have installed via of programs suite? don't want user bothered options or have download 2 apps. want allow users install or uninstall apps needed. if start app 1 apps "select app want", how make second app in suite open, e.g. word, without opening second apps "select app want" start screen. [e.g. should send intents between apps, or have alternate start activities in manifest?] can install new apps, , delete duplicate app select menu images within new program if program has installed app select menu screen....