Thursday, 15 May 2014

python - matplotlib: subplot background (axes face + labels) colour [or, figure/axes coordinate systems] -



python - matplotlib: subplot background (axes face + labels) colour [or, figure/axes coordinate systems] -

i have figure containing 3x2 subplots, , set background colour on middle pair of subplots create clearer axis labels belong subplot.

setting facecolor when constructing subplot changes colour of area defined axes; tick , axis labels still drawn on figure.patch. assuming there no simple way this, add together rectangular patch behind relevant instances in figure.axes.

after bit of experimenting around, appears figure.axes[x].get_position() returns axes coördinates (normalised coördinates [0.0-1.0]), yet rectangle() appears want display coördinates (pixels). code more or less works (ed: interactively, when outputting png (using agg renderer), positioning of rectangle off):

import matplotlib.pyplot plt import matplotlib f = plt.figure() plt.subplot( 121 ) plt.title( 'model' ) plt.plot( range(5), range(5) ) plt.xlabel( 'x axis' ) plt.ylabel( 'left graph' ) plt.subplot( 122 ) plt.title( 'residuals' ) plt.plot( range(5), range(5) ) plt.xlabel( 'x axis' ) plt.ylabel( 'right graph' ) plt.tight_layout(pad=4) bb = f.axes[0].get_position().transformed( f.transfigure ).get_points() bb_pad = (bb[1] - bb[0])*[.20, .10] bb_offs = bb_pad * [-.25, -.20] r = matplotlib.patches.rectangle( bb[0]-bb_pad+bb_offs, *(bb[1] - bb[0] + 2*bb_pad), zorder=-10, facecolor='0.85', edgecolor='none' ) f.patches.extend( [r] )

but seems hackish, , feels i've missed out on important. can explain what, whether there simpler/better way it, , if so, is?

since need write file, presently don't have solution.

just utilize transform kwarg rectangle, , can utilize coordinate scheme you'd like.

as simple example:

import matplotlib.pyplot plt matplotlib.patches import rectangle fig, axes = plt.subplots(3, 2) rect = rectangle((0.08, 0.35), 0.85, 0.28, facecolor='yellow', edgecolor='none', transform=fig.transfigure, zorder=-1) fig.patches.append(rect) plt.show()

however, if wanted things more robustly, , calculate extent of axes, might this:

import matplotlib.pyplot plt matplotlib.transforms import bbox matplotlib.patches import rectangle def full_extent(ax, pad=0.0): """get total extent of axes, including axes labels, tick labels, , titles.""" # text objects, need draw figure first, otherwise extents # undefined. ax.figure.canvas.draw() items = ax.get_xticklabels() + ax.get_yticklabels() # items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label] items += [ax, ax.title] bbox = bbox.union([item.get_window_extent() item in items]) homecoming bbox.expanded(1.0 + pad, 1.0 + pad) fig, axes = plt.subplots(3,2) extent = bbox.union([full_extent(ax) ax in axes[1,:]]) # it's best transform figure coordinates. otherwise, won't # behave correctly when size of plot changed. extent = extent.transformed(fig.transfigure.inverted()) # can create rectangle in figure coords using "transform" kwarg. rect = rectangle([extent.xmin, extent.ymin], extent.width, extent.height, facecolor='yellow', edgecolor='none', zorder=-1, transform=fig.transfigure) fig.patches.append(rect) plt.show()

python matplotlib

Inserting numeric data type using SQL statement in Java -



Inserting numeric data type using SQL statement in Java -

i writing method allows users store info within database.

the problem have storing numeric datatype in database, user's id.

firstly, how can tell if id number auto-incrementing? these it's properties:

type: numeric column size: 4 decimal digits: 0 part of primary key: true part of index: true position: 1

i'm sure read somewhere that, setting part of index (true) allows auto-incrementation. can confirm?

more importantly, when inserting info table receive error stating:

columns of type 'numeric' cannot hold values of type 'char'.

this snippet of insert code (i can reveal more if need be):

statement pstatement = conn.createstatement(); string selectsql = ("insert app.person values ('" + '3' + "','" + user + "','" + pass + "','" + fname + "','" + sname + "','" + squestion + "','" + sanswer + "') "); pstatement.executeupdate(selectsql);

as can see setting id (the first value), 3 manually. believe throwing error , know how insert numeric value, using insert command.

i coding in java, using netbeans 7.3 beta 2, on mac os x mount lion. using derby database.

hey bro suggest u utilize preparestatement

string template = "insert app.person values (your,table,collumn,name) values (?,?,?,?)"; preparedstatement stmt = yourconnection.preparestatement(template);

so if want set id integer, allow java with

stmt.setint(1, id); stmt.setstring(2, user); stmt.setstring(3, fname); stmt.executeupdate();

i dont know how table construction illustration if want utilize int utilize stmt.setint(1, 3);

1--> position u set in string template

3--> maybe u want hard coded id

here illustration pattern utilize preparestatement

string name = "shadrach" double cost = "100.00" int qty = 3; string template = "insert product (name,price,qty) values (?,?,?)"; preparedstatement stmt = connection.preparestatement(template); stmt.setstring(1, name); stmt.setdouble(2, price); stmt.setint(3, qty); stmt.executeupdate();

java sql numeric javadb

ios - Animating UITextInput's textInputView -



ios - Animating UITextInput's textInputView -

uikit text input components, such uitextview , uitextfield have property inputview add together custom keyboard. there 2 questions have relating this.

if keyboard visible , property set new input view, nil happens. resigning , regaining first responder status refreshes input , displays new view. best way it? if might reply bigger question:

is possible animate transition between 2 input views?

from uiresponder docs:

responder objects require custom view gather input user should redeclare property readwrite , utilize manage custom input view. when receiver subsequently becomes first responder, responder infrastructure presents specified input view automatically. similarly, when view resigns first responder status, responder infrastructure automatically dismisses specified view.

so unfortunately reply 1 yes , 2 no.

ios objective-c uitextfield uitextview uitextinput

Vb.Net get radio 1s nowplaying from json file in windows form -



Vb.Net get radio 1s nowplaying from json file in windows form -

now making radio programme , ive come across http://www.bbc.co.uk/radio1/developers/api/ have thought how implement in program. it's using .json file. know how using php shows loads stuff don't need nor know how use. , don't want host php page because hosting have slow times , constant pinging create slower. there way in program. grabbing .json bbc page. , json things "artist":, "image": , "title": give thanks in advance. oh im still in secondary school im not pro in vb.net

try using json.net (http://james.newtonking.com/projects/json-net.aspx) parse info .net classes , utilize resulting objects in vb application.

vb.net json winforms radio

html - How can I swap in and out text inside a DIV using only javascript? -



html - How can I swap in and out text inside a DIV using only javascript? -

i have text within div this:

<div> @*<p class="header">xxx</p> <p> yyy </p> <p> yyy </p>*@ <p class="header">xxx</p> <p> yyy </p> <p> yyy </p> </div>

i commented out first 3 paragraphs , replaced them sec three. there way create every 10 seconds changes between showing first 3 paragraphs , sec three. note don't utilize jquery on page. want find solution not utilize jquery.

without jquery:

put 2 groups of

in 2 div id.

document.getelementbyid('iddiv1').style.display = "none"; --> create invisibile div1 document.getelementbyid('iddiv2').style.display = "block"; --> create visibile div2

for create in automatic mode, have utilize timer function of javascript, here. link of w3school.

javascript html css

python 3.x - Modifying logging message format based on message logging level in Python3 -



python 3.x - Modifying logging message format based on message logging level in Python3 -

i asked question python 2 here, bumped issue 1 time again when the reply no longer worked python 3.2.3.

here's code works on python 2.7.3:

import logging # effort set python3 logger print custom messages # based on each message's logging level. # technique recommended python2 not appear work # python3 class customconsoleformatter(logging.formatter): """ modify way debug messages displayed. """ def __init__(self, fmt="%(levelno)d: %(msg)s"): logging.formatter.__init__(self, fmt=fmt) def format(self, record): # remember original format format_orig = self._fmt if record.levelno == logging.debug: self._fmt = "debug: %(msg)s" # phone call original formatter grunt work result = logging.formatter.format(self, record) # restore original format self._fmt = format_orig homecoming result # set logger my_logger = logging.getlogger("my_custom_logger") my_logger.setlevel(logging.debug) my_formatter = customconsoleformatter() console_handler = logging.streamhandler() console_handler.setformatter(my_formatter) my_logger.addhandler(console_handler) my_logger.debug("this debug-level message") my_logger.info("this info-level message")

a run using python 2.7.3:

tcsh-16: python demo_python_2.7.3.py debug: debug-level message 20: info-level message

as far can tell, conversion python3 requires slight mod customconsoleformatter.init():

def __init__(self): super().__init__(fmt="%(levelno)d: %(msg)s", datefmt=none, style='%')

on python 3.2.3:

tcsh-26: python3 demo_python_3.2.3.py 10: debug-level message 20: info-level message

can see, want replace '10' 'debug' beingness thwarted.

i've tried digging around in python3 source , looks percentstyle instantiation clobbering self._fmt after i, well, clobber myself.

my logging chops stop short of beingness able work around wrinkle.

can recommend way or perhaps point out i'm overlooking?

with bit of digging, able modify python 2 solution work python 3. in python2, necessary temporarily overwrite formatter._fmt. in python3, back upwards multiple format string types requires temporarily overwrite formatter._style._fmt instead.

# custom formatter class myformatter(logging.formatter): err_fmt = "error: %(msg)s" dbg_fmt = "dbg: %(module)s: %(lineno)d: %(msg)s" info_fmt = "%(msg)s" def __init__(self): super().__init__(fmt="%(levelno)d: %(msg)s", datefmt=none, style='%') def format(self, record): # save original format configured user # when logger formatter instantiated format_orig = self._style._fmt # replace original format 1 customized logging level if record.levelno == logging.debug: self._style._fmt = myformatter.dbg_fmt elif record.levelno == logging.info: self._style._fmt = myformatter.info_fmt elif record.levelno == logging.error: self._style._fmt = myformatter.err_fmt # phone call original formatter class grunt work result = logging.formatter.format(self, record) # restore original format configured user self._style._fmt = format_orig homecoming result

and here halloleo's illustration of how utilize above in script (from python2 version of question):

fmt = myformatter() hdlr = logging.streamhandler(sys.stdout) hdlr.setformatter(fmt) logging.root.addhandler(hdlr) logging.root.setlevel(debug)

logging python-3.x

javascript - Iterate through Array of Objects using Dustjs -



javascript - Iterate through Array of Objects using Dustjs -

after jsonp phone call returned:

[ { "text": "yo whats up?", "id": 1 }, { "text": "hey man!", "id": 2 }, { "text": "dude.", "id": 3 } ]

heres actual api call: http://api.twitter.com/1/statuses/user_timeline/codinghorror.json

using dust.js like:

<ul> {#myposts} <li>{text}, {id}{~n}</li> {:else} <p>humm...</p> {/myposts} </ul>

but there no key "myposts" in response. that's problem. checkout api phone call see how json beingness returned, mabye i'm interpreting wrong.

what syntax utilize in dust.js iterate through each object in array?

you can utilize "current context" shortcut.

{#.} {text} - {id}<br /> {/.}

javascript json dust.js

Redirect output from Python logger to tkinter widget -



Redirect output from Python logger to tkinter widget -

having spent time on redirecting stdout , logging output tkinter text widget, i've decided need help. code follows:

#!/usr/bin/env python tkinter import * import logging threading import thread class iodirector(object): def __init__(self,text_area): self.text_area = text_area class stdoutdirector(iodirector): def write(self,str): self.text_area.insert(end,str) def flush(self): pass class app(frame): def __init__(self, master): self.master = master frame.__init__(self,master,relief=sunken,bd=2) self.start() def start(self): self.master.title("test") self.submit = button(self.master, text='run', command=self.do_run, fg="red") self.submit.grid(row=1, column=2) self.text_area = text(self.master,height=2.5,width=30,bg='light cyan') self.text_area.grid(row=1,column=1) def do_run(self): t = thread(target=print_stuff) sys.stdout = stdoutdirector(self.text_area) t.start() def print_stuff(): logger = logging.getlogger('print_stuff') logger.info('this not show') print 'this show' print_some_other_stuff() def print_some_other_stuff(): logger = logging.getlogger('print_some_other_stuff') logger.info('this not show') print 'this show' def main(): logger = logging.getlogger('main') root = tk() app = app(root) root.mainloop() if __name__=='__main__': main()

i know 1 can define new logging handler based on text widget can't working. function "print_stuff" wrapper around many different functions having own logger set up. need help defining new logging handler "global" can instantiated each of functions having own logger. help much appreciated.

just create sure understand correctly:

you want print logging messages both stdout , tkinter text widget logging won't print in standard console.

if indeed problem here's how it.

first let's create simple console in tkinter, text widget i'm including completeness:

class logdisplay(tk.labelframe): """a simple 'console' place @ bottom of tkinter window """ def __init__(self, root, **options): tk.labelframe.__init__(self, root, **options); "console text space" self.console = tk.text(self, height=10) self.console.pack(fill=tk.both)

now let's override logging handlers redirect console in parameter , still automatically print stdout:

class loggingtogui(logging.handler): """ used redirect logging output widget passed in parameters """ def __init__(self, console): logging.handler.__init__(self) self.console = console #any text widget, can utilize class above or not def emit(self, message): # overwrites default handler's emit method formattedmessage = self.format(message) #you can alter format here # disabling states no user can write in self.console.configure(state=tk.normal) self.console.insert(tk.end, formattedmessage) #inserting logger message in widget self.console.configure(state=tk.disabled) self.console.see(tk.end) print(message) #you can print stdout in overriden emit no need black magic

hope helps.

python tkinter

php - Silex redirects adding port 80 to location -



php - Silex redirects adding port 80 to location -

i have app using silex security firewall. when load app @ https://app.com/web , i'm not authenticated redirected https://app.com:80/web/user/login_check

this produces ssl error trying create ssl connection on non-ssl port.

my firewall config looks this,

$app['security.firewalls'] = array( 'login' => array( 'pattern' => '^/user/login$', ), 'admin' => array( 'pattern' => '^.*$', 'form' => array('login_path' => '/user/login', 'check_path' => '/user/login_check'), 'logout' => array('logout_path' => '/user/logout'), 'users' => array( // raw password demo 'test' => array('role_admin', 'qldd7mo0ol7e2lijc1qdnxqjpkidhqlpjhum0rn/n6ajehqgzzfsyph94r/aefrm8aet9y6l$ ), ), );

i know can access https://app.com/web/index.php without port beingness added not web server, when redirected /user/login page.

i read symfony doesn't utilize port in url 1 defined in _server server_port, setting

$_server['https'] = 'on'; $_server['server_port'] = 443;

doesn't help me.

the initial request redirects returns in headers,

request url:https://app.com/web/ request method:get status code:302 found

location:https://app.com:80/web/user/login

does know how stop silex's redirection adding port 80 location?

edit: should have mentioned running on redhat's openshift cloud infrastructure.

in theory should able solve setting "trusted proxies" on request described here http://symfony.com/blog/security-release-symfony-2-0-19-and-2-1-4

i've had problem when using cloudflare, though, has hundreds of ips impractical list them "trusted" simplest way i've been able solve problem. set @ top of bootstrap file before autoloader:

// prepare ip cloudflare if (isset($_server['http_cf_connecting_ip'])) { $_server['http_x_forwarded_for'] = $_server['http_cf_connecting_ip']; $_server['http_client_ip'] = $_server['http_cf_connecting_ip']; $_server['remote_addr'] = $_server['http_cf_connecting_ip']; } // prepare ssl cloudflare if (isset($_server['http_cf_visitor'])) { if (preg_match('/https/i', $_server['http_cf_visitor'])) { $_server['https'] = 'on'; $_server['http_x_forwarded_port'] = 443; $_server['server_port'] = 443; } }

php symfony2 silex openshift

asp.net - Jquery UI Combobox and DropDownList -



asp.net - Jquery UI Combobox and DropDownList -

i'm having problems jquery jquery ui combobox & asp.net

the dropdown not working or render

javascript error "uncaught typeerror: cannot set property '_renderitem' of undefined" 'input.data("ui-autocomplete")._renderitem = function (ul, item)'

<script type="text/javascript"> (function ($) { $.widget("ui.combobox", { _create: function () { var input, = this, wasopen = false, select = this.element.hide(), selected = select.children(":selected"), value = selected.val() ? selected.text() : "", wrapper = this.wrapper = $("<span>") .addclass("ui-combobox") .insertafter(select); function removeifinvalid(element) { var value = $(element).val(), matcher = new regexp("^" + $.ui.autocomplete.escaperegex(value) + "$", "i"), valid = false; select.children("option").each(function () { if ($(this).text().match(matcher)) { this.selected = valid = true; homecoming false; } }); if (!valid) { // remove invalid value, didn't match $(element) .val("") .attr("title", value + " didn't match item") .tooltip("open"); select.val(""); settimeout(function () { input.tooltip("close").attr("title", ""); }, 2500); input.data("ui-autocomplete").term = ""; } } input = $("<input>") .appendto(wrapper) .val(value) .attr("title", "") .addclass("ui-state-default ui-combobox-input") .autocomplete({ delay: 0, minlength: 0, source: function (request, response) { var matcher = new regexp($.ui.autocomplete.escaperegex(request.term), "i"); response(select.children("option").map(function () { var text = $(this).text(); if (this.value && (!request.term || matcher.test(text))) homecoming { label: text.replace( new regexp( "(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escaperegex(request.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi" ), "<strong>$1</strong>"), value: text, option: }; })); }, select: function (event, ui) { ui.item.option.selected = true; that._trigger("selected", event, { item: ui.item.option }); }, change: function (event, ui) { if (!ui.item) { removeifinvalid(this); } } }) .addclass("ui-widget ui-widget-content ui-corner-left"); input.data("ui-autocomplete")._renderitem = function (ul, item) { homecoming $("<li>") .append("<a>" + item.label + "</a>") .appendto(ul); }; $("<a>") .attr("tabindex", -1) .attr("title", "show items") .tooltip() .appendto(wrapper) .button({ icons: { primary: "ui-icon-triangle-1-s" }, text: false }) .removeclass("ui-corner-all") .addclass("ui-corner-right ui-combobox-toggle") .mousedown(function () { wasopen = input.autocomplete("widget").is(":visible"); }) .click(function () { input.focus(); // close if visible if (wasopen) { return; } // pass empty string value search for, displaying results input.autocomplete("search", ""); }); input.tooltip({ tooltipclass: "ui-state-highlight" }); }, _destroy: function () { this.wrapper.remove(); this.element.show(); } }); })(jquery); $(function () { $("#ddl_company").combobox(); $("#toggle").click(function () { $("#ddl_company").toggle(); }); });

ui-autocomplete key available jqueryui 1.10, seek autocomplete instead

jquery asp.net jquery-ui combobox

html - Submenu Positioning -



html - Submenu Positioning -

(i have since updated code reflect working code. code below works now)

ive been working on trying position submenu. record, have done homework on lastly week trying create work think messing somewhere parent/child relationships.

what trying place menu in column on page, then, when hovering, have submenu appear right hand side. problem menu appears when resize page, submenu jumps on place. looks relative , absolute positions problems cant see where

here css code:

#col1 { background-color:#000033; width:15%; height:100%; float:left; color:#fff000; font-family: bold; font-size: 100%; } ul.nav li { position:relative; float:left; width:100%; } ul.nav { display: block; background-color:#b2b2d9; margin-right:3%; margin-bottom:1%; margin-left:1%; text-decoration:none; border-top-color:#ffffff; border-right-color:#e6e6e6; border-bottom-color:#ffffff; border-left-color:#e6e6e6; border-top-width: 3%; border-right-width: 3%; border-bottom-width: 3%; border-left-width: 3%; border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; padding: 2%; } ul.nav { position:relative; list-style-type: none; padding-left:0px; line-height:1.5em; } ul.nav2 { display: block; background-color:#000033; border:solid 3px black; padding:5%; margin-right:0px; margin-bottom:0%; margin-left:0%; text-decoration:none; color:white; border-top-color:#ffffff; border-right-color:#e6e6e6; border-bottom-color:#ffffff; border-left-color:#e6e6e6; } ul.nav2 { position:absolute; top:0; left:100%; display:none; font-size:100%; list-style-type: none; width:8em; line-height:1.5em; float: none; clear: none; margin: 0px; } ul.nav2 li { display:block; margin-left:-2.8em; width:100%; line-height:1.3em; }

here html , javascript:

<script> $(document).ready(function () { $('.nav').hover(function (e) { $('.nav2').slidedown('normal'); }, function () { $('.nav2').slideup('normal'); }); }); </script> </head> <body> <div id="banner"> <img src="images/banner.jpg" width="100%" alt="banner" /> </div> <div id="wrapper"> <div id="col1"> <ul class="nav"> <li><a href="http://www.ahome.com">home</a></li> <li><a href="http://www.ab.com">about</a></li> <ul class="nav2"> <li><a href="http://www.albio.com">bio</a></li> <li><a href="http://www.acred.com">credentials</a></li> <li><a href="http://www.aled.com">education</a></li> </ul> <li><a href="http://www.anew.com">new listings</a></li> <li><a href="http://www.afeat.com">featured home</a></li> <li><a href="http://www.atow.com">town facts</a></li> <li><a href="http://www.acme.com">contact me</a></li> </ul> </div> <div id="main"> "lorem ipsum dolor sit down amet, consectetur adipisicing elit, sed eiusmod tempor incididunt </div> </div> </body> </html>

as can see, menu problem. can me pointed in right direction?

you might need way. if able alter html , tweak css little, can accomplish this.

html <ul class="nav"> <li> <a href="#">menu 1</a> <ul> <li><a href="#">sub menu item</a></li> <li><a href="#">sub menu item</a></li> <li><a href="#">sub menu item</a></li> </ul> </li> <li> <a href="#">menu 2</a> <ul> <li><a href="#">sub menu item</a></li> <li><a href="#">sub menu item</a></li> <li><a href="#">sub menu item</a></li> </ul> </li> <li> <a href="#">menu 3</a> <ul> <li><a href="#">sub menu item</a></li> <li><a href="#">sub menu item</a></li> <li><a href="#">sub menu item</a></li> </ul> </li> </ul> css * {font-family: "segoe ui", tahoma;} ul.nav {border-bottom: 1px solid #999;} ul.nav li {display: block; text-decoration: none; color: #333; padding: 5px; border: 1px solid #fff;} ul.nav > li:hover {border: 1px solid #666; border-bottom: 1px solid #fff;} ul.nav li a:hover {background: #ccc; border: 1px solid #999;} ul.nav > li {display: inline-block; position: relative; border: 1px solid #fff;} ul.nav > li ul {display: none; position: absolute; left: -1px; width: 150px; border: 1px solid #666; border-top-color: #fff; margin-top: 1px;} ul.nav > li:hover ul {display: block;} ul.nav > li ul li {display: block;} /* vertical menu */ ul.nav > li ul li {display: inline-block;} /* horizontal menu */ fiddle: http://jsfiddle.net/vmuxa/ (vertical menu) http://jsfiddle.net/vmuxa/1/ (horizontal menu)

html css submenu

php - Regex for [title](http://) links -



php - Regex for [title](http://) links -

i'm trying parse links using php construction such [google](http://google.com), , far i've got this:

"/\[(.+?)\]((.+?\))/is"

the part can't work part parenthesis ')'.

any help great!

[edit]

@jari - part of code:

$find = array( "@\n@", "/[**](.+?)[**]/is", "/\[(.+?)\]\((.+?)\)/is" ); $replace = array( "<br />", "<strong>$1</strong>", "<a href\"$1\" target=\"_blank\" rel=\"no follow\"></a>" ); $body = htmlspecialchars($body); $body = preg_replace($find, $replace, $body); homecoming $body;

the parenthesis special character , marks sub-patterns within expression, need escape them (just did square brackets, btw):

"/\[(.+?)\]\((.+?)\)/is"

php regex hyperlink

c# - Programatically close TabItem in WPF -



c# - Programatically close TabItem in WPF -

how hell programmatically close tabitem in windows 8 wpf desktop tabcontrol?

there no options in intellisense, , things appear in search results custom implementations of either tabcontrol or tabitem.

why can't tabcontrol.selecteditem.close();?

i think closing same removing tabitem tabcontrol

edit: ex:

tabcontrol1.items.removeat(tabcontrol1.selectedindex);

c# .net xaml

d3.js - How do I post parameter on d3.json? -



d3.js - How do I post parameter on d3.json? -

i'm using d3.json dynamic data.

d3.json("/myweb/totalqtyservice.do", function(json) { drawchart(json); });

how post parameter on d3.json? i.e.

data : { year: "2012", customer: "type1“ }

any thought pass parameter on post? not url parameter /myweb/totalqtyservice.do?year=2012&customer=type1

i tried such below, couldn't create work. because info construction different

d3.json => [object, object, object, object]

$.ajax => {entity_name: "activa"entity_tar_val: 350entity_val: 400level: 1_proto_: object},...

$.ajax({ type: "post", url: url, // parameter here info : {year: "2012", customer: "type1“}, success: function(json){ // console.log(json); **drawchart(json);** } , error:function (request, err, ex) { } });

note: reply applies older version of d3.json, see joshuataylor's comment below.

d3.json convenience method wrapping d3.xhr; it's hardwired create requests.

if want post can utilize d3.xhr directly.

something this:

d3.xhr(url) .header("content-type", "application/json") .post( json.stringify({year: "2012", customer: "type1"}), function(err, rawdata){ var info = json.parse(rawdata); console.log("got response", data); } );

because no callback specified in creation of request object it's not sent immediately. 1 time received json response can parsed in standard javascript way i.e. json.parse(data) documentation d3.xhr here.

d3.js

hover - Using jQuery to highlight a div, whilst greying out others -



hover - Using jQuery to highlight a div, whilst greying out others -

i'm half way there issue have become stuck. believe similar issues have been raised in past nil quite i'm looking for.

i have demo code on jsfiddle can viewed here: http://jsfiddle.net/wolfhook/jb36d/

html

<div id="thumbscontainer"> <div class="imageholder"> image in here... </div> <div class="imageholder"> image in here... </div> <div class="imageholder"> image in here... </div>

css

#thumbscontainer { background:#000; padding:20px; overflow:auto;} .imageholder { background:#eee; float:left; margin:5px; width:50px; height:50px; padding:5px; border:1px solid #666;}

jquery

$('#thumbscontainer').children('.imageholder').hover(function() { $(this).siblings().stop().animate({'opacity':'0.5'}); }, function() { $(this).siblings().stop().animate({'opacity':'1'}); });

the desired effect have divs display per normal, 1 time hover on div, other surrounding ones gray out or have sort of overlay added them. purpose give impression div have mouse pointer on highlighted.

you can see code have on jsfiddle achieves applies opacity each div rather sort of overlay , it's causing me problems, on current project divs sit down above background image rather total black background opacity isn't going work , makes whole thing confusing.

ideally apply div overlay on unhighlighted divs , can style using css give greyed out effect. @ stage i'm open suggestions on how accomplish desired effect.

anyone kind plenty chip in , provide me pointers?

much appreciated.

instead of applying opacity imageholder div, or introducing new overlay element, why not apply opacity contents (e.g. thumbnail image) of div? background color of imageholder show through, providing grayness of "grayed out" effect.

new:

$('#thumbscontainer').children('.imageholder').hover(function() { $(this).siblings().children('img').stop().animate({'opacity':'0.5'}); }, function() { $(this).siblings().children('img').stop().animate({'opacity':'1'}); });

sample updating yours thumbnails within imageholders , background image behind all: http://jsfiddle.net/jb36d/11/

jquery hover overlay mouseover highlight

c# - How to let user decide which service to request in WCF? -



c# - How to let user decide which service to request in WCF? -

in wcf how allow user decide service request when inquire 2 values , have ability perform different calculations values.

for illustration inquire value1 , value 2. , user have selection perform addition, subtraction , multiplication values.

how can accomplish that?

[operationcontract] int gettwovalues(int value1, int value2); public int addition(int value1, int value2){ homecoming value1+value2; } public int subtraction(int value1, int value2){ homecoming value1-value2; }

how logic

if user.request="addition"{ add-on } else if user.request="subtraction"{ subtraction }

i know not code have written trying have understanding of saying. help appreciated.

not quite sure understand question

[operationcontract] public int subtraction(int value1, int value2) { homecoming value1 - value2; } [operationcontract] public int addition(int value1, int value2) { homecoming value1 + value2; }

would work like

[operationcontract] public int calculation(int value1, int value2, string calctype) { switch (calctype) { case "addition": homecoming value1 + value2; case "subtraction": homecoming value1 - value2; } //return default or throw exception }

not either without drawbacks of course, both meet criteria.

edit: comment raises obvious point switch case allows user perchance supply value doesn't map.

yes , wouldn't utilize strings, example!

possible ways round it?

validate user input - allow them know when provide isn't valid use default throw exception use enum forcefulness user select pre defined list similarly utilize first method

i think perhaps need explain more in question want achieve.

c# .net windows wcf communication

Choosing an appropriate Zend Framework exception class -



Choosing an appropriate Zend Framework exception class -

using zend framework, want throw exception within particular method in model class if there arguments passed considered illegal method. in java, example, this:

public void addname(string name) { if (name.equals('')) { throw new illegalargumentexception(); } // other code if ok. }

however, far can see, php , zend framework lack such basic built-in exception classes illegalargumentexception. should utilize pass exception describes went wrong? create such exception class myself? isn't kind of code framework supposed eliminate?

i'm starting learning zend framework. haven't wrote lot of php in life please sense free explain me things think should obvious decent php programmer.

here list of available exceptions in php spl exception class.

exception logicexception badfunctioncallexception badmethodcallexception domainexception invalidargumentexception lengthexception outofrangeexception runtimeexception outofboundsexception overflowexception rangeexception underflowexception unexpectedvalueexception

zend framework's zend_exception wrapper php's built in exceptions, of major components have callable exception class.

for example:

public function setid($id) { $validator = new my_validator_id(); if ($validator->isvalid($id)) { $this->id = $id; homecoming $this; } else { throw new zend_validate_exception("$id not valid value id field."); } }

or php's built in excepition:

public function __get($name) { $property = strtolower($name); if (!property_exists($this, $property)) { throw new \invalidargumentexception( "getting property '$property' not valid entity"); } //truncated... }

zend framework 2 has more specific exceptions available.

zend-framework

iphone - Pinterest integration in ios app? -



iphone - Pinterest integration in ios app? -

i trying post image app on pinterest.from lastly 5 days looking perfect solution after posting question on inch away solve problem.the issue when post image using url successfuly post image on pinterest below code show.

-(nsstring*) generatepinteresthtml { nsstring *description = @"post description here"; nsstring *surl = [nsstring stringwithformat:@"http://4.bp.blogspot.com/-w4otzjlpgwo/t5_pi-kjpui/aaaaaaaaaom/rkm3e0xcbgy/s1600/flower.png"]; nslog(@"url:%@", surl); nsstring *protectedurl = (__bridge nsstring *)cfurlcreatestringbyaddingpercentescapes(null,(__bridge cfstringref)surl, null, (cfstringref)@"!'\"();:@&=+$,/?%#[]% ",cfstringconvertnsstringencodingtoencoding(nsutf8stringencoding)); nslog(@"protected url:%@", protectedurl); nsstring *imageurl = [nsstring stringwithformat:@"\"%@\"", surl]; nsstring *buttonurl = [nsstring stringwithformat:@"\"http://pinterest.com/pin/create/button/?url=www.flor.com&media=%@&description=%@\"", protectedurl, description]; nsmutablestring *htmlstring = [[nsmutablestring alloc] initwithcapacity:1000]; [htmlstring appendformat:@"<html> <body>"]; [htmlstring appendformat:@"<p align=\"center\"><a href=%@ class=\"pin-it-button\" count-layout=\"horizontal\"><img border=\"0\" src=\"http://assets.pinterest.com/images/pinext.png\" title=\"pin it\" /></a></p>", buttonurl]; [htmlstring appendformat:@"<p align=\"center\"><img width=\"400px\" height = \"400px\" src=%@></img></p>", imageurl]; [htmlstring appendformat:@"<script type=\"text/javascript\" src=\"//assets.pinterest.com/js/pinit.js\"></script>"]; [htmlstring appendformat:@"</body> </html>"]; homecoming htmlstring; } -(void)viewdidload { [super viewdidload]; nsstring *htmlstring = [self generatepinteresthtml]; nslog(@"generated html string:%@", htmlstring); mywebview.backgroundcolor = [uicolor clearcolor]; mywebview.opaque = no; if ([mywebview ishidden]) { [mywebview sethidden:no]; } [mywebview loadhtmlstring:htmlstring baseurl:nil]; }

below screen shot show above code result

but when trying upload image app not works fine here code

- (void)viewdidload { nsarray *paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory,nsuserdomainmask, yes); nsstring *documentsdirectory = [paths objectatindex:0]; savedimagepath = [[documentsdirectory stringbyappendingpathcomponent:@"savedimage.png"] mutablecopy]; nslog(@"savedimagepath..%@",savedimagepath); nsdata* imagedata = uiimagepngrepresentation(mypimage); [imagedata writetofile:savedimagepath atomically:yes]; [super viewdidload]; nsstring *htmlstring = [self generatepinteresthtml]; nslog(@"generated html string:%@", htmlstring); mywebview.backgroundcolor = [uicolor clearcolor]; mywebview.opaque = no; if ([mywebview ishidden]) { [mywebview sethidden:no]; } [mywebview loadhtmlstring:htmlstring baseurl:nil]; } - (nsstring*) generatepinteresthtml { nsstring *description = @"post description here"; nsstring *stringurl = [nsstring stringwithformat:@"%@",savedimagepath]; nslog(@"stringurl:%@", stringurl); nsurl *urltoupload = [[nsurl alloc]initfileurlwithpath:stringurl]; nsstring* surl = [nsstring stringwithformat:@"%@",urltoupload]; nsstring *protectedurl = (__bridge nsstring *)cfurlcreatestringbyaddingpercentescapes(null,(__bridge cfstringref)surl, null, (cfstringref)@"!'\"();:@&=+$,/?%#[]% ",cfstringconvertnsstringencodingtoencoding(nsutf8stringencoding)); nslog(@"protected url:%@", protectedurl); nsstring *imageurl = [nsstring stringwithformat:@"\"%@\"", surl]; nsstring *buttonurl = [nsstring stringwithformat:@"\"http://pinterest.com/pin/create/button/?url=www.flor.com&media=%@&description=%@\"", protectedurl, description]; nsmutablestring *htmlstring = [[nsmutablestring alloc] initwithcapacity:1000]; [htmlstring appendformat:@"<html> <body>"]; [htmlstring appendformat:@"<p align=\"center\"><a href=%@ class=\"pin-it-button\" count-layout=\"horizontal\"><img border=\"0\" src=\"http://assets.pinterest.com/images/pinext.png\" title=\"pin it\" /></a></p>", buttonurl]; [htmlstring appendformat:@"<p align=\"center\"><img width=\"400px\" height = \"400px\" src=%@></img></p>", imageurl]; [htmlstring appendformat:@"<script type=\"text/javascript\" src=\"//assets.pinterest.com/js/pinit.js\"></script>"]; [htmlstring appendformat:@"</body> </html>"]; homecoming htmlstring; }

for above code screen shot result link1link2 please suggest method reslove problem.thanks

after posted images on server , assigned appropriate url address pinit button, worked me. post answers herefor post local images app on pinterest.

hope helpful all.

thanks

iphone ios xcode webview pinterest

java - InputVerifier incorrectly yielding focus and need advice using it with other ActionListener methods -



java - InputVerifier incorrectly yielding focus and need advice using it with other ActionListener methods -

i have gui in user enters measurements number of fields , calculates result based on measurement. trying implement next fields-

the values entered must in proper range i have alternative dialog among other things, sets units. field has value in it, must updated current units when value in field changes, need see if measurements entered, , if so, (or redo) calculation.

i've done tables (the model retained values in 'standard' units , custom renderer , cell editor handled showing user values in current units , storing values in 'standard' units in model).

i don't believe jtextfield has renderer override, document editor looked bit daunting, , user didn't jformattedtextfield, thought create custom jtextfield stored 'standard' value , utilize inputverifier used table.

example code below (it works). used jcombobox stand-in alternative dialog , implemented 1 text field.

i utilize expert advice-

i may misunderstanding setinputverifier. thought should invoked if attempted alter focus text field , maintain focus in text field if said don't yield focus. if set 'aa' in text field (without hitting enter) can alter value in combobox. debugging println say-

volume value changed (f) // focus listener fired off updating model // focus listener verifying: 'aa' // input verifier invalid number // input verifier

the text box gets reddish outline , hear beep, combobox active. text field ends empty value, since combobox action listener called when alter value. why allowed alter combox value? how stop that?

my adding inputverifier, 2 actionlisteners , focuslistener seems wrong. logical separation of tasks. should doing? should extend doubleverifier , override actionperformed include what's in doubleverifier , in volumevaluelistener?

i want text field validated , view of underlying info updated either when user enters (cr) , stays in field or when leaves field. why action , focus listeners.

any corrections or insights welcome.

unitstextfield.java

import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; class unitstextfield extends jtextfield { double modelvalue = null; double viewvalue = null; unitstextfield( int cols ) { super( cols ); } public void updatemodel() throws exception { system.out.println( "updating model" ); modelvalue = conversion.modelvalue( this.gettext() ); } public void refreshview() { this.settext( conversion.viewstring( modelvalue ) ); } public double getmodelvalue() { homecoming modelvalue; } }

unitslabel.java

import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; class unitslabel extends jlabel { public void refreshview() { super.settext( conversion.viewlabel() ); } }

conversion.java

import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; class conversion { public static enum units {cc, l, gal}; public static map<string,units> unittypes = new hashmap<string, units>() { { put( "cubic centimeters", units.cc ); put( "liters", units.l ); put( "gallons", units.gal ); } }; public static map<units,double> unitconversions = new hashmap<units, double>() { { put( units.cc, 1.0 ); put( units.l, 1000.0 ); put( units.gal, 4404.9 ); } }; private static units unittype = units.cc; public static void setunittype( units unit ) { unittype = unit; } public static void setunittype( string unitstring ) { unittype = unittypes.get(unitstring); } public static string[] getunitnames() { homecoming (unittypes.keyset()).toarray(new string[0]); } public static string viewlabel() { homecoming unittype.tostring(); } public static double modelvalue( string viewstring ) throws exception { double value = null; if (viewstring != null && viewstring.length() > 0) { value = double.parsedouble( viewstring ); value = value * unitconversions.get(unittype); } homecoming value; } public static string viewstring( double modelvalue ) { double value = null; if (modelvalue != null) { value = modelvalue / unitconversions.get(unittype); } homecoming (value == null) ? "" : value.tostring(); } }

doubleverifier.java

import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; import java.text.numberformat; import java.awt.toolkit; public class doubleverifier extends inputverifier implements actionlistener { public boolean shouldyieldfocus(jcomponent input) { jtextfield tf = (jtextfield) input; boolean inputok = verify(input); if (inputok) { tf.setborder( new lineborder( color.black ) ); homecoming true; } else { tf.setborder( new lineborder( color.red ) ); toolkit.getdefaulttoolkit().beep(); homecoming false; } } public boolean verify(jcomponent input) { jtextfield tf = (jtextfield) input; string txt = tf.gettext(); double n; system.out.println( "verifying: '" + txt + "'" ); if (txt.length() != 0) { seek { n = double.parsedouble(txt); } grab (numberformatexception nf) { system.out.println( "invalid number" ); homecoming false; } } homecoming true; } public void actionperformed(actionevent e) { system.out.println( "input verification" ); jtextfield source = (jtextfield) e.getsource(); shouldyieldfocus(source); } }

volumetextfieldtest.java

import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; class volumetextfieldtest extends jframe { private jcombobox volumecombo; private unitslabel volumelabel; private unitstextfield volumefield; public volumetextfieldtest() { setsize(300, 100); setdefaultcloseoperation(jframe.exit_on_close); volumecombo = new jcombobox( conversion.getunitnames() ); volumecombo.addactionlistener( new volumelistener() ); volumecombo.addfocuslistener( new volumelistener() ); volumelabel = new unitslabel(); volumelabel.refreshview(); volumefield = new unitstextfield(8); doubleverifier dverify = new doubleverifier(); volumefield.setinputverifier( dverify ); volumefield.addactionlistener( dverify ); volumefield.addactionlistener( new volumevaluelistener() ); volumefield.addfocuslistener( new volumevaluelistener() ); jpanel mypane = new jpanel(); mypane.add(volumecombo); mypane.add(volumefield); mypane.add(volumelabel); getcontentpane().add(mypane); setvisible(true); } public class volumelistener implements actionlistener, focuslistener { @override public void actionperformed( actionevent ae ) { system.out.println( "volume type changed" ); conversion.setunittype( (string) volumecombo.getselecteditem() ); volumelabel.refreshview(); volumefield.refreshview(); } @override public void focusgained( focusevent fg ) { } @override public void focuslost( focusevent fl ) { system.out.println( "volume type changed" ); conversion.setunittype( (string) volumecombo.getselecteditem() ); volumelabel.refreshview(); volumefield.refreshview(); } } public class volumevaluelistener implements actionlistener, focuslistener { @override public void actionperformed( actionevent ae ) { system.out.println( "volume value changed (a)" ); seek { volumefield.updatemodel(); volumefield.refreshview(); } grab (exception e) {} } @override public void focusgained( focusevent fg ) { } @override public void focuslost( focusevent fl ) { system.out.println( "volume value changed (f)" ); seek { volumefield.updatemodel(); volumefield.refreshview(); } grab (exception e) {} } } public static void main(string[] args) { seek { swingutilities.invokelater( new runnable() { public void run () { volumetextfieldtest runme = new volumetextfieldtest(); } }); } grab (exception e) { system.out.println( "gui did not start" ); } } }

i understand part of problem additional research. inputverifier concerned focus. if input invalid, not transfer focus, however, allow action events occur. complaints have seen have been related people had exit button action performed if info in field invalid. in case, have combobox action can still performed though inputverifier complaining invalid info (text field gets reddish border , beeps). in respect aspect of problem, don't believe there solution. 1 suggestion variable action listeners checked before performing action, set inputverifier. i've got (ideally) reusable routines in separate files, have problems solution.

i'm still unsure of how gracefully handle situation have several distinct generic actions (verify input, convert units, update view) needed given field , want assign actionlisteners , focuslisteners in sequential order. thought right have base of operations listener, illustration verifies input, extend , override actionperformed, focusgained , focuslost methods, though seems end duplicating code every combination.

java actionlistener inputverifier

xampp - Using PHP in Aptana Studio 3 I get "No PHP executables defined" -



xampp - Using PHP in Aptana Studio 3 I get "No PHP executables defined" -

i'm long time hobbiest using m/s visual studio trying away asp .net. have installed aptana studio 3 , working on html5 web page except php. test website consists of single index.html, single javascript access php , single php page respond javascript.

i uploaded 3 files domain's server , worked correctly. using aptana 3, set 3 files in new php project "no php executables defined" when seek preview project. searched web no help.

some info seems php interpreter should installed aptana, others have sepparately. still others have install wamp. unable decipher aptana website documentation resolve problem.

any help on how set / configure aptana studio 3 preview html5 website php apreciated.

regardless of whether aptanta studio comes php or not, download , install latest version of php on safe side: http://php.net/downloads.php

then in aptana studio, go preferences -> aptanta studio -> editors -> php -> php interpreters , specify php installation details.

then seek 1 time again , see if helps.

php xampp wamp aptana3

PHP get value from url and pass it to text field -



PHP get value from url and pass it to text field -

hi jsf programmer , want integrate documents repositary developed using php in jsf application. doing when user clicks link jsf screen gets value link pass php url , opens page user can add together docs. getting value url , displaying in page. want instead of user entering *number field(please @ screen shot) value url should pass automatically database number , number field should removed . please @ screen shots.

and code snippets

<td class="throws">*number</td> $cellvalue = ""; if ((!isset($_get["add_fd9"])) && (!isset($_post["add_fd9"]))) { $itemvalue = ""; } else { $itemvalue = qsrequest($_get["add_fd9");

then

fieldprompts[_no] = "*number";

pgitm_no= document.getelementsbyname("add_fd9")[0];

i dont understand pass url value

try :

$cellvalue = ""; if (!isset($_request["add_fd9"])) { $itemvalue = ""; } else { $itemvalue = qsrequest($_request["add_fd9"]); }

php

angularjs - Adding angular js attribute after page render -



angularjs - Adding angular js attribute after page render -

i have application contains div content in it. when click button jquery adds angularjs directive div. after adding directive phone call scope.$apply(), doesn't seem inform angular new directive on div. can explain me how can inform angularjs new directive added jquery?

you shouldn't adding directives markup jquery. utilize angular whenever possible.

that said, if have add together directives via straight dom manipulations that, you'll need utilize $compile provider compile element , bind scope before add together it.

angularjs angularjs-directive

c - Is the value of a struct variable just an address(like in the case of array)? -



c - Is the value of a struct variable just an address(like in the case of array)? -

in c next legal:

int a[] = {27,2}; int *b; int c; b = a; c = *b; /* c == 27 */

the point is address of array can assign pointer. why same not true struct, assume value of struct variable address , hence should able assign pointer in:

struct foo bar; struct foo *doo; bar.x = 0; doo = bar; //is legal? doo.x = 0; //why can't utilize dot?

in other words if value of struct variable address of first component(and suppose case array) above code should legal.

as others have pointed out, semantics arrays different structs. why that's case, have remember c derived before languages (bcpl , b), both of "typeless" languages saw memory linear array of fixed-length "words" or "cells". in older languages, when declared array like

auto v[10];

11 memory cells set aside; 1 object named v, , 10 more array elements; address of first element of array stored in v.

from dennis ritchie's paper the development of c language:

problems became evident when tried extend type notation, add together structured (record) types. structures, seemed, should map in intuitive way onto memory in machine, in construction containing array, there no place stash pointer containing base of operations of array, nor convenient way arrange initialized. example, directory entries of unix systems might described in c as struct { int inumber; char name[14]; }; i wanted construction not simply characterize abstract object describe collection of bits might read directory. compiler hide pointer name semantics demanded? if structures thought of more abstractly, , space pointers hidden somehow, how handle technical problem of initializing these pointers when allocating complicated object, perhaps 1 specified structures containing arrays containing structures arbitrary depth? solution constituted crucial jump in evolutionary chain between typeless bcpl , typed c. it eliminated materialization of pointer in storage, , instead caused creation of pointer when array name mentioned in expression. rule, survives in today's c, values of array type converted, when appear in expressions, pointers first of objects making array.

emphasis mine. why array expressions in c treated differently other look types, including struct types.

c pointers

ruby on rails - JSON gem failing to compile on Mac OS X 10.8.2 -



ruby on rails - JSON gem failing to compile on Mac OS X 10.8.2 -

os: mac os x 10.8.2 xcode: latest command line tools installed (version 4.6) rails: version 3.2.3

i trying generate routes project working on (been doing on regular basis), when got error message, recommendation bundle install , bundle exec. did, , time around, process broke off while compiling json gem (version 1.7.7).

doing research on stackoverflow, recommendation update xcode's command line tools, , did, did not solve problem.

i tried installing json version 1.7.7 separately, , failed, telling me error log in:

~/.rvm/gems/ruby-1.9.3-p125/gems/json-1.7.7/ext/json/ext/generator/gem_make.out

which reads:

/users/mine/.rvm/rubies/ruby-1.9.3-p125/bin/ruby extconf.rb creating makefile create compiling generator.c make: /usr/bin/gcc-4.2: no such file or directory make: *** [generator.o] error 1

i looked /usr/bin/gcc-4.2, , indeed, it's not there. but, when do:

ls -l /usr/bin/gcc

here's get:

lrwxr-xr-x 1 root wheel 12 feb 14 15:49 /usr/bin/gcc -> llvm-gcc-4.2

how prepare problem?

i think problem when install xcode command line tools, gcc sym-linked llvm, , llvm can't compile ruby , gems correctly.

if install autoconf, automake, , gcc straight (or through homebrew), should able prepare compiler errors.

ruby-on-rails json osx

iphone - UISearchBar cancel button not responding -



iphone - UISearchBar cancel button not responding -

i have implemented searchbar shows cancel button 1 time user has focus in searchbar. have written searchbar.showscancelbutton = yes; in searchbartextdidbeginediting method. in searchbarsearchbuttonclicked, resign keyboard user can view total tableview.

problem: @ point searchbar cancel button not responding. responds 1 time searchbar gets focus again. default property of search bars cancel button or missing in code. want utilize cancel button without giving focus in searchbar again.

this search bar cancel button's default behaviour. if want other functionality, can uncheck cancelbutton property search bar , can utilize uibutton cancel button.

iphone uisearchbar

object - What is [....] in Ruby? -



object - What is [....] in Ruby? -

this question has reply here:

methods in ruby: objects or not? 5 answers what recursive arrays for? 2 answers

ended accidentally doing equivalent of in ruby other night:

class="lang-ruby prettyprint-override">a = *1..5 # => [1, 2, 3, 4, 5] << a # => [1, 2, 3, 4, 5, [...]] a.last # => [1, 2, 3, 4, 5, [...]]

what [...] , can it?

it's way array.inspect displays recursive arrays. lastly element of itself. if displayed after 5, inspect end in endless loop:

[1, 2, 3, 4, 5, [1, 2, 3, 4, 5, [1, 2, 3, 4, 5, [1, 2, 3, 4, 5, [...]]]]]

ruby object

php - Remove blockquotes from string? -



php - Remove blockquotes from string? -

this question has reply here:

php: strip specific tag html string? 6 answers

i've php string this:

i <blockquote> <strong>string</strong> <blockquote> lot of</blockquote> in <a href="#">it</a> </blockquote> hiya!

and need remove blockquotes transform in:

i hiya!

i think regex can usefull can't find on stackoverflow nor on google , don't know how write myself that.

can tell me how using php?

(i found this, isn't regex , don't know if can remove html element too. using php remove html element string)

try this

$out=preg_replace("~<blockquote(.*?)>(.*)</blockquote>~si","",' '.$str.' ');

php regex string

c# - insert into table from another table and values -



c# - insert into table from another table and values -

i want insert table info , textbox value in table. trying insert command below not working.

insert table_useranswer ( userquizid, quizid, questionid, title, answer1, answer2, answer3, answer4, correctanswer ) '" + m.tostring() + "', select top 5 quizid, questionid, title, answer1, answer2, answer3, answer4, correctanswer [table_question] order newid()"

use insert into...select statement,

insert table_useranswer ( userquizid, quizid, questionid, title, answer1, answer2, answer3, answer4, correctanswer) select top 5 'userquizidvalue', quizid, questionid, title, answer1, answer2, answer3, answer4, correctanswer table_question order newid()

the value of userquizidvalue m.tostring().

c# asp.net sql sql-server sql-insert

orchardcms - Zengallery imagepath pattern -



orchardcms - Zengallery imagepath pattern -

i hoping bertand reply since wrote module zen gallery :)

i want able take product.sku imagepath (pattern) don't know how write pattern.

i have productpart attached productcontenttype if come in /productimages/{content.productpart.sku} pattern module not able pick up.

here setting utilize on nwazet.com: product/{content.sku}

this using nwazet commerce, provides sku token.

orchardcms

Intersect multiple lists in a dictonary using python -



Intersect multiple lists in a dictonary using python -

this has been bugging me whole day. need send emails different person, emails may have multiple recipients, , recipient receives multiple emails.

so suppose have dictionary this:

{ 'email4': ['msg1', 'msg4', 'msg5'], 'email2': ['msg1', 'msg3'], 'email3': ['msg1', 'msg2', 'msg4'], 'email1': ['msg1', 'msg2', 'msg3'] }

and want produce like:

{ 'email1, email2, email3, email4': ['msg1'], 'email1, email3': ['msg2'], 'email1, email2': ['msg3'], 'email3, email4': ['msg4'], 'email4': ['msg5'] }

i figured multiple intersection on both keys , values of dictionary sort of thing, anyway, idea.

quick question, how do in python.

thanks help, have nice day.

update why utilize email(s) keys let's i'm gonna send email email address 4, instead of sending msg1, msg4, , msg5 in separate emails, want combine them 1 email. tuple keys it's demonstration, of course of study can utilize tuples, how's gonna solve problem?

thanks all

example using defaultdict of sets intermediate info structure:

#!/usr/bin/env python # encoding: utf-8 collections import defaultdict pprint import pprint messages = { 'email4': ['msg1', 'msg4', 'msg5'], 'email2': ['msg1', 'msg3'], 'email3': ['msg1', 'msg2', 'msg4'], 'email1': ['msg1', 'msg2', 'msg3'] } intermediate = defaultdict(set) email, msgs in messages.items(): msg in msgs: intermediate[msg].add(email) inverted = {tuple(v): k k, v in intermediate.items()} pprint(inverted) # {('email2', 'email1'): 'msg3', # ('email3', 'email1'): 'msg2', # ('email4',): 'msg5', # ('email4', 'email2', 'email3', 'email1'): 'msg1', # ('email4', 'email3'): 'msg4'}

python

TextInput in iOS gains then immediately loses focus won't open softkeyboard. FocusManager says still has focus. Flex Flash Builder AIR Mobile -



TextInput in iOS gains then immediately loses focus won't open softkeyboard. FocusManager says still has focus. Flex Flash Builder AIR Mobile -

dev environment: flash builder 4.7 sdk: flex 4.6.0 (build 23201) air 3.5 arguments: -local en_us -swf-version=16 testing platform: ios 6 on ipad 2

severe bug, believe. renders ios apps developed using these technologies utterly unusable.

situation: whenever touch textinput component on testing platform device, 1 of 2 things:

it perform supposed to. gains focus (focusin event dispatched), bluish focus rect surrounds it, prompt text replaced flashing cursor, soft keyboard activates , displayed (all expected events dispatched). it fail. gain focus (focusin event dispatched), , bluish focus rect appear briefly , disappear, prompt text remains displayed , there no cursor in field (focusout event dispatched). softkeyboardactivate event dispatched , softkeyboarddeactivate event dispatched. keyboard not appear briefly.

i can tap tap tap tap , 1 tap (no different other) successful , #1 happen instead of #2.

here's oddest thing. focusmanager tells me displayobject has focus same object when focusin event dispatched , after focusout event dispatched (and if check every 10ms using timer, results don't change... right has focus.

below code trace output.

<?xml version="1.0" encoding="utf-8"?> <s:itemrenderer xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" xmlns:c="components.*" width="100%" creationcomplete="creationcompletehandler()"> <fx:declarations> <s:dropshadowfilter id="dropshadowfilter" blurx="6" blury="6" alpha="0.5" distance="6" angle="60" strength=".5" quality="{bitmapfilterquality.high}"/> </fx:declarations> <fx:script> <![cdata[ import flash.filters.bitmapfilterquality; import mx.utils.objectproxy; import spark.skins.mobile.textareaskin; import views.tools.makeatoolbase; [bindable] private var pad:number = 15; [bindable] public var dataproxy:objectproxy; [bindable] public var v:makeatoolbase; protected function creationcompletehandler():void { trace("learnitlistitemrenderer function creationcompletehander()"); dataproxy = new objectproxy(data); dataproxy.choosepicturebutton = choosepicturebutton; } ]]> </fx:script> <s:layout> <s:horizontallayout horizontalalign="center"/> </s:layout> <s:hgroup id="listitem" gap="33" paddingtop="15" paddingbottom="15" horizontalalign="center" paddingleft="15" paddingright="44" verticalalign="middle" width="100%" height="210" filters="{[dropshadowfilter]}"> <s:group height="100%"> <s:rect height="100%" width="100%" radiusx="5" radiusy="5"> <s:fill> <s:solidcolor color="0xffffff" alpha="1"/> </s:fill> <s:stroke> <s:solidcolorstroke weight=".5" color="0x000066"/> </s:stroke> </s:rect> <s:label text="{dataproxy.numberlabel}" fontsize="32" color="#000072" verticalalign="middle" verticalcenter="0" paddingleft="12" paddingright="12"/> </s:group> <c:choosepicturebutton id="choosepicturebutton" height="{listitem.height-pad-pad}" width="{(4*(listitem.height-pad-pad))/3}"/> <s:vgroup id="textinputboxesgroup" height="100%" width="100%"> <s:textinput id="behaviornametextinput" color="#000000" textalign="left" width="100%" prompt="enter behavior name..." needssoftkeyboard="true" interactionmode="touch" skinclass="spark.skins.mobile.textinputskin" returnkeylabel="done" showpromptwhenfocused="true" touchbegin="trace('touch');" softkeyboardactivate= "trace('############################# softkeyboardactive #####################################');" softkeyboarddeactivate="trace('############################# softkeyboarddeactivating #####################################');" softkeyboardactivating="trace('############################# softkeyboardactivating #####################################');" focusin="trace('textinput focusin: '+this.focusmanager.getfocus())" focusout="trace('textinput focusout: '+this.focusmanager.getfocus())" creationcomplete="{data.behaviornametextinput=behaviornametextinput;}" /> <s:spacer id="behaviorspacer" height="2"/> <s:textarea id="behaviordescriptiontextarea" fontfamily="verdana" fontsize="16" verticalalign="top" textalign="left" width="100%" height="100%" verticalscrollpolicy="on" interactionmode="touch" color="#000000" prompt="enter behavior description..." softkeyboardtype="{softkeyboardtype.default}" needssoftkeyboard="true" showpromptwhenfocused="true" skinclass="spark.skins.mobile.textareaskin" creationcomplete="{data.behaviordescriptiontextarea=behaviordescriptiontextarea}"/> </s:vgroup> <c:yesnoverticalbuttonsgroup/> /s:hgroup> </s:itemrenderer>

trace output [ edited brevity ]

textinput focusin: picturetoolsonthemovemakeit0.tabbedviewnavigatorapplicationskin6.tabbednavigator.tabbedviewnavigatorskin8.contentgroup._picturetoolsonthemovemakeit_viewnavigator3.viewnavigatorskin35.contentgroup.makeatoollearnitview471.skinnablecontainerskin472.contentgroup.itemlist.listskin475.scroller477.scrollerskin478.datagroup476.learnitlistitemrenderer566.listitem.textinputboxesgroup.behaviornametextinput ############################# softkeyboardactivating ##################################### ############################# softkeyboarddeactivating ##################################### textinput focusout: picturetoolsonthemovemakeit0.tabbedviewnavigatorapplicationskin6.tabbednavigator.tabbedviewnavigatorskin8.contentgroup._picturetoolsonthemovemakeit_viewnavigator3.viewnavigatorskin35.contentgroup.makeatoollearnitview471.skinnablecontainerskin472.contentgroup.itemlist.listskin475.scroller477.scrollerskin478.datagroup476.learnitlistitemrenderer566.listitem.textinputboxesgroup.behaviornametextinput ############################# softkeyboarddeactivating #####################################

[ failed attempts 2 - 22 removed readability ]

textinput focusin: picturetoolsonthemovemakeit0.tabbedviewnavigatorapplicationskin6.tabbednavigator.tabbedviewnavigatorskin8.contentgroup._picturetoolsonthemovemakeit_viewnavigator3.viewnavigatorskin35.contentgroup.makeatoollearnitview471.skinnablecontainerskin472.contentgroup.itemlist.listskin475.scroller477.scrollerskin478.datagroup476.learnitlistitemrenderer566.listitem.textinputboxesgroup.behaviornametextinput ############################# softkeyboardactivating ##################################### ############################# softkeyboardactive #####################################

ios flex mobile textinput flash-builder

css - How do you center form controls with Bootstrap? -



css - How do you center form controls with Bootstrap? -

i can't figure out how center form controls in bootstrap. seek wrapping in .center div centers things , screws others.

.center { text-align: center; }

you can utilize text-center class

<p class="text-center">center aligned text.</p>

other text alignment classes are

<p class="text-left">left aligned text.</p> <p class="text-center">center aligned text.</p> <p class="text-right">right aligned text.</p> <p class="text-justify">justified text.</p> <p class="text-nowrap">no wrap text.</p>

for detailed info please visit http://getbootstrap.com/css/

css twitter-bootstrap

javascript - How can I decrypt AES CBC Mode in Hex String? -



javascript - How can I decrypt AES CBC Mode in Hex String? -

my task decrypt aes-128 in cbc mode have encrypted hex string , key (also in hex). have tried simple code like:

function dodecrypt(){ var encrypteddata = "1d4c76364618b6efce62258353f89810" var key = "11112222333344445555666677778888"; encrypteddata = cryptojs.enc.hex.parse(encrypteddata); key = cryptojs.enc.hex.parse(key); var decrypted = cryptojs.aes.decrypt(encrypteddata, key); alert(cryptojs.enc.hex.stringify(decrypted)); }

the result blank word array (in "decrpyted"), can point out did wrong please?

do need additional info such iv, salt or not?

"aes-128 in cbc mode" not info format. there no universal way of writing encrypted info along required metadata. need know you've been handed , how generated. can work out how implement same cryptojs in cases. in particular, need know following:

what algorithm? "aes-128" ambiguous. mean "aes 128-bit key size" or mean "aes 128-block size , other key size." what key size (see above) what mode? (you've answered this: it's cbc.) what padding? mutual pkcs#7, there no padding. (for cbc mode, pkcs#7.) what iv? there always iv cbc. iv incorrectly set null (this makes cbc less secure). possible iv generated somehow password (this how openssl works). do have key, insecure key, or password. key series of random bytes size of key. insecure key when password treated key (by copying human-typed letters key buffer). insanely insecure, common. if have proper password, kdf , parameters used convert key? example, did utilize openssl kdf or pbkdf2 or bcrypt or scrypt? is there other metadata, such hmac? (an hmac required secure aes-cbc. without it, attacker can modify ciphertext decrypt desired plaintext.)

when have these answers, can work out how implement cryptojs.

javascript aes cryptojs

What do the following icons mean when creating a new workitem in TFS 2012? -



What do the following icons mean when creating a new workitem in TFS 2012? -

the next image in spanish not matter.

the menu shows list of workitems on tfs , opens when click on "create new work item". don't know mean different icons , why first 2 workitemtypes have different one.

i created workitems can see there wasn't aware of doing different on them set different icon nor different place on menu.

these icons represent category specific work item types in. instance, clipboard check corresponds work item type in task category , 1 below chat box , exclamation point represents work item type in requirements category. these categories defined in process template when creating team project, , can exported/edited/imported current project. hope helps :)

here msdn link on customizing categories: http://msdn.microsoft.com/en-us/library/vstudio/dd273721.aspx

tfs visual-studio-2012 tfs2012 tfs-workitem

c# - Using HTML5 file (Multiple) control in asp.net -



c# - Using HTML5 file (Multiple) control in asp.net -

i looking way manage <input type="file" multiple="multiple"> tag of html 5 in asp.net 3.5 project. have done before single command on page, if have multiple upload controls on same page. please see code:

protected void btnsave_click(object sender, eventargs e) { //---------need check if upload command has files: please suggest perfect way if (fupattachment.postedfile != null || fupattachment.postedfile.filename != "" || fupattachment.postedfile.contentlength>0)//here problem, not checks blank file upload command httpfilecollection hfc = request.files; string strdirectory = server.mappath("~/") + "mailer/" + hidcampid.value; if (hfc.count>0) { if (!system.io.directory.exists(strdirectory)) { system.io.directory.createdirectory(strdirectory); } if (system.io.directory.exists(strdirectory)) { (int = 0; < hfc.count - 1; i++) { hfc[i].saveas(strdirectory + "/" + hfc[i].filename.replace(" ", "_")); } } } } }

my asp page this:

//----this command want multiple upload files <input type="file" multiple="multiple" runat="server" id="fupattachment" /> // upload command there takes input when page loads <asp:fileupload id="fupmailinglist" runat="server" />

so, problem when page loads "fupmailinglist" has taken file, , when want utilize multiple upload command "fupattachment", unable check if has files or not, hfc checks upload controls , gets file in 1 of them. so, please tell me way check "fupattachment" command , work correctly.

rather iterating on files in request, should check on per input basis.

var uploadedfiles = request.files.getmultiple("fupattachment"); if(uploadedfiles.count > 0) { // }

c# asp.net html5 file-upload

java - Logging in custom ant tasks -



java - Logging in custom ant tasks -

i'm creating custom ant task, performs io tasks based on user received param(like file write/append)

i wanted write task if developer using in ant task runs -v or -d flag, output more,

i'm wondering how core ant tasks doing it. checking output level before printing console or done using java.util.logging.logger

follow tutorial.

extract :

integration taskadapter

our class has nil ant. extends no superclass , implements no interface. how ant know integrate? via name convention: our class provides method signature public void execute(). class wrapped ant's org.apache.tools.ant.taskadapter task , uses reflection setting reference project , calling execute() method.

setting reference project? interesting. project class gives nice abilities: access ant's logging facilities getting , setting properties , much more. seek utilize class:

import org.apache.tools.ant.project;

public class helloworld {

private project project; public void setproject(project proj) { project = proj; } public void execute() { string message = project.getproperty("ant.project.name"); project.log("here project '" + message + "'.", project.msg_info); } }

[...]

java logging ant

iphone - Interface Builder won't allow connections to custom UIView class? -



iphone - Interface Builder won't allow connections to custom UIView class? -

using xcode 4.3.3, can't figure out how connect outlets in custom uiview class objects created in interface builder.

in 1 viewcontroller, have variety of buttons, sliders, etc i'm trying grouping views. so, within viewcontroller in ib, added 3 views. 1 view visible @ given time.

i derived custom uiview classes handle each of these 3 views. view controller instantiates each of classes. selected view(s) in ib, opened identity inspector , set class(es) custom class(es). when tried dragging connections view and/or it's constituent controls custom view's .h file ib won't add together connection.

ib allows me add together outlets/actions dragging parent view controller's .h, not custom view's .h file. thought 1 time set view's class custom class, drag outlets view's components custom class rather in view controller.

this question seems identical mine: how connect uiview outlets custom subview 2 solutions (manually adding outlets , setting view's class in ib) did not alter behavior me. here manual outlets added:

customview3.h

#import <uikit/uikit.h> @interface customview3 : uiview @property (retain) iboutlet customview3 *view3; @property (retain) iboutlet uislider *slider; @end

customview3.m

#import "customview3.h" @implementation customview3 @synthesize view3, slider; - (id)initwithframe:(cgrect)frame { self = [super initwithframe:frame]; if (self) { // initialization code } homecoming self; } @end

what missing here? else need set/check in order add together outlets custom uiview rather view controller?

note did work today, had insert/type outlets hand in derived class, drag header file ui element in storyboard, not other way around.

iphone ios ipad uiview iboutlet

networking - Using trace file in NS-3 -



networking - Using trace file in NS-3 -

i want know how utilize own video trace in illustration given in ns-3 examples folder.

do need create alter in line of code?

udptraceclienthelper client(server address,port, "url address video trace")

i looking video traces site:

http://trace.eas.asu.edu/mpeg4/single/sonycif_g16b1mp/sonycif_g16b1mp01/

in url address, using address of verbose trace file. right approach?

when this, still making utilize of default hard coded file trace file.

in short, want know how utilize video trace file in ns3 ?

it's pretty simple, download file , save location in project (you may replace "default hard coded file" named it) ;)

networking network-programming ns-3

php - 'if/elseif' and 'is_active_sidebar' statement in Wordpress theme -



php - 'if/elseif' and 'is_active_sidebar' statement in Wordpress theme -

i have code:

<?php if ( is_active_sidebar('lt') && is_active_sidebar('rt')) { ?> <div class="grid_6 eqh"> <?php } elseif ( !is_active_sidebar('lt') || !is_active_sidebar('rt')) { ?> <div class="grid_9 eqh"> <?php } elseif ( !is_active_sidebar('lt') && !is_active_sidebar('rt')) { ?> <div class="grid_12 eqh"> <?php }; ?>

it's part of wordpress theme i'm developing. it's supposed show different classes according sidebar beingness active or not. response wp if sidebar active 1 , null if isn't. works if 'lt' sidebar active, 'rt' not, diplays 'grid_9' div, if none of sidebars active, displays 'grid_12' div, if 'rt' sidebar inactive , 'lt' active, still displays 'grid_6' div. if remove 1st if statement:

<?php if ( is_active_sidebar('lt') && is_active_sidebar('rt')) { ?>

it doesn't display of divs.

i've tried every combination came mind, i've separated the:

<?php } elseif ( !is_active_sidebar('lt') || !is_active_sidebar('rt')) { ?>

statement in 2 different ones, tried separate if statements without 'elseif', tried with, 'and' , 'or' instead of '&&' , '||' , whole bunch of other variations, nil worked.

if can help me or @ to the lowest degree pont me in right direction, i'd grateful.

as per @one-trick-pony 's suggestion, code now:

<?php $ltactive = is_active_sidebar('lt'); $rtactive = is_active_sidebar('rt'); if($ltactive && $rtactive){ $class = 'grid_6'; }elseif(!$ltactive && !$rtactive){ $class = 'grid_12'; }else{ $class = 'grid_9'; // <== } ?> <div class="<?php echo $class; ?> eqh">

the php code working, seems there bug is_active_sidebar() function in wp, ignoring question on wp back upwards forum.

first, set homecoming result in variables (it speed processing little):

$ltactive = is_active_sidebar('lt'); $rtactive = is_active_sidebar('rt');

now, problem in 2nd status - you're checking if of sidebars inactive, , if 1 of them or both are, 3rd status never evaluated.

so:

(!$ltactive && !$rtactive)

must go before:

(!$ltactive || !$rtactive)

(last status not necessary, can leave else{...})

ok here's code:

if($ltactive && $rtactive){ $class = 'class when both sidebars active'; }else(!$ltactive && !$rtactive){ $class = 'class when both sidebars inactive'; }else{ $class = 'class when 1 of sidebars active (either one)'; } ?> <div class="<?= $class; ?>">

php wordpress if-statement

sql - How to retrieve records having many to many relationship bet two tables? -



sql - How to retrieve records having many to many relationship bet two tables? -

i have 2 tables:

1) employee columns: e_id, e_name, address;

2) project columns: p_id, p_name, start_date, end_date.

there many-to-many relationship between these 2 tables.

how can store relationship , how can query retrieving "employee details , project details on working"?

you need cross reference table inbetween:

employeeprojectxref: e_id, p_id

the combination of e_id , p_id can primary key xref table.

then, if @e_id variable holding selected employee id:

select e.e_name, p.p_name employeeprojectxref epx bring together employee e on e.e_id = epx.e_id bring together project p on p.p_id = epx.p_id epx.e_id = @e_id order p.name

for more details, add together them select list. e.g.: select e.e_name, e.address, p.p_name, p.start_date, p.end_date, etc. here e alias employee table, , p alias project table. query homecoming 1 row each entry in employeeprojectxref table (provided references real entries in employee , project tables.) if there 1 employee , 3 projects, you'll 3 rows.

sql sql-server sql-server-2008 tsql

How to pass parameter to a python script when I pipe it to a Django shell -



How to pass parameter to a python script when I pipe it to a Django shell -

so have integration test tests multiple components of application together, whole end-to-end test. need pipe django shell in order able access models etc. need pass parameter script. doing:

venv/bin/python src/manage.py shell < src/integration_tests/endtoend.py

but want is:

venv/bin/python src/manage.py shell < src/integration_tests/endtoend.py -o 2

if that, throws exception though:

usage: src/manage.py shell [options] runs python interactive interpreter. tries utilize ipython, if it's available. src/manage.py: error: no such option: -o

how should this?

you need write python script takes parameters , outputs script can pipe manage.py.

python src/integration_tests/endtoend.py -o 2 | python src/manage.py shell

i'm pretty sure wouldn't that, that's need pass in command line parameters.

other options environment variables , configuration files.

python django ubuntu

export - exporting from 3ds Max to XNA -



export - exporting from 3ds Max to XNA -

i have created 3ds model in 3ds max , after exported fbx file , loading xna models rendered without mapping , textures 3ds max ?

could know hoe export mapping , textures?

i had same problem , solved right now. before render texture need "bake" it. here how it.http://www.delta3d.org/article.php?story=20051115140557167&topic=tutorials follow until create texture bake. advice simple color adding using material editor before going utilize own texture. after adding color baking thing!. after .tga file set texture folder in project. while model having texture or color on it, export models folder in project. .fbx file has reference .tga file. add together comment if fail...

cheers..

export 3dsmax 3d-modelling 3d-model

Jquery planner calendar -



Jquery planner calendar -

hoping has stumble on help me, trying add together jquery calendar site, , ones can seem find ones have hourly events, 1 person. looking grid, booked out type thing. explanation poor brought pictures. like.

so can add together list of items , days marked out. sort of booking system. don't need hourly, daily markers.

anyone know one? if not going have write own.

thanks.

why need calendar? have no dates weekly concept, , can need tables or divs.

you need homecoming json object person , availability.

data = { 'schedule': [ { 'name': 'car1', 'week': 51, 'availability': { 'mon': true, 'tue': false, //etc } }, /etc ] }

or

data = { // ... 'availability': [1,0,0,0,0,0,1] }

just 2 cents, dont see particular need calendar.

jquery calendar

When does node-mongodb-native hits the database? -



When does node-mongodb-native hits the database? -

i have problem understanding when database nail when using node-mongodb-native. couldn't find reference on that. callback based, gave me feeling every single phone call hits database ... example, 2 snippets different in terms of how many times database nail :

// ---- 1 db.collection('bla', function(err, coll) { coll.findone({'blo': 'bli'}, function(err, doc) { coll.count(function(err, count) { console.log(doc, count) }) }) }) // ---- 2 db.collection('bla', function(err, coll) { coll.findone({'blo': 'bli'}, function(err, doc) { db.collection('bla', function(err, coll) { coll.count(function(err, count) { console.log(doc, count) }) }) }) })

i wondering whether can cache instances of collections , cursors. example, why not fetch collections need once, @ server start, , reuse same instances indefinitely ?

i'd understand how whole thing work, i'd appreciate link explaining stuff in details.

looking @ source code node.js driver collection seems not ping mongodb upon creation of collection unless have strict mode on: https://github.com/mongodb/node-mongodb-native/blob/master/readme.md#strict-mode

the source code looked @ ( https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/db.js#l446 ) reinforced thought if strict not on seek , create new node.js collection object , run callback.

however findone , count break "lazy" querying of node.js , forcefulness query database in order results.

note: count beingness on collection won't enforce "true" count of items in collection. instead garnish info collection meta.

so first snippet should see 2 queries run. 1 findone , 1 count , 2 sec snippet since creating collection after findone should not enforce query mongodb.

mongodb node-mongodb-native

dns - Point Domain to my vServer -



dns - Point Domain to my vServer -

i've problem vserver. own 2 domains , want point them new vserver.

now want edit hosts-file , create entry new domains.

i changed "sites-available" entry:

/etc/apache2/sites-available

and added 1 file configurations:

<virtualhost * > # anmerkung: default domain muss vorhanden sein serveradmin domainname@me.com servername www.domainname.de serveralias domainname.de # anmerkung: sicherstellung der erreichbarkeit bei schreibfehlern; *domain –> problem mit subdomains documentroot /var/www/ # pfad zu lokalen verzeichnis unserer debian etch webseite :-) <directory /var/www/> order deny,allow allow options -indexes # alternative = keine auflistungvon verzeichnissen im browser </directory> </virtualhost>

i've linked file a2ensite , restartet apache. when type www.domainname.de in browser, nil happens.

my host-file:

127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters # auto-generated hostname. please not remove comment. 83.169.2.78 lvps83-169-2-78.dedicated.hosteurope.de lvps83-169-2-78

i've searched 1 week now, , everywhere, in every tutorial: create new file domainname, link it, restart apache , that's it.

where problem configuration?

you need point dns records servers public ip address. assuming have dns services provided company bought domains through, go command panel , there.

dns debian

How to add check box value in array if it already coming from DB in php -



How to add check box value in array if it already coming from DB in php -

i have code displays items in check boxes items existing in db , values have given in db need map in page. how force array? code follow:

echo print_chkbx("select * product_master", database_connect($dbname));

and function is

function print_chkbx($query, $link){ $queried = mysql_query($query, $link); while ($result = mysql_fetch_array($queried)) { $menu .= ' <input name="check" type="checkbox" value="'. $result['product_id'] .'" />' . $result['product_name']; } homecoming $menu; }

this create products array in form.

put [] characters after input name signify inputs name separate entries in array.

$menu .= ' <input name="check" name="products[]" type="checkbox" value="'. $result['product_id'] .'" />' . $result['product_name'];

then upon submit served array:

<?php $products = $_request['products']; // used request unsure of (get||post) echo '<pre>',print_r($products),'</pre>';

php