Posts

Showing posts from August, 2010

cluster computing - qsub array job - get number of tasks -

is possible number of tasks submitted array job? $sge_task_id task number. for example if submit job qsub -t 1-4 my_script.sh i'd 4 . i don't know of automatic variable that, can think of way via torque (i'm betting same arguments work sge or have corresponding arguments). unfortunately, you'd have manually: qsub -t 1-4 my_script.sh -v total_tasks=4 then, within job script you'll have environment variable $total_tasks set desired. doesn't give automatically give information need.

r - subseting in a for loop -

my dataset has 34,000 rows , 353 columns. 1 column location , has 11,000 unique values. want subset dataset within loop. can creating new data frame each subset, want subsets form single data frame. have included sample dataset below structure(list(x = structure(c(1l, 1l, 1l, 1l, 3l, 3l, 3l, 2l, 3l), .label = c("car", "dog", "house"), class = "factor"), y = c(20l, 20l, 20l, 20l, 410l, 410l, 410l, 410l, 60l), z = structure(c(1l, 3l, 8l, 1l, 7l, 5l, 2l, 4l, 6l), .label = c("argentina", "berlin germany", "buenos aires argentina", "dublin ireland", "from austria", "germany", "in transit germany", "river plate argentina"), class = "factor"), k = structure(c(1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l, 1l), .label = "a", class = "factor")), .names = c("x", "y", "z", "k"), class = "data.frame", r...

c++ - Finding cluster info of a file -

i've been trying find information on file using createfile() , deviceiocontrol(). keep running error_handle_eof understanding means starting virtual cluster number past end of file though starting @ 0. here few snippets of code, let me know if guys have idea what's going wrong. handle hfile = invalid_handle_value; //drive or file checked lpwstr txtfile = l"text.txt"; //text file hfile = createfile(txtfile, //target file generic_read | generic_write, //read , write file_share_read|file_share_write,//allows sharing of read , writes null, //security prevents child process inheriting handle open_existing, //open file or drive if exist file_attribute_normal, //default settings files null); //template file generiv re...

python - "Could not run curl-config: [Errno 2] No such file or directory" when installing pycurl -

i'm trying install pycurl via: sudo pip install pycurl it downloaded fine, when when runs setup.py following traceback: downloading/unpacking pycurl running setup.py egg_info package pycurl traceback (most recent call last): file "<string>", line 16, in <module> file "/tmp/pip-build-root/pycurl/setup.py", line 563, in <module> ext = get_extension() file "/tmp/pip-build-root/pycurl/setup.py", line 368, in get_extension ext_config = extensionconfiguration() file "/tmp/pip-build-root/pycurl/setup.py", line 65, in __init__ self.configure() file "/tmp/pip-build-root/pycurl/setup.py", line 100, in configure_unix raise configurationerror(msg) __main__.configurationerror: not run curl-config: [errno 2] no such file or directory complete output command python setup.py egg_info: traceback (most recent call last): file "<strin...

asp.net - Disabling caching for MVC Controller Action -

i know can write custom actionfilter asp.net mvc controller action set headers in response disable caching. my question is, there out-of-the-box actionfilter in mvc bcl this? or must have create own custom one? you can use [outputcache] filter: [httpget] [outputcache(location = outputcachelocation.none, nostore = true)] public actionresult index() { // .... return view(); } see msdn

google chrome - flex: 0 0 using new css flexbox -

in chrome set child element of display: flex element flex: 0 0 . took mean no stretching or shrinking, shrinks 0 pixels. 0 have different meaning stretch , shrink , or bug in chrome? edit here's fiddle http://jsfiddle.net/bpk4q/ you want flex: none (which special value that's equivalent flex: 0 0 auto ). the value you're using, flex: 0 0 (without 'auto'), implies flex-basis of 0%, indeed tends make things 0-sized (given flex-grow value 0). quoting flexbox spec flex shorthand: <‘flex-basis’> [...] when omitted flex shorthand, specified value 0%. http://www.w3.org/tr/css3-flexbox/#flex-property so, anyway, sounds want flex: none .

php - Html body tag how to link to default html page -

i making cms software, , need php generate pages, of content on pages same, wondering possible link body tag default html page. example have html page <body> <h1> hello </h1> </body> , pages php generate have content. did searching , found 1 question did not have detailed answer, , tried creating html page(for example called page.html) <body> <h1> hello </h1> </body> , make php generate body using <body src="page.html"></body no luck. thanks in advanced remember can include files in php, can include , push html files piece piece. for example, header.html : <html><body><h1>hello</h1> footer.html </body></html> in php, can : include header.html include unique_page_content_here include footer.html many mvc frameworks allow easily

windows runtime - WinJS webpage inside webview returns 0x80070005 on ajax call that uses cors -

we have winjs apps shows web site inside webview control, webpage loads fine every ajax call fails 0x80070005 access denied error . tried adding " internet (client) ", " internet (client/server) " , " private networks " capabilities app without success. the calls use cors allow calling multiple domains, site is working fine on every desktop browser , on ie inside modern environment. however, when site running inside webview control, preflight request runs, despite server being responding status code 200, real request never being sent. we can see using fiddler, here preflight request: options /queries/querycontentareas/getavaliablecontentareas http/1.1 accept: */* origin: https://myapp.demo.es access-control-request-method: access-control-request-headers: accept, authorization ua-cpu: amd64 accept-encoding: gzip, deflate user-agent: mozilla/5.0 (windows nt 6.3; win64; x64; trident/7.0; msapphost/2.0; rv:11.0) gecko host: myappapi.demo.es content-...

java - How to end a loop when the value is 0? -

how loop go infintly have end when value reaches 0? want process end when int money reaches 0. not familiar loops sorry if question dumb. system.out.println(list.get(0).array[3]); (int = 10; <= 1; = - money) { system.out.println("enter in vaule want bet out of $" + money + ""); string moneyvalue = input.next(); int = integer.parseint(moneyvalue);// user input // amount of money want // bet int x = money;// total money if (i > x) { system.out.println("please enter acceptable value 1-" + x); } if (i <= x) { system.out.println("which horse want win, enter in 1-5"); string horsechoice = input.next(); int randomhorse = (int) (math.random() * 5 + 1); int horsechoice1 = integer.parseint(horsechoice); system.out.println(randomhorse); if (horsechoice1 == ra...

reporting services - SSRS Tables - Grouping Part Numbers without showing properties until list is dropped down -

i wondering if possible have ssrs table group part number , preceding field's values show after click on drop down? have list grouped part numbers , parts requirements show on same line. how this: |part number||requirement|value| -------------------------------- +ab1 dropped down this: |part number||requirement|value| -------------------------------- -ab1 r1 200 r2 100 thanks guys! yes, called toggle. need set toggle visibility grouping rows controlled part number text box. if read following article shows how it: toggling visibility

c++ - Retrieve current century with boost -

i able retrieve current year calling: boost::posix_time::second_clock::local_time().date().year(); but how can extract number of centuries year boost function? what's wrong dividing 100?

ruby on rails - Devise: How to prevent users from seeing other users information -

when user logged in has ability see events attending. action in users controllers following class userscontroller < applicationcontroller before_filter :authenticate_user! def events @title = "events" @event = user.find(params[:id]) @events = @event.event_presence.paginate(page: params[:page]) render 'show_events' end end however user(2) able see events of user(3) changing http adress from: /users/2/events users/3/events so question is, how can make sure user(2) able see events of user(2) , not of user(3). thanks filter on current_user.id in events method instead of params[:id] @event = user.find(current_user.id) however, better way have special route doesn't include id get 'events' => 'users#events', as: :users_events and use so = link_to 'events', users_events_path

Why does git-describe prefix the commit ID with the letter 'g'? -

typical output of git-describe looks like some-tag-32-gf31f980 where some-tag tag name, 32 means described commit 32 commits after commit tag, , gf31f980 means commit id uniquely abbreviated f31f980 . my question g in gf31f980 . why there? first thought inserted disambiguate parsing of output of git-describe . can't think of case in helps have it. example, 32 component might omitted, , there no way know output above describes commit 32 commits after tag some-tag , rather commit at tag some-tag-32 . g doesn't this. a regex match extract commit id can search /-g([0-9a-f]+)$/ . there no easy way simplify this; can't /-g(.*)$/ example because might erroneously match g in tag name. without g still /-([0-9a-f]+)$/ , g isn't helping there. non-regex parsing processes behave similarly. the g generated explicitly; relevant source code (around line 240 of builtin/describe.c ) is: static void show_suffix(int depth, const unsigned char *sha1) { ...

ios7 - UIWindow shows the status bar - can't make it go away -

i have ios 7 app. uses key view controller-based status bar appearance set yes each view controller controls appearance of status bar. of course, in case ios ignores calls uiapplication 's setstatusbarhidden: , it's variants. problems starts when show uiwindow on uiviewcontroller sets status bar hidden. uiwindow becomes visible, status bar appears, , can't hide it. assuming status bar hidden using -(bool)prefersstatusbarhidden , run following piece of code, status bar re-appears, , can't turn off. suggestions, anyone? static uiwindow* w = nil; // testing code, makes sure w not autodestruct... if (!w){ cgrect r = [[uiscreen mainscreen] bounds]; w = [[uiwindow alloc] initwithframe:r]; w.backgroundcolor = [uicolor greencolor]; } [w makekeyandvisible]; // colors screen green, shows status bar

sql server 2008 - Which of these two have higher performance: ODBC Connection or SQL Connection? -

i have application uses fedex api integration. application using odbc connection connect sql server.it's large data , takes long time fetch data , perform operation. there can change in performance if use sql connection? in simple , of 2 have faster performance? odbc: odbcconnection conn2 = new odbcconnection(); conn2.connectionstring = @"dsn=excel files;dbq=" + lfilename + ";driverid=1046;maxbuffersize=2048;pagetimeout=5"; sql: sqlconnection con=new sqlconnection (); con.connectionstring ="data source=myserveraddress;initial catalog=mydatabase;integrated security=sspi; user id=mydomain\myusername;password=mypassword;" i'm going assume you're asking if .net framework data provider odbc faster using native sql server provider, rather asking if odbc driver sql server faster .net provider sql server. generally, you'll find using native provider database faster using ...

javascript - Node JS: Listening for HTTPS POST JSON Requests -

i have network server posting information me json payloads specific url endpoint. the specification states need standup https server can listen post json requests. i've created simple node js listener shown below. i can confirm request hitting endpoint, when logged, appears garbled data. can please tell me if i'm missing parameter in script preventing json decoding happening correctly? var express = require('express'); var http = require('http'); var https = require('https'); var fs = require('fs'); var logger = require('logger'); var bodyparsernew = require('body-parser'); var application_root = __dirname; var path = require("path"); var util = require('util'); var options = { key: fs.readfilesync('./privatekey.pem'), cert: fs.readfilesync('./server.crt') }; var app = express(); app.set('port', process.env.port); app.use(express.static(path.join(__dirname, 'site...

Multiple SendDTMF extension in asterisk -

good day, need type extension after dial, wrote macros , use in dial command, example: dial(local/123123@outbound-allroutes,,m(sendnum^5^123) [macro-sendnum] exten => s,1,wait(${arg1}) exten => s,n,senddtmf(${arg2}) 
 but need type several ext. numbers, how can that? i guessed pass more params in macros @ first param count of ivr steps, , other params options steps in macros process params in loop, example: dial(local/123123@outbound-allroutes,,m(sendnum^2^5^2010^6^123) and macros this: macro-sendnum] exten => s,1,set(times=${arg1}) exten => s,n,set(i=0}) exten => s,n,while($[${i} < ${times}]) exten => s,n,set(i=$[ ${i} + 1 ]) exten => s,n,wait(${arg$[${i} + 1]}) exten => s,n,senddtmf(${arg$[${i} + 2]}) exten => s,n,endwhile but doesn't work. please me? thank in advance , sorry bad endgish. pro-sip*cli> core show application senddtmf -= info application 'senddtmf' =- [synopsis] sends arbitrary dtmf digits ...

ios - Split NSString from first whitespace -

i have name textfield in app, both firstname maybe middle , lastname written. want split these components first whitespace, space between firstname , middlename/lastname, can put model. for example: textfield text: john d. sowers string 1: john string 2: d. sowers. i have tried using [[self componentsseparatedbycharactersinset:[nscharacterset whitespacecharacterset]] firstobject]; & [[self componentsseparatedbycharactersinset:[nscharacterset whitespacecharacterset]] lastobject]; these work if have name without middlename. since gets first , last object, , middlename ignored. how manage accomplish want? /*fullnamestring nsstring*/ nsrange rangeofspace = [fullnamestring rangeofstring:@" "]; nsstring *first = rangeofspace.location == nsnotfound ? fullnamestring : [fullnamestring substringtoindex:rangeofspace.location]; nsstring *last = rangeofspace.location == nsnotfound ? nil :[fullnamestring substringfromindex:rangeofspace.location + 1]; ...the ...

javascript - Writing MongoDB result to file using native Node.js driver -

i trying write results of mongodb query file using native node.js driver. code following (based on post: writing files in node.js ): var query = require('./queries.js'); var fs = require('fs'); var mongoclient = require('mongodb').mongoclient; mongoclient.connect("mongodb://localhost:27017/test", function(err, db) { if(err) { return console.dir(err); } var buildscoll = db.collection('blah'); collection.aggregate(query.test, function(err, result) { var jsonresult = json.stringify(result); //console.log(jsonresult); fs.writefile("test.json", jsonresult, function(err) { if(err) { console.log(err); } else { console.log("the file saved!"); } }); }); collection.aggregate(query.next, function(err, result) { var jsonresult = json.stringify(result); //console.log(jsonresult); db....

c++ - nCk modulo p when n % p or k % p == 0 -

i'm trying solve coding challenge on hacker rank requires 1 calculate binomial coefficients mod prime, i.e. nchoosek(n, k, p) i'm using code answer works first 3 sets of inputs begins failing on 4th. stepped through in debugger , determined issue arises when: n % p == 0 || k % p == 0 i need know how modify current solution handle specific cases n % p == 0 or k % p == 0. none of answers i've found on stack exchange seem address specific case. here's code: #include <iostream> #include <fstream> long long factorialexponent(long long n, long long p) { long long ex = 0; { n /= p; ex += n; }while(n > 0); return ex; } unsigned long long modularmultiply(unsigned long long a, unsigned long long b, unsigned long p) { unsigned long long a1 = (a >> 21), a2 = & ((1ull << 21) - 1); unsigned long long temp = (a1 * b) % p; // doesn't overflow under assumptions temp = (temp << 21) % p;...

python - Which regular expression to use to exclude certain ending in string? -

i have 2 slugs, capture one. struggle exclude second has added # plus text. here 2 slugs: slugs = ['/sub/12345678', '/sub/12345678#is'] and here tried python's re : cleaned_slugs = [] in slugs: slug_check = re.match('/sub/[0-9]{8}[^#]', i).group(0) cleaned_slug.append(slug_check) when try out regex on pythex , selects first slug. what wrong? btw: know for loop not elegant way. appreciate shorter answer… if want sub included , 1 without "#": slugs = ['/sub/12345678', '/sub/12345678#is'] cleaned_slugs = [] in slugs: patt= re.search(r'/sub/[0-9]{8}$', i) if patt: cleaned_slugs.append(patt.group()) cleaned_slugs ['/sub/12345678']

python - Unble to use strip method -

here's input: vendor: seagate product: st914602ssun146g revision: 0603 serial no: 080394enwq size: 146.81gb <146810536448 bytes> my code: iostat_cmd = client.executecmd('iostat -en '+disk+'|egrep \'vendor|size\'') vendor = re.search(r'vendor:(.*)product:',iostat_cmd) vendor = str(vendor.groups()).strip() product = re.search(r'product:(.*)revision:',iostat_cmd) product = str(product.groups()).strip() revision = re.search(r'revision:(.*)serial no:',iostat_cmd) revision = str(revision.groups()).strip() serial = re.search(r'serial no:(.*)',iostat_cmd) serial = str(serial.groups()).strip() size = re.search(r'size:(.*)<.*>',iostat_cmd) size = str(size.groups()).strip() the problem is, it's not converting result of groups() string, why strip() doesn't anything. want remove leading , trailing whitespaces. ...

ios - UICollectionView cell can't be selected after reload in case if cell was touched during reloading -

i use uicollectionview display server-related information. uicollectionview allows cells selection display nested data. unfortunately if user touches , holds cells during app calls [collectionview reloaddata] cell doesn't react on touches anymore ( collectionview:didselectitematindexpath: method isn't called). can select cells except one. i created simple application can reproduce problem: link any ideas how fix it? looks bug (i believe there similar issue cell.selected = yes without -selectitematindexpath:animated:scrollposition: caused cell unable unselected) however if this: [self.collectionview reloaditemsatindexpaths:[self.collectionview indexpathsforvisibleitems]]; instead of [self.collectionview reloaddata] working expected. update: found the answer of issue mentioned above another update: appears indeed bug. tested original project on ios8 simulator , issue resolved.

Perl - Using a Variable that is inside an if statement -

i've been putting perl script defines variable, , via if statement assign new value variable. i want use last assigned value if statement , reference somewhere else outside if altogether. it appears when referencing it uses original value. here's code: ## variables $filename = $input[0]; open $info, $datafile or die "can't open <$datafile> reading $!"; { while (my $line = <$info>) { chomp $line; @input = split(':', $line); chomp(@input); $filename = $input[0]; $permit = $input[1]; $filesize = -s "$tiff_dl_location/$permit\_$filename"; $short_permit = substr($permit, 0, 2); ### debug ### print "$filename / $permit / $ftpbase/$short_permit/$permit/$filename\n"; $ftp = net::ftp::throttle->new( "example.com", megabitspersecond => $throttlelvl, debug => $debuglvl ) or die "cannot connect: $@"...

javascript - jQuery .attr returns undefined -

i have html element .replylink , input field type hidden has value (in case 462). want able value of value attribute of input .hddnscrapid when click on .replylink element. html: <div class="scrapitemparent"> <input class="hddnscrapid" type="hidden" value="462"/> <img class="scrapprofilepic" src=" static/img/user/personalprofilepicture/mod_50_50/150972db1a0c9e863746c12797398b6e40ae05c8.jpg" /> <div class="scrapcontent"><br /> <video class="scrapvideo" controls> <source src="../../../scrapll_m/static/vid/4045e7944d8ea8f10dd4826a1e1595a7cef73b0c.mp4" type="video/mp4"> </video><br /> <span class="scraptime">2014-05-27 16:51:22<br />erol simsir <a class="replylink" href="javascript:void(0);">reply</a> <a c...

ios - Bad url exception when using accented characters in url -

i using afnetworking fetch data server. when there accented character in url error this: userinfo={"nsunderlyingerror"=>#<__nscferror:0xfd3aa70, description="bad url", code=-1000, domain="kcferrordomaincfnetwork", userinfo={"nslocalizeddescription"=>"bad url"}>, "nslocalizeddescription"=>"bad url"}> however, when try url browser (chrome), backend api returns results fine. here sample url i'm trying: http://localhost:9000/my/jalapeños a url requires encoded. given example string representing uri, it's wrong. you may take @ nsurlcomponents (available osx >= 10.9 , ios >= 7.0) , rfc 3986 .

regex - HOW TO EXTRACT LIST 1 FROM LIST2 in Bash/Unix? -

i have 2 list. need extract rows have first list row elements second list. looking right syntax read 1 list , other , extract list 1 2 based on regex. looking exact text match. output include whole row list2 well. thanks. list 1 in text file: abc efg hij klm list 2 in text file: tttt;kkkkkkk;ooooo;efg dalfjkhd;hij;ppp gsfdhgjh;fhajdjfkasljk;abc;asdkfhjaskabc;fa;lkdja abc;hhhhh;llll dddd;lllll ppppppppp:rrrrrrrrrradjkfjadl;fireuqwoepiruqwepiormvndfkgjs; hflahflakjdfhalksdfhfjaoeirfjaklf;sdfgsfgs desired output..the text in list 1 found ..space , row found in list 2.: efg tttt;kkkkkkk;ooooo;efg hij dalfjkhd;hij;ppp abc gsfdhgjh;fhajdjfkasljk;abc;asdkfhjaskabc;fa;lkdja abc abc;hhhhh;llll try grep -f grep -f list1 list2 man grep -f file, --file=file read 1 or more newline separated patterns file. empty pattern lines match every input line. newlines not considered part of pattern. if file empty, nothing matched. edi...

php - wordpress pagination url first page -

i using paginate_links on website. when clicked number 2 url chage mywebsite.com /page/2 . cicled pagination page number 1 , site url show mywebsite.com /page/1 . want remove /page/1 on home page firs page. this issue home page.category page working good. ex : <<prev | 1 | 2 | next >> anyone can me ? paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '/page/%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => $wp_query->max_num_pages, 'prev_next' => true, 'prev_text' => __('prev page'), 'next_text' => __('next page'), 'type' => 'array' ) ); if yoursite.com/page/1 , yoursite.com same, why don't use jquery change href attribute of pagination links? $(".paginatio...

pjax - Loop through HTML elements string and insert with jquery -

i using rails , jquery. on button hit i'm returning results partial. $(".blog-posts ul").append("<%= j render('blog/posts')%>").hide().fadein(400); the results are: "<li class=\"post item\"><div class=\"overlay\"><h5><a href=\"/blog/post-slug\">post title<\/a><\/h5><\/div><\/li> <li class=\"post item\"><div class=\"overlay\"><h5><a href=\"/blog/post-slug\">post title<\/a><\/h5><\/div><\/li> <li class=\"post item\"><div class=\"overlay\"><h5><a href=\"/blog/post-slug\">post title<\/a><\/h5><\/div><\/li>" as can see returns string trying grab every li element html , append ul can't seem working. i've tried multitude of things, similar this $('li', $("<%= j render(...

ruby on rails - how to make devise admin see everything? -

i have scoped current_user eg: @integrations = current_user.integrations.all for trouble shooting, want admin see users. have boolean on user model admin: true to around admin seeing everything, keep doing this: def index if current_user.admin? @integrations = integration.all.includes(:user) @reports = report.all else @integrations = current_user.integrations @reports = current_user.reports end end i feel there easier way... suggestions? thanks! you maybe abstract admin check protected/private method in user controller: def is_admin current_user.admin? end and @ top of controller, place before action catch whatever methods want: class userscontroller < applicationcontroller before_action :is_admin, only: [:index, :show] # rest of code end or class userscontroller < applicationcontroller before_action :is_admin, except: [:destroy] # rest of code end

fortran - Error: Non-numeric character in statement label at (1)? -

i wrote following 2 lines in fortran c23456789 real h3 = 0 h3=h*h*h and received following errors gdb : ljmd.f:186.5: real h3 = 0 1 error: non-numeric character in statement label @ (1) ljmd.f:187.5: h3=h*h*h 1 error: non-numeric character in statement label @ (1) ljmd.f:187.6: h3=h*h*h 1 what proper way create , use new variables in middle of else's fortran program? c23456789 label of current column used in program. this in random fortran tutorial. expect have fixed source form. statement must start @ column 7 or farther. also, real h3 = 0 isn't legal in free form source fortran , different thing in fixed form (see @francesalus' comment). , in case there no reason initialize var...

c# - Xamarin.iOS system exception -

Image
i getting error shown on picture while trying debug on device. could explain means , possibly how fix it? i not have button called "logindknap" thanks, look if have removed interface builder connections code. if have removed connection in code can still have referencing outlet in interface builder. open storyboard file , check not have references components logindknap. save rebuild wrapper in xamarin.

php - Magento load product attributes by group? -

is there way foreach loop , loop through product attributes in attribute group in magento? please check screenshot. example, wanna loop through values in attributes of design group. https://s3.amazonaws.com/uploads.hipchat.com/62230/429611/8eocq5jqckvukjr/screen%20shot%202014-05-29%20at%204.10.10%20pm.png thanks no there no built in function return array of product attributes organized group. 1 of missing functionalities. need create in helper or block class. [edit] it looks wrong. there method return attributes given group. in mage_catalog_model_product::getattributes() . first argument there group id. can this: $groupid = mage::getmodel('eav/entity_attribute_group')->getcollection() ->addfieldtofilter('attribute_set_id', array('eq' => $_product->getattributesetid())) ->addfieldtofilter('attribute_group_name', array('eq' => 'general')) ->getfirstitem()->getid(); foreach($_produc...

sql server - .NET, the SqlConnection object, and multi-threading -

we have application uses sql server 2008 r2 database. within application, calls database made using sqlconnection object. this sqlconnection object initialized once, first time accessed, , re-used throughout application. action use following: protected _cn sqlconnection = nothing ... protected sub open() if _cn nothing _cn = new sqlconnection(_sqlconn) end if if _cn.state = connectionstate.closed orelse _cn.state = connectionstate.broken _cn.open() end if end sub this works fine during normal execution of program. however, there few portions of application executed in multi-threaded fashion. when 1 of these parts executing, frequent errors occur if other actions made. after digging bit, realised because there times 2 different threads both attempted use same sqlconnection object. so, after identifying problem, need find solutions. obvious solution re-create sqlconnection object every time database call requires 1 - in case, never sha...

angularjs - Is there any better way for creating by code a directive object? -

angular.element('<my-directive></my-directive>') why can not name of directive ? seems strange write html line inside js... any better way creating instance of directive in memory? a common pattern writing directives this. angular.module('myapp.directives', ['myapp.services']) /* toggleclass generic directive toggling class directly on element or specifying toggle-target option eg. toggleclass="{class: 'open', target='.element'}" */ .directive('toggleclass', function(){ return { restrict: 'a', link: function(scope, element, attrs){ element.on('click', function(){ var ops = scope.$eval(attrs.toggleclass); // if toggle-target set if(ops.target){ element = angular.element(document.queryselector(ops.target)); ...

Bootstrap and iFrame google map -

i've used bootstrap template ("stylish portfolio" - http://startbootstrap.com/stylish-portfolio ) make simple portfolio page friend of mine. i should say, enjoy coding in spare time, , such not professional in way, apologize newbieness! :-) anyway, can't figure out how change location of iframe google map embedded in template's html. default set locate twitters hq. that's not want. i need show philadelphia on map, cant work! more specific, exact view map need provide: https://www.google.com/maps/place/philadelphia,+pa/@40.002498,-75.1180329,11z/data=!3m1!4b1!4m2!3m1!1s0x89c6b7d8d4b54beb:0x89f514d88c3e58c1 when @ html code map, have this: <!-- map --> <div id="contact" class="map"> <iframe width="100%" height="100%" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.com/maps?f=q&amp;source=s_q&a...

java - One Controller for different views?(MVC) -

i got app, has homescreen. on homescreen can click buttons, open other views(for music, gallery, video, games etc.). ask myself, if should use 1 controller of these views or 1 controller 1 view. music , video views got same buttons , hyperlinks.the gallery, games , settings views have different ui controls. searched in internet answer, can't found anything, when create new controller. the recommendation use separate controllers. don't have if pages not have lot of functionality on them.

sql - Check if a table has X amount of records -

i have script connects database , inserts data based on form selections function(tx) { ensuretableexists(tx); var firstname = firstnamebox.value; var playingposition = playingpositionbox.value; var sql = 'insert yellows (firstname, playingposition) values ("' + firstname + '","' + playingposition + '")'; tx.executesql(sql); }, what best method search if table has 5 entries. if database has 5 entries reject insert statement , inform user there no space.

single sign on - Test adfs config - after authentification, it's redirected to HTTP 400 -

i'm trying configure ad fs. have following setup active directory forest (windows server 2012 r2) adfs server running windows server 2012 r2 (domain controller) when testing ad fs configuration in ie, after enter credentials on sso page, it's redirected http 400 bad request. happened both logging in administrator , domain user.

preg replace - Warning: preg_replace(): Unknown modifier 'p' in -

when type in search form , click search keyword make / people read first (make) not second (people) this code for($k=$no_words; $k>0 ;$k--) { $w=trim($search_array[$k-1]); if($w!='') { $result[$i]['description'] = preg_replace('~'.$search_array[$k-1].'~i','<b>'.$search_array[$k-1].'</b>',$result[$i]['description']); $result[$i]['title'] = preg_replace('~'.$search_array[$k-1].'~','<b>'.$search_array[$k-1].'</b>',$result[$i]['title']); } }

javascript - Insert div into random location inside a container of divs -

how insert div random location inside container of divs? similar insert div in random location in list of divs except i'm not using list. right appears inside random container div, not randomly inside container itself: http://jsfiddle.net/frank_o/qxdl3/15/ html: <div class="template" style="display: none;"> <div class="image"> <img src="http://placekitten.com/75/150"> </div> </div> <div class="main"> <div class="image"> <img src="http://lorempixel.com/75/150"> </div> <div class="image"> <img src="http://lorempixel.com/75/150"> </div> <div class="image"> <img src="http://lorempixel.com/75/150"> </div> </div> js: var template = $('.template').find('.image').clone(), target = $('.main'), targetchildren = t...

scala - How can I load Avros in Spark using the schema on-board the Avro file(s)? -

i running cdh 4.4 spark 0.9.0 cloudera parcel. i have bunch of avro files created via pig's avrostorage udf. want load these files in spark, using generic record or schema onboard avro files. far i've tried this: import org.apache.avro.mapred.avrokey import org.apache.avro.mapreduce.avrokeyinputformat import org.apache.hadoop.io.nullwritable import org.apache.commons.lang.stringescapeutils.escapecsv import org.apache.hadoop.fs.path import org.apache.hadoop.fs.filesystem import org.apache.hadoop.conf.configuration import java.net.uri import java.io.bufferedinputstream import java.io.file import org.apache.avro.generic.{genericdatumreader, genericrecord} import org.apache.avro.specific.specificdatumreader import org.apache.avro.file.datafilestream import org.apache.avro.io.datumreader import org.apache.avro.file.datafilereader import org.apache.avro.mapred.fsinput val input = "hdfs://hivecluster2/securityx/web_proxy_mef/2014/05/29/22/part-m-00016.avro" val inu...

python - How do I print a function in a string? -

so trying simple calculation using python 2.7 code follows: print 'in schmooland 9.33356564 times heavier on earth.\n' weight = float(raw_input('how weigh on earth in pounds?\n')) print 'in schmooland weigh' print weight * 9.3356564 print 'in pounds' the output looks though how weigh on earth in pounds? 235423423 in schmooland weigh 2197832185.64 in pounds how print result of weight calculation on same line string print this in schmooland weigh 2197832185.64 in pounds i'm total n00b - help! add comma end of each print line avoid implicit newline: print 'in schmooland weigh', print weight * 9.3356564, print 'in pounds', from print documentation : a '\n' character written @ end, unless print statement ends comma.

GWT client-side image upload & preview -

i using gwt , want upload image , display preview without interacting server, gwtupload lib not way go. after image uploaded , displayed, user can optionally save it. idea send image through gwt-rpc base64 encoded string , store in db clob. is there easy way either gwt or using jsni? this document answers question: reading files in javascript using file apis

javascript - Get GenericSync per Surface or View -

i want scroll list bunch of surface images. when click or touch on surface, want surface object being affected , (like change content ). the way setup below have scrollview -> container -> view -> modifier -> surface . don't know if efficient or not (maybe redundant). cannot exact object triggering event in console.log(data) of each sync object. define(function(require, exports, module) { var engine = require('famous/core/engine'); var surface = require('famous/core/surface'); var containersurface = require("famous/surfaces/containersurface"); var view = require('famous/core/view'); var scrollview = require('famous/views/scrollview'); var transform = require('famous/core/transform'); var modifier = require("famous/core/modifier"); var genericsync = require("famous/inputs/genericsync"); var mousesync = require("famous/inputs/mousesync")...

jQuery Ajax Cross-site scripting -

i know question has been asked (many times) before still can't seem right. i want perform ajax request in jquery , "arbitrary" contents - e.g. may html, text, json, img when perform following infamous no 'access-control-allow-origin' header present on requested resource. origin ' http://mydomain.com ' therefore not allowed access. $.ajax({ url: "http://www.pureexample.com/jquery/cross-domain-ajax.html", // datatype: "jsonp", crossdomain: true, success: function (data) { console.log('success'); console.log(data); }, error: function(request, status, error) { console.log('error on request. ' + request.responsetext); alert('error on request. ' + request.responsetext); } }); i not serving data, cannot on server-side al...

simple form - Rails 4 action routes with simple_form and shallow nested resources -

resources :users, shallow: true resources :shoes end this gives me 2 different routes create , edit user_shoes_path shoes_path in shoes _form.html.erb if leave form tag :url default missing routes error when submit new or updated shoe. if supply url in form can work either new or edit update, can't work both. this works new: <%= simple_form_for :shoe, url: user_shoes_path |f| %> this works edit, fail once tries actual update since redirects /:param_id : <%= simple_form_for :shoe, url: shoes_path(@shoe) |f| %> how can make work both? thanks. you should use <% = simple_form_for [@user, @shoe] |f| %> and let simple_form work... this case, if there @user, simple form use (as new), if there isn't (like edit), simple form won't use it...

Nginx add headers PHP FPM returns an error -

i'm using laravel 4 nginx , php-fpm serving application. the application implements api , i've added open cors rules nginx seem working fine. whenever application throws error, nginx doesn't seem add headers part of response. there way force without having install more headers extension? my config follows: server { listen 80; server_name mediabase.local; root /home/vagrant/mediabase/public; index index.html index.htm index.php; charset utf-8; location / { try_files $uri $uri/ /index.php?$query_string; add_header access-control-allow-origin "*"; add_header access-control-allow-methods "get, options, post, head, delete, put"; add_header access-control-allow-headers "authorization, x-requested-with, content-type, origin, accept"; add_header access-control-allow-credentials "true"; add_header access-control-max-age: 86400; } location = /favicon.ico { access_log...

python - gropuby and remove specified groups in pandas DataFrame -

i have pandas dataframe: df=pd.dataframe({'a':[1,1,2,2,3,3],'b':['c','t','k','c','c','k']}) i need group df , remove groups b ='t'. pandas groupby syntax this? in example answer groups 2 , 3. a groupby/filter work here (filter return groups meet condition). so, example, following: >>> df.groupby('a').filter(lambda x: (x['b'] != 't').all()) b 2 2 k 3 2 c 4 3 c 5 3 k (x['b'] != 't').all() allows keep group if there no rows 't' in column b or write filter following way: create booleen series based on whether row of column b 't'. if sum booleen series, sum greater 0 if of elements 't': >>> df.groupby('a').filter(lambda x: (x['b'] == 't').sum() == 0) b 2 2 k 3 2 c 4 3 c 5 3 k there other ways write filter condition have same flavor.

ruby - Strings that compare equal don't find same objects in Hash -

i have 2 strings appear equal: context = "marriott international world’s admired lodging company fortune 14th yr. via @fortunemagazine http://cnnmon.ie/1kcfzsq" slice_str = context.slice(105,24) # => "http://cnnmon.ie/1kcfzsq" str = "http://cnnmon.ie/1kcfzsq" slice_str == str # => true slice_str.eql? str # => true but when values in hash keys strings, not return same thing in ruby 2.1.0 , ruby 2.1.1: redirects = {"http://cnnmon.ie/1kcfzsq"=>""} redirects.key?(slice_str) # => false redirects.key?(str) # => true what explanation there behaviour? ruby 1.9.3 works expected. this bug in ruby < 2.1.3 $ rvm use 2.1.2 using /users/richniles/.rvm/gems/ruby-2.1.2 $ irb 2.1.2 :001 > context = "marriott international world’s admired lodging company fortune 14th yr. via @fortunemagazine http://cnnmon.ie/1kcfzsq" => "marriott inter...

java - What is differene between secondary namenode and passive namenode -

what other namenode use in highavailabilty of namenode known , other namenodes used in hadoop federation confused hope information solves confusion 1)namenode:: namenode holds meta data hdfs namespace information, block information etc. namenode stores hdfs filesystem information in file named fsimage . updates file system (add/remove blocks) not updating fsimage file , appended edit log, fsimage contains mapping of blocks files , other file system properties called snapshot of namenode. when restaring, namenode reads fsimage , applies changes log file bring filesystem state date in memory. 2)secondary namenode:: the secondary namenode periodically pulls these two(edits nd fsimage) files, , namenode starts writing changes new edits file. then, secondary namenode merges changes edits file old snapshot fsimage file , creates updated fsimage file. updated fsimage file copied namenode. 3)failover namenode or passive n...

hadoop - Calculate Average Count Using MapReduce in HBase -

i have table called log every single row represent single activity , have table structure this info:date, info:ip_address, info:action, info:info the example of data this column family : info date | ip_address | action | info 3 march 2014 | 191.2.2.2 | delete | blabla 4 march 2014 | 191.2.2.3 | view | blabla 5 march 2014 | 191.2.2.4 | create | blabla 3 march 2014 | 191.2.2.5 | delete | blabla 4 march 2014 | 191.2.2.5 | create | blabla 4 march 2014 | 191.2.2.6 | delete | blabla what want calculate average of total of activity based on time. first things compute total activity based on time: time | total_activity 3 march 2014 | 2 4 march 2014 | 3 5 march 2014 | 1 then, want calculate average of total_activity output represent this (2 + 3 + 1) / 3 = 2 how can in hbase using mapreduce? thinking using 1 reducer capable compute total of activity based on time. thanks suggest scalding - it's ...

c++ - How to catch the last line error message by boost::python -

any way catch last line error message python(using msvc2008)? try { boost::python::exec_file( "somescript.py", main_namespace, local_namespace ); return true; }catch(const boost::python::error_already_set &){ using namespace boost::python; pyobject *exc,*val,*tb; pyerr_fetch(&exc,&val,&tb); boost::python::handle<> hexc(exc), hval(boost::python::allow_null(val)), htb(boost::python::allow_null(tb)); boost::python::object traceback(boost::python::import("traceback")); boost::python::object format_exception(traceback.attr("format_exception")); boost::python::object formatted_list = format_exception(hexc, hval, htb); boost::python::object formatted = boost::python::str("\n").join(formatted_list); std::string const result = extract<std::string>(formatted); std::cout<<result<<std::endl; //pop out lot of error mess...

jquery - Get request and query string -

i'm trying information route ajax call. have query strings need fetch in route. $.ajax({ url: '/servers', type: 'get', data: {ip: serverip, port: serverport}, }) .done(function() { console.log("success" + data); }) however, console returns 404. i'm not sure how request in routes. route::get('/servers', function(){ $ip = input::get('ip'); $port = input::get('port'); return $ip . $port; // checking if works }); eventually request router controller, i'm trying ajax request work first. doing wrong? you may try retrieve post/get inputs: $ip = input::get('ip'); $port = input::get('port'); but in case (for query strung) uri should contain them, example: http://example.com/servers?ip=serverip&port=serverport so, pass them url in ajax // query string: ?ip=serverip&port=serverport url: '/servers?ip='+serverip+'&port=...

objective c - iOS 7: in app purchase receipt validation and verification -

i new receipt validation in ios. have implemented in-app purchase successfully. wish include receipt validation part in in-app puchase. my in-app purchase 3 products. want before purchase of each single product in app, receipt validation should performed. for followed following link: official apple developer tutorial i managed receipt data, puzzled after getting receipt data. how send apple server verification , start in-app purchase process? following code: -(void)paymentqueue:(skpaymentqueue *)queue updatedtransactions:(nsarray *)transactions { nslog(@"transactions count : %d",transactions.count); bool flgisproductrestorable=no; (skpaymenttransaction *transaction in transactions) { switch (transaction.transactionstate) { case skpaymenttransactionstatepurchasing: { // show wait view here //statuslabel.text = @"processing..."; nslog(@"processing..."); } break; ...

Search in Array PHP -

i want make search function in following array: array( array("key" => "net_sale", "value" => "net sale crtn"), array("key" => "productive_calls", "value" => "productive calls"), array("key" => "drop_size_value", "value" => "drop size value"), array("key" => "sku", "value" => "sku per bill"), array("key" => "net_amount", "value" => "net amount"), array("key" => "drop_size_crtn", "value" => "drop size crtn"), array("key" => "productive_pops", "value" => "productive pops"), array("key" => "scheduled_pops", "value" => "scheduled pops") ); this functi...