Posts

Showing posts from May, 2010

php - Log in with cURL and echo response with cookie -

i trying write "auto-login" script, uses curl log in specific site , echoing response, user can "bypass" login. (for example, grant one-time logins etc) obviously, using following method, cookie stored on server, not on client, in cookie.txt. i've tried setting $_cookie, won't work, since urls (actually subdomains) of auto-login script , service logged into, different. login works fine. see screen if logged in, clicking link requires login again. any ideas? thanks the code i've used auto-login: <?php $username="email@domain.com"; $password="password"; $url="http://sub.domain-to-login.com/index.php/sessions/login"; $cookie="cookie.txt"; $postdata = "email=".$username."&password=".$password.'&btn_login=login'; $ch = curl_init(); curl_setopt ($ch, curlopt_url, $url); curl_setopt ($ch, curlopt_ssl_verifypeer, false); curl_setopt ($ch, curlopt_useragent, &

How to use multiple random strings in Python / Pyramid? -

so have definition saves user's profile. have 1 success message, rotate between multiple success , error messages the: value = {'result': 'success', 'message': '...'} how go this? @view_config(route_name="profile", request_method='post') def save_profile(self): try: json = self.request.json_body first_name = str(json['firstname']) last_name = str(json['lastname']) organization = str(json['organization']) title = str(json['title']) phones = (json['phones']) emails = (json['emails']) self.profiles.update(firstname=first_name, lastname=last_name, organization=organization, title=title, emails=emails, phones=phones) value = {'result': 'success', 'message': "saved! worry not, nothing sent nsa... far know"} except exception, err: print err value = {'r

plugins - Vim Search with "Current Occurrence / Total Occurrences" Shown at the Bottom -

this question has answer here: show count of matches in vim 8 answers i using * / # search next/previous occurrence of variable or function under cursor. there way display current occurrence , total occurrences of search result @ bottom of vim. example, 1 of 5 when search word in chrome. it doesn't need list occurrences in window, guess should able know occurrences in background. you can use vimgrep open list in bottom :vimgrep foo % :copen :cclose close list. you can use :cnext or :cprevious navigate in list of results. % alias current file name & path. you can use option grepprg , command :grep use system grep. as mentioned sehe, lgrep or lvimgrp possible variable.(with associated lopen , lclose ,...) have @ :help grep see options better you.

ios - Restricting text input to only alpha characters -

i have seen multiple approaches cannot work. i trying restrict text field allow alpha characters entered it. i.e. abcdefabcdef (but of them). here existing method: -(bool)textfield:(uitextfield *)textfield shouldchangecharactersinrange:(nsrange)range replacementstring:(nsstring *)string { // check space/delete if (string.length <=0 ) { if ([self.wordarray lastobject]) { [self.wordarray removeobjectsinrange:range]; [self.tilecollectionview reloaddata]; return yes; } } // check make sure word not above 16 characters, should enough right? if (textfield.text.length >= 16 ) { nslog(@"wooo slow down text above 16"); return no; } else { [self.wordarray addobject:string]; [self.tilecollectionview reloaddata]; return yes; } } at present check space , remove last entry array. if letter accepted add letter object array, else. logic alp

Is it possible / good idea to use Akka for multithreading in a Glassfish EAR? -

context: client server app. @ moment ejb looks like: public class serversidejob { @webmethod(operationname = "launchjob") public string launchjob(@webparam(name = "iduser") string iduser, @webparam(name = "name") string name, @webparam(name = "param") object param) { runnable controller = new jobcontroller(screenname, fof, mm, job); new thread(controller).start(); return "job launched"; } } the job launching several other threads. at point, i'd add possibility client interrupt job. interrupting thread "the outside" quite a dirty affair (i'd have add many more calls per op db that), , prompts me switch akka multithreading. problem: not sure how / if can merge akka logic code of ejb above. how call top actor of hierarchy launchjob function? (ok, surely noob question...) public class serversidejob { @webmethod(operationname = "launchjob") public st

osx - What address families can getaddrinfo return? -

when call getaddrinfo af_unspec , can theoretically return address families likes: af_inet , af_inet6 , maybe appletalk, bluetooth, datalink, netlink addresses... in practice, returns af_inet , af_inet6 on platforms: on freebsd, can return af_inet or af_inet6 (checked in source) on linux, ditto (according glibc manpage) on windows, similarly, "a value of af_unspec ai_family indicates caller accept af_inet , af_inet6 address families." [msdn, getaddrinfo] what other systems? there platforms might other address structures? i'm particularly suspicious of macos - source seems missing opensource.apple.com/source/libc , manpage doesn't say. have unreproducible log file mac test run may indicate getaddrinfo returned other address family. other platforms support aix, solaris, hp-ux. i'm aware can check family in structure returned. can't guess interesting strings , hints might need used non-af_inet(6) results out though. there no guaran

javascript - ValidatorEnable not disabling requiredfieldvalidator -

i have client side script in aspx file enables or disables required field validator based on whether form field visible or not. var oval1 = document.getelementbyid(v1); var oval2 = document.getelementbyid(v2); validatorenable(oval1, true); validatorenable(oval2, false); when alert enabled properties of oval1 , oval2, show correct settings condition - oval1 enabled, oval2 disabled. the problem validators firing. need selectively disable 1 since field isn't visible, it's not required in case. try this... var controlandvalidator = { "controlnamegoeshere" : "0"//validate 1, not validate : 0 }; $(document).ready(function () { // or trigger u want $.each(controlandvalidator, function (index, validate) { var validatorname = document.getelementbyid(index); if (validatorname != null) { validatorenable(validatorname, parseint(validate) == 1 ? true : false);

opengl - How do you apply shader on CCRenderTexture twice? -

i managed apply blur shader on ccrendertexture. works single-pass shader (in case 1 direction). /* ... after initializing ccglprogram ... */ rendertexture->getsprite()->setshaderprogram( shader ); rendertexture->begin(); parallaxnode->visit(); rendertexture->end(); in case program draw horizontally blurred image, image composite made parallax node. if apply vertical blur shader on same ccrendertexture object again, ignore previous applied shader, image end vertical blurring. retrieving cctexture rendertexture right after begin - end block, e.g: rendertexture->begin(); parallaxnode->visit(); rendertexture->end(); cctexture2d * texture = rendertexture->getsprite()->gettexture(); ccsprite * sprite = ccsprite::createwithtexture( texture ); shows sprite still image before shader applied on it. so, how 1 approach ? when , how can retrieve texture has shader applied on ccrendertexture ? can me ?

mysql - selecting multiple rows in one table with different fields -

i have following queries: select count(id) table_1 field_1 = 1 select count(id) table_1 field_2 = 1 select count(id) table_1 field_2 = 1 can done in single query.. 1 table use 3 outputs like: count(id) | count(id) | count(id)<br> 12 | 44 | 55 yes can use result using aggregate function case expression similar following: select sum(case when field_1 = 1 1 else 0 end) field1total, sum(case when field_2 = 1 1 else 0 end) field2total table_1 you add more sum(case...) expression remaining items want total.

node.js - Connection to Mysql from NodeJS on Heroku server -

any idea how can connect nodejs mysql cleardb on heroku? i able connect cleardb mysql runing on heroku navicat, created table called t_users. i'm having problems connecting nodejs heroku. this code, simple: works find until tries connect mysql web.js: var express = require("express"); var app = express(); app.use(express.logger()); var mysql = require('mysql'); var connection = mysql.createconnection({ host : 'us-cdbr-east-04.cleardb.com', user : '', password : '', database : '' }); connection.connect(); app.get('/', function(request, response) { response.send('hello world!!!! hola mundooooo!!!'); connection.query('select 1 + 1 solution', function(err, rows, fields) { if (err) throw err; response.send('the solution is: ', rows[0].solution); }); }); var port = process.env.port || 5000; app.listen(port, function() { console.log("listening

c# - Elegant way of binding combobox in datagrid with a new reference of ObservableCollection -

Image
i have combobox in datagrid i'm binding observable collection to. xaml <usercontrol x:class="ddcscheduler.view.ddcschedule" ... ... <datagrid x:name="scheduledatagrid" itemssource="{binding schedulecollection}" canuserresizecolumns="true" autogeneratecolumns="false" isreadonly="true"> <datagridtemplatecolumn header="holidays" width="auto"> <datagridtemplatecolumn.celltemplate> <datatemplate> <combobox itemssource="{binding relativesource={relativesource findancestor, ancestortype={x:type my:ddcschedule}}, path=datacontext.nationalholidaycollection}" displaymemberpath="holidaycategoryname" selectedvalue="{binding nationalholiday,

python - Custom sort order of list -

i have lists such as: mylist1 = ['alpha', 'green'] mylist2 = ['blue', 'alpha', 'red'] i want sort these 2 lists custom ordered list: ['red','blue','green','alpha'] so mylist1 = ['green', 'alpha'] , mylist2 = ['red','blue','alpha'] how can in python? demonstration : >>> mylist1 = ['alpha', 'green'] >>> mylist2 = ['blue', 'alpha', 'red'] >>> sort_order = ['red', 'blue', 'green', 'alpha'] >>> mylist1.sort(key=sort_order.index) >>> mylist1 ['green', 'alpha'] >>> mylist2.sort(key=sort_order.index) >>> mylist2 ['red', 'blue', 'alpha'] explanation : the key parameter in list.sort causes list determine order comparing key(element) instead of element . example, case-insensitive sort

c++ - Is it possible to use the hardware de-multiplexing for highload network servers? -

for example, asynchronous io using tcp/ip (using posix poll/select or more advanced epoll, kqueue, poll_set, iocp), network driver starts interruption in different ( hardware demultiplexer ) cpu-cores, receives messages , dump them single ( multiplexer ) buffer @ kernel level. then, our thread-acceptor using epoll / kqueue / poll_set / iocp receives single buffer list of descriptors of sockets of messages came , again scatters ( demultiplexer ) across threads (in thread-pool) running on different cpu-cores. in short scheme looks like: hardware interruption ( hardware demultiplexor ) -> network driver in kernel space ( multiplexor ) -> user's acceptor in user space using epoll / kqueue / poll_set / iocp ( demultiplexor ) is not easier , faster, rid of last 2 links, , use "hardware demultiplexor"? an example. if network packet arrives, network card interrupt cpu. on systems today, these interrupts distributed across cores. i.e. work hardware demultiplexer. a

How to create shared formula in Excel via Automation -

i write vc automation program importing type library of excel 2003 , using classes. how create shared formula via automation classes. cannot find property/method in ms document related create shared formula. thanks we can use range.copy creating shared formula. and parameter of method target range. please @ below sample: excel.worksheet objworksheet= (excel.worksheet)globals.thisworkbook.activesheet; excel.range oresizerange; objworksheet.cells[1, 5] = "1.33"; objworksheet.cells[2, 5] = "1.565"; objworksheet.cells[3, 5] = "1"; objworksheet.cells[4, 5] = "1"; objworksheet.cells[5, 5] = "1"; objworksheet.cells[6, 5] = "1"; oresizerange = objworksheet.get_range("e8", "e8").get_resize(missing.value, 1); oresizerange.formula = "=sum(e2:e6)"; objworksheet.range["f1"].formula = "=e1*10&qu

javascript - Highcharts date tick position hiding removing -

Image
i have tried using sorts of combinations of tickinterval, tickpixelinterval label formatter , tickpositioner , haven't been able solve issue. i have chart builder pulls in different feeds , allows user modify date range of feeds before shooting data highcharts , spitting out chart. the problem of time, first and/or last dates cut off. here example: without adjusting margins of chart (which causes chart take less space), how prevent happening? if able determine pixel location of ticks , labels, in theory, hide specific ticks , corresponding labels located outside graph / cut off. thoughts? without looking @ code - there few things can do. rotate labels play around x/y axis labels align them right hopefully 1 of these cause.

Hibernate testing with DBUnit without hbm files -

i'm trying test app uses hibernate dbunit. tests run on in-memory db create-drop strategy. i keep getting nosuchtableexception when dbunit tries feed db. examples found on web of combination (hibernate , dbunit) had database structure declared in *hbm files. is mandatory have hbm files in order integrate hibernate dbunit? cheers! you don't need have hbm files. what's happening dbunit creates in memory db, it's clean db. unable load data. as part of setup code, need initialize hibernate before load data. can issuing call select 1 through hibernate api. force hibernate create tables, call dbunit setup populate them.

java - org.hibernate.TransientObjectException when all @OneToMany are cascade=ALL -

i have small data structure data structure serialize in hibernate using jpa annotations: (below simplified) public class result { @id @generatedvalue(strategy=generationtype.identity) public int id; @onetomany(cascade=cascadetype.all) @ordercolumn("row") @joincolumn("resultid) public list<row> rows } public class row { @id @generatedvalue(strategy=generationtype.identity) public int id; @elementcollection @ordercolumn("col") public list<double> value; } when try persist() result, transientobjectexception. how can be? shouldn't cascade=all take care of this? turns out, i've run quite interaction between hibernate , guava (google collections). in fact, 1 feature of guava needs more explicitly announced. the code sample in question incomplete. relevant (and missing) detail fact had constructor of result took list<list<double>> parameter - being more natural rest of a

javascript - Image in formatSelection markup is broken when sending user to new page on selecting event -

if have markup formatselection includes image , have window.location.href in select2-selecting event, image broken. if remove window.location.href , image works , can seen before new page loaded. $('.select2#topbarsearch').on("select2-selecting", function(e) { window.location.href = 'www.example.com'; }); function selectionformat(data) { var markup = "<table class='search-result'><tr>"; if (data.image !== undefined) { markup += "<td class='data-image'><img style='height: 25px;' src='" + data.image + "'/></td>"; } markup += "<td class='data-info-selected'><div class='data-title'>" + data.title + "</div>"; markup += "</td></tr></table>"; return markup; } the image has verified it's done loaded before re

javascript - Why is Template.mytemplate.rendered getting triggered twice when trying to animate live changes in Meteor.js? -

i have issues figuring out how meteor.rendered works exactly. i'm trying animate live change in meteor, this question does. whenever click on element, want blink. however, template gets rendered twice every time element clicked, in turn triggers animation 2 times. here code: template <body> {{> myitemlist}} </body> <template name="myitem"> <div class="item {{selected}}"> <h4>{{name}}</h4> <p>{{description}}</p> </div> </template> <template name="myitemlist"> {{#each items}} {{> myitem}} {{/each}} </template> javascript template.myitemlist.helpers({ items: function () { return items.find(); } }); template.myitem.helpers({ selected: function () { return session.equals('selected', this._id) ? "selected" : ""; } }); template.myitem.events({ 'click .item' : function () { session.set

javascript - jquery: spaces is added instead of %20 -

i have url (school.php/region%20division). when click anchor tag, should open page have url school.php/region%20division. of moment, page opens url school.php/region division. contains whitespace instead of %20. should keep %20? in advance. here code var url=escape("school.php/"+region+' '+division); //school.php/region%20/division $("a.searchlink").html("<a href="+url+">click here</a>"); you can use encodeuri(uri) function in javascript for eg: <script> var uri="school.php/region%20division"; document.write(encodeuri(uri)+ "<br>"); </script> answer school.php/region%2520division and use it... have encode %20 in url ll give desired output

c# - How can you set legal as the default printing size in an rdlc file? -

i have c#.net reportviewer rdlc file want print in legal size default. no matter print dialog has paper size set letter. unless change legal before printing report cut off. someone suggested setting report size manually or changing units cm inches didn't seem have affect. ideas? this contents of rdlc file: <?xml version="1.0" encoding="utf-8"?> <report xmlns:rd="http://schemas.microsoft.com/sqlserver/reporting/reportdesigner" xmlns="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition"> <body> <reportitems> <subreport name="loadoutreport"> <reportname>loadoutreport</reportname> <parameters> <parameter name="groupingproperty"> <value>grouping</value> </parameter> <parameter name="groupingvalue"> <value>1</value&g

ios - PhoneGap App rejected 10.6 -

our phonegap app got rejected. binary rejected: 10.6: apple , our customers place high value on simple, refined, creative, thought through interfaces. take more work worth it. apple sets high bar. if user interface complex or less may rejected text: "we found following issues user interface of app: did not include ios features. example, appropriate use native ios buttons , ios features other web views, push notifications, or sharing. specifically, noticed app provides consumption of information limited ways users can interact information. appropriate add ios specific ui , functionality rather displaying text , table views." on above first referring interface , , next reffering content/function , app provides informations. the interface clean , simple. it application provides (premium) informations. there several apps in app store work this. i heard including plugin or api can justify app. there no sense in app use of plu

linux - Loading shared libraries with ssh framework -

hi there i'am using sshxcute framework access linux server. idea execute application compiled gcc java project. gcc applications has next dependency: libdl.so.2 => /lib64/libdl.so.2 (0x000000300ca00000) libocci.so.11.1 => /e01/demov7/lib/libocci.so.11.1 (0x00002ac507b33000) libclntsh.so.11.1 => /u01/app/oracle/product/11gr2/lib/libclntsh.so.11.1 (0x00002ac507e2e000) libnnz11.so => /u01/app/oracle/product/11gr2/lib/libnnz11.so (0x00002ac50a459000) libstdc++.so.6 => /usr/lib64/libstdc++.so.6 (0x000000301ec00000) libm.so.6 => /lib64/libm.so.6 (0x000000300c600000) libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x000000301ac00000) libc.so.6 => /lib64/libc.so.6 (0x000000300c200000) /lib64/ld-linux-x86-64.so.2 (0x000000300be00000) libpthread.so.0 => /lib64/libpthread.so.0 (0x000000300ce00000) libnsl.so.1 => /lib64/libnsl.so.1 (0x000000300fa00000) libaio.so.1 => /usr/lib64/libaio.so.1 (0x0000003a92800000) but

haskell - Parse JSON with fieldnames that contain reserved keywords -

i'm trying parse following json aeson. { "data": [ { "id": "34", "type": "link", "story": "foo" }, { "id": "35", "type": "link", "story": "bar" } ] } since there lot of field i'd ignore, seems i should use ghc generics . how write data type definition uses haskell keywords data , type ? following of course gives: parse error on input `data' data feed = feed {data :: [post]} deriving (show, generic) data post = post { id :: string, type :: string, story :: string } deriving (show, generic) you can write own fromjson , tojson instances without relying on ghc.generics. means can use different field names data representation , json representation. example instances post: {-# lan

math - Resolving a Circle-Circle Collision -

Image
i writing software extends circle-rectangle collision detection (intersection) include responses collision. circle-edge , circle-rectangle rather straight-forward. circle-circle has me stumped. for example, let 2 circles collide, 1 red , 1 green, in discrete event simulation. might have following situation: immediately after collide have: here rip , gip locations of circles @ previous clock tick. @ current clock tick, collision detected @ rdp , gdp. however, collision occurred between clock ticks when 2 circles @ rcp , gcp. @ clock tick, red circle moves rvy downward , rvx rightward; green circle moves gvy downward , gvx leftward. rvy not equal gvy; nor rvx equal gvx. the collision occurs when distance between circle centers less or equal sum of circles' radii, is, in preceding figure, d <= ( rr + gr ). @ collision d < ( rr + gr ), need position dps cps before adjusting circles' velocity components. in case of d == ( rr + gr ), no repositioning required

sql server - Estimate size of restored DB -

the amount of free space on machine limited, , i'd know how many dbs can fit on before restoring them. so given .bak file, how can estimate how big restored database on sql server be? this output: restore filelistonly disk = 'c:\path\file.bak'; has size column (in bytes). can perform math extrapolate there, example let's results in column are: 3211264 802816 these in bytes, , expressed in kb (at least how windows explorer exposes it) be: 3211264 + 802816) / 1024 = 3,136 kb and in mb be: 3211264 + 802816) / 1024 / 1024.0 = 3.0625 mb you may want sum of whole column, or may want restore ... move , place different files on different drives if have ability so, in case you'll want consider different files separately.

c# - web service only working sometimes -

i have developed web service in c# , tested through browser in... to test operation using http post protocol, click 'invoke' button. when submit parameter string through browser, works correctly: operation updating database , returning operation completed message. i wrote small application submits identical parameter string web service. small application returns success message sql commands in of web service don't seem have been executed. now, in web-service code, program execution flow such cannot return operation success message without going through sql part (which when parameter string entered through browser). however, small application sending identical parameter string url receives success message without sql sequence being executed. the sql transaction section has start trans , commit , rollback always(?) returning success or otherwise of operation. for reason sql code of service not being executed(?) when parameter submitted program , normal traps

c++ - std::thread in C++11, how to ensure a thread is finished inside a destructor -

i want make sure thread completed before object destructed. here basic example think of: struct user { std::thread worker_thread; ~user() { if (worker_thread.joinable()) { worker_thread.join(); } } }; is correct approach problem? it not correct, join() may throw exception, , don't want let exception escape destructor. herb sutters exceptional c++ in section destructors throw , why they're evil. : observe canonical exception safety rules: never allow exception escape destructor or overloaded operator delete() or operator delete[](); write every destructor , deallocation function though had exception specification of " throw() ."

spring - Implicit dependency between BeanNameAutoProxyCreator and imported configuration -

at company, we're working on aspect-oriented trace interceptor, similar debuginterceptor . we're configuring customizabletraceinterceptor , using beannameautoproxycreator auto-proxy beans aop. the problem we're facing that, when introduce beannameautoproxycreator in configuration: @configuration @import(bconfig.class) @enableaspectjautoproxy public class aconfig { @bean public static beannameautoproxycreator beannameautoproxycreator() { beannameautoproxycreator beannameautoproxycreator = new beannameautoproxycreator(); beannameautoproxycreator.setinterceptornames(new string[] {debug_interceptor_name}); beannameautoproxycreator.setbeannames(new string[] {beans_names_expression}); return beannameautoproxycreator; } } we org.springframework.beans.factory.nosuchbeandefinitionexception: no qualifying bean of type [x], x resteasy proxy. resteasy proxy declared in bconfig . now, if move resteasy proxy bean configuration

selenium - Text is blacked out when taking a firefox screenshot running headless with xvfb -

Image
i have jenkins setup on amazon ec2 , running fine except tiny issue selenium. every time run whole suite of tests (~30 min), selenium gets stuck on test. i've take screenshot @ moment , seems there alert on screen, alert text blacked out. i've run xvfb, started selenium, taken screen capture xwd , converted image imagemagick. i've scoured internet , have no clue. figured out. turns out it's font thing. i've run steps indicated below , can read text. it's still on dark green background, text readable. on amazon ec2 ubuntu instance need to: 1) enable multiverse apt-get open /etc/apt/sources.list editor on ec2 seems multiverse isn't present copied these lines file , saved deb http://us.archive.ubuntu.com/ubuntu/ lucid multiverse deb-src http://us.archive.ubuntu.com/ubuntu/ lucid multiverse deb http://us.archive.ubuntu.com/ubuntu/ lucid-updates multiverse deb-src http://us.archive.ubuntu.com/ubuntu/ lucid-updates multiverse 2)

.net - Is Binary Formatter good for MSMQ? -

i'm using msmq pass around xml. however, i'd make queue more generic, letting accept class instances messages. brings mind need binary formatter. i've been reading binary formatter , msmq. seems using binary formatter, i'm making msmq isn't meant do. in other words, i'm passing binary based data on msmq when wants instead light , string based. or have wrong? what i've read more complex types of data (i.e., binary), should stored in database. however, presents own issues since data serializable. the data i'm passing isn't stream based. if i'm going leverage msmq, should used strictly string based messages , not binary? it seems using binary formatter, i'm making msmq isn't meant do. you misinformed. in fact, msmq ships own binarymessageformatter class, intended used when want increase speed @ cost of flexibility. the documentation has say: the binarymessageformatter efficient , can used serialize

javascript - AJAX Request with PHP -

i'm working on ajax first time , feel i'm close solving problem need help. have webpage file first below, has input field email address. when user submits, ajax dowork() function should called creates request , processes request. have fixed initial issue of request being created i'm positive correct object has been created based on browser. issue there's no response text being submitted , no email created. goal user enter email, introductory email sent address, when successful, response string should submitted letting user know have been added mailing list , submission has worked. help, appreciated. <?php include('../includes/educateheader.php');?> <script type="text/javascript" charset="utf-8" src="ajax.js"></script> <div class="involve"> <h1>how involved in oec</h1> <span>want become more involved in operation:educate children , don't know how? share email addres

javascript - Magnific popup: getting "The image could not be loaded" and image url is undefined -

i cannot make magnific popup work reason getting "the image not loaded" time. image url "undefined". <div class="album"> <a href="http://lorempixel.com/1024/768/?a=1"> <img src="http://lorempixel.com/168/168/?a=1" /> </a> <a href="http://lorempixel.com/1024/768/?a=2"> <img src="http://lorempixel.com/168/168/?a=2" /> </a> <a href="http://lorempixel.com/1024/768/?a=3"> <img src="http://lorempixel.com/168/168/?a=3" /> </a> </div> <script> $(function() { $('div.album').magnificpopup({ type: 'image' }); }); </script> http://jsfiddle.net/8vtyf/2/ changed code to: $(function() { $('div.album').magnificpopup({delegate: 'a', type: 'image' }); }); as http://dimsemenov.com/plugins/magnific-popup/d

python - Conditional merging in Python3 -

i trying merge variables keys existing in dictionary. here rules: if key exists, increment value counter one. if partial match key exists: a. if variable length smaller key re.search not none, increment value counter 1 b. if variable length larger key , re.search not none, replace key variable , increment counter one if variable exists after still has no match in dictionary, add variable dictionary i have been able accomplish 1, 2a , 2b not sure how add 3. help/suggesstions appreciated. here script in present form: see "turtle" in dict. animals = ["phant", "eleph", "tiger", "turtle", "zebra", "ostrich"] dict = {"horse":1, "elephant":1, "iger":1, "ostrich":1} name in animals: if name in dict: dict[name]=dict[name]+1 else: key, val in dict.items(): if len(name) < len(key):

vb.net - File.Exists(curFile) Error -

i'm using visual studio 2012 vb.net. every time try use if file.exists(curfile) = true then comes error 1 'file' not declared. may inaccessible due protection level. missing api? you need either import system.io or change code if system.io.file.exists(curfile) = true then .

for loop - Tcl script to correct my output -

i have written tcl code gives me output below. close need. code: for { set row 0 } { $row < 3 } {incr row } { set row[expr {$row + 1}] [lindex $sub_list $row] puts "row[expr {$row + 1}] [lindex $sub_list $row]" set pattern_number [llength [lindex $sub_list $row]] puts "pattern_number = $pattern number" set pattern_index [lindex $sub_list $row] {set p 0} { $p < $pattern_number} {incr p} { set pattern[expr {$p + 1}] [lindex $pattern_index $p] puts "pattern[expr {$p + 1}] [lindex $pattern_index $p]" } } output of above code: row1 b c d pattern number = 4 pattern1 pattern2 b pattern3 c pattern4 d row2 p q r s pattern number = 4 pattern1 p pattern2 q pattern3 r pattern4 s row3 w x y pattern number = 3 pattern1 w pattern2 x pattern3 y instead, want code give me output follows: row1 b c d pattern number = 4 pattern1 pattern2 b pattern3 c pattern4 d row2 p q r s pattern number = 4 pattern5 p pattern6 q pattern7 r patte

imageview - I would like to store images of users in the server. (Android) -

i have user's name , picture. cannot find way upload on table in mysql, guess not size. found store in localhost. wouldn't in table, in localhost. using php admin, there simple way or tutorial store it? thanks i suppose want upload images server running on localhost ,in order save image in database table have use blob type if using mysql example. there many tutorial available try : http://androidexample.com/upload_file_to_server_-_android_example/index.php?view=article_discription&aid=83&aaid=106

HTML Image not displaying, while the src url works -

<img class="sealimage" alt="image of seal" src="file:///c:/users/anna/pictures/nikon%20transfer/seals%20project/j3evn.jpg"> that doesn't display image, alt. if go to file:///c:/users/anna/pictures/nikon%20transfer/seals%20project/j3evn.jpg in browser, image displays. i'm hosting on xampp, on windows machine right now. i've tried different browsers, , , without %20 space, know correct way.(it worked both, actually) and know images visible on machine that's hosting it, that's not problem. your file needs located inside www directory. example, if you're using wamp server on windows, j3evn.jpg should located, c:/wamp/www/img/j3evn.jpg and can access in html via <img class="sealimage" alt="image of seal" src="../img/j3evn.jpg"> look www, public_html, or html folder belonging web server. place files , resources inside folder. hope helps!

java - SwitchPreference and CheckBoxPreference in code -

i creating preference page app after api-14, switchpreference available. , use replace checkboxpreference on api14+ devices it easy use res/xml , res/xml-14 correct xml resource however, in coding part, not convenient switching preference according api. public class settingactivity extends preferenceactivity { private checkboxpreference enable; private switchpreference enablev14; @override protected void oncreate(bundle savedinstancestate) { addpreferencesfromresource(r.xml.setting); if (build.version.sdk_int < 14) enable = (checkboxpreference) findpreference(key_enable); else enablev14 = (switchpreference) findpreference(key_enable); } ... } now way use if-clause check build.version , corresponding object process it. quite inconvenient , hard manage code. has smarter way it? maybe set android:key attribute both of switchpreference , checkboxpreference xml, this: <?xml version=&q

html5 - valid data- variables for JavaScript Buttons -

is there list of valid "data-??????" variables , meanings? e.g. data-amount = amount of transaction looking table of variables used make standard buttons javascript. no limit: data-* ; * (lowercase) see documentation

Protcol Buffers - Python - Issue with tutorial -

Image
context i'm working through tutorial: https://developers.google.com/protocol-buffers/docs/pythontutorial i've created files copy , pasting above tutorial issue when run below file in python launcher nothing happens: #! /usr/bin/python import addressbook_pb2 import sys # iterates though people in addressbook , prints info them. def listpeople(address_book): person in address_book.person: print "person id:", person.id print " name:", person.name if person.hasfield('email'): print " e-mail address:", person.email phone_number in person.phone: if phone_number.type == addressbook_pb2.person.mobile: print " mobile phone #: ", elif phone_number.type == addressbook_pb2.person.home: print " home phone #: ", elif phone_number.type == addressbook_pb2.person.work: print " work phone #: ", print phone_number.number # main procedu

asp.net mvc - Hide the column and show the field when edit or add in jqGrid -

i have more colimns in jqgrid . need hide columns(fields) in jqgrod. when edit or add need show fields in jqgrid edit popup or add popup. there property this. code : $("#datasourcegrid").jqgrid({ postdata: { caid: function () { return $('#hdnchnappid').val(); } }, colnames: ['datasourceid', 'title','sort order'], colmodel: [ { name: 'datasourceid', index: 'datasourceid', align: 'left', key: true, editable: false, hidden: true, search:false,width: '10'}, { name: 'datasourcetitle', index: 'datasourcetitle', sortable: true, align: 'left', width: '400',editable: true, edittype: 'text', editrules: { required: true },stype:'text', search:true,searchoptions:{sopt:['eq']}}, { name: 'sortorder', index: 'sortorde

osx - Java Version Error while installing Apache Tomcat -

i know question asked many times never found answer relates question. trying install apache tomcat server on macbook pro. answers answered windows , eclipse. want install , configure server using terminal. problem happening @ last step of installation. getting below error while installing server. know problem java version @ run time, can't fix it. note: have updated java version latest one. please help. exception in thread "main" java.lang.unsupportedclassversionerror: org/apache/catalina/startup/bootstrap : unsupported major.minor version 51.0 @ java.lang.classloader.defineclass1(native method) @ java.lang.classloader.defineclasscond(classloader.java:631) @ java.lang.classloader.defineclass(classloader.java:615) @ java.security.secureclassloader.defineclass(secureclassloader.java:141) @ java.net.urlclassloader.defineclass(urlclassloader.java:283) @ java.net.urlclassloader.access$000(urlclassloader.java:58) @ java.net.urlclassloa

windows - How does NTFS handle the conflict of short file names? -

as described @ http://technet.microsoft.com/en-us/library/cc781134(v=ws.10).aspx , each ntfs file has long file name , corresponding short file name. ntfs can create more 300 000 files under directory, , in such case, short file names conflicts. if have large number of files (300,000 or more) in folder, , files have long file names same initial characters, time required create files increases. increase occurs because ntfs bases short file name on first 6 characters of long file name. in folders more 300,000 files, short file names start conflict after ntfs uses of 8.3 names similar long file names. repeated conflicts between generated short file name , existing short file names cause ntfs regenerate short file name 6 8 times. however, microsoft doesn't answer question: how ntfs handle conflict of short file names? provided under directory d:\tmp\, there more 300 000 files, therefore, there @ least 2 different files short file names both thisis~1.txt,

c - Tic-Tac-Toe AI picks wrong position -

i making c program of tic-tac-toe. trying make ai invincible @ moment have encountered problem. problem ai prints symbol in next available question. why? , how can fix it? here's calling function: void determinmove(char positions[]) { int num, i, currentbestscore, score; currentbestscore = -100; for(i = 0; < 9; i++) { if(positions[i] == ' ') { score = getfuturescoreofmove(positions, 'c'); if(score > currentbestscore) { num = i; currentbestscore = score; } positions[i] = ' '; } } positions[num] = comp; } and other recursive function: int getfuturescoreofmove(char positions[], char turn

vb.net - How do I reload the formatted text into RTB? -

i have rtb in vb.net, , put event handler save formatted text file after encrypting it. however, can't figure out how reload formatting - when open it, shows symbols of formatting instead of formatted text. here's code: dim filename string = textbox1.text file.delete(filename) dim encryptelement new tripledescryptoserviceprovider encryptelement.key = {ascw("b"c), ascw("a"c), ascw("1"c), ascw("r"c), ascw("3"c), ascw("9"c), ascw("g"c), ascw("v"c), ascw("5"c), ascw("s"c), ascw("p"c), ascw("0"c), ascw("l"c), ascw("z"c), ascw("4"c), ascw("m"c)} '128 bit key encryptelement.iv = {ascw("n"c), ascw("b"c), ascw("5"c), ascw("3"c), ascw("g"c), ascw("l"c), ascw("2"c), ascw("q"c)} ' 64 bit initialization vector dim fs

syntax - Custom "let" expression in Scala -

i'd love have let construct similar 1 in haskell in scala. tried few ways, none seems good. here's code: object customlet extends app { val data = (i <- 1 1024; j <- 1 512) yield (i % j) * * (i + 1) - 1 def heavycalc() = { println("heavycalc called"); data.sum } def dosomethingwithres(res: int) = { println(s"${res * res}") 1 } def cond(value: int): boolean = value > 256 // not usable, though it's expression (2x heavycalc calls) def withoutlet() = if (cond(heavycalc())) dosomethingwithres(heavycalc()) else 0 // not expression def letwithval(): int = { val res = heavycalc() if (cond(res)) dosomethingwithres(res) else 0 } // lot of code simulate "let", @ least expression def letwithmatch(): int = heavycalc() match { case res => if (cond(res)) dosomethingwithres(res) else 0 } // not perfect solution // http://stackoverflow.com/questions/3241101/with-statement-equivalent

python - How do I run uwsgi with virtualenv -

i'm developing first real python flask project , set build server deploy "latest build" built on every check-in. i have set startup script start application using uwsgi , part working fine. have started using virtualenv , doing packages installed added project under projectname\flask\lib\site-packages . i'm using nginx web server , config looks this: location / { try_files $uri @graderbuild; } location @graderbuild { include uwsgi_params; uwsgi_param uwsgi_chdir /usr/local/grader/build; uwsgi_param uwsgi_pyhome /usr/local/grader/build; uwsgi_pass 127.0.0.1:3031; } i'm starting uwsgi using this: exec /usr/local/bin/uwsgi --master --socket 127.0.0.1:3031 --wsgi-file restserver.py --callable app --processes 4 --die-on-term --threads 2 >> /var/log/grader-build.log 2>&1 now know if i'm doing right... deploying entire folder build server. don't want install global python modules build work. right or wrong?

javascript - jQuery .text() values are empty - iframe -

i have strange behavior assigning value variable jquery. can't values form .text(). other functions on other sites work. spotify problem. when elements loaded doesn't stuff out. function: function gettrackspotify() { var track; track = $("#radio-artist .outgoing").text() + " - " + $("#radio-track .outgoing").text(); // both elements empty. please check code in pastebin. console.log(track); return track; } i coding 10 hours today, maybe brains burned much, , can't see nothing.. html: <div id="radio-track-info"> <h2 id="radio-track"> <a class="outgoing" href="https://play.spotify.com/album/3g18adjiqo3bnlivzrenb1/track/04o7scgvdejixinhtu4nxl/action/select"> see me </a> </h2> <h2 id="radio-artist"> <a class="outgoing" href="https://play.spotify.com/artist/73sibhcqh3z3nyqhkz7fol"> childi

primefaces - jsf ajax rendered does not work -

i ask why partial rendering primefaces not work. post requests keeping sent, not rerender. <?xml version='1.0' encoding='utf-8' ?> <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:p="http://primefaces.org/ui"> <h:head> <title>facelet title</title> </h:head> <h:body> <p:messages /> <h:form> <table style="width: 100%"> <tr> <td><p:outputlabel for="inp1" value="s1" /></td> <td> <p:inputtext id="inp1" value="#{form.e.s1}"> <p:ajax process="