Posts

Showing posts from January, 2014

concurrency - Concurrent blocking queue in C++11 -

for message passing in between threads, i'm looking concurrent queue following properties: bounded size pop method blocks/waits until element available. abort method cancel wait optional: priority multiple producers, 1 consumer. the concurrent_bounded_queue of tbb provide that, i'm looking alternatives avoid additional dependency of tbb. the application uses c++11 , boost. couldn't find suitable in boost. options? naive implementation using boost library(circular_buffer) , c++11 standard library. #include <mutex> #include <condition_variable> #include <boost/circular_buffer.hpp> struct operation_aborted {}; template <class t, std::size_t n> class bound_queue { public: typedef t value_type; bound_queue() : q_(n), aborted_(false) {} void push(value_type data) { std::unique_lock<std::mutex> lk(mtx_); cv_pop_.wait(lk, [=]{ return !q_.full() || aborted_; }); if (aborted_) throw operation_aborted();

java - How to make Apache Tomcat accept DELETE method -

i'm working on project of restful web services, i'm using apache tomcat , jax-rs. i want accept delete requests client whenever send delete request advanced rest client chrome plugin gives response code 403 forbidden. so how can make apche tomcat accept delete request? tomcat blocking delete methods me because of cors filters. i needed new filters registered in web.xml file. here's example of permissive one: <filter> <filter-name>corsfilter</filter-name> <filter-class>org.apache.catalina.filters.corsfilter</filter-class> <init-param> <param-name>cors.allowed.headers</param-name> <param-value>accept,accept-encoding,accept-language,access-control-request-method,access-control-request-headers,authorization,connection,content-type,host,origin,referer,token-id,user-agent, x-requested-with</param-value> </init-param> <init-param> <param-name&

runtime - what is the GOMAXPROCS default value -

is guaranteed gomaxprocs set 1 when environment variable of same name not set? this code shows value: package main import ( "runtime" "fmt" ) func getgomaxprocs() int { return runtime.gomaxprocs(0) } func main() { fmt.printf("gomaxprocs %d\n", getgomaxprocs()) } and running this: $ gomaxprocs= go run max.go gomaxprocs 1 shows 1 in case, looking confirmation here. no, there's no guarantee default is; though known implementations use value '1'. if code, in absence of environment variable, requires specific default value should set in code. additionally : gomaxprocs sets maximum number of cpus can executing simultaneously , returns previous setting. if n < 1, not change current setting. number of logical cpus on local machine can queried numcpu. this call go away when scheduler improves. (emphasis mine)

Mule ESB annotation doesn't work -

i try use @schedule annotation in mule esb, not work. don't know what's wrong it. java code : public class mycache { @schedule(interval=1000) public void writestr(){ log.debug("111112222222223333333334444444444"); system.out.println("111112222222223333333334444444444"); } } for reason goes beyond imagination, have use @schedule annotated java components in obsolete model/service container work. your above class (that put in com.acme package) works following on mule 3.4.0: <model> <service name="mycachescheduler"> <component> <singleton-object class="com.acme.mycache" /> </component> </service> </model>

javascript - How can I define two model in html with AngularJs -

i new angularjs if want define 2 model in html how define it? i haved tried times please help <body ng-app="experiment"> <div ng-controller="functioncrtl" id="staff"> <div ng-modle="data1.data"> <ng-view></ng-view> </div> <div ng-app="experiment_left"> <div ng-controller="accordtioncrtl"> <div ng-model="accordtion.accordtion"> <ng-view></ng-view> </div> </div> experiment.config (function($routeprovider) { $routeprovider.when("/",{ templateurl : "function1.html", controller: 'functioncrtl'}); i want dynamic load 2 page , how can do? but answer question read http://docs.angularjs.org/api/ng.directive:input . controller: angular.module('myapp').controller('createuserctrl', function ($scope) { $scope.firstname = 'john'

javascript - video is not playing in IE8 by mediaelement.js -

i not able play video in ie8 using mediaelementjs. i using html5 video tag , want video played in ie8 , below browsers. i know ie8 doesn't support html5 video tag.hence implementing mediaelement.js make video play in ie8. can tell me how make video play in ie8 using mediaelement.js(html5 video tag)? i guess something's wrong <script> tag. ie takes html errors more seriously, if forgot close / forgot type="text/javascript" , chose example xhtml 1.0 strict doctype, mediaelement.js can not used. or can have error elsewhere of course, can't identify unless showing code.

serialization - Can serialVersionUID of java standard objects change ? -

on project, have several objects serialized. necessary use these objects on machine different jvm (possibly different versions). our objects serialversionuid fixed , won't change, concerned serialversionuid of jvm standard objects, instance arraylist/hashset used in our serialized objects. so question is, can these serialversionuid change between different versions of jvm or between different jvm ? or have use serialization mechanism support different jvms ? the serialversionuid should changed if there change class not compatible serialized versions of it. to see changes potentially break compatibility check specification i highly doubt new version of java introduce changes core classes break compatibility.

php - modrewrite/htaccess - force default language in url -

i'm struggling modrewrite/htaccess problem (using php). i'm running multi-language web has urls www.mydomain.com/en/index.php " en " translate &lang=en now i'm looking way force english default language url- eg. if user tries accessing url www.mydomain.com/dashboard.php , should automatically translate www.mydomain.com/en/dashboard.php any ideas how solve this? thanks assuming have list of languages site supports: rewritecond %{request_uri} !^/(en|fr|es|de)/ rewriterule ^(.*)$ en/$1 [r] this rewrite url if doesn't start either /en/ , /fr/ , /es/ or /de/ .

character encoding - Has PHP's behaviour changed? -

studying zend-ce exam, came across question: given php.ini setting of: default_charset = utf-8 following code print in browser? <?php header('content-type: text/html; charset=iso-8859-1'); echo '&#9986;&#10004;&#10013;'; ?> a. garbled data b. & # 9986 ; & # 10004 ; & # 10013 ; c. blank line due charset mismatch the expected answer c, expected - , when ran code, got garbled data (answer a)! wonder if phps behaviour had been changed or if error in test? i not aware php behaviour has changed in respect. however, html standard has changed. prior html 4, numeric character references such &#9986; interpreted respect document character set (which specified in content type header field). reasonable that, code point 9986 not exist in iso 8859-1, nothing printed. since html 4, numeric character references interpreted unicode code points. echo '&#9986;&#10004;&#10013;'

About Timer and Action...Help!!----(Android App) -

there problem! want action after second change words after 5 second.i set besides setting of timer. i think easy pick android 3 days. should do? use alarmmanager repeating actions. example: pendingintent pintent = pendingintent.getservice(context, 0, new intent(context, yourintenthere.class), 0); alarmmanager alarm = (alarmmanager) context.getsystemservice(context.alarm_service); alarm.cancel(pintent); alarm.setrepeating(alarmmanager.rtc, calendar.getinstance().gettimeinmillis(), iinterval, pintent); so encapsulate logic want repeat in wich capable intent (activity or service). alternatively use asynctask sleep, not recommend sth that. see also: http://developer.android.com/reference/android/app/alarmmanager.html http://www.techrepublic.com/blog/android-app-builder/use-androids-alarmmanager-to-schedule-an-event/

javascript - Executing a function attached to a button -

i trying execute function has been pre-declared. function attached button when click button error message 'popuppicker has not been declared'. below copy of function , buttons trying execute function. function popuppicker(ctl,w,h) { var popupwindow = null; settings='width='+ w + ',height='+ h + ',location=no,directories=no, menubar=no,toolbar=no,status=no,scrollbars=no,resizable=no,dependent=no'; popupwindow=window.open(<%= getservername.getservername("/quoteman/datepicker.aspx?ctl=") %> + ctl,'datepicker',settings); popupwindow.focus(); } this buttons. <td style="width: 120px"> <asp:textbox id="dateouttxt" runat="server" width="80px"></asp:textbox> <asp:imagebutton id="imagebutton5" runat="server" borderstyle="none" imageurl="~/icons/vwicn063.gif" onclientclick="popuppicker('dateouttxt

jquery - Do we need to unbind event listeners in directives when angular starts to destroy? -

there heavy memory leak in application haven't found out causes, , here background. i using angularjs + jquery(plugins) many listeners bound following: $(element).on("keyup", function() {}); so question is do need unbind listeners in directives following? scope.$on("$destroy", function() { $(element).off(); }); btw, how find out memory leak in web application? use chrome's profile (see here profiling memory performance ) not trace codes memory leaks. have suggestions? thanks lot! the angular documentation scope destroy, implies need remove dom events. http://docs.angularjs.org/api/ng.$rootscope.scope#$destroy note that, in angularjs, there $destroy jquery event, can used clean dom bindings before element removed dom.

onclick - GWT - How to retrive real clicked widget? -

i have onclick event on somepanel. , click on , works. but.. how retrive real click target? when click on panel inside od somepanel show me click on somepanel.. i know have this: element e = element.as( event.getnativeevent().geteventtarget()); but returns element - want widget.. how this? i use feature in gwtquery widget associated given element: https://code.google.com/p/gwtquery/wiki/gettingstarted#manipulating_your_widgets widget = $(e).widget(); the problem element clicked couldn't element associated widget child. in case use gquery selectors traverse dom until parent widget based on css property. // gwt widgets contains class .gwt- fail // use more accurate selector 1 in example widget = $(e).closest("[class*='.gwt-']") if wanted yourself, taking method getassociatedwidget in gquery gives solution: eventlistener listener = dom.geteventlistener(e); // no listener attached element, no widget exist element if (listener ==

android - eclipse, your project has error ,please fix it -

i have android application integrated google maps v2, using support v4, want integrate facebook, downloaded facebook sdk, , used in program , perfect, want use facebook sdk in main project, imported did in dummy project put has problem because facebook sdk has suppor v4 jar, deleted support v4 , there no syntax error nor compilar error nor error. but eclipse put `x` sign in project , when wanted run , told me project has errors, error please, me find or thing , thanks i had faced issues faced. had resolved. eclipse reason chose keep facebook project java 1.5 eventhough eclipse preferences had setting use java compiler 1.6. so, go project properties in facebook project , select java compiler 1.6. solved problem. hope solves yours too.

svn - SmartSVN how to revert ignored files -

i ignored few files using smartsvn. now, want revert changes. read following command can used: svn propdel svn:ignore -r but there error: "the path '.' appears part of subversion 1.7 or greater working copy. please upgrade subversion client use working copy." what best way revert ignore operation ? to undo ignore, can use smartsvn: right click directory in ignored files reside, in pop-up menu choose properties -> ignore patterns... you dialog, shows file patterns set ignored. remove ones not needed , save. locally effective immediately, have commit property change (the directory) make change permanent in repository.

MongoDb: Query not pulling item from array - why? -

the intention of query below pull items locs array, x=2 , y=9. items these values remain in array after query. db.mycollection.update( { }, //all records { $pull: { 'locs' : { $elemmatch : {'x' : 2 , 'y' : 9 } } } } ) could tell me why it's not working? edit: example document: { "_id" : objectid("55555555555"), "locs" : [{ "x" : 2, "y" : 9 }], "v" : 99 } in general, $pull not work this. removes "a value array" ( http://docs.mongodb.org/manual/reference/operator/pull/ ). can not use $elemmatch here, neither have to. so if have document looks this: { 'title': 'example', 'locs': [ { x: 2, y: 12 }, { x: 7, y: 9 }, { x: 2, y: 9 }, ] } the follow should remove x:2 / y:9 value pair: db.so.update( {}, { $pull: { 'locs' : { 'x' : 2 , 'y' :

web services - 401: Unauthorized Exception occurred with an apache axis client(java) to invoke a webservice(.net) with an NTLM Authentication Technique -

i calling web service written in .net located remotely running under iis server. i created respective stub using apache axis 1.4 eclipse ide , created respective web service client. test client in actual web application going call web service. we have kept 2 different endpoint keeping security credential enable/disable. "ip:port/pigeon/pigeon.svc;" // authentication disabled "ip:port/pwa/pigeon.svc; // authentiction enabled so when using endpoint no (1) able call web service , gets things done, since want apply security credential mandatory when use endpoint no (2) getting below exception (401)unauthorized (401)unauthorized axisfault faultcode: { http://xml.apache.org/axis/ }http faultsubcode: faultstring: (401)unauthorized faultactor: faultnode: faultdetail: {}:return code: 401 i want pass credential in format : 1) domain\username 2) password i tried adding suggestion of other post on here says set respective before ca

asp.net mvc - Drop down / SelectListItem in ViewModel MVC -

i new mvc , have been told not use selectlistitem in view untidy. advised put in model , pass view. i have no idea whether code in model correct. assistance highly appreciated. code here: public class zipcodemodel { public string zipcode { get; set; } public static readonly ienumerable<selectlistitem> items; static zipcodemodel() { items = new list<selectlistitem> { new selectlistitem {text = "a"}, new selectlistitem {text = "b"}, new selectlistitem {text = "c"}, new selectlistitem {text = "d"} }; } } thanks in advance :) try this @html.dropdownlistfor(m => m.zipcodemodel, new selectlist(m.audiothemes, "value", "text"), new { @class = "class" })

objective c - How do I write the method name of a variadic method that also contains known arguments? -

i'm trying make method accept unknown number of arguments, , known number of other arguments. i'm wondering syntax of naming method. method body seems fine. i realize make method take known arguments first , unknown arguments , this: -(id)init: (nsstring*)type withmodifier:(nsstring*)mod withnames:(nsstring*)names,...; i'm looking list unknown arguments first, followed known arguments. how name method this? this i'm trying do, proper syntax of course: -(id)initwithnames: (nsstring*)names,... withtype:(nsstring*)type withmodifier:(nsstring*)mod; thanks help. you can't - the variadic argument must last one. try initwithtype:(nsstring *)t modifier:(nsstring *)m names:(nsstring *)n, ... instead.

vbscript - VBS - script works on Windows 7 a doesnt work on Windows 8 -

whats wrong? code works on windows 7 , doesnt work on windows 8. looks error code null time. dim objshell, reglocatename, reglocatedn0, strname set objshell = wscript.createobject("wscript.shell") on error resume next set objuser = getobject("ldap://" & struser) set objsysinfo = createobject("adsysteminfo") struser = objsysinfo.username set objuser = getobject("ldap://" & struser) strname = objuser.fullname strphone = objuser.homephone reglocatename = "hkey_local_machine\software\activa\activatsp\calleridname0" reglocatedn0 = "hkey_local_machine\software\activa\activatsp\dn0" set shell = createobject( "wscript.shell" ) shell.regwrite "hkey_local_machine\software\activa\activatsp\authtype", 1, "reg_dword" 'shell.regwrite "hkey_local_machine\software\activa\activatsp\calleridname0", "" & strname , "reg_sz" objshell.regwrite reglocatename,strname,&

java - Differences between these 2 factory methods -

i know difference between these 2 methods: public static executorservice newfixedthreadpool(int nthreads) and public static executorservice newfixedthreadpool(int nthreads, threadfactory tf) obviously 1 takes specified threadfactory threads creation. know kind of standard threadfactory former use? why convenient using latter rather former or vice-versa? in advance. the first 1 uses defaultthreadfactory inner class of executors . when define own threadfactory can influence created threads. can choose name, priority, etc.

queue - Queuing jQuery $.each iterations -

i'm guessing should simple, can't life of me find out how it. i have each loop, runs through number of products, , runs function against each of them. function, amongst other things, updates table product's information. however, need wait until 'runthisfunction()' completes, before moving on next product, , running function again. for example; $.each(data.products, function(id, v) { runthisfunction(v); }); inside runthisfunction(), pulls information product localstorage database, because runs quickly, moves on next product before it's done needs do. add delay, don't want purposely slow down. i know should simple... have @ queue() function of jquery. http://api.jquery.com/queue/ another useful source: what queues in jquery?

binding - How to bind properties of two UI objects in Java? -

i have simple java application textfields , buttons. looking best , quick way bind state of 1 jtextfield state of 1 jbutton. i'm using eclipse, don't need tricks of netbeans ide. suppose user needs input value textfield in order able send request. button should enabled if value of textfield not empty , consists @ least of 3 symbols. if user deletes input, button becomes disabled. i come flex-world. such task can solved there easy. 1 should write this: <mx:button enabled = "{mytextfield.text.length >= 3}" /> is there such opportunity in java? how called? hope, don't need write event listeners each pair of logicaly connected ui elements, i? i documentlistener on jtextfield. every time document changes, check state of button, button.setenabled(textfield.gettext().length > 3)

regex - PHP : preg_match_all none xhtml attributes -

i want improve code not know how write regexp. i want none xhtml attributes in tag. so after preg match want : array( 0 => "required", 1 => "autocomplete" ); $balise = <input id="myid" class="myclassa myclassb myclassc" required autocomplete/>; i use preg_match_all("/(?<=\s)[\w]+(?=[\s\/>])/i", $balise, $attributs); but regexp : array( 0 => "myclassb", 1 => "required", 3 => "autocomplete" ); i not want myclassb ... can me write regex ? thx you can add negative look-ahead (?![^=]*?") make sure next " doesn't precede next =, way you're getting words aren't within quoted value. single-quote string " in regex won't terminate it. preg_match_all('/(?<=\s)[\w]+(?=[\s\/>])(?![^=]*?")/i', $balise, $attributs);

c++ - Problems linking .o library files together into a shared object -

i working on collection of reusable libraries need made available both static libraries (.a & .lib) , dynamic libraries (.so & .dll). i want dependency management dynamic libraries simple possible (you take 1 dynamic library each bit of functionality need), of functional dependencies each dynamic library has statically linked it. thus, dynamic libraries offer functionality downstream clients dynamically, upstream dependencies satisfied statically. the upshot of all of static libraries need compiled -fpic code suitable linkage shared library. same goes third-party library use. has static library, compiled -fpic. (i could, suppose, build both pic , non-pic variants of libraries - not want compile libraries third time each target platform -- twice quite (more than) enough!). so, here problem: i have been trying compile boost_system static library -fpic, not sure if succeeding: /b2 --build-type=complete variant=release link=static threading=multi runtime-link=stati

haskell - How do I make cabal-dev build documentation by default -

i work in places in have no internet access. move place in have minimal internet access. having documentation locally on system absolutely invaluable me. using straight cabal, i'm able enabling documentation option in configuration file. how can same effect cabal-dev? specifically, when install package using cabal-dev, want package documentation generated , index.html file project's documentation directory updated include package. update : question duplicate of documentation cabal-install configuration file edit ~/.cabal/share/cabal-dev-$version/admin/cabal-config.in , set value of documentation field true . cabal-config.in file template used initialising cabal-dev/cabal.config when creating new sandbox. if want enable documentation existing cabal-dev sandbox, edit cabal-dev/cabal.config . for users of cabal's native sandboxes: either enable documentation in ~/.cabal/config or create file cabal.config in same directory cabal.sandbox.confi

android - I want to start a new activity when I click on a listview item -

i set onitemclicklistener crashes when click on 1 of list item. want know if can done here code update: public class inbox extends listactivity { private static string[] numbers; private static string[] content; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.inbox_list); dictionaryopenhelper helper = new dictionaryopenhelper(this,"mytable", null, 2); sqlitedatabase database = helper.getreadabledatabase(); cursor c = database.rawquery("select * mytable", null); numbers = new string[c.getcount()]; content = new string[c.getcount()]; c.movetofirst(); int count = 0; do{ numbers[count] = c.getstring(c.getcolumnindex("phonenumber")); content[count] = c.getstring(c.getcolumnindex("message")); count++;

java - JdbcDaoSupport with a SQL SELECT FROM INSERT -

i trying create "select insert" within spring jdbcdaosupport class , having trouble figuring out how get data select statement , return it. my eventjdbctemplate (my daoimpl): @service public class eventjdbctemplate extends jdbcdaosupport implements eventdao { private static final logger logger = logger.getlogger(eventjdbctemplate.class); private static final string sql_insert_event = "select event_id final table " + "(insert ebt10dbb.sb0401t0 (event_name, host_name, user_id) " + "values(?, ?, \'emp0321\'))"; @autowired public eventjdbctemplate(datasource pdatasource) { super.setdatasource(pdatasource); } @override public integer createevent(eventbean peventbean) { //(integer id, string eventname) if (logger.istraceenabled()) { logger.trace("entering create(event event) of eventjdbctemplate."); } // sql works, insert only. /*this.getjdbctemplate().query(sql_insert_event,

visual studio - What is a .sln.ide file? -

i have visual studio 2012 solution /foobar.sln . contains 1 class library project , 1 unit test project. few days ago noticed new file /foobar.sln.ide/graph/foobar.sln.ide . contents: <solution format="0.0.0.3"> <version>0001-01-01t00:00:00z</version> </solution> i'm not sure doing when created, since didn't notice until few days after created. today, several days later first asked question, appeared again in excel vsto add-in project. guess it's related closing solution, since appeared in between time committed changes , time opened new project (not vs project, file being edited). haven't reproduced it. what created file? do? safe delete? should checked in source control? are using "roslyn" compiler. if so, creates .sln.ide folder in solution folder. believe it's complier caching.

php - unique combination of arrays -

i want write function return random unique pair numbers every time call range until resetting it. this: function randomuniquepairs($ranges, $reset = false){ if ($reset === false){ // code reseting } /* code creating random unique pair numbers */ return $result; } randomuniquepairs(range(1,10), range(1,20)); /* function returns example: array(2,9) */ randomuniquepairs(range(1,10), range(1,20)); /* function returns example: array(5,19) */ randomuniquepairs(range(1,10), range(1,20)); /* function returns example: array(5,19) */ //this function returns random unique pairs until pass reset paramer true i try 2 approaches: 1)one them make of possible pairs select them randomly, inefficient, because if ranges wide, consumes lot of memory. code: class { private $asqar; function __construct() ($range) { // cycle ranges foreach ($range[0] $v1) { foreach ($range[1] $v2) { $asqar[] =

can't read json items with jquery -

i've got unordered list customer names json file. want add click event, jquery can't seem read it. list looks in html source file, list items don't show in console.log . manual added dummy customer handles click event fine. html <ul id="customers"> <li>dummy customer</li><!-- manually added test --> </ul> js (filling unordered list) var getcustomers = 'json_webservice_api_i_can't_share'; $.getjson( getcustomers ) .done(function( data ) { for(var = 0; < data.length; i++) { $('#customers').append('<li>' + data[i].name + '</li>'); } }); js (click event) $('#customers li').click(function() { console.log($(this).text()); } i'm guessing text inside list items filled customer names json file no real strings(?). or that. can help? chances you're binding event when not have li elements try $(document).on('click', &

php - showing module code once when multiple joomla modules in same page -

in joomla menu item page placed same module instances multiple times(i duplicated in module manager).now it's severe requirement codes of module have 1 time in page.because module's each instance injects same code again , again. how avoid codes appear in page once when have multiple module instances of module in same page? searching through web found unreliable ways - 1.using session in module track whether same module loading 2 or more times , restrict code injecting 1 time 2.using constant way - if(!defined('module_already_loaded')){ //echo codes want done once //this set constant , other modules won't load/echo code define('module_already_loaded', true); } but not sure how compatible 2nd way joomla 2.5 joomla 3 versions !.if there better error free way provide me asap. in module code, can use addscript method (it checks duplicate scripts) instead of writing js directly. so, externalize scripts, in code : $document = jfactory::getdocume

json - Phonegap - jQuery Mobile and very large listview -

in page of app, developed phonegap , jquery mobile, loading data json external file. these data compose listview on web application. the problem when click voice list, page called flickering; same effect when go list page (header particulary). i think longer lists should paginate. best way? try this.. <div data-role="header" data-theme="d" data-position="fixed" data-tap-toggle="false" > <div data-role="footer" data-theme="d" data-position="fixed" data-tap-toggle="false" > fixed data-position="fixed" , data-tap-toggle="false", when tap on page, header , footer not flickered .

multithreading - Android - AsyncTask fatal exception -

i load image in bitmap javacameraview. 1 send async task in order send php file. during first-second there no problem. after time, have problem of thread don't find solution. logcat : 07-25 16:36:29.492: e/androidruntime(17507): fatal exception: asynctask #5 07-25 16:36:29.492: e/androidruntime(17507): java.lang.runtimeexception: error occured while executing doinbackground() 07-25 16:36:29.492: e/androidruntime(17507): @ android.os.asynctask$3.done(asynctask.java:299) 07-25 16:36:29.492: e/androidruntime(17507): @ java.util.concurrent.futuretask$sync.innersetexception(futuretask.java:273) 07-25 16:36:29.492: e/androidruntime(17507): @ java.util.concurrent.futuretask.setexception(futuretask.java:124) 07-25 16:36:29.492: e/androidruntime(17507): @ java.util.concurrent.futuretask$sync.innerrun(futuretask.java:307) 07-25 16:36:29.492: e/androidruntime(17507): @ java.util.concurrent.futuretask.run(futuretask.java:137) 07-25 16:36:

php - Parse page with different encoding -

i made parser wordpress since wp , db using utf-8 , pages in different encoding, when parse them gibrish. use curl content outside urls , match , replace regex. any suggestions how solve problem? i used suggestion joni below , solved problem. sample code used future queries on problem: preg_match("/charset=(.*?)(\n|'|\"|>)/ism", $content, $charset); $content = preg_replace('/^http+[^<]+</', '<', $content); $charset = @trim($charset[1]); if (preg_match("~(windows-1251|1251)~i", $charset)) return 'windows-1251'; elseif (preg_match("~iso-8859-7~i", $charset)) return 'iso-8859-7'; elseif (preg_match("~(koi8|iso-ir-111)~i", $charset)) return 'koi8-r'; detect correct encoding content type header (or html meta tag if header missing) , use when parse document.

Android shuffle Questions and Answers (string arrays) -

i making app in there list of questions , respective answers. questions in 1 string array, while answers in string array. i have implemented following in wish shuffle questions. (of course answers need linked question, else meaningless) code: selected_q = new string[totalnoofq]; selected_a = new string[totalnoofq]; int[] random_code = new int[totalnoofq]; (int = 0; < totalnoofq; i++) { random_code[i] = i; } collections.shuffle(arrays.aslist(random_code)); (int j = 0; j < totalnoofq; j++) { int k = random_code[j]; selected_q [j] = databank_q [k]; selected_a[j] = databank_a [k]; } the code reports no fatal error, selected_q still in sequential order. why? please show me how can amend codes? thanks

regex - Grep unknown number of spaces (linux) -

suppose have file named abc.txt - file contains 2 (or more) lines: word -c (09:35:20) word -c (09:38:49) if run command $ grep "word -c" abc.txt 1st line, because number of spaces between 1 , -c not match 2nd line. there way fix problem? you cannot use grep'word1|word2' /path/to/file spaces between word , -c vary. use + regex character, match @ least 1 of preceding character: grep -e "word +-c" abc.txt this regex reads "match 'word', followed 1 or more spaces, followed '-c'."

How to take path from variable Bash -

this question has answer here: how manually expand special variable (ex: ~ tilde) in bash 13 answers i can't path variable in bash. how correct? example: my@pc:~$ a="~/.bashrc" my@pc:~$ cat $a cat: ~/.bashrc: no such file or directory didn't work, but cat .bashrc and cat ".bashrc" works well. here right answer fedorqui cat $(eval echo $a) the reason issue tilde expanded home directory shell. when store in variable, tilde not expanded , cat looks file .bashrc in folder ~ (rather home directory) there 2 ways around issue: proposed eval, , using $home: a="$home/.bashrc"

python - Following hyperlink and "Filtered offsite request" -

i know there several related threads out there, , have helped me lot, still can't way. @ point running code doesn't result in errors, nothing in csv file. have following scrapy spider starts on 1 webpage, follows hyperlink, , scrapes linked page: from scrapy.http import request scrapy.spider import basespider scrapy.selector import htmlxpathselector scrapy.item import item, field class bbritem(item): year = field() appraisaldate = field() propertyvalue = field() landvalue = field() usage = field() landsize = field() address = field() class spiderbbrtest(basespider): name = 'spiderbbrtest' allowed_domains = ["http://boliga.dk"] start_urls = ['http://www.boliga.dk/bbr/resultater?sort=hus_nr_sort-a,etage-a,side-a&gade=septembervej&hus_nr=29&ipostnr=2730'] def parse2(self, response): hxs = htmlxpathselector(response) bbrs2 = hxs.select("id('evaluationcon

CSS keyframe animation -webkit-transform reset Chrome Bug -

i'm getting bug using css keyframe animation. when animating -webkit-transform property, if add -webkit-animation-play-state: paused; , remove it, animation jumps start , resumes again. here example of in action: http://jsfiddle.net/najff/8/ happens when toggling animation state javascript: http://jsfiddle.net/najff/7/ is there workaround issue? thanks! it's bug issue in webkit, affected might interested in roman komarov's technique of tricking webkit transitions on pseudos via inheritance. checkout below link pseudos :)

converting jquery easying code from ul li to table -

here have jquery easing in/out feature, , trying convert ul li table instead, didn't work me. $(document).ready(function(){ $('.topnav li').find('a[href]').parent().each(function() { var li = $(this), = li.find('a'), div = $('<div>' + '<\/div>'); li.hover(function() { a.stop().animate({margintop: '-135'}, 600, "easeoutback"); }, function() { a.stop().animate({margintop: '0'}, 500, "easeoutback"); }) .append(div); }); }); i'm wondering changes have make other replacing main ul class .topnav li .topnav tr td i used html before: <ul class="topnav"> <li><a href="#">my link</a><div>hello</div></li> </ul> then changed table this: <table class="topnav"> <tr> <td><a href="#">my li

javascript - sharing settings/config between client and backend -

i have application using node.js backend , require.js/backbone frontend. backend has config/settings system, depending on environment (dev, production, beta) can different things. propagate of variables client well, , have them affect template rendering (e.x change title or url of pages). what best way achieve that? i came way it, , seems working don't think smartest thing , can't figure out how make work requirejs optimizer anyway. on backend expose /api/config method (through get) , on client have following module config.js: // module loads environment config // server through api define(function(require) { var cfg = require('text!/api/config'); return $.parsejson(cfg); }); any page/module needs config do: var cfg = require('config'); as said having problem approach, can't compile/optimize client code requirejs optimizer since /api/config file doesn't exist in offline during optimization. , sure there many other reason approach

Google Analytic Event Not Tracking Ruby on Rails -

i wondering whether see wrong way have setup tracking have been testing on , off several days , doesn't seem want track. #index <head> ... <script type="text/javascript" async="" src="http://www.google-analytics.com/ga.js"> ... </head> <body> ... <div class="product-buy"> <a href="<%= url_with_protocol(general.url)%>" onclick="_gaq.push(['_trackevent', 'general', 'click', '<%= general.title %>', '<%= general.position %>']);" target="blank">learn more/visit site</a> </div> ... </body> i believe have followed analytics guide tee no data seems passing? any people can offer appreciated. the issue was passing 3rd argument of '1' string instead of integer. it should have been general.position turned integer .to_f , speech marks moved analyti

c++ - C++11 cin input validation -

what best way in c++11 (ie. using c++11 techniques) validate cin input? i've read lots of other answers (all involving cin.ignore, cin.clear, etc.), methods seem clumsy , result in lots of duplicated code. edit: 'validation', mean both well-formed input provided, , satisfies context-specific predicate. i'm posting attempt @ solution answer in hopes useful else. not necessary specify predicate, in case function check well-formed input. am, of course, open suggestions. //could use boost's lexical_cast, throws exception on error, //rather taking reference , returning false. template<class t> bool lexical_cast(t& result, const std::string &str) { std::stringstream s(str); return (s >> result && s.rdbuf()->in_avail() == 0); } template<class t, class u> t promptvalidated(const std::string &message, std::function<bool(u)> condition = [](...) { return true; }) { t input; std::string buf; wh

Javascript jQuery textbox creation and output -

currently, have 2 table rows 2 textboxes. want buid button allows user add , subtract author row depending on how many want. once increase amount of authors need input, user clicks on generate button, input textboxes outputed @ bottom of page. trying pull off javascript , jquery. ten day old student javascript , jquery , feel if have bit off more can chew. an example of want can found @ lnk: http://www.mkyong.com/jquery/how-to-add-remove-textbox-dynamically-with-jquery/ . however, need input textboxes outputed on same page. <!doctype html> <head> </head> <body> <table> <tbody> <tr> <td>author</td> <td><input type="text" id="1" class="normalinput" placeholder="last"></td> <td><input type="text" id="2" class="normalinput" placeholder="first"></td>

mysql - My Search engine code in php giving me no result -

i making search engine in php,but receiving no or 0 result. when search keywords in database showed me no result. can please me doing wrong.. below code. <?php $k = $_get['k']; $terms = explode(" ", $k); $query = ("select * search "); foreach($terms $each){ $i++; if($i == 1) $query.= (" 'keywords' '%$each%' "); else $query.= (" or 'keywords' '%$each%' "); } //connect db require("./db.php"); $query = mysql_query($query); $numrows = mysql_num_rows($query); if( $numrows>0 ){ while( $row = mysql_fetch_assoc($query) ) $id = $row['id']; $title = $row['title']; $description = $row['description']; $keywords = $row['keywords']; $link = $row['link']; echo "<h2><a href = '$link'>$title</a></

video streaming - Does or will Google Glass support wifi direct? -

i know people have managed it, new android development stumbling badly. want able stream camera frames google glass android device using wifi direct protocol. seems me wifi direct might way kind of data bandwidth. have looked wifi via router , bluetooth. i have been studying google provided sample code learn how this. my questions are: does or google glass support wifi direct? is wifi direct firmware (software) feature or require special hardware? the explorer edition not have feature. i don't know how android functionality google put consumer release version of glass.

sql server 2008 - SP Duration, Locked table? -

i'm working on db wich has lot of trafic, , there times 1 sp(store procedure) has duration of 382656ms , sp easy operation other times (with same parameters) has duration of 200 ms. used profiler tool , , in first case (382656ms), has around 12 millons of reads. 2th (at other day) has 215 reads. the sp this: alter procedure [dbo].[mysp] @id int, @startdate datetime, @enddate datetime, @statusid int set @startdate = convert(datetime, convert(varchar(10), @startdate, 101), 101) set @enddate = dateadd(dd, 1, @enddate) set @enddate = convert(datetime, convert(varchar(10), @enddate, 101), 101) select t3.name, t3.code, sum(cdoi.count) cout1, sum(isnull(s.cant, 0)) count2 table1 t1 with(nolock) join dbo.table2 t2 with(nolo

c# - setting an asp.net label to the title of a jquery dialog -

i set jquery dialog title using asp.net label . possible? i have tried : $(div1).dialog('option', 'title', 'title name'); but title name here static. use asp.net label here instead of 'title name'. i have code updated below : asp.net code : <div id="div1" class="insertbar"> <asp:label id="label2" runat="server" visible="true" font-bold="true"></asp:label> <asp:panel id="panel1" runat="server" horizontalalign="left" scrollbars="auto"> <asp:gridview> *******gridview code ************************ </asp:gridview> </asp:panel> </div> java script code : <script type="text/javascript">

How do I set the default number of threads for Scala 2.10 parallel collections? -

in scala before 2.10, can set parallelism in defaultforkjoinpool (as in answer scala parallel collections degree of parallelism ). in scala 2.10, api no longer exists. documented can set parallelism on single collection ( http://docs.scala-lang.org/overviews/parallel-collections/configuration.html ) assigning tasksupport property. however, use parallel collections on codebase , not add 2 lines every single collection instantiation. there way configure global default thread pool size somecollection.par.map(f(_)) automatically uses default number of threads? i know question on month old, i've had same question. googling wasn't helpful , couldn't find looked halfway sane in new api. setting -dscala.concurrent.context.maxthreads=n suggested here: set parallelism level collections in scala 2.10? seemingly had no effect @ all, i'm not sure if used correctly (i run application 'java' in environment without 'scala' installed explicitly, might

java - POSTing a file to resteasy -

i'm getting error @ bottom of post. can spot issue? resteasy http call: @post @path("/") public void upload(final @multipartform fileuploadform form) { log.info(string.format("/%s/%s/%s/%s", form.geta(), form.getb(), form.getc(), form.getd())); } associated java model: private class fileuploadform { private string a; private string b; private string c; private string d; private byte[] file; @formparam("a") @parttype(mediatype.text_plain) public void seta(final string a) { this.a = a; } public string geta() { return a; } @formparam("b") @parttype(mediatype.text_plain) public void setb(final string b) { this.b = b; } public string getb() { return b; } @formparam("c") @parttype(mediatype.text_plain) public void setc(final string c) { this.c = c; } public string getc() { return c; } @formparam("d") @parttype(mediatype.text_plain) public void s