Posts

Showing posts from July, 2014

foreach - For Each Loop Unable to assign value to a variable -

i have execute sql tasks gets missing ids , stores them objectvariable(missingids of datatype object).using each loop container wanna insert data multi tenant architecture db based on id's name(which name of schema). i've used each ado enumerator , used objectvariable(missingids) ado objectsourcevariable , enumeration mode "rows in first table".in variable mappings mapped variable(companyid) of datatype string index 0. in each container,i wish name of id , store in variable called schema(datatype string).i've used execute sql task getting error. error: 0xc002f309 @ getting schema name accountid, execute sql task: error occurred while assigning value variable "schema": "single row result set specified, no rows returned.". task failed: getting schema name accountid i've used breakpoints , able see data available accountid. anyone knows issue be? thanks vijay

java - com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize out of START_ARRAY token -

i'm getting start_array error following model. i'm expecting object of inputdetails class inputdetails{ public list<eachfielddetails> fielddetails; } class eachfielddetails{ public string fieldname; public string value; } json input follows: [{"fieldname":"sitename","value":"warehouse"},{"fieldname":"ponumber","value":"po1"},{"fieldname":"itemcode","value":"itemcode1"},{"fieldname":"asdnserialno","value":"null"}] can provide me solution. here class public response setwhdetails(@beanparam requestbean requestbean,inputdetails saveinputs) { //do operation } your json specifies array while you're trying deserialize object. if json like: { "fielddetails" : [ {"fieldname":"sitename","value":"warehouse"}, {...

java - How can I add security header in message? -

i wanto built simple soap client in java call soap java web service. have import wsdl in project ad built client. if try run code, have erro: avvertenza: unable find required classes (javax.activation.datahandler , javax.mail.internet.mimemultipart). attachment support disabled. axisfault faultcode: { http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd }invalidsecurity faultsubcode: faultstring: error: no security header found in message faultactor: faultnode: faultdetail: { http://xml.apache.org/axis/ }stacktrace:error: no security header found in message @ org.apache.axis.message.soapfaultbuilder.createfault(soapfaultbuilder.java:222) @ org.apache.axis.message.soapfaultbuilder.endelement(soapfaultbuilder.java:129) @ org.apache.axis.encoding.deserializationcontext.endelement(deserializationcontext.java:1087) @ com.sun.org.apache.xerces.internal.parsers.abstractsaxparser.endelement(abstractsaxp...

ruby - Rails polymorphic comments ajax - 500 (Internal Server Error) -

Image
i used tutorial making polymorphic comments https://gorails.com/episodes/comments-with-polymorphic-associations it works fine when set remote true comments form got 505 error(the new comment not appended list) when trying add new comment. but when reload page new comment appears in list. what can wrong here? i got files in views/comments folder: create.js <% unless @comment.errors.any? %> $("ul.comments").append('<%= j render "comments/comment" %>') $("#new_comment")[0].reset(); <% end %> _form.html.erb <%= simple_form_for([commentable, comment.new], remote: true) |f| %> <%= f.input :body, label: false %> <%= f.button :submit, "submit" %> <% end %> comments_controller.rb def create @comment = @commentable.comments.new(comment_params) @comment.user = current_user @comment.save respond_to |format| format.html { redirect_to @commentable, notice:...

html - Trying to align input field with labels -

Image
i want align input fields shown below, keep using <label> in correct way. the code below: <form action="add.php" method="post" enctype="multipart/form-data"> <label for="refno">field1 name (long)</label> <input id="refno" type="text" name="refno" value="" /><br> <label for="name">field2 name</label> <input id="name" type="text" name="name" value="" /><br> <input type="submit" value=":: add ::" name="addbtn" /> </form> i thinking separate <label> tags in <div> , input fields in , floating manipulation make intended alignment, correct way? how form > label { min-width: 185px; display: inline-block; } <form action="add.php" method="post" enctype="multipart...

linux - Thread management in a cloned process with CLONE_VM flag set -

i need thread management inside cloned process. point need create , destroy threads inside cloned process asynchronously ( pthread_cancel_asynchronous set). fine if clone_vm not set, need because main , child process must share same address space. below example demonstrate question. being compiled clone_vm flag program hangs @ pthread_join while without clone_vm fine. there ways deal problem? p.s. tried @ debian gnu/linux versions 7,8 , unstable (kernels 3.2, 3.16, 4.0). #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <pthread.h> #include <sched.h> #include <string.h> #include <signal.h> #include <sys/types.h> #include <sys/wait.h> /* compile # gcc -o pthread_test -lpthread pthread_test.c */ #define clone 1 pthread_mutex_t mutex = pthread_mutex_initializer; void *thread_test(void *unused) { pthread_setcanceltype(pthread_cancel_asynchronous, null); pthread_setcancelstate(pthread_cancel_...

php - Data taken from mysql display division if the date by day is changed -

Image
currently have code takes data mysql , displays text , tried make underline bar if date day changed, no luck the first picture shows code , second 1 i'm trying do. tried check if current date different new 1 no luck. how detect date change current code, can make break between same day easy viewing? <?php chdir(__dir__); error_reporting(e_strict | e_all); ini_set('display_errors', true); ini_set('display_startup_errors', true); require_once 'config.php'; $mysqli = new mysqli($server, $db_user, $db_password, $database); if ($mysqli->connect_error) { die("connection failed: " . $conn->connect_error); } $sql_list = "select date, name, quantity, 0 price, 'download' source downloads union select date, name, quantity, price, 'sale' source sales order by(`date`) desc"; $result_list = $mysqli->query($sql_list); $ans_lists = array(); while($row = $result_list->fetch_assoc()){ $sourc...

Chrome App webview does not allow access to MessageEvent source in inspector -

i using webview in google chrome app, , when try send message webview parent page, come through, can't access source property send back. have specified origin send parent window origin, , still comes through client, when try inspect in client console, throws error. webview.addeventlistener('contentload', function() { webview.contentwindow.postmessage('welcome', window.location.origin); }); and in webview: window.addeventlistener('message', function(event){ console.log(event); }); it turned out event.source.postmessage still accessible, couldn't inspect in console.

java - IBk with custom similarity function as a recommender system -

i'm trying implement recommender system based on content-based similarity function (which uses description logics). using similarity function built similarity matrix items of dataset. decided use kind of information in order implement knn classifier. i'm using weka's implementation of knn , implemented similarity function extending normalizabledistance . it gets distance score between 2 instance , returns it, because has been computed . using function construct classifier in way: ibk knn = new ibk(numneigh); knn.getnearestneighboursearchalgorithm().setdistancefunction(new mycustomfunction()); in context, i'm not able understand how should use dataset. dataset in form: (user_id, item_id) where each pair represents user has seen item (implicit feedback). if try construct instances object using dataset have, i'm not able run appropriately knn algorithm because each instance not item can used similarity function. so should create dataset contain...

javascript - Tooltips for dynamic elements -

i'm having tooltips on page var btnarr = ["#b1", "#b2"]; var ttarr = ["submit", "clear"]; $.each(btnarr, function (i, v) { $(btnarr[i]).prop('title', ttarr[i]); $(v).tooltip({ text: ttarr[i] }); }); how can have tooltips working dynamically created elements? you can bind tooltip widget top-level element , use items option filter elements want show on: $(document).tooltip({ items: ".mytooltipbuttonclass" }); this document or container element or multiple container elements. other alternative reinstantiate new widget each time dynamically create new button tooltip, that's in cases unnecessarily complicated here's update on fiddle: http://jsfiddle.net/h5qbhvmc/ on side note text isn't valid option , doesn't anything. ref. list of valid options

orm - How can I update hasandbelongstomany relations for multiple models at once in strongloop loopback -

i have 2 models in strongloop loopback api products tags between 2 models have defined hasandbelongstomany-relation . in cms want bulk-update functionality products, in can select many products, , assign many tags, in 1 action. how can save mysql-db, without having iterate on each product, iterate on each tag, , link 2 ? i checked in docs , found add , remove functions, connect 1 model 1 relatedmodel. there loopback-functionality want? unfortunately, there no bulk update yet. see https://github.com/strongloop/loopback/issues/1275

c# - How to host a bot server on a hosting service? -

i made simple bot application c# console application interacts users via http requests. want publish on host service online. steps wanted take export of bot server's class class library , make asp.net application , upload host service (maybe plesk panel) , let asp.net make instance of server class , start it. problem is, every time open browser , make request asp.net application dispatch new thread me thread pool everytime make new instance of server class , start it. how can access same server class? is possible? i know can buy vps , run console application there isn't wasting resources simple bot server application? sorry if question not clear. you it's not recommended way it. create class has getobj() returns running object, if there no object creates 1 , returns it. see: https://en.wikipedia.org/wiki/singleton_pattern have object make thread runs in background. have thread save it's variables sql server redundancy. when create object first t...

php - How Do I Pass Which Item I Want To Delete? -

i've inherited code , new laravel. have cart , can add items cart. part delete items cart isn't working. each line has delete remove button. somehow needs pass controller item needs remove. cart.blade.php has: @foreach($custom_quote_items $custom_quote_item) <tr> <td><p>{{ $custom_quote_item->name }}</p></td> <td><p>{{ $custom_quote_item->description }}</p></td> <td><p>{{ intval($custom_quote_item->quantity) }}</p></td> <td><p>{{ $custom_quote_item->pricing($custom_quote_item->name) }}</p></td> <td> <p> {{ form::open(array('action' => 'customquotecontroller@removefromquote', 'method' => 'delete')) }} {{ form::hidden('id'...

asp.net mvc - Prevent AngularJS route to load view if receives 403 error -

Image
i'm creating permission back-end code that, whenever user tries access specific page, i'll check permissions and, if don't have permissions, return 403 error in json result. the following show how proccess work: i have route handles page access: this route asp.net mvc page returns viewresult - view - angularjs: the view action has attribute verify authentication of user and, if user doesn't have permissions, i'll return 403 json response instead view: i created interceptor handles response error - in case response throw 403 error -, can redirect user login page instead: the steps working fine , it's redirecting login when 403 error. however, i'm getting strange error on console (don't worry route name, it's correct): it seems angularjs continues promise flow instead stop when intercept 403 error. there way prevent occur? mean, stop flow after 403 error , foward user route, same i'm doing now? thank all!

java - JSON: use deserializing name different than serializing name json -

i have 1 class user , received json (for user class) system1 , should read info , validate forward system2, can't touch these 2 systems, problem names of keys different, want differentiate between deserialized , serialized name received json : {"userid":"user1","pwd":"123456","country":"us"} "{"username":"user1","password":"123456","country":"us"}" but sent should i using gson lib, , code, please help user class: public class user implements cloneable { @serializedname("username") private string username ; @serializedname("password") private string password ; @serializedname("country") private string country ; public user(string username, string password, string country) { super(); this.username = username; this.password = password; this.countr...

Buffon's needle simulation in python -

import numpy np import matplotlib.pylab plt class buffon_needle_problem: def __init__(self,x,y,n,m): self.x = x #width of needle self.y = y #witdh of space self.r = []#coordinated of centre of needle self.z = []#measure of alingment of needle self.n = n#no of throws self.m = m#no of simulations self.pi_approx = [] def samples(self): # throwing needles in range(self.n): self.r.append(np.random.uniform(0,self.y)) self.z.append(np.random.uniform(0,self.x/2.0)) return [self.r,self.z] def simulation(self): self.samples() # m simulation j in range(self.m): # n throw hits = 0 #setting succes 0 in range(self.n): #condition hit if self.r[i]+self.z[i]>=self.y or self.r[i]-self.z[i] <= 0.0: hits += 1 else: continue ...

How to print backslash with Python? -

when write: print '\' or print "\" or print "'\'" python doesn't print me backslash \ symbol. what should expected result? you need escape backslash preceding with, yes, backslash: print "\\" the \ character called escape character, interprets character following differently. example, n letter, when precede backslash, becomes \n , newline character. as can guess, \ needs escaped doesn't function escape character. have to... escape escape, essentially.

newsletter - PHPlist - running it from localhost with tracking via live website -

i've got large mailing list - 50k+ subscribers. avoid stressing servers, avoid sending emails through components embedded on website. sending through here sends cpu usage through roof - i'd able send emails locally. can send emails through mandrillapp, sending emails out not problem. however, i've hit bit of snag. phplist seems assume living on public site, , inserts tracking info routes users phplist directory on site (which obviously) not exist. question 1: first of all, i'd avoid embedding tracking - possible? or else there someway include , avoid 404 error. have install phplist anyway on server? question 2: i've got acymailing handle unsubscribes, possible keep in place - make sure acymailing still point of reference? question 3: how people handle sending out large mailing lists? know campaignmonitor, mailchimp etc, these bit expensive situation. i'd keep sending "internally" speak. there elegant solution not kill server not expensive? ...

javascript - how to convert json without &quot -

var text = [{&quot;name&quot;:&quot;en3&quot;,&quot;value&quot;:234},{&quot;name&quot;:&quot;en4&quot;,&quot;value&quot;:135},{&quot;name&quot;:&quot;en1&quot;,&quot;value&quot;:335},{&quot;name&quot;:&quot;en2&quot;,&quot;value&quot;:310},{&quot;name&quot;:&quot;en5&quot;,&quot;value&quot;:1548}] how convert json without "? like: [{"name":"en3","value":234}, and on? i have try use json.parse('${resultdata}'.replace(/&quot;/g, '\\"')) ,but throws error uncaught syntaxerror: unexpected token \ just replace regex /&quot;/g, '"' i.e code should json.parse('${resultdata}'.replace(/&quot;/g, '"'))

closures - How to init a NSMapTable with a value of block by swift -

when use nsmaptable , trouble make me unhappy,i [self.map setobject:block forkey:key] in obj-c ok,but when do map.setobject(block as! anyobject, forkey: key) in swift, error could not cast value of type '() -> ()' (0x15d9a604) 'swift.anyobject' (0x15d7335c) how can fix when used nsmaptable ? don't want use dictionay , because key complex. a block not object. wrap block in class, assign block class property. class myclass { let block: void -> void } [self.map setobject:myclass forkey:key]

Select photo from camera and show crop option with fixed size android -

my requirement crop image fixed size in android.. getting image gallery or camera , want show fixed size of crop option on image user drag rectangle box , set anywhere on image , save. please google question before asking them on stackoverflow... there plenty of libraries doing want. use this one stable, clear , easy use you'll find plenty of others looking on github search like this . for fixed size, there maybe option directly implemented in api of library proposed (never had requirement), if not, have change draw method of transparent rectangle.

MongoDB inserting scala Map throws exception -

i have code snippet val dbobj: basicdbobject = new basicdbobject("mymap",map) //here map scala.collection.mutable.map[string,int] dbops.bulkwrite.find(document).upsert().update(new basicdbobject("$inc", dbobj)) this throws exception: org.bson.codecs.configurtion.codecconfiguration: can't find codec class scala.collection.immutable.maplike$$anon$2 the first thing noticed exception says immutable map while have mutable map have no idea what's wrong help!

javascript - Onsenui;[ng:areq] Argument 'AppController' is not a function, got undefined in angularjs -

i developing hybrid app using onsenui , cordova.i got error in while loading in controller ons-page . have referred many stackoverflow questions related issue,but didn't solution "error: [ng:areq] argument 'appcontroller' not function, got undefined scripts <script src="js/cordova.js"></script> <script src="lib/onsen/js/onsenui_all.min.js"></script> <script src="js/app.js"></script> html content <ons-template id="home.html" > <ons-navigator var="mynavigator"> <ons-page ng-controller="appcontroller"> ##contents goes here </ons-page> </ons-navigator> </ons-template> app.js (function(){ 'use strict'; var module = angular.module('app', ['onsen']); module.controller('appcontroller', function() { alert("inside controller"); }); })(); ...

android - How to add views to scrollview dynamically? -

i'm tring add layout views in scrollview dynamically. know how use listview in case dont want use listview. so, first inflate layout view, , add linearlayout inside scrollview. problem can't adding layout multiply time. view layoutinflated; scrollview scrollview; linearlayout childview; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main_matan); scrollview = (scrollview) findviewbyid(r.id.scroll_view_container); childview = (linearlayout) findviewbyid(r.id.linear_row_container); layoutinflated = getlayoutinflater().inflate(r.layout.row_message, scrollview, false); childview.addview(layoutinflated); } main.xml: <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:onegravity="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:orientation="horizontal...

laravel - Manually inject model relation using Eloquent -

how can add model relations array of model? e.g. domain belongsto owner. owner hasone domain. i have $domain (instance of domain). i have $owner (instance of owner). i want add $domain $owner->relations[] can use $owner->domain later on in code. the reason doing such in 1 particular controller need partial data set each model use fluent query join performance reasons fill models. then readability's sake i'd use $owner->domain->id etc $domain->owner()->associate($owner); gives me $domain->owner option but can't work out opposite version $owner->domain()->associate($domain) $owner->domain()->attach($domain) both result in following fatal error call undefined method illuminate\database\query\builder::[attach|associate] () nb: don't want save i've loaded data need. setrelation() should work. sets value in relations array. $owner->setrelation('domain', $domain);

testing - Dismiss Alert Dialog in Android Espresso Test -

i've looked around solution can't find one. i'm creating espresso test , need dismiss alert dialog appears in middle of screen first time particular activity screen displayed. there no buttons on dialog dismiss user needs click anywhere outside box. know how can espresso. tried clicking on layout on underlying screen espresso fails saying view cannot found in hierarchy. use onview(withtext("alert_dialog_text")).perform(pressback()); must dismiss dialog.

javascript - Change images randomly on click without repeating -

i found code on stack overflow: change images on click . and works me. want random, how can prevent repeating images. should first repeat images, when user has clicked through images. i have made jsfiddle code: http://jsfiddle.net/gr3f4hp1/ jquery code: var images = ["02.jpg","03.jpg","01.jpg"]; $(function() { $('.change').click(function(e) { var image = images[math.floor(math.random()*images.length)]; $('#bg').parent().fadeout(200, function() { $('#bg').attr('src', 'items/'+image); $(this).fadein(200); }); }); }); keep track of numbers have generated, , if repeat new number. you can work around var usedimages = {}; var usedimagescount = 0; function displayimage(){ var num = math.floor(math.random() * (imagesarray.length)); if (!usedimages[num]){ document.canvas.src = imagesarray[num]; usedimages[num] = true; ...

amazon ec2 - Sonar qualityprofile page does not display correctly using docker when data volume is mounted from disk. -

i'm setting sonarqube server , wanted use official dockerised version, when mount data folders volumes preserve state between restarts qualityprofiles page fails display profiles. the profiles stored though, can see them in 'compare profiles' dropdown, , preserved on restart. i've tried on safari , chrome, , behaviour consistent. there no errors in logs, , there are, far can see, no permission issues, since data being written. without mounting data volumes works fine, state not persisted on restart, deal-breaker.. anyone else problem has managed solve it? this docker-compose config sonarqube: image: sonarqube:5.1 links: - db:postgres ports: - "9000:9000" - "9092:9092" - "5432:5432" environment: - sonarqube_jdbc_url=jdbc:postgresql://postgres:5432/sonar - sonarqube_jdbc_password=sonar - sonarqube_jdbc_username=sonar volumes: - /data/sonar:/opt/sonarqube/data ...

Generate PDF from a template using Java -

i want generate pdf template, template should have automatically take values database(here using mongodb) while generating pdf. using itext creating pdf document. how can create template take values db every time generate pdf.? tried using html template. confused how take values database? this adobe make lot of money on adobe acrobat pro. call form can filled data xml, database, csv... can use software trial or try 1 of lot of free software: project xhtml pdf standalone software on windows, mac , linux: http://wkhtmltopdf.org/ template pdf php: create new pdf template php

c# - Excel DNA packing issue -

i trying pack dlls xll using exceldnapack.exe, using below command , generating pack xll file me. "$(solutiondir)dependencies\excel-dna.0.32.0\tools\exceldnapack.exe" "$(targetdir)exceltrader-addin.dna" /y but when running xll file folder dont have dependent dlls throwing exception "an exception occured while calling function onload". exception message not load file or assembly 'openapisecuritylib, version=1.0.0.0,culture=neutral,publickeytoken=null' i have main project exceltrader.dll references openapisecuritylib.dll , openapiclientlib.dll, have added reference attribute in dna file both these dlls , dependencies , added externallibrary attribute exceltrader.dll if put both openapisecuritylib.dll , openapiclientlib.dll in same folder xll file, xll file runs fine please suggest doing wrong here thanks <dnalibrary name="exceltrader add-in" runtimeversion="v4.0"> <reference path="newtonsoft.json....

For a Spring webapp with pure Java config, does it make sense to have 2 distinct contexts? -

i new spring java config, , wondering something. traditionnally spring webapps have had 2 different contexts, root application context , dispatcher servlet context. root context contains service layer (persistence configuration jpa , data access layer) , servlet context containing mvc , other web-related things. the web context inherits root context, web components have access beans in root context not opposite. with modern approach using xml-less config , org.springframework.web.webapplicationinitializer , still make sense have 2 different contexts ? it seem simpler have few annotated @configuration classes regrouping beans layer (e.g. 1 data access layer, 1 service layer, 1 web layer) , load of them in same context, : public class mywebapplicationinitializer implements webapplicationinitializer { @override public void onstartup(servletcontext container) { // create dispatcher servlet's spring application context annotationconfigwebapplicat...

javascript - Chrome won't clear cache (ctrl+F5, shift+F5 (also with debug console opened) does not work) -

i working on website, chrome decided not clear cache no matter do. if open file (css , js) on new tab, can see new updated version being loaded, chrome not use files on website. i tried f5, ctrl+f5, shift+f5, f12 + empty cache , hard reload, f12 , ctrl+f5 (and shift+f5). had issue before , tried removing local storage, deleting local storage file, uninstalling chrome , clearing data not deleted. nothing works! as told, had issue before, , did tenaming file edited. wont keep renaming files edit (or adding version query strings them). when try device mode (mobile emulation option in debug console on chrome), uses new version of files there. when disable it, goes old version in cache. any ideas? extremly annyoing , preventing me work on website, changes css , js being ignored. ps.: know there question: chrome won't clear cache... ctrl + f5 doesn't seem work either , accepted answer not working @ me , faq has nothing like: "what if have same question once ans...

asp.net - Consume Web API haing Action methods with custom name -

Image
i trying consume web api in action method names custome createcustomer(..), getcustomer(...). these annotated [httppost]/[httpget]. not sure how consume using httpclient(). if set following , me call httpclient client = new httpclient(); client.baseaddress = new uri("http://host/directory/"); client.defaultrequestheaders.accept.add(new mediatypewithqualityheadervalue("application/json")); var response = client.postasjsonasync("api/customer", cutomerobj).result; it throws 404. if use fiddler , send arequest http://host/directory/api/customer json customer object works perfectly what missing here? need user post , methods? you need configure route include action api/{controller}/{action}/{id} , make call api/customer/createcustomer from c#, var t = new httpclient().getasync("http://localhost:63154/api/userapi/createcustomer").result.content.readasstringasync().result;

properties - Wso2 - call sequence with get-property -

this scenario: - 3 sequences: s1, s2, s3 - 1 variable stored in registry (localentry) sets 1 - seqname concat - try call sequence get-property what i've done until now: 1) extract value <property name="getsequence" expression="get-property('registry','conf:repository/myversion2.xml')" scope="default" type="om"/> <log level="custom"> <property name="testversion::localentry" expression="$ctx:getsequence//localentry"/> </log> 2) concat <property name="seqname" expression="concat('s', $ctx:getsequence//localentry)" scope="default" type="string"/> 3) call sequence <sequence key="get-property('seqname')"/> 4) execute test 5) error: tid: [0] [esb] [2015-07-08 10:27:36,325] info {org.apache.synapse.mediators....

django, name 'IndexView' is not defined -

i following this tutorial . @ moment @ this point when start server python manage.py runserver 0.0.0.0:8000 , open url in browser, receive following error: name 'indexview' not defined this urls.py from django.conf.urls import include, url django.contrib import admin django.conf.urls import patterns rest_framework_nested import routers authentication.views import accountviewset router = routers.simplerouter() router.register(r'accounts', accountviewset) urlpatterns = patterns( '', url(r'^admin/', include(admin.site.urls)), url(r'^api/v1/', include(router.urls)), url('^.*$', indexview.as_view(), name='index'), ) i don't know how solve problem, since never saw myself declaring indexview somewhere. awesome if guys give me suggestions on one. edit: my views.py from django.shortcuts import render # create views here. rest_framework import permissions, viewsets authentication.models import...

Cakephp 3 pagination - how get active link -

i wanted ask, how can configure pagination show active link. no have this: when on 3 page, cant style button show user position. template pagination looks this: $config = [ 'number' => '<li><a href="{{url}}">{{text}}</a></li>', 'current' => '<li><a href="{{url}}">{{text}}</a></li>',]; i have tried cakephp3 docs, without success. this easy way working. $config = [ 'number' => '<li><a href="{{url}}">{{text}}</a></li>', 'current' => '<li class="current"><a href="{{url}}">{{text}}</a></li>', ];

xpath - Extracting path from xml -

i trying extract particular xpath returned xml response on jmeter. sample response xml: <?xml version="1.0" encoding="utf-8"?> <responses> <rate href="http://test.com/psi?attribute1=x&attribute2=y"> <cost currency='usd'>10</cost> </rate> </responses> i using http://codebeautify.org/xpath-tester# obtain xpath. need cost "10". looking @ xpath - //responses/rate/cost/text() returns blank value. update xml (note: removed href part) : <?xml version="1.0" encoding="utf-8"?> <responses> <rate> <cost currency='usd'>10</cost> </rate> </responses> the same xpath //responses/rate/cost/text() returns "text = 10". idea problem href causing? i tried xml , jmeter gives me: assertion failure message: reference entity "attribute2" must end ';' delimiter. see log file further detai...

compare using like operator in mysql is not working -

the mysql query tried is select 'a? b?' 'a b' currently output 0. how make result 1? if need match it. must change like not like . select 'a? b?' not 'a b' result 1. edit you need add % . select 'a? b?' '%a%b%'

android - Activity retain instance of Fragment on onSaveInstance -

i'm writing application using onsaveinstance(..) retain values on device config change(say device font, local). here application activity using multiple fragment display. after chnage in config change when coming back app oncreate(..) execute , app checked if bundle object null. till state app didn't set fragment child but still last set fragment (before change in config) child started execute it's life cycle method. how can prevent it, 1 way check same bundle object fragment child, same activity , return. there other way remove child activity on device-config change! activity reference code handle re-calling: protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.reading_activity); if(savedinstancestate == null) { init(savedinstancestate); } else { // don't } } here init(..) responsible set fragment child.

hadoop - Running MapReduce Code on Eclipse -

i have doubt. if run mapreduce code via eclipse in master node , code run using resources of entire cluster or run locally on master machine ? "entire cluster". this depends on configuration , yarn manager(can see log , status on yarn)

javascript - Array not accessed outside of function -

i'm trying use global arrays store data used @ later course. however when run through chrome debugger console push function doesn't add them array associated either, nor errors. i've looked @ many other examples , cannot see i'm going wrong. could show me i'm going wrong? javascript: var hv = ['1', '2', '3', '4']; $(document).ready(function () { (var = 0; < hv.length; i++) { getvmsonhyper(hv[i]); } }); function getvmsonhyper(id) { $.ajax({ type: "get", url: "/api/function/" + id, contenttype: "application/json; charset=utf-8", datatype: "json", success: virtualmachineinfo }) } var avrg_mem = []; var avrg_cpu = []; var avrg_lng = []; function virtualmachineinfo(vmdata) { var vmcount = vmdata.length; avrg_lng.push(vmcount); var mem_size = "medium"; var cpu_size = "medium"; ...

javascript - Why let and var bindings behave differently using setTimeout function? -

this question has answer here: what's difference between using “let” , “var” declare variable? 21 answers this code logs 6 , 6 times: (function timer() { (var i=0; i<=5; i++) { settimeout(function clog() {console.log(i)}, i*1000); } })(); but code... (function timer() { (let i=0; i<=5; i++) { settimeout(function clog() {console.log(i)}, i*1000); } })(); ... logs following result: 0 1 2 3 4 5 why? is because let binds inner scope each item differently , var keeps latest value of i ? with var have function scope, , 1 shared binding of loop iterations - i.e. i in every settimeout callback means the same variable finally equal 6 after loop iteration ends. with let have block scope , when used in for loop new binding each iteration - i.e. i in every settimeout callback means a different va...

Regarding conversion of image-to-base64 string in TouchDevelop -

i getting image (encoded in base64 string format) server. base64-encoded string has converted image. doing in 2 steps: convert base64 encoded string buffer - using bits -> string buffer (string,"base64") write buffer picture (of same dimensions) - using picture -> write buffer (buffer) , i'm displaying picture. the base64 string server (whole string): ivborw0kggoaaaansuheugaaajeaaaaecayaaaaspvwuaaaamuleqvr42u3sqqoaiqgawl7h/x+6sqslhcqcpi7qitgnmvysiik+lex+/zjpcifnsnvs5pzw3paunlgrm/w6ezpqv3yjqqqrrbbbbbfeeeeeeuqqqqqrrbbbbbfeeeeeeuqqqqqrrbbbbbfeeeeeeuqqqqqrrbbbbbfeeeeeeuqqqqqrrbbbbbfeeeeeeuqqqqqrrbbbviuoawqllkahgpjnaaaaaelftksuqmcc the problem is: not getting desired image when display on wall. shows small image. so tried finding string touchdevelop expected in bits -> string buffer(string,"base64") method. i obtained original image online converter ( http://www.motobit.com/util/base64-decoder-encoder.asp ) supplying same string o...

numpy - ValueError: index must be monotonic increasing or decreasing -

ser3 = series(['usa','mexico','canada'],index = ['0','5','10']) here ranger = range(15) i error while using forward fill in ipython ser3.reindex(ranger,method = 'ffill') /users/varun/anaconda/lib/python2.7/site-packages/pandas/core/index.pyc in _searchsorted_monotonic(self, label, side) 2395 return len(self) - pos 2396 -> 2397 raise valueerror('index must monotonic increasing or decreasing') 2398 2399 def get_slice_bound(self, label, side, kind): valueerror: index must monotonic increasing or decreasing there's original index being string , not numeric. if change original index numeric (e.g., index=[0, 5, 10]), works correctly. in [1]: pandas import series ...: ser3 = series(['usa','mexico','canada'],index = [0,5,10]) ...: ranger = range(15) ...: ser3.reindex(ranger,method = 'ffill') ...: out[1]: 0 usa...

javascript - Highlight text in HTML by int offset (start-end) without knowing actual textNodes -

i need highlight text in html, given start , end position (integers, example 600th 712th character). i able using range.setstart(startnode, startoffset) , range.setend(endnode, endoffset) , works if know startnode , endnode , textnodes , inside shallow element. is possible highlight text without knowing these nodes ? if not, optimal solution determine start , end nodes ? 1 solution go through dom , count characters... you can use treewalker textnodes main div , go through textcontent's length determine start , end points should : var maindiv = document.getelementbyid('main'); // create treewalker accept textnodes var treewalker = document.createtreewalker(maindiv,nodefilter.show_text,null,false); // array containing our textnodes var textnodelist = []; while(treewalker.nextnode()) textnodelist.push(treewalker.currentnode); function getrangefromint(start, end){ var indexsizeerror = 'indexsizeerror: index or size negative or greater...

java - Message sent from server not received by client when sending outside ServerHandler -

i trying send message netty server connected client. what want similar this question . however, using io.netty (the 1 org.jboss.netty.* package) version 3.10.0.final here have done : telnetserver.java contains code initiate server. public static void main(string[] args) throws exception { // configure ssl. final sslcontext sslctx; if (ssl) { selfsignedcertificate ssc = new selfsignedcertificate(); sslctx = sslcontext.newservercontext(ssc.certificate(), ssc.privatekey()); } else { sslctx = null; } // configure server. serverbootstrap bootstrap = new serverbootstrap( new nioserversocketchannelfactory( executors.newcachedthreadpool(), executors.newcachedthreadpool())); // configure pipeline factory. bootstrap.setpipelinefactory(new telnetserverpipelinefactory(sslctx)); // bind...

Openstack: login as admin and retrieve server data from different tenants via python -

i'm writing cron job in python openstack should read server ids database , servers api using python-novaclient. in pseudo code things should work this: session = login_to_keystone(user="admin", password="something") #or use token nova_client = get_nova_client(session) #the servers array holds dictionaries server, user , tenant ids strings # e.g. {"server_id": "1-2-3", "tentant_id": "456", user_id: "11111-2222"} server in servers: server_obj = nova_client.servers.get(server.server_id) ...do stuff server_obj (read data it, delete,...)... what i've come following, it's not right endpointnotfound exception. i'm using devstack juno. from keystoneclient.v2_0 import client keystone_client keystoneclient import session novaclient import client nova_client #the url admin endpoint keystone = keystone_client.client(token="my-admin-token", auth_url="http://192.168.1....