Posts

Showing posts from August, 2013

otp - About a client for pusher written in Erlang -

i want write module need able push message pusher in erlang. found repo https://github.com/bradfordw/pusherl , not maintained anymore, think can adapt make work. followed readme, , ran rebar command. open rebar console command ./rel/pusherl/bin/pusherl console so server should start. when try call gen_server:call(pusherl_server, {push, {"channelname", "eventname", "payload"}}). then throws error: exception exit: {noproc,{gen_server,call, [pusherl_server, {push, {"channelname","eventname","payload"}}]}} in function gen_server:call/2 (gen_server.erl, line 182) i'm quite new erlang , otp, , takes me half of day make work not successful. please me solve this. appreciate. by way, if know other pusher client, please suggest me. lot. here code gen_server callback: -module(pusherl_server). -behaviour(gen_server). -define(server

How do I compare strings in Java? -

i've been using == operator in program compare strings far. however, ran bug, changed 1 of them .equals() instead, , fixed bug. is == bad? when should , should not used? what's difference? == tests reference equality (whether same object). .equals() tests value equality (whether logically "equal"). objects.equals() checks nulls before calling .equals() don't have (available of jdk7, available in guava ). consequently, if want test whether 2 strings have same value want use objects.equals() . // these 2 have same value new string("test").equals("test") // --> true // ... not same object new string("test") == "test" // --> false // ... neither these new string("test") == new string("test") // --> false // ... these because literals interned // compiler , refer same object "test" == "test" // --> true // ... should call objects.equals() o

android - How can I show image taken from camera -

i'm trying write android app, works camera. show preview of camera in textureview, working. if press button camera take picture , show on imageview on second half of screen. everytime press button app stops working, tells me error android.view.viewrootimpl$calledfromwrongthreadexception: original thread created view hierarchy can touch views. so looked up, , seems can't change image of imageview try to. don't know how else solve problem. can give me advise? here code: image changed in "imagereader.onimageavailablelistener" in method takepicture(). public class mainactivityold extends activity { private textureview mtextureview; private imageview mimageview; private cameradevice mcameradevice; private size mpreviewsize; private capturerequest.builder mpreviewbuilder; private cameracapturesession mpreviewsession; private button mbtnshot; @override protected void oncreate(bundle savedinstancestate) { supe

c++ - Is strtok() safe to use -

this question has answer here: strtok function thread safety 2 answers i reading lot negative things strtok() , obsolete, not thread safe, etc. so truth, can use strtok() ? , thread safe? note: using visual c++. you can use it, it's part of standard library. it uses internal storage shared across users of function, no it's not thread-safe. it modifies string hand it, quite scary. i not recommend using it, in cases.

jquery - move images in a line with timed effect -

the idea have div images ( in horizontal line) see first image within div. there 5 images. want move images right left leaving div (and screen) , after last images has moved first image in front (that 1 entire loop) start animation, click button. now trick of this, @ every uneven numbered image animation has stop few moments. starting image 1, pass number 2 , stop @ 3 few seconds pass numver 4 , stop @ number 5 after image continues first 1 again , stops until start button clicked again. i want able expand amount of images easy. what have far in css / html is <body> <div id="container"> <div id="fotos"> <div class="image"><img src="afb_stuk/1.png"/></div> <div class="image"><img src="afb_stuk/2.png"/></div> <div class="image"><img src="afb_stuk/3.png"/></div> <div style="clear

php - Getting values stored in mutiple arrays. Checkboxes involved -

heloo, i have following php code: <?php $ratings = array( 1 => "all", 2 => "love", 3 => "hate", 4 => "maybe", 5 => "super" ); $question = array( 1 => "pizza", 2 => "prajitura", 3 => "placinta", ); echo '<form method="post" action="' . $_server['php_self'] . '">'; echo '<p>how feel each topic?</p>'; foreach ($question $key=>$value){ echo "".$value."<br>"; echo "aici valoarea".$key; $importhtml=""; foreach ($ratings $cheie => $raspuns) { // echo "cheie: ".$key."cheie raspuns:".$cheie."raspuns".$raspuns."\n"; $importhtml .= "$raspuns <input type='checkbox&#

java - How much string objects are created (String.format())? -

after dispute colleague couldn't find solution. question for(int = 0; < 2; i++) { string.format("variable = %d", i); } how variables created during running code? have opinion, here can created 4 variables: "variable = %d", "variable = %d" - on both cycle steps created object formatting "variable = 0", "variable = 1" - resulted strings. am right? "variable = %d" string literal, put in string pool , not created twice. hence, you'll have total of 3 strings: "variable = %d" , "variable = 0" , "variable = 1" .

java - jOpenDocument: problems trying to generate PDF from ODS in -

i have .ods file , want export pdf using jopendocument (java). i use following code: // load ods file final opendocument filledcertificate = new opendocument(); filledcertificate.loadfrom("filledcertificate.ods"); // open pdf document document document = new document(pagesize.a4); file outfile = new file("certificate.pdf"); pdfdocument pdf = new pdfdocument(); document.adddoclistener(pdf); system.out.println("test"); fileoutputstream fileoutputstream = new fileoutputstream(outfile); pdfwriter writer = pdfwriter.getinstance(pdf, fileoutputstream); pdf.addwriter(writer); document.open(); // create template , graphics2d object rectangle pagesize = document.getpagesize(); int w = (int) (pagesize.getwidth() * 0.9); int h = (int) (pagesize.getheight() * 0.95); pdfcontentbyte cb = writer.get

css - Remove bullet points from HTML list items -

how remove bullet points #box5 , #box6 , #box7 ? thought using #box5 a , it's not working. html <div id="con3"> <!-- irrelevant markup omitted --> <div id="box5"> <li><a href="#">liam price<br>australia</a></li> </div> <div id="box6"> <li><a href="#">jess kwartz<br>germany</a></li> </div> <div id="box7"> <li><a href="#">ali jab<br>mexico</a></li> </div> </div> css #box5 { margin-left: 110px; margin-top: 10px; font-family: 'pt_serifitalic'; font-size: 9pt; line-height: 16px; } #box5 { color:white; text-decoration: none; list-style: none; } you should put list items li in either ul or ol or menu follow html spec. see here: http://www.w3.org/tr/html

javascript - Promise.allSettled in babel ES6 implementation -

i'm using babel transpile node.js@0.10.x code , i'm stuck promises. i need allsettled -type functionality use in q , bluebird or angular.$q example. on babel's core-js promise , there no allsettled method. currently i'm using q.allsettled workaround: import { allsettled } 'q'; is there in babel polyfill? alternatively, algorithm me try implement? alternatively, algorithm me try implement? create new promise executor function use counter/result array in scope of executor register then() callback each parent promise saving results in array resolve/reject promise step 1 when counter indicates parent promises done

python - How are numeric and string variables determined in SPSS? -

Image
so found page explains different types of variables well: http://www.spss-tutorials.com/spss-variable-types-and-formats/ i know though, how numeric , string types differentiated when export data? numeric , string mapped code? i parse spss data in python. if take note of print output generated code below, you'll notice string variables "exported" strings (not surprisingly) , numeric variables converted/exported floats. date variables converted floats, date represented number of seconds have elapsed since october 14, 1582 - manner in spss stores date variables within spss there various formats date variable can set displayed (the float value stored internally of course remains same). input file variable formats: input file data view: code read spss data python , print results: get file="c:\program files\ibm\spss\statistics\23\samples\english\employee data.sav". begin program. import spss, spssdata allfiles = spssdata.spssdata().fe

powershell v3.0 - Enter-PSSession to remote server fails with "cannot find the computer" -

my desktop win7 , trying connect server 2012. both hosts on same domain. if do: enter-pssession -computername *servername*** i following failure message winrm enter-pssession : connecting remote server xxx failed following error message : winrm cannot process request. following error occurred while using kerberos authentication: cannot find computer xxx. verify computer exists on network , name provided spelled correctly.* it doesn't matter if use server name or if enter qualified. both systems show $psversiontable.psversion 4 0 -1 -1 i have tried various troubleshooting hints found i.e. run enable-psremoting -force , set trustedhosts = * on both sides. disabled firewall service on both sides. when try enter-pssession server desktop works desired. desktop server error message computer cannot found. run winrm quickconfig powershell session on remote machine

java - annotation security spring file properties -

i want use annotation @preauthorized , @postauthorized in application in spring, use , not nothing. need activate "something" in application.properties, don´t know that. read put servlet.xl <global-method-security pre-post-annotations="enabled" /> but in file properties? use java annotations haven't activate this. i suggest use configurations this: @configuration @enableglobalmethodsecurity(prepostenabled = true) @enablewebsecurity public class authenticationconfiguration extends websecurityconfigureradapter { // authorisation service, need provide 1 @autowired private userauthenticationservice userdetailsservice; @override protected void configure(authenticationmanagerbuilder auth) throws exception { auth.userdetailsservice(userdetailsservice); } @override protected void configure(httpsecurity http) throws exception { http.authorizerequests().anyrequest().fullyauthenticated(); h

java - BACnetServer with bacnet4j - invalid apdu in this state -

i'm trying bacnet server running using bacnet4j. i use default settings bacnet4j , i'm able see bacnet server in tool i'm using client (baceye). if have limited number of datapoints on local device, seems alright. when having more 128 datapoints timeouts on server , client complains invalid apdu in state. on server errors timeout while waiting response id 52 and no waiting recipient messages address = ...abortreason=invalid apdu in state has experienced errors bacnet4j , can help? thanks!

ios - Link Private Apple Framework with CocoaPods -

disclaimer: working on library linked non-app store project via cocoapods. library uses private api's multiple functionalities. i'm asking technical solution. i working on library redistributed using cocoapods. in core project of library linking 1 of private frameworks shipped xcode. exact location of framework is: /applications/xcode.app/contents/developer/platforms/iphoneos.platform/developer/sdks/iphoneos8.3.sdk/system/library/privateframeworks i avoid copying framework library linked "cocoapods private framework" , rather link directly according ios sdk choosen in xcode project or podfile . so question is: does cocoapods support linking against apple's private frameworks shipped xcode? if yes, correct syntax specify framework in .podspec file? i have not been able find exact information on web, linking specific frameworks. thanks.

ajax - Submit empty value to bean anyway on input with required="true" -

i've below input required="true" : <p:inputtext value="#{bean.value}" required="true"> <p:ajax event="change" listener="#{bean.change()}" /> </p:inputtext> when user changes value, listener fired , can access changed value. when user empties field, listener not fired , empty value not updating in bean. gather caused requried="true" . update bean empty value , fire listener anyway when user empties field. how can achieve this? you can use expression language (el) in required attribute too. can check if main submit button of form has been pressed. imagine form has "save" button below, <p:inputtext ... required="true"> <p:ajax ... /> </p:inputtext> ... <p:commandbutton ... action="#{bean.save}" /> then can let required attribute evaluate true if button invoked. can achieve referencing component via binding , checking if cl

wordpress - Redux Framework not working when used in plugin -

i'm going use redux framework plugin options, showing in admin panel , can save settings, i used sample config file option panel, so problem m not getting option values printing global opt_name variable. if add redux framework config file theme functions.php worked, not working in plugin, please me if 1 know problem. lead dev of redux here. the issue redux hasn't had chance run yet! if you're using new redux api run: redux::init('opt_name') , work. :)

oracle - SCORE declaration in SQL is giving the following error -

im trying execute below query score select distinct id, score ( select distinct id,score(1) score,name testtable contains (name,'about(test)', 1) > 34 order upper(name) ) rownum <= 100 order score desc but throwing ora-29908: missing primary invocation ancillary operator unable figure out cause. tia help

python - Plot hlines in embedded graph? -

i'm practicing tkinter , matplotlib in piece of code , supposed embed simple matplotlib graph tkinter gui. thing want horizontal lines plotted in embedded graph mouse clicks i'm not getting result want. what i'm getting first mouse click new plot created outside tkinter gui of same graph 1 horizontal line in (where clicked on). if close plot window popped , try click again on embedded graph new plot pops time contains horizontal line. what's going on? the code i'm practicing on: from tkinter import * import matplotlib matplotlib.use('tkagg') matplotlib import pyplot plt matplotlib.backends.backend_tkagg import figurecanvastkagg, navigationtoolbar2tkagg matplotlib.figure import figure root = tk() frame = frame(root) frame.pack() fig = plt.figure(figsize=(16,8)) plt.plot([1,2,3],[1,2,3]) canvas = figurecanvastkagg(fig, frame) canvas.show() canvas.get_tk_widget().pack(fill='both', expand=true) toolbar = navigationtoolbar2tkagg(canvas, fram

uitableview - Create swipe to reveal buttons for iOS 7, using clear color for background -

i followed tutorial http://www.teehanlax.com/blog/reproducing-the-ios-7-mail-apps-interface/ add more button beside delete button when swiping. but problem cell need use clear color background image can seen. approach used scrollview display content view , buttons view of tableview cell. if content view of scrollview has background color instead of clear color, can hide buttons these buttons display part determined our finger when swiping on cell, using clear color background makes these buttons show without need swipe right left on cell. so can give me suggestion use clear color display background image without revealing under buttons? you can use mgswipetablecell class creating swipeable buttons colour need. not interfere tableview cell color well. easy , quick implement. https://github.com/mortimergoro/mgswipetablecell

javascript - How to gulp build index.html reference assets with absolute paths? -

scaffolded yeoman web application gulp-angular . my gulp build process outputs dist/index.html file references assets using relative paths: <html> <head> ... <link rel="stylesheet" href="styles/vendor-f57bbe49.css"> <link rel="stylesheet" href="styles/app-a0b8907b.css"> </head> <body> ... <script src="scripts/vendor-a30f25be.js"></script> <script src="scripts/app-b7f411d9.js"></script> </body> </html> how force gulp use absolute paths instead? e.g. /scripts/ instead of scripts/ , /styles/ instead of styles/ here's excerpt of current src/index.html : <html> <head> ... <!-- build:css({.tmp/serve,src}) styles/vendor.css --> <link rel="stylesheet" href="app/vendor.css"> <!-- bower:css --> <!-- run `gulp inject` automatically popul

elasticsearch - Query chaning in elasticseacrh -

i have 1 index projectrecords in elasticsearch.it contains documents.each document has 1 doctype field,contains "article", "generation" this.there relation between article , generation.my requirment 1) records match org field "user" value , doctype type "article" value. 2) take first query output input second query based on can filter documents date. 1 query want in query chaining. how can this. thank in advance

spring boot - Trouble getting started with SpringBoot and Gradle -

i new java, gradle , spring. i setup new project following gradle script: buildscript { repositories { maven { url "http://repo.spring.io/snapshot" } maven { url "http://repo.spring.io/milestone" } } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.0.build-snapshot") } } apply plugin: 'java' apply plugin: 'spring-boot' repositories { maven { url "http://repo.spring.io/snapshot" } maven { url "http://repo.spring.io/milestone" } } dependencies { compile("org.springframework.boot:spring-boot-starter-web") testcompile("org.springframework.boot:spring-boot-starter-test") } when trying build above script, following errors: e:\projects\springapptutorial>gradlew failure: build failed exception. * went wrong: problem occurred configuring root project 'springapptutorial'. > not resolve depende

Regex to find a substring with a specific length that contains minimum occurrences of a specific characters -

is there regex find substring specific length contains minimum number of specific char occurrences? for example have string such as: aababaaaaa string have substring length 5 contains 2 b => aabab regex should find it. but aaaabaaaab there not substring length of 5 contains 2 b. suppose our string contains , b , want find substring length of 5 contains @ least 2 b: aaaabaaaab -> invalid aaaaaaaabb -> valid aaaaaaaaaabaabaaaaaa -> valid aaaabaaaaaaabaaaaaaa -> invalid brute force: .b..b|b...b|..bb.|.b.b.|..b.b|bb...|b.b..|...bb|b..b.|.bb.. well, know such regular expression not parametrizable. on other hand it's possible obtain programmatically (the example in python): import itertools def get_regex(char, charnum, strsize): chars = char * charnum + "." * (strsize - charnum) return "|".join("".join(x) x in set(itertools.permutations(chars))) print get_regex("b", 2, 5)

Exception Handling in Ruby - call begin if it goes to rescue -

i have simple exception handling block begin <connect network , make request> rescue <comes here if didnt connect / whatever other error> end i want modify such if comes rescue - goes begin again. give 5 tries . if still not connecting - come out of block you want keyword retry . couple max_retries. i.e. if (max_retries -= 1) > 0 retry

mongodb - Error 10334 "BSONObj size is invalid" when importing a back up with mongorestore -

i have mongodb collection backup containing many small documents. produced mongodump , when try import using mongorestore error: assertionexception handling request, closing client connection: 10334 bsonobj size: 18039019 (0x11340eb) invalid. size must between 0 , 16793600(16mb) i'm running mongodb version 3.0.3 (from trunk). using --batchsize=100 fixes issue me every time. e.g. mongorestore -d my-database --batchsize=100 ./database-dump-directory

xcode - How to include more search items in iOS spotlight search -

i created project, settings name, say: abcxyz. when use ios search app (swipe down in main menu), type xyz, app doesn't appear. what have include in xcode project in order more option in search? like, type a, type x, show app. in case of abc-xyz also. additional, want user can search our company name also. company1, search company1 , show our company's apps (in case abcxyz). you can't since spotlight's search mechanism built-in in ios. when user types keyword, ios search following 2 names of installed apps: the app's bundle display name (the name used in home screen). the (usually) longer name used in app store. when searching, ios case-insensitive match beginning of each "word" in name. example, if app called abcxyz , both a , abc , abcx match name, not xyz . however, it's worth pointing out each "component" of camel-case styled name treated different word. if app named abcxyz , keyword of abc , xyz both match app

javascript - Updating doc in Pouch DB -

i have db in pouchdb, , need able update documents. when click "update" in table data fields form, want change data in form , press "save updated" button , have fields updated. here's i've tried: function saveupdated(){ var vaucherid = window.document.vaucherform.vaucherid.value; var date = window.document.vaucherform.date.value; var invoicenumber = window.document.vaucherform.invoicenumber.value; var vendorid = window.document.vaucherform.vendorid.value; var amount = window.document.vaucherform.amount.value; var fund = window.document.vaucherform.fund.value; var deptid = window.document.vaucherform.deptid.value; var descript = window.document.vaucherform.descript.value; //i idvalue when have values db form db.get('idvalue').then(function(doc) { return db.put({ _id: 'idvalue', _rev: doc._rev, vaucherid: vaucherid, date: date, invoicenumber: invoicenu

javascript - How to determine if an Office Add-in is running under Excel or Excel Online? -

i'm writing office add-in (formerly, apps office). i'm using office.js , in point of code want check if app running in excel (desktop software) or running on web (excel online) something like: if (office.isrunningonweb){ // something. } you can use document type: if (microsoft.office.webextension.context.document instanceof osf.dda.excelwebappdocument) { //your app running on web } if (microsoft.office.webextension.context.document instanceof osf.dda.exceldocument) { //your app running in excel }

bash - How to automatically move a fully downloaded file to a new directory -

i using wget download files group of files ingested in program. know can use "-p" send file tmp directory, unsure best method move file needed destination once downloaded. rsync best way move files or method preferred using scripting? if intend move file if download done make move or if not downloaded no need of move, can use "logical and" between commands of wget , mv wget http://mysite.example.com/file1.tgz && mv file1.tgz /new_dest/

C# add event handler to class that has been loaded from an assembly at run time -

as part of evaluating 3rd party dll called "gembox.document", want able run assembly during run time. in order run in trial mode, need use this: componentinfo.freelimitreached += (sender, e) => e.freelimitreachedaction = freelimitreachedaction.continueastrial; this standard way if directly reference dll in application. however, want able calling dll @ runtime. correct syntax this? edit: componentinfo public static class of gembox.document for future reference, here how can load gembox.document assembly @ run-time , set in trial mode through reflection: using system; using system.reflection; class program { // load gembox.document assembly. static assembly gemboxassembly = assembly.loadfrom(@"c:\gembox.document.dll"); // create method handling freelimitreached event. static void handlefreelimit(object sender, eventargs e) { // call: e.freelimitreachedaction = freelimitreachedaction.continueastrial dy

c# - Selected date is not showing in datepicker in angular.js -

Image
i working in mvc 5 project angular js. using date picker control in webpage using directive in app.js . myapp.directive('datepicker', function () { return { restrict: 'a', require: 'ngmodel', link: function (scope, element, attrs, profilectrl) { element.datepicker({ //dateformat: 'dd, d mm, yy', dateformat: 'dd-mm-yyyy', autoclose: true, onselect: function (date) { profilectrl.$setviewvalue(date); //profilectrl.$render(); scope.$apply(); } }); } }; }); everything works fine problem when select date it's shows selected date in date picker. example selected date june 1 2015 i save value on database. populate date picker again, selected date not selected in date picker. actually system date format dd-mm-yyyy . edit : please see html code below. <div ng-app="myapp"

hadoop - Oozie stack trace -

i'm triying submit spark job oozie using spark's sparksubmit java class suggested in launching spark program using oozie workflow java action failed error message main class [org.apache.oozie.action.hadoop.javamain], exit code [1] is there way access execution error log / stack trace can see happened? comment / answer appreciated. to java action log, use oozie's web console find hadoop job id of action. , use hadoop's yarn webui hadoop job's mapper log. with command line interface, above steps be: run oozie cmd hadoop job id: oozie job -info <your job id here> and "external id" in output, such : job_200904281535_0254 run yarn cmd hadoop job log: yarn logs -applicationid <your app id here> you can app id replacing "job" "application" in job id, such application_200904281535_0254

objective c - NSURLRequest setAllowsAnyHTTPSCertificate to Swift -

what equivalent swift code of objective-c code below? [nsurlrequest setallowsanyhttpscertificate:yes forhost:[url host]]; this not available on foundation framework. it's apple private api , apple says application rejected if use private api.

arrays - Check whether the input is digit or not in C programming -

i reading book: the c programming language - kernighan , ritchie (second edition) , 1 of examples having trouble understanding how check whether input digit or not. example on page 22, explaining under array chapter. below example. #include <stdio.h> /* count digits, white space, others */ main() { int c, i, nwhite, nother; int ndigit[10]; nwhite = nother = 0; (i = 0; < 10; ++i) { ndigit[i] = 0; } while ((c = getchar()) != eof) { if (c >= '0' && c <= '9') { ++ndigit[c-'0']; } else if (c == ' ' || c == '\n' || c == '\t') { ++nwhite; } else { ++nother; } printf("digits ="); (i = 0; < 10; ++i) { printf(" %d", ndigit[i]); } printf(", white space = %d, other = %d\n",nwhite, nother); } for example, confused me author mentioned line ++ndigit[c-&#

swift - Can I automatically derive some instances like Equatable? -

say have struct memebers equatable . struct s { let : string let b : int let c : double } would know of way automatically make s equatable without manually , boringly defining == ? no, you'll have define manually: func == (l: s, r: s) -> bool { return l.a == r.a && l.b == r.b && l.c == r.c } that's short can make it. it's pretty darn short (one line!), meaning clear, , it's ready future complications may add type. happy!

javascript - Override Jade script. block -

i'm trying override jade script. tag,but don't work. i have following code: layout.jade block foot footer.container#footer .row .twelve.columns todos os direitos reservados. &copy; 2015 pet feeder block scripts script(src="/javascripts/js/jquery.min.js") script(src="/javascripts/lib/jqueryui/jquery-ui-1.8.18.custom.min.js") script(src="/javascripts/js/s_scripts.js") script(src="/javascripts/js/jquery.ui.extend.js") script(src="/javascripts/lib/qtip2/jquery.qtip.min.js") script(src="/javascripts/lib/fullcalendar/fullcalendar.min.js") script(src="/javascripts/js/jquery.list.min.js") script(src="/javascripts/js/pertho.js") script. $(document).ready(function(){ prth_common.init(); }); until here,everything fine,and script runs charm. when need put script,from other views,the script. added view doesn&

ios - How can I populate a UICollectionView with a Parse array of objectIds? -

i using parse.com. have array(named "wants" of objectids want use populate uicollectionview each objectid's corresponding image. i'm not quite sure start. i tried using pfquery wherekey of "wants", i'm not sure put in "equalto" parameter. var downloadcards = pfquery(classname: "user") downloadcards.wherekey("wants", equalto:"") downloadcards.orderbyascending("number") downloadcards.limit = 200 downloadcards.findobjectsinbackgroundwithblock { (objects: [anyobject]?, error: nserror?) -> void in if error == nil { if let objects = objects as? [pfobject] { object in objects { objectids.append(object.objectid!) parseobjects.append(object["image"] as! pffile) imagenames.append(object["number"] as! string)

c++ - incompatible implicit declaration of built-in function 'malloc' -

my program is #include <iostream> char * grabnumber ( char * begin ) { // interpret *begin start of double , add characters // string retstr char * begincpy = begin; int founddot = 0; while ((*begin >= '0' && *begin <= '9') || *begin == '.') { if (*begin == '.') { if (founddot == 0) founddot = 1; else break; } ++begin; } long n = begin - begincpy; // # of characters parsed char * retstr = malloc(sizeof(char) * (n + 1)); // string returned (long k = 0; k < n; ++k) retstr[k] = *begincpy++; retstr[n] = '\0'; return retstr; } int main() { char str [] = "abc3.14def"; std::cout << grabnumber(str+3); // should print "3.14" return 0; } and errors i'm getting are line 20: warning: incompatible implicit declaration of built-in function 'malloc' line 21: error: 'f

c# - Entity Framework AddOrUpdate implementation -

i'm trying create extension method similar addorudpate . the usage should this: var student = context.students.getorcreate( s => s.name, new student() { name = "somename" }) if there user name should return it, otherwise should create new user. this have: public static tentity getorcreate<tentity>( idbset<tentity> set, expression<func<tentity, object>> identifierexpression, tentity entity) tentity : class { var func = identifierexpression.compile(); var id = func.invoke(entity); var persistedentity = set.firstordefault(e => func.invoke(e) == id); if (persistedentity != null) { return persistedentity; } return set.add(entity); } but can't call invoke using linq entities. how should use identifierexpresion ? use create new expression can pass firstordefault , let ef provider handle converting expression sql. new expression test equality id retrieved compi

php - Adding custom field to permalink structure -

i have wordpress site uses custom post type 'external-projects'. within custom post type there custom field 'director'. trying rewrite permalinks include directors name. have working on external-projects messes rest of sites urls. 404s etc. below code. great. add_action('init', 'tdd_add_rewrite_rules', 10, 0); function tdd_add_rewrite_rules(){ // register custom rewrite rules global $wp_rewrite; $wp_rewrite->add_rewrite_tag('%external-projects%', '([^/]+)', 'external-projects='); $wp_rewrite->add_rewrite_tag('%director%', '([^/]+)', 'director='); $wp_rewrite->add_permastruct('external-projects', '/%director%/%external-projects%', false); } add_filter('post_type_link', 'tdd_permalinks', 10, 3); function tdd_permalinks($permalink, $post, $leavename){ $no_data = 'no-director'; $post_id = $post->id; if($post->post_type != 'externa

Swift: Reduce with closure -

code: var treasures: [treasure] = [] treasures = [treasurea, treasureb, treasurec, treasured, treasuree] let recttodisplay = self.treasures.reduce(mkmaprectnull) { (maprect: mkmaprect, treasure: treasure) -> mkmaprect in // 2 let treasurepointrect = mkmaprect(origin: treasure.location.mappoint, size: mkmapsize(width: 0, height: 0)) // 3 return mkmaprectunion(maprect, treasurepointrect) } in code above, running reduce function on treasures array, 2 parameters passed in closure: (maprect: mkmaprect, treasure: treasure) . how closure know second parameter element treasures array , first parameter result of closure returns? is default second parameter passed in closure element array that's executing reduce function? swift's array class has definition of reduce looks this: func reduce<t>(initial: t, fn: (t, t) -> t) -> t { var val = initial e in self { val = fn(val

php - My comment fields don't show Placeholder text -

i have wordpress website in comment fields don't show place holder text. has 4 fields. 1 each name, email address, website , comment. first 3 fields have no place holder text due dificult identify field thing. here piece of code found in comments.php file , believe causing problem. any helps fix problem? $fields = array( 'author' => '<div class="comment-left pull-left"> <p class="input-block"> <label for="comment_name" class="required">'.__('name', kopa_get_domain()).' <span>*</span></label> <input type="text" id="comment_name" name="author" class="valid"> </p>', 'email' => '<p class="input-block"> <label for="comment_email" class=&

java - False with regular expression from properties file -

so here problem. have string comment in java: string s = "// "then" clause: decrease" and when i'm doing this: system.out.println(s.matches("(^(//).+)")); its true . but, when have properties file, where listing = "(^(//).+)" and doing same system.out.println(s.matches(resourcebundle.getstring("listing"))); i'm receiving false . why? , regex must in properties receive true? thanks remove quotation mark in properties file. listing = (^(//).+)

java - C# WinForms Key Bindings -

what closest equivalent of java's keybindings in c#? attempting port swing application c#, unclear method should use. here sample of java porting: action goup = new abstractaction() { @override public void actionperformed(actionevent e) { panel.uppressed = true; } }; action stopup = new abstractaction() { @override public void actionperformed(actionevent e) { panel.uppressed = false; } }; inputmap getinputmap = panel.getinputmap(jcomponent.when_in_focused_window); getinputmap.put(keystroke.getkeystroke("w"), "goup"); getinputmap.put(keystroke.getkeystroke("released w"), "stopup"); panel.getactionmap().put("goup", goup); panel.getactionmap().put("stopup", stopup); in winforms, not aware of inputmap . keyboard input handled in 1 of 2 ways: shortcut keys, i.e. menuitem.shortcut . assignable in designer, or in code. pressing associated key invoke menu item's cli

python - How to call a function from a list? -

for example, have following list: method = [fun1, fun2, fun3, fun4] then show menu user must select number 1-4 ( len(method) ). if user selects i , have use function funi . how can that? eg. a=['hello','bye','goodbye'] def hello(n): print n**2 def bye(n): print n**3 def goodbye(n): print n**4 if want call function bye array a, using >>>a[1](7) traceback (most recent call last): file "<pyshell#0>", line 1, in <module> a[2](5) typeerror: 'str' object not callable how can use names saved in a call functions? because every method saved in string. let's see... you call function fn using parens () in fn() you access item list indexing operator [] in lst[idx] so, combining 2 lst[idx](*args) edit python list indices zero-based, first item 0, second 1, etc... if user selects 1-4, you'll have subtract one. edit given clarification, following can done def method1(): pass def

How to make mystery box like in mario games in Tiled map Editor? -

i'am making simple platformer (c++, tiled). dont't understand how implement mystery box. must object or tile? if better tile, how animate tiles in tmx map. assuming want predetermine come out of mystery box, easier use object (can tile object) , not plain tile on tile layer. because can associate custom property tile object, tell game item should come out. alternatively, can use different tiles each mystery box, render them same in game. allow see put item in editor. using object in game rather plain tile should make easier animate it. but, can wait creating such object until point necessary.

linux - Designing a python kde widget -

i started trying figure out how make kde widget using python finished quick tutorials ( https://techbase.kde.org/development/tutorials/plasma4/python/using_widgets ) want design more complicated gui , of designing tool widgets in python, there such thing ? or make life easier trying design whole thing code ? if i'm not terribly mistaken, there no kde widgets. kde uses qt create gui's you'd need see qt designer program. there's no reason couldn't design uis in gtk, supported in kde environments. there can use anjuta ide , can use glade ui designer actual graphical layout. all these packages should available in repository.

ios - Managing Timers Passed as Variables -

i trying perform thought simple task. have handful of repeating timers need started , stopped. i created methods starting , stopping timers, , attempt pass timers methods parameters. the problem timers never seem stopped. ideas why might not working properly? thank you! top of file: #import "viewcontroller.h" nstimer *launchtimer; nstimer *transactiontimer; starting method: -(void) startingmethod { nsstring *urlstring = @"http://google.com"; [[asynchrequestservice sharedinstance] performasynchronousurlrequest:urlstring completion:^(bool success, nsstring *responsebody, nsstring *responsestatus) { if (success) { [self stopresponsetimer:launchtimer]; } else { [self startresponsetimer:launchtimer method:@selector(startingmethod) interval:10]; } }]; } method start timer: -(void)startresponsetimer:(nstimer *) timer method:(sel) metho

jquery - I don't know how to do a list like this -

Image
i'm using jquery mobile i'm tring list web app, when resize window, list won't resize fit in new screen. fiddle <ul data-role="none"> <li> <a href="index.html"> <div class="ev"> <div class="fot"> <img src="img/football.png" width="80px" height="80px"> </div> <div class="contef"> <h2>torneo en barcelona</h2> </div> <div class="contef_cn"> <p>torneo de futbol sala en barcelona centro</strong> <br>incripcion l-v 9:00 apartir del dia 21/2/2069</p> </div> </div> </a> </li> <!--fin--> </ul>

database design - What is the difference between an Information Model and an Ontology? -

what difference between information model , ontology ? they same me. thanks! the short answer ontology theory , information model application. difference between ontology , epistemology ontology studies how various existing entities can grouped on basis of similar characteristics , tries find out similarities. field tries find relation between objects exist. in particular application, don't need of entities , of relationships. need ones make sense application or group of applications (company). a simple example address. companies store address string, because use address when generating correspondence company or customer. the united states postal service needs break addresses distinct fields. have cross check zip code city , state. in larger cities, zip codes can change depending on house number of particular street. this address ontology postal service detailed other companies use.

javascript - How can I concat the content of dynamic textboxes to a single variable? -

here file (test.php) try run on localhost. javascript works , creates text boxes. php-part not work , makes problem. <html> <head> <title>test</title> <script> function newcheckbox() { var alabel = document.form1.getelementsbytagname('label'); var last = alabel[alabel.length-1]; var label = document.createelement('label'); label.appendchild(box(alabel.length)); label.appendchild(document.createtextnode(' '+document.getelemenbyid('text').value)); last.parentnode.insertbefore(label, last); document.getelementbyid('text').value = ''; } function box(num) { var elm = null; try { elm=document.createelement('<input type="checkbox" class="chk">'); } catch(e) { elm = document.createelement('input'); elm.setattribute('type', 'checkbox'); elm.classname='chk&#