Posts

Showing posts from January, 2013

devise - Rails: Switch User Gem and issues with switching back to original user -

in app using switch_user ( https://github.com/flyerhzm/switch_user ) gem allow admins login user. gem has ability log in admin, having hard time conceptualizing how it. here config: switchuser.setup |config| # provider may :devise, :authlogic, :clearance, :restful_authentication, :sorcery, or :session config.provider = :devise # available_users hash, # key model name of user (:user, :admin, or name use), # value block return users can switched. config.available_users = { :user => lambda { user.all } } # available_users_identifiers hash, # keys in hash should match key in available_users hash # value name of identifying column find by, # defaults id # hash allow specify different column # expose instance username on user model instead of id config.available_users_identifiers = { :user => :id } # available_users_names hash, # keys in hash should match key in available_users hash # value column name displayed in select box config.availab...

bash - Shell script to get one to one map and rename the filename -

i have 2 files sorted numerically. need shell script read these 2 files , 1:1 mapping , rename filenames mapped case#; for example: cat case.txt 10_80 10_90 cat files.txt bcd_x 1.pdf bcd_x 2.pdf ls pdf_dir bcd_x 1.pdf bcd_x 2.pdf read these 2 txt , rename pdf files in pdf_dir : a bcd_x 1.pdf bcd_10_80.pdf bcd_x 1.pdf bcd_10_90.pdf if have bash 4.0 help: #!/bin/bash declare -a map i=0 ifs='' while read -r case; (( ++i )) map["a bcd_x ${i}.pdf"]="a bcd_${case}.pdf" done < case.txt while read -r file; __=${map[$file]} [[ -n $__ ]] && echo mv "$file" "$__" ## remove echo when things seem right already. done < files.txt note: make sure run script in unix file format.

Android: Google Authentication + Ubertoken -

ok, give up. have experience using google's issueauthtoken , mergesession authenticate google services not have official api access? in case i'm trying google bookmarks (from google.com/bookmarks). i sid , lsid using getauthtoken , works fine. call uri issue_auth_token_url = uri.parse("https://accounts.google.com/issueauthtoken?service=bookmarks&session=false"); string url = issue_auth_token_url.buildupon() .appendqueryparameter("sid", sid) .appendqueryparameter("lsid", lsid) .build().tostring(); i receive "ubertoken". i mergesession , that's goes wrong: string url2 = "https://accounts.google.com/mergesession?source=chrome&uberauth="+ubertoken+"&service=bookmarks&continue=https%3a%2f%2fwww.google.com%2fbookmarks%2f"; httpget getcookies = new httpget(url2); looking through headers of getcookies not seeing cookies should see, , see...

How can I save html page with changes of jquery? -

i have html page, these codes: <script> $(document).ready(function(){ $("h4").click(function(){ $(this).html("read"); }); }); </script> {% data in collecteddata %} <div align="center" class="box">{{ data }}</div><h4>unread</h4> {% endfor %} for example click "unread" , became "read" when refresh page becomes "read" again. i'm sorry might silly question how can save jquery effects on html page ? edit:i 'm not working on server local, use jinja , have no database. use jinja , python. you must store (persist) modified data somewhere. use ajax request server mark message read (as in case). or can use localstorage/sessionstorage, known web storage , store data in browser. advised data can changed user sensitive information should not stored in web storage. another new , exciting thing indexeddb , acts sql database on client-side.

html5 - Reading a javascript variable containing a string into another file -

for example in 1 file test.js var test = { string: "test string" }; i want read in js file this: test.string should give me "test string" output. any ideas good. thanks modifying question bit: i not able read global variable declared in same file. var test = { string: "test string" }; is in same file. how using in variable. "mytest":{ "prop":{ myvar: "test.string" } } so trying print mytest.prop.myvar , expecting "test string" giving test.string output i'm not sure understood correctly: once have javascript file loaded, if variable declared in global namespace becomes available other scripts, long load them in correct order. in case have include <script src="test.js"></script> load second file <script src="secondfile.js"></script> in secondfile.js can use test.string normal. update after update: have declared variable :...

r - How to determine whether a points lies in an ellipse -

i had posted similar question earlier. trying determine whether point lies within ellipse. generate bivariate normal data , create ellipse. heres code use library(mass) set.seed(1234) x1<-null x2<-null k<-1 sigma2 <- matrix(c(.72,.57,.57,.46),2,2) sigma2 rho <- sigma2[1,2]/sqrt(sigma2[1,1]*sigma2[2,2]) eta<-replicate(300,mvrnorm(k, mu=c(-2.503,-1.632), sigma2)) p1<-exp(eta)/(1+exp(eta)) n<-60 x1<-replicate(300,rbinom(k,n,p1[,1])) x2<-replicate(300,rbinom(k,n,p1[,2])) rate1<-x1/60 rate2<-x2/60 library(car) dataellipse(rate1,rate2,levels=c(0.05, 0.95)) i need find out whether pair (p1[,1],p1[,2]) lies within area of ellipse above. dataellipse returns ellipses polygons, use point.in.polygon function sp library check whether points inside ellipse: ell = dataellipse(rate1, rate2, levels=c(0.05, 0.95)) point.in.polygon(rate1, rate2, ell$`0.95`[,1], ell$`0.95`[,2]) when run following code... library(mass) ...

search - ldap returns on subtree and one level, but not base -

on active directory can subtree , 1 level ldap search using following filters: base dn: cn=users,dc=local,dc=tld filter: (samaccountname=dummyaccount) the dummyaccount in users container. can explain me why one-level , subtree work whereas base not? there can base find object? when perform base ldap search, reading properties of object specify base dn, nothing else. a base search useful if want read properties of single object , know dn. in case, set base dn dn of object, specify attributes you'd retrieved , provide "dummy" search filter ( because filter cannot ommited ) - (objectclass=*) . you can of course use filter ensure dn reading conforms expectations: might know dn, want ensure object reading user, i.e. then, search filter may used.

Socket connect() on iOS blocks for more than 30 seconds -

i have no clue causing this, using socket on ios , calling connect() makes app hang 30s 1 minute or more. , when returns, half of time connection failed, if server working. i using low level sockets, since avoid having objective c code @ all. cause this? while behavior normal, can set socket nonblocking before connecting, , able other things while waiting it. use select see if it's writeable , when returns true, connect has completed (one way or another). details how detect if connection successful or not here

In C is there a pattern for variables in an array which are assigned 0 value? -

i want know if array of int elements declared in c. there pattern according values of array assigned 0 while others store garbage values? ex: #include <stdio.h> void main() { int a[5]; int i; (i=0;i<=4;i++) { printf("%d\n",a[i]); } } after compile , run program output,i.e. 0 0 4195344 0 2107770384 so zeroes there in a[0], a[1] , a[3] while a[2] contains same value each time compiled , run whereas a[4] value keeps on changing (including negative numbers). why happen fixed indices of array initialized 0 , have related past allocation of memory space? this behaviour undefined , merely coincidence. when declare array on stack , not initialize array take on values (likely previous) stack frame. aside: if wanted zero-fill array declared on stack (in constant time) can initialize using following initialization syntax: int arr[ 5 ] = { 0 }; it write first element 0 , zero-fill rest of elements. however, if declare...

if statement - jQuery get/toggle class and animate if -

still learing dem jqueries , found problem - wanted recreate classical feedback panel/slide side thing. html <div id="foobar" class="slide closed"> <img class="slidebutton" src="img/slide.png" alt="slide"> <div id="slidetext"> <p>slide me out</p> </div> </div> jquery $(document).ready(function() { $(".slidebutton").click(function () { $('#foobar').toggleclass("open closed"); if $('#foobar').attr('class') returns 'closed' { $( "#foobar" ).animate({ "left": "+=200px" }, "slow" ); } else { $( '#foobar' ).animate({ "right": "+=200px" }, "slow" ); }); }); }); if test toggle without if statement works assume made mistake considering animation? infinite kn...

xml - Android layout reuse -

i have android application needs use linear layout in several activities. reason, have extracted needed linearlayout separate xml file don't know how add layout other layouts. simply, idea this: <xml layout id: "somesharedcontrols" /> <xml layout id:"mainwindow"> add @id somesharedcontrols ... other xml controls in current window ... </xml> <xml layout id: "anotherwindow"> add @id somesharedcontrols ... other xml controls in current window ... </xml> how achieve that? you can use <include> . read this .

java - Window.open() in GWT opening file -

i'm trying run code string outputfile = "file:///c:/reports/1016.html"; window.open(outputfile, "test", ""); window.open("http://www.bing.com/", "bing", ""); as can see, outputfile not weblink, file. chrome/firefox not seem want open it, keep opening about:blank window. thought had done wrong added third line actual webaddress works fine. doing wrong here? can window.open() not open files? i think security reasons. try start chrome browser disabled security , see happens: chromium --disable-web-security if local file shown, know security reasons disabled. (and can nothing against it). maybe web debugger shows warning ( f12 )

image - Java KeyListener isn't detecting keyboard input -

i'm trying modify program draws image of castle , able scale image using , down arrow keys. can't manage keylistener work, program runs isn't responding key presses. appreciated, thanks. import java.awt.*; import java.awt.geom.*; import java.util.*; import javax.swing.*; import java.net.*; import java.awt.event.*; public class drawimage extends jframe implements keylistener { int scale = 1; private image image; enter code here public static void main(string[] args) { new drawimage(); } public drawimage() { super("drawimage"); setsize(600,600); setvisible(true); setdefaultcloseoperation(jframe.exit_on_close); toolkit tk = toolkit.getdefaulttoolkit(); image = tk.getimage(geturl("castle.png")); addkeylistener(this); } private url geturl(string filename) { url url = null; try { url = this.getclass().getresource(filename); }...

c# - Customizing SimpleMembershipProvider -

is possible customize simplemembershipprovider in sense of requiring more user name , password login? for example, suppose want 4 pieces of information: login, password, abc, xyz (abc , xyz generic placeholders, now) suppose login is: john/mypassword555/1/1 (authenticated) -> pagex john/mypassword999/1/2 (authenticated) -> pagey bob/mypassword333/1/1 (authenticated) -> pagex bob/mypassword333/1/2 (authenticated) ->pagey bob/mypassword333/1/3 (authenticated) -> pagez having john/mypassword or bob/mypassword333 insufficient. i want able have either same password logins or different passwords, still require 4 fields before request.isauthenticated true. i'm not sure if mean, but: if need data a, b, , c plus password log in, store a, b, , c object structure, serialize object string, , pass string custom membership provider "login" along password, deserialize object parts. @ point can whatever want in custom provider.

actionscript 3 - Using a mask in a data driven display -

my application displays data on graph. graph extracts data database , displays series of points appear horizontally on graph. each point joined line viewer view data points. has worked until when started notice line failing appear. interestingly, line disappears when there 96 or more data points in database. i've checked data , not problem database. have spent 2 days attempting track down bug , found if stop joining line being mask, bug disappears, lose important visual effect. suspect problem might connected use of mask, cannot find similar bug reports online. has seen similar problem or can recommend approach might take fix error? i'll happy add more code post below, have not done code quite complex. //draw backgrond gradient masking var gradientboxmatrix:matrix = new matrix(); gradientboxmatrix.creategradientbox(gradientboxwidth, 400, math.pi/2, 0, 0); backgroundgradient.graphics.begingradientfill(gradienttype.linear, [0xff0000, 0xf...

php - In CakePHP, beforeRender in the AppController is saving to database twice -

i new cakephp, i'm still learning lot of behaviors , everything. 1 i'm struggling find solution fact have code in appcontroller using beforerender. code saves user's id, ip address, , current time of page load database in order record activity. i'm getting rather curious result, , though i've looked around answer haven't been able find it. upon loading page controlled controller (in case, usercontroller), saves data database exact duplicate. right have handful of pages. main index page, login page, register page, user profile page, , user settings page. index page controlled in usercontroller, have redirect login , register pages urls /login instead of /users/login. interestingly, duplicates aren't created on login or register pages-- profile , settings page. i had placed code in beforefilter, , got 3 copies of same data instead of 2. i've tried in afterfilter still got 2 copies. i should mention, 3 fields updating not located in users table ...

node.js - While loop in Javascript with a Callback -

i trying write pseudocode given here https://dev.twitter.com/docs/misc/cursoring javascript using node-oauth https://github.com/ciaranj/node-oauth . afraid because of nature of callback functions cursor never assigned next_cursor , loop runs forever. can think workaround this? module.exports.getfriends = function (user ,oa ,cb){ var friendsobject = {}; var cursor = -1 ; while(cursor != 0){ console.log(cursor); oa.get( 'https://api.twitter.com/1.1/friends/list.json?cursor=' + cursor + '&skip_status=true&include_user_entities=false' ,user.token //test user token ,user.tokensecret, //test user secret function (e, data, res){ if (e) console.error(e); cursor = json.parse(data).next_cursor; json.parse(data).users.foreach(function(user){ var name = user.name; friendsobject[name + ""] = {twitterhandle : "@" + user.name, profilepic: user.profi...

Spring @Cacheable with SpEL key: always evaluates to null -

i having problem @cacheable , using custom key based on spring expression language. have following code @cacheable(value = "mycache", key = "#providerdto.identifier") clientvo loadclientvobyproviderdto(providerdto providerdto); this throwing following error org.springframework.expression.spel.spelevaluation exception: el1007epos 0): field or property 'identifier' cannot found on null the providerdto argument not null, have verified many times. docs should work confused. docs give following example @cacheable(value="books", key="#isbn.rawnumber") i have tried static method. throws nullpointerexception because providerdto null here. public static string cachekey(providerdto providerdto) { ...

objective c - ios simulator black screen with status bar -

i new objective-c , i'm making first app, single-view app. when run program ,the fullscreen ad supposed appear (i'm using revmob) appears. however, when exit ad black screen blue status bar @ top. i have tried many things, such setting main view controller initial view controller, restarting computer, changing/removing debugger, resetting ios simulator, etc. my xcode version 4.6 , os mac osx 10.8.4 i don't want delete xcode , don't want remove ads because source of income. here code: appdelegate.m @implementation appdelegate - (bool)application:(uiapplication *)application didfinishlaunchingwithoptions: (nsdictionary *)launchoptions { [revmobads startsessionwithappid:@"myappid"]; self.window = [[[uiwindow alloc] initwithframe:[[uiscreen mainscreen] bounds]] autorelease]; [self.window makekeyandvisible]; return yes; } - (void)applicationwillresignactive:(uiapplication *)application { // sent when application move active inac...

java - Anything wrong with using a DB wrapper Class like this? -

is there wrong using parent function handle messy catch/finally stuff in connection pool? public connection getconnection() { try { return this.datasource.getconnection(); } catch (sqlexception e) { // todo auto-generated catch block e.printstacktrace(); } return null; } public resultset executequery(connection connection, preparedstatement stmt) { try { return stmt.executequery(); } catch (sqlexception e) { // todo auto-generated catch block e.printstacktrace(); } { if (stmt != null) { try { stmt.close(); } catch (sqlexception e) { // todo auto-generated catch block e.printstacktrace(); } } if (connection != null) { try { connection.close(); } catch (sqlexception e) { // todo auto-generated catch block e.printstacktrace(); ...

php - How to include stripe client api with symfony2. How to include files with no classes in symfony2 -

i'm trying include file in symfony2 project file bunch of require statements. unfortunately this, file doesn't contain class. don't want manually write namespaces included file contain classes need wondering how can include file in way include other files need. file i'm trying include symfony2 looks : <?php // tested on php 5.2, 5.3 // snippet (and of curl code) due facebook sdk. if (!function_exists('curl_init')) { throw new exception('stripe needs curl php extension.'); } if (!function_exists('json_decode')) { throw new exception('stripe needs json php extension.'); } if (!function_exists('mb_detect_encoding')) { throw new exception('stripe needs multibyte string php extension.'); } // stripe singleton require(dirname(__file__) . '/stripe/stripe.php'); // utilities require(dirname(__file__) . '/stripe/util.php'); require(dirname(__file__) . '/stripe/util/set.php'); // errors re...

sql - SqlBulkCopy exception, find the colid -

using sqlbulkcopy , getting exception: received invalid column length bcp client colid 30. i've been banging head against 1 hours. know row having issue, don't know column "colid 30" is. there 178 columns in data table. values seem correct , don't see longer column data types in database. this database holds property listings , has on 3 million records, of fine. is there way pinpoint colid 30 is? or there way view actual sql bcp submitting database? i hope helps solve else's issues well. the error because 1 of string/varchar fields in datatable had semicolon ";" in it's value. apparently need manually escape these before doing insert! i did loop through rows/columns , did: string.replace(";", "char(59)"); after that, inserted smoothly.

php random link from array -

<? $urls = array( array( 'http://cur.lv/xlnc', 'http://cur.lv/xln8', 'http://cur.lv/xln5', 'http://cur.lv/xln4', 'http://cur.lv/xlmv', 'http://cur.lv/xlms', 'http://cur.lv/xllz', 'http://cur.lv/xllp', 'http://cur.lv/xllj', 'http://cur.lv/xlle', 'http://cur.lv/xll9', 'http://cur.lv/xll5', 'http://cur.lv/xlks', 'http://cur.lv/xlkl', 'http://cur.lv/xlke', 'http://cur.lv/xlk4', 'http://cur.lv/xljv', 'http://cur.lv/xlje', 'http://cur.lv/xlj9', 'http://cur.lv/xlj1', 'http://cur.lv/xjxu', 'http://cur.lv/xjxd', 'http://cur.lv/xjx4', 'http://cur.lv/xjwz', 'http://cur.lv/xjw1', ...

java - Is there a way to show action buttons on all devices including ones with menu button? -

the question says all. want search button in top right of screen on devices. know if there hardware menu button action buttons in popup menu @ bottom don't want that. need buttons on actionbar. preferably not overflow button workaround either. you can use actionbarsherlock or new v7 support library support actionbar on older devices, including ones hardware menu key. make search menu item have android:showasaction="always"

osx - Finding Path to Current Desktop Picture -

during pre-sandbox era, there way of finding file path current desktop picture. think 1 use defaults read com.apple.desktop.plist (library > preferences) see path. now, suppose aren't allowed access file more. there alternative way of finding file path current desktop picture? yup, nsworkspace has desktopimageurlforscreen: if you've got 1 screen, can gotten [nsscreen mainscreen] .

asp.net mvc 3 - How To Upgrade Visual Studio To Use MVC 3 Architecture -

i using vs 2010 , want use mvc 3 architecture since need razor c# , not possible in visual studio. availing me mvc 2 c# razor not possible how upgrade vs use mvc 3 razor c# ? you should install asp.mvc 3 use razor view in asp.net. can find on asp.net . open source.

python - Elastic Beanstalk not creating RDS Parameters -

i'm following tutorial in effort create django application on aws. http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_python_django.html i able working local sqlite database trying push app production server. while going through elastic beanstalk init process, choose create rds instance. my mysite/settings.py looks this: import os databases = { 'default': { 'engine': 'django.db.backends.mysql', 'name': os.environ['rds_db_name'], 'user': os.environ['rds_username'], 'password': os.environ['rds_password'], 'host': os.environ['rds_hostname'], 'port': os.environ['rds_port'], } } i should have access rds parameters @ point don't. manage.py file becomes unresponse. (djangodev)laptop-id:mysite user-name$ python manage.py runserver unknown command: 'runserver' type 'manage.py help...

php - Websites hosted on different servers being hacked 'again and again' with same base64 malware codes -

my websites hosted on different servers being hacked again , again same base64 malware codes. when decoded base64 code got link mbrowserstats.com/stath/stat.php. please note: websites core php , wordpress being hacked. placing base64 malware codes in following files - index.php, main.php, footer.php, template files of wordpress (index.php, main.php, footer.php), index.php files in wp-admin, plugins, themes folders etc. i have tried below things websites being hacked again , again. changed ftp passwords changed ftp client filezilla winscp removed malware codes , re-upload files server uploaded old backup files without malware codes disabled magic_quotes_gpc, register_globals, exec & shell_exec functions used index files prevent direct folder access used mysql_real_escape_string function sanitize data insert queries in php websites updated wordpress , plugins latest version installed malwarebytes anti-malware , scanned computer malwares (full scan) confirmed websi...

javascript - different size divs align top left -

css #box1, #box2, #box3, #box4, #box5, #box6, #box7, #box8, #box9, #box10, #box11, #box12, #box13, #box14, #box15, #box16, #box17, #box18, #box19, #box20 { position: relative; list-style: none; float: left; clear:left: } #box1 { width: 60px; height: 60px; background: yellow; } #box2 { width: 80px; height: 50px; background: blue; } #box3 { width: 40px; height: 60px; background: red; } #box4 { width: 200px; height: 150px; background: green; } #box5 { width: 60px; height: 100px; background: red; } #box6 { width: 70px; height: 30px; background: blue; } #box7 { width: 40px; height: 80px; background: yellow; } #box8 { width: 90px; height: 60px; background: red; } #box9 { width: 50px; height: 80px; background: blue; } #box10 { width: 40px; height: 60px; background: yellow; } #box11 { width: 60px; height: 60px; background: yellow; } #box12 { ...

c++ - Grabbing the mouse cursor in GLFW -

my question if glfw has easy way of 'grabbing' mouse cursor. sdl has grab cursor function clamps mouse inside window area. glfw have equivalent sdl_wm_grabinput? if want system cursor visible , restricted window no, not possible. however, if want system cursor grabbed , hidden, example if wish draw own cursor or implement free-look camera, can use disabled cursor mode. in case, see glfwsetinputmode , glfw_cursor_disabled . mouse input act if cursor unrestricted, in fact unable leave window until change mode or window loses focus.

c# - Problems getting XML content -

i'm trying content current loading page using awesomium. if page xml(rss) result incorrect. test program demonstrate problems using system; using system.diagnostics; using system.threading; using system.threading.tasks; using awesomium.core; namespace awesomiumtest { class program { static void main(string[] args) { webcore.initialize(new webconfig() { loglevel = loglevel.none }); string result; //example #1 //ok writepagetoconsole("http://www.google.com/"); //example #2 //small problem. result has added tags , replace "<" ">" "&lt;" "&gt;" writepagetoconsole("http://social.msdn.microsoft.com/search/es-es/feed?query=vb&format=rss"); //example #3 //big problem. result = 'undefined' !!!!!!! write...

multithreading - C# - Windows Service, thread, timer - not run -

this code windows service...but unfortunately, method mytimer_elapsed() invoked when @ least 60 sec. after starting service. why not start after switching service? public partial class myservice : servicebase { private system.threading.thread myworkingthread; private system.timers.timer mytimer = new system.timers.timer(); protected override void onstart(string[] args) { myworkingthread = new system.threading.thread(preparetask); myworkingthread.start(); } private void preparetask() { mytimer.elapsed += new system.timers.elapsedeventhandler(mytimer_elapsed); mytimer.interval = 60000; mytimer.start(); system.threading.thread.sleep(system.threading.timeout.infinite); } void mytimer_elapsed(object sender, system.timers.elapsedeventargs e) { ..my code prepare binary db files binarydb rdr = new binarydb(); rdr.readfile(...) } } it because timer interval set 1 minute...

powershell - How do I escape the "&" symbol in Sql server -

i have execute following code in query editor exec xp_cmdshell 'sqlps -command "$http=new-object system.net.webclient;$http.uploadstring(\"http://192.168.2.3:8080/thermalmap/dbtest.jsp\",\"param1=somevalue & param2=thriu\")"' it gives me error. but following code working , gives me output exec xp_cmdshell 'sqlps -command "$http=new-object system.net.webclient;$http.uploadstring(\"http://192.168.2.3:8080/thermalmap/dbtest.jsp\",\"param1=somevalue\")"' here in second code passing single parameter , don't error if pass 2 parameter need add "&" symbol , getting error. how can escape "&" symbol here? according this article need escape ampersands this: ^& . unescaped ampersands treated command separators.

c# - Threading (Does these threads exits or aborts itself?) -

i wanted ask clarification program below: foreach (match match in mc) { string link = match.groups["link"].tostring(); if (link.contains("ebay.de/itm/")) { int endindex = link.indexof("?pt"); link = link.substring(0, endindex); if (link != lastlink) { geteanperlink = delegate { getean(link); }; new thread(geteanperlink).start(); } lastlink = link; } } it creates lot of threads when program loops. wanted ask if threads ends or exits itself. or if not, how can abort each of threads created? each thread end when getean method exits. if does, don't have more, thread , thread object go away cleanly. it's possible abort threads, it's not recommended because throws exception in middle of whatever thread doing. recommended way communicate thread want end, can @ convenient place in code.

api - How to programmatically get a list of my LinkShare merchants domains -

i know if there api can use linkshare merchant domain url. merchant search endpoint returns uid , name . according linkshare docs can list of default urls advertisers in program (by joining data 2 apis), still affiliate links on linkshare redirect domains. need write script visit links , return final destination url, grab root domain of url. steps: follow instructions here: http://helpcenter.linkshare.com/publisher/questions.php?questionid=1030 write script in language of choice curl affiliate link , grab curl_getinfo(curl_init(), curlinfo_effective_url); see it's redirecting to. parse response regexp grab root domain http[s]?://([^/]+)

mysql - Select data based on another table -

i have 3 tables, i'll list important columns db_players id | name players id | teamid | careerid db_teams the db_teams id links players teamid. i need run query select rows db_players long db_teams.id isn't in row in players teamid careerid = 1. i've never attempted type of query mysql before, know 2 queries , involve php i'm intrigued whether it's possible pure db query. thanks. edit - simpler now. select dp.first_name tbl_foot_career_db_players dp inner join tbl_foot_career_players p on p.playerid != dp.id p.careerid = 1 the idea want return rows tbl_foot_career_db_players id table isn't present in row in tbl_foot_career_players in column playerid. , tbl_foot_career_players.careerid must equal 1. list db_players not in players career = 1 select d.* db_players d left join players p on p.player_id = d.id , p.career = 1 p.id null

javascript - Read json from php server -

i want read json php server using javascript (not jquery) like xmlhttp.onreadystatechange=function() { if (xmlhttp.readystate==4 && xmlhttp.status==200) { json = xmlhttp.responsetext; json.parse(json, function (key, val) { alert(key + '-'+ val); }); } } in php file do $data = array(); $data['id'] = '1'; $data['name'] = '2'; print json_encode($data); but output is id-1 name-2 -[object object] // why?? how fix thanks if using normal javascript, want loop through properties of object, u can in javascript for in statement. <script> var xmlhttp; 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==2...

html - Navigation, moving second level of my nav few pixels to the left -

i have navigation: http://jsfiddle.net/xdnd9/ it works fine, move fdsa 10 pixels left. if add left: -10px; in there, position in left of screen. if change position relative, crashes list. how position sub-list 10px left? edit: sine see wasn't clear, want move fdsa <- way add following: ul > li { display: inline-block; position: relative; } and ul > li:hover ul{ display: block; position: absolute; left: -10px; } position: relative makes absolute positioning of nested elements being calculated relatively element, left: -10px; no longer moves inner elements next left side of screen. demo

r - draw cube into 3D scatterplot in RGL -

Image
i'm trying add smaller cube/mesh (with specified side length) 3d scatterplot. i'd cube positioned @ origin. how go doing that? i've played around cube3d() can't seem position cube right nor make mesh (so can see data points contains. here's have: library(rgl) x <- runif(100) y <- runif(100) z <- runif(100) plot3d(x,y,z, type="p", col="red", xlab="x", ylab="y", zlab="z", site=5, lwd=15) there cube3d function default returns list object (but not plot it) represents cube spanning x:[-1,1]; y:[-1,1]; z:[-1,1]. if apply color sides, solid default. need make sides transparent 'alpha" (see ?rgl.materials ). if start out plot used: library(rgl) x <- runif(100) y <- runif(100) z <- runif(100) plot3d(x,y,z, type="p", col="red", xlab="x", ylab="y", zlab="z", site=5, lwd=15) c3d <- cube3d(color="red", alpha=0.1) #...

css - Retina Display background-size: cover -

if i'm using background-size: cover , want make sure image looks on retina macbook pro has resolution of 2880x1880, need make image resolution, or need double resolution because it's retina (as in when have image in site @ 800px x 400px displayed @ 400px x 200px ensure looks on retina). .bg { color:#ccc; background-attachment:fixed; background-repeat: no-repeat; -moz-background-size: cover; -webkit-background-size: cover; background-size: cover; margin: 0; padding: 0; } thanks - appreciated. make images approximately resolution of device. want adjust bit browser/webclip chrome final image size bit different. see custom icon , image creation guidelines more information. additional background retina display devices have devicepixelration of 2 - ration of physical pixels device independent pixels. quirks mode : dips abstract pixels used feed information width/height media queries , meta viewport device-wid...

c - Mutex | Spinlock | ??? in LKM -

what should using if (on multicore system) wanted make kernel module function ran 1 core @ time? said in other words, avoid 2 cores running same function @ same time; aka, 1 of cores should wait other 1 finish running function. mutex? spinlock? else? you need use variants of spinlock() i.e raw_spin_lock_irqsave(), raw_spin_lock_irqrestore() ( https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/include/linux/spinlock.h#n188 ), not mutex() cause they're sleep-able, might wake on other cpus. , spinlock make sure code won't executed other cores. it's been documented in linux kernel tree @ documentation/spinlock.txt ( https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/documentation/spinlocks.txt ).

ios - AFNetworking spits out an error, but how can I display it? -

i have app user can authenticate instapaper. need instapaper subscription able this, however, if try log in account isn't subscribed instapaper, want display error them. but when try log in, afnetworking sees successful, displays error console: error: error domain=afnetworkingerrordomain code=-1011 "expected status code in (200-299), got 400" userinfo=0x8374840 {nslocalizedrecoverysuggestion=[{"error_code": 1041, "message": "subscription account required", "type": "error"}], afnetworkingoperationfailingurlrequesterrorkey=https://www.instapaper.com/api/1/bookmarks/list>, nserrorfailingurlkey= https://www.instapaper.com/api/1/bookmarks/list , nslocalizeddescription=expected status code in (200-299), got 400, afnetworkingoperationfailingurlresponseerrorkey=} all i'm using afxauthclient modification of afnetworking. subclassed create custom instapaper api client looks this: #import "...

c++ - Size of a empty Class & Derived Virtual Class -

1.why size of derived4 class shows 8 bytes ?? class empty {}; class derived4 : virtual public empty { char c; }; 2.while size of derived2 class shows 4 byte ?? class empty {}; class derived2 : virtual public empty {}; note sizeof(any_class) implementation-defined. but happens in case. well, using virtual inheritance, implementations use hidden pointer implement feature cost sizeof(pointer) bytes (the pointer stored in derived class itself), plus sizeof members (if any) , plus padding if necessary , plus sizeof base class(es) (which reduced zero, in case of empty base class, due empty-base-optimization). for more detailed answer, search "padding in c++" on site. find lots of topics on it.

actionscript 3 - how to call objects created in a loop? -

newbie question: if create several shape objects in loop, like: var i:int; (i = 0; < 3; i++) { var circle:shape = new shape(); circle.graphics.beginfill(color); circle.graphics.drawcircle(100,100, radius); circle.graphics.endfill(); addchild(circle); } how can call different shapes separately , manipulate properties? seem me have same name? you can access them via index (the order have been put on stage). like: displayobject(getchildat(1)).x = 100; // 1 index (starting @ 0)

c++ - What does throw do when not in used with try and catch? -

what throw when not used try , catch? like: if (isempty()) throw "stack empty, cannot delete"; does printed in console? but when throw contains int or char arguments, thrown catch; happens in case? the c++ runtime have along lines of (this not how looks, can think of working way, unless working on special): void beforemain() { try { int res = main(); exit(res); } catch(...) { cout << "unhandled exception. terminating..." << endl; terminate(); } }

c++ - A dll with a vector of vectors. in one of its classes methods -

in c++ program i'm trying create dll houses functionality of a* algorithm. encounter problem when trying pass map it, first tried use 2d array, limited map sizes, i'm trying use vector in vector , keep hitting odd snag. in dlls .h file: namespace iinterface { class iinterface { public: // sets map static __declspec(dllexport) void setmap(int h, int w,vector<vector<byte>> &myarray); private: static vector<vector<byte>> mymap; } finaly in .cpp have: #include "iinterface.h" #include <windows.h> #include <stdexcept> #include <vector> using namespace std; namespace iinterface { void iinterface::setmap(int h, int w,vector<vector<byte>> &myarray) { mymap = myarray; } } im getting few errors on compilation tho code looks fine me. error c2061: syntax error : identifier 'vector' c:\users\steven\documents\github\schooladvgdproject\game code\deathastardll\iinterface.h 7 1 ...

javascript - How to end() a file stream -

i having weird issue piece of sample code got here , central part being this: server.on('request', function(request, response) { var file = fs.createwritestream('copy.csv'); var filesize = request.headers['content-length']; var uploadedsize = 0; request.on('data', function (chunk) { uploadedsize += chunk.length; uploadprogress = (uploadedsize/filesize) * 100; response.write(math.round(uploadprogress) + "%" + " uploaded\n" ); var bufferstore = file.write(chunk); console.log(bufferstore); console.log(chunk); if(!bufferstore) { request.pause(); } }); file.on('drain', function() { request.resume(); }); request.on('end', function() { response.write('upload done!'); response.end(); }); }); the problem is, file copy.csv not contain after process finished. tried add file.end(); in request.on('end' -callback, did not trick. h...

windows - exception 1001 error while uninstallation -

i encountering error 1001 while un installation of application windows 7. not error snapshot.but same. i tried search solving problem wasn't able find easy , satisfying answer. but friend of mine resolved error. by formatting partitioned un-formatted drives of windows. did partitioning of local drives , installed fresh version of windows didn't formatted , used local drives. contributing somehow in error. so formatted these drives , un installed application.it installed. i shared of because may you. , me in understanding real cause , solution of problem. if understand correctly, partitioned 1 of drives, installed fresh os, attempted uninstall, failed, , resolved issue formatting. chances application attempting uninstall somehow involved area partitioned. possibly attempting read files non-existent since portion of hard drive mapped separate disk. additionally, lack of formatting left important configuration files, seen application, contained data rel...

javascript - Kineticjs to small image -

i have simple code , want set minimum width , minimum height of image, set min. height , min. width, , when comes these limits, tag off want, when click on image, tag appears in different place , can not enlarge photos.. if (width && height) { if (min_width < width || min_height < height) { image.setsize(width, height); } else { group.children[1].hide(); group.children[2].hide(); group.children[3].hide(); group.children[4].hide(); $(".tosmall").dialog({ modal: true, width: 350, height: 180, buttons: { "ok": function() { $(this).dialog("close"); image.setsize(image.width, image.height); console.log(activeanchor.attrs.draggable = false); activeanchor.attrs.x *= 2; activeanchor.attrs.y *= 2; image.off(...