Monday, 15 June 2015

php - Smarty variable expansion -



php - Smarty variable expansion -

if have ($abc} in smarty template file, $abc has been constructed in php using nowdoc syntax as,

$abc = <<<'eot' $key eot

is there way smarty fist expand $abc, , expand within $abc, i.e. expand $key well. right string literal $key in output, not within of $key.

reason doing this

i have snippets copied on place. place these tpl snippets in files of own, leads explosion of files. have single file contains these snippets. cannot include big mutual snippet file everywhere. ended constructing php file has these snippets, , utilize variables @ places need.

you utilize smarty's eval-function, php documentation says "no parsing done within nowdoc".

could utilize heredoc instead?

<? $key = 'something'; $abc = <<<eot $key eot; // {$abc} print something; ?>

php smarty

c# - Call one-way method -



c# - Call one-way method -

i'm trying implement task requires long time complete, one-way method of single web service.the thought method returns command , began perform task without forcing user wait. on local machine works fine, when deployed server - looks one-way method not called @ all. added logging, not 1 of methods of new web service has not been called. server supports anonymous access. windows business relationship anonymous access set , other services no problems. advise problem. give thanks you.

//main service ... string directory = server.mappath(...); using(onewaylauncherservice.onewaylauncher onewaylauncher= new onewaylauncherservice.onewaylauncher()) { onewaylauncher.launch(directory, doc); } ... /// oneway service namespace onewaylauncher { [webservice(namespace = "http://tempuri.org/")] [webservicebinding(conformsto = wsiprofiles.basicprofile1_1)] [toolboxitem(false)] public class onewaylauncher: system.web.services.webservice { [soapdocumentmethod(oneway = true)] [webmethod] public void launch(string directory, string doc) { processor requestprocessor = new processor(templatedirectory); string processingresult = string.empty; processingresult = requestprocessor.process(doc); } } }

if comment [soapdocumentmethod (oneway = true)] - works. think may premature cleanup, without using exact same situation.

c#

dojo - Spring.addElementDecoration for dijit.form.filteringselect fails in IE -



dojo - Spring.addElementDecoration for dijit.form.filteringselect fails in IE -

i using spring roo create page makes ajax phone call , populates section of page search form ajax call. done using standard roo tags , javascript libraries. form returned ajax simple, 1 select list.

<jsp:root xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:fn="http://java.sun.com/jsp/jstl/functions" xmlns:field="urn:jsptagdir:/web-inf/tags/form/fields" xmlns:form="urn:jsptagdir:/web-inf/tags/form" xmlns:springform="http://www.springframework.org/tags/form" xmlns:jsp="http://java.sun.com/jsp/page" xmlns:spring="http://www.springframework.org/tags" version="2.0"> <div> <jsp:directive.page contenttype="text/html;charset=utf-8" /> <jsp:output omit-xml-declaration="yes" /> <form:search id="fc_domain_profile_combination" modelattribute="combination" path="/profiles/search/combinations" z="e2lxrqkkd2cs7zjefas2zxpw4xynm="> <field:select field="searchprocessingcenter" renderempty="true" disabled="true" id="c_profile_combofilter_processingcenter" items="${proccenters}" path="/profiles" itemlabel="name" itemvalue="id"/> </form:search> <input type="hidden" id="blocksubmithd" value="false" /> </div>

this code works fine in firefox , google chrome fails in ie "unknown error". problem happens in ajax method included in roo:

function callxhrget(contentid, ajaxurl){ var _targetnode = dojo.byid(contentid); var xhrargs = { url: ajaxurl, preventcache: true, handleas:"text", load: function(data) { dojo.html.set(_targetnode,data,{parsecontent:true}); dojo.foreach(dojo.query("script", _targetnode),function(node){ dojo.eval(node.innerhtml); }); dojo.parser.parse(_targetnode); }, error: function(error) { _targetnode.innerhtml = "an unexpected error occurred: " + error; } }; dojo.xhrget(xhrargs);

}

the dojo.eval(node.innerhtml); fails when tries process next line:

spring.adddecoration(new spring.elementdecoration({elementid : '_searchprocessingcenter_id', widgettype: 'dijit.form.filteringselect', widgetattrs : {hasdownarrow : true, required : false, invalidmessage: 'please come in valid role type' }}));

the interesting part when list empty works fine, other dijit.form.tags work fine well. advice , feedback how resolve issue?

spring dojo spring-roo

In Android----Days widget not update when System date change by user -



In Android----Days widget not update when System date change by user -

android days widget since days not alter when user alter date manually. days left automatically called when user alter date manually.

i used date picker in code.

thanks.

use this...

<receiver android:name=".widgetprovider1_1" android:label="@string/app_name" > <intent-filter> <action android:name="android.appwidget.action.appwidget_update" /> <action android:name="android.intent.action.time_set"/> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_info1_1" /> </receiver>

android android-widget datepicker

html - Apply background-image and custom bullet to css heading -



html - Apply background-image and custom bullet to css heading -

so <h1>'s should have individual custom pattern backgrounds , individual image bullets in front end of them. problem is, can't apply both style-elements background-images (i've heard can have several bg-images css3? want seek more cross-browser compatible way now.)

html:

<div id="content"> <h1>heading</h1> <p>paragraph</p> </div>

css:

#content > h1 { background: url("heading-bg.png") repeat; padding: 25px 0 25px 80px; }

now tried doing bullet image in front end of <h1> in css:

#content > h1:before {background: url("bullet1.png") no-repeat left;}

i add together div around <h1>'s , apply pattern on that, , bullet direcly on <h1>. there smarter way accomplish desired effect though?

thanks!

yes, before & after not work unless content there,

you

#content h1:before{ content:""; width:50px; height:50px; background:url('images/bullet.png'); }

html css background-image

eclipse - Section Header using Android XML? -



eclipse - Section Header using Android XML? -

enter code herelooking through android ui guidelines came across section / example:

in illustration above, there few headers called 'section' horizontal line underneath them.

im still getting grips appropriate way replicate - there specific header xml element utilize automatically style font , horizontal line? or more primitive, i.e. textview 1 pixel horizontal image (imageview?) underneath it?

possible duplicate question of one: android 4.0 sub-title (section) label styling

in short: seek adding attribute style="?android:attr/listseparatortextviewstyle" textview element, wish create that, in xml layout file.

android eclipse user-interface

Specifying index with Symfony2 for Doctrine's PersistentCollection -



Specifying index with Symfony2 for Doctrine's PersistentCollection -

can tell me how can configure symfony2/doctrine index objects within persistentcollection, specified column in entity?

for illustration assume have 2 tables; categories , products, many products 1 category. when utilize repository load category, , phone call getproducts() load products, want them returned indexed product id, or whatever column specify. they're indexed incrementally zero.

is there anyway this, or need loop through , manually set keys myself?

mapping onetomany associations allows define indexby property. annotation mappings, following

class category { // ... /** * @onetomany(targetentity="products", indexby="productid", mappedby="product") */ protected $products; // ... }

xml, yaml , php mappings allow too, , works manytomany.

symfony2 doctrine

c++ - easiest way to read a file line by line? -



c++ - easiest way to read a file line by line? -

this question has reply here:

c++: reading file line line 3 answers

i have file this

joshua 21 234 5 40.9 jones 14 403 4 39.2

now want know easiest way tell compiler read each line , print on screen? please seek reply using standard c++ libraries , not creating custom function. please no vectors. far have tried this

ifstream myfile; string line; { cout << getline(myfile,line); }while(!myfile.eof()); break;

it simple. utilize fstream open file , read line line.

here example.

#include <iostream> #include <fstream> int main() { std::ifstream file_in; file_in.open("test.txt", std::ios::in); if(file_in.fail()) { std::cout << "error: unable open test.txt.\n"; return(1); } char c; while(!file_in.fail() && !file_in.eof()) { file_in.get(c); std::cout << c; } file_in.close(); return(0); }

this uses std , allow read line line.

c++

caching - Spring Cache Configuration -



caching - Spring Cache Configuration -

this 1 seems simple question. when effort run or compile maven project in eclipse, error:

severe: servlet /articleservices threw load() exception org.xml.sax.saxparseexception; linenumber: 73; columnnumber: 32; prefix "p" attribute "p:name" associated element type "bean" not bound. @ org.apache.xerces.util.errorhandlerwrapper.createsaxparseexception(unknown source) @ org.apache.xerces.util.errorhandlerwrapper.fatalerror(unknown source) @ org.apache.xerces.impl.xmlerrorreporter.reporterror(unknown source) @ org.apache.xerces.impl.xmlerrorreporter.reporterror(unknown source)..

note truncated error message since believe root quite self-explanatory...but no matter how much around , check, doesn't seem there's wrong configuration file, follows:

<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:cache="http://www.springframework.org/schema/cache" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> <context:component-scan base-package="mylittlecacheproject" /> <mvc:resources mapping="/**" location="/" /> <!-- enables spring mvc @controller programming model --> <mvc:annotation-driven /> <!-- annotation caching --> <cache:annotation-driven /> <!-- enables aspjectj model --> <aop:aspectj-autoproxy proxy-target-class="true" /> <!-- validator --> <bean id="validator" class="org.springframework.validation.beanvalidation.localvalidatorfactorybean" /> <!-- resolve logical view names .jsp resources in /web-inf/views directory --> <bean class="org.springframework.web.servlet.view.internalresourceviewresolver"> <property name="prefix" value="/web-inf/jsp/" /> <property name="suffix" value=".jsp" /> <property name="order" value="3" /> </bean> <!-- xmlconverter injection --> <bean id="xmlconverter" class="mppiwebservices.utils.xml.xmlconverter"> <property name="marshaller" ref="castormarshaller" /> <property name="unmarshaller" ref="castormarshaller" /> </bean> <bean id="castormarshaller" class="org.springframework.oxm.castor.castormarshaller"> <property name="mappinglocation" value="classpath:rssmapping.xml" /> <property name="ignoreextraelements" value="true" /> </bean> <!-- generic cache manager --> <bean id="cachemanager" class="org.springframework.cache.support.simplecachemanager"> <property name="caches"> <set> <bean class="org.springframework.cache.concurrent.concurrentcachefactorybean" p:name="rsspassthrough" /> </set> </property> </bean> </beans>

okay i'm lazy clip out other beans used in project, question be...am specifying right schema location spring's cache? or missing here?

finally found it, in spring documentation, namespace xmlns:p="http://www.springframework.org/schema/p"

was not included in illustration configuration.

spring caching

How to Upload a blob to windows azure by splitting it into chunks and calling PutBlockList using REST and PHP -



How to Upload a blob to windows azure by splitting it into chunks and calling PutBlockList using REST and PHP -

please can post code or give reference on how can upload blob azure storage splitting chunks , calling putblocklist using rest , php. have reference same using .net code here http://wely-lau.net/2012/02/26/uploading-big-files-in-windows-azure-blob-storage-with-putlistblock/

take @ windows azure sdk php: https://github.com/windowsazure/azure-sdk-for-php this: https://github.com/windowsazure/azure-sdk-for-php/blob/master/windowsazure/blob/blobrestproxy.php. either utilize sdk or @ code understand how blob upload implemented.

rest azure windows-azure-storage

java - AsyncTask has errors - beginner -



java - AsyncTask has errors - beginner -

eventually wanting method values in text document , homecoming true of username , password nowadays there. having problems implementing asynctask. have tried follow guide @ http://developer.android.com/reference/android/os/asynctask.html have had no success.

the error getting @ homecoming type on doinbackground method "the homecoming type incompatible asynctask.doinbackground(string[])"

private class authenticateuser extends asynctask<string, integer, boolean> { string user; string pass; protected void onpreexecute(string uname, string passwd) { user = uname; pass = passwd; } protected boolean doinbackground(string... strings) { homecoming true; } protected boolean onpostexecute(boolean v) { homecoming v; } }

i know not way authenticate user @ all. trying figure out. thanks.

the problem here asynctask extensions generic , need 3 types: asynctask<params, progress, result> may void or class, not primitive info types.

so happens told compiler doinbackground returns primitive boolean expecting instance of class boolean. , "the homecoming type incompatible" error.

just alter protected boolean doinbackground(string... strings) protected boolean doinbackground(string... strings) , should fine.

java android android-asynctask

sql - Re-order columns of table in Oracle -



sql - Re-order columns of table in Oracle -

i have table 50+ columns , need swap order of first 2 columns. best way accomplish using oracle? assume table name orderdetails , is, first 2 columns item_id , order_id. 1 time rename complete, table name should still orderdetails first 2 columns order_id , item_id. fwiw, column types , rest of columns , order irelevent.

correct me if i'm wrong, think general steps are:

rename existing table. drop primary key constraint. re-create table right column order. list item run insert .. select move info temp table in step #3. drop temp table.

i have little experience oracle perhaps i'm missing step or two.

does primary key imply index in oracle? dropping primary key drop index?

sql examples much appreciated.

edit: un-sincere question why needs done instead of providing help. reply question why needs done: i'm next orders else says need way , order of columns matter. thoughts/opinions on irrelevent.

look @ bundle dbms_redefinition. rebuild table new ordering. can done table online.

as phil brownish noted, think before doing this. there overhead in scanning row columns , moving info on update. column ordering rules utilize (in no particular order):

group related columns together. not null columns before null-able columns. frequently searched un-indexed columns first. rarely filled null-able columns last. static columns first. updateable varchar columns later. indexed columns after other searchable columns.

these rules conflict , have not been tested performance on latest release. have been tested in practice, didn't document results. placement options target 1 of 3 conflicting goals: easy understand column placement; fast info retrieval; , minimal info motion on updates.

sql oracle rename

javascript - Knockout.js 2.2.1 can't find observable array -



javascript - Knockout.js 2.2.1 can't find observable array -

not sure what's going wrong here, knockoutjs having issues finding observable array that's within masterviewmodel. using 2.2.1 jquery 1.8.x not first kjs app. here is:

initialize

$(function() { window.vm = new masterviewmodel(); ko.applybindings(vm); });

viewmodel

function masterviewmodel(data) { var self = this; self.currentappview = ko.observable(); // users self.userlist = ko.observablearray([]); self.templatelistgetter = ko.computed(function() { $.getjson("/user/list"), function(data) { var mapped = $.map(data, function(item) { homecoming new usermodel(item) }); self.userlist(mapped); }; }); self.gotoappview = function(appview) { location.hash = '!/' + appview; }; sammy(function() { this.get('#!/:appview', function() { self.currentappview(this.params.appview); $('.appview').hide(); ko.applybindings(new window[this.params.appview+'vm']()); }); this.notfound = function(){ location.hash = "!/dashboard"; } //this.raise_errors = true; }).run(); }

the view

<table class="table table-bordered table-striped"> <tbody data-bind="foreach: userlist"> <tr> <td data-bind="text: guid"></td> <td data-bind="text: firstname"></td> <td data-bind="text: lastname"></td> <td data-bind="text: email"></td> <td data-bind="text: updated"></td> <td data-bind="text: suspended"></td> </tr> </tbody> </table>

i have simple table loading

even after double-checking couple things adding defer="defer" js tag , ensuring userlist exists, cannot find observablearray. gives error:

message: referenceerror: userlist not defined; bindings value: foreach: userlist error {}

anyone have thought what's going on?

update

for wondering gets called every time hash changes:

function usersvm() { // info var self = this; // behaviours $('#users').show(); }

it looks you're initializing knockout undefined viewmodel?

ko.applybindings(new window[this.params.appview+'vm']());, yet actual viewmodel window.vm. case sensitivity ftw. also, viewmodel on window created / initialized. don't need new operator.

so, alter applybindings line be

ko.applybindings(window[this.params.appview+'vm']());

updated answer: poster

there no necessity maintain running ko.applybindings every time route changed since applying bindings on page load. sammy.js changed to:

sammy(function() { this.get('#!/:appview', function() { self.currentappview(this.params.appview); $('.appview').hide(); window[this.params.appview+'route'](); }); this.notfound = function(){ location.hash = "!/dashboard"; } //this.raise_errors = true; }).run();

it ko.computed or regular function phone call window.vm.getuserlist() isn't running properly, saved different question.

function usersroute() { // info var self = this; // behaviours $('#users').show(); window.vm.getuserlist(); }

javascript mvvm knockout.js knockout-2.0

regex - jQuery Validate method checking for special characters -



regex - jQuery Validate method checking for special characters -

i trying (and failing) write regular look statement checks special characters such !@#$%^&*()_+<>?'"{}[] in javascript form validation.

i understand has been asked 1000 times i'm under serious time pressure. if rather not reply question below , able point me in direction of previous reply above question appreciate it.

on similar note, can tell me why next shooting error when come in lowercase 'abc', etc? i'm baffled.

jquery.validator.addmethod("specialchars", function( value, element ) { var regex = new regexp("^[a-za-z0-9]+$"); var key = string.fromcharcode(event.charcode ? event.which : event.charcode); if (!regex.test(key)) { event.preventdefault(); homecoming false; } }, "please utilize alphanumeric or alphabetic characters");

thanks help.

cheers, tim

instead of writing own custom method scratch, include additional-methods.js file , utilize alphanumeric rule.

$(document).ready(function () { $('#myform').validate({ rules: { field: { alphanumeric: true } } }); });

demo: http://jsfiddle.net/ysakx/

if don't want include additional external file, re-create default alphanumeric method out of it...

jquery.validator.addmethod("alphanumeric", function(value, element) { homecoming this.optional(element) || /^\w+$/i.test(value); }, "letters, numbers, , underscores please");

jquery regex jquery-validate

How should I structure my WordPress categories/tags for SEO? -



How should I structure my WordPress categories/tags for SEO? -

i have trance music website located @ http://trancefanatic.com. there 2 categories: trance djs , trance vocalists. underneath each of corresponding names. tags, i've been using things "lyrics", "music video", etc. however, noticed i've been using artists' names tags, in add-on having them sub-categories.

i've read bad seo. i'm not sure best way re-structure categories/tags, without losing traffic. website provides trance/vocal trance music, lyrics.

any suggestions awesome. thanks!

first of all, install seo plugin wordpress wordpress seo yoast (the best in opinion).

secondly, should take noindex, follow tags or categories (as wish) take 1 avoid duplicate content bad seo.

you don't need re-structure website process.

wordpress seo

Show data(numbers) instead of pins on google map -



Show data(numbers) instead of pins on google map -

i want show info (numbers) database on map, instead of pointing place , clicking on pin show data, want shown pin is. utilize illustration create google map pins: http://tips4php.net/2010/10/use-php-mysql-and-google-map-api-v3-for-displaying-data-on-map/

i cannot show images because i'm new user, here illustration of want show on map, info prices instead of usual pins: http://www.norc-imobiliare.ro

you may utilize dynamic icons of image charts -api. api deprecated, may(but must not) stop working in 2015.

the other options:

create own serverside script takes strings(prices) argument , delivers desired image based on input. create overlay instead of marker, may contain html. e.g. infobox usable.

google-maps

jquery - Hide a div near the button when button gets clicked -



jquery - Hide a div near the button when button gets clicked -

ok, have div 100% height , 100% width , have button centered div. when user clicks button. want div collapse near button , hide. here code. , can see on js fiddle

http://jsfiddle.net/zxb4z/

$('button').click(function(){ $("div").animate({ left:'24%', top:'48%', opacity:'0', height:'0px', width:'0px' },'slow');});

use margin instead of position properties (top/left):

$('button').click(function(){ $("div").animate({ marginleft:'24%', margintop:'48%', opacity:'0', height:'0px', width:'0px' },'slow'); });

or apply position absolute on div:

div { position: absolute }

jquery html css css3

Read list of numbers in txt file and store to array in C -



Read list of numbers in txt file and store to array in C -

i have list of integers, 1 number per line , store each of these numbers in integer array utilize later in program.

for illustration in java this:

filereader file = new filereader("integers.txt"); int[] integers = new int [100]; int i=0; while(input.hasnext()) { integers[i] = input.nextint(); i++; } input.close();

how done in c?

give go. you'll much improve off if read man pages each of these functions (fopen(), scanf(), fclose()) , how allocate arrays in c. should add together error checking this. example, happens if integers.txt not exist or don't have permissions read it? if text file contains more 100 numbers?

file *file = fopen("integers.txt", "r"); int integers[100]; int i=0; int num; while(fscanf(file, "%d", &num) > 0) { integers[i] = num; i++; } fclose(file);

c arrays

ios - function does not work until I click on the screen during run time -



ios - function does not work until I click on the screen during run time -

i want show animated image 1 time view loaded few seconds hide , view 2 other images, have used array animate image set timer phone call function ontimer repeatedly ,inside function check if image animated once, if stop timer , view 2 other images

it works fine when run project except 2 images not appear until click on screen!

her code:

- (void)viewdidload { [super viewdidload]; // additional setup after loading view. outline.animationimages = [nsarray arraywithobjects: [uiimage imagenamed:@"traffic.png"], [uiimage imagenamed:@"red.png"], [uiimage imagenamed:@"yellow.png"], [uiimage imagenamed:@"green.png"], nil]; [outline setanimationrepeatcount:1]; outline.animationduration = 4; [outline startanimating]; timer = [nstimer scheduledtimerwithtimeinterval: 1.0/30.0 target:self selector:@selector(ontimer) userinfo:nil repeats:yes]; } -(void) ontimer { if (![outline isanimating] == true){ // if animation has been played once, nslog(@"animation stopped, something"); rannan.image = [uiimage imagenamed:@"rannan.png"]; outline.image = [uiimage imagenamed: @"outline.png"]; [ timer invalidate]; // } }

it looks reason isanimating not set true until click on screen when project running

hope find reply 1 :)

i wonder why fire timer every 1/30 of second. set animation 4 seconds can fire timer after 4 seconds.

a way check if view no longer animating:

calayer *presentationlayer = (calayer*)outline.layer.presentationlayer; if(![presentationlayer animationkeys]) { nslog(@"animation stopped, something"); }

ios xcode ipad nstimer

javascript - Go back or redirect to url -



javascript - Go back or redirect to url -

i've been using button users navigate page came from, problem is, if user navigates there in new tab or direct link, haven't "been anywhere" before redirected blank page.

is there solution this? i'm thinking navigate if possible, , if not it'll take specific url.

this have far:

<a href="#" onclick="history.go(-1);return false;">go back</a>

how using document.referrer? it's hack , not recommend since you'll not maintaining post info (if any). if page doesn't need repost data, should work.

class="lang-html prettyprint-override"><a id="mylink" href="#">go back</a> class="lang-js prettyprint-override">$('#mylink').click(function () { if (history.length == 0) { document.location = document.referrer; } else { history.go(-1); } });

i must agree schautdollar's comment - message far improve warning.

javascript jquery html

google bigquery - "Exception in thread "main" java.net.ConnectException: Connection refused: connect" after entering OAuth code provided by the url -



google bigquery - "Exception in thread "main" java.net.ConnectException: Connection refused: connect" after entering OAuth code provided by the url -

i new bigquery, want utilize bigquery through java class. have got url authorize bigquery access , have got permission code url, when utilize permission code in code next error.

paste url web browser authorize bigquery access: https://accounts.google.com/o/oauth2/auth?client_id=488768089408.apps.googleusercontent.com&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&scope=https://www.googleapis.com/auth/bigquery&state ... , type code received here: 4/-p5sevjsfx8hcztka_spjdqcp6xh.ovcnnapn5t4sol05ti8zt3a9jbs6eqi exception in thread "main" java.net.connectexception: connection refused: connect @ java.net.plainsocketimpl.socketconnect(native method) @ java.net.plainsocketimpl.doconnect(plainsocketimpl.java:333) @ java.net.plainsocketimpl.connecttoaddress(plainsocketimpl.java:195) @ java.net.plainsocketimpl.connect(plainsocketimpl.java:182) @ java.net.socket.connect(socket.java:519) @ sun.net.networkclient.doconnect(networkclient.java:152) @ sun.net.www.http.httpclient.openserver(httpclient.java:388) @ sun.net.www.http.httpclient.openserver(httpclient.java:500) @ sun.net.www.protocol.https.httpsclient.(httpsclient.java:271) @ sun.net.www.protocol.https.httpsclient.new(httpsclient.java:328) @ sun.net.www.protocol.https.abstractdelegatehttpsurlconnection.getnewhttpclient(abstractdelegatehttpsurlconnection.java:176) @ sun.net.www.protocol.http.httpurlconnection.plainconnect(httpurlconnection.java:733) @ sun.net.www.protocol.https.abstractdelegatehttpsurlconnection.connect(abstractdelegatehttpsurlconnection.java:162) @ sun.net.www.protocol.http.httpurlconnection.getoutputstream(httpurlconnection.java:836) @ sun.net.www.protocol.https.httpsurlconnectionimpl.getoutputstream(httpsurlconnectionimpl.java:230) @ com.google.api.client.http.javanet.nethttprequest.execute(nethttprequest.java:84) @ com.google.api.client.http.httprequest.execute(httprequest.java:980) @ com.google.api.client.auth.oauth2.tokenrequest.executeunparsed(tokenrequest.java:299) @ com.google.api.client.googleapis.auth.oauth2.googleauthorizationcodetokenrequest.execute(googleauthorizationcodetokenrequest.java:175) @ com.ymsli.client.bigqueryjavagettingstarted.exchangecode(bigqueryjavagettingstarted.java:250) @ com.ymsli.client.bigqueryjavagettingstarted.createauthorizedclient(bigqueryjavagettingstarted.java:110) @ com.ymsli.client.bigqueryjavagettingstarted.main(bigqueryjavagettingstarted.java:68)

please help me out.

thanks in advance shri kant

this looks lot potential firewall issue. application running? have access network , https (port 443)?

google-bigquery

python - How to check collision between the mouse and a sprite group -



python - How to check collision between the mouse and a sprite group -

i'm trying observe collision between mouse , sprite group. have searched around awhile couldn't find it. if know how please explain how such thing done? if appreciate it. i'm not sure parts of code need show if need please tell me part of need , post it.

if using pygame, easiest way create sprite not have image, , position alter mouse. access mouse coordinates utilize :

pygame.mouse.get_pos(): homecoming (x, y)

then can utilize existing collision detection new sprite.

python mouse pygame collision

java - Database Benchmark : Weird results when testing concurrency (ExecutorService) -



java - Database Benchmark : Weird results when testing concurrency (ExecutorService) -

i developing java benchmark evaluate usecases (inserts, updates, deletes, etc.) apache derby database.

my implementation next :

after having warmed jvm, execute serie (for loop : (100k 1m iterations)) of, let's say, Ìnsert in (single table @ moment) of database. apache derby, knows, test every mode (in memory/embedded, in memory/network, persistent/embedded, persistent/network)

the execution of process may singlethreaded, or multithreaded (using executors.newfixedthreadpool(poolsize)

well, here goes problem :

when execute benchmark 1 thread, have pretty realistics results

in memory/embedded[simple integer insert] : 35k inserts/second (1 thread)

then, decide execute 1 , 2 (concurrent) threads sequentially.

now, have next results :

in memory/embedded[simple integer insert] : 21k inserts/second (1 thread) in memory/embedded[simple integer insert] : 20k inserts/second (2 thread)

why results 1 thread alter much ?

basically, start , end timer before , after loop :

// processing long start = system.nanotime(); (int = 0; < loopsize; i++) { process(); } // end timer long abstime = system.nanotime() - start; double abstimemilli = abstime * 1e-6;

and process() method :

private void process() throws sqlexception { preparedstatement ps = clientconn.preparestatement(query); ps.setobject(1, val); ps.execute(); clientconn.commit(); ps.close(); }

as executions processed sequantially, reste of code (data handling) should not alter benchmark ?

the results go worse number of sequential threads grows (1, 2, 4, 8 example).

i sorry in advance if confusing. if needed, i'll provide more info or re-explain it!

thank you help :)

edit :

here method (from usecase class) calling aforementionned execution :

@override public arraylist<contextbean> bench(int loopsize, int poolsize) throws interruptedexception, executionexception { future<contextbean> t = null; arraylist<contextbean> cbl = new arraylist<contextbean>(); seek { executorservice es = executors.newfixedthreadpool(poolsize); (int = 0; < poolsize; i++) { benchexecutor = new benchexecutor(eds, insertstatement, loopsize, poolsize, "test-varchar"); t = es.submit(be); cbl.add(t.get()); } es.shutdown(); es.awaittermination(long.max_value,timeunit.milliseconds); } grab (interruptedexception e) { e.printstacktrace(); } grab (sqlexception e) { e.printstacktrace(); } homecoming cbl; }

on simple operations, every database behaves described.

the reason threads spawning seek operate on same table (or set of tables), database must serialize access.

in situation every thread works little slower, overall result (small) gain. (21k+20k=41k against 35k of single threaded version).

the gain decreases (usually exponentially) number of threads, , may experience loss, due lock escalation (see http://dba.stackexchange.com/questions/12864/what-is-lock-escalation).

generally, multithread solution gains when performance not bound single resource, multiple factors (i.e calculations, selects on multiple tables, inserts on different tables).

java concurrency benchmarking derby

jquery - $.ajax().fail() -



jquery - $.ajax().fail() -

i know kind of reasons can fail $.ajax() request? haven't had chance see any, because code's worked far, need know them. allow me tell why! assume $.ajax request fails reason. jquery gives me chance in case .fail() .can seek repeat/resend request within .fail() ? reason failed request, occur again? if does, occur each time resend request , crunch application/code?

jquery

sql - Pass conditions to subqueries - rails activerecords -



sql - Pass conditions to subqueries - rails activerecords -

i have questioncategory model hasmany question.

when query @quizzs = questionscategory.find(:all) ok. it's querying catégories , associated questions:

questionscategory load (0.2ms) select `questions_categories`.* `questions_categories` question load (0.3ms) select `questions`.* `questions` `questions`.`questions_category_id` = 1 question load (0.4ms) select `questions`.* `questions` `questions`.`questions_category_id` = 2 question load (0.3ms) select `questions`.* `questions` `questions`.`questions_category_id` = 3

but, i'd pass status questions subqueries. @quizzs = questionscategory.find(:all, :questions => [ :conditions => {my conditions} ])

and subqueries looking this:

select questions.* questions questions.questions_category_id = 2 and conditions

possible? cheers mates

to result sql ( select questions.* questions questions.questions_category_id = 2 , conditions) can follows:

quetionscategory.find(2).questions.all(:conditions => [your conditions])

sql ruby-on-rails rails-activerecord

ruby on rails - Gems suddenly missing -



ruby on rails - Gems suddenly missing -

i'm learning how utilize ruby on rails , fine. today, tried utilize command rails new foo or rails -v gave me this:

c:\users\me\ruby>rails new demo_app c:/program files (x86)/ruby-1.9.2/lib/ruby/site_ruby/1.9.1/rubygems.rb:926:in `r eport_activate_error': not find rubygem railties (>= 0) (gem::loaderror) c:/program files (x86)/ruby-1.9.2/lib/ruby/site_ruby/1.9.1/rubygems .rb:244:in `activate_dep' c:/program files (x86)/ruby-1.9.2/lib/ruby/site_ruby/1.9.1/rubygems

.rb:236:in activate' c:/program files (x86)/ruby-1.9.2/lib/ruby/site_ruby/1.9.1/rubygems .rb:1307:ingem' c:/ruby193/bin/rails:22:in `'

so... whats going wrong?

gem list rails gave me this:

c:\users\me\ruby>gem list rails *** local gems ***

i'm using windows 7 , have no rvm or pik, worked fine lastly 5 days.

okay, tried install rails new 'gem install rails' , said this:

c:\users\me\ruby>gem install rails fetching: i18n-0.6.1.gem (100%) fetching: multi_json-1.5.0.gem (100%) fetching: activesupport-3.2.11.gem (100%) fetching: builder-3.0.4.gem (100%) fetching: activemodel-3.2.11.gem (100%) fetching: rack-1.4.5.gem (100%) fetching: rack-cache-1.2.gem (100%) fetching: rack-test-0.6.2.gem (100%) fetching: journey-1.0.4.gem (100%) fetching: hike-1.2.1.gem (100%) fetching: tilt-1.3.3.gem (100%) fetching: sprockets-2.2.2.gem (100%) fetching: erubis-2.7.0.gem (100%) fetching: actionpack-3.2.11.gem (100%) fetching: arel-3.0.2.gem (100%) fetching: tzinfo-0.3.35.gem (100%) fetching: activerecord-3.2.11.gem (100%) fetching: activeresource-3.2.11.gem (100%) fetching: polyglot-0.3.3.gem (100%) fetching: treetop-1.4.12.gem (100%) fetching: mail-2.4.4.gem (100%) fetching: actionmailer-3.2.11.gem (100%) fetching: rack-ssl-1.3.3.gem (100%) fetching: json-1.7.6.gem (100%) error: error installing rails: 'json' native gem requires installed build tools. please update path include build tools or download devkit 'http://rubyinstaller.org/downloads' , follow instructions @ 'http://github.com/oneclick/rubyinstaller/wiki/development-kit'

well... installed devkit 5 days ago, did again, time starting command line admin.

then 'tried' install json:

c:\users\me\devkit>gem install json temporarily enhancing path include devkit... building native extensions. take while... error: error installing json: error: failed build gem native extension. "c:/program files (x86)/ruby-1.9.2/bin/ruby.exe" extconf.rb creating makefile create makefile:160: warning: overriding commands target `c:/program' makefile:153: warning: ignoring old commands target `c:/program' makefile:160: warning: overriding commands target `files' makefile:153: warning: ignoring old commands target `files' c:/program files (x86)/ruby-1.9.2/bin/ruby -e "puts 'exports', 'init_generator'" > generator-i386-mingw32.def /bin/sh: -c: line 0: syntax error near unexpected token `(' /bin/sh: -c: line 0: `c:/program files (x86)/ruby-1.9.2/bin/ruby -e "puts 'expor ts', 'init_generator'" > generator-i386-mingw32.def' make: *** [generator-i386-mingw32.def] error 2 gem files remain installed in c:/program files (x86)/ruby-1.9.2/lib/ruby/ge ms/1.9.1/gems/json-1.7.6 inspection. results logged c:/program files (x86)/ruby-1.9.2/lib/ruby/gems/1.9.1/gems/jso n-1.7.6/ext/json/ext/generator/gem_make.out

and got this-.-

im beginner in this, dont know else try.

you messed ruby/rails installation @ point.

i highly recommend using railsinstaller takes care of installing ruby, rails , gotchas (devkit etc) you, in 1 click.

of course of study should uninstall first.

ruby-on-rails windows heroku

reading in missing data c# input string was not in a correct format -



reading in missing data c# input string was not in a correct format -

i new c#. have been trying read in dataset missing data. after reading in headers, read in rest of file using:

list<int> idlist = new list<int>(); list<int[]> vallist = new list<int[]>(); string line = sr.readline(); while (line != null) { string[] lineparts = line.split(delimiters); int id = convert.toint32(lineparts[0]); idlist.add(id); int[] vals = new int[numtests]; (int = 0; < numtests; i++) { vals[i] = convert.toint32(lineparts[i + 1]); } vallist.add(vals); line = sr.readline(); } childids = idlist.toarray(); int[][] values = vallist.toarray();

when run this, error message "input string not in right format." can't quite figure out how read in missing data. suggestions? thanks

"input string not in right format" means you're trying parse int nonsense string.

for example:

convert.toint32("the letter q"); // throw exception.

c# string input missing-data

internet explorer 9 - JQuery .is(':hover') not working correctly in IE9 -



internet explorer 9 - JQuery .is(':hover') not working correctly in IE9 -

i having problem popup div in ie9 next code:

<li id="info001" class="listinfo" onmouseover="showpreview(this);" onmouseout="hidepreview();">

and hidepreview checks create sure mouse isn't on listitem or preview itself, this:

function hidepreview() { if (!($('#thepreview').is(':hover') || $('#info001').is(':hover'))) { $('#thepreview').hide(); } }

this works fine in chrome , firefox, in ie9 preview starts flickering move on both listitem , preview, , move on preview alone, gets hidden.

is there way avoid this?

edit: clarity, thepreview div overlaps info001 li plenty move mouse between them.

edit: http://jsfiddle.net/controlfreak/qqsgs/

try doing instead:

var $thepreview = $("#thepreview"); $(".listinfo").hover( function () { $thepreview.show(); }, function () { $thepreview.hide(); } );

working illustration on jsfiddle.

you can still utilize code, need alter pseudo-event hover mouseenter mouseleave (if you're running 1.9+). see more info: jquery.com/upgrade-guide/1.9/#hover-pseudo-event

jquery internet-explorer-9 hover onmouseout

How does AngularJS recognize a function as controller directive -



How does AngularJS recognize a function as controller directive -

i looking @ angular api reference. says ngcontroller directive, , give next example:

function settingscontroller($scope) { $scope.name = "john smith"; }

this looks plain javascript function, argument $scope passed in. thought define directives, need call:

app.directive("name", func())

does angular treats function $scope argument controller directive? or if modify dom element include ng-controller = "settingscontroller" settingscontroller interpreted such?

ngcontroller directive (directives referred in dom--angular allows specify directives via tag names, attributes, class names , comments). ngcontroller directive written create controller instance based on name passed in directive (in case string "settingscontroller". function not directive.

angularjs angularjs-directive

c++ - Execute a code when a callback disconnect from boost::signals2::signal -



c++ - Execute a code when a callback disconnect from boost::signals2::signal -

short: there way execute code when callback connected using connect disconnected?

long: have class multiple callbacks expensive , want generate callbacks interested user:

boost::signals2::connection bind_to_signal(signal_code code, signal_signature const& fn) { start_callback(code); homecoming signal_[code].connect(fn); }

now want execute stop_callback when callbacks bound signal disconnected.

c++ boost signals2

Linking MATLAB to a DLL library -



Linking MATLAB to a DLL library -

i trying execute illustration code matlab toolkit, 'oscmex'. toolkit allows communication using osc protocol on matlab. presume question non-specific; should apply any toolkit set-up in manner 1 is.

reasons aside, i'm having simple problem getting toolkit , running. toolkit comes no documentation whatsoever; set of 6 dll files (in 1 directory), , set of 4 matlab '.m' illustration code files (in directory). every toolkit i've used in past has either been built-in kit or has had intuitive (semi-automated) install procedure.

after downloading toolkit, first thing tried run 1 of '.m' illustration codes. failed first line of code contained function osc(), not (currently) recognised matlab.

so, figured maybe need move '.m' files same folder dlls; perhaps matlab see functions within dlls. no dice.

so, realise have somehow link matlab dlls on startup. tried adding dlls folder , adding entry in 'pathdef.m' file. failed.

i've read somewhere can load dll file using loadlibrary() function. so, tried doing dll files. failed on first file:

>> loadlibrary('osc_free_address.dll') error using loadlibrary>lfullpath (line 587) not find file osc_free_address.h.

i'm starting run out of options... how can set of dlls , running?

browsing library's web page seems these dlls old form of mex files. therefore, should not used in context of shared library (e.g., using loadlibrary , calllib), rather compiled straight mex files.

to so, suggest next steps:

make sure have working mex compiler configured matlab. in matlab, type:

>> mex -setup

this guide through configuration process. understand working on windows machine, work visual studio compiler - works best me.

this library's readme file suggests osc

requires liblo 0.22 or later. see http://plugin.org.uk/liblo/

make sure have library , located in ld_library_path (see e.g., this question details, or mex docs).

get source code osc library their repository.

compile sources in matlab using

>> mex -o -largearraydims osc_free_address.c >> mex -o -largearraydims osc_free_server.c

and on 7 c source files. after mex-ing c files you'll have mex files can run matlab if regular functions. may find useful utilize library's create file, suggested andrew mao.

good luck,

matlab dll

java - Heap error when using custom RecordReader with large file -



java - Heap error when using custom RecordReader with large file -

i've written custom file reader not split input files big gzipped files , want first mapper job gunzip them. followed illustration in 'hadoop definitive guide' heap error when trying read in byteswritable. believe because byte array of size 85713669, i'm not sure how overcome issue.

here code:

public class wholefilerecordreader extends recordreader<nullwritable, byteswritable> { private filesplit filesplit; private configuration conf; private byteswritable value = new byteswritable(); private boolean processed = false; @override public void close() throws ioexception { // nil } @override public nullwritable getcurrentkey() throws ioexception, interruptedexception { homecoming nullwritable.get(); } @override public byteswritable getcurrentvalue() throws ioexception, interruptedexception { homecoming value; } @override public float getprogress() throws ioexception, interruptedexception { homecoming processed ? 1.0f : 0.0f; } @override public void initialize(inputsplit split, taskattemptcontext context) throws ioexception, interruptedexception { this.filesplit = (filesplit) split; this.conf = context.getconfiguration(); } @override public boolean nextkeyvalue() throws ioexception, interruptedexception { if (!processed) { byte[] contents = new byte[(int) filesplit.getlength()]; path file = filesplit.getpath(); filesystem fs = file.getfilesystem(conf); fsdatainputstream in = null; seek { in = fs.open(file); ioutils.readfully(in, contents, 0, contents.length); value.set(contents, 0, contents.length); } { ioutils.closestream(in); } processed = true; homecoming true; } homecoming false; }

}

in general can not load whole file memory of java vm. should find streaming solution process big files - read info chunk chunk , save results w/o fixing in memory whole info set specific task - unzip not suited mr since there no logical partition of info records. please note hadoop handling gzip automatically - input stream decompressed.

java hadoop heap

r - qplot dynamic plotting -



r - qplot dynamic plotting -

i create dynamic plotting on given dates, ie want plots appear 1 after through specific dates when code run. code seems work plot function not qplot.

any ideas?

thanks in advance,

x headings t, date, aum, profit

windows(5,5) dev.set() (i in 1:10){ z <- x[x$t == i,] <- unique(z$date) qplot(z$aum,z$profit,main=a,xlim=range(0:2.5e+08),ylim=range(0:6e+06)) }

you need add together print() call, i.e. print(qplot(...)).

the reason ggplot2 uses grid graphics requires print call.

print(qplot(z$aum,z$profit,main=a,xlim=range(0:2.5e+08),ylim=range(0:6e+06)))

this r faq 7.16.

r dynamic ggplot2

vba - Offset Until An Empty CellIs Found -



vba - Offset Until An Empty CellIs Found -

i have column consisting of various names. trying figure out how re-create selected item first empty cell in column f. i've done far:

sub copyfill() if range("f3") = empty activecell.copy range("f3") elseif range("f3") <> empty activecell.copy range("f3").offset(1, 0) end if end sub

but thing can't understand how apply dountil function here in order maintain offsetting until find empty cell excel populate current selection.

thank much in advance time , attention.

p.s. using f3 because column starts me in file.

the efficient way accomplish want next line of code:

activecell.copy range("f:f").find(what:="", after:=range("f3"), lookin:=xlformulas, lookat _ :=xlpart, searchorder:=xlbyrows, searchdirection:=xlnext, matchcase:= _ false, searchformat:=false)

the .find need.

if want loop manually (which much slower), can utilize code:

sub copyfill() dim rng range set rng = range("f3") while rng.value "" set rng = rng.offset(1) wend activecell.copy rng end sub

instead of while status ... wend can utilize do while status ... loop or do until not status ... loop.

vba

salesforce - First Box.com integration. How do I query for a list of folders? -



salesforce - First Box.com integration. How do I query for a list of folders? -

i have oauth stuff working expected. no challenges there. need utilize access token something. nil have tried works. i'm sure it's simple, not sure how translate examples in curl http post/get requests.

box.com help says: curl https://api.box.com/2.0/folders/folder_id \ -h "authorization: bearer your_access_token"

how write using http post/get?

as long requests beingness sent via standard http functionality don't believe platform matters. regardless, i'm using apex write in salesforce.com.

note: know there app on appexchange integrate box.com , salesforce. purposes don't want rely on apps unique specific platform.

any help appreciated.

it's request headers , optionally xml / json post payload, not sure what's specific problem? have tried writing code?

simple example: http://www.salesforce.com/us/developer/docs/api_asynch/content/asynch_api_quickstart_login.htm

bit more advanced: http://developer.force.com/cookbook/recipe/scheduling-an-apex-call-from-the-command-line

curl powerful tool , list of it's commandline options not faint of heart. still - utilize reference, "-h" meaning http header. think "\" indicating it's multiline command, can ignore it.

salesforce integration

meteor - Make a http get request to rest api and convert to a collection -



meteor - Make a http get request to rest api and convert to a collection -

is possible create meteor.http.get("localhost:4000/api/resource.json") , utilize returned response meteor.collection?

sure. let's json looks like:

{ 'results': [ { 'name': 'bob', 'eyes': 'brown' }, { 'name': 'sue', 'eyes': 'blue' } ] }

to insert collection do:

meteor.http.get("localhost:4000/api/resource.json", function(error, result) { if (result.statuscode === 200) { (var = 0; < result.data.results.length; i++) { mycollection.insert(result.data.results[i]) } } else { console.log(result); } }

meteor

iphone - ASIHTTPRequest convert response data to NSArray -



iphone - ASIHTTPRequest convert response data to NSArray -

i using asihttprequest json response server. , want convert response nsarray. code:

nsurl *url = [nsurl urlwithstring:@"http://chirkov.net.ua/iosnettest/request.php?act=showdata&query=2;0;3;0;asc"]; asihttprequest *request = [asihttprequest requestwithurl:url]; [request startsynchronous]; nserror *error = [request error]; if (!error) { nsdata *responsedata = [[nsmutabledata alloc] initwithdata:[request responsedata]]; nsarray *array = [nskeyedunarchiver unarchiveobjectwithdata:responsedata]; nslog(@"array = %@",array); }

but got exception terminating app due uncaught exception 'nsinvalidargumentexception', reason: '*** -[nskeyedunarchiver initforreadingwithdata:]: incomprehensible archive (0xffffffef, 0xffffffbb, 0xffffffbf, 0x5b, 0x7b, 0x22, 0x69, 0x64. how can solve problem?

you getting json info have convert info using nsjsonserialization. have @ class reference.

http://developer.apple.com/library/ios/#documentation/foundation/reference/nsjsonserialization_class/reference/reference.html

also check working json

iphone ios objective-c asihttprequest nskeyedarchiver

wireshark - How to read SSL/TLS Encrypted Alert code under Ephemeral RSA -



wireshark - How to read SSL/TLS Encrypted Alert code under Ephemeral RSA -

i trying debug ssl encrypted alerts on web server. not sure problem , things appear working, seeing many tlsv1 encrypted alerts in wireshark sense should not there.

the tlsv1 alert protocol (http://en.wikipedia.org/wiki/transport_layer_security#alert_protocol) provides error codes indicating wrong, unfortunately code encrypted.

wireshark allows ssl decrypted providing private key (which have) in ssl preferences page. not work me due session beingness setup ephemeral rsa (sharkfest'09 http://sharkfest.wireshark.org/sharkfest.12/presentations/mb-1_ssl_troubleshooting_with%20_wireshark_software.pdf page 59).

i want know how can read alert code. of next me there: a) have wireshark decrypt ssl using ephemeral rsa b) avoid using ephemeral rsa wireshark can decrypt c) forcefulness ssl utilize null encryption can read code debug it

b) avoid using ephemeral rsa wireshark can decrypt

if web server apache, seek following:

httpd.conf sslprotocol +all -sslv2 -sslv3 sslciphersuite -keecdh:-kedh:+krsa:+high:+medium:-low:-exp

c) forcefulness ssl utilize null encryption can read code debug it

this might little trickier, seek moving enull front end of list. enull rejected client, worth try. suspect rejected because client won't allow cipher (or anull, matter).

if client have enull, still might not used. server honors client's ciphers, unless client requests enull, have find override on server configuration.

ssl wireshark

pagination - Laravel - Paginating Eloquent Retrieved results -



pagination - Laravel - Paginating Eloquent Retrieved results -

this have in controller

$projects=project::where_sup_id($user_id)->get(); $total=count($projects); $per_page=3; $projects = paginator::make($projects, $total, $per_page); homecoming view::make('project.index')->with('projects',$projects);

and in view

@foreach ($projects->results $project) {{$project->title}} @endforeach {{$projects->links();}}

but when view in browser displaying rows in pages...the links displaying perfectly! u think problem? please help! give thanks u in advance!

you counting rows, not using limit @ all, laravel fluent query builder has skip() , take() method that.

btw, don't need manually paginate it. laravel pagination automatically paginate() method.

do way:

$projects = project::where_sup_id($user_id)->paginate(3); // 3 means records per page homecoming view::make('project.index')->with('projects', $projects);

you doing view work correctly.

pagination laravel eloquent

Haskell: Non-exhaustive patterns in function (simple functions) -



Haskell: Non-exhaustive patterns in function (simple functions) -

i confused why 1st , 3rd versions of functions give error whereas sec definition works fine.

-- head , tail 3rd :: [a] -> 3rd [a] = head (tail (tail[a])) -- pattern matching third2 :: [a] -> third2 (_:_:x:_) = x -- list indexing third3 :: [a] -> third3 [a] = [a]!!2

thanks in advance

that odd sec 1 not complain non-exhaustive patterns, since third2 not match lists of length zero, one, or two. third , third3 functions complain because [a] not variable, pattern. [a] desugars (a:[]), have written them as

third (a:[]) = head (tail (a:[])) third3 (a:[]) = (a:[]) !! 2

neither of work, single element lists. suspect want is

third = head (tail a) third3 = !! 2

haskell non-exhaustive-patterns

iphone - Is there a way to use `someButton.enabled = NO;` without dimming the custom image UIButton? -



iphone - Is there a way to use `someButton.enabled = NO;` without dimming the custom image UIButton? -

is there way utilize somebutton.enabled = no; without dimming custom image of uibutton?

i alter images without ios enabled=no effect.

it's matter of setting image of disabled button equal image when button enabled:

uiimage* image=[button imageforstate: uicontrolstatenormal]; [button setimage: image forstate: uicontrolstatedisabled];

iphone ios objective-c uibutton

javascript - jQuery Masonry - I want the div to scroll, not the page -



javascript - jQuery Masonry - I want the div to scroll, not the page -

let me describe i'm trying achieve. on left side of browser have types of check boxes , radio buttons used filter data. on right side i'm displaying info using jquery masonry. when info set big have scroll downwards on page. want specify height on div , scroll downwards on users can see filter choices @ times. has done masonry? i've "googled" on several different occasions , can't seem find has done this.

i cannot explain why worked, worked purely own purposes.

<style type="text/css"> #results {overflow: auto;} </style> <script type="text/javascript"> $(function () { $("#results").masonry({ itemselector : '.item', isfitwidth: true, isanimated: true }).css("height", "450px"); </script>

i haven't looked @ in chrome yet i'll testing more thoroughly before rolling out.

javascript jquery jquery-plugins jquery-masonry

MySQL select where like path -



MySQL select where like path -

setting wordpress project staging environment, have ran issue regarding paths set development environment, , don't fit ones in staging.

so need update paths in database, c:\xampp\htdocs\site.com /var/www/site.com

at first, tried replacing, same way replaced urls:

update `wp_slider` set `url` = replace(`url`, 'http://local.', 'http://');

then paths:

update `wp_slider` set `path` = replace(`path`, 'c:\xampp\htdocs\site.com', '/var/www/site.com');

which didn't work. tried select see rows can retrieve:

select * `wp_slider` `path` "%c:\xampp\htdocs\site.com%"

which homecoming empty result. missing?

forgot mention, tried escaping \ doing \\ , still no result

a total path of i'm trying replace like: c:\xampp\htdocs\site.com/wp-content/plugins/slider/skins/slider\circle\circle.css

that's way go:

mysql> select replace('c:\\xampp\\htdocs\\site.com\\foo\\bar.txt', 'c:\\xampp\\htdocs\\site.com', '/var/www/site.com'); +----------------------------------------------------------------------------------------------------------+ | replace('c:\\xampp\\htdocs\\site.com\\foo\\bar.txt', 'c:\\xampp\\htdocs\\site.com', '/var/www/site.com') | +----------------------------------------------------------------------------------------------------------+ | /var/www/site.com\foo\bar.txt | +----------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) mysql>

if 0 matches that's because db records not contain think do. create sure don't have blanks or command characters. if mysql client not create easy spot such things, can utilize hex():

select path, hex(path) wp_slider path not "c:\\xampp\\htdocs\\site.com%"

additionally, i'm not sure can utilize \ path separator in unix systems. suggest replace well:

update wp_slider set path = replace(path, '\\', '/') path not null

update:

what i'm trying explain procedure right (except escaping \ not optional):

mysql> create table wp_slider( -> path varchar(2083) -> ); query ok, 0 rows affected (0.06 sec) mysql> insert wp_slider (path) values ('c:\\xampp\\htdocs\\site.com/wp-content/plugins/slider/skins/slider\\circle\\circle.cs s'); query ok, 1 row affected (0.04 sec) mysql> update wp_slider set path=replace(path, 'c:\\xampp\\htdocs\\site.com', '/var/www/site.com'); query ok, 1 row affected (0.03 sec) rows matched: 1 changed: 1 warnings: 0 mysql> select * wp_slider; +----------------------------------------------------------------------------+ | path | +----------------------------------------------------------------------------+ | /var/www/site.com/wp-content/plugins/slider/skins/slider\circle\circle.css | +----------------------------------------------------------------------------+ 1 row in set (0.00 sec)

if don't matches it's because database contains different info think, such (but not restricted to) whitespace or command characters:

mysql> truncate table wp_slider; query ok, 0 rows affected (0.03 sec) mysql> insert wp_slider (path) values ('c:\xampp\htdocs\site.com/wp-content/plugins/slider/skins/slider\circle\circle.css'); query ok, 1 row affected (0.02 sec) mysql> update wp_slider set path=replace(path, 'c:\\xampp\\htdocs\\site.com', '/var/www/site.com'); query ok, 0 rows affected (0.00 sec) rows matched: 1 changed: 0 warnings: 0 mysql> select * wp_slider; +------------------------------------------------------------------------------+ | path | +------------------------------------------------------------------------------+ | c:xampphtdocssite.com/wp-content/plugins/slider/skins/slidercirclecircle.css | +------------------------------------------------------------------------------+ 1 row in set (0.00 sec)

in lastly example, forgot escape \ when inserting , result don't match when replacing because input info not thought was.

mysql select where sql-like

ruby - Rack Routing - NoMethodError -



ruby - Rack Routing - NoMethodError -

i'm trying set basic routing scheme in rack, however.. can't understand why first route ('/') works, , sec ('/help') doesn't. gets returned in case of '/help' nomethoderror. why that, , how can prepare it? give thanks you.

require 'rack' class myapp def self.call(env) new.call(env) end def self.get(path, &block) @@routes ||= {} @@routes[path] = block end def call(env) dup.call!(env) end def call!(env) @req = rack::request.new(env) @res = rack::response.new @res.write route(@req.path) @res.finish end def route(path) if @@routes[path] @@routes[path].call else 'not found' end end def to_do(arg) arg end end myapp.get '/' 'index' end myapp.get '/help' to_do 'help' end run myapp

ruby routing rack

javascript - Google Map mouse wheel bug -



javascript - Google Map mouse wheel bug -

normally it's possible scroll / zoom vertically out of map. there gray background. "disabled / blocked" that.

this works fine if utilize controls google map. if zoom mouse wheel it's kinda buggy , can zoom out of map, gray area visible.

here live example: example

how prepare without disabling mouse wheel zoom?

image:

theme.gmap.position = function () { var allowedbounds; var lastcenter; var lastzoom; var initcenter; var initzoom; function checkbounds() { if (theme.base.isundefined(allowedbounds)) { homecoming false; } if (allowedbounds.getnortheast().lat() > theme.gmap.google_map.getbounds().getnortheast().lat()) { if (allowedbounds.getsouthwest().lat() < theme.gmap.google_map.getbounds().getsouthwest().lat()) { lastcenter = theme.gmap.google_map.getcenter(); lastzoom = theme.gmap.google_map.getzoom(); homecoming true; } } theme.gmap.google_map.panto(lastcenter); theme.gmap.google_map.setzoom(lastzoom); homecoming false; } homecoming { createlatlng:function (lat, lng) { homecoming new google.maps.latlng(lat, lng); }, centermap:function (latlng) { theme.gmap.google_map.setcenter(latlng); }, setlimit:function () { allowedbounds = new google.maps.latlngbounds( this.createlatlng(-85.0511, -122.591), this.createlatlng(85.0511, -122.333) ); initcenter, lastcenter = theme.gmap.google_map.getcenter(); initzoom, lastzoom = theme.gmap.google_map.getzoom(); google.maps.event.addlistener(theme.gmap.google_map, 'bounds_changed', function () { checkbounds(); }); google.maps.event.addlistener(theme.gmap.google_map, 'center_changed', function () { checkbounds(); }); } }; }();

i guess forced 2 competing events, both event fire each time. center_changed event redundant(the bounds alter when center changes), may remove center_changed-listener(for me fixes issue)

javascript google-maps google-maps-api-3 zoom mousewheel

How to build 3D environment in android? -



How to build 3D environment in android? -

i have developed few simple android apps. want build apps , games 3d environment. eg like this. kindly tell me how started? have not developed in 3d.

probably first thing you'll need larn opengl , larn utilize in android

android 3d

vb.net - Search DataTable with values from another table -



vb.net - Search DataTable with values from another table -

i'm trying search 1 datatable values anotherdatatable using linq, no progress far... how it?

in illustration below have table, in search, , pltable, has 1 column; , need retrieve every row table, in name field contains @ to the lowest degree 1 string of name field in pltable's rows.

dim epltable ienumerable(of datarow) = pltable.asenumerable() dim found = row in table.asenumerable row(0).contains(epltable) select row homecoming found.copytodatatable.rows

surely not work, .contains wants string argument

surely not work, .contains wants string argument

that's exatly problem, utilize typed field extension method cast it's right type , enumerable.any if @ to the lowest degree 1 string contained in name:

dim strings = row in pltable select row.field(of string)(0) dim found = row in table.asenumerable strings.any(function(s) row.field(of string)("name").contains(s)) select row homecoming found.copytodatatable()

vb.net linq datatable linq-to-dataset

javascript - ZeroMQ with node.js pipeline sink stops receiving messages after a while -



javascript - ZeroMQ with node.js pipeline sink stops receiving messages after a while -

i've been trying set ventilator / worker / sink pattern in order crawl pages, never got past testing phase. 1 particularity of setup sink lives in same process ventilator. nodes utilize ipc:// transport. moment test messages exchanged. ventilator sends tasks, workers receive them , wait send confirmation sink.

symptoms: after time (generally less 5 minutes) sink stops receiving confirmation messages though ventilator keeps on sending tasks , workers maintain on receiving them , sending confirmations messages.

i know confirmations sent because if restart sink, gets missing messages on startup.

i thought zeromq dealt auto-reconnect.

ventilator/sink

var force = zmq.socket('push'); var sink = zmq.socket('pull'); var pi = 0; setinterval(function() { push.send(['ping', pi++], zmq.zmq_sndmore); push.send('end'); }, 2000); push.bind('ipc://crawl.ipc'); sink.bind('ipc://crawl-sink.ipc'); sink.on('message', function() { var args = [].slice.apply(arguments).map(function(e) {return e.tostring()}); console.log('got message', args.join(' ')); });

worker.js

var pull = zmq.socket('pull'); var sink = zmq.socket('push'); sink.connect(opt.sink); pull.connect(opt.push); pull.on('message', function() { var args = [].slice.apply(arguments).map(function(e) {return e.tostring()}); console.log('got job ', args.join(' ')); settimeout(function() { console.log('job done ', args.join(' ')); sink.send(['job done', args.join(' ')]); }, math.random() * 5 * 1000); });

edit tried moving sink process , seems work. live in same process , observed similar behaviour when dealing more 1 zmq socket per process, regardless of pattern used

edit i'm using module https://github.com/justintulloss/zeromq.node

i don't expect reply accepted, i'm placing here reference. there faithful node-only module called axon inspired zeromq.

axon has no compiled dependencies, , re-creates same socket types zeromq. axon builds upon pub/sub socket type create network event-emitter. finally, zmqs req/rep socket not work node.js because zmq expects reply occur synchronously. beingness native node, axon library handles req/rep pattern properly.

note: zmq , axon not interoperable.

javascript node.js zeromq pipeline

wpf - SelectedItem is null in DataGridTemplateColumn with ComboBox -



wpf - SelectedItem is null in DataGridTemplateColumn with ComboBox -

i have datagrid , datagridtemplatecolumn combobox

<datatemplate x:key="comboboxpackagingtype"> <combobox selecteditem="{binding packagingtype.selecteditem, mode=twoway}" itemssource="{binding packagingtype.itemssource}"/> </datatemplate>

...

<datagridtemplatecolumn celltemplate="{staticresource comboboxpackagingtype}"/>

the selecteditem never changing value after selecting item list. set breakpoints on both , set functions , stopping on function after changing itemsource of datagrid never on set function after selecting item list.

why?

try adding updatesourcetrigger=propertychanged binding of combobox's selected item so:

<datatemplate x:key="comboboxpackagingtype"> <combobox selecteditem="{binding packagingtype.selecteditem, mode=twoway, updatesourcetrigger=propertychanged}" itemssource="{binding packagingtype.itemssource}"/> </datatemplate>

this worked me.

wpf datagrid datagridtemplatecolumn

Split sample of R tm corpus objects -



Split sample of R tm corpus objects -

i using r tm package, trying split corpus training set , testing set, , encode metadata selection. what's easiest way (suppose i'm trying split sample in half)?

here things i've tried:

i know when type... > meta(d) metaid y 1 0 1 2 0 1

i see ids, cannot seem access them (in order first half belong in 1 set, , sec in set). rownames(attributes(d)$dmetadata) gives me indexes, looks ugly, , they're factors.

now, after converting dataframe, d dataset, say: half <- floor(dim(d)[1]/2) d$train <- d[1:half,] d$test <- d[(half+1):(half*2),]

but how can like...

meta(d, tag="split") = ifelse((meta(d,"id")<=floor(length(d)/2)),"train","test")

...to result like:

> meta(d) metaid y split 1 0 1 train 2 0 1 train ... . . ... 100 0 1 test

unfortunately, meta(d,"id") doesn't work, meta(d[[1]],"id") == 1 does, redundant. i'm looking whole-vector way of accessing meta id, or smarter way of subsetting , assigning "split" meta variable.

a corpus list. can split normal list . here example:

i create data. utilize info within tm package

txt <- system.file("texts", "txt", bundle = "tm") (ovid <- corpus(dirsource(txt))) corpus 5 text documents

now split info train , test

nn <- length(ovid) ff <- as.factor(c(rep('train',ceiling(nn/2)), ## create split factor want rep('test',nn-ceiling(nn/2)))) ## can add together validation set example... ll <- split(as.matrix(ovid),ff) ll $test corpus 2 text documents $train corpus 3 text documents

then assign new tag

ll <- sapply( names(ll), function(x) { meta(ll[[x]],tag = 'split') <- ff[ff==x] ll[x] })

you can check result:

lapply(ll,meta) $test.test metaid split 4 0 test 5 0 test $train.train metaid split 1 0 train 2 0 train 3 0 train

r tm

c# - WPF MVVM PropertyChanged notifications in the ViewModel triggered by Model Events -



c# - WPF MVVM PropertyChanged notifications in the ViewModel triggered by Model Events -

i having problem understanding how propagate property changed event in model class through viewmodel , view. trying conform mvvm pattern please maintain in mind.

i have model trying expose viewmodel. model class queries api phone call server status , exposes status in public properties. ex:

public class serverstatusrequest : apirequest { //exposable properties request public serverstatushelperclass status { get; set; }

where serverstatushelperclass wrapper combined results in query:

public class serverstatushelperclass { public bool serverstatus { get; set; } public int onlineplayers { get; set; }

the cool thing apirequest base of operations class checks cache time of particular api phone call , updates results using system.timers.timer. so, example, serverstatus api phone call cached 3 minutes on api, every 3 minutes serverstatusapirequest object have fresh info it. expose updatedresults event in apirequest classes notify when new info comes in.

now want viewmodel have instance of serverstatusapirequest , bind serverstatushelperclass status property , remain date changes every time info updated, view (for binding) can't know model, , thus, doesn't know updatedresults event in apirequest class. how can reflect out view through viewmodel? doing weird here?

here have semi-working sense hacky solution:

in viewmodel:

public const string eveserverstatuspropertyname = "eveserverstatus"; private serverstatusrequest _eveserverstatus = new serverstatusrequest(); public serverstatusrequest eveserverstatus { { homecoming _eveserverstatus; } set { //if (_eveserverstatus == value) //{ // return; //} //raisepropertychanging(eveserverstatuspropertyname); _eveserverstatus = value; raisepropertychanged(eveserverstatuspropertyname); } } public void updateeveserverstatus(object sender, eventargs e) { eveserverstatus = (serverstatusrequest)sender; }

and in viewmodels constructor subscribe model's event:

eveserverstatus.updatedresults += new updatedresultseventhandler(updateeveserverstatus);

as can see, seems extremely redundant. , ran problem had comment out check in setter eveserverstatus because @ point _eveserverstatus updated value without knowing , wanted fire event anyway.

i fell i'm missing key concept here link much more easily.

thanks input.

i have come across much improve way implement behavior looking for. here code in viewmodel:

private serverstatusrequest _eveserverstatus = new serverstatusrequest(); public serverstatusrequest eveserverstatus { { homecoming _eveserverstatus; } }

no setter viewmodel nor view should changing data. , within serverstatusrequest class have property exposing serverstatushelperclass object shown in question. have changed serverstatushelperclass , made implement inotifypropertychanged so:

public class serverstatushelperclass : observableobject { private bool _serverstatus; public bool serverstatus { { homecoming _serverstatus; } set { _serverstatus = value; raisepropertychanged("serverstatus"); } } ...

observableobject simple class implements inotifypropertychanged me mvvmlight.

by doing view automatically updated when apirequest class modifies it's serverstatushelperclass object.

input on solution welcome.

c# wpf data-binding mvvm mvvm-light

html - How to select all children in subparents apart from first -



html - How to select all children in subparents apart from first -

this should simple thing can't seem find i'm after. i've got parent div sub-parents , children inside.

<div class="parent"> <div class="subparent1"> <div class="foo">foo1 </div> <div class="bar">bar1 </div> </div> <div class="subparent2"> <div class="foo">foo2 </div> </div> <div class="subparent3"> <div class="bar">bar2 </div> <div class="foo">foo3 </div> <div class="bar">bar3 </div> </div> </div>

i want hide '.foo' classes apart first one. how utilize css3 select rest of '.foo' apart first?

ps -- number of '.foo' dynamic , change.

a situation depends on prior knowledge of html structure; there's no way using css lone without having predictable html, because css doesn't have ability select first grandchild of kind, first child.

for example, if know first .foo always occur in first subparent, may able away selecting .foo display block, selecting subsequent subparents , .foos using general sibling combinator ~ , hiding them:

class="lang-css prettyprint-override">.parent > .subparent1 > .foo { display: block; } .parent > .subparent1 > .foo ~ .foo, /* .foo after first in .subparent1 */ .parent > .subparent1 ~ div > .foo { /* .foo in subparents after .subparent1 */ display: none; }

if .subparent1 may not contain .foo elements @ all, , want select first .foo regardless of subparent, don't think it's possible css selectors alone. may have find different way, e.g. assigning class first .foo since it's dynamically generated, or using javascript apply styles instead.

html css css3 css-selectors

c# - Commit and rollback Oracle transactions -



c# - Commit and rollback Oracle transactions -

i'm calling proc in c# oracle. made proc homecoming error. in other words proc fails , pv_error populated string , rollback gets triggered, doesn't work. i'm not sure why. so, doing wrong? in advance.

private void hhrcv_update_dc_grs_carton() { oraclecommand cmd = new oraclecommand(); cmd.connection = conn; conn.open(); oracletransaction trans = conn.begintransaction(); cmd.commandtimeout = 0; cmd.commandtext = "dc.hhrcv_update_dc_grs_carton"; cmd.commandtype = commandtype.storedprocedure; cmd.parameters.add("pn_dc_grs_no", oracledbtype.number).value = txtdcgrsno.text; cmd.parameters.add("pn_pallet_id_no", oracledbtype.number).value = txtpalletid.text; cmd.parameters.add("pn_carton_code", oracledbtype.varchar).value = txtcartoncode.text; cmd.parameters.add("pn_company_id_no", oracledbtype.number).value = companyid; cmd.parameters.add("pn_order_no", oracledbtype.number).value = txtorderno.text; cmd.parameters.add("pn_emp_id_no", oracledbtype.number).value = empid; cmd.parameters.add(new oracleparameter("pv_error", oracledbtype.varchar)); cmd.parameters["pv_error"].direction = parameterdirection.output; string pv_error; cmd.executenonquery(); pv_error = cmd.parameters["pv_error"].value.tostring(); if (pv_error.tostring() == "") { trans.commit(); } else { trans.rollback(); messagebox.show("" + pv_error, "error"); frmreturns r = new frmreturns(); r.show(); this.hide(); } } the stored procedure not committing oracle sql developers autocommit disabled when run stored procedure in oracle sql developers works (fails - have made , doesn't commit) only when running stored procedure in vs2005 proc fails, triggers rollback doesn't execute it

most need add:

cmd.transaction = tran;

after calling begintransaction.

without runtime not know cmd part of transaction tran!

for details see the documentation.

c# oracle stored-procedures

c# - use ascx control in a div tag -



c# - use ascx control in a div tag -

i created user command named "uctest.ascx". want show .ascx command in div tag out using aspx page. if it's possible means please help me this?

as people here it's impossible without aspx page. however, can think not clean solution this.

you can create aspx page, place command there , load aspx page through ajax div. lose server side functionality of command don't know if solution you

c# asp.net

Instantly show autocompletion results using Android's search dialog -



Instantly show autocompletion results using Android's search dialog -

i redesigning search interface android app. i've reddish google's api guide (http://developer.android.com/guide/topics/search/search-dialog.html).

the current version of app uses classic scheme search dialog. lacks autocompletion want provide in new version.

my requirements in terms of auto-completion: if query string less 3 characters, app should auto-suggest search results based on set of stored favorites stored locally. if query consists of @ to the lowest degree 3 characters, search shall conducted remotely via search api.

since historically, app's minimum api level 7, cannot utilize honeycomb's searchview (api 11+) or actionbarsherlock searchview (api 8+). decided stick search dialog provided searchmanager.

i've sucessfully implemented requirements stated above.

though, 1 thing reduces usability.

when user starts search, search dialog gains focus. desired behaviour instantly, favorites suggested. though, true on htc legend running froyo (2.2). on galaxy nexus, app of times not instantly show suggestions. callbacks searchprovider not until user has entered @ to the lowest degree 1 character.

my question: there way instantly show suggestions/get callback searchprovider across android versions starting api 7+?

i've tried different calls searchmanager (startsearch()) no luck.

android search

c# - insert into statment error -



c# - insert into statment error -

i've been trying insert specific info database (in case microsoft access), next code wrote using c#:

string sql = "insert orders(user,pid,pname,price,amount)" + " values('" + od.user + "','" + od.pid + "','" + od.pname + "','" + od.price + "','" + od.amount + "')";

now assume form wrote fine , isnt it? error is:

syntax error in insert statement.

user reserved keyword. set brackets around specify want utilize identifier, not command:

string sql = "insert orders([user],pid,pname,price,amount)" + " values('" + od.user + "','" + od.pid + "','" + od.pname + "','" + od.price + "','" + od.amount + "')";

this should solve immediate problem. using parameterised query (as several has suggested) avoid future problems also.

c# asp.net sql ms-access

java - PrimeFaces customize RowEditor in datatable -



java - PrimeFaces customize RowEditor in datatable -

is there way customize roweditor button? mean if possible alter image or add together text. if not possible, there way obtain same behaviour command button or link?

just utilize css. below illustration assumes want apply on datatables/roweditors , have desired image files in /resources/images folder.

class="lang-css prettyprint-override">.ui-datatable .ui-row-editor .ui-icon-pencil { background-image: url("#{resource['images/pencil.png']}"); } .ui-datatable .ui-row-editor .ui-icon-check { background-image: url("#{resource['images/check.png']}"); } .ui-datatable .ui-row-editor .ui-icon-close { background-image: url("#{resource['images/close.png']}"); } see also: how override classes defined in primefaces.css?

java jsf-2 primefaces

java - Lucene - Return results ordered by the number of matching fields -



java - Lucene - Return results ordered by the number of matching fields -

i have lucene index numerous fields. i'd utilize find documents ranked number of fields matched , have results indicate how many fields matched.

in particular example, documents in lucene index represent web pages , fields things title, meta description, h1 text, etc.

if search term "bicycle", want documents contain word "bicycle" in field returned. however, i'd relevancy score indicate number of fields contain keyword "bicycle". example, if document contains "bicycle" in title , meta description, i'd document rank higher 1 contains "bicycle" in title. i'd able determine first document contains 2 matches sec document contains 1 match. frequency of keyword in particular field not matter. care know whether or not matched.

i know can utilize booleanquery find matches on single field , can combine these , or or on multiple fields i'm not sure how perform query homecoming document matches on field homecoming indicator of how many fields matched.

any help much appreciated!

in lucene, searching on field can done forming queries title:a web page. suppose create queries q1, q2, .. qn above n fields. searching using these queries homecoming document ids store in lists l1, l2,.. ln. now, merge them in set s. each item in s, check how many lists (or lists) item belong to. should solve problem, if understood right.

java lucene

Do a search using a dropdownlist in php where the values are from the database -



Do a search using a dropdownlist in php where the values are from the database -

guys need help... don't have thought on how create search , display results in tabular form using dropdown list values in dropdownlist came database. here scenario... when take 1 of options or choices dropdownlist(for illustration closed - closed status cases) when click closed display results in tabular form cases has status equivalent closed same other statuses when there no match display message. (it nice when values dropdownlist came database in future can add together status automatically populate in dropdownlist nice if same in search...) hope guys help me in one...

php search drop-down-menu using

javascript - AngularJS directive template not updating if scope is populated via ajax -



javascript - AngularJS directive template not updating if scope is populated via ajax -

i tried give question precise title could. i'm pretty new angularjs i'm stomped on issue. tried create jsfiddle improve illustrate issue relies on many separate files. , alas not online yet, bear verbosity. :) have app built yeoman init angular, , app.js looks this:

"use strict" var myapp = angular.module("myapp", []) .config(function($routeprovider) { $routeprovider .when("/lineup", { templateurl: "views/lineup.html", controller: "lineupctrl" }) //other routes .otherwise({ redirectto: "/" }); }) .directive("playerlist", function() { homecoming { restrict: "e", transclude: false, scope : {}, templateurl : "views/directives/playerlist.html", controller : function($scope) { $.get("/players") .success(function(players) { $scope.players = players; }); }, replace : true } });

my index.html picks app.js , has anchor references #/lineup, opens views/lineup.html; simplify things, let's assume latter contains (custom) <playerlist></playerlist> tag. within directive's controller function i'm sure $.get("/players") works should because can see chrome's network tab response comes through correctly array of players. finally, views/directives/playerlist.html has code replaces <playerlist> tag, follows:

<table class="table table-striped"> <thead> <tr> <th>name</th> <th>age</th> <th>role</th> <th>strength</th> </tr> </thead> <tbody> <tr ng-repeat="player in players"> <td>{{player.first_name}} {{player.last_name}}</td> <td>{{player.age}}</td> <td>{{player.role}}</td> <td>{{player.strength}}</td> </tr> </tbody> </table>

my thought create "playerlist" directive independent lineupctrl might want reuse elsewhere in project. ok here goes: when click on anchor loads #/lineup first time, tbody element of above table empty (no rows appended it); funny thing is, when click on sec time, table correctly populated players $.get("/players") instruction. suspect due slight lag occurs between rendering of playerlist.html , $scope.players variable beingness assigned. isn't whole point of angular app? when scope variables alter respective views (and templates) updated? please help! cheers, andrea

whenever update scope variables outside of angular function, need tell angular changed. see scope.$apply.

$.get("/players") .success(function(players) { $scope.$apply(function () { $scope.players = players; }); });

on different note, angular has built in ajax service, there no need utilize jquery. explanation can found in tutorial: 5 - xhrs & dependency injection.

javascript angularjs

metaprogramming - Find the start and end of a Java function -



metaprogramming - Find the start and end of a Java function -

in java, possible generate corresponding curly brace sample of java source code, given source code string, start of curly brace?

public class findfunctionstartandend{ public static object findcorrespondingcurlybrace(string sourcecode, string startingposition){ //return string position corresponds matching curly brace //the input string should source code of java class //if sourcecode not valid java code, homecoming false } }

you need run through string , count open , closing brackets origin @ starting position , match them up. problem be, there several cases in need ignore them (here couple of examples):

in line comment (between // , "new line") in block comment (between /* (not hidden line comment) , */) in string literals (between 2 matching "'s (ignoring escapes (\", watch \\" or \\\"!))) in char literals (between 2 matching ''s) possibly more

you can either maintain counters of these run through string, or come regular look match entire function body (including these cases in list) , apply 1 time , see matching index ends after found body.

either 1 should bit involved right in cases, recommend hitting google see if can find examples of pre-made regular expressions, example.

java metaprogramming syntax-highlighting

javascript - the w3c Statement generate an error~can you help me? -



javascript - the w3c Statement generate an error~can you help me? -

the first written

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <textarea rows="7" cols="49" id="box" onclick=tellpoint()></textarea> <script language="javascript"> function tellpoint() { var rng = event.srcelement.createtextrange(); rng.movetopoint(event.x,event.y); rng.movestart("character",-event.srcelement.value.length); pnum.value = rng.text.length; } </script> <p></p> position:<input type="text" value="0" id="pnum" size="8">

it wrong in ie8.0 browser

however,the sec written

<textarea rows="7" cols="49" id="box" onclick=tellpoint()></textarea> <script language="javascript"> function tellpoint() { var rng = event.srcelement.createtextrange(); rng.movetopoint(event.x,event.y); rng.movestart("character",-event.srcelement.value.length); pnum.value = rng.text.length; } </script> <p></p> 光标位置:<input type="text" value="0" id="pnum" size="8">

it right.

i have no idea,how can can create first work well?thanks~

javascript jquery