Posts

Showing posts from February, 2013

list - Is it better to use generics or Object type for a static helper class in Java? -

i writing program other day required me to: frequency of particular object inside arraylist<string> , remove occurrences of given item, etc., etc. not specified list interface. decided write own helper class , wanted make reusable possible. decided specify list parameter type of collection use class implementing list interface. these classes defined using generics, , did not know class type item removed be. either had define static helper methods generically since static class can not contain generic types explicitly, or define class type of object removed object . implemented in both ways, see below, wondering if there benefits using 1 on other. some further questions on topic: why able work around reference of generic type in static context defining in method header rather class header? when using static method, why not have declare class type in usage? i.e. listtools_v2.getfrequencyof(arraylist<string> items, string s) still works. implementation using

ruby - File Shows error -

while inserting content file: file1=file.new("output.txt","w+") puts "enter string" in1=gets.chomp if file1 file1.syswrite() else puts cant write end file1.close try this, uses write method on file class . remember when you're writing puts statement, succeeding string needs in quotes. file1=file.new("output.txt","w+") puts "enter string" in1=gets.chomp if file1 file1.write(in1) else puts "can't write" end file1.close

java - itext (Text - Pdf) center alignment -

i using itext generate pdf file. want align text in middle of page. input file looks in below format we refer isda credit support annex dated of 1 oct 2009. below data. portfolio mtm usd 24,479,059.69 independent amount usd 0.00 threshold usd 1,000,000.00 credit support amount / exposure usd 23,479,059.69 credit support balance usd 26,140,600.00 net margin requirement usd 2660940.31 minimum transfer amount usd 250,000.00 rounding amount usd 10,000.00 delivery amount usd 2670000 my java code below fileinputstream fis = new fileinputstream(infile); datainputstream in = new datainputstream(fis)

c# - Using TextFieldParser.FixedWidth in variable length strings -

Image
i working on parser intended read in data in fixed-width format (8 char x 10 col). however, isn't case, , there valid data in areas not meet this. not safe assume there escape character (such + in figure below), 1 of several formats. i had attempted using textfieldparser.fixedwidth, , giving 8x10 input, not meet quantity sent errorline instead. it doesn't seem practice parse exception catching block, it? since discrepant lines require additional work, brute force submethod best approach? of data comes in 8 char blocks. final block in line can tricky in may shorter if manually entered. (predicated on #1 being ok do) is there better tool using? feel i'm trying fit square peg in round hole fixedwidth textfieldparser. note: delimited parsing not option, see 2nd figure. edit clarification: text below pair of excerpts of input decks nastran, finite element code. aiming have generalized parsing method read text files in, , hand off split string[]s other methods pro

prepared statement - What is the difference between the following to methods for bind_param PHP -

i'm getting on using singleton approach , starting prepared statements... i'm racking brain on why 1 version of works , 1 not when, me, seem same thing... want work second way in order meet end goal. this works: call_user_func_array(array($stmt, 'bind_param'), array("i", 2)); this not: $params = array("i", 2); call_user_func_array(array($stmt, 'bind_param'), $params); you getting error message like mysqli_stmt::bind_param() expected reference, value given in... the problem bind_param() in php 5.3+ requires array values reference while 5.2 works real values. from docs : care must taken when using mysqli_stmt_bind_param() in conjunction call_user_func_array() . note mysqli_stmt_bind_param() requires parameters passed reference, whereas call_user_func_array() can accept parameter list of variables can represent references or values ( ref ). one solution create array of references $params = array(&qu

ruby - undefined local variable or method `welcome_goodbye_path' in Rails? -

i beginner in rails , trying learn using "agile web development using rails".i wanted create link webpage.this code: <h1>hello, rails!</h1> <p> <%= time.now %> </p> <p> time <%= link_to "goodbye", welcome_goodbye_path %>! </p> but gives error... undefined local variable or method `welcome_goodbye_path' what doing wrong ? code of welcome controller: class welcomecontroller < applicationcontroller def index end def goodbye end end this result of rake routes: prefix verb uri pattern controller#action articles /articles(.:format) articles#index post /articles(.:format) articles#create new_article /articles/new(.:format) articles#new edit_article /articles/:id/edit(.:format) articles#edit article /articles/:id(.:format) articles#show patch /articles/:id(.:format) articles#upd

How to find the maximum "depth" of a python dictionary or JSON object? -

i have json string , want know maximum depth is. depth mean number of embedded keys. if 1 key 7 "children" , know other key had many, depth 8. since types (i believe) can embed other objects arrays , other dictionaries need checked. there way check this? i hoping achieve without external modules if not targeting python3. note: here mean "depth" the following dictionary: { "path": "/0001_anthem", "name": "0001_anthem", "ismovie": true, "runtime": 3600, "thumbnaillocation": "/thubs/test.png", "id": 1, "media": [ { "path": "/0001_anthem/louvers.mp4", "name": "louvers.mp4" } ] } would have "depth" or length of 3 because farthest embedded item key/value pair (level 3) in media array (level 2), in main dictionary (level 1). not sure terminology others use, terminolo

jquery - Changing CSS when changing select -

this working. i'm wondering why isn't affecting css of every .container within .filteritem . it's finding first 1 on page whereas want to change .container within .filteritem . $(document).ready(function () { $('#select').on('change', function () { if (this.value == 'alltopics') { $('.filteritem').fadein(500); } else { var elems = $('.filteritem[data-aa_eventtopic="' + this.value + '"]'); $('.filteritem').not(elems).closest('.filteritem').fadeout(500); elems.closest('.filteritem').fadein(500); //here $('.filteritem').each(function () { settimeout(function () { $('.container').filter(':visible').first().css({ bordertop: 'none', paddingtop: '0px'}); }, 501);

iphone - View Controller too thin for IOS simulator -

Image
as shown on pictures, ios simulator shows view controller small screen. can't figure out if there wrong properties of view controller, ios simulator or both ... thank :) your design view represents 1 possible size, if looks there doesn't mean on sizes. have 2 options make content adapt different sizes use autolayout constraints use autoresizingmask both of them can set on interface builder scenarios. have pick 1 or other, autolayout contraints provides more possibilities autoresizing mask it's more complex. we there third option: change sizes view sizes programatically according screen size. in cases doesn't make lot of sense exists option.

Unable to open Video File in Python using OpenCV -

i have installed opencv in windows 7 (32 bit) , put cv2.pyd file in python modules directory , working fine except opening of video file {i have tried 5-6 different kind of extensions nothing helping} code:: import numpy np import cv2 cap = cv2.videocapture('vtest.avi') while(cap.isopened()): ret, frame = cap.read() gray = cv2.cvtcolor(frame, cv2.color_bgr2gray) cv2.imshow('frame',gray) if cv2.waitkey(1) & 0xff == ord('q'): break cap.release() cv2.destroyallwindows() the line cap.isopened() returns false {i tried providing absolute path video file} return false please can please me why line returning false i have found solution there file present in c:\opencv\sources\3rdparty\ffmpeg\opencv_ffmpeg.dll copy , paste file python base directory c:\python\opencv_ffmpeg.dll , rename file version of opencv using in case v3.0.0 have rename c:\python\opencv_ffmpeg300.dll if system x64 add _64 @ end c:\python\opencv_ffmpeg3

ios - How can I add tag value in sender while creating an UICollectionViewCell? -

i'm noob swift, have question solve trouble in app. in uiview have added collection view sub view, in each cell added different image inside "wrapper view", question is... how can add gesture receives tag value sender each cell? example, when tap cell it'll print indexpath i have code: func collectionview(collectionview: uicollectionview, cellforitematindexpath indexpath: nsindexpath) -> uicollectionviewcell { var cell:uicollectionviewcell = collectionview.dequeuereusablecellwithreuseidentifier("collectioncell", forindexpath: indexpath) as! uicollectionviewcell; cell.backgroundcolor = uicolor.bluecolor().colorwithalphacomponent(0); //agregamos imagen la celda var imageview = uiimageview(frame: cgrectmake(0, 0, cell.frame.width - 0, cell.frame.height - 0)) var image = uiimage(named: "car_aguas_gerber_7.png") imageview.image = image cell.backgroundview = uiview() cell.backgroundview!.addsubview(image

Scala factory method with generics -

i have couple of objects i'm trying write factory method. simplified, these are: case class a[a1,a2](j:a1, k:a2) {} case class b[b1,b2](j:b1, k:b2) {} i create method allow me pass in type, , instance of class. trying this: class myfactory[t] { def make[k,l](p1: k, p2: l): t[k,l] = { new t(p1,p2) } } that doesn't work (for various reacons, including 't cannot take parameters'), there elegant solution creating this? 0__'s answer there. if make factory[a[_,_]] typeclass set. here example names standardised: // enable higher kinded types prevent warnings import scala.language.higherkinds // our case classes case class a[a1,a2](j:a1, k:a2) case class b[b1,b2](j:b1, k:b2) // define our factory interface trait factory[t[_,_]] { def make[p1,p2](p1: p1, p2: p2): t[p1,p2] } // companion class makes factory easier use object factory { def apply[t[_, _]](implicit ev: factory[t]) = ev } // add implicit implementations of factory[a]

PDF file not showing or downloading in nginx server -

i've been searching day, not founding solution. here's problem: vm running ubuntu nginx server php apps. application works fine except cant see or download pdf files in browser. i'll try describe of configuration me solve problem: nginx 1.6.2 php 5.5.26 my /etc/nginx/nginx.conf: user www-data; worker_processes 1; worker_rlimit_nofile 1024; error_log /var/log/nginx/error.log; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; access_log /var/log/nginx/access.log; sendfile on; server_tokens on; types_hash_max_size 1024; types_hash_bucket_size 512; server_names_hash_bucket_size 64; server_names_hash_max_size 512; keepalive_timeout 65; tcp_nodelay on; gzip on; gzip_disable "msie [1-6]\.(?!.*sv1)"; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } my /etc/nginx/sites-available/

sorting - Emberjs advanced sort hasMany association as a computed property -

i have asked variant of question here . need create computed property operated on hasmany association. need sorting similar javascript sort function; can files = ["file 5", "file 1", "file 3", "file 2"]; files.sort(function(a,b){ return parseint(b.split(' ').pop()) - parseint(a.split(' ').pop()) }); result: ["file 5", "file 3", "file 2", "file 1"] here jsbin: http://emberjs.jsbin.com/simayexose/edit?html,js,output any appreciated. note: jsbin presently not working correctly (for reasons other question). have posted question here . did not want hold answer question. update 1 thanks @engma. implemented instructions. matter of fact, copied , pasted posted. new jsbin. http://emberjs.jsbin.com/roqixemuyi/1/edit?html,js,output i still not sorted, though. , if did, still not have sorted way it. i need following: (below errors when try implement in code, not jsbin,

java - How do I restart a scheduled thread if an exception occurs? -

i running thread scheduled run every 10 milliseconds scheduledexecutorservice. thread fails because of random uncaught exception, , wanted know how restart thread when happens. tried make thread global, , check if thread alive using scheduled thread, returns false when it running. tried check state of global thread, returned "new". appreciated! here code initializes everything: scheduledexecutorservice scheduler = executors.newscheduledthreadpool(4); thread update = new thread(new updatethread()); scheduler.scheduleatfixedrate(update, 0, 10, timeunit.milliseconds); whatever runnable you're passing executorservice should have body in try{} catch (runtimeexception) {/*log it*/} block. javadoc scheduledexecutorservice.scheduleatfixedrate explicitly says if scheduled runnable throws exception, future executions suppressed. if reason don't want wrap body in try/catch - can use scheduledfuture returned scheduleatfixedrate ; based on quick testing, calli

c# - putting this line into excel.Formula "=IF(C4 = "x";1;0)" isnt working because of double `" "` -

i want put line excel cell c# : =if(c4 = "x";1;0) but when type: .formula = "=if(c4 = "x";1;0)" , cuts sentence 2 seperate parts, because of double " , idea how fix this? thank in advance use escape characters \" read " string

c# - MVC Multiple Models in One View -

i want reach multiple models in 1 view. have dal folder , dbcontext. class cvcontext : dbcontext { public cvcontext() : base("cvcontext") { } public dbset<linkmodel> links { get; set; } public dbset<aboutmodel> abouts { get; set; } public dbset<portfoliomodel> portfolios { get; set; } public dbset<skillmodel> skills { get; set; } protected override void onmodelcreating(dbmodelbuilder modelbuilder) { modelbuilder.conventions.remove<pluralizingtablenameconvention>(); } } and homecontroller public class homecontroller : controller { private cvcontext db = new cvcontext(); public actionresult index() { return view(db.links.tolist()); } } index.cshtml @model ienumerable<mvccv.models.linkmodel> <ul> @foreach (var item in model) { <li> <a href="@html.displayfor(modelitem => item.linkurl)"> @html.di

data visualization - Connected bubble chart in R -

Image
i have following: type <- c('a', 'b', 'c', 'a&b', 'a&c', 'b&c', 'a&b&c') distribution <- c(.25, .1, .12, .18, .15, .05, .15) i create bubble chart 1 shown in selected answer question: proportional venn diagram more 3 sets bubble areas proportional values in distribution vector , connecting lines show relationship between 3 main bubbles 'a', 'b', , 'c'. using igraph library data, create edges , vertices represent desired plot. here's 1 way it library(igraph) type <- c('a', 'b', 'c', 'a&b', 'a&c', 'b&c', 'a&b&c') distribution <- c(.25, .1, .12, .18, .15, .05, .15) mx <- strsplit(type,"&") ei <- sapply(mx,length)>1 cx <- do.call(rbind, mapply(cbind, type[ei], mx[ei])) gg <- graph.edgelist(cx, directed=false) v(gg)[type]$size<-distribution *2

python - Apache Spark: Error while starting PySpark -

on centos machine, python v2.6.6 , apache spark v1.2.1 getting following error when trying run ./pyspark seems issue python not able figure out 15/06/18 08:11:16 info spark.sparkcontext: stopped sparkcontext traceback (most recent call last): file "/usr/lib/spark_1.2.1/spark-1.2.1-bin-hadoop2.4/python/pyspark/shell.py", line 45, in <module> sc = sparkcontext(appname="pysparkshell", pyfiles=add_files) file "/usr/lib/spark_1.2.1/spark-1.2.1-bin-hadoop2.4/python/pyspark/context.py", line 105, in __init__ conf, jsc) file "/usr/lib/spark_1.2.1/spark-1.2.1-bin-hadoop2.4/python/pyspark/context.py", line 157, in _do_init self._accumulatorserver = accumulators._start_update_server() file "/usr/lib/spark_1.2.1/spark-1.2.1-bin-hadoop2.4/python/pyspark/accumulators.py", line 269, in _start_update_server server = accumulatorserver(("localhost", 0), _updaterequesthandler) file "/usr/lib64/pytho

orchardcms - Orchard CMS: How to add version to theme scripts and styles -

i want automaticaly add version parameter theme scripts , styles, this: <script type="text/javascript" src="/themes/mytheme/styles/common.min.css?v=12345"></script> are there ways orchard cms? have @ combinator module on orchard gallery. it fingerprint resources, combining , minifying them if want (all configured in admin interface)

excel - Can't set CopyFromRecordset results to Date or Number -

i'm trying import data set access 2010 excel using range.copyfromrecordset . there fields in query of values have been cast dates or numbers, e.g.: iif(isdate([install date]),cdate([install date]),[install date]) [install date (cast)], iif(isnumeric([feature number]),cdbl([feature number]),[feature number]) [feature number (cast)] here code using generate worksheet data: private sub createrssheet(db dao.database, rsname string, sheetname string) dim rs dao.recordset dim sht worksheet dim fldctr long dim columnrng range 'get recordset set rs = db.openrecordset(rsname) 'add worksheet set sht = bk.sheets.add sht.name = sheetname 'import recordset worksheet sht.range("a2").copyfromrecordset rs 'iterate through fields fldctr = 0 rs.fields.count - 1 sht.cells(1, fldctr + 1) = rs.fields(fldctr).name 'check if field date field if instr(ucase(rs.fields(fldctr).name), "date") > 0 'format column date

network programming - Creating key:attribute pairs in networkx for Python -

i working on creating graph method analyzing images using pixels nodes in python. using networkx graph support(documentation here: https://networkx.github.io/documentation/latest/index.html ) take example: new=np.arange(256) g=nx.graph() x in new: g.add_node(x) h=g.order() print h as expected, 256 nodes created. now, create node:attribute pairs based on array, namely: newarray=np.arange(256) x in new: g.add_node(x) nx.set_node_attributes(g, 'value' newarray[x]) with addition of line, hoping first node of newarray assigned first node of g. however, rather, values of g assigned last value of newarray. namely, 256. how can add attribute pairs each node, element element? you need pass in dictionary third parameter set_node_attribute, 1 that's aligned graph. see if code need: import numpy np import networkx nx array1 = np.arange(256) array2 = np.arange(256) * 10 g = nx.graph() valdict = {} x in array1: g.add_node(x) valdict[x] = a

swift - need to convert UTC time to current timezone of device -

im using repo https://github.com/remirobert/tempo can me understand how grab current time zone of device, , notify tempo? using timeagonow() function of tempo find display how long ago post made, timezone difference messing up. datasource using utc time. cocoa uses utc internally. of date/time calculations. if create nsdate now: nsdate() you date number of elapsed seconds since midnight, 1970 in utc time. dates have time zones when display them. by default logging date console logs in utc, can confusing. if i'm working on project lot of date/time calculations i'll create debugging method converts nsdate date/time string in current locale, easier read/debug without having mentally convert utc local time. i have never used tempo, don't know if using date strings, nsdate, or "internet dates" (which in utc, use different "zero date" or "epoch date")

rails + satelizer - twitter login -

i using satelizer social logins in rails app. there's no ruby implementation, made 1 adapted node version . so, after pressing login twitter button, controller, , following code produces message: "bad authentication data", code: 215 what doing wrong? requesttokenurl = 'https://api.twitter.com/oauth/request_token' accesstokenurl = 'https://api.twitter.com/oauth/access_token' profileurl = 'https://api.twitter.com/1.1/users/show.json?screen_name=' requesttokenoauth = { consumer_key: env['twitter_key'], consumer_secret: env['twitter_secret'], callback: env['twitter_callback'] }; params = {'oauth' => requesttokenoauth } require "net/https" require "uri" uri = uri.parse requesttokenurl http = net::http.new(uri.host, uri.port) # https stuff http.use_ssl = true http.verify_mode = openssl::ssl::verify_none request

java - Whats the simplest way when writing & reading a 2D-boolean-Array to a CSV File? -

i'd write 2-dimensional boolean-array csv file. im using apache commons' csvparser. problem couldnt find built-in way turn array can written csv-file , later converted back. so there way apart using arrays.deeptostring(...) , writing complicated , error-prone function parse array? it great if boolean[][] array = arrays.parse<boolean[][]>(arrays.deeptostring(oldarray)) existed... thanks help. use univocity-parsers write/read booleans. public static void main(string ... args){ csvwritersettings writersettings = new csvwritersettings(); objectrowwriterprocessor writerprocessor = new objectrowwriterprocessor(); // handles rows of objects , conversions string. writerprocessor.convertall(conversions.toboolean("t", "f")); // write "t" , "f" instead of "true" , "false" writersettings.setrowwriterprocessor(writerprocessor); csvwriter writer = new csvwriter(writersettings);

algorithm - How to detect palindrome cycle length in a string? -

suppose string "abaabaabaabaaba", palindrome cycle here 3, because can find string aba @ every 3rd position , can augment palindrome concatenating number of "aba"s string. i think it's possible detect efficiently using manacher's algorithm how? you can find searching string s in s+s. first index find cycle number want (may entire string). in python like: in [1]: s = "abaabaabaabaaba" in [2]: print (s+s).index(s, 1) 3 the 1 there ignore index 0 , trivial match.

inheritance - Hibernate omit table when extended class contains only embeded collection -

i using @ moment inheritence strategy inheritancetype.joined. extended class contains map of type string stored in own table. wonder if there possibility omit table extended class contains id. please let me know how model differently if there exist no direct option "omit" table. the example shows have base class "attribute" extended class "stringmapattribute". extendend class contains collection. table "stringmapattribute" contains in end "id" "design overhead" can use inheritace , model different attribute types. therefore not ideal have table 1 single id column. // base class @entity @inheritance(strategy = inheritancetype.joined) @discriminatorcolumn(name="type", discriminatortype=discriminatortype.string) public abstract class attribute<t> implements serializable { @id @generatedvalue private int id; private string name; ... } // extended class embedded map @entity @table(name="a

c# - app.config custom configuration - 'System.TypeInitializationException' -

i tried following instruction app.config custom configuration however, got stuck. app.config code: <?xml version="1.0" encoding="utf-8"?> <configuration> <configsections> <section name="configuration" type="dp.configuration, myassembly" /> </configsections> <startup> <supportedruntime version="v4.0" sku=".netframework,version=v4.5.2"/> </startup> <configuration inputloc="c:\input" /> </configuration> here configuration class: using system.configuration; namespace dp { public class configuration : configurationsection { private static readonly configuration settings = configurationmanager.getsection("configuration") configuration; public static configuration settings { { return settings; } }

Unable to get ASP.NET MVC and Web API routing straight in my mind - getting 404s galore -

Image
i struggling routing issues in asp.net mvc + webapi app. feel have moving target here because when add or change 1 route break another. here specific example. first, controllers, can see names: next, mvc routing config (i understand config duplicative, because trying things): and web api routing config (i understand config duplicative, because trying things): as routing problem example, here's podcastfeeds api controller: so post create action method... and can see error: 404 not found - "no http resource found matches request uri . i love direction here... the order or registering routes important since requests handled firs route matches patter. because default route first 1 selected. you need put default route last 1 , register routes starting constraining , ending default one. see in screenshots of routes not configured: example api/podcastfeeds route doesn't specify controller (it needs similar feedroutemap route second screens

facebook - FBSDKLoginManager fails with error code - 308 -

we using fbsdkloginmanager our own ui login facebook. login fails error code 308 . as per docs reason - fbsdkloginbadchallengestring , have searched on internet find out reason have had no luck. any explanation why error occurs , how resolve it? the reason had error login , logout code used 2 different instances of fbsdkloginmanager. see answer here https://stackoverflow.com/a/32659830/4068264 (i not have reputation comments apologies community if response not fall in category of "answer")

node.js - Why does mongoose model's hasOwnProperty return false when property does exist? -

i have code : user.findone( { 'email' : email }, function( err, user ) { if ( err ) { return done(err); } if ( !user ) { return done(null, false, { error : "user not found"}); } if ( !user.hasownproperty('local') || !user.local.hasownproperty('password') ) { console.log("here: " + user.hasownproperty('local')); // displays here: false } if ( !user.validpass(password) ) { return done(null, false, { error : "incorrect password"}); } return done(null, user); }); since app supports other kinds of authentication, have user model has nested object called local looks local : { password : "users_password" }

Why does Python automatically combine two seperate strings? -

this question has answer here: string concatenation without '+' operator in python 4 answers why allow concatenation of string literals? 10 answers if forget comma in list of strings, python (2.7) automatically concatenate 2 strings. example: x = ['id', 'date' 'time'] print(x) #[id, 'datetime'] this behavior seems run contrary vast majority of "use cases" user forgot comma. leads either missing error in code or getting odd error message. in example above, instance, list of attributes object , threw attributeerror: 'yourobjectclass' object has no attribute 'datetime' . feature or bug, , if it's feature why feature? it's feature, , rationale given in the part of spec describes it : multipl

javascript - Not allowing a user to move forward to logging in until given access -

this question exact duplicate of: blocking user logging in permission level , alert displaying let them know why i trying figure out how deny user access signing in site unless have been approved. making site private allow join. can register, once they given permission/group level of 1 or 'bench'. once accept user , change permission level, able login. as of now, stopping level/group 1 users redirect index page(where sign in at). however, want not allow them move forward next page @ all. reason being want display sort of pop alert displaying message created. i'm not sure if can validation or way trying it. added on login code , attempting put permission code had on signed in page try stop start. basically, in attempt if user tries log in, script dies once sees permission level @ group 'bench'. pop alert displays saying why. i'm not having success it. group/permission levels have name , id. hav

I was running the following PHP code using addition? -

this question has answer here: php: echo ('x' == 0) prints 1 (true). correct? 1 answer this code: <?php $a = "4 fox , 3 cows"; // simple string $b = 22; echo $ab = $a + $b; echo "output::".$ab; ?>' output: first index being read 26 logic behind this..? instead should error.. 2.another example: <?php $a = "four fox , 3 cows"; // simple string $b = 22; echo $ab = $a + $b; echo "output::".$ab; ?>' output: 22 logic behind this..? you should type juggling , php it's best accommodate ability transform type casting on fly, using + operator in php meant 2 numbers whether integer, decimal, etc. since strings don't have integral value, when use + operator use first part of string can make val

javascript - Ruby on Rails - Passing data directly to jQuery -

i'm trying update or populate table on click passing variables. for checkbox, have done following, works perfectly. <td><%= check_box_tag item_counter, item.to_json, false, {:class => 'show', :onclick => "select.update(this)"}%></td> and jquery function is, $(function () { select.init(); }); select = { update: function (obj) { //table update logic missing simplicity console.log(obj); } } now need creat link similar functionality check_box_tag, have done this, <%= link_to item_count[:name],"#", {:onclick => "select.update(this)", :id => item_count_counter} %> how pass parameters jquery function in case? i've seen using rails tag helpers work things similar describing. however, can little messy when want incorporate client side functionality it. it might worth ditching <%= %> clarity - @ least. but provided you're comm

c# - How to reset a WPF control's default opacity toggling via IsEnabled after setting opacity explictly? -

when disable control (button), dark hard read text. so using extension method set opacity 1.0 (100%) can read easily, when disabled: public static void isenabledspecial(this system.windows.uielement control, bool isenabled) { control.isenabled = isenabled; control.opacity = 1.0; // makes disabled control more readable } normally, when opacity not explicitly set wpf control, appears toggle between 1.0 (100%) when control enabled , 0.35 (35%) when control disabled. once explicitly set opacity using extension method, control thereafter ceases toggle between 1.0 , 0.35 when set isenabled without extension method. gets "stuck" @ 1.0 (100%), when isenabled set false; after set opacity, how can later reset control normal opacity toggling between 1.0 , 0.35? the changing of opacity being done through triggers. setting value directly, overriding value may produced style or triggers. not way go doing sort of thing. should using styles , trigge

c# - ASP.Net MVC 5 using webconfig credentials and Membership.ValidateUser method -

i storing single credential in web.config file usual way: <authentication mode="forms"> <forms loginurl="~/login" timeout="2880"> <credentials passwordformat="clear"> <user name="admin" password="123" /> </credentials> </forms> </authentication> i aware of top notch security , password strength :). then in custom authprovider class validate user usual (old) way: bool result = formsauthentication.authenticate(username, password); and works fine, however, method deprecated (obsolete). want use new way (which believe right thing): bool result = membership.validateuser(username, password); but exception: a network-related or instance-specific error occurred while establishing connection sql server. server not found or not accessible. verify instance name correct , sql server configured allow remote connections. (pro

java - audio reading in jar executable file -

in eclipse when run it, works fine , audio okay, have problem when create .jar executable file. audio file in package , read getresourceasstream want let know. here problem.. inputstream input = getclass().getresourceasstream("/optician/funny-doorbell.wav"); audioinputstream audioin; try{ clip clip; audioin = audiosystem.getaudioinputstream(input); clip=audiosystem.getclip(); clip.open(audioin); clip.start(); } catch (unsupportedaudiofileexception | ioexception e1) { e1.printstacktrace(); } catch (lineunavailableexception e1) { e1.printstacktrace(); } in first case when run eclipse, works fine, when run .jar executable file : reset/mark not supported. second case same : bufferedinputstream input = (bufferedinputstream) getclass().getresourceasstream("/optician/funny-doorbell.wav"); so same, point try bufferedinputstream problem : exception in thread "awt-eventqueue-0" java.lang.classcastexception: sun.new.www.protocol.jar.jarurlconnection$jar

objective c - Cannot get the my location dot for Google Maps iOS SDK -

Image
currently, not able location in app developing. basically, in documentation google maps ios sdk, google mentions can: enable blue "my location" dot , compass direction setting mylocationenabled on gmsmapview https://developers.google.com/maps/documentation/ios/map#my_location however, when that, dot not appear in view. here's setup, have view controller contains view. view contains 3 things, 2 buttons , map view: i have linked mapview gmsmapview , can see map without problems. now, want, located. i tried 2 things. first, using custom, draft button (the information), tried manually set location mapview wasn't working though locationservicesenabled method returned yes. then, tried using googlemaps's dot isn't working either. here's code: studydisplayviewcontroller.h : #import <uikit/uikit.h> #import <corelocation/corelocation.h> #import "googlemaps/googlemaps.h" @interface studydisplayviewcontroller

How to announce streams on Reddit -

hi want launch subreddit gamer, 1. want know how can announce streams on sub reddit twitch or youtube. same watch people code sub reddit 2. can post automatic messages other reddits related gaming category ? if you're interesting in writing bot, can find documentation here: https://www.reddit.com/dev/api and subreddits disallow bots, don't. you'd have find out specifics on own.

Jquery: Get 'title' attribute of each element, not just the first -

i trying display title attribute of each element class "tooltip", using jquery plugin tooltipster . but whatever reason, "title" of first element - every element on page. <i class="tooltip game-1" title="219"></i> <i class="tooltip game-2" title="30"></i> <i class="tooltip game-3" title="122"></i> $(document).ready(function() { $('.tooltip').tooltipster({ content: $(''+$(this).attr('title')+' people played game') }); }); i 219 on , over. try using each() apply tooltipster() each .tooltip element seperately. $(document).ready(function() { $('.tooltip').each(function(){ $(this).tooltipster({ content: $(''+$(this).attr('title')+' people played game') }); }); });

Unable to send push notifications to IOS using php-apn -

hi have installed package php-apn on linux sending push notifications ios , error is: "unable use specified private key" i tried using stream_socket_client , got similar error. path key/cert correct, have regenerated keys/certs again same outcome the code below // apns contex $apn = apn_init(); apn_set_array($apn, array( 'certificate' => '/var/www/html/scripts/certs/pushchatcert.pem', 'private_key' => '/var/www/html/scripts/certs/apns_cert.pem', // 'private_key_pass' => '', 'mode' => apn_production )); //apn_sandbox // notification payload context $payload = apn_payload_init(); apn_payload_set_array($payload, array( 'body' => 'push ', 'sound' => 'default', 'badge' => 1, '

javascript - creating multiple objects with browserify -

i trying use design pattern below: human.js function human(name){ this.name = name this.sayname = function(){ console.log(this.name); } } var = new human("bob"); var b = new human("ted"); however haven't used browserify , don't know how in browserify. what notice when require human.js , try create new object, appears replacing old object. how use browserify design pattern? rest of code along lines of: module.exports = { myhuman:human } and in file 1: var human = require('human.js') var ted = new human('ted') ted.sayname(); and in file 2: var human = require('human.js') var bob = new human('bob') bob.sayname(); with commonjs (browserify), export when call require (however, careful assuming export singleton, it's not case experience). in case, want export human class directly. in each file need instantiate human, require class , instantiate there. human.js func

ios - Checking data integrity on iPhone? -

we collect data on form. then, form submitted via web. network connection unavailable, gets stored in .plist file. is there way (in xcode or otherwise) pull plist file iphone? want see state of file after crash, before start app again.

Clearing current WebView Content and reloading a different content in JavaFX -

i have webview displays html page, maingraph.html, , execute javascript function "false" parameter. on clicking 1 of menuitems, want same javascript function called "true" parameter. when menuitem selected, there 2 outputs of same javascript instead of latest 1 replacing older one. analysiscontroller.java public class analysiscontroller implements initializable { public void displaymaingraph(webengine wemaingraph, boolean pblnfisheyelens) { system.out.println("analysiscontroller.displaymaingraph(): called"); string strdatafile = strcurrentinputfile + ".json"; final url urlloadmaingraph = getclass().getresource("html/maingraph.html"); wemaingraph.getloadworker().stateproperty().addlistener((ov, oldstate, newstate) -> { if (newstate == state.succeeded) { wemaingraph.executescript(" doeverything(' "+strdatafile+" ', "+pbl

winapi - LowLevelKeyboardHook C -

this question has answer here: wh_keyboard_ll hook not called 3 answers i try write litte hook programm in c. programm don't work , don't know why. #include <stdio.h> #include <stdlib.h> #include <windows.h> lresult callback lowlevelkeyboardproc( int ncode, wparam wparam, lparam lparam ) { if(ncode >= 0) { char key; kbdllhookstruct *pkeyboard = (kbdllhookstruct *)lparam; key = (char)pkeyboard->vkcode; printf("%c\n",key); } return callnexthookex(null, ncode, wparam, lparam); } int main(void) { hinstance instance = loadlibrary("user32"); hhook hook = setwindowshookex( wh_keyboard_ll, lowlevelkeyboardproc, instance, 0); getchar(); unhookwindowshookex(hook); printf("ready"); return exit_success; } i think mistake somewhere @ setwindo

How can I import a python package or __init__.py file using the full path? -

i have package: pyfoo in directory /home/user/somedir the package normal 1 '/home/user/somedir/pyfoo/__init__.py' i able import module using full-path '/home/user/somedir/pyfoo/' how non-package modules shown in: how import module given full path? but seem unable work when module package. the odd use case found embed deep script execution before writing file h5py. i had uninstall h5py , reinstall parallel version openmpi, though uninstalled h5py(serial) still in memory. did not want restart, because script took long time. attempted reload module, did not work. tried import filename using directory , __init__.py, got relative import errors. tried adding new install location sys.path , executing normal import, failed. i have import_from_filepath function in personal utility library, , i'd add import_from_dirpath well, i'm having bit of trouble figuring out how done. here script illustrating issue: # define 2 temporary modules not i

ios - How to set array of different objects (NSString, UIImage,NSString,etc) to a message body of MFMessageViewController in Same Order in array -

mfmessagecomposeviewcontroller *msgcomposer=[[mfmessagecomposeviewcontroller alloc] init]; msgcomposer.messagecomposedelegate = self; msgcomposer.recipients = [nsarray arraywithobjects:@"9688069434",nil]; msgcomposer.body = @"message body"; [self presentviewcontroller:msgcomposer animated:yes completion:nil]; the property "body" nsstring. have tried attachments. how assign nsarray messagebody?

javascript - How to handle custom headers with CORS Pre-flight request? AJAX - CodeIgniter -

Image
i'm working codeigniter , restfull api structure web server private api. i've started using cors per requirements framework i'm using. working jquery, can see 2 requests sent, first 1 option type - expected - without custom header (x-api-key security, default in codeigniter restful api). i receive invalid api key error message shown in picture. right after proper request being sent correct headers in meantime, first requests triggered .fail() function handle errors. what's best practice handle scenario ? ajax request smoothly handle first preflight option request without triggering error on app today, normal call custom headers per how cors works , execute success call without never triggering error call in first preflight request ? triggerfriendswall: function() { //get location var options = { timeout: 30000, enablehighaccuracy: true, maximumage: 90000 }; //we