Friday, 15 March 2013

php - How to insert row to first place in db -



php - How to insert row to first place in db -

i have question, want insert new row db (mysql) using php , need add together first place in table, comes lastly position.

i need short this:

3

2

1

but shorts like

1

2

3

can help me please?

thanks lot, stepan

assuming using incremental id unique key, can do:

order id desc

if not, can add together column db called "created" datetime set now() when create row. do:

order created desc

php mysql

php - Array Key Values In Magento Template Files -



php - Array Key Values In Magento Template Files -

within magento template file how can output value of array key.

for example:

{{var rewards.usablepoints}}

will return

array

the contents this:

[0] (int) => 12

using magento's mustache syntax ({{...}}) how display "12" instead of "array".

{{var rewards.usablepoints.0}}

php magento templates mustache

java - What is the 'wildcard address' In the context of UDP Broadcasts? -



java - What is the 'wildcard address' In the context of UDP Broadcasts? -

referring java 6 api docs datagramsocket class:

udp broadcasts sends enabled on datagramsocket. in order receive broadcast packets datagramsocket should bound wildcard address. in implementations, broadcast packets may received when datagramsocket bound more specific address.

could tell me 'wildcard address' is? , next valid listening udp broadcasts:

multicastsocket socket = new multicastsocket(new inetsocketaddress(inetaddress.getbyname("0.0.0.0"),4445);

the wildcard address 0.0.0.0. not confused broadcast-to-all-subnets address, 255.255.255.255. more correctly called 'any' address, after inaddr_any.

in java used supplying null bind-address, or omitting parameter altogether, e.g. new inetsocketaddress(null, 0) or new inetsocketaddress(0) respectively. in other words default when binding, , hence implicitly 'good practice'.

java network-programming broadcast multicast datagram

ios - How can animation be unit tested? -



ios - How can animation be unit tested? -

modern user interfaces, macos , ios, have lots of “casual” animation -- views appear through brief animated sequences largely orchestrated system.

[[mynewview animator] setframe: rect]

occasionally, might have more elaborate animation, animation grouping , completion block.

now, can imagine bug reports this:

hey -- nice animation when mynewview appears isn't happening in new release!

so, we'd want unit tests simple things:

confirm animation happens check duration of animation check frame rate of animation

but of course of study these tests have simple write , mustn't create code worse; don’t want spoil simplicity of implicit animations ton of test-driven complexity!

so, what tdd-friendly approach implementing tests casual animations?

justifications unit testing

let's take concrete illustration illustrate why we'd want unit test. let's have view contains bunch of widgetviews. when user makes new widget double-clicking, it’s supposed appear tiny , transparent, expanding total size during animation.

now, it's true don't want need unit test scheme behavior. here things might go wrong because fouled things up:

the animation called on wrong thread, , doesn't drawn. in course of study of animation, phone call setneedsdisplay, widget gets drawn.

we're recycling disused widgets pool of discarded widgetcontrollers. new widgetviews transparent, views in recycle pool still opaque. fade doesn't happen.

some additional animation starts on new widget before animation finishes. result, widget begins appear, , starts jerking , flashing briefly before settles down.

you made alter widget's drawrect: method, , new drawrect slow. old animation fine, it's mess.

all of these going show in back upwards log as, "the create-widget animation isn't working anymore." , experience has been that, 1 time used animation, it’s hard developer notice right away unrelated alter has broken animation. that's recipe unit testing, right?

the animation called on wrong thread, , doesn't drawn. in course of study of animation, phone call setneedsdisplay, widget gets drawn.

don't unit test directly. instead utilize assertions and/or raise exceptions when animation on wrong thread. unit test assertion raise exception appropriately. apple aggressively frameworks. keeps shooting in foot. , know when using object outside of valid parameters.

we're recycling disused widgets pool of discarded widgetcontrollers. new widgetviews transparent, views in recycle pool still opaque. fade doesn't happen.

this why see methods dequeuereusablecellwithidentifier in uitableview. need public method reused widgetview chance test properties alpha reset appropriately.

some additional animation starts on new widget before animation finishes. result, widget begins appear, , starts jerking , flashing briefly before settles down.

same number 1. utilize assertions impose rules on code. unit test assertions can triggered.

you made alter widget's drawrect: method, , new drawrect slow. old animation fine, it's mess.

a unit test can timing method. calculations ensure remain within reasonable time limit.

-(void)testanimationtime { nsdate * start = [nsdate date]; nsview * view = [[nsview alloc]init]; (int = 0; < 10; i++) { [view display]; } nstimeinterval timespent = [start timeintervalsincenow] * -1.0; if (timespent > 1.5) { stfail(@"view took %f seconds calculate 10 times", timespent); } }

ios cocoa design-patterns animation tdd

How to set header data in a Qt QAbstractItemModel? -



How to set header data in a Qt QAbstractItemModel? -

there setheaderdata function in qt qabstractitemmodel. can events create function called set header data, such f2 key or mouse double click?

sure can create slot connected "double click" signal , phone call model instance setheaderdata //if overridden function in own model type need emit headerdatachanged signal, see here

qt

LDAP verify a password outside of code -



LDAP verify a password outside of code -

i have ldap error in c# code talking invalid customers username / password.

i need confirm if password in fact correct, or way have manipulated users dn remove escape characters has caused user unknown.

i'm not familiar domains , how fits in windows, have access free ldap browsers e.g. http://www.ldapbrowser.com/ or can download other software need validate password somehow.

any ideas how?

the "ldapbrowser" should work.

we prefer http://directory.apache.org/studio/

what error code?

i assume using ad?

we have help advertisement , ldap

ldap

Dynamic table with HTML and jQuery -



Dynamic table with HTML and jQuery -

i need write javascript ui web page booking appointments in hair saloon. have dynamic table saloon opening hours on 1 horizontal axis , stylists on vertical. page have list of checkboxes stylist names. when user selects/unselects stylist corresponding column in table should showed/hidden. info populating table come json object. when appointment lasts more 2 hours or more cells represent should joined.

i'm not professional developer, can utilize help. there ui library can use? how manipulate table efficiently?

thanks, anna

there plenty of plugin available altering tables require sum setting , have there advantages disadvantages.

a simple google search "jquery table" homecoming quite lot mention need json importing there requited convert.

the best choise jtable, provide need start. http://www.jtable.org/

they have great demo of real time actions: http://www.jtable.org/realtime

jquery html jquery-ui

php - Issue with retrieving a parameter from a $.ajax call -



php - Issue with retrieving a parameter from a $.ajax call -

hey guys have next $.ajax call:

$.ajax({ type: "post", datatype: "json", url: '/pcg/popups/getnotes.php', data: { 'namenotes': notes_name.text(), }, success: function(response) { $('#notes_body').text(response.the_notes); alert(response.the_notes); } )};

now focus on data: lets sent 'billcosby'. sent on file specified , have within file:

$username_notes = $_post['namenotes'];

now lets have $username_notes homecoming in json this...

$returnarray = array( 'the_notes' => $username_notes ); echo json_encode($returnarray);

this work , response billcosby. out of way, when seek value billcosby mysql database using pdo homecoming null....before show code whole file want create clear pdo works perfect, if give variable $username_notes direct value of 'billcosby' run through database perfect, returns null if have $_post['namenotes']; in front.

getnotes.php:

$username_notes = $_post['namenotes']; grabnotes($username_notes); function grabnotes($xusername) { ..... $newuser = $xusername; seek { # mysql pdo_mysql $dbh = new pdo("mysql:host=$hostname;dbname=$database", $username, $password); $dbh->setattribute( pdo::attr_errmode, pdo::errmode_exception ); } catch(pdoexception $e) { echo "i'm sorry, i'm afraid can't that."; file_put_contents('pdoerrors.txt', $e->getmessage(), file_append); } $sql = "select notes csvdata username = :username"; $getmeminfo = $dbh->prepare($sql); $getmeminfo->execute(array(':username' => $newuser)); $row = $getmeminfo->fetch(pdo::fetch_assoc); $notes = $row['notes']; $returnarray = array( 'the_notes' => $row['notes'],); echo json_encode($returnarray); $dbh = null; }

so question is, why can not homecoming value pdo statement? work perfect if told pdo statement name - 'billcosby' within file $.ajax file calls to. not work , returns null if value through $_post $.ajax. funny thing can homecoming same value sent in.

thanks time guys!

try trimming :

$username_notes = trim( $_post['namenotes'] );

sometimes spaces in string cause sort of error, , can hard spot.

php jquery pdo

delphi - Checking if the file is in use and by which application? -



delphi - Checking if the file is in use and by which application? -

trying utilize below mentioned approach more details locked file.

is file in use

function getfileinuseinfo(const filename : widestring) : ifileisinuse; var rot : irunningobjecttable; mfile, enumindex, prefix : imoniker; enummoniker : ienummoniker; monikertype : longint; unkint : iinterface; begin result := nil; olecheck(getrunningobjecttable(0, rot)); olecheck(createfilemoniker(pwidechar(filename), mfile)); olecheck(rot.enumrunning(enummoniker)); while (enummoniker.next(1, enumindex, nil) = s_ok) begin olecheck(enumindex.issystemmoniker(monikertype)); if monikertype = mksys_filemoniker begin if succeeded(mfile.commonprefixwith(enumindex, prefix)) , (mfile.isequal(prefix) = s_ok) begin if succeeded(rot.getobject(enumindex, unkint)) begin if succeeded(unkint.queryinterface(iid_ifileisinuse, result)) begin result := unkint ifileisinuse; exit; end; end; end; end; end; end;

but phone call

unkint.queryinterface(iid_ifileisinuse, result)

always returns e_nointerface.

platform: windows 7 32 bit-os, opening word files , .msg files.

checked opening files explorer , trying delete. shows proper details application in file opened. in application, seek display info application in file opened. when trying cast pointer ifileisinuse interface, queryinterface calls fails homecoming code e_nointerface means object in rot not implement ifileisinuse. afasik, ms office files implements ifileisinuse

any thought wrong here?

in fact code works fine. problem programs testing against not implement ifileisinuse. when scheme returns e_nointerface accurate. interface not implemented.

i tested file in utilize sample sdk. files added rot application, implement ifileisinuse, picked code. on other hand, files opened acrobat 8 , word 2010 not.

the conclusion draw ifileisinuse fine thought in principle, not much utilize if applications don't back upwards it. , appears there major applications not.

it clear need utilize 1 or more of other mechanisms observe application has file locked when find ifileisinuse not implemented.

delphi delphi-2009 windows-api-code-pack

android - How to validate edit Text so it is only possible to enter valid email? -



android - How to validate edit Text so it is only possible to enter valid email? -

i making android application using eclipse. have edittext box validate email. edittext in xml , id of "edittext1". found answers how validate email problem is: don't know how apply "edittext1" in java code.

below nowadays code email validation found: public final pattern email_address_pattern = pattern.compile( "[a-za-z0-9\\+\\.\\_\\%\\-\\+]{1,256}" + "\\@" + "[a-za-z0-9][a-za-z0-9\\-]{0,64}" + "(" + "\\." + "[a-za-z0-9][a-za-z0-9\\-]{0,25}" + ")+" ); private boolean checkemail(string email) { homecoming email_address_pattern.matcher(email).matches(); }

when paste code java file message:

"the method checkemail(string) type mainactivity never used locally"

you have reference edittext

something should work:

edittext et = (edittext) findviewbyid(r.id.edittext1);

then can text edittext this:

string str = et.gettext().tostring();

then can phone call validate method

if(checkemail(str)){ //email valid }

however based on question asking , manner in you've asked can tell benefit going , studying plain java before dive android. , 1 time you've got java syntax down, should start examples , tutorials on official android developer website, covers lot of basics seem having problem understanding.

and 1 lastly aside, "edittext1" not name edittext, doesn't explain object. code easier work if strive utilize more descriptive names objects, perhaps "emailtext" might improve choice?

android

sql - string not accepting " 's " while writing to database -



sql - string not accepting " 's " while writing to database -

hello creating settings page application using mvc4. in settings page:

1.it contains 2 text areas wherein user can type anything.

2.after typing if user clicks submit button, text has written saved in sql database.

3.the main application read info database , display it.

here respective codes:

model:

public string partnerinfo1 { get; set; } public string partnerinfo2 { get; set; }

controller:

[httppost] public actionresult index(adddetailmodel model) { pinfo1 = model.partnerinfo1; pinfo2 = model.partnerinfo2; sqlconnection con = new sqlconnection(configurationmanager.connectionstrings["sample"].connectionstring); con.open(); sqlcommand cmd = new sqlcommand("update dbo.partner_design set partnerinfo1='" + pinfo1 + "',partnerinfo2='" + pinfo2 + "' [partnerid]='cs'", con); cmd.executenonquery(); homecoming redirecttoaction("index"); }

and in view:

@html.textareafor(m => m.partnerinfo1) @html.textareafor(m => m.partnerinfo2)

in database, corresponding table contains 2 columns partnerinfo1,partnerinfo2 , datatype nvarchar(max).

my problem when type apostrophe in text area gives me error.for illustration if type "world's" gives error on clicking submit button.

this error:

incorrect syntax near 's'. unclosed quotation mark after character string ''.

please suggest can avoid this.any help appreciated.

your method expose query sql injection attacks. much improve using parameterised query sort out ' issue well.

string connstring = configurationmanager.connectionstrings["sample"].connectionstring; using (sqlconnection con = new sqlconnection(connstring)) { sqlcommand cmd = new sqlcommand("update dbo.partner_design " + "set partnerinfo1=@pinfo1, " + "partnerinfo2=@pinfo2 " + "where [partnerid]=@partnerid", con); cmd.parameters.addwithvalue("@pinfo1", model.partnerinfo1); cmd.parameters.addwithvalue("@pinfo2", model.partnerinfo2); cmd.parameters.addwithvalue("@partnerid", "cs"); con.open(); cmd.executenonquery(); }

sql asp.net-mvc data-type-conversion

Passing the Event Object to a Function in Jquery -



Passing the Event Object to a Function in Jquery -

typically, can pass event anonymous jquery function so:

$(".click_me").on("click", function(e) { e.preventdefault(); });

now let's remove anonymous function still want pass event it:

function onclickme(e){ e.preventdefault(); } $(".click_me").on("click", onclickme(e));

unfortunately, doesn't work expected. error:

referenceerror: e not defined

so how else can pass event external function?

just pass function reference, jquery handle passing arguments (it always passes event first argument handler function). so:

function onclickme(e){ e.preventdefault(); } $(".click_me").on("click", onclickme);

jquery function parameters

Cannot receive echo from PHP file via jQuery and AJAX -



Cannot receive echo from PHP file via jQuery and AJAX -

i want begin saying sorry asking question because know has been asked lot on here already. i've search through site , used google, , looked @ other examples can't figure out what's wrong. running script firebug running shows post sent nil gets received. i've posted code below.

jquery code:

$('#studio').submit(function (event) { $('#formlaunch').click(); $.ajax({ url: 'test.php', type: 'post', data: { search_var: 'test' }, datatype: 'html', success: function (data) { //$('#result').html(data); alert(data); } }); event.preventdefault(); });

php code:

<?php $term = $_post['search_var']; echo $term; ?>

the end result of code (once ajax request starts working) process sent variables , echo image want displayed in div box on page. starters though trying basic 'shell' work properly.

thanks in advance help or direction.

jeff

always provide error function, when in development. suspect have error response (404, 500, etc). providing error function debugging purposes help see more quickly.

php jquery ajax

Trying to retrieve result using linq -



Trying to retrieve result using linq -

hi have table has column allowstockedit bit

i trying check user has edit access , show edit , delete buttons on radgridview

this code using

protected void accesslevels(object sender, eventargs e) { linqdatacontext dc = new linqdatacontext(); userpermission = dc.userpermissions.where(a => a.id == (int)session["permission"]).singleordefault(); up.allowstockedit = true; } /*show hide buttons */ protected void selectedstockgridview_rowdatabound(object sender, gridviewroweventargs e) { if (e.row.rowtype == datacontrolrowtype.datarow) { // show edit button when user has right access level if { button btnedit = (button)e.row.findcontrol("showeditbutton"); button btndelete = (button)e.row.findcontrol("showdeletebutton"); btnedit.visible = true; btndelete.visible = true; } } }

i trying check see if user has edit access if show buttons

any help appreciated

something that:

protected bool accesslevels() { linqdatacontext dc = new linqdatacontext(); homecoming dc.userpermissions.where(a => a.id == (int)session["permission"]).singleordefault().allowstockedit; } protected void selectedstockgridview_rowdatabound(object sender, gridviewroweventargs e) { if (e.row.rowtype == datacontrolrowtype.datarow) { // show edit button when user has right access level if(accesslevels() == true) { button btnedit = (button)e.row.findcontrol("showeditbutton"); button btndelete = (button)e.row.findcontrol("showdeletebutton"); btnedit.visible = true; btndelete.visible = true; } } }

linq

javascript - SharePoint 2010 Context menu stop working until page is refreshed -



javascript - SharePoint 2010 Context menu stop working until page is refreshed -

problem: using sharepoint 2010 in ie 8; default context menu document library items menue works 1 time on each page stop responding unless page refreshed.

the status bar error shows - "javascript:;" , nil else.

java scripting enables in ie, sharepoint portal in trusted sites.

what be? hints?

thanks, val

have tried changing zoom size? have had similar problem list items , able recreate when zoom setting set 125 %. problem went away when set zoom setting 100 %. odd , unexpected worked...

another approach/test see if problem occurs ie 9.

javascript sharepoint

sql server 2008 - Group by excluding Null - tsql -



sql server 2008 - Group by excluding Null - tsql -

i have script below:

;;with cte ( select rank() on (partition portfolioid order sum(percentage) desc,max(securityname)) [rank] , reportingdate , portfolioid , portfolionme , max(securityname) securityname , cast(sum(percentage) decimal(22,1)) [weight] , sedol , max(isin) isin @worktable wt wt.issuetype2 <> '010' , wt.issuetype2 <> '055' , wt.issuetype1 <> '110' -- remove cash , fx , collateral grouping wt.reportingdate , wt.portfolioid , wt.portfolionme , wt.sedol ) select convert(varchar, reportingdate, 103) reportingdate , portfolioid fundcode , portfolionme fundname , securityname instrumentname , [rank] , [weight] percentage , sedol , isin cte [rank] <= 10 order reportingdate, portfolioid, [rank], [weight] desc

i'm grouping sedol want grouping same sedols together, causing nulls grouping together. i've tried changing script adding max around sedol , putting:

case when sedol null securityname else sedol end

in grouping no success.

any help much appreciated.

thanks

how about:

;;with cte ( select rank() on (partition portfolioid order sum(percentage) desc,max(securityname)) [rank] , reportingdate , portfolioid , portfolionme , max(securityname) securityname , cast(sum(percentage) decimal(22,1)) [weight] , isnull(sedol, securityname) sedol , max(isin) isin @worktable wt wt.issuetype2 <> '010' , wt.issuetype2 <> '055' , wt.issuetype1 <> '110' -- remove cash , fx , collateral grouping wt.reportingdate , wt.portfolioid , wt.portfolionme , isnull(wt.sedol, securityname) ) select convert(varchar, reportingdate, 103) reportingdate , portfolioid fundcode , portfolionme fundname , securityname instrumentname , [rank] , [weight] percentage , sedol , isin cte [rank] <= 10 order reportingdate, portfolioid, [rank], [weight] desc

sql-server-2008 tsql group-by common-table-expression

java - Inject a list of beans using Spring @Configuration annotation -



java - Inject a list of beans using Spring @Configuration annotation -

i've got spring bean, , in spring bean have dependency on list of other beans. question is: how can inject generic list of beans dependency of bean?

for example, code:

public interface color { } public class reddish implements color { } public class bluish implements color { }

my bean:

public class painter { private list<color> colors; @resource public void setcolors(list<color> colors) { this.colors = colors; } } @configuration public class myconfiguration { @bean public reddish red() { homecoming new red(); } @bean public bluish blue() { homecoming new blue(); } @bean public painter painter() { homecoming new painter(); } }

the question is; how list of colors in painter? also, on side note: should have @configuration homecoming interface type, or class?

thanks help!

what have should work, having @resource or @autowired on setter should inject instances of color list<color> field.

if want more explicit, can homecoming collection bean:

@bean public list<color> colorlist(){ list<color> alist = new arraylist<>(); alist.add(blue()); homecoming alist;

and utilize autowired field way:

@resource(name="colorlist") public void setcolors(list<color> colors) { this.colors = colors; }

or

@resource(name="colorlist") private list<color> colors;

on question returning interface or implementation, either 1 should work, interface should preferred.

java spring spring-annotations

php - url issues with codeignitor -



php - url issues with codeignitor -

i have illustration @ following url, sends user basic form.

the code form following;

<?php echo validation_errors(); ?> <?php echo form_open('form'); ?> <h5>username</h5> <input type="text" name="username" value="" size="50" /> <div><input type="submit" value="submit" /></div> </form>

if understand correctly, 1 time user presses "submit", should go controller named "form". not work expected.

i want submit index.php/form, , instead goes /index.php/index.php/form

feel free test out website @ url above , see issue yourself.

i looked @ source code , noticed this:

<form action="http://helios.hud.ac.uk/u0862025/codeigniter/index.php/index.php/form" method="post" accept-charset="utf-8">

which displays 2 "index.php"s. means have "index.php" set in base of operations url , index page configuration. should remove "index.php" 1 of sources, preferably base_url.

php codeigniter

.net - Getting Room Appointments Efficiently from Exchange -



.net - Getting Room Appointments Efficiently from Exchange -

the problem

i need able appointment info meeting rooms using exchange managed api. have had service running month serves purpose fine using exchangeservice.getuseravailability() follows:

class="lang-cs prettyprint-override">private ienumerable<calendarevent> getevents(exchangeservice exchangeservice, string room, datetime time, datetime end) { list<attendeeinfo> attendees = new list<attendeeinfo>(); end = new datetime(time.ticks + math.max(end.ticks - time.ticks, time.adddays(1).ticks - time.ticks)); attendeeinfo roomattendee = new attendeeinfo(); roomattendee.attendeetype = meetingattendeetype.room; roomattendee.smtpaddress = getemailaddress(room); attendees.add(roomattendee); collection<calendarevent> events = exchangeservice.getuseravailability( attendees, new timewindow(time, end), availabilitydata.freebusy ).attendeesavailability[0].calendarevents; homecoming (from e in events e.endtime > time select e); }

however, have had extend service perform other tasks have required larger spans of time (gone 1 day several months). method becomes highly inefficient increment in time, , can throw errors when there many results.

the question

is efficient way of going this? have found no improve ways, grateful confirmation.

you can seek using exchangeservice.finditems enables :

use pagination fetch huge resultsets. select fields want server

specify searchfilter filter query server side :

from e in events e.endtime > time select e

.net wcf calendar exchange-server ews-managed-api

How to make Product List in ASP.net C# -



How to make Product List in ASP.net C# -

how display product list in asp.net c#? i'm creating e-commerce website thesis need display in grid form >> sample product list limitation per page illustration 10 products per page please need help

i utilize datalist control. here can find tutorial

c# asp.net

How to get the users location and zoom in upon loading maps Android V2 -



How to get the users location and zoom in upon loading maps Android V2 -

i can display map , have button show on map, when tap it want do. in code have this:

googlemap.setmylocationenabled(true); googlemap.getmylocation();

is there way automatically upon loading map, without having tap zoom location button?

i researched , found examples on getting users location, examples found didn't wanted, not sure code v2 maps. certainly there must easy, code minimal way now?

i read through this post on stackoverflow, have no thought code:

googlemap.getcameraposition().target

target takes location think?

any assistance appreciated!

thanks!

i solved using next code:

lm =(locationmanager) getsystemservice(context.location_service); criteria crit = new criteria(); towers = lm.getbestprovider(crit, false); location location = lm.getlastknownlocation(towers); if(location != null){ double glat = location.getlatitude(); double glon = location.getlongitude(); }

then setting map up:

cameraposition cp = new cameraposition.builder() .target(new latlng(glat, glon)) .zoom(15) .build(); googlemap.animatecamera(cameraupdatefactory.newcameraposition(cp));

this users location, , when map loads, automatically zooms location, should see bluish dot sit!

android android-maps-v2

java - ANTLR 4 $channel = HIDDEN and options -



java - ANTLR 4 $channel = HIDDEN and options -

i need help antlr 4 grammar after deciding switch v4 v3. not experienced antlr sorry if question dumb ;)

in v3 used next code observe java-style comments:

comment : '//' ~('\n'|'\r')* '\r'? '\n' {$channel=hidden;} | '/*' ( options {greedy=false;} : . )* '*/' {$channel=hidden;} ;

in v4 there no rule-specific options. actions (move hidden channel) invalid.

could please give me hint how in antlr v4?

the v4 equivalent like:

comment : ( '//' ~[\r\n]* '\r'? '\n' | '/*' .*? '*/' ) -> channel(hidden) ;

which set single- , multi line comment on hidden channel. however, if you're not doing these hidden-tokens, skip these tokens, this:

comment : ( '//' ~[\r\n]* '\r'? '\n' | '/*' .*? '*/' ) -> skip ;

note tell lexer or parser match ungreedy, don't utilize options {greedy=false;} anymore, append ?, similar many regex implementations.

java migration antlr antlr4

c++ - printf("%cx", FILE2CHAR(F(fr))) to cout -



c++ - printf("%cx", FILE2CHAR(F(fr))) to cout -

how can express printf("%cx", file2char(f(fr))) "cout"? (note: file2char(f(fr)) returns int`)

i have tried cout<<hex<<file2char(f(fr)); in cases, still returns me wrong hex.

my mistake. file2char(f(fr)) not homecoming int. f(fr) returns int

file2char macro:

#define file2char(f) ('a'+(f)) /* file text */

sorry confusion please help~

thanks

what trying print? %cx print character followed x. why utilize hex manipulator anyway? – parkydr because thought x refers hex, right? kind of confused syntax here.

still bit confused i'll cover both situations.

to print character, printf should be

printf("%c", file2char(f(fr)));

the stream equivalent is

cout << static_cast<char>(file2char(f(fr)));

the cast required because file2char homecoming integer cout display integer value.

to print hex value, printf should be

printf("%x", file2char(f(fr)));

the stream equivalent is

cout << hex << file2char(f(fr));

note: subsequent numbers displayed in hex until utilize dec manipulator.

c++ printf cout

session - header('location:index.php') redirects me to index.php after refreshing the page for 2 times -



session - header('location:index.php') redirects me to index.php after refreshing the page for 2 times -

i have php page (index.php) in after verifying username , password session set($_session['expire']) expired , unset after 30 mins (30 mins after pressing login button) , redirect index.php again:

header('location:index.php');

after verifying, menu shown in index page 1 of item contentmanager.php. shown below clicking item connected db , come in contentmanager.php

switch($_request['action']) { case 'contentmanager' : include('model/content.php'); $contents = getcontent($conn); include('view/contentmanager.php'); break; }

in contentmanger.php have:

<?php //if session not unset , expired yet if ( isset($_session['expire']) && ($now<= $_session['expire'])) { ?> sth... <?php } else { //unset session , redirect index.php 1 time again unset($_session['expire']); session_destroy(); header('location:../index.php');} ?>

this works fine, problem after passing 30 mintues have press "contentmanager" 2 times redirect index.php if press 1 time blank page shown. refreshing page sec time redirect login page (index.php) again.

please help me...

its because youre outputting text (probably blank line) before header. in illustration posted output blank line between ?> ,

php session redirect header unset

Display Last Week Records & Delete Previous Records in iPhone Application using Sqlite3 database -



Display Last Week Records & Delete Previous Records in iPhone Application using Sqlite3 database -

i want display lastly week records & delete previous records in iphone application.

so i'm getting 1 week later date-time using,

//now nowdate = [entrydateformat stringfromdate:[nsdate date]]; //1 week previous weekdate = [entrydateformat stringfromdate:[[nsdate date] datebyaddingtimeinterval: -604800.0]];

then, executing sql query like

nsstring *selectsql = [nsstring stringwithformat:@"select * tbltest time between \"%@\" , \"%@\"", weekdate, nowdate];

so getting value of query ::

select * tbltest time between "04-02-2013 17:20:36" , "11-02-2013 17:20:36";

same delete previous records

delete tbltest time < "04-02-2013 17:20:36";

so, it'll work 1st, 2nd & 3rd of current date. it'll not executes previous month's dates '30-01-2013' & '31-01-2013'.

i've seek this:

delete tbltest time < date('now','-7 days');

but no results.:(

what functions sqlite side, can perform operation based on functions , exact values lastly week records.?

please help me situation.

thanks in advance.

in sqlite, timestamps should stored year field first, i.e., in format yyyy-mm-dd hh:mm:ss.

iphone database datetime sqlite3

laravel - Questionmark in url -



laravel - Questionmark in url -

i'm trying utilize http://api.jqueryui.com/autocomplete/#option-source laravel , need send request url ends "?term=foo". i've tried escape "?" backslash, doesn't work. clarify, want:

route::get('search\?term=(:any)', function() { //do }

is possible have questionmarks in url laravel?

having question mark in url should create no difference. you're using php framework, , speaking, ...?term=parameters should not problematic. knowledge, there should no need escape such question mark... handled appropriately default.

laravel

c - When I turn O_NONBLOCK on i get "0" and "I/O error" -



c - When I turn O_NONBLOCK on i get "0" and "I/O error" -

when turn on o_nonblock connection len returns 0 , errno returns eio. expecting len -1 , errno eagain. based on getting can assume there problem initial connection. don't understand why getting it. if comment out turn on o_nonblock not have issue @ all. missing in regards turning on o_nonblcok?

my code (main())

long len; //var o_nonblocking int flags; printf("r thread - starting\n"); maintcpipindex = tcpipindex = 0; while ( fmainshutdown == false ) { s_muxwait(5000, "", &hevtcpipbuffavail[maintcpipindex], 0); if ( hevtcpipbuffavail[maintcpipindex] == 0) continue; len = s_recv( lsocket, tcpiprecord[maintcpipindex].tcpipbuffer, sizeof(tcpiprecord[maintcpipindex].tcpipbuffer)); //initialize flags var flags = fcntl(lsocket, f_getfl, 0); //turns on o_nonblocking fcntl(lsocket, f_setfl, flags | o_nonblock); if (len == -1 || len == 0 && errno != eagain) //0 = connection broken host { receiveerror = errno; hevreceiveerror = 1; printf("r_main - set hevreceiveerror on\n"); pthread_exit(null); } //catches o_nonblock if (len == -1 && errno == eagain) { logmessage(&logstruct, info, logqueue + logscreen, "caught o_nonblocking\n"); len = 0; continue; } // record length tcpiprecord[maintcpipindex].ultcpipbuflen = len; // tell t thread have message hevtcpipbuffused[maintcpipindex] = 1; hevtcpipbuffavail[maintcpipindex] = 0; // maintain index if ( ++maintcpipindex >= max_tcpip_buffs ) maintcpipindex = 0; }//end while

edit

maybe did not create clear first time, understand errno , len has s_recv issue getting undesired results when turn on o_nonblock; s_recv's errno eio , len 0. if turn turn off o_nonblock of issues go away; len 1 or more , errno not need checked.

below illustration of th scenarios expect:

in first bad scenario s_recv's len 0 or -1, errno not eagain, , connection reset.

in sec bad sceanrio s_recv's len -1 , errno eagain. exepected scenario when o_nonblock turned on based off man pages.

in sceanrio s_recv's len more 1 , there no need check errno.

the alter o_nonblock not relevant before next read.

so, must check len , errno before phone call fcntl. , must check homecoming value of fcntl of course, because might fail well.

to summarize, len == 0 , errno == eio has nil alter o_nonblock, s_recv before.

additionally, aware

if (len == -1 || len == 0 && errno != eagain)

is same

if (len == -1 || (len == 0 && errno != eagain) )

which not meaningful, because if homecoming value not -1, errno must ignored. if homecoming value 0, peer has closed connection.

update:

i've built simple echo client

fd = socket(af_inet, sock_stream, 0); if (fd == -1) error("socket"); = gethostbyname("localhost"); memset(&addr, 0, sizeof(addr)); addr.sin_family = af_inet; addr.sin_addr.s_addr = ((struct in_addr*)he->h_addr)->s_addr; addr.sin_port = htons(7); /* echo */ if (connect(fd, (struct sockaddr*) &addr, sizeof(addr)) == -1) error("connect"); while (fgets(buf, sizeof(buf), stdin)) { n = strlen(buf); printf("fgets=%d, %s", n, buf); if (send(fd, buf, n, 0) == -1) error("send"); n = recv(fd, buf, sizeof(buf), 0); if (n == -1) error("recv"); printf("recv=%d, %s", n, buf); flags = fcntl(fd, f_getfl, 0); printf("flags=%d\n", flags); if (fcntl(fd, f_setfl, flags | o_nonblock) == -1) error("fcntl"); }

and after setting o_nonblock, receive

errno=11 recv: resource temporarily unavailable

if move fcntl(o_nonblock) before loop, works fine.

so, seems not advisable fiddle non blocking after reading or writing socket.

c linux tcp redhat

objective c - iOS UI Automation element finds no sub-elements -



objective c - iOS UI Automation element finds no sub-elements -

i'm starting out ui automation ios app , having trouble. i'm unable attach screen shots i'll best describe scenario.

i'm building ios 6.0 , using storyboard. app launches screen navigation controller. root view controller contains main view has 1 uiview subview takes bottom 60% of screen , segmented command sits above subview. able configure accessibility main view (label "mainview"). able locate element in test no problem. however, having problem finding segmented controller. decided log out length of "elements()" , "segementedcontrols()" "mainview" element , length of each array 0. somehow when test running app it's saying there no sub-elements on main view.

another thing note not find accessibility section in identity inspector of storyboard editor segmented control. temporarily added button main view , configured accessibility label, test if elements() or buttons() calls subsequently show element main view when running test, these arrays still returning empty, button.

here's script:

var target = uiatarget.localtarget(); var app = target.frontmostapp(); function selectlistview() { var testname = "selectlistview"; uialogger.logstart(testname); var view = app.mainwindow().elements()["mainview"]; if (!view.isvalid()) { uialogger.logfail("could not locate main view"); } uialogger.logmessage("number of elements sub element: " + view.elements().length); var segmentedcontrol = view.segmentedcontrols()[0]; if (!segmentedcontrol.isvalid()) { uialogger.logfail("could not locate segmented command on physician collection parent view"); } var listbutton = segmentedcontrol.buttons()[1]; if (!listbutton.isvalid()) { uialogger.logfail("could not locate list button on segemented controller on physician collection parent view"); } uialogger.logmessage("tapping list button on physician collection view's segmented control"); listbutton.tap(); uialogger.logpass(testname); } selectlistview();

any help appreciated.

edit: added script search entire view hierarchy main window, set accessibility label value segmented command in initwithcoder (since don't seem able set 1 in storyboard editor segmented control, stated earlier) , still not find element - it's though it's not in view hierarchy, though it's on screen , functions fine:

function traverse(root, name) { if (root.name() == name) { homecoming root; } var elements = root.elements(); (var = 0; < elements.length; i++) { var e = elements[i]; var result = traverse(e, name); if(result != null) { homecoming result; } } homecoming null; } function selectlistview() { var testname = "selectlistview"; var segmentedcontrol = traverse(uiatarget.localtarget().frontmostapp().mainwindow(), "mysegementedcontrol"); if (segmentedcontrol == null) { uialogger.logmessage("still not find it"); } .... }

edit: added phone call app.logelementtree() , still no segmented command in sight ("physiciancollectionparentview" "mainview" - can see, no sub-elements there):

edit: here screen shots. first shows "master" view controller. next shows in add-on segmented command there uiview subview. 3rd shows basic entry point app in storyboard.

here class extension "master" view controller here, showing outlets segmented command , other uiview subview:

@interface physiciancollectionmasterviewcontroller () @property (strong, nonatomic) iboutlet uisegmentedcontrol *viewselectioncontrol; @property (strong, nonatomic) iboutlet uiview *physiciancollectionview; @end

edit: here's interesting - decided go brand new script created within instruments , take advantage of record feature. when clicked on segmented control, here's javascript created show me how had accessed 1 of buttons on segmented control:

var target = uiatarget.localtarget(); target.frontmostapp().mainwindow().elements()["physiciancollectionparentview"].tapwithoptions({tapoffset:{x:0.45, y:0.04}});

so, guess worst-case go this, makes no sense me ui automation not think command exists. strange. there must i'm missing setup basic can't imagine be.

when set accessibilitylabel element , flag isaccessibilityelement = yes; subviews of element hidden. automation, should utilize accessibilityidentifier instead of accessibilitylabel , set isaccessibilityelement = no;

in objective c code after physiciancollectionview rendered, remove label , accessibility flag , instead:

physiciancollectionview.accessibilityidentifier = @"physiciancollectionparentview"; physiciancollectionview.isaccessibilityelement = no;

for lastly elements in element tree, not have sub views, set isaccessibilityelement = yes;

ios objective-c ios-ui-automation

css - Looking for a more efficient way to write this Javascript -



css - Looking for a more efficient way to write this Javascript -

is there improve way me write togglefullscreen(). i'm repeating style rules on every browser seems unnecessary.

function togglefullscreen() { var elem = document.getelementbyid("video_container"); var db = document.getelementbyid("defaultbar"); var ctrl = document.getelementbyid("controls"); if (!document.fullscreenelement && // alternative standard method !document.mozfullscreenelement && !document.webkitfullscreenelement) { // current working methods if (document.documentelement.requestfullscreen) { db.style.background ='red'; ctrl.style.width = '50%'; ctrl.style.left = '25%'; elem.requestfullscreen(); } else if (document.documentelement.mozrequestfullscreen) { db.style.background ='red'; ctrl.style.width = '50%'; ctrl.style.left = '25%'; elem.mozrequestfullscreen(); } else if (document.documentelement.webkitrequestfullscreen) { db.style.background ='red'; ctrl.style.width = '50%'; ctrl.style.left = '25%'; elem.webkitrequestfullscreen(); } } else if (document.exitfullscreen) { db.style.background ='yellow'; ctrl.style.width = '100%'; ctrl.style.left = '0'; document.exitfullscreen(); } else if (document.mozcancelfullscreen) { db.style.background ='yellow'; ctrl.style.width = '100%'; ctrl.style.left = '0'; document.mozcancelfullscreen(); } else if (document.webkitcancelfullscreen) { db.style.background ='yellow'; ctrl.style.width = '100%'; ctrl.style.left = '0'; document.webkitcancelfullscreen(); } }

the out of fullscreen style rules beingness applied page loads.

that's because of code:

full.addeventlistener('click', togglefullscreen(), false);

if executes togglefullscreen() , passes homecoming value addeventlistener instead. code should read:

full.addeventlistener('click', togglefullscreen, false);

this code passes reference function instead of homecoming value.

refactoring

by using || operator can simplify existing conditions.

var fullscreenelement = document.fullscreenelement || document.mozfullscreenelement || document.webkitfullscreenelement; if (fullscreenelement) { var requestfullscreen = document.documentelement.requestfullscreen || document.documentelement.mozrequestfullscreen || document.documentelement.webkitrequestfullscreen db.style.background ='red'; ctrl.style.width = '50%'; ctrl.style.left = '25%'; requestfullscreen.call(elem); } else { var exitfullscreen = document.exitfullscreen || document.mozcancelfullscreen || document.webkitcancelfullscreen; db.style.background ='yellow'; ctrl.style.width = '100%'; ctrl.style.left = '0'; exitfullscreen.call(document); }

javascript css html5 javascript-events eventlistener

javascript - Parse string regex for known keys but leave separator -



javascript - Parse string regex for known keys but leave separator -

ok, nail little bit of snag trying create regex.

essentially, want string like:

error=some=new item user=max datefrom=2013-01-15t05:00:00.000z dateto=2013-01-16t05:00:00.000z

to parsed read

error=some=new item user=max datefrom=2013-01-15t05:00:00.000z ateto=2013-01-16t05:00:00.000z

so want pull known keywords, , ignore other strings have =.

my current regex looks this:

(error|user|datefrom|dateto|timefrom|timeto|hang)\=[\w\s\f\-\:]+(?![(error|user|datefrom|dateto|timefrom|timeto|hang)\=])

so i'm using known keywords used dynamically can list them beingness know.

how write include requirement?

you utilize replace so:

var input = "error=some=new item user=max datefrom=2013-01-15t05:00:00.000z dateto=2013-01-16t05:00:00.000z"; var result = input.replace(/\s*\b((?:error|user|datefrom|dateto|timefrom|timeto|hang)=)/g, "\n$1"); result = result.replace(/^\r?\n/, ""); // remove first line

result:

error=some=new item user=max datefrom=2013-01-15t05:00:00.000z dateto=2013-01-16t05:00:00.000z

javascript regex key-value

android - Reducing font size of AlertDialog.Builder's components -



android - Reducing font size of AlertDialog.Builder's components -

i created alertdialogue using next code :

int selectedmodeid=0; public void sorttypemodeselection(){ alertdialog.builder alertbuilder=new alertdialog.builder(watchlistdetailactivity.this); alertbuilder.setsinglechoiceitems(r.array.watchlist_sorting_modes,selectedmodeid, new dialoginterface.onclicklistener(){ public void onclick(dialoginterface dialog, int which) { switch (which){ case 0: selectedmodeid=0; break; case 1: selectedmodeid=1; break; case 2: selectedmodeid=2; break; case 3: selectedmodeid=3; break; case 4: selectedmodeid=4; break; case 5: selectedmodeid=5; break; case 6: selectedmodeid=6; break; case 7: selectedmodeid=7; break; } dialog.cancel(); } }); alertbuilder.show(); }

i made alert, want cut down font size of list items of dialog. how can this?

note: don't recommend inflating custom layout accomplish this, wish know if there approach.

i able accomplish through styles. added style styles.xml file in values directory:

<style name="alertdialogtheme" parent="android:theme.dialog"> <item name="android:textsize">14sp</item> </style>

then when creating alertdialog, wrapped activity context in contextthemewrapper , passed builder constructor:

contextthemewrapper cw = new contextthemewrapper( this, r.style.alertdialogtheme ); alertdialog.builder b = new alertdialog.builder( cw );

this produced smaller text size list items in dialog.

android android-alertdialog android-custom-view android-fonts

css - Opacity of element not set in media Query -



css - Opacity of element not set in media Query -

good day

i setting opacity on 2 elements, li element , image element. on hover effect, take away opacities.

problem: using media query display site on mobile phones. issue when set media query 1024px, want take away opacities completely, not trigger when viewport below 1024px ...refreshed well

why that:

code:

html:

<div id="app" class="span3"> <ul> <li id="apple"><a href="#" title="partyat iphone , ipad"><img src="images/apple.png" /></a></li> <li id="android"><a href="#"><img alt="partyat android app on google play" src="images/android.png" /></a></li> </ul> </div> , <div id="social" class="row-fluid"> <div class="span7"> <div id="app2"> <a href="https://itunes.apple.com/za/app/partyat/id597807299?mt=8" title="partyat iphone , ipad"><img src="images/apple.png" /></a> <a href="https://play.google.com/store/apps/details?id=io.ik.partyat"><img alt="partyat android app on google play" src="images/android.png" /></a> </div> </div> <div class="span5"> <a href="" title="partyat sa facebook page" target="_blank"><img src="images/fb.png" border="0" /></a> <a href="" title="partyat sa twitter page" target="_blank"><img src="images/twitter.png" border="0" /></a> </div> </div>

css:

#app ul li{ opacity:0.7; -ms-filter: "progid:dximagetransform.microsoft.alpha(opacity=70)"; filter:alpha(opacity=70); padding-bottom: 15px; } #social .span5 img { opacity: 0.7; -ms-filter: "progid:dximagetransform.microsoft.alpha(opacity=70)"; filter:alpha(opacity=70); }

media query:

@media screen , (max-width: 1024px;){ #app ul li { opacity:1; -ms-filter: "progid:dximagetransform.microsoft.alpha(opacity=100)"; filter:alpha(opacity=100); padding-bottom: 15px; } #social .span5 img { opacity: 1; -ms-filter: "progid:dximagetransform.microsoft.alpha(opacity=100)"; filter:alpha(opacity=100); } }

your media query working, after that, overwriting it:

@media screen , (max-width: 1024px;){ /* custom styles... */ #app ul li { opacity:1; } } /* normal styles */ #app ul li { opacity:0.7; }

so can utilize !important avoid conflict:

#app ul li { opacity:1 !important; }

warning: should not utilize !important if there improve solution. please, read following:

when 2 css rules conflicting, order of priority is:

rules !important have top priority inline styles more of import (e.g. <div class="someclass" style="inline style"></div> normal styles more specific rules > less specific (#one .example tag .yeah > .yeah) if 2 rules have same priority, lastly 1 applied wins

so, inspect css see what's happening. maybe can move media query end of stylesheet...

if still have problems, please post finish example.

css

arrays - Java classes and ArrayList clarification -



arrays - Java classes and ArrayList clarification -

i have created java class , trying larn how arraylist work.

let's have top class called complex. in class have houses, employees etc, of these separate classes.

if wanted create arraylist how go that?

the number of elements dynamic when says add together new house, phone call method asks questions relating house , adds list i'm assuming?

to create arraylist hold objects of type house, can do:

arraylist<house> houselist = new arraylist<house>(); houselist.add(new house());

to loop on items in list

for(house house:houselist){ // house object }

see the documentation larn other functions.

java arrays list class arraylist

asp.net mvc 4 - Ajax.BeginForm doesn't work properly -



asp.net mvc 4 - Ajax.BeginForm doesn't work properly -

i have problem ajax submit. have main view render partialview , within lastly 1 load partialview. this:

main view

list of elements -> partialview 1

create new element -> partialview 2 within partialview 1

i using ajaxbeginform replace , update options:

@using (ajax.beginform("create", "mycontroller", new ajaxoptions { insertionmode = insertionmode.replace, updatetargetid = "form0", httpmethod = "post" }))

my problem submit works first time. saves new element , re-render partialview 1 ( updates list ). if want submit 1 time again redirect me partialview 1.

why happening , wrong in code? how can ?

here's controller action:

[httppost] public partialviewresult create(model viewmodel) { viewmodel.save(viewmodel.formmodel); var newviewmodel = new defaultviewmodel(viewmodel.xid,viewmodel.yid); homecoming partialview("_defaultpartialview", newviewmodel); }

it's ok action returns partialview? should of type jsonresult ?

and partialview 1:

@using (ajax.beginform("createbehaviorlog", "behaviorlog", new ajaxoptions { insertionmode = insertionmode.replace, updatetargetid = "form0", httpmethod = "post" })) { @model defaultviewmodel @scripts.render("~/bundles/jquery") <h2>title</h2> { html.renderpartial("partialview2", model.modelforpartialview2); } <div id="listofelements"> @foreach(var item in model.x) { --list-- } </div> }

thank you.

update:

i fixed ( newbie error ). i'll post tomorrow reply because it's kinda late , need sleep!

so, first of all, when create ajax phone call sure included need. here mean:

be sure have <add key="unobtrusivejavascriptenabled" value="true"/> in webconfig.

be sure have included script in page.

if using latest jquery need alter live function on in unobtrusive script.

btw, if have problem mentioned above here have done first time ( changed because it's not such solution ) :

mainview @using (ajax.beginform("create", "mycontroller", new ajaxoptions { insertionmode = insertionmode.replace, updatetargetid = "form0", httpmethod = "post" })) { renderpartial1 renderpartial1.2 } renderpartial2 .. renderpartialn

as can see, i've set ajaxbeginform outside partial1.2 submit, in mainview. method wasn't because if need 2 forms ?

in end quit using ajaxbeginform , used htmlbeginform ajax post javascript.

ajax asp.net-mvc-4

lm - R - interaction with only one factor level in regression -



lm - R - interaction with only one factor level in regression -

in regression model possible include interaction 1 dummy variable of factor? example, suppose have:

x: numerical vector of 3 variables (1,2 , 3) y: response variable z: numerical vector

is possible build model like:

y ~ factor(x) + factor(x) : z

but include interaction 1 level of x? realize create separate dummy variable each level of x, simplify things if possible.

really appreciate input!!

one key point you're missing when see important effect x2:z, doesn't mean x interacts z when x == 2, means the difference between x == 2 , x == 1 (or whatever reference level is) interacts z. it's not level of x interacting z, it's 1 of contrasts has been set x.

so 3 level factor default treatment contrasts:

df <- data.frame(x = sample(1:3, 10, true), y = rnorm(10), z = rnorm(10)) df$x <- factor(df$x) contrasts(df$x) 2 3 1 0 0 2 1 0 3 0 1

if think first contrast important, can create new variable compares x == 2 x == 1, , ignores x == 3:

df$x_1vs2 <- na df$x_1vs2[df$x == 1] <- 0 df$x_1vs2[df$x == 2] <- 1 df$x_1vs2[df$x == 3] <- na

and run regression using that:

lm(y ~ x_1vs2 + x_1vs2:z)

r lm

android - How to initialize context? -



android - How to initialize context? -

this stupid question set context equal in context context = ...

just declaring sets null , need utilize context app.

you cannot instantiate context object. controlled system. however, every application has context , every activity context, have couple of obtain pointer context object:

assign pointer activity object context object pointer (i.e. using keyword)

the activity class has method called getapplicationcontext() retrieves pointer context object contained application.

android android-context

codeigniter - get file path from url in php? -



codeigniter - get file path from url in php? -

i using php sdk uploading images facebook album.for need give real path of images.incase of server can give real path of image , upload facebook working fine. here want upload images facebook album via using external image url. ie,i want upload image fb using next image url.http://i.nokia.com/r/image/view/-/2003984/highres/2/-/lumia-620-smart-shoot.jpg

$this->facebook->setfileuploadsupport(true); $photo = $this->facebook->api('/*********/photos', 'post', array( 'access_token' => $this->config->item('facebook_page_access_token'), 'source' => '@' .$imagepath, 'message' => "description text" ) );

this code uploading images fb. here how can path of image using given url in php?

you can publish photo external source using 'url' parameter.

$photo = $this->facebook->api('/*********/photos', 'post', array( 'access_token' => $this->config->item('facebook_page_access_token'), 'url' => $imagepath, 'message' => "description text" ) );

checkout below document.

https://developers.facebook.com/docs/reference/api/photo/

php codeigniter curl facebook-php-sdk filepath

cordova - iOS notification.alert() not working using Phonegap 2.3.0 -



cordova - iOS notification.alert() not working using Phonegap 2.3.0 -

i have unusual issue when attempting utilize navigator.notification.alert() in xcode 4.6 using phonegap 2.3.0.

i have 2 files, index.html , other.html. clicking 'test alert' index.html triggers alert expected, after dismissing alert , navigating other.html, clicking 'test other alert' not trigger alert.

however, if click 'test alert' 2 or more times on index.html before moving other.html, alert go on function expected. it's after triggering alert 1 time , changing pages alerts stop functioning together.

index.html

<!doctype html> <html> <head> <script type="text/javascript" src="cordova-2.3.0.js"></script> <script type="text/javascript" charset="utf-8"> function alerttest() { navigator.notification.alert('testing', null, 'alert test', 'ok'); } </script> </head> <body> <a href='other.html'>move other page</a> <a href="#" onclick="alerttest(); homecoming false;">test alert</a> </body> </html>

other.html

<!doctype html> <html> <head> <script type="text/javascript" src="cordova-2.3.0.js"></script> <script type="text/javascript" charset="utf-8"> function alerttest() { navigator.notification.alert('testing', null, 'alert test', 'ok'); } </script> </head> <body> <a href="index.html">go back</a> <a href="#" onclick="alerttest(); homecoming false;">test alert</a> </body> </html>

i @ finish loss why happens, in app need able trigger alerts on button presses on different pages, seemingly hit-and-miss in example.

any help or nudge in right direction appreciated!!

update:

this seems happen ios 6 , 6.1 simulators. when alerts don't pop up, pressing home key , opening app 1 time again makes missing alerts appear @ once.

this illustration has same behaviour: http://docs.phonegap.com/en/2.3.0/cordova_notification_notification.md.html#notification

can confirm if simulator bug in latest xcode?

this problem exists since phonegap 2.2 see: notification in phonegap ios same problem on windowsmobile on phonegap 2.3.

i didn't update 2.1 ... seems lastly version worked properly.

don't forget add together document.addeventlistener("deviceready", ondeviceready, true); above.

ios cordova alert

osx - How to unmount webcam from Mac to make it work inside Virtualbox -



osx - How to unmount webcam from Mac to make it work inside Virtualbox -

unlike usb pendrive, unable select webcam device virtual machine.

i next error when trying so:

failed attach usb device logitech photographic camera [0010] virtual machine windows. usb device 'logitech camera' uuid {0fe606fc-298c-4250-aee3-f7fb6cc8ef2f} busy previous request. please seek 1 time again later.

i similar error pendrive if it's mounted.

i using virtualbox extension , invitee additions installed.

how unmount photographic camera , create work on virtual machine?

i came across same error when seek plug old usb scanner virtual box instance running windows xp. ( when installed drivers first time in virtual machine worked. after time when trying re plug it, error displayed "usb device busy previous request")

what did

i unplugged scanner form usb port , unplug scanner powerfulness source well. then forcefulness closed virtual machine without saving status. updated virtual box newest version. disable usb 2.0 (ehci) back upwards in bios, ( goto settings -> select usb devices) start virtual machine. plugin usb , plug scanner powerfulness source. add new filter usb ( goto settings -> usb devices) select detected scanner bottom usb device list.

after doing virtual box auto detected , installed drivers again

good luck

osx virtualbox

javascript - for-loop gets stuck on the same number -



javascript - for-loop gets stuck on the same number -

below loop runs 1 time i=0, indefinitely i=1 browser crash, i.e. not increment:

cascadecomponent: function(item, fn, scope) { if (fn.call(scope || this, item) !== false) { if (item.items) { (i = 0; < item.items.items.length; i++) { this.cascadecomponent(item.items.items[i], fn, scope); } } } }

i can avoid issue using frameworks iteration loop. alternatively have same loop working slight difference array found in item.items vs. item.items.items.

any ideas why happens? it's same in chrome , firefox.

you using global i variable. add together line @ start of function:

var i;

otherwise each recursive phone call resets i 0 invocations of cascadecomponent.

javascript

javascript - Posting to Twitter through OAuthSimple.js -



javascript - Posting to Twitter through OAuthSimple.js -

i've been stuck on 1 while. i'm trying utilize oauthsimple.js interact twitter in chrome extension i've written.

the signing process seems work fine requests retrieve user's statuses, can't seem build request authenticate when seek retweet, reply, or mark tweet favorite.

i'm next guides here. have tried numerous ways of structuring request, , comparing request contents against output of oauth tool provided twitter ( seems check out ), i'm still getting 401 errors , generic "we couldn't authenticate you" responses.

here's how i'm trying form request:

var sendtwitterrequest = function(url, params, method, callback) { var request = null; if ( localstorage.twitterauthtoken ) { oauthsimple().reset(); request = oauthsimple(twitterconsumerkey,twitterconsumersecret).sign({ action:method, method:"hmac-sha1", datatype:"json", path:url, parameters:params, signatures:{ oauth_version:'1.0', oauth_token:localstorage.twitterauthtoken, oauth_secret:localstorage.twitterauthverifier } }); console.log(request); $j.ajax({ url:request.signed_url, type:method, data:request.parameters, success:callback }); } };

then, making calls method this:

// works, info , can stuff sendtwitterrequest('http://api.twitter.com/1/statuses/user_timeline.json?user_id=',null,'get',somemethod()); // fails , throws 401 error every time sendtwitterrequest("https://api.twitter.com/1/statuses/retweet/"+tweetkey+".json",null,'post',someothermethod());

am missing something? in advance!

it turns out requests creating fine, needed final 1 exchange request tokens oauth tokens. thought step covered when user prompted input, turns out wrong.

i ended switching oauthsimple.js oauth.js, on business relationship of fact oauth.js process both token requests , timeline requests.

some of pretty specific application doing, need modify it.

the new sendtwitterrequest method:

var sendtwitterrequest = function(options){ var accessor={ consumersecret:twitterconsumersecret }; var message={ action:options.url, method:options.method||"get", parameters:[ ["oauth_consumer_key",twitterconsumerkey], ["oauth_signature_method","hmac-sha1"], ["oauth_version","1.0"] ] }; if(options.token){ message.parameters.push(["oauth_token",options.token]) } if(options.tokensecret){ accessor.tokensecret=options.tokensecret } for(var in options.parameters) { message.parameters.push(options.parameters[a]) } oauth.settimestampandnonce(message); oauth.signaturemethod.sign(message,accessor); seek { $j.ajax({ url:message.action, async:options.async||true, type:message.method||'get', data:oauth.getparametermap(message.parameters), datatype:options.format||'json', success:function(data) { if (options.success) {options.success(data);} } }); } grab ( e ) { } };

and methods depend on it:

// asks twitter oauth request token. user authorizes , request token provided requesttwittertoken = function() { // semi-specific extension doing, callback string may need // different. var callbackstring = window.top.location + "?t=" + date.now(); var params = [ [ 'oauth_callback', callbackstring ] ]; sendtwitterrequest({ url: "https://api.twitter.com/oauth/request_token", method: 'post', parameters: params, format: 'text', success: function(data) { var returnedparams = getcallbackparams(data); if ( returnedparams.oauth_token ) { chrome.tabs.create({ url:"https://api.twitter.com/oauth/authorize?oauth_token=" + returnedparams.oauth_token }); } },error:function( e ) { console.log( 'error' ); console.log( e ); } }); }; // exchanges twitter request token actual access token. signintotwitter = function(token, secret, callback) { var auth_url = "https://api.twitter.com/oauth/access_token"; var authcallback = function(data) { var tokens = getcallbackparams(data); localstorage.twitterauthtoken = tokens.oauth_token || null; localstorage.twitterauthtokensecret = tokens.oauth_token_secret || null; callback(); }; seek { sendtwitterrequest({url:auth_url, method:'post', async:true, format:'text', token:token, tokensecret:secret, success:authcallback}); } grab ( e ) { console.log(e); } };

with this, steps follows:

ask twitter token ( requesttwittertoken() ) , provide callback in callback, check see if token provided. if so, it's initial token pass token twitter , open twitter auth page, allows user grant access in callback call, see if access token provided exchange request token access token ( signintotwitter() )

after that, utilize sendtwitterrequest() method nail twitter's api fetch timeline , post tweets.

javascript oauth google-chrome-extension twitter twitter-oauth

python - Scrapy - doesn't crawl -



python - Scrapy - doesn't crawl -

i'm trying recursive crawl running , since 1 wrote wasn't working fine, pulled illustration web , tried. don't know, problem is, crawl doesn't display errors. can help me this.

also, there step-by-step debugging tool help understand crawl flow of spider.

any help regarding appreciated.

macbook:spiders hadoop$ scrapy crawl craigs -o items.csv -t csv /system/library/frameworks/python.framework/versions/2.6/extras/lib/python/zope/__init__.py:1: userwarning: module pkg_resources imported /system/library/frameworks/python.framework/versions/2.6/extras/lib/python/pkg_resources.pyc, /library/python/2.6/site-packages beingness added sys.path__import__('pkg_resources').declare_namespace(__name__) /system/library/frameworks/python.framework/versions/2.6/extras/lib/python/zope/__init__.py:1: userwarning: module site imported /system/library/frameworks/python.framework/versions/2.6/lib/python2.6/site.pyc, /library/python/2.6/site-packages beingness added sys.path__import__('pkg_resources').declare_namespace(__name__) 2013-02-08 20:35:55+0530 [scrapy] info: scrapy 0.16.4 started (bot: myspider) 2013-02-08 20:35:55+0530 [scrapy] debug: enabled extensions: feedexporter, logstats, telnetconsole, closespider, webservice, corestats, spiderstate 2013-02-08 20:35:55+0530 [scrapy] debug: enabled downloader middlewares: httpauthmiddleware, downloadtimeoutmiddleware, useragentmiddleware, retrymiddleware, defaultheadersmiddleware, redirectmiddleware, cookiesmiddleware, httpcompressionmiddleware, chunkedtransfermiddleware, downloaderstats 2013-02-08 20:35:55+0530 [scrapy] debug: enabled spider middlewares: httperrormiddleware, offsitemiddleware, referermiddleware, urllengthmiddleware, depthmiddleware 2013-02-08 20:35:55+0530 [scrapy] debug: enabled item pipelines: 2013-02-08 20:35:55+0530 [craigs] info: spider opened 2013-02-08 20:35:55+0530 [craigs] info: crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) 2013-02-08 20:35:55+0530 [scrapy] debug: telnet console listening on 0.0.0.0:6023 2013-02-08 20:35:55+0530 [scrapy] debug: web service listening on 0.0.0.0:6080 2013-02-08 20:35:58+0530 [craigs] debug: crawled (200) <get http://sfbay.craigslist.org/npo/> (referer: none) 2013-02-08 20:35:58+0530 [craigs] info: closing spider (finished) 2013-02-08 20:35:58+0530 [craigs] info: dumping scrapy stats: {'downloader/request_bytes': 230, 'downloader/request_count': 1, 'downloader/request_method_count/get': 1, 'downloader/response_bytes': 7291, 'downloader/response_count': 1, 'downloader/response_status_count/200': 1, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2013, 2, 8, 15, 5, 58, 415553), 'log_count/debug': 7, 'log_count/info': 4, 'response_received_count': 1, 'scheduler/dequeued': 1, 'scheduler/dequeued/memory': 1, 'scheduler/enqueued': 1, 'scheduler/enqueued/memory': 1, 'start_time': datetime.datetime(2013, 2, 8, 15, 5, 55, 343482)} 2013-02-08 20:35:58+0530 [craigs] info: spider closed (finished)

the code have used follows,

from scrapy.contrib.spiders import crawlspider, rule scrapy.contrib.linkextractors.sgml import sgmllinkextractor scrapy.selector import htmlxpathselector #from craigslist_sample.items import craigslistsampleitem class myspider(crawlspider): name = "craigs" allowed_domains = ["sfbay.craigslist.org"] start_urls = ["sfbay.craigslist.org/npo/"] rules = (rule (sgmllinkextractor(allow=("d00\.html", ),restrict_xpaths=('//p[@id="nextpage"]',)) , callback="parse_items", follow= true), ) def parse_items(self, response): hxs = htmlxpathselector(response) titles = hxs.select("//p") items = [] titles in titles: item = craigslistsampleitem() item ["title"] = titles.select("a/text()").extract() item ["link"] = titles.select("a/@href").extract() items.append(item) return(items)

modify sgmllinkextractor payala suggested remove restrict_xpaths section of link extractor

these changes prepare issue beingness experienced. i'd create next suggestion xpath used select titles, remove empty items occur because next page links beingness selected.

def parse_items(self, response): hxs = htmlxpathselector(response) titles = hxs.select("//p[@class='row']")

python web-crawler scrapy

xml - Edit joomla content in component via CSS on a template i created -



xml - Edit joomla content in component via CSS on a template i created -

how edit body text (content) of component in joomla. css edit #content responding other attributes padding/margin, border, width/height , background not on font attributes...

in index.php

<body> <div id="content"><jdoc:include type="component" /></div> </body>

css

#content { padding:20px 10px 0 20px; width:670px; border-right:1px groove; line-height:30px; font-family:monotype corsiva; font-size:16px; }

hmm.. if think font attributes important, can utilize !important property overrule styling :)

#content { padding:20px 10px 0 20px; width:670px; border-right:1px groove; line-height:30px; font-family:monotype corsiva !important; font-size:16px !important; }

css xml html5 joomla1.5 joomla-template

Fatal error: Function name must be a string in web/mhswpindahprodi.det.php on line 221 -



Fatal error: Function name must be a string in web/mhswpindahprodi.det.php on line 221 -

here code

tampilkanjudul("mahasiswa pindah prodi"); if (!empty($mhswid)) { $gos = (empty($_request['gos']))? 'konfirmasipindah' : $gos; $mhsw = getfields("mhsw m left outer bring together programme prg on m.programid=prg.programid left outer bring together prodi prd on m.prodiid=prd.prodiid left outer bring together statusmhsw sm on m.statusmhswid=sm.statusmhswid", 'm.mhswid', $mhswid, "m.*, prg.nama prg, prd.nama prd, sm.nama sm, sm.keluar"); if ($mhsw['keluar'] == 'y') echo errormsg("tidak dapat dipindahkan", "status mahasiswa: <b>$mhsw[sm]</b> yang berarti sudah tidak dapat dipindah lagi. <hr size=1 color=silver> pilihan: <a href='?mnux=mhswpindahprodi'>kembali</a>"); else $gos ($mhsw); // line 221 } ?>

its geting error fatal error:

function name must string in /var/www/clients/client9/web31/web/mhswpindahprodi.det.php on line 221

$gos = (empty($_request['gos']))? 'konfirmasipindah' : $gos;

replace line with:

$gos = (empty($_request['gos']))? 'konfirmasipindah' : $_request['gos'];

it's pointless test whether variable exists, , utilize different variable instead ;)

php string runtime-error

Animated javascript scrollBy -



Animated javascript scrollBy -

i have next button when clicked want scroll downwards page 517px.

using next code (which have found on site) have made button scroll in smooth animated way. need add together that?

the code using follows:

function scrollbypixels(x, y) { window.scrollby(x, y); }

and next on actual button:

onclick="javascript:scrollbypixels(0, 517)"

thanks in advance

function scrollbypixels(x, y) { $('html,body').stop().animate({ scrollleft: '+=' + x, scrolltop: '+=' + y }); }

...or simple plugin:

$.fn.scrollby = function(x, y){ homecoming this.animate({ scrollleft: '+=' + x, scrolltop: '+=' + y }); };

demo

javascript

validation - validate pages folder in netbeans on demand like eclipse -



validation - validate pages folder in netbeans on demand like eclipse -

how validate pages folder in netbeans on demand eclipse ?

in eclipse we, right click on pages folder , validate folder. how in netbeans

eclipse validation netbeans

sqlite3 - sql JOIN with boolean on WHERE -



sqlite3 - sql JOIN with boolean on WHERE -

first, please note have little experience sql (in case sqlite3) , title of question may ill-phrased.

suppose have table of notes (n), , table of keywords notes (k), , table associating 1 or more keywords each note (nk). i'd find notes each contain 2 (or more) keywords.

to bit more specific, below (sqlite3) how i've set database.

create table n(nid integer primary key autoincrement, content); create table k(kid integer primary key autoincrement, content); create table nk(nkid integer primary key autoincrement, nid, kid); insert n(content) values ("note 1"); insert n(content) values ("note 2"); insert k(content) values ("keyword 1"); insert k(content) values ("keyword 2"); insert nk(nid, kid) values (1, 1); insert nk(nid, kid) values (1, 2); insert nk(nid, kid) values (2, 1);

with this, can notes tagged keyword id of 1 with

select * n left bring together nk on nk.nid = n.nid nk.kid=1;

and question how can notes keyword ids 1 and 2. i've done searching on web, i'm afraid knowledge insufficient think of searching terms. hope on site can help , -- importantly -- apologize if silly question.

to improve on @gordonlinoff's answer:

select * n nid in (select nid (select * nk kid in (1,2)) s grouping nid having count(distinct s.kid) = 2)

this records have kid matching 1 , 2 if other kid values might nowadays (3,4,etc). sqlfiddle here.

sql sqlite3

xcode - Trying to Center Map on Pin (MKMapView) -



xcode - Trying to Center Map on Pin (MKMapView) -

struggling find way create map zoom , center on annotation pin. pin drops, map loads ocean. code below.

- (void) connectiondidfinishloading:(nsurlconnection *)connection { [self setstring]; nsdictionary *dic = [nsjsonserialization jsonobjectwithdata:responsedata options:0 error:nil]; nsdictionary *location = [dic objectforkey:@"location"]; nsdictionary *coordinate = [location objectforkey:@"coordinate"]; nsstring *lat = [coordinate objectforkey:@"latitude"]; nsstring *lon = [coordinate objectforkey:@"longitude"]; (nsdictionary *diction in coordinate) { [array addobject:lat]; [array addobject:lon]; } { cllocationcoordinate2d track; track.latitude = [lat doublevalue]; track.longitude = [lon doublevalue]; mapviewannotation *newannotation = [[mapviewannotation alloc] initwithtitle:@"title of place here" andcoordinate:track]; [self.mapview addannotation:newannotation]; } }

2nd question, related:

after implementing reply above question, have since modified code. now, have coordinates coming mkmapview previous view, don't have bother making api phone call twice, sec beingness in mkmapview. in viewwillappear have following, , 1 time again experiencing problem view not center , zoom on pin:

if ([self.stringtodisplay isequaltostring: @"firehouse gallery"]) { uiimage *img = [uiimage imagenamed:@"firehouse.jpg"]; [imageview setimage:img]; cllocationcoordinate2d track; track.latitude = [lat doublevalue]; track.longitude = [lon doublevalue]; mkcoordinateregion region; mkcoordinatespan span; span.latitudedelta = 0.01; span.longitudedelta = 0.01; region.span = span; region.center = track; mapviewannotation *newannotation = [[mapviewannotation alloc] initwithtitle:@"firehouse gallery" andcoordinate:track]; [self.mapview addannotation:newannotation]; [self.mapview setregion:region animated:true]; [self.mapview regionthatfits:region]; }

feedback appreciated, can't tell else should do. pin loads on right coordinates, doesn't center/zoom...

try this:

{ cllocationcoordinate2d track; track.latitude = [lat doublevalue]; track.longitude = [lon doublevalue]; mkcoordinateregion region; mkcoordinatespan span; span.latitudedelta = 0.01; span.longitudedelta = 0.01; region.span = span; region.center = track; mapviewannotation *newannotation = [[mapviewannotation alloc] initwithtitle:@"title of place here" andcoordinate:track]; [self.mapview addannotation:newannotation]; [self.mapview setregion:region animated:true]; [self.mapview regionthatfits:region]; }

xcode xcode4 annotations mkmapview

python - How to chain {% includes %} in django templating -



python - How to chain {% includes %} in django templating -

i have base.html file looks this:

<!doctype html public "-//w3c//dtd html 4.01//en"> <html lang="en"> <head> {% block header %}{% endblock %} </head> <body> {% block content %}{% endblock %} {% block footer %}{% endblock %} </body> </html>

and have file, auth.html extends this:

{% extends "base.html" %} {% block content %} [my content] {% endblock %}

which works fine, want have separate header.html file plugs header block above.

what's right way construction auth.html , header.html in order include both , have both extend base.html?

i tried adding {% include header.html %} line auth.html, , structuring header.html follows:

{% extends "base.html" %} {% block header %} [header content here] {% endblock %}

but didn't work. how should doing this?

you need {{ block.super }}:

if need content of block parent template, {{ block.super }} variable trick. useful if want add together contents of parent block instead of overriding it.

its burried in template inheritance documentation.

suppose want add together stuff header block in auth.html. header defined in index.html:

your auth.html like:

{% extends "index.html" %} {% block header %} {{ block.super }} stuff, come after whatever in header block {% endblock %}

python html django

Can't iterate through a string and collect a list of strings in python. Typerror? -



Can't iterate through a string and collect a list of strings in python. Typerror? -

i'm looking able gather list of strings divides larger string marker ',

however, maintain getting error:

typeerror: string indices must integers, not str

here's code if take @ it

for f in phonebook: print f if phonebook[f] + phonebook[f+1] == "'," : linestring = phonebook[startpoint:(f+1)] arrayofstrings[j] = linestring startpoint = f+2 j = j+1 #iterate through array homecoming arrayofstrings

a sample of how want code in end like:

print arrayofstrings[1]

+445557284

print arrayofstrings[4]

+445558928 etc.

every f going 1 of strings in list phonebook. it's list, needs indexed integers, can see.

what want enumerate

for idx, val in enumerate(phonebook): if phonebook[idx] + phonebook[idx+1] == "',"

you should create sure check bounds, otherwise you're going run on end of list here!

there recipe pairwise implment:

from itertools import tee, izip def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, none) homecoming izip(a, b) a, b in pairwise(phonebook): if + b == "',":

python string int typeerror

c# - Updating a NVarChar(MAX) column with Linq causing an error -



c# - Updating a NVarChar(MAX) column with Linq causing an error -

i trying create update on existing value in database using linq in c#.

i instantiate variable:

var projecttrackingentity = context.project_trackings.single(pt => pt.project_id == projectid);

then update action column(it nvarchar(max)), checking if has action. if add together on semi-colon eg. action1;action2

when call:

context.submitchanges();

i error while debugging:

system.notsupportedexception: sql server not handle comparing of ntext, text, xml, or image info types.

i have tried setting updatecheck = updatecheck.never, doesn't prepare problem.

edit: adding code update actions (the variable "action" string)

var actions = projecttrackingentity.action.split(';'); bool equalactions = false; foreach (string in actions) { if (string.equals(a, action, stringcomparison.currentcultureignorecase)) { equalactions = true; break; } } if(!equalactions) { projecttrackingentity.action = string.isnullorempty(projecttrackingentity.action) ? //if action : //true projecttrackingentity.action + ';' + action; //false } context.submitchanges();

method 1:

for prepare issue open dbml file xml editor , set updatecheck never follows:

<column canbenull="true" dbtype="xml" name="permissionsxml" type="system.xml.linq.xelement" updatecheck="never"></column>

method 2:

change field in varchar(max)

method 3:

change updatecheck updatecheck.whenchanged

i hope help you.

c# linq

IE7 add element and value to javascript array -



IE7 add element and value to javascript array -

i declaring array such

var positions = [];

or

var positions = new array();

either way works

later in script value added such

positions[0].top = 0;

everything fine in every browser except ie7 gets error

error: unable set value of property 'top': object null or undefined

is there way should populate arra in ie7?

you want javascript function push(). should doing across board.

var positions = ["something", "somethign else"]; positions.push("something new");

.top property of dom elements believe, not appropriate array.

javascript arrays internet-explorer-7

Java encrypt/decript data from PHP to Java, IllegalBlockSizeException -



Java encrypt/decript data from PHP to Java, IllegalBlockSizeException -

i'm trying read base64 encoded , aes 128-bit encrypted string php, i'm getting illegalblocksizeexception.

php encrypt:

encrypt("my f awesome test !"); function encrypt($string){ $td = mcrypt_module_open('rijndael-128', '', 'cbc', "1cc251f602cf49f2"); mcrypt_generic_init($td, "f931c96c4a4e7e47", "1cc251f602cf49f2"); $enc = mcrypt_generic($td, $string); mcrypt_generic_deinit($td); mcrypt_module_close($td); homecoming base64_encode($enc); }

and returned value is:

mcbey73gq5fawxiunvkpquupiperlt9ntymrzjbpfti=

now want read in java:

static public string decrypt(string data) throws exception { info = new string( base64.decode(data, base64.no_wrap) ); byte[] keybyte = "f931c96c4a4e7e47".getbytes("utf-8"); byte[] ivbyte = "1cc251f602cf49f2".getbytes("utf-8"); key key = new secretkeyspec(keybyte, "aes"); ivparameterspec iv = new ivparameterspec(ivbyte); cipher c = cipher.getinstance("aes/cbc/nopadding"); c.init(cipher.decrypt_mode, key, iv); byte[] bval = c.dofinal( data.getbytes("utf-8") ); homecoming new string( bval ); }

and i'm getting exception:

javax.crypto.illegalblocksizeexception: info not block size aligned

this might caused padding?

edit

your error caused conversion of plaintext , string. it's not necessary anyway - utilize byte arrays:

byte[] info = base64 .decodebase64("mcbey73gq5fawxiunvkpquupiperlt9ntymrzjbpfti="); byte[] keybyte = "f931c96c4a4e7e47".getbytes("utf-8"); byte[] ivbyte = "1cc251f602cf49f2".getbytes("utf-8"); key key = new secretkeyspec(keybyte, "aes"); ivparameterspec iv = new ivparameterspec(ivbyte); cipher c = cipher.getinstance("aes/cbc/nopadding"); c.init(cipher.decrypt_mode, key, iv); byte[] bval = c.dofinal(data); system.out.println(new string(bval)); // prints f awesome test !

i recommend utilize padding in encryption, otherwise cannot cope arbitrarily-sized input.

java php aes encryption

How to get response's body with mocha / node.js -



How to get response's body with mocha / node.js -

i'm new mocha / omf. have basic test below:

omf('http://localhost:7000', function(client) { client.get('/apps', function(response){ response.has.statuscode(200); response.has.body('["test1","test2"]'); }); });

i'd check if value "test2" among list returned cannot figure out how feasible. i'm thinking of like:

omf('http://localhost:7000', function(client) { client.get('/apps', function(response){ response.has.statuscode(200); // response.body.split.contains("test2"); // }); });

can access response.body , parse string ?

** update **

i've tried test mocha, simple status code:

request = require("request"); describe('applications api', function(){ it('checks existence of test application', function(done){ request .get('http://localhost:7000/apps') .expect(200, done); }); });

but got next error:

typeerror: object # has no method 'expect'

any thought ? mocha need have additional addons ?

the sec illustration can not work shown. request.get asynchronous.

here's working illustration running request , should

request = require("request"); should = require("should"); describe('applications api', function() { it('checks existence of test application', function(done) { request.get('http://google.com', function(err, response, body) { response.statuscode.should.equal(200); body.should.include("i'm feeling lucky"); done(); }) }); });

node.js mocha

c++ - How to return an array of structs from a class in a getter function -



c++ - How to return an array of structs from a class in a getter function -

i have relatively simple question cant seem find reply specific case , may not approaching problem right way. have class looks this:

struct tileproperties { int x; int y; }; class loadmap { private: allegro_bitmap *maptoload[10][10]; tileproperties *individualmaptile[100]; public: //get struct of tile properties tileproperties *getmaptiles(); };

i have implementation looks getter function:

tileproperties *loadmap::getmaptiles() { homecoming individualmaptile[0]; }

i have code in loadmap class assign 100 tile properties each struct in array. want able access array of structs in main.cpp file cant seem find right syntax or approach. main.cpp looks this.

struct teststruct { int x; int y; }; int main() { loadmap _loadmap; teststruct *_teststruct[100]; //this assignment not work, there //a improve way? _teststruct = _loadmap.getmaptiles(); homecoming 0; }

i realize there many approaches this, i'm trying maintain implementation private possible. if please point me in right direction appreciate it. give thanks you!

teststruct *_teststruct; _teststruct = _loadmap.getmaptiles();

this pointer first element in array returned. can iterate through other 99.

i highly recommend using vectors, or container, , writing getters don't homecoming pointers bare arrays that.

c++ arrays struct allegro