Posts

Showing posts from January, 2013

mongoid returns document not found even if its present + tire + mongoid -

i m using tire , mongoid in rails 4 application. class agent include mongoid::document include mongoid::timestamps include mongoid::taggable include tire::model::search include tire::model::callbacks ... mapping indexes :id, index: :not_analyzed indexes :name, type: 'string', analyzer: 'pattern' indexes :tags_array, type: 'string', analyzer: 'pattern' end ... def self.search(params) tire.search(load: true) query string "name:#{params}" string "tags_array:#{params}" end end end ... there 4 agents as agent.all.collect(&:tags) => ["pune", "pune", "press", "pune press"] agent.all.collect(&:name) => ["agent smith", "first", "second", "third"] i have 3 issues as 1) first problem agent not searchable 'name'. results = agent.search('first') ...

php - Why can't I update my database when I submit a form? -

<form name="applyform" action="applyform.php" method="post"> <fieldset> <legend>application details</legend> <p>name :<?php echo $row ["emp_fname"]; ?></p> <p>id number :<?php echo $row['emp_id']; ?></p> <p>email :<?php echo $row['emp_email']; ?></p> <p>address :<?php echo $row['emp_address']; ?></p> <p>handphone number :<?php echo $row['contactno_hp']; ?></p> <p>phone number :<?php echo $row['contactno_home']; ?></p> <p>date of application :<?php echo $row['leave_requestdate']; ?></p> <p>type of leave: <select name="leave type"> <option selected>annual leave</option> <option>sick leave</optio...

Durandal.js .NET VS2012 How to use Weyland in build process -

i'm using vsix durandal template (version 2.0). previous version (1.2) had optimizer.exe run part of build process. think weyland has replaced i'm not sure how can running build step in release mode. here's how it: if $(configurationname) == release ( cd "$(projectdir)" attrib -r app\main-built.js weyland build ) i clear read-only flag in case main-built.js put in source control, may not need line. note: if build fails (or don't have node , weyland installed), refer following page more info: https://github.com/bluespire/durandal/issues/254 update: to setup npm use authenticated proxy, try these commands in elevated command prompt (last 2 may not necessary, useful other tools): npm config set proxy http://username:password@proxy:8080 npm config set https-proxy http://username:password@proxy:8080 setx http_proxy http://username:password@proxy:8080 /m setx https_proxy http://username:password@proxy:8080 /m then restart visual s...

jenkins - How can I start a java program by sending an email -

we working on project , im involved in continuous integration testing. i need deploy new project code on staging server, not using jenkins, ftp; after deploy email sent indicate successfull deploy , need start integration tests; integration tests, if successfull, start deploy on integration server. i going write java program login jenkins , execute integration tests. question is: how can email message activate java program? edit: normally, jenkins offers feature starts job after getting email, having security problem that make program or script peridically poll mail server box , upon getting appropirate email run java program.

Handling orientation change during the asyntask in android -

i'm having problem in asyntask. when progress bar has start , once rotate screen, progress bar disappear , activity restart. trying use setrequestedorientation(activityinfo.screen_orientation_nosensor); but if asynctask not in activity... in class file common many activity class. how can setrequestedorientation(activityinfo.screen_orientation_nosensor); help. this works in app. put line in manifest. **android:configchanges="orientation|screensize"**

Refresh XML data from web in Excel -

i'm using excel 2010 link table xml file on server. i'd distribute excel file group of people , have updated every time xml file updated on server. in excel, i'm pulling data using "data", "from web" , type in path of xml file. excel builds table data if xml file updated on server, data remains static, if click "refresh" or "refresh xml data" on table. it should able download new data including new columns table, if any. is there way this? i not expert in vba , here 1. refreshing when opening excel file , can done by sub refreshdata() activeworkbook.refreshall ' or can give specific workbook , worksheet identification end sub private sub workbook_open() 'call refresh data subroutine when opening file refreshdata end sub you can use worksheet activate event handler if have multiple worksheet in file. private sub worksheet_activate() 'call refresh data subroutine when opening file re...

How to convert php array variable to javascript variable -

this question has answer here: converting php result array json 2 answers here code retrieving db... , stored column values in array() variable... $res1 = array(); while ($row = mysql_fetch_assoc($res)) { $res1[$i] = $row['address']; $i = $i + 1; } print_r($res1); but problem wen trying print array printing below: "array ( [0] => ameerpet [1] => panjagutta )" but need print array below can store in js variable further using...... ["ameerpet", "panjagutta"]; use json_encode() encode array json format: $json = json_encode($res1); you can use variable in javascript , use use json.parse() : json = <?php echo $json; ?> var obj = json.parse(json); // obj contains array documentation: json.parse()

python - Find strings that begins with a '#' and create link -

i want check whether string (a tweet) begins '#' (i.e. hashtag) or not, , if create link. below i've tried far doesn't work (error on last line). how can fix , code work purpose? tag_regex = re.compile(r""" [\b#\w\w+] # hashtag found!""", re.verbose) message = raw_message tag in tag_regex.findall(raw_message): message = message.replace(url, '<a href="http://statigr.am/tag/' + message[1:] + '/">' + message + '</a>') >>> msg = '#my_tag rest of tweet' >>> re.sub('^#(\w+) (.*)', r'<a href="http://statigr.am/tag/\1">\2</a>', msg) '<a href="http://statigr.am/tag/my_tag">the rest of tweet</a>' >>>

jQuery Mobile: change/switch theme on listview data-split-icon -

i have split listview (with collapsible set) in jquery mobile (jqm). can see here on jsfiddle. i want split icon act checkbox. icon has default data-theme="c" grey , want change data-theme b on click, icon color should change blue. i tried different solutions change data-theme , found several more or less (more less) working solution. best simple jqm code $(this).buttonmarkup({theme: 'b'}); , but, changing data theme way dont change color of icon, change color of background, can try in mentioned jsfiddle. normaly data-theme on split listview, affect icon, when changed way, affects icons background. want change icon, not background , cannot find way that. wrong selector or kind of bug. what think? add below code. demo $(this).find('span.ui-btn').buttonmarkup({ theme: 'b' }); and $(this).find('span.ui-btn').buttonmarkup({ theme: 'c' }); as span.ui-btn holds icon , its' style.

sql server - SQL Looping temp table and reading data -

i have following script create temp data declare @name nvarchar(100), @marks int declare @mytable table ( [name][nvarchar](100) null, [marks][int] null ) insert @mytable ([name],[marks]) values ('mark',50); insert @mytable ([name],[marks]) values ('steve',50); insert @mytable ([name],[marks]) values ('don',50); now want loop it, shown in below script select @maxpk = max(pk) @mytable while @pk <= @maxpk begin set @name = select name @mytable set @marks = select marks @mytable print @name print @marks set @pk = @pk + 1 end but error near select statement. "incorrect syntax near keyword select"! the 2 rows set variables can put this. way scan table once. select @name = name, @marks = marks @mytable just know row chosen put in variables arbitary (and same row every time) unless add whereclause.

entity framework - EntityFramework stored prrocedure with Npgsql -

this silly question : how call stored procedure entityframework on postgresql database using npgsql data provider. i have tried executefunction tells me the functionimport 'clientfields' not found in container 'businesscontext'. i can see function in ssdl file : but no trace of in object layer class...

.net - C# - How to get the mouse clicks in command line exe without using winform -

i saw "alike" questions. answers asking questioner use winform. in need of 100% console aplplication can hook windows message queue , give mouse click points. mouse click can happen in window. what did: made using winforms. copied of code 1 blog. working. current project "automating tests". here have launch of applications console application. otherwise operation become mess. tried imessagefilter, came know requires form. can guide me in proper direction? note: using windows7, .net4.5, visual studio express - 2012 edit: i not @ caring console. target getting mouse click coordinates(any in screen). means first lauch program console, make clicks on screen. console should print out coordinates of mouse clicks instantly. this take on need do, although i'm still little hazy on whether or not understand question. create normal console application. install mouse hook, wh_mouse_ll . deal mouse messages hook please, example outputting infor...

java - what are read barriers and write barriers in synchronized block -

i looking how synchronized , volatile variable works in java , came across concept called read , write barrier . can me understand meaning of terms ( answers above quite complete), want demonstrate concept simple scheme thread 1 thread 2 | | | | | | | thread 1 | | wrote before here | | | | | _ _ _ _ _ _ _ _ _ _ | ( write barrier) (happens before) (read barrier) ...

Socks proxy in android -

how connect socks proxy connection in android emulator, able connect socks proxy server on system browser not work in emulator, when using system network setting. have tried system.setproperty("socksproxyhost", proxyhost); system.setproperty("socksproxyport", port); and socketaddress addr = new inetsocketaddress(proxyhost, proxyport); proxy httpproxy = new proxy(proxy.type.socks, addr);urlconn = url.openconnection(httpproxy); but falied. want connect , consume socks proxy connection & web service in app on device.thanks in advance. this works me on android 4.3 on rooted nexus 4 sshtunnel running: socketaddress proxyaddr = new inetsocketaddress("127.0.0.1", 1984); socketaddress hostaddr = new inetsocketaddress(address, port); java.net.proxy proxy = new java.net.proxy(java.net.proxy.type.socks, proxyaddr); socket = new socket(proxy); socket.connect(hostaddr); note: installed iptables beta i'm not sure ...

How to use import statement for custom modules in Python -

i new python programming , writing simple helloworld program using python 3.3 on windows environoment.the helloworld program saved hello.py. how can use in module. tried sys.path.append , give path of save file not working. can tell me have set environment variable in windows xp thanks. use way: import sys then: sys.path.insert(0,"x") where x directory want import from. after need import custom module: import x thats all.

javascript - Durandal issue with Breeze and Q -

hi i'm new building web pages applications, started hottowel videos john papa , used hottowel vsix template. when decided update durandal 2.0 faced issue application not proceed activate method in shell module. after google search's found out problem has due durandal using jquery promises, have tried fix announced in http://durandaljs.com/documentation/q/ not working, can provide me light on issue. ps: im new js , web in general i'm sorry if question isn't clear enough in shell.js have: function activate() { app.title = config.apptitle; return datacontext.primedata() .then(boot) .fail(failedinitialization); } function boot() { logger.log('codecamper backend loaded!', null, system.getmoduleid(shell), true); router.map(config.routes).buildnavigationmodel(); return router.activate(); } function addsession(item) { router.navigateto(item.hash); } function failedinitialization(error) { var ...

css - Why Bootstrap 3 navbar dropdown doesn't work in IE8? -

the bootstrap 3 dropdown doesn't work in ie8, don't know why, on that. people because bs added css filter property bootstrap3 workes fine ie 8 have make sure add respond.js , html5shiv , latest version of jquery like this: <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="css/bootstrap.min.css" rel="stylesheet" media="screen"> <!--[if lt ie 9]> <script src="js/html5shiv.js"></script> <script src="js/respond.min.js"></script> <![endif]-->

How to get first string from a bash list? -

i have bash list (space separated string) , want extract first string it. example: var="aaa bbb ccc" -> need "aaa" var="xxx" -> need "xxx" is there other trick using break ? try format: echo "${var%% *}" another way is: read first __ <<< "$var" echo "$first"

C program in Xcode -

i have problem c code, hope can me. program making basic book "database". when run following code (in xcode), don't know why following sentence gets skipped: gets(nombre[i]); on terminal directly prints following if take option 1 menu: bienvenido al catalogo de libros. catalogo de tarjetas: 1. introducir 2. buscar por autor 3. buscar por titulo 4. salir elija opcion:1 warning: program uses gets(), unsafe. introduzca el nombre del libro:introduzca el autor del libro: ok, i've tested scanf("%d", &opcion); using printf("%d", opcion); right after proove scanf reads correctly input. surprisingly, reads option introduce correctly. moreover, i've tried running program no "\n" in part see if gets(nombre[i]) works still gets jumped... any ideas? this full code (not long): #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <ctype.h> #define max 100 c...

html - Php - detect which form was posted -

this question has answer here: how access form's 'name' variable php 10 answers i have single page multiple forms may appear on it. there anyway of distinguishing between these forms in php (some kind of form iding system)? there many methods can use give submit button unique name or value each form, <input type="submit" name="form1" value="submit"> if (isset($_post['form1'])){ // form1 filled in } add hidden input field <input type="hidden" name="form" value="form1"> if (isset($_post['form']) && $_post['form'] == "form1"){ // form1 filled in } use parameter in action url. <form action="index.php?form=form1" method="post"> if (isset($_get['form']) && $_get['form'] ...

android - Changing screen orientation makes login to begin again -

i have app login screen. when checking if login ok, show "loading" dialog . if change screen orientation, dialog disappears , think check of login starts again, app crashes after that. i've read solutions, can't works. here code: mainactivity.java public void entrar(view view) { /* escondemos el teclado */ inputmethodmanager imm = (inputmethodmanager)getsystemservice( context.input_method_service); imm.hidesoftinputfromwindow(edittextusuario.getwindowtoken(), 0); /* comprobamos si hay conexión internet */ if(myapplication.isonline()) { loadingmaintask mywebfetch = new loadingmaintask(this); mywebfetch.execute(); } /* si no se dispone de conexión internet, mostramos un error */ else { myapplication.mostrarmensaje(this, r.string.error_conexion_titulo, r.string.error_conexion_mensaje); } } private class loadingmaintask extends asynctask<string, void, boolean...

html - CSS display-table + SPAN error -

i have example: fiddle link a table using display: table, display: table-cell, display: table-row i need add before <p> <span> tag, table structure breaks . any idea? thanks example: <fieldset> <span> <p> <label>first name: </label> <input type="text" /> </p> </span> <span> <p> <label>second name: </label> <input type="text" /> </p> </span> <span> <p> <label>country: </label> <select> <option>choose</option> </select> </p> </span> <span> <p> <label>age: </label> <select> <option>choose</option> </select> </p> </span> </fieldset> if going display table elements should follow same structural property's fieldset span { display: table-row-group; } fiddle: h...

android - WebView loadDataWithBaseURL method cannot load images -

i have html string containing seveal img tags passing webview's loaddatawithbaseurl method like string data = "some html <img> , <link>....."; wview.loaddatawithbaseurl("http://dummy.baseurl/", data, "text/html", "utf-8", null); if dont pass first parameter html can displayed subsequent requests or css files not triggered thats why passing dummy baseurl. running code when try requests made under shouldinterceptrequest () below wview.setwebviewclient(new webviewclient() { @override public webresourceresponse shouldinterceptrequest(webview view, string url) { log.d("url="+url, "resources"); .... } }); the can see outputs http://dummy.host.name/images/face.jpg etc but original html contains ".." in img src <img src="../images/face.jpg"> trouble parent directory (..) part ignored webview this ".....

java - Inject beans from other projects into Vaadin view -

in 1 of vaadin views i'm trying hold of business object resides in project (bll) injecting @inject. vaadin view: public class fruitsaladview extends verticallayout implements view { @inject bananaservice bananaservice; ... } i can't this, of course, bananaservice object null @ runtime, because have component-scan packages. i'm using annotations have no web.xml in vaadin web project, don't have web-inf folder. i know there alternatives, cdi-utils , vaadin cdi vaadin addons, some other solutions this, seem inject stuff main ui (not views) , web application itself, not other modules. i'm using vaadin 7 , tomcat 7 (as long it's feasible using tomcat given answer question below) question: recommended way inject bean module vaadin view , need in order accomplish this? follow-up question: using tomcat application problem after using above method? tomcat servlet container, if want use cdi must use jee6 compliant server, tomee or...

mysql - SELECT MAX() and corresponding field in the same row -

here's table a orderid groupid nameid 1 grade foo 2 grade bar 3 grade rain 1 grade b rain 2 grade b foo 3 grade b bar 1 grade c rain 2 grade c bar 3 grade c foo desired result: rain bar foo i need nameid of max(orderid) each grade. can right orderid each grade, nameid stays first. thanks lot! praveen gave right query! question under answer edit: fixed mistake in answer. you looking quite like: select orderid, groupid, nameid concat(orderid,'-',groupid) in (select concat(max(orderid),'-',groupid) group groupid) edit: in regards question: put list in order of nameid, add query: order nameid

date - JAVA : Get a wrong current time -

i try current time : dateformat dateformat = new simpledateformat("yyyy/mm/dd hh:mm:ss"); calendar cal = calendar.getinstance(); string sendingdateandtime = dateformat.format(cal.gettime()).trim(); but gmt time when want system time (and not local time because software executed in several countries can use timezone object). i need use date library , gregoriancalendar library same wrong result. many people have same problem solution saw it's put hard code "europe" or else in timezone object. if can you. thankssss ---------------------------- update ------------------------------------ i tried use system.currenttimemillis() , give parameter calendar object, gmt time too how gmt time? calendar calendar = calendar.getinstance(timezone.gettimezone("gmt")); and local computer time? calendar calendar = calendar.getinstance(); dateformat default local time zone. internal format of calendar object number of milliseconds pas...

bootstrap, tooltip with dropdown, in button group seems to have an effect -

in bootstrap, tooltip dropdown, hover data-toggle attached 1 button in button group seems have effect when hover mouse on button responsible tool tip adjust position not good. please me. here code:- <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="css/bootstrap.css" rel="stylesheet" media="screen"/> <link href="css/bootstrap-responsive.css" rel="stylesheet" media="screen"/> </head> <body> <div class="btn-group"> <a href="#" class="btn btn-small btn-inverse add1" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="add selected contacts">add</a> <a class="btn btn-inverse dropdown-toggle" data-toggle="dropdown" ...

sql - Invalid column index during procedure execution -

below exception got after invoking stored procedure using spring jdbc template java. org.springframework.jdbc.uncategorizedsqlexception: callablestatementcallback; uncategorized sqlexception sql [{call pkg_ibs_ac_change_api.p_update_account_currency(?, ?, ?, ?, ?, ?, ?, ?, ?)}]; sql state [null]; error code [17004]; invalid column type; nested exception java.sql.sqlexception: invalid column type @ caused by: java.sql.sqlexception: invalid column type @ oracle.jdbc.driver.databaseerror.throwsqlexception(databaseerror.java:112) org.springframework.jdbc.core.statementcreatorutils.setparametervalue(statementcreatorutils.java:127) @ org.springframework.jdbc.core.callablestatementcreatorfactory$callablestatementcreatorimpl.createcallablestatement(callablestatementcreatorfactory.java:212) @ org.springframework.jdbc.core.jdbctemplate.execute(jdb so ran same code using spring debug mode , below few output logger. debug:28-08-2013 17:55:57,503: callmetadataprovider...

.net - VB.NET difficulty in COOKIES -

i new vb.net , want ask questions cookies. please not downvote question if sounds silly. not mean waste of precious time, not find clear related in google cookies -> want store data in computer of user check if logged in or not. want know if there called cookies or other thing can store info in user's pc in vb.net. if there nothing related that, of course have store info in database , delete them act cookies. please tell me if there know. surely appreciated. cookies relate web applications , in context of vb.net, can use these when create asp.net web application or website if want store information locally when using desktop application there many options: file (ini/xml/etc.) registry database, etc. there pros , cons of these

Autocomplete in JQuery is not working properly -

i trying use jquery auto complete .it not working showing 1 option every time don't why getting this. code var options_df1 = { serviceurl: '/'+company+'/city_names.html', width: 230, minchars: 1, maxheight: 500, delimiter: /(,|;)\s*/, onselect: onautocompleteselect_df1, deferrequestby: 0, //miliseconds params:{country: 'yes'}, }; var onautocompleteselect_df1 = function(value_df, data_df) { startlocation_df = data_df; } i hope problem because of caching use code .use nocache property var options_df1 = { serviceurl: '/'+company+'/city_names.html', width: 230, minchars: 1, maxheight: 500, delimiter: /(,|;)\s*/, onselect: onautocompleteselect_df1, deferrequestby: 0, //miliseconds params:{country: 'yes'}, nocache: false //set true, disable caching };...

internet explorer - jQuery validation engine - [IE8] "object doesn't support this property or method" -

this error message apears if i'm using validationengine in internet explorer 8 (not tried other versions). in message written problem @ line 714, 4th character, code: if(!required && !(field.val()) && field.val().length < 1 && rules.indexof("equals") < 0) options.iserror = false; i don't know problem .indexof isn't supported in <= ie8. as workaround create custom indexof() implementation, placed in perhaps centralised js script file targeted ie8. example, // create self-invoking anonymous indexof() function (function () { if (!array.prototype.indexof) { array.prototype.indexof = function (obj, start) { (var = (start || 0), j = this.length; < j; i++) { if (this[i] === obj) { return i; } } return -1; }; } })();

Android NavigationDrawer and ViewPager as its one of fragment -

Image
i have created sherlockfragmentactivity has 3 fragments viewpager. want use activity in navigationdrawer confused how this. google+ app has kind of implementation wondering how achieve this. navigationdrawer have following ui elements: fragmentactivity(contains 3 fragment viewpager) second fragment third fragment is kind of layout possible navigation drawer if yes, how should it. if not, should achieve kind of navigation in app. you can use below libraries navigation model similar requirement actionbarsherlock (github) nested-fragments (github) pagerslidingtabstrip (github) navigationdrawer (android developer site) latest support v4 library have @ post below screenshot of sample app navigation drawer tab strip example @ github

mysql - PHP caches RAND() variable values -

i have following code in file index.php : include('db_connect.php'); //here's script provides mysql connection database $a = round(rand(1,100)); $b = round(rand(160,202)); $c = round(rand(50,110)); $d = round(rand(1,99999)); $sql = "insert sinstance (p1,p2,p3,p4) values ('".$a."','".$b."','".$c."','".$d."')"; $result = mysql_query($sql) or die(mysql_error()); obviously, randomly generates values , inserts them record myisam database table sinstance . the problem : after ~1000 records generated & inserted, it's impossible generate new records (with unique sets of values). every new record clone of old 1 (with same p1-p2-p3-p4 values). the question : how avoid , make php generate unique records? the clue : server-side problem php, somehow caches values set of rand() function. problem not connected neither browser, nor mysql itself. not sure if you're not doin...

python - Where do I create custom profile models for django-userena? -

i have django app called my_app uses django-userena ; trying create , use own profile model following django-userena installation documentation. in my_app/models.py i've added from django.contrib.auth.models import user django.utils.translation import ugettext _ userena.models import userenabaseprofile class myprofile(userenabaseprofile): user = models.onetoonefield(user, unique=true, verbose_name=_('user'), related_name='my_profile') favourite_snack = models.charfield(_('favourite snack'), max_length=5) and i've modified my_app/settings.py include auth_profile_module = 'my_app.myprofile' . and yet, when try view web page my_app siteprofilenotavailable . error goes away if move myprofile accounts/models.py it seems bad idea modify accounts app in order add custom fields. wrong? there w...

Implicit Argument Passing in Python? -

the code below hackermeter.com , i'm not sure think of it. variable being passed implicitly run() or expect more modification specifies? import sys def run(): # code here! in range(int(sys.stdin.readline())): run() i'd argue poor coding practice. reason run() has access i i global. the following arguably better force programmer pass i run() explicitly (if required): import sys def run(): # code here! def main(): in range(int(sys.stdin.readline())): run() if __name__ == '__main__': main()

php - Wamp run as standard user? -

i installed wamp under (windows 7) administrator account, , works ( green color )! however, i've created user account "standard user". when logged in i'm able see wamp folder contains "wampmanager.exe" once try run it- of course require administrator password. how can force wamp server run under standard user without requiring me enter admin password ? possible ?

opengl - Deferred rendering position recontruct -

i made first step of deferred rendering, fbo wit color, normal, position , depth texture. when im lighting positions moving , rotating me. first pass vertex: void main(){ gl_position=gl_modelviewprojectionmatrix*gl_vertex; vec4 positiontotexture = gl_modelviewprojectionmartix*gl_vertex; } so how can original position? i assume positiontotexture go fragment shader , saved in texture. when doing first pass have view position, not viewprojection. can use: vec4 positiontotexture = gl_modelviewmartix*gl_vertex; in second pass can use: vec3 position = texture(texpos, vvaryingtexcoord0.xy).rgb; the previous way quite simple (yet when learning) require lot of memory (you have store 3 element vector). better way recreate view-position screen position/depth: link article . such techniques used in modern engines. (thanks andon-m-coleman suggestion) here repo basic deferred: https://github.com/fenbf/efg_deferred/tree/master/code/shaders

Does Go support volatile / non-volatile variables? -

Image
i'm new language bear me. i curious how go handles data storage available threads, in sense non-local variables can non-volatile, in java instance. go has concept of channel, which, it's nature -- inter thread communication, means bypasses processor cache, , reads/writes heap directly. also, have not found reference volatile in go lang documentation. tl;dr : go not have keyword make variable safe multiple goroutines write/read it. use sync/atomic package that. or better yet do not communicate sharing memory; instead, share memory communicating . two answers two meanings of volatile .net/java concurrency some excerpts go memory model . if effects of goroutine must observed goroutine, use synchronization mechanism such lock or channel communication establish relative ordering. one of examples incorrect synchronization section example of busy waiting on value. worse, there no guarantee write done ever observed main, since there no s...

symfony - In Symfony2, how to use Multiple Routes in Default Controller -

i've been trying map multiple routes default controller, , doesn't seem working expected. i'm using annotations in controller: /** * @route("/", name="index_controller"); * @template("seoslinkybundle:default:index.html.twig"); */ public indexaction() {} but want this: /** * @route("/", name="index_controller"); * @route("/{timeoption}", name="index_controller"); * @template("seoslinkybundle:default:index.html.twig"); */ public indexaction($timeoption = "today") { echo $today; exit; } that works, , if go to: http://myapp/hello the controller echoes "hello" but if go to http://myapp/ the controller should echo "today" but instead i'm getting error: cannot import resource "/usr/share/www/myapp/src/myappbundle/controller/" "/usr/share/www/myapp/app/config/routing.yml". these contents of routing.yml ...

java - How to make a JMS Producer to listen to a Response back from Consumer using TemporaryQueue? -

i made java component in mule flow sends message queue, want programatically instead of using mule jms component. from producer got code: @override public object oncall(muleeventcontext eventcontext) throws exception { string payload = eventcontext.getmessage().getpayloadasstring(); jmsconnector amqconnector = (jmsconnector) eventcontext.getmulecontext().getregistry().lookupconnector("active_mq"); connectionfactory factory = amqconnector.getconnectionfactory(); connection connection; connection = factory.createconnection(); try { connection.start(); session session = connection.createsession(false, session.auto_acknowledge); queue queue = session.createqueue("examplequeue"); messageproducer producer = session.createproducer(queue); temporaryqueue replyqueue = session.createtemporaryqueue(); textmessage message = session.createtextmessage(payload); message.setjmsreplyto(reply...

magento - Adding Grid Serializer of a custom module into a custom product tab -

i new magento. have made custom module named "custom_press" using module creator , customized little bit. working fine. following fields in form of module. press title press image press date press thumbnail status i want show of data in grid serializer in custom product tab. press can selected grid serializer against product default magento functionality of upsell , cross-sells product's grid serializer. you need add new tab tabs block 'namespace/module/block/adminhtml/form/edit/tabs.php': $product_content = $this->getlayout()->createblock('module/adminhtml_form_edit_tab_product', 'adminform_products.grid')->tohtml(); $serialize_block = $this->getlayout()->createblock('adminhtml/widget_grid_serializer'); $serialize_block->initserializerblock('adminform_products.grid', 'getselectedproducts', 'products', 'selected_products'); $serialize_block->addcolumninputname(...

python.net - Does Python for .NET event handler execute in a worker thread -

i have python .net (2.7) script subscribes event defined in .net assembly. when event fires , python-based event handler called, handler executing in python's main thread or in worker thread? ... def myeventhandler(source, args): print 'received message: ' + args.message ... dotnetobject.someevent += myeventhandler ... i figured must worker thread when put line of code in handler: print threading._active it reported main thread: {8920: <_mainthread(mainthread, started 8920)>} how can tell thread given line of python executing in? update: okay, found threading.current_thread(). outside of handler returns: <_mainthread(mainthread, started 7064)> while inside handler returns <_dummythread(dummy-1, started daemon 7916)> so "dummythread" worker thread? why didn't show in threading._active? thanks. dummythreads worker threads , show in call: threading.enumerate() so, yes, event handler execut...

PHP: analyse variable -

i creating website school. i have subjects of student saved in database. it's saved --> 1,2,3,6,7 this means student x subject id 1,2,3, 6 , 7 the subjects 1 student returned database in 1 variable $subjects output subject name (subject names stored in database). since variable returned in $subjects not 1 subject, multiple, can't search subject name. possible convert $subjects array $subjects[0] 1 in example , $subjects[1] 2 (see above @ it's saved this). simply said: should not $subjects = 1,2,3,6,7 but $subjects[0] = 1 $subjects[1] = 2 $subjects[2] = 3 $subjects[3] = 6 $subjects[4] = 7 you can use explode convert string array: explode(',', $students); it should noted, however, exploding , doing more queries database subject names inefficient way this. rather store students subjects in 1 field should create whole table relationship. in additional students table , subjects table, have relationship: table: studentsubjects stude...

php - What is this encoding \u0641\u0648\u0627\u0632 -

when json data server in xcode if result content arabic character shows \u0641\u0648\u0627\u0632 what encoding this? how can decode ? it looks unicode characters (arabic symbols in case)

mysql - SELECT unique values and the associated timestamp without having the timestamp making things unique -

i apologize poorly worded question. it's best illustrated through example , i've come far: table "myinfo" has columns: 1. id (pk) 2. key 3. value 4. metaid table "meta" has columns: 1. id (pk) 2. metaname 3. metavalue 4. instancenum metaid in "myinfo" table correlates instancenum in "meta" table. value of "value" column changes on different rows metaid. think of metaid link timestamp value in "meta" table("timestamp" , value go metaname , metavalue columns respectively). i want select distinct values of 'value' column in "myinfo". far have: select distinct mi.key, mi.value myinfo mi join metadata meta mi.metaid=meta.instancenum , meta.key = 'timestamp' , mi.key='maxweight'; but want timestamps associated values. want output like: key value timestamp maxweight 10 tons 15:00:05 2011-01-01 maxweight 5 tons 08:00:07 2011-10...

matlab - How can I extract the ROI from mammogram image without using the im2bw function -

when using matlab code roi extraction mammography image (unit8) must convert binary image. need extract roi without using convert function. i'm using code org = imread('mdb.pgm'); org = im2bw(org); ext = org(any(org,2),:); ext = ext(:,any(org,1));

chromecast - What do I put as cast.receiver.RemoteMedia.NAMESPACE? -

on receiver examples see cast.receiver.remotemedia.namespace used. supposed replaced own name? tried using 'ramp' tried 'myownnamespace' , 'ramp','myown' , of brackets around them. time change cast.receiver.remotemedia.namespace code stops working. below code talking about: var receiver = new cast.receiver.receiver( 'your_app_id_here', [cast.receiver.remotemedia.namespace], "", 5); var remotemedia = new cast.receiver.remotemedia(); remotemedia.addchannelfactory( receiver.createchannelfactory(cast.receiver.remotemedia.namespace)); i tried found on document, didn't work either. var receiver = new cast.receiver.receiver('myappid', ['ramp', 'other']); var ramphandler = new cast.receiver.remotemedia(); ramphandler.addchannelfactory(receiver.createchannelfactory('ramp')); var channelhandler = new cast.receiver.channelhandler('other...

random - Is it more secure to use a cryptographically secure PRNG to generate passwords? -

we have script stand new web server @ job. script involves creating number of accounts run services, app pools etc. we needed create password each of these users -- i.e. generate 32-or-so-character ascii string used logon password. we had disagreement whether 1 ought use cryptographically-secure prng job, or whether using non-cryptographically secure prng (with time-dependent seed) suffice (we work in .net, concrete decision between generating strings system.random , using rngcryptoserviceprovider -- however, not language-specific issue). must 1 use cryptographically-secure randomness generating passwords, or sensibly-seeded plain prng sufficient? in many cases, attacker can recover state of (non-cryptographic) random number generator few output values – without knowing seed. after that, it's trivial predict future , previous random numbers. how many outputs required depends on algorithm. in case of linear congruential generator, such java's java.util.ran...

batch file - if %variable% ==, not working -

so making rpg, pokemon style fighting game (with movie characters) test skills, need more work. batch (.bat) file, using notepad++. " katniss " part work, while other 3 don't work. %char% (character) set , katniss works can't problem there. problem " if " statement think. here fragment of code, have whole thing it's around 400 lines , i've narrowed down section using pause s. `:character2 cls rem --------------------------------------------------characters aren't working here if %char% == katniss set hp=100 set mattack1=knife set rattack1=arrow set rattack2=fire arrow set rattack3=explosive arrow set block1=bow block set armr=2 set energy=140 set m1enc=50 set m1hpd=25 set m2enc=25 set r1hpd=20 set r1enc=65 set r2hpd=50 set r2enc=110 set r3hpd=75 set r3enc=140 set bk1md=5 set bk1ec=50 set defense=2 goto corc if %char% == gandalf set hp=120 set mattack...

java - Program that should work, but it isn't -

this question has answer here: how compare strings in java? 23 answers import javax.swing.imageicon; import javax.swing.joptionpane; public class example { public static void main(string[] args) { string name; name = joptionpane.showinputdialog(null, "enter test below:"," ",3 ); if (name == "test") { joptionpane.showmessagedialog(null, "welcome " + name + ", works "," ", 1, new imageicon("pictures/example.jpg")); } else { joptionpane.showmessagedialog(null,"welcome " + name + ", doesn't work."," ", 1, new imageicon("pictures/example.jpg")); } } } instead of comparing strings this: name == "test" you should use this: name.equals("test...

Passing Special Characters to PHP via AJAX -

i'm collecting form data, sending php validation script through ajax call. issue on special characters php validation script not working expected. html: <input type="text" name="firstname" class="firstname" placeholder="[first name]" required autofocus maxlength="25" size="25" /> js: $(".button").click(function () { var firstname = encodeuricomponent($("input.firstname").val()); var datastring = "firstname=" + firstname; $.ajax({ type: "post", url: "/scripts/validatesignup.php", data: datastring, cache: false, success: function (errormessage) { //print screen } }); }); php validation $postdata = $_post; if (filter::validatestring($postdata['firstname']) == false) { echo "oops! characters used in first name not valid."; } php filter //returns t...

python - Extending pylint to deal with template variables? -

i wrote say module make formatted printing simpler , more straightforward. e.g. say("{len(items)} retrieved; {n_errors} encountered") rather than: print("{0} retrieved; {1} encountered".format(len(items), n_errors)) that part going great. run pylint gotchas , mistakes. unfortunately, many data values constructed solely usefulness in output operations, , pylint cannot "see" use in say call (or other templates output mechanism) constitutes genuine use of variable. wave after wave of w0612 (unused-variable) warnings can result. it's possible put in ignore comments, seems retrograde. i'd rather extend pylint understand variables used in say() templates are, in fact, used. .../pylint/checkers/variables.py appears place add check, i'm unfamiliar codebase. hints or suggestions how register variables used in format-style strings are, indeed, used? in 'variables' checker, used variable removed self._to_consume[-1] ...

c# - How to close the previous window when a new window shows -

this scenario: my first window contains listview, each items in listview contain button, if user click button, detail window shows. i don't want application shows many window, 1 enough, if user click item, window shows, , when user click item, content of window changes, doesn't create new window show. make window singleton, of content using databinding (mvvm pattern), if close window, resource disposed, not show again, override closing method, let window cancel, not closed, in way, close application, window still not been disposed, there's process can see in task manager. anybody has more sensible idea? thanks. edit: private void window_closing(object sender, system.componentmodel.canceleventargs e) { e.cancel = true; this.visibility = visibility.hidden; } try making custom user control can loaded dynamically in run-time. example: //constructor builds customer user control using form argument itemcontrol control = new itemco...

SQL join two record into one row with multiple column -

i want join 2 record (from same table) 1 row multiple column. employment history structure follows: staffid startdate enddate deptid ================================================== 1 2010-10-01 2011-01-19 1 1 2011-01-20 2012-12-31 2 1 2013-01-01 2013-05-29 4 how can join 2 rows 1 row if same staffid , 2nd record startdate 1 day after enddate of 1st record (continuous employment) the output should this staffid effectivedate new_deptid prev_deptid ================================================== 1 2011-01-20 2 1 1 2013-01-01 4 2 the following sql statement doesn't work select distinct ca1.staffid, ca1.projectdepartment prev_deptid, ca1.startdate, ca1.enddate, ca2.projectdepartment new_deptid, ca2.startdate, ca2.enddate emp_hist ca1, emp_hist ca2 (ca1.staffid = ca2.staffid) , ca1.startda...

javascript - jQuery fadeIn/Out stuttering with rounded div -

i have circular div contains image. on hover of image i'd opacity change black , display overlapping div containing information. far i'm able hover when users mouse crosses 200px x 200px div boundary, fadein fires - isn't bad thing. when user moves mouse within circle, fires again. ideas? html: <div class="prodava" onmouseover="jquery('#fader-123').fadein('fast');" onmouseout="jquery('#fader-123').fadeout('fast');"> <a href="www.google.com/asd" class="product_item_link"> <img src="theimage.jpg" /> <div id="fader-123" class="prodavahl" style="display: none;"> <span>hello</span> </div> </a> </div> css: .prodava { position: relative; border: 1px solid white; border-radius: 1px; display: block; height: 200px; ...