问:
Self-join Query
Is it possible to do parent-child query just using join without looping through temporary table?

Database sample :

```<code>menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0002   Master Nominal      A0001   /master/nominal.aspx
A0003   Master Satuan Other A0001   /master/satuan.aspx
A0004   Master Kondisi      A0000   /master/kondisi.aspx
A0005   Master Tujuan       A0003   /master/tujuan.aspx
A0006   Master Item         A0003   /master/item.aspx
A0007   Master Warehouse    A0000   /master/warehouse.aspx
A0008   Master Kapal        A0006   /master/kapal.aspx
</code>```

Desired result if choosed uri = '/master/kapal.aspx' :

```<code>menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0003   Master Satuan Other A0001   /master/satuan.aspx
A0006   Master Item         A0003   /master/item.aspx
A0008   Master Kapal        A0006   /master/kapal.aspx
</code>```

Desired result if choosed uri = /master/tujuan.aspx' :

```<code>menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0005   Master Tujuan       A0003   /master/tujuan.aspx
</code>```

Sample query :

```<code>declare @menuid varchar(255) = 'menuid'
declare @parent varchar(255) = 'parent'
declare @temp_parent varchar(255)
declare @i smallint = 0

delete from temp_menu
while (@menuid <> @parent)
begin
  if(@i = 0)
  begin
    insert into temp_menu
    select * from menu where uri = '/master/kapal.aspx'
    select @menuid = menuid, @parent = parent from menu where uri = '/master/kapal.aspx'
    set @i = 1;
    end
  else
  begin
    insert into temp_menu
    select * from menu where menuid = @parent
    select @menuid = menuid, @temp_parent = parent from menu where menuid = @parent
    set @parent = @temp_parent;
    end
end
select * from temp_menu
</code>```

Sample with hieararchy :

```<code>A0000
|_______________________
|               |       |
A0001           A0004   A0007
|________
|       |
A0002   A0003
        |_______
        |       |
        A0005   A0006
                |
                A0008
</code>```

UPDATED :
I want to get all rows from  the longest branch possible from nodes parent to menuid and stopped if the parent same with menuid or there is no menuid match with parent.

ADDED WITH SCRIPT AND SAMPLES

```<code>IF OBJECT_ID('dbo.menu', 'U') IS NOT NULL
  DROP TABLE dbo.menu
GO

IF OBJECT_ID('dbo.temp_menu', 'U') IS NOT NULL
  DROP TABLE dbo.temp_menu
GO

IF OBJECTPROPERTY(object_id('dbo.sp_get_parent'), N'IsProcedure') = 1
  DROP PROCEDURE dbo.sp_get_parent
GO

create table dbo.menu (
menuid varchar(255)
, name varchar(255)
, parent varchar(255)
, uri varchar(255)
);

insert into dbo.menu (menuid, name, parent, uri)
values ('A0000', 'Master', 'A0000', '#')
, ('A0001', 'Rekening', 'A0000', '/master/rekening.aspx')
, ('A0002', 'Master Nominal', 'A0001', '/master/nominal.aspx')
, ('A0003', 'Master Satuan Other', 'A0001', '/master/satuan.aspx')
, ('A0004', 'Master Kondisi', 'A0000', '/master/kondisi.aspx')
, ('A0005', 'Master Tujuan', 'A0003', '/master/tujuan.aspx')
, ('A0006', 'Master Item', 'A0003', '/master/item.aspx')
, ('A0007', 'Master Warehouse', 'A0000', '/master/warehouse.aspx')
, ('A0008', 'Master Kapal', 'A0006', '/master/kapal.aspx');

create table dbo.temp_menu (
menuid varchar(255)
, name varchar(255)
, parent varchar(255)
, uri varchar(255)
);

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[sp_get_parent]
@uri VARCHAR (255)
AS

declare @menuid varchar(255) = 'menuid'
declare @parent varchar(255) = 'parent'
declare @temp_parent varchar(255)
declare @i smallint = 0

delete from temp_menu
while (@menuid <> @parent)
begin
  if(@i = 0)
  begin
    insert into temp_menu
    select * from menu where uri = @uri
    select @menuid = menuid, @parent = parent from menu where uri = @uri
    set @i = 1;
  end
  else
  begin
    insert into temp_menu
    select * from menu where menuid = @parent
    select @menuid = menuid, @temp_parent = parent from menu where menuid = @parent
    set @parent = @temp_parent;
  end
end
select * from temp_menu order by menuid asc
GO
</code>```

For desired sample above can try this query :

```<code>sp_get_parent '/master/kapal.aspx'
</code>```

AND

```<code>sp_get_parent '/master/tujuan.aspx'
</code>```

答:
Use a common table expression (CTE) like this:

```<code>WITH cte_name AS
(
    SELECT <base_elements> FROM <table_name> WHERE <root_condition>
    UNION ALL
    SELECT <child_elements>
    FROM cte_name
    JOIN <table_name> ON cte_name.id = <table_name>.parentid
)
SELECT DISTINCT * FROM cte_name
</code>```

What this does is it will select all elements that are root elements. In your case, this would be something like menuid = 'A0000'.

It then unions all of these back onto itself and joins the original table again as long as it finds matches for parentId to (child)-Id in your case the on condition would be menu.parent = cte.menuid.

And then it selects everything distinct from whatever that recursive query returns netting you all paths. If you want to get the maximum depth, you will have to add a constant value on the root select like (0) and then subsequently increase it with every union all. Then you can select a max(nesting_level) from the final distinct query.

In your case something like this could work

```<code>WITH cteMenu AS
(
    SELECT menuid, name, parent, url, 0 as nesting_level FROM menu WHERE menuid = 'A0000'
    UNION ALL
    SELECT menu.menuid, menu.name, menu.parent, menu.url, nesting_level + 1
        FROM menu
        JOIN cteMenu ON menu.parent = cteMenu.menuid
        WHERE menu.id <> 'A0000'
)
SELECT DISTINCT * FROM cteMenu WHERE nesting_level = (SELECT MAX(nesting_level) FROM cteMenu)
</code>```

/update: added the WHERE-clause WHERE menu.id <> 'A0000' to the inner select, this removes the root element from the selection and stops the infinite recursion.

Title: Self-join Query

Body:
Is it possible to do parent-child query just using join without looping through temporary table?

Database sample :

menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0002   Master Nominal      A0001   /master/nominal.aspx
A0003   Master Satuan Other A0001   /master/satuan.aspx
A0004   Master Kondisi      A0000   /master/kondisi.aspx
A0005   Master Tujuan       A0003   /master/tujuan.aspx
A0006   Master Item         A0003   /master/item.aspx
A0007   Master Warehouse    A0000   /master/warehouse.aspx
A0008   Master Kapal        A0006   /master/kapal.aspx

Desired result if choosed uri = '/master/kapal.aspx' :

menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0003   Master Satuan Other A0001   /master/satuan.aspx
A0006   Master Item         A0003   /master/item.aspx
A0008   Master Kapal        A0006   /master/kapal.aspx

Desired result if choosed uri = /master/tujuan.aspx' :

menuid  name                parent  url
----------------------------------------------------------
A0000   Master              A0000   #
A0001   Rekening            A0000   /master/rekening.aspx
A0005   Master Tujuan       A0003   /master/tujuan.aspx

Sample query :

declare @menuid varchar(255) = 'menuid'
declare @parent varchar(255) = 'parent'
declare @temp_parent varchar(255)
declare @i smallint = 0

delete from temp_menu
while (@menuid <> @parent)
begin
  if(@i = 0)
  begin
    insert into temp_menu
    select * from menu where uri = '/master/kapal.aspx'
    select @menuid = menuid, @parent = parent from menu where uri = '/master/kapal.aspx'
    set @i = 1;
    end
  else
  begin
    insert into temp_menu
    select * from menu where menuid = @parent
    select @menuid = menuid, @temp_parent = parent from menu where menuid = @parent
    set @parent = @temp_parent;
    end
end
select * from temp_menu

Sample with hieararchy :

A0000
|_______________________
|               |       |
A0001           A0004   A0007
|________
|       |
A0002   A0003
        |_______
        |       |
        A0005   A0006
                |
                A0008

UPDATED :
I want to get all rows from  the longest branch possible from nodes parent to menuid and stopped if the parent same with menuid or there is no menuid match with parent.

ADDED WITH SCRIPT AND SAMPLES

IF OBJECT_ID('dbo.menu', 'U') IS NOT NULL
  DROP TABLE dbo.menu
GO

IF OBJECT_ID('dbo.temp_menu', 'U') IS NOT NULL
  DROP TABLE dbo.temp_menu
GO

IF OBJECTPROPERTY(object_id('dbo.sp_get_parent'), N'IsProcedure') = 1
  DROP PROCEDURE dbo.sp_get_parent
GO

create table dbo.menu (
menuid varchar(255)
, name varchar(255)
, parent varchar(255)
, uri varchar(255)
);

insert into dbo.menu (menuid, name, parent, uri)
values ('A0000', 'Master', 'A0000', '#')
, ('A0001', 'Rekening', 'A0000', '/master/rekening.aspx')
, ('A0002', 'Master Nominal', 'A0001', '/master/nominal.aspx')
, ('A0003', 'Master Satuan Other', 'A0001', '/master/satuan.aspx')
, ('A0004', 'Master Kondisi', 'A0000', '/master/kondisi.aspx')
, ('A0005', 'Master Tujuan', 'A0003', '/master/tujuan.aspx')
, ('A0006', 'Master Item', 'A0003', '/master/item.aspx')
, ('A0007', 'Master Warehouse', 'A0000', '/master/warehouse.aspx')
, ('A0008', 'Master Kapal', 'A0006', '/master/kapal.aspx');

create table dbo.temp_menu (
menuid varchar(255)
, name varchar(255)
, parent varchar(255)
, uri varchar(255)
);

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[sp_get_parent]
@uri VARCHAR (255)
AS

declare @menuid varchar(255) = 'menuid'
declare @parent varchar(255) = 'parent'
declare @temp_parent varchar(255)
declare @i smallint = 0

delete from temp_menu
while (@menuid <> @parent)
begin
  if(@i = 0)
  begin
    insert into temp_menu
    select * from menu where uri = @uri
    select @menuid = menuid, @parent = parent from menu where uri = @uri
    set @i = 1;
  end
  else
  begin
    insert into temp_menu
    select * from menu where menuid = @parent
    select @menuid = menuid, @temp_parent = parent from menu where menuid = @parent
    set @parent = @temp_parent;
  end
end
select * from temp_menu order by menuid asc
GO

For desired sample above can try this query :

sp_get_parent '/master/kapal.aspx'

AND

sp_get_parent '/master/tujuan.aspx'

Body:
Use a common table expression (CTE) like this:

WITH cte_name AS
(
    SELECT <base_elements> FROM <table_name> WHERE <root_condition>
    UNION ALL
    SELECT <child_elements>
    FROM cte_name
    JOIN <table_name> ON cte_name.id = <table_name>.parentid
)
SELECT DISTINCT * FROM cte_name

What this does is it will select all elements that are root elements. In your case, this would be something like menuid = 'A0000'.

It then unions all of these back onto itself and joins the original table again as long as it finds matches for parentId to (child)-Id in your case the on condition would be menu.parent = cte.menuid.

And then it selects everything distinct from whatever that recursive query returns netting you all paths. If you want to get the maximum depth, you will have to add a constant value on the root select like (0) and then subsequently increase it with every union all. Then you can select a max(nesting_level) from the final distinct query.

In your case something like this could work

WITH cteMenu AS
(
    SELECT menuid, name, parent, url, 0 as nesting_level FROM menu WHERE menuid = 'A0000'
    UNION ALL
    SELECT menu.menuid, menu.name, menu.parent, menu.url, nesting_level + 1
        FROM menu
        JOIN cteMenu ON menu.parent = cteMenu.menuid
        WHERE menu.id <> 'A0000'
)
SELECT DISTINCT * FROM cteMenu WHERE nesting_level = (SELECT MAX(nesting_level) FROM cteMenu)

/update: added the WHERE-clause WHERE menu.id <> 'A0000' to the inner select, this removes the root element from the selection and stops the infinite recursion.


来源: stackexchange

问:
Getting values of textfields on page
Lets just say that I have some (many many many) text fields on a page... and i enter a new value in one of them, then click a button... How can I update the database with just that new value? Or, if it would be easier... How can I update all of those textfields to the database?

Thanks :)

答:
As I can see this, it has two approaches

1 - After you clicks the save button, you collect all the values to an array (Using javascrip) and pass that array (As a comma separated list or something) to the server. there inside a transaction block you delete all the existing values from the table and insert the new values.

2 - But If you have many, many text values, have a javascript to identify the changing text boxes only.

simple procedure would be,

select a text field

get its value to a variable

when user does a change to the text
field always compare with the
original value

If the value changed, flag that text
box

when user clicks 'save' get only the
changed value fields

cheers

sameera

ContentLicense: CC BY-SA 2.5

Title: Getting values of textfields on page


问:
Magento 2 override default.phtml and items.phtml in new order email
I made a module that overrides default.phtml and i put and product image in there, and it works fine!

I made this sales_email_orders_renderers.xml to overide the default.phtml

```<code><page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
    <referenceBlock name="sales.email.order.renderers">
        <block class="Magento\Sales\Block\Order\Email\Items\Order\DefaultOrder" as="default" template="EmizenTech_SalesEmail::email/items/order/default.phtml"/>
    </referenceBlock>
</body>
</page>
</code>```

The original is in vendor/magento/module-sales/view/frontend/templates/email/items/order/

But how to also override the items.phtml in an other folder?

/vendor/magento/module-sales/view/frontend/templates/email/

Do i need to make an other xml or can i put some tags in the existing one?

答:
Please go to your theme and create folder
Magento_Sales/templates/email/items/order

then
download default.phtml file

from
/vendor/magento/module-sales/view/frontend/templates/email/items/order

then paste here
Magento_Sales/templates/email/items/order your theme.

ContentLicense: CC BY-SA 3.0

Body:
I made a module that overrides default.phtml and i put and product image in there, and it works fine!

I made this sales_email_orders_renderers.xml to overide the default.phtml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

    <referenceBlock name="sales.email.order.renderers">
        <block class="Magento\Sales\Block\Order\Email\Items\Order\DefaultOrder" as="default" template="EmizenTech_SalesEmail::email/items/order/default.phtml"/>
    </referenceBlock>

</page>

The original is in vendor/magento/module-sales/view/frontend/templates/email/items/order/

But how to also override the items.phtml in an other folder?

/vendor/magento/module-sales/view/frontend/templates/email/

Do i need to make an other xml or can i put some tags in the existing one?


问:
Regex split string by spaces taking into account nested brackets
I know that this has been asked/answered several times but unfortunately none of the solutions I've tried so far works in my case.
I need to split something like this:

```<code>contrast(200%) drop-shadow(rgba(0, 0, 0, 0.5) 0px 0px 10px)
</code>```

into this:

```<code>contrast(200%)
drop-shadow(0px 0px 10px rgba(0,0,0,.5))
</code>```

By following this solution, I'm currently doing this:

```<code>myString = "contrast(200%) drop-shadow(rgba(0, 0, 0, 0.5) 0px 0px 10px)"
myString.match(/[^\(\s]+(\(.*?\)+)?/g)
</code>```

but this gives me:

```<code>contrast(200%)
drop-shadow(rgba(0, 0, 0, 0.5)  <== notice the missing second ) here
0px    <== unwanted, should go with previous one
0px    <== unwanted, should go with previous one
10px)  <== unwanted, should go with previous one
</code>```

as the regexp does not capture all closing brackets...

答:
Here is my solution:</p>

```<code>function splitBySpaces(string){
    var openBrackets = 0, ret = [], i = 0;
    while (i < string.length){
        if (string.charAt(i) == '(')
            openBrackets++;
        else if (string.charAt(i) == ')')
            openBrackets--;
        else if (string.charAt(i) == " " && openBrackets == 0){
            ret.push(string.substr(0, i));
            string = string.substr(i + 1);
            i = -1;
        }
        i++;
    }

    if (string != "") ret.push(string);
    return ret;
}
</code>```

Body:
I know that this has been asked/answered several times but unfortunately none of the solutions I've tried so far works in my case.
I need to split something like this:

contrast(200%) drop-shadow(rgba(0, 0, 0, 0.5) 0px 0px 10px)

into this:

contrast(200%)
drop-shadow(0px 0px 10px rgba(0,0,0,.5))

By following this solution, I'm currently doing this:

myString = "contrast(200%) drop-shadow(rgba(0, 0, 0, 0.5) 0px 0px 10px)"
myString.match(/[^\(\s]+(\(.*?\)+)?/g)

but this gives me:

contrast(200%)
drop-shadow(rgba(0, 0, 0, 0.5)  <== notice the missing second ) here
0px    <== unwanted, should go with previous one
0px    <== unwanted, should go with previous one
10px)  <== unwanted, should go with previous one

as the regexp does not capture all closing brackets...

Body:
Here is my solution:

function splitBySpaces(string){
    var openBrackets = 0, ret = [], i = 0;
    while (i < string.length){
        if (string.charAt(i) == '(')
            openBrackets++;
        else if (string.charAt(i) == ')')
            openBrackets--;
        else if (string.charAt(i) == " " && openBrackets == 0){
            ret.push(string.substr(0, i));
            string = string.substr(i + 1);
            i = -1;
        }
        i++;
    }

    if (string != "") ret.push(string);
    return ret;
}


问:
What can I do when avoiding overdrawing conflicted with batch rendering in OpenGL?
Say, I have some render units sorted in distance from camera order.

Such as ru0, ru1, ru2, ru3, ru4, ru5....The purpose of doing this is to avoid overdrawing by z depth test.

But, in batch rendering view, this is a kind of wast.

Assume, ru1, ru3, ru5 have same render state(same opengl state, and same shader program), So they should be batched and render in one time.

But, this is not Avoiding overdrawing want me to do.

So, my question is, is this a problem based on specific scenario(such as in some case, the overdrawing's consuming time is not more than opengl state changing's consuming) or there is another way to solve this problem?

NOTE, all my render units are opaque, so I am not taking transparent unit into account here.

答:
Modern hardware is very likely to implement "Early z-test", i.e. performing depth test before fragment (pixel) shader is run. Alternatively, it is implementable by hand.

So, it is likely more beneficial to sort by state,  unless you have transparency issues. In the latter case you may want to look into "Order-independent transparency".

In any case, trust no one. Measure (profile) and compare before optimizing anything.


问:
How to send data from one window to another window?
Could you please tell me how to send data from one window to another window?
I have one button on my parent window. On click of that button I am moving to another page (There is success button present in another page). When I click success button on child or another window I am redirecting to parent window. I want to print "success" text on parent window.

http://plnkr.co/edit/6IRDD0DHxK6A7mExWOUP?p=preview

```<code>$(function() {
  $('#f').on('click', function() {
    // alert('ddd');
    window.open('a.html')
  })

   $('#succ').on('click', function() {
    // alert('succ');
    window.open('index.html')
  })
})
</code>```

答:
Just do the following:

on your parent page add the following code:

```<code>$(document).ready(function() {
   var referrer =  document.referrer;    //to get previous url
   if(referrer == 'a.html'){
       alert("success");    // here i am showing an alert box with success message, you can print it inside a div or span as per your need.
   }
});
</code>```

NOTE: on Plunker replace "if condition" with this one:

```<code>  if(referrer=='http://run.plnkr.co/Bwm0sBW4RRnrmWRA/a.html'){
       alert("success");    // here i am showing an alert box with success message, you can print it inside a div or span as per your need.
   }
</code>```

and to send data along with it:

```<code>do something like this:
window.open('index.html','height=400, width=650, left=300, top=100, status=yes');
or
window.open("index.html?cid=hello");
</code>```

That's it. :)

Body:
Could you please tell me how to send data from one window to another window?
I have one button on my parent window. On click of that button I am moving to another page (There is success button present in another page). When I click success button on child or another window I am redirecting to parent window. I want to print "success" text on parent window.

http://plnkr.co/edit/6IRDD0DHxK6A7mExWOUP?p=preview

$(function() {
  $('#f').on('click', function() {
    // alert('ddd');
    window.open('a.html')
  })

   $('#succ').on('click', function() {
    // alert('succ');
    window.open('index.html')
  })
})

Body:
Just do the following:

on your parent page add the following code:

$(document).ready(function() {
   var referrer =  document.referrer;    //to get previous url
   if(referrer == 'a.html'){
       alert("success");    // here i am showing an alert box with success message, you can print it inside a div or span as per your need.
   }
});

NOTE: on Plunker replace "if condition" with this one:

  if(referrer=='http://run.plnkr.co/Bwm0sBW4RRnrmWRA/a.html'){
       alert("success");    // here i am showing an alert box with success message, you can print it inside a div or span as per your need.
   }

and to send data along with it:

do something like this:
window.open('index.html','height=400, width=650, left=300, top=100, status=yes');
or
window.open("index.html?cid=hello");

That's it. :)


问:
Heroku/Rails: Task scheduler is working but does nothing
I have an app running on heroku and once a day it runs taks called every_day. Task scheduler is working fine but it does nothing to my database. I also tried to run it manually and it's the same result. I think that problem is with my code and I will be thankful if someone could tell me what is wrong. This code of task:

```<code>task :every_day => :environment do
  unactive_auction = Auction.where(ended: false).where('created_at < ?', 14.days.ago)
  unactive_auction.update_all(:ended => true)
end
</code>```

When I run it manually I get this:

```<code>, [2017-06-07T07:08:26.348223 #4] DEBUG -- :   Auction Load (1.7ms)  SELECT  "auctions".* FROM "auctions" ORDER BY "auctions"."id" ASC LIMIT $1  [["LIMIT", 1000]]
D, [2017-06-07T07:08:26.677182 #4] DEBUG -- :   SQL (1.3ms)  UPDATE "auctions" SET "ended" = 't' WHERE "auctions"."ended" = $1 AND (created_at < '2017-05-24 07:08:26.674476')  [["ended", false]]
</code>```

I have no idea what I'm doing wrong. It looks like it's working but... But it does nothing.

答:
Are you sure there are objects satisfying your query parameters ?
Run in the rails console:

```<code> unactive_auction = Auction.where("ended is ? and created_at < ?", false, 14.days.ago)
</code>```

And see if it returns anything before running the task.

Body:
I have an app running on heroku and once a day it runs taks called every_day. Task scheduler is working fine but it does nothing to my database. I also tried to run it manually and it's the same result. I think that problem is with my code and I will be thankful if someone could tell me what is wrong. This code of task:

task :every_day => :environment do
  unactive_auction = Auction.where(ended: false).where('created_at < ?', 14.days.ago)
  unactive_auction.update_all(:ended => true)
end

When I run it manually I get this:

, [2017-06-07T07:08:26.348223 #4] DEBUG -- :   Auction Load (1.7ms)  SELECT  "auctions".* FROM "auctions" ORDER BY "auctions"."id" ASC LIMIT $1  [["LIMIT", 1000]]
D, [2017-06-07T07:08:26.677182 #4] DEBUG -- :   SQL (1.3ms)  UPDATE "auctions" SET "ended" = 't' WHERE "auctions"."ended" = $1 AND (created_at < '2017-05-24 07:08:26.674476')  [["ended", false]]

I have no idea what I'm doing wrong. It looks like it's working but... But it does nothing.

Body:
Are you sure there are objects satisfying your query parameters ?
Run in the rails console:

 unactive_auction = Auction.where("ended is ? and created_at < ?", false, 14.days.ago)

And see if it returns anything before running the task.


问:
Handling $_SESSION object in a load-balanced setup, PHP
I have a setup where I have a host which routes multiple requests in a load-balanced fashion. My backend uses PHP. Now, I need to use the $_SESSION object for some of my processing.

Will $_SESSION work where I have 3 backend servers which can receive any request at any time?

If not, Can one suggest alternatives to handle such cases?

EDIT: I do understand that we can store sessions in a database and find a way to track it. But, the problem in a realtime load-balanced production scenario is the number of calls that go into a DB. That can be a real bummer for my performance. I'm kind of hoping that, we can handle this at an webserver level.

Not sure, if it is possible, but, if two webservers have some kind of replication mechanism like databases do, it will be brilliant. I dont have to do a thing.

If such a thing does not exist, PHP should be modified to support it. That will actually, make it a seriously robust language.

答:
Look into either memcache (Is it recommended to store PHP Sessions in MemCache?) or REDIS (https://joshtronic.com/2013/06/20/redis-as-a-php-session-handler/).

There is a good tutorial on setting up memcache on Ubuntu at https://www.globo.tech/learning-center/php-memcached-instances-ubuntu-16/.  Which also covers using haproxy as a load balancer (although you may already a solution).

Perhaps have a read of https://blog.newtonhq.com/session-handling-for-1-million-requests-per-hour-68cdece15030.


问:
Jenkins ext-email plugin fails to send email on build success
I have Jenkins version 1.480.3 installed on my machine and Email-Extension Plugin 2.28.

I have configured my jobs on Jenkins and everything works fine except the final build success email.

I have configured four triggers for Email-Extension plugin:

Failure

Success

Unstable

Before Build

For all the triggers I have enabled "Attach Log" and all works fine except the "Success".

I get the following message on screen:

Email was triggered for: Success

  Sending email for trigger: Success

  Request made to compress build log

  Sending email to: abc@example.com def@example.com

  Error sending to the following VALID addresses: abc@example.com def@example.com

  Notifying upstream projects of job completion

  Capturing build context information.

  Finished: SUCCESS

Please could someone help me since I really have no clue how to resolve this.

答: If every thing fails, try restarting jenkins process. That solved for me. Somehow the Jenkins system was unable to load all of the configs without a restart? But give it a try.</p>


问:
Why won't Angular run in Outlook 2013 as folder homepage?
I am attempting to recreate this Outlook Kanban board using Angular.  I've successfully created the app and have it working in IE11.  Thinking this would be enough, I configured my Outlook 2013 instance to use it as the homepage for my task folder, and was immediately greeted with several script errors.

So I thought I'd see if I could get a bare minimum Angular app working.  I created a new project via Angular CLI, built the page and configured my Outlook task folder to use it.  I was greeted with the same script errors again:

'Expected identifier' in polyfills.bundle.js

```<code>ZoneAwarePromise.prototype.catch = function (onRejected) {
</code>```

'Object doesn't support property or method bind' in styles.bundle.js

```<code>update = applyToSingletonTag.bind(null, styleElement, styleIndex, false);
</code>```

'Expected identifier, string or number' in vendor.bundle.js

```<code>  'zwnj': '\u200C',
};
</code>```

'Object doesn't support property or method defineProperty' in main.bundle.js

```<code>Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
</code>```

The third error seems to be the trailing comma on the last property definition, but the other three I don't have a clue.

Even though Outlook uses the IE engine to render webpages, it must be using an old version (IE11 is installed) or is doing some sort of emulation.  Has anyone had success getting Angular to run as a static file within Outlook?  Is there a way to utilize office-js to help resolve this?

I realize this isn't a common scenario, but thought I'd give it a shot anyway.  Seems like an easy way to visualize my Outlook tasks if I can get it working.

Thanks in advance!

答: After the release of Outlook 2016, Outlook version 2013 or older are considered legacy clients. To provide the best experience for our customers and make the best use of our resources we are not investing further in those versions, it is only maintained for security issues. We suggest looking at outlook module extension https://dev.office.com/docs/add-ins/outlook/extension-module-outlook-add-ins?product=outlook and task pane add-ins to accomplish what you are trying to do.</p>

Body:
I am attempting to recreate this Outlook Kanban board using Angular.  I've successfully created the app and have it working in IE11.  Thinking this would be enough, I configured my Outlook 2013 instance to use it as the homepage for my task folder, and was immediately greeted with several script errors.

So I thought I'd see if I could get a bare minimum Angular app working.  I created a new project via Angular CLI, built the page and configured my Outlook task folder to use it.  I was greeted with the same script errors again:

'Expected identifier' in polyfills.bundle.js

ZoneAwarePromise.prototype.catch = function (onRejected) {

'Object doesn't support property or method bind' in styles.bundle.js

update = applyToSingletonTag.bind(null, styleElement, styleIndex, false);

'Expected identifier, string or number' in vendor.bundle.js

  'zwnj': '\u200C',
};

'Object doesn't support property or method defineProperty' in main.bundle.js

Object.defineProperty(__webpack_exports__, "__esModule", { value: true });

The third error seems to be the trailing comma on the last property definition, but the other three I don't have a clue.

Even though Outlook uses the IE engine to render webpages, it must be using an old version (IE11 is installed) or is doing some sort of emulation.  Has anyone had success getting Angular to run as a static file within Outlook?  Is there a way to utilize office-js to help resolve this?

I realize this isn't a common scenario, but thought I'd give it a shot anyway.  Seems like an easy way to visualize my Outlook tasks if I can get it working.

Thanks in advance!


问:
Javascript draw dynamic line
I'm looking for Javascript code for letting the user draw a line (on an image).

Just as the line tool in Photoshop (for example):

The user clicks on the image, drags the mouse (while the line between the start point and the mouse point is dynamically drawn on mouse drag).

I would also need a callable function to send the page the start and end coordinates.

I've found this very nice script for area selection:
http://www.defusion.org.uk/code/javascript-image-cropper-ui-using-prototype-scriptaculous/

and I've found many script for drawing lines (and other shapes in JS), but could not find what I'm looking for.

Thanks

答:
A cross-browser solution for drawing lines in javascript, without requiring any external libraries, can be found here: http://bytes.com/topic/javascript/answers/88771-drawing-vector-lines-javascript

This works in all browsers, including IE.

Title: Javascript draw dynamic line


问:
Does work Batch normalization when Batchnormalization=false to true in Matconvnet
I am using matconvnet library. In the MNIST example the default parameter batchnormalization=true. But VL_NNBNORM() function has nothing(just comment lines). Is it working though this? or Am i have to change vl_nnbnorm function?
I mean that if i change batchnormalization=false to true, is it enough?
Thanks..</p>

答:
Yes it's enough. If you see faster convergence, it means batch norm is working.
vl_nnbnorm.m has nothing because it calls a mex file. This is how Matlab calls a mex file --- you have a dummy .m file with the same name.</p>


问:
Javascript Regular Expression For a Valid Input
I want JavaScript regular expression which validates below number format (only number and min length should be 11 and maximum 16).<br>
e.g   </p>

```<code>12345678901 // valid
+1234567890 // valid
+1234567890+ // invalid
+123456789trtr // invalid
+trtr // invalid
</code>```

答:
This works assuming that only digits are allowed, and + is allowed at the beginning of the string.</p>

```<code>/^(?:\+\d{10,15}|\d{11,16})$/
</code>```

Body:
I want JavaScript regular expression which validates below number format (only number and min length should be 11 and maximum 16).

e.g

12345678901 // valid
+1234567890 // valid
+1234567890+ // invalid
+123456789trtr // invalid
+trtr // invalid

Body:
This works assuming that only digits are allowed, and + is allowed at the beginning of the string.

/^(?:\+\d{10,15}|\d{11,16})$/


问:
Duplicate entry: AbstractHttpContent.class while
I am developong an app that uses google app engine.
Building is fine but when I'm trying to run it,
I get this error:

```<code>Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/appengine/repackaged/com/google/api/client/http/AbstractHttpContent.class
</code>```

when trying to run the application in android studio.

here is my gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "bgu.wingmanapp"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    //compile fileTree(dir: 'libs', include: ['*.jar'])
   // testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.0'
    compile 'com.android.support:design:23.2.0'
    compile 'com.android.support:support-v4:23.2.0'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile project(path: ':backend', configuration: 'android-endpoints')
    compile ('com.google.appengine:appengine-api-1.0-sdk:1.9.18')
    compile ('com.google.appengine:appengine-endpoints:1.9.18')
}
</code>```

and backend gradle:

```<code>// If you would like more information on the gradle-appengine-plugin please refer to the github page
// https://github.com/GoogleCloudPlatform/gradle-appengine-plugin

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.google.appengine:gradle-appengine-plugin:1.9.18'
    }
}

repositories {
    jcenter();
}

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'appengine'

sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7

dependencies {
  appengineSdk 'com.google.appengine:appengine-java-sdk:1.9.18'
  compile 'com.google.appengine:appengine-endpoints:1.9.18'
  compile 'com.google.appengine:appengine-endpoints-deps:1.9.18'
  compile 'javax.servlet:servlet-api:2.5'
}

appengine {
  downloadSdk = true
  appcfg {
    oauth2 = true
  }
  endpoints {
    getClientLibsOnBuild = true
    getDiscoveryDocsOnBuild = true
  }
}
</code>```

I understand that i have a ducplicate dependency, but I can't solve it. thanks!

答:
If you compile this project:

```<code>compile project(path: ':backend', configuration: 'android-endpoints')
</code>```

if you run the two below complies then you will have duplicates of the project you compiled above. And you should remove them:

```<code>compile ('com.google.appengine:appengine-api-1.0-sdk:1.9.18')

compile ('com.google.appengine:appengine-endpoints:1.9.18')
</code>```

Also if you are using the:

```<code>compile fileTree(dir: 'libs', include: ['*.jar'])......(I am aware you have commented it out)
</code>```

You also probably have the same External library file as in your 'app' or 'backend' modules which are being called twice due to compiling of the entire file tree.

Body:
I am developong an app that uses google app engine.
Building is fine but when I'm trying to run it,
I get this error:

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/google/appengine/repackaged/com/google/api/client/http/AbstractHttpContent.class

when trying to run the application in android studio.

here is my gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "bgu.wingmanapp"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    //compile fileTree(dir: 'libs', include: ['*.jar'])
   // testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.0'
    compile 'com.android.support:design:23.2.0'
    compile 'com.android.support:support-v4:23.2.0'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile project(path: ':backend', configuration: 'android-endpoints')
    compile ('com.google.appengine:appengine-api-1.0-sdk:1.9.18')
    compile ('com.google.appengine:appengine-endpoints:1.9.18')
}

and backend gradle:

// If you would like more information on the gradle-appengine-plugin please refer to the github page
// https://github.com/GoogleCloudPlatform/gradle-appengine-plugin

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.google.appengine:gradle-appengine-plugin:1.9.18'
    }
}

repositories {
    jcenter();
}

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'appengine'

sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7

dependencies {
  appengineSdk 'com.google.appengine:appengine-java-sdk:1.9.18'
  compile 'com.google.appengine:appengine-endpoints:1.9.18'
  compile 'com.google.appengine:appengine-endpoints-deps:1.9.18'
  compile 'javax.servlet:servlet-api:2.5'
}

appengine {
  downloadSdk = true
  appcfg {
    oauth2 = true
  }
  endpoints {
    getClientLibsOnBuild = true
    getDiscoveryDocsOnBuild = true
  }
}

I understand that i have a ducplicate dependency, but I can't solve it. thanks!

Body:
If you compile this project:

compile project(path: ':backend', configuration: 'android-endpoints')

if you run the two below complies then you will have duplicates of the project you compiled above. And you should remove them:

compile ('com.google.appengine:appengine-api-1.0-sdk:1.9.18')

compile ('com.google.appengine:appengine-endpoints:1.9.18')

Also if you are using the:

compile fileTree(dir: 'libs', include: ['*.jar'])......(I am aware you have commented it out)

You also probably have the same External library file as in your 'app' or 'backend' modules which are being called twice due to compiling of the entire file tree.


问:
Unknown exception while deserializing using simple XML
I am deserializing data using Simple XML in Java, but i get an exception telling me:

```<code>protokolsimulering.model.Terminal.<init>()
</code>```

This is my serializing code:

```<code>public void saveSimulationState(String simulationFile) {
    try{
        Strategy strategy = new CycleStrategy("id", "ref");
        Serializer serializer = new Persister(strategy);
        File result = new File(simulationFile);
        serializer.write(this.sm, result);
    }
    catch(Exception ex)
    {
        System.out.println(ex.getMessage());
    }
}

public void loadSimulationState(String simulationFile) {
    try {
        Strategy strategy = new CycleStrategy("id", "ref");
        Serializer serializer = new Persister(strategy);
        File source = new File(simulationFile);
        this.sm = serializer.read(Simulation.class, source);
    } catch (Exception ex) {
        System.out.println(ex.getLocalizedMessage());
    }
}
</code>```

The code for Terminal.java is:

```<code>package protokolsimulering.model;

import java.util.ArrayList;
import protokolsimulering.model.DataPacket.*;

public class Terminal extends Sensor {

    public Terminal(int x, int y, double r) {
        super(x,y,r);
        learnPosition();
    }

    @Override
    public void init() {
        this.broadcast(PacketFactory.newRutePacket(this,0));
    }

    @Override
    public void step() {
        ArrayList<AbstractPacket> packetsThisStep = (ArrayList<AbstractPacket>) this.getPackages();

        for(AbstractPacket p : packetsThisStep) {
            if(p instanceof HalloPacket) {
                // Rutningsprotokol
                send(p.getSender(),PacketFactory.newRutePacket(this,0));

                // Lokaliseringsprotokol
                send(p.getSender(), PacketFactory.newHerPacket(this, this.getKnownPosition()));
        }
    }
}
</code>```

}

The entire source code can be found at:

http://code.google.com/p/sensor-protocol-simulation/source/browse/#svn/trunk/src/protokolsimulering

答:
The exception means the problem is related to invoking the Terminal constructor.

Typically, to construct objects when deserializing, a no-args contructor must be available, like this:

```<code>public Terminal() {
    ...
}
</code>```

OwnerDisplayName: utdiscant

Body:
I am deserializing data using Simple XML in Java, but i get an exception telling me:

protokolsimulering.model.Terminal.<init>()

This is my serializing code:

public void saveSimulationState(String simulationFile) {
    try{
        Strategy strategy = new CycleStrategy("id", "ref");
        Serializer serializer = new Persister(strategy);
        File result = new File(simulationFile);
        serializer.write(this.sm, result);
    }
    catch(Exception ex)
    {
        System.out.println(ex.getMessage());
    }
}

public void loadSimulationState(String simulationFile) {
    try {
        Strategy strategy = new CycleStrategy("id", "ref");
        Serializer serializer = new Persister(strategy);
        File source = new File(simulationFile);
        this.sm = serializer.read(Simulation.class, source);
    } catch (Exception ex) {
        System.out.println(ex.getLocalizedMessage());
    }
}

The code for Terminal.java is:

package protokolsimulering.model;

import java.util.ArrayList;
import protokolsimulering.model.DataPacket.*;

public class Terminal extends Sensor {

    public Terminal(int x, int y, double r) {
        super(x,y,r);
        learnPosition();
    }

    @Override
    public void init() {
        this.broadcast(PacketFactory.newRutePacket(this,0));
    }

    @Override
    public void step() {
        ArrayList<AbstractPacket> packetsThisStep = (ArrayList<AbstractPacket>) this.getPackages();

        for(AbstractPacket p : packetsThisStep) {
            if(p instanceof HalloPacket) {
                // Rutningsprotokol
                send(p.getSender(),PacketFactory.newRutePacket(this,0));

                // Lokaliseringsprotokol
                send(p.getSender(), PacketFactory.newHerPacket(this, this.getKnownPosition()));
        }
    }
}

}

The entire source code can be found at:

http://code.google.com/p/sensor-protocol-simulation/source/browse/#svn/trunk/src/protokolsimulering

LastEditorDisplayName: Yuval A

Body:
The exception means the problem is related to invoking the Terminal constructor.

Typically, to construct objects when deserializing, a no-args contructor must be available, like this:

public Terminal() {
    ...
}

OwnerDisplayName: Jordan Liggitt


问:
Where does forever store console.log output?
I installed forever and am using it, finding it quite funny.

But I realized that the logs are placed to somewhere else. Is there any tips?

答:
Need to do normal
forever start script.js
to start, and to check console/error logs use
forever logs
this will print list of all logs being stored by forever
and then you can use tail -f /path/to/logs/file.log and this will print live logs to your window. hit ctrl+z to stop logs print.


问:
How to filter unpaired lines from table?
I created the following table in SAP:

How can I print only these lines, where the employee has signed in (KOMMEN), but not signed out (GEHEN)?

In this example I want print only the last line.

答:
The output method you use is called ABAP list output. There are many different output methods in ABAP. The list output is only one. The pitty with this list output in your case is, that adding a filter is up to the developer. I.e. there is no default feature of the ABAP list output to filter for certain values. This output method is really kept simple.

Like said in the comments you should change your ABAP code and do the filtering 'manually' in the loop. To give an example:

```<code>LOOP AT lt_employees INTO ls_employee
  WHERE komgeh = 'KOMMEN'.
  WRITE: / ls_employee-mandt,
           ls_employee-id,
           ls_employee-pnr,
           ls_employee-komgeh,
           ls_employee-datum,
           ls_employee-uhrzeit.
ENDLOOP.
</code>```

Note that there are also other possibilities to filter for the 'KOMMEN'-values in the internal table. You could think of an IF-statement inside the LOOP. Anyways applying a WHERE-clause at the LOOP-statement is one of the most performant ways of filtering an internal table.

In addition, as you did not posted your code, you need to transfer the names I used in the code snippet to your code.

Body:
The output method you use is called ABAP list output. There are many different output methods in ABAP. The list output is only one. The pitty with this list output in your case is, that adding a filter is up to the developer. I.e. there is no default feature of the ABAP list output to filter for certain values. This output method is really kept simple.

Like said in the comments you should change your ABAP code and do the filtering 'manually' in the loop. To give an example:

LOOP AT lt_employees INTO ls_employee
  WHERE komgeh = 'KOMMEN'.
  WRITE: / ls_employee-mandt,
           ls_employee-id,
           ls_employee-pnr,
           ls_employee-komgeh,
           ls_employee-datum,
           ls_employee-uhrzeit.
ENDLOOP.

Note that there are also other possibilities to filter for the 'KOMMEN'-values in the internal table. You could think of an IF-statement inside the LOOP. Anyways applying a WHERE-clause at the LOOP-statement is one of the most performant ways of filtering an internal table.

In addition, as you did not posted your code, you need to transfer the names I used in the code snippet to your code.


问:
C# looping array object multidimensional from ajax post
I have Multidimensional array object How to loop all value in c# ?
in C#

```<code>charge[0]{[ChargeMultiId, da95aad9-0cdc-40bb-a5db-3bc0933dea4a ]}
charge[1]{[ChargeMultiNoteslist, Testing notes 29/04/2016 ]}
charge[22]{[Diagnosis, : ["1", "2", "3", "4", "5", "6", "7", "8", "9"]}
</code>```

Ajax

```<code>    charge =
    "ChargeMultiId": "da95aad9-0cdc-40bb-a5db-3bc0933dea4a",
    "ChargeMultiNoteslist": "Testing notes 29/04/2016",
    "ChargeMultiCode": "99238",
    "ChargeMultiCodeName": "HOSP DSCHRG D MGMT 30 MIN/ < > & '",
    "ChargeMultiProcedureID": "89c5ecaf-903b-41d7-8564-e4034d94934f",
    "Diagnosis": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
}, {}
]
</code>```

答:
I think you should make the model class as below.

```<code>public class Charge
{
     public Guid ChargeMultiId { get; set; }
     public string ChargeMultiNoteslist { get; set; }
     public int ChargeMultiCode { get; set; }
     public string ChargeMultiCodeName { get; set; }
     public Guid ChargeMultiProcedureID { get; set; }
     public List<int> Diagnosis { get; set; }
}
</code>```

Install Newtonsoft.Json using below command (In NuGet package manager).

```<code>Install-Package Newtonsoft.Json
</code>```

To deserialize your JsonString to Object List as below.

```<code>List<string> listOfObjects = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Charge>>(yourJsonStringHere);
</code>```

For more Information about Newtonsoft.Json Please visit below link.

http://www.newtonsoft.com/json/help/html/Introduction.htm

Body:
I have Multidimensional array object How to loop all value in c# ?
in C#

charge[0]{[ChargeMultiId, da95aad9-0cdc-40bb-a5db-3bc0933dea4a ]}
charge[1]{[ChargeMultiNoteslist, Testing notes 29/04/2016 ]}
charge[22]{[Diagnosis, : ["1", "2", "3", "4", "5", "6", "7", "8", "9"]}

Ajax

    charge =
    "ChargeMultiId": "da95aad9-0cdc-40bb-a5db-3bc0933dea4a",
    "ChargeMultiNoteslist": "Testing notes 29/04/2016",
    "ChargeMultiCode": "99238",
    "ChargeMultiCodeName": "HOSP DSCHRG D MGMT 30 MIN/ < > & '",
    "ChargeMultiProcedureID": "89c5ecaf-903b-41d7-8564-e4034d94934f",
    "Diagnosis": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
}, {}
]

Body:
I think you should make the model class as below.

public class Charge
{
     public Guid ChargeMultiId { get; set; }
     public string ChargeMultiNoteslist { get; set; }
     public int ChargeMultiCode { get; set; }
     public string ChargeMultiCodeName { get; set; }
     public Guid ChargeMultiProcedureID { get; set; }
     public List<int> Diagnosis { get; set; }
}

Install Newtonsoft.Json using below command (In NuGet package manager).

Install-Package Newtonsoft.Json

To deserialize your JsonString to Object List as below.

List<string> listOfObjects = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Charge>>(yourJsonStringHere);

For more Information about Newtonsoft.Json Please visit below link.

http://www.newtonsoft.com/json/help/html/Introduction.htm


问:
Recycle Application Mod_Mono 2.8
I have a CentOS 5.x server running Mono 2.8.1 and mod_mono 2.8 with apache2.

Every time I deploy a site from visual studio 2010 to my server by ftp, and navigate to the site, I get a 404 not found error page.

Sites in other subdomains (virtual hosts) are not affected.

Performing a restart of httpd using /etc/init.d/httpd restart fixes the problem, and I can view my ASP site again. Obviously restarting the entire httpd process is less than adequate.

My guess is that this is similar to application domains in IIS. Is there a way to 'recycle' and app domain in mod_mono? Can I set this to happen on deployment?

答: You should be able to do /etc/init.d/httpd reload to force Apache to re-read its files from /etc/apache without it having to restart.

Title: Recycle Application Mod_Mono 2.8


问:
Ionic 2 Angularfire2 - add list of objects from database to FirebaseListObservable
I'm trying to display a list of objects in my Firebase Database, but I am having a hard time to add the objects to the FirebaseListObservable.

Here is my code:

```<code>    products: FirebaseListObservable<any[]>;

    this.db.list('products/' + this.user.uid, { preserveSnapshot: true})
                .subscribe(snapshots=>{
                  var jsonObject = [];
                  snapshots.forEach(snapshot => {
                    jsonObject.push(snapshot.val());
                  });
                  this.products = jsonObject;
    });
</code>```

The error I get is that I can't assigne any[] to a FirebaseListObservable.

This is my HTML:

```<code><ion-list>
    <ion-item class="text" *ngFor="let product of products | async">
      {{product}}
    </ion-item>
 </ion-list>
</code>```

My database looks like this:

答:
your products is FirebaseListObservable, however, your jsonObject is an array, so you can't let this.products = jsonObject

maybe you should do like the following:

```<code>products: Observable<any[]>;
this.products = this.db.list('products/' + this.user.uid, { preserveSnapshot: true})
            .map(snapshots=>{
             return snapshots.map(snapshot => {
                return snapshot.val();
              });
});
</code>```

Body:
I'm trying to display a list of objects in my Firebase Database, but I am having a hard time to add the objects to the FirebaseListObservable.

Here is my code:

    products: FirebaseListObservable<any[]>;

    this.db.list('products/' + this.user.uid, { preserveSnapshot: true})
                .subscribe(snapshots=>{
                  var jsonObject = [];
                  snapshots.forEach(snapshot => {
                    jsonObject.push(snapshot.val());
                  });
                  this.products = jsonObject;
    });

The error I get is that I can't assigne any[] to a FirebaseListObservable.

This is my HTML:

<ion-list>
    <ion-item class="text" *ngFor="let product of products | async">
      {{product}}
    </ion-item>
 </ion-list>

My database looks like this:

Body:
your products is FirebaseListObservable, however, your jsonObject is an array, so you can't let this.products = jsonObject

maybe you should do like the following:

products: Observable<any[]>;
this.products = this.db.list('products/' + this.user.uid, { preserveSnapshot: true})
            .map(snapshots=>{
             return snapshots.map(snapshot => {
                return snapshot.val();
              });
});


问:
grey out checkbox2 and checkbox3 unless checkbox1 = true
Another VBA dilemma for you.

I have checkbox1, checkbox2 and checkbox3.
I would like checkbox2 and checkbox3 to be greyed out if checkbox1=true
I have used a code similar for greying out a textbox

```<code>    Private Sub CheckBox1_Click()
    Dim en As Boolean
    en = Not CheckBox1.Value
    EnableControls Array(tbappgn, tbappfn), en

'utility sub: enable/disable controls
Private Sub EnableControls(cons, bEnable As Boolean)
    Dim con
    For Each con In cons
        With con
            .Enabled = bEnable
            .BackColor = IIf(bEnable, vbWhite, RGB(200, 200, 200))
        End With
    Next con
End Sub
</code>```

Just having an issue with getting the same code to work on other checkboxes.

Can add the checkbox numbers to the code above but I don't want that checkbox to be the trigger to grey/un grey the other checkboxes

something like this but with the correct terms.

```<code>Private Sub CheckBox11_Click()
 Dim en As Boolean
   en = Not CheckBox11.Value
    EnableControls Array(checkbox12, checkbox13), en

    Private Sub CheckBox15_Click()
    Dim en As Boolean
    en = Not CheckBox15.Value
    EnableControls Array(checkbox16, checkbox17), en

Private Sub EnableControls(cons, bEnable As Boolean)
    Dim con
    For Each con In cons
        With con
            .Enabled = bEnable
            .BackColor = IIf(bEnable, vbWhite, RGB(200, 200, 200))
        End With
    Next con
End Sub
</code>```

答:
Is this what you're asking for? When checkbox1 is true, the other will be grey... and vice versa... </p>

```<code>Private Sub CheckBox1_Click()
    If CheckBox1.Value = True Then
        CheckBox2.Enabled = False
        CheckBox3.Enabled = False
    Else
        CheckBox2.Enabled = True
        CheckBox3.Enabled = True
    End If
End Sub
</code>```

Body:
Another VBA dilemma for you.

I have checkbox1, checkbox2 and checkbox3.
I would like checkbox2 and checkbox3 to be greyed out if checkbox1=true
I have used a code similar for greying out a textbox

    Private Sub CheckBox1_Click()
    Dim en As Boolean
    en = Not CheckBox1.Value
    EnableControls Array(tbappgn, tbappfn), en

'utility sub: enable/disable controls
Private Sub EnableControls(cons, bEnable As Boolean)
    Dim con
    For Each con In cons
        With con
            .Enabled = bEnable
            .BackColor = IIf(bEnable, vbWhite, RGB(200, 200, 200))
        End With
    Next con
End Sub

Just having an issue with getting the same code to work on other checkboxes.

Can add the checkbox numbers to the code above but I don't want that checkbox to be the trigger to grey/un grey the other checkboxes

something like this but with the correct terms.

Private Sub CheckBox11_Click()
 Dim en As Boolean
   en = Not CheckBox11.Value
    EnableControls Array(checkbox12, checkbox13), en

    Private Sub CheckBox15_Click()
    Dim en As Boolean
    en = Not CheckBox15.Value
    EnableControls Array(checkbox16, checkbox17), en

Private Sub EnableControls(cons, bEnable As Boolean)
    Dim con
    For Each con In cons
        With con
            .Enabled = bEnable
            .BackColor = IIf(bEnable, vbWhite, RGB(200, 200, 200))
        End With
    Next con
End Sub

Body:
Is this what you're asking for? When checkbox1 is true, the other will be grey... and vice versa...

Private Sub CheckBox1_Click()
    If CheckBox1.Value = True Then
        CheckBox2.Enabled = False
        CheckBox3.Enabled = False
    Else
        CheckBox2.Enabled = True
        CheckBox3.Enabled = True
    End If
End Sub


问:
How to create buttons dynamicly based on file/folder structure in android
im new to android and im trying to make a "simple" app.
However i would like to know if, what i have planned, is possible in android.

Basicly it's a crude database reader/navigator.

I made a folder structure in the assets folder with a few directories and *.txt files.
Now the plan is to read/scan the folder structure on startup of the program and dynamicly create buttons labeld  based on the folder,- and file names.
The buttons have to link to the files and folders so the user can navigate the folder structure and open a *.txt file and read it. Also the idea is that the buttons reflect the folder structure as it is in the assets folder.

The idea is that the user can easly retrieve info from the app and i can add info to the app trough *.txt files  and adjust the structure just by adding/removing directories and files in the assets folder.

i am using android studio but like i already say'd: i am a beginner with programming and would like to know if this is even possible with android.
And if it is: could someone please tell me how i should start this project or link me to some example code on how this could be done?

Thanks in advance.

答:
If i read your idea correctly, what you are trying to achieve is very much possible. I would start looking at the AssetManager class and I believe what you are looking for is the list() command which should give you what you need.

https://developer.android.com/reference/android/content/res/AssetManager.html

You can obtain the AssetManager from everywhere within your app through the Context object which you will find to be everywhere around. ;)

From there on you can build your hierarchy and open files.

There are some useful wizard projects in Android studio, which will basically setup a general structure of an Android App. I would recommend starting with a Single Activity application and move on from there.


问:
HTML table with JSON
I have a different format of JSON below, I need to put it with HTML table and display it. I need to do this in AngularJS. I tried with normal JSON format it was working fine but for this JSON it's not working. This example is for indexing search, so I need to maintain JSON like that.

For example:

                Name
                Position
                Office

       {{x.Name}}
       {{x.City}}
       {{x.Country}}

```

<p>Now I need to do the same thing with the below JSON format:</p>

<pre class="lang-js prettyprint-override"><code>{
    "data": [
            [
                "1",
                "supply chain Management",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "1"

            ],

            [
                "2",
                "Data Tower",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "2"
            ],
            [
                "3",
                "Enter business",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "3"
            ],
            [
                "4",
                "IOT",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "4"
            ],
            [
                "5",
                "Supplys Chain",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "5"
            ],
            [
                "6",
                "Supplys Chain",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "6"
            ]

        ]
    }
</code>```

答:
Let's call the second object "dataObj". dataObj.data holds an array of arrays, which is why a simple ng-repeat won't work on it.

dataObj.data[0][0] would return:

  "1",
  "supply chain Management",
  "https://www.google.co.in/",
  "abc",
  1234567,
  "abc@gmail.com",
  "assdadsddsf",
  "1"```

$scope.names is an array of objects. If you change the dataObj to an array of objects as well, it will work!

Title: HTML table with JSON

Body:
I have a different format of JSON below, I need to put it with HTML table and display it. I need to do this in AngularJS. I tried with normal JSON format it was working fine but for this JSON it's not working. This example is for indexing search, so I need to maintain JSON like that.

For example:

                Name
                Position
                Office

       {{x.Name}}
       {{x.City}}
       {{x.Country}}

Now I need to do the same thing with the below JSON format:

{
    "data": [
            [
                "1",
                "supply chain Management",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "1"

            ],

            [
                "2",
                "Data Tower",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "2"
            ],
            [
                "3",
                "Enter business",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "3"
            ],
            [
                "4",
                "IOT",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "4"
            ],
            [
                "5",
                "Supplys Chain",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "5"
            ],
            [
                "6",
                "Supplys Chain",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "6"
            ]

        ]
    }

Body:
Let's call the second object "dataObj". dataObj.data holds an array of arrays, which is why a simple ng-repeat won't work on it.

dataObj.data[0][0] would return:

  "1",
  "supply chain Management",
  "https://www.google.co.in/",
  "abc",
  1234567,
  "abc@gmail.com",
  "assdadsddsf",
  "1"

$scope.names is an array of objects. If you change the dataObj to an array of objects as well, it will work!


问:
PHP User Set Display Order
I am trying to build a CMS and was wondering how I can have it so the user on the backend can dynamically set the pages display order. I know with MySQL how to the ORDER BY but I want the user to able to say this page should be first, etc. I am not even sure how to approach this so any help would be greatly appreciated! Thanks!</p>

答: Just add an 'order' INT field to your 'pages' table, or where ever you are storing the data for those. Then just give the user the option of editing that somehow, such as drag n' dropping the page, then, when setting up the navigation, just order by the order field.</p>

Title: PHP User Set Display Order


问:
Java how to reset "set" values after being changed
```<code>public static void reset() {
        //goblin
        stats gob = new stats();
        gob.setName("Goblin");
        gob.setHP(15);
        gob.setATK(3);
        //END-goblin

        //orc
        stats orc = new stats();
        orc.setName("Orc");
        orc.setHP(25);
        orc.setATK(5);
        //END-orc

        stats[] enemies = new stats[3];
        enemies[1] = new stats();
        enemies[1] = gob;
        enemies[1].getName();
        enemies[1].getHP();
        enemies[1].getATK();
        enemies[2] = new stats();
        enemies[2] = orc;
        enemies[2].getName();
        enemies[2].getHP();
        enemies[2].getATK();
    }

    public static void fight() {

        //user
        player user = new player();
        user.setP_Name(username);
        user.setP_ATK(atk);
        user.setP_HP(hp);
        //END-user

        //goblin
        stats gob = new stats();
        gob.setName("Goblin");
        gob.setHP(15);
        gob.setATK(3);
        //END-goblin

        //orc
        stats orc = new stats();
        orc.setName("Orc");
        orc.setHP(25);
        orc.setATK(5);
        //END-orc

        stats[] enemies = new stats[3];
        enemies[1] = new stats();
        enemies[1] = gob;
        enemies[1].getName();
        enemies[1].getHP();
        enemies[1].getATK();
        enemies[2] = new stats();
        enemies[2] = orc;
        enemies[2].getName();
        enemies[2].getHP();
        enemies[2].getATK();

        System.out.println("\u001B[32m" + "\nWelcome to Gilenor, " + user.getP_Name() + "." + "\u001B[39m"
                + "\u001B[32m" + "\nIn this world, you will fight monsters consecutively," + "\u001B[39m"
                + "\u001B[32m" + "\nattempting to get through all of them." + "\u001B[39m"
                + "\u001B[32m" + "\nFor each enemy you kill, you will grow stronger." + "\u001B[39m"
                + "\u001B[32m" + "\nFlee to go back to the past enemy, but do not flee on your first enemy!" + "\u001B[39m"
                + "\u001B[32m" + "\nA fair warning to you, " + user.getP_Name() + ":" + "\u001B[39m"
                + "\u001B[32m" + "\nEach monster gets stronger after every win. Good luck!" + "\u001B[39m");

        int answer = 0;
        int d;
        int e;
        boolean alive;

        int i;
        for (i = 1; i < 3; i++) {

            System.out.print("\n");

            System.out.println(enemies[i].getName() + " has appeared!");

            System.out.print("\n");

            alive = true;

            while (alive == true) {

                reset();

                System.out.println(enemies[i].getName() + " stats:");
                System.out.println("Hitpoints[HP]: " + enemies[i].getHP());
                System.out.println("Attack[ATK]  : " + enemies[i].getATK());
                System.out.print("\n");

                if (user.getP_HP() > 0) {
                    System.out.println("\u001B[34m" + "[1 - Attack]" + "\u001B[39m");
                    System.out.println("\u001B[34m" + "[2 - Flee]" + "\u001B[39m");

                    answer = In.getInt();

                    clrscr();

                    System.out.print("\n");
                } else if (user.getP_HP() <= 0) {
                    System.out.println(user.getP_Name() + " has been slain by the " + enemies[i].getName() + "!");
                    return;
                }

                if (answer == 1) {

                    d = enemies[i].getHP() - user.getP_ATK();
                    enemies[i].setHP(d);

                    System.out.println(user.getP_Name() + " strikes the " + enemies[i].getName() + " for " + user.getP_ATK() + " damage.");
                    System.out.println(enemies[i].getName() + " has " + enemies[i].getHP() + " HP remaining.");
                    System.out.print("\n");

                    if (enemies[i].getHP() > 0) {
                        e = user.getP_HP() - enemies[i].getATK();
                        user.setP_HP(e);

                        System.out.println("The " + enemies[i].getName() + " attacked " + user.getP_Name() + "for " + enemies[i].getATK() + " damage.");
                        System.out.println(user.getP_Name() + " has " + user.getP_HP() + " HP remaining.");
                        System.out.println("\n");
                    } else if (enemies[1].getHP() <= 0) {

                        System.out.println("\u001B[32m" + user.getP_Name() + " has slain the " + enemies[i].getName() + "!" + "\u001B[39m"
                                + "\u001B[32m" + "\nYou have gained " + (i * 1) + " attack and " + i * 10 + " HP!" + "\u001B[39m");

                        user.setP_ATK(user.getP_ATK() + (i * 1));
                        user.setP_HP(user.getP_HP() + (i * 10));

                        alive = false;
                    }

                } else if (answer == 2) {
                    if (i == 1) {
                        System.out.println("You ran from your first enemy, tripped, then died! How embarassing!");
                        alive = false;
                        return;
                    } else {
                        System.out.println("You ran away, back to the last monster you saw!");
                        System.out.print("\n");
                        i = (i - 1);
                    }
                }
            }
        }
    } //fight method
</code>```

In this code, I set values for objects and then put them into an array called

enemies. Afterwards, I change the value of the elements of the objects using the

enemies array. After the "HP" value of the element array reaches zero, it goes

onto the next element. I made it so the user can go back to the previous element

and re-do it, but the element still has the same values as when the user first

altered them. I put all the "set" and enemies arrays which originally defined

the value into a method and tried calling it so it can reset, but I wasn't in

luck. Is there any way I can properly do this?

EDIT:

For those wondering, this is my cheap workaround:

```<code>public static void fight() {

    //user
    player user = new player();
    user.setP_Name(username);
    user.setP_ATK(atk);
    user.setP_HP(hp);
    //END-user

    System.out.println("\u001B[32m" + "\nWelcome to Gilenor, " + user.getP_Name() + "." + "\u001B[39m"
            + "\u001B[32m" + "\nIn this world, you will fight monsters consecutively," + "\u001B[39m"
            + "\u001B[32m" + "\nattempting to get through all of them." + "\u001B[39m"
            + "\u001B[32m" + "\nFor each enemy you kill, you will grow stronger." + "\u001B[39m"
            + "\u001B[32m" + "\nFlee to go back to the past enemy, but do not flee on your first enemy!" + "\u001B[39m"
            + "\u001B[32m" + "\nA fair warning to you, " + user.getP_Name() + ":" + "\u001B[39m"
            + "\u001B[32m" + "\nEach monster gets stronger after every win. Good luck!" + "\u001B[39m");

    int answer = 0;
    int d;
    int e;
    boolean alive;

    int i;
    for (i = 1; i < 6; i++) { //CHEAP WORKAROUND
        //goblin1
        stats gob = new stats();
        gob.setName("Goblin");
        gob.setHP(15);
        gob.setATK(3);
        //END-goblin
        //orc2
        stats orc = new stats();
        orc.setName("Orc");
        orc.setHP(25);
        orc.setATK(5);
        //END-orc
        //pheonix3
        stats pheonix = new stats();
        pheonix.setName("Pheonix");
        pheonix.setHP(75);
        pheonix.setATK(5);
        //END-pheonix
        //ancient dragon4
        stats ancdr = new stats();
        ancdr.setName("Ancient Dragon");
        ancdr.setHP(220);
        ancdr.setATK(13);
        //END-ancient dragon
        //hades5
        stats hades = new stats();
        hades.setName("Hades");
        hades.setHP(500);
        hades.setATK(25);
        //END-hades
        stats[] enemies = new stats[6];
        enemies[1] = new stats();
        enemies[2] = new stats();
        enemies[3] = new stats();
        enemies[1] = gob;
        enemies[2] = orc;
        enemies[3] = pheonix;
        enemies[4] = ancdr;
        enemies[5] = hades;
        enemies[1].getName();
        enemies[2].getName();
        enemies[3].getName();
        enemies[4].getName();
        enemies[5].getName();
        enemies[1].getHP();
        enemies[2].getHP();
        enemies[3].getHP();
        enemies[4].getHP();
        enemies[5].getHP();
        enemies[1].getATK();
        enemies[2].getATK();
        enemies[3].getATK();
        enemies[4].getATK();
        enemies[5].getATK(); //CHEAP WORKAROUND

        System.out.print("\n");

        System.out.println(enemies[i].getName() + " has appeared!");

        System.out.print("\n");

        alive = true;

        while (alive == true) {

            System.out.println(enemies[i].getName() + " stats:");
            System.out.println("Hitpoints[HP]: " + enemies[i].getHP());
            System.out.println("Attack[ATK]  : " + enemies[i].getATK());
            System.out.print("\n");

            if (user.getP_HP() > 0) {
                System.out.println("\u001B[34m" + "[1 - Attack]" + "\u001B[39m");
                System.out.println("\u001B[34m" + "[2 - Flee]" + "\u001B[39m");

                answer = In.getInt();

                clrscr();

                System.out.print("\n");
            } else if (user.getP_HP() <= 0) {
                System.out.println(user.getP_Name() + " has been slain by the " + enemies[i].getName() + "!");
                return;
            }

            if (answer == 1) {

                d = enemies[i].getHP() - user.getP_ATK();
                enemies[i].setHP(d);

                System.out.println(user.getP_Name() + " strikes the " + enemies[i].getName() + " for " + user.getP_ATK() + " damage.");
                System.out.println(enemies[i].getName() + " has " + enemies[i].getHP() + " HP remaining.");
                System.out.print("\n");

                if (enemies[i].getHP() > 0) {
                    e = user.getP_HP() - enemies[i].getATK();
                    user.setP_HP(e);

                    System.out.println("The " + enemies[i].getName() + " attacked " + user.getP_Name() + " for " + enemies[i].getATK() + " damage.");
                    System.out.println(user.getP_Name() + " has " + user.getP_HP() + " HP remaining.");
                    System.out.println("\n");
                } else if (enemies[1].getHP() <= 0) {

                    System.out.println("\u001B[32m" + user.getP_Name() + " has slain the " + enemies[i].getName() + "!" + "\u001B[39m"
                            + "\u001B[32m" + "\nYou have gained " + (i * 1) + " attack and " + i * 10 + " HP!" + "\u001B[39m");

                    user.setP_ATK(user.getP_ATK() + (i * 1));
                    user.setP_HP(user.getP_HP() + (i * 10));

                    alive = false;
                }

            } else if (answer == 2) {
                if (i == 1) {
                    System.out.println("You ran from your first enemy, tripped, then died! How embarassing!");
                    alive = false;
                    return;
                } else {
                    System.out.println("You ran away, back to the last monster you saw!");
                    System.out.print("\n");
                    i = (i - 1);
                }
            }
        }
    }
} //fight method
</code>```

答:
So many things here just don't make sense:

In the reset function:

```<code>// This stats[] array is local, it won't effect the one out side of the function...
stats[] enemies = new stats[3]; // Why size 3 if only use 2? first index is 0.
enemies[1] = new stats(); // This new stats instance will be override next line, so it have no effect.
enemies[1] = gob; // here you share reference to the gob instance, not copying it. so any change on 'enemies[1]' will in fact be apply on gob.
enemies[1].getName(); // Do nothing...
enemies[1].getHP(); // Do nothing...
enemies[1].getATK(); // Do nothing...
enemies[2] = new stats();
enemies[2] = orc;
enemies[2].getName();
enemies[2].getHP();
enemies[2].getATK();
</code>```

And this is just by glancing on the first function, checking the rest make even less sense. sorry, but if you have more specific question I will be happy to answer.

Body:
public static void reset() {
        //goblin
        stats gob = new stats();
        gob.setName("Goblin");
        gob.setHP(15);
        gob.setATK(3);
        //END-goblin

        //orc
        stats orc = new stats();
        orc.setName("Orc");
        orc.setHP(25);
        orc.setATK(5);
        //END-orc

        stats[] enemies = new stats[3];
        enemies[1] = new stats();
        enemies[1] = gob;
        enemies[1].getName();
        enemies[1].getHP();
        enemies[1].getATK();
        enemies[2] = new stats();
        enemies[2] = orc;
        enemies[2].getName();
        enemies[2].getHP();
        enemies[2].getATK();
    }

    public static void fight() {

        //user
        player user = new player();
        user.setP_Name(username);
        user.setP_ATK(atk);
        user.setP_HP(hp);
        //END-user

        //goblin
        stats gob = new stats();
        gob.setName("Goblin");
        gob.setHP(15);
        gob.setATK(3);
        //END-goblin

        //orc
        stats orc = new stats();
        orc.setName("Orc");
        orc.setHP(25);
        orc.setATK(5);
        //END-orc

        stats[] enemies = new stats[3];
        enemies[1] = new stats();
        enemies[1] = gob;
        enemies[1].getName();
        enemies[1].getHP();
        enemies[1].getATK();
        enemies[2] = new stats();
        enemies[2] = orc;
        enemies[2].getName();
        enemies[2].getHP();
        enemies[2].getATK();

        System.out.println("\u001B[32m" + "\nWelcome to Gilenor, " + user.getP_Name() + "." + "\u001B[39m"
                + "\u001B[32m" + "\nIn this world, you will fight monsters consecutively," + "\u001B[39m"
                + "\u001B[32m" + "\nattempting to get through all of them." + "\u001B[39m"
                + "\u001B[32m" + "\nFor each enemy you kill, you will grow stronger." + "\u001B[39m"
                + "\u001B[32m" + "\nFlee to go back to the past enemy, but do not flee on your first enemy!" + "\u001B[39m"
                + "\u001B[32m" + "\nA fair warning to you, " + user.getP_Name() + ":" + "\u001B[39m"
                + "\u001B[32m" + "\nEach monster gets stronger after every win. Good luck!" + "\u001B[39m");

        int answer = 0;
        int d;
        int e;
        boolean alive;

        int i;
        for (i = 1; i < 3; i++) {

            System.out.print("\n");

            System.out.println(enemies[i].getName() + " has appeared!");

            System.out.print("\n");

            alive = true;

            while (alive == true) {

                reset();

                System.out.println(enemies[i].getName() + " stats:");
                System.out.println("Hitpoints[HP]: " + enemies[i].getHP());
                System.out.println("Attack[ATK]  : " + enemies[i].getATK());
                System.out.print("\n");

                if (user.getP_HP() > 0) {
                    System.out.println("\u001B[34m" + "[1 - Attack]" + "\u001B[39m");
                    System.out.println("\u001B[34m" + "[2 - Flee]" + "\u001B[39m");

                    answer = In.getInt();

                    clrscr();

                    System.out.print("\n");
                } else if (user.getP_HP() <= 0) {
                    System.out.println(user.getP_Name() + " has been slain by the " + enemies[i].getName() + "!");
                    return;
                }

                if (answer == 1) {

                    d = enemies[i].getHP() - user.getP_ATK();
                    enemies[i].setHP(d);

                    System.out.println(user.getP_Name() + " strikes the " + enemies[i].getName() + " for " + user.getP_ATK() + " damage.");
                    System.out.println(enemies[i].getName() + " has " + enemies[i].getHP() + " HP remaining.");
                    System.out.print("\n");

                    if (enemies[i].getHP() > 0) {
                        e = user.getP_HP() - enemies[i].getATK();
                        user.setP_HP(e);

                        System.out.println("The " + enemies[i].getName() + " attacked " + user.getP_Name() + "for " + enemies[i].getATK() + " damage.");
                        System.out.println(user.getP_Name() + " has " + user.getP_HP() + " HP remaining.");
                        System.out.println("\n");
                    } else if (enemies[1].getHP() <= 0) {

                        System.out.println("\u001B[32m" + user.getP_Name() + " has slain the " + enemies[i].getName() + "!" + "\u001B[39m"
                                + "\u001B[32m" + "\nYou have gained " + (i * 1) + " attack and " + i * 10 + " HP!" + "\u001B[39m");

                        user.setP_ATK(user.getP_ATK() + (i * 1));
                        user.setP_HP(user.getP_HP() + (i * 10));

                        alive = false;
                    }

                } else if (answer == 2) {
                    if (i == 1) {
                        System.out.println("You ran from your first enemy, tripped, then died! How embarassing!");
                        alive = false;
                        return;
                    } else {
                        System.out.println("You ran away, back to the last monster you saw!");
                        System.out.print("\n");
                        i = (i - 1);
                    }
                }
            }
        }
    } //fight method

In this code, I set values for objects and then put them into an array called

enemies. Afterwards, I change the value of the elements of the objects using the

enemies array. After the "HP" value of the element array reaches zero, it goes

onto the next element. I made it so the user can go back to the previous element

and re-do it, but the element still has the same values as when the user first

altered them. I put all the "set" and enemies arrays which originally defined

the value into a method and tried calling it so it can reset, but I wasn't in

luck. Is there any way I can properly do this?

EDIT:

For those wondering, this is my cheap workaround:

public static void fight() {

    //user
    player user = new player();
    user.setP_Name(username);
    user.setP_ATK(atk);
    user.setP_HP(hp);
    //END-user

    System.out.println("\u001B[32m" + "\nWelcome to Gilenor, " + user.getP_Name() + "." + "\u001B[39m"
            + "\u001B[32m" + "\nIn this world, you will fight monsters consecutively," + "\u001B[39m"
            + "\u001B[32m" + "\nattempting to get through all of them." + "\u001B[39m"
            + "\u001B[32m" + "\nFor each enemy you kill, you will grow stronger." + "\u001B[39m"
            + "\u001B[32m" + "\nFlee to go back to the past enemy, but do not flee on your first enemy!" + "\u001B[39m"
            + "\u001B[32m" + "\nA fair warning to you, " + user.getP_Name() + ":" + "\u001B[39m"
            + "\u001B[32m" + "\nEach monster gets stronger after every win. Good luck!" + "\u001B[39m");

    int answer = 0;
    int d;
    int e;
    boolean alive;

    int i;
    for (i = 1; i < 6; i++) { //CHEAP WORKAROUND
        //goblin1
        stats gob = new stats();
        gob.setName("Goblin");
        gob.setHP(15);
        gob.setATK(3);
        //END-goblin
        //orc2
        stats orc = new stats();
        orc.setName("Orc");
        orc.setHP(25);
        orc.setATK(5);
        //END-orc
        //pheonix3
        stats pheonix = new stats();
        pheonix.setName("Pheonix");
        pheonix.setHP(75);
        pheonix.setATK(5);
        //END-pheonix
        //ancient dragon4
        stats ancdr = new stats();
        ancdr.setName("Ancient Dragon");
        ancdr.setHP(220);
        ancdr.setATK(13);
        //END-ancient dragon
        //hades5
        stats hades = new stats();
        hades.setName("Hades");
        hades.setHP(500);
        hades.setATK(25);
        //END-hades
        stats[] enemies = new stats[6];
        enemies[1] = new stats();
        enemies[2] = new stats();
        enemies[3] = new stats();
        enemies[1] = gob;
        enemies[2] = orc;
        enemies[3] = pheonix;
        enemies[4] = ancdr;
        enemies[5] = hades;
        enemies[1].getName();
        enemies[2].getName();
        enemies[3].getName();
        enemies[4].getName();
        enemies[5].getName();
        enemies[1].getHP();
        enemies[2].getHP();
        enemies[3].getHP();
        enemies[4].getHP();
        enemies[5].getHP();
        enemies[1].getATK();
        enemies[2].getATK();
        enemies[3].getATK();
        enemies[4].getATK();
        enemies[5].getATK(); //CHEAP WORKAROUND

        System.out.print("\n");

        System.out.println(enemies[i].getName() + " has appeared!");

        System.out.print("\n");

        alive = true;

        while (alive == true) {

            System.out.println(enemies[i].getName() + " stats:");
            System.out.println("Hitpoints[HP]: " + enemies[i].getHP());
            System.out.println("Attack[ATK]  : " + enemies[i].getATK());
            System.out.print("\n");

            if (user.getP_HP() > 0) {
                System.out.println("\u001B[34m" + "[1 - Attack]" + "\u001B[39m");
                System.out.println("\u001B[34m" + "[2 - Flee]" + "\u001B[39m");

                answer = In.getInt();

                clrscr();

                System.out.print("\n");
            } else if (user.getP_HP() <= 0) {
                System.out.println(user.getP_Name() + " has been slain by the " + enemies[i].getName() + "!");
                return;
            }

            if (answer == 1) {

                d = enemies[i].getHP() - user.getP_ATK();
                enemies[i].setHP(d);

                System.out.println(user.getP_Name() + " strikes the " + enemies[i].getName() + " for " + user.getP_ATK() + " damage.");
                System.out.println(enemies[i].getName() + " has " + enemies[i].getHP() + " HP remaining.");
                System.out.print("\n");

                if (enemies[i].getHP() > 0) {
                    e = user.getP_HP() - enemies[i].getATK();
                    user.setP_HP(e);

                    System.out.println("The " + enemies[i].getName() + " attacked " + user.getP_Name() + " for " + enemies[i].getATK() + " damage.");
                    System.out.println(user.getP_Name() + " has " + user.getP_HP() + " HP remaining.");
                    System.out.println("\n");
                } else if (enemies[1].getHP() <= 0) {

                    System.out.println("\u001B[32m" + user.getP_Name() + " has slain the " + enemies[i].getName() + "!" + "\u001B[39m"
                            + "\u001B[32m" + "\nYou have gained " + (i * 1) + " attack and " + i * 10 + " HP!" + "\u001B[39m");

                    user.setP_ATK(user.getP_ATK() + (i * 1));
                    user.setP_HP(user.getP_HP() + (i * 10));

                    alive = false;
                }

            } else if (answer == 2) {
                if (i == 1) {
                    System.out.println("You ran from your first enemy, tripped, then died! How embarassing!");
                    alive = false;
                    return;
                } else {
                    System.out.println("You ran away, back to the last monster you saw!");
                    System.out.print("\n");
                    i = (i - 1);
                }
            }
        }
    }
} //fight method

Body:
So many things here just don't make sense:

In the reset function:

// This stats[] array is local, it won't effect the one out side of the function...
stats[] enemies = new stats[3]; // Why size 3 if only use 2? first index is 0.
enemies[1] = new stats(); // This new stats instance will be override next line, so it have no effect.
enemies[1] = gob; // here you share reference to the gob instance, not copying it. so any change on 'enemies[1]' will in fact be apply on gob.
enemies[1].getName(); // Do nothing...
enemies[1].getHP(); // Do nothing...
enemies[1].getATK(); // Do nothing...
enemies[2] = new stats();
enemies[2] = orc;
enemies[2].getName();
enemies[2].getHP();
enemies[2].getATK();

And this is just by glancing on the first function, checking the rest make even less sense. sorry, but if you have more specific question I will be happy to answer.


问:
Place 3 buttons in a LinearLayout to occupy equal amount of space
i would like to have three buttons taking equal amount of available space horizontally in a row.
I used android:layout_gravity. What is the problem?

layout xml :

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="1.0"
    >

    <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/Bg"
            android:background="@drawable/button_red"
            android:layout_weight=".2"
            android:layout_gravity="left"
    />
    <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/Bm"
            android:background="@drawable/button_red"
            android:layout_weight=".2"
            android:textColor="#ffffff"
            android:layout_gravity="center"
    />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/button_red"
        android:layout_weight=".2"
        android:text="@string/Bf"
        android:layout_gravity="right"
    />

</LinearLayout>
</code>```

if someone see whats wrong, thanks.

答:
Please consider the following layout snippet:

```<code><LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="3">

    <ImageView
        android:src="@drawable/logo1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="left|center_vertical" />

    <TextView
        android:id="@+id/toolbar_title"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Some Title"
        android:textColor="@android:color/black"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_weight="1" />

    <ImageView
        android:src="@drawable/logo2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="right|center_vertical" />

</LinearLayout>
</code>```

2 things to note above.

A. I created a LinearLayout with weightSum of 3.

B. Then inside that I create 3 elements each having layout_weight of 1 so that I can have my child elements distribute the entire space among themselves evenly.

Body:
i would like to have three buttons taking equal amount of available space horizontally in a row.
I used android:layout_gravity. What is the problem?

layout xml :

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="1.0"
    >

    <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/Bg"
            android:background="@drawable/button_red"
            android:layout_weight=".2"
            android:layout_gravity="left"
    />
    <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/Bm"
            android:background="@drawable/button_red"
            android:layout_weight=".2"
            android:textColor="#ffffff"
            android:layout_gravity="center"
    />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/button_red"
        android:layout_weight=".2"
        android:text="@string/Bf"
        android:layout_gravity="right"
    />

</LinearLayout>

if someone see whats wrong, thanks.

Body:
Please consider the following layout snippet:

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="3">

    <ImageView
        android:src="@drawable/logo1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="left|center_vertical" />

    <TextView
        android:id="@+id/toolbar_title"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Some Title"
        android:textColor="@android:color/black"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_weight="1" />

    <ImageView
        android:src="@drawable/logo2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="right|center_vertical" />

</LinearLayout>

2 things to note above.

A. I created a LinearLayout with weightSum of 3.

B. Then inside that I create 3 elements each having layout_weight of 1 so that I can have my child elements distribute the entire space among themselves evenly.