Posts

Showing posts from May, 2015

How to re take move in 2D array for tic tac toe in Java? -

i making tic tac toe game. works fine except can't determine condition should write in order re-take invalid move. this how move taken (there public method call these 2 private methods.) private string gethumanmove() { scanner in = new scanner(system.in); system.out.println("enter move: "); string str = in.next(); return str; } private string getcomputermove() { system.out.println("enter move: "); random r = new random(); int r_row = r.nextint(3) +1; int r_col = r.nextint(3) +1; string str = string.valueof(r_row)+ string.valueof(r_col); return str; } this isvalidmove() method public boolean isvalidmove(string move) { int row = (int)(move.charat(0)-'0'); int col = (int)(move.charat(1)-'0'); if(board[row-1][col-1] == ' ') { return true; } return false; } i tried using while loop within isvalidmove() didn't work. please show me how input move again?

android - Kotlin: assignable "it"? -

i'm trying simplify parcelable code in kotlin: public class c() : parcelable { var b1: boolean = false var b2: boolean = false var b3: boolean = false var i1: int = 0 var i2: int = 0 val parcelbooleans = listof(b1, b2, b3) val parcelints = listof(i1, i2) override fun writetoparcel(p: parcel, flags: int) { parcelbooleans.foreach { p.writeboolean(it) } parcelints.foreach { p.writeint(it) } } private fun readfromparcel(p: parcel) { parcelbooleans.foreach{ = p.readboolean() } // not compile "it" "val" } // ... parcel creator bla bla } writeboolean() , readboolean() extension functions. is there way have foreach on list assignable "it"? update: in comment 1 of answers author clarifies question as: my point list not mutable, elements inside are. elements properties. i'm realizing maybe, listof making value copy of properties… either must rely on reflection, or w

How to sort a list according to another list? Python -

so if have 1 list: name = ['megan', 'harriet', 'henry', 'beth', 'george'] and have list each value represents names in right order score_list = [9, 6, 5, 6, 10] so megan = 9 , beth = 6 (this dictionary way) how sort name alphabetically keep score_list matching name? have done sorting numbers using bubble sort method not strings. you can sort them @ same time tuples using zip . sorting name: tuples = sorted(zip(name, score_list)) and then name, score_list = [t[0] t in tuples], [t[1] t in tuples]

mysql - Select rows from database then change a value in a column -

i'm using following query: select id,link,size files status='-1' order id desc limit 10 then want change 'status' column values of selected rows -2, possible combine 'select' , 'update' functions in same query don't have query database again? you not need combine select update: try: update files set status='-2' status='-1' order id desc limit 10; the fields names irrelevant here.

what is the purpose of protected variable and method in java -

this question has answer here: in java, difference between default, public, protected, , private 25 answers i new java, please tell me - "what purpose of protected variable , method in java". thanks in advance. jp. take @ docs following table shows access members permitted each modifier. access levels modifier class package subclass world public y y y y protected y y y n no modifier y y n n private y n n n so, protected elements in java application accessible form subclasses, class , classes in same package! , knowing this, should use protected when methods or attributes of 1 class needs shared around. if don't want leaking of internal state, declaring member variables private way go. if don't care subclasses can access internal

c - Should syslog's openlog() be called before or after seteuid/setegid -

the code have calls openlog() once, before altering effective uid/gid of program (a daemon). security standpoint, or predictability standpoint, calling openlog() after setting effective uid/gid better? i'm guessing on platforms openlog() open unix socket syslogd? permissions on restrictive allow socket opened system users. perhaps has specific case openlog requires elevated privileges, found none (and have in mind lynx , used have in compiled-in default features - til 2009 ). daemons (see this page) not have run root, , use feature. the book the hacker's handbook: strategy behind breaking , defending networks cites openlog , associated functions vulnerability, which allow attacker inject "counterfeit" syslog messages log file given that, ensuring there no weaknesses in application doubly important (since there possibility of becoming agent of other program's intrusion). so answer seems no, there may no need this, dropping privile

java - Is it better to invalidate a session in a servlet in which it is declared or in the jsp page where its values will be used? -

is better invalidate session in servlet in declared or in jsp page values used ? i posting code of servlet below - package controller.uploadinfo; import file.fileoperations; import java.io.ioexception; import java.io.printwriter; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.http.httpsession; import controller.databaseexception.*; public class attendenceinfoupload extends httpservlet { protected void processrequest(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { response.setcontenttype("text/html;charset=utf-8"); try (printwriter out = response.getwriter()) { httpsession session; if (fileoperations.fileupload(request)) { try { fileoperations.exceltoattendence();

ios - Why doesn't Xcode allow me to use presentViewController? -

i want implement share function in spritekit game. have button , i'm trying in gamescene . that's code i've found that: func handletwitter(sender: anyobject) { // check if twitter available if(slcomposeviewcontroller.isavailableforservicetype(slservicetypetwitter)) { // create tweet let tweet = slcomposeviewcontroller(forservicetype: slservicetypetwitter) tweet.setinitialtext("i want share app: ") tweet.addimage(uiimage(named: "shareimage")) self.presentviewcontroller(tweet, animated: true, completion: nil) it looks logical have problem in self.presentviewcontroller(tweet, animated: true, completion: nil) xcode tells me gamescene doesn't have member called "presentviewcontroller" . need implement code in gameviewcontroller.swift ? if so, how use in game scene , others? have 2 scenes share buttons in it. or issue in slcomposeviewcontroller ? don't understand problem, need declare kind of delegate in gamescene make work?

Google Map api V3, setPosition/setCenter is not working -

there 2 places need show google maps. i'm using same code both maps(i mean i'm reusing same code both maps). below links can find screen shots of 2 maps. https://drive.google.com/file/d/0b2jnvvxsaaludlvzemrvmznmajf4ofb1v0jxc0run1p4ewfv/view - map1 https://drive.google.com/file/d/0b2jnvvxsaaluvgrhnm1hsldhqnpzt3k4s2i2r1yyqkp4owzz/view - map2 i'm showing second map(map2) in bootstarp modal first map(map1) working fine. in second map(map2), though have used setcenter method, marker not showing @ center of map(instead showing @ top left corner). should place marker @ center of map(in second map)? below code.. initialize: function(options){ //initializing geocoder this.geocoder = new google.maps.geocoder(); this.map; }, //on show of view //onshow marionette method, triggered when view shown onshow: function(){ var address = this.model.get("address"); //render map dummy latlang this.rendermap(); //render map pr

java - search restaurant based on current geolocation -

i have database of restaurants exact address , when user search restaurant mobile device want show him restaurant in the order of distance current location restaurant close comes first in result. best way this? you can use called haversine formula . the below example php/mysql query still need. $sql = "select *, ( 3959 * acos( cos( radians(" . $lat . ") ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(" . $lng . ") ) + sin( radians(" . $lat . ") ) * sin( radians( lat ) ) ) ) distance your_table having distance < 5"; where $lat , $lng coordinates of point, , lat/lng table columns. above list locations within 5 nm range. replace 3959 6371 change kilometers. this link useful: https://developers.google.com/maps/articles/phpsqlsearch_v3 you can add order by clause order results distance .

java - Why can't I add an EmptyBorder to a custom JComponent? -

Image
my code unable set border of custom jcomponent object new emptyborder(50, 50, 50, 50) . looks on monitor (as can see, works jbutton not custom jcomponent): import java.awt.*; import javax.swing.*; import javax.swing.border.*; public class sandbox { public static void main(string[] args) { // instantiate components needed. jframe frame = new jframe(); jpanel panel = new jpanel(); frame.add(panel); widecomponent wc = new widecomponent(); jbutton button = new jbutton("test"); // add borders emptyborder empty1 = new emptyborder(50, 50, 50, 50); wc.setborder(empty1); emptyborder empty2 = new emptyborder(50, 50, 50, 50); button.setborder(empty2); // add stuff panel panel.add(wc); panel.add(button); // add panel frame, show frame frame.add(panel); frame.setvisible(true); frame.pack(); } } class widecomponent extends

The object stored into a PHP session gets the wrong value stored -

i have created shopping cart object works. when try save object session wrong content of object stored. value being saved value after object cleared shopping cart, empty one. <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>testing shopping cart</title> </head> <body> <?php # cart.php // script uses shoppingcart , item classes. //error_reporting(0); // create cart: session_start(); try { require('shoppingcart.php'); require('usermenu.php'); $cart = new shoppingcart(); // create items: require('item.php'); require ('connect.php'); $conn=connect::doconnect(); $query = "select product_id, product_name, product_price product"; $result = mysqli_query($conn, $query); $i=0; $w = array(); $new_cart; if ($result->num_rows > 0) { // output data of each row echo '<table border='."1".'><form action="c

c# - Reg Expression Error after combining -

format: tb-string1-string2-year-numericdata1-numericdata1digitalways examples per above format. tb-testdata1-testdata2-2015-65789-3 this have tried for var result = regex.match(testdata, @"\t\b-\s{2,5}\-\s{2,5}\-[\d{4}]\-\^[0-9]+$\-[\d]"); if (result.success) { return match; else { return nomatch; } it throwing invalid argument exception. here requirement. first 2 letters “tb”. not case sensitive. each items above separated “-”. string1 --> characters z. not case sensitive. should between 2 5 characters. string2 --> characters z. not case sensitive. should between 2 5 characters year --> should 4 characters numeric data. year data. should +ve numbers only. numericdata1 --> positive numeric data only. should between 2 10 characters. numericdata1digitalways --> 1 digit numeric data between 0 8 only. i have tried each parts individually. breaks

How to change n-th element in list of lists with python list comprehensions? -

i have list of sublists that: posts = [[1, 'text1', 0], [1, 'text2', 0]] and function change_text(text) how can apply function text elements of each sub-list? i have tried this: posts = [change_text(post[1]) post in posts] but got texts ['changed_text1', 'changed_text2'] you can have list within list comprehension >>> change_text = lambda x:'changed_'+x >>> posts = [[1, 'text1', 0], [1, 'text2', 0]] >>> [[post[0],change_text(post[1]),post[2]] post in posts] [[1, 'changed_text1', 0], [1, 'changed_text2', 0]]

Write HTTPS web service in asp.net and call it from android -

i have write web service in asp.net , android application takes list providing username , password pair , show result in listview. communication should takes place in ssl manner. web service model must use? there tutorial doing this? solution splitted 2 parts : 1- creating https web service steps in brief: normally create web site using visual studio add web services web site deploy in iis install server certificates on web server step create simple web service configure web service virtual directory require ssl test web service using browser tutorials & references : https://msdn.microsoft.com/en-us/library/ff649205.aspx configure ssl web services https://rmanimaran.wordpress.com/2010/06/24/creating-and-using-c-web-service-over-https-%e2%80%93-ssl-2/ https://support.microsoft.com/en-us/kb/324069?wa=wsignin1.0 2- consuming https web services in android app : i dont have experiences in android app found lot of tutorials explain trick of consum

networking - Sliding window algorithm implementation -

Image
i having trouble figuring how derive numbers solution question. following steps, numbers not come near of solution. can give concise step step way figuring out both problems. solution part a t = 0 rtt sender sends frames 0, 1 , 2 (theoretically) simultaneously. t = 0.5rtt receiver receives frames 0,1 , 2. receiver updates lfr = 2 , laf = 5 . receiver sends ack each of 3 frames. t = 1 rtt sender receives ack frames 0, 1, , 2, , sends out frames 3,4, , 5. sender updates lar = 2 , , lfs = 5 . t = 1.5 rtt receiver receives frames 3 , 5. receiver updates lfr = 3 , laf = 6 . sends ack frame 3. t = 2 rtt sender receives ack frame 3, , sends out frame 6. sender updates lar = 3 , , lfs = 6 . t = 2.7 rtt sender times out on frame 4 . part b t = 0 rtt sender sends frames 0, 1 , 2 (theoretically) simultaneously. t = 0.5rtt receiver receives frames 0,1 , 2. receiver updates lfr = 2 , laf = 5 . receiver sends ack each of 3 frames. t = 1 rtt sender rec

javascript - Resolve "Uncaught ReferenceError: require is not defined" error in Node.js -

i trying set basic contact form using senggrid , keep getting "uncaught referenceerror: require not defined" error. i have code in script tag in head of html page. var sendgrid = require('sendgrid')(username,pass); i have looked @ requirejs, not sure why getting error. explain me how can resolve issue? require() not built browser. so when "i have code in script tag in head of html page." explain why symbol require not defined when script runs. if want use require() in browser, need first use script tag load library defines require function , supports require() type functionality , make sure loaded before try use require() . requirejs 1 such library use. require() built node.js on server available there.

c# - Issue with drawing routes on Windows Phone 8.0 maps - 0x8004231C -

i want create app shows route location desired point. problem works (for locations route drawn) in cases error: "system.runtime.interopservices.comexception (0x8004231c): excepion hresult: 0x8004231c. in addition followed tutorial found here: https://msdn.microsoft.com/en-us/library/windows/apps/jj244363%28v=vs.105%29.aspx here's code: private async void getcoordinates() { // phone's current location. geolocator mygeolocator = new geolocator(); mygeolocator.desiredaccuracyinmeters = 5; geoposition mygeoposition = null; try { mygeoposition = await mygeolocator.getgeopositionasync(timespan.fromminutes(1), timespan.fromseconds(10)); mycoordinates.add(new geocoordinate(mygeoposition.coordinate.latitude, mygeoposition.coordinate.longitude)); mapka.center = new geocoordinate(mygeoposition.coordinate.latitude, mygeoposition.coordinate.longitude); } catch (unauthori

php - Selection dropdown items not loading when I refresh the page -

so i'm using code population dropdown: <select id="sel" name="char"> <?php $s = $mysqli->query("select * `characters` `accountid`='" . $_session['id'] . "' order `id` asc") or die($mysqli->error); while ($c = $s->fetch_array()) { echo '<option value="' . $c['id'] . '">' . $c['name'] . '</option>'; } ?> </select> this works initially, when refresh page options not show anymore. blank dropdown. wondering reason is? i've made sure session_start(); on page well. suggestions?

Deeper Sub Category with php mysql -

Image
i have problem creating multiple sub category php , mysql deeper sub category doesn't indented. screenshot like: . sealer , wall paint should indented hobe. ex: 1. painting, 1.1 hobe, 1.1.1 sealer, 1.1.2 wall paint i have 3 table: kategori contain: id_kat, nama_kat subkategori contain: id_subkat, id_kat, nama_subkat supersubkategori contain: id_supersub, id_subkat, id_kat, nama_supersub my code is: include "config.php"; $sql = mysql_query("select * kategori"); while($data=mysql_fetch_array($sql)) { echo "<li>".$data['nama_kat'].""; // kategori $sql2 = mysql_query("select * subkategori id_kat = '".$data['id_kat']."'"); // sub kategori if($sql2) { echo "<ul>"; while($data2=mysql_fetch_array($sql2)) { echo "<li>".$data2['nama_sub']."</li>"; }

cucumberjs - Using Protractor with loops to fill in a form getting data from a Cucumber.js table -

(i have seen this discussion, not sure how apply case, i’m asking new question. hope it’s not duplicate) i testing form written in angular using protractor cucumber.js. so tell protractor go click on title of field (which link) then, when field appears, enter text in it, move on title of next field, , on. here step in cucumber: when fill form following data | field | content | | first name | john | | last name | doe | | address | test address | # , forth here’s half-hearted attempt @ step definition: this.when(/^i fill form following data$/, function (table, callback) { data = table.hashes(); # gives me array of objects such one: # [ { field: 'first name', content: 'john' },...] (var = 0; < data.length; i++){ var el = element(by.csscontainingtext('#my-form a', data[i].field)); el.click().then(function(){ var

differential equations - Matlab does not replace symbolic function by its expression -

i have 3 symbolic functions : sigma_r, sigma_theta , sigma_z. 3 functions expressed function of 2 other symbolic functions : epsilon_r, epsilon_theta. example sigma_r = 125021*epsilon_r + 132154*epsilon_theta moreover epsilon_r, epsilon_theta function of symbolic function u(r) example epsilon_r = diff(u) i solve following differential equation : diff(sigma_r)+(sigma_r-sigma_theta)/r+rho*w^2*r==0 actually differential equation can expressed differential equation of u(r). i ask matlab substitute in expression of sigma_r (and sigma_theta) variable sigma_r (and sigma_theta) expressed function of u. matlab did when solves differential equation doesn't replace sigma_theta expression of u. replaces sigma_r. here commands: sigma_r = subs(sigma_r) sigma_theta = subs(sigma_theta) u(r) = dsolve(diff(sigma_r)+(sigma_r-sigma_theta)/r+rho*w^2*r==0) it solves , returns: u(r) = (r*sigma_theta - (r^3*rho*w^2)/3)/r + c5/r you can see sigma_theta still dependent of u.

am force-stop command error on Android 5.0 -

Image
am force-stop package-name doesnot work on galaxy s5 android 5.0 work on galaxy win jelly bean 4.1.2 here screenshot faced same error im using correct command still error error type 2 android.util.androidexception : can't connect activity manager ; system running ? here screenshot try : force-stop --user current c.c.c

oracle12c - I am getting a message whenever I connect my database in oracle 12c 'Your password is soon going to expire'. How do I change the password? -

will connection still work after change password? once logged in, use command alter user user_name identified new_password; to change password. more info here replace user_name user name.

Python Pandas velocity -

i have dataframe, first column when customer entered theater , second column name. time name 1 2 3 4 b 5 b 6 c 7 b 8 c i want average time customer entry (ignore fact customer has leave in order enter again). i trying group data frame df.groupby(['name']).agg({'time' : my_function()}) where def my_function(): j in range(1,len(time)): total = total + time[j] - time[i] = + 1 return total / (len(time)-1) i think trying take average difference in times: in [11]: g = df.groupby('name') in [12]: g['time'].apply(lambda x: x.diff().mean()) out[12]: name 1.0 b 1.5 c 2.0 name: time, dtype: float64 edit: i'm not sure whether want or mean: in [13]: g['time'].mean() out[13]: name 2.000000 b 5.333333 c 7.000000 name: time, dtype: float64

javascript - JS Loop - how do I loop through X items then wait for response to finish the loop -

i want loop through x items want loop through 2 of items wait response function when done start loop on. so, 2 loops run @ given time until items haven finished. best efficient way accomplish this? the news single-threaded nature of javascript works advantage here. bad news if work requires form of asynchronous input, you'll have a) write thread-blocking/locking code, or b) creative recursion , settimeout. the simpler solution (a) goes this. let's assume need prompt user every 2 loops continue operation. for( var i=0, n=0; < 10000; i++, n++ ){ if ( n == 2 ) { /* example of thread blocking operation "confirm" function blocks thread, loop stop executing until user clicks "ok" */ if ( !confirm("keep looping?") ){ break; }; // reset n fires again in 2 iterations n = 0; } } of course, if work doesn't require asynchronous input user or ajax call, better. fortunat

Removing Column from Dataframe that contains a string in R -

i'm trying create shiny app allows people input data. make data usable i'm trying remove column has instance of string in dataframe df. task simple in python in r has become quite tough. my first try df[ ,colsums(apply(df, margin=c(1,2),fun=is.character))==0] the problem apply implicitly calls as.matrix (as understand it) make dataframe mixed values is.character drops every column if column has string in it! i tried few loops go through each cell , try drop column has been failing well. any or pointers superbly helpful! you cannot have column of mixed types (at least not in r). column can have numeric, character or factor values, not values different types. have check if columns character or not, , not every single value. try: df <- data.frame(c1 = 1:10, c2 = letters[1:10], c3 = sample(10, 10), c4 = letters[sample(10,10)], stringsasfactors = false) df[!sapply(df, is.character)] c1 c3 1 1 4 2 2 10 3 3 5 4 4 6 5 5 7 6 6 3 7 7 9 8

netbeans - Jess printout contents print in Java -

i trying printout contents jess rhs of rule. similar question described here: output of jess in java there not concrete solution how use router printout command. instead of printing rule's printout contents in java console want print them in dedicated jtextarea. declared string e.g. string result; hold contents , print out string contents jtextarea through outputtxt.settext(result); the jess manual discusses case, explicitly; see http://www.jessrules.com/jess/docs/71/library.html#routers , http://www.jessrules.com/jess/docs/71/library.html#reader . couldn't easier: // create text area; you'll need add gui, of course textarea ta = new textarea(20, 80); // sort of adapter lets jess print textarea. // there's jtextareawriter swing guis textareawriter taw = new textareawriter(ta); // create rule engine instance rete engine = new rete(); // connect "t" router textarea. point on, // jess code executes "(printout t ..." send out

java - Android's datepicker date shown -

i can't find method or solution set exact date shown on datepicker 's spinners. my problem want set date through spinners , then, when user wants edit date, great start spinners day , not maximum possible (the default). datepickerdialog has 2 constructors, both of accept parameters setting initial date.

python - Kallithea (waitress) not starting -

i made kallithea's installation (into virtualenv) according official guide. then, got following error: (metal)1:17:46 root@dervish mercurial paster serve my.ini 2015-04-26 01:17:49.003 info [kallithea.model] initializing db sqlite:////opt/scm/mercurial/kallithea.db?timeout=60 2015-04-26 01:17:49.003 info [kallithea.lib.auth] getting information available permissions starting server in pid 12321. traceback (most recent call last): file "/opt/scm/mercurial/metal/bin/paster", line 9, in <module> load_entry_point('pastescript==1.7.5', 'console_scripts', 'paster')() file "/opt/scm/mercurial/metal/lib/python2.7/site-packages/paste/script/command.py", line 104, in run invoke(command, command_name, options, args[1:]) file "/opt/scm/mercurial/metal/lib/python2.7/site-packages/paste/script/command.py", line 143, in invoke exit_code = runner.run(args) file "/opt/scm/mercurial/metal/lib/python2.7/site-

javascript - jquery click function already clicked/executed on page -

i have following function: $(document).ready(function() { $('#login-trigger').click(function() { $(this).next('#login-content').slidetoggle(); $(this).toggleclass('active'); if ($(this).hasclass('active')) $(this).find('span') else $(this).find('span') }) }); when clicks button, login form drops down. however, if type incorrect login information , page reloads error message below form, how can make button has been clicked , form displayed? right now, if type in wrong information, page reloads , not logged in. see error, must click drop down login form see error. confuse people , doesn't make sense. if understood question: first of this: if ($(this).hasclass('active')) $(this).find('span') else $(this).find('span') if has .active class find span, , if didn't find span anyway? , it

Retrieve the picture associated with a Facebook Graph API PlaceTag node without /picture edge? -

i'm working latest version of facebook's graph api (v2.3). i'm using tagged_places edge on user object show list of places i've been tagged. according docs, include location tags on photos, videos, posts, statuses , links on profile. for each tagged place, receive placetag node . according docs can use picture edge retrieve picture tagged in location - presumably works when post in question photo (rather status or link, etc). however seems picture edge removed v2.3 of graph api. when perform request picture against placetag, following response: { "error": { "message": "(#12) picture edge type deprecated versions v2.3 , higher", "type": "oauthexception", "code": 12 } } the docs don't provide alternative removed edge. how can retrieve picture associated specific placetag ? possible graph api v2.3? thanks

Bad Indentation of OCaml Comments in vim -

i use ocamldoc-style comment, vim annoying me because indents comment when should not. for instance, following code: (** * {[ if open new line when being of second line of above code, vim indent code like: (** * {[ * so need remove 4 spaces everytime. i tried using ocp-indent , result same. what can not have 4 additional spaces when open new line in ocamldoc comment? thanks. leading stars in comments not idiomatic @ in ocaml (and badly handled ocamldoc), drop stars. the behavior observed expected. indentation engine try indent code in comments, , {[ start of code block explains indentation.

validation - How to avoid to update record in self referenced model due to not refers to itself and also not to be duplicate references -

i have self referenced model: class component < activerecord::base has_and_belongs_to_many :allergens has_many :cqnames, as: :cqnable has_many :inclusions has_many :ingredients, :through => :inclusions accepts_nested_attributes_for :cqnames, allow_destroy: true accepts_nested_attributes_for :ingredients accepts_nested_attributes_for :inclusions, allow_destroy: true translates :name, :description validates :name, presence: true, uniqueness: true def self.get_children(ing) @tree ||= [] if ing.ingredients.nil? return @tree else @tree << ing.ingredients get_children(ing.ingredients) end end end i have avoid self referencing same record , records referenced when respecting record updating. experiment before_validation...: class component < activerecord::base before_validation :hokus has_and_belongs_to_many :allergens has_many :cqnames, as: :cqnable has_many :inclusions has_many :ingredients, :thro

jquery - Ajax during call and on error -

i have ajax call gets location of user , pulls city , province database. when click button trigger call want input box disappear , replaced loading gif. if unable return anything, box should come back. i have tried using this: .ajaxstart(function(data) { $('#location').attr('disabled', 'disabled'); }) but prevents script doing anything. var x = document.getelementbyid("demo"); function getlocation() { if (navigator.geolocation) { navigator.geolocation.getcurrentposition(showposition); } else { x.innerhtml = "geolocation not supported browser."; } } function showposition(position) { var formdata = { 'latitude' : ''+ position.coords.latitude +'' , 'longitude' : ''+ position.coords.longitude +'', }; // process form $.ajax({ type : 'post', // define type

SQL to select distinct values from table with foreign key -

i have 2 tables: a ( a_id int, string fields...) , b ( b_id , string field "name" , referenced column a_id ). want select unique values table a b.name like "%somestring%". you use exists : select a.* tablea exists ( select 1 tableb b a.a_id = b.a_id , b.name "%somestring%" )

php - Laravel 5 localization: exclude /public/ directory -

i trying implement localization in laravel 5 project , i'm running issue. middleware put in catch language follows: <?php namespace app\http\middleware; use closure; use illuminate\routing\redirector; use illuminate\http\request; use illuminate\foundation\application; use illuminate\contracts\routing\middleware; class language implements middleware { public function __construct(application $app, redirector $redirector, request $request) { $this->app = $app; $this->redirector = $redirector; $this->request = $request; } /** * handle incoming request. * * @param \illuminate\http\request $request * @param \closure $next * @return mixed */ public function handle($request, closure $next) { // make sure current locale exists. $locale = $request->segment(1); if ( ! array_key_exists($locale, $this->app->config->get('app.locales'))) { $

Android EditText .setText("") not working -

i trying clear text in edit text field reason not working. i have declared edit text field in xml of view: <edittext android:id="@+id/enterglucoselevel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/mysimplexyplot" android:layout_centerhorizontal="true" android:ems="10" android:inputtype="numberdecimal" /> i have used attribute onclick link button enterglucoseaction() method in mainactivity class: <button android:id="@+id/enterglucosebutton" android:clickable="true" android:onclick= "enterglucoseaction" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/enterglucoselevel" android:layout_centerhorizontal="true" android:text="@string/

java - Android Studio Facebook: onActivityResult in normal class -

in order listen facebook login event must override in activity function onactityresult , make call facebook's callbackmanager. protected void onactivityresult(int requestcode, int resultcode, intent data) { super.onactivityresult(requestcode, resultcode, data); callbackmanager.onactivityresult(requestcode, resultcode, data); } so far everything's working. i'd create static class facebook handles facebook callbacks, such login, etc. is there substitute onactivityresult in case? you mean want class handle activity returning? have have onactivityresult of activity calls startactivityforresult call facebook class. there's no way reroute automatically.

java - Index out of bounds error when parsing to Integer -

i getting error when trying parse string integer or double . int id = integer.parseint(stringparts[2]); if print stringparts[2] works, throws error when parsing. this complete loop i'm using: public static studentrecord[] creates(string filename) throws ioexception { bufferedreader br = new bufferedreader(new filereader("/users/dna40/desktop/lab11input.txt")); int linetext = linecount("/users/dna40/desktop/lab11input.txt"); string record; string cons = ("[ ]"); studentrecord[] student = new studentrecord[linetext]; string[] stringparts = new string[5]; for(int = 0; < linetext ; i++){ student[i] = new studentrecord();//creates object class record = br.readline(); //stores first line of text file stringparts = record.split("\\s+");//splits line parts student[i].setfirstname(stringparts[0]); student[i].setlastname(stringparts[1]); int id = integ

c++ - 'new' runs out of memory with very little memory allocated -

i'm working on large scientific code run non-interactively on cluster. code uses singleton scheme store large matrices in memory, repeated future multiplications. lately code has been crashing, after allocation of type of these matrices, our exception handler returning output this: ## std::bad_alloc caught in terminatehandler ########## new ran out of memory. peak rss memory = 905179136 bytes current rss memory = 905179136 bytes ####################################################### each process ought have @ least 16 gb of ram available it, difficult see how running out of memory @ 905179136 bytes; furthermore, manipulating code use more or less memory results in program still crashing, smaller (larger) value 'peak rss memory' reported. i can think of 2 possibilities: memory fragmentation. a large 'new' request being made reason, such exceed 16 gb if serviced. it may relevant cuda ap

sql server - "Cannot resolve collation conflict" even after fixing the collation -

the current database i'm using "primarydatabase" has collation " sql_latin1_general_cp1_ci_as ", while "secondarydatabase" i'm trying access has collation " arabic_ci_as " i changed collation secondarydatabase , set " sql_latin1_general_cp1_ci_as " , made sure has been changed in tables. however, when run query below still collation conflict. select * [myserver].[secondarydatabase].[dbo].[secondarytablename] ltrim(rtrim([secondarytablename])) not in (select ltrim(rtrim(primaryfieldname)) primarytablename primaryfieldname2=1) one way make query work use collate clause in order apply collation cast on both fields being involved in predicate of where clause: select * [myserver].[secondarydatabase].[dbo].[secondarytablename] ltrim(rtrim([secondaryfieldname])) collate sql_latin1_general_cp1_ci_as not in (select ltrim(rtrim(primaryfieldname)) collate sql_latin1_general_cp1_ci_as primaryt

algorithm - O notation proof for exponents and power -

i trying prove 4^n not in order of o(2^n). is valid method ? 4^n >= c*2^n => 4^n/2^n >= c => 2^n >= c i got lost here... well, method concrete. should proceed in same direction. currently, don't have better option. 4^n = ((2^2)^n) = (2^2n) = (2^n) * (2^n) > 2^n values of n>0. as, (2^n) * (2^n) > o(2^n) . this because (2^n) * (2^n) > c * 2^n. therefore,there doesn't exist constant value greater 2^n! hence, 4^n != o(2^n) 4^n > 2^n values of n>0 .

css - Ember modal only shows overlay -

i'm having trouble showing modal ember. i've followed cookbook when click button modal, shows overlay , not modal itself. here's gist: https://gist.github.com/sunocean-sand/e11111cea44274417012 i appreciate help! i've got similar implementation in 1 of apps. try changing routes/application.js code below. believe problem you're not using bootstrap's programmatic api . export default ember.route.extend({ actions: { openmodal: function(modal) { this.render(modal, { into: 'application', outlet: 'modal' }); return ember.run.schedule('afterrender', function() { ember.$('.modal').modal('show'); }); }, closemodal: function() { ember.$('.modal').modal('hide'); return this.disconnectoutlet({ outlet: 'modal', parentview: 'application' }); } } });

javascript - Change a value over a set amount of time with jQuery? -

i'm working on project calls circular progress bar. found 1 trick here: http://codepen.io/shankarcabus/pen/gzafb but need animate on page load go in value each time: <div class="progress-pie-chart" data-percent="43"> so on "page1.htm", need data-percent value automatically increase incrementally 0-20. on "page2.htm" 20-33, etc. i'm pretty new jquery, have no idea begin on that. how create function increase data-percent value on say, 500 milliseconds? using setinterval can produce like. use math calculate steps based on fps create smooth animation. decimals can used percent var start = 0; var end = 30; var time = 800; //in ms var fps = 30; var increment = ((end-start)/time)*fps; $('.progress-pie-chart')[0].dataset.percent = start; var timer = setinterval(function() { $('.progress-pie-chart')[0].dataset.percent = parsefloat($('.progress-pie-chart')[0].dataset.percent

error handling - VB.NET How do i use ApplicationEvents to catch an exception within a thread? -

i have piece of code in applicationevents.vb supposed handle exceptions: namespace ' following events available myapplication: ' ' startup: raised when application starts, before startup form created. ' shutdown: raised after application forms closed. event not raised if application terminates abnormally. ' unhandledexception: raised if application encounters unhandled exception. ' startupnextinstance: raised when launching single-instance application , application active. ' networkavailabilitychanged: raised when network connection connected or disconnected. partial friend class myapplication private delegate sub safeapplicationthreadexception(byval sender object, byval e threading.threadexceptioneventargs) private sub showdebugoutput(byval ex exception) dim frmd new frmdebug() frmd.rtferror.appendtext(ex.tostring()) frmd.showdialog() environment.exit(0) end sub private sub myapplication_startu

api - How is data sent in REST web services -

i learning web services. have understanding of soap. have few questions regarding rest web services. 1) get, put & post methods in rest web services work same way work simple website. 2) , put & post methods in rest web services allows send/receive data(say: tweet in twitter) between client & web service. message sent(put & post) & received(get) in body of post/put method in xml/json/other formats or file(in specific format) sent separately. 3) there browser tools available see sent & received in rest web services. first of all, clarifying few things. rest architectural style, set of constraints guide structural design decisions. rest not coupled particular underlying protocol, it's not dependent on http, although it's common. second, keep in mind rest became buzzword refer http api isn't soap, , of called rest apis aren't rest @ all. of them simple rpc on http. recommend reading this answer clarification on that. now, que

java - JWPlayer in Webview doesn't work Android Studio -

Image
i don't know why iframe doesn't want work, use html external file in asset folder. iframe appears, it's written : error loading player: no playable sources found . here code : protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); webview wv = (webview) findviewbyid(r.id.webcamview); websettings websettings = wv.getsettings(); websettings.setbuiltinzoomcontrols(true); wv.getsettings().setjavascriptenabled(true); wv.loadurl("file:///android_asset/test.html"); } here html : <!doctype html public "-//w3c//dtd html 4.01 transitional//en"> <html><head> <title>bundoran surf co</title> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <script async="" src="//www.google-analytics.com/analytics.js"></script><script> (functio