Posts

Showing posts from September, 2013

Why jQuery .data() function is not accessing HTML5 camel-case data attribute -

i have button in web page: <button class="slidetoggle" data-slidetoggle="slider">slidetoggle</button> when button clicked trying access data stored inside data-slidetoggle attribute useing following code, nothing. $('body').on('click', '.slidetoggle', function(){ alert($(this).data('slidetoggle')); }); but works when use: alert($(this).attr('data-slidetoggle')); this problem occurs when use camel-case data attribute. new html5 , jquery , can not figure out going wrong it. all previous answers miss 1 thing: can work existing html structure. consider this: $('body').on('click', '.slidetoggle', function(){ alert($(this).data('slidetoggle')); // wait, what? }); to understand happens here, it's crucial check following lines in jquery source code : name = "data-" + key.replace( rmultidash, "-$1" ).tolowercase(); data = elem.get

PHP Difference of two assoc Arrays -

i have 2 arrays of assoc arrays: first one: array ( [0] => array ( [24] => s [23] => czarny ) [1] => array ( [24] => m [23] => czarny ) [2] => array ( [24] => l [23] => czarny ) ) and second: array ( [0] => array ( [24] => l [23] => czarny ) [1] => array ( [23] => czarny [24] => m ) ) in output get: array ( [24] => s [23] => czarny ) because 2 of arrays: [0] => array ( [23] => czarny [24] => m ) and [0] => array ( [24] => m [23] => czarny ) are same me. have idea how deal that? tried fourth nested foreach got confused.. this little loop crazy, work. $array1[0][23] = '

c++ - Eigen elements manipulation without loop -

i want check if elements of matrix smaller 0 want assign 0 them, in matlab done using this: ind = find(floatframe < 0); floatframe(ind) = 0; is there equivalent eigen matrices? you can use select function , similar ternary ?: operator in c. example: floatframe = (floatframe < 0).select(0, floatframe)

unix - commandline output lines that are specified in another file -

iam searching command line takes text file , file line numbers (one on each line) (alternatively stdin) , outputs lines first file. the text file may several hundreds of mb large , line list may contains several thousands of entries (but sorted ascending) in short: one file contains data another file contains indexes a command should extract indexed lines first file: many lines of course different , contain important data ... more lines ... more lines second file 1 5 7 expected output many lines more lines more lines the second (line number) file not have exist. data may come stdin (in deed optimum). format of data may vary shown if make task easier. this can approach: $ awk 'fnr==nr {a[$1]; next} fnr in a' file_with_line_numbers file_with_data many lines more lines more lines it reads file_with_line_numbers , stores lines in array a[] . reads other file , keeps checking if line number in array, in case line printed. the trick use

google app engine - How often should you backup appengine HRD data -

we have appengine app, has 300gb of data in hrd.. performed full backup google-cloud-storage every night. has become costly, costing 100 dollar per day. i moved backup once per week. since data in hrd (high replication datastore)... there need backing data? we cannot afford losing data of more day. thats why did daily backup. costs 100 dollar per day. regarding hrd, iare backups needed? recommend. i know business question too, has technical aspects. data stored in hrd replicated in various regions, there no need perform backups, unless you're afraid data can modified / deleted via app or developers console.

gridextra - R: Wrap text within grid.table when string exceeds set length -

i using grid.table within gridextra package display list of survey comments in table format. when comments(string variable) exceeds given length want automatically insert line break "\n". library(gridextra) df<-data.frame(comments = c("here short string", "here long string needs broken in half doesn't run off page", "here short string")) grid.newpage() print(grid.table(df$comments)) i open using different table package if feature available elsewhere. you can use strwrap, d = sapply(lapply(df$comments, strwrap, width=50), paste, collapse="\n") grid.table(d)

java - Remove log debug displaytag -

in application java use library displaytag version 1.2. when execute application, it's appears: 10:50:09.258 [http-8080-1] debug org.displaytag.tags.tabletag - [objeto] first iteration=false (row number=82) 10:50:09.258 [http-8080-1] debug org.displaytag.tags.tabletag - [objeto] first iteration=false (row number=82) 10:50:09.258 [http-8080-1] debug org.displaytag.tags.tabletag - [objeto] first iteration=false (row number=82) 10:50:09.258 [http-8080-1] debug org.displaytag.tags.tabletag - [objeto] first iteration=false (row number=82) 10:50:09.258 [http-8080-1] debug org.displaytag.tags.tabletag - [objeto] first iteration=false (row number=82) 10:50:09.258 [http-8080-1] debug org.displaytag.tags.tabletag - [objeto] first iteration=false (row number=82) 10:50:09.258 [http-8080-1] debug org.displaytag.tags.tabletag - [objeto] first iteration=false (row number=82) how remove because not necessary show debug log. in application , have logging.properties: handlers = org.apach

node.js - Express.js Mocha testing having issues connecting to test db -

i trying test suite run within express.js app, first express.js app first time working mocha , unsure how set up. here test should = require 'should' assert = require 'assert' expect = require 'expect' request = require 'superagent' mongoose = require 'mongoose' config = require '../../config/config' describe "post", -> app = require('../../app') beforeeach (done)-> mongoose.connect config.db, (err) -> if err console.log "error! #{err}" done() describe '/users/:id/activities', -> 'should return created document', (done) -> request(app).post('http://localhost:3000/users/1/activities').send( description: "hello world" tags: "foo, bar" ).set('content-type','application/json') .end (e, res) -> console.log(res.body.description) expect(res.body.

.net - Long beep in vb 2010 -

in vb6 used beep (1000,2000) which means beep(frequency, duration) how make long beep in vb 2010, because doesn't support version. unless missing obvious you're looking console.beep method. signature follows public static void beep(int frequency, int duration) you'll call as console.beep(1000,2000) i believe that's you're after. note: documentation mentions caveat the beep method not supported on 64-bit editions of windows vista , windows xp. thought worth adding here.

cassandra - composite column keys & composite row keys -

i'm trying understand concept of composite column key & composite row key unable it. think it's used getting range of values can't use timestamp column cluster key purpose ? use case, advantages, disadvantages & implementation. please explain using cql 3. composite column key: http://i.stack.imgur.com/qlbok.png composite row key: http://i.stack.imgur.com/xa6hz.png maybe confuse both terms refers how cassandra stores compounds primary keys. i'll explain how composite keys works , how stored physically cassandra 2.0 , cql3. cassandra stores logical rows same partition key single physical wide row. partition key divided in (partition_key, clustering_key). partition_key: identifies row in cassandra. registers same partition_key go same machine , store together. can compound partition_key. clustering_key: keep data same partition_key ordered. can set multiple clustering keys separated commas. imagine have table purchase definition: create

c# - Google maps api in updatepanel - HTML in InfoWindow do not show up on refreshing update panel -

i have google map canvas inside update panel . map refreshes content(location) every time update panel refreshes. need show content in tabular format in infowindow . problem if use html tags in infowindow shows first time when application loads , when refreshing update panel application freezes. if use plain strings in infowindow content shows every time. here's code in c# generating tabular content of infowindow. sb.append("<div id=\"content\"><table>"); foreach (datarow dr in dt.rows) { sb.appendline("<tr><td>" + dr[0].tostring() + "</td></tr>"); } sb.append("</table></div>"); this doesnt works after updating update panel. below code works: stringbuilder sb = new stringbuilder(); foreach (datarow dr in dt.rows) { sb.appendline(dr[0].tostring()); } i putting generated string hiddenfield , using in js file this: var contentstring = document.getelementby

javascript - Android Hybrid App : JQueryMobile ajax is not working with https but works with http -

we have hybrid android app based on jquerymobile [with js/css/html packaged inside apk]. app able fetch json data server [with restful interface] using jqm ajax call [for http url] when trying same thing using https fails. another bit is: have used bouncycastle based certificate enable tls [on server] working fine native android calls [using java]. now confused why working http not https. hint in regard appreciated. don't think cors/xor problem our ajax http calls working fine. i'm assuming you're using android webview class? if so, check error implementing method: webview.setwebviewclient(new webviewclient() { public void onreceivedsslerror (webview view, sslerrorhandler handler, sslerror error) { log.d("ssl_error", "the error is: " + error); } with code, can see error, if any, causing blank page. if it's error can accept, replace log.d line handler.proceed(); (with if condition verify it's same error). ideally, y

ruby on rails - Minitest - NoMethodError: undefined method `get' -

i stuck error when run simple test minitest-rails gem. have rails 4.1.5 , minitest 5.4.0 rake test:controllers 1) error: dashboardcontroller::index action#test_0001_anonymous: nomethoderror: undefined method get' #<#<class:0x00000008e28170>:0x00000008eeb9b8> test/controllers/dashboard_controller_test.rb:6:in block (3 levels) in ' test: require "test_helper" describe dashboardcontroller context "index action" before :index end { must_respond_with :success } "must render index view" must_render_template :index end end end my test_helper: env["rails_env"] = "test" require file.expand_path("../../config/environment", __file__) require "rails/test_help" require "minitest/rails" require "minitest/rails/capybara" class minitest::spec class << self alias :context :describe end end class requesttest < minitest

Focus method not working on asp.net gridview -

i have web page gridview. received requirement first checkbox on gridview should have focus when page loads. put following code: checkbox chkbox = (checkbox)grdmenupublichealth.rows[0].findcontrol("chkselect"); //chkbox.checked = true; chkbox.focus(); i put checked method in make sure checkbox being found, , works. however, focus() method doesn't appear working. has run before? thanks in advance guidance. i found following jquery worked: <script type="text/javascript"> $(document).ready(function () { $('input[type=checkbox]:first').focus(); }); </script>

c++ - How does subscripting std::array multiple times work? -

how subscripting multiple times work std::array though operator[] returns reference, without using proxy-objects (as shown here )? example: #include <iostream> #include <array> using namespace std; int main() { array<array<int, 3>, 4> structure; structure[2][2] = 2; cout << structure[2][2] << endl; return 0; } how/why work? you call structure.operator[](2).operator[](2) , first operator[] returns reference third array in structure second operator[] applied. note reference object can used object itself.

android - First time Google Map API -

i first time android studio user, trying google map app run samples provided. android-studio running on gentoo linux platform, using java 8 . have followed directions on how add google play services , added definition gradle , far can tell virtual device not have google play service support. have added pro-guard rules, error same. build rules , dependencies have entries documentation. looks should work. it obvious missing basic. basic helloworld works fine, stumbling on google's security , mechanism invoked. reviewing documentation, see references googleapiclient -- have setup client connection before trying connect? there, perhaps sample code process defined correctly, pieces? the studio @ current revision levels. error, possible have missed else, activitynotfound exception? the logcat message stream 09-10 10:07:16.449 1006-1006/cx.ath.klatt.test1 e/androidruntime﹕ fatal exception: main android.content.activitynotfoundexception: no activity found h

java - How to set relativelayout height equal to its width? -

i searched lot find out how gonna work , got nothing. found java code dynamically didn't work ant of theme , when opening program, show force close. code: <linearlayout android:baselinealigned="false" android:layout_width="match_parent" android:layout_height="wrap_content" > <relativelayout android:id="@+id/rlv1" android:layout_width="match_parent" android:layout_height="150dp" android:layout_weight="1" android:background="@drawable/rectengle2" > </relativelayout> <relativelayout android:id="@+id/rlv2" android:layout_width="fill_parent" android:layout_weight="1" android:background="@drawable/rectengle" > </relativelayout> </linearlayout> as can see created rectangle shape , used in relative layout lineaer layout parent ,

javascript - cross domain ajax POST fails with CORS and Tomcat -

i have been banging head against wall while trying cross domain ajax calls work. i have enabled cors on tomcat 7.0.5.0 server (windows), , can requests javascript, post requests still fail access denied. before enabling cors failed, seems working bit. the same code works fine same host, fails on remote hosts. i have tried everything, , every browser, no luck. javascript code: var request = new xmlhttprequest(); var debug = this.debug; request.onreadystatechange = function() { console.log(request.statustext); console.log(request.responsetext); console.log(request.responsexml); if (request.readystate != 4) return; if (request.status != 200 && request.status != 204) { console.log('error: sdk post web request failed'); } ... }; request.open('post', url, true); request.setrequestheader("content-type", "application/xml"); request.sen

opengl - I stored more data on VRAM than it's actual size. How is that possible? -

i analysing performance of simple voxelized world renderer. wanted find performance limits different techniques, kind of stress test. @ point found wierd. allocating geometry data in chunks using different vbo each chunk. i'm using few counters programmed engine helped me see happening data. here trying allocate 664 chunks containing 1 199 824 voxels altogether built using 28 795 776 vertices. each vert consists of 3 floats position, 3 floats normal vector , 4 floats rgba color. float apparently 4 bytes of size, based on calculated estimated memory size of whole world 1098mb ( vertexcount * 3 * 4 * 2 + vertexcount * 4* 4). i ran program fine @ amazing speed of 7 fps, worked , looked should. problem i'm using gigabyte geforce gtx 460 oc2 1 gb of video memory. how able allocate trough vbo 1098mb of data? data cached of compressed somehow once inside vram? or maybe there few mb of reserve memory had no idea about? explanation counters giving me wrong results or the

expressionengine - Conditional using site_url is always false -

i trying use following conditional statement in template: {if "{site_url}" == "http://dev.site.com" } true {if:else} false {/if} when test outputting site_url in template http://dev.site.com , expression evaluates false. i've tried variations without brackets , quotes no luck. try adding custom variable config.php (/system/expressionengine/config/ folder): //### custom variables ### global $assign_to_config; $protocol = (isset($_server["https"]) && $_server["https"] == "on") ? "https://" : "http://"; $assign_to_config['global_vars'] = array( "root_url" => $protocol.$_server['http_host'], "domain" => $_server['http_host'] ); then change template be: {if "{root_url}" == "http://dev.site.com" } true {if:else} false {/if} or {if "{domain}" == "dev.site.com&

scope - R: How can a function assign a value to a variable that will persist outside the function? -

this easy confused hell environments. use call function assign value variable, need able use variable after call. however, assume, variable created function exist within function environment. in short, need akin global variable (but beginner r). the following code : assignvalue = function(varname){ assign(varname,1) } assignvalue("test") test returns error: object 'test' not found whereas equivalent test <- 1 test i read in documentation of assign environments, not understand it. say foo parameter of function. this: assignvalue <- function(foo) { varname <<- foo } assignvalue("whatever") varname the variable varname point out value "whatever" .

Windows Universal App - In-app product for Windows 8.1 not working -

my app published on windows store , windows phone store. consumable in-app products working windows phone not windows. this code not work example: var listing = await currentapp.loadlistinginformationasync(); it gives exception: hresult: 0x801900cc and when want purchase in-app product, tells me app not found in windows store. published today , can download store. i doing in msdn documentation , exact same code windows phone version , there works. had deactivate in-app purchasing in windows 8.1 app because otherwise wouldn't pass certification because of problem. in-app products defined in store during submission. , app has correct name , publisher infos in visual studio 2013. so know problem here? ok seems have make sure in app products don't crash when no internet connection or server down or app not published yet. because otherwise certification not activate products when defined before submitting. when handle exceptions , app doesn't crash act

javascript - Round up if positive, round down if negative? -

i'm trying make following figures true: etc 5 = -2 6 = -1 7 = -1 8 = 0 9 = +1 10 = +1 11 = +2 and on. what i'm using right : function abilitymodifier( n) { return math.round( (n-8) /2); } which returns correct positive figures, makes 7 = 0, 6 = -1, 5 = -1, etc. wrong. is there better formula using? bare in mind i'm using nbos character sheet designer. function abilitymodifier(n) { var x = n - 8; if (x > 0) return math.ceil(x / 2); return math.floor(x / 2); }

javascript - jQuery store div parent id , and delete it from an array -

i trying build input element dynamically option add , remove inputs. have drop down build dynamically data base using php. while adding input sore parent id in array , when delete input using splice delete it. every box adding or remove contain several inputs i adding inputs array , succeed pass them using ajax, issue when deleting 1 input deleting parents divs in loop. var x = 1 var appletestlist; var appleinputlist = new array(); $('#appleplus').click(function(e){ //on add input button click var wrapper = $("#appledinamicbox"); //fields wrapper ; //initlal text box count $.ajax({ async: false, type: "get", url: "sqlfunctrions.php", data: 'func=dropdownbyvalue&table=test&value=test_id&display=test_name&column=test_type&valueby=apple&selectname=appletest&choosefrom=test', success: function(msg){

android - How to add EditText value in arraylist in Custom ListView -

i have created 2 textview , 1 edittext in first custom listview,i want add/store edittext value in arraylist because want show edittext value in second custom listview 1 one,so how please give hint or code solve problem.. public class mmenu extends activity { arraylist<candy> myarrlist; arraylist<string> edittextvalues; protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); myarrlist = new arraylist<candy>(); edittextvalues = new arraylist<string>(); final listview lisview1 = (listview)findviewbyid(r.id.listview1); final listview lisview2 = (listview)findviewbyid(r.id.listview2); myarrlist.add(new candy("butterscotch", "rs 10")); myarrlist.add(new candy("birthday cake", "rs 100")); myarrlist.add(new candy("black crunch", "rs 102")); myarrlist.add(new candy("industrial choco

sql - How to select a winning records based on a priority field -

i have table has following columns: eid ( pk ), memberid ( pk ), ename , priority , qualified there can multiple records particular eid , memberid combination each different priority, this 1234, jsmith, news, 1, null 2345, jsmith, reactivation, 2, null i need write query evaluate rows in table , assign qualified column based on priority, results be 1234, jsmith, news, 1, y 2345, jsmith, reactivation, 2, n so complicate matters table have rows added through out day , each time new set of data added need rerun prioritization query. an annoying note, cannot use cursors, variables or temp tables this. can create supporting tables , copy data them on temporary basis physical tables. any appreciated. if description of problem sucks, apologize, let me know how can more explanatory , best. thanks if understand question correctly, think sql give want update mytable set qualified='n' update mytable set mytable.qualified = 'y' myta

actionscript 3 - AS3 Add array to another array -

example of problem. var array_1:array = new array(); array_1[0] = [2,4,6,8]; var array_2:array = new array(); array_2[0] = [10,12,14,16]; array_2[1] = [18,20,22,24]; // , out come want trace(array_1[0]) // 2,4,6,8,10,12,14,16,20,22,24 // did try array_1[0] += array_2[0] didn't work any suggestion great. this perform looking , allows add multiple rows of data array_1 or array_2 var array_1:array = new array(); array_1[0] = [2,4,6,8]; var array_2:array = new array(); array_2[0] = [10,12,14,16]; array_2[1] = [18,20,22,24]; var combinedarray:array = new array(); for( var i:int = 0; < array_1.length; i++ ) { combinedarray = combinedarray.concat(array_1[i]); } for( = 0; < array_2.length; i++ ) { combinedarray = combinedarray.concat(array_2[i]); } trace(combinedarray);

jquery - Multiple call from same javascript function with ajax, object in parameters not the same between the function body and the ajax success callback -

i've got strange result when called javascript method ajax. when user click on arrow, load data, don't want user stuck let him change when want. , when data come server, want load data @ object in collection. html ( little more complex hard paste , think it's enough understand) : <a href='#' data-bind='click:loadexactresult'>next</a> js: function loadexactresult(dateobj) { //method body (function(dateobj) { var payload = { searchcriteriaparam: "", }; console.log(moment() + " - calling exact date: " + dateobj().date()); dateobj().isallflightloading(true); $.ajax({ url: 'bla/bla', data: payload, cache: false, success: function(result) { console.log(moment() + " - exact date success: " + dateobj().date()); // ajax body. } }); })(dateob

app store - Switch a native existing app with cordova/phonegap -

i'm trying update existing native app (actually two: 1 ios , 1 android) switching content cordova. need rewrite app cordova update same app instead of asking users uninstall old 1 , install new one. possible? advice? thank in advance! yes possible. need use same app ids native apps used on android/ios (define them in cordova config.xml) - , android need sign final apk using original *.keystore file.

c++11 - Initialize class member variables in C++ 11 -

consider following class definition: class c { public: int = 9; const int j = 2; }; without using flag enable c++11 when compiling (using g++, e.g. g++ -o test test.cpp ) compiler complains on member variable initializations. however, using -std=c++11 works fine. why has rule been changed in c++11? considered bad practice initializing member variables in manner? initializing non-static data members @ point of declaration wasn't "bad practice"; wasn't possible at all prior c++11. the equivalent c++03 code be: class c { public: c() : i(9), j(2) { } int i; const int j; }; and in case: what weird colon-member syntax in constructor?

replace - Optimal string replacing in files for AIX -

i need remove 40 emails several files in distribution list. 1 address might appear in different files , need removed of them. working in directory several .sh files have several lines. i have done in couple of test files: find . -type f -exec grep -li address_to_find {} 2>/dev/null \; | xargs sed -i 's/address_to_remove/ /g' * it works fine once try in real files, takes long time , sits there. need run in different servers, main cause want optimize this. i have tried run this: find . -type f -name '*sh' 2>/dev/null | xargs grep address_to_find but return: ./filecontainingaddress.sh:address_to_find how add this: awk '{print substr($0,1,10)}' but return me before " : "? i can rest there, haven't found how trim part you can use -exec predicate in find , long don't use multiple file + version, means can provide several -exec clauses each of dependent on success of previous one. style avoid construction o

python - Plot table and display Pandas Dataframe -

Image
i want display pandas dataframe on screen in tabular format: df = pd.dataframe({'apples': 10, 'bananas': 15, 'pears': 5}, [0]) i'm not sure how so. know pd.dataframe.plot() has options display table, along graph. want display table (i.e. dataframe) on screen. thanks! edit: here's screenshot of creating table using pandas plot function. want bottom table portion however, not graph. want popup of table figure. edit 2: i managed display dataframe on figure following: plt.figure() y = [0] plt.table(celltext=[10, 15, 5], rowlabels=[0], columnlabels=['apple', 'bananas', 'pears'], loc='center') plt.axis('off') plt.plot(y) plt.show() this display table without of axes. don't know if best way go it, suggestions appreciated. also, there way add title table? way know use plt.text , place text (title of table) within figure, have keep axes...any ideas? line 2-4 hide graph above,but somehow gr

javascript - Underscore.js script not rendering in Node? -

noob js , underscore -- in following simple code trying iterate through var animalnames using underscore (_.each fxn) when run code in node in terminal goes right cmd prompt ie. nothing runs. please explain what's going. function animalmaker(name) { return { speak: function () { console.log("my name ", name); } }; }; var animalnames = ['', '', '']; var farm = []; us.each(animalnames, function (name) { farm.push(animalmaker(name)); }); firstly, map method more appropriate in case, because you're mapping array of names array of animals // renamed animalmaker // in js it's convention capitalize constructors , keep normal functions camel-case var createanimal = function(name) { return { speak: function() { console.log("my name is", name); } }; }; var names = ["chicken", "cow", "pig"]; var animals = us.map(names, createanimal); with code you've created list

c# - How to change value of DefaultValue attribute in subclass -

i'm not sure if want possible, figured i'd ask. i have abstract base class has property that's decorated defaultvalue attribute, so: public abstract mybaseclass { [defaultvalue( "some value" )] public string stringproperty { { return istringproperty; } set { istringproperty = value; } protected string istringproperty = "some value"; // other code here } i want derive child class mybaseclass , want value in defaultvalue attribute, default value of property, different. end, have added default constructor child class, follows: public class mychildclass : mybaseclass { // type specific properties & fields here public mychildclass() : base() { istringproperty = "new value"; } // other code here } how change value of defaultvalue attribute in derived class it's "new value"? if property virtual override , apply defaultvalue it. [de

jquery: (newbie) trying to get a tooltip to work -

i using example code here: http://jsfiddle.net/tj_vantoll/kybwu/ but since don't want user decide arrow comes - setting arrow myself position. since not using textbox, want tool tip display mouses on image class name "hide-option" my modified code: <script> $(function() { var position = { my: 'left center', at: 'right+10 center' }; position.collision = 'none'; $('.hide-option').tooltip('option', 'position', position); $('.hide-option').tooltip('option', 'tooltipclass', classname); $('.hide-option').tooltip(); }); </script> my html: <img src="siteimgs/comments_icon.png" class="hide-option" title="total comments: 80" > but not work, gives me error in console: "uncaught error: cannot call methods on tooltip prior initialization; attempted call method 'option'

javascript - Not work with getElementById -

not work getelementbyid ("val5" + i). , input3 not running i hope code enough info provide the error somewhere in line /* digitalinput */ index = input2_offs for(i=0;i<4;i++) getelementbyid("val5"+i).src = valuearray[input2_offs[i]] == "0" ? 'gif/dot_red.gif' : 'gif/dot_gr.gif' where problem enter code here <!-- var req = null; req = ajaxinit(); var postbuffer = new array; var trace; /* number of channels per sensor input type */ var inputchannels = 4; /* max 4 digital inputs */ var names = new array(); var units = new array(); var offs = new array(); var gain = new array(); var value = new array(); var input2_offs = 25; var input3_offs = 26; /* function called on body load , later every 5s request new set of data controller */ function update() { var x = math.random()*1000; /* add random number url avoid caching content in browser */ x=x.tofixed(3); ajaxgetreque

c# - How to write integration/health test of a wcf service on which I have no control? -

i need write little more simple test service. have no control on it, specific request returns specific response know should return. you create project in solution named yourproject.integrationtests , place tests of kind in there. you use same tools use unit testing create test cases (nunit, xunit, mstest, etc)

what does double star regex means in spring security url -

i came across spring project saw security configuration following <intercept-url pattern="/register/**" access="permitall()" /> after google , digging more not able find out double star means /register/** great if explain me. significance of stars in urls spring security. these patters ant-style path patterns ( https://ant.apache.org/manual/dirtasks.html#patterns ). ** matches 0 or more 'directories' in path, take @ antpathmatcher

javascript - How to write in shorthand form if / else if / else? -

is there shorthand if / else if / else statement? example, know there's 1 if / else statement: var n = $("#example div").length; $("body").css("background", (n < 2) ? "green" : "orange"); but how write following in shorthand syntax above? var n = $("#example div").length; if (n < 2) { $("body").css("background", "green"); } else if (n > 2) { $("body").css("background", "blue"); } else { $("body").css("background", "orange"); } it exist it's highly un recommended because it's pretty hard read , maintain. var n = $("#example div").length, color; color = (n < 2) ? 'green' : (n > 2) ? 'blue' : 'orange'; $("body").css("background", color);

canvas - How to set the the zindex of datatemplate's in a longlistselector -

i have longlistselector images add in longlistselector. change margins of image make image go or down , on. want put image infront of image in longlistselector. have tried using canvas.zindex. have tried setting @ grid level, @ image level , @ top level of of longlistselector.() still doesn't work. have idea's? can find code bellow: <phone:longlistselector x:name="southlonglistselector" verticalalignment="bottom" itemssource="{binding cards}" canvas.zindex="{binding layer}" selectionchanged="southlonglistselector_selectionchanged" layoutmode="grid" gridcellsize="50,200" margin="0,0,0,-26" > <phone:longlistselector.itemtemplate > <datatemplate> <grid background="transparent"

multithreading - Reg multiple synchronised block with multiple JVM's -

i have java application deployed on was.it receives request wps(websphere process server) , inserts data oracle db. inorder avoid multithreading issues,i wrote code in synchronised block.now application working fine on dev env(single jvm). came know qa has multiple jvm's. heared synchronised block doesn't work on multiple jvm's,so worried whether application works in qa env? the synchronized keyword works using locks against instances in jvm method invoked, won't guarantees of thread safety if application running across multiple jvms. (in fact, guarantee in single jvm if careful synchronize on .) this mechanism documented, including oracle javadocs , blog posts on topic might easier understand. i don't think can tell whether application work in "qa" information you've given. depends on detail of what's being done. example, let's assume wps sending requests out jvms , have insert them in database. if inserting database using pr

javascript - How to change the HTML input type attribute from 'password' to' text'? -

i change html 'input' element 'type' attribute, type="password" type="text". i aware easier find element id not every page has same id password input. how target password inputs , change inner value type of text. i have few lines of javascript code: a=document.getelementsbytagname("input"); a.setattribute(type,text); to convert elements of type password text: var arr = document.getelementsbytagname("input"); (var = 0; < arr.length; i++) { if (arr[i].type == 'password') arr[i].setattribute('type','text'); } note: not browsers allow dynamic changes type attribute on inputs.

How can I get Jenkins SCM polling to accumulate changes? -

Image
i have job takes while complete , quite resource heavy. ever want run 1 instance of job @ time, , if there new scm changes. i set scm trigger , left off checkbox "execute concurrent builds if necessary". the problem have queues next build on first scm change detects. what want whenever scm trigger sees change, replaces job queued new job, newer scm revision. don't want running new instance next change, , don't want ton of jobs queued up. basically, want job run in loop, , pause if there no scm changes. how do that? you might looking quiet period option under advanced project options section. you can set value (in seconds ) quiet period per requirement. reduce frequency of builds.

algorithm - How to count the number of set bits in a 32-bit integer? -

8 bits representing number 7 this: 00000111 three bits set. what algorithms determine number of set bits in 32-bit integer? this known ' hamming weight ', 'popcount' or 'sideways addition'. the 'best' algorithm depends on cpu on , usage pattern is. some cpus have single built-in instruction , others have parallel instructions act on bit vectors. parallel instructions (like x86's popcnt , on cpus it's supported) fastest. other architectures may have slow instruction implemented microcoded loop tests bit per cycle ( citation needed ). a pre-populated table lookup method can fast if cpu has large cache and/or doing lots of these instructions in tight loop. can suffer because of expense of 'cache miss', cpu has fetch of table main memory. if know bytes 0's or 1's there efficient algorithms these scenarios. i believe general purpose algorithm following, known 'parallel' or 'variable-precision

c# - Problems with passing two models to one view -

i want pass 2 models 1 view using viewmodel my models : public class candidat { public int id { set; get; } public string num_cin { set; get; } public icollection<poste> postes { get; set; } } public class poste { public int id { set; get; } public string poste_name {set;get} public list<candidat> candidats {set;get;} } public class postecandidatviewmodel { public candidat candidat { get; set; } public poste poste { get; set; } } the controller action : [httppost] public actionresult index( poste poste,string num_cin) { if (modelstate.isvalid) { var v = (from c in _db.candidats c.num_cin == num_cin && c.postes.any(p => p.id == poste.id) select c) .singleordefault(); if (v != null) { return redire

mysql - Generating a sql query in php using for loop -

code : $nerd_result = mysql_query("select * nerd_profile nerd_reg_no = '$reg_no'"); $nerd_data = mysql_fetch_array($nerd_result); $tags = array(); $tags = explode(",",$nerd_data['nerd_interests']); for($i = 0; $i < sizeof($tags)-1; $i++) { if($i != sizeof($tags)-2) { $sub_query = $sub_query."`tags` %".$tags[$i]."% or "; } else { $sub_query = $sub_query."`tags` %".$tags[$i]."% "; } } $proper_query = "select * `qas_posts` ".$sub_query." , `post_date` '%$today%'"; $result = mysql_query($proper_query); while($each_qas = mysql_fetch_array($result)) description : i adding clause along php variable in string , concatenating further variables clause come. in end when echo perfect query want mysql_fetch_array() does not accept generated query rather if hard code , works perfect doing wrong ?? can ?? when doing string comp

ruby - How to program faster, (generate code from a pattern?) -

i run problems solved automating code writing, aren't long enough justify tediously entering each piece faster. here example: putting lists dictionaries , things this. converting b. a hotdog hd hamburger hb hat h b def symbolizetype case self.type when "hotdog" return "hd" when "hamburger" return "hb" when "hat" return "h" end sure come automatically, make sense if list 100+ items long. list of 10-20 items, there better solution tediously typing? ruby example, typically run cases time. instead of case statement, maybe it's dictionary, maybe it's list, etc. my current solution python template streaming input , output in place, , have write parsing , output code. pretty good, there better? feel vim macro excel at, i'm experienced vim. can vim easily? i frequently, , use single register , macro, i'll share. simply

javascript - How to replace a letter with another letter in a textbox -

say want target specific letter in textbox region , replace letter using either jquery or javascript, how , still able target letter afterwards, , again, , again etc.? letter change , changed inputed either textbox or dropdown (whichever easier) p.s tried jquery's replace function , didn't work (i didn't use correctly though :) $( "button" ).click( function() { $( "changed" ).replacewith( $( "new" ) ); }); $("button").click(function() { var old = $("#changed").val(); var replacement = $("#new").val(); var regexp = new regexp(old, 'g'); $("#input").val(function(i, current) { return current.replace(regexp, replacement); }); }); you need use # before ids select them. you need values of inputs using .val() . jquery's .replacewith replacing entire dom elements, not changing value of input. you use .val() change value of input. when ar

ruby on rails - Couldn't find Wiki without an ID error? -

i making wiki clone app in ruby on rails , trying destroy wiki, after click on destroy link error: couldn't find wiki without id and has problems code block def destroy @wikis = wiki.all @wiki = wiki.find(params[:wiki_id]) @collaborator = @wiki.users.find(params[:user_id]) authorize @wiki end where call delete function in wiki#views file. link looks this: <%= link_to "delete wiki", @wiki, method: :delete, class: 'btn btn-danger', data: { confirm: 'are sure want delete wiki?' } %> this error caused following line: @wiki = wiki.find(params[:wiki_id]) params[:wiki_id] nil . you're doing this: @wiki = wiki.find(nil) in case find throw error you're seeing, since cannot find records id of nil . as per tadman's suggestion, try changing line following: @wiki = wiki.find(params[:id])

php - Need a safe way to execute external code -

i wondering if possible allow people write , execute php code website without use of "eval" due risks. have googled around , did find answers, not answers looking (call_user_func). not looking not allow people run full php script. it's small group of people executing server load not issue. edit 1: users should not able corrup/delete files; users should able create complete scripts.; users should able run html code trigger php php tags used. you can write own wrapper process around php uses ptrace control execution of child php process prevent opening file handles, connecting network, etc. that way, if people decide try using malicious code in eval, system calls blocked on native level.

rotation - Rotating a model around all 3 (X, Y, Z) axis in DirectX 11.2 C++ -

i have next problem. trying rotate 3d model around 3 axis @ same time. meaning want rotate model around x axis, y axis, again x , forth pressing buttons on keyboard. problem when use xmmatrixrotationx, xmmatrixrotationy or xmmatrixrotationz this: void rotate(float radians_x, float radians_y, float radians_z) { directx::xmstorefloat4x4(&_transfer.world, directx::xmmatrixtranspose(directx::xmmatrixrotationz(radians_z))); directx::xmstorefloat4x4(&_transfer.world, directx::xmmatrixtranspose(directx::xmmatrixrotationy(radians_y))); directx::xmstorefloat4x4(&_transfer.world, directx::xmmatrixtranspose(directx::xmmatrixrotationx(radians_x))); } only last rotation gets done. want able rotate object around each of axis specific angle (actually, radians), can see in code. have found out xmmatrixrotationaxis method this, takes 1 angle parameter, , want use different 1 each axis. can me how can done? also, don't know send first paramet

Many-To-Many Fields View on Django Admin -

Image
basically trying recreate fields in model similar django user authenticate system, try using many-to-many fields ended this. i trying have field can show exist , field have chosen similar django admin, looks this. this code class category(models.model): name = models.charfield(max_length=128, unique=true) class blogpage(models.model): category = models.manytomanyfield(category) title = models.charfield(max_length=128) preview = models.textfield(max_length=256) content = models.textfield() i believe want filter_horizontal widget used in admin template. should help: django admin manytomanyfield

javascript - TinyMCE Sanitizing input -

Image
i'm trying use tinymce (version 4.1.2) wysiwyg editor. logged in users can write own pages , see directly shown on page when visitor visits. now, i'd html stored directly. example: the logged in user sees this text! , in fact tinymce displays <p>this text!</p> . there's styles <h1> , links can added. now, user can insert hyperlink, giving link , text should displayed. problem however, if user manually write <a href='example.com'>example</a> , shows in editor gets stored in pure html well, when displaying hyperlink text example . this how code sort of looks (left out configuration): tinymce.init({ setup: function(editor){ editor.on('change', function(e){ $('[name="'+editor.id+'"]').next("textarea").html(editor.getcontent({format: 'html'})); }); } }); so text tinymce field gets copied <textarea> inside <form> gets submit

r - opts_current: how does it work in knitr? -

i trying set different figure size in different chunks. first define global settings using: opts_chunk$set(fig.width=7, fig.height=7) then, specific chunks, use: opts_current$set(fig.width=7, fig.height=14) but later neglected. so, how opts_current work? for specific code chunks, put chunk options in chunk header, e.g. ```{r fig.width=7, fig.height=14} these called local chunk options, override global chunk options (temporarily specific chunk).

rest - How to integrate Swagger with Maven + Java + Jersey +Tomcat -

i can't seem understand how integrate swagger generate api documentation. url: ####:8080/myservice/rest/users/getall have added annotations code , dependency. try visit: ####:8080/myservice/rest/ says not found. //web.xml <servlet> <servlet-name>mycompany-users-serlvet</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.servletcontainer</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>com.users.services.mycompany,com.wordnik.swagger.jersey.listing</param-value> </init-param> ` <servlet> <servlet-name>jerseyjaxrsconfig</servlet-name> <servlet-class>com.wordnik.swagger.jersey.config.jerseyjaxrsconfig</servlet-class> <init-param> <param-name>api.version</param-name> <param-value>1.0.0</param-value> </init-param> <