Posts

Showing posts from August, 2011

javascript - Search 2 text fields as 1 field -

i'm search users name , i've properties: firstname , lastname . if had property fullname trivial don't have it. i want search "peter robert" , need combine theses 2 fields 1 before searching. how do it? sounds want "text search" . text indexes can span on multiple fields terms entered searched indexed fields: db.collection.ensureindex({ "firstname": "text", "lastname": "text" }) db.collection.find({ "$text": { "$search": "peter robert" } }) that 1 way handle this. return other matches exact matches have highest score can rank them. alternately, if know getting string "peter robert" in order can "split" , tokenize input: var input = "peter robert"; var parts = input.split(/ /); // splits on space db.collection.find({ "firstname": parts[0], "lastname" parts[1] ]) which pretty basic. or apply $reg...

google chrome - html base tag with different domain from the top domain gives security issue -

i've website displays , edits contents of different web pages adding css codes them. it works this, use curl contents of webpages edit content , add base tag href attribute points url got contents of it. put edited content iframe on website. working year, yesterday noticed error google chrome shows me security warning page. i've tried many things fix problem couldn't fix it. when use base tag different domain top domain, shows warning page. u have idea how can pass problem. have use base tag different domain base tag. it looks google side error :d contact them , problem fixed :)

sqlite - Yii - protected - (403 Forbidden Error) -

is possible change configuration of yii, to: 1- make yii , database accessible outside folder 'protected' 2- send data outside folder 'protected' files inside 'protected' or there other solution ? thank help. it possible since protected folder protected .htaccess file. if eliminate "defensive rules" , have right directory/file permissions, protected folder can made accessible outside. however recommend not this, because direct access protected folder (as name suggests) should made inaccessible standard users.

javascript - Cannot get all possible overlapping regular expression matches -

i have string started: 11.11.2014 11:19:28.376<br/>ended: 1.1.4<br/>1:9:8.378<br/>request took: 0:0:0.2 i need add zeros in case encounter 1:1:8 should 01:01:08 same goes date. tried using /((:|\.|\s)[0-9](:|\.))/g but did not give possible overlapping matches. how fix it? var str = "started: 11.11.2014 11:19:28.376<br/>ended: 11.11.2014<br/>11:19:28.378<br/>request took: 0:0:0.2"; var re = /((:|\.|\s)[0-9](:|\.))/g while ((match = re.exec(str)) != null) { //alert("match found @ " + match.index); str = [str.slice(0,match.index), '0', str.slice(match.index+1,str.length)]; } alert(str); this want: str.replace(/\b\d\b/g, "0$&") it searches lone digits \d , , pad 0 in front. the first word boundary \b checks there no [a-za-z0-9_] in front, , second checks there no [a-za-z0-9_] behind digit. $& in replacement string refers whole match. if want pad 0 ...

ios - objective-c : Use a array to point to another array -

i have 2 mutable arrays. "friendsarray" contains whole list os users , "inviteindex" contains indexes (indexpath.row) of of them (get using uiswitch button table list). the fill inviteindex array as: [inviteindex addobject:[nsnumber numberwithinteger:indexpath.row]]; in order have selected users do: (int =0; i< [inviteindex count]; i++) { myelement *friend =[friendsarray objectatindex:[inviteindex objectatindex:i] ]; nslog(@"button pressed %@", friend.friendid); } but app crash message: [__nsarraym objectatindex:]: index 400931632 beyond bounds [0 .. 4]' i trid used myelement *friend =[friendsarray objectatindex:(nsinteger)[inviteindex objectatindex:i] ]; same result. any please? in advance. [inviteindex objectatindex:i] return nsnumber object. want nsinteger value within nsnumber object: for (int =0; i< [inviteindex count]; i++) { nsinteger index = [[inviteindex objecta...

embedded - rasberry pi B+ not booting for yocto -

i have rasberry pi b+ board , downloaded 12 mb compressed image of yocto link (www.cnx-software.com/raspberry-pi/rpi-basic-image-raspberrypi-20130702123605.rootfs.rpi-sdimg.7z). after decompressing issued following command terminal of ubuntu 14.04 sudo dd if=./rpi-basic-image-raspberrypi-20130702123605.rootfs.rpi-sdimg of=/dev/sdb bs=1m my sd card of 8 gb , attachd machine. now have inserted sd card on board , attached keyboard , monitor it. my issue when give power board nothing comes up. can ?? i guess waiting x server start. rpi-basic-image doesn't provide that. should log rpi ssh. can detect rpi ip scanning ssh servers in subnet. nmap -p 22 --open -sv your_subnet_address/subnet_size example: nmap -p 22 --open -sv 192.168.1.0/24 ayman

pig latin - load with text qualifier -

i trying load datafile in pig latin script, data has 2 columns there text qualifier in 2nd column , sample data below : device_id,supported_tech a2334,"gsm900,gsm1500,gsm200" a54623,"gsm900,gsm1500" a86646,"gsm1500,gsm200" when try loading date below, 2nd column not recognized 1 column devicelist = load 'devicelist.csv' using pigstorage(',') (device_id:chararray, supported_tech:chararray ); how can define text qualifier while loading data set ? try , let me know if need different output format input.txt device_id,supported_tech a2334,"gsm900,gsm1500,gsm200" a54623,"gsm900,gsm1500" a86646,"gsm1500,gsm200 pigscript: a = load 'input.txt' line; devicelist = foreach generate flatten(regex_extract_all(line,'^(\\w+),(.*)$')) (device_id:chararray, supported_tech:chararray ); dump devicelist; output: (device_id,supported_tech) (a2334,"gsm900,gsm1500,gsm200") (a54623,...

mysql - How to store immutable, unique, ordered, lists? -

i have entity millions of instances. each instance has reference ordered list of items . lists have unique no list stored more once. once created, both lists , entity instances immutable. there far more entity instances lists , , database has support fast insertions of entities . so what's insert-efficient, robust, way of storing immutable , unique , ordered lists ? edit: far, i've considered these approaches: 1) lists table has these columns: <list_id> <order> <item> if list #5 contains elements [10,20,30] table contain: 5 1 10 5 2 20 5 3 30 the entity table have item_list_id column references lists table (it's not foreign key since list_id not unique column in lists table - the can solved adding table single column contains valid list_ids ). this solution makes inserts bit tricky it places responsibility enforcing uniqueness of lists on application, isn't great. 2) lists table has these columns: <...

c# - Use system.web.UI.Control.FindControl to retrieve multiple controls -

i've got webpage repeater. have single repeater shows articles <asp:repeater runat="server" id="rptarticles" datasource="<%# currentarticles %>"> inside these articles few checkboxes can use check articles , actions them. to retrieve , return checkboxes have following methods protected readonly property articlerepeater repeater return directcast(findcontrol("rptarticles"), repeater) end end property protected overridable function getselectedarticles() string dim checkboxes htmlinputcheckbox() = dataconvert.findcontrolsbytype(of htmlinputcheckbox)(articlerepeater, true) dim selectedvalues string() = (from cbx in checkboxes cbx.checked select cbx.value).toarray return string.join(";", selectedvalues) end function these methods work @ moment. but want filter articles little bit more have repeater inside initial repeater, filters them , show...

permissions - How to add a group to an ACL in ubuntu -

problem i need give read/write access system group called "mongodb" on usb key that's been formatted ext4. seems command worked, when try have system user write folder, permissions error: 2014-11-11t10:41:19.326-0500 [initandlisten] exception in initandlisten std::exception: boost::filesystem::status: permission denied: "/media/me/mongotest/mongodb", terminating here's command used check group has access: me@medev:~$ getfacl /media/me/mongotest/mongodb/ getfacl: removing leading '/' absolute path names # file: media/me/mongotest/mongodb/ # owner: root # group: root user::rwx group::r-x group:mongodb:rwx mask::rwx other::r-x additional test just prove working, did following: create new user in ubuntu called "test". created new group called testers added test testers. added testers acl list /media/me/mongotest/mongodb folder on usb: me@medev:~$ getfacl /media/me/mongotest/mongodb/ getfacl: removing leading '/...

javascript - select <option> based on a value -

i have following html structure <div> <select> <option value="">select</option> <option value="blue">blue</option> <option value="red">red</option> <option value="orange">orange</option> <option value="green">green</option> </select> <ul> <li>blue</li> <li>red</li> <li>orange</li> <li>green</li> </ul> </div> i want when user clicks <li> , appropriate <option> <select> should selected automatically, attach click event handler each li element takes content of li , uses set value of select element: $('ul > li').on('click', function() { $('select').val( $.trim( $(this).text() ) ); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></scri...

xml - Send HTTP POST followed by GET using same socket -

i trying create perl script should send http post request xml data followed http request using same socket. i tried using lwp::useragent seems it's creating new socket each request. i tried using io::socket i'm not sure how use send xml data. my code: #!/usr/bin/perl use strict; use warnings; use lwp::useragent; use http::request::common; $message = <<'xml'; <includefiltersets> <filterset> <filter> <filtername>version_name</filtername> <operator> <name>in</name> </operator> <value>10.0u</value> </filter> </filterset> </includefiltersets> xml $webpage = "https://www.test.com/abc/cde.xml"; $url = "https://www.test.com"; $ua = lwp::useragent->new; $response1 = $ua->post($webpage, content_type => 'text/xml', content => $message); $response2 = $ua->get($url); as ...

angularjs - Pass expression to directive for transclusion -

i have directive uses template generate typeahead in form associated label , css classes. <div class="form-group" ng-class="{ 'has-success': hassuccess(field), 'has-error' : haserror(field) }"> <label class="control-label" for="{{ field }}"> {{ label }} </label> <input type="text" class="form-control" ng-model="model" name="{{ field }}" id="{{ field }}" typeahead="{{ items }}" required> </div> this created using following markup: <fe-ta model='model.state2' label='state' items='s in states'></fe-ta> the problem expression passed items . following exception: syntax error: token 'in' unexpected token @ column 3 of expression \ [s in states] starting @ [in states]. my directive takes items in isolate sc...

ios - Add padding to UILabel using Auto Layout or layoutMargins? -

Image
this question has answer here: resizing uilabel accommodate insets 6 answers i want add inset between label's frame , text. under possible using layoutmargins ( http://carpeaqua.com/2014/07/24/auto-layout-in-ios-8-layout-margins/ ) have no been able this. i have sample project can see doing (wrong?): https://github.com/runmad/messagingapp if you, subclass uilabel , add uiedgeinsets . in subclass of uilabel this: .m file - (id)initwithframe:(cgrect)frame { self = [super initwithframe:frame]; if (self){ //property in header file can add custom insets per instance of class self.edgeinsets = uiedgeinsetsmake(0, 0, 0, 0); } return self; } -(void)drawtextinrect:(cgrect)rect { [super drawtextinrect:uiedgeinsetsinsetrect(rect, self.edgeinsets)]; } /* w...

c# - Can an interface have a templated method name? -

i know answer no, still confirm. can interface have variable method name? interface ivariablemethodname //something similar <t> { void t(int param); void t(string param); } i have classes require function overload couple functions same parameter different name , have different functionality. there better way instead of making bunch interfaces same content except method name? edited: example class adder { public int add(int a, int b){} public float add(float a, float b){} public decimal add(decimal a, decimal b){} } class subber { public int sub(int a, int b){} public float sub(float a, float b){} public decimal sub(decimal a, decimal b){} } what trying similar examples difference return type class itself. , methods have different functionality. i still not sure understand question completely. however, sure not possible define single interface interface members can take on different names depending on implementing class. gi...

java - Derby included in Tomcat Webapp -

my web app connects derby database - ok. my web app , derby installed separately in tomcat 7 server - ok derby installed using derby.war file being deployed , me moving derby*.jar files tomcat lib directory. my web app deployed exporting war file tomcat webapps directory. i deploy derby without having put jars tomcat lib directory - problem in production environments. my question(s) is/are can derby.war file amended in anyway? - tried adding web-inf/lib directory , putting derby*.jar files in there , re-deploying it. didn't work, removed jars , lib directory. perhaps need else? or is there way of including derby jar files , derby web.xml own web application? tried not in anger, first attempt caused few issues regressed in panic. i admit attempts deploy derby without using tomcat lib directory little rushed , have spent more time researching it. won't have access dev system while, thought i'd ask if be/has been done anyone. trevor you use...

javascript - moment.js: format a date keeping the locale's day, month and year order -

i using moment.js format dates in "country specific" order, using native locale feature. so, example, code print date ordered in netherlands's default: moment.locale('nl'); nldate = moment(); nldate.format('ll'); // "12 nov. 2014" a different locale setting print different order: moment.locale('en'); nldate = moment(); nldate.format('ll'); // "nov 12, 2014" what change format of output string, keeping locale order; example: (nl) 12 nov. 2014 --> 12-11-'14 (en) nov 12, 2014 --> 11-12-'14 sadly, custom format , not able keep locale order: nldate = moment(); nldate.locale('nl'); nldate.format("dd-mm-'yy"); // "12-11-'14" nldate.locale('en'); nldate.format("dd-mm-'yy"); // "12-11-'14" from above get: (nl) 11-12-'14 (en) 12-11-'14 any help? i addressing effort here , here not sure in right direc...

javascript - angularJS window resize issue -

so somehow made memory leak in js. continously resized window of page, , buum, 86% memory usage. out of 16gbs of memory. after shut down had restart pc because still said 72% usage. system takes 17%. so don't understand whats happening there, wanted somehow react when user resizes window because i'd change layout if width less 640px instance. but yea here code. index.html: <div id="wrapper" ng-controller="appctrl" resize> <div class="left-side" ng-class="{ fullw: smallr }">random content</div> <div class="right-side" ng-class"={ fullw: smallr }">random content2</div> </div> the idea , have left , right side, after screen width below 640px, push them under each other attaching .fullw { width: 100% } style them. my directive: .directive('resize', function ($window) { return function (scope, element, attr) { var w = angular.element($window); sc...

c# - cannot await object in the async call -

i have method called dosomething() returns object , time-consuming. use async/await let run in background while gui showing " waiting response... " message. in calling method: task taskdosomething = new task(dosomethingasync); taskdosomething.start(); taskdosomething.wait(); // continue program my dosomethingasync method: private async void dosomethingasync() { object result = await dosomething(); } but getting error: cannot await [objecttype] and [objecttype] type of object have created myself. used object above not confuse reader. please let me know doing wrong , set me free of scattered processing of backgroundworker . i think you've misunderstood how async , await works. if dosomething() long-running method isn't designed asynchrony, want in different thread, e.g. starting separate task: task<object> task = task.run<object>(dosomething); note means dosomething won't able interact ui, it'll on d...

Javascript associavtive array -

i want create array javascript var person = {firstname:"john", lastname:"doe", age:46}; var person = {firstname:"peter", lastname:"toh", age:20}; for example want create person[1].firstname return me john person[2].firstname return me peter how declare javascript make 2 element works. you aren't creating associative array, creating array of objects. can either initialize array literal: var person = [ {firstname:"john", lastname:"doe", age:46}, {firstname:"peter", lastname:"toh", age:20} ]; (keep in mind arrays in javascript start zero, person[0] john , person[1] peter). or can create empty array , add entries afterwards. allows choose indexes freely: var person = []; person[1] = {firstname:"john", lastname:"doe", age:46}; person[2] = {firstname:"peter", lastname:"toh", age:20};

php - Variable count is not set in array -

i want $id increase 1 every time form submitted. should appended array $users. why not working? <?php $users = array(); $id = 0; if(isset($_post["submit"])){ $id = $id + 1; $users[] = $id; } echo "<pre>"; print_r($users); echo "</pre>"; ?> <form action="random.php"> buy ticket <input type="submit" name="submit"> </form> this because once php code stops executing value of $id , $users gone forever. http , php stateless. once page processed gone , never existed. if want persist state need use persistent data store sessions or database. <?php session_start(); if(isset($_post["submit"])){ if (!isset($_session['users'])) { $_session['users'] = 0 } $_session['users']++; } echo "<pre>"; print_r($_session['users']); echo "</pre>"; ?> ...

javascript - Script isn't working on Coppermine -

i want add backstretch on coppermine script don't seem work! works on wordpress not in coppermine. here backstretch code <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-backstretch/2.0.3/jquery.backstretch.min.js"></script> <script> $.backstretch([ "http://www.hqdiesel.net/gallery/albums/userpics/10004/hqdiesel9~65.jpg" , "http://www.hqdiesel.net/gallery/albums/userpics/10004/selena_hqdiesel7.jpg" , "http://www.hqdiesel.net/gallery/albums/userpics/10004/hqdiesel4~132.jpg" , "http://www.hqdiesel.net/gallery/albums/userpics/10004/hqdiesel0~106.jpg" ], {duration: 5000, fade: 750}); </script> and how applied it <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/t...

javascript - Rails 4 turbolinks page:load with JS -

i have following basic javascript ( coffeescript ) in app window.onload = -> menu = document.getelementbyid("menu") wrapper = document.getelementbyid("wrapper") togglemenu = false menu.onclick = -> if togglemenu false wrapper.style.left = "278px" togglemenu = true else wrapper.style.left = "0px" togglemenu = false when click on turbolinks, stops working. i found solution on so, don't know how implement in javascript: $(document).on('page:change', function () { // actions }); i did try document.onchange no success. pure javascript solution this? document.addeventlistener('page:change', function(){ console.log('called') }); # page reloaded, no clicks yet => called # click turbolinks link => called

Using strstr to determine if a given string contains a string with spaces [C] -

i'm working through example of using strstr() function. if input "pamela sue smith", why program output ""pamela" sub-string!" , not ""pamela sue smith" sub-string!". #include <stdio.h> #include <string.h> void main(void) { char str[72]; char target[] = "pamela sue smith"; printf("enter string: "); scanf("%s", str); if (strstr( target, str) != null ) printf(" %s sub-string!\n", str); } main not have return-type void int . scanf can fail. check return-value. if successful, returns number of parameters assigned. %s reads non-whitespace, until next whitespace (thus 1 word). %s not limit how many non-whitespace characters read. buffer-overflow can deadly. use %71s (buffer-size: string-length + 1 terminator) you swapped arguments strstr .

php - view sql data into html -

i'm trying view information sql db inside html page, doesn't work. code shows no results @ all. <?php $host = "drhatem-pc"; $user = "sa"; $pass = "23635451"; $db = "dr_hatem_clinic"; @$connect = odbc_connect("driver={sql server};server={".$host."}; database={".$db."}", "".$user."", "".$pass."") or die("<center><b style=\"border:1px dashed #ff0000;\">".str_replace("[microsoft][odbc sql server driver][sql server]", "", odbc_errormsg())."</b></center>"); $row = odbc_fetch_array(odbc_exec($connect, "select * entrance")); ?> <!doctype html public "-//w3c//dtd html 4.01//en" "http://www.w3.org/tr/html4/strict.dtd"> <html> <head> <ta...

scala - Convert Array[Array[Double]] to Array[Double] -

how can convert array of arrays of doubles array of doubles using scala 2.10.4? convert: array[array[double]] => array[double] use flatten : val r: array[double] = doubledouble.flatten

SaveState=false not working as expected - Spring batch -

we using multi threaded step in spring batch following. read multiple rows in table. each row in table processed , written separate excel file. to implement thread safety in jdbccursoritemreader - have done following. 1) created synchronizeditemreader delegates synchronized call jdbccursritemreader's read method. 2) set savestate=false in jdbcitemreader bean. 3) added process indicator in input table i have following questions 1)per understanding if set savestate=false spring batch not storing state in execution context i.e. read_count, commit_count, write_count etc stay @ 0. however, savestate=false counts being updated. have given xml config below. ideas why happening? 2) understand jdbcbatchitemwriter thread safe. mean, 1 thread doing business data write @ time? or thread safe maintaining state purpose? if 1 thread writing db @ time not sure if performance good <?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springf...

hardware acceleration - Accelerated canvas context translation: bug, or my mistake? -

i found odd behavior while working on pet game. wanted draw few objects on canvas, of them required image / icon rotated. quite common use case, usual solution make use of context's rotate method. going blow used translate nicely , consistently put images in desired place. this worked fine, until tried chrome on windows laptop, hardware acceleration enabled. images started blink , teleport across screen. found related acceleration (turning off accelerated graphics fixes problem) , best guess when updating frame renderer assumes drawing calls independent , can executed in parallel. when context transforms take place not case because context state changes. example of undesired behavior: having canvas element id 'screen' try following: var canvas = document.getelementbyid("screen"), ctx = canvas.getcontext("2d"); var drawrect = function () { ctx.fillstyle = this.color; ctx.translate(this.x+10, this.y+10); ctx.rotate(this.rotatio...

Ruby Class setter -

i have difficulties understanding setter , how apply value in use. in below example, def time_string=(seconds) @time_string = calculator(seconds) end how can seconds' value setter? thanks lot class timer def seconds @seconds = 0 end def time_string @time_string end def seconds=(t) @seconds = t end def time_string=(seconds) @time_string = calculator(seconds) end def calculator(x) array = [] sec = (x % 60).to_s min = ((x / 60 ) % 60).to_s hour = (x / 3600).to_s temp = [hour, min, sec] temp.map {|i| i.length < 2 ? array.push("0#{i}") : array.push("#{i}") } array.join(":") end end i think you're trying accomplish. first, calculate code...why? why not use methods in time class? second, there not such thing setters in ruby. in ruby method . technically, call setter method acts setter. in code, both methods seconds= , seconds act setter (the first s...

Using Nested Dictionaries in Python -- combining two datasets with a common 'key' and different other variables -

i have 2 csv datasets county level data. each dataset identifies county fips code. want create nested 'master' dictionary such can call identifying fips code , return corresonding 'inner' dictionary fips, contains information both datasets. i understand general way set nested dictionaries, namely: >>> d = {} >>> d['dict1'] = {} >>> d['dict1']['innerkey'] = 'value' >>> d {'dict1': {'innerkey': 'value'}} but don't know how generalize , populate data read in 2 separate csvs. say define master dictionary as: master = {} first, iterate on smaller data set foo can populate master dictionary using fips code key, , storing data under 'foo' key: for row in foo_csv_reader: fips_code = row[...] # row storing fips code. inner_data = {} inner_data['foo'] = ... # data foo csv. master[fips_code] = inner_data now, iterate on large...

Why would C automatically process the next available pointer if the designated pointer is closed? -

i have question file pointer operations in c; specifically, happens when command uses closed file pointer. here example file *fp1; fp1 = fopen(file1,"r"); function1(fp1); fclose(fp1); file *fp2; fp2 = fopen(file2,"r"); function2(fp1); fclose(fp2); so found out is: since fp1 closed, code automatically use next open/linked pointer, in case, fp2. however, if code changed file *fp1; //fp1 = fopen(file1,"r"); //function1(fp1); fclose(fp1); file *fp2; fp2 = fopen(file2,"r"); function2(fp1); fclose(fp2); there segmentation fault. in addition, if there open file pointer fp3 in between fp1 , fp2, , fp1 closed, code select fp3. i not sure way of c dealing deleted/closed file pointer language specific fail-safe mechanism, or has way these pointer variables lie in physical memory? , happens these pointers after fclose()? eg. if file pointers stored consecutively in memory , fclose delete memory current pointer uses, c access n...

How to create Test Certificate in visual studio 2010? -

Image
i'm using visual studio 2010. need add test certificates in signing tab. but "create test certificate" button disabled. wrong? how active or how create test certificate?

Variables in buttons in C# -

i have school project , i'm making game. here's code: public partial class room2 : form { public room2() { initializecomponent(); random rand1 = new random(); int32 t =6 ; int32 fight = rand1.next(1, 11); int32 j = 10; label4.text = convert.tostring(10); if (fight <= t) { label3.text = convert.tostring(j); } else { txtdialogbox.text = ("no fight in room"); } } private void attack_click(object sender, eventargs e) { random rand2 = new random(); int32 j = 10; int32 attack = rand2.next(1, 4); int64 y = 1; int64 t = 10; //opponents hp bar goes down 1 j --; label3.text = convert.tostring(j); // chance hp bar go down if (attack >= y) { label4.text = convert.tostring(t); t--; } } } when pu...

java - How can differentiate between dividable by 2 and dividable by 4? -

i create program : for 1st item , a, 2nd item , b, 3rd item , c , 4th item, d, 5th item , a, 6th item , b, 7 th item c , 8th item , d .... , on. pattern . and , can differentiate odd , even, how can achieve above, 1 seem not work if ( position % 2 == 0) { if ( position % 4 == 0) { d(); } else { b(); } } else { if ( position % 3 == 0) { c(); } else { a(); } } thanks helping position % 3 == 0 should be position % 4 == 3 to select last of every 4 items. you'll need reorder function calls match description; think correct order a,c,d,b. the code clearer using switch: switch (position % 4) { case 0: a(); break; case 1: b(); break; case 2: c(); break; case 3: d(); break; } assuming whichever language you're using supports such c...

css - Why does .b:not(#a>.b) not work? -

i'm working css , wondering why following piece doesn't work: .container:not(#topic-title>.container) is there anyway else can achieve same thing? i'm open javascript solutions. you use selector : :not(#topic-title) > .container .container { height:20px; } :not(#topic-title) > .container { background:green; } <div id="topic-title"> <div class="container">parent #topic-title</div> </div> <div> <div class="container"> parent not #topic-title</div> </div>

How to assign each line in a text to an array in shell scripting? -

i have text file named "raj.txt" containing following content: raj magesh popey ravi how can assign each word array element? a[0]=raj a[1]=magesh a[2]=popey a[3]=ravi try bash : while ifs= read -r line set -- $line echo "$1" echo "$2" done < file

cordova - How to get crash reason, if it is crashing from URL opened in iframe in Webview in iOS? -

url opened in cordova project in iframe, causing crash on ios 7. no direct way of checking webview crash, or atleast know. can recommend steps towards this: i) open content/web page in browser , check errors throws in browser ii) stop/delete unnecessary service calls iii) webview sandbox environment has within 10 mb iv) make sure not getting 404 errors, use browser check v) update , refine codes simple , avoid service calls not required in webview environment

ios - Creating an Array of objects from the Facebook SDK in Swift -

im new swift , ios programming in general maybe im google ing wrong things i have facebook sdk working , returning albums. want data in objects named album. these album objects datasource of collection view cells when trying run following problem: i can't objects object array! here code have far: var = 0 var list: [string] = [] rawfeed : anyobject in data { if rawfeed fbgraphobject { if var jsonfeed = rawfeed as? fbgraphobject { var app = jsonfeed["name"] string list.append(app) var = album(albumname: jsonfeed["name"] string , albumid:jsonfeed["id"] int,count: jsonfeed["count"] int) arrayofalbums.append(test) i++ } } i thought use value of i object name. like this: arrayofalbums = { [0] => albumobject0, [1] => albumobject1 } when trying following error on i++ rule: 'album' not ...

printing out a 2 text files in java -

here code printing out 2 text files out put nor right keeps printing first line on , on example text in file : 1 2 3 4 1 2 3 when call function output : 1 1 1 1 1 1 1 public static void printuser() { bufferedreader br = null; bufferedreader br1 = null; try { br = new bufferedreader(new filereader("info.txt")); br1 = new bufferedreader(new filereader("info ai.txt")); } catch (filenotfoundexception e) { // todo auto-generated catch block e.printstacktrace(); } string line = null; string line1 = null; try { while((line = br.readline())!= null) { while((line1 = br1.readline())!= null){ system.out.println(line+" === "+line1); } } } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } it's because of double while loop, each round of first while, second 1 restarts...

twitter bootstrap 3 - Floating right panel with Bootstrap3 -

i have full-width template sidebar @ left. main content area wrapped in <div class=row><div class=col-lg-12> . want add "search" button , if user clicks full-height search sidebar should appear @ right side col-3 size. main content area should shrink col-9. of course, can javascript toggling necessary classes on divs. in case search panel show under main content on small devices. need show above main content. again, wide screen - sidebar must show @ right col-3, small screen - sidebar must show in full width above main content. possible?

How to use ODE as a objective function in MATLAB for optimization -

i have ode equation: d[ras]/dt = x1*[0.4]*[0.7] + (x2 + x3)*[0.013]. now need optimize equation. how should represent equation in .m file use objective function optimization in matlab? do need first solve ode or can use objective function?

python class that acts as mapping for **unpacking -

without subclassing dict, class need considered mapping can passed method ** from abc import abcmeta class uobj: __metaclass__ = abcmeta uobj.register(dict) def f(**k): return k o = uobj() f(**o) # outputs: f() argument after ** must mapping, not uobj at least point throws errors of missing functionality of mapping, can begin implementing. i reviewed emulating container types defining magic methods has no effect, , using abcmeta override , register dict validates assertions subclass, fails isinstance(o, dict). ideally, dont want use abcmeta. the __getitem__() , keys() methods suffice: >>> class d: def keys(self): return ['a', 'b'] def __getitem__(self, key): return key.upper() >>> def f(**kwds): print kwds >>> f(**d()) {'a': 'a', 'b': 'b'}

excel - How to use COUNT/COUNTIF to count cell value of a given range in another sheet -

Image
sheet1 contains raw data: name (col-1), project (col-2), year.... etc (columns) sheet2 range (a1:a5) has project name list i need count, in sheet2 (range b1:b5), of each project in list sheet1. how can use countif that? you can use following formula in sheet2 count of each projects listed in sheet1 . =countif(sheet1!b:b,a2) lets take of how implement above formula. lets have following data in sheet1 . check below image: now, lets take how enter formula count in sheet2. check below image: as can use formula enter in cell b2 of sheet2 . using countif can count of projects in sheet1

java - Double colored oval -

Image
i bit new in java , have stuff homework. have make the thing have no idea how make circle double colored yellow , black stuff. after use of threads have make rotate counter clock wise. here code circle, know how create it, don't know how multi color >.< . import java.awt.*; import java.awt.event.*; import java.util.logging.logger; import javax.swing.*; import javax.swing.border.titledborder; import javax.swing.jcombobox; import javax.swing.japplet; import javax.swing.jslider; import java.awt.color; import java.awt.graphics; import java.util.logging.level; import java.util.logging.logger; import javax.swing.japplet; public class lab4a extends japplet implements runnable { public void init() { thread t = new thread(this); t.start(); } public void paint(graphics g){ super.paint(g); int w = getwidth(); int h = getheight(); g.drawoval(25, 35, 200, 200); g.drawoval(45, 55, 160, 160); } } have @ drawarc instead of drawoval . this...

html - Align Header and logo -

Image
i new css , html , have problem while aligning logo , title in header: i have tried several solutions have not succeed. appreciate if give me hint it. thanks. html code: <! doctype html> <html> <head> <meta charset="utf-8"> <title>title goes here</title> <meta name="description" content="description of site goes here"> <meta name="keywords" content="keyword1, keyword2, keyword3"> <link href="css/style.css" rel="stylesheet" type="text/css"> </head> <body> <div class="page"> <div class="header" > <h1> <img src="images/img1.jpg" width="250" height="190" float="right" /> text here </h1> </div> </body> </html> my css code: body { font-family: sans-serif,arial; font-size: 12px; color: #000000; marg...

c# - Is there a way to programmatically choose a certificate for a System.Windows.Forms.WebBrowser request and if so how can this be done? -

the problem i'm having ie , other browsers default looking client certificates in certificates - current user . want grab specific 1 certificates (local computer) store (i've got code written already) , use 1 user chooses or choose 1 them if possible. choosing 1 them optimal solution. also i'm not 100% locked using webbrowser , need way embed browser windows form , have web browser able authenticate via client certificates. have code written via httpwebresponse , wasn't able use inside webbrowser .

python - How is django's default cache invalidated by an app -

i've had disable django's cache middleware; middleware_classes = ( #'django.middleware.cache.updatecachemiddleware', ... #'django.middleware.cache.fetchfromcachemiddleware', ) this because caching views default, causing incorrect information rendered because our methods don't invalidate cache. i'm familiar writing custom cache methods models , necessary signals delete cache keys, if django creating cache keys itself, how delete correct keys when change object example?

python - Splitting a string like shell would -

i'm reading line file looks this key1=4 key2="hello world" i split list ['key1=4', 'key2=hello world'] is there simple way shell-like processing in python without having walk string searching next ' ' or '"' , incrementally processing it? use shlex.split : >>> import shlex >>> s = 'key1=4 key2="hello world"' >>> shlex.split(s) ['key1=4', 'key2=hello world']

java - How to Auto Subtract input values of JText Field in swing -

this question has answer here: how auto calculate input numeric values of text field in java 2 answers i want auto subtract jtextinput value , want subtracted value in text field q. how can achieve this? here jtextfield code: public class showdata1 extends jframe { public showdata1() { this.setdefaultcloseoperation(jframe.dispose_on_close); container c = getcontentpane(); c.setlayout( new flowlayout()); // setundecorated(true); dimension screensize = toolkit.getdefaulttoolkit().getscreensize(); setbounds(0,0,screensize.width, screensize.height); opening_km= new jlabel("opening km"); opening_km.setbounds(0,280,258,30); opening_km.setfont(new java.awt.font("times new roman", 1,25)); // noi18n c.add(opening_km); opening_kms= new jtextfield(""); opening_kms.setbounds(2...

PHP SQL Search With Duplicate Entries -

i'm trying make search either last name or first name in database have return values , echo them out. have gotten far i'm getting stuck when there duplicate entry such first name. ex; 2 entries within database have same firstname value bill , different lastname values how can return ones same first name value? i've tried multiple solutions have not been able it. feel i'm missing easy i'm being blind , can't see it. $query = $handler->query("select * rwapplicants group firstname having count(*) >= 1"); $r = $query->fetch(pdo::fetch_assoc); if($r){ echo "first"; print_r($r);} gives me first row not others i've tried , different variations of it..hopefully can help! thank you! you're mixing db libraries. using ->query() suggests you're using pdo or mysqli. try actual result rows mysql_fe...

javascript - Add text to downloads link via jquery -

this question has answer here: how update (append to) href in jquery? 4 answers i want know if possible via jquery since can't add in markup: i want add download.php?file= url (links change can't replace whole href ): <a class="boton" target="_blank" href="http://www.test.com/wp-content/uploads/2014/11/prueba-es.pdf">download</a> so link this: <a class="boton" target="_blank" href="http://www.test.com/wp-content/uploads/2014/11/download.php?file=prueba-es.pdf">download</a> any ideas? this should work $('.boton').each(function (i) { var hreforig = $(this).attr('href'); var segments = hreforig.split('/'); var file = segments.pop() var hrefnew = hreforig.replace(file, 'download.php?file='+file); $(thi...

node.js - Limit scope in Node JS -

i want let users create custom plugins 1 of apps programmed in node js. i thought of using method similar dynamic libraries, using node modules. problem don't want users able harmful things making inappropriate use of network or accessing file system. is there way can limit node native api specific module? i doubt there real defense if grant code execution level access server. @ best, in arms race trying plug holes discovered. if want allow customers expand functionality of product, should develop api customer products interface with. way, there limited attack surface area , can control access points application.

java - How do I make this program with multiple classes run? -

i doing project school , have been given code need modify. problem cannot code run in first place. know having problems class paths , packages because have never used them before. these classes: import java.util.scanner; import java.io.*; public class sudsolve { public static void main(string[] args) { try { scanner scan = new scanner(system.in); system.out.println("enter sudoku file name"); string name = scan.next(); readboard r = new readboard(name); r.readlines(); sudboard b = new sudboard(r.getboardnums()); b.display(); b.solve(); } catch (ioexception e) { system.out.println(e); } } } import java.util.scanner; import java.io.*; public class echo { string filename; // external file name scanner scan; // scanner object reading external file public echo(string f) throws ioexception{ filename = f; scan = new scanner(...

python - Speeding up take with numba? -

is possible speed np.take using numba? here attempt, lot slower. can't use nopython mode not np.empty_like command. import numba import numpy np timer import timer def take( x, indices ): result = np.empty_like( indices, dtype=x.dtype ) in range( len( indices ) ): result[i] = x[ indices[ ] ] return result jtake = numba.jit("f4[:](f4[:],i4[:])" )( take ) if __name__=='__main__': n = 100000 m = 100 idx = np.random.random_integers( 0, n, m ) x = np.random.randn( n ) num_tests=10000 timer( 'take' ): in range( num_tests ): r0 = take( x, idx ) timer( 'numba take' ): in range( num_tests ): r1 = jtake( x, idx ) timer( 'numpy.take' ): in range( num_tests ): r2 = x.take( idx ) which has results: beginning take take took 2.46 seconds beginning numba take numba take took 1.11 seconds beginni...

Android: how to get calling application developer's public key -

i have following situation. application calling mine (using startactivityforresult). since have sure calling activity comes developer trust i'd read developer public key , compare value hardcoded in app. tried following: string packagename = callingactivity.getpackagename(); string signature = null; try { packageinfo pi = manager.getpackageinfo(packagename, packagemanager.get_signatures); // assumption: first available signature // according google applications there 1 element signature = pi.signatures[0]. tocharsstring(); } but gives me application (not developer) signature. use android custom permissions purpose. defining permission in application, can restrict other apps use activity/service unless have uses-permission in manifest. read more info : http://developer.android.com/training/articles/security-tips.html#permissions for example: https://stackoverflow.com/a/8817231/607968

database - Magento Varien_Data_Collections: when is SQL query executed -

i`d know how magento internally processes database calls on varien_data_collections. example: 1 of models returns data collection block. additional clauses added via layout xml blocks , afterwards appended returned data collection te model. does mean database calls made twice? 1 on initial $model->getcollection() method , 1 on $collection->addfieldtofilter('x',array('eq'=>'y')) in block. or magento make sql call on iteraror? see situation below: model class: <?php class x_y_model_a extends mage_core_model_abstract{ ... public function getrelateditems(){ return $this->getcollection() ->addfieldtofilter('id',array('eq'=>$this->getid())); } } ?> block class: <?php class x_y_block_a extends mage_core_block_template{ private $limit = 5; public function setdblimit($limit){ $this->limit = (int)$limit; return $this; } public functi...