Monday, 15 February 2010

php - Yii webcam extension -



php - Yii webcam extension -

in yii,iam using yii-jpegcam webcam extension used taking photos in application , works fine next url format

index.php?r=user/newphoto

but application in "/" format (index.php/user/newphoto). extension not working url format. how can solved?

extension link used : http://www.yiiframew...on/yii-jpegcam/ http://www.yiiframework.com/extension/yii-jpegcam/

and view code :

<?php $onbeforesnap = "document.getelementbyid('upload_results').innerhtml = '<h1>uploading...</h1>';"; $completionhandler = <<<block if (msg == 'ok') { document.getelementbyid('upload_results').innerhtml = '<h1>ok! ...redirecting in 3 seconds</h1>'; // reset photographic camera shot webcam.reset(); settimeout(function(){window.location = "index.php?r=user/index";},3000); } else alert("php error: " + msg); block; $this->widget('application.extensions.jpegcam.ejpegcam', array( 'apiurl' => 'index.php?r=user/jpegcam.savejpg', 'shuttersound' => false, 'stealth' => true, 'buttons' => array( 'configure' => 'configure', 'takesnapshot' => 'take snapshot!' ), 'onbeforesnap' => $onbeforesnap, 'completionhandler' => $completionhandler )); ?>

if urlmanager enabled in config, should alter apiurl value createurl method :

$this->widget('application.extensions.jpegcam.ejpegcam', array( 'apiurl' => yii::app()->urlmanager->createurl('index.php/user/jpegcam.savejpg'), 'shuttersound' => false, 'stealth' => true, 'buttons' => array( 'configure' => 'configure', 'takesnapshot' => 'take snapshot!' ), 'onbeforesnap' => $onbeforesnap, 'completionhandler' => $completionhandler ));

php yii webcam yii-extensions yii-components

java - in working with ejb I have problems understanding something from the code below. it works perfect just confused about the lookup process(see code) -



java - in working with ejb I have problems understanding something from the code below. it works perfect just confused about the lookup process(see code) -

in working ejb have problems understanding code below. works perfect confused lookup process(see code)

import java.util.properties; import javax.naming.context; import javax.naming.initialcontext; import javax.naming.namingexception; import com.coolstory.thebeanremote; public class main { /** * @param args * @throws namingexception */ public static void main(string[] args) { // todo auto-generated method stub properties p= new properties(); p.put((context.provider_url) ,"t3://localhost:7001"); p.put((context.initial_context_factory),"weblogic.jndi.wlinitialcontextfactory"); seek { //create context , pass in properties contain lookup info context ctx= new initialcontext(p); thebeanremote bean= (thebeanremote)ctx.lookup("mrbean#com.coolstory.thebeanremote"); /*what pound sign function here confused */ string x= ctx.getenvironment().tostring(); system.out.println(x); bean.sayhi(); system.out.println("main.main()"+ bean.sayhi()); } grab (namingexception e) { // todo auto-generated grab block e.printstacktrace(); } }

the convention <ejb-name>#<interface-name>, # delimiter between ejb name , interface name.

java ejb-3.0 jndi

c++ - How to return a lambda function? -



c++ - How to return a lambda function? -

for example, can define lambda function as

auto f = [](double value) {double ratio = 100; homecoming value * ratio;}

now want generate function ratio argument , homecoming lambda function like

auto makelambda(double ratio) { homecoming [=](double value) {return value * ratio;}; }

how it?

with c++14 function homecoming type deduction, should work.

in c++11, define lambda (which can deduce homecoming type), rather function (which can't):

auto makelambda = [](double ratio) { homecoming [=](double value) {return value * ratio;}; };

as noted in comments, farther wrapped, if particularly want function:

auto makelambdafn(double ratio) -> decltype(makelambda(ratio)) { homecoming makelambda(ratio); }

c++ c++11 lambda

delphi - Trying to remove all vowels from a phrase -



delphi - Trying to remove all vowels from a phrase -

i trying create programme remove vowels sentence or phrase. don't syntax error, when add together word 'cool' or more 2 vowels next each other, not of them removed. why this? here code:

procedure tform1.btnprocessclick(sender: tobject); var sentence: string; k : integer; begin sentence :=uppercase(edtsentence.text); k := 1 length(sentence) if (sentence[k] in ['a', 'e', 'i', 'o', 'u']) begin delete(sentence,k,1); lbloutput.caption := sentence; end;

you counting when deleting instead of counting down.

your loop should read :-

for k := length(sentence.text) downto 1 do

delphi delphi-xe

C# Regex to C++ boost::regex -



C# Regex to C++ boost::regex -

i have requirement match strings in c++ code of form

l, n{1, 3}, n{1, 3}, n{1, 3}

where in above pseudo-code, l letter (upper or lower case) or fullstop (. character) , n numeric [0-9].

so explicitly, might have b, 999, 999, 999 or ., 8, 8, 8 number of numeric characters same after each , , either 1, 2 or 3 digits in length; d, 23, 232, 23 not possible.

in c# match follows

string s = " b,801, 801, 801 other stuff"; regex reg = new regex(@"[\.\w],\s*\d{1,3},\s*\d{1,3},\s*\d{1,3}"); match m = reg.match(s);

great. however, need similar regex using boost::regex. have attempted

std::string s = " b,801, 801, 801 other stuff"; boost::regex regex("[\\.\w],\s*\d{1,3},\s*\d{1,3},\s*\d{1,3}"); boost::match_results<std::string::const_iterator> results; boost::regex_match(s, results, regex);

but giving me 'w' : unrecognized character escape sequence , same s , d. documentation under impression can utilize \d, \s , \w without issue.

what doing wrong here?

edit. have switched std::regex as-per comment above. now, presumably regex same , next compiles regex does not match...

std::string p = "xx"; std::string s = " b,801, 801, 801 other stuff"; std::regex regex(r"del([\.\w],\s*\d{1,3},\s*\d{1,3},\s*\d{1,3})del"); if (std::regex_match(s, regex)) p = std::regex_replace(s, regex, "");

you can utilize \w, \s, , \d in regular expressions. however, that's not you're doing; you're trying utilize \w character in string. there \ followed w in actual string, need escape \ (same s , d, of course):

boost::regex regex("[\\.\\w],\\s*\\d{1,3},\\s*\\d{1,3},\\s*\\d{1,3}");

as of c++11, can utilize raw string literals create code more similar c# version:

boost::regex regex(r"del([\.\w],\s*\d{1,3},\s*\d{1,3},\s*\d{1,3})del");

c# c++ boost boost-regex

javascript - Rotate Polygon with Coordinates -



javascript - Rotate Polygon with Coordinates -

i trying rotate polygon (3 edges) (i have coordinates of edges). i'm using cos , sin new coordinates of every single point, doesn't work have no thought why.

http://jsfiddle.net/sh3rlock/gqk23/

(m middle-point of polygon , kr radius of circle)

newx = x + ((x - m[0]) * c - (y - m[1]) * s) * kr;

newy = y + ((y - m[1]) * c + (x - m[0]) * s) * kr;

function drawplayer(x, y, r, tcolor) { if (typeof c === "undefined") color = 'rgba(0,0,200,1)'; //canvas.width = canvas.width; var radians = r * (math.pi / 180); var m = getmiddleofpg([ [x, y + 5], [x, y - 5], [x + 15, y] ]); // mitte des polygons var = [x, y + 5]; var b = [x, y - 5]; var c = [x + 15, y]; drawpolygonfromarray([a, b, c], ctx, 'rgba(0,200,0,1)'); var speed = 1; var right = math.cos(radians) * 1; var = -(math.sin(radians) * 1); var x2 = x; var y2 = y; var c = math.cos(radians); var s = math.sin(radians); x = x2; y = y2 + 5; var kr = math.sqrt((x - m[0]) * (x - m[0]) + (y - m[1]) * (y - m[1])); var ax = x + ((x - m[0]) * c - (y - m[1]) * s) * kr; var ay = y + ((y - m[1]) * c + (x - m[0]) * s) * kr; x = x2; y = y2 - 5; kr = math.sqrt((x - m[0]) * (x - m[0]) + (y - m[1]) * (y - m[1])); var bx = x + ((x - m[0]) * c - (y - m[1]) * s) * kr; var = y + ((y - m[1]) * c + (x - m[0]) * s) * kr; x = x2 + 15; y = y2; kr = math.sqrt((x - m[0]) * (x - m[0]) + (y - m[1]) * (y - m[1])); var cx = x + ((x - m[0]) * c - (y - m[1]) * s) * kr; var cy = y + ((y - m[1]) * c + (x - m[0]) * s) * kr; x = x2; y = y2; var = [ax, ay]; var b = [bx, by]; var c = [cx, cy]; drawpolygonfromarray([a, b, c], ctx, tcolor); drawmiddleofpg([a, b, c], 'rgba(255,0,0,1)'); //drawmiddleofpg([[x,y],[x,y-5],[x+15,y]], 'rgba(0,255,0,1)'); //alert(right + " " + up); cr += 20; if (cr > 255) { cb += 20; cr = 0; } if (cb > 255) { cg += 20; cb = 0; cr = 0; } t = settimeout(function () { drawplayer(x, y, r + 1, 'rgba(' + cr + ',' + cb + ',' + cg + ',1)') }, 20); return;

javascript rotation polygon

android - ListView in Fragment won't refresh -



android - ListView in Fragment won't refresh -

i trying create list in fragment, able grow when pressing button.

the list within fragment.

here's part of mainactivity:

public class mainactivity extends fragmentactivity{

public static string[] values = { "" }; private static listview listview; public static notesdbadapter helper; public static arraylist<fragment> fragments; public static viewpager viewpager; public static custompageradapter pageradapter; public static customlistadapter listadapter; @override protected void oncreate(bundle arg0) { super.oncreate(arg0); setcontentview(r.layout.activity_main); viewpager = (viewpager)findviewbyid(r.id.viewpager); listadapter = new customlistadapter(this); helper = new notesdbadapter(this); helper.open(); pageradapter = new custompageradapter(getsupportfragmentmanager()); fragments = new arraylist<fragment>(); fragments.add(new listfragment()); log.d("debug", "helper count: " + integer.tostring(helper.fetchallnotes().getcount())); values = new string[helper.fetchallnotes().getcount()]; for(int = 0; < values.length; i++) { values[i] = "klappt"; } updatelist(); viewpager.setadapter(pageradapter); } public void addnote() { log.d("debug", "new note"); helper.createnote("", ""); updatelist(); } public class customlistadapter extends arrayadapter<string> { private context context; private int res; private textview textview; public customlistadapter(context context) { super(context, r.layout.list_item, values); this.context = context; this.res = r.layout.list_item; } @override public view getview(int position, view convertview, viewgroup parent) { layoutinflater inflater = (layoutinflater) context.getsystemservice(layout_inflater_service); view rowview = inflater.inflate(res, parent, false); textview = (textview)rowview.findviewbyid(r.id.list_item_textview); textview.settext(values[position]); homecoming rowview; } } public static class listfragment extends fragment { @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view v = inflater.inflate(r.layout.fragment_list, container, false); listview = (listview)v.findviewbyid(r.id.fragment_list_listview); listview.setadapter(listadapter); homecoming v; } } public void updatelist() { values = new string[helper.fetchallnotes().getcount()]; for(int = 0; < values.length; i++) { values[i] = "klappt"; } listadapter.notifydatasetchanged(); }

}

so add together item list pressing on actionbar item. works, can confirm that. see alter have leave app , re-enter see changes or alter screen orientation landscape , back. want immeadiately show updated list, don't know how.

listadapter.notifydatasetchanged();

does not work me, don't know why. tried create new listadapter so:

listadapter = new customlistadapter(getapplicationcontext());

and set listview adapter:

listview.setadapter(listadapter);

but forcefulness close (i don't know why).

so know haven't got thought how prepare problem. able refresh listview when calling updatelist() method.

i logcat when trying apply new adapter listview:

06-19 18:17:32.506: e/androidruntime(12259): java.lang.runtimeexception: unable start activity componentinfo{com.ochs.androidnotepad/com.ochs.androidnotepad.mainactivity}: java.lang.nullpointerexception

android listview android-fragments android-listview

dynamic - spring batch : Read flat file which is getting changed continously -



dynamic - spring batch : Read flat file which is getting changed continously -

i have requirement, have read flat text file continuously changing. let's assume have file 100 lines read using flatfilereader in batch , process lines. 1 time again when step gets called let's after 30 sec, there 110 lines. in case batch should read line 101. know there 'linestoskip' parameter in reader can define @ start of batch not dynamically. file defined in batch configuration should reloaded 1 time again on phone call of step(step continuous process).

any thought this?

thanks niraj

i suggest next approach:

wrap reader step listener , utilize before , after hooks. create sure both step , flatfileitemreader bean defined @ step scope.

in before step read lastly line processed count persistence (file/db/etc) , place on stepexecutioncontext. use value placed on stepexecutioncontext set linestoskip in flatfileitemreader using spel in after step take current writecount , skipcount execution context sum value before step. persist value next execution

your listener similar 1 below

@component public class linecursorlistener implements steplistener { @beforestep public exitstatus beforestep(stepexecution stepexecution){ int curser = 0;//read persistence stepexecution.getexecutioncontext().put("linestoskip", curser); homecoming stepexecution.getexitstatus(); } @afterstep public exitstatus afterstep(stepexecution stepexecution){ int nextcurser= stepexecution.getwritecount() + stepexecution.getskipcount(); nextcurser =nextcurser + stepexecution.getexecutioncontext().getint("linestoskip"); // persistence nextcurser homecoming stepexecution.getexitstatus(); } }

your job xml similar

<batch:job> ... <batch:step id="processcsv"> <batch:tasklet transaction-manager="transactionmanager"> <batch:chunk reader="somefilereader" writer="writter" commit-interval="10" /> </batch:tasklet> <batch:listeners> <batch:listener ref="linecurserlistener" /> </batch:listeners> </batch:job> <bean id="somefilereader" scope="step" class="org.springframework.batch.item.file.flatfileitemreader" > ... <property name="linestoskip" value="#{stepexecutioncontext['linestoskip']}" /> <property name="linemapper"> ... </property> </bean>

i presenting spring batch point of view issue, guess need watch out concurrency issue related file read/write

dynamic spring-batch filereader

sql server - why the row is not blocked? -



sql server - why the row is not blocked? -

i using transaction in sql server managemnet studio 2012

begin transaction select * tabl1 with(xlock, rowlock) id = 1153; select * table2; rollback

i set breakpoint in sec query. first query block row of pieza id 1153 while transaction not commit or rollback, when code stop in breakpint, in instance of sql server management studio do:

select * table1

this query think wating until transaction of first sql server management studio finish, las query can finish without problem.

however if in t-sql in transaction ef row blocked.

i have tried too:

begin transaction select * tabl1 with(xlock, rowlock) id = 1153; go select * table2; rollback

but not solve problem.

how can seek hints of sql server in management studio?

thanks.

edit:

this transaction blocks row:

begin transaction select * tabl1 with(xlock, rowlock);

select * table2; rollback

so when set status id row not blocked.

from: http://msdn.microsoft.com/en-us/library/ms187373.aspx

lock hints rowlock, updlock, , xlock acquire row-level locks may place locks on index keys rather actual info rows. example, if table has nonclustered index, , select statement using lock hint handled covering index, lock acquired on index key in covering index rather on info row in base of operations table.

so index satisfying first query, sec (select *) can satisfied clusterd index.

sql-server transactions block hint

html - Prevent contenteditable element from getting focus when clicking parent -



html - Prevent contenteditable element from getting focus when clicking parent -

when clicking anywhere above "outside" div container in next example, contenteditable span element gets focus.

<div style="margin:30px"> <span contenteditable="true" style="background:#eee"> hello world </span> <div>outside</div> </div>

here's jsfiddle: http://jsfiddle.net/axm4y/

i want contenteditable behave more real text input, clicking span element should trigger focus. how do this? how can event capturing of container element stopped. i've tried "e.stoppropagation()" jquery on parent div, didn't work.

i fixed way set pointer-events: none on parent element , pointer-events: all on element content editable attribute.

html events focus contenteditable

java - Select query using Prepared Statement -



java - Select query using Prepared Statement -

i not know wrong in code. next conditions in code given below:

i come in client id in jtextfield after entering client id in database search relative info of client id (customer_id,customer_name,customer_contact). after collecting relative info of particular client id, display on jtextfield.

these code given below:

import java.awt.container; import java.awt.event.actionevent; import java.awt.event.actionlistener; import java.sql.*; import javax.swing.*; public abstract class customer_details extends jframe implements actionlistener { jtextfield textfieldid; jtextfield textfieldid1; jtextfield textfieldid2; jtextfield textfieldid3; jlabel l1; jlabel l2; jlabel l3; jlabel l4; jlabel l5; jbutton b1,b2; container c = getcontentpane(); customer_details() { super("shree datta digambar"); setbounds(140,250,777,555); c.setlayout(null); textfieldid = new jtextfield(); textfieldid1 = new jtextfield(); textfieldid2 = new jtextfield(); textfieldid3 = new jtextfield(); this.setextendedstate(jframe.maximized_both); l1 = new jlabel("update client details:-"); l2 = new jlabel("customer id"); l3 = new jlabel("customer id"); l4 = new jlabel("name"); l5 = new jlabel("contact"); l1.setbounds(10,10,340,20); l2.setbounds(10,20,140,70); l3.setbounds(10,100,140,70); l4.setbounds(100,100,140,70); l5.setbounds(270,100,140,70); textfieldid.setbounds(10,70,70,20); textfieldid1.setbounds(10,160,70,20); textfieldid2.setbounds(100,160,150,20); textfieldid3.setbounds(270,160,90,20); b1 = new jbutton("ok"); b1.setbounds(100,70,50,20); b2 = new jbutton("update"); b2.setbounds(380,160,90,20); c.add(b1); c.add(b2); c.add(l1); c.add(l2); c.add(l3); c.add(l4); c.add(l5); c.add(textfieldid); c.add(textfieldid1); c.add(textfieldid2); c.add(textfieldid3); setvisible(true); setdefaultcloseoperation(exit_on_close); b1.addactionlistener(this); b2.addactionlistener(this); } public static void main(string[] args) { customer_details eeap=new customer_details() {}; } public void actionperformed(actionevent e) { system.out.println("you clicked button"); if(e.getsource()==b1) { seek { connection con; con = drivermanager.getconnection("jdbc:odbc:dalvi"); java.sql.statement st = con.createstatement(); preparedstatement ps = con.preparestatement("select customer_id,customer_name,customer_contact customer_details customer_id = ?"); ps.setstring(1,textfieldid.gettext()); resultset rs1=ps.executequery(); while(rs1.next()) { textfieldid1.settext(rs1.getstring(1)); textfieldid2.settext(rs1.getstring(2)); textfieldid3.settext(rs1.getstring(3)); } textfieldid.settext(""); } grab (sqlexception s) { system.out.println("sql code not execute."); joptionpane.showmessagedialog(null,"please come in detail correctly"); } } }

}

take @ query (formatting added improve readability, inconsequential issue):

select customer_id,customer_name,customer_contact customer_details customer_id = ' ?'

by surrounding ? single quotes ('), you've turned in sql character literal. way, jdbc not recognize special character, , cannot bind it. if remove them, jdbc able bind (and take care of datatypes too):

select customer_id,customer_name,customer_contact customer_details customer_id = ?

java sql jdbc

C# PHP AES 256 CBC Encryption -



C# PHP AES 256 CBC Encryption -

hello i'm trying encrypt files/strings on server using php , aes 256 cbc mode, because of strings ending '\0' can easly remove padding them aes adds, files cannot because of them contain null bytes. before send info encode base64 string.

here c# decrypt function

internal static byte[] __aes_decrypt(byte[] input, string _key, string _iv) { var myrijndael = new rijndaelmanaged() { padding = paddingmode.zeros, mode = ciphermode.cbc, keysize = 256, blocksize = 256 }; byte[] key = encoding.ascii.getbytes(_key); byte[] iv = encoding.ascii.getbytes(_iv); var decryptor = myrijndael.createdecryptor(key, iv); var sencrypted = input; var fromencrypt = new byte[sencrypted.length]; var msdecrypt = new memorystream(sencrypted); var csdecrypt = new cryptostream(msdecrypt, decryptor, cryptostreammode.read); csdecrypt.read(fromencrypt, 0, fromencrypt.length); homecoming fromencrypt; }

this function works fine strings , bytes too. believe php encrypt function wrong files works strings.

function encrypt($str) { $key = 'keygoeshere'; $iv = "ivgoeshere"; $str =mcrypt_encrypt(mcrypt_rijndael_256, $key, $str, mcrypt_mode_cbc, $iv); //$str = str_replace("\0","",$str); works strings not files. homecoming base64_encode($str); }

if don't want alter form of padding, append single 1 byte end of file contents, , on decryption, after removing trailing nulls, remove appended 1 byte. won't accidently remove 0 bytes belong file.

c# php encryption aes

c# - Generic BeginInvoke Scheme to ensure function calls in same threading context -



c# - Generic BeginInvoke Scheme to ensure function calls in same threading context -

i'm moving code winforms command object separate object improve modularity. however, there calls external object issuing callbacks, have no command of , can fired different threads main ui thread. avoid utilize known begininvoke scheme check, whether phone call should transfered main ui thread.

when move code separated object, have not necessary winforms reference anymore. handle on command object still ensure running in same thread. rather have generic mechanism same ensuring, threadconext in e.g. object created or specific entry function called used subsequent calls issued e.g. external callbacks.

how achieved ?

example:

public class illustration { threadedcomponent _cmp = new threadedcomponent(); public example() { _cmp.threadedcallback += new threadedcomponent.cb(callback); } public void startfunction() { // called in threadcontexta _cmp.start(); } void callback(status s) { // called in threadcontextb if(s == somestatus) _cmp.continuefunction(); // must called in threadcontexta } }

for clarification

continuefunction must called same threadcontext startfunction called. not ui thread, @ moment of course of study button handler.

there no 'generic' scheme, class cannot create lot of assumptions thread used on , object can provide begininvoke() method need. take 1 of next options:

do not help @ all, document event can raised on worker thread. whatever code exists in gui layer can of course of study figure out how utilize begininvoke() when needed.

allow client code pass command object through class constructor. can store , phone call begininvoke() method. works, isn't terribly pretty because class usable in winforms project.

expose property called "synchronizingobject" of type isynchronizeinvoke. gui layer has option inquire phone call isynchronizeinvoke.begininvoke(). if property set, fire event straight otherwise. several .net framework classes this, process, filesystemwatcher, eventlog, etc. has same problem previous solution, interface isn't readily available in non-winforms application.

demand client code creates object on ui thread. , re-create synchronizationcontext.current in constructor. can, later, utilize post() method invoke. compatible option, gui class libraries in .net provide value property.

do maintain problem in mind when take 1 of latter bullets. client code event unsynchronized thread's code execution. concrete event handler want access properties on class find out more state of class. state unlikely still valid since thread has progressed past begininvoke() call. client code has no alternative @ insert lock prevent causing trouble. should consider not help @ if that's real issue, is.

c# .net multithreading thread-safety

java - flume-ng - avro event delivery reliability -



java - flume-ng - avro event delivery reliability -

i using flume-ng aggregate info produced applications central location processing. producers publish events local http source, forwarded collectors via avro sink. collectors receive events avro sink via avro source. producers replicate events both collectors.

i have noticed few nuances in wild concern me, , have not been able understand finish ramifications of configuration via docs , surrounding info on flume-ng. apple apple comparing of event publication producer indicates not events arrive @ collector. latency of events delivered higher anticipated. see events landing @ front end door of collector hours behind schedule. intermittent exceptions in both downstream , upstream flume-ng logs.

using file channels on producer leads me believe still durable, flume-ng eventually events upstream (correct?). with collectors leveraging memory channels exposing ourselves info loss? if so, there techniques determining how many events lost, or @ to the lowest degree how lost? with collector's transaction capacity lower producer, issues arise? what sane checkpoint intervals file channels requiring guaranteed delivery? assume interval how flume-ng ensures events on local disk (eg. based on configuration expect maximum 1s info loss in powerfulness outage, etc).

below relevant snippets of each stage's flume-ng configuration stack trace snippets. wondering if can shed lite on discrepancies in configuration based on aforementioned questions (assuming there any).

upstream exceptions:

(org.apache.avro.ipc.nettyserver$nettyserveravrohandler.channelclosed:209) - connection /<ip address>:<port> disconnected. (org.apache.avro.ipc.nettyserver$nettyserveravrohandler.exceptioncaught:201) - unexpected exception downstream.

downstream exceptions:

(org.apache.flume.sinkrunner$pollingrunner.run:160) - unable deliver event. exception follows. org.apache.flume.eventdeliveryexception: failed send events @ org.apache.flume.sink.abstractrpcsink.process(abstractrpcsink.java:382) @ org.apache.flume.sink.defaultsinkprocessor.process(defaultsinkprocessor.java:68) @ org.apache.flume.sinkrunner$pollingrunner.run(sinkrunner.java:147) @ java.lang.thread.run(thread.java:679) caused by: org.apache.flume.flumeexception: nettyavrorpcclient { host: <producer ip>, port: <producer port> }: rpc connection error @ org.apache.flume.api.nettyavrorpcclient.connect(nettyavrorpcclient.java:161) @ org.apache.flume.api.nettyavrorpcclient.connect(nettyavrorpcclient.java:115) @ org.apache.flume.api.nettyavrorpcclient.configure(nettyavrorpcclient.java:590) @ org.apache.flume.api.rpcclientfactory.getinstance(rpcclientfactory.java:88) @ org.apache.flume.sink.avrosink.initializerpcclient(avrosink.java:127) @ org.apache.flume.sink.abstractrpcsink.createconnection(abstractrpcsink.java:209) @ org.apache.flume.sink.abstractrpcsink.verifyconnection(abstractrpcsink.java:269) @ org.apache.flume.sink.abstractrpcsink.process(abstractrpcsink.java:339) ... 3 more caused by: java.io.ioexception: error connecting /<producer ip>:<producer port> @ org.apache.avro.ipc.nettytransceiver.getchannel(nettytransceiver.java:261) @ org.apache.avro.ipc.nettytransceiver.<init>(nettytransceiver.java:203) @ org.apache.avro.ipc.nettytransceiver.<init>(nettytransceiver.java:152) @ org.apache.flume.api.nettyavrorpcclient.connect(nettyavrorpcclient.java:147) ... 10 more caused by: java.net.noroutetohostexception: no route host @ sun.nio.ch.socketchannelimpl.checkconnect(native method) @ sun.nio.ch.socketchannelimpl.finishconnect(socketchannelimpl.java:592) @ org.jboss.netty.channel.socket.nio.nioclientsocketpipelinesink$boss.connect(nioclientsocketpipelinesink.java:396) @ org.jboss.netty.channel.socket.nio.nioclientsocketpipelinesink$boss.processselectedkeys(nioclientsocketpipelinesink.java:358) @ org.jboss.netty.channel.socket.nio.nioclientsocketpipelinesink$boss.run(nioclientsocketpipelinesink.java:274) @ java.util.concurrent.threadpoolexecutor.runworker(threadpoolexecutor.java:1146) @ java.util.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor.java:615) ... 1 more

producer configuration:

agent.sources.t1d.type = http agent.sources.t1d.bind = <source ip> agent.sources.t1d.port = <source port> agent.sources.t1d.channels = c01 c02 c03 agent.sources.t1d.selector.type = replicating agent.channels.c01.type = file agent.channels.c01.checkpointdir = /path/to/checkpoint1 agent.channels.c01.datadirs = /path/to/data1 agent.channels.c01.capacity = 4000000 agent.channels.c01.transactioncapacity = 10000 agent.channels.c01.checkpointinterval = 1000 agent.channels.c01.keep-alive = 3 agent.channels.c02.type = file agent.channels.c02.checkpointdir = /path/to/checkpoint2 agent.channels.c02.datadirs = /path/to/data2 agent.channels.c02.capacity = 4000000 agent.channels.c02.transactioncapacity = 10000 agent.channels.c02.checkpointinterval = 1000 agent.channels.c02.keep-alive = 3 agent.channels.c03.type = file agent.channels.c03.checkpointdir = /path/to/checkpoint3 agent.channels.c03.datadirs = /path/to/data3 agent.channels.c03.capacity = 4000000 agent.channels.c03.transactioncapacity = 10000 agent.channels.c03.checkpointinterval = 1000 agent.channels.c03.keep-alive = 3 agent.sinks.s01.type = avro agent.sinks.s01.hostname = <collector ip> agent.sinks.s01.port = <collector port> agent.sinks.s01.channel = c01 agent.sinks.s01.batch-size = 1000 agent.sinks.s01.compression-type = deflate agent.sinks.s01.compression-level = 5 agent.sinks.s02.type = avro agent.sinks.s02.hostname = <collector ip> agent.sinks.s02.port = <collector port> agent.sinks.s02.channel = c02 agent.sinks.s02.batch-size = 1000 agent.sinks.s02.compression-type = deflate agent.sinks.s02.compression-level = 5 agent.sinks.s03.type = file_roll agent.sinks.s03.channel = c03 agent.sinks.s03.sink.directory = /path/to/producer/reconciliation agent.sinks.s03.sink.rollinterval = 1200

collector configuration:

agent.sources.a.type = avro agent.sources.a.bind = <source ip> agent.sources.a.port = <source port> agent.sources.a.channels = c01 c03 agent.sources.a.compression-type = deflate agent.channels.c01.type = memory agent.channels.c01.capacity = 1000000 agent.channels.c01.transactioncapacity = 1000 agent.channels.c03.type = memory agent.channels.c03.capacity = 1000000 agent.channels.c03.transactioncapacity = 1000 agent.sinks.s01.type = file_roll agent.sinks.s01.channel = c01 agent.sinks.s01.sink.directory = /path/to/storage/s01 agent.sinks.s01.sink.rollinterval = 300 agent.sinks.s03.type = file_roll agent.sinks.s03.channel = c03 agent.sinks.s03.sink.directory = /path/to/storage/s03 agent.sinks.s03.sink.rollinterval = 300

collector b configuration:

agent.sources.b.type = avro agent.sources.b.bind = <source ip> agent.sources.b.port = <source port> agent.sources.b.channels = c11 c13 agent.sources.b.compression-type = deflate agent.channels.c11.type = memory agent.channels.c11.capacity = 1000000 agent.channels.c11.transactioncapacity = 1000 agent.channels.c13.type = memory agent.channels.c13.capacity = 1000000 agent.channels.c13.transactioncapacity = 1000 agent.sinks.s11.type = file_roll agent.sinks.s11.channel = c11 agent.sinks.s11.sink.directory = /path/to/storage/s11 agent.sinks.s11.sink.rollinterval = 300 agent.sinks.s13.type = file_roll agent.sinks.s13.channel = c13 agent.sinks.s13.sink.directory = /path/to/storage/s13 agent.sinks.s13.sink.rollinterval = 300

java flume flume-ng

arrays - Why autoboxing is not supporting in collection.toArray() in java -



arrays - Why autoboxing is not supporting in collection.toArray() in java -

is there no short cutting nicely?

that ugly 2 loops (one loop read pmlist , sec loop add together markuparray) alternative (instead of arrayutils).

arraylist<double> pmlist = new arraylist<double>(); pmlist.add(0.1); // adding through loop in real time. pmlist.add(0.1); pmlist.add(0.1); pmlist.add(0.1); double[] markuparray = new double[pmlist.size()]; arkuparray = pmlist.toarray(markuparray); // says method toarray(t[]) in type arraylist<double> not applicable arguments (double[])

simply utilize double[] array, instead of double[] works fine. if know size of list ahead of time, can skip list , insert straight array. might worth traverse input 2 times: 1 time retrieving size , 1 time insertion.

auto boxing works primitive types, not arrays of primitive types. double[] array no t[] array, since type parameter t must object. while double may autoboxed t (with t=double), double[] cannot autoboxed t[].

the reason why arrays not autoboxed operation costly: boxing array means creating new array , boxing each element. big arrays, has huge performance hit. don't want such costly operation done implicitly, hence no autoboxing arrays. in addition, boxing finish array yield new array. thus, when writing new array, changes not write through old array. see, there semantics problems array-boxing, not supported.

if must homecoming double[] array, must either write own function or utilize third-party library guava (see msandiford's answer). java collections framework has no methods (un)boxing of arrays.

java arrays collections

html - Javascript function does not work :/ -



html - Javascript function does not work :/ -

this question has reply here:

$(document).ready not working 5 answers jsfiddle code not working in regular browser 4 answers

this piece of code trying create expander button. re-create paste jsfiddle. why on jsfiddle not work on browser?

<!doctype html> <html> <body> <input type="button" id="button-1" value="(click here more information)"><br> <p id="special1"> blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah </p> <script> alert(0); $(document).ready(function(){ var count = 0; alert(1); $("#special1").hide(); $("#button-1").click(function(){ count++; if(count % 2 != 0){ $("#special1").show(); }else{ $("#special1").hide(); } }) }) </script> </body> </html>

you have not loaded jquery anywhere in page. jsfiddle loads you.

add script tag it:

<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>

if in browser's error console, saying undefined not function because $ not defined anywhere.

javascript html expand

.htaccess redirect homepage only to mobile -



.htaccess redirect homepage only to mobile -

i extremely new .htaccess files, still in learning process , copying code find around web want. redirect homepage via .htaccess file in root directory mobile version of homepage. example, www.mysite.com (which www.mysite.com/index.html) gets redirected www.mysite.com/mobile on mobile devices. other pages on site such www.mysite.com/page1 remain intact , not undergo redirect. few snippets tried worked fine homepage /mobile, if user clicked on link take them page in site, got 1 time again redirected mobile home page forming endless loop. help appreciated, , 1 time again i'm new of this. give thanks much time.

.htaccess redirect mobile

c - Failed to create a simulated 2D dynamic array in a structure -



c - Failed to create a simulated 2D dynamic array in a structure -

struct level_info { char **map; } level[level_amount]; (int cnt_1 = 0; cnt_1 < level_amount; cnt_1++) { level[cnt_1].map = malloc(rbn_col * sizeof(char*)); (int cnt_2 = 0; cnt_2 < rbn_col; cnt_2++) level[cnt_1].*(map+cnt_2) = malloc(rbn_row * sizeof(char)); /* line 10 */ }

gcc says: expected identifier before 「*」 token @ line 10, how prepare it?

replace

level[cnt_1].*(map+cnt_2) = malloc(rbn_row * sizeof(char));

with

*(level[cnt_1].map+cnt_2) = malloc(rbn_row * sizeof(char));

or

level[cnt_1].map[cnt_2] = malloc(rbn_row * sizeof(char));

as sizeof(char) defintion 1 do

level[cnt_1].map[cnt_2] = malloc(rbn_row);

or remain flexible in terms of map points do

level[cnt_1].map[cnt_2] = malloc(rbn_row * sizeof(level[cnt_1].map[cnt_2][0]));

additionally please note prefered type index arrays size_t, not int.

so snippet should like:

struct level_info { char ** map; } level[level_amount]; (size_t cnt_1 = 0; cnt_1 < level_amount; ++cnt_1) { level[cnt_1].map = malloc(rbn_col * sizeof(level[cnt_1].map[0])); (size_t cnt_2 = 0; cnt_2 < rbn_col; ++cnt_2) { level[cnt_1].map[cnt_2] = malloc(rbn_row * sizeof(level[cnt_1].map[cnt_2][0])); } }

c pointers

python - Is there a non-copying constructor for a pandas DataFrame -



python - Is there a non-copying constructor for a pandas DataFrame -

reposted https://groups.google.com/forum/#!topic/pydata/5mhuatnal5g

it seems when creating dataframe structured array info copied? similar results if info instead dictionary of numpy arrays.

is there anyway create dataframe structured array or similar without copying or checking?

in [44]: sarray = randn(1e7,10).view([(name, float) name in 'abcdefghij']).squeeze() in [45]: n in [10,100,1000,10000,100000,1000000,10000000]: ...: s = sarray[:n] ...: %timeit z = pd.dataframe(s) ...: 1000 loops, best of 3: 830 µs per loop 1000 loops, best of 3: 834 µs per loop 1000 loops, best of 3: 872 µs per loop 1000 loops, best of 3: 1.33 ms per loop 100 loops, best of 3: 15.4 ms per loop 10 loops, best of 3: 161 ms per loop 1 loops, best of 3: 1.45 s per loop

thanks, dave

this definition coerce dtypes single dtype (e.g. float64 in case). no way around that. view on original array. note helps construction. operations tend create , homecoming copies.

in [44]: s = sarray[:1000000]

original method

in [45]: %timeit dataframe(s) 10 loops, best of 3: 107 ms per loop

coerce ndarray. pass in copy=false (this doesn't impact structured array, plain single dtyped ndarray).

in [47]: %timeit dataframe(s.view(np.float64).reshape(-1,len(s.dtype.names)),columns=s.dtype.names,copy=false) 100 loops, best of 3: 3.3 ms per loop in [48]: result = dataframe(s.view(np.float64).reshape(-1,len(s.dtype.names)),columns=s.dtype.names,copy=false) in [49]: result2 = dataframe(s) in [50]: result.equals(result2) out[50]: true

note both dataframe.from_dict , dataframe.from_records re-create this. pandas keeps like-dtyped ndarrays single ndarray. , expensive np.concatenate aggregate, done under hood. using view avoids issue.

i suppose default structrured array if passed dtypes same. have inquire why using structured array in first place. (obviously name-access..but reason?)

python pandas

css - bootstrap grids in internet explorer 7 -



css - bootstrap grids in internet explorer 7 -

struggling ie7 improperly wrapping columns in bootstrap 3, 3-column layout.

my grid-system works way (stacking when in resolution reflects smaller device) in every other browser including ie8. i'd figure out back upwards i'm losing ie8 ie7 causing not wrap in ie7 displays column has portion of it's content in 9+ position of column on new line.

< col-md-3 >< col-md-3 >< col-md-3 >

displays as:

< col-md-3 >< col-md-3 ><br /> < col-md-3 >

solution

boostrap 3 uses padding-left/padding-right on each of column elements while using < style = "width:100%;"> accomplish consistent structure.

ie7 doesn't render padding space , instead renders other browsers margin space. i.e. if parent container 960px wide, width of children plus added margins must less 960. in essence (960/3)!=((320+margins)*3).

to overcome issue wrapped each column in fixed width container.

like aibrean mentions, best solution create separate stylesheet ie7. seek using conditional comments:

http://www.quirksmode.org/css/condcom.html

<!--[if ie 7]> <link rel='stylesheet' type='text/css' href='/path/to/ie7styles.css' /> <![endif]-->

css twitter-bootstrap-3 internet-explorer-7 grid-system

Should a database abstraction layer/data access layer also be an ORM? -



Should a database abstraction layer/data access layer also be an ORM? -

i'm curious whether should combine part of software responsible retrieving info database part returns objects application logic layer. benefits have? considerations need aware of?

does create difference database have pretty dynamic/loose schema?

my plan @ moment separate application 4 distinct parts:

database - document-oriented, going utilize mongodb. abstraction/access/orm layer - not sure whether should 3, or combination don't yet know plenty things consider, 1 reason came inquire here. application logic layer/business engine - responsible (you guessed) application logic , such. interface layer - responsible providing quick easy way generate dynamic ui elements.

can experienced offer immediate thoughts on general overview? comments appreciated.

orm abstraction project-planning

ruby - How to call different methods as given in an array -



ruby - How to call different methods as given in an array -

especially when working structs, nice able phone call different method per each element in array, this:

array = %w{name 4 tag 0.343} array.convert(:to_s, :to_i, :to_sym, :to_f) # => ["name", 4, :tag, 0.343]

are there simple one-liners, activesupport methods, etc. easily?

i this:

class array def convert(*args) map { |s| s.public_send args.shift } end end array = %w{name 4 tag 0.343} args = [:to_s, :to_i, :to_sym, :to_f] array.convert(*args) #=> ["name", 4, :tag, 0.343] args #=> [:to_s, :to_i, :to_sym, :to_f]

i included lastly line show convert leaves args unchanged, though args emptied within convert. that's because args splatted before beingness passed convert.

as per @arup's request, i've benchmarked , solutions:

class array def sq_convert(*args) zip(args).map { |string, meth| string.public_send(meth) } end def lf_convert(*args) map { |s| s.public_send args.shift } end end require 'benchmark' n = 1_000_000 array = %w{name 4 tag 0.343} args = [:to_s, :to_i, :to_sym, :to_f] benchmark.bmbm(15) |x| x.report("arup's super-quick :") { n.times { array.sq_convert(*args) } } x.report("cary's lightning-fast:") { n.times { array.lf_convert(*args) } } end # rehearsal ---------------------------------------------------------- # arup's super-quick : 2.910000 0.000000 2.910000 ( 2.922525) # cary's lightning-fast: 2.150000 0.010000 2.160000 ( 2.155886) # ------------------------------------------------- total: 5.070000sec # user scheme total real # arup's super-quick : 2.780000 0.000000 2.780000 ( 2.784528) # cary's lightning-fast: 2.090000 0.010000 2.100000 ( 2.099337)

ruby arrays map

ember.js - How to change parent view classname on child view load? -



ember.js - How to change parent view classname on child view load? -

i need alter parent view classname on kid view load code

var childview = em.view.extend({ willinsertelement : function() { this.get('parentview').set('classnames',['childview']); }, template : em.handlebars.compile(template) });

regards chandru.

use classnamebindings , send event kid view update property.

consider example:

{{#view app.aparentview}} {{view app.achildview}} {{/view}}

the app:

app = ember.application.create(); app.aparentview = em.view.extend({ bgcolor: 'lightgray', classnames: ['parent-view'], classnamebindings: 'bgcolor', updatebg: function(bg) { this.set('bgcolor', bg); } }); app.achildview = em.view.extend({ classnames: ['child-view', 'blue'], willinsertelement: function() { this.get('parentview').send('updatebg', 'green'); } });

the css see working:

html, body { margin: 20px; } .parent-view { padding: 4rem; } .child-view { padding: 2rem; } .lightgray { background-color: lightgray; color: black; } .blue { background-color: blue; } .green { background-color: green; }

see jsbin here.

ember.js

hibernate - How to update @Transient member -



hibernate - How to update @Transient member -

i have class this

@entity public class order { ... ... @transient private orderdetail detail; private integer orderdetailid; } @entity public class orderdetail { ... ... }

note: existing class. utilize jpa/hibernate

i want update orderdetail through order object. how can accomplish it?

thanks

you have marked detail transient. since not persistent cannot update it.

isn't there relation between order , orderdetail?

hibernate jpa

SQL Server - Compare on multiple columns in differnet rows within same table -



SQL Server - Compare on multiple columns in differnet rows within same table -

i have table holds values read 2 meters:

---------------------------- date | meterid | value ---------------------------- 1/2/14 1.3 2/2/14 1.8 2/2/14 b 3.8 3/3/14 1.2 4/3/14 1.8 4/3/14 b 2.9

i need query count number of days reading exists both meter types (a & b)? in illustration above should yield 2 result.

thanks.

you can utilize temporary table list [date]s when there occurrences in meterid both a , b , count() [date]s :

select count(t.*) ( select [date] [table] grouping [date] having count(distinct [meterid]) = 2 ) t

sql sql-server compare

html - Most efficient way to handle multiple descendant selectors? -



html - Most efficient way to handle multiple descendant selectors? -

i'm creating site has 2 sections; largely static side uses intricate designs coloured backgrounds, , dynamic blog uses white background.

i've specified in _settings.scss (foundation 5) file utilize dark text on white background text elements. working without issue, , applies blog , static side perfectly.

where stumbling finding efficient way manage different coloured backgrounds , appropriate text styles each background on static side.

i have "dark" & "light" section utilize dark , lite bluish background respectively, alternating downwards page.

i have far been using each class name acts wrapper around content. i.e.

<div class="dark section"> <div class="row"> <div class="small-8 columns (etc.)> <h1> header </h1> <p> text </p> </div> </div> </div> <div class="light section"> <div class="row"> <div class="small-8 columns (etc.)> <h1> header </h1> <p> text </p> </div> </div> </div>

that's html. text (p) white both, , have no issues styling (overriding _settings.scss). it's headers giving me issue. struggling find method of targeting headers in each coloured section without spilling next, alternate coloured section; or without adding numerous classes each , every instance of header dependant on background colour.

thus far have been using: (colours simplified i'm using scss variables)

.dark { background-color: dark-blue; colour: white; } .dark h1,h2 { colour: orange; } .light { background-color: light-blue; colour: white; } .light h1,h2 { colour: dark-blue; } .section { *insert various padding here* }

now mind, should work. however, i'm having styles light class override styles (where different) in dark class. i.e. dark sections have dark-blue headers, rather orange. can't seem stop selector riding 1 'section' through cascade.

i've made stupidly simple oversight, help appreciated.

just utilize descendant selector:

.dark h1 { color: orange; }

here have selected class (.dark), , selected h1 kid at level selected class. apply any <h1> elements within your <div class="dark section"> element, no matter level.

if want utilize descendant selector multiple elements, you'll need add together class each side of comma. selection of .dark h1, h2 selecting h1 elements children of class .dark (as i've explained above), and h2 elements anywhere in body, period... , likewise .light. what need is:

.dark h1, .dark h2 { color: orange; } .light h1, .light h2 { color: dark-blue; }

note original code above, typing colour instead of color. spec uses american english, you'll need prepare these unless have renamed them variables or using pre-processor. note haven't added closing " "small-8" class names.

html css

python - Django: Getting a link to admin page in a template -



python - Django: Getting a link to admin page in a template -

i'm trying add together link in django template page handled default admin console. setup below, don't believe {% url %} part of equation right , i'm getting next error:

reverse 'profile_profilemodel' arguments '()' , keyword arguments '{}' not found.

how right , link admin console template.

template.html

<a href="{% url 'admin:profiles_profilemodel' %}">profiles</a>

profiles.models.py

class profile (models.model)

profiles.admin.py

class profileadmin (admin.modeladmin) admin.site.register (profile, profileadmin)

url.py

urlpatterns = patterns("", url(r"^admin/", include(admin.site.urls)),)

the name of changelist url model {{ app_label }}_{{ model_name }}_changelist. in case, if app_label profiles , model in profile, view name profiles_profile_changelist.

try following:

<a href="{% url 'admin:profiles_profile_changelist' %}">profiles</a>

see django docs on reversing admin urls more information.

python django django-templates django-admin admin

bash - using data one by one of two different variable to replace words using sed -



bash - using data one by one of two different variable to replace words using sed -

i have 2 files list1.txt , list2.txt

list1.txt have name b c d list2.txt have names 1 2 3 4

i have stored 2 lists info in 2 variables say

var1=$(<list1.txt) var2=$(<list2.txt)

i have file contain x y names in want create files replacing 2 x y 1 info list1 , 1 list2 have create 4 files file1 have 1 file2 have b 2 , on...

please help me out have create several files info stored in 2 list files.

one way utilize paste bring together corresponding lines of list1.txt , list2.txt , utilize split split result multiple output files, 1 line per file.

split -a 1 -d -l 1 <(paste -d" " list1.txt list2.txt) out

the other way utilize arrays:

arr1=( $(<list1.txt) ) arr2=( $(<list2.txt) ) (( i=0; i<${#arr1[@]}; i++ )) echo "${arr1[$i]} ${arr2[$i]}" > "out$i" done

bash shell sed

angularjs - Angular tests: How to expect element events to be triggered? -



angularjs - Angular tests: How to expect element events to be triggered? -

i'm decorating forms this:

angular.module('validation').directive('form', function() { homecoming { restrict: 'e', link: function(scope, element) { var inputs = element[0].queryselectorall('[name]'); element.on('submit', function() { (var = 0; < inputs.length; i++) { angular.element(inputs[i]).triggerhandler('blur'); } }); } }; });

now, i'm trying test directive:

describe('directive: form', function() { beforeeach(module('validation')); var $rootscope, $compile, scope, form, input, textarea; function compileelement(elementhtml) { scope = $rootscope.$new(); form = angular.element(elementhtml); input = form.find('input'); textarea = form.find('textarea'); $compile(form)(scope); scope.$digest(); } beforeeach(inject(function(_$rootscope_, _$compile_) { $rootscope = _$rootscope_; $compile = _$compile_; compileelement('<form><input type="text" name="email"><textarea name="message"></textarea></form>'); })); it('should trigger "blur" on inputs when submitted', function() { spyon(input, 'trigger'); form.triggerhandler('submit'); expect(input.trigger).tohavebeencalled(); // expected spy trigger have been called. }); });

but, test fails.

what's right angular way test directive?

you have problems:

1) input = form.find('input'); , angular.element(inputs[i]); 2 different wrapper objects wrapping same underlying dom object.

2) should create spy on triggerhandler instead.

3) you're working straight dom hard unit-test.

an illustration of is: angular.element(inputs[i]) is not injected have difficulty faking in our unit tests.

to ensure point 1) returns same object. can false angular.element homecoming pre-trained value input = form.find('input');

//jasmine 1.3: andcallfake //jasmine 2.0: and.callfake angular.element = jasmine.createspy("angular.element").and.callfake(function(){ homecoming input; //return same object created form.find('input'); });

side note: form angularjs directive, avoid conflicting defined directive, should create directive , apply form. this:

<form mycustomdirective></form>

i'm not sure if necessary. because we're spying on global function (angular.element) may used in many places, may need save previous function , restore @ end of test. finish source code looks this:

it('should trigger "blur" on inputs when submitted', function() { var angularelement = angular.element; //save previous function angular.element = jasmine.createspy("angular.element").and.callfake(function(){ homecoming input; }); spyon(input, 'triggerhandler'); form.triggerhandler('submit'); angular.element = angularelement; //restore expect(input.triggerhandler).tohavebeencalled(); // expected spy trigger have been called. });

running demo

angularjs jasmine angular-directive

android - Image processing, replace picture background or cut out picture background -



android - Image processing, replace picture background or cut out picture background -

in android app, user take or take image of him / device , replace background 1 (for illustration awesome beach).

i'm looking library can cutting out original image background (the original background can color or maybe landscape). or maybe library can give me tools draw part of image maintain / remove.

if such library not exist, think "pixel replacement" method best way if original image has color background (for example, black pixel , alter them transparent pixel).

i have found this tutorial can see result not perfect. there way not check 1 color range of colors ? there way define programmatically range of colors check ?

thank in advance tips , links !

android android-image android-library

Define Enumeration inside Main() gives compile Error ( c#) -



Define Enumeration inside Main() gives compile Error ( c#) -

define enumertion within main() gives compile error,why ? (if define in 'class program, working fine)

using system; class programme { // if define here, works fine. // public enum days {sunday,monday,tuesday,wednesday,thursday,friday,saturday}; static void main() { public enum days {sunday,monday,tuesday,wednesday,thursday,friday,saturday} days today; today = days.saturday; console.writeline("today {0}",today); } }

compile error:

d:\myprogs>csc _19enum.cs microsoft (r) visual c# 2010 compiler version 4.0.30319.1 copyright (c) microsoft corporation. rights reserved. _19enum.cs(7,5): error cs1513: } expected _19enum.cs(10,15): error cs1519: invalid token '=' in class, struct, or interface fellow member declaration _19enum.cs(10,30): error cs1519: invalid token ';' in class, struct, or interface fellow member declaration _19enum.cs(12,20): error cs1519: invalid token '(' in class, struct, or interface fellow member declaration _19enum.cs(12,41): error cs1519: invalid token ')' in class, struct, or interface fellow member declaration _19enum.cs(15,1): error cs1022: type or namespace definition, or end-of-file expected

you can't define enums within method. define them in class, or preferably outside class if going utilize them elsewhere:

using system; public enum days {sunday,monday,tuesday,wednesday,thursday,friday,saturday} class programme { // here fine static void main() { days today; today = days.saturday; console.writeline("today {0}",today); } }

c# enumeration

java - 'The requested resource is not available.', for program using richfaces -



java - 'The requested resource is not available.', for program using richfaces -

well i'm newbie. i've beingness trying write richfaces sample program. whenever seek run programme gives me '404 error' saying requested resource not available. i've gone thru previous posts. set jars required richfaces , included them in /web-inf/lib folder, mentioned in previous comments. still error persists. below error:-

http status 404 - /rf/newfile.faces

type status report

message /rf/newfile.faces

description requested resource not available.

apache tomcat/7.0.54

java jsf richfaces

javascript - How to minimize code based on selector in jQuery -



javascript - How to minimize code based on selector in jQuery -

jquery script code:

$(function() { $('#html_btn1').change(function(){ var val = $(this).val(); switch(val.substring(val.lastindexof('.')+1).tolowercase()){ case 'jpg' : case 'png' : case 'gif' : case 'jpeg' : showimagepreview1(this); break; default : $('#errorimg').html("invalid photo"); break; } }); $('#html_btn2').change(function(){ var val = $(this).val(); switch(val.substring(val.lastindexof('.')+1).tolowercase()){ case 'jpg' : case 'png' : case 'gif' : case 'jpeg' : showimagepreview2(this); break; default : $('#errorimg').html("invalid photo"); break; } }); $('#html_btn3').change(function(){ var val = $(this).val(); switch(val.substring(val.lastindexof('.')+1).tolowercase()){ case 'jpg' : case 'png' : case 'gif' : case 'jpeg' : showimagepreview3(this); break; default : $('#errorimg').html("invalid photo"); break; } }); function showimagepreview1(input) { if (input.files && input.files[0]) { var filerdr = new filereader(); filerdr.onload = function(e) { $('#cu1').attr('src', e.target.result); }; filerdr.readasdataurl(input.files[0]); } } function showimagepreview2(input) { if (input.files && input.files[0]) { var filerdr = new filereader(); filerdr.onload = function(e) { $('#cu2').attr('src', e.target.result); }; filerdr.readasdataurl(input.files[0]); } } function showimagepreview3(input) { if (input.files && input.files[0]) { var filerdr = new filereader(); filerdr.onload = function(e) { $('#cu3').attr('src', e.target.result); }; filerdr.readasdataurl(input.files[0]); } } });

html markup:

<div class="form-group"> <img id="cu1" src="upload-photo-img.jpg"/> <input type="file" path="images" id="html_btn1" /> <img id="cu2" src="upload-photo-img.jpg"/> <input type="file" path="images" id="html_btn2" /> <img id="cu3" src="upload-photo-img.jpg"/> <input type="file" path="images" id="html_btn3" /> </div>

above code works fine whenever trying upload image checks validate , preview image

but want minimize code 1 alter function , 1 showimagepreview function

please give me thought how achieve?

@huangism correct, should on codereview. but, sake of helping:

$(function() { // combine binding selector in 1 $('#html_btn1,#html_btn2,#html_btn3').change(function(){ var val = $(this).val(); switch(val.substring(val.lastindexof('.')+1).tolowercase()){ case 'jpg' : case 'png' : case 'gif' : case 'jpeg' : showimagepreview(this); break; // alter single "showimagepreview" function default : $('#errorimg').html("invalid photo"); break; } }); function showimagepreview(input) { // grab "cu#" using original element's id var cu_id = '#cu' + input.id.match(/\d+$/)[0]; /* alt: var cu_id = input.id.replace('html_btn','#cu'); */ if (input.files && input.files[0]) { var filerdr = new filereader(); filerdr.onload = function(e) { // reference id here $(cu_id).attr('src', e.target.result); }; filerdr.readasdataurl(input.files[0]); } } }); combine bindings in 1 using comma-separated selector remove duplicated showimagepreview# methods , unify 1 function change hard-coded cu# ids in dynamic id based on original input's id. reference id in selector.

javascript jquery html

javascript - How to get access token from node-webkit for a desktop app without hosting page? -



javascript - How to get access token from node-webkit for a desktop app without hosting page? -

i'm trying create desktop app node-webkit. part of app require utilize of facebook get/post content profile (facebook user) utilize desktop app on personal computer.

regarding facebook api documentation (https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.0) , have manually implement login flow , utilize next uri redirect uri: https://www.facebook.com/connect/login_success.html

currently, in node-webkit app, via kid window (a popup), user can login facebook , authorize desktop app interact it's profile. here part of code:

var url = "https://www.facebook.com/dialog/oauth?client_id=myclientid&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=token&scope=publish_actions"; loginwindow = window.open(url, 'login facebook', 'location=yes,toolbar=yes,menubar=yes,directories=yes,status=yes,resizable=yes,scrollbars=yes,height=480,width=640', false);

after that, user redirected next uri , mentioned in doc, access token appear correctly:

https://www.facebook.com/connect/login_success.html#access_token=thebigtokenstring&expires_in=3864.

but appears few seconds , after url replaced https://www.facebook.com/connect/blank.html#_=_ (with security warning message).

i've read post propose add together eventlistener hashchange opened window in order capture access token. after redirect within kid window, i'm no longer available interact via javascript.

so finally, can't access token kid window has retrieved , create visible few seconds.

is can help me user access token node-webkit? don't want utilize server (for hosting web page) between desktop app , facebook.

thanks in advance help.

with help of other question (here) found solution problem.

i post code utilize , hope help else:

var url = "https://www.facebook.com/dialog/oauth?&client_id=mybigclientid&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=token&scope=publish_actions"; function response() { this.access_token = null; this.expires_in = null; }; var response = new response(); //function called every 500ms check if token in url window.hashupdate = function() { if(window.loginwindow.closed){ window.clearinterval(intervalid); start(); //just callback i'm using start part of application (after caught token) } else { var url = window.loginwindow.document.url; var taburl = url.split("#"); //first split separate domain part , parameter part var paramstring = taburl[1]; //i concerned sec part after '#' if(paramstring != undefined){ var allparam = paramstring.split("&"); (var = 0; < allparam.length; i++) { var oneparamkeyvalue = allparam[i].split("="); response[oneparamkeyvalue[0]] = oneparamkeyvalue[1]; //store token in form of key => value }; //close window after 1500ms settimeout(function(){ window.loginwindow.close(); }, 1500); } } } //open url , start watching process window.loginwindow = window.open(this.url, 'login facebook', false); this.intervalid = window.setinterval("window.hashupdate()", 500);

javascript facebook node.js facebook-graph-api node-webkit

algorithm - Golang: How do I convert command line arguments to integers? -



algorithm - Golang: How do I convert command line arguments to integers? -

i want create script insertion sort on arguments provided user, this:

$ insertionsort 1 2 110 39

i expect return:

[1 2 39 110]

but returns:

[1 110 2 39]

i think it's because elements in os.args array strings. so, question how convert elements of os.args array integers? here's code:

bundle main import ( "fmt" "os" "reflect" "strconv" ) func main() { := os.args[1:] := 0; <= len(a); i++ { strconv.atoi(a[i]) fmt.println(reflect.typeof(a[i])) } j := 1; j < len(a); j++ { key := a[j] := j - 1 >= 0 && a[i] > key { a[i+1] = a[i] = - 1 a[i+1] = key } } fmt.println(a) }

as heads up, when substitute

strconv.atoi(a[i])

for

a[i] = strconv.atoi(a[i])

i next error:

./insertionsort.go:14: multiple-value strconv.atoi() in single-value context

thank time!

atoi returns number , error (or nil)

parseint interprets string s in given base of operations (2 36) , returns corresponding value i. if base of operations == 0, base of operations implied string's prefix: base of operations 16 "0x", base of operations 8 "0", , base of operations 10 otherwise.

the bitsize argument specifies integer type result must fit into. bit sizes 0, 8, 16, 32, , 64 correspond int, int8, int16, int32, , int64.

the errors parseint returns have concrete type *numerror , include err.num = s. if s empty or contains invalid digits, err.err = errsyntax , returned value 0; if value corresponding s cannot represented signed integer of given size, err.err = errrange , returned value maximum magnitude integer of appropriate bitsize , sign.

you need :

var err error nums := make([]int, len(a)) := 0; < len(a); i++ { if nums[i], err = strconv.atoi(a[i]); err != nil { panic(err) } fmt.println(nums[i]) }

working illustration : http://play.golang.org/p/xdba_pszml

algorithm sorting go type-conversion command-line-arguments

javafx - JavaFX8 triggering an event if the Node is shown on screen -



javafx - JavaFX8 triggering an event if the Node is shown on screen -

in javafx 8 have few tabs in tabbed pane, these tabs added dynamically based on logic. tab's content loaded fxml.

when tab active , visible 1 of node nowadays in tab has populated starting task. task must stop if other tab chosen. i.e when tab contents visible should start task , if tab no longer visible need stop task.

i have tried attaching changelistener visibleproperty of 1 of node's in tab, doesn't produce changeevent expected.

any thoughts?

attach listener selecteditem property of tabpane's selection model:

tabpane.getselectionmodel() .selecteditemproperty() .addlistener((obs, oldtab, newtab) -> { // if oldtab == tab node, stop task // if newtab == tab node, start task });

javafx javafx-8

javascript - Get the most left X and the most right X from the AmXYChart -



javascript - Get the most left X and the most right X from the AmXYChart -

let's have amxychart 1 below. how can automatically coordinates of left , right x values? illustration in our case 1 , 15.

you can min/max of value axis accessing min , max properties. note, can after chart rendered: http://jsfiddle.net/qge47/1/ getaxisbounds = function(){ console.log(chart.valueaxes[0].min + " " + chart.valueaxes[0].max); console.log(chart.valueaxes[1].min + " " + chart.valueaxes[1].max); }

javascript charts amcharts

javascript - Handlebars - data not being displayed at all -



javascript - Handlebars - data not being displayed at all -

hello everyone,

i've been playing around handlebars trying create work in project, maintain getting no results when i'm testing page.

i'm using json info have received page. info should displayed after compiling template. nil happens, no results @ all.

get_items_data.js

var source = $("#mytemplate").html(); var template = handlebars.compile(source); var items = array(); getting_items_data = true; $.get('getitemsdata',function(responsejson) { if(responsejson!=null){ $.each(responsejson, function(key,value) { items.push({ "id": value['item_id'], "blabla": "bla" }); }); } }); $('body').append(template(items));

test.jsp

<script id="mytemplate" type="text/x-handlebars-template"> <table> <thead> <th>items</th> </thead> <tbody> {{#each this}} <tr> <td>{{id}}</td> <td>{{blabla}}</td> </tr> {{/each}} </tbody> </table> </script>

json info format:

[{"itemid":74,"sectionid":4},{"itemid":78,"sectionid":4}]

any ideas may wrong here?

it looks template function called before have info returned, items array empty when elements appended dom. unlike angularjs, handlebars static templating won't update dom if update array later.

try move render logic callback of get:

$.get('getitemsdata',function(responsejson) { if(responsejson!=null){ $.each(responsejson, function(key,value) { items.push({ "id": value['item_id'], "blabla": "bla" }); }); $('body').append(template(items)); } });

javascript jquery handlebars.js

python - compare 3 lists and delete all matched elements -



python - compare 3 lists and delete all matched elements -

hy,

i want compare 3 lists , whenever match occurs, elements of lists deleted.

( --> every time gpos = g00 , xpos = 0 , ypos = 0 )

gpos = ['g01','g01','g00','g00','g00','g00','g00','g00','g00','g00'] xpos = ['249','248', '0' , '0' , '72', '0' , '66','67' ,'81' , '82'] ypos = ['18', '28' , '0' , '0' , '52', '0', '53','55' ,'54' , '52'] --------------------- output should be: --------------------- gpos = ['g01','g01','g00',g00','g00','g00','g00'] xpos = ['249','248', '72','66','67' ,'81' , '82'] ypos = ['18', '28' , '52','53','55' ,'54' , '52']

i have no thought o_o

this rather crude, work.

for index,element in enumerate(xpos): if element == '0': if ypos[index] == '0': if gpos[index] == 'g00': del gpos[index] del xpos[index] del ypos[index]

just add together this, should have atleast tried , set question. doesn't matter how much wrong are, should seek best code on own.

python python-3.x

go - Is this a safe way to empty a list in Golang? -



go - Is this a safe way to empty a list in Golang? -

an traditional way:

// clear elements iterating var next *element e := l.front(); e != nil; e = next { next = e.next() l.remove(e) }

how using:

l.init()

is safe way not causing memory leak?

from http://golang.org/pkg/container/list/#list.init

init initializes or clears list l.

a side note, piece improve usage scenarios, check slice tricks.

list go

Regex: Numeric Range java -



Regex: Numeric Range java -

i have little generator wich allows me create string out of regex-expression. high german license plate pretty easy do. ([a-z]{1,3}[- ][a-z]{1,2}[0-9]{1,4}) -> e.g. "cd-b802"

public string generate() { string forreturn = null; (string rule : generator.read(fileregexconfig)) { seek { xeger generator = new xeger(rule); forreturn = generator.generate(); } grab (exception e) { system.err.println(rule + ':' + e.getmessage()); } } homecoming forreturn; } public static string[] read(string str) { list<string> list = new arraylist<string>(); seek { bufferedreader in = new bufferedreader(new filereader(str)); string zeile = null; while ((zeile = in.readline()) != null) { if (zeile != null && zeile.trim().length() > 0) list.add(zeile); } in.close(); } grab (exception e) { e.printstacktrace(); } homecoming (string[]) list.toarray(new string[0]); }

the problem have is, how can build regex range of int. illustration seek find way descripe area of validity [37-78].

according http://www.regular-expressions.info/numericranges.html easy describe [0-x] cant find way solve problem. suggestions? in advance!

regexforrange help you:

to match range [37;78]: (3[7-9]|[4-6][0-9]|7[0-8])

java regex

How to Deploy Mule as a REST Service -



How to Deploy Mule as a REST Service -

hi working mule studio , running flow in mule studio. have issues related implementation level since have multiple flows in 1 project.

how deploy mule rest service existing flow.

if deploying mule rest service inputs have provide create run external http client based program.

when utilize http client , when utilize mule client. 1 fits where.

you can create utilize of raml

1.create raml , generate flows internally referes current flows

you can configure http details in generated flows

why want utilize http client , mule client in flows?

mule mule-studio mule-el mule-cluster mule-component

How to do data- attributes with haml and rails? -



How to do data- attributes with haml and rails? -

i can have

%a{href: '#', data_toggle_description_length: 'toggle_me_ajax'}

which gives me underscores not dashes, i.e.

<a href="#" data_toggle_description_length="toggle_me_ajax"></a>

however want have html5 data- attributes, i.e.

<a href="#" data-toggle-description-length="toggle_me_ajax"></a>

but when seek replacing underscores dashes, i.e.

%a{href: '#', data-toggle-description-length: 'toggle_me_ajax'}

i syntax errors:

/home/durrantm/dropnot/webs/rails_apps/linker/app/views/links/_links.html.haml:13: syntax error, unexpected tlabel ...data-toggle-description-length: 'toggle_me_ajax')}>\n tog... ... ^ /home/durrantm/dropnot/webs/rails_apps/linker/app/views/links/_links.html.haml:13: syntax error, unexpected ')', expecting '}' ...ption-length: 'toggle_me_ajax')}>\n togglemeajax\n </a>\... ... ^ /home/durrantm/dropnot/webs/rails_apps/linker/app/views/links/_links.html.haml:13: unknown regexp options - pa /home/durrantm/dropnot/webs/rails_apps/linker/app/views/links/_links.html.haml:13: syntax error, unexpected $undefined ... togglemeajax\n </a>\n</span>\n", -1, false);::haml::util.h... ... ^ /home/durrantm/dropnot/webs/rails_apps/linker/app/views/links/_links.html.haml:13: unterminated string meets end of file /home/durrantm/dropnot/webs/rails_apps/linker/app/views/links/_links.html.haml:13: syntax error, unexpected $end, expecting '}'

try this:

%a{"data-toggle-description-length" => "toggle_me_ajax", href: "#"}

or

%a{href: "#", :data => {:toggle_description_length => "toggle_me_ajax"}}

for more details refer here

you can utilize html2haml converter available online

edit:

as mentioned in comments there couple more syntaxes work

%a{href: "#", { "data-toggle-description-length": "toggle_me_ajax" }}

or

%a{href: "#", { :"data-toggle-description-length" => "toggle_me_ajax" }}

i still prefer first 2 though think latter ones ugly , kinda messy.

ruby-on-rails ruby-on-rails-3 haml custom-data-attribute html5-data

excel - Reverse order of For Each loop -



excel - Reverse order of For Each loop -

one of powerful things vb ability loop through objects in collection without referring index - for each loop.

i find useful want remove objects collection.

when doing removing objects predefined such rows on spread sheet code simpler if utilize indexing , start @ largest , work first. (step -1 iterator) (otherwise requires offset each moves enumerator pointer previous object 1 time active 1 deleted)

eg.

for inta = 10 1 step -1 ' ... next

what when using each | next eg.

for each rngcell in selection.cells ' ... next

how loop backwards using for each loop syntax?

for built in collections (eg range) short reply is: can't. user defined collections reply linked @vblades might useful, although cost might outweigh benifit.

one work around seperate identification of items removed actual removal. eg, range, build new range variable using union, process variable, eg delete rows in 1 go. range example, can take advantage of variant array method farther speed things up.

whether or not of useful depend on actual utilize case.

excel vba excel-vba foreach

Python dictionary with len(20) compare to list with range(7804) -



Python dictionary with len(20) compare to list with range(7804) -

i have been trying convert xml file csv file format. , have little problem. if else statement of printing csv files.

this have

i have dictionary len of 20.

rankings{4706: '8.185', 2358: '0.444', 6245: '0.851', 615: '0.444', 7626: '2.164', 2219: '0.315', 4338: '0.348', 3790: '0.876', 6194: '0.362', 2228: '0.541', 597: '0.495', 6838: '3.883', 4567: '1.173', 7800: '0.521', 3796: '0.326', 2042: '5.076', 5141: '0.316', 1722: '0.595', 5566: '0.555', 1429: '0.435'}

and have few list 7804 big.

eventidlist = [] artkeylist = [] languageall = [] startdatetime = [] enddatetime = [] sentenceid = [] sentencecontent = []

i utilize dictionarykey compare eventidlist if it's same, print value of key csv file.

so have tried using

for in rankings: in range(7804): if(int(a) == int(eventidlist[i])): csvfile.write(eventidlist[i] + ',' + ...... +',' + rankings[a]) else: csvfile.write(eventidlist[i] + ',' + ..... + ',' + " "(rankings) + ',' + sentencecontent[i])

the problem programme go through if statement. still need go through else statement.

any thought went wrong in codes?

if arrays have same length, , output must line per array position, loop should this

eventidlist = range(7804) sentencecontent = range(7804) rankings = {4706: '8.185', 2358: '0.444', 6245: '0.851', 615: '0.444', 7626: '2.164', 2219: '0.315', 4338: '0.348', 3790: '0.876', 6194: '0.362', 2228: '0.541', 597: '0.495', 6838: '3.883', 4567: '1.173', 7800: '0.521', 3796: '0.326', 2042: '5.076', 5141: '0.316', 1722: '0.595', 5566: '0.555', 1429: '0.435'} idx in range(len(eventidlist)): if rankings.get(idx,'') , eventidlist[idx] == rankings.get(idx,''): csvfile.write( "%i, %s" % (eventidlist[idx] , rankings[idx])) else: csvfile.write( "%i, %i" % (eventidlist[idx] , sentencecontent[idx]))

python dictionary

html - Nav bar is vertical and i need it horizontal -



html - Nav bar is vertical and i need it horizontal -

i using bootstraps 3 create nav bar , life of me cannot layout way like. having hard time learning these bootstrap classes. anyways 5 of elements here layed out horizontally in single row see in fiddle 5 components on different row. suggestions?

fiddle : http://jsfiddle.net/cdewey/7m7sj/1/

code:

<nav id="navbar" class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <form class="form form-horizontal" role="form"> <ul class="nav navbar-nav"> <li> <div class="form-group"> <button type="button" class="btn btn-default btn-sm"> <span class="glyphicon glyphicon-chevron-left"></span> </button> </div> </li> <li> <div class="form-group"> <div class="col-md-2"> <div class='input-group date row' id='datetimepicker1' data-date-format="yyyy/mm/dd"> <input type='text' class="form-control"/> <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div> </div> </div> </li> <li> <div class="form-group"> <div class="col-md-2"> <div class='input-group date row' id='datetimepicker2'> <input type='text' class="form-control" /> <span class="input-group-addon"><span class="glyphicon glyphicon-time"></span> </span> </div> </div> </div> </li> <li> <div class="form-group"> <div class="col-md-2"> <div class='input-group date row' id='datetimepicker3'> <input type='text' class="form-control" /> <span class="input-group-addon"><span class="glyphicon glyphicon-time"></span> </span> </div> </div> </div> </li> <li> <div class="form-group"> <button type="button" class="btn btn-default btn-sm"> <span class="glyphicon glyphicon-refresh"></span> </button> </div> </li> </ul> </form> </div> <script type="text/javascript"> $(function () { $('#datetimepicker2').datetimepicker({ pickdate: false }); $('#datetimepicker3').datetimepicker({ pickdate: false }); $('#datetimepicker1').datetimepicker({ picktime: false }); }); </script> </nav>

use tag open menu div:

<div class="navbar navbar-default navbar-fixed-top" role="navigation">

look clear illustration understand how works: http://getbootstrap.com/examples/navbar-fixed-top/

html css twitter-bootstrap twitter-bootstrap-3

html - Unable to center a div containing a menu.. So confused -



html - Unable to center a div containing a menu.. So confused -

i've been trying hr menu centered.

i've tried google has suggested me no avail.

can tell me obvious thing doing wrong please?

here's html:

<header> <div class="wrap-header zerogrid"> <div id="logo"><a href="#"><img src="./images/logonew.png"/></a></div> <nav> <div class="wrap-nav"> <div class="menu"> <ul> <li><a href="index.html">home</a></li> <li><a href="food.html">our food</a></li> <li><a href="drinks.html">our bar</a></li> <li><a href="gallery.html">gallery</a></li> <li><a href="contact.html">contact us</a></li> </ul> </div> <div class="minimenu"><div>menu</div> <select onchange="location=this.value"> <option></option> <option value="index.html">home</option> <option value="food.html">our food</option> <option value="single.html">our bar</option> <option value="gallery.html">gallery</option> <option value="contact.html">contact us</option> </select> </div> </div> </nav> </div>

and here's css:

header {background:#e7dcd5; border-bottom: 0px solid #e7dcd5; background:url(../images/speckledbg.jpg) repeat scroll 0 0; text-align: center;} header .wrap-header{height: 150px; text-align: center;} header #logo {position:absolute; top: 15px; padding:5px; width: 100%; margin: 0 auto;} nav {width:100%;text-align:center; height:37px; display:block; margin-left:auto;margin-right:auto;} nav .wrap-nav{position:absolute; top:115px; height: 37px; background:#e7dcd5; text-align:center;} .menu ul {list-style: none;margin: 0;padding: 0; text-align:center; } .menu ul li {position: relative;float: left;padding: 6px 5px 0px 5px;} .menu ul li:hover {background:#b9aaa0;} .menu ul li {font-size: 18px; line-height:14px;color: #3e3223;display: block;padding: 6px 10px;margin-bottom: 5px;z-index: 6;position: relative;} .menu ul li:hover {color:#ffffff;} .minimenu{display:none;} .minimenu{position: relative;margin: 0px;background:#333333;} .minimenu div{overflow: hidden;position: relative;font: 18px/37px 'pt sans narrow' !important;color: #fff;text-align:center;text-transform:uppercase;font-weight:bold;} .minimenu select{position: absolute;top: 0px;left: 0px;width: 100%;height: 100%; opacity: 0;filter: progid:dximagetransform.microsoft.alpha(opacity=0); cursor: pointer;}

here's jsfiddle

thanks in advance

you need specify width .wrap-nav , assign display:inline-block menu , it's done.

you can see working here: http://jsfiddle.net/gfb8k/5/

html css

asp.net - Automatic Mailing based on server datetime -



asp.net - Automatic Mailing based on server datetime -

i working in asp.net mvc, have scenario follows.

"employee have specific end time finish task, 1 time time completed, mail service has sent automatically team lead notify."

in way have check server datetime , specified end datetime constantly,my frnd suggested me check database datetime endtime every 30 secs creating console scheduler watch time, have alternative without checking database frequently?

i suggest windows service check timings.

do have alternative without checking database frequently

you implement kind of caching mechanism - maintain tasks in memory , check against server time - if tasks updated cache become outdated or need way synch cache database.

so usethe approach check every x seconds (30 seconds seems little, how accurate want notifications be?? perhaps 1 time every 5 minutes plenty depending on requirements).

asp.net asp.net-mvc-3 asp.net-mvc-4 scheduler

ios - NSNumberFormatter desired results for UITextField -



ios - NSNumberFormatter desired results for UITextField -

i'm having problem getting desired nsnumberformatter results. i've tried several combinations of properties haven't gotten i'm looking for.

i'd format uitextfield user types decimal pad keyboard.

acceptable input formats:

12

12.3

12.34

a minimum of 2 digits preceeding decimal , maximum of 2 digits next decimal. maximum value possible in case 99.99.

as user types 1 2 3 4.. textfield should display following

1

12

12.3

12.34

if user doesn't explicitly utilize decimal key, should automatically inserted.

here's latest attempt, said.. i've tried lot of things

-(void)textfielddidchange:(uitextfield *)thetextfield { if (thetextfield.text) { nsnumberformatter *formatter = [[nsnumberformatter alloc] init]; [formatter setnumberstyle:nsnumberformatterdecimalstyle]; nsnumber *number = [formatter numberfromstring:thetextfield.text]; //[formatter setminimumintegerdigits:2]; [formatter setmaximumintegerdigits:2]; [formatter setmaximumfractiondigits:2]; thetextfield.text = [nsstring stringwithformat:@"%@", [formatter stringfromnumber:number]]; } }

i'd take approach.

in textfielddidchange not format validate nspredicate , regex.

-(void)textfielddidchange:(uitextfield *)thetextfield { if (thetextfield.text) { nsstring *regex = @"^[0-9]{0,2}[\\.]{0,1}[0-9]{0,2}$"; nspredicate *pred = [nspredicate predicatewithformat:@"self matches %@", regex]; if (![pred evaluatewithobject:mystring]) { // error, input not matching! remove lastly added character. int len = thetextfield.text.length-((thetextfield.text.length-1 == 3) ? 2 : 1; thetextfield.text = [thetextfield.text substringwithrange:nsmakerange(0, len)]; // checks if new length, i.e. length when lastly digit has been deleted 3, means decimal dot lastly character. if remove 2 instead of 1 character! } else { // okay here, whatever if(thetextfield.text.length == 2) // add together decimal dot if 2 digits have been entered! thetextfield.text = [nsstring stringwithformat:@"%@.", thetextfield.text]; } } }

ios uitextfield nsnumberformatter

What is the usecase for ignored parameters in Swift -



What is the usecase for ignored parameters in Swift -

in swift, can write following:

func foo(_:int) -> { homecoming 1 }

where underscore ignored parameter. know because of documentation, cannot think of usecase on why this. missing something?

ignoring parameters (or members of tuple, pretty close same thing) makes sense when:

you're overriding superclass function or implementing function defined protocol, implementation of function doesn't need 1 of parameters. example, if hook app launching don't need reference shared uiapplication instance in method:

override func application(_: uiapplication!, didfinishlaunchingwithoptions _: nsdictionary!) -> bool { /* ... */ }

you're providing closure (aka block in objc) parameter api, utilize of api doesn't care 1 of parameters closure. example, if you're submitting changes photos library , want throw caution wind, can ignore success , error parameters in completion handler:

phphotolibrary.sharedphotolibrary().performchanges({ // alter requests }, completionhandler: { _, _ in nslog("changes complete. did succeed? knows!") })

you're calling function/method provides multiple homecoming values, don't care 1 of them. example, assuming hypothetical nscolor method returned components tuple, ignore alpha:

let (r, g, b, _) = color.getcomponents()

the reasoning behind makes code more readable. if declare local name parameter (or tuple member) don't end using, else reading code (who several-months-later version of yourself) might see name , wonder or how gets used in function body. if declare upfront you're ignoring parameter (or tuple member), makes clear there's no need worry in scope. (in theory, provide optimization hint complier, might create code run faster, too.)

parameters swift ignore