Monday, 15 April 2013

mysql - Foreign Key Tables Updates -



mysql - Foreign Key Tables Updates -

i started learning sql bit confused.

if have table has primary key : customerid & table b foreign key customerid

i added foreign key constraint using cascade foreign key should update or delete automatically when primary key deleted or updated.

however, works delete. when add together new record in primary field table, record not shown in foreign key table, why ?

corresponding rows updated or deleted in referencing table when row updated or deleted in parent table. cascade cannot specified if timestamp column part of either foreign key or referenced key. on delete cascade cannot specified table has instead of delete trigger. on update cascade cannot specified tables have instead of update triggers.

as mention in msdn. have mentioned update , delete operation of primary key table impact foreign key table's column. if insert made primary key, not affected foreign key. since main objective in primary key , foreign key relationship

"an each every record available in foreign key table, should contain corresponding record should nowadays in primay key table , vice versa not applicable".

if insert record foreign key table throws foreign referential integrity error. not allows insert record in foreign table unless , until corresponding record in primary key table.

for info take in next in msdn links

http://msdn.microsoft.com/en-us/library/ms179610.aspx

note:

if want accomplish functionality have write logic in stored procedure or trigger.

mysql sql sql-server constraints

javascript - D3JS SVG Viewbox Attribute -



javascript - D3JS SVG Viewbox Attribute -

i appending svg div , applying viewbox attribute of '0 0 100% 100%'. console stating error d3.js.

error: invalid value <svg> attribute viewbox="0 0 100% 100%"

here snippet code

d3.select("#chart") .append("svg") .attr("viewbox", "0 0 100% 100%");

is using percentages in viewbox attribute allowed?

a valid viewbox must consist of 4 numbers separated whitespace and/or comma. percentages not allowed.

javascript svg d3.js

indexing - MySQL fulltext inadequate. Creating an index would exceed 1000 bytes limit. What to do then? -



indexing - MySQL fulltext inadequate. Creating an index would exceed 1000 bytes limit. What to do then? -

here columns involved:

order_id int(8) tracking_number char(13) carrier_status varchar(128) recipient_name varchar(128) recipient_address varchar(256) recipient_state varchar(32) recipient_country_descr varchar(128) recipient_zipcode varchar(32)

getting error when seek create index of these columns:

mysql #1071 - specified key long; max key length 1000 bytes

what can given index of import database?

i need allow users search fields form single search field. i'm using query:

where concat(tracking_number, recipient_name, recipient_address, recipient_state, recipient_country_descr, recipient_zipcode, order_id, carrier_status) '$keyword1'

i've considered using fulltext match() against(). problem doesn't allow searches *keyword scratched , doing simple %keyword1% , %keyword2% each keyword.

but i've ran problem, query may slow cannot create single index containing columns searched.

what in situation?

a conventional b-tree index cannot help when you're searching keyword may in multiple columns, or may in middle of string.

think of telephone book. it's index on (last name, first name). if inquire search lastly name, helps lot book sorted way. if inquire search specific lastly name , first name combination, sort order of book helpful.

but if inquire search specific first name "bill", fact book sorted not helpful. occurrences of "bill" found anywhere in book, have read cover-to-cover.

likewise if inquire search anyone's name contains substring in middle of name or @ end. example, anyone's lastly name ends in "-son".

your illustration of using concat() on bunch of columns , comparing keyword in like pattern has same problem.

the solution utilize fulltext search engine, does offer ability search words anywhere in middle of strings. indexes in different way one-dimensional b-tree sorting.

if don't find mysql's fulltext index flexible plenty (and wouldn't blame because mysql's implementation pretty rudimentary), suggest @ more specialized search technology. here few free software options:

apache solr sphinx search xapian

this may mean have re-create searchable text mysql search engine, , maintain copying incrementally changes made mysql data. lot of developers this.

mysql indexing full-text-search limit

php - Preserve session after redirect? -



php - Preserve session after redirect? -

if var_dump session variable before calling redirect function, looks okay. however, after redirecting external clickabnk's payment page, i'm no longer able access session variable on page after payment.

i'm redirecting using function below :

public function redirect($url) { if(!headers_sent()) { //if headers not sent yet... php redirect header('location: '.$url); exit(); } else { //if headers sent... javascript redirect... if javascript disabled, html redirect. echo '<script type="text/javascript">'; echo 'window.location.href="'.$url.'";'; echo '</script>'; echo '<noscript>'; echo '<meta http-equiv="refresh" content="0;url='.$url.'" />'; echo '</noscript>'; exit(); } exit(); }

i'm using session_start on scripts i'm using sessions.

the page below 1 makes redirection

<?php if(!session_id()) session_start(); require_once("core.php"); $core = new coreoptions(); $options = $core->getchosenoptions(); $numoptions = count($options); $url = ""; switch($numoptions) { case 1: $url = $core->url1options; break; case 2: $url = $core->url2options; break; case 3: $url = $core->url3options; break; case 4: $url = $core->url4options; break; case 5: $url = $core->url5options; break; case 6: $url = $core->url6options; break; case 7: $url = $core->url7options; break; case 8: $url = $core->url8options; break; case 9: $url = $core->url9options; break; default: $url = $core->urldefaultoptions; break; } $core->redirect($url); exit(); ?>

below content of core.php

..... // options public function getchosenoptions(){ if (isset($_session["chosenoptions"])) homecoming $_session["chosenoptions"]; homecoming false; } // set options public function setchosenoptions($c) { $_session["chosenoptions"] = $c; } ..... // function redirect given page public function redirect($url) { if(!headers_sent()) { //if headers not sent yet... php redirect header('location: '.$url); exit(); } else { //if headers sent... javascript redirect... if javascript disabled, html redirect. echo '<script type="text/javascript">'; echo 'window.location.href="'.$url.'";'; echo '</script>'; echo '<noscript>'; echo '<meta http-equiv="refresh" content="0;url='.$url.'" />'; echo '</noscript>'; exit(); } exit(); } .....

the page below 1 want access $_session["chosenoptions"] from. why page below cannot access session variable although set correctly in page makes redirection? :

<?php if(!session_id()) session_start(); require_once("core.php"); $core = new coreoptions(); $uid = $core->uid(); $options = $core->getchosenoptions(); var_dump($options); // line shows null. why ? if (empty($options)) exit("options empty"); if (count((array)$options)>0) { seek { $conn = new pdo() // stripped conn info $conn->exec("set character set utf8"); // sets encoding utf-8 $conn->setattribute(pdo::attr_errmode, pdo::errmode_exception); $sql = "insert availablecommands (for_whom, oname, is_available) values (:fw, :on, :ia)"; $statement = $conn->prepare($sql); foreach($options $o) { $statement->bindvalue(":fw", $uid); $statement->bindvalue(":on", $o); $statement->bindvalue(":ia", 1); $count = $statement->execute(); $conn = null; // disconnect } } catch(pdoexception $e) { echo $e->getmessage(); } } $core->redirect("dashboard.php"); ?>

read session_id(). alter code accordingly:

<?php session_start(); if ( !isset($_session['oldid']) || $_session['oldid'] !== session_id() ) { // new session started ... ? } $_session['oldid'] = session_id(); ...

you need manually check whether current session old 1 or if new session has been started extent ever.

php session redirect

How to create a batch file that read parameters from another file -



How to create a batch file that read parameters from another file -

omeone help me create batch file read 3 parameters file e.g. config.conf in same directory?

the config file contains next information:

--url="jdbc:oracle:thin:@192.168.0.91:1521:xe" --username=testuser01 --password=passowrd01

i need set 3 prameters %url% , %username% , %pwd% in mig.bat file, working there parameters.

thanks , regards

if on 1 line , in same order...

@echo off setlocal set "cfgfile=c:\test.cfg" /f "tokens=2,4,6 delims==- " %%a in ('type "%cfgfile%"^| find /i "url"') ( set "url=%%~a" set "user=%%~b" set "pass=%%~c" ) echo %url% %user% %pass% endlocal

batch-file parameters parameter-passing configuration-files

android - Menu is null when activity gets recreated -



android - Menu is null when activity gets recreated -

i have inflated action bar menu in base of operations activity , modifying action bar items in base of operations activity. when alter orientation, menu null , thats why doesn't update action bar items. why null? here tried code:

@override public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.base, menu); mmenu = menu; homecoming true; } @override public boolean onoptionsitemselected(menuitem item) { // switch (item.getitemid()) { if (item.getitemid() == r.id.action_refresh) { refreshnewsdata(); homecoming true; } if (item.getitemid() == r.id.action_share) { sharenewsdata(); homecoming true; } if (item.getitemid() == r.id.action_favorite) { addfavorites(); homecoming true; } homecoming super.onoptionsitemselected(item); }

i have written code in base of operations activity. protected void showicons(int id) {

if (mmenu != null) { menuitem item = mmenu.finditem(id); item.setvisible(true); } } protected void hideicons(int id) { if (mmenu != null) { menuitem item = mmenu.finditem(id); item.setvisible(false); }

i'm using these methods update action bar menu items

you cannot update actionbar menu items directly. whenever want update menu items, create phone call invalidateoptionsmenu() this'll redraw action bar menus , create phone call onprepareoptionsmenu(). you'll have take care of menu items want show / hide within onprepareoptionsmenu().

android android-actionbar

Jquery for nested element -



Jquery for nested element -

i have div construction below (pls check image). wanted alter content of text box when click on relative button using jquery.

for example, if click button (1), content of textbox (1) should change. if click button (2) content of textbox (2) should change.

i have written next code, working button(2), when click button(1) changes content of both textbox.

$(document).on('click', '.b', function(e) { var = $(this).closest('.a'); $('.c', a).val("sample text"); });

i can solve having different classes different button / textbox. wanted have same class construction , solve problem.

if dom construction same in image, should work.

html:

<div class="a"> <input type="text" class="c"> <input type="button" value="button" class="b"> <div class="a"> <input type="text" class="c"> <input type="button" value="button" class="b"> </div> </div>

jquery:

$('.b').on('click', function () { //find parent .a var $a = $(this).parent(); //add in text $a.children(".c").val("sample text"); });

working example

jquery

java - BIRT csv emitter plugin error - -



java - BIRT csv emitter plugin error - -

i trying csv study using this well-known plugin , illustration documentation, throws exception. wonder why, because copied of code doc.

my code is:

import java.io.fileinputstream; import java.io.filenotfoundexception; import java.util.logging.level; import org.eclipse.birt.core.exception.birtexception; import org.eclipse.birt.core.framework.platform; import org.eclipse.birt.report.engine.api.engineconfig; import org.eclipse.birt.report.engine.emitter.csv.csvrenderoption; import org.eclipse.birt.report.engine.api.ireportengine; import org.eclipse.birt.report.engine.api.ireportenginefactory; import org.eclipse.birt.report.engine.api.ireportrunnable; import org.eclipse.birt.report.engine.api.irunandrendertask; public class runreport { static void runreport() throws filenotfoundexception, birtexception { string resourcepath = "c:\\users\\hpsa\\workspace\\my reports\\"; fileinputstream fs = new fileinputstream(resourcepath + "new_report_1.rptdesign"); ireportengine engine = null; engineconfig config = new engineconfig(); config.setenginehome("c:\\birtre\\birt-runtime-4_3_2\\"); config.setlogconfig("c:\\birtre\\", level.fine); config.setresourcepath(resourcepath); platform.startup(config); ireportenginefactory mill = (ireportenginefactory) platform.createfactoryobject(ireportenginefactory.extension_report_engine_factory); engine = factory.createreportengine(config); engine.changeloglevel(level.fine); ireportrunnable design = engine.openreportdesign(fs); irunandrendertask task = engine.createrunandrendertask(design); csvrenderoption csvoption = new csvrenderoption(); string format = csvrenderoption.output_format_csv; csvoption.setoutputformat(format); csvoption.setoutputfilename("newbirtcsv.csv"); csvoption.setshowdatatypeinsecondrow(true); csvoption.setexporttablebyname("secondtable"); csvoption.setdelimiter("\t"); csvoption.setreplacedelimiterinsidetextwith("-"); task.setrenderoption(csvoption); task.setemitterid("org.eclipse.birt.report.engine.emitter.csv"); task.run(); task.close(); platform.shutdown(); system.out.println("report generated sucessfully!!"); } public static void main(string[] args) { seek { runreport(); } grab (exception e) { e.printstacktrace(); } } }

i getting exception:

exception in thread "main" java.lang.noclassdeffounderror: org/eclipse/core/runtime/coreexception @ org.eclipse.birt.core.framework.platform.createplatformlauncher(platform.java:115) @ org.eclipse.birt.core.framework.platform.startup(platform.java:74) @ com.demshin.birttest.runreport.runreport(runreport.java:26) @ com.demshin.birttest.runreport.main(runreport.java:55) caused by: java.lang.classnotfoundexception: org.eclipse.core.runtime.coreexception @ java.net.urlclassloader$1.run(urlclassloader.java:366) @ java.net.urlclassloader$1.run(urlclassloader.java:355) @ java.security.accesscontroller.doprivileged(native method) @ java.net.urlclassloader.findclass(urlclassloader.java:354) @ java.lang.classloader.loadclass(classloader.java:425) @ sun.misc.launcher$appclassloader.loadclass(launcher.java:308) @ java.lang.classloader.loadclass(classloader.java:358) ... 4 more

i found bundle org.eclipse.core.runtime , registered in build path, getting same exception. indeed, there no coreexception.class in org.eclipse.core.runtime package. doing wrong?

setting engine home deprecated , of time prevent platform start, such in case. remove line:

config.setenginehome("c:\\birtre\\birt-runtime-4_3_2\\");

you have ensure birt runtime 4.3.2 in classpath of context. furthermore recommend seek generate native format such pdf first, , seek csv format.

java birt birt-emitter

html - div height not fully 100% at browser window in firefox but works great in chrome, ie & safari -



html - div height not fully 100% at browser window in firefox but works great in chrome, ie & safari -

i searched hours annoying issue on div 100% height of browser window. read 15 articles on stackoverflow , other forums none of them offered solution. gray bar @ left should 100% vertical browser window, not div content.

i tried min-height:100%, display:block, cell, table, table-cell, inline-block etc. can't work. , annoying part of it: worked @ beginning. apparently altered code in time saw problem late don't know worked.

the classes problem are:

maincontainer

.navigation .content

could please help trying/correct code? i'm pulling hair out here ;)

the page in question https://www.paybrick.com/example.php dead link

thank in advance!

use:

#maincontainer { display: table; height: 100%; min-height: 100%; /* seek give value in px instead of percent */ }

html css

back button logout symfony2 php error -



back button logout symfony2 php error -

i developing symfony2 app , have problem.

when log out of app, correctly, if press button of browser, go page in logged.

if write url go page, can't.

thanks in advance

this security.yml

security: encoders: simple\profilebundle\entity\user: algorithm: sha1 encode_as_base64: false iterations: 1 role_hierarchy: role_admin: [role_user] providers: main: entity: class: simple\profilebundle\entity\user property: username firewalls: secured_area: pattern: ^/ anonymous: ~ form_login: login_path: login check_path: login_check always_use_default_target_path: true default_target_path: /logged/portada logout: path: /logout target: /portada access_control: - { path: ^/logged, roles: role_admin }

i tested scenario in own symfony 2.3 applications , found in fact security flaw comes browser cache (not framework issue because it's out of command of framework.)

here discussion around issue. general (but not complete) solution send "expire" headers browser may (or may not) pay attending when utilize back-button behaviour. here's symfony docs http cache headers

i have not tested in 2.5.* environment yet, may have been addressed in later version of symfony.

php symfony2 button logout back

javascript - Dynamic Date and Time -



javascript - Dynamic Date and Time -

i trying build appointment form. have used xdsoft jquery date , time picker. after selecting date checks appointments time , returns available time schedule ajax. when alert info result dont info in picker. help helpful. tnx

here's tried

demo without ajax

http://jsfiddle.net/4ppj2/1/

html

<form id="schedule_time_form" method="post" action="#"> <label>select date</label> <input type="text" id="datepicker_time" name="datepicker_time" class="input-medium"> <label>select time from</label> <input type="text" id="timepicker1_time" disabled name="timpepicker1_time" class="input-small"> </form>

jquery

var logic = function( currentdatetime ){ if( currentdatetime ){ var day = "day="+currentdatetime.getday(); $.ajax({ url : "helper/getdate.php", type: "post", info : day, success: function(data, textstatus, jqxhr) { $('#timepicker1_time').datetimepicker({ datepicker:false, format:'h:i', allowtimes:[data] }); }, error: function (jqxhr, textstatus, errorthrown) { } }); } }; $('#datepicker_time').datetimepicker({ mindate: 0, timepicker:false, format:'y-m-d', onchangedatetime:logic, inline: true, });

javascript jquery ajax datetime

kineticjs, local svg, drawHitFromCache, Internet Explorer 10 SecurityError -



kineticjs, local svg, drawHitFromCache, Internet Explorer 10 SecurityError -

i took standard drawhitfromcache demo (http://www.html5canvastutorials.com/kineticjs/html5-canvas-pixel-detection-with-kineticjs/) , , replaced 1 of images .svg image (gray polygon) .

live demo : http://preview.yw.sk/kineticdrawhit/

source : http://preview.yw.sk/kineticdrawhit/kineticdrawhitsvg.rar

fiddle : http://jsfiddle.net/5cpyj/ - not work since of local images need.

so thing changed src svg image , added 'drawhitfromcache', works in chromefirefox, in net explorer :

kinetic warning: unable draw nail graph cached scene canvas. securityerror

but utilize local image (monkey.svg) no external resource, why pops securityerror ? since of error image drawn not react on mouse enter. png files right.

jq.browser - removed jquery, plugin jquery , + need canvg library fo magic . canvg need @ leat 207 revision fixed draw bug . https://code.google.com/p/canvg/source/detail?r=207 , can download latest svn installed (http://canvg.googlecode.com/svn/trunk/)

solution security error in warious browsers ie10+ , safari, ipad etc, solution utilize canvg create png images current resolution svg images .

var pngfallbackenabled = null; project.pngfallbackcheck = function () { if (pngfallbackenabled == null) { if (typeof enablesvgpngfallback != 'undefined' && enablesvgpngfallback == true && typeof jq.browser != 'undefined' && (jq.browser.mobile == true || jq.browser.msie == true || jq.browser.mozilla == true)) { pngfallbackenabled = true; console.log('png fall-back enabled'); } else { pngfallbackenabled = false; } } homecoming pngfallbackenabled; }; var cachedpngimages = []; var currentgamecanvasratio = null; /** require canvg library*/ project.createpngimagefromsvgimage = function (svglink, width, height, cacheindex) { var extension = svglink.split('.').pop(); if (extension == "png" || extension == "jpg" || extension == "gif" || extension == "jpeg" || extension == "gif") { homecoming svglink; } if (typeof cacheindex != 'undefined' && typeof cachedpngimages[cacheindex] != 'undefined') { homecoming cachedpngimages[cacheindex]; } var canvas = document.getelementbyid("pngdrawercanvas"); var canvascontext = canvas.getcontext('2d'); if (canvas == null) { var canvaselement = document.createelement('canvas'); canvaselement.setattribute("id", "pngdrawercanvas"); canvaselement.setattribute("width", "200"); canvaselement.setattribute("height", "200"); canvaselement.setattribute("style", "display: none"); document.body.appendchild(canvaselement); canvas = document.getelementbyid("pngdrawercanvas"); } if(currentgamecanvasratio == null){ currentgamecanvasratio = window.module.canvas.getcurrentratio(); /*custom function ratio current screen resolution*/ } var imagewidth = math.floor(width * currentgamecanvasratio); var imageheight = math.floor(width * currentgamecanvasratio); canvas.width = imagewidth; canvas.height = imageheight; jq('#pngdrawercanvas').css('width', imagewidth); jq('#pngdrawercanvas').css('height', imageheight); //canvg('pngdrawercanvas', svglink, 0, 0); canvascontext.drawsvg(svglink, 0, 0, imagewidth, imageheight); var img = canvas.todataurl("image/png"); if (typeof cacheindex != 'undefined') { cachedpngimages[cacheindex] = img; } homecoming img; };

svg kineticjs internet-explorer-10 local securityexception

jquery - Javascript Function Not Executed Correctly -



jquery - Javascript Function Not Executed Correctly -

i have app uses html & javascript, , isnt working correctly. video describes bug:

http://vk.com/video170263591_169020196

and code goes this:

function load() { $("#load").show(0,function(){ console.log('spinner loaded'); }); } function unload() { $("#load").hide(); console.log('load ended'); } function server(datasend) { var response; var posturl = "http://mailsnitch.ipx-il.com/get/index.php"; $.ajax({ type: 'post', url: posturl, datatype: 'json', timeout:4000, async: false, data: datasend, beforesend : load(), success: function(valueable){ console.log('success'); response = valueable; console.log(valueable); unload(); }, error: function(jqxhr, exception) { console.log('error'); if (jqxhr.status === 0) { alert('not connect.\n verify network.'); } else if (jqxhr.status == 404) { alert('requested page not found. [404]'); } else if (jqxhr.status == 500) { alert('internal server error [500].'); } else if (jqxhr.status == 502) { alert('bad gateway [502].'); } else if (exception === 'parsererror') { alert('requested json parse failed.'); } else if (exception === 'timeout') { alert('time out error.'); } else if (exception === 'abort') { alert('ajax request aborted.'); } else { alert('uncaught error.\n' + jqxhr.responsetext); } unload(); }, }); homecoming response; }

and log in function:

function login(redirect) { load(); if(redirect) { var email = escapehtml(document.getelementbyid("login_email").value); var password = escapehtml(document.getelementbyid("login_password").value); } else { if(localstorage.getitem("email") == null) document.location.href = 'login.html'; var email = escapehtml(localstorage["email"]); var password = escapehtml(localstorage["password"]); } if(email != "" && password != "") { if(validateemail(email)) { var valuable = server('login=&email='+email+'&password='+password);

the problem is: when loading "login" function, load function should run, isnt running. though functions order is:

load()

server() { before: load(); , ajax... }

within console, can see "load successful" shows @ same milisecond "ajax success", means load waiting ajax load before doing function.

thx helpers.

you're calling function immediately, not referencing it, should be

$.ajax({ type: 'post', url: posturl, datatype: 'json', timeout:4000, async: false, data: datasend, beforesend : load, ....

adding parenthesis calls function , returns result, undefined, $.ajax phone call sees.

also note setting async : false defeats entire purpose of asynchronous javascript , xml, made synchronous instead.

edit

your code should more this

function load() { $("#load").show(); } function unload() { $("#load").hide(); } function server(datasend) { homecoming $.ajax({ type : 'post', url : "http://mailsnitch.ipx-il.com/get/index.php", datatype : 'json', timeout : 4000, info : datasend, beforesend : load }); } function login(redirect) { if(redirect) { var email = escapehtml(document.getelementbyid("login_email").value); var password = escapehtml(document.getelementbyid("login_password").value); } else { if(localstorage.getitem("email") == null) { document.location.href = 'login.html'; } var email = escapehtml(localstorage["email"]); var password = escapehtml(localstorage["password"]); } if(email != "" && password != "") { if(validateemail(email)) { server({login : '', email: email, password: password}).done(function(valuable) { // utilize valuable here }).always(unload); } } }

javascript jquery ajax

c - treating an array as a single variable -



c - treating an array as a single variable -

code 1:

. . int main() { char ch1[3]; ch1[0]=ch1[1] = null; ch1[2]=0x01; ch1[2] = ch1[2]<<2; printf("%u", ch1[2]); system("pause"); homecoming 0; } . .

the output of code:1 4 (as expected).

code 2:

. . int main() { char ch1[3]; ch1[0]=ch1[1] = null; ch1[2]=0x01; *ch1 = *ch1<<2; printf("%u", ch1[2]); system("pause"); homecoming 0; } . .

but output of code:2 1 not expected! in line 6 of code:2, modification done changing ch1[2] = ch1[2]<<2; *ch1 = *ch1<<2;. have tried treating char array 1 numerical value , have done << operation; believe method incorrect. there right method treat array single numerical value basic mathematical operations?

update 1:

i have changed code following:

int main() { char ch1[3]; ch1[0]=ch1[1] = null; ch1[2]=0x01; *(ch1+2) = *(ch1+2)<<9; printf("%u", ch1[1]); system("pause"); homecoming 0; }

now output:0. shouldn't getting output 2 (i.e. 2^(9-8))? still, how treat array single numerical value?

right; actual question if possible treat array single value or not; considering ch1[0], ch1[1], ch1[2] single block of memory of 24 bits.

the type of pointer important ch1 similar pointer char- char*. when *ch1 refering char ch1 pointing at. if want treat entire array number need cast integer, problematic because array has 3 bytes, , integer has 4, top byte of x in illustration below pointing at, undefined

int main() { char ch1[3]; ch1[0]=ch1[1] = 0; ch1[2]=0x01; int *x = (int*)ch1; *x <<= 2; printf("%u", ch1[2]); system("pause"); homecoming 0; }

c arrays pointers operators

c++ - Copy the address of all elements using std::copy -



c++ - Copy the address of all elements using std::copy -

i'm trying obtain address of elements of given collection , re-create them std::set. basically, instead of

std::set<t> s1; std::copy(first1, last1, std::inserter(s1, s1.begin()));

i'd insert addresses. like:

std::set<std::add_pointer<t>> s1; std::copy(reference_iterator(first1), reference_iterator(last1), std::inserter(s1, s1.begin()));

here, reference_iterator iterator returning address of element, instead of element, opposed boost indirect_iterator does. there standard way it? many thanks.

use std::transform re-create modification.

std::transform(first1, last1, std::inserter(s1, s1.begin()), std::addressof<t>);

c++ boost iterator std

How do I replace Hibernate with DataNucleus JPA in a JHipster project? -



How do I replace Hibernate with DataNucleus JPA in a JHipster project? -

i'm building on top of of jhipster template, uses spring boot, hibernate , jpa extensively. however, have object construction requires can traverse different levels of object tree without returning entire tree each time, i want utilize datanucleus fetch-group capability going forward.

in order create switch, modifications need create in jhipster-based project?

pieces of code change: pom.xml main/java/resources/logback.xml reload configs user persistence classes cache annotations should switch hibernate datanucleus

---answer not finished----

datanucleus jhipster

php - Save Bag for Later in Magento 1.8? -



php - Save Bag for Later in Magento 1.8? -

there default button - clear shopping bag in magento 1.8,

but don't need button, need button 'save handbag later' - possible in magento?

below code frontend\mystore\default\template\checkout/cart.phtml

<div class="row box-cart-control"> <ul class="items-button-cart pull-right"> <li class="col-lg-4"><button type="submit" name="update_cart_action" value="update_qty" title="<?php echo $this->__('update shopping bag'); ?>" class="btn-update btn btn-primary button-cart-control"><?php echo $this->__('update shopping bag'); ?></button></li> <?php if($this->getcontinueshoppingurl()): ?> <li class="col-lg-4"><button type="button" title="<?php echo $this->__('continue shopping') ?>" class="btn-continue btn btn-primary button-cart-control" onclick="setlocation('<?php echo $this->getcontinueshoppingurl() ?>')"><?php echo $this->__('continue shopping') ?></button></li> <?php endif; ?> <li class="col-lg-4"><button type="submit" name="update_cart_action" value="empty_cart" title="<?php echo $this->__('clear shopping bag'); ?>" class="btn-empty btn btn-primary button-cart-control" id="empty_cart_button"><?php echo $this->__('clear shopping bag'); ?></button></li> </ul> </div>

what should utilize 'save handbag later' replace below?

button type="submit" name="update_cart_action" value="empty_cart"

php magento magento-1.8

java - Servlet to Servlet Communication -



java - Servlet to Servlet Communication -

i'm making java web application i'm newbie in java.

i have servlet (/locatemodules) seek find other servlets in server (/modules/*), servlet find name of other servlets (/modules/logout, /modules/invoice, etc), need properties , phone call methods discovered servlets, properties , methods same in servlets.

calling like: discoveredservlet.getmenuitem();

getmenuitem returns values, menuname, menuurl, sidemenu[], sideurl[], etc... create menu item in web application dinamically, discovered servlets has post , when called on main menu.

i'm find inter servlet communication articles, unfourtunally doesn't work api 2.2 , later.

how can solution this?

import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class loaded extends httpservlet { public void doget(httpservletrequest req, httpservletresponse res) throws servletexception, ioexception { res.setcontenttype("text/plain"); printwriter out = res.getwriter(); servletcontext context = getservletcontext(); enumeration names = context.getservletnames(); while (names.hasmoreelements()) { string name = (string)names.nextelement(); servlet servlet = context.getservlet(name); out.println("servlet name: " + name); out.println("servlet class: " + servlet.getclass().getname()); out.println("servlet info: " + servlet.getservletinfo()); out.println(); } } }

servlets classes supposed take requests on servers , respond them.

as making httpservlet supposed take http request via http methods get , post (so methods doget() , dopost() in servlets), , servlet processes request , sends http response.

if want communicate between servers should set attributes using setattribute() method , redirect (using response.sendredirect()) or forwards request servlet , utilize getattribute() method receive values.

servlets not meant used normal classes, create objects of servlet class , phone call methods.

java servlets

ruby on rails - Active Admin after login redirect to admin site not requested url -



ruby on rails - Active Admin after login redirect to admin site not requested url -

i implemented active admin in rails 3.2 application. problem when request restricted resource application redirect me login page after login redirect user admin section of site. want redirect after login requested url. how can resolve issue. seek below alter not work.

class applicationcontroller < actioncontroller::base protect_from_forgery private def after_sign_in_path_for(resource) user_path(resource) end end class applicationcontroller < actioncontroller::base protect_from_forgery private def after_sign_in_path_for(resource) stored_location_for(resource) || root_path end end

ruby-on-rails ruby-on-rails-3 devise activeadmin

c# - "is a field but is being treated like a type" error -



c# - "is a field but is being treated like a type" error -

this question has reply here:

“is field , used type” error 2 answers

i trying create array of lists of structs. initialise list of structs so:

list<mystruct> mydata = new list<mystruct>();

but when seek create array (example beingness array 1 element), ie

list<mystruct>[] mydata = new list<mystruct>[1]; mydata[0] = new list<mystruct>();

i error saying

mydata field beingness treated type.

i've looked @ reply don't understand difference is: answer

is there fundamental difference how c# treats structs, compared integers?

thanks help.

included clarity, code in full:

namespace my_project { using tradingtechnologies.ttapi; public partial class form1 : form { list<timeandsalesdata>[] mydata = new list<timeandsalesdata>[10]; //here believe making mistake: mydata[1] = new list<timeandsalesdata>(); //i error mydata field beingness used type. public form1() { initializecomponent(); } } } namespace tradingtechnologies.ttapi { // summary: // represents single trade transaction instrument public struct timeandsalesdata { public timeandsalesdata(instrument instrument, bool isoverthecounter, cost tradeprice, quantity tradequantity, tradedirection direction, datetime timestamp); // summary: // gets side trade public tradedirection direction { get; } // // summary: // gets instrument associated trade transaction public instrument instrument { get; } // // summary: // gets whether trade over-the-counter (otc) public bool isoverthecounter { get; } // // summary: // gets time trade occurred public datetime timestamp { get; } // // summary: // gets cost @ trade occurred public cost tradeprice { get; } // // summary: // gets quantity traded in trade transaction public quantity tradequantity { get; } } }

you have code floating around within class definition. needs within of method or constructor of sort:

public partial class form1 : system.windows.forms.form { public form1() { initializecomponent(); list<timeandsalesdata>[] mydata = new list<timeandsalesdata>[10]; mydata[1] = new list<timeandsalesdata>(); } }

if want mydata field , not local variable, need just declare @ top level of class, initialize in constructor/method.

c#

php - filtering search results using multiple parameters from $_GET -



php - filtering search results using multiple parameters from $_GET -

i working on faceted search scheme in php uses arguments $_get filter search results. i'm having problem returning right search results. core of problem revolves around next (wrong) code:

$hits = results_from_db(); $results = array(); foreach ($hits $hit) { if (isset($_get['online']) && !in_array('online', $hit)){ continue; } elseif (isset($_get['on-site']) && !in_array('on-site', $hit)){ continue; } elseif (isset($_get['scheduled']) && !in_array('scheduled', $hit)){ continue; } elseif (isset($_get['on-demand']) && !in_array('on-demand', $hit)){ continue; } $results[] = $hit; } homecoming $results;

if user selects more 1 alternative - 'online' , 'scheduled' - $results should contain of hits have 'online' and/or 'scheduled' inclusive. if user selects no options, of results should returned.

in above code, however, results won't homecoming if more 1 alternative selected.

i sense simple logic problem, i'm still stumped.

as per comment, sounds job database, here solution:

if( foreach ($hits $hit) { $matches = false; if (isset($_get['online']) && in_array('online', $hit)){ $matches = true; } elseif (isset($_get['on-site']) && in_array('on-site', $hit)){ $matches = true; } elseif (isset($_get['scheduled']) && in_array('scheduled', $hit)){ $matches = true; } elseif (isset($_get['on-demand']) && in_array('on-demand', $hit)){ $matches = true; } if($matches){ $results[] = $hit; } }

edit per comment, total solution:

$hits = results_from_db(); $categories = array( 'online', 'on-site', 'scheduled', 'on-demand' ); $optionselected = false; foreach ($categories $cat) { if(isset($_get[$cat])){ $optionselected = true; break; } } if(!$optionselected){ //return info homecoming $hits; } $results = array(); foreach ($hits $hit) { $matches = false; foreach ($categories $cat) { if (isset($_get[$cat]) && in_array($cat, $hit)){ $matches = true; break; } } if($matches){ $results[] = $hit; } } homecoming $results;

this more extended incorporate future categories adding $categories array

php

javascript - moving the caption of a tooltip -



javascript - moving the caption of a tooltip -

can please tell me how arrange caption above image in jsfiddle below can not seem it. caption below image. in advance.

sample code

<script type="text/javascript"> $(function(){ $("ul.thumb li").hover(function() { $(this) .css('z-index', '10') .find('img').addclass("hover") .stop() .animate({ margintop: '-150px', marginleft: '-150px', top: '50%', left: '50%', width: '300px', height: '300px', padding: '20px' }, 200, function() { var $this = $(this), h = $this.height(); $caption = $('<div class="caption">' + this.title + '</div>') .css('top', h.tostring() + 'px'); $this.after($caption); }); }, function() { $('.caption').remove(); $(this) .css('z-index', '0') .find('img').removeclass("hover") .stop() .animate({ margintop: '0', marginleft: '0', top: '0', left: '0', width: '200px', height: '200px', padding: '5px' }, 400); }); }); </script>

i hope helps

here updated fiddle.

the relevant line one:

.css('top', -h.tostring() + 'px');

it positions div text, , alter position above image, placed negative sign in front end of h.tostring(). finely adjust position multiplying h.tostring() coefficient -.8 or -.92 create finer adjustments. may problematic putting above image, because you'll have adjust position based on height of text div.

javascript jquery html css tooltip

reload - How to make a webpage link load without reloading the whole webpage -



reload - How to make a webpage link load without reloading the whole webpage -

sorry confusing title, not think of how describe in words. beingness said, i'll seek show mean. if go www.icracked.com/repair can click device, , it'll load next set of options without reloading whole webpage. want same thing, can't figure out how to, if can point me right direction, appreciate it.

are trying show user multiple bits of information, click on different parts of web page? or need gather , manipulate user input, , later? (for instance, user clicks on 'iphone', clicks on '4s', , want write code execute based on choice.)

if first scenario want, consider using css create hidden divs. these can triggered events such click or mouseover.

without knowing bit more detail trying do, may not possible me reply like.

i hope helps.

webpage reload

android - Using MediaPlayer with setOnPreparedListener -



android - Using MediaPlayer with setOnPreparedListener -

i'm trying set onpreparedlistener, error:

the method setonpreparedlistener(mediaplayer.onpreparedlistener) in type mediaplayer not applicable arguments (new onpreparedlistener(){})

dv global mediaplayer.

string url = "<myurl>"; dv = new mediaplayer(); dv.setaudiostreamtype(audiomanager.stream_music); dv.setdatasource(url); dv.prepareasync(); dv.setonpreparedlistener(new onpreparedlistener() { public void onprepared(mediaplayer mp) { mp.start(); } });

add code:

import android.media.mediaplayer.onpreparedlistener;

alternatively, can use:

new mediaplayer.onpreparedlistener() {...}

sourced this comment @squonk

android android-mediaplayer

function - I can't sum the values of a column whose values are generated using if statement -



function - I can't sum the values of a column whose values are generated using if statement -

sum function not helping me sum column, tried manually come in cells not help. if there values in column, 0 reply in cell have entered sum function.

i have next status 10 cells in column =if(b1=0,20,2) , sum cells =sum(a1:a10). column autoupdated when b1 updated , sum updated when values of cells change.

if have different workbooks if changes =if([d.xlsx]tabelle1!$a$1=0,2,10). d.xslx name of sec workbook check value tabelle1 name of sheet , $a$1 checked cell.

function excel-formula excel-2007

php - select data for "some value" if data null then select data for field IS NULL -



php - select data for "some value" if data null then select data for field IS NULL -

here have query returns cost respective condition... doing now... here haveing conditon checking event_id null or event_id = "some value" ... think wrong want fetch info rows if there info exist "some value" should homecoming info if there no info "some value" should check null..

here want query info event_id

1) event_id int should homecoming info event_id

2) if (1) info null theen should select info event_id null

how can thing query

query 1 (checks event_id) :

select `tpliv`.`ticket_sub_type_id` `ticketsubtypeid` , `tst`.`ticket_sub_type` `ticketsubtype` , `tpliv`.`price` `ticketprice` , `tpliv`.`tax` `tickettax` , `tpliv`.`ticket_price_list_item_vendor_id` `ticketpricelistid` , `tpliv`.`ticket_price_list_id` `ticketpricelist` , `tpliv`.`fee` `ticketfee` , `tpliv`.`status` `status` `ticket_price_list_item_vendor` `tpliv` bring together `ticket_price_list` `tpl` on tpl.ticket_price_list_id =tpliv.ticket_price_list_id , tpl.event_group_id = "45" , tpl.vendor_id = "442" , tpl.dinner_category_id null , tpl.status =1 , tpl.event_id = "39152" , tpl.seat_section_id null , tpl.vendor_sub_group_id null , tpl.vip_seat_id null , tpl.seat_block_section_id null , tpl.is_upsale null bring together `ticket_sub_types` `tst` on tst.ticket_sub_type_id = tpliv.ticket_sub_type_id , tst.status =1 bring together `ticket_sub_type_vendor` `tstv` on tstv.ticket_sub_type_id=tst.ticket_sub_type_id , tstv.status =1 limit 0 , 30

query 2 (checks event_id null) :

select `tpliv`.`ticket_sub_type_id` `ticketsubtypeid` , `tst`.`ticket_sub_type` `ticketsubtype` , `tpliv`.`price` `ticketprice` , `tpliv`.`tax` `tickettax` , `tpliv`.`ticket_price_list_item_vendor_id` `ticketpricelistid` , `tpliv`.`ticket_price_list_id` `ticketpricelist` , `tpliv`.`fee` `ticketfee` , `tpliv`.`status` `status` `ticket_price_list_item_vendor` `tpliv` bring together `ticket_price_list` `tpl` on tpl.ticket_price_list_id =tpliv.ticket_price_list_id , tpl.event_group_id = "45" , tpl.vendor_id = "442" , tpl.dinner_category_id null , tpl.status =1 , tpl.event_id null , tpl.seat_section_id null , tpl.vendor_sub_group_id null , tpl.vip_seat_id null , tpl.seat_block_section_id null , tpl.is_upsale null bring together `ticket_sub_types` `tst` on tst.ticket_sub_type_id = tpliv.ticket_sub_type_id , tst.status =1 bring together `ticket_sub_type_vendor` `tstv` on tstv.ticket_sub_type_id=tst.ticket_sub_type_id , tstv.status =1 limit 0 , 30

so want execute query 1 if homecoming info null execute query , retrieve data...

is possible handle these queries in 1 query...

i want combine 2 query in 1 query .... next scenario 1) in first query if info (not null) not have check sec query 2) if info null in first query should homecoming info query 2 ... 3) want combine both queries , create 1 query real world scenario ( why can not utilize **(event_id null or event_id = "soem value")** ) -> if "some event_id" 3 rows in homecoming info ->and event_id null 2 rows ... -> in scenario want 3 rows come "some event id" , dont need other data... ->if "some event_id" null info , want utilize query 2 retrieve data..

php mysql select null

python - Suddenly, No module named models -



python - Suddenly, No module named models -

i have project 3 apps, called projects, specimens , tests. working fine until made alter (i don't remember what). after that, django throws importerror: no module named models. can't imagine problem because think have referenced , organized.

this error:

importerror @ / no module named models request method: request url: http://127.0.0.1:8000/ django version: 1.5.5 exception type: importerror exception value: no module named models exception location: /home/david/mysqldb/dev/mysqldb/teams_db/specimens/views.py in <module>, line 11 python executable: /usr/bin/python python version: 2.7.5

and traceback:

/home/david/mysqldb/dev/mysqldb/teams_db/teams_db/urls.py in <module> (r'^specimens/', include('specimens.urls')), ▶ local vars /usr/local/lib/python2.7/dist-packages/django/conf/urls/__init__.py in include urlconf_module = import_module(urlconf_module) ▶ local vars /usr/local/lib/python2.7/dist-packages/django/utils/importlib.py in import_module __import__(name) ▶ local vars /home/david/mysqldb/dev/mysqldb/teams_db/specimens/urls.py in <module> views import new_specimen, list_specimens, info_specimen ▶ local vars /home/david/mysqldb/dev/mysqldb/teams_db/specimens/views.py in <module> tests.models import test ▶ local vars

inside app tests have class test, 1 causing error. function throws error (specimens.views):

from django.shortcuts import render django.http import httpresponse, httpresponseredirect,\ httpresponseforbidden, httpresponsebadrequest,\ httpresponseservererror django.core.urlresolvers import reverse django.template import requestcontext django.shortcuts import render_to_response, get_object_or_404 forms import searchform, specimenform projects.models import project, serie models import specimen tests.models import test ## test importation!! import simplejson import json django.core import serializers django.forms.models import model_to_dict import datetime def new_specimen(request, project_id=none, serie_id=none): ...

and test class in tests.models:

from django.db import models projects.models import project specimens.models import specimen #from operator.models import operator django.core.validators import regexvalidator class test(models.model): ref = models.charfield(max_length=70, unique=true) #name = models.charfield(max_length=70, null=true, blank=true, default='null') project = models.foreignkey(project) specimen = models.foreignkey(specimen) #operator = models.foreignkey(operator) notes = models.textfield(max_length=170, blank=true) description = models.textfield(max_length=170, blank=true) start_date = models.datefield(null=true, blank=true) finish_date = models.datefield(null=true, blank=true) status = models.charfield(max_length=70, blank=true)

would need more information? please, allow me know if necessary. ideas of problem? name tests reserved word??

thanks in advance!!

it import loop, uncertainty import test model anywhere else. don't utilize relative import in view from models import specimen might causing problem. , don't set models in tests.py should used tests , shouldn't need test models tests.

python django

java - Strange Lazy initialization exception -



java - Strange Lazy initialization exception -

i getting lazy initialization exception don't understand...

i work java, hibernate, spring , wicket.

so, save method of form (extends wicket form) lazyinitializationexception when accesing colletion of object, right away can access collection of same object has same "configuration" collection fires exception:

here code in form:

therapygroup.gettherapies().clear(); therapygroup.gettherapies().addall(therapiesoldgroup); therapygroup.gettoxicities().add(lasttherapy.gettoxicity());

and here part collections defined in class:

@onetomany(mappedby = "therapygroup", fetch = fetchtype.lazy, orphanremoval=true) @cascade(value = { cascadetype.merge, cascadetype.persist, cascadetype.delete, cascadetype.save_update }) @orderby(value = "date asc") @filters( { @filter(name = "deletedfilter", status = "deleted <> :deletedparam") }) @cache(usage = cacheconcurrencystrategy.transactional, part = "therapygroup") @lazy public set<therapy> gettherapies() { homecoming therapies; } @onetomany(mappedby = "therapygroup", fetch = fetchtype.lazy, orphanremoval=true) @cascade(value = { cascadetype.merge, cascadetype.persist, cascadetype.delete, cascadetype.save_update }) @orderby(value = "date asc") @filters( { @filter(name = "deletedfilter", status = "deleted <> :deletedparam") }) @cache(usage = cacheconcurrencystrategy.transactional, part = "therapygroup") @lazy public set<toxicity> gettoxicities() { homecoming toxicities; }

the "problematic" collection toxicities collection. if swap order , phone call toxicities first, throws lazyinitializationexception. exception fired toxicities , not therapies... why?

edit: here's stack trace

root cause:

org.hibernate.lazyinitializationexception: failed lazily initialize collection of role: com.mycompany.myapp.data.therapygroup.toxicities, no session or session closed @ org.hibernate.collection.abstractpersistentcollection.throwlazyinitializationexception(abstractpersistentcollection.java:383) @ org.hibernate.collection.abstractpersistentcollection.throwlazyinitializationexceptionifnotconnected(abstractpersistentcollection.java:375) @ org.hibernate.collection.abstractpersistentcollection.initialize(abstractpersistentcollection.java:368) @ org.hibernate.collection.persistentset.add(persistentset.java:212) @ com.mycompany.myapp.web.support.therapyend.therapyendsupportform.onsaveformdata(therapyendsupportform.java:135) @ com.mycompany.myapp.web.base.baseform.dosave(baseform.java:370) @ com.mycompany.myapp.web.base.baseform.saveandtrigger(baseform.java:1137) @ com.mycompany.myapp.web.base.baseform.switchmodalwindow(baseform.java:1128) @ com.mycompany.myapp.web.base.baseform.switchmodalwindow(baseform.java:1077) @ com.mycompany.myapp.web.base.baseform.onsubmit(baseform.java:567) @ com.mycompany.myapp.web.comp.quasiajaxsubmitbutton.onsubmit(quasiajaxsubmitbutton.java:49) @ com.mycompany.myapp.web.comp.quasiajaxbutton$1.onsubmit(quasiajaxbutton.java:65) @ com.mycompany.myapp.web.comp.quasiajaxformsubmitbehavior.onevent(quasiajaxformsubmitbehavior.java:151) @ org.apache.wicket.ajax.ajaxeventbehavior.respond(ajaxeventbehavior.java:177) @ org.apache.wicket.ajax.abstractdefaultajaxbehavior.onrequest(abstractdefaultajaxbehavior.java:286) @ org.apache.wicket.request.target.component.listener.behaviorrequesttarget.processevents(behaviorrequesttarget.java:119) @ org.apache.wicket.request.abstractrequestcycleprocessor.processevents(abstractrequestcycleprocessor.java:92) @ org.apache.wicket.requestcycle.processeventsandrespond(requestcycle.java:1250) @ org.apache.wicket.requestcycle.step(requestcycle.java:1329) @ org.apache.wicket.requestcycle.steps(requestcycle.java:1428) @ org.apache.wicket.requestcycle.request(requestcycle.java:545) @ org.apache.wicket.protocol.http.wicketfilter.doget(wicketfilter.java:479) @ org.apache.wicket.protocol.http.wicketfilter.dofilter(wicketfilter.java:312) @ org.mortbay.jetty.servlet.servlethandler$cachedchain.dofilter(servlethandler.java:1139) @ org.springframework.orm.jpa.support.openentitymanagerinviewfilter.dofilterinternal(openentitymanagerinviewfilter.java:113) @ org.springframework.web.filter.onceperrequestfilter.dofilter(onceperrequestfilter.java:76) @ org.mortbay.jetty.servlet.servlethandler$cachedchain.dofilter(servlethandler.java:1139) @ org.mortbay.jetty.servlet.servlethandler.handle(servlethandler.java:378) @ org.mortbay.jetty.security.securityhandler.handle(securityhandler.java:216) @ org.mortbay.jetty.servlet.sessionhandler.handle(sessionhandler.java:181) @ org.mortbay.jetty.handler.contexthandler.handle(contexthandler.java:765) @ org.mortbay.jetty.webapp.webappcontext.handle(webappcontext.java:417) @ org.mortbay.jetty.handler.handlerwrapper.handle(handlerwrapper.java:152) @ org.mortbay.jetty.server.handle(server.java:324) @ org.mortbay.jetty.httpconnection.handlerequest(httpconnection.java:535) @ org.mortbay.jetty.httpconnection$requesthandler.content(httpconnection.java:880) @ org.mortbay.jetty.httpparser.parsenext(httpparser.java:747) @ org.mortbay.jetty.httpparser.parseavailable(httpparser.java:218) @ org.mortbay.jetty.httpconnection.handle(httpconnection.java:404) @ org.mortbay.jetty.bio.socketconnector$connection.run(socketconnector.java:228) @ org.mortbay.thread.queuedthreadpool$poolthread.run(queuedthreadpool.java:520)

com.mycompany.myapp.web.support.therapyend.therapyendsupportform.onsaveformdata(therapyendsupportform.java:135) line phone call therapygroup.gettoxicities().add(lasttherapy.gettoxicity());

set breakpoint in both methods. when run code, you'll see somewhere, gettherapies() called within of transaction. means have collection there , hibernate utilize instead of trying load database when phone call method within of save().

the same isn't true gettoxicities(). hibernate tries load there no current transaction, loading fails. create sure save() gets transaction somewhere. maybe forgot annotation somewhere?

java spring hibernate wicket lazy-initialization

database - Oracle 10g Datamasking -



database - Oracle 10g Datamasking -

i have oracle 10g database. want mask record of tables. doesn't need create sense, doesn't need readable. needs masked. example:

select * customer; last_name first_name address -------------- -------------- -------------------- doe john 10 someroad st

i convert :

last_name first_name address -------------- -------------- -------------------- ahd uiea 55 xxxx ue

i need open source software can work. should use?

you can utilize ora_hash or dbms_crypto bundle total fill requirements. giving solution using dbms_crypto:

--source data:

create table customer(last_name varchar2(50),first_name varchar2(50), address varchar2(200));

--encrypt function(script source):

create or replace function encrypt_value (p_in in varchar2, p_key in raw) homecoming raw l_enc_val raw (2000); l_mod number := dbms_crypto.encrypt_aes128 + dbms_crypto.chain_cbc + dbms_crypto.pad_pkcs5; begin l_enc_val := dbms_crypto.encrypt ( utl_i18n.string_to_raw (p_in, 'al32utf8'), l_mod, p_key ); homecoming l_enc_val; end;

--function implementation:

select encrypt_value(last_name,'aabbcc'),encrypt_value(first_name,'aabbcc'), encrypt_value(address,'aabbcc') customer;

database oracle10g

angularjs - How have the return of the current date via javascript -



angularjs - How have the return of the current date via javascript -

how have homecoming of current date via javascript, time-in-class label can utilize jquery or angular.

the thought have lastly update date.

if knows grateful.

can not come in direct value, feature @ runtime add together date has created ..

<div class="footer"> <div class="col-md-12"> <span class="pull-left time-label"></span> <div class="pull-right"> <a href="#" class="toggle-legend visible-lg pull-left clineswap">legend</a> </div> </div>

there's date constructor in javascript when called without arguments, give current time , date: https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/date

in order help more, need specify want do.

javascript angularjs

python 2.7 - Convert 2D numpy.ndarray to pandas.DataFrame -



python 2.7 - Convert 2D numpy.ndarray to pandas.DataFrame -

i have pretty big numpy.ndarray. array of arrays. want convert pandas.dataframe. want in code below

from pandas import dataframe cache1 = dataframe([{'id1': 'abc1234'}, {'id1': 'ncmn7838'}]) cache2 = dataframe([{'id2': 3276827}, {'id2': 98567498}, {'id2': 38472837}]) ndarr = [[4.3, 5.6, 6.7], [3.2, 4.5, 2.1]] arr = [] idx, in enumerate(ndarr): id1 = cache1.ix[idx].id1 idx2, val in enumerate(i): id2 = cache2.ix[idx2].id2 if val > 0: arr.append(dict(id1=id1, id2=id2, value=val)) df = dataframe(arr) print(df.head())

i mapping index of outer array , inner array index of 2 dataframes ids. cache1 , cache2 pandas.dataframe. each has ~100k rows.

this takes really long, few hours complete. there way can speed up?

i suspect ndarr, if expressed 2d np.array, has shape of n,m, n length of cache1.id1 , m length of cache2.id2. , lastly entry in cache2, should {'id2': 38472837} instead of {'id': 38472837}. if so, next simple solution may needed:

in [30]: df=pd.dataframe(np.array(ndarr).ravel(), index=pd.multiindex.from_product([cache1.id1.values, cache2.id2.values],names=['idx1', 'idx2']), columns=['val']) in [33]: print df.reset_index() idx1 idx2 val 0 abc1234 3276827 4.3 1 abc1234 98567498 5.6 2 abc1234 38472837 6.7 3 ncmn7838 3276827 3.2 4 ncmn7838 98567498 4.5 5 ncmn7838 38472837 2.1 [6 rows x 3 columns]

actually, think, maintain having multiindex may improve idea.

python-2.7 pandas multidimensional-array

java - ArrayList not persisting between methods -



java - ArrayList not persisting between methods -

i'm trying load csv file arraylist later break , store it. between methods arraylist beingness reset null. i'm confused cause , grateful advice

package testinput; import java.io.bufferedinputstream; import java.io.datainputstream; import java.io.file; import java.io.fileinputstream; import java.io.filenotfoundexception; import java.io.ioexception; import java.util.arraylist; public class bean { private string filecontent; private string filecontent2; private arraylist<string> filecontentarray; private int counter = 0; public int getcounter() { homecoming counter; } public void setcounter(int counter) { this.counter = counter; } public arraylist<string> getfilecontentarray() { homecoming filecontentarray; } public void setfilecontentarray(arraylist<string> filecontentarray) { this.filecontentarray = filecontentarray; } public string getfilecontent() { homecoming filecontent; } public void setfilecontent(string filecontent) { this.filecontent = filecontent; } public string getfilecontent2() { homecoming filecontent2; } public void setfilecontent2(string filecontent2) { this.filecontent2 = filecontent2; } public void upload() { file file = new file("/users/t_sedgman/desktop/finalproject/test_output_data.rtf"); fileinputstream fis = null; bufferedinputstream bis = null; datainputstream dis = null; arraylist<string> temparray = new arraylist<>(); seek { fis = new fileinputstream(file); // here bufferedinputstream added fast reading. bis = new bufferedinputstream(fis); dis = new datainputstream(bis); // dis.available() returns 0 if file not have more lines. while (dis.available() != 0) { // statement reads line file , print // console. temparray.add(dis.readline()); } setfilecontentarray(temparray); // dispose resources after using them. fis.close(); bis.close(); dis.close(); filecontent = filecontentarray.get((filecontentarray.size() - 2)); } grab (filenotfoundexception e) { e.printstacktrace(); } grab (ioexception e) { e.printstacktrace(); } } public void next() { arraylist<string> temparray = getfilecontentarray(); int size = filecontentarray.size(); if (counter <= size) { counter++; filecontent2 = temparray.get(counter); } else { counter = 0; } } }

many thanks

tom

you can seek marking bean @viewscoped/@sessionscoped

java jsf ejb javabeans

xml - WiX Installer failed to parse condition -



xml - WiX Installer failed to parse condition -

i trying create wix installer makes sure user on windows 7 , doesn't have .net framework 4.5 installed. below both error code , xml/wxs code in bundle. i'm @ loss why doesn't understand unless parentheses. but, without them doesn't understand not is.

code:

<chain> <exepackage id="prepackage" sourcefile="dotnetfx45_full_setup.exe" installcondition="(versionnt &gt;= v6.1) , not (net4fullversion &gt;= 4.5)" /> <msipackage id="mainpackage" sourcefile="samplefirst.msi" installcondition="versionnt &gt;= v6.1" /> </chain>

error:

[0a20:0954][2014-06-23t12:07:14]e000: error 0x8007000d: failed parse status "(versionnt >= v6.1) , not (net4fullversion >= 4.5)". unexpected character @ position 49.

having experimented locally, looks net4fullversion needs have version number quoted; means in case quotes have escaped:

<exepackage id="prepackage" sourcefile="dotnetfx45_full_setup.exe" installcondition="(versionnt >= v6.1) , not (net4fullversion >= &quot;4.5&quot;)" />

xml parsing wix condition

Fxcop Custom code designed targeting VS 2010 not working for VS 2012 -



Fxcop Custom code designed targeting VS 2010 not working for VS 2012 -

i have written code analysis rules , created rule set file contain custom rules , miscrosoft rules. rules developed , build on ms visual studio 2010 , working fine on it. when same rule set tried utilize in ms visual studio 2012 custom rules fail load without warning.

i have tried build same project targeting vs 2012 , used same assembly new ruleset still custom rule fails load.

this referencing issue.

your custom rule uses references fxcopsdk.dll , microsoft.cci.dll. version changes every time new visual studio gets released.

where visual studio 2010 uses version 10.0, visual studio 2012 uses version 11.0.

you add together relative paths in .csproj-file. allows instant rebuilding in each new visual studio version:

<reference include="microsoft.cci"> <hintpath>$(codeanalysispath)\microsoft.cci.dll</hintpath> </reference> <reference include="fxcopsdk"> <hintpath>$(codeanalysispath)\fxcopsdk.dll</hintpath> </reference>

visual-studio-2012 code-analysis fxcop

sql server - How to execute this @query variable? -



sql server - How to execute this @query variable? -

declare @query varchar(200); set @query='select count(*) stud';

i have used this:

exec (@query) execute sp_executesql @query

but it's not working.

error: must declare scalar variable.

how declare scalar variable , how execute query.

use

declare @query nvarchar(max) set @query = 'select count(*) stud' execute sp_executesql @query

sql-server tsql

javascript - Jquery UI and Bootstrap Issue -



javascript - Jquery UI and Bootstrap Issue -

i have drag-and-drop function simplified in jsfiddle below:

http://jsfiddle.net/jdh9/6hamv/13/

i added modal button, , drag-and-drop doesn't work.

the drag , drop uses next scripts:

1.5.0/jquery.min.js 1.8.9/jquery-ui.min.js

and modal button / window uses:

bootstrap.min.js code.jquery.com/jquery.js

does have thought work around drag-and-drop works as, bootstrap modal?

here's javascript code:

class="lang-js prettyprint-override">$(init); function init() { $('#element_1').data( 'number', 1 ).attr( 'id', 'card'+1 ).draggable( { containment: '#content', stack: '#cardpile div', cursor: 'move', revert: true } ); $('#slot_1').data( 'number', 1 ).droppable( { accept: '#cardpile div', hoverclass: 'hovered', drop: handlecarddrop } ); } function handlecarddrop( event, ui ) { var slotnumber = $(this).data( 'number' ); var cardnumber = ui.draggable.data( 'number' ); if ( slotnumber == cardnumber ) { ui.draggable.addclass( 'correct' ); ui.draggable.draggable( 'disable' ); $(this).droppable( 'disable' ); ui.draggable.position( { of: $(this), my: 'left top', at: 'left top' } ); ui.draggable.draggable( 'option', 'revert', false ); } }

they shouldn't impact 1 another.

the modal button wasn't visible because had class hidden-xs , people viewing through jsfiddle's narrower result pane.

other that, both should work simultaneously. if isn't working, first @ console see if there errors on page. i'd @ each individually create sure both still working:

this fiddle should work fine:

http://jsfiddle.net/6hamv/31/

javascript jquery twitter-bootstrap

javascript - Using a submit button to submit to the same form and using the values to run SQL queries -



javascript - Using a submit button to submit to the same form and using the values to run SQL queries -

sorry title confusing best way think describe it. issue creating form people set info it. part of validation form compare current values past values database. need process form identification fields in order find user's lastly entry database. way supposed work (in head) is: user fills out data, hits check button (a type=submit button) form runs validations based on previous db entries , enables submit button user click perform final submission. thought or suggestions? right check button submits form can't proper validations because need of form info pull sql queries.

i suggest making check button type=button. way can set onclick event handler phone call function validation via ajax without submitting form server.

javascript html sql forms

In Assembly language (LC 2200 MIPS), Coding Confusion -



In Assembly language (LC 2200 MIPS), Coding Confusion -

if increment $a0 0 10 using loop. then, increment memory address 0 0 10 using loop...

would code like

loop: addi $a0,1

this how implement loops in mips assembly:

.globl main main: # start of loop loop: bgt $a0,10,exit # checks if $a0 greater 10 loop ending status addi $a0,$a0,1 # adds 1 $a0 loop variable j loop # jumps go on loop exit: li $v0,10 # sets value of $v0 10 terminate programme syscall # terminate

kindly check link if want larn more loops in mips assembly

assembly mips pipeline processor

php - mail() in foreach loop -



php - mail() in foreach loop -

mail() used send email users in array provided foreach loop. want set limit number of emails sent per hour. besides, need maintain track of how many emails sent , not sent ( ajax perchance ).

is there can set pause between time each email sent, other sleep()? coz stops whole script , not able track number of emails beingness sent.

code simple:

foreach ($user_emails $user_email) { if(mail( $user_email, $subject, $model->message, $headers)) { echo "sent </br>"; } }

advice on library great! :)

you can set mails want send in database, , execute cronjob/crontab open php file reads database , send x amount of emails. cronjob can configured run every minute, half hour, hour, etc, per requirement. in terms of load improve run cronjob more , send smaller amount of emails per execution, instead of running cronjob less , sending more mails @ same time.

of course, don't forget remove email record (or mark sent) db after running mail service command record, won't sent twice.

php email

ios - First UITableViewCell UIButton in search remains the same -



ios - First UITableViewCell UIButton in search remains the same -

i have table loads 3 cells. first cell's label text "don" , lastly 2 cells' label texts "test".

i've noticed when search “don” first, uibutton tag 100 (correct tag #). next i'll search "test" , first cell's uibutton tag 100 (should 101) , sec cell's uibutton tag 102 (correct).

when rerun application , search "test" first, first cell's uibutton tag 101 (correct) , sec cell's uibutton tag 102 (correct). when search "don" afterwards, cell's uibutton tag 101 (should 100).

i'm not sure if it's overlapping on first cell or providing cell code below.

- (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { // register cell identifier custom cell nib static nsstring *cellidentifier = @"friendcell"; uitableviewcell *cell = [tableview dequeuereusablecellwithidentifier:cellidentifier]; // avatar settings uiimageview *imvavatar = [[uiimageview alloc] initwithframe:cgrectmake(3, 3, 45, 45)]; [imvavatar setimage:[uiimage imagenamed:@"btnavatar2.png"]]; imvavatar.layer.cornerradius = imvavatar.frame.size.height/2; imvavatar.layer.maskstobounds = yes; //imvavatar.layer.bordercolor = [uicolor colorwithred:59/255 green:59/255 blue:121/255 alpha:1].cgcolor; //imvavatar.layer.borderwidth = 1.0f; // befriend button settings uibutton *btnbefriend = [[uibutton alloc] initwithframe:cgrectmake(281, 14, 36, 22)]; [btnbefriend addtarget:self action:@selector(btnbefriendpressed:event:) forcontrolevents:uicontroleventtouchupinside]; // collect friend info if (tableview == self.searchdisplaycontroller.searchresultstableview) { friend = [searchresults objectatindex:indexpath.section]; } else { friend = [arrfriends objectatindex:indexpath.section]; } nsstring *user_id = (nsstring *)[friend objectatindex:0]; // user id nsstring *username = (nsstring *)[friend objectatindex:1]; // username nsstring *fname = (nsstring *)[friend objectatindex:2]; // first name nsstring *lname = (nsstring *)[friend objectatindex:3]; // lastly name nsstring *full_name = (nsstring *)[friend objectatindex:4]; // total name uiimage *picture = (uiimage *)[friend objectatindex:5]; // image (img) nsstring *type = (nsstring *)[friend objectatindex:6]; // type nsstring *arrindex = (nsstring *)[friend objectatindex:7]; // arrfriends index // configure cell if (!cell) { cell = [[uitableviewcell alloc] initwithstyle:uitableviewcellstyledefault reuseidentifier:cellidentifier]; // set width depending on device orientation cell.frame = cgrectmake(cell.frame.origin.x, cell.frame.origin.y, tableview.frame.size.width, cell.frame.size.height); // name settings uilabel *lblname = [[uilabel alloc] initwithframe:(cgrectmake(60, 3, 215, 45))]; [lblname setfont:[uifont systemfontofsize:14]]; // update name, status, picture, befriend button lblname.text = full_name; // total name imvavatar.image = picture; // image (img) if ([type isequaltostring:@""]) { [btnbefriend setimage:[uiimage imagenamed:@"btnbefriend.png"] forstate:uicontrolstatenormal]; } else { [btnbefriend setimage:[uiimage imagenamed:@"btnbefriended.png"] forstate:uicontrolstatenormal]; } // cell subviews imvavatar.tag = 1; lblname.tag = 2; btnbefriend.tag = [arrindex intvalue]+100; [cell.contentview addsubview:imvavatar]; [cell.contentview addsubview:lblname]; [cell.contentview addsubview:btnbefriend]; cell.clipstobounds = yes; } else { // create sure images, buttons , texts don't overlap // avatar uiimageview *imvavatar = (uiimageview *)[cell viewwithtag:1]; imvavatar.image = picture; // name uilabel *lblname = (uilabel *)[cell.contentview viewwithtag:2]; lblname.text = full_name; // befriendbutton uibutton *btnbefriend = (uibutton *)[cell.contentview viewwithtag:[arrindex intvalue]+100]; if ([type isequaltostring:@""]) { [btnbefriend setimage:[uiimage imagenamed:@"btnbefriend.png"] forstate:uicontrolstatenormal]; } else { [btnbefriend setimage:[uiimage imagenamed:@"btnbefriended.png"] forstate:uicontrolstatenormal]; } } homecoming cell; }

i assumed problem on lines:

friend = [searchresults objectatindex:indexpath.section]; and/or uibutton *btnbefriend = (uibutton *)[cell.contentview viewwithtag:[arrindex intvalue]+100];

but corect imageview , label texts appear, not exclusively sure what's causing problem.

help much appreciated. in advance.

you should create custom uitableviewcell avatr image , buttons , other necessary elements required , reuse custom cell. if u adding elements cell in - (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath then, cell reused not ui elements imvavatar , btnbefriend adding cell, these elements initialised . can cause memory issues well

ios objective-c uitableview uibutton

java - Implementing compareTo() method in a Generic class -



java - Implementing compareTo() method in a Generic class -

i have project i'm working on , have started with:

public class pair<t extends comparable, e extends comparable> implements comparable{ private e e; private t t; public int compareto(pair arg0) { // todo auto-generated method stub homecoming 0; } }

i need utilize class sort ordered pairs in ascending order. if first ones equal, should sort send point.

could guys please help me start on this?

in class definition, t , e generics lack comparing against themselves. happens pair class. definition of class should be:

public class pair<t extends comparable<t>, e extends comparable<e>> implements comparable<pair<t, e>> { }

now can define how compare pair. here's example:

public class pair<t extends comparable<t>, e extends comparable<e>> implements comparable<pair<t, e>> { private e e; private t t; public int compareto(pair<t, e> pair) { int result = t.compareto(pair.t); homecoming (result == 0) ? e.compareto(pair.e) : result; } }

java generics

multithreading - Does Python support multithread in Webpage -



multithreading - Does Python support multithread in Webpage -

i going setup python web server using cherrypy. when user submit form python. want create thread within webpage beingness called. possible?

as have tried pthread in php before, , seems pthread not work in webpage. want create clear python back upwards multi thread in webpage before dive in.

thanks  

python not threading, don't know needs advise take @ celery distributed task queu, can runs tasks.

if don't find celery useful, may need utilize multiprocessing it's solution run tasks in parallel. should know limited number of processor cores

python multithreading

sharepoint 2010 - I want to know how to send an email to list of people -



sharepoint 2010 - I want to know how to send an email to list of people -

i need send alert several hundereds of recipienats. have names in excel sheet, of these fields might invalid entry. there anyway can create sharepoint accepts valid entries , auto-delete invalid ones, , proceed send emails. give thanks much

if emails sharepoint users, can cycle , check if users such emails exist. when have valid emails, append them 1 string added email's "to" section. hope helps

sharepoint-2010

C# application log4net log file not created when used in C++/CLI -



C# application log4net log file not created when used in C++/CLI -

i've written c# dll - foo.dll - uses log4net logging. dll used in c++ application via c++\cli wrapper. c++ application works perfectly, log file not created. when utilize dll in testing c# application (that uses original c# dll) log file create without problems.

this configuration set in foo.dll.config:

<configsections> <section name="log4net" type="log4net.config.log4netconfigurationsectionhandler, log4net"/> </configsections> <log4net> <root> <level value="debug" /> <appender-ref ref="rollingfileappender" /> </root> <appender name="rollingfileappender" type="log4net.appender.rollingfileappender"> <file value="d:\\foo.log" /> <appendtofile value="true" /> <rollingstyle value="size" /> <maxsizerollbackups value="5" /> <maximumfilesize value="10mb" /> <staticlogfilename value="true" /> <layout type="log4net.layout.patternlayout"> <conversionpattern value="%date [%thread] %level - %message%newline" /> </layout> </appender> </log4net>

other configuration read without problems foo.dll.config file , c++ application has writing permissions log directory.

any thought i'm missing here?

i re-write comment answer.

you must seek define app.config file c++ application (not dll itself), , include on log4net configuration.

c# c++ dll c++-cli log4net

javascript - Amending canonical url with JS -



javascript - Amending canonical url with JS -

i have canonical url seo friendly, when going page there redirect in place. having issues google plus because of this. if add together next end of url ?geoip=noredirect works fine don't want alter actual url robots search.

if create alter js/jquery after page has loaded, have impact on seo?

sounds making website over-complicated , causing problems.

you need simply.

i have canonical url seo friendly, when going page there redirect in place.

geo ip redirects cause problems seo - ie google redirected usa because of server location.

instead recommend updating little part of page based on geo ip, not redirecting users.

javascript jquery seo

unicode - How to exit a Perl program as soon as the "Wide character in print at X line Y" message appears? -



unicode - How to exit a Perl program as soon as the "Wide character in print at X line Y" message appears? -

i have perl programme that's giving me next output:

wide character in print @ foo.pl line 139, <file> line 1. wide character in print @ foo.pl line 139, <file> line 2. wide character in print @ foo.pl line 139, <file> line 3.

as don't want add together :utf8 layer, , don't want turn off warnings either, i'm looking way terminate programme , exit error code if message above appears.

as print statement 1 throwing error, tried utilize or die next print statement, didn't help. e.g.>

print output $_."\n" or die "something wrong happened - $!";

i guess that's not working because print not failing - it's displaying message.

what looking is:

use warnings fatal => 'utf8';

which cause "wide character" warning fatal, , cause perl process die.

for example:

#!/usr/bin/env perl utilize strict; utilize warnings; utilize utf8; utilize feature 'say'; (1 .. 3) { "παν γράμμα"; } "=" x 80; utilize warnings fatal => 'utf8'; (1 .. 3) { "παν γράμμα"; }

outputs:

alex@kyon:~$ ./fatal_wide.pl wide character in @ ./fatal_wide.pl line 9. παν γράμμα wide character in @ ./fatal_wide.pl line 9. παν γράμμα wide character in @ ./fatal_wide.pl line 9. παν γράμμα ================================================================================ wide character in @ ./fatal_wide.pl line 17.

and exits non-zero exit status:

alex@kyon:~$ echo $? 255

perl unicode

batch file - Launch a .jar multiple times with different parameters -



batch file - Launch a .jar multiple times with different parameters -

i've got 2186 jpeg files need convert filetype specific program. unfortunately, i'm bad when comes batch files, here's have far:

java -jar -xmx1024m convert.jar -d2 -h64 -w64 -s untitled_000000.jpeg output_000000.schematic

it takes file untitled_000000.jpeg , converts output_000000.schematic . how go around making convert 2186 files automatically, output_002185.schematic?

thanks!

try this:

main.bat @echo off /l %%a in (0, 1, 2185) (pad.bat "%%a")

and in same directory:

pad.bat set var=%1 :loop set var=0%var% if "%var:~5,1%"=="" goto :loop java -jar -xmx1024m convert.jar -d2 -h64 -w64 -s untitled_%var%.jpeg output_%var%.schematic

and should work you. (i have tested it)

batch-file

dependency management - Maven declare version range, avoid unnecessary libraries -



dependency management - Maven declare version range, avoid unnecessary libraries -

i'm trying avoid next situation:

i have library a depends on library b in version 1.1. next create new project depend on a , c depends on library b in version 2.0. understand have 2 libraries b in different versions. if a can depends on b in version 2.0, 1 lib needed? nice if define a works interval, in case: <1.1 - 2.0>.

is there way so?

you can specify range in version like

<dependency> <groupid>junit</groupid> <artifactid>junit</artifactid> <version>[3.0, 3.8.2)</version> </dependency>

but prior build have invoke

mvn versions:resolve-ranges

to resolve actual version number

reference

maven dependency-management

matlab - Edge detection and segmentation -



matlab - Edge detection and segmentation -

i trying extract object paper currency image. on original image applied sobel border detection. here image:

my question in next cropped image want have number 100 displayed out other noises. how can please?

the code used far is:

close all; clear all; note1 = imread('0001.jpg'); note2 = imread('0007.jpg'); figure(1), imshow(note1); figure(2), imshow(note2); note1=rgb2gray(note1); note2=rgb2gray(note2); edge1=edge(note1,'sobel'); edge2=edge(note2,'sobel'); figure(5), imshow(edge1),title('edge sobel1'); figure(6), imshow(edge2),title('edge sobel2'); rect_note1 = [20 425 150 70]; rect_note2 = [20 425 150 70]; sub_note1 = imcrop(edge1,rect_note1); sub_note2 = imcrop(edge2,rect_note2); figure(7), imshow(sub_note1); figure(8), imshow(sub_note2);

for completeness, original image:

use gaussian filter clean noise before applying border detector:

% create gaussian filter hsize = [5 5] , sigma = 3.5 g = fspecial('gaussian',[7 7], 3.5); note1f = imfilter(note1,g,'same'); edge1f=edge(note1f,'sobel'); sub_note1f = imcrop(edge1f,rect_note1); figure(6), imshow(sub_note1f);

this results in much cleaner 100 image

you utilize canny border detector instead of sobel transform.

edge1c = edge(note1,'canny', [0.2, 0.4] , 3.5); sub_note1c = imcrop(edge1c,rect_note1); figure(7), imshow(sub_note1c);

matlab image-processing image-segmentation edge-detection

How to covert a cell array into a matrix filling the inconsistencies dimensions with NaN values and plot it in MATLAB -



How to covert a cell array into a matrix filling the inconsistencies dimensions with NaN values and plot it in MATLAB -

this question:

a={[1 2 3]; [1] ; [5 1]};

now want convert variable matrix, this:

[b]=functionx(a)

b= [1 2 3; 1 nan nan; 5 1 nan];

once first question solved, wanna plot matrix, have (i don't know if there more simple way it):

figure;hold on i=1:size(b) plot(b(i,:),'o') end

and graphic:

so, wondering if maybe there way create matlab recognize 1 data, mean, appears in legend "data 1" instead "data 1, info 2 , info 3".

the first part can done this

maxlength = max( cellfun(@(x)(numel(x)),a)); b = cell2mat(cellfun(@(x)cat(2,x,nan*ones(1,maxlength -length(x))),a,'uniformoutput',false));

for sec part utilize this

plot(repmat((1:size(b,1))',size(b,2),1),reshape(b',[],1),'o')

matlab

asp.net - Enable audit to azure DB -



asp.net - Enable audit to azure DB -

i've created azure db , want enable audit (e.g. user alter entry,when,etc), how can ?

i click on manage , didn't find place when can that...

azure sql database not back upwards alter info capture (cdc) feature in standard sql server provides in-built auditing capabilities. need solve auditing requirement other way (pre / post triggers?)

the total set of azure sql db limitations (and differences standard sql server) listed here: http://msdn.microsoft.com/en-us/library/azure/ff394115.aspx.

there's older technet blog on how accomplish workable solution here: http://social.technet.microsoft.com/wiki/contents/articles/2976.how-to-enable-sql-azure-change-tracking.aspx

asp.net azure sql-azure

What scala version Intellij Idea scala plugin uses? -



What scala version Intellij Idea scala plugin uses? -

i have en error java annotation on scala enums. scala bug seems fixed, inteliij thought shows error. how can ensure intellij thought scala plugin uses actual scala version?

you can check scala compiler , language level of project under project options file > project structure... > modules > scala

scala intellij-idea annotations intellij-plugin

scala - Transforming Parser[Any] to a Stricter Type -



scala - Transforming Parser[Any] to a Stricter Type -

programming in scala's chapter 33 explains combinator parsing:

it provides example:

import scala.util.parsing.combinator._ class arith extends javatokenparsers { def expr: parser[any] = term~rep("+"~term | "-"~term) def term: parser[any] = factor~rep("*"~factor | "/"~factor) def factor: parser[any] = floatingpointnumber | "("~expr~")" }

how can map expr narrower type parser[any]? in other words,

i'd take def expr: parser[any] , map via ^^ stricter type.

note - asked question in scala google groups - https://groups.google.com/forum/#!forum/scala-user, haven't received finish reply helped me out.

as stated in comments, can narrow downwards type like. have specify after ^^.

here finish illustration info construction given code.

object arith extends javatokenparsers { trait look //the info construction case class fnumber(value: float) extends look case class plus(e1: expression, e2: expression) extends look case class minus(e1: expression, e2: expression) extends look case class mult(e1: expression, e2: expression) extends look case class div(e1: expression, e2: expression) extends look def expr: parser[expression] = term ~ rep("+" ~ term | "-" ~ term) ^^ { case term ~ rest => rest.foldleft(term)((result, elem) => elem match { case "+" ~ e => plus(result, e) case "-" ~ e => minus(result, e) }) } def term: parser[expression] = factor ~ rep("*" ~ factor | "/" ~ factor) ^^ { case factor ~ rest => rest.foldleft(factor)((result, elem) => elem match { case "*" ~ e => mult(result, e) case "/" ~ e => div(result, e) }) } def factor: parser[expression] = floatingpointnumber ^^ (f => fnumber(f.tofloat)) | "(" ~> expr <~ ")" def parseinput(input: string): look = parse(expr, input) match { case success(ex, _) => ex case _ => throw new illegalargumentexception //or alter result try[expression] } }

now can start parse something.

arith.parseinput("(1.3 + 2.0) * 2") //yields: mult(plus(fnumber(1.3),fnumber(2.0)),fnumber(2.0))

of course of study can have parser[string] or parser[float], straight transform or evaluate input string. said you.

scala parsing

matplotlib - Python networks change color of nodes when using draw_network_nodes() -



matplotlib - Python networks change color of nodes when using draw_network_nodes() -

the goal obtain similar to

to define graph use:

import matplotlib.pyplot plt import networkx nx graph = { '1': ['2', '3', '4'], '2': ['5','11','12','13','14','15'], '3' : ['6','7','66','77'], '5': ['6', '8','66','77'], '4': ['7','66','77'], '7': ['9', '10'] } mg = nx.digraph() mg.add_edges_from([(start, stop, {'weigth' : len(graph[start]) }) start in graph stop in graph[start]])

and code plot is:

plt.figure(figsize=(8,8)) pos=nx.graphviz_layout(mg,prog="twopi",root='1') n in mg.nodes_iter(): nx.draw_networkx_nodes(mg, pos, nodelist = [n], node_size = 2000 / float(len(mg[n[0]])+1), node_color = (len(mg[n[0]])+1), alpha = 1/float(len(mg[n[0]])+1), with_labels=true ) xmax=1.1*max(xx xx,yy in pos.values()) ymax=1.1*max(yy xx,yy in pos.values()) plt.xlim(0,xmax) plt.ylim(0,ymax) plt.show()

there 2 things here know:

how can have color node depending on number of links each node has (i.e. len(mg[0]))?

where labels?

thanks

how this? can utilize matplotlib's colormaps map values colors nodes.

import matplotlib.pyplot plt import networkx nx graph = { '1': ['2', '3', '4'], '2': ['5','11','12','13','14','15'], '3' : ['6','7','66','77'], '5': ['6', '8','66','77'], '4': ['7','66','77'], '7': ['9', '10'] } mg = nx.digraph(graph) plt.figure(figsize=(8,8)) pos=nx.graphviz_layout(mg,prog="twopi",root='1') nodes = mg.nodes() grade = mg.degree() color = [degree[n] n in nodes] size = [2000 / (degree[n]+1.0) n in nodes] nx.draw(mg, pos, nodelist=nodes, node_color=color, node_size=size, with_labels=true, cmap=plt.cm.blues, arrows=false) plt.show()

python matplotlib networkx

Fit to Android Imageview Matrix Center of Screen -



Fit to Android Imageview Matrix Center of Screen -

hello im using function fit screen on topic android image view matrix scale + translate

float imagewidth = imagedetail.getdrawable().getintrinsicwidth(); float imageheight = imagedetail.getdrawable().getintrinsicheight(); rectf drawablerect = new rectf(0, 0, imagewidth, imageheight); rectf viewrect = new rectf(0, 0, imagedetail.getwidth(), imagedetail.getheight()); matrix.setrecttorect(drawablerect, viewrect, matrix.scaletofit.center); imagedetail.setimagematrix(matrix); imagedetail.invalidate();

it works not first time. when start application doesnt work. image doesnt show. when m tap works. im wrong? advice

hi should place code in onwindowfocuschanged method.

@override public void onwindowfocuschanged(boolean hasfocus) { super.onwindowfocuschanged(hasfocus); float imagewidth = image.getdrawable().getintrinsicwidth(); float imageheight = image.getdrawable().getintrinsicheight(); rectf drawablerect = new rectf(0, 0, imagewidth, imageheight); rectf viewrect = new rectf(0, 0, image.getwidth(), image.getheight()); matrix matrix = new matrix(); matrix.setrecttorect(drawablerect, viewrect, matrix.scaletofit.center); image.setimagematrix(matrix); image.invalidate(); }

android matrix imageview center