Thursday, 15 July 2010

php - Correct way to handle maintenance mode from a Database setting -



php - Correct way to handle maintenance mode from a Database setting -

building cms , looking find out right way of showing maintenance mode message users.

my plan have alternative in admin backend. have table in db website config , have field has value. using 1 normal , 2 maintenance mode. want able update database.

my question however, whats proper way this?

my first thought check db , if value "2" redirect user (all php) e.g. 503.php.

but have seen improve way in .htaccess , can allow ip still have access. can in .htaccess managed database check?

looking things curious the 'standards' way of doing this.

is first suggestion feasible? main reason 'maintenance mode' protect myself. site has gone through lots of testing, want way can shut downwards access site (seo freindly) whilst prepare issues. or whilst updating site itself.

thanks

you shouldn't command maintenance mode setting database, if don't have to.

the database adds layer of complexity may fail @ point.

in practice, have few options:

add text file setting maintenance mode. prior serving request, utilize php open , read value of file. then, can handle appropriately issuing redirect if needed.

use external service pingometer monitor site(s). automates process and, if of them go down, utilize web hook functionality send request php script switches value (perhaps using method described in #1) maintenance mode.

i think goal that, if happens site (externally), maintenance mode automatically tripped -- #1 , #2 offer easy solution.

php .htaccess http-status-code-503 maintenance-mode

c++ - Dependencies and errors when using atoi -



c++ - Dependencies and errors when using atoi -

i given task refactor old project, , in these current days i'm checking dependencies of executables because reasons, changed since 2009, passing 4 14. more specific, job maintain dependencies before 2009, changes code occuring until today.

i tracked downwards instruction causing trouble. it'a function within library used project:

chain(str, pps) char *pps; char *str; { int pp = 0; pp = atoi(pps); // ic sunt leones.

if comment or replace atoi assignment of integer 0, 1 or 3, library compile fine, executable using .lib gives me these errors:

nafxcw.lib(wincore.obj) : error lnk2001: unresolved external symbol __imp__initcommoncontrols@0 nafxcw.lib(wincore.obj) : error lnk2001: unresolved external symbol __imp__dragacceptfiles@8 nafxcw.lib(appcore.obj) : error lnk2001: unresolved external symbol _closeprinter@4 nafxcw.lib(appcore.obj) : error lnk2001: unresolved external symbol _documentpropertiesa@24 nafxcw.lib(appcore.obj) : error lnk2001: unresolved external symbol _openprintera@12 nafxcw.lib(filecore.obj) : error lnk2001: unresolved external symbol __imp__shgetfileinfoa@20 nafxcw.lib(filecore.obj) : error lnk2001: unresolved external symbol _getfiletitlea@12

if otherwise utilize different value assignment, 2, 4 or every other integer, compile correctly , work.

any advice? what's happening here? why unusual behaviour?

edit: apparently problem not atoi. if utilize home made function , take char* , homecoming int or replacing straight sec parameter of function chain int , assigning straight still receive same errors.

you can seek :

include ('limits.h'); int my_getnbr(char *str) { int i; long nbr; int neg; neg = 0; nbr = 0; = 0; if (str[0] == '-') { neg = 1; str++; } while (str[i] >= '0' && str[i] <= '9') { nbr = nbr * 10 + (str[i++] - '0'); if (nbr > int_max) homecoming (0); } homecoming (neg ? (int)nbr * -1 : (int)nbr); }

it's home made atoi like.

edit : int_max alter mann. edit bis : if (nbr > int_max) alter mann 1 time again :)

c++ c visual-c++

reporting - Grouping by parameter value in jasper -



reporting - Grouping by parameter value in jasper -

well, don't know, maybe i'm missing something, i've been trying grouping info in jasper report, far grouping appears if grouping look field. possible grouping info parameter value instead of field value? i.e., like

<groupexpression><[!cdata[$p{some_param}]]></groupexpression>

instead of

<groupexpression><[!cdata[$f{some_field}]]></groupexpression>

in .jrxml file? in advance help can give me on this, pointer working illustration showing grouping parameter values, or anything.

is possible grouping info parameter value instead of field value?

yes, is, mentioned. have no syntax errors , study generated.

the problem may not bring you're expecting. grouping bands printed every time "groupexpression" changes. parameter needs associated alter during study generation (for example, filling parameter of subreport field in way subreport uses paramater grouping expression). , of course, needs associated makes sense , bring desirable behavior.

you can have in subreport:

... <parameter name="start" class="java.util.date"/> <parameter name="end" class="java.util.date"/> ...

and in detail band of "super" report:

<subreport> <reportelement x="0" y="10" width="555" height="200" uuid="ac2c99da-f595-4498-a518-2bfb1f31b73c"/> <subreportparameter name="start"> <subreportparameterexpression><![cdata[$f{start}]]></subreportparameterexpression> </subreportparameter> <subreportparameter name="end"> <subreportparameterexpression><![cdata[$f{end}]]></subreportparameterexpression> </subreportparameter> ... </subreport>

just notice i'm assuming fields $f{end} , $f{start} "java.util.date" objects.

jasper-reports reporting group

python - Is it expected behavior with os.path.join() -



python - Is it expected behavior with os.path.join() -

example1 path2 starts '/' results /dir2/dir3/ (missing path1)

path1='/volumes/disk1/' path2='/dir2/dir3/' print os.path.join(path1,path2)

example2 path2 not start '/' results proper /volumes/disk1/dir2/dir3/:

path1='/volumes/disk1/' path2='dir2/dir3/' print os.path.join(path1,path2)

question: thought purpose of os.path.join() allow avoid work of tedious work of verifying if it's mac, windows or linux file path: 1 command all. if have watch if path2 starts or not start '/' (or '\') ruins every hope had , brings ton of code... solution? don't want ugliness:

if path2 , path2.replace('\\','/')[1:] , path2.replace('\\','/').startswith('/'): path2=path2[1:]

in order work without hassle of checking separators have start without them or remove them before passing os.path.join() . in code below, show 3 ways can (live ideone example play with).

individual directories import os print os.path.join('volumes', 'disk1', 'dir2', 'dir3') split paths join path1 = '/volumes/disk1/' path2 = '/dir2/dir3/' import os # convert same above: # i.e., os.path.join('volumes', 'disk1', 'dir2', 'dir3') print os.path.join(*(path1.split(os.sep) + path2.split(os.sep))) custum bring together function

using above code, can write custom join() works either single- or multi- path strings:

def join(*paths): import os homecoming os.path.join(*[part path in paths part in path.split(os.sep)]) path1 = '/volumes/disk1/' path2 = '/dir2/dir3/' print join(path1, path2)

output:

'volumes/disk1/dir2/dir3'

python

connection - IPTables: connexion refused with MySQL (10061) -



connection - IPTables: connexion refused with MySQL (10061) -

before asking i've read first: http://dev.mysql.com/doc/refman/5.0/fr/access-denied.html first try:

~# mysql -h 127.0.0.1 -p 3306 -u uu dbname -p reading table info completion of table , column names can turn off feature quicker startup -a welcome mariadb monitor. commands end ; or \g. mariadb connection id 3296 server version: 5.5.37-mariadb-1~wheezy-log mariadb.org binary distribution copyright (c) 2000, 2014, oracle, monty programme ab , others. type 'help;' or '\h' help. type '\c' clear current input statement. mariadb [dbname]> bye ~# mysql -h 127.0.0.1 -p 3307 -u uu dbname -p error 2003 (hy000): can't connect mysql server on '127.0.0.1' (111)

so it's listening on port 3306. let's see network config:

~# ifconfig eth0 link encap:ethernet hwaddr d4:ae:52:cd:71:d6 inet addr:62.210.129.132 bcast:62.210.129.255 mask:255.255.255.0 blabla ~#

so let's seek right working port not 127.0.0.1:

~# mysql -h 62.210.129.132 -p 3306 -u uu dbname -p error 2003 (hy000): can't connect mysql server on '127.0.0.1' (111)

so i've tried prepare with:

mariadb [dbname]> grant privileges on dbname 'uu'@'62.%' identified 'xx'; query ok, 0 rows affected (0.00 sec) mariadb [dbname]> grant privileges on dbname.* 'uu'@'62.%' identified 'xx'; query ok, 0 rows affected (0.00 sec) mariadb [dbname]> bye ~# mysql -h 62.210.129.132 -u uu dbname -p error 2003 (hy000): can't connect mysql server on '62.210.129.132' (111) ~# ~# mysql -h 127.0.0.1 -u uu dbname -p reading table info completion of table , column names can turn off feature quicker startup -a ... blabla

i've checked table user well:

mariadb [mysql]> select user, host, password user; +------------------+----------------+--------------------+ | user | host | password | +------------------+----------------+--------------------+ | [skipping root ] | | uu | localhost | *c5e430fb96ff191af | | uu | 62.210.129.132 | *c5e430fb96ff191af | | uu | 62.% | *c5e430fb96ff191af | +------------------+----------------+--------------------+ 9 rows in set (0.00 sec) mariadb [mysql]>

so not working. i'm wondering whether comes ip policy or mysql server policy. here's iptables policy:

chain prerouting (policy take 1143 packets, 131k bytes) pkts bytes target prot opt in out source destination chain input (policy take 56 packets, 2938 bytes) pkts bytes target prot opt in out source destination chain output (policy take 236 packets, 17506 bytes) pkts bytes target prot opt in out source destination chain postrouting (policy take 236 packets, 17506 bytes) pkts bytes target prot opt in out source destination chain input (policy drop 0 packets, 0 bytes) pkts bytes target prot opt in out source destination 1 211 take -- * * 0.0.0.0/0 0.0.0.0/0 state related,established 0 0 take tcp -- eth0 * 62.210.129.132 0.0.0.0/0 0 0 take tcp -- eth0 * 0.0.0.0/0 0.0.0.0/0 tcp dpt:80 0 0 take tcp -- eth0 * 0.0.0.0/0 0.0.0.0/0 tcp dpt:443 0 0 take -- lo * 0.0.0.0/0 0.0.0.0/0 chain forwards (policy drop 0 packets, 0 bytes) pkts bytes target prot opt in out source destination chain output (policy take 3 packets, 852 bytes) pkts bytes target prot opt in out source destination

what missing, should look?

thanks this question, found solution. turned out had comment bind-address directive in my.cnf file:

#bind-address = 127.0.0.1

then works.

mysql connection

html - Targeting an element nested in two div classes -



html - Targeting an element nested in two div classes -

sometimes working wordpress can pain. im trying style menu generated wordpress.

here basic html

<div class="footer"> <!--generated wordpress--> <ul class="menu"> <li class="menu-item"> <a></a> <ul class="sub-menu"> <li class="menu-item"> <a></a> </li> </ul> </li> </ul> <!--end generated--> </div>

i want create css target <a> within sub menu, without messing <a> in main menu. cant mess other menus have set on site, must specific footer menu.

would proper method?

.footer .sub-menu { }

what proper method this?

actually right next ways appropriate:

1

.footer .sub-menu a{}

2

.footer ul.sub-menu a{}

3

ul.sub-menu a{}

html css wordpress

ruby on rails - Cannot require file in application.rb -



ruby on rails - Cannot require file in application.rb -

i'm trying simplify our configuration creating little configuration classes can included in our application.rb.

lib/logging.rb

class << logging def configure(config) # ... configure logging stuff end end

application.rb

require 'lib' module myapp class application < rails::application logging.configure(config) end end

the problem if don't utilize require "lib" undefined constant logging error. if seek require get:

bin/rails:6: warning: initialized constant app_path /opt/qtip/bin/rails:6: warning: previous definition of app_path here

the way i've been able work doing limiting.

config.autoload_paths = %w(lib) config.after_initialize ::logging.configure(config) end

you have wrong class declaration.

instead

class << logging

you should use

class logging class << self def configure(config) end end end

ruby-on-rails ruby

terminal - du command not giving accurate results -



terminal - du command not giving accurate results -

when seek utilize du command, see size of folders example:

du -h --max-depth=1 some-folder/

28m 11m 8.0k 4.2m 260k 896k 86m 7.9m 24k 8.6m 22m 14m 6.0m 60k 912k 365m total

,final size not shows real sum of above numbers. why summary size wrong?

the command you're executing shows folders only. hence files in some-folder added total not listed individually. seek this:

du -hs some-folder/*

but note if have hidden files (ie. files dot prefix) won't listed command either.

terminal command size folder du

javascript - Disabling tabs generated by Angular Strap (AngularJS) -



javascript - Disabling tabs generated by Angular Strap (AngularJS) -

i'm creating tabs in html page im using angularstrap library. want disable 1 of tab in it.

my code :

<div bs-tabs> <div data-title="general"> <!-- tab needs disabled --> </div> </div>

i tried using ng-show, ng-disabled , ng-if -- doesn't disabled.

any help appreciated.

this has been fixed in 2.1.3.

after upgrading, 'ng-if' should enough:

<div ng-model="tabs.activetab" bs-tabs=""> <div ng-repeat="tab in tabs" title="{{ tab.title }}" bs-pane="" ng-if="tab.show"> <div ng-include="tab.page"></div> </div> </div>

javascript angularjs angular-strap

SQL-SERVER: Properly using ISNULL to return default value -



SQL-SERVER: Properly using ISNULL to return default value -

i have multiple queries tied generating ranked list selecting top each. problem t4.area in final select nullable , may have homecoming null trying set default value of 'tbd'.

if break out query , run below, runs fine:

select isnull(max(area),'tbd') mdc mdccte3 row = 5

but including in main query next returns no results:

select t1.area growth, t2.area efficiency, t3.area risk, isnull(t4.area,'tbd') mdc gcte3 t1, ecte3 t2, rcte3 t3, mdccte3 t4 t1.row = 1 , t2.row = 1 , t3.row = 1 , t4.row = 5 grouping t1.area, t2.area, t3.area, t4.area

declare @mainhospital varchar(50)='hospital1'; --growth area rank gcte ( select 4 score, growth1 area survey mainhospital = @mainhospital union select 3 score, growth2 area survey mainhospital = @mainhospital union select 2 score, growth3 area survey mainhospital = @mainhospital union select 1 score, growth4 area survey mainhospital = @mainhospital union select 0 score, growth5 area survey mainhospital = @mainhospital ), gcte2 ( select area, sum(score) score gcte grouping area having area not null ), gcte3 ( select area, score, row_number() on (order score desc) row, rank() on (order score desc) rank gcte2 ), --efficiency area rank ecte ( select 4 score, efficiency1 area survey mainhospital = @mainhospital union select 3 score, efficiency2 area survey mainhospital = @mainhospital union select 2 score, efficiency3 area survey mainhospital = @mainhospital union select 1 score, efficiency4 area survey mainhospital = @mainhospital union select 0 score, efficiency5 area survey mainhospital = @mainhospital ), ecte2 ( select area, sum(score) score ecte grouping area having area not null ), ecte3 ( select area, score, row_number() on (order score desc) row, rank() on (order score desc) rank ecte2 ), --risk area rank rcte ( select 4 score, risk1 area survey mainhospital = @mainhospital union select 3 score, risk2 area survey mainhospital = @mainhospital union select 2 score, risk3 area survey mainhospital = @mainhospital union select 1 score, risk4 area survey mainhospital = @mainhospital union select 0 score, risk5 area survey mainhospital = @mainhospital ), rcte2 ( select area, sum(score) score rcte grouping area having area not null ), rcte3 ( select area, score, row_number() on (order score desc) row, rank() on (order score desc) rank rcte2 ), --all mdc's ger rank mdccte ( select 2 score, growthmdc1 area survey mainhospital = @mainhospital union select 1 score, growthmdc2 area survey mainhospital = @mainhospital union select 0 score, growthmdc3 area survey mainhospital = @mainhospital union select 2 score, efficiencymdc1 area survey mainhospital = @mainhospital union select 1 score, efficiencymdc2 area survey mainhospital = @mainhospital union select 0 score, efficiencymdc3 area survey mainhospital = @mainhospital union select 2 score, riskmdc1 area survey mainhospital = @mainhospital union select 1 score, riskmdc2 area survey mainhospital = @mainhospital union select 0 score, riskmdc3 area survey mainhospital = @mainhospital ), mdccte2 ( select area, sum(score) score mdccte grouping area having area not null ), mdccte3 ( select area, score, row_number() on (order score desc) row, rank() on (order score desc) rank mdccte2 ) select t1.area growth, t2.area efficiency, t3.area risk, isnull(t4.area,'tbd') mdc gcte3 t1, ecte3 t2, rcte3 t3, mdccte3 t4 t1.row = 1 , t2.row = 1 , t3.row = 1 , t4.row = 4 grouping t1.area, t2.area, t3.area, t4.area

group needs tbd well.

select t1.area growth, t2.area efficiency, t3.area risk, isnull(t4.area,'tbd') mdc gcte3 t1, ecte3 t2, rcte3 t3, mdccte3 t4 t1.row = 1 , t2.row = 1 , t3.row = 1 , (t4.row = 5 or t4.row null) grouping t1.area, t2.area, t3.area, isnull(t4.area,'tbd')

i don't way handling joins results in poor performance db has generate cartesian before filter, if don't have performance issues. shrug , wasn't part of question.

i think should bring together this... tables relate eachother?

select t1.area growth, t2.area efficiency, t3.area risk, isnull(t4.area,'tbd') mdc gcte3 t1, left bring together ecte3 t2 on t1.row = t2.row left bring together rcte3 t3 on t2.trow = t3.row left bring together mdccte3 t4 on t3.row = t4.row , t4.row = 5 t1.row = 1 grouping t1.area, t2.area, t3.area, isnull(t4.area,'tbd')

this may work need see sample info in t1, t2, t3 , t4 improve understand dilemma , expected results you're after.

as far why it works in single query not in group. single query returning max value , if 1 isn't found returning tbd row 5 doesn't have contend joins.

when you're joinging records each record first combined records of other table.

so if t1 has 10 records, t2 has 10 records, t3 has 10 records , t4 has 5... 10*10*10*5 rows generated 5000 database engine filters out ones t1.row <> 1 t2.row <> 2 , t3.row <> 1. filter out t4.row <> 5. there no row five. no records returned.

this why think left joins work improve homecoming records preceding table , match , nulls processed tbd t4.area.

but work tables have relate on something; , nil stated far indicates how relate.

sql-server

python - How to extend Django Group and still use in Django User -



python - How to extend Django Group and still use in Django User -

i looking extend functionality of django's group, can have properties on grouping such url group's homepage. this:

class organization(group): url = models.charfield(max_length=100)

however when using organization , adding user (by using org.user_set.add(user)) have no way of accessing url field user. when user.groups.all() shows user in grouping (not organization) same name set on organization org. how add together functionality grouping maintain accessible user info?

you have 2 option;

1) new model;

class groupprofile(models.model): grouping = models.onetoonefield('auth.group', unique=true) url = models.charfield(max_length=100)

2) monkey patch;

group.add_to_class('url', models.charfield(max_length=100))

in sec alternative have utilize app south db migration.

python django django-models user

java - LibGDX: Eclipse Import Gradle 'CreateProcess error = 5' -



java - LibGDX: Eclipse Import Gradle 'CreateProcess error = 5' -

while importing libgdx gradle project in eclipse next error 1 time "build model" button pressed:

image of screen improve reference: http://i.stack.imgur.com/pqoyj.png

title bar: "error in runnable 'creating gradle model'" content of error box: "createprocess error = 5, access denied"

any help appreciated, not find on error!

i figured out while ago, might still post reply in case encounters error - create sure have latest java version/jdk/sdk on scheme , eclipse using it!

java eclipse gradle libgdx project

Memory Leak in Sqlite3 database in Linux Qt -



Memory Leak in Sqlite3 database in Linux Qt -

i know question has been answered, still didn't right resolution of problem.

i developing application arm9 based microprocessor using ubuntu 12.10.

i have used sqlite3.8.3 info management.

i have experienced memory leak in database. have followed next cases.

case-1 - suppose memory leak done qsql driver`. have implemented next code simple insert method.

qsqlquery *query = new qsqlquery(sqlitecon); query->prepare("query inserting database"); if(query->exec()) { qstring retval = query->lastinsertid().tostring(); query->finish(); query->clear(); } delete query; sqlitecon.close();

but still not free memory. have tried utilize sqlite3 library straight through simple c code.

case-2 straight using sqlite3.8 library insert method.

code example

sqlite3 *db; rc = sqlite3_open("test.db", &db); if( rc ) { fprintf(stderr, "can't open database: %s\n", sqlite3_errmsg(db)); exit(0); } else { fprintf(stderr, "opened database successfully\n"); } sprintf("query insert"); rc = sqlite3_exec(db, sqlquery, callback, 0, &zerrmsg); if( rc != sqlite_ok ) { fprintf(stderr, "sql error: %s\n", zerrmsg); } else { fprintf(stdout, "records created successfully\n"); } sqlite3_free(zerrmsg); sqlite3_close(db);

it still not free memory.

what ? there options of sqlite_enable_memory_management , cache_size . should utilize options ? if yes how can compile sqlite using these options ?

thanks in advance.

qt memory-management memory-leaks sqlite3 arm

java - RESTful web applications using WAN IP instead of localhost -



java - RESTful web applications using WAN IP instead of localhost -

i developing web application in java using restful web services , tomcat. far using localhost in uri: http://localhost:8080/3.serverapi/rest/variable. if want utilize real ip?

i have tried on local network replacing localhost lan ip , works fine: http://192.168.1.2:8080/3.serverapi/rest/variable application @ address received variable.

if want send through net long know have utilize wan ip: http://188.39.25.247:8080/3.serverapi/rest/variable

my question is, if utilize lastly uri wan ip need port forwards lan ip configuring router or going work when used lan ip ??

thanks in advance

it depends on network setup really.

you may have enable port forwarding on router direct request machine server on, create sure router allows connections port 8080.

i had when working callbacks on external apis. seem remember had enable port forwarding on router work. wasn't hard though, check router instructions on how - say, depends on network setup though.

hope helps.

java rest tomcat networking ip

Playframework Accept version routing -



Playframework Accept version routing -

i trying implement rest versioning in play 2.2.

i expect client send next in header:

accept: application/vnd.helloworld+json; version=1

and based on version header, server phone call matching controller action. plan snapshot finish controller bundle each version of api.

something this:

com.helloworld.v1.controllers com.helloworld.v2.controllers

for example:

post /users/login { "email": "foo@gmail.com", "password": "bar" }

i direct request next controller:

com.helloworld.v1.controllers.usercontroller

how can cleanly accomplish in global.onrouterequest?

after thinking awhile i'm having hard time imagining working way describe without using runtime reflection phone call package/classes version. i'd weary of doing way, api versions may have different parameters, create types incompatible.

here's way defining default api uri in routes, uri each version. in onrouterequest can re-route incoming request different uri, (without using redirect) , remain unknown user other uris exist. note query parameters needed allow them pass through default url (if types going changing, don't think there's way).

routes:

get /api controllers.application.index /v1/api controllers.v1.test.index(test: int ?= 0) /v2/api controllers.v2.test.index(test: string ?= "")

in globalsettings object:

override def onrouterequest(request: requestheader): option[handler] = { // strip version headers val regex = "version=(\\d+)".r val version: option[int] = request.headers.get("accept").flatmap(x => regex.findfirstmatchin(x).map(_.group(1).toint)) // re-create version uri (if found) in new requestheader (if found), , re-route val req: requestheader = version.map(v => request.copy( uri = "/v" + v.tostring + request.uri, path = "/v" + v.tostring + request.path ) ).getorelse(request) super.onrouterequest(req) }

the part of solution consider unclean necessity enumerated routes, hard overcome considering code gymnastics reverse routes compiler does.

playframework playframework-2.2

java - How to get percentage of how much do two body overlap? -



java - How to get percentage of how much do two body overlap? -

i new in libgdx , want know how can percentage of how much 2 bodies overlap. know need utilize contact listener what? using libgdx in java not c++. there way of getting size of surface of bodies , maybe comparing them somehow? appreciate kind of help. :)

for example.. let´s have 2 bodies (squares) named b1 , b2. 1 of them set sensor can go through each other. , want console prints out percentage of how much overlap when x coordinate same.

for 2 polygons, utilize polygon clipping algorithm find overlapping region. there examples in many languages here: http://rosettacode.org/wiki/sutherland-hodgman_polygon_clipping

for 2 circles it's much easier, should able find how quick google search, eg. http://mathworld.wolfram.com/circle-circleintersection.html

for circle , polygon, i'm not aware of easy or convenient method.

java libgdx box2d

Mysql UNION with dynamic query -



Mysql UNION with dynamic query -

i have next problem. inherited software uses database prefix every customer. tables have same construction , columns. info migration new version want union these tables , set client foreign key instead , rid of subtables. i'm looking way create view task because want remain backwards compatible now. found dynamic query seems want can't execute on mysql server. assume written sql server.

the table name construction (about 80 client tables): customer1_faxe customer2_faxe customer3_faxe customer4_faxe ...

how approach problem?

declare @selectclause varchar(100) = 'select *' ,@query varchar(1000) = '' select @query = @query + @selectclause + ' ' + table_name + ' union ' information_schema.tables table_name '%_faxe' select @query = left(@query, len(@query) - len(' union ')) exec (@query)

this query using sql server syntax. need this:

declare @selectclause varchar(8000); declare @query varchar(8000); set @selectclause = 'select *'; select @query := group_concat(@selectclause, ' ', table_name separator ' union ') information_schema.tables table_name '%_faxe'; prepare stmt @query; execute stmt;

note group_concat() separator simplifies logic.

mysql dynamic union

php - How to make a dropDownList in Yii? -



php - How to make a dropDownList in Yii? -

i have 2 attributes in model jobs, tag , category, want create dropdownlist display value of tag have category equal 'salary', here code:

$s= chtml::listdata($model2, 'salary', 'tag'); echo chtml::dropdownlist('salary', 'salary', $s);

my db:

tag / category

1 / val1

2 / val1

a / val2

1000 / salary

2000 / salary

but got dropdownlist contains lastly value have these conditions. wrong in code?

there 2 reasons why can 1 results, firstly number of results in $model2 affects results, check if using findall homecoming rows matching status , not find , findbypk homecoming 1 value,

secondly sec attribute of listdata should value field 'salary' not attribute of model, has valuefield(see this).

it remain same if assigned salary - constant value alternative elements, meaning array overwritten each reach leaving array of 1 element containing lastly value.

you should 'tag_id'/'id' or sort of primary key model or tag value( assuming unique) identify tag by

$model2 = mymodel::model()->findall("category = salary"); $s= chtml::listdata($model2, 'tag', 'tag'); echo chtml::dropdownlist('salary', 'salary', $s,array('empty'=>'--select--'));

php yii yii-chtml

python 3.x - Updating Label text after OptionMenu selection changes -



python 3.x - Updating Label text after OptionMenu selection changes -

my objective update contents of label price, every time new item in alternative menu w selected. code far, returning errors not sure how fix.

class app(frame): def __init__(self, master=none): frame.__init__(self, master) label(master, text="ore:").grid(row=0) label(master, text="price:").grid(row=1) self.price = label(master, text="0.00").grid(row=1, column=1) variable = stringvar(master) variable.set("select ore") # default value def displayprice(self): self.price = oreprice[self.w.get()] self.w = optionmenu(master, variable, *oreprice, command=displayprice).grid(row=0, column=1) # here application variable self.contents = stringvar() # set value self.contents.set("this variable") # tell entry widget watch variable #self.w.bind('<button-1>', )

you can assume that:

oreprice = {'gold': 300, 'silver': 50, 'bronze': 10} # etc... can add together more if sense it.

i'm newbie @ python gui, hence messy and/or badly written code.

i ammended code. whenever alter ore type, cost field updated:

from tkinter import * class app(frame): def __init__(self, master=none): frame.__init__(self, master) label(master, text="ore:").grid(row=0) label(master, text="price:").grid(row=1) self.pricevar = stringvar() self.pricevar.set("0.00") self.price = label(master, textvariable=self.pricevar).grid(row=1, column=1) self.oreprice = {'gold': 300, 'silver': 50, 'bronze': 10} variable = stringvar(master) variable.set("select ore") # default value self.w = optionmenu(master, variable, *self.oreprice, command=self.displayprice).grid(row=0, column=1) # here application variable self.contents = stringvar() # set value self.contents.set("this variable") # tell entry widget watch variable #self.w.bind('<button-1>', ) def displayprice(self, value): self.pricevar.set(self.oreprice[value]) root = tk() app = app(root) root.mainloop()

python-3.x tkinter

objective c - NSTextStorage paragraph numbering -



objective c - NSTextStorage paragraph numbering -

is possible paragraph number nstextstorage? has property called paragraphs nsarray, it's not clear how deal individual objects in array.

i looking way number each paragraph in storage, find out in 1 changes made.

i thinking mark paragraphs ranges problem if add together or delete characters in 1 paragraph, ranges of next paragraphs became invalid (they change).

ideally great if find solution paragraph number via range, wouldn't necessary iterate each paragraph. here's code getting range of edited paragraph:

let paragraphrange = textstorage.string.bridgetoobjectivec().paragraphrangeforrange(editedrange)

but how can utilize find out exact number of paragraph in array? can't compare strings because user can type 2 or more identical strings.

update: thought came using whole bunch of nstextviews, each single paragraph. have no thought how else track changes in particular paragraph. thing concerns me if document have, let's say, 1000 pages or more, can hope such construction of nstextview series won't slow downwards runtime?

so far, best thought came this:

var attributes = [nsfontattributename: defaultfont] nsmutabledictionary attributes.setobject(nsuuid().uuidstring, forkey: "identifier") textview.typingattributes = attributes

that is, add together new key in attributes dictionary, name "identifier" , assign unique string. each paragraph have unique identifier.

when user edits text, can grab running attributes of text storage , iterate through array of paragraphs matching "identifier" key.

objective-c cocoa swift nstextstorage

angularjs - angularFireAuth does not work with google -



angularjs - angularFireAuth does not work with google -

i seek utilize firebase angularjs authenticate users. works fine except google. (classic, facebook , twitter works great).

this sample of code :

i seek understand problem displaying error in console :

angularfireauth.login(provider, { email: useremail, password: userpassword }).then(function(user) { //success }, function(error) { //error console.error('login failed: ', error); });

the error object contains message: "invalid jwt"

i searched web did not find explanation error.

one of enlighten me?

in advance, give thanks you.

assuming ok google app , angularfireauth is:

$scope.angularfireauth = $firebasesimplelogin(<your_firebase_ref>);

(you read more angularjs login on here)

you should seek this:

$scope.angularfireauth.$login(provider) // code missing '$' before login. .then(function(user) { //success }, function(error) { //error console.error('login failed: ', error); });

you don't need utilize email nor password due you're trying log in google not email

i hope helps you.

angularjs firebase angularfire

ios - Enable dragging for only one uitableviewcell -



ios - Enable dragging for only one uitableviewcell -

i've got uitableviewcontroller has custom uitableviewcell. cell has got uiscrollview, , on dragging shows hidden buttons.

everything works perfectly, disables uitableview scroll while dragging, unfortunately can't disable multi-dragging (if utilize 2 or more fingers on more cells drags these cells).

i solved assigning tag every scroll view , adding 2 functions which:

1 function: disable scrolling of every scroll id different 1 scrolling.

code:

func disablescrolling(tag:int){ var = 0; < count cells; ++i{ if(i != tag){ var scroll:uiscrollview? = self.view.viewwithtag(i) as? uiscrollview scroll!.scrollenabled =false } } }

in other function enables scrolling of every uiscrollview.

then phone call these functions in uiscrollview delegate methods

ios objective-c uitableview swift

How do I start reading a file from the top in python? -



How do I start reading a file from the top in python? -

i trying add together dependencies list requirements.txt file depending on platform software going run. wrote next code:

if platform.system() == 'windows': # add together windows requirements platform_specific_req = [req1, req2] elif platform.system() == 'linux': # add together linux requirements platform_specific_req = [req3] open('requirements.txt', 'a+') file_handler: requirement in platform_specific_req: already_in_file = false # create sure requirement not in file line in file_handler.readlines(): line = line.rstrip() # remove '\n' @ end of line if line == requirement: already_in_file = true break if not already_in_file: file_handler.write('{0}\n'.format(requirement)) file_handler.close()

but happening code when sec requirement going searched in list of requirements in file, for line in file_handler.readlines(): seems pointing lastly element of list in file new requirement compared lastly element in list, , if not same 1 gets added. causing several elements duplicated in list, since first requirement beingness compared against elements in list. how can tell python start comparing top of file again?

solution: received many great responses, learned lot, guys. ended combining 2 solutions; 1 antti haapala , 1 matthew franglen one. showing final code here reference:

# append requirements requirements.txt file open('requirements.txt', 'r') file_in: reqs_in_file = set([line.rstrip() line in file_in]) missing_reqs = set(platform_specific_reqs).difference(reqs_in_file) open('requirements.txt', 'a') file_out: req in missing_reqs: file_out.write('{0}\n'.format(req))

you open file handle before iterating on existing requirement list. read entire file handle each requirement.

the file handle finish after first requirement because have not reopened it. reopening file each iteration wasteful - read file list , utilize within loops. or set comparison!

file_content = set([line.rstrip() line in file_handler]) only_in_platform = set(platform_specific_req).difference(file_content)

python

android - GL_OES_texture_float not supported on OpenGL ES 3.0 device in a 2.0 context? -



android - GL_OES_texture_float not supported on OpenGL ES 3.0 device in a 2.0 context? -

i've got opengl es 2.0 app depends on gl_oes_texture_float extension. pretty much every device in past 3 years has it, that's not problem.

however, using galaxy s5 adreno 330 gpu, i've got problem. adreno 330 supports opengl es 3.0, includes float texture back upwards natively, no extension required. , indeed, grabbing extension strings opengl on device not study gl_oes_texture_float valid extension.

but when using opengl es 2.0 context on device, usages of float textures fail bind, though has capability since gpu supports 3.0. appears it's not working because i'm in 2.0 context, , no longer study extension.

has else run scenario this?

android opengl-es android-ndk opengl-es-2.0 opengl-es-3.0

Wistia Javascript API - conversion event to redirect to a confirmation page -



Wistia Javascript API - conversion event to redirect to a confirmation page -

i'm using wistia's turnstile capture e-mail in end of video. problem redirect page after user clicks submit. message have request check e-mail confirm double opt-in.

i have tried using 2 embed types no sucess.

iframe:

<iframe src="//fast.wistia.net/embed/iframe/7zu6ze7v40?videofoam=true" allowtransparency="true" frameborder="0" scrolling="yes" class="wistia_embed" name="wistia_embed" allowfullscreen mozallowfullscreen webkitallowfullscreen oallowfullscreen msallowfullscreen id="my_wistia_video"></iframe> <script src="//fast.wistia.net/assets/external/iframe-api-v1.js"></script> <script> wistiaembed = document.getelementbyid("my_wistia_video").wistiaapi; wistiaembed.bind("conversion", function(type, val) { window.location.href == "http://the_page"; }); </script>

api:

<div id="wistia_7zu6ze7v40" class="wistia_embed" style="width:640px;height:508px;">&nbsp;</div> <script charset="iso-8859-1" src="//fast.wistia.com/assets/external/e-v1.js"></script> <script> wistiaembed = wistia.embed("7zu6ze7v40", { videofoam: true }); wistiaembed.bind("conversion", function(type, val) { window.location.href == "http://the_page"; }); </script>

any hints or advices?

looks you're using comparing operator (a boolean operator) there ==, , you'll want utilize single = in place set window.location.href in example. if you're curious more on comparing operators, check this w3 page.

anyhow, i'd recommend embed:

<div id="wistia_7zu6ze7v40" class="wistia_embed" style="width:640px;height:508px;">&nbsp;</div> <script charset="iso-8859-1" src="//fast.wistia.com/assets/external/e-v1.js"></script> <script> wistiaembed = wistia.embed("7zu6ze7v40", { videofoam: true }); wistiaembed.bind("conversion", function(type, val) { window.location.href = "http://the_page"; }); </script>

javascript wistia

java - Jaxb Enums with subtype -



java - Jaxb Enums with subtype -

i have country enum.

@xmlenum public enum country { ....,es,fr,....; }

country used in product:

public class product { ... @xmlelement(name = "country") private list<country> origin; ... }

the produced output is:

<product> <name>egestas</name> <description>montes</description> <country>es</country> <country>fr</country> </product>

the problem need produce kind of output.

<product> <name>egestas</name> <description>montes</description> <country> <id>es</id> </country> <country> <id>fr</id> </country> </product>

how can produce later output enums without using adapter?

a

class country { private countryid id; //... }

with

enum countryid { ..., es, fr,... }

should produce xml requested.

later

of course, requires more code create element 1 additional layer.

product p = ...; country es = new country(); es.setid( countryid.es ); p.getcountry().add( es );

java enums jaxb

proxy server test in c# -



proxy server test in c# -

i making web request using proxy

httpwebrequest wr = (httpwebrequest)webrequest.create(inputurl); webproxy proxy = new webproxy(101.1.1.1,80); wr.headers.set(httprequestheader.acceptlanguage, "en-us"); wr.timeout = 100000; wr.method = "get"; wr.contenttype = "text/html;charset=utf-8";

when in fiddler, not see proxy information. how can create sure proxy beingness used correctly?

thanks

string proxyip = "61.135.178.114"; int proxyport = 80; var req = (httpwebrequest)httpwebrequest.create("http://ip-api.com/json"); req.proxy = new webproxy(proxyip, proxyport); var resp = req.getresponse(); var json = new streamreader(resp.getresponsestream()).readtoend(); var myip = (string)jobject.parse(json)["query"]; if (myip == proxyip) { messagebox.show("ok..."); }

you need json.net library run code

c# proxy

random - How to call the API key randomly in PHP and send to json -



random - How to call the API key randomly in PHP and send to json -

please help, have 10 api keys , want phone call random "api key":

this code: $keyword = str_replace(' ', '+' , get_the_title()); $api = api1 , api2 , api3 $jsonfile='domain.com/get.php?q='.$keyword.'&key='.$api.'&format=json'; $data = json_decode(file_get_contents($jsonfile));

but... how select random api? thanks.

use rand() function:

$api_keys = array('key1','key2','key3','key4','key5','key6','key7','key8','key9','key10'); $randkey = rand(0,10); $jsonfile='domain.com/get.php?q='.$keyword.'&key='.$api_keys[$randkey].'&format=json';

php random

PHP codesniffer scan whole directory not working -



PHP codesniffer scan whole directory not working -

i want scan entire project using phpcs (codesniffer) , problem here when trying scan phpcs in current directory scans php files not sub directories. help appreciated. i've tried

phpcs --report-file=/path/file/ subdirectories1 subdirectories2 ...

but 1 time again scans php files.

php

sql - Deleting rows in datastore by time range -



sql - Deleting rows in datastore by time range -

i have ckan datastore column named "recvtime" of type timestamp (i.e. using "timestamp" type @ datastore_create time, as shown in link). illustration value column "2014-06-12t16:08:39.542000".

i have big numbers of records in datastore (thousands) , delete rows before given date in "recvtime". first thought doing using rest api datastore_delete operation using range filter, not possible described in next q&a.

is there other way of solving issue, please?

given have access host ckan server running, wonder if achieved executing regular sql sentence on postgresql engine datastore persisted. however, haven't found info manipulating ckan underlying datamodel in ckan documentation, don't know if thought or if risky...

any workaround or info pointer highly welcome. thanks!

you straight on underlying database if willing dig in there (the construction pretty simple tables named after corresponding resource id). turn api of own using extension (though you'd want careful permissions).

you might interested in new back upwards (master atm) extending datastore api via plugin in extension - see https://github.com/ckan/ckan/pull/1725

sql postgresql ckan

c# - How to save/restore serializable object to/from file? -



c# - How to save/restore serializable object to/from file? -

i have list of objects , need save somewhere in computer. have read forums , know object has serializable. nice if can example. illustration if have following:

[serializable] public class someclass { public string someproperty { get; set; } } someclass object1 = new someclass { someproperty = "somestring" };

but how can store object1 somewhere in computer , later retrieve?

you can utilize following:

/// <summary> /// serializes object. /// </summary> /// <typeparam name="t"></typeparam> /// <param name="serializableobject"></param> /// <param name="filename"></param> public void serializeobject<t>(t serializableobject, string filename) { if (serializableobject == null) { return; } seek { xmldocument xmldocument = new xmldocument(); xmlserializer serializer = new xmlserializer(serializableobject.gettype()); using (memorystream stream = new memorystream()) { serializer.serialize(stream, serializableobject); stream.position = 0; xmldocument.load(stream); xmldocument.save(filename); stream.close(); } } grab (exception ex) { //log exception here } } /// <summary> /// deserializes xml file object list /// </summary> /// <typeparam name="t"></typeparam> /// <param name="filename"></param> /// <returns></returns> public t deserializeobject<t>(string filename) { if (string.isnullorempty(filename)) { homecoming default(t); } t objectout = default(t); seek { xmldocument xmldocument = new xmldocument(); xmldocument.load(filename); string xmlstring = xmldocument.outerxml; using (stringreader read = new stringreader(xmlstring)) { type outtype = typeof(t); xmlserializer serializer = new xmlserializer(outtype); using (xmlreader reader = new xmltextreader(read)) { objectout = (t)serializer.deserialize(reader); reader.close(); } read.close(); } } grab (exception ex) { //log exception here } homecoming objectout; }

c# serialization stream

ruby on rails - Confirmation token is invalid -



ruby on rails - Confirmation token is invalid -

i using devise 3.2.2. , turned on confirmable.

with sql, shows successful token created in users table.

and token in email link that's generated. clicking on it, gives confirmation token invalid error. having working code allow login using username or email, hope not conflicting.

erb:

<p>welcome <%= @email %>!</p> <p>you can confirm business relationship email through link below:</p> <p><%= link_to 'confirm account', confirmation_url(@resource, :confirmation_token => @resource.confirmation_token) %></p>

user model:

class user < activerecord::base # include default devise modules. others available are: # :confirmable, :lockable, :timeoutable , :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable # virtual attribute authenticating either username or email # in add-on real persisted field 'username' attr_accessor :login # setup accessible (or protected) attributes model attr_accessible :email, :password, :password_confirmation, :remember_me, :approved, :role, :username, :userfriendlyname, :persona, :public, :login, :active, :confirmation_token, :confirmed_at, :confirmation_sent_at # attr_accessible :title, :body # mtm 06/21/2014 allow login username or email def self.find_for_database_authentication(warden_conditions) conditions = warden_conditions.dup if login = conditions.delete(:login) where(conditions).where(["lower(username) = :value or lower(email) = :value", { :value => login.downcase }]).first else where(conditions).first end end # mtm 06/23/2014 allow login username or email def self.find_first_by_auth_conditions(warden_conditions) conditions = warden_conditions.dup if login = conditions.delete(:login) where(conditions).where(["lower(username) = :value or lower(email) = :value", { :value => login.downcase }]).first else where(conditions).first end end end

first, read through lot of other similar questions on so, , 1 helped @ to the lowest degree understand flow, since user in similar bind. devise confirmation resend "login can't blank" error & confirmation link email has "confirmation token invalid" error

but got solution work next things.

step 1.

confirmation_instructions.html.erb created when using pre devise 3.1.x version, link_to code had changed. there many articles in on this.

essentially, replacing :confirmation_token => @resource.confirmation_token :confirmation_token => @token.

step 2.

this tricky part. had created custom mailer before working fine, , there had re-create on devise actions custom mailer. again, maybe because using older version of devise @ time, there no mention of @token in these actions, added @token = token, in confirmation_instructions action/method, since token passed action/method parameter.

def confirmation_instructions(record, token, opts={}) @token = token devise_mail(record, :confirmation_instructions) end

by doing so, , looking @ rails console submitted resend of confirmation instructions request, see other articles talking regarding typical devise 3.1 , higher behavior, is, confirmation_token created , stored in database, not same value sent confirmation instructions email, seems encrypted version. when click on email link, went login page , said confirmation successful.

ruby-on-rails

c++ - How to remove this space(margin) from a QWidget form -



c++ - How to remove this space(margin) from a QWidget form -

i have qwidget form, have added qtextedit on form, there space(margin) in top.

i tried utilize following:

qwidget *widget = new qwidget(this); widget->layout()->setcontentsmargins(0,0,0,0);

but unfortunately, did not want.

how remove space(margin) left, right , down side ?

full code

qwidget *widget = new qwidget(this); qtextedit *textedit = new qtextedit(widget); qmdisubwindow *mdiwindows = ui->mdiarea->addsubwindow(widget); mdiwindows->setgeometry(5, 5, 300, 250); mdiwindows->setwindowtitle(finfo.basename()); mdiwindows->setwindowstate(qt::windowmaximized); mdiwindows->layout()->addwidget(textedit); mdiwindows->layout()->setcontentsmargins(0,0,0,0); textedit->settext(cache); widget->setmaximumheight(0); mdiwindows->show();

try addding

widget->layout()->setspacing(0);

c++ qt margin qt5

css - image not fit the screen -



css - image not fit the screen -

in ruby on rails web application, have image consists of 2 colours first portion black , sec portion blue. when set image on background, image repeating:

body { background:url("bg.png"); }

but when utilize below repeatation of image remove:

body { background:url("bg.png") 0 0 repeat-x; }

but vertically not fit screen,

it covers 2/3rd portion of screen. , black portion fit bluish portion not cover remaining screen , want increment bluish portion of image not black, possible.

kindly suggest me, waiting reply. thanks.

different elements

using background images art

i recommend using 2 elements - "nav" element & set background of body bluish gradient. can utilize background-size: cover property create work:

http://jsfiddle.net/wm2b7/

#app/assets/stylesheets/application.css.scss body { background: url("gradient.png"); background-size: cover; } nav { height: 45px; display: block; background: url("black.png") 0 0 repeat-x; }

this allow give illusion of having single background image, whilst maintaining flexibility of having multiple elements (i.e body styling deed body, nav styling deed nav)

css ruby-on-rails

android pay - Use Google wallet with braintree payment gateway -



android pay - Use Google wallet with braintree payment gateway -

i want know, can utilize google wallet braintree payment gateway in android application. more technical clear, take maskedwallet google wallet , fetch useful info , send braintree payment gateway completing purchase.

please help.

i'm couple of days working on same, devoid of technical specifics (more conceptual). i'm doing on "web" side of wallet instant buy (not android), though concept of sending payment details through, , meeting (pci) requirements, (any) credit card payment gateway should same.

unless i'm corrected googler:

you'll need create fullwalletrequest obtain "full wallet" means actual card details need send gateway (card no, cvc/cvv, expiration, billing address etc.).

at point, wouldn't differ other/existing (gateway type) credit card processing.

at end of day, google wallet instant purchase does:

provide merchant application (droid/ios/web) "virtual onetime card", which,

represents google wallet user's real card stored in his/her google wallet account, hence securing actual card details , scoping transaction (because it's one-time)

i think possible caveat whether or not gateway accepts such type of of card (" mastercard-branded virtual prepaid debit card")..unlikely issue (in us, api limited @ time...)....

digressing bit. other caveat comes mind if employ fraud screening service. you're given "virtual card" (not real card of cardholder), if service uses/needs info come risk score, need business relationship for...

hth....

android-pay braintree

How do I display data retrieved from mysql db in a specific order using php -



How do I display data retrieved from mysql db in a specific order using php -

i trying display questions, along users reply in specific order, not asc or desc, defined "question_order" column.

i have next tables in mysql db:

questions (qid, question_text) answers (aid, uid, answer) usermeta (userid, question_order) "questions" table contains questions "answers" table contains every users answers questions "usermeta" table contains sort order questions in "question_order".

"question_order" unique per user , in db pipe delimited list. (i.e.: 85|41|58|67|21|8|91|62,etc.)

php version 5.3.27

if entire procedure can improve accomplished using different method, please allow me know.

my php ability limited. said, below have @ moment after several hours of playing ...

$sql = " select * ".usermeta_table." userid = {$userid} "; $result = $db->query($sql) or sql_error($db->error.'<br />'.$sql); $row = $result->fetch_assoc(); $order_array = explode('|', $row['question_order']); $sql = " select * ".questions_table." "; $result = $db->query($sql) or sql_error($db->error.'<br />'.$sql); $row = $result->fetch_assoc(); // effort @ sorting questions. $order_array // not have unique id kind of lost // how create work usort($myarray, function($order_array, $row) { homecoming $order_array - $row['qid']; }); $sql = " select * ".questions_table." "; $result = $db->query($sql) or sql_error($db->error.'<br />'.$sql); while ( $row = $result->fetch_assoc() ) { $sql = " select * ".answers_table." uid = {$userid} , qid = ".$row['qid']." limit 1 "; $result2 = $db->query($sql) or sql_error($db->error.'<br />'.$sql); $row2 = $result2->fetch_assoc(); echo ' <p>'.$row['question_text'].'</p>'."\n"; echo ' <p>'.$row2['answer'].'</p>'."\n"; }

filter out info when retrieving db.

use:- select * [table_name] order qid desc

then in php can utilize session variables , modify values accordingly.

php mysql arrays usort

html - DIV won't align to center -



html - DIV won't align to center -

i have problem centering div element. tried marings (margin: o auto) , left/right css atributes (left: 50%, right: 50%) result wrong. can tell me where's problem?

edit:

i using javascript fill content of "boxcard" div. problem content of "boxcard" div not aligned center (it's aligned left). using javascript code (added below) fill div's content.

this have:

edit 2:

here jsfiddle : jsfiddle

css:

* { margin: 0; padding: 0; } body { font: 18px verdana; color: #fff; background: #ccc; } #picbox { margin: 0px auto; width: auto; } #boxcard { z-index: 1; margin: 0px auto; width: auto; } #boxcard div{ float: left; width: 100; height: 120; margin: 5px; padding: 5px; border: 4px solid #ee872a; cursor: pointer; border-radius: 10px; box-shadow: 0 1px 5px rgba(0,0,0,.5); background: #b1b1b1; z-index: 2; } #boxcard > div:nth-child(6n+1) { clear: both; } #boxcard div img { display: none; border-radius: 10px; z-index: 3; } #boxbuttons { text-align: center; margin: 20px; display: block; } #boxbuttons .button { text-transform: uppercase; background: #ee872a; padding: 5px 10px; margin: 5px; border-radius: 10px; cursor: pointer; } #boxbuttons .button:hover { background: #999; }

html

<div id="picbox"> <span id="boxbuttons"> <span class="button" id="rezz"> result <span id="counter">0</span> </span> <span class="button" id="ttime"></span> <span class="button"> <a onclick="resetgame();">reset</a> </span> </span> <div id="boxcard" align="center"></div> </div>

this js code creates div blocks (i.e. cards)

function shuffleimages() { var imgall = $(source).children(); var imgthis = $(source + " div:first-child"); var imgarr = new array(); (var = 0; < imgall.length; i++) { imgarr[i] = $("#" + imgthis.attr("id") + " img").attr("src"); imgthis = imgthis.next(); } imgthis = $(source + " div:first-child"); (var z = 0; z < imgall.length; z++) { var randomnumber = randomfunction(0, imgarr.length - 1); $("#" + imgthis.attr("id") + " img").attr("src", imgarr[randomnumber]); imgarr.splice(randomnumber, 1); imgthis = imgthis.next(); } } $(function() { (var y = 1; y < 3 ; y++) { $.each(imgsource, function(i, val) { $(source).append("<div id=card" + y + + "><img src=" + val + " />"); }); } $(source + " div").click(opencard); shuffleimages(); });

you need add together display: table. how center element undefined width

demo http://jsfiddle.net/s7w3q/2/

#boxcard { z-index: 1; display: table; margin: 0px auto; width: auto; }

html css alignment

r - Compare consecutive rows in data.table and replace row values -



r - Compare consecutive rows in data.table and replace row values -

i have data.table in r contains multiple status values each user collected @ different time points. want compare the status values @ consecutive time points , update rows flag whenever status changes. please see below example

dt_a <- data.table(sid=c(1,1,2,2,2,3,3), date=as.date(c("2014-06-22","2014-06-23","2014-06-22","2014-06-23", "2014-06-24","2014-06-22","2014-06-23")), status1 = c("a","b","a","a","b","a","a"), status2 = c("c","c","c","c","d","d","e")) dt_a_final <- data.table(sid=c(1,1,2,2,2,3,3), date=as.date(c("2014-06-22","2014-06-23","2014-06-22","2014-06-23", "2014-06-24","2014-06-22","2014-06-23")), status1 = c("0","1","0","0","1","0","0"), status2 = c("0","0","0","0","1","0","1"))

the original info table dt_a is

sid date status1 status2 1 1 2014-06-22 c 2 1 2014-06-23 b c 3 2 2014-06-22 c 4 2 2014-06-23 c 5 2 2014-06-24 b d 6 3 2014-06-22 d 7 3 2014-06-23 e

the final required info table dt_a_final

sid date status1 status2 1 1 2014-06-22 0 0 2 1 2014-06-23 1 0 3 2 2014-06-22 0 0 4 2 2014-06-23 0 0 5 2 2014-06-24 1 1 6 3 2014-06-22 0 0 7 3 2014-06-23 0 1

please help how can accomplish this?

here option:

dt_a[, c("s1change", "s2change") := lapply(.sd, function(x) c(0, head(x, -1l) != tail(x, -1l))), .sdcols=c("status1", "status2"), # .sd contains these columns by=sid ]

here, create 2 new columns, populate lapply on .sd (defined contain status1 , status2). function compares first value of column lastly of same column. homecoming true time there alter in column. add together 0 @ origin since first value never change; coerces result numeric vector (thanks eddi).

then, by sid, , voila:

sid date status1 status2 s1change s2change 1: 1 2014-06-22 c 0 0 2: 1 2014-06-23 b c 1 0 3: 2 2014-06-22 c 0 0 4: 2 2014-06-23 c 0 0 5: 2 2014-06-24 b d 1 1 6: 3 2014-06-22 d 0 0 7: 3 2014-06-23 e 0 1

you can subset drop original status columns if want. isn't possible re-use them because info type of result different original (numeric vs. character).

r data.table

c# - Datepicker for MVC View -



c# - Datepicker for MVC View -

i using asp.net mvc razor , need implament datepicker in fields. maybe offer useful nuget bundle in mvc razor view? give thanks you.

you can utilize 1 :

install-package jquery.ui.widgets.datepicker

c# asp.net-mvc

wso2carbon - How to get UDDIPublisher permission for a user in wso2 to run JAXR sample -



wso2carbon - How to get UDDIPublisher permission for a user in wso2 to run JAXR sample -

i trying run jaxr sample in governance registry in wso2 deals uddi support.it before running should add together user uddipublisher permission scoutv3.properties file .i dont know username , password need add together file in order run sample.please help.

the role user belongs should have uddipublisher permission publish service uddi registry. hence should add together valid username , password in scoutv3.properties file (instead of root/root).

to tryout sample can utilize admin/admin userid , password. (admin has permissions)

wso2 wso2carbon

c# - Adding Torque To Character With FixedAngle 2D -



c# - Adding Torque To Character With FixedAngle 2D -

i've been stuck on lastly few days i'm hoping guys can help.

i'm making 2d game , want character slip, fall backwards, , nail head when tries run on water ice long. goal have if maintain holding run button long plenty on ice, slip backwards , harm himself. i'm using playmaker know little c# programming.

the first thing tried making animated float adds rotation z axis on time, went horribly wrong , makes character jump/skip/glitch on place.

the sec thing thought of add together 2d torque create him start slipping backwards, stays in same rotation fixedangle true.

so made fixedangle false when on ice, falls forwards or backwards start running. made center of mass right in middle stands fine long not moving.

does know way of achieving effect want? first game , noob, there easier/correct way of going this. doing wrong, guide in right direction appreciated.

it seems verbage, want tracking amount of time player has been running on ice.

if want tie run key beingness down, start timer if button downwards , trigger "slip-and-fall" event occur after amount of time.

if want tie amount of time player has been on ice, start timer when player reaches water ice , trigger "slip-and-fall" event occur after amount of time.

if want there visual tilting, tie time delta angle of object. set angle trigger "slip-and-fall" event.

update(){ if(this.running && _terrainatpos == <ice> && isgrounded){ transform.rotate(0,0,3*time.deltatime); if(tranform.rotation.z > 180){ //do falling event } } }

edit: above not working sample. whipped illustrate.

c# unity3d 2d game-physics

html - CSS linear gradient appears as alternate lines of different colors -



html - CSS linear gradient appears as alternate lines of different colors -

i trying linear gradient of 2 colours not working , instead showing me alternate lines of different colors seen in image

i using css

body{ background: linear-gradient(white, rgb(221,221,221));}

this finish jsfiddle

just add together height:768px; in css .

http://jsfiddle.net/arshidkv12/78cx3/1/

html css css3

c# - WP7 - How to get the list box items from ViewModel? -



c# - WP7 - How to get the list box items from ViewModel? -

i trying selected name list box when click list box button.

my xaml page:-

<listbox name="mylistbox" height="733" itemssource="{binding studentdetails,mode=twoway}" horizontalalignment="left" margin="0,35,0,0" verticalalignment="top" width="476"> <listbox.itemtemplate> <datatemplate> <border borderbrush="gray" padding="5" borderthickness="1"> <stackpanel orientation="horizontal"> <border borderbrush="wheat" borderthickness="1"> <image name="listpersonimage" source="{binding personimage}" height="100" width="100" stretch="uniform" margin="10,0,0,0"/> </border> <textblock text="{binding firstname}" name="firstname" width="200" foreground="white" margin="10,10,0,0" fontweight="semibold" fontsize="22" /> <textblock text="{binding lastname}" name="lastname" width="200" foreground="white" margin="-200,50,0,0" fontweight="semibold" fontsize="22" /> <textblock text="{binding age}" name="age" width="200" foreground="white" margin="10,10,0,0" fontweight="semibold" fontsize="22" /> <button command="{binding buttonclick}" datacontext="{binding datacontext, elementname=mylistbox}" margin="-200,0,0,0" height="80" width="80"> <button.background> <imagebrush stretch="fill" > <imagebrush.imagesource> <bitmapimage urisource="/newexample;component/images/icon_increase.png" /> </imagebrush.imagesource> </imagebrush> </button.background> </button> </stackpanel> </border> </datatemplate> </listbox.itemtemplate> </listbox>

xaml.cs:-

private void button_click(object sender, routedeventargs e) { button mybutton = sender button; listboxwithbuttonmodel dataobject = mybutton.datacontext listboxwithbuttonmodel; int index = mylistbox.items.indexof(dataobject); messagebox.show("button clicked" + dataobject.firstname); }

here can selected name when click button. same thing want view model. please help me selected name viewmodel.

i have seek this.

listbutton = new reactiveasynccommand(); listbutton.subscribe(x => { listboxwithbuttonmodel dataobject = listbutton.datacontext listboxwithbuttonmodel; //int index = mylistbox.items.indexof(dataobject); messagebox.show("button clicked" + dataobject.firstname); });

but here getting error datacontext not contain reactiveasyccommand. please help me solve problem.

my viewmodel:-

public reactiveasynccommand buttonclick { get; set; } public listboxwithbuttonviewmodel() { buttonclick = new reactiveasynccommand(); buttonclick.subscribe(x => { messagebox.show("test"); }); }

herer can show message box. how selected item here??

my try.

public relaycommand<listboxwithbuttonmodel> itemselectedcommand { get; private set; } public listboxwithbuttonviewmodel() { itemselectedcommand = new relaycommand<listboxwithbuttonmodel>(itemselected); } private void itemselected(listboxwithbuttonmodel myitem) { messagebox.show("testing"); if (null != myitem) messagebox.show("name==>" + myitem.firstname); }

here can not selected item. please give me thought resolve problem.

it isn't stated suspect problem myitem parameter null because never pass parameter in xaml.

use commandparameter property pass parameter command, illustration :

<button command="{binding datacontext.itemselectedcommand, elementname=mylistbox}" commandparameter="{binding}" margin="-200,0,0,0" height="80" width="80"> <button.background> <imagebrush stretch="fill" > <imagebrush.imagesource> <bitmapimage urisource="/newexample;component/images/icon_increase.png" /> </imagebrush.imagesource> </imagebrush> </button.background> </button>

c# xaml windows-phone-7 mvvm listbox

javascript - New value for cookie appended -



javascript - New value for cookie appended -

this javascript code

function writecookie(cookiename, cookievalue, cookieduration) { var expiration = new date(); var = new date(); expiration.settime(now.gettime() + (parseint(cookieduration) * 60000)); document.cookie = cookiename + '=' + escape(cookievalue) + '; expires=' + expiration.togmtstring() + '; path=/'; } function readcookie(cookiename) { if (document.cookie.length > 0) { var origin = document.cookie.indexof(cookiename + "="); if (beginning != -1) { origin = origin + cookiename.length + 1; var ending = document.cookie.indexof(";", beginning); if (ending == -1) ending = document.cookie.length; homecoming unescape(document.cookie.substring(beginning, ending)); } else { homecoming ""; } } homecoming ""; } var before = readcookie('totali'); var after = before + 1; writecookie('totali', after, 43200);

should read cookie 'totali', add together "1" value , rewrite new value. first time run code, cookie becomes "1", sec time becomes "11", 3rd "111" , on. problem?

you concatenating strings. convert value read cookie number before attempting add together it:

var after = parseint(before) + 1;

but problem first time read cookie, value empty string, , parseint("") nan. in case, have check before utilize it. assign 1 if function returns empty string, or value stored in cookie + 1 if not:

var after = (before.trim() == "") ? 1 : parseint(before) + 1;

this assumes never place other number in totali cookie.

see http://jsfiddle.net/9rlzp/3/ (i changed name of cookie, can see alter without having remove previous cookie)

javascript cookies

node.js - Differrent date in mongodb and nodejs -



node.js - Differrent date in mongodb and nodejs -

mongo's date differ scheme , nodejs date settings. how can prepare that?

mongo:

> new date() isodate("2014-06-23t08:53:45.585z") > exit bye

debian system:

root@vm85820:/var/node/mrandom.com# date mon jun 23 12:54:14 msk 2014

node:

root@vm85820:/var/node/mrandom.com# node > new date() mon jun 23 2014 12:54:24 gmt+0400 (msk)

they not different. mongodb time in utc, other 1 in msk timezone (+4 hours).

node.js mongodb date

javascript - Decrement scalar Perl variable everytime an ajax script is ran -



javascript - Decrement scalar Perl variable everytime an ajax script is ran -

on page there header notification button shows number of unarchived notifications given perl code:

@notices_posts = system::notice->fetch_all_posts(userid => $user->userid(), visible => 1); @regular_posts = sort { $a->created() cmp $b->created() } grep { !$_->important() } @notices_posts;

and displayed in header:

<b><%= (scalar @regular_posts) %></b>

i have ajax script:

$(document).on('click', '.archive-button', function(){ var notice_id = $(this).data('notice_id'); var archiveaddress = '/user/notices/archivenotice/' + notice_id; var archived_notice = 'tr.notification-' + notice_id; $.post(archiveaddress, {notice_id: notice_id}).done(function(){ $(archived_notice).css("background" , "#f2f2f2"); }); });

which runs everytime clicks "archive" button on notice. have notice becomes grayed out when perl script archiving run want update scalar number in header displaying number of unarchived notices everytime user archives something. decrement displayed value perchance everytime ajax script ran.

i'd give element id , utilize jquery set number.

<b id="incme"><%= (scalar @regular_posts) %></b> ... $(document).on('click', '.archive-button', function(){ var notice_id = $(this).data('notice_id'); var archiveaddress = '/user/notices/archivenotice/' + notice_id; var archived_notice = 'tr.notification-' + notice_id; $.post(archiveaddress, {notice_id: notice_id}).done(function(){ $(archived_notice).css("background" , "#f2f2f2"); $('#incme').html(parseint($('#incme').html(), 10)+1) }); });

reference: jquery increment value of <span> tag

javascript ajax perl

oracle adf - ADF Mobile: Invoke AMX Page to display on user screen using JavaScript -



oracle adf - ADF Mobile: Invoke AMX Page to display on user screen using JavaScript -

my question simple.

in adf mobile, have html page , there button on it. want run javascript code on button click , navigate amx page. how can accomplish functionality.

thank you!

in button properties in amx page click action listener , create bean , method

add below code in order execute zoomin js function

adfmfcontainerutilities.invokecontainerjavascriptfunction("com.mohamed.ios.feature1", "zoomin", new object[] { }); first parameter: feature id second parameter: javascript function name 3rd parameter: java script function parameters

if it's html page 1 time take button in property inspector under javascript find javascript events can use( if property inspector not visible click view -> property inspector).

you can add together js function in onclick event in js function can utilize below code go feature has amx page.

adf.mf.api.gotofeature("feature0", function(req, res) { alert("gotofeature complete"); }, function(req, res) { alert("gotofeature failed " + adf.mf.util.stringify(res); } );

make sure include js file in feature under content tab.

and in order navigate amx page button on amx page pass flowcase below method

public void donavigation(string flowcase) { adfmfcontainerutilities.invokecontainerjavascriptfunction(adfmfjavautilities.getfeaturename(), "adf.mf.api.amx.donavigation", new object[] { flowcase }); }

the donavigation method calling standard adfm js api called adf.mf.api.amx.donavigation , passes flowcase name it.

oracle-adf oracle-adf-mobile

Showing a search results page which has values from a multidimentional array in php -



Showing a search results page which has values from a multidimentional array in php -

i have array

array ( [availabletrips] => array ( [ac] => false [arrivaltime] => 1830 [availableseats] => 4 [boardingtimes] => array ( [bpid] => 460319 [bpname] => kalasipalyam [location] => kalasipalyam [prime] => false [time] => 1215 ) [bustype] => non a/c semisleeper (2+2) [bustypeid] => 110 [cancellationpolicy] => 0:8:100:0;8:24:50:0;24:-1:15:0 [departuretime] => 1215 [doj] => 2014-06-18t00:00:00+05:30 [droppingtimes] => array ( [bpid] => 559663 [bpname] => mananthavaadi [location] => mananthavaadi [prime] => false [time] => 390 ) [fares] => 650 [id] => 100102612640227182 [idproofrequired] => false [nonac] => true [operator] => 5127 [partialcancellationallowed] => false [routeid] => 100102600000227182 [seater] => true [sleeper] => false [travels] => sks travels [mticketenabled] => true ) )

which response api of bus ticket booking service.this search result of single bus got particular source , destination.for other source destination pairs,the result can like,if there more 1 bus on route.

array ( [availabletrips] => array ( [0] => array //1st bus in search result ( [ac] => true [arrivaltime] => 1845 [availableseats] => 28 [boardingtimes] => array ( [0] => array ( [bpid] => 46768 [bpname] => kalasipalyam main road [location] => kalasipalyam main road [prime] => false [time] => 1260 ) [1] => array ( [bpid] => 46774 [bpname] => christ university [location] => christ university [prime] => false [time] => 1280 ) [2] => array ( [bpid] => 46771 [bpname] => madiwala [location] => madiwala [prime] => true [time] => 1305 ) [3] => array ( [bpid] => 46776 [bpname] => electronic city toll gate [location] => electronic city toll gate [prime] => false [time] => 1330 ) [4] => array ( [bpid] => 46778 [bpname] => bommasandra post office [location] => bommasandra post office [prime] => false [time] => 1340 ) [5] => array ( [bpid] => 46779 [bpname] => attibele [location] => attibele [prime] => false [time] => 1350 ) [6] => array ( [bpid] => 46780 [bpname] => hosur [location] => hosur [prime] => false [time] => 1360 ) ) [bustype] => volvo multiaxle a/c seater semi sleeper (2+2) [bustypeid] => 101 [cancellationpolicy] => 0:12:100:0;12:-1:10:0 [departuretime] => 1305 [doj] => 2014-06-18t00:00:00+05:30 [droppingtimes] => array ( [0] => array ( [bpid] => 46886 [bpname] => edapally toll gate [location] => edapally toll gate [prime] => false [time] => 1825 ) [1] => array ( [bpid] => 46884 [bpname] => palarivattam [location] => palarivattam [prime] => false [time] => 1830 ) [2] => array ( [bpid] => 46882 [bpname] => vytla junction [location] => vytla junction [prime] => true [time] => 1845 ) [3] => array ( [bpid] => 46972 [bpname] => mg road [location] => mg road [prime] => false [time] => 1860 ) ) [fares] => 1000.00 [id] => 200855412640007772 [idproofrequired] => false [nonac] => false [operator] => 7478 [partialcancellationallowed] => true [routeid] => 200855400000007772 [seater] => true [sleeper] => false [travels] => shama transport [mticketenabled] => true ) [1] => array //2nd bus in search result ( [ac] => true [arrivaltime] => 1710 [availableseats] => 33 [boardingtimes] => array ( [0] => array ( [bpid] => 34106 [bpname] => kalasipalyam main road [location] => kalasipalyam main road [prime] => false [time] => 1080 ) [1] => array ( [bpid] => 34099 [bpname] => dairy circle [location] => dairy circle [prime] => false [time] => 1095 ) [2] => array ( [bpid] => 34098 [bpname] => christ university [location] => christ university [prime] => false [time] => 1100 ) [3] => array ( [bpid] => 34093 [bpname] => madiwala [location] => madiwala [prime] => true [time] => 1170 ) [4] => array ( [bpid] => 34103 [bpname] => electronic city toll gate [location] => electronic city toll gate [prime] => false [time] => 1185 ) [5] => array ( [bpid] => 34109 [bpname] => narayana hridayalaya [location] => narayana hridayalaya [prime] => false [time] => 1195 ) [6] => array ( [bpid] => 34095 [bpname] => attibele [location] => attibele [prime] => false [time] => 1200 ) [7] => array ( [bpid] => 34114 [bpname] => bommasandra post office [location] => bommasandra post office [prime] => false [time] => 1210 ) [8] => array ( [bpid] => 34112 [bpname] => hosur [location] => hosur [prime] => false [time] => 1215 ) ) [bustype] => volvo multiaxle a/c seater semi sleeper (2+2) [bustypeid] => 101 [cancellationpolicy] => 0:12:100:0;12:-1:10:0 [departuretime] => 1170 [doj] => 2014-06-18t00:00:00+05:30 [droppingtimes] => array ( [bpid] => 45746 [bpname] => vytala bye pass [location] => vyttila [prime] => true [time] => 1710 ) [fares] => 1100.00 [id] => 200855412640007290 [idproofrequired] => false [nonac] => false [operator] => 6708 [partialcancellationallowed] => true [routeid] => 200855400000007290 [seater] => true [sleeper] => false [travels] => atlas travels [mticketenabled] => true )

this goes on , on depending on number of results.

this part of code outputs results above.

$availablebuses = json_decode($availabletrips,true); echo "<pre>"; print_r($availablebuses); echo "</pre>";

now trying is,to loop , parse through array output results div like.

<h1>search results </h1> <div>bus name:<?php echo $ availablebuses['availabletrips']['travels'];?>boarding place:<?php echo $availablebuses['availabletrips']['boradingtimes']['location']</div>

the above like

**search results** bus name : sks travels boarding place : kalasipalyam

if there more results above repeated as

**search results** bus name : sks travels boarding place : kalasipalyam bus name : 1 travels boarding place : place 1 bus name : 2 travels boarding place : place 2 .......

im unable parse complex array properly

i have tried

$jsoniterator = new recursiveiteratoriterator( new recursivearrayiterator(json_decode($availabletrips, true)), recursiveiteratoriterator::self_first); foreach( $jsoniterator $output) { echo $output['travels']; echo $output['droppingtimes']['location']; }

but couldnt wanted.i want repeats div appropriate contents number of bus increase.

**i know can dumb questions around,but im finding hard through nor google did helped.if here help me of great help

thanks.

please excuse long question,didnt find way explain this.

given next array :

$availablebuses = array ( "availabletrips" => array ( "0" => array //1st bus in search result ( "ac" => "true", "arrivaltime" => "1845", "availableseats" => "28", "boardingtimes" => array ( "0" => array ( "bpid" => "46768", "bpname" => "kalasipalyam main road", "location" => "kalasipalyam main road", "prime" => "false", "time" => "1260" ), "1" => array ( "bpid" => "46774", "bpname" => "christ university", "location" => "christ university", "prime" => "false", "time" => "1280" ), "2" => array ( "bpid" => "46771", "bpname" => "madiwala", "location" => "madiwala", "prime" => "true", "time" => "1305" ), "3" => array ( "bpid" => "46776", "bpname" => "electronic city toll gate", "location" => "electronic city toll gate", "prime" => "false", "time" => "1330" ), "4" => array ( "bpid" => "46778", "bpname" => "bommasandra post office", "location" => "bommasandra post office", "prime" => "false", "time" => "1340" ), "5" => array ( "bpid" => "46779", "bpname" => "attibele", "location" => "attibele", "prime" => "false", "time" => "1350" ), "6" => array ( "bpid" => "46780", "bpname" => "hosur", "location" => "hosur", "prime" => "false", "time" => "1360" ), ), "bustype" => "volvo multiaxle a/c seater semi sleeper (2+2)", "bustypeid" => "101", "cancellationpolicy" => "0:12:100:0;12:-1:10:0", "departuretime" => "1305", "doj" => "2014-06-18t00:00:00+05:30", "droppingtimes" => array ( "0" => array ( "bpid" => "46886", "bpname" => "edapally toll gate", "location" => "edapally toll gate", "prime" => "false", "time" => "1825", ), "1" => array ( "bpid" => "46884", "bpname" => "palarivattam", "location" => "palarivattam", "prime" => "false", "time" => "1830" ), "2" => array ( "bpid" => "46882", "bpname" => "vytla junction", "location" => "vytla junction", "prime" => "true", "time" => "1845" ), "3" => array ( "bpid" => "46972", "bpname" => "mg road", "location" => "mg road", "prime" => "false", "time" => "1860" ) ), "fares" => "1000.00", "id" => "200855412640007772", "idproofrequired" => "false", "nonac" => "false", "operator" => "7478", "partialcancellationallowed" => "true", "routeid" => "200855400000007772", "seater" => "true", "sleeper" => "false", "travels" => "shama transport", "mticketenabled" => "true" ), "1" => array //2nd bus in search result ( "ac" => "true", "arrivaltime" => "1710", "availableseats" => "33", "boardingtimes" => array ( "0" => array ( "bpid" => "34106", "bpname" => "kalasipalyam main road", "location" => "kalasipalyam main road", "prime" => "false", "time" => "1080", ), "1" => array ( "bpid" => "34099", "bpname" => "dairy circle", "location" => "dairy circle", "prime" => "false", "time" => "1095" ), "2" => array ( "bpid" => "34098", "bpname" => "christ university", "location" => "christ university", "prime" => "false", "time" => "1100" ), "3" => array ( "bpid" => "34093", "bpname" => "madiwala", "location" => "madiwala", "prime" => "true", "time" => "1170" ), "4" => array ( "bpid" => "34103", "bpname" => "electronic city toll gate", "location" => "electronic city toll gate", "prime" => "false", "time" => "1185" ), "5" => array ( "bpid" => "34109", "bpname" => "narayana hridayalaya", "location" => "narayana hridayalaya", "prime" => "false", "time" => "1195" ), "6" => array ( "bpid" => "34095", "bpname" => "attibele", "location" => "attibele", "prime" => "false", "time" => "1200" ), "7" => array ( "bpid" => "34114", "bpname" => "bommasandra post office", "location" => "bommasandra post office", "prime" => "false", "time" => "1210" ), "8" => array ( "bpid" => "34112", "bpname" => "hosur", "location" => "hosur", "prime" => "false", "time" => "1215" ) ), "bustype" => "volvo multiaxle a/c seater semi sleeper (2+2)", "bustypeid" => "101", "cancellationpolicy" => "0:12:100:0;12:-1:10:0", "departuretime" => "1170", "doj" => "2014-06-18t00:00:00+05:30", "droppingtimes" => array ( "bpid" => "45746", "bpname" => "vytala bye pass", "location" => "vyttila", "prime" => "true", "time" => "1710" ), "fares" => "1100.00", "id" => "200855412640007290", "idproofrequired" => "false", "nonac" => "false", "operator" => "6708", "partialcancellationallowed" => "true", "routeid" => "200855400000007290", "seater" => "true", "sleeper" => "false", "travels" => "atlas travels", "mticketenabled" => "true" ) ) );

you want doing :

$workingarrayforbuses = array(); if(isset($availablebuses['availabletrips']['ac'])){ //one result $workingarrayforbuses[] = $availablebuses['availabletrips']; }else{ //multiple results $workingarrayforbuses = $availablebuses['availabletrips']; } echo '<h1>search results</h1>'; foreach($workingarrayforbuses $availablebuses){ echo '<div>'; echo 'bus name : '.$availablebuses['travels'].'<br/>'; $workingarrayforboardings = array(); if(isset($availablebuses['boardingtimes']['bpid'])){ //one result $workingarrayforboardings[] = $availablebuses['boardingtimes']; }else{ //multiple results $workingarrayforboardings = $availablebuses['boardingtimes']; } echo 'boarding place(s) :<br/>'; foreach($workingarrayforboardings $boardingtimes){ echo '- '.$boardingtimes['location'].'<br/>'; } echo '</div>'; }

that output :

bus name : shama transport boarding place(s) : - kalasipalyam main road - christ university - madiwala - electronic city toll gate - bommasandra post office - attibele - hosur bus name : atlas travels boarding place(s) : - kalasipalyam main road - dairy circle - christ university - madiwala - electronic city toll gate - narayana hridayalaya - attibele - bommasandra post office - hosur

well, guess need update want.

note : problem there is, way handle single result , multiple results homecoming array, problem beingness homecoming array 1 result :

array ( 'ac' => true ... )

instead of being

array ( [0] => array( 'ac' => true ... ) )

not satisfied trick used handle this, don't know how another(better) way. if got idea, know !

hope helps.

php arrays json foreach