Posts

Showing posts from June, 2011

iOS Swift: How to create a multi column hierarchy with UITableView/UICollectionView in landscape mode on iPad -

Image
i create app ipad (and later adopt iphone) lets manage data in 4 hierarchical levels. each level depends on selection make in previous level. e.g. first select country list of countries, city list of cities in country , on. the layout inspired spotify app ipad in landscape mode. can select artist , album artist , song. (i didn't attach screenshot spotify, might know looks like.) the problem is, can't find right approach create ui whithin xcode. i'd start using 4 uitableviewcontrollers or uicollectionviewcontrollers. how display them on view @ same time? i know it's possible combine multiple view controllers in 1 parent view controller, e.g. when using uipageviewcontroller. in case don't know kind of controller start with. right show 4 uitableviewcontrollers fullscreen , stacked. how can combine them shown @ same time , make possible user navigate through them in spotify app?

javascript - Get iteration count of for...of loop -

this question has answer here: how can current number of accessed in of loop? 5 answers access es6 array element index inside for-of loop 2 answers how current iteration count of for...of loop? let iterable = new set([1, 1, 2, 2, 3, 3]); let = 0; (let value of iterable) { console.log('value in iteration count = ' + + ' :' + value); i++; } this have, there kind of built in iteration count variable can replace variable i ? you can use indexof if don't want make temp variable, solution more efficient. can iterate on keys of collection, rather values.

ionic framework - Save information about cordova packages -

i using several cordova packages in ionic app. below command use installing cordova package cordova plugin add cordova-plugin-network-information this works fine. challenge information not saved in package.json. so, next developer has pulled code has manually install cordova plugins have installed. i looking 'npm install xxxx --save' save plugin/packages information somewhere , command pull packages automatically. in projects, have seen following in package.json "cordovaplugins": [ "cordova-plugin-camera", "cordova-plugin-statusbar" ] however, not able find command add these package.json or should updated manually? if you're using cordova 4.3.0 or higher plugins using should documented in , restored config.xml automatically. see docs here . see docs on saving plugins , on restoring plugins .

laravel - has() function on empty ErrorBag returns different boolean result depending on environment -

in laravel app, have discrepancy on output of following line: $errors->has(); depending on environment; returns false locally, true on stage , prod. i dumped defined vars , same empty array in both: "errors" => viewerrorbag {#170 ▼ #bags: [] } i $errors->count(); returns 0 in both envs. what reason?

Django advanced queries -

i have 3 models: pupils , instructor , group . connected through pupils model so: class pupils(models.model): instructor = models.foreignkey(instructor, blank=true, default=none, null=true) group = models.foreignkey(group, default=none, null=true, blank=true) how write property group model returns instructor s have pupils current group? best can find instructors have pupils: @property def instructors(self): pupils.models import instructor return list(instructor.objects.filter(pupils__isnull=false).values()) how count number of pupils current group each instructor ? i have 3 models: pupils, instructor, group. connected through pupils model so: this means have m2m relation between instructor , group can define this: class instructor: #... groups = models.manytomanyfield(group, through='pupils') now using m2m relation, can take instructor groups this: instructor.groups.all() you can use reverse relation of m2m r

javascript - How do I wrap a return type with a promise in TypeScript? -

i'm writing angular 1.x typescript, , have service (dataservice) that's responsible loading data. simple example, queries node , returns node. in interface: getnode(id: number): ng.ipromise<node>; and implementation: getnode(id: number) { return this.ajaxservice.getnode(id) .then((result: ng.ihttppromisecallbackarg<node>) => { return new node(result.data.id, result.data.name); }); } however, introduce service stores these results , returns them if i've queried them before. like: getnode(id: number) { var loadednode = this.storageservice.nodes.filter(e => (e.id == id)); if (loadednode.length > 0) { return loadednode[0]; } return this.ajaxservice.getnode(id) .then((result: ng.ihttppromisecallbackarg<node>) => { var n = new node(result.data.id, result.data.name); this.stora

java - Android ProgressBar in FrameLayout is never visible -

Image
hello i'm trying show circular progress bar when user clicks on log in button, similar screenshot below. problem progress bar never shown, tough changed it's visibility view.visible in loginactivity.showprogressbar() with progressbar.setvisibility(view.visible); . activity_log_in.xml <?xml version="1.0" encoding="utf-8"?> <framelayout style="@style/layout" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context=".activity.loginactivity"> <!-- tw login form --> <include android:id="@+id/log_in_form" layout="@layout/log_in"/> <!-- loading indicator --> <progressbar android:id="@+id/progress_bar" style="@style/widget.appcompat.progressbar" android:layout_width="wrap_content" android:layout_h

c# - Convert Grayscale image into RGB with Magick.Net -

is possible convert image grayscale color space rgb using magick.net? if is, has done? i've tried this: image.format = magickformat.png; image.colorspace = imagemagick.colorspace.srgb; when setting values format , colorspace respectively persist in memory, once write method called gets reverted original values. i'm wondering if needed perform transformation or along these lines, example when converting cmyk rgb 1 has this: image.transformcolorspace(imagemagick.colorprofile.uswebcoatedswop, imagemagick.colorprofile.srgb); it looks me i'm missing obvious, it's hard find out there subject.

How to create a directory in C directory of Windows7 in C#.Net -

i writing exception log (eg. log.txt) , want write in following path "c:\program files (x86)\app\log". when so, whole path access denied means cannot create folder called log , simultaneously write log.txt , have compression code zip log files log.zip days based? did try of code snippets stack overflow apparently nothing fruitful. how resolve problem?? regards, gibson the error getting due fact regular user doesn't have permission create folders or files beneath "c:\program files (x86)\" directory. this on purpose because regular user should not writing directory. applications installed beneath directory administrative user, or user elevated permissions. application should writing log files location beneath user's profile directory, e.g. somewhere beneath "%appdata%". i work in department have support poorly-written vendor software needs update files somewhere beneath %programfiles% directory, , it's total nightmare. d

iOS - Where is object stored in application NSUserDefault? -

this question has answer here: iphone - [nsuserdefaults standarduserdefaults] file stored on computer? 3 answers i using nsuserdefault in application of times can't find it's storing object (storing means it's there in app somewhere). googled couldn't find location. stored? thank you! very exact answer is coresimulator/devices/->device id<-/data/library/preferences where nsuserdefault storing? nsuserdefault stored in where [nsuserdefaults standarduserdefaults] file stored on mac?

java - How parse internal array json -

this question has answer here: why gson fromjson throw jsonsyntaxexception: expected type other type? 2 answers i have json: { "id": 1, "result": [ { "id": 1, "imgurl": "http://test.com/image.jpg", "title": "image" }, { "id": 2, "imgurl": "http://test.com/image2.jpg", "title": "image2" } ], "jsonrpc": "2.0" } how can parse internal array, try default retroif gson parsing using model public class testrequest { public int id; public list<arrayitems> result; public string jsonrpc; } public class item { public int id; public string imgurl; public string title; } and have error: expected begin_object begin_array. try hand parse ite

ios - Swift Json data parsing without array -

i have working json data parsing array codes want change dictionary parsing. new json file { "id": 450, "name": "nameforitem", "image": "234234.jpg" } my old json file working success [{ "id": 450, "name": "nameforitem", "image": "234234.jpg" }] my parsing codes. /// convert json data array private func getfromjson(jsondata: nsdata) throws -> [place] { var places = [place]() { if let jsonarray = try nsjsonserialization.jsonobjectwithdata(jsondata, options: .allowfragments) as? [[string: anyobject]] { in jsonarray { var properties = [string: anyobject]() properties[placejsonkeys.id] = i[placejsonkeys.id] properties[placejsonkeys.name] = i[placejsonkeys.name] let place = place(properties: properties) places.appe

Using Boolean expressions as arguments on Xtext -

i'm trying create grammar on xtext allows pass boolean expression argument special function gets only boolean parameters (implicitly, without declaring it's boolean type). for example: somefunction(...){ foo(4>3, a==b) } foo(arg1,arg2) { //do arg1 , arg2 } do have simple example demonstrates how it? thank you. from question not quite clear actual problem is. if building grammar expression: use starting point expression: orexpression ; orexpression returns expression: andexpression ({orexpression.left=current} "||" right=andexpression)* ; andexpression returns expression: comparisonexpression ({andexpression.left=current} "&&" right=comparisonexpression)* ; comparisonexpression returns expression: primaryexpression ({comparisonexpression.left=current} operator=("<"|"<="|"=="|">="|">") right=primaryexpression)* ; primaryexpres

java - Error in MockMvc test case for controller -

Image
i have written junit test case controller layer method, , failing due mismatch in expected outcome. test case follows: @test public void testgetnodestatuscount() throws exception { listnodes listnodes = new listnodes(); // argumentcaptor<integer> userid = argumentcaptor.forclass(integer.class); when(usermanagementhelper.getnodestatuscount(0)).thenreturn( new responseentity<listnodes>(listnodes, new httpheaders(), httpstatus.ok)); mockmvc.perform(get("/usermgmt/nodestatus")).andexpect(status().isok()); } method test case written follows : @requestmapping(value = "/nodestatus", method = requestmethod.get, produces = mediatype.application_json_value) @responsebody public responseentity<listnodes> getnodestatuscount(@requestparam("userid") int userid) { return usermanagementhepler.getnodestatuscount(userid); } failure message : thing not

set background image to relative layout in xamarin.forms -

how can set background image relative layout in xamarin.forms portable project? i have tried following code: xamal file : <relativelayout x:name="title"> <label text="hello xamarin" textcolor="black" fontsize="22" fontfamily="tahoma" horizontaloptions="center" horizontaltextalignment="center" relativelayout.xconstraint="{constraintexpression type=relativetoparent,property=width, factor=0.03}" relativelayout.yconstraint="{constraintexpression type=relativetoparent, factor=0, property=y}" /> xaml.cs file : public partial class mainapp : contentpage { public image bgimage { get; set; } public mainapp() { this.backgroundimage = "/images/landing_page.jpg"; bindingcontext = this; initializecomponent(); } } you can add image view relative layout, pleas

xml - How to merge elements between two documents using XSLT 2.0? -

i have default configuration items in xml document follows: <programconfig> <fragment xml:lang="en" name="targetsector">fragment/target_sector.xdp</fragment> <fragment xml:lang="fr" name="targetsector">fragment/target_sector_fr.xdp</fragment> <mastertemplate xml:lang="en">master/default_en.xdp</mastertemplate> <mastertemplate xml:lang="fr">master/default_fr.xdp</mastertemplate> </programconfig> specific programs can override default configuration, example: <programconfig> <fragment xml:lang="en" name="targetsector">fragment/1-5abq/target_sector.xdp</fragment> <mastertemplate xml:lang="fr">master/default_fr_1-5abq.xdp</mastertemplate> </programconfig> i need merge xml documents, output becomes: <programconfig> <fragment xml:lang="en" na

Aurelia event won't fire on first page load -

i'm using aurelia's eventaggregator publish , subscribe events in app. of custom elements take while load, i've used loading event tell main app.js add spinner page during loading. this works fine once app has loaded , start switching between routes, however, on first page load event doesn't seem fire - or @ least, isn't picked subscribe method. here's app.js does: attached () { this.mainloadingsubscription = this.eventaggregator.subscribe('main:loading', isloading => { // if main loading if (isloading) { document.documentelement.classlist.add('main-loading'); } // stopped loading else { document.documentelement.classlist.remove('main-loading'); } }); } and here's custom elements do: constructor () { this.eventaggregator.publish('main:loading', true); } attached () { this.dosomeasyncaction.then(() => { this

Convert full time string to Unix timestamp in jQuery / javascript -

i need produce timestamp of each date/time string gets produced in foreach loop. how turn string mon aug 08 2016 10:09:42 gmt+0100 (bst) unix timestamp comparison? i going use single value jquery sort (code below) var boards = $(".socialbox"); boards.sort(function(a, b){ return $(a).data("date") - $(b).data("date"); }); $("#social-board").html(boards); as can imagine above code doesn't work on current date/time string. you can convert string data date object along .gettime() number of milliseconds since 1970/01/01: boards.sort(function(a, b){ return new date($(a).data("date")).gettime() - new date($(b).data("date")).gettime(); });

java - Launch an mobile app on emulator using appium -

i wanted launch app in genemotion using appium - java. i can launch app on real device, feel better use emulators instead of real devices. how can ? just add virtual emulator on genemotion, make , running. open terminal , type: adb devices it show, list of devices attached, make sure new virtual device running on port. ie : 192.168.56.101:5555 device now use below use desired capabilities below : desiredcapabilities capabilities = new desiredcapabilities(); capabilities.setcapability("devicename", "name of emulator"); capabilities.setcapability("platformname", "android"); driver = new androiddriver(new url("http://0.0.0.0:4723/wd/hub"), capabilities); it launch apk in genemotion.

Wit.ai: search strategy options -

Image
there 3 search strategies own entities: trait , free-text , keywords , explained in documentation . can't understand, allowed combinations of these options. able choose either: trait keywords free-text , keywords why can't free-text chosen on it's own, in combination keywords ? edit: definition of free-text , documentation: when need extract substring of message, , substring not belong predefined list of possible values. definition of keywords : when entity value belongs predefined list, , need substring matching in sentence. from definition, free-text , keywords mutually exclusive me. therefore can't understand why can't choose free-text on own, , why possible choose both simultaneously. i think solution in word 'extract' in free-text , 'matching' in keywords, cause in case of free-text extract substring message substring has have words matches original message. in example there ' i be ' mu

javascript - Sorting key value pair on basis of another array -

i have key value pairs : var x={1:car, 2: cycle, 3:john } this response coming json.[object object] have array :var arr=[1,3,2] want sort x per arr . order should : {1:car,3:john,2:cycle} in javascript how achieve this. you don't need sort them, make new empty array , populate getting values of arr , using them index of x . var x = { 1: 'car', 2: 'cycle', 3: 'john' }; var arr = [1, 3, 2]; var output = []; arr.foreach(function(item){ output.push(x[item]); }); console.log(output); fiddle .

MySQL Datetime showing incorrect time. ASP.NET C# -

i added mysql table column called "registerdate", datatype of column datetime (i tried timestamp) , in default have current_timestamp . the datetime comes automatically after registration, showing correct day month , year showing incorrect hour (-10 hours). hope knows how fix it, helping. from mysql documentation on timestamp (emphasis mine): mysql converts timestamp values current time zone utc storage, , utc current time zone retrieval. ( this not occur other types such datetime. ) default, current time zone each connection server's time. https://dev.mysql.com/doc/refman/5.5/en/datetime.html

CSS issue in JQuery date picker -

i using below script date picker in jquery: $('#dob').datepicker({ mindate: new date(1900,1-1,1), maxdate: '-18y', dateformat: 'dd-m-yy', changemonth: true, changeyear: true, yearrange: '-100:-18' }); but date picker goes under table , header portion showing rest portion hide table. i have tried below css putted in style.css not solved. .ui-datepicker{ z-index: 9999 !important;} how solve issue? please help use z-index while calling function this $('#dob').datepicker({ mindate: new date(1900,1-1,1), maxdate: '-18y', dateformat: 'dd-m-yy', changemonth: true, changeyear: true, yearrange: '-100:-18', //comment beforeshow handler if want see ugly overlay beforeshow: function() { settimeout(function(){ $('.ui-datepicker-div').css({'position': 'relative', &

javascript - Cannot call angularjs function from dropdown(select) using select2 -

i hitting database on dropdown's on-change event. have make tags after userselects of them. jsp file <select id="multipleselectlocation" data-placeholder="select option" ng-model="search" ng-change="searchlocation(search)" multiple="true" > <option value="1">option 1</option> <option value="2" ng-repeat="location in userlocationlist"> {{ location.city }},&nbsp; {{location.state}}, &nbsp;<b>{{location.country}}</option> </select> controller $scope.searchlocation = function(search) { /* if (search.length < 3) { $scope.userlocationlist = null; return false; }*/ $http.get( location.protocol + '//' + location.host + contextpath + '/services/searchlocation', {

Save multiple values of a command line option in Perl array -

i have script needs take options, 1 of these -i (input). tried following code input parameters array: #!/usr/bin/perl use strict; use warnings; use getopt::long; @input = (); $help = ''; $other = ''; getoptions( 'help' => \$help, 'input=s{1,}' => \@input, 'other=s' => \$other ); when try run ./my_script.pl -i param1 param2 -o aaa this: error in option spec: "input=s{1,}" if run explicitly perl perl my_script.pl -i param1 param2 -o aaa works smoothly. there way these parameters array (not using @argv ) without explicitly invoking perl command line? turns out have more 1 version of perl installed. 1 of them (the older one) has older version of getopt::long module doesn't support input=s{1,} syntax. when switched invoking perl up-to-date version installed, script ran no errors.

xamarin.ios - Xamarin.Forms Unhandled Exception -

Image
i'm trying carouselview on project. when run project,i error. here xaml code; <?xml version="1.0" encoding="utf-8"?> <base:hoteldetailpagexaml xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:class="xamarincrm.pages.hotels.hoteldetailpage" xmlns:statics="clr-namespace:xamarincrm.statics" xmlns:base="clr-namespace:xamarincrm.pages.hotels" xmlns:hotelviews="clr-namespace:xamarincrm.views.hotels" xmlns:i18n="clr-namespace:xamarincrm.localization" xmlns:cv="clr-namespace:xamarin.forms;assembly=xamarin.forms.carouselview" title="{binding hotel.name}"> <base:hoteldetailpagexaml.content> <stacklayout spacing="0"> <cv:carouselview itemssource="{binding hotel.hotelimages}"> <cv:carouselview.itemtemplate> <

php - WooCommerce custom coupon discount -

i trying change default woocommerce coupon discount function adds discount price total cart price. instead of subtracting discount should add price. i found done in includes/class-wc-cart.php file, in function called: get_discounted_price , woocommerce_get_discounted_price i tried add filter accomplish above not working quite well: function custom_discount($price) { global $woocommerce; $undiscounted_price = $price; $product = $values['data']; $discount_amount = $coupon->get_discount_amount( 'yes' === get_option( 'woocommerce_calc_discounts_sequentially', 'no' ) ? $price : $undiscounted_price, $values, true ); $discount_amount = min( $price, $discount_amount ); $price = max( $price + $discount_amount, 0 ); return $price; } add_filter( 'woocommerce_get_discounted_price', 'custom_discount', 10); anyone can me out on this? thanks ok, thing works set negative coupon discount, -10:)

curl - guzzlephp 401 unauthorized issue -

i trying guzzle http post request $ch = curl_init(); curl_setopt($ch, curlopt_url, 'https://android.googleapis.com/gcm/send'); curl_setopt($ch, curlopt_post, true); curl_setopt($ch, curlopt_httpheader, $headers); curl_setopt($ch, curlopt_returntransfer, true); curl_setopt($ch, curlopt_ssl_verifypeer, false); curl_setopt($ch, curlopt_postfields, json_encode($fields)); $result = curl_exec($ch); curl_close($ch); return $result; where headers is $headers = [ 'authorization: key=' . $api_access_key, 'content-type: application/json', ]; and post fields are $fields = [ 'registration_ids' => $registrationids, 'data' => [ 'title' => $title, 'message' => $message, 'type' => $type, ], ]; which response ok , expected if call request guzzlehttp client $url='htt

is it possible for NGINX to have a pool of N open connections to backend? -

trying use nginx reverse proxy, , have constant number of open connections backend (upstream) open @ times. is possible nginx (maybe haproxy..?) ?? running on ubuntu if makes difference something can done haproxy. end result there no more n concurrent connections backend server + open connections shared between requests coming different clients. backend app http-reuse safe server server1 127.0.0.1:8080 maxconn 32 server server2 127.0.0.2:8080 maxconn 32 the example shows 2 servers, haproxy not open more 32 connection each server, , each connection can shared between several clients whenever can done safely.

database - Unable to Connect to Azure MySQL using MySQL Work Bench -

Image
i create mysql storage in microsoft azure. did portal clicked "new > data+storage > mysql". kept defaults , continued. after azure says storage , ready. so, went "dashboard > clicked on newly created database resource". can see ip address of database. i opened mysql work bench, clicked "database >connect database" , inserted ip found in above step. kept port 3306 is. user name , password inserted username , password inserted during database creation. anyway can't connect database, below error. i tried editing "security group" in azure. below screenshot of contains now. inbound rules: outbound rules even after of these things, why still can't connect azure mysql? i using 'bitnami' , 'bitnami' comes own username , password! default password bitnami 'bitnami' , user name 'root'

WordPress project setup - Trellis, Valet or Docker? -

i want start new wordpress project developer. decisions made are: we want use bedrock wp structure we want use sage wp theme we put project in git repository i ask myself if should use trellis, valet or docker. my personal opinion trellis / docker bit project 2 developers working on it. additionally experience vagrant not positive, slow when used it. favorite valet, because it's slim. repository use beanstalk, there trigger deployments test , live system. additionally not 100% sure if server want deploy project needs docker installed - knows that? , happens when server runs on apache , not nginx? now docker has native mac , windows apps wouldn't need vagrant local dev, , running series of docker containers much faster full-fledged vm vagrant+virtualbox. right have mariadb + php-fpm + nginx + wordpress + phpmyadmin, , whole thing fast relative previous experience vagrant. faster in: faster initial install, faster start/stop, faster make changes , have

Apache Solr Tokenizers -

i using apache solr semantic search engine. in users can type , have retrieve using relevant results using words. i want split string in tokens. example: "actorsfrommumbai" -> "actors mumbai" how can achieve feature in solr ? it looks searching decompounding -> https://wiki.apache.org/solr/languageanalysis#decompounding gives possibility search part of compounding words.

php - SQL result not being sent in email -

i have forgot password php page sends user password if email in database. code working password in sent email blank. think it's cause haven't converted string cant find how so. have salted passwords in database, affecting anything? the salt: <?php $salt1 = "qm&h*"; $salt2 = "pg!@"; $token = hash('ripemd128', "$salt1$pass$salt2"); ?> the forgot password php page: <?php $error = $email = ""; if (isset($_post['email'])) { $email = sanitizestring($_post['email']); if ($email == "") $error = "not fields entered<br>"; else if (!filter_var($email, filter_validate_email)) $error='email invalid'; else { $resulte = querymysql("select email users email='$email'"); $result_pass = querymysql("select * users email='$email'"); $

Java apache poi to read exact date format as mentioned in excel -

this question has answer here: how read exact cell content of excel file in apache poi 2 answers excell cell style issue 1 answer i have seen link apache poi dataformatter on cell containing date solution updated "dd/mm/yyyy" format using simpledateformat dtformat = new simpledateformat("dd/mm/yyyy"); in case i'm not aware of format..it may in date format. in case how can handle? i have tried read date value date cell in xlsx file. cell having data as: 8/5/2016 output im getting : 8/5/16 i need same format mentioned in date cell. if know format can use simpledateformat dtformat = new simpledateformat("dd/mm/yyyy") . without knowing format there way it? sample code: int r1c1=5; switch (cell.getcelltype()) { case xssfcell.cell_ty

html - .NET Core separating JavaScript from CSHTML and access ViewData -

is there way access viewdata separate javascript file way can access embedded javascript code on cshtml? i separate javascript code , have data load directly in javascript file instead of using hidden field in html , access pull getelementbyid seems tedious pass data html javascript , html again. cshtml file @using statisticondoappcore.models.viewmodels; @using { var info = (shop)viewdata["shopinfo"]; } embedded javascript code subscriptionshopdata = [ { y: 'uge ' + @info.currentweek, a: @info.creationscurrentweek }, { y: 'uge ' + @info.currentweek - 1, a: @info.creationslastweek }, { y: 'uge ' + @info.currentweek - 2, a: @info.creationscurrentweekminustwo }, { y: 'uge ' + @info.currentweek - 3, a: @info.creationscurrentweekminusthree } ]; new morris.bar({ element: 'bar-subscriptions-shop', data: subscriptionshopdata, ... you can't access

android wear application not installing immediately -

i developing mobile multidex application has wear support.when install signed apk mobile,it works takes lot of time deploy on huawei watch. i not know root cause of delay. . has come across same situation?i factory reset both handset , watch.thanks or clue. finally downgrade playservice library 8.4, not know why if choose 9.4 or >9.0 not deployed wearable application huawei watch

appending a class to an element based on its data-html using javascript -

i want append class 'activetab' tag on document ready. need select tag it's data-html i'm not sure how this. so how html loads currently: <ul class="tabbedgroupings_tabs"> <li class="tg_tab" data-html="academicprofessionalanddevelopment">academic, professional , development</li> <li class="tg_tab" data-html="cultural">cultural</li> <li class="tg_tab" data-html="physicalactivityandperformance">physical activity , performance</li> <li class="tg_tab" data-html="politicsreligionandcampaigning">politics, religion , campaigning</li> <li class="tg_tab" data-html="society">society</li> <li class="tg_tab" data-html="specialinterest">special interest</li> <li class="tg_tab" data-html="all">all</li> </ul> i add '

javascript - backbone - event not fired on selected element changed -

i'm generating drop down list backbone.view . after attaching dom, change event not fired. delegateevents doesn't fixes it. can show me blind spot is? model , collection: app.models.dictionaryitem = backbone.model.extend({ default: { key: '', value: '', id: 0 } }); app.collections.dictionary = backbone.collection.extend({ model: app.models.dictionaryitem, initialize: function (models, options) { }, parse: function (data) { _.each(data, function (item) { // if(item){ var m = new app.models.dictionaryitem({ key: item.code, value: item.name }); this.add(m); // } }, this); } }); views: app.views.itemview = backbone.view.extend({ tagname: 'option', attributes: function () { return { value: this.model.get('key')

Struts2 xml validation on HTML tags -

we migrating our application struts1 struts2. our forms composed html tags , not using struts2 tags. forms displayed without problem. when add struts xml validation files forms empty (no input displayed). is there way use struts2 xml validation on html tags ? i suggest use validate() method actionsupport class. method have wide range of validation possibilities. struts validators have possibility check single values without relation, see struts form validation . with method can check whatever want: public class myaction extends actionsupport { string valuetocheck = ""; @override public void validate() { if (valuetocheck.isempty()) { addfielderror("valuetocheck", "please fill in..."); } } } if fielderrors -map filled, validation method return result of type input , otherwise execute() -method called (or maybe defined).

java - how to check if fragment exists and is Visible in a container? how to remove it if it exists? -

i calling method displays data on button click everytime. each time button clicked call method that creates frag object bundles data frag puts data in frag adds frag view in main activity commits transaction i'm facing 'caused by: java.lang.illegalstateexception: commit called' on button click need check if frag exists , either replace or something. i'm confused. here's code. public void retrieve_and_display_data(string co) { string res = null; try { res = new getvaluefromservicecall().execute(co, "", "").get(); } catch (interruptedexception e) { e.printstacktrace(); } catch (executionexception e) { e.printstacktrace(); } list < string > company_stock_details = arrays.aslist(res.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)", -1)); stock_price_frag frag_obj = new stock_price_frag(); bundle b = new bundle(); b.putstri

c++ - WM_XBUTTONDOWN return value difference between ATL/MSDN documented value? -

from https://msdn.microsoft.com/en-us/library/windows/desktop/ms646245(v=vs.85).aspx , extract that: if application processes message, should return true. more information processing return value, see remarks section. in case matters, same holds wm_xbuttonup , wm_xbuttondblclk . i expected find msg_wm_xbuttondown this. however, in atlcrack.h chromium ( https://src.chromium.org/svn/trunk/src/third_party/wtl/include/atlcrack.h ) , find following: // void onxbuttondown(int fwbutton, int dwkeys, cpoint ptpos) #define msg_wm_xbuttondown(func) \ if (umsg == wm_xbuttondown) \ { \ setmsghandled(true); \ func(get_xbutton_wparam(wparam), get_keystate_wparam(wparam), _wtypes_ns::cpoint(get_x_lparam(lparam), get_y_lparam(lparam))); \ lresult = 0; \ if(ismsghandled()) \ return true; \ } similar pieces can found msg_wm_xbuttondown , msg_wm_xbuttondblclk . in snippet, line lresult = 0 confuses me. shouldn't lresu

javascript - Random Hover Effects -

how can randomize hover effects? for example: <p>test</p> p:hover { background: yellow; } p:hover: background: red; } please note above for-example only. question is, how can randomize hover effects, shows background:yellow; , background:red; once in random order on onmouseover ? there should not order, example: on first hover - 1 class added, on second - another. should completely random . use following function random colors , use mouseover event change background color. function getrandomcolor () { var letters = '0123456789abcdef'.split(''); var color = '#'; (var = 0; < 6; i++) { color += letters[math.floor(math.random() * 16)]; } return color; } }) $( "p" ).mouseover(function() { $(this).css("background",getrandomcolor()); }); please check fiddle .

How do I create a Rails model in a different DB schema? -

i have rails 3.2 app backed ms sql 2008. models default created in dbo schema. want have model db table has limited access want put different db schema. how do that? turns out can define table name: def change create_table "schema_name.table_name" |t| #init table end end

android How to refresh my main activity after updating database? -

i have 3 activities,the first 1 used hold values database,and list view showed on second one,when click item in list view i'll jumping third activity , able edit item selected,after updating data in database,new datas shown in second activity,but when return first one,nothing refreshed.how can updated data in first activity too? appreciated. the second activity code: import android.content.contentvalues; import android.content.context; import android.content.intent; import android.database.cursor; import android.database.sqlite.sqlitedatabase; import android.os.bundle; import android.support.v7.app.appcompatactivity; import android.util.log; import android.view.menu; import android.view.menuinflater; import android.view.menuitem; import android.view.view; import android.widget.adapterview; import android.widget.listadapter; import android.widget.listview; import android.widget.toast; public class setupacti

python - Get the content HTML of an API -

i'm tring content of api result in python. html template image inside. i tried lot of method content don't work everytime. the fuction : def screenshotlayer(self, access_key, secret_keyword, domain, args): domain = "http://" + domain url = "http://api.screenshotlayer.com/api/capture?access_key=api_key&url=http://google.com&viewport=1440x900&width=250" html = urllib2.urlopen(url).read() print html soup = beautifulsoup(html, 'html.parser') return soup.findall('img')[0]['src'] when print html , there lot of incomprehensible characters. can me resove problem ? thank much. the api not returns html, raw image file (default png). you need see if status_code 200, , if so, save result file. import requests res = requests.get( 'http://api.screenshotlayer.com/api/capture', params={ 'access_key': 'api_key', 'url': 'http:

php - How is best to setup MySQL Relational Database? -

i've been working on improving ticket system made sometime ago , don't know best way store ticket updates. background- each ticket can updated text, status can updated , can assigned other people. the tickets table looks this: tickets: |tk_id|tk_status|tk_opened_by|tk_assigned|tk_room|tk_problem|tk_date|tk_time| |-----|---------|------------|-----------|-------|----------|-------|-------| currently when ticket updated (either comment, status change or assignment) different tables used this. follows: tk_update: |update_id|tk_id|user_id|comment|date|time| |---------|-----|-------|-------|----|----| tk_status: |status_update_id|tk_id|user_id|status|comment|date|time| |----------------|-----|-------|------|-------|----|----| tk_assign: |assign_id|tk_id|user_id|assigned_to|comment|date|time| |---------|-----|-------|-----------|-------|----|----| this current set means pulling data 3 tables ticket , ordering them before displaying data on webpage. i'm think

c - Is there any faster implementation for this Splay Tree range sum? -

i have coded splay tree. nodes represented this. struct node{ node *l; /// left node node *r; /// right node int v; /// value }; now, need know summation of numbers in tree within range. this, implemented following function named summation. void summation(node *r, int st, int ed) { if(!r) return; if(r->v < st){ /// should not call left side summation(r->r, st, ed); } else if(r->v > ed){ /// should not call right side summation(r->l, st, ed); } else{ /// should call both side ret+=r->v; summation(r->l, st, ed); summation(r->r, st, ed); } return; } ret global int variable initialized 0 before calling summation function. 2 parameters st & ed defines range (inclusive). the summation function works @ complexity of o(n). can suggest faster implementation this?? this splay tree implementation did time ago , tested agains

javascript - Cascading parent child select boxes from dynamic JSON data -

Image
i've created chained select-boxes dynamically json data receive server. chaining/cascading works in way every select-box named object following properties: parent attribute: name of object parent of select-box object. options: array of option objects, each object contains: (a) option value (b) parent option value - parent select-box value current value mapped. (c) option id. selected option: object 2 properties: (a) selected value (b) id of selected value. i creating select-boxes using ng-repeat in "option" tag, or using ng-option in "select" tag, , using custom filter filter retrieved options (2) matching parent option value (2 > b) of option values (2 > a) "currently selected value" (3 > a) of parent object. doing many-to-one mapping child option values selected parent value using custom filter. i able correctly map parent-child select-boxes, issue when change parent select-box value, "selected option value" of chil

python - Why does doctest fail with string containing UTF-8 chars? -

i'm reading plain ascii html file (charset=utf-8) containing string: <title>what’s new?</title> this string unusable came function (to used after string has been hexlify'd). then, included docstring test: def to_be_replaced(reprstring): """ :reprstring: repr(string) -- won't work otherwise >>> s = "<title>what’s new?</title>" >>> r = repr(s) >>> print r <title>what\xe2\x80\x99s new?</title> >>> to_be_replaced(r) set(['\xe2\x80\x99']) """ regex = re.compile('([\x7f-\xff]{2,})') return set(re.findall(regex, reprstring)) unfortunately, test fails: >"e:\python27\pythonw.exe" -u "test_to_be_replaced.py" replaced: set(['\xe2\x80\x99']) ********************************************************************** file "test_to_be_replaced.py", line 14, i

preg match - Search URL from Database using regular expression in SQL-Query -

i want search url "www.google.co.in/" database table. when search adding "google.co.in/" query not able search , find record because 'www' not added. want use regular expression in query search 'google.co.in' table (it doesnot mater whether http or www added or not) for using simple like operator search: select * wp_postmeta meta_value '%www.google.co.in/%' just try search this: select * wp_postmeta meta_value '%google.co.in%' or select * wp_postmeta meta_value '%google%'