Posts

Showing posts from March, 2014

How to redirect to a html page from a java servlet along with the variables from the servlet? -

i want open html page java servlet , variables of servlet should used assign form fields in html page opened. this servlet import java.io.*; import java.sql.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; public class signin extends httpservlet { public void dopost(httpservletrequest req,httpservletresponse res)throws ioexception,servletexception { printwriter pw=res.getwriter(); string fname=null,lname=null,uname,pwd,dept=null,mobno=null; connection con=null; statement stat=null; resultset rs=null; try { class.forname("sun.jdbc.odbc.jdbcodbcdriver"); con=drivermanager.getconnection("jdbc:odbc:userdb"); stat=con.createstatement(); uname=req.getparameter("un"); pwd=req.getparameter("password"); //pw.println(pwd); rs=stat.executequery("select * userdb uname= '"+uname+"' , pwd='"+pwd+"

Grails Spring Security Core: Get users with specific ROLE -

Image
i'm trying user s follow criteria , have role_user . criteria: arraylist<user> users = user.createcriteria().list() { inlist("gender", whichgenderlist) ne("uid", uid) profile { inlist("age", whichage) } firstresult(usersperpage * currentpage) maxresults(usersperpage) } question: possible add criteria condition select users role_user ? i'm using: grails 2.4.4 spring security core 2.0-rc4 update: minimal user table: role table: userrole table: arraylist<user> users = user.createcriteria().list() { inlist("gender", whichgenderlist) ne("uid", uid) role { eq("authority","role_user") } profile { inlist("age", whichage) } firstresult(usersperpage * currentpage) maxresults(usersperpage) }

javascript - Ajax Return Value show on div but not show on input fields -

hi have ajax code can change innerhtml of div not work input text field. this ajax code: <script> function hallprice(str) { if (window.xmlhttprequest) { // code ie7+, firefox, chrome, opera, safari xmlhttp = new xmlhttprequest(); } else { // code ie6, ie5 xmlhttp = new activexobject("microsoft.xmlhttp"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readystate == 4 && xmlhttp.status == 200) { document.getelementbyid("hallcharges").innerhtml = xmlhttp.responsetext; } } xmlhttp.open("get","<?php echo base_url();?>admin/hallreservation/get_hallprice?q="+str,true); xmlhttp.send(); } </script> <div id="hallcharges"></div> <input id="hallcharges" name="hallcharges" type='text' class="form-control" /> how update text field responsetext ? you have same id div , input , please change

tic tac toe - Why my TicTacToe game doesn't complete running the codes? (Python 2.7.9) -

when run codes,it gets stuck after choose wether play first or not. so, here codes: #tictactoe game import random null = '' new = ['','','','','','','','',''] player = '' computer = '' #x or o signs def sign(player, computer): player = raw_input('please choose either x or o:') while player not in ('x','x','o','o'): print ('not appropriate choice!') player = raw_input('please choose either x or o;') if player == 'x' or player == 'x': print ('you have chosen x!') computer = 'o' else: print ('you have chosen o!') computer = 'x' return player.upper(), computer.upper() #which player play first def whoplaysfirst(): shift = none while shift not in ('yes','yes','yes','no','no&

geolocation - My current location in android -

i'm new , has taken lots of time trying figure out. have code below seems not working , crashes. know might little thing holding need fixed , running. can in correcting please want learn well. import com.google.android.maps.geopoint; import com.google.android.maps.mapactivity; import com.google.android.maps.mapcontroller; import com.google.android.maps.mapview; import android.content.context; import android.location.location; import android.location.locationlistener; import android.location.locationmanager; import android.os.bundle; import android.view.menu; import android.view.menuitem; public class mainactivity extends mapactivity { protected static final geopoint geopoint = null; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); mapview view = (mapview) findviewbyid(r.id.mapview); view.setbuiltinzoomcontrols(true); final mapco

uiimageview - iOS: How to code a Tool Tip when user hovers over a UIView -

Image
i have tool tip show on set of uiimageview when user hovers on it. don't see see methods leverage in uiimageview class. how can accomplish this? tool tip support not directly available in ios @ time. can accomplish same effect couple of approaches: using existing tool tip framework there open source solutions available solve problem, can pull own project , use , save lot of time, long ensure license compatible apple's policies (many of them are, require credit author somewhere in project source). study code learn technique. example there ampoptip project on github here's corresponding youtube video : here similar stackoverflow.com question (there may more): is possible show tooltip in ios app? trying code yourself you'd use long press gesture, see apple's gesture recognizers documentation , perform kind of hit test determine when finger on uiview subview (in case uiimageview) , time entry of it, , how long held in view without movi

scala - Returning the same value type, but with success/failure -

let's have method.. def foo(b: bar): try[bar] = ??? try placeholder here. foo bar , returns value indicate success/failure. want return original value success/failure indication, when have collection, can know which ones failed , succeeded, , them. try doesn't work me, because failure wraps exception (let's don't care reason why failed). i maybe return either[bar, bar] , seems redundant repeat type parameter. are there better alternatives this? either[bar, bar] , (boolean, bar) isomorphic , choice between them matter of taste. i'd prefer either because nicer set of operations mapping on collection pattern matching, etc., merge extension method allows write results.map(_.merge) seq[bar] if in situation no longer need make distinction between successful , failed results. find this: val result: either[bar, bar] = foo(input).tooption.toright(input) a little nicer than: val result: (boolean, bar) = foo(input).map((true, _)).getor

android - How can I save an Array after closing an Activity and load it back if the same activity called? -

i have following code implemented doesnt work want: my onsaveinstancestate , restore: @override public void onsaveinstancestate(bundle savedinstancestate) { super.onsaveinstancestate(savedinstancestate); savedinstancestate.putintarray("colorarray", colorarraysave); } @override public void onrestoreinstancestate(bundle savedinstancestate) { super.onrestoreinstancestate(savedinstancestate); colorarraysave = savedinstancestate.getintarray("colorarray"); } my onstop, onresume, onpause methods: @override protected void onpause() { super.onpause(); savegridviewcolor(colorarraysave); } @override protected void onstop() { super.onstop(); savegridviewcolor(colorarraysave); } @override protected void onresume() { super.onresume(); colorthegridview(colorarraysave); } so have int array want save if activity stopped/closed , load instanly if activity called again code use doesnt work. savegridviewcolor() saving int[] ar

objective c - Interface Builder doesn't show IBActions -

the problem i have class ( appcontroller ) 2 outlets , 2 actions. 2 outlets picked interface builder , connected fine. 2 actions, though, not present in hud window appearing when ctrl+clicking appcontroller object in interface builder, nor show in library->classes->appcontroller->actions. appcontroller.h #import <cocoa/cocoa.h> @interface appcontroller : nsobject { iboutlet nswindow *newdownloadsheet; iboutlet nsbox *downloadsbox; nsstring *sourcefileurl; nsstring *destinationfilename; nsmutablearray *downloads; } - (ibaction)newdocument; // new download - respond file->new, delegates shownewdownloadsheet: - (ibaction)shownewdownloadsheet (id)sender; @end in .m file defined (although afaik interface builder doesn't @ .m files). also, code compiles fine (without warnings) , 'run', can't because can't connect ibactions. system information mac os x 10.6 – yes, know it's old. computer too, can't upgrade

irb - Interact with Ruby script after it runs -

i used following in ipython: run foo and load file foo.py. every variable defined in file in scope. learning ruby. have hello.rb file have following: puts "hello" x = 1 when load in irb with load './hello.rb' the terminal prints on screen "hello". don't play variable x. how can this? thanks. in ruby cannot access local variables defined in required files. in irb file's local variables out of scope. there few things can solve this: define constant: #hello.rb module sharedconst x = 1 end puts "hello" #in irb puts sharedconst::x # => 1 define instance variables #hello.rb puts "hello" @x = 1 #in irb @x # => 1

php - Sql ignore utf-8 upper or low case while search -

i have added search function on website. if search "öüa" shows me "öüä" , ignores words "Öüä" (where 1 of letters uppercase). $news = db::getinstance()->query("select * news title '%{$keywords}%' order time desc"); i have tried add collate sql_latin1_general_cp1_ci_as like problem persists. upper , lower didn't solve problem either..

ios - How to share Image and text in Iphone -

i want share image , text installed app in iphone please me i'm new in iphone development. don't know how this. i complete in android below code. uri imageuri = uri.parse(sharepath); intent intent = new intent(intent.action_send); intent.settype("image/png"); intent.putextra(intent.extra_text, s); intent.putextra(intent.extra_stream, imageuri); startactivity(intent.createchooser(intent, "share")); but don't know how in iphone. you may use uiactivityviewcontroller share images or text. please go through this or this link.

ios - Where are SKNode positioned in the responder chain? -

sknode inherits nsresponder i'm having trouble understanding how nodes included in responder chain , inserted. for example, how sknode receive mousedown: message? when view clicked, hit testing process occurs determine deepest view @ hit location , mousedown: sent responder chain point. sknodes not views cannot send message directly (because it handled skview). how included in responder chain?

Java framework for Url mapping wiyh methods -

i wanted know best light-weight java framework url mapping each methods of class. in spring framework - annotations used mark class controller , methods against various urls, want framework this. think using spring means using wholw mvc framework...which want avoid such small usage of it. similarly, can tell such small frameworks each module of ? e.g. - spring hibernate, etc. you mean creating rest endpoints? what spark ? on other hand, if want @ higher level of abstraction, check dropwizard

javascript - adding google ads to a webpage : access denined -

i trying add google adsence adds website. created adunit , copied code webpage. when iam trying run page in browser(ie) getting following exception "0x80070005 - javascript runtime error: access denied." <!-- homepage --> <ins class="adsbygoogle" style="display:inline-block;width:300px;height:600px" data-ad-client="ca-pub-3585435689000xx" data-ad-slot="151456789"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> if 1 solved issue before please guide me. thanks.

android - MvvmCross FilePlugin save files to SD card -

we use beautiful mvvmcross framework in our app , utilize fileplugin work filesystem in cross-platform way. by default fileplugin stores data in default location, /data/data/<appname> in android. if want store big files, video or 3d models? in ios store in app folder, in android you'll want store files on sd card. what solution recommend usecase? mean, should inherit fileplugin , override app root directory android somehow? i hade same problem, , solved creating own implementation of imvxfilestore. implementation allows me specify absolute path. internal class custommvxandroidfilestore : mvxfilestore { private context _context; private context context { { if (_context == null) { _context = mvx.resolve<imvxandroidglobals>().applicationcontext; } return _context; } } protected override string fullpath(string path) { if (pathisabsolu

excel - Count occurrences starting with a specific number (Benford's Law) -

Image
i have table in excel countries , associated population counts. count how many times number starts 1, 2, ... 9. it's benford's law , school homework. i tried nb.si or countif didn't work. tried convert numbers text nb.si didn't work better. do have idea? with data in column a , in b1 enter: =left(a1,1) and copy down. in c1 enter: =countif(b$1:b$20,row()) and copy down through c9

javascript - How to not apply skrollr js properties to a div inside another div? -

i have created 2 concentric circles, c1 , c2 respectively. trying user scroll down, circle shrinks , vanishes. using jquery plugin "skrollr js" , problem facing inside circle want content stay fixed on screen , circle vanishes should vanish too. basically, trying re-create http://www.evanshalshaw.com/bondcars/index.html in basic manner. <div id="skrollr-body"> <div class="slides"> <div id="c1" class="circle-mask centred" data-0="transform:scale(2); " data-1000="transform:scale(0);"> <div class="content">hello</div> </div> <div id="c2" class="circle-mask centred" data-1000="transform:scale(2);" data-2000="transform:scale(0);"></div> </div> </div> for full code, please see fiddle. i have created far : https://jsfiddle.net/lplq5mla/ as shown in jsfiddle "hello" moving

javascript - Equivalent of jQuery's $(this) in Ractive.js event proxies -

i reading ractive.js event proxies here . i want replace click event (currently written in jquery) event proxy in ractive.js. current code: $('.filter-close').click(function(){ $(this).parent().hide(); }); the html bit easy: <a on-click="closefilter" class="filter-close">close</a> and know how create proxy in ractive.js: ractive.on( 'closefilter', function ( event ) { //code here }); if place alert in there, executes correctly on click. the problem i'm running is, how access element itself. in example above, need hide parent of clicked element. in jquery used $(this) find element. how do same in ractive? this returns entire ractive object, $(this) throws error, , fetching element id, think, defeats purpose of using ractive in first place. i'm aware of possibility pass argument along event, on-click="closefilter:{{arg}}" , don't know arg should in case (or if correct approach @ all).

algorithm - sum of contiguous subarray modified -

given 1 dimensional array of size n may contain both positive , negative integers , integer k, find sum of contiguous subarray of numbers has largest sum such no element in selected array greater k. k changes provided q queries each containing 1 integer i.e k. example : let n=5 , q=6 , array [1 2 3 4 5] , queries : query 1 : k=5 chosen subarray [1,2,3,4,5]. sum of elements = 15. query 2 : k=4 chosen subarray [1,2,3,4]. sum of elements = 10. query 3 : k=3 chosen subarray [1,2,3]. sum of elements = 6. query 4 : k=2 chosen subarray [1,2]. sum of elements = 3. query 5 : k=1 chosen subarray [1]. sum of elements = 1. query 6 : k=0 there no element x in array such x <= 0. therefore, answer "no solution". how answer these queries effieciently ? please 1 ≤ n,q ≤ 5*10^5 , -10^ 9 ≤ ai,k ≤ 10^9 you can solve linearly. here steps : initialize sum=0 , maximum_sum=0 loop through index 1 n -- if current index value less or equal k add current value sum

How do I center these images in the middle (HTML and CSS)? -

i these 4 images centered in middle of screen while still remaining side side are. <h2><img src="images/colorado parks.gif" alt="button colorado parks webpage" id="colparks"/></h2> <h2><img src="images/colorado monuments.gif" alt="button colorado monuments webpage" usemap="#gotocolmons" id="colmonuments"/></h2> <h2><img src="images/spotlight park.gif" alt="button spotlight park webpage" id="spotpark"/></h2> <h2><img src="images/places stay.gif" alt="button places stay webpage" id="tostay"/></h2> #colmonuments, #spotpark, #tostay, #colparks { float:left; margin: 8px; } looks display:inline-block best that. demo: http://jsfiddle.net/nn82mzjj/ .class-name { text-align: center; font-size: 0; } .class-name h2 { margin: 0 8px; display: inline-bloc

prolog - Predicate that take a list and give me the last item of this list do not work as i expect -

i cannot understand why predicate not work expect.i thought tail of list list 1 item last element of list.so when run query last(x,[1,2,3]) result x=3 take false. last(item,[_|[item]]). what last try , unify second argument list 2 elements. list? this empty list: [] this non-empty list: [_|rest] here, rest must list. can empty list, or non-empty list. here proper lists of length 1, 2, 3: [1|[]] , [1|[2|[]]] , [1|[2|[3|[]]]] . important understand that: ?- [1] = [x|[]]. x = 1. ?- [1,2] = [x|[y|[]]]. x = 1, y = 2. ?- [1|[2]] = [x|[y|[]]]. x = 1, y = 2. you can @ this answer on programmers stackexchange different ways of defining last/2 in prolog.

java - Making a class more generic -

here's code i've inherited game. sample code creates armor. at moment make new armor, need write new class. e.g. // armor.java public class armor extends item { public int tier; public armor( int tier ) { this.tier = tier; } } and // clotharmor.java public class clotharmor extends armor { { name = "cloth armor"; } public clotharmor() { super( 1 ); } @override public string desc() { return "some cloth armor."; } } how structure code make more generic? seem obvious read text-based config file can see running problems when wanted create armor special abilities example. are there resources or design patterns can use figure out how proceed? if intent add dynamically behaviour armor , can use decorator design pattern. try have here . 1 of used pattern of gof's book, design patterns . so, if understand needs, can read file properties want add base ar

cakephp 3.0 - Cakephp3.0 Authentication issue -

problem facing can authenticate using blog tutorial when doing same thing patients table , want login through url/patients/login everytime authenticate said incorrect username , password , in adding user how can add hash password . or can suggest me code in users login access can redirect user based on role admin , author how can check if user admin redirect admin dashboard , if author possible if yes please give login function code i searching on net how add multi level user authentication system find solution using blog example full code , in login system added code : public function login() if ($this->request->is('post')) { $user = $this->auth->identify(); if ($user['role'] === 'admin') { $this->auth->setuser($user); return $this->redirect(['controller' => 'articles']); } else if ($user['role'] === 'author'){ $this->auth->setuser($user);

package - Getting a resource from a different jar -

i have 2 dependant projects: server , app , defined this: val server = project in file("server") val app = project in file("app") dependson server in server project have route should return resource "webapp/app.html" , can found in app 's project .jar . when run app project, have server on classpath , works fine, when hit endpoint doesn't return me required file, though if try resource in server.jar can see it. seems if run app project server on classpath, server can't see files app.jar , there way make work?

java - Can't make Files and Folders -

Image
so i'm working on simple windows explorer replacement. want add ability create folders , files. reason, works when i'm in root or c:/ folder, it's somewhere else (for example c:\program files (x86)) doesn't work. either java.io.ioexception: access denied when create file , when try create folder, no exception comes up, no folder created. this code new file: string location = getpath(); string name = joptionpane.showinputdialog("fill in name of new file. \ndon't forget add file type (.txt, .pdf).", null); if(name == null){ } else { file newfile = new file(location + "\\" + name); boolean flag = false; try { flag = newfile.createnewfile(); } catch (ioexception io) { jframe messagedialog = new jframe("error!"); joptionpane.showmessagedialog(messagedialog, "file creation failed following reason: \n" + io); } } this code new folder: string location = getpath(); string

regex - Unable to match double quotes inside C program -

this question has answer here: my regex matching much. how make stop? 4 answers i've been struggling hours this. coding c program matches regex patterns read file. e.g: https?\:\/\/(\w+\.)+[a-z]{2,4}(\/.*)* href\=\"https?\:\/\/(\w+\.)+[a-z]{2,4}(\/.*)*\" the first line matches every link in html page until end of line, in order avoid that, have created second 1 should match hyperlinks. unfortunately, not work either. computer running linux, , using reference linux man page man 3 regex in addition, have tried single double quote in file well, no positive result. disclaimer: know done easier in bash or python, have use c. you can solve making use of ungreedy capture group. although url complicated, instance in case, don't capture ip-adress based urls (e.g. 127.0.0.1/file ) ports (e.g. 127.0.0.1:8080 ), queries ( foo.bar/index.php?foo=

ios - What are some cool animations that I can do with UIWebView and UITextView -

detailsview.layer.transform = catransform3dmakescale(0.1,0.1,1) uiview.animatewithduration(0.25, animations: { self.detailsview.layer.transform = catransform3dmakescale(1,1,1) }) i have tried one, zooms, thing when app opened. i want can slide top bottom. look here, how create uiview bounce animation? , here, https://github.com/pdetagyos/cooluiviewanimations

javascript - Cannot read property '__reactAutoBindMap' of undefined -

for last week i've been @ loss how set server side rendering react. new project it's express server , i'm attempting render super simple hello world react app uses react-router-component.. i think best way me share code have right , i'm hoping can please tell me i'm doing wrong! i've followed tutorial after tutorial , tried sorts of different things keep getting error after error! this app.js express server, relevant code * route if scroll down bit: require('node-jsx').install({extension: '.jsx'}); var react = require('react'); var app = require('./src/app.jsx'); var request = require('superagent'); var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieparser = require('cookie-parser'); var bodyparser = require('body-parser'); var url = require('url'); //database , p

PHP disable error reporting when working locally but disable it online -

is there way disable error reporting when site on actual host people can view , enable when i'm working on locally on usb webserver? i find pain toggle between error_reporting(1) , (0) whenever want debug. have set in connection file included on every page on website btw edit: ended adding connection file $addrip = $_server['remote_addr']; if($addrip == "::1" || $addrip == "127.0.0.1" ){ error_reporting(0); }else{ error_reporting(1); } "@fred-ii- created similar myself guess thats solution, if post answer ill flag solution :)" as per op's request post comment answer: you can use of these: if ($_server['http_host'] == 'localhost') { // } else { // else } or: $whitelist = array( '127.0.0.1' ); if(!in_array($_server['remote_addr'], $whitelist)) { // } else { // else }

jsf 2 - JSF Validator Problems -

i'm doing following: i want validation implements interface validator of jsf. have following code: index.xhtml: <h:form id="inicio"> <p:panel id="panel" header="digite sus credenciales"> <p:focus context="panel"/> <h:panelgrid id="gridinicio" columns="3" cellpadding="5" > <p:outputlabel for="identificacion" value="identificacion:"/> <p:inputtext id="identificacion" onfocus="true" value="# {ingresomb.usuario.identificacionusuario}" required="true" label="identificacion"> <f:validator validatorid="numericovalidator"/> <f:validatelength minimum="2" /> </p:inputtext> </h:panelgrid> <p:commandbutton value="ingresa

java - How JTextArea "tells" to JScrollPane to change view position while selecting text by dragging mouse outside visible view? -

i have created scroll pane - working fine, noticed, if add jtextarea view panel, , if selecting text mouse dragging outside visible view - scroll pane not change it's view position make cursor/selected text visible. think jtextarea uses method notify scroll pane change view position in such case. how can notify custom scroll pane change position?

javascript - SQS with MongoDB for handling duplicates -

i have couple of ideas stopping duplicate handling of messages amazon's sqs queues. app have mongodb server, think can effective part of either strategy: store queue items in mongo, 'status' field - default pending. use sqs queue id of new message. 1 of worker processes id, findandmodify on actual item in mongo set status processing, unless it's being processed, when flag up. store queue items in queue. workers pick items queue, attempt insert mongo item id , other info. if item existed, don't insert or continue, since it's dupe. the problems , questions have: solution 1 seems counter-intuitive: why use sqs @ all? think it's because polling sqs more correct whole load of worker processes polling mongo work. solution 2 don't know how implement. there atomic find-and-insert-if-doesn't-exist? simple get-or-insert-but-tell-me-which-occurred operation trick. will of these work in large scale scenario, and/or there proven method h

json - Creating an Android app for a website based on WordPress -

so i'm developing android application website based on wordpress. i understand parse every post, need using concept of json parsing. i've been following tutorial, http://karanbalkar.com/2014/08/tutorial-85-fetch-data-from-wordpress-posts-using-json-api/ after research i've discovered wordpress has new wp rest api apparently makes things easier , faster. can't find how use in android app. how different parsing json in above tutorial? it same, wp api http rest api can , post wordpress related objects. plugin still in beta test tho. if need read articles website , display them in android app, maybe using built in rss feed better : www.example.com/feed/ can parse feed app in simple way. note rss feed using xml not json wp api.

Android SQLite fetch user_id -

how can fetch user_id sqlite database? i have user table created (just simple one): private static final string create_table_user = "create table " + table_user + "("+ column_user_id + " integer primary key autoincrement," + column_user + " text not null, " + column_password + " text not null" + ");"; i want user's information throughout whole application (using shared preferences). at log in page, have 2 textfields: username , password . can save these values variable, , put them in createsession(string name, string email, long userid) method. however, since dont have user_id textfield, can't fetch user_id .. needed createsession() method. public void createsession(string name, string email, long userid){ // storing name in pref editor.putstring(key_name, name); // storing password in pref

php - OOP MySQLi Connect -

im newbie in oop. have class database class database{ private $host; private $user; private $pass; private $db; public $mysqli; function db_connect(){ $this->host = 'localhost'; $this->user = 'root'; $this->pass = ''; $this->db = 'db'; $this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->db); return $this->mysqli; } inside class database have function db_num function db_num($sql){ $num = mysqli_num_rows(mysqli_query($this->mysqli,"{$sql}")); return $num; } but cant connect database when im using in con argument $this->mysqli it bad practice mix mysqli object style , procedural style. try this: function db_num($sql){ $result = $this->mysqli->query($sql); return $result->num_rows; } be sure connect database before call db_num() , e.g.: $db = new database(); $db->db_connect(); $db->db_num("select fields

r - Matching pattern multiple times in same string with regex -

this question has answer here: finding indexes of multiple/overlapping matching substrings 1 answer i'm trying find matches of particular pattern "8ab|ab8" in string "8ab8" . tried r command gregexpr("8ab|ab8","8ab8") hoping return vector starting positions c(1,2) . unfortunately, seems happens once first pattern matched, portion of string "removed" , second pattern won't matched. for example, once "8ab" matched, "8ab8" becomes "8" , when r tries matching "ab8" in "8", pattern won't found. know because gregexpr("8ab|ab8","8ab ab8") works fine , returns starting positions of pattern matches c(1,5) . the question is, how match same pattern multiple times in first case? use perl regular expressions: perl=true . (see ?regex

Storing Database Security Credentials in PHP Securely -

is storing database credentials 1 relative-level in directory structure ( ../dbconn_inc.php ) secure? we have basic shared hosting account through godaddy runs cpanel, main page being stored in /public_html . hoping find simple solution securely store database credentials in php include file. have not changed folder permissions (yet - willing so). our primary methods of directory manipulation cpanel's directory manager , filezilla. @ moment, referencing include file stored in root directory ( / ), unsure if safe. thank in advance! it's reasonably safe keep database information inside of script, security of scripts dependent on host , how configure , work server. the disadvantage keeping connection information inside of .php file hosted inside of web root if server stops parsing php , outputs script plain text user loading page, best keep database config outside of web root keep access restricted. your directory this: |-config | --database.php | |-public

Find the max number in a list using recursion Java -

this question has answer here: finding max value in array using recursion 9 answers public static int counter = 0 ; public static int max = 0 ; public static final int findmaxrecursively(list<integer> numbers) { if (numbers.get(counter) > max){ max = numbers.get(counter); counter++; } if (counter == numbers.size() - 1){ return max; } counter++; return findmaxrecursively(numbers); } i have assignment asks me find largest number in list numbers using recursion. the above code throwing index exception believe being caught in main not have access to. what wrong code / logic? edit thanks replies. i went ahead , removed first counter, understand broke there, still not allow me find max number. here's assignment: /* * findmaxrecursively * * takes list of numbers , finds largest among them * using r

android - Styling actionBar action item button -

Image
so have actionbar: how change style of mute button text isn't bold , smaller , of different color? adding android:actionmenutextcolor apptheme has no effect. defining android:actionbarstyle has no effect, it's being ignored! i've looked @ every other answer can find, nothing works! these styles produce actionbar seen above: <style name="appbasetheme" parent="@style/theme.appcompat"> <item name="colorprimary">@color/actionbar_bgr</item> <item name="colorprimarydark">@color/primary_dark</item> </style> <style name="apptheme" parent="appbasetheme"> <item name="android:windowbackground">@color/activity_bgr</item> <item name="android:textcolor">@color/activity_text</item> <item name="android:textsize">@dimen/small_text_size</item> <item name="android:actionbarstyle&qu

api - Facebook Graph Search NLP interface SDK? -

in today's time able see facebook providing interface natural language query processing. know if there sdk or api leveraging can build such queries while searching on facebook through app using graph api. talking search query such my friends single , have been under age which translates url https://www.facebook.com/search/me/users-younger/single/users/me/friends/intersect is there sdk/framework or api me so? public post search has been deprecated since april 30th 2014 graph api v2.0. i believe affects user searches have been unable facebook graph api explorer see https://developers.facebook.com/docs/apps/changelog#v2_0_graph_api

xcode - Creating html file in specific folder -

Image
i new xcode , working on existing application created cordova. trying create new .html file in www folder every time try , create file, spits out main folder , can't drag it. i've tried adding file in www doesn't show nor duplicating existing (coupons.html) work either. can explain me how can add .html file www folder?

ios - MKLocalSearch not finding all nearby restaurants -

i implemented mklocalsearch within region on mkmapview returns array of restaurants within region. through research, 10 restaurants being shown. there's way mklocalsearch can return more 10 restaurants within region? here code, mklocalsearchrequest *request = [[mklocalsearchrequest alloc]init]; request.naturallanguagequery = @"restaurant"; request.region = midregion; mklocalsearch *localsearch = [[mklocalsearch alloc]initwithrequest:request]; [localsearch startwithcompletionhandler:^(mklocalsearchresponse *response, nserror *error) { nsmutablearray *annotations = [nsmutablearray array]; [response.mapitems enumerateobjectsusingblock:^(mkmapitem *item, nsuinteger idx, bool *stop){ customannotation *annotation = [[customannotation alloc] initwithplacemark:item.placemark]; annotation.title = item.name; annotation.subtitle = item.placemark.addressdictionary[(nsstring *)kabpersonaddressstreetkey]; annotation.phone = item.phonenumbe

ruby on rails - How to relate User and Client Portfolio models in Active Record? -

i'm writing rails client phone-book company provides audit services. company has client portfolio , these clients divided among employees (managers, seniors , assistants). see following diagram, instance: manager 40 customers | ________________________________ | | senior senior 20 customers 20 customers | | __________________ _________________ | | | | assistant assistant assistant assistant 10 customers 10 customers 10 customers 10 customers *total customer portfolio: 40 customers the application show user list of phone numbers belonging client use

ios - Objective C - Passing data between two UITableViewControllers -

this question has answer here: passing data between view controllers 35 answers display details in second uitableviewcontroller my application simple recipebook understand uitableviewcontrollers. application contains 2 uitableviewcontrollers. first uitableviewcontroller contains uitableview list of recipe names. if select cell segue second uitableviewcontroller. second uitableviewcontroller contains uitableview list of ingredients. the application contains following classes: recipetableviewcontroller (first) ingredienttableviewcontroller (second) recipeobject recipedata the recipeobject class contains 2 properties. 1 property of type nsstring recipe name. other property of type nsarray ingredients. recipeobject objects in recipedata class. recipeobject *recipe1 = [[recipeobject alloc]init]; recipe1.name = @"fresh coconut cake"; recipe1.ingred

winapi - C# .NET Process class: How do I send input to a console process that is waiting for input? -

here's situation: our c# wpf application needs parse output 3rd-party console application writes file. starting process , parsing file after waitforexit() easy enough, unfortunately app written such after 20 lines of output, stops output , waits user hit return. yes, though writes output file, still pause , wait user hit return before writing next 20 lines. 3rd-party app closed source , there's no hope of recompiling disable behavior. it's quirky in respect, too: despite being console app, must run within it's own directory. given it's win32 port of old dos app, guess shouldn't surprised. i'm aware of usual solutions waitforinputidle() or hacky win32 stuff, can't find suits situation. involves finding open window , sending input via win32 isn't option since console app can't run in window. so think? have not found right win32 hack yet? maybe should wrap console app in winform , can use waitforinputidle()? if it's normal conso

How to insert text to a (worksheet) textbox using VBA in Excel? -

i have inserted text box in worksheet, using menu "insert/text box" @ ribbon of excel 2007. has automatically been named "textbox 17". trying set value using vba code, can't figure out way it. tried run single-line routine feed textbox text (like following , other combinations) failed. sub test() sheets(1).shapes.item(14).text = "eventually text" sheets(1).shapes(14).text = "eventually text" worksheets(1).shapes(14).value = "eventually text" sheets(1).shapes("textbox 17").text = "eventually text" sheets(1).shapes("textbox 17").controlformat.value = "eventually text" worksheets(1).shapes(14).textframe.textrange.text = "eventually text" end sub while in research this, found answers activex textboxes. far understood, textbox have inserted not of kind. can help? this seems working no problem: sheets(1).shapes(14).textframe.characters.text = &q

objective c - move a subview down when scrolling UITableViewController -

i have uitableviewcontroller static cells. add view in lower left corner. wish subview stay "glued" lower left corner , come down/up user scrolling. how can achieve this? have @ link, requires slight alteration have view stick bottom left corner instead of bottom middle. https://developer.apple.com/library/ios/documentation/userexperience/conceptual/autolayoutpg/autolayoutbyexample/autolayoutbyexample.html

php - Regex txt file with the line breaks and two different delimiters -

this question has answer here: my regex matching much. how make stop? 4 answers --- settings --- first: 1 second: 2 --- settings 2 --- first: 3 second: 4 --- settings 3 --- first: 5 second: 6 i trying parse regex #--- ([a-za-z0-9-_,. ]+) ---\n(.*)\n#is but getting block --- settings --- second: 6. how can parse correctly? with s modifier, .* grab can, including newlines , else. try adding ? after .* make regex not greedy. i.e. #--- ([a-za-z0-9-_,. ]+) ---\n(.*?)\n#is or drop s modifier if don't need - .* stop @ end of line.

c# - asp.net mvc + knockout: Showing validation result from server side logic -

i want pass validation result server client , show message. without knockout.js simple: call validation logic. add validation result modelstate . every thing hooked automatically. ( html.validationmessagefor ) what should when using knockout? best practice here? do need return modelstate viewmodel? if yes, how should bind validationmessage placeholder? there plugin use? update 1: i know how use client side validation libraries (ko validation, jquery validation) not problem. i know how return model state client using ajax. the problem is: what standard way of binding errors list, ui elements? need iterate collection , bind them 1 one? there plugin can bind model state object ui? (just when not using knockout , mvc takes care of , binds them validation message place holders.) i facing same problem. first tried implement solution ( https://datatellblog.wordpress.com/2015/06/26/client-and-server-validation-with-web-api-and-knockout/ ) didn't work.

Can a Field class from Java reflection work on any object? -

i curious if can store instance of field object , use on object pass it. i'm doing ton of reflection work, , recall reading somewhere unsafe store field object , use singleton (more or less) access field class. is possible, or i'm trying dangerous or flawed in way? made quick test check, , appears work... i'm unsure if test alone proves that. this assumes we're allowed access field , securityexception won't raised. code used test: package test; import java.lang.reflect.field; public class testclass { public static void main(string[] args) { field fa = null; field fb = null; (field f : test.class.getdeclaredfields()) { switch (f.getname()) { case "a": fa = f; break; case "b": fb = f; break; } } fa.setaccessible(true); fb.setaccessible(true); test ta = new tes

Want to count occurances of Strings in Java -

so have .txt file calling using string[] data = loadstrings("data/data.txt"); the file sorted , looks like: animal animal cat cat cat dog i looking create algorithm count sorted list in java, without using libraries multisets or without use of maps/hashmaps. have managed far print out top occurring word so: arraylist<string> words = new arraylist(); int[] occurrence = new int[2000]; arrays.sort(data); (int = 0; < data.length; ++ ) { words.add(data[i]); //put each word words arraylist } for(int =0; i<data.length; i++) { occurrence[i] =0; for(int j=i+1; j<data.length; j++) { if(data[i].equals(data[j])) { occurrence[i] = occurrence[i]+1; } } } int max = 0; string most_talked =""; for(int =0;i<data.length;i++) { if(occurrence[i]>max) { max = occurrence[i]; most_talked = data[i]; } } println("the talked keyword " + most_talked + " occuring " + max + " times."); i want rat

ruby - RSpec test for a method that contains gets.chomp -

how design rspec test assigning gets.chomp method instance variable? def choose puts "please enter type want:" @type = gets.chomp puts "thank you, please enter how many of want:" @quantity = gets.chomp end you can use stubs/mocks that. main question is: did place def choose ? it's important since i'll stub it's calls on object. let imagine have method in class item : class item def choose puts "please enter type want:" @type = gets.chomp puts "thank you, please enter how many of want:" @quantity = gets.chomp end end then i'll able stub gets , chomp calls simulate user's input: rspec.describe item describe '#choose' before io_obj = double expect(subject) .to receive(:gets) .and_return(io_obj) .twice expect(io_obj) .to receive(:chomp) .and_return(:type) expect(io_obj) .to receive(:ch

python - Mapping Wordnet Senses to Verbnet -

http://digital.library.unt.edu/ark:/67531/metadc30973/m2/1/high_res_d/mihalcea-2005-putting_pieces_together-combining_framenet.pdf in link above on sixth page, paper mentions mapping made. "the process of mapping verbnet wordnet semi-automatic. first manually link semantic constraints defined in verbnet (there 36 such constraints) 1 or more nodes in wordnet semantic hierarchy." i trying use mapping on nltk python verbnet , wordnet. code used mapping? this mapping can found on rada mihalcea's page: http://web.eecs.umich.edu/~mihalcea/downloads.html , direct link: http://web.eecs.umich.edu/~mihalcea/downloads/fnwnverbmap1.0.tar.gz there codes for: verbnet: http://www.nltk.org/_modules/nltk/corpus/reader/verbnet.html framenet: http://www.nltk.org/howto/framenet.html wordnet: http://www.nltk.org/howto/wordnet.html but there no code in nltk read mappings (at least not yet).