Posts

Showing posts from February, 2015

ruby on rails - RailsTutorial Chp 3 (Section 3.2.2) -

here's issue section 3.2.2 adding page: they intentionally left out creating page (in section 3.1.2) teach me how use tdd guide me through development process. progressed through adding code spec tests, route, , staticpages controller (listings 3.13, 3.14 , 3.15 steps in between). however when came step right before listing 3.16 had tilt head. here's text: "to solve issue, add view. involves creating new file called about.html.erb in app/views/static_pages directory contents shown in listing 3.16." my question how "add view , create new file called about.html.erb in app/views/static_pages directory"? added action staticpages controller doesn't virtue of test $ bundle exec rspec... says i'm missing "template" or view. yet next step "involves creating new file called about.html.erb" no direction on how. the last time remember creating static page files section 3.1.2 using $ rails generate controller staticpages home --no

Adding a checkmark to fpdf file -

i retrieving data database , displaying using fpdf. have data value 0 or one. if one, want display checkmark. there way output checkmark ? i appreciate suggestions. here's have tried did not work. stores image in folder instead of displaying it: $im = imagecreate( 200, 80 ); $pdf->cell(20,7, imagejpeg($im,"checkmark.jpg"));

java - Drawn Image In OpenGL Comes Out Wrong Size And With Black Boxes In It -

Image
im trying work on java project includes lwjgl. have come far "game" im drawing image screen. the problem im getting drawn image gets drawn black boxes in , not correct size. here image of how looks visually. here how actualy red square image should like: here code use rendering opengl, cannot figure out im doing wrong. public class renderer { //integers used player cordinates, taken player class using static variables int playerx; int playery; spritesheetloader spriteloader; texture player; public renderer(){ } public void initrenderer(){ //initialize opengl gl11.glmatrixmode(gl11.gl_projection); gl11.glloadidentity(); // resets previous projection matrices gl11.glortho(0, 800, 600, 0, 1, -1); gl11.glmatrixmode(gl11.gl_modelview); try { player = textureloader.gettexture("png",resourceloader.getresourceasstream("res/paddletemp.png")); } catch (ioexception e) { // todo auto-generated catch b

c# - Event Creation is not working -

i have source "source401" used log "log401". need use source "log402" log , delete log "log401". (if can rename “log401” “log402” fine. need done programmatically) with code below, getting following exception. best way achieve it? source source401 exists on local computer. note: when delete old log, working fine. events not getting created. update from msdn the operating system stores event logs files. when use eventloginstaller or createeventsource create new event log, associated file stored in %systemroot%\system32\config directory on specified computer. file name set appending first 8 characters of log property ".evt" file name extension. the source must unique on local computer; new source name cannot match existing source name or existing event log name. each source can write 1 event log @ time; however, application can use multiple sources write multiple event logs. code string source = "

xslt - Combining Similar Lines XML -

i have xml record have repeating unique id's combine similar id's 1 record, concat reference fields , summing amount field. the xml looks this: <root> <row> <f01>123456</f01> <f02>abc company</f02> <f03>0</f03> <f04>47582736</f04> <f05>151.12</f05> </row> <row> <f01>123456</f01> <f02>abc company</f02> <f03>0</f03> <f04>47643792</f04> <f05>191.09</f05> </row> <row> <f01>123456</f01> <f02>abc company</f02> <f03>0</f03> <f04>47643793</f04> <f05>95.32</f05> </row> <row> <f01>223344</f01> <f02>dk corp</f02> <f03>0</f03> <f04>36819319</f04> <f05>138.87</f05> </row> <row> <f01>223344</f01>

bash - How to accept multiple input into a same script -

how can accept multiple-line input same script. or in other words process multiple files following script: #!/bin/bash echo 'enter file names (wild cards ok)' read input_source if test -f "$input_source" sort $var | uniq -c | head -10 fi add loop: #!/bin/bash echo 'enter file names (wild cards ok)' read files input_source in $files ; if test -f "$input_source" ; sort $var | uniq -c | head -10 # should include $input_source somewhere fi done

Python import and module scoping (specifically sys.ps1) -

why following not work: from sys import ps1 ps1 = 'something else ' but does? import sys sys.ps1 = 'something else ' if run simple test import sys sys import ps1 ps1 = 'something else' sys.ps1 = 'something else' the first assignment doesn't work, second does. id() both ps1 , sys.ps1 same, should refer same thing, right? the short version is: assignment doesn't mutate in python, rebinds names. rebinding different name, happens bound reference same string sys.ps1 doesn't affect sys.ps1 in way. let's go through step step: from sys import ps1 this imports sys (but doesn't bind name sys in current globals), binds name ps1 in current globals same object sys 's ps1 . ps1 = 'something else ' this rebinds name ps1 in current globals same object literal 'something else' . there's no way possibly affect sys module. import sys this imports sys , , binds name sys in current glo

python - Variable assignment in function -

i'm writing basic fighting game , trying make each attack subtracts amount of attack enemy's health , prints enemy's current health. however, health resets original amount after run script once , loop it. how can resign enemies health current health? here script: import random while true: health = 20 enemy_health = 20 def punch(): mylist = (xrange(0,3)) x = random.choice(mylist) if x == 3: print"your hit effective enemy lost 3 hp" print("enemy health is" enemy_health - x) if x == 2: print "your punch effective enemy lost 2 hp" print("enemy health is" enemy_health - x) if x == 1: print "enemy lost 1 point" print("enemy health is" enemy_health - x) def kick(): mylist = (xrange(0,5)) x = random.choice(mylist) if x > 3: "%d" % x

.net - C# performance counter data is "all over the map" -

Image
i need calculate cpu , ram usage overall system specific process. i've never done in c#. able come following code (that took samples on web site): try { process proc = process.getcurrentprocess(); string strprocname = proc.processname; console.writeline("process: " + strprocname); using (performancecounter total_cpu = new performancecounter("process", "% processor time", "_total", true)) { using (performancecounter process_cpu = new performancecounter("process", "% processor time", strprocname, true)) { (; ; ) { console.cursortop = 1; console.cursorleft = 0; float t = total_cpu.nextvalue() / environment.processorcount; float p = process_cpu.nextvalue() / environment.processorcount; console.writeline(string.format("total cpu (%) = {0}\t\t\napp cpu (%) = {1}\t\t\napp ram (kb

php - Extract value from row in csv and sum it -

i'm getting csv file in input, example of content: time,value 2010,77.77046 2010,60.32812 2010q1,63.33447 2010q2,61.29888 2010q3,59.06448 2010q4,57.62415 2011,60.75586 2011q1,60.97929 2011q2,61.36082 2011q3,59.88779 2011q4,60.79407 that code use take csv, read content , put array. if (($handle = fopen("csvextracttor.csv", "r")) !== false) { # set parent multidimensional array key 0. $nn = 0; while (($data = fgetcsv($handle, 1000, ",")) !== false) { # count total keys in row. $c = count($data); # populate multidimensional array. ($x=0;$x<$c;$x++) { $brim[$nn][$x] = $data[$x]; } $nn++; } # close file. fclose($handle); }; what need, take values of each quarters​​, example, 2010q1, 2010q2, 2010q3, 2010q4, sum , divided / 4 medium , save operation unique value in 2010, csv or in variable. i've tried lots of solutions none works good. tried method strp

Allowing AJAX requests to service behind nginx proxy based on request_method -

i'm new nginx, pardon me if i'm being obtuse. have service sitting behind nginx proxy, , using auth_basic prevent being able hit it. want allow angular app hit service, want control allowed perform particular request methods (get, post, del, options), , using auth_basic doesn't seem best bet, since don't want hardcode login/password js (duh). way can figure out how say: if ($request_method = options) { proxy_pass_header access-control-allow-origin *; proxy_pass_header access-control-allow_methods get, options; etc... } at point, i'd allow , options requests anyone, want restrict post, del locations (such internally, or trusted ip). currently, though, if put proxy_pass_header block, says directive not allowed. i've seen other examples people use add_header inside if block that, i'm confused why isn't working. so first of all, best way of doing things, , if not, have recommendation? if best way of handling things,

web services - Separate User Authentication Module -

at organization, we're moving towards modular software architecture.. we're still in beginning phases, , working on user authentication (ua) module. i'm looking information on best practices in terms of user authentication module. my current notion following: client queries ua module login details ua module checks login details. if valid, ua module creates & stores access token, associating token validated user's unique id. the token sent client. client stores token. whenever client requires authentication, queries ua module token. ua module returns user's unique id if token valid, or returns error code if token invalid. i appreciate criticism on methods. i'm interested in knowing how deal accumulation of tokens. if user chooses log out, token removed. my notion tokens should have expiry dates associated them, , worker process should clean these tokens @ regular interval. right way go things? please comment! reference documents

perl - count the number of keys that map to a value -

i have following hash my %hash = ( w1 => '0', e2 => '1', r1 => '2', o3 => '1', h4 => '0', t5 => '1', ); i number of keys map each value in hash. 3 keys map value 1. 1 key map value 2. 2 keys map value 0. i without using function module. one way thought of doing looping through values of hash. if value has key increment counter key. problem knowing values beforehand can initialize counters each value. there's easier solution this. think regex might work. attempt 1 my $string; foreach $value (value %hash) { $string = join(",", $value); } # count number of occurrences each value (separated commas) use hash count occurrences. #!/usr/bin/perl use warnings; use strict; %hash = ( w1 => '0', e2 => '1', r1 => '2', o3 => '1', h4 => '0', t5 => '1', ); %count; $value (values

google mirror api - How does a service identify the user? -

Image
use case: a user takes beautiful photo , wants save evernote account. user authorizes oauth 2.0. service stores credentials. just after oauth 2.0 dance completes, service inserts contact called "save evernote". next, service subscribes updates in user's timeline inserting subscription timeline collection. the user activates contact. save evernote set up. over time, user takes photos. the user shares photo save evernote. makes timeline card associated photo accessible service. because service subscribed timeline updates, notification sent service. notification links timeline item containing shared photo. the service examines notification , uses included id fetch timeline card contains photo. next, service examines timeline item , uses attachment id fetch bytes of photo. the service uploads photo user's evernote. finally, service constructs new timeline card , inserts user's timeline card success message. from mirror api documentation appear

mysql - Flyway:init doesn't create schema database -

i'm using flyway manage multi-schema database in mysql , i've configured flyway using maven. have listed database called 'metadata' first in <schemas> tag flyway put schema_version table here. when run mvn flyway:migrate i'm expecting table and metadata database created. flyway 2.1.1 tries create table, not create database first fails. [debug] schemas: metadata,temp,other_dbs_redacted [debug] schema `temp` exists. skipping schema creation. [debug] database: mysql 5.6 [error] com.googlecode.flyway.core.api.flywayexception: error setting current sc hema `metadata` [error] caused com.mysql.jdbc.exceptions.jdbc4.mysqlsyntaxerrorexception: unk nown database 'metadata' i thought mvn flyway:init might create schemas, fails different related error. [info] --- flyway-maven-plugin:2.1.1:init (default-cli) @ database --- [info] creating metadata table: `metadata`.`schema_version` [error] com.googlecode.flyway.core.api.flywayexception: error exe

javascript - add two li elements into the end of the ul -

here jsfiddle tried this: http://jsfiddle.net/fxmfh/ i want add 2 li's end of submenu jquery, seems doesnt navigate ul needs to: $(document).ready(function() { $(".navigation_container nav > ul > li > ul").append('<li><a href="#">test</a></li>'); }); this must problem: $(".navigation_container nav > ul > li > ul") i must doing noobish here.. try $(document).ready(function() { $(".navigation_container nav > ul > li > div.sub-menu > ul").append('<li><a href="#">test</a></li>'); }); demo: fiddle but shorten selector $(document).ready(function() { $(".navigation_container nav div.sub-menu > ul").append('<li><a href="#">test</a></li>'); }); demo: fiddle

Can a batch file execute commands within a python shell? -

can use batch file start python shell , execute commands? know that python will start python shell, batch file containing python 1+1 will first run python, , when quit python attempt run 1+1. not execute commands within python shell. after little searching around, managed find this website has method this. see on website, need is: @setlocal enabledelayedexpansion && python -x "%~f0" %* & exit /b !errorlevel! #start python code here print "hello world" this didn't work me, thought might help. i haven't been able find other source says it's possible. just thought of else haven't tested. combined bear's answer , mine. @for /f "skip=1 delims=" %i in (%0) @python -c "%i" #start python here. however, other method should used.

c++ - syntax error while returning nested class of a template -

i have following class declaration: template <typename key_t, typename mapped_t, size_t maxlevel = 5> class skiplist { public: class iterator { typedef std::pair<key_t, mapped_t> valuetype; template <typename key1, typename obj1, size_t maxlevel1> friend class skiplist; public: //iterator functions private: //iterator data }; skiplist(); ~skiplist(); skiplist(const skiplist &); skiplist &operator=(const skiplist &); std::pair<iterator, bool> insert(const valuetype &); template <typename it_t> void insert(it_t range_beg, it_t range_end); void erase(iterator pos); private: //data }; when declaring skiplist insert function outside class definition template <typename key_t, typename mapped_t, size_t maxlevel> typename std::pair<skiplist<key_t,mapped_t,maxlevel>::iterator, bool> skiplist<key_t,mapped_t,maxlevel>::insert(const valuetype &input)

Understanding Javascript immutable variable -

i trying understand javascript immutable variable means. if can do: var x = "astring"; x = "str"; console.log(x); //logs str` , why immutable? the answer can think (from little bit of c know) var x pointer memory block value "astring", , after 2nd statement points block value "str". case? and bonus question: confused value types of javascript. variables objects under hood? number , strings? values immutable; variables not; hold reference (primitive) values. the 3 primitive types string, number , boolean have corresponding types instances objects: string, number, boolean . called wrapper types . the following values primitive : strings: "hello" numbers: 6, 3.14 (all numbers in javascript floating point) booleans: true, false null: explicitly assigned undefined: default (automatically assigned) value all other values objects, including wrappers primitives. so: objects mutable default

LINQ ToList() causes all records to be the last one off a coroutine -

i seem have misunderstanding because following code works correctly if don't append tolist() command: ienumerable<processorinfo> query = ( n in infoget(emachineinfodepth.logicalprocessor) select n ) .tolist(); infoget looks this: internal static ienumerable<processorinfo> infoget(emachineinfodepth depth) { processorinfo result = new processorinfo(); // loop through workgroups foreach (workgroup wg in workgroups_s) { result.workgroup = wg; if (depth >= emachineinfodepth.numanode) { // loop through numanodes foreach (numanode node in wg.numanodes) { result.numanode = node; if (depth >= emachineinfodepth.cpu) { // loop through cpus foreach (cpu cpu in node.cpus) { result.cpu = cpu; if (depth >= emac

javascript - standalone web app link script - stop it from appending links which have a specific class? -

this script prevents links opening in mobile safari. when web app in app mode on ios (home screen bookmark). gist.github.com/1042026 if(("standalone" in window.navigator) && window.navigator.standalone){ // if want prevent remote links in standalone web apps opening mobile safari, change 'remotes' true var noddy, remotes = false; document.addeventlistener('click', function(event) { noddy = event.target; // bubble until hit link or top html element. warning: body element not compulsory better stop on html while(noddy.nodename !== "a" && noddy.nodename !== "html") { noddy = noddy.parentnode; } if('href' in noddy && noddy.href.indexof('http') !== -1 && (noddy.href.indexof(document.location.host) !== -1 || remotes)) { event.preventdefault(); document.location.href = noddy.href; }

sql - How can I access these data returned by the result_array() function from a PDO query in CodeIgniter? -

public function get_details($id) { //my query in pdo form getting records $query = $this->db->query("select * users idno='". $id ."'"); //check if query successfull if($query) { $query->result_array();//get result through array form print_r($query);//prints array } // end if }//end function the result of code above this: ci_db_pdo_result object ( [num_rows] => 1 [conn_id] => pdo object ( ) [result_id] => pdostatement object ( [querystring] => select * users idno='888812' ) [result_array] => array ( [0] => array ( [idno] => 888812 [lname] => smith [fname] => john [username] => john [password] => password [usertype] => [status] => ) ) [result_object] => array ( ) [custom_result_object] => array ( ) [current_row] => 0 [row_data] => ) usually result of result_array() function array of cursor/result query being executed, have problem on how values re

javascript - Faster to append or create html elements before? -- JQuery -

i trying make application faster. want elements appear when ajax request has succeeded. faster create elements append when request has succeeded, or faster create html element in actual html , insert content in element .html? according jsperf : plain old innerhtml beats .html() (and .html() beats .append() ). however according jsperf : dom beats innerhtml . so, might want documentfragment , specified in dom1 , supported in ie6 (so there no reason not use it). since document fragment in memory , not part of main dom tree, appending children not cause page 'reflow' (computation of element's position , geometry). consequently, using document fragments results in better performance. john resig did nice write-up here , concludes: a method largely ignored in modern web development can provide serious (2-3x) performance improvements dom manipulation. you might want combine of techniques per case want optimize. hope helps!

c# - Autofac: how to inject properties with dynamic values? -

by autofac, it's easy inject static value currentdate property instances of classes in given assembly: builder.registerapicontrollers(asm).withproperty("currentdate", new datetime(2012, 1, 13)); however, how inject dynamic values e.g. values returned lamda () => { return datetime.now; } currentdate property? sounds use pretty standard property injection, this: builder.registerapicontrollers(asm) .onactivating(e => { e.instance.currentdate = datetime.now; }); note may need cast e.instance of type object. see lifetime events in documentation more info. on second thought, why not put initialization in base class constructor? public datetime currentdate { get; private set; } protected apicontroller() { currentdate = datetime.now; } the current date isn't dependency need di container provide.

Installing Ruby - RVM - Mac OSX Mountain Lion -

so i'm trying install ruby 1.9.3 on mac running mountain lion. have xcode installed , date. i've installed rvm , trying install ruby using rvm install 1.9.3 when run looks it's going install gives me error please see below: rvm install 1.9.3 searching binary rubies, might take time. no binary rubies available for: osx/10.8/x86_64/ruby-1.9.3-p392. continuing compilation. please read 'rvm mount' more information on binary rubies. installing requirements osx, might require sudo password. up-to-date. certificates in '/users/colin/.rvm/etc/openssl/cert.pem' date. installing ruby source to: /users/colin/.rvm/rubies/ruby-1.9.3-p392, may take while depending on cpu(s)... ruby-1.9.3-p392 - #downloading ruby-1.9.3-p392, may take while depending on connection... ruby-1.9.3-p392 - #extracted /users/colin/.rvm/src/ruby-1.9.3-p392 (already extracted) ruby-1.9.3-p392 - #configuring........ error running './configure --prefix=/users/colin/.rvm/rubies/ruby-1.9.3-p

c# - Cant deserialize a list from DataContractSerializer -

im on c# , im having trouble deserializing list xml file created used datacontractserializer wich has list of entities entity framework in it, code used this: list<proveedores> proveedores = obtenerentidadesproveedores(); foreach (proveedores proveedor in proveedores) { proveedor.proveedoresdomicilios.load(); } type[] tipocoleccion = new type[1]; tipocoleccion[0] = typeof(proveedores); datacontractserializer serializador = new datacontractserializer(typeof(list<proveedores>), tipocoleccion); serializador.writeobject(entrada, proveedores); salida = entrada; im using datacontractserializer because map related entities proveedores xml. now problem when try back, list 1 element: list<proveedores> proveedores = new list<proveedores>(); type[] tipocoleccion = new type[1]; tipocoleccion[0] = typeof(proveedores); datacontractserializer serializador = new datacontractserializer(typeof(list<proveedores>), tipocoleccion); proveedores = serializa

java 7 - Unhandled loop exception when moving frames around in Eclipse -

if start @ standard java view , move 1 of open programs side (so can see 2 open programs @ once, side side), , click on either of frames, unhandled event loop exception item not added i following in event detail's stack trace - eclipse.buildid=m20130204-1200 java.version=1.7.0_17 java.vendor=oracle corporation bootloader constants: os=win32, arch=x86_64, ws=win32, nl=en_us framework arguments: -product org.eclipse.epp.package.jee.product command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.jee.product error sat apr 20 00:36:50 edt 2013 unhandled event loop exception org.eclipse.swt.swterror: item not added @ org.eclipse.swt.swt.error(swt.java:4387) @ org.eclipse.swt.swt.error(swt.java:4276) @ org.eclipse.swt.swt.error(swt.java:4247) @ org.eclipse.swt.widgets.widget.error(widget.java:468) @ org.eclipse.swt.widgets.toolbar.createitem(toolbar.java:392) @ org.eclipse.swt.widgets.toolitem.<init>(toolitem.j

javascript - Displaying JSON content -

this should pretty simple, i'm pretty new this. want know how how display following information file: http://worldoftanks.com/community/accounts/1003576349/api/1.8/?source_token=wg-wot_assistant-1.3.2 i want display (for example purposes) following using javascript: -status -vehicles -> spotted -summary -> wins -data -> defender thanks help! just deal json normal javascript object , access properties/ arrays other object. can values looking this. fiddle var json={...yourjson...}; alert('status ' + json.status); alert('spotted ' + json.data.vehicles[0].spotted); alert('wins ' + json.data.summary.wins); alert('defender ' + json.data.achievements.defender); for further dwelling @ so post.

how to capture whole layout when layout exceeds screensize in android -

in application zooming layout when zoom layout want capture layout.i tried below code capturing content visible in screen.please me how capture layout. view content = findviewbyid(r.id.main_container); content.setdrawingcacheenabled(true); bitmap bitmap = content.getdrawingcache(); // actual width of image (img bitmap object) // int width = bitmap.getwidth(); // int height = bitmap.getheight(); // recreate new bitmap , set bitmap = bitmap.createbitmap(bitmap.createbitmap( l1.getwidth() * 2, l1.getheight() * 2, bitmap.config.argb_8888)); // bitmap mb = bitmap.copy(bitmap.config.argb_8888, true); canvas bitmapcanvas = new canvas(); bitmapcanvas.setbitmap(bitmap); bitmapcanvas.scale(2.0f, 2.0f); content.draw(bitmapcanvas); bytearrayoutputstream out = new bytearrayoutputstream(); bitmap.compress(bitmap.compressformat.png, 100, out); file imagesfolder = new file(environment.get

Google Analytics in PHP -

i have website displays movietimes. (e.g. movietime.php?movieid=1) i track 2 things. how many times movietime.php has been visited how many times movieid=1 has been visited (same goes movieid=2, movieid=3 etc) how should that? i did below before </head> not getting results. <!-- google analytics tracking --> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setaccount', 'ua-xxxxxxxx-x']); _gaq.push(['_setcustomvar', 1, 'movieid', <?php echo $movieid; ?>, 1]); _gaq.push(['_trackpageview']); (function() { var ga = document.createelement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = docum

php - loop is not showing Zero before numbers in framework -

this question has answer here: in php, how add zero-padded numeric string , preserve 0 padding? 4 answers i making form in custom framework in when user enter 2 numbers e.g start number , ending number . loop shows numbers between numbers . example if user enter 0300 , 0309 result show 0300 0301 0302 0303 0304 0305 0306 0307 0308 0309 but showing 0300 301 302 303 304 305 306 307 308 309 is there problem loop ? function did_ehmad_sec_submit($editform) { $count=0; $start=$editform['from_to']; $end=$editform['to_range']; $desc=$editform['description']; ($i=$start;$i<=$end;$i++) { $result = mysql_query("insert did_number(did_number, description) values ('$i','$desc')"); } return $result; }

Hadoop & Hive as warehouse: daily data deliveries -

i evaluating combination of hadoop & hive (& impala) repolacement large data warehouse. set version , performance great in read access. can give me hint concept should used daily data deliveries table? have table in hive based on file put hdfs. have on daily basis new transactional data coming in. how add them ti table in hive. inserts not possible. hdfs cannot append. whats gernal concept need follow. any advice or direction documentation appreciated. best regards! inserts not possible inserts possible ,like can create new table , insert data new table old table. but simple solution can load data of file hive table below command. load data inpath '/filepath' [overwrite] table tablename; if use overwrite existing data replced new data otherwise appending only. you can schedule script creating shell script.

javascript - Cannot call method 'appendChild' of null for iframes -

i have following script create iframe function createiframe() { var iframe = document.createelement("iframe"); iframe.style.position = "absolute"; iframe.style.visibility = "hidden"; document.body.appendchild(iframe); // firefox, opera if(iframe.contentdocument) iframe.doc = iframe.contentdocument; // internet explorer else if(iframe.contentwindow) iframe.doc = iframe.contentwindow.document; // magic: force creation of body (which null default in ie). // force styles of visited/not-visted links. iframe.doc.open(); iframe.doc.write('<style>'); iframe.doc.write("a{color: #000000; display:none;}"); iframe.doc.write("a:visited {color: #ff0000; display:inline;}"); iframe.doc.write('</style>'); iframe.doc.close(); // return iframe: iframe.doc contains iframe. return iframe; } however in chrome console giving me error ca

objective c - Spreadsheet Style Control (iOS)? -

i need control closely represents style of spreadsheet in ios application writing. would uicollectionview provide appearance? all need display data there no editing of data needed. fritzables. you maybe need uiscrollview manage "cells" yourself. collection views useful if need content "flow" in way think not case here. you might consider table view includes vertical scrolling , row editing etc. still have deal horizontal offscreen content yourself. with uiscrollview have full flexibility lay out cells (like tiles) desired in fixed way. panning , zooming included free.

python - First common element from two lists -

x = [8,2,3,4,5] y = [6,3,7,2,1] how find out first common element in 2 lists (in case, "2") in concise , elegant way? list can empty or there can no common elements - in case none fine. i need show python new it, simpler better. upd: order not important purposes, let's assume i'm looking first element in x occurs in y. this should straight forward and effective gets (for more effective solution check ashwini chaudharys answer , effective check jamylaks answer , comments): result = none # go trough 1 array in x: # element repeats in other list... if in y: # store result , break loop result = break or event more elegant encapsulate same functionality function using pep 8 coding style conventions : def get_first_common_element(x,y): ''' fetches first element x common both lists or return none if no such element found. ''' in x: if in y: return

angularjs - ng-grid headerRowTemplate - Has anyone used this? -

my team wanting use feature of ng-grid. not seem documented anywhere. put "plus" icon last column of header area of ng-grid. has found way this? just modify headercelltemplate last column in grid (see https://github.com/angular-ui/ng-grid/wiki/templating ). here example (note <img src="plus-icon.png" /> in second line): var myheadercelltemplate = '<div class="ngheadersortcolumn {{col.headerclass}}" ng-style="{\'cursor\': col.cursor}" ng-class="{ \'ngsorted\': !nosortvisible }">' + '<div ng-click="col.sort($event)" ng-class="\'colt\' + col.index" class="ngheadertext">{{col.displayname}} <img src="plus-icon.png" /></div>' + '<div class="ngsortbuttondown" ng-show="col.showsortbuttondown()"></div>' +

signals - Linear Frequency Modulated Wave -

i trying generate lfm wave in matlab. using code: samplerate = 1e8; % define sample rate of baseband signal (hz) pulsewidth = 10e-6; % define pulse width (seconds) pulserepititioninterval = 50e-6;% define pulse repetition interval (seconds) bandwidth = 10e6; % bandwidth of pulse (hz) iphase = 0; % initial phase in degrees of icomponent qphase = 90; % initial phase in degrees of qcomponent tvector = 0:1/samplerate:pulsewidth; % vector generate ideal pulse icomponent = chirp(tvector,-bandwidth/2,tvector(end), bandwidth/2,'linear',iphase); qcomponent = chirp(tvector,-bandwidth/2,tvector(end), bandwidth/2,'linear',qphase); iqdata = icomponent + 1i*qcomponent; but pulse specification like: pulse width 50e-6 , number of samples in each pulse 1024 , number of pulses 10. please tell changes make in this, or other new have try...

php - Initializing Codeigniter Utilities inside contstructor on Custom Class -

i have been doing ci few months , got point wanted create own library class on ci. now, problem can't seem instance of ci in order me utilize native resources. i've done this. class myclass{ protected $instance; public function __construct() { $this->$instance = &get_instance(); <-- did (theoretically speaking) } } other things i've tried class myclass{ protected $instance = &get_instance(); <-- reports syntax error on apatana public function __construct() { } } anyone of out there can give me better idea on how instance (initializing 1 point on source code) <-- being said that, wanted instance once , use on over class you can use in way in constructor $this->ci = & get_instance(); can use $this->ci->load->model();

java - LibGdx What is the proper way to copy an Actor? -

i have custom implementation of image animates. want make multiple copies of instance of class using minimum memory , processor time rendering , copying. how go it? easiest recreate whenever need 1 or there proper or suggested method copying image instances. ask because can't find copy constructor , don't know if .clone() implemented in image. if want take care memory can give actors same image. if change image in way , @ 1 of actors change @ actors it(i did sprite , changed textureregion. monsters looked @ same direction). if have same image whole time can create objects , give same reference 1 image. for example this: public arraylist<actor> generateimageactor(){ arraylist<actor> temp = new arraylist<actor>(); image img = new image(____); for(int = 0; <10; i++){ myactor act = new myactor(img); temp.add(act); } return temp; } the rendertime not effect if refare 1 image or

apex code - How to turn off error messages in visualforce? -

i have visualforce page has 3 functionalities, hence has 3 'public pagereference' subroutines, called when action happens in page [i.e. button] one of functionalities requires user input [i.e. inputtext], main apex code has variable declaration input: public string userinput { get; set; } since each task not related, when hit button on other 2 functionalities, visualforce error, because inputtext object has no user input, how can prevent happening, another way solve this, how turn off visualforce error messages? can error handling apex, looking @ debug log file, error in visualforce not apex, thanks if don't want fire validation can use immediate = true attribute on commandbutton/commandlink bypass validation. - isn't optimal in opinion if want submit part of page , still fire validation have @ actionregion. should allow wrap particular region action call. best purpose. sorry don't have time post full examples should point in right dire

scala - Custom JodaTime serializer using Play Framework's JSON library? -

how implement custom jodatime's datetime serializer/deserializer json? i'm inclined use play framework's json library (2.1.1). there default datetime serializer, uses dt.getmillis instead of .tostring return iso compliant string. writing reads[t] amd writes[t] case classes seems straightforward, can't figure out how same datetime. i use play 2.3.7 , define in companion object implicit reads/writes string pattern: case class user(username:string, birthday:org.joda.time.datetime) object user { implicit val yourjodadatereads = reads.jodadatereads("yyyy-mm-dd't'hh:mm:ss'z'") implicit val yourjodadatewrites = writes.jodadatewrites("yyyy-mm-dd't'hh:mm:ss'z'") implicit val userformat = json.format[user] }

R How to call '[.class<-' directly -

out of curiosity, how call '[.class' function in r directly? i know can do: test <- c(2,4,6) test[2] but possible specify class directly? , if so, how? '[.numeric<-'(test , 2) '[.numeric'(test , 2) i have tried these come error: not find function "[.numeric" [ internal generic , means dispatch occurs in c, , base types (like numeric) don't have s3 methods in r. that's why there's no [.numeric or [<-.numeric . it's not clear want, example, can do test <- 1:3 `[`(test, 2) `[<-`(test, 2, 3)

jslint - In Javascript, under what conditions is it appropriate to only use `this` in constructor functions? -

i found an interesting line of code in jshint's config options. the comment associated option reads tolerate using in non-constructor function. i confused. misunderstanding config option? aren't there lot of cases want use this in non-constructor function? when ever want warned it? this options used tell jshint function invoked valid this parameter. for example: function myrandomfunction() { alert(this.something); } myrandomfunction.call(someobject); if strict mode on, jshint warn myrandomfunction shouldn't using this , since doesn't constructor or member function. if know called this (eg, callback), can add /*jshint validthis: true */ suppress warning.