Wednesday 15 January 2014

node.js - req undefined when called from next() -



node.js - req undefined when called from next() -

//in routes.js

test = require('test'); app.get('/test', function(req, res) { test.first( req,res, test.second, 'info' ); });

//in test.js

exports.first= function(req, res, next, inf){ req.test= inf; console.log(inf); //info next(); }; exports.second= function(req, res, next){ console.log(req); //undefined res.jsonp(req.test);//error :s };

this follow question how phone call controller express routes , include defined parameter

assuming calling next(); in test.first(), means passing no arguments test.second(). current setup need next(req, res); in test.first() instead.

node.js express routing undefined

java - For Loop Card game stuck -



java - For Loop Card game stuck -

i trying design card game in java scores 1 point each card in run of 3 or more consecutive cards in hand of 5 cards (does not have same suit). illustration 2,3,k,3,4 = 2 runs (2,3,4 & 2,3,4)-(swapping 3)

however i'm stuck on how should write code.. can guide me right direction?

this have far:

public static int[] card; public static void main(string args[]) { int[] card = new int[5]; (card1 = 0; card1 <= 4; card1++) { if (card[1] == card[0] + 1) { (card2 = card1 + 1; card2 <= 4; card2++) { if (card[2] == card[1] + 1) { countvalueforrun++; } (card3 = card2 + 1; card3 <= 4; card3++) { if (card[3] == card[2] + 1) { countvalueforrun++; } (card4 = card3 + 1; card4 <= 4; card4++) { if (card[3] == card[3] + 1) { countvalueforrun++; } } } } } } system.out.println((countvalueforrun)); }

since asking direction here is:

assuming have devised method card input user entry or random, approach problem follows:

step1: first arrange arrange in ascending order initializing array cardarranged[card.length] using nested & if loop.

step2: run cardarranged in 2 nested loops, checking each card whether has "run" in pack or not. moment sequence crosses (count of) 3, countvalueforrun gives +1.

for(int i=0;i<cardarranged.length;i++) { int sequence = 0; int cardcount=0; for(int j=i;j<cardarranged.length;j++) //j=i because cards arranged in ascending order { if(cardarranged[i]==cardarranged[cardcount]+1) { sequence++; } cardcount++; } if(sequence>=3) { countvalueforrun++; }

step 3: print countvalueforrun

hope helps !!

java loops if-statement

ios - Getting Warning with Parse.com -



ios - Getting Warning with Parse.com -

i'm triying access each item on nsarray trough enumerateobjectsusingblock, since allow me utilize fast enumration , evaluating index.

when utilize findobjectsinbackgroundwithblock,

i warning: long-running operation beingness executed on main thread. break on warnblockingoperationonmainthread() debug.

as thought used in background not block mainthread. here code , i'm triying accomplish have 2 uiimageview container i'm pulling images result of relation on query. since there container tought improve evaluate index of nsarray.

not sure how can remedy warning.

thanks

[query findobjectsinbackgroundwithblock:^(nsarray *objects, nserror *error) { if (objects != 0) { [objects enumerateobjectsusingblock:^(pfuser *object, nsuinteger idx, bool *stop) { if (idx == 0) { pffile *userprofile = [object objectforkey:@"userpic"]; cell.promoter1.file = userprofile; cell.promoter1.contentmode = uiviewcontentmodescaleaspectfit; [cell.promoter1 loadinbackground]; cell.promoter1name.textalignment = nstextalignmentcenter; cell.promoter1name.linebreakmode = nslinebreakbywordwrapping; } if (idx == 1) { pffile *userprofile = [object objectforkey:@"userpic"]; cell.promoter2.file = userprofile; cell.promoter2.contentmode = uiviewcontentmodescaleaspectfit; [cell.promoter2 loadinbackground]; nsattributedstring *promoter1name; cell.promoter2name.textalignment = nstextalignmentcenter; *stop = yes; } }]; } }];

troubleshooting code, realized findobjectsinbackgroundwithblock not cause warning.

on part of code had this:

pfuser *user = [pfquery getuserobjectwithid:@"ebwfrl8pcf"]; [relation addobject:user]; [self.event saveinbackground];

which block main thread.

i apologize.

ios objective-c parse.com cell fast-enumeration

java - check a list how many is positive number -



java - check a list how many is positive number -

write programme called positivenegative reads unspecified number of integers, determines how many positive , negative values have been entered, , computes sum , average of input values (not counting zeros). reading of input ends when user enters 0 (zero). display number of positive , negative inputs, sum , average. average should computed floating-point number. design programme such asks user if want go on new inputs after each set of entries, ending programme when not respond question "yes".

here sample run:

input list of integers (end 0): 1 2 -1 3 0 # of positive inputs: 3 # of negative inputs: 1 total: 5.0 average: 1.25 go on new inputs? yes input list of integers (end 0): 0 no numbers entered except 0 go on new inputs? no

and here code:

import java.util.*; public class positivenegative { public static void main(string[] args){ scanner input = new scanner(system.in); string answer; int countpositive = 0; int countnegative = 0; int total = 0; int num = 0; system.out.print("input list of integers (end 0): "); do{ string list = input.nextline(); for(int = 0; ; i=i+2 ){ num = integer.parseint(list.substring(i,i+1)); if( num == 0) break; else if ( num > 0) countpositive++; else if ( num < 0) countnegative--; total = total + num; } double average = total/(countpositive + countnegative); system.out.println("# of positive inputs: "+countpositive); system.out.println("# of negative inputs: "+countnegative); system.out.println("the total: "+total); system.out.println("the average"+average); system.out.println("\n "); system.out.print("would go on new inputs? "); reply = input.next(); }while(answer.equalsignorecase("yes")); } }

i can compile file, when run it, can't result sample run.

you decrementing (countnegative--;) count of negative integers instead of incrementing (countnegative++;) when negative integer encountered.

java string loops

css - Left margin is appearing in html that I don't want -



css - Left margin is appearing in html that I don't want -

there left margin in nav bar unable alter fiddle here

html

<body> <div class="wrapper"> <div class="container"> <nav class="nav"> <ul> <a class="navlic" href="index.html"><li>home</li></a> <a class="navli" href="portfolio.html"><li>portfolio</li></a> <a class="navli" href="blog.html"><li>blog</li></a> <a class="navli" href="about.html"><li>about</li></a> </ul> </nav> </div> <div class="content"> <span><h1></h1></span> </div> <footer> <p></p> </footer> </div> </body>

css in fiddle

the nav object has fixed position...use left:0 instead

js fiddle example

html css css3 margin

javascript - how to search for a fixed value when clicked on search button from a list which is already retrieved from database using AngularJs -



javascript - how to search for a fixed value when clicked on search button from a list which is already retrieved from database using AngularJs -

i using search functionality searched records list retrieved database , populated in html page,i getting filtered search not finish search list in controller. need fixed value result showed when clicked on search button(eg.i should not 'john' when searched 'j',i should exact value search),can 1 help me out. this piece of html code.

<ul class="col-sm-11 col-xs-12 searchfields"> <li class="col-md-2 col-sm-4"><span class="col-xs-12">tin</span><input type="text" ng-model="data.providertin" ng-keyup="formattin($event)" ng-trim="false" ng-blur="clearerror()" id="tinelem" placeholder="tin" maxlength="11" autofocus /></li> <li class="col-md-2 col-sm-4"><span class="col-xs-12">last name</span><input type="text" ng-model="data.providerfulllastname" ng-keyup="formatlast($event)" placeholder="last name" maxlength="20" /></li> <li class="col-md-2 col-sm-4"><span class="col-xs-12">first name</span><input type="text" ng-model="data.providerfirstname" ng-keyup="formatfirst($event)" placeholder="first name" maxlength="12" /></li> <li class="col-md-2 col-sm-4"><span class="col-xs-12">city</span><input type="text" ng-model="data.prvdadrcitynm" ng-keyup="formatcity($event)" placeholder="city" maxlength="21" /></li> <li class="col-md-2 col-sm-4"><span class="col-xs-12">state</span><input type="text" ng-model="data.prvdadrstcd" ng-keyup="formatstate($event)" ng-trim="false" ng-blur="clearerror()" placeholder="state" maxlength=2 /></li> <li class="col-md-2 col-sm-4"><span class="col-xs-12">phone</span><input type="text" ng-model="provider.prvdtelnum" ng-keyup="formatphone($event)" ng-blur="clearerror()" placeholder="(xxx) xxx-xxxx" onkeydown="javascript:backspacerdown(this,event);" onkeyup="javascript:backspacerup(this,event);" maxlength="14" required /></li> </ul> <div class="col-md-1 col-sm-4 searchblock"> <button class="searchbtn" type="button" id="searchbtn" ng-click="">search</button> </div> <tr ng-repeat= "data in recommendatnlist| filter:searchd" > <td><a href="#/viewprvddtlpage/{{data.providerid}}" class="openlink">{{data.providertin}}</a></td> <td>{{data.providerfulllastname}}</td> <td>{{data.providerfirstname}}</td> <td>{{data.providerpracticename}}</td> <td>{{data.prvdadrcitynm}}</td> <td>{{data.prvdadrstcd}}</td> <td>{{data.prvdadrxpndzipcd}}</td> <td>{{data.measure}}</td> <td>{{data.grade}}</td> <td>{{data.measurepaid}}</td> <td>{{data.totalpaid}}</td> <td>{{data.nooflettrsanymeasure}}</td> <td>{{data.nooflettrsrecommmeasure}}</td> <td>{{data.currclaimanymeasure}}</td> <td>{{data.currclaimcurrrecomm}}</td> <td class="interventtblecol"><input type="checkbox" ng-checked="data.letter" ng-model="data.letter"></td> <td class="interventtblecol"><input type="checkbox" ng-checked="data.mcr" ng-model="data.mcr"></td> <td class="interventtblecol"><input type="checkbox" ng-checked="data.fcr" ng-model="data.fcr"></td> <td class="interventtblecol"><input type="checkbox" ng-checked="data.siu" ng-model="data.siu"></td> <td class="interventtblecol"><input type="checkbox" ng-checked="data.removeclaimrvw" ng-model="data.removeclaimrvw" ></td> <td class="interventtblecol"><input type="checkbox" ng-checked="data.flag" ng-model="data.flag"></td> </tr>

and controller

angular.module('admapp').controller( "recommendationctrl", [ '$scope', '$stateparams', 'recommendationservice', function($scope, $stateparams, recommendationservice) { recommendationservice.fetchrecommendatns().then(function(data) { alert("data"+json.stringify(data)); $scope.recommendatnlist=data; });

that odd thing request.

tl;dr: plunkr illustration on explicit filter wrote below, bit more beginners struggling angularjs.

but trying create explicit filter?

like if have

$scope.records = [{name:'john', phone:'555-1276'}, {name:'mary', phone:'800-big-mary'}, {name:'mike', phone:'555-4321'}, {name:'adam', phone:'555-5678'}, {name:'julie', phone:'555-8765'}, {name:'juliette', phone:'555-5678'}];

you want j nowadays nil , john nowadays name:john, phone: 555-1276 ?

if case need utilize anuglarjs custom filters.

i've created plunker reason: working explicit filter using same records above.

the filter method rather not smart i'll give short explanation :

newapp.filter('explicitsearch',function(){ //angularjs -> declaring new filter in our newapp module. homecoming function(items, string){ //the parameters here: first parameter in filter homecoming function info referring to. //the sec parameter argument passing filter, //example : looks <tr ng-repeat='friend in friends | filtername:filtersecondparam'> var filtered = []; //this array, going our filtered results. //this simple js code, iterate on info filter have passed, if find explicitly equal, add together our filtered array. (var = 0; < items.length; i++) { var item = items[i]; if (item.name === string) { filtered.push(item); } if(item.phone === string){ filtered.push(item); } } homecoming filtered; } });

use upon html:

<body ng-controller='ctrl'> search: <input ng-model="searchtext"> <table> <thead> <tr> <th>name</th> <th>phone</th> </tr> </thead> <tbody> <tr ng-repeat='record in records | explicitsearch:searchtext '> <td>{{record.name}}</td> <td>{{record.phone}}></td> </tr> </tbody> </table> </body>

javascript html angularjs

cpu speed - Equations and big numbers in programming -



cpu speed - Equations and big numbers in programming -

so if have lets 4 integers:

int = 50000 , int b = 5000000 , int c = 100 , int d = 500

now wanted run b - , c - d.

my question b-a run slower c - d or executed in exact same speed processor?

first of all, in case presented operations same. can read how these circuits work here

second of all, fixed point mathematics very fast on computers these days. if bottleneck, don't know tell you.

cpu-speed

Importing images from a directory (Python) -



Importing images from a directory (Python) -

is there way import images within directory (the directory known, don't need find it). have found way of finding out length of directory, i'm not sure how can import images (using pil/pillow) different variables, list or dictionary, length of directory.

i'd start using glob:

from pil import image import glob image_list = [] filename in glob.glob('yourpath/*.gif'): #assuming gif im=image.open(filename) image_list.append(im)

then need list of images (image_list).

python python-imaging-library pillow

Type-safe named fields in haskell ADTs -



Type-safe named fields in haskell ADTs -

there's mutual problem easy haskell. code-snippet describes this:

data jobdescription = jobone { n :: int } | jobtwo | jobthree { n :: int } deriving (show, eq) taskoneworker :: jobdescription -> io () taskoneworker t = putstrln $ "n: " ++ (show $ n t) main :: io () main = -- runs ok: taskoneworker (jobone 10) -- fails @ runtime: -- taskoneworker jobtwo -- works, didn't want to: -- taskoneworker (jobthree 10)

i described problem , it's possible solutions in article: https://www.fpcomplete.com/user/k_bx/playing-with-datakinds

here, on stackoverflow, i'd inquire -- best solutions problem, using tools , documentation?

i suggest using prism. prism _jobone represents int value lives within jobone constructor. in taskoneworker using ^?. either value t indeed jobone constructor , argument homecoming in just, or not jobone constructor , nothing.

{-# language templatehaskell #-} import control.lens info jobdescription = jobone { n :: int } | jobtwo | jobthree { n :: int } deriving (show, eq) $(makeprisms ''jobdescription) taskoneworker :: jobdescription -> io () taskoneworker t = case t ^? _jobone of n -> putstrln $ "n: " ++ show n nil -> putstrln "not jobone" -- or 'return ()' if want ignore these cases main :: io () main = taskoneworker (jobone 10) taskoneworker jobtwo taskoneworker (jobthree 10) -- *main> main -- n: 10 -- not jobone -- not jobone

haskell

ios - When via a class method get an object, why before return the value, the method can put the value into AutoReleasePool? -



ios - When via a class method get an object, why before return the value, the method can put the value into AutoReleasePool? -

e.g.

method1:

-(void)method1{ id array1 = [[nsmutablearray alloc] init];//now,retaincount of array1 1 }

method2:

-(void)method2{ id array2 = [nsmutablearray array]; //now,retaincount of array2 2 }

question 1:int method2,the implementation of class method +array not utilize [alloc [init]]? why did not homecoming value directly?and set value in autoreleasepoll?

question 2:which improve (faster & more efficient) utilize between 2 way? why?

both of these statements equivalent , sec 1 doesn't add together retain count of array1. first method function assume ownership , subsequently responsible release calls later on, arc don't have worry these details.

in pre-arc days, values methods homecoming set in autorelease pools avoid premature deallocation , memory leaks. consider next cases:

-(nsarray *)emptyarray { // create homecoming value calls alloc , init. nsarray *returnarray = [[nsarray alloc] init]; homecoming returnarray; }

because there no phone call [returnarray release]; value returned method never deallocated , there memory leak. @ first may seem there no direct solution this.

-(nsarray *)emptyarray { nsarray *returnarray = [[nsarray alloc] init]; homecoming returnarray; [returnarray release]; // unreachable statement }

and

-(nsarray *)emptyarray { // create homecoming value calls alloc , init. nsarray *returnarray = [[nsarray alloc] init]; [returnarray release]; homecoming returnarray; // homecoming deallocated object }

so instead add together array autorelease pool released after time--long plenty retained whatever receiving homecoming value, still preventing memory leaks.

ios objective-c cocoa memory-management automatic-ref-counting

Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use -



Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use -

okay im having annying error when im trying typing in username , password know problem ?

the error : http://gyazo.com/9ee7a24d164be385c499a2bf82022720 database: http://gyazo.com/4524567fd304d4181ce0c82f8e715ea8

<!doctype html> <html> <head> </head> <body> <h1>login</h1> <p> <?php if (strtoupper($_server['request_method']) == 'post') { $link = mysql_connect('localhost', 'databasename', 'password'); if (!$link) { die('not connected : ' . mysql_error()); } $db_selected = mysql_select_db('databasename', $link); if (!$db_selected) { die ('can\'t utilize foo : ' . mysql_error()); } $query = "select username, pass hejsan ='".$_post['username'] ."' , pass ='".$_post['pass']."' limit 0, 30 "; echo $query; echo "<br><br>"; $result = mysql_query($query); if (!$result) { $message = 'invalid query: ' . mysql_error() . "\n"; $message .= 'whole query: ' . $query; die($message); } echo "<ul>"; while ($row = mysql_fetch_assoc($result)) { echo "<li>"; echo "inloggad som:". $row['username']." med lösen:".$row['pass']; echo "</li>"; } echo "</ul>"; mysql_free_result($result); } ?> <form method="post"> username:<input type="text" name="username"><br> password:<input type="text" name="pass"><br> <input type="submit"> </form> </p> </body> </html>

you didn't specify field in query.

it should be

"select username, pass hejsan ***username*** ='".$_post['username'] ."' , pass ='".$_post['pass']."'

limit 0, 30 ";

where username field usernames stored.

mysql

.htaccess - How do I set canonical URLs and redirect to https? -



.htaccess - How do I set canonical URLs and redirect to https? -

i have redirects working http https, canonicalization non www urls redirect www version…well, sort of.

http://www.domain.com redirects https://www.domain.com

http://domain.com redirects https://www.domain.com

https://www.domain.com loads fine

however, https://domain.com won't connect (different browsers give different messages).

i verified mod_rewrite enabled. here's code below:

#redirect ssl rewritecond %{http:x-forwarded-proto} !https rewriterule ^.*$ https://%{server_name}%{request_uri}[r01,l] #canonicalization rewritecond %{http_host} !^www.domain.com$ [nc] rewriterule ^(.*)$ https://www.domain.com/$1[l,r01]

two questions:

1.) why doesn't https://domain.com route https://www.domain.com?

2.) i've seen flag r=301 redirects, r01 mean?

thanks!

you can combine 2 this:

rewritecond %{http:x-forwarded-proto} !https [or] rewritecond %{http_host} !^www.domain.com$ [nc] rewriterule ^(.*)$ https://www.domain.com/$1 [l,r=301]

a few things:

r01 incorrect, it's not flag, , have caused 500 error if wasn't missing space before flags you're missing space separates target url , flags: $1[l,r01] ends beingness interpreted part of target url.

.htaccess mod-rewrite

regex - How to parse unicode characters in UTF-8 HTML document with PHP -



regex - How to parse unicode characters in UTF-8 HTML document with PHP -

i have html file generated google next headings,

<!doctype html><html><head><title>ddd</title><meta http-equiv="content-type" content="text/html;charset=utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=2">

and utilize next pattern match text contains unicode (chinese , special characters).

$pattern_title = '/class=\"text1t\">[\’\w\s\:\d]+/u';

i know can utilize "u" enable uniform matching in php utf-8 compatible documents.however, though utf-8 document, there wrong here. when run php code , parse online html page (without saving contents in computer), not match due "u" letter. when remove "u", code works fine fails match chinese characters. copied html contents , stored them within string variable php code , saved file. run code "u" , works fine.

so, have no thought how prepare problem. there post in stackoverflow converting non utf-8 utf-8 in php, used no difference @ all. html code generated google.

any idea? in advance.

php regex

java - Activiti using receiveTask to pause and resume an activiti -



java - Activiti using receiveTask to pause and resume an activiti -

i new activiti framework. learning concepts via prototypes. here prototype working : 1. have integrated activiti vaadin project 2.activiti version : 5.16.1

here process flow

my main vaadin java class starts process flow.the first service task modalwindow java class. @ point add together subwindow using ui.getcurrent().addwindow(modalwindow);

this window has textfield , submit button. @ point process wait user click on submit button.

what have tried far : 1. added receivetask between modalwindow , temptask. receive task signalled end in button.clicklistener of modalwindow class.

what happened : 1.once subwindow added main page, process continued till endevent, skipping on temtask. 2. when user clicked on submit, entire process started beginning!!

what required : on buttonclick how "unpause" process , go on onto temptask class.

could please guide me

you need using user task. user task initiated, process come in wait state until task explicitly completed using task.complete() api.

your vaadin application can automatically wait task assigned (look @ of task unit tests examples of how this) , enable submit button.

bpmn , activiti extremely powerful there many ways same thing.

let me know if need more help.

cheers, greg harley - bp3

java vaadin7 activiti

for loop - LUA nil value error after touch event -



for loop - LUA nil value error after touch event -

so question related question posted yesterday link!. i'm working on lift game , i'm trying move passenger based on y value of elevator(lift).

function movelift(event) i=1,passenger_amount j=1,4 if passengers[i].travelling == true if event.phase == "began" marky = event.target.y passengers[i].y = event.target.y elseif event.phase == "moved" local y = (event.y - event.ystart) + marky event.target.y = y passengers[i].y = event.target.y elseif event.phase == "ended" if (hascollided( event.target, hotspots[j] )) if (event.target.destination == hotspots[j].floor) if event.target.occupied == true display.remove(floortext) floortext = nil gameareagroup.remove(passengers[i]) passengers[i] = nil succesfullpassengers = succesfullpassengers + 1 if succesfullpassengers == passenger_amount gameisover = true createdialogue("congratulations! have completed level!") i=1,lift_amount,1 lifts[i]:removeeventlistener( "touch", movelift ) end end end end end end end end end end

when passenger enters elevator, set boolean called travelling true know passenger can moved.but when move lift right floor (random value between 1-4) receive error (attempt index field '?' (a nil value)) on line 96, is:

if passengers[i].travelling == true

so guess passenger isnt removed propperly, right?

for-loop lua drag-and-drop corona lua-table

javascript - HTML injection using Jquery? -



javascript - HTML injection using Jquery? -

i want insert label called "octosplit-label" right under current octosplit-label.

how do in javascript?

i had effort didn't work here

function addonecheckbox($label) { $('#issues-container .table-list').append($label); }

try modifying function this:

function addonecheckbox($label) { $('#octosplit-label').after($label); }

remember ids should unique, html contained within $label should not have same id (which octosplit-label) , there should no other labels on page same id.

javascript jquery html

html - Muting an embedded vimeo video -



html - Muting an embedded vimeo video -

on website building have vimeo video embedded. client needs maintain sound on video people find on vimeo. website sound plain annoying. need find way mute sound within code embed. have googled can't seem find legible. can see code below, have used autoplay command within link hoping similar thing mute sound.

<iframe src="http://player.vimeo.com/video/4415083? title=0&amp;byline=0&amp;portrait=0&amp;color=d01e2f&amp;autoplay=1" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>

thanks

you using setvolume api in vimeo.. player.api('setvolume', 0); this...

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="//f.vimeocdn.com/js/froogaloop2.min.js"></script> <iframe id="vimeo_player" src="http://player.vimeo.com/video/4415083? title=0&amp;byline=0&amp;portrait=0&amp;color=d01e2f&amp;autoplay=1" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> <script> var iframe = $('#vimeo_player')[0], player = $f(iframe), status = $('.status'); player.addevent('ready', function() { player.api('setvolume', 0); }); </script>

html vimeo vimeo-api mute vimeo-player

javascript - Angular $location change path works second time, not first time -



javascript - Angular $location change path works second time, not first time -

the code seems simple, read the docs $location, notice there's lot of complexity don't understand. setup follows:

// in app.js $routeprovider.when('/done' , {templateurl: 'partials/done.html', controller: 'donecontroller'}); // in controller $location injected, on button press... if (!$scope.errors.length) { $scope.model.save().then(function() { alert("did here?"); $location.path('/done'); }); }

i press button , see alert, no alter in view. press button sec time (saving info cloud sec time), see alert sec time , view change. ideas why? in advance.

i believe there must asynchronous in sequence. happens when using external libraries jquery.

the problem $watch -> $digest -> $apply cycle of angular not triggered external libraries events. alter has been made, not propagated angularjs.

using $scope.$apply() solve problem

if (!$scope.errors.length) { $scope.model.save().then(function() { alert("did here?"); $scope.$apply(function(){ $location.path('/done'); }); }); }

javascript angularjs

Understanding algorithm language syntax -



Understanding algorithm language syntax -

https://codility.com/media/train/3-prefixsums.pdf

i trying hand @ algorithms on codility. stuck @ 1 of notations used in algorithm in above link.

what p = [0] * (n + 1) mean? language this?

thanks r

other terms, such xrange, shows language python. generally, search web words see in code, may help know name of language.

in python, [0] list containing single zero, , [0] * (n + 1) list of (n + 1) zeroes, [0, 0, ..., 0].

algorithm

Linden Scripting Language Post to PHP -



Linden Scripting Language Post to PHP -

when send request linden scripting language script php llhttprequest don’t values in php:

example: ( lsl )

if(group_invite == "yes") { list agents = llparsestring2list(this_agent_name, [" "], []); string params = lldumplist2string([ "firstname=" + lllist2string(agents, 0), "lastname=" + lllist2string(agents, 1)], "&"); llhttprequest( "http://mysite/post-page.php", [http_method,"post"], params); }

i never firstname , lastname values.

to submit arguments in format in post request, request must have content-type header set application/x-www-form-urlencoded:

llhttprequest( "http://example.com/post-page.php", [http_method, "post", http_mimetype, "application/x-www-form-urlencoded"], params);

linden-scripting-language

Avoid consecutive "if let" declarations in Swift -



Avoid consecutive "if let" declarations in Swift -

in swift used if let declarations check if object not nil

if allow obj = optionalobj { }

but sometimes, have face consecutive if let declarations

if allow obj = optionalobj { if allow = obj.a { if allow b = a.b { // stuff } } }

i'm looking way avoid consecutive if let declarations.

i seek :

if allow obj = optionalobj && if allow = obj.a && if allow b = a.b { // stuff }

but swift compiler not allow this.

any suggestion ?

i wrote little essay on alternatives time ago: https://gist.github.com/pyrtsa/77978129090f6114e9fb

one approach not yet mentioned in other answers, kinda like, add together bunch of overloaded every functions:

func every<a, b>(a: a?, b: b?) -> (a, b)? { switch (a, b) { case allow (.some(a), .some(b)): homecoming .some((a, b)) default: homecoming .none } } func every<a, b, c>(a: a?, b: b?, c: c?) -> (a, b, c)? { switch (a, b, c) { case allow (.some(a), .some(b), .some(c)): homecoming .some((a, b, c)) default: homecoming .none } } // , on...

these can used in if let statements, case expressions, optional.map(...) chains:

// 1. var foo: foo? if allow (name, phone) = every(parsedname, parsedphone) { foo = ... } // 2. switch every(parsedname, parsedphone) { case allow (name, phone): foo = ... default: foo = nil } // 3. foo = every(parsedname, parsedphone).map{name, phone in ...}

having add together overloads every boilerplate'y has done in library once. similarly, applicative functor approach (i.e. using <^> , <*> operators), you'd need create curried functions somehow, causes bit of boilerplate somewhere too.

swift

How to make Rails Heroku Application Contents Searchable in google? -



How to make Rails Heroku Application Contents Searchable in google? -

i have heroku rails app blogs doesn't seem searchable google. eg. have article on site , when type article's tile in google included heroku , name of app in search did not retrieve link app's article.

check google's webmasters tool: https://www.google.com/webmasters/ html file google gives verify site must placed in /myappname/public folder.

ruby-on-rails heroku

javascript - How can I expand images on hover with canvas? -



javascript - How can I expand images on hover with canvas? -

i in illustration http://www.nytimes.com/newsgraphics/2013/09/13/fashion-week-editors-picks/ how images expand on hover. know how jquery know wouldn't fast , reliable. give seek d3js new it, thought start or other viable alternatives?

thanks

try this:

html:

<div style = "display:inline;" id = "imgbar"> </div>

css:

#imgbar{ //css here } #imgbar > img:hover{ width:200px; //just set width double it's default value height:200px; //same above; 200px dummy value }

then, can add together images div javascript.

good luck!

javascript css angularjs canvas d3.js

java - How can I update the available Android APIs in Eclipse (ADT) -



java - How can I update the available Android APIs in Eclipse (ADT) -

i trying update api level choices within eclipse. currently, highest can api 19:

-

i interested in starting 5.0 , making target api, cannot seem available option.

i have tried updating eclipse via help -> check updates, have seen nil new.

currently, using adt via eclipse (see image below)

-

i sure simple missing, can tell me can find update can start working things glass api, wearables, , lollipop? there section updating have not seen? all!

steps updating eclipse

1. download eclipse official site 2. download , install jdk latest version 3. after installing eclipse , go help > install new software. 4. click add, in top-right corner. 5. in add together repository dialog appears, come in "adt plugin" name , next url location: https://dl-ssl.google.com/android/eclipse/ 6. click ok. 7. in available software dialog, select checkbox next developer tools , click next. 8. in next window, you'll see list of tools downloaded. click next. 9.read , take license agreements, click finish. 10. if security warning saying authenticity or validity of software can't established, click ok. 11. when installation completes, restart eclipse.

after restarting eclipse , goto android sdk manager .

now see android versions , tools

java android eclipse api adt

python - Possible Race Condition in Serial read/write Code -



python - Possible Race Condition in Serial read/write Code -

i writing python code reads , writes serial device. device arduino mega running marlin 3d printer firmware.

my python code sending series of gcode commands (ascii strings terminated newlines, including checksums , line numbers). marlin responds each received line "ok\n". marlin has limited line buffer size if total marlin hold off on sending "ok\n" response until space freed up.

if checksum fails marlin requests line sent 1 time again "resend: 143\n" response. possible response "ok t:{temp value}\n" if current temperature requested.

my code uses 3 threads. main thread, read thread , write thread. here stripped downwards version of code:

class printer: def connect(self): self.s = serial.serial(self.port, self.baudrate, timeout=3) self.ok_received.set() def _start_print_thread(self): self.print_thread = thread(target=self._empty_buffer, name='print') self.print_thread.setdaemon(true) self.print_thread.start() def _start_read_thread(self): self.read_thread = thread(target=self._continous_read, name='read') self.read_thread.setdaemon(true) self.read_thread.start() def _empty_buffer(self): while not self.stop_printing: if self.current_line_idx < len(self.buffer): while not self.ok_received.is_set() , not self.stop_printing: logger.debug('waiting on ok_received') self.ok_received.wait(2) line = self._next_line() self.s.write(line) self.current_line_idx += 1 self.ok_received.clear() else: break def _continous_read(self): while not self.stop_reading: if self.s not none: line = self.s.readline() if line == 'ok\n': self.ok_received.set() go on # if got ok need nil else. if 'resend:' in line: # illustration line: "resend: 143" self.current_line_idx = int(line.split()[1]) - 1 if line: # if received _anything_ set flag self.ok_received.set() else: # if no printer attached, wait 10ms check again. sleep(0.01)

in above code, self.ok_received threading.event. mostly works ok. 1 time every couple of hours gets stuck in while not self.ok_received.is_set() , not self.stop_printing: loop within of _empty_buffer(). kills print locking machine.

when stuck within loop, can print go on sending command manually. allows read thread set ok_recieved flag.

since marlin not respond checksums, guess possible "ok\n" gets garbled. 3rd if statement in read thread supposed handle setting flag if anything received marlin.

so question is: have possible race status somewhere? before add together locks on place or combine 2 threads 1 understand how failing. advice appreciated.

it looks read thread info in window write thread has broken out of is_set loop, has not yet called self.ok_received.clear(). so, read thread ends calling self.ok_received.set() while write thread still processing previous line, , write thread unknowingly calls clear() 1 time done processing previous message, , never knows line should written.

def _empty_buffer(self): while not self.stop_printing: if self.current_line_idx < len(self.buffer): while not self.ok_received.is_set() , not self.stop_printing: logger.debug('waiting on ok_received') self.ok_received.wait(2) # start of race window line = self._next_line() self.s.write(line) self.current_line_idx += 1 # end of race window self.ok_received.clear() else: break

a queue might way handle - want write 1 line in write thread every time read thread receives line. if replaced self.ok_received.set() self.recv_queue.put("line"), write thread write 1 line every time pulls queue:

def _empty_buffer(self): while not self.stop_printing: if self.current_line_idx < len(self.buffer): while not self.stop_printing: logger.debug('waiting on ok_received') try: val = self.recv_queue.get(timeout=2) except queue.empty: pass else: break line = self._next_line() self.s.write(line) self.current_line_idx += 1 else: break

you shrink window point won't nail in practice moving phone call self.ok_received.clear() after exiting inner while loop, technically there still race.

python multithreading serial-port python-multithreading

.eot font is not working in IE8 -



.eot font is not working in IE8 -

@font-face { font-family:"helveticaneueltstd-th"; src: url("includes/helveticaneueltstd-th.eot") format("truetype"); } @font-face { font-family:"helveticaneueltstd-thex"; src: url("includes/helveticaneueltstd-thex.eot") format("truetype"); } @font-face { font-family: 'helveticaneueltstd-bdcn'; src: url('includes/helveticaneueltstd-bdcn.eot') format('embedded-opentype'); font-weight: normal; font-style: normal; }

this css adding font in .eot format still not working on ie8. checked http://www.queness.com/post/14873/19-most-useful-font-face-generators-for-converting-fonts-to-web-safe-fonts on link.there lots of code generators not single working . plzz help

fonts

java - Parsing .txt file line by line -



java - Parsing .txt file line by line -

i trying parse .txt file. need @ file line line , access info enclosed ''. here have tried far:

public static void main(string[] args) { string[] test; string word; scanner inputstream = null; seek { inputstream = new scanner(new fileinputstream("stuff.txt")); } catch(filenotfoundexception e) { system.out.println("output.txt not found, or not opened"); } while(inputstream.hasnextline()) { word = inputstream.nextline(); test = word.split("['']"); for(int = 0; < test.length; i++) { system.out.println(test[i]); } } }

and here format of input file:

type = 'home' title = 'please work' start = '2000, september, 10, 10, 10' end = '2010, october, 20, 20, 20' comment = 'please word '

i need access type, title, comment, , individual values in start , end

that file looks property file, can consider utilize format of file.

also, should splut using '=' instead brackets.

java file parsing file-io

Atomically increment an integer in a document in Azure DocumentDB -



Atomically increment an integer in a document in Azure DocumentDB -

how can atomically increment integer in document in azure documentdb?

the increment operation must atomic in presence of concurrent writers. no lost increments allowed (they possible in naive read-modify-write algorithm).

from documentation:

how documentdb provide concurrency?

documentdb supports optimistic concurrency command (occ) through http entity tags or etags. every documentdb resource has etag, , documentdb clients include latest read version in write requests. if etag current, alter committed. if value has been changed externally, server rejects write "http 412 precondition failure" response code. clients must read latest version of resource , retry request.

one can utilize property implement cas loop:

while (true) { var existingdoc = readdoc(); existingdoc.int++; seek { writedoc(existingdoc); break; } grab { //concurrency violation continue; } }

also note transactions in azure documentdb run on snapshot of info (snapshot isolation).

btw: if bit more automated (auto increment when modifies document) can utilize trigger , separated collection current value of integer. triggers executed in same transaction consistent , automated.

azure azure-documentdb

c# - Append to a json file in windows application -



c# - Append to a json file in windows application -

i have created json format file in windows application using newtonsoft.the code working , json creating fine.but want append new file old json file,now replacing.here code

list<devicedata> tempdate = new list<devicedata>(); devicedata d = new devicedata(); d.deviceid = st_id.tostring(); d.ansid = answerstr; tempdate.add(d); string ans = jsonconvert.serializeobject(tempdate, formatting.indented); system.io.file.writealltext(@"e:\" + " device.json", ans);

can 1 help.thanks in advance.

according documentation, method writealltext creates new file, writes specified string file, , closes file. if target file exists, overwritten.

to accomplish want need check whether file exists or not

string ans = jsonconvert.serializeobject(tempdate, formatting.indented); if (file.exists(@"e:\" + " device.json") file.appendalltext(@"e:\" + " device.json", appendtext); else system.io.file.writealltext(@"e:\" + " device.json", ans);

c# json json.net

c++ - Getting the type of a variable in a template -



c++ - Getting the type of a variable in a template -

this spawned trying extract type unique_ptr, turned out easy. however, interested in general case.

here's looking for:

template<class childobj> void mychildfunc() { // stuff childobj type }; template<class objtype> void myfunc(objtype obj) { mychildfunc<type of objtype::child????>(); }; struct myintstruct { int child; }; struct mydoublestruct { double child; }; void main(void) { myintstruct int_struct; mydoublestruct double_struct; myfunc(int_struct); myfunc(double_struct); }

so want way of calling mychildfunc using type of attribute object passed in myfunc. know can create template function, , pass obj.child allow deduction, hoping way deduce type manually, , utilize in template argument directly.

as said, more academic real, why code contrived, interested know if there way it.

how's this:

template<class childobj> void mychildfunc() { // stuff childobj type }; template<class objtype> void myfunc(objtype obj) { mychildfunc<decltype(objtype::child) >(); }; struct myintstruct { int child; }; struct mydoublestruct { double child; }; int main(int argc, const char * argv[]) { myintstruct int_struct; mydoublestruct double_struct; myfunc(int_struct); myfunc(double_struct); homecoming 0; }

i compiled xcode 6 , seems work desired.

c++ templates

node.js - Error: Cannot find module 'bonescript' in Cloud9 -



node.js - Error: Cannot find module 'bonescript' in Cloud9 -

i got error in cloud9 error: cannot find module 'bonescript' when next code excuted node.js

enter code here var b = require('bonescript'); b.pinmode('usr0', b.output); b.pinmode('usr1', b.output); b.pinmode('usr2', b.output); b.pinmode('usr3', b.output); b.digitalwrite('usr0', b.high); b.digitalwrite('usr1', b.high); b.digitalwrite('usr2', b.high); b.digitalwrite('usr3', b.high); settimeout(restore, 2000);

this code can executed command line: node blinkled.js in debian linus on beagelbone black without problem. can run on beaglebone.org web demo.

does know how solve issue?

i had searched , seek online solution 6 hours, not successful. thought might cloud9 config issue. contact cloud 9 back upwards no solution.

update: need utilize cloud9 on beaglebone black 192.168.7.2:3000 cloud9 on https://ide.c9.io cannot find right bonescript library

node.js

dojo - How to populdate the dijit.form.ComboBox by calling the URL which will returns JSON data? -



dojo - How to populdate the dijit.form.ComboBox by calling the URL which will returns JSON data? -

i have combox box component in dojo datagrid like

var tacstore = {items:[]}; tac

and have button when clicked button trying populate combo box using below code.

function loadtimezones() { dojo.xhrget({ //url: "/aaorpcadapterservicesweb/rpcadapter/httprpc/timezoneservice/gettimezones", url: "/aaorpcadapterservicesweb/rpcadapter/httprpc/deliverableservice/getalltacs", handleas:"json", load: createtimezonestore, error: function(error,ioargs){ console.log(error); } }); homecoming false; } function createtimezonestore(response) { console.log("createtimezonestore::response:: "+response); if ( response.result != null) { var timezone = []; for(var resultcounter=0; resultcounter<response.result.length;resultcounter++) { timezone[resultcounter] = {}; timezone[resultcounter]['name']=response.result[resultcounter]; console.log("createtimezonestore::response.result[resultcounter]:: "+response.result[resultcounter]); } console.log("createtimezonestore::tacstore::tacs: "+tacstore); tacstore= new dojo.data.itemfilewritestore({data:{items:timezone}}); } homecoming false; }

am getting response. values not showing in combobox. , when click on combo box getting error this.fetch not function

first, using itemfilewritestore, old dojo/data/api api. combo box uses newer dojo/store/api api (specifically, can utilize dojo/store/memory implementation).

var mystore = new memory({data: timezone});

also, creating store, not connecting combobox. if programatically creating combobox, use

var mycombobox = new combobox({store: mystore}); mycombobox.placeat(/* wherever */); mycombobox.startup();

if combobox created (either programatically, or using markup data-dojo-id), use

mycombobox.set('store', mystore); /* may need startup combobox after - not sure */ mycombobox.startup();

combobox dojo dojox.grid.datagrid

python web server error handling -



python web server error handling -

this python webserver code. doesn't work error message wish. so, please, help me right generate error message.

import sys import http.server http.server import( simplehttprequesthandler) srvr=http.server.httpserver hnd=simplehttprequesthandler protocol='http/1.0' try: if sys.argv[1:]: port=int(sys.argv[1]) else: port=8000 srvradrs=('localhost',port) hnd.protocol_version=protocol h=srvr(srvradrs,hnd) except ioerror: self.send_error(404,'file not found please check 1 time again , come in right flie name!!!!!!!!!: %s' %self.path) print("it's worked , welcome web server!") h.serve_forever()

you utilize "self" in self.send_error, you're not within method (member function) of class c.q. object.

python-3.x error-handling webserver

excel - How do I use a combo box to display information based on the user's selection? -



excel - How do I use a combo box to display information based on the user's selection? -

i have combo box few different selections:

selection 1 selection 2 selection 3

now know 1 time create selection homecoming number in whichever cell specify:

1 2 3

now let's have =sumifs function in next format:

=sumifs(data!$g:$g,data!$a:$a,account!$b$6,data!$b:$b,">=" & c5,data!$b:$b, "<=" & d5)

now have separate sheet "database" or raw info i'm using populate these cells data. if @

data!$g:$g (which column i'm summing)

is there way either way sum specific column based on combo box selection in =sumifs formula?

assuming combo box take column letter in a1:

=sumifs(indirect("data!" & $a$1 & ":" & $a$1),data!$a:$a,account!$b$6,data!$b:$b,">=" & c5,data!$b:$b, "<=" & d5)

this is, of course, assuming combo box lets select letter. if selections else , want letter hidden user, perhaps create hidden cell somewhere has nested if statement resulting in column letter tied each selection, have formula above reference cell.

excel excel-formula excel-2007 excel-2010

exception - (Weblogic) WSSERVLET11: failed to parse runtime descriptor: java.lang.NullPointerException -



exception - (Weblogic) WSSERVLET11: failed to parse runtime descriptor: java.lang.NullPointerException -

i error when deploy in weblogic.how solve problem ?

exception : deployment failed. message was: weblogic.management.deploymentexception: com.sun.xml.ws.transport.http.servlet.wsservletexception: wsservlet11: failed parse runtime descriptor: java.lang.nullpointerexception module has not been deployed. see server log details. @ org.netbeans.modules.j2ee.deployment.devmodules.api.deployment.deploy(deployment.java:210) @ org.netbeans.modules.maven.j2ee.executionchecker.performdeploy(executionchecker.java:178) @ org.netbeans.modules.maven.j2ee.executionchecker.executionresult(executionchecker.java:130) @ org.netbeans.modules.maven.execute.mavencommandlineexecutor.run(mavencommandlineexecutor.java:212) @ org.netbeans.core.execution.runclassthread.run(runclassthread.java:153)

weblogic.xml

<?xml version="1.0" encoding="utf-8"?> <weblogic-web-app xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/1.0/weblogic-web-app.xsd"> <jsp-descriptor> <keepgenerated>true</keepgenerated> <debug>true</debug> </jsp-descriptor> <context-root>/testproject</context-root> </weblogic-web-app>

sun-jaxws.xml

<?xml version="1.0" encoding="utf-8"?> <endpoints version="2.0" xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"> <endpoint name="eftgidenservices" implementation="com.yaz.yazproject.eft.services.eftgidenservices" url-pattern="/eftgidenservices"/> <endpoint name="ehacizservices" implementation="com.yaz.yazproject.ehaciz.services.ehacizservices" url-pattern="/ehacizservices"/> <endpoint name="cekservice" implementation="com.yaz.yazproject.cek.services.cekservice" url-pattern="/cekservice"/> </endpoints>

web.xml

<?xml version="1.0" encoding="utf-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <listener> <listener-class>com.sun.xml.ws.transport.http.servlet.wsservletcontextlistener</listener-class> </listener> <servlet> <servlet-name>eftgidenservices</servlet-name> <servlet-class>com.sun.xml.ws.transport.http.servlet.wsservlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>ehacizservices</servlet-name> <servlet-class>com.sun.xml.ws.transport.http.servlet.wsservlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>cekservice</servlet-name> <servlet-class>com.sun.xml.ws.transport.http.servlet.wsservlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>eftgidenservices</servlet-name> <url-pattern>/eftgidenservices</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ehacizservices</servlet-name> <url-pattern>/ehacizservices</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>cekservice</servlet-name> <url-pattern>/cekservice</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> </web-app>

exception weblogic

ruby on rails - Adding Facebook Pages Search Directory to Website -



ruby on rails - Adding Facebook Pages Search Directory to Website -

are there methods of adding existing facebook pages directory website?

directory can found here: https://www.facebook.com/directory/pages/

i using facebook api in rails app , have way solve problem. however, requires requesting access facebook , getting approved take bit of time , adding search might improve alternative implementation anyway.

the way implement facebook page search on website search api: https://developers.facebook.com/docs/graph-api/using-graph-api/v2.2#search

you not need approved that, need app access token. see next links access tokens:

https://developers.facebook.com/docs/facebook-login/access-tokens/ http://www.devils-heaven.com/facebook-access-tokens/

ruby-on-rails facebook facebook-graph-api

mercurial - How can I make `hg status` to show only the files that `hg diff` show -



mercurial - How can I make `hg status` to show only the files that `hg diff` show -

there more number of files gets printed out hg status because shows files changes, including permissions. hg diff on other hand, ignores permissions. if want have workflow permission on source tree ignored, kind of configuration need?

i haven't seen evidence inquire possible. question duplicate of this one 2011, suggests obvious work-around: add together commit hook normalize permissions of files, don't alter when don't expect them to. whether that's useful depends on why need prepare in first place.

mercurial

python - Does a file opened with os.system() have to be closed before the program continues? -



python - Does a file opened with os.system() have to be closed before the program continues? -

i writing text based game in python requires uses lexicon. need able leave text file open while rest of programme running. there way this, or opened file have closed before programme can continue. here before question describes why need opened file: open text file window using python

based on other question, using os.system not open file specifically, open external editor display/edit file.

os.system "synchronous" call, in case means python code after os.system wont run until edit programme exits.

if want code run while editor running - need find way :

look @ parts of subprocess module allow run external editor in way not synchronous (this called asynchronous) - utilize subprocess.popen find different way display/edit text not require external editor

python

javascript - Testing errors with angularjs/Intern/BDD -



javascript - Testing errors with angularjs/Intern/BDD -

i have error handling module logging. here angular js module:

angular.module('error_handling', []) .service('default_logger', function () { // default logging this.logging_mode = 'debug'; function invalidinputexception(message) { this.name = 'invalidinputexception'; this.message = message; } invalidinputexception.prototype = new error(); invalidinputexception.prototype.constructor = invalidinputexception; this.set_logging_mode = function(mode){ if (mode !== 'log' && mode !== 'debug' && mode !== 'info' && mode !== 'warn' && mode !== 'error' && mode !== 'all' && mode !== 'off'){ throw new invalidinputexception('invalid logging mode.'); } this.logging_mode = mode.tolowercase(); }; this.log = function (msg) { check_mode('log', this.logging_mode) && console.trace(msg); }; this.debug = function (msg) { check_mode('debug', this.logging_mode) && console.debug(msg); }; this.info = function (msg) { check_mode('info', this.logging_mode) && console.info(msg); }; this.warn = function (msg) { check_mode('warn', this.logging_mode) && console.warn(msg); }; this.error = function (msg) { check_mode('error', this.logging_mode) && console.error(msg); }; function check_mode(action, logging_mode){ if (logging_mode === 'debug' || logging_mode === 'all'){ homecoming true; } else if(logging_mode === action){ homecoming true; } else if(logging_mode === 'off'){ homecoming false; } else{ homecoming false; } }; }) .factory('delegated_default_logger', ['default_logger', function(default_logger) { homecoming function($delegate) { //todo: utilize $delegate variable? (which should equal angular's default $log service) homecoming angular.extend({}, default_logger); }; }]) .config(function($provide) { $provide.decorator('$exceptionhandler', ['$log', '$delegate', function($log, $delegate) { homecoming function(exception, cause) { $log.debug('default exception handler.'); $delegate(exception, cause); }; } ]); });

and here test file:

define([ 'intern!bdd', 'intern/chai!expect', //'intern/order!node_modules/intern/chai', // 'intern/order!node_modules/chai/lib/chai', // 'intern/order!node_modules/sinon/lib/sinon', // 'intern/order!node_modules/sinon-chai/lib/sinon-chai', 'intern/order!vendor/src/sinonjs-built/lib/sinon', 'intern/order!vendor/src/sinonjs-built/lib/sinon/spy', 'intern/order!vendor/src/sinonjs-built/lib/sinon/call', 'intern/order!vendor/src/sinonjs-built/lib/sinon/behavior', 'intern/order!vendor/src/sinonjs-built/lib/sinon/stub', 'intern/order!vendor/src/sinonjs-built/lib/sinon/mock', 'intern/order!vendor/src/sinonjs-built/lib/sinon/collection', 'intern/order!vendor/src/sinonjs-built/lib/sinon/assert', 'intern/order!vendor/src/sinonjs-built/lib/sinon/sandbox', 'intern/order!vendor/src/sinonjs-built/lib/sinon/test', 'intern/order!vendor/src/sinonjs-built/lib/sinon/test_case', 'intern/order!vendor/src/sinonjs-built/lib/sinon/match', 'intern/order!vendor/src/angular/angular', 'intern/order!vendor/src/angular-mocks/angular-mocks', 'intern/order!src/common/modules/error_handling/error_handling', 'intern/order!src/app' ], function (bdd, expect) { // (bdd) { describe('error handler module', function () { var test, scope, ctrl, error_handler, log; function inject (fn) { homecoming function() { angular.injector(['ng', 'ngmock', 'ngnomi']).invoke(fn); } } beforeeach(inject(function($log){ log = $log; })); it('should object', function(){ expect(log).to.be.an('object'); }); it('should default debug logging mode', function() { expect(log.logging_mode).to.equal('debug'); }); it('should phone call console.debug string test , default logging mode', function(){ var spy = sinon.spy(console, 'debug'); log.debug('test'); expect(console.debug.calledonce).to.be.true; expect(console.debug.calledwith('test')).to.be.true; console.debug.restore(); }); it('should able set logging mode', function(){ log.set_logging_mode('off'); expect(log.logging_mode).to.equal('off'); }); it('should throw error on invalid logging mode', function(){ expect(log.set_logging_mode('bad_mode')).to.throw(invalidinputexception); }); }); } });

all tests pass except lastly one, gives me output:

>> 1/9 tests failed warning: fail: main - error handler module - should throw error on invalid logging mode (0ms) invalidinputexception: invalid logging mode. @ </users/evanvandegriff/documents/work/nomi_v2/nomi_v2/web/src/common/modules/error_handling/error_handling.js:16> @ </users/evanvandegriff/documents/work/nomi_v2/nomi_v2/web/src/common/modules/error_handling/error_handling.test.js:67> @ <__intern/lib/test.js:169> @ <__intern/lib/suite.js:237> @ <__intern/node_modules/dojo/deferred.js:37> @ <__intern/node_modules/dojo/deferred.js:258> @ runtest <__intern/lib/suite.js:241> @ <__intern/lib/suite.js:249> 1/5 tests failed 1/9 tests failed 1/9 tests failed utilize --force continue.

it's acting encountering error, fine, not getting caught test (i.e. passing). why happening? also, structuring error_handling module in way makes sense? should putting error classes in file in spot, or somewhere else?

when you're checking whether exception thrown, need pass expect function call, like:

expect(function () { log.set_logging_mode('bad_mode') }).to.throw(invalidinputexception);

when pass function call, log.set_logging_mode('bad_mode'), parameter expect, phone call evaluated (and exception thrown) before expect called.

javascript angularjs intern

amazon web services - Is it possible to create an EC2 instance from a Launch Configuration via command line interface or API? -



amazon web services - Is it possible to create an EC2 instance from a Launch Configuration via command line interface or API? -

amazon aws allows create launch configurations used auto scaling groups. how can spin-up individual instance instance based on launch configuration?

if looking using template create instance, utilize aws cloudformation. cloudformation, create template , utilize cloudformation cli or api launch it. here a sample template launch instance.

if want reuse launch configuration, can still utilize aws cloudformation create template autoscaling group, this. launch configuration defined in cloudformation template.

amazon-web-services amazon-ec2 autoscaling

latex - built in PDF is not updated after quick build -



latex - built in PDF is not updated after quick build -

i using texmaker 4.2 on mac osx10.9.3. built in pdf view not update after press quick build button. need press view pdf button see update. ideas in advance

i found error in compilation prevent generating pdf automatically, why need press on view pdf self show pdf, fixed error, , found pdv updated automatically quick build.

latex texmaker

java - dynamically change the length of String inside the EditText field in Android -



java - dynamically change the length of String inside the EditText field in Android -

i using edittext field in application.

edittext entering ddns input:

e.g www.example.com/xxxx

i want restrict length of ddns id 30 characters after "/" character.

i.e after "/" character, follows must of maximum 30 characters

i want dynamically , restrict user not type more 30 characters.

how can it.

you can seek below way restrict user come in less 30 character.

tf.addactionlistener(new actionlistener() { @override public void actionperformed(actionevent arg0) { //processing part } });

java android regex android-edittext

c++ - Is it possible to return an 'accurate' object from a polymorphic container of pointers? -



c++ - Is it possible to return an 'accurate' object from a polymorphic container of pointers? -

i found out whenever want polymorphism, need pointers or references, because storing derived instance in base variable 'slices' off isn't defined in 'base'.

(i suppose that's because derived , base instances don't occupy same space in memory. correct?)

so when want container holds kinds of objects, derived subclasses of base, need container of pointers , not container of actual objects.

and if want function gets object container , returns 'as is' (not sliced), can this:

base* get_pointer(int index) { homecoming container[index]; }

but want following:

base get_object(int index) { homecoming *container[index]; }

i.e.: homecoming real object, not pointer. possible? or should manage pointers when want kind of polymorphism?

i know whenever want polymorphism, need pointers or references [...] correct?

that absolutely correct. however, not limited "plain" pointers built language. smart pointers, such std::unique_ptr<t> , std::shared_ptr<t> nowadays improve alternative lets preserve polymorphic behavior.

[i want to] homecoming real object, not pointer. possible?

you can that, slicing back. base returned value, result stripped of derived functionality. happens when pass or homecoming value (passing , returning 2 sides of same thing, basic mechanism in play same in both cases).

if homecoming base& reference, however, same syntax in caller, , objects not sliced:

base& get_object(int index) { homecoming *container[index]; }

the grab item in container must remain in place while code holding reference it.

c++ pointers polymorphism

sql - Would it be better to rewrite this query using EXISTS instead of IN? How would I do that? -



sql - Would it be better to rewrite this query using EXISTS instead of IN? How would I do that? -

i have following, , i've read it's improve avoid "in" , utilize "exists" instead (1, 2). though i've read exists faster , more consistent, don't think i've grasped exclusively why is, or how go rewriting utilize exists instead.

select qryaccountnamesconcat.accountid, qryaccountnamesconcat.accountname, qryaccountnamesconcat.jobtitle qryaccountnamesconcat (((qryaccountnamesconcat.accountid) in ( select accountid tblaccount accounttypeid in (1, 2)) or qryaccountnamesconcat.accountid in ( select childaccountid qryaccjunctiondetails parentaccounttypeid in (1, 2)) ));

basically, accounttypeid = 1 or 2 trade or private client account, looking accounts are, or children of (usually employees of) client accounts.

i not know if exists improve in ms access (although exists performs improve in in other databases). however, write as:

select anc.accountid, anc.accountname, anc.jobtitle qryaccountnamesconcat anc exists (select 1 tblaccount a.accounttypeid in (1, 2) , anc.accountid = a.accountid ) or exists (select 1 qryaccjunctiondetails jd jd.parentaccounttypeid in (1, 2) , jd.childaccountid = anc.accountid );

for best performance, want index on tblaccount(accountid, accounttypeid) , qryaccjunctiondetails(childaccountid, parentaccounttypeid).

sql ms-access

html - How to set innerText in JavaScript for Chrome? -



html - How to set innerText in JavaScript for Chrome? -

i trying set innertext between element's start , end tag in chrome, far not working. why that? have tried these:

element.balancetext = "changed."; element.innertext = "changed."; element.innerhtml = "changed."; element.textcontent = "changed."; element.value = "changed."; $(element).val("changed.");

here fiddle: http://jsfiddle.net/la1tadpd/

your jsfiddle configured utilize coffee script not plain javascript, , because of this, you're getting error:

uncaught syntaxerror: reserved word "var"

due input tag beingness invalid html, suggest removing additional text node browser creates, replace input element div containing text want:

class="snippet-code-js lang-js prettyprint-override">var element = document.getelementbyid('test'); element.nextsibling.parentnode.removechild(element.nextsibling); var div = document.createelement('div'); div.textcontent = 'changed.'; element.parentnode.replacechild(div, element); class="snippet-code-html lang-html prettyprint-override"><input id='test'>hello</input>

javascript html google-chrome text innertext

math - Normalize a vector differently than normal -



math - Normalize a vector differently than normal -

i have vector represents alter between 1 vector , another. vectors diagonal each other. example, if first vector (1, 0) , sec was(3, 2), alter (2, 2), should normalized (1, 1). "normal" normalizing dividing both x , y vector's length results in 2.83 illustration vector not need. how can accomplish "normalization"?

divide both components of vector greatest mutual divisor.

math greatest-common-divisor

javascript - Uncaught ReferenceError in jquery code compiled from coffeescript -



javascript - Uncaught ReferenceError in jquery code compiled from coffeescript -

i have next jquery code (compiled coffee script).

(function() { $(function() { homecoming $.get('/proteins', function(proteins) {}); }); $.each(proteins, function(index, protein) { homecoming $('#proteins').append($("<li>").text(protein.name)); }); }).call(this);

the coffeescript generated code looks this:

$ -> $.get '/proteins', (proteins) -> $.each proteins, (index, protein) -> $('#proteins').append $("<li>").text protein.name

i maintain getting "uncaught referenceerror: proteins not defined" @ line 6 of generated code.

am missing (very basic) here?

thanks!!

there tab indenting $.each , spaces elsewhere. indentation not correct. utilize editor coffeescript support.

javascript jquery coffeescript referenceerror

php - absolute url paths for localhost to file sytem -



php - absolute url paths for localhost to file sytem -

i'm trying utilize absolute path set href of . path doesn't work, if alter relative path works fine.

works:

include_once('../../utils/utils/html/banner.html');

doesn't work:

include_once('http://localhost/apps/myvyn/utils/utils/html/banner.html'); include_once('/apps/myvyn/utils/utils/html/banner.html');

what doing wrong?

if want more of "absolute" path, can prepend include path $_server['document_root']. thought.

include_once($_server['document_root'] . '/apps/myvyn/utils/utils/html/banner.html');

php

ruby on rails - RSpec tests hanging just on new machine OSX -



ruby on rails - RSpec tests hanging just on new machine OSX -

i got newer mbp , after installing brew, rvm, mysql, bundler, etc. , getting gemset set up, test database created, tried run spec suite using parallel_tests: rake parallel:spec[4]

it starts chugging along hangs. waits 60s or more before gets uncorked , chugs along set of greenish dots (~130), , repeat. in fact delay after each pause seems longer. when hangs spinner in terminal tab goes away , comes when wakes up.

the same test suite running in parallel on old mbp doesn't periodically hang.

i have no thought start diagnose hung, in environment different between 2 machines.

running spec tests in serial seems hang between each assertion (dot) well.

i appreciate tips.

other env details: ruby 2.0.0p451, redis 2.8.13, rails 3.2.19, mysql 5.6.20

tl;dr - net:http (via css_parser, via premailer, via premailer_rails) taking 60s fail locating css referenced in email template on 'bad' machine.

details: narrowed downwards delay on 'bad' machine phone call in css_parser's read_remote_file css http://my-machine-mb:3001/stylesheets/email.css. reason, net::http taking total 60s fail find. on 'good' machine, fails within 5s. news realized unit tests inlining css email when doesn't need to. still need figure out why request takes 60s fail on 'bad' machine.

ruby-on-rails ruby rspec

angularjs - ng-model not working with typeahead -



angularjs - ng-model not working with typeahead -

i using angular's typeahead, , running problem ngmodel.

here typeahead html

<input type= "text" ng-model= "symbol" placeholder= "begin typing" typeahead= "hit.message nail in gettypeaheadcontents($viewvalue)" typeahead-loading= "loadingsymbols" typeahead-editable= "false" typeahead-on-select= "onselect($item, $model, $label)" typeahead-min-length= 2 typeahead-wait-ms= 500 class= "form-control" /> <input ng-click= "search()" value= "search!"/>

here code in controller (quite basic time being)

$scope.search = function(){ alert($scope.symbol); }

now, autocomplete code works expected, when click search button, alert message "undefined"

what's weirder tried setting

$scope.symbol = "";

at origin of controller, , when click search button without typing typeahead, empty string alerted me, expected. however, when type typeahead , 1 time again nail search, "undefined" 1 time again. clearly, angular's typeahead not playing nicely ng-model, i'm not sure here.

advice?

don't know if still issue you. i've tried latest release of angularstrap (2.1.4) , got working when set ng-model object on set property.

$scope.selectedpart = {} <input type="text" class="form-control" ng-model="selectedpart.part_id" data-animation="am-flip-x" ng-options="part.value part.name part in parts" placeholder="selecteer onderdeel" bs-typeahead>

somewhere in function (could deep $watch)

console.log($scope.selectedpart.part_id)

angularjs angularjs-scope undefined typeahead angular-ngmodel

python - Variables not updated from within baseHTTPserver class -



python - Variables not updated from within baseHTTPserver class -

i trying build simple web server, receives gps coordinates through post requests , shows them on webpage. receive fine coordinates phone, prints them server window understand variables 'lat' , 'lon' should have been updated actual coordinates, when open browser "test test".. sorry noob question, new python , cannot understand why class myhandler can't access variables.. code far:

port = 5050 lat="test" lon="test" speed="test" def serv_responseget(s): s.send_response(200) s.send_header("content-type", "text/html") s.end_headers() s.wfile.write(lat, lon) def serv_responsepost(s): s.send_response(200) s.send_header("content-type", "text/html") s.end_headers() s.wfile.write(' '); class myhandler(basehttpserver.basehttprequesthandler): def do_post(s): print s.path length = int(s.headers['content-length']) post_data = urlparse.parse_qs(s.rfile.read(length).decode('utf-8')) key, value in post_data.iteritems(): if key=="lat": lat=''.join(value) if key=="lon": lon=''.join(value) if key=="speed": speed=''.join(value) print datetime.datetime.now() print "lat=", lat print "lon=", lon print "spd=", speed serv_responsepost(s) def do_get(s): print s.path serv_responseget(s) if __name__ == '__main__': server_class = basehttpserver.httpserver httpd = server_class(('', port), myhandler) print time.asctime(), "server starts - %s:%s" % ('', port) httpd.serve_forever()

and on python window after post phone:

/ 2014-10-25 16:23:20.598733 lat= 37.971649 lon= 23.727053 spd= 0.0 192.168.2.50 - - [25/oct/2014 16:23:20] "post / http/1.1" 200 -

in python, when assign variable within procedure, assumes meant create local variable , ignores global variables. assign global variables, need declare them first. add together line

global lat, lon, speed

to start of do_post , believe prepare it.

python variables basehttpserver

rust - Cannot move out of dereference of `&`-pointer -



rust - Cannot move out of dereference of `&`-pointer -

i have next code

pub struct propertydeclarationblock { pub declarations: arc<vec<(propertydeclaration, propertydeclarationimportance)>> } impl propertydeclarationblock { pub fn select_declarations(&self) -> arc<vec<propertydeclaration>> { arc::new(self.declarations.clone().map_in_place(|p| { allow (declaration, _) = p; declaration })) } }

i want able phone call .select_declarations() on propertydeclarationblock , have homecoming clone of declarations instead of beingness arc vec (propertydeclaration, propertydeclarationimportance) arc vec propertydeclaration, in other words returning a vector of propertydeclaration instead of previous tuple.

the previous won't compile getting next error:

error: cannot move out of dereference of `&`-pointer arc::new(self.declarations.clone().map_in_place(|p| { ^~~~~~~~~~~~~~~~~~~~~~~~~

from understand, since function take self parameter take ownership of it. since i'd rather have function burrow self utilize &.

edit

here error message after implementing new function:

error: cannot move out of dereference of `&`-pointer arc::new(self.declarations.iter().map(|&(declaration, _)| declaration).collect()) ^~~~~~~~~~~~~~~~~ note: attempting move value here (to prevent move, utilize `ref declaration` or `ref mut declaration` capture value reference) arc::new(self.declarations.iter().map(|&(declaration, _)| declaration).collect()) ^~~~~~~~~~~

i tried applying ref keyword before declaration suggested error message didn't help.

self.declarations.clone() clones arc, while believe intended clone vec. resolve phone call map_in_place, compiler automatically dereferences arc able phone call method, defined on vec. compiler knows how dereference arc because arc implements deref. deref returns borrowed pointer, , error comes from. clone vec, must explicitly dereference arc: (*self.declarations).clone().

however, map_in_place not suitable in case, (propertydeclaration, propertydeclarationimportance) doesn't have same size propertydeclaration (unless propertydeclarationimportance has size of zero, not case), required per docs. fails message similar this:

task '<main>' failed @ 'assertion failed: mem::size_of::<t>() == mem::size_of::<u>()', /build/rust-git/src/rust/src/libcollections/vec.rs:1805

here's proper implementation:

impl propertydeclarationblock { pub fn select_declarations(&self) -> arc<vec<propertydeclaration>> { arc::new(self.declarations.iter().map(|&(declaration, _)| declaration).collect()) } }

here, utilize iter on vec create iterator on vector's items. returns items, implements iterator on immutable references.

then, utilize map lazily map (propertydeclaration, propertydeclarationimportance) propertydeclaration. note how destructure tuple and reference in closure's parameter list (this works in fns too) instead of using let statement.

finally, utilize collect create new collection container sequence. collect's result generic; can type implements fromiterator. vec implements fromiterator, , compiler infers vec method's signature.

rust

vba - Regex - match between 1st and last occurrence of double square brackets -



vba - Regex - match between 1st and last occurrence of double square brackets -

i'm looking match text , non text values, located within " " , between 1st , lastly instance of [[ , ]]

window.google.ac.h(["text",[["text1",0],["text2",0,[3]],["text3",0],["text4",0,[3]],["text5",0],["text6",0],["text7",0 ]],{"q":"hygjgjhbjh","k":1}])

so far i've managed results (far ideal) using: "(.*?)",0 issue have either matches way until

"text4",0,[3]]

or starts matching @

["text",

i need match text1 text2 text3 .. text7

notes: double square bracket position , nr of instances, between 1st , lastly not consistent.

thanks help guys!

edit: i'm using http://regexr.com/ test it

well, didn't language, using .net regex (which largely follows perl standard), first match groups of matches of global match using next regex contain values want:

(?<=\[\[.*)"(.+?)"(?=.*\]\])

a global match on "(.+?)" lone homecoming matches first match groups contain characters between quotes. lookbehind assertion (?<=\[\[.*) tells include cases there [[ anywhere behind, i.e. after first instance of [[. similarly, lookahead assertion (?=.*\]\]) tells include cases there ]] anywhere ahead, i.e. before lastly instance of ]].

i tested using powershell. exact syntax global match , extract first match groups of results depend on language.

regex vba excel-vba

.net - PDF Convert to Black And White PNGs -



.net - PDF Convert to Black And White PNGs -

i'm trying compress pdfs using itextsharp. there lot of pages color images stored jpegs (dctdecode)...so i'm converting them black , white pngs , replacing them in document (the png much smaller jpg black , white format)

i have next methods:

private static bool trycompresspdfimages(pdfreader reader) { seek { int n = reader.xrefsize; (int = 0; < n; i++) { pdfobject obj = reader.getpdfobject(i); if (obj == null || !obj.isstream()) { continue; } var dict = (pdfdictionary)pdfreader.getpdfobject(obj); var subtype = (pdfname)pdfreader.getpdfobject(dict.get(pdfname.subtype)); if (!pdfname.image.equals(subtype)) { continue; } var stream = (prstream)obj; seek { var image = new pdfimageobject(stream); image img = image.getdrawingimage(); if (img == null) continue; using (img) { int width = img.width; int height = img.height; using (var msimg = new memorystream()) using (var bw = img.toblackandwhite()) { bw.save(msimg, imageformat.png); msimg.position = 0; stream.setdata(msimg.toarray(), false, pdfstream.no_compression); stream.put(pdfname.type, pdfname.xobject); stream.put(pdfname.subtype, pdfname.image); stream.put(pdfname.filter, pdfname.flatedecode); stream.put(pdfname.width, new pdfnumber(width)); stream.put(pdfname.height, new pdfnumber(height)); stream.put(pdfname.bitspercomponent, new pdfnumber(8)); stream.put(pdfname.colorspace, pdfname.devicergb); stream.put(pdfname.length, new pdfnumber(msimg.length)); } } } grab (exception ex) { trace.traceerror(ex.tostring()); } { // may or may not help reader.removeunusedobjects(); } } homecoming true; } grab (exception ex) { trace.traceerror(ex.tostring()); homecoming false; } } public static image toblackandwhite(this image image) { image = new bitmap(image); using (graphics gr = graphics.fromimage(image)) { var graymatrix = new[] { new[] {0.299f, 0.299f, 0.299f, 0, 0}, new[] {0.587f, 0.587f, 0.587f, 0, 0}, new[] {0.114f, 0.114f, 0.114f, 0, 0}, new [] {0f, 0, 0, 1, 0}, new [] {0f, 0, 0, 0, 1} }; var ia = new imageattributes(); ia.setcolormatrix(new colormatrix(graymatrix)); ia.setthreshold((float)0.8); // alter threshold needed var rc = new rectangle(0, 0, image.width, image.height); gr.drawimage(image, rc, 0, 0, image.width, image.height, graphicsunit.pixel, ia); } homecoming image; }

i've tried varieties of colorspaces , bitspercomponents, "insufficient info image", "out of memory", or "an error exists on page" upon trying open resulting pdf...so must doing wrong. i'm pretty sure flatedecode right thing use.

any assistance much appreciated.

the question:

you have pdf colored jpg. instance: image.pdf

if within pdf, you'll see filter of image stream /dctdecode , color space /devicergb.

now want replace image in pdf, result looks this: image_replaced.pdf

in pdf, filter /flatedecode , color space alter /devicegray.

in conversion process, want user png format.

the example:

i have made illustration makes conversion: replaceimage

i explain illustration step step:

step 1: finding image

in example, know there's 1 image, i'm retrieving prstream image dictionary , image bytes in quick , dirty way.

pdfreader reader = new pdfreader(src); pdfdictionary page = reader.getpagen(1); pdfdictionary resources = page.getasdict(pdfname.resources); pdfdictionary xobjects = resources.getasdict(pdfname.xobject); pdfname imgref = xobjects.getkeys().iterator().next(); prstream stream = (prstream) xobjects.getasstream(imgref);

i go /xobject dictionary /resources listed in page dictionary of page 1. take first xobject encounter, assuming imagem , image prstream object.

your code improve mine, part of code isn't relevant question , works in context of example, let's ignore fact won't work other pdfs. care steps 2 , 3.

step 2: converting colored jpg black , white png

let's write method takes pdfimageobject , converts image object changed grayness colors , stored png:

public static image makeblackandwhitepng(pdfimageobject image) throws ioexception, documentexception { bufferedimage bi = image.getbufferedimage(); bufferedimage newbi = new bufferedimage(bi.getwidth(), bi.getheight(), bufferedimage.type_ushort_gray); newbi.getgraphics().drawimage(bi, 0, 0, null); bytearrayoutputstream baos = new bytearrayoutputstream(); imageio.write(newbi, "png", baos); homecoming image.getinstance(baos.tobytearray()); }

we convert original image black , white image using standard bufferedimage manipulations: draw original image bi new image newbi of type type_ushort_gray.

once done, want image bytes in png format. done using standard imageio functionaltiy: write bufferedimage byte array telling imageio want "png".

we can utilize resulting bytes create image object.

image img = makeblackandwhitepng(new pdfimageobject(stream));

now have itext image object, please note image bytes stored in image object no longer in png format. mentioned in comments, png not supported in pdf. itext alter image bytes format supported in pdf (for more details see section 4.2.6.2 of the abc of pdf).

step 3: replacing original image stream new image stream

we have image object, need replace original image stream new 1 , need adapt image dictionary /dctdecode alter /flatedecode, /devicergb alter /devicegray, , value of /length different.

you creating image stream , dictionary manually. that's brave. leave job itext's pdfimage object:

pdfimage image = new pdfimage(makeblackandwhitepng(new pdfimageobject(stream)), "", null);

pdfimage extends pdfstream, , can replace original stream new stream:

public static void replacestream(prstream orig, pdfstream stream) throws ioexception { orig.clear(); bytearrayoutputstream baos = new bytearrayoutputstream(); stream.writecontent(baos); orig.setdata(baos.tobytearray(), false); (pdfname name : stream.getkeys()) { orig.put(name, stream.get(name)); } }

the order in things here important. don't want setdata() method tamper length , filter.

step 4: persisting document after replacing stream

i guess it's not hard figure part out:

replacestream(stream, image); pdfstamper stamper = new pdfstamper(reader, new fileoutputstream(dest)); stamper.close(); reader.close();

problem:

i not c# developer. know pdf inside-out , know java.

if problem caused in step 2, you'll have post question asking how convert colored jpeg image black , white png image. if problem caused in step 3 (for instance because using /devicergb instead of /devicegray), reply solve problem.

.net pdf itextsharp system.drawing