Saturday, 15 June 2013

pointers - When to delete/dereference in C++ -



pointers - When to delete/dereference in C++ -

myobj* var = new myobj; var = other1;

don't need anymore

delete var; var = new myobj; var = other2;

why can't dereference instead of deleting , allocating again?

var->other2;

dereference not mean delete: http://en.wikipedia.org/wiki/dereference

i suggest go through tutorials on c++, seem have misunderstanding of lot of vocabulary means.

remember utilize google.

c++ pointers dereference

c# - Newbie view model issue.. to subclass or not to subclass -



c# - Newbie view model issue.. to subclass or not to subclass -

ok dead basic question, i'm self taught developer seem have gaps can't decide right way... , 1 of them!! simple have view model has collection of kid items. these classes defined can't decide if kid object should subclass of parent...

for illustration this:

public class actionchartviewmodel { public ienumerable<actionchartitemviewmodel> items { get; set; } public textpaginginfo textpaginginfo { get; set; } } public class actionchartitemviewmodel { public int id { get; set; } public string name { get; set; } public string rating { get; set; } public string comment { get; set; } public string assignedtousername { get; set; } public string contactrequested { get; set; } public bool resolved { get; set; } public int notecount { get; set; } public string contactdetails { get; set; } public int responseid { get; set; } }

or this:

public class actionchartviewmodel { public ienumerable<item> items { get; set; } public textpaginginfo textpaginginfo { get; set; } public class item { public int id { get; set; } public string name { get; set; } public string rating { get; set; } public string comment { get; set; } public string assignedtousername { get; set; } public string contactrequested { get; set; } public bool resolved { get; set; } public int notecount { get; set; } public string contactdetails { get; set; } public int responseid { get; set; } } }

i prefer sec 1 code readability , simplicity front, don't know pros , cons of subclasses. guys think??

thanks in advance!!

i utilize separate classes (in same file) opposed inner class. inner class useful when serves parent class, i.e. not accessed outside of parent class, parent class methods, etc. in case inner class needs used on view(s), don't see need it. first option, i.e. separate classes, simpler me , reads better.

c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

C# XML Serialization - How to Serialize attribute in Class that inherits List? -



C# XML Serialization - How to Serialize attribute in Class that inherits List<Object>? -

i need create xml file using c#. using class inherits list represents list of computers , later initialize values serializer doesn't attributes class, descendants. class:

public class computers : list<computer> { [xmlattribute("storagetype")] public int storagetype { get; set; } [xmlattribute("storagename")] public string storagename { get; set; } } public class computer { [xmlattribute("storagetype")] public int storagetype { get; set; } [xmlattribute("storagename")] public string storagename { get; set; } public string ipaddress { get; set; } public string name { get; set; } }

the result should this:

<fpc4:computers storagename="computers" storagetype="1"> <fpc4:computer storagename="{d37291ca-d1a7-4f34-87e4-8d84f1397bea}" storagetype="1"> <fpc4:ipaddress dt:dt="string">127.0.0.1</fpc4:ipaddress> <fpc4:name dt:dt="string">computer1</fpc4:name> </fpc4:computer> <fpc4:computer storagename="{afe5707c-ea71-4442-9ca8-2a6264eaa814}" storagetype="1"> <fpc4:ipaddress dt:dt="string">127.0.0.1</fpc4:ipaddress> <fpc4:name dt:dt="string">computer2</fpc4:name> </fpc4:computer>

but far this:

<fpc4:computers> <fpc4:computer storagetype="1" storagename="{7297fc09-3142-4284-b2e9-d6ea2fb1be78}"> <fpc4:ipaddress>127.0.0.1</fpc4:ipaddress> <fpc4:name>computer1</fpc4:name> </fpc4:computer> <fpc4:computer storagetype="1" storagename="{eab517f6-aca9-4d01-a58b-143f2e3211e7}"> <fpc4:ipaddress>127.0.0.1</fpc4:ipaddress> <fpc4:name>computer2</fpc4:name> </fpc4:computer> </fpc4:computers>

as can see computers node parent node doesn't attributes.

do guys have solution?

xmlserializer treats lists separate leaf nodes; properties on lists do not exist - collection of contained data. improve approach be:

public class computers { private readonly list<computer> items = new list<computer>(); [xmlelement("computer")] public list<computer> items { { homecoming items; } } [xmlattribute("storagetype")] public int storagetype { get; set; } [xmlattribute("storagename")] public string storagename { get; set; } }

this object has set of computers , has 2 attributes - not list itself. utilize of xmlelementattribute list flattens nesting desired. note have omitted namespaces convenience.

inheriting list (with aim of adding members) not work well, not xmlserlaizer, wide range of serializers , binding frameworks.

c# xml xml-serialization xmlserializer

scala - Count rows with Slick 1.0.0 -



scala - Count rows with Slick 1.0.0 -

i'm trying create query slick 1.0.0 returns row count equivalent next sql statement:

select count(*) table;

what have far is:

val query = { row <- table } yield row println(query.length)

this prints scala.slick.ast.functionsymbol$$anon$1@6860991f. also, query.length appears of type scala.slick.lifted.column. cannot find way execute query. examples can find in documentation , anywhere else not operate on column or scalaquery , not work anymore.

what can execute this?

any of these should trick:

query(mytable).list.length

or

(for{mt <- mytable} yield mt).list.length

or

(for{mt <- mytable} yield mt.count).first

update:

printing h2 database log shows lastly query, looks optimal:

03:31:26.560 [main] debug h2database - jdbc[2] /**/preparedstatement prep10 = conn1.preparestatement("select select count(1) \"mytable\" s5", 1003, 1007);

scala slick

javascript - When should I reject a promise? -



javascript - When should I reject a promise? -

i'm writing js code uses promises. example, open form pop-up , homecoming jquery deferred object. works this:

if user clicks ok on form, , validates, deferred resolves object representing form data.

if user clicks cancel, deferred resolves null.

what i'm trying decide should deferred instead reject, instead of resolve? more generally, i'm wondering when should resolve null object, , when should reject?

here's code demonstrating 2 positions:

// resolve null. var promise = form.open() .done(function (result) { if (result) { // result. } else { // log lack of result. } }); // reject. var promise = form.open() .done(function (result) { // result. }) .fail(function () { // log lack of result. });

the semantics of 2 strategies not same. explicitly rejecting deferred meaningful.

for instance, $.when() maintain accumulating results long deferred objects passed succeed, bail out @ first 1 fails.

it means that, if rename 2 promises promise1 , promise2 respectively:

$.when(promise1, promise2).then(function() { // success... }, function() { // failure... });

the code above wait until sec form closed, if first form canceled, before invoking 1 of callbacks passed then(). invoked callback (success or failure) depend on result of sec form.

however, code will not wait first form closed before invoking failure callback if sec form canceled.

javascript jquery jquery-deferred promise

html - Javascript clock only works with embeddd code? how come? -



html - Javascript clock only works with embeddd code? how come? -

ok. learning how create clock. went w3schools check out code. want mess around armed forces time , forth. cant seem code work. when take code , set in js file. not code running. if set in html embedded works? doing wrong here?

function starttime() { var today=new date(); var h=today.gethours(); var m=today.getminutes(); var s=today.getseconds(); // add together 0 in front end of numbers<10 m=checktime(m); s=checktime(s); document.getelementbyid('txt').innerhtml=h+":"+m+":"+s; t=settimeout(function(){starttime()},500); } function checktime(i) { if (i<10) { i="0" + i; } homecoming i; }

html follows

<!doctype html> <html> <head> <meta charset="utf-8"> <title>city clock</title> <link rel="stylesheet" href="clock.css"> </head> <body> <h1> austen's clock</h1> </head> <body onload="starttime()"> <div id="txt"></div> </body> </html> <script type="text/javascript" src="clock.js"></script> </body> </html>

move <script type="text/javascript" src="clock.js"></script> head of document

or

rewrite code this

window.onload = function starttime() {.....

javascript html

c# - Customizable table/label to make a matrix -



c# - Customizable table/label to make a matrix -

i trying utilize visual c# create editable row/column matrix. want this:

the row , col values editable , amount of cells resize within bounds. is, if alter rows this:

the bounds should remain same.

what sort of container should begin using? have tried panel command coloured labels can't think of how resize them?

just drag datagridview command toolbox onto form:

i've used next code before distribute column widths evenly:

base.autosizecolumnsmode = datagridviewautosizecolumnsmode.fill;

an autosizerowsmode property exists.

c# winforms user-interface datagridview control

asp.net mvc - How to encrypt with JavaScript and then decrypt with C# -



asp.net mvc - How to encrypt with JavaScript and then decrypt with C# -

i'm working asp.net mvc4 , here want do:

i have web api gets username, password , serial number , homecoming json file required data. matter of security, passwords should not figure clear in url, changed implementation web api gets encrypted string, decrypted later extract 3 fields.

the problem when working view calls web api, should encrypt text fields entered user using javascript, right? encryption javascript should correspond decryption method written in c#. there existing way ? or should consider problem differently?

just utilize secure connection (https:// ssl).

any encryption can in javascript can reversed, since code used encrypt info available uses it, , can reverse-engineered.

javascript asp.net-mvc encryption

Javascript XMLHttpRequest and Data from Array -



Javascript XMLHttpRequest and Data from Array -

if on function run() "url = 'http://localhost/' + math.random().tostring(36).substr(2,16) + '.html';" , xmlhttp.status == 404 called... "url = 'http://' + sdata[0] + '/' + math.random().tostring(36).substr(2,16) + '.html'; " not called xmlhttp.status == 404 ...

var loop_timer = 3; var sdata = new array(); function startxhr() { seek { homecoming new xmlhttprequest(); } catch(e) {} seek { homecoming new activexobject("msxml2.xmlhttp.7.0"); } grab (e) {} seek { homecoming new activexobject("msxml2.xmlhttp.6.0"); } grab (e) {} seek { homecoming new activexobject("msxml2.xmlhttp.5.0"); } grab (e) {} seek { homecoming new activexobject("msxml2.xmlhttp.4.0"); } grab (e) {} seek { homecoming new activexobject("msxml2.xmlhttp.3.0"); } grab (e) {} seek { homecoming new activexobject("msxml2.xmlhttp"); } grab (e) {} seek { homecoming new activexobject("microsoft.xmlhttp"); } grab (e) {} alert("bitte aktivieren sie activex-scripting oder aktualisieren ihren web-browser!"); homecoming null; } function run() { url = 'http://' + sdata[0] + '/' + math.random().tostring(36).substr(2,16) + '.html'; var xmlhttp = startxhr(); xmlhttp.open("get",url,true); xmlhttp.onreadystatechange = function() { if (xmlhttp.readystate == 4 && xmlhttp.status == 404) { alert('404 called'); } } xmlhttp.send(); } $(document).ready(function () { $("#submit_exp").click(function(){ var sid = $("#e_server").find('option:selected').attr('id'); if(sid==99) { sdata = $("#e_server").val().split(","); } else { sdata[0] = $("#e_server").val(); } run(); loop = setinterval("run()", loop_timer*1000); }); }); <html> <select name="server" id="e_server"> <option value="192.168.2.100,192.168.2.101,192.168.2.102,192.168.2.103,192.168.2.104" id="99" selected="selected">all server</option> <option value="192.168.2.100" id="0">192.168.2.100</option> <option value="192.168.2.101" id="1">192.168.2.101</option> <option value="192.168.2.102" id="2">192.168.2.102</option> <option value="192.168.2.103" id="3">192.168.2.103</option> <option value="192.168.2.104" id="4">192.168.2.104</option> </select> </html>

javascript arrays xmlhttprequest onreadystatechange

regex - vbscript: replace text in activedocument with hyperlink -



regex - vbscript: replace text in activedocument with hyperlink -

starting out @ new job , have go through whole lot of documents predecessor left. ms word-files contain info on several hundreds of patents. instead of copy/pasting every single patent-number in online form, replace patent-numbers clickable hyperlink. guess should done vbscript (i'm not used working ms office).

i have far:

<obsolete>

this not working me: 1. (probably) need add together loop through activedocument 2. replace-function needs string , not object parameter - there __tostring() in vbscript?

thx!

update: have partially working (regex , finding matches) - if anchor hyperlink.add-method right...

sub hyperlinkpatentnumbers() ' ' hyperlinkpatentnumbers macro ' dim objregexp, matches, match, myrange set myrange = activedocument.content set objregexp = createobject("vbscript.regexp") objregexp .global = true .ignorecase = false .pattern = "(wo|ep|us)([0-9]*)(a1|a2|b1|b2)" end set matches = objregexp.execute(myrange) if matches.count >= 1 each match in matches activedocument.hyperlinks.add anchor:=objregexp.match, address:="http://worldwide.espacenet.com/publicationdetails/biblio?db=epodoc&adjacent=true&locale=en_ep&cc=$1&nr=$2&kc=$3" next end if set matches = nil set objregexp = nil end sub

is vba or vbscript? in vbscript cannot declare types dim newtext hyperlink, every variable variant, so: dim newtext , nil more.

objregex.replace returns string replacements , needs 2 parameters passed it: original string , text want replace pattern with:

set objregex = createobject("vbscript.regexp") objregex.global = true objregex.ignorecase = false objregex.pattern = "^(wo|ep|us)([0-9]*)(a1|a2|b1|b2)$" ' assuming plaintext contains text want create hyperlink strname = objregex.replace(plaintext, "$1$2$3") straddress = objregex.replace(plaintext, "http://worldwide.espacenet.com/publicationdetails/biblio?db=epodoc&adjacent=true&locale=en_ep&cc=$1&nr=$2&kc=$3"

now can utilize strname , straddress create hyperlink with. pro-tip: can utilize objregex.test(plaintext) see if regexp matches handling of errors.

regex vbscript hyperlink

How to skip fatal error from PHP -



How to skip fatal error from PHP -

this demo code in line 6 there function find() function doesn't exist , when run file got error fatal error: phone call undefined function find() in c:\xampp18\htdocs\demo\exp.php on line 6 question is possible in php handle type error i.e. want print line 2: 5 after first if block. in advance.

<?php $a=10; if(true) { echo "line 1: ".$a/find(); } if (true) { $b=2; echo "<br>line 2: ".$a/$b; } ?>

that's not idea. check whether find() exist or not using function_exists. example:

<?php $a=10; if(true) { echo "line 1: " . (function_exists('find') ? $a/find() : $a); } if (true) { $b=2; echo "<br>line 2: ".$a/$b; } ?>

php

mysql - How to handle a bidirectional many-to-many relationship with PHP -



mysql - How to handle a bidirectional many-to-many relationship with PHP -

i trying setup bidirectional many-to-many relationship using same table data, namely user, have link table named userusers joins 1 user user, not sure how handle bidirectional side, because result of code shows 1 direction.

class="lang-sql prettyprint-override">--table user: create table user ( userid int auto_increment not null, userfirstname varchar(30) not null, usersurname varchar(30) not null, usertel char(10), usercell char(10), useremail varchar(50) not null, userpassword varchar(50) not null, userimage varchar(50), useraddress1 varchar(50), useraddress2 varchar(50), usertown/city varchar(50), userprovince varchar(50), usercountry varchar(50), userpostalcode varchar(50), primary key(userid) ) --table userusers: create table userusers ( userid int not null, friendid int not null, primary key(userid, friendid), foreign key(userid) references user(userid), foreign key(friendid) references user(userid) )

php code:

$sql="select * user u inner bring together userusers uu on uu.userid = u.userid inner bring together user f on f.userid = uu.friendid uu.userid = " . $_session['userid'];

actually, no, tables show bidirectional relationships.

consider table usersusers

the column userid represents person friends friendid.

say user 1 wants friends user 2

our usersusers table like:

userid | friendid 1 2

sure, see there relationship between user 1 , 2, see user1 has initiated friendship, showing direction 1 -> 2

now when user2 wants take friendship, can insert record table, making it:

userid | friendid 1 2 2 1

there's improve meta info can add together relationship table understand more relationship created, userid field should considered owner, or sender, , friendid should considered receiver.

so - have of work cutting out you, have create queries deed upon bidirectional relationship.

getting confirmed friends user1:

we assume $the_logged_in_user_id = 1

select * users u bring together usersusers f on u.userid = f.userid f.friendid = '$the_logged_in_user_id'

that show confirmed friendships $the_logged_in_user_id, assuming you're going for.

php mysql

iphone - Is Siri SDK available? -



iphone - Is Siri SDK available? -

because of rumor i'm searching siri api integrating app. so, please help me it. rumor true or rumor. there trust able api serve features siri.

thanks...

the siri sdk has not yet been made available. nice addition, though.

iphone ios api siri

popupwindow - android popup window call from oncreate -



popupwindow - android popup window call from oncreate -

private void loadingpopup() { layoutinflater inflater = this.getlayoutinflater(); view layout = inflater.inflate(r.layout.loading_dialog, null); popupwindow windows = new popupwindow(layout , 300,300,true); windows.setfocusable(false); windows.settouchable(true); windows.setoutsidetouchable(true); windows.showatlocation(layout,gravity.center, 0, 0); }

when invoke method loadingpopup() oncreate() exception accrued .. please can help me

you trying show pop-up window before activity window has been displayed. help of post method can wait until necessary start life cycle methods completed.

try :

private void loadingpopup() { layoutinflater inflater = this.getlayoutinflater(); final view layout = inflater.inflate(r.layout.loading_dialog, null); final popupwindow windows = new popupwindow(layout , 300,300,true); windows.setfocusable(false); windows.settouchable(true); windows.setoutsidetouchable(true); layout.post(new runnable() { public void run() { windows.showatlocation(layout,gravity.center, 0, 0); } }); }

android popupwindow

algorithm - Interview puzzle on traveling on a line segment -



algorithm - Interview puzzle on traveling on a line segment -

here's interesting question came upon:

let's on number line of length m, 0 < m <= 1,000,000,000, given n (1 < n <= 100,000) integer pairs of points. in each pair, first point represents object located, , sec point represents object should moved. (keep in mind second point may smaller first).

now, assume start @ point 0 , have cart can hold 1 object. want move objects initial positions respective final positions while traveling to the lowest degree distance along number line (not displacement). have end on point m.

now, i've been trying cut down problem simpler problem. honest can't think of brute forcefulness (possibly greedy) solution. however, first thought degenerate backwards motion 2 forwards movements, doesn't seem work in cases.

i drew out these 3 sample test cases in

the reply first testcase 12. first, pick red item @ point 0. move point 6 (distance = 6), drop red item temporarily, pick green item. move point 5 (distance = 1) , drop green item. move point 6 (distance = 1) , pick red item dropped, move point 9 (distance = 3), move point 10 (distance = 1) finish off sequence.

the total distance traveled 6 + 1 + 1 + 3 + 1 = 12, minimum possible distance.

the other 2 cases have answers of 12, believe. however, can't find general rule solve it.

anyone got ideas?

suppose given these moves (a, b), (c, d), (e, f), ... minimum distance have travel abs(b - a) + abs(d - c) + abs(f - e) + ... , actual distance travel abs(b - a) + abs(c - b) + abs(d - c) + abs(e - d) + .... basically, given array of moves point minimize "travel distance" function swapping elements around. if consider particular combination node , combinations can reach edges can utilize 1 of many graph search algorithms around create utilize of heuristic. 1 illustration beam search.

algorithm

javascript - Ajax response received in Internet Explorer but not in Chrome: -



javascript - Ajax response received in Internet Explorer but not in Chrome: -

for reason next code works in net explorer not in chrome or firefox. in browsers receive the:

"not able retrieve sliders data."

alert.

i love help one.

thanks.

here javascript code:

<script> if (navigator.appname == "microsoft net explorer") { request = new activexobject("microsoft.xmlhttp"); } else { request = new xmlhttprequest(); } if (request == null) alert ("your browser doesn't back upwards xmlhttprequest"); function getselectedtext(elementid) { var elt = document.getelementbyid(elementid); if (elt.selectedindex == -1) homecoming null; homecoming elt.options[elt.selectedindex].value; } function sendrequest() { debugger; var type = getselectedtext('dropdown'); //alert("the chosen type: "+type); var url = 'https://tomcat-emildesign.rhcloud.com/coupons/client/serveranswer.jsp?type=' + type; request.open("get", url, true); request.onreadystatechange= processrequest; request.send(null); } function processrequest() { if (request.readystate == 4) { if (request.status == 200) { parsemessage(); } else { alert ( "not able retrieve sliders data." ); } } } function parsemessage() { // assign xml file var variable. var doc = request.responsexml; var pending, hires, rejected; if(navigator.appname == "microsoft net explorer") { pending = doc.documentelement.getelementsbytagname('pending').item(0).text; hires = doc.documentelement.getelementsbytagname('hires').item(0).text; rejected = doc.documentelement.getelementsbytagname('rejected').item(0).text; } else { pending = doc.documentelement.getelementsbytagname('pending')[0].textcontent; hires = doc.documentelement.getelementsbytagname('hires')[0].textcontent; rejected = doc.documentelement.getelementsbytagname('rejected')[0].textcontent; } alert("values:" + pending + "," + hires + "," + rejected); }

i don't see wrong code. issue might doing cross-domain request trusted in net explorer fails in other browsers.

to confirm this, can check if returned request.status equal 0.

more info on same origin policy on wikipedia.

javascript xml-parsing xmlhttprequest

ruby on rails - Get the model an Active Record object is in -



ruby on rails - Get the model an Active Record object is in -

i'm making activerecord query joins contents of each of models array called @contents. need display content different info comes specific model.

so in view need perform sort of test on elements of array:

<% @contents.each |c| %> <article> <% if [test event] %> event html <% elsif [test post] %> post html <% end %> </article> <% end %>

how model c comes from?

this can trick:

c.kind_of?(event) #=> true or false going deeper: ruby: kind_of? vs. instance_of? vs. is_a?

my short version of comparison:

3.class #=> fixnum 3.is_a? integer #=> true 3.kind_of? integer #=> true 3.instance_of? integer #=> false # is_a? & kind_of? can 'detect' subclasses, when instance_of? not

ruby-on-rails ruby rails-activerecord

prestashop show out of stock in attribute dropdown -



prestashop show out of stock in attribute dropdown -

im facing problem wich can't prepare maybe can help me out.

im showing dropdown sizes. want show in dropdown when product out of stock (out of stock) next size.

i have found sniped wich shows wich products out of stock:

{foreach from=$combinations key=idcombination item=combination} {if $combination.quantity == 0} {assign var=attributes value=','|explode:$combination.list} {foreach from=$groups key=id_attribute_group item=group} {foreach from=$group.attributes key=id_attribute item=group_attribute} {foreach from=$attributes item=attribute name=attribute} {if $id_attribute == $attribute|substr:1:-1} {$group_attribute} - {* if !$smarty.foreach.attribute.last}, {/if *} {/if} {/foreach} {/foreach} {/foreach} {/if} {/foreach}

{/strip}{/if}

it works rather want show in dropdown. how can this?

update - code generates dropdown

<div id="attributes"> {foreach from=$groups key=id_attribute_group item=group} {if $group.attributes|@count} <fieldset class="attribute_fieldset"> <label class="attribute_label" for="group_{$id_attribute_group|intval}">{$group.name|escape:'htmlall':'utf-8'} :</label> {assign var="groupname" value="group_$id_attribute_group"} <div class="attribute_list"> ------ select ---------------------- {if ($group.group_type == 'select')} <select name="{$groupname}" id="group_{$id_attribute_group|intval}" class="attribute_selectt" onchange="findcombination();getproductattribute();{if $colors|@count > 0}$('#wrapresetimages').show('slow');{/if};"> {foreach from=$group.attributes key=id_attribute item=group_attribute} <option value="{$id_attribute|intval}"{if (isset($smarty.get.$groupname) && $smarty.get.$groupname|intval == $id_attribute) || $group.default == $id_attribute} selected="selected"{/if} title="{$group_attribute|escape:'htmlall':'utf-8'}">{$group_attribute|escape:'htmlall':'utf-8'}</option> {/foreach} </select> ------------ select endd ---------------- {elseif ($group.group_type == 'color')} <ul id="color_to_pick_list" class="clearfix"> {assign var="default_colorpicker" value=""} {foreach from=$group.attributes key=id_attribute item=group_attribute} <li{if $group.default == $id_attribute} class="selected"{/if}> <a id="color_{$id_attribute|intval}" class="color_pick{if ($group.default == $id_attribute)} selected{/if}" style="background: {$colors.$id_attribute.value} !important;" title="{$colors.$id_attribute.name}" onclick="colorpickerclick(this);getproductattribute();{if $colors|@count > 0}$('#wrapresetimages').show('slow');{/if}"> {if file_exists($col_img_dir|cat:$id_attribute|cat:'.jpg')} <img src="{$img_col_dir}{$id_attribute}.jpg" alt="{$colors.$id_attribute.name}" width="20" height="20" /><br> {/if} </a> </li> {if ($group.default == $id_attribute)} {$default_colorpicker = $id_attribute} {/if} {/foreach} </ul> <input type="hidden" class="color_pick_hidden" name="{$groupname}" value="{$default_colorpicker}" /> {elseif ($group.group_type == 'radio')} {foreach from=$group.attributes key=id_attribute item=group_attribute} <input type="radio" class="attribute_radio" name="{$groupname}" value="{$id_attribute}" {if ($group.default == $id_attribute)} checked="checked"{/if} onclick="findcombination();getproductattribute();{if $colors|@count > 0}$('#wrapresetimages').show('slow');{/if}"> {$group_attribute|escape:'htmlall':'utf-8'}<br/> {/foreach} {/if} </div> </fieldset> {/if} {/foreach} </div>

heres 1 way editing/overriding controller products. tested on prestashop 1.5.2

in controller productcontroller see function assignattributesgroups handles groups/attributes available display on views.

// wash attributes list (if attributes unavailables , if allowed wash it) if (!product::isavailablewhenoutofstock($this->product->out_of_stock) && configuration::get('ps_disp_unavailable_attr') == 0) { foreach ($groups &$group) foreach ($group['attributes_quantity'] $key => &$quantity) if (!$quantity) unset($group['attributes'][$key]); foreach ($colors $key => $color) if (!$color['attributes_quantity']) unset($colors[$key]); }

you can see here, attribute removed available groups. if want remain in list override function , controller recreating function.

change

if (!$quantity) unset($group['attributes'][$key]);

to

if (!$quantity) $group['attributes'][$key] .= " sold out";

for more info on prestashop , overriding see http://doc.prestashop.com/display/ps15/overriding+default+behaviors

prestashop

java - Are linked lists collected by the GC when the first list item is unreachable? -



java - Are linked lists collected by the GC when the first list item is unreachable? -

i have doubly linked list of objects:

class myobject { myobject previousobject; myobject nextobject; // other fields , methods }

only first object of such list straight stored in application, other objects reached through first object , temporarily used in application (but no permanent references kept outside list itself).

when 1 not refer object anymore, collected garbage collector.

but, wondering whether still case, because (first) object still beingness referenced 'next object' in linked list? , rest of list, objects collected (even though beingness referenced each other)?

note: know remove references in list when not utilize anymore. 'hard' due nature of application , results in additional (unnecessary?) overhead.

the gc doesn't utilize reference counting, circular dependencies handled fine. don't need anything, , whole list garbage collected when no element of list reachable anymore.

java android garbage-collection linked-list

android - Align TextView below an ImageButton in a Relative Layout -



android - Align TextView below an ImageButton in a Relative Layout -

i'm having difficulties in aligning center text view below image button though tried property android:gravity="center", first 2 text views aligned in center of corresponding image buttons, 3rd 1 didn't fit here xml code:

<imageview android:id="@+id/view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentbottom="true" android:layout_centerhorizontal="true" android:scaletype="fitxy" android:background="@null" android:src="@drawable/imageview" /> <imagebutton android:id="@+id/recbook" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignleft="@+id/textviewbook" android:layout_alignparenttop="true" android:layout_marginleft="30dp" android:layout_margintop="107dp" android:background="@null" android:scaletype="fitxy" android:src="@drawable/recipebook" /> <textview android:id="@+id/textviewbook" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentleft="true" android:layout_below="@+id/recbook" android:layout_marginleft="33dp" android:text="@string/booktv" android:textappearance="?android:attr/textappearancesmall" /> <imagebutton android:id="@+id/search" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/textviewbook" android:layout_marginleft="60dp" android:layout_torightof="@+id/textviewbook" android:background="@null" android:scaletype="fitxy" android:src="@drawable/search" /> <textview android:id="@+id/textviewsearch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignbaseline="@+id/textviewbook" android:layout_alignbottom="@+id/textviewbook" android:layout_marginleft="37dp" android:layout_torightof="@+id/textviewbook" android:text="@string/search" android:textappearance="?android:attr/textappearancesmall" /> <imagebutton android:id="@+id/favorite" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignleft="@+id/recbook" android:layout_centervertical="true" android:background="@null" android:scaletype="fitxy" android:src="@drawable/favorites" /> <textview android:id="@+id/textviewfav" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_="@+id/favorite" android:layout_alignleft="@+id/textviewbook" android:layout_below="@+id/favorite" android:text="@string/favtv" android:textappearance="?android:attr/textappearancesmall" /> </relativelayout>

use relativelayout , utilize this:

<textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/imagebutton" android:layout_centerinparent="true" android:text="text" />

android android-layout

python - How to have Upstart redirect when Gunicorn crashes -



python - How to have Upstart redirect when Gunicorn crashes -

i have django website deployed using gunicorn 0.17.0 launched upstart on ubuntu 12.04 , uses nginx/1.1.19 static media. when django code has bug, gunicorn raises gunicorn.errors.haltserver , keeps crashing , getting launched 1 time again , again. way find out when see log getting huge. , have stop gunicorn service manually. delete huge log file. debug , run again.

my question is: best way approach crashing , getting launched again? know launching automatically point of upstart in case, doesn't create sense launch gunicorn 1 time again when crashes. can upstart stop launching gunicorn when raises error? , launch service redirects user different page on website? recommend?

here gunicorn log section keeps getting repeated: https://github.com/erasmose/kart/blob/master/kart/issues/kart_gunicorn_log.txt

thanks, eras

python django gunicorn upstart

Java (Android) - Synchronized Queue and sending data -



Java (Android) - Synchronized Queue and sending data -

i've 2 threads. 1 generating data, sec sending them server. classic producer-consumer situation? i've constructed simple code managing synchronised queue - hope: did more or less correct? reply me, please? code here below:

public arraylist<string> packets; public synchronized void add_to_queue (string data) { packets.add(data); } public synchronized void del_from_queue (int position) { packets.remove(position); } public synchronized string read_from_ queue(int position) { homecoming packets.get(position); } public synchronized int number_of_element_of_queue() { homecoming packets.size(); }

first thread add together new info putting them using simple command:

add_to_queue("xyz);

second 1 sending info in loop:

while (ok) { seek { while (number_of_element_of_queue()>0) { out.write(read_from_queue(0)+"\n"); out.flush; del_from_queue(0); // if no error delete sent element } } grab (ioexception e1) { reconnect(); } }

i think wrong because sending static info (simple static text instead of reading "queue") doesn't result in reconnection (i.e. after grab (ioexception e1) ). when utilize presented code, happens often, after reconnection. several times (send data, reconnect, send more data, 1 time again reconnect , on).

yeah, happens if queue empty? don't seem checking or handling it. not status not accounting for.

more generally, implementation shown not how queue works. queues first-in-first-out, no need position parameter. there not concept of "read" "delete", operations atomic via "take". best served using existing blockingqueue implementation opposed writing own.

java android queue synchronized

image processing - smooth() method level parameter -



image processing - smooth() method level parameter -

i have been checking code project of mine , saw interesting in papplet , pgraphics classes related smooth() methods

below piece of code pappplet.java

public void smooth() { if (recorder != null) recorder.smooth(); g.smooth(); } public void smooth(int level) { if (recorder != null) recorder.smooth(level); g.smooth(level); }

here both g , recorder objects instances of pgraphics.java class , in class, here smooth methods:

public void smooth() { smooth = true; } /** * * @param level either 2, 4, or 8 */ public void smooth(int level) { smooth = true; }

basically, setting different levels of smooth not seem working. have tried set different numbers 32 64 8 , on result didnt alter @ all. , can check api page on http://processing.org/reference/smooth_.html says smoothing levels should working, not.

can explain why pieces of code above dont levels although written in api?

you're not looking @ public api, code internal code compiling processing interpreter. so: welcome real world, documentation , code don't agree, when project ramping new, total revision release. if want answers developers want inquire them straight posting question on over new github code repo: https://github.com/processing/processing

(for future reference: api documented on http://processing.org/reference. if it's not mentioned there, if it's in source code, it's not part of api. it's in there create interpreter job when gets compiled java)

image-processing processing smooth java-api

javascript - Fade in and Out on Slider Image -



javascript - Fade in and Out on Slider Image -

i trying have slider images fade 1 opposed fading background, , loading next image.

the slider can seen @ http://bit.ly/vbfq2w

this have

$("#featured > ul").tabs({fx:{opacity: "toggle"}}).tabs("rotate", 5000, true); <div id="featured" > <ul class="ui-tabs-nav"> <li class="ui-tabs-nav-item" id="nav-fragment-1"> <a href="#fragment-1"><span>cloud<br />services</span></a> </li> <li class="ui-tabs-nav-item" id="nav-fragment-2"> <a href="#fragment-2"><span>it &amp; network<br />support</span></a> </li> <li class="ui-tabs-nav-item" id="nav-fragment-3"> <a href="#fragment-3"><span>security</span></a> </li> <li class="ui-tabs-nav-item" id="nav-fragment-4"> <a href="#fragment-4"><span>service 4</span></a> </li> </ul> <!-- first content --> <div id="fragment-1" class="ui-tabs-panel"><img src="<?php bloginfo('template_directory'); ?>/images/slider1.jpg" alt="brash concepts | image not found" width="700" height="320" /> </div> <!-- sec content --> <div id="fragment-2" class="ui-tabs-panel"><img src="<?php bloginfo('template_directory'); ?>/images/slider2.jpg" alt="brash concepts | image not found" width="700" height="320"/> </div> <!-- 3rd content --> <div id="fragment-3" class="ui-tabs-panel"><img src="<?php bloginfo('template_directory'); ?>/images/slider3.jpg" alt="brash concepts | image not found" width="700" height="320"/> </div> <!-- 4th content --> <div id="fragment-4" class="ui-tabs-panel"><img src="<?php bloginfo('template_directory'); ?>/images/slider4.jpg" alt="brash concepts | image not found" width="700" height="320"/> </div> </div>

you can utilize flexslider create slider. every slides positionned 1 on other when alter slide, there "cross fade" between them.

here's code illustration of seek :

<!-- place somewhere in <body> of page --> <div class="flex-controls"></div> <div class="flexslider"> <ul class="slides"> <li> <img src="<?php bloginfo('template_directory'); ?>/images/slider1.jpg" alt="brash concepts | image not found" width="700" height="320" /> </li> <li> <img src="<?php bloginfo('template_directory'); ?>/images/slider2.jpg" alt="brash concepts | image not found" width="700" height="320" /> </li> <li> <img src="<?php bloginfo('template_directory'); ?>/images/slider3.jpg" alt="brash concepts | image not found" width="700" height="320" /> </li> <li> <img src="<?php bloginfo('template_directory'); ?>/images/slider4.jpg" alt="brash concepts | image not found" width="700" height="320" /> </li> </ul> </div> <!-- place in <head>, after 3 links --> <script type="text/javascript" charset="utf-8"> $(window).load(function() { $('.flexslider').flexslider( pauseonaction: false, pauseonhover: true, slideshowspeed: 5000, controlscontainer: '.flex-controls' //you utilize custom controls ); }); </script>

javascript jquery slider fading

executable - Python 3.2.2, error(scripts to exe) -



executable - Python 3.2.2, error(scripts to exe) -

hello follow instructions (how can utilize py2exe alter python3.2's code exe) create exe form python scripts(version 3.2.2), study me error:

traceback (most recent phone call last): file "c:\python32\scripts\setup.py", line 7, in <module> executables = [executable("ochranka.py")]) file "c:\python32\lib\site-packages\cx_freeze\dist.py", line 365, in setup distutils.core.setup(**attrs) file "c:\python32\lib\distutils\core.py", line 136, in setup raise systemexit(gen_usage(dist.script_name) + "\nerror: %s" % msg) systemexit: usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help error: no commands supplied

this setup.py file:

from cx_freeze import setup, executable setup( name = "ochranka", version = "1.0", description = "test", executables = [executable("ochranka.py")])

i beginner, not know it.

you have pass command setup.py; in case, build*:

python setup.py build

i bet forgot build part.

*note: i'm not 100% sure build command want (it's been while since used cx_freeze). see the documentation.

python executable

Can't override ctrl+s in Firefox using jQuery Hotkeys -



Can't override ctrl+s in Firefox using jQuery Hotkeys -

i'm using jquery hotkeys plugin: http://code.google.com/p/js-hotkeys/

here code i'm using:

$(document).bind('keydown', 'ctrl+s', function(event) { alert('saving?'); homecoming false; });

in chrome works fine , ctrl+s default functionality over-ridden, in firefox fires alert , tries save html page.

i know there has someway work, wordpress in firefox let's press ctrl+s save.

any ideas?

seems bug in firefox alert breaks synchronicity of code. delaying alert seems workaround issue:

$(document).bind('keydown', 'ctrl+s', function(event) { settimeout(function() { alert('saving?'); }, 0); homecoming false; });

jsbin

here's test case prove bug claim.

$(document).bind('keydown', 'ctrl+s', function(event) { event.preventdefault(); });

the above (bin) prevent save dialog nicely. if add together alert either before or after it, save dialog will appear nevertheless if event.preventdefault() , event.stopimmediatepropagation() or return false:

$(document).bind('keydown', 'ctrl+s', function(event) { event.preventdefault(); event.stopimmediatepropagation(); alert('saving?'); homecoming false; });

bin

event.preventdefault() on own plenty prevent save dialog if there no alerts, alert possible prevent default action.

jquery jquery-plugins jquery-hotkeys

xml - Using query_to_xml in PostgreSQL with prepared statements -



xml - Using query_to_xml in PostgreSQL with prepared statements -

i'm using postgresql's function query_to_xml function generate xml of query result.

select * query_to_xml( 'select * some_table id = ?',true,false,'')

problem is, when utilize jdbc, prepared statements '?' ignored, postgres says:

"the column index out of range..."

is there possible solution pass parameters such query ?

try move ? outside string literal:

select * query_to_xml( 'select * some_table id = '||?,true,false,'')

xml postgresql prepared-statement

asynchronous - C#, Async Tasks and NetworkStream.BeginRead, how to guarantee the buffer won't be overwritten? -



asynchronous - C#, Async Tasks and NetworkStream.BeginRead, how to guarantee the buffer won't be overwritten? -

i'm trying write piece of code in c# read tcpclient asynchronously. here's code:

using system; using system.net; using system.net.sockets; using system.threading.tasks; class connection { private tcpclient socket; private networkstream socketstream; private byte[] buffer; private int bytesread; private task<int> readtask; public connection(tcpclient socket) { this.socket = socket; socketstream = socket.getstream(); buffer = new byte[4096]; readtask = task.factory.fromasync<byte[], int, int, int>( this.socketstream.beginread , this.socketstream.endread , this.buffer , 0 , this.buffer.length , null ); readtask.continuewith( (task) => { this.bytesread = (int)task.result; //do buffer. } , taskcontinuationoptions.onlyonrantocompletion ); } }

the problem asynchronous beginread seek write on connection object's buffer , 1 time new info arrives old 1 overwritten regardless of whether consumed or not. how should tackle problem? afaik should have closures can't figure out how!

you'd have have collection of buffers need process. allocate local buffer (var buffer = new byte[4096];) add together buffer collection (maybe stack) in continuation. you'll end having deal notifying thread process new info in queue.

for example:

class connection { private tcpclient socket; private networkstream socketstream; private int bytesread; private task<int> readtask; private stack<byte[]> bufferstoprocess; private readonly object lockobject = new object(); public connection(tcpclient socket) { this.socket = socket; socketstream = socket.getstream(); var buffer = new byte[4096]; readtask = task.factory.fromasync<byte[], int, int, int>( this.socketstream.beginread , this.socketstream.endread , buffer , 0 , buffer.length , null ); readtask.continuewith( (task) => { this.bytesread = (int) task.result; var actualbytes = new byte[bytesread]; array.copy(buffer, 0, actualbytes, 0, bytesread); lock (lockobject) { bufferstoprocess.push(actualbytes); } // todo: bufferstoprocess } , taskcontinuationoptions.onlyonrantocompletion ); } }

but, haven't presented plenty info tell need situation. e.g. why hasn't previous buffer been processed yet?

c# asynchronous

css - why margins collapse effect background images? -



css - why margins collapse effect background images? -

i have simple html , css following. notice bottom margin collapse between .outside box , .inside box. i don't understand why can't see background image when bottom margin collapse, background image should nil margin. :)

<div class="outside"> <div class="inside"> content </div> </div> .outside {background:url(http://blurfun.com/temp/images/bottom.png) left bottom no-repeat; padding-top:1px;} .inside { background:#00ccff; margin:0 0 10px 0; padding:0 0 20px 0;}

you experimenting vertical margin collapse between nested divs include overflow property (any value not equal visible job), , work ok

.outside { background:#ff0000 url(http://blurfun.com/temp/images/bottom.png) left bottom no-repeat; padding-top:1px; overflow:hidden; }

the reddish color added test result. of course of study can wiped.

detailed comment

your outside div uses sort of yellowish strip @ left bottom.

your within div has bottom margin of 10 px , there nil in between margin , outside div bottom margin. thats why collapsing.

you prevent happen including bottom padding or bottom border outside div. alter design intentions.

that why suggested using overflow property prevents vertical margin collapse , not interfere design.

in fiddle added left margin within div , reddish background outside div.

for didactic porpouse included transparent background within div.

vertical margins collapsing

prevented overflow:hidden

play it. delete overflow property , watch vertical margins collapsing. hope clear plenty you.

have day , enjoy coding :-)

css background margin

php - Passing data to model CI -



php - Passing data to model CI -

thanks @mischa helping me out here.

answer :

model :

function validate_login($username, $password) { $bcrypt = new bcrypt(17); $sql = "select * users username = ? "; $loginq = $this -> db -> query ($sql, array($username)); $database = $loginq->row(); $hash = $database->password; if ($bcrypt -> verify($password, $hash)){ homecoming $loginq; } }

controller :

function validate_credentials() { $this -> load -> library('form_validation'); $this -> load -> library('bcrypt'); $this -> form_validation -> set_rules('username', 'username', 'required|alpha_numeric|min_length[4]|max_length[15]'); $this -> form_validation -> set_rules('password', 'password', 'required|min_length[7]|alpha_dash|max_length[20]'); if ($this -> form_validation -> run() == false) { $this -> index(); } else { $this -> load -> library('bcrypt'); $this -> load -> model('login_model'); $username = $this -> input -> post('username'); $password= $this -> input -> post('password'); if ($loginq = $this -> login_model -> validate_login($username, $password)) { if ($activated = $this -> login_model -> activated($username)) { $session_array = array('username' => $this -> input -> post('username'), 'loggedin' => true); $this -> session -> set_userdata($session_array); redirect('staff_controller/index'); } else { $this -> session -> sess_destroy(); $this -> load -> view('accessdenied_view'); $this -> output -> _display(); die(); } } else { $this -> index(); } } }

what you're trying works when passing info views. have pass separate variables model. this:

function validate_login($username, $password) { $bcrypt = new bcrypt(17); $sql = "select * users username = ? limit ? "; $loginq = $this -> db -> query ($sql, array($username, 1)); $row = $loginq->result(); $hash = $row['password']; if ($brcrypt -> verify($password, $hash)){ homecoming $loginq; } }

of course of study means have alter controller code pass variables separately.

another alternative utilize $date['username'] , $data['password'] in model, wouldn't recommend that, because makes code harder read.

update create more clear:

controller:

$username = $this->input->post('username'); $password = $this->input->post('password'); $this->login_model->validate_login($username, $password);

model:

function validate_login($username, $password) { // etc. }

php mysql codeigniter select

javascript - Jquery - click on element generated by jquery function -



javascript - Jquery - click on element generated by jquery function -

i have jquery slider (nivo slider) generates next , prev button jquery. i'm trying add together hide() action div on buttons.

$(document).ready(function(){ $(".nivo-prevnav").live('click', function() { $("#slide3").hide(); }); });

.nivo-prevnav class generated jquery function of slider

any ideas on how can prepare because not working

.live() has been deprecated. utilize .on() instead:

$(document).on("click", ".nivo-prevnav", function() { $("#slide3").hide(); });

for improve performance, should phone call .on() on closest parent that's available before nivo plugin runs:

$("#nivo-wrapper").on("click", ".nivo-prevnav", function() { $("#slide3").hide(); });

you should alter #nivo-wrapper whatever element you're calling nivo slider on.

javascript jquery live

ms access - Search returning blanks -



ms access - Search returning blanks -

i had set next

private sub fncombobox_afterupdate() dim strwhere string if not isnull(me.fncombobox) strwhere = strwhere & " , id = " & me.fncombobox me.fncombobox = null end if docmd.openform "mailinglist", , , mid(strwhere, 6) end sub

to pull records query populate contact form. stands when i'm on search form drop downwards (or 1 can type in name) works fine see names in database. when record pulls of fields in contact form blank.

recently number of entries database deleted don't see how alter search function.

in property have row source set query 'findfn' , row source type set table/query.

perhaps i'm not giving plenty info here, if sees solution appreciated.

ms-access access-vba ms-access-2010

aggregate functions - count records in MYSQL table before certain spot -



aggregate functions - count records in MYSQL table before certain spot -

i have simple 2 column table in mysql: col1=sex , col2=name

i want find out how many records (count) exist prior particular record. in pseudo-mysql:

select count(*) before sex="m" , name="bob" sort name

assuming there 1 bob, , lots of male , female records.

how can count how many records meet criteria prior chosen record?

try this,

select count(*) table rownum < (select rownum table sex='m' , name='bob' limit 1);

mysql aggregate-functions

how to send soap request with certificate file and get response in java -



how to send soap request with certificate file and get response in java -

can give simple illustration sending soap request (which takes certificate file) , soap response in java.

thanks in advance

soap certificate

jquery - My Cordova Code Wont Work AJAX Call -



jquery - My Cordova Code Wont Work AJAX Call -

i dont know going on! cordova project wont allow me info ajax call! trying create phone call server user auth, now, focused on sending info server , having come alerted. do!

html, js, jquery

<head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="format-detection" content="telephone=no"> <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi"> <title>hello world</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" type="text/javascript"> </script> <script type="text/javascript"> $(document).ready(function () { $("form").submit(function () { var uname = document.getelementbyid("username").value; var pword = document.getelementbyid("password").value; var postdata = { username: uname, password: pword }; $.ajax({ url: "http://www.yellowcabsavannah.com/test.php", type: "post", data: postdata, async: false, datatype: 'json', contenttype: 'json', cache: false, success: function (data) { var d = json.parse(data); alert(d); } }); homecoming false; }); }); </script> </head> <body> <form action=""> <input type='text' id="username" name="username" placeholder="username"> <br> <input type='password' id="password" name="password" placeholder="password"> <br> <input type="submit" id="submit" value="login"> </form> </body>

php

echo json_encode(array("username" => $_post["username"], "password" => $_post["password"]));

jquery ajax cordova

javascript - Local Instance Reference -



javascript - Local Instance Reference -

in javascript have:

var person = (function () { function person(data) { info = $.extend({ name: "", age: 0 }, data); this.name = data.name; this.age = data.age; } homecoming person; })(); person.prototype.getname = function () { homecoming this.name; };

...if understand 'this' keyword correctly in javascript, can refer pretty much window object in-between (e.g. callers of object). question how heck write methods .getname() know i'll have reference value stored in person object's name property if never can sure 'this' refer in method? .getname() called , 'this' references window object - how value need then?

i'm asking because i've inherited code using pretty heavy prototyping , i'm running kinds of issues trying reference properties , methods on objects within themselves. seems i'm missing i've been looking scope, closures, , other patterns day , can't around this.

the value of this set language according how function/method called.

if have object method , do:

obj.method()

then, this set point object within of method() function.

but, if method this:

var p = obj.method; p();

then, because there no object reference in actual function call, this set either window or undefined depending upon whether in strict mode or not.

additionally, caller can specify want this set using obj.method.call() or obj.method.apply() or p.call() or p.apply() previous example. can these methods on mdn see more details how work.

so, in previous code, should work:

function person(data) { info = $.extend({ name: "", age: 0 }, data); this.name = data.name; this.age = data.age; } person.prototype.getname = function () { homecoming this.name; }; var p = new person({name:"john"}); var n = p.getname(); // homecoming "john"

working demo: http://jsfiddle.net/jfriend00/a7mkp/

if needed pass getname() 3rd party library won't phone call object context, there few options this:

anonymous function:

var myperson = new person("john"); callthirdparty(function() { // callback calls getname right object context homecoming myperson.getname(); });

using .bind() (not suported in older browsers):

var myperson = new person("john"); var boundfn = myperson.getname.bind(myperson); callthirdparty(boundfn);

from own method:

var self = this; callthirdparty(function() { // callback calls getname right object context homecoming self.getname(); });

fyi, there no reason self-executing function have surrounding person constructor function. makes code more complicated , adds no value in case.

javascript design-patterns

xml parsing - new to xml: Get children data into php variable -



xml parsing - new to xml: Get children data into php variable -

i need mean , lean solution confirmation form. retrieve contact e-mail address server xml response. follows:

<users> <user loginname="test1" owner="" alias="" usertype="paid" clienttype="obm" quota="10737418240" timezone="gmt+08:00 (cst)" language="en" datafile="1" datasize="1536" retainfile="0" retainsize="0" enablemssql="y" enablemsexchange="y" enableoracle="y" enablelotusnotes="y" enablelotusdomino="y" enablemysql="y" enableinfiledelta="y" enableshadowcopy="y" enableexchangemailbox="n" exchangemailboxquota="0" enablenasclient="y" enabledeltamerge="y" enablemsvm="n" msvmquota="0" enablevmware="n" vmwarequota="0" bandwidth="0" notes="" status="enable" registrationdate="1302687743242" suspendpaiduser="n" suspendpaiduserdate="20140503" lastbackupdate="1302699594652" enablecdp="y" enableshadowprotectbaremetal="y" enablewinserver2008baremetal="y" hostname="123.abc.com"> <contact name=""email="www@qqq.com"/> </user> … </users>

i got far have next results:

object(simplexmlelement)#7 (1) { [0]=> string(6) "company" } object(simplexmlelement)#8 (1) { [0]=> string(26) "email@address.ext" }

now need variables. seem unable accomplisch this. code here:

$request = "http://$server/obs/api/getuser.do? sysuser=$sysuser&syspwd=$syspwd&loginname=$logonname"; // execute api phone call , place xml output in array variable $response = simplexml_load_file($request); // retrieve loginname attribute array foreach($response->children() $child) { foreach($child->attributes() $data) { echo var_dump($data); } }

any newbie help appriciated. give thanks you

frank

here's simple illustration of reading name , email out of xml:

$response = simplexml_load_file($request); foreach($response->user $user) { foreach($user->contact $contact) { $name = $contact->attributes()->name; $email = $contact->attributes()->email; echo $name; echo $email; } }

demo

php xml-parsing

Different environment between server/localhost is changing the date format - php pdo mysql/oci -



Different environment between server/localhost is changing the date format - php pdo mysql/oci -

i'm having problems configure server environment, php pdo not formatting date localhost. test it, created 2 connections (using pdo oci , mysql). on localhost, oci , mysql runs normally, on server mysql maintains right format.

important detail: on sqldeveloper, shows info in same format localhost pdo/oci.

my localhost windows 7 , server linux debian x64.

what happening pdo/oci on server?

code:

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>documento sem título</title> </head> <body> <?php seek { $params->host = "172.0.0.0:1521"; $params->dbname = "geo"; $params->user = "root"; $params->pass = ""; $conn = new pdo("oci:dbname=//$params->host/$params->dbname;charset=utf8", "$params->user", "$params->pass"); $conn->setattribute(pdo::attr_errmode, pdo::errmode_exception); $stmt = $conn->prepare("select * tb_geooficio tipo = 1 , cadastro_im = 37693500 "); $stmt->execute(); $result = $stmt->fetchall(pdo::fetch_assoc); print_r($result); } catch(exception $e) { echo $e->getmessage(); } ?> <?php seek { $host = "200.0.0.1"; $user = "postmaster"; $pass = "^postm@ster^"; $db = "bd_controleinternet"; $conn = new pdo("mysql:host=$host; dbname=$db", "$user", "$pass"); $conn->setattribute(pdo::attr_errmode, pdo::errmode_exception); $stmt = $conn->prepare("select * tbl_secretaria sec_id = 7"); $stmt->execute(); $result = $stmt->fetchall(pdo::fetch_assoc); print_r($result); } catch(exception $e) { echo $e->getmessage(); } ?> </body> </html>

result:

in oracle, can utilize next alter default format used date conversion match mysql default:

alter session set nls_date_format='yyyy-mm-dd hh24:mi:ss';

this create oracle dates output mysql dates do.

you can create happen on every connect pdo:

$driver_options = array( pdo::mysql_attr_init_command => 'alter session...' ); seek { $dbh = new pdo($dsn, $user, $pw, $driver_options); } grab (pdoexception $e) { // handle exception }

both oracle , mysql have functions format dates explicitly, can phone call in expressions in query select-list. in oracle function to_char() , in mysql function date_format(), makes harder write rdbms-independent code.

re comment:

it seems nls_date_format can set globally in initorcl.ora, can set logon trigger, can set @ session level, etc. business relationship different behavior in 2 different environments. here's interesting post it:

http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::p11_question_id:351017764854

php mysql oracle pdo

javascript - How to load disqus when scroll to the bottom of the page? -



javascript - How to load disqus when scroll to the bottom of the page? -

i see jekyll powered blogs utilize disqus comments , comments section won't load untill scroll bottom of page.

how can approach this?

i've tried this:

<div id="disqus_thread"></div> <div id="disqus_loader" style="text-align: center"> <button onclick="load_disqus()">load disqus comments</button> <script> function load_disqus() { var dsq = document.createelement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = "http://[your-disqus-shortname].disqus.com/embed.js"; (document.getelementsbytagname('head')[0] || document.getelementsbytagname('body')[0]).appendchild(dsq); var ldr = document.getelementbyid('disqus_loader'); ldr.parentnode.removechild(ldr); } </script> </div>

a click button load disqus. i'm wondering how can load when scroll bottom of page.

with help javascript: how observe if browser window scrolled bottom?

var disqus_loaded = false; function load_disqus() { disqus_loaded = true; var dsq = document.createelement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = "http://[your-disqus-shortname].disqus.com/embed.js"; (document.getelementsbytagname('head')[0] || document.getelementsbytagname('body')[0]).appendchild(dsq); var ldr = document.getelementbyid('disqus_loader'); ldr.parentnode.removechild(ldr); } window.onscroll = function(e) { if ((window.innerheight + window.scrolly) >= document.body.offsetheight) { //hit bottom of page if (disqus_loaded==false){ load_disqus() }; } };

javascript disqus

c++ - Linked List not looping properly -



c++ - Linked List not looping properly -

here code:

void setupeachflechette(int numflechettes){ int = 0; int totalnum = 0; flechette* next; flechette* head; flechette* pend; flechette* temp; while(numflechettes != i){ double x = getrandomnumberx(); double y = getrandomnumberx(); double z = getrandomnumberz(); if(i != 0) temp = next; next = new flechette; next->setxyz(x, y, z); if(i == 0) head = next; else next->link = temp; i++; next->display(); } cout<<"\nthe total number of flechettes "<<totalnum<<endl<<endl; char yes = null; cout<<"ready? "; cin>>yes; = 0; next->link = null; next = head; while(next != null){ next->display(); next = next->link; i++; }

}

for reason, when looping through linked list, displaying first 4 nodes in list , continues repeat first four. cannot end on null can run through while(next != null) loop. wondering how come coding doesn't loop through of flechettes? reference, should loop through 20 different flechettes, not 4 flechettes 'i' number of times.

i think functions pretty self explanatory. if arent' allow me know , i'll explain them you.

thank of help

p.s. learning pointers , linked lists please bare me.

you not modifying variable totalnum before printing. think code should this

void setupeachflechette(int numflechettes){ int = 0; int totalnum = 0; flechette* next; flechette* head; flechette* pend; flechette* temp; srand (time(null)); while(numflechettes != i){ int x = rand(); int y = rand(); int z = rand(); if(i != 0) temp = next; next = new flechette; next->setxyz(x, y, z); if(i == 0) head = next; else temp->link = next; i++; next->display(); } totalnum = numflechettes; cout<<"\nthe total number of flechettes "<<totalnum<<endl<<endl; char yes; cout<<"ready? "; cin>>yes; = 0; next->link = null; next = head; while(next != null){ next->display(); next = next->link; i++; } }

in original code head node lastly node , head->next null

i expect initializing fellow member variable link null within constructor of flechette

c++ list

Pushing data across App Engine instances -



Pushing data across App Engine instances -

let's have several clients connected app engine using channel api. each client sends messages, should propagated other conntected clients according rules. tricky part clients may not same app engine instance.

is there way push info 1 instance others?

(yes, know memcache, require kind of polling.)

you're asking 2 questions here.

a. can force info 1 instance without utilize of polling. reply no.

b. can 1 client send messages server can propagated other clients? yes, , not require propagating messages other server-side instances.

consider channel api service. clients connected channel api service; not connected particular instance. hence instance can send messages client.

you'll need store channel tokens of clients in datastore, in way that's queryable match rules. your client makes http request send message server. the handler on server queries channel tokens needs propagate message (either memcache or datastore). the handler on server sends messages clients.

if list of destination clients extremely large, might want steps 3/4 in task queue operation can run longer.

google-app-engine

php - match array against database -



php - match array against database -

i have array(61) contain possible user names , want validate each 1 of them against database entry. using next code:

foreach(profilename("dev","db") $k => $val){ $db->query("select profile_name eb_user_account profile_name = '$val'"); if($db->numrows() == 0){ echo $val ." [match found @ key: {$k}]"; break; } }

profilename("dev","db") function holds array. code works nice , smooth , break match doesn't occur. curious if there faster , improve way perform task. please suggest me.

with thanks

you're looking combination of mysql's in operator, , phpimplode() function:

$query = sprintf( 'select profile_name eb_user_account profile_name in (%s)', implode(',', profilename("dev","db")) );

it's worth noting if you're using parameterized queries not possible pass list of arguments of arbitrary length. eg:

$stmt = $dbh->prepare('select * table col in (?)'); $rs = $stmt->execute(array(implode(',', $myarray)));

will fail. number of parameters in in statement must match number of placeholders. eg:

$stmt = $dbh->prepare('select * table col in (?,?,?)'); $rs = $stmt->execute(array(1,2,3));

on sec thought...

$myarray = profilename("dev","db"); $placeholders = array_fill(0, count($myarray), '?'); $query = sprintf( 'select profile_name eb_user_account profile_name in (%s)', implode(',', $placeholders); ); $stmt = $dbh->prepare($query); $rs = $stmt->execute($myarray);

should have parameterized correctly.

php arrays

ios - Change background of frame -



ios - Change background of frame -

i have "frame within frame" scenario. there 600x600 area within of main screen. color 600x600 area can visualize working. have tried using self.backgroundcolor = [uicolor whitecolor]; colors whole screen instead of 600x600 area.

what best way color background of 600x600 area?

- (id)initwithframe:(cgrect)frame { self = [super initwithframe: cgrectmake(84, 0, 600, 600)]; if (self) { //initialization code tilearray = [[nsmutablearray alloc]initwithcapacity: 9]; tile1 = [[tileview alloc] initwithframe:cgrectmake(100, 100, 128, 128) withimagenamed:@"yellow1.png"]; [self addsubview:tile1]; int x = [self frame].size.width; int y = [self frame].size.width; nslog(@" width: %i. height: %i.", x,y); } homecoming self; }

ios objective-c uiview frame

jsf - How to create a draggable marker? -



jsf - How to create a draggable marker? -

code below it's able create marker.

but want create draggable marker, problem is not sending click event server after marker has been created.

when markes created draggable flag set true.

any ideas?

class="lang-html prettyprint-override"><p:gmap id="gmap" center="36.890257,30.707417" zoom="13" type="hybrid" style="width:600px;height:400px" model="#{mapbean.emptymodel}" onpointclick="handlepointclick(event);" widgetvar="map"> <p:ajax event="markerdrag" listener="#{mapbean.onmarkerdrag}" update="messages" /> </p:gmap> <p:dialog widgetvar="dlg" effect="fade" effectduration="0.5" close="false" fixedcenter="true"> <h:form prependid="false"> <h:panelgrid columns="1"> <h:outputlabel value="are sure?"/> <f:facet name="footer"> <p:commandbutton value="yes" actionlistener="#{mapbean.addmarker}" update=":messages" oncomplete="markeraddcomplete()"/> <p:commandbutton value="cancel" onclick="return cancel()"/> </f:facet> </h:panelgrid> <h:inputhidden id="lat" value="#{mapbean.lat}"/> <h:inputhidden id="lng" value="#{mapbean.lng}"/> </h:form> </p:dialog> <script type="text/javascript"> var currentmarker = null; function handlepointclick(event) { console.log("click event"); console.log(event.marker); if (currentmarker == null) { document.getelementbyid('lat').value = event.latlng.lat(); document.getelementbyid('lng').value = event.latlng.lng(); currentmarker = new google.maps.marker({ position: new google.maps.latlng(event.latlng.lat(), event.latlng.lng()) }); map.addoverlay(currentmarker); dlg.show(); } } function markeraddcomplete() { //currentmarker = null; 1 can added. dlg.hide(); } function cancel() { dlg.hide(); currentmarker.setmap(null); currentmarker = null; homecoming false; } </script>

problem beingness caused attribute onpointclick of p:gmap. javascript callback function handlepointclickevent() in case.

so setted attribute el expression, after creating marker, look evaluate null, component p:gmap updates in ajax call, , draggable events work ;)

jsf primefaces primefaces-gmap

AngularJS - ForEach Accessing previous/next index array, Possible? -



AngularJS - ForEach Accessing previous/next index array, Possible? -

$scope.todos = [ {text:'learn', done:true}, {text:'build', done:false}, {text:'watch', done:false}, {text:'destroy', done:false}, {text:'rebuild', done:false}]; $scope.remaining = function() { var count = 0; angular.foreach($scope.todos, function(todo,i) { todo.text = 'want2learn'; todo.text[i+1] = todo.text; });

is possible foreach function accessing/set previous/next index array value of object, possible?

yes,

$scope.todos[i+1].text = todo.text;

you'll want guard against indexing past end of array though:

if(i < $scope.todos.length - 1) { $scope.todos[i+1].text = todo.text; }

angularjs

Passing a PHP Variable by URL Link in Wordpress -



Passing a PHP Variable by URL Link in Wordpress -

i trying pass variable mysql query page way of user clicking on link.

my query lists out in table number of reports. want user able click on study number in table send user page in plan run query based on study number variable sent in link.

here code prints out table rows:

while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['report_number'] . "</td>"; echo "<td class='tableleft'>" . $row['inspector'] . "</td>"; echo "<td class='tableleft'>" . $row['idate'] . "</td>"; echo "<td class='tableleft'>" . $row['vendor'] . "</td>"; echo "</tr>"; }

row 1 string $row['report_number'] variable want pass page way of link.

the problem having beingness executed on wordpress page page have link to, page in wordpress, not have .php page type.

i can not figure out how write link pass variable without .php in example:

<a href="edit_form.php?id=<?php echo $row['id']; ?>">edit</a>

you don't need .php in link. can utilize link example: http://site.com/page?id=2&something=10. so, clear, after link page want link to, type "?" , attach variables.

one more thing. have careful , post variable names in wordpress, because of them restricted , may truncated request.

hope helps.

php wordpress variables

php - Trying to load theme assets in pyrocms only using template and asset library -



php - Trying to load theme assets in pyrocms only using template and asset library -

in trying find out how have next work. i'm using template , asset libraries pyrocms help in aiding ci application , i’m trying figure out how can have dashboard images/css/js files in file construction below opposed regular assets folder in public_html folder since files pertain theme. far know code below used render specific css file. theme running smoothly when line below gets called renders nil if there no code line present.

i'm still trying find out why line isn't getting rendered. i'm still needing thought this.

<?php echo asset::css(‘bootstrap/bootstrap.min.css’); ?> public_html/ application/ themes/ supr/ assets/ js/ images/ css/ bootstrap/bootstrap.min.css views/ layouts/ default.php

asset::css() adds file want include list (array) of css files. need phone call asset::render_css() generate actual <link> html.

http://docs.pyrocms.com/2.1/manual/developers/tools/assets

php codeigniter pyrocms

c++ - Linker Error In C: undefined Reference to "method" c -



c++ - Linker Error In C: undefined Reference to "method" c -

i have c file trying build it's giving me linker error. reason beingness cannot find method definition defined @ other source files. trying here have definition of method beingness located source file. giving code main programme trying build. suggestions welcome , appreciated.

#include<stdio.h> #include<jni.h> #include<windows.h> #include <stdbool.h> #include "runnerclass.h" #include "unistd.h" #include "apr_getopt.h" #include "apr_portable.h" #include "c:\jnitest\src\common\error_debug.h" #include "c:\jnitest\src\common\event.h" #include "c:\jnitest\src\common\context.h" #include "c:\jnitest\src\common\alloc.h" #include "c:\jnitest\src\core\nxlog.h" #include "c:\jnitest\src\core\modules.h" #include "c:\jnitest\src\core\router.h" #include "c:\jnitest\src\core\ctx.h" #include "c:\jnitest\src\core\core.h" #define nx_logmodule nx_logmodule_core static nxlog_t nxlog; static apr_os_thread_t _nxlog_initializer = 0; static void winapi nx_win32_svc_main(dword argc, lptstr * argv); static void winapi nx_win32_svc_change(dword); extern void nx_logger_disable_foreground(); static void print_usage(); static void set_configfile(); static bool do_install = false; static bool do_uninstall = false; static service_status svc_status; static service_status_handle *svc_status_handle = null; jniexport void jnicall java_runnerclass_parse_1cmd_1line (jnienv * env, jobject jobj, jint argc, const jstring * const *argv){ char *opt_arg; int rv; apr_getopt_t *opt; int ch; static apr_getopt_option_t options[] = { { "help", 'h', 0, "print help" }, { "foreground", 'f', 0, "run in foreground" }, { "stop", 's', 0, "stop running instance" }, // { "reload", 'r', 0, "reload configuration of running instance" }, { "conf", 'c', 1, "configuration file" }, { "verify", 'v', 0, "verify configuration file syntax" }, { "install", 'i', 0, "install service available service manager" }, { "uninstall", 'u', 0, "uninstall service" }, { null, 0, 1, null }, }; apr_getopt_init(&opt, nxlog.pool, argc,(void *) argv); while ( (rv = apr_getopt_long(opt, options, &ch,(void *) &opt_arg)) == apr_success ) { switch ( ch ) { case 'c': /* configuration file */ nxlog.cfgfile = apr_pstrdup(nxlog.pool, opt_arg); break; case 'f': /* foreground */ nxlog.foreground = true; break; case 'h': /* help */ print_usage(); exit(-1); case 's': /* stop */ nxlog.do_stop = true; break; /* case 'r': // reload nxlog.do_restart = true; break; */ case 'v': /* verify */ nxlog.verify_conf = true; nxlog.ctx->ignoreerrors = false; break; case 'i': /* install */ do_install = true; break; case 'u': /* uninstall */ do_uninstall = true; break; default: print_usage(); exit(-1); } } set_configfile(); if ( (rv != apr_success) && (rv !=apr_eof) ) { throw(rv ,"could not parse options");/////////// } } jniexport void jnicall java_runnerclass_nx_1win32_1svc_1stop (jnienv * env, jobject jobj){ sc_handle service_manager = null; sc_handle service_handle = null; service_status status; nx_exception_t e; // connect service manager service_manager = openscmanager(null, null, sc_manager_all_access); if ( service_manager == null ) { nx_win32_error("cannot initialize access service manager"); } seek { service_handle = openservice(service_manager, "nxlog", service_all_access); if ( service_handle == null ) { nx_win32_error("couldn't open nxlog service"); } else { if ( queryservicestatus(service_handle, &status) ) { if ( status.dwcurrentstate != service_stopped ) { log_info("service currenty active - stopping service..."); if ( !controlservice(service_handle, service_control_stop, &status) ) { nx_win32_error("couldn't stop service"); } else { sleep(500); } } else { log_error("service stopped"); } } // close connection service closeservicehandle(service_handle); } // close connection service manager closeservicehandle(service_manager); } catch(e) { if ( service_handle != null ) { closeservicehandle(service_handle); } if ( service_manager != null ) { closeservicehandle(service_manager); } rethrow(e); } } jniexport void jnicall java_runnerclass_nx_1win32_1svc_1install (jnienv * env, jobject jobj){ sc_handle service_manager; sc_handle new_service = null; hkey regkey; uint32_t regtype = 0; char regvalbuf[1024]; uint32_t regvalbufsize = 1024; char servicename[1024]; // connect service manager service_manager = openscmanager(null, null, sc_manager_all_access); if ( service_manager == null ) { nx_win32_error("cannot initialize access service manager"); } //fixme utilize nxlog.ctx.user invoke service in createservice // default in case registry lookup fail apr_cpystrn(servicename, "\"c:\\program files\\nxlog\\nxlog.exe\" -c \"c:\\program files\\nxlog\\nxlog.conf\"", sizeof(servicename)); if ( regopenkey(hkey_local_machine, "software\\nxlog", &regkey) == error_success ) { if ( regqueryvalueex(regkey, "installdir", 0,(void *) &regtype,(unsigned char *) regvalbuf,(void *) &regvalbufsize) == error_success ) { if ( regtype == reg_sz ) { apr_snprintf(servicename, sizeof(servicename), "\"%snxlog.exe\"", regvalbuf); } } regclosekey(regkey); } // install new service new_service = createservice(service_manager, "nxlog", "nxlog", service_all_access, service_win32_own_process, service_auto_start, service_error_ignore, servicename, null, null, "eventlog\0", null, null); if ( new_service == null ) { nx_win32_error("couldn't create service"); } else { closeservicehandle(new_service); log_info("service installed"); } // close connection service manager closeservicehandle(service_manager); } jniexport void jnicall java_runnerclass_nx_1win32_1svc_1uninstall (jnienv * env, jobject jobj){ sc_handle service_manager = null; sc_handle service_handle = null; service_status query_status; nx_exception_t e; // connect service manager service_manager = openscmanager(null, null, sc_manager_all_access); if ( service_manager == null ) { nx_win32_error("cannot initialize access service manager"); } seek { // connect service service_handle = openservice(service_manager, "nxlog", service_all_access | delete); if ( service_handle == null ) { nx_win32_error("couldn't open nxlog service"); } else { // check service stopped if ( queryservicestatus(service_handle, &query_status) && (query_status.dwcurrentstate == service_running) ) { throw_msg("service running, please stop first."); } else { // can remove if ( deleteservice(service_handle) == false ) { nx_win32_error("couldn't delete service"); } else { log_info("service uninstalled"); } } // close connection service closeservicehandle(service_handle); } // close connection service manager closeservicehandle(service_manager); } catch(e) { if ( service_handle != null ) { closeservicehandle(service_handle); } if ( service_manager != null ) { closeservicehandle(service_manager); } rethrow(e); } } jniexport void jnicall java_runnerclass_nx_1win32_1svc_1main (jnienv * env, jobject jobj, jint argc, jstring *argv){ nx_context_t thread_context; nx_exception_t e; if ( _nxlog_initializer == 0 ) { // running service manager assert(nx_init((void *)&argc, (void *)&argv, null) == true); nxlog_init(&nxlog); nx_logger_disable_foreground(); } else if ( _nxlog_initializer != apr_os_thread_current() ) { // service dispatcher runs in new thread, need // initialize exception context. _nxlog_initializer = apr_os_thread_current(); memset(&thread_context, 0, sizeof(nx_context_t)); init_exception_context(&thread_context.exception_context); apr_threadkey_private_set(&thread_context, nx_get_context_key()); } log_debug("nx_win32_svc_main"); seek { // read config cache nx_config_cache_read(); log_debug("nxlog cache read"); // load dso , read , verify module config nx_ctx_config_modules(nxlog.ctx); log_debug("nxlog config ok"); // initialize modules nx_ctx_init_modules(nxlog.ctx); // initialize log routes nx_ctx_init_routes(nxlog.ctx); nx_ctx_init_jobs(nxlog.ctx); nx_ctx_restore_queues(nxlog.ctx); // setup threadpool nxlog_create_threads(&nxlog); // start modules nx_ctx_start_modules(nxlog.ctx); if ( nxlog.foreground != true ) { // register service manager svc_status_handle = (void *)registerservicectrlhandler("nxlog", nx_win32_svc_change); if ( svc_status_handle == 0 ) { nx_win32_error("registerservicectrlhandler() failed, couldn't register service command handler"); } // signal svc manager running svc_status.dwwin32exitcode = 0; svc_status.dwservicespecificexitcode = 0; svc_status.dwcheckpoint = 0; svc_status.dwwaithint = 0; svc_status.dwservicetype = service_win32; svc_status.dwcurrentstate = service_running; svc_status.dwcontrolsaccepted = service_accept_stop; if ( setservicestatus(*svc_status_handle, &svc_status) == false ) { nx_win32_error("cannot send start service status update"); } } //log_info(package"-"version_string" started"); } catch(e) { log_exception(e); log_error("exiting..."); svc_status.dwcurrentstate = service_stopped; setservicestatus(*svc_status_handle, &svc_status); exit(e.code); } // mainloop nxlog_mainloop(&nxlog, false); nxlog_shutdown(&nxlog); if ( nxlog.foreground != true ) { // signal stopped svc_status.dwcurrentstate = service_stopped; setservicestatus(*svc_status_handle, &svc_status); } nxlog_exit_function(); } jniexport void jnicall java_runnerclass_nx_1win32_1svc_1dispatch (jnienv * env, jobject jobj){ static service_table_entry svc_dispatch_table[] = { { "nxlog", null }, { null, null } }; if ( startservicectrldispatcher(svc_dispatch_table) == false ) { nx_win32_error("cannot start service dispatcher"); } } jniexport void jnicall java_runnerclass_nx_1win32_1svc_1start (jnienv * env, jobject jobj, jint argc, jstring argv){ sc_handle service_manager = null; sc_handle service_handle = null; service_status status; nx_exception_t e; // connect service manager service_manager = openscmanager(null, null, sc_manager_all_access); if ( service_manager == null ) { nx_win32_error("cannot initialize access service manager"); } seek { service_handle = openservice(service_manager, "nxlog", service_all_access); if ( service_handle == null ) { nx_win32_error("couldn't open nxlog service"); } else { if ( queryservicestatus(service_handle, &status) ) { if ( status.dwcurrentstate != service_running ) { log_info("service not running - starting service..."); if ( startservice(service_handle, argc,(void *) argv) == 0 ) { nx_win32_error("failed start nxlog service"); } } else { log_error("service running"); } } // close connection service closeservicehandle(service_handle); } // close connection service manager closeservicehandle(service_manager); } catch(e) { if ( service_handle != null ) { closeservicehandle(service_handle); } if ( service_manager != null ) { closeservicehandle(service_manager); } rethrow(e); } } jniexport void jnicall java_runnerclass_nxlog_1exit_1function (jnienv * env, jobject jbobj){ static bool exited = false; if ( exited == true ) { return; } exited = true; if ( _nxlog_initializer == 0 ) { return; } if ( nxlog.pid != (int) getpid() ) { return; } nx_ctx_free(nxlog.ctx); apr_pool_destroy(nxlog.pool); apr_terminate(); } /* callback service changes */ static void winapi nx_win32_svc_change(dword cmd) { // stop command handled switch ( cmd ) { case service_control_stop: log_warn("stopping nxlog service"); nxlog.terminate_request = true; // wait until service stops while ( svc_status.dwcurrentstate != service_stopped ) { sleep(500); } break; case service_control_interrogate: // ignore log_debug("ignoring unsupported service alter request: service_control_interrogate"); break; case service_control_pause: log_warn("ignoring unsupported service alter request: service_control_pause"); break; case service_control_continue: log_warn("ignoring unsupported service alter request: service_control_continue"); break; case service_control_paramchange: log_warn("ignoring unsupported service alter request: service_control_paramchange"); break; case 200: nxlog_dump_info(); break; case 201: { nx_ctx_t *ctx; log_info("got user command signal, switching debug loglevel"); ctx = nx_ctx_get(); ctx->loglevel = nx_loglevel_debug; } break; default: log_warn("ignoring unsupported service alter request (%d)", cmd); } } static void print_usage() { printf(/*package*/ "-" /*ersion_string*/ "\n" " usage: " " nxlog.exe [options]\n" " [-h] print help\n" " [-f] run in foreground, otherwise seek start nxlog service\n" " [-c conffile] specify alternate config file\n" " [-i] install service available service manager\n" " [-u] uninstall service\n" " [-s] stop running nxlog service\n" " [-v] verify configuration file syntax\n" ); // " [-r] reload configuration of running instance\n" } static void set_configfile() { hkey regkey; uint32_t regtype = 0; char regvalbuf[1024]; uint32_t regvalbufsize = 1024; if ( nxlog.cfgfile != null ) { return; } if ( regopenkey(hkey_local_machine, "software\\nxlog", &regkey) == error_success ) { if ( regqueryvalueex(regkey, "installdir", 0, (void *)&regtype, (unsigned char *) regvalbuf,(void *) &regvalbufsize) == error_success ) { if ( regtype == reg_sz ) { nxlog.cfgfile = apr_psprintf(nxlog.pool, "%sconf\\nxlog.conf", regvalbuf); } } regclosekey(regkey); } if ( nxlog.cfgfile == null ) { //nxlog.cfgfile = apr_pstrdup(nxlog.pool, nx_configfile); } }

what's exact error message getting???

from memory, jniexport not include ' extern "c" ' - if source file c++ function name mangled (and linker not find them).

c++ c linker-error undefined-reference