Posts

Showing posts from March, 2012

Understanding Type Classes, Scala implicit and C# -

i read blog post joe duffy haskell type classes , c# interfaces. i'm trying understand have enabled c# have type classes, , wonder whether feature scala's implicits solve it? having kind of feature enable writing this: public interface ireducableof<t> { t append(t a, t b); t empty(); } public t reduce(this ienumerable<t> vals, **implicit** ireducerof<t> reducer ) { enumerable.aggregate(vals, reducer.append); } making sure have in our context implementation of ireducerof<t> compiler "just" pick reducer , use execute code. of course, code cannot compile. but questions are: can enable implementing type classes? is similar happening in scala? i'm asking general understanding , not particular problem. update i've encountered github repo on possible implementation of type classes in c# yes, how type classes implemented in scala. general design principle in scala add general , re-usable features

ios - I am getting the following error when i am trying t o build my project -

Image
ld: file small (length=0) file '/users/ashutoshp/library/developer/xcode/deriveddata/thebouqs-arlmufhxskabmgbuixdzfozlrsph/build/intermediates/thebouqs.build/debug-iphonesimulator/thebouqs.build/objects-normal/x86_64/homevc.o' architecture x86_64 clang: error: linker command failed exit code 1 (use -v see invocation) i got same issue able solve following steps : just clear derived data contents xcode. quit , restart xcode. for clear derived data can use following steps or link . step 1 : click on xcode > preferences... step 2 : select location step 3 : delete derived data folder... hope you...

scala - Type inference is not happening in polymorphic function -

i have written 2 version of codes below . in 1st version , getting run time error below , not able understand why getting error while passing iterator type function : using . in version 2 running fine while passing type of resource type function : using . error:(23, 11) inferred type arguments [iterator[string],nothing] not conform method using's type parameter bounds [a <: anyref{def close(): unit},b] control.using(source.fromfile("c:\users\pswain\ideaprojects\test1\src\main\resources\employee").getlines){a => {for (line <- a) { println(line)}}} ^ 1st version:- /** * created pswain on 9/22/2016. */ import java.io.{ioexception, filenotfoundexception} import scala.io.source object control { def using[ <: {def close() : unit},b ] (resource : a) (f: => b) :b = { try { f(resource) } { resource.close() } } } object filehandling extends app { control.using(source.fromfile("c:\\users\\

gradle - Android build tools unaligned 2.2.0 -

i have found when trying create signed release build, apk not aligned. else find this? there needed change work? com.android.tools.build:gradle:2.2.0 gradle command: assemblerelease temp solution: temporarily set build tools 2.1.3 , works fine.

java - Is realm a relational database? -

i have tried searching realm following questions not answered. please me understand following questions properly: realm relational database? how more efficient compared sqlite? no, realm not relational database. it allows declare relationships between objects same in object graph in language of choice. jp's talk on core describes in more detail , highly recommended. it stores objects in optimal memory-mapped format, using column-store techniques fast searching. accessors in different language sdks map directly functions using memory-mapped storage. in contrast, using relational database sqlite has multiple layers of copying buffers. note: on realm xamarin team.

How to clear the img placeholder for choose image using jQuery -

i have form fileupload. <input class="file" type="file" name="files[]"> i curently cloning input, if file choosen clones choosen filinput, there way clear selected image? script: $('.fieldset-content_doc').first().clone().appendto('.fieldset-clone_doc').find('.file').reset(); fieldset-content_doc: holds formvalues apparently issue reproducible on firefox. but, can set value property of element null : $('.fieldset-content_doc') .first() .clone() .appendto('.fieldset-clone_doc') .find('.file') .each(function() { this.value = null; }); see fiddle

ios - Trouble adding observer to NotificationCenter in Swift 3.0 -

i'm having trouble adding notification observer in swift 3.0. code so: notificationcenter.default.addobserver(self, selector: .playeritemdidplaytoendtime, name: notification.name(avplayeritemdidplaytoendtimenotification), object: playeritem) i getting error: "cannot invoke value of type notification.name.type (aka nsnotification.name.type) argument list (nsnotification.name)" with: avf_export nsstring *const avplayeritemdidplaytoendtimenotification ns_available(10_7, 4_0); what doing wrong here? as martin r commented, name argument should be: nsnotification.name.avplayeritemdidplaytoendtime and complete code be: notificationcenter.default.addobserver(self, selector: .playeritemdidplaytoendtime, name: nsnotification.name.avplayeritemdidplaytoendtime, object: playeritem)

Regex Replace in ABAP for replacing multiple characters occurring multiple times? -

this string c: programming fun, not abap. statement have written single character replace occurrences of regex '\m' in c '@'. works fine, how replace other single characters using same statement. for example: need replace 'm', 'i' using 1 single replace statement. how write this, replace occurrences of regex '\m\p' in c '@'. not working ps: new abap learning. this not abap related 'problem' question of how use regex :-) try this: data: lv_string type string. lv_string = 'replace m, p , s in string @'. replace occurrences of regex '(m|p|s)' in lv_string '@'. write lv_string. ciao!

Pandas HDF5 append time series fails -

going through documentation of pandas hdf5 usability ( http://pandas.pydata.org/pandas-docs/stable/io.html#io-hdf5 ) given example raises error: import pandas pd import numpy np store = pd.hdfstore('store.h5') np.random.seed(1234) index = pd.date_range('1/1/2000', periods=8) df = pd.dataframe(np.random.randn(8, 3), index=index) store['df'] = df df1 = df[0:4] df2 = df[4:] store.append('df', df1) store.append('df', df2) traceback (most recent call last): file "c:\anaconda3\lib\site-packages\ipython\core\interactiveshell.py", line 2885, in run_code exec(code_obj, self.user_global_ns, self.user_ns) file "<ipython-input-225-ef7f2e059c6a>", line 1, in <module> store.append('df', df1) file "c:\anaconda3\lib\site-packages\pandas\io\pytables.py", line 919, in append **kwargs) file "c:\anaconda3\lib\site-packages\pandas\io\pytables.py", line 1252, in _write_to_grou

Modifying JMeter dashboard generation -

i executing jmeter test script using command line. jmeter has provided command generates dashboard using log.jtl file. jmeter -g %jtllogpath% -o %dashboardpath% in dashboard, there apdex (application performance index) table, statistics table, , graphs. there setting or properties table in dashboard show required column , enable/disable graphs? there no such possibility of apache jmeter 3.0 but can submit enhancement request giving more details on need. see: http://jmeter.apache.org/issues.html

javascript - canvas - Substract shape from a clipped canvas -

i want clip annulus (i.e. ring) image via javascripts canvas. have approach think inelegant (and dont understand why works, , why doesnt result in smaller circle). see jsfiddle context.drawimage(imageobj, 0, 0, 500, 500); //crop outer circle context2.beginpath(); context2.arc(250, 250, 200, 0, 2 * math.pi, false); context2.closepath(); context2.clip(); //draw circle context2.drawimage(canvas,0,0); //crop inner circle context2.beginpath(); context2.arc(250, 250, 100, 0, 2 * math.pi, false); context2.closepath(); context2.clip(); //clear context 2 context2.clearrect(0,0,500,500) // draw annulus context2.drawimage(canvas2,0,0); is there better way this? this work because clipping areas called clip method stack. imo, indeed not best way it, need call ctx.save(); before clipping , ctx.restore() afterward, heavy methods. my preferred way use compositing : var ctx = canvas.getcontext('

swing - After mac os sierra update facing scrolling issue with Java applications like Intellij -

after recent update, mac os sierra, macbook pro, i'm facing scrolling issues java applications intellij idea community edition. the scrolling in editor panes extremely fast. unit of scroll increments seem large. intellij idea version 2016.2.3. java version java 8 update 10.1. i see same behavior in "system preference" -> "java" -> "advanced" tab . this known bug , caused by jdk : it looks jdk issue , reproducible simple scrollable jlist. sierra generates more events el captain. these events contain values ~0.1 instead of expected ~1. java converts these small number 1 anyway. edit: see openjdk bug: https://bugs.openjdk.java.net/browse/jdk-8166591 edit2: described in other answer, jetbrains have fixed custom jdk. can download here , follow these instructions make intellij use jdk instead (select option labeled ... choose custom location).

java - How to enable server stack-trace for Rest calls in IBM Mobile First 8 -

in mf8, when try hit rest service urls unable stack trace when server returns 500 error. below error in postman. "unexpected error in server, see logs" how can enable server stack trace? it's unclear if you're using devkit or mobile foundation service. assuming you're using devkit, can find logs in devkit-folder/mfp-server/usr/servers/mfp/logs folder... there see messages.log file.

node.js - sqlite3 nodejs get value from table -

i've got function getname in db.js function getname(uid){ db.all("select name table uid = ? ", function (err){ if(err){ console.log(err); }else{ console.log(this); } }); } and want name , save var name in file. var uid = req.session.user; var name = db.getname(uid); console.log(name); what wrong db function getname why undefined? great if me! returning data async function might return undefined database request might not have completed on execution of return statement. function getname(uid, callback){ var query = "select name table uid = " + uid; var name = null; db.all(query, function (err, rows) { if(err){ console.log(err); }else{ name = rows[0].name; } }); return name; <--- can execute before db.all() if executed therefore returning null. because javascript runs asynchronously. } the result database query needs passed in callback o

php - Laravel : Upload multiple image but First image only uploaded -

i using laravel 4.2 , have form upload multiple images the problem when submit form returns view page , first image uploaded. can please review code , correct mistake {{ form::open(array('url'=>'doaddprojectimage', 'files'=>'true', 'method'=>'put', 'class'=>'margin-top-30 width-100per pull-left')) }} {{ form::file('img[]', array('class'=>'file', 'multiple'=>true)) }} {{ form::submit('add images project', array('class'=>'btn-success btn pull-left')) }} {{ form::hidden('pid', session::get('insid')) }} {{ form::close() }} and controller public function doaddprojectimage() { $proid = input::get('pid'); $projectimages = new projectsimages(); $files = input::file('img'); foreach($files $file) { $destination_path = 'images/projects/';

javascript - Replacing spaces between html tags with nbsps -

i want replace spaces between html tags nbsps using pure javascript. html: <div><span>apple</span> <span>grapes</span></div> you can see spaces between 2 span nodes. these spaces should replaced &nbsps. result should be: <div><span>apple</span><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span>grapes</span></div> please me. try simple logic var input= "<div><span>apple</span> <span>grapes</span></div>" var output = input.replace( /<\/span>\s*<span>/g, function(match){ return match.replace(/\s/g, "&nbsp;") } ); console.log( output );

java - Spring RestTemplate & AsyncRestTemplate with Netty4 hangs forever -

very simple setup: pom.xml <?xml version="1.0" encoding="utf-8"?> <project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelversion>4.0.0</modelversion> <groupid>com.example</groupid> <artifactid>demo-rest-client</artifactid> <version>0.0.1-snapshot</version> <packaging>jar</packaging> <name>demo-rest-client</name> <description>demo project spring boot</description> <parent> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-parent</artifactid> <version>1.4.1.release</version> <relativepath/> <!-- lookup parent repository --> </pa

python - How can i use matplotlib on Anaconda? (Win 7 x64) -

i'm using anaconda on windows 7 64 bits i'm unable use external package (numpy, matplotlib,scipy). @ first when tried load code: import matplotlib.pyplot plt plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show() i got dll error. then, downloaded , installed manually 64 bits packages here: http://www.lfd.uci.edu/~gohlke/pythonlibs/ when ran code message appeared: "apparently core died unexpectedly. use 'restart core' continue using terminal." i appreciate if can me problem because have projects , i'm wasting time. thank in advance. you should try run installation without mkl optimizations. conda remove mkl mkl-service conda install nomkl numpy scipy scikit-learn numexpr edit: your problem seems installed packages website , not anaconda channels. clean current environment packages (or create new one) , execute: conda install numpy matplotlib

c# - Multiple messages from Xamarin Messaging center when application is restarted -

i have xamarin forms application in use messagingcenter send data specific platform xamarin.forms application. in page subscribe messages in base.onappearing() , unsubscribe in base.ondisappearing() method. works expected. the problem i'm having when application get's stopped androidos (example of when change language of device) start getting copies of messages. i'm confused why happening noticed base.ondisappearing() method not called when application restarted. does have idea cause problem , how fix it? also, there way in xamarin see publishers , subscribers? like greensy said, in addition subscribing in onappearing() , unsubscribing in ondisappearing() , unsubscribe message before subscribing because, why not: protected override async void onappearing() { base.onappearing(); messagingcenter.unsubscribe<string>(this, "keyhere"); messagingcenter.subscribe<string>(this, "keyhere", string => { }))

directory - How to change PHPStorm 8 default new project location? -

when create new project, must edit current project location each time, because our global projects on: ~/sites/ however, phpstorm sets default as: ~/phpstormprojects/ how can change default location mine? there no gui that. phpstorm should remember last used folder (when created new project) , use default next 1 (does me; although i'm using same path since v1 .. maybe broken since then). if not , if have brave heart .. can edit config file directly :) phpstorm v8 , earlier: close ide open file in text editor: c:\users\username\.webide80\config\options\ide.general.xml (path phpstorm v8 on windows 7; other os/versions please see link: https://intellij-support.jetbrains.com/entries/23358108-directories-used-by-the-ide-to-store-settings-caches-plugins-and-logs ) file short -- find <option name="lastprojectlocation" node , edit value attribute -- put desired path there save changes, launch ide , see if worked you. phpstorm v9 , newer:

android - espresso times out on CookieManager.getInstance().setCookie(name, value) -

i'm writing espresso test login activity sets cookies: cookiemanager.getinstance().setcookie(name, value) but test hangs @ above code times out. looking setcookie code think calls native jni method. i can't try setcookie(name, value, callback) because code needs support api level 19. any idea why happening? many thanks! update: add seems happen when test run against emulator. runs without problem against real device.

Sticky footer in Liferay 6.2 -

how create sticky footer in liferay? i've read lot of docs of them haven't worked. i have in custom.css #footer { background-color: black; color: white; font-size: 200%; text-align: center; line-height: 3em; clear: both; position: relative; z-index: 10; height: 3em; margin-top: -3em; } and in portal_normal.vm : <div id="footer">powered german</div> in mentioned previous question asked how create footer , change color. then, in comment, asked how create sticky footer , got no answer, created thread. ok, solved problem!!! first of all, should @ line: <div class="container-fluid" id="wrapper"> in portlet_normal.vm : our footer category, every time not in end of browser page in end of block. need close block , place footer below: <div id="footer" class="row-fluid"> <div class="span12 text-center">

amazon web services - AWS adding load balancer and autoscaling to existing https instance using let's encrypt -

i've existing ec2 instance running apache2 set https on, using let's encrypt service. i'd create autoscaling group (with 1 3 of these instances) , load balancer , i'd keep https certificate. wich best way that? if ssl certificate going installed on each ec2 instance, can setup port 443 on load balancer tcp listener, , pass traffic on port 443 directly instance, ssl certificate served. note going require let's encrypt working on each instance gets created. easier new (free) certificate via aws acm service, , install on load balancer.

python - Wont run PyGame in Pycharm -

i running python 2.7.12 , pycharm school project doing. i have tried several methods make pygame run including virtualenv , installing in interpreter. nothing has worked , when run thing shows up: "/system/library/frameworks/python.framework/versions/2.7/bin/python2.7". i advice or step step guide on how run pygame code in pycharm

jscript - Fiddler - intercept request return different response -

in fiddler have custom rules upon getting response server, sends out new request automatically: static function onbeforeresponse(osession: session) { ... if (osession.uricontains("something.aspx")) { var requestb = "..." fiddlerobject.utilissuerequest(requestb); } ... } i want intercept requesta client, wait until have received response requestb, , return requestb's response requesta. know of way accomplish this? you may want try function fiddlerapplication.oproxy.sendrequestandwait this: static function onbeforeresponse(osession: session) { ... if (osession.uricontains("something.aspx")) { var osd = new system.collections.specialized.stringdictionary(); var getresquestbanswer : session = fiddlerapplication.oproxy.sendrequestandwait(requestb.orequest.headers, requestb.requestbodybytes, osd, null); if (200 == getresquestbanswer.responsecode) { osession.r

Illegal characters in path in -File parameter in powershell -

hallo i've got question, trying execute command in cmd , i'm getting copy-item : illegal characters in path. basing on exception stack looks cmd having problem prj - www part. command looks this powershell.exe -executionpolicy remotesigned -file ..\utils\deploy.ps1 "\\192.168.1.2\c$\program files (x86)\prj\prj - www\" interesting thing when launch using powershell using ..\utils\deploy.ps1 "\\192.168.1.2\c$\program files (x86)\prj\prj - www\" it works no problem. ideas?

javascript - Append additional html to cloned object in jquery -

i want add additional html in cloned object. var item = $("#clone") .clone(true, true) .attr({"id": "citem", "class": "row cartitem_" + item_id}) .css('display', 'block') .appendto("#all-items"); i know wrap method else. want append html after cloned object. or somehow can manipulate html of cloned object element. assuming trying add html after clone: $("#toclone") .clone() .attr({"id":"cloned"}) .appendto("#all-items") .after("<div>some more content <em>after</em> clone</div>"); the .appendto() returns element appended, can manipulate required, eg using .after()

c++ - Combining multiple functions to single generic function -

i have couple of function initialise interface pointer , each function initialise pointer particular version. have make these functions single generic function. bool init_9(mstsclib::imsrdpclient9* iface) { iface->putsomedata1(); iface->putsomedata2(); iface->putsomedata3(); } bool init_8(mstsclib::imsrdpclient8* iface) { iface->putsomedata2(); } bool init_7(mstsclib::imsrdpclient7* iface) { iface->putsomedata1(); iface->putsomedata3(); } i want know if there better implementation below prototype because each statement require explicit casting of interface pointer , visual studio intellisense have hard time fetching details. bool init(void* ptriface, int version) { void* iface; // todo: make type required version // cast iface @ run-time according version number // switch(version){} iface = reinterpret_cast<mstsclib::imsrdpclient9*>(ptriface); iface = reinterpret_cast<mstsclib::imsrdpclient8*>(ptrif

php - Select rows that have columns equal values in laravel 5.2 -

i'm new user of laravel 5.2 for example have data rows this: mytable ------------------------------- url | ip ------------------------------- google.com | 11.44.180.149 <----- msn.com | 11.44.180.149 google.com | 11.44.180.149 <----- yahoo.com | 11.44.180.149 google.com | 11.44.180.149 <----- i want select rows 2 or 3 columns value equal , delete rows equal it's more one for example convert this: mytable ------------------------------- url | ip ------------------------------- google.com | 11.44.180.149 <----- msn.com | 11.44.180.149 yahoo.com | 11.44.180.149 guys i'm sorry because can't speak english well. thank you you can use groupby() method eloquent: mytable::groupby('ip')->get(); or query builder: db::table('mytable')->groupby('ip')->get();

Select specific constructor with AutoFixture -

i'm using autofixture , i'd use specific constructor. i have following code , select constructor itemplateparameterhandler. public sealed class templatesegmenthandler : itemplatesegmenthandler { public templatesegmenthandler(itemplateiterator iterator) : this(new templateparameterhandler(iterator)) { contract.requires(iterator != null); } public templatesegmenthandler(itemplateparameterhandler parameterhandler) { contract.requires(parameterhandler != null); _parameterhandler = parameterhandler; _parameterhandler.ending += endingparameter; } // ... } edit: i want inject following fake implementation. (i'm using nsubstitute create fake object.) public sealed class customtemplateparameter : icustomization { private readonly itemplateparameterhandler _context; public customtemplateparameter() { _context = substitute.for<itemplateparameterhandler>(); } public

java - How do you specify a filter query with Solrj with embedded whitespace? -

i using solrj search solr . my application works fine until receive filter query embedded whitespace i have tried following formats string filterquery_1 = "\"xxx xxx xxx\"*"; string filterquery_2 = "xxx\\ xxx\\ xxx*"; string filterquery_3 = "(xxx xxx xxx)*"; none give satisfactory results they either result in no filtering being applied @ or rows not appear have relationship have filtered on how search solr solrj filter strings have embedded whitespace? ****** update 0001 ****** all text fields attempting search embedded blanks defined follows:- <field name="text_field_00001" type="text_general" indexed="true" stored="true" /> these fields contain postal address details. e.g. 123 road town county country aa1 1aa i guess trying - solr exact search blank character , wildcard this works, depends of configuration schema(field definition)

laravel notification on slack channel webkook -

an app sends http request url , records response in database, if in case there response website dawn, should automatical save response , send message slack channel. first question library use integrate slack laravel> there numerous slack-api wrappers in php. these 2 of expressive: https://github.com/vluzrmos/laravel-slack-api https://github.com/maknz/slack follow through readme , see fits best needs.

visual studio - How to check IP Address changes in VB.NET? -

how detect live ip changes? example: my ip without vpn: 3.3.3.3, whenever connect vpn ip changes 5.5.5.5. question is: how detect ip has changed when form running? i have tried: private sub timer4_tick(sender object, e eventargs) handles timer4.tick dim adapters networkinterface() = networkinterface.getallnetworkinterfaces() addhandler networkchange.networkaddresschanged, addressof downloadip dim n networkinterface each n in adapters timer4.stop() msgbox("ip changed") next n end sub try checking ip on external website for example: public sub getexternalip() try dim withevents ipbrowser new webbrowser ipbrowser.visible = false me.controls.add(ipbrowser) ipbrowser.navigate("http://seemyip.com/onyoursite.php") catch label2.text = "failed external ip" end t

intellij idea - Setup PhpStorm and Docker for PHP development without PHP on the host -

i want use phpstorm (in fact intellij php plugin) develop php software. i've been using linux laptop, php 5.5 , oracle library. has been difficult setup , had few compatibility problems. i have macbook need setup development environment. want try , use docker development, should allow me have different php versions no interaction. still want use phpstorm, , if possible don't want install php on host keep clean. is there way setup phpstorm use php interpreter inside docker machine don't need install php on host? i'm using this guide , i'm trying follow this setup php interpreter. phpstorm not require php installed anywhere. php required run or debug scripts , tests, use composer, etc. the simplest way osx host use phpstorm vagrant . still can use docker described in phpstorm remote interpreter , still uses same vm, may require bit more effort configure dockerfile.

javascript - animate left not working on page scroll -

i have 2 div's in pink , sky blue color, make them same height , width. pink div covering height of screen, when scroll down , scrollbar reaches sky blue want animate blue div right , when scrollbar leave div want div move comes from. $(document).ready(function(){ $(window).scrolltop(function(){ $(this).scroll(function(){ var scrolltoporbottom = $(document).height() - $(window).height() - $(window).scrolltop(); if(flag === 0 && scrolltoporbottom < 1256){ $('#bluediv').animate({right: '200px'}, function(){ flag = 1; }); } if(flag === 1 && scrolltoporbottom < 740){ console.log(scrolltoporbottom); $('#bluediv').slideleft(); flag = 0; } }); }); }); js fiddle you can apply logic: use transition animate element, css this: #bluediv { width: 50%; height: 100px; background-color: blue; position: absolute; left:0; transition:left 2s linear; } #bluediv.right {

Send HTML email from google spreadsheet using a button -

i new stack overflow , looking advice , guidance on google spreadsheet have been working on. a demo of can found @ https://docs.google.com/spreadsheets/d/1t9wfcg_1_maavpn0l3v58jdd04y1ll3phaeotukq0z4/edit?usp=sharing basically jist of require following. a sendemail button in tool bar @ top send html formatted email email on active page in specific colour. essentially allow me send reminder clients in groups , colour status. have mail each client individually using canned response pretty time consuming. so far using following script basis, can send email run errors if email fields empty. looking overlook empty fields , continue searching email address. can locate template of active sheet require locate template of sheet , use that. when try adding in html script picks template sends plain text , not sent html. function sendemails() { var sheet = spreadsheetapp.getactivesheet(); var startrow = 2; // first row of data process var numrows = 100; // number of rows

How to remove script from Google Spreadsheet button -

in google spreadsheet have simple script, changes a1 cell's background colour red. script assigned button in spreadsheets. after assigning script cannot find way remove script or edit button. wonder how done? here link similar file see problem in practice. go tools > script editor inside spreadsheet , you'll have option edit script.

c - Nested strtok_r : command line argument parsing -

code here: http://ideone.com/aznxfm #include <stdio.h> #include <stdlib.h> #include<string.h> int main() { char *buffer; size_t bufsize = 32; size_t characters; buffer = (char *)malloc(bufsize * sizeof(char)); if( buffer == null) { perror("unable allocate buffer"); exit(1); } printf("type something: "); characters = getline(&buffer,&bufsize,stdin); printf("%zu characters read.\n",characters); printf("you typed: %s",buffer); char *end_str,*token2; char *token = strtok_r(buffer,";",&end_str); printf("token : %s \n", token); int count =0,wordcnt=0; while(token !=null) { char *end_token; count++; printf("outside count ------------------------%d\n", count); strtok_r(token," ",&end_token); while(token2!=null) { wordcnt++;

PHP Post Webservice Issue -

trying implement post webservice in php can used in ios app communicating db. can please identify mistake. please find code below. saying "request method not accepted" status 0 returned <?php // create connection $con=mysqli_connect("myhost.com","myuser","mypassword","mydb"); if($_server['request_method'] == "post"){ // data $lat= isset($_post['lat']) ? mysql_real_escape_string($_post['long']) : ""; $long= isset($_post['long']) ? mysql_real_escape_string($_post['long']) : ""; $timestamp = isset($_post['timestamp']) ? mysql_real_escape_string($_post['timestamp']) : ""; $deviceid = isset($_post['deviceid']) ? mysql_real_escape_string($_post['deviceid']) : ""; // insert data data base $sql = "insert `gpsreporting` (`lat`, `long`, `timestamp`, `deviceid`) values ('$lat', '$long', '

How to use MSBuild transform when ItemGroup files all have identical names? -

i have bunch of files x.txt in various directories throughout project. part of build step, collect these , place them in single folder (without needing declare each one). can detect them using: <itemgroup> <myfiles include="$(srcroot)\**\x.txt"/> </itemgroup> however, if copy these single folder - overwrite each other. have tried using transform append guid each file name, guid created once, , re-used each transform (thus overwrite each over). there way of generating unique names in msbuild when copying itemgroup identically named files? end naming scheme not important, long files end in folder. the transform works have 'force' generate new data on each iteration. took me while figure out , makes sense couldn't find documentation explaining this. works referencing other existing metadata: msbuild sees has evaluated on every iteration happily evaluate part of new metadata. example, using %(filename): <target name="cre

ios - Issue passing a closure that takes an escaping closure to a function that accepts a closure of that type -

in old swift world (2.0 believe) had following y-combinator implementation func y<t, r>( f: (t -> r) -> (t -> r) ) -> (t -> r) { return { (t: t) -> r in return f(self.y(f))(t) } } i call y-comb elsewhere create recursive closure, so: let delaytime = dispatch_time(dispatch_time_now, int64(1 * double(nsec_per_sec))) let repeatclosure = self.y { (f: () -> () ) -> (() -> ()) in return { if self.responses_received != responses_expected { dispatch_after(delaytime, dispatch_get_main_queue()) { // resend nsnotificationcenter.defaultcenter(). postnotificationname(senddata, object: nil, userinfo: datatosend) f() } } else { print("completed!") self.responses_received = 0 } } } repeatclosure() the idea being observer of 'sendd

c# - Autofac equivalent of StructureMap's WhatDoIHave() -

does autofac have analog structuremap's whatdoihave() method? i'd able see visual representation of services registered in container. i've looked @ autofac's documentation , can't find similar. if such method not exist, there technical issue autofac makes difficult implement or has there not been interest in providing it? you can use registrationfor method of icomponentregistry registered service. can access component registry componentregistry method of icomponentcontext (ie : ilifetimescope icontainer ) icontainer container = builder.build(); container.componentregistry.registrationfor(new typedservice(typeof(ixservice));

javascript - Check email if exist using ajax -

basically, want check email if exist in db automatically. function not work when connection.php & mysqli queries inserted. html: <input type="email" name="email" class="formemail"> js: $( document ).ready(function() { $('.formemail').on('change', function() { //ajax request $.ajax({ url: "queries/checkemail.php", data: { 'email' : $('.formemail').val() }, datatype: 'json', success: function(data) { if(data == true) { alert('email exists!'); } else { alert('email doesnt!'); } }, error: function(data){ //error } }); }); }); php: require_once("../connection.php"); $useremail = $_get['emai

docker - ImageMagick Go API HTTP Hangs on ReadImageBlob -

i have written beego http server, when user hits endpoint: the server requests image server (for instance imgur) it reads bytes of image , passes them gographics/imagick this (should) resize image , return byte array of result what happens http server hangs, don't error handling, , 502 bad gateway on endpoints of server. my code looks this: func processcontactimage(idx int, image []byte) ([]byte, error) { imagick.initialize() defer imagick.terminate() log.println("idx: ", idx) mw := imagick.newmagickwand() log.println("reading image blob: ", image) err := mw.readimageblob(image) if err != nil { log.println("reading blob failed: ", err) return []byte{}, err } //... } i can see in terminal log message "reading image blob: [bytes, bytes bytes]" , have copied bytes printed small program test bytes indeed hold image, do. hangs on err := mw.readimageblob(image) , don't think g

c++ - How can optional fields that are not assigned values in protocbuf be allocated spaces -

if defined: message { required int32 first = 1; optional int32 second = 2; } the size of space when set_second(0) serializetoarray() not same when set_second(14353355445) serializetoarray() are there ways make them have same size of space ? in other ways,how can make optional fields not assigned values have same size of space assigned values? my recommendation is: don't try protobuf. protobuf not designed give fixed nor predictable sizes, if that's want, protobuf isn't right tool job. sure, can use hacks using fixed32 , trying make sure fields have non-default values, fighting tools. else change in future makes sizes unpredictable again. better choose tool matches needs.

Java code cannot invoke method from scriptengine with new context -

i trying implement example invoking method javascript in java. private static final string js = "function doit(p) { list.add(p); return true; }"; public static void main(string[] args) throws scriptexception, nosuchmethodexception { list<string> list = new arraylist<>(); scriptenginemanager scriptmanager = new scriptenginemanager(); scriptengine engine = scriptmanager.getenginebyname("nashorn"); scriptcontext context = new simplescriptcontext(); context.setbindings(engine.createbindings(), scriptcontext.engine_scope); bindings scope = context.getbindings(scriptcontext.engine_scope); scope.put("list", list); engine.eval(js, context); invocable invocable = (invocable) engine; invocable.invokefunction("doit", "hello!!!"); system.out.println(list.size()); } } this code throws exception: exception in thread "main" java.lang.nosuchmethodexception: no such funct

Parameter Layout in ASP.NET Report Viewer (SSRS 2016) -

the 2016 sql server report builder allows users arrange how parameters laid out when report renders. gives more flexibility previous versions shoved parameters 2-column stack @ top of report. however seems asp.net report viewer not honor layout i'm specifying. example, if layout parameters in 4x3 rows, rendered report in asp.net report viewer still shows parameters in 2x6 grid. does asp.net reportviewer not support custom parameter layouts remote reports? fyi: i'm using version 11 of reportviewer. https://www.nuget.org/packages/microsoft.report.viewer/11.0.0 i'm pretty sure need using v13. here's nuget install line: install-package microsoft.reportingservices.reportviewercontrol.webforms.preview here's msdn webpage: https://msdn.microsoft.com/library/01a821c4-2920-400c-be03-93d26c749bb1.aspx if sql server data tools or sql server management studio sql 2016 installed, make sure it’s updated latest version. earlier versions of ssdt incor

Triggers the azure message queue an event when a message was added? How can I subscribe to? this event? -

is possible configure azure message queue calls web request or whatever when message added or deleted? or thing can polling new messages in queue? no. can use azure queues trigger events/functions azure webjobs , such. can find more information here: https://azure.microsoft.com/en-us/documentation/articles/websites-dotnet-webjobs-sdk-storage-queues-how-to/

c++ - Get Index Given Row and Column -

is there formula can used index given current column , row? following have far. problem is, however, code works first row... for (int = 0; < rows; i++) { (int j = 0; j < columns; j++) { index = * (columns - 1) + j; } } this should work: index = * columns + j;

angular - Angular2 custom form control including textfield and error message -

i write custom form control including textfield , error message tooltip, works model-driven form. at rc5, code following worked fine, @ 2.0, doesn't. https://embed.plnkr.co/bvfbsf5q74j7ehwuh5y7/ is there way establish relationship host formcontrol , child ngmodel, or access host formcontrol inner? otherwise, there way realize idea? i found way. finally, code becomes this. @component({ selector: 'custom-input', template: ` <input type="text" [required]="required" [(ngmodel)]="value" #model="ngmodel"/> <div>inner ngmodel errors: {{model.errors|json}}</div> <div>ngcontrol errors: {{ngcontrol.errors|json}}</div> `, providers: [{ provide: ng_value_accessor, useexisting: forwardref(() => custominput), multi: true }] }) export class custominput implements controlvalueaccessor, oninit { private innervalue: = ''; private ngcontrol: ngcontrol;

Links in Excel workbook not loading due to local google drive location -

i posted in superuser, think may have been wrong place, cross posting here. - edit: tag google-drive-sdk, it's problem google drive in windows, not api. guess there's no option google drive itself i have master workbook has links 9 different files. have 2 other workbooks used other people link master workbook information. of these files saved on google drive , associated has access of files individually. until yesterday there wasn't problem loading files, of sudden when opening files on other computers, can't find links , can't load new information. i'm assuming part of problem due me having google drive saved d:\ drive instead of c:\ of other computers, , in files links point d:\google drive\, said, working until yesterday. is there way work around issue, without changing drive location? know i'm not person has put google drive on different partition windows, there potential that, causing conflicts. thank help, , let me know if need more infor

javascript - How to send JSON from a checkbox form -

i coded this, working think there better way this.. have form user can check checkboxes. each checkbox have multiple info want send servlet, thought create manually json... <input name="warehouse" value="{ 'version':'<%=b.getversion()%>', 'product':'<%=b.getproduct()%>', 'productiondate':'<%=b.getproductiondate()%>', 'order':'<%=b.getorder()%>' }" type="checkbox"> then in servlet, read checkboxes... string[] product = request.getparametervalues("warehouse"); i replace " ' product.replace("'","\""); and convert every string in json by: objectmapper mapper = new objectmapper(); box box = mapper.readvalue(product, box.class); is there better way above send these info servlet?

java - how to control the number of mappers per region server for reading a HBase table -

Image
i have hbase table(written through apache phoenix) , needs read , write flat text file. current bottleneck have 32 salt buckets hbase(phoenix) table opens 32 mappers read. , when data grows on 100 billion becomes time consuming. can point me how control number of mappers per region server reading hbase table? have seen program explains in below url , " https://gist.github.com/bbeaudreault/9788499 " not have driver program explains fully. can help? in observation, number of regions of table = number of mappers opened framework . so reduce number of regions in turn reduce number of mappers. how can done : 1) pre-split hbase table while creating ex 0-9 . 2) load data in these regions generating row prefix between 0-9.* below various ways splitting : also, have look @ apache-hbase-region-splitting-and-merging moreover, setting number of mappers not guarantee open many, driven input splits you can change number of mappers using setnummapta

java - The gernerated SOAP WEb Service classes contain void methods -

i got wsdl files generate soap project. configured apache-cxf-2.7.18 in eclipse. after craeting web dynmic project --> droped wsdl files relatedschemas new created web dynamic project --> right click --> other --> web service --> checked configuration in client enviment configuration (i have apache cfx2.x selected) --> finsihed. generated code contains classes void method without return vlaue , when sending request soapui web service, getting xml message , not unterstand how getting response void method. javax.xml.ws.holder class work?

c++ - Constructor using std::forward -

to knowledge, 2 common ways of efficiently implementing constructor in c++11 using 2 of them foo(const bar& bar) : bar_{bar} {}; foo(bar&& bar) : bar_{std::move(bar)} {}; or 1 in fashion of foo(bar bar) : bar_{std::move(bar)} {}; with first option resulting in optimal performance (e.g. single copy in case of lvalue , single move in case of rvalue), needing 2 n overloads n variables, whereas second option needs 1 function @ cost of additional move when passing in lvalue. this shouldn't make of impact in cases, surely neither choice optimal. 1 following: template<typename t> foo(t&& bar) : bar_{std::forward<t>(bar)} {}; this has disadvantage of allowing variables of possibly unwanted types bar parameter (which problem i'm sure resolved using template specialization), in case performance optimal , code grows linearly amount of variables. why nobody using forward purpose? isn't optimal way? people perfect forwa

c# - Error converting SQL with join to LINQ -

i have sql query i'm trying convert linq , having trouble understanding obscure error messages when query enumerated. the sql query (which works intended), is: select a.testguid, min(a.starttime) starttime, count(b.testcaseid) numtests, count(dinstinct a.id) numscenarios loadtestsummary join loadtesttestsummarydata b on a.loadtestrunid = b.loadtestrunid a.targetstack = env , a.testguid not null , a.starttime not null , a.loadtestrunid not null group a.testguid converting linq, following: var q = in _context.loadtestsummary a.targetstack == env && a.testguid != null && a.starttime != null && a.loadtestrunid != null join b in _context.loadtesttestsummarydata on new { loadtestrunid = convert.toint32(a.loadtestrunid) } equals new { loadtestrunid = b.loadtestrunid } group new { a, b } new {

Complex object as a queryparameter in in java rest application -

i need able query resource filter many parameters (all optionals) my url specification : get http://something/version/resource?f={"param1":"1","param2":"something else", "param3":"tomato" i tried 2 approaches: @xmlrootelement created class filter , annotated @xmlrootelement parameters not parsed class. @xmlrootelement myclassfilter{ string param1; string param2; .......... } @beanparam removed @xmlrootelement annotation , put @queryparam annotation every field in class , in resource method put @beanparam one. myclassfilter{ @queryparam("param1") string param1; @queryparam("param2") string param2; .......... } i null objects both methods. point me right direction? consume services don't have experience on server side. i solved problem, in method receive filter string: @queryparam(value = "f") string f and parse using o