问:
Concatenating two existing columns within a new query
I have this query below that parses names within columns based on specific criteria. I would like to augment this query in order to contain a new row that will include a concatenation of two columns from the mk_kw table.

```<code>insert into mk_kw
with a(v) as (
select "Campaign"
from adwords_raw
), pre as (
select split_part(v, '{', 1) a,split_part(v, '{', 2) b
from a)
select
split_part(a, '-', 1) ca,
split_part(a, '-', 2) cb,
split_part(split_part(a, '-', 3), '|', 1) cc,
split_part(split_part(a, '-', 3),
split_part(split_part(a, '-', 3), '|', 1) || '|', 2) cd,
'{' || b ce
from pre;
</code>```

The current input table looks like the following,  "Campaign" being the current column in action

```<code>Campaign                           |Adgroup |
-----------------------------------+--------+
ES-SRC-IOT|Connectivity|SIM|USA|{e}|Watches |
</code>```

The current output of this looks like the following

```<code> ca | cb  |    cc     |             cd             |  ce
----+-----+-----------+----------------------------+------
 ES | SRC | IOT       |  Connectivity | SIM | USA  | {e}
</code>```

I would like to add a concatenation in this formula that would create this as an output

```<code> ca|cb |cc |cd                  |ce |Campaign&AdGroup
---+---+---+--------------------+---+------------------------------
 ES|SRC|IOT|Connectivity|SIM|USA|{e}|ES-SRC-IOT|Connectivity|SIM|USA
   |   |   |                    |   |{e}Watches
</code>```

Is it possible to add this concatenation or would I have to scrap this query entirely?

Cheers.

答:
Try this</p>

```<code>insert into mk_kw
with a(v,a) as (
select "Campaign","Adgroup"
from adwords_raw
), pre as (
select split_part(v, '{', 1) a,split_part(v, '{', 2) b,v||a as Campaign&AdGroup
from a)
select
split_part(a, '-', 1) ca,
split_part(a, '-', 2) cb,
split_part(split_part(a, '-', 3), '|', 1) cc,
split_part(split_part(a, '-', 3),
split_part(split_part(a, '-', 3), '|', 1) || '|', 2) cd,
'{' || b ce,
Campaign&AdGroup
from pre;
</code>```

Body:
I have this query below that parses names within columns based on specific criteria. I would like to augment this query in order to contain a new row that will include a concatenation of two columns from the mk_kw table.

insert into mk_kw
with a(v) as (
select "Campaign"
from adwords_raw
), pre as (
select split_part(v, '{', 1) a,split_part(v, '{', 2) b
from a)
select
split_part(a, '-', 1) ca,
split_part(a, '-', 2) cb,
split_part(split_part(a, '-', 3), '|', 1) cc,
split_part(split_part(a, '-', 3),
split_part(split_part(a, '-', 3), '|', 1) || '|', 2) cd,
'{' || b ce
from pre;

The current input table looks like the following,  "Campaign" being the current column in action

Campaign                           |Adgroup |
-----------------------------------+--------+
ES-SRC-IOT|Connectivity|SIM|USA|{e}|Watches |

The current output of this looks like the following

 ca | cb  |    cc     |             cd             |  ce
----+-----+-----------+----------------------------+------
 ES | SRC | IOT       |  Connectivity | SIM | USA  | {e}

I would like to add a concatenation in this formula that would create this as an output

 ca|cb |cc |cd                  |ce |Campaign&AdGroup
---+---+---+--------------------+---+------------------------------
 ES|SRC|IOT|Connectivity|SIM|USA|{e}|ES-SRC-IOT|Connectivity|SIM|USA
   |   |   |                    |   |{e}Watches

Is it possible to add this concatenation or would I have to scrap this query entirely?

Cheers.

Body:
Try this

insert into mk_kw
with a(v,a) as (
select "Campaign","Adgroup"
from adwords_raw
), pre as (
select split_part(v, '{', 1) a,split_part(v, '{', 2) b,v||a as Campaign&AdGroup
from a)
select
split_part(a, '-', 1) ca,
split_part(a, '-', 2) cb,
split_part(split_part(a, '-', 3), '|', 1) cc,
split_part(split_part(a, '-', 3),
split_part(split_part(a, '-', 3), '|', 1) || '|', 2) cd,
'{' || b ce,
Campaign&AdGroup
from pre;


来源: stackexchange

问:
PL/SQL use a value declared for setting a sequence start
I'm new in PL/SQL in Oracle and what I've tried so far doesn't work

I want to get the max(id) of my table... And then create a SEQUENCE which starts with this maxID+1

```<code>DECLARE maxId NUMBER;

BEGIN
  SELECT max(id)+1 INTO maxId FROM TABLE;
  CREATE SEQUENCE "DB"."SEQ_TABLE"  MINVALUE 1 MAXVALUE 999999 INCREMENT BY 1 START WITH maxId CACHE 20 NOORDER NOCYCLE;
END;
/
</code>```

But I can't use CREATE here ...

How can I achieve this ?

答:
Thanks for your help but finnaly I've found my way !

I did like so :

```<code>DECLARE maxId NUMBER;

BEGIN
  SELECT max(id)+1 INTO maxId FROM TABLE;
  execute immediate 'CREATE SEQUENCE  "DB"."SEQ_TABLE"  MINVALUE 1 MAXVALUE 9999999999 INCREMENT BY 1 START WITH '|| maxId ||' CACHE 20 NOORDER  NOCYCLE';
END;
  /
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm new in PL/SQL in Oracle and what I've tried so far doesn't work

I want to get the max(id) of my table... And then create a SEQUENCE which starts with this maxID+1

DECLARE maxId NUMBER;

BEGIN
  SELECT max(id)+1 INTO maxId FROM TABLE;
  CREATE SEQUENCE "DB"."SEQ_TABLE"  MINVALUE 1 MAXVALUE 999999 INCREMENT BY 1 START WITH maxId CACHE 20 NOORDER NOCYCLE;
END;
/

But I can't use CREATE here ...

How can I achieve this ?

Body:
Thanks for your help but finnaly I've found my way !

I did like so :

DECLARE maxId NUMBER;

BEGIN
  SELECT max(id)+1 INTO maxId FROM TABLE;
  execute immediate 'CREATE SEQUENCE  "DB"."SEQ_TABLE"  MINVALUE 1 MAXVALUE 9999999999 INCREMENT BY 1 START WITH '|| maxId ||' CACHE 20 NOORDER  NOCYCLE';
END;
  /


问:
node-red call node function from nodes, like call common function
I have 2 nodes, which needs to call one function - it's common place in programming.

I suppose, there is no way in node-red to call the function, except "wiring" Function nodes sequentially.

Well, I did try it, but with no success.

Please look(copy_paste) at my flow and give help:

```<code>[{"id":"d86b4b3b.0670d8","type":"inject","z":"901492e5.e9666","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"x":169,"y":224,"wires":[["1a6b10c8.0788cf"]]},{"id":"1a6b10c8.0788cf","type":"function","z":"901492e5.e9666","name":"func0","func":"if(msg.payload.second_call){return [null,msg];}\nelse {msg.payload[\"second_call\"] = true;\nmsg.payload[\"count\"] = 0;\nreturn [msg,null];\n}\n","outputs":"2","noerr":0,"x":350,"y":223,"wires":[["577ae7e1.0c1948"],["b2204e3f.44cef"]]},{"id":"577ae7e1.0c1948","type":"function","z":"901492e5.e9666","name":"func1","func":"msg.payload.count++;\nreturn msg;","outputs":1,"noerr":0,"x":352,"y":316,"wires":[["1a6b10c8.0788cf"]]},{"id":"4e8f3348.10ab0c","type":"debug","z":"901492e5.e9666","name":"","active":true,"console":"false","complete":"payload","x":783.5,"y":332,"wires":[]},{"id":"b2204e3f.44cef","type":"function","z":"901492e5.e9666","name":"func3","func":"msg.payload.count++;\nreturn msg;","outputs":1,"noerr":0,"x":619,"y":332,"wires":[["4e8f3348.10ab0c"]]},{"id":"5bf50c74.5376e4","type":"inject","z":"901492e5.e9666","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"x":160,"y":422,"wires":[["c9b5e6b.ae91818"]]},{"id":"c9b5e6b.ae91818","type":"function","z":"901492e5.e9666","name":"func10","func":"if(msg.payload.second_call){return [null,msg];}\nelse {msg.payload[\"second_call\"] = true;\nmsg.payload[\"count\"] = 0;\nreturn [msg,null];\n}\n","outputs":"2","noerr":0,"x":345,"y":422,"wires":[["f11eb781.083348"],["b2204e3f.44cef"]]},{"id":"f11eb781.083348","type":"function","z":"901492e5.e9666","name":"func11","func":"msg.payload.count+=10;\nreturn msg;","outputs":1,"noerr":0,"x":348,"y":508,"wires":[["c9b5e6b.ae91818"]]}]
</code>```

答:
There are a few of options here.

If you are going to use the "function" multiple time then you could wrap it up in a sub-flow. This means that there is one copy of the code to edit and you can chain this into flows that do not have a common end.

If you are not going to have to change the "function" at all once it's written you can add it to the functionGlobalContext in the settings.js. This will let you include it in a given function node. See the doc for how to use the context. This does mean that you can't change the code without restarting Node-RED

Body:
I have 2 nodes, which needs to call one function - it's common place in programming.

I suppose, there is no way in node-red to call the function, except "wiring" Function nodes sequentially.

Well, I did try it, but with no success.

Please look(copy_paste) at my flow and give help:

[{"id":"d86b4b3b.0670d8","type":"inject","z":"901492e5.e9666","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"x":169,"y":224,"wires":[["1a6b10c8.0788cf"]]},{"id":"1a6b10c8.0788cf","type":"function","z":"901492e5.e9666","name":"func0","func":"if(msg.payload.second_call){return [null,msg];}\nelse {msg.payload[\"second_call\"] = true;\nmsg.payload[\"count\"] = 0;\nreturn [msg,null];\n}\n","outputs":"2","noerr":0,"x":350,"y":223,"wires":[["577ae7e1.0c1948"],["b2204e3f.44cef"]]},{"id":"577ae7e1.0c1948","type":"function","z":"901492e5.e9666","name":"func1","func":"msg.payload.count++;\nreturn msg;","outputs":1,"noerr":0,"x":352,"y":316,"wires":[["1a6b10c8.0788cf"]]},{"id":"4e8f3348.10ab0c","type":"debug","z":"901492e5.e9666","name":"","active":true,"console":"false","complete":"payload","x":783.5,"y":332,"wires":[]},{"id":"b2204e3f.44cef","type":"function","z":"901492e5.e9666","name":"func3","func":"msg.payload.count++;\nreturn msg;","outputs":1,"noerr":0,"x":619,"y":332,"wires":[["4e8f3348.10ab0c"]]},{"id":"5bf50c74.5376e4","type":"inject","z":"901492e5.e9666","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"x":160,"y":422,"wires":[["c9b5e6b.ae91818"]]},{"id":"c9b5e6b.ae91818","type":"function","z":"901492e5.e9666","name":"func10","func":"if(msg.payload.second_call){return [null,msg];}\nelse {msg.payload[\"second_call\"] = true;\nmsg.payload[\"count\"] = 0;\nreturn [msg,null];\n}\n","outputs":"2","noerr":0,"x":345,"y":422,"wires":[["f11eb781.083348"],["b2204e3f.44cef"]]},{"id":"f11eb781.083348","type":"function","z":"901492e5.e9666","name":"func11","func":"msg.payload.count+=10;\nreturn msg;","outputs":1,"noerr":0,"x":348,"y":508,"wires":[["c9b5e6b.ae91818"]]}]


答:
you don't need concat, just reuse existing columns:</p>

```<code>with a(v,g) as (
select "Campaign","Adgroup"
from adwords_raw
), pre as (
select split_part(v, '{', 1) a,split_part(v, '{', 2) b,v||g "Campaign&AdGroup"
from a
)
select
split_part(a, '-', 1) ca,
split_part(a, '-', 2) cb,
split_part(split_part(a, '-', 3), '|', 1) cc,
split_part(split_part(a, '-', 3),
split_part(split_part(a, '-', 3), '|', 1) || '|', 2) cd,
'{' || b ce,
"Campaign&AdGroup"
from pre;
</code>```

Title: Concatenating two existing columns within a new query

Body:
you don't need concat, just reuse existing columns:

with a(v,g) as (
select "Campaign","Adgroup"
from adwords_raw
), pre as (
select split_part(v, '{', 1) a,split_part(v, '{', 2) b,v||g "Campaign&AdGroup"
from a
)
select
split_part(a, '-', 1) ca,
split_part(a, '-', 2) cb,
split_part(split_part(a, '-', 3), '|', 1) cc,
split_part(split_part(a, '-', 3),
split_part(split_part(a, '-', 3), '|', 1) || '|', 2) cd,
'{' || b ce,
"Campaign&AdGroup"
from pre;


问:
Firefox WebExtensions API how to make AJAX call to current tab website
I want my web extension to make an AJAX call to the website which the user is currently looking at. I know that the current website has an endpoint available at /foo/bar?query=.

Is there anything blocking me from using the fetch API or an XMLHttpRequest to contact this endpoint?

My attempts to use these methods just tell me that a server error has occurred, and nothing comes up in the network tab while I'm trying to debug my extension. I feel like there should be a WebExtensions API for this task, but I can't find one.

答:
<s>You can get an object describing the current tab the user is looking at using browser.tabs.getCurrent(). This object has a property url, which you can then use to make an XMLHttpRequest.

```<code>browser.tabs.getCurrent().then(currentTab => {
    let xhr = new XMLHttpRequest();
    xhr.open("GET", currentTab.url);
    // ...
});
</code>```

</s>

Edit:

As pointed out by Makyen, tabs.currentTab is not actually what you want. Instead tabs.query with active: true should be used. Something like that should work:

```<code>browser.tabs.query({active: true, currentWindow: true}).then(tabs => {
    let currentTab = tabs[0];
    let xhr = new XMLHttpRequest();
    xhr.open("GET", currentTab.url);
    // ...
})
</code>```

In order to make cross origin requests, you will need to get permission in your manifest.json file:

```<code>{
  ...
  "permissions": [
    "tabs",
    "<all_urls>"
  ],
  ...
}
</code>```

<all_urls>for instance will allow you to make http requests to any url.

You can read more here.

Body:
<s>You can get an object describing the current tab the user is looking at using browser.tabs.getCurrent(). This object has a property url, which you can then use to make an XMLHttpRequest.

browser.tabs.getCurrent().then(currentTab => {
    let xhr = new XMLHttpRequest();
    xhr.open("GET", currentTab.url);
    // ...
});

</s>

Edit:

As pointed out by Makyen, tabs.currentTab is not actually what you want. Instead tabs.query with active: true should be used. Something like that should work:

browser.tabs.query({active: true, currentWindow: true}).then(tabs => {
    let currentTab = tabs[0];
    let xhr = new XMLHttpRequest();
    xhr.open("GET", currentTab.url);
    // ...
})

In order to make cross origin requests, you will need to get permission in your manifest.json file:

{
  ...
  "permissions": [
    "tabs",
    "<all_urls>"
  ],
  ...
}

<all_urls>for instance will allow you to make http requests to any url.

You can read more here.


问:
Apache Spark - Why are executor being removed? What does 'Idle' mean?
With Dynamic Resource Allocation :

A Spark application removes an executor when it has been idle for
  more than spark.dynamicAllocation.executorIdleTimeout seconds.

And when I set the executor idle timeout property
 as followed spark.dynamicAllocation.executorIdleTimeout= 300 , it throws the following warning :

```<code>spark.ExecutorAllocationManager: Removing executor 0 because it has been idle for 300 seconds (new desired total will be 2)
</code>```

What does mean to be "Idle"? Does it means the worker use no CPU? Does a blocking call to database count as Idle?

答:
Idle means two things:

No active stages on this executor

No (explicitly) persisted data on this executor

Body:
With Dynamic Resource Allocation :

A Spark application removes an executor when it has been idle for
  more than spark.dynamicAllocation.executorIdleTimeout seconds.

And when I set the executor idle timeout property
 as followed spark.dynamicAllocation.executorIdleTimeout= 300 , it throws the following warning :

spark.ExecutorAllocationManager: Removing executor 0 because it has been idle for 300 seconds (new desired total will be 2)

What does mean to be "Idle"? Does it means the worker use no CPU? Does a blocking call to database count as Idle?


问:
measure time in a function in C
I'm debugging an C application and I'd like to know how much time it spends in a particular function.

I could change the source code and add some more code to do the measurement, but it doesn't seem right to me. I'd rather do it with external application, without recompiling every time.

I found out it's possible to set up a break point in GDB so I thought, it must be possible to track the time using similar tool by simple procedure:
 - set breakpoint
 - when stopped, measure actual time and run the function
 - when leaving function, measure time again
However, i haven't found a way how to do this in gdb :(

any ideas? Thanks

答:
Put this into your ~/.gdbinit

```<code>define timeme
    python import time
    python starttime=time.time()
    next
    python print("Previous takes: " + (str)(time.time()-starttime) + "s")
end
document timeme
    Measure executing time of next function
    Usage: timeme or ti
end
</code>```

type timeme or ti when you want to measure the time of next function.

Title: measure time in a function in C

Body:
Put this into your ~/.gdbinit

define timeme
    python import time
    python starttime=time.time()
    next
    python print("Previous takes: " + (str)(time.time()-starttime) + "s")
end
document timeme
    Measure executing time of next function
    Usage: timeme or ti
end

type timeme or ti when you want to measure the time of next function.


问:
Copy selected data from one worksheet to another with Excel VBA
I am trying to copy selected data from one worksheet to another with Excel VBA. As you can see in my pictures when the value is a 0, the value of the test_Point should be written in another worksheet. So I want to copy the test_Point value of each cell where the value is 0.

Source data on Sheet1:

Expected result to be put on Sheet2:

答:
This should work, just change the name of the sheets/workbooks to whatever you are using, also both workbooks has to be open for this code to run.</p>

```<code>Option Explicit

Sub Copydata()

Dim i As Long, j As Long, lLr As Long
Dim wsSource As Worksheet, wsTarget As Worksheet
Dim wbSource As Workbook, wbTarget As Workbook

    Set wbSource = Workbooks("WbSource") 'sets source workbook
    Set wbTarget = Workbooks("WbTarget") 'sets target workbook

Set wsSource = wbSource.Worksheets("SourceSheet") 'sets source worksheet
Set wsTarget = wbTarget.Worksheets("TargetSheet") 'sets target worksheet

lLr = wsSource.Range("B" & Rows.Count).End(xlUp).Row

j = 1

For i = 2 To lLr

    If wsSource.Range("b" & i) = 0 Then

        wsTarget.Range("a" & j).Value = wsSource.Range("A" & i)
        wsTarget.Range("a" & j).NumberFormat = "0.0"
        j = j + 1

    End If

Next i

End Sub
</code>```

Body:
This should work, just change the name of the sheets/workbooks to whatever you are using, also both workbooks has to be open for this code to run.

Option Explicit

Sub Copydata()

Dim i As Long, j As Long, lLr As Long
Dim wsSource As Worksheet, wsTarget As Worksheet
Dim wbSource As Workbook, wbTarget As Workbook

    Set wbSource = Workbooks("WbSource") 'sets source workbook
    Set wbTarget = Workbooks("WbTarget") 'sets target workbook

Set wsSource = wbSource.Worksheets("SourceSheet") 'sets source worksheet
Set wsTarget = wbTarget.Worksheets("TargetSheet") 'sets target worksheet

lLr = wsSource.Range("B" & Rows.Count).End(xlUp).Row

j = 1

For i = 2 To lLr

    If wsSource.Range("b" & i) = 0 Then

        wsTarget.Range("a" & j).Value = wsSource.Range("A" & i)
        wsTarget.Range("a" & j).NumberFormat = "0.0"
        j = j + 1

    End If

Next i

End Sub


答:
Таке a look at the below example:</p>

```<code>Option Explicit

Sub Test()

    Dim rSrc As Range
    Dim rDst As Range

    ' First cell with source data which is to be evaluated
    Set rSrc = ThisWorkbook.Sheets("Sheet1").Range("B2")
    ' First destination cell where to put result
    Set rDst = ThisWorkbook.Sheets("Sheet2").Range("A1")

    Do
        ' Check if source cell is empty
        If rSrc = "" Then Exit Do
        ' Check if source cell is 0
        If rSrc = 0 Then
            ' Copy value of the cell to the left to the destination
            rDst.Value = rSrc.Offset(0, -1).Value
            ' Move destination down
            Set rDst = rDst.Offset(1, 0)
        End If
        ' Move source down
        Set rSrc = rSrc.Offset(1, 0)
    Loop

End Sub
</code>```

Title: Copy selected data from one worksheet to another with Excel VBA

Body:
I am trying to copy selected data from one worksheet to another with Excel VBA. As you can see in my pictures when the value is a 0, the value of the test_Point should be written in another worksheet. So I want to copy the test_Point value of each cell where the value is 0.

Source data on Sheet1:

Expected result to be put on Sheet2:

Body:
Таке a look at the below example:

Option Explicit

Sub Test()

    Dim rSrc As Range
    Dim rDst As Range

    ' First cell with source data which is to be evaluated
    Set rSrc = ThisWorkbook.Sheets("Sheet1").Range("B2")
    ' First destination cell where to put result
    Set rDst = ThisWorkbook.Sheets("Sheet2").Range("A1")

    Do
        ' Check if source cell is empty
        If rSrc = "" Then Exit Do
        ' Check if source cell is 0
        If rSrc = 0 Then
            ' Copy value of the cell to the left to the destination
            rDst.Value = rSrc.Offset(0, -1).Value
            ' Move destination down
            Set rDst = rDst.Offset(1, 0)
        End If
        ' Move source down
        Set rSrc = rSrc.Offset(1, 0)
    Loop

End Sub


问:
What is meant by immutable?
What exactly does immutable mean - that is, what are the consequences of an object being mutable or immutable? In particular, why are Java's Strings immutable?

My understanding is that the StringBuilder type is something like a mutable equivalent to String. When would I use StringBuilder rather than String, and vice-versa?

答:
Immutable Objects

An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code.

Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.

Programmers are often reluctant to employ immutable objects, because they worry about the cost of creating a new object as opposed to updating an object in place. The impact of object creation is often overestimated, and can be offset by some of the efficiencies associated with immutable objects. These include decreased overhead due to garbage collection, and the elimination of code needed to protect mutable objects from corruption.

The following subsections take a class whose instances are mutable and derives a class with immutable instances from it. In so doing, they give general rules for this kind of conversion and demonstrate some of the advantages of immutable objects.

Source

OwnerDisplayName: askgelal

ContentLicense: CC BY-SA 4.0

Title: What is meant by immutable?

LastEditorDisplayName: Greg Hewgill


问:
Displaying errors for rails has_many through associations
I have the following class:

class Person < ApplicationRecord
  validates :name, presence: true

  has_many :parenthoods
  has_many :children, through: :parenthoods, index_errors: true

  has_many :childhoods, class_name: 'Parenthood', foreign_key: 'child_id'
  has_many :parents, through: :childhoods, source: :person
end
```

<p>With an explicit join-table model:</p>

<pre class="lang-rb prettyprint-override"><code>class Parenthood < ApplicationRecord
  belongs_to :person
  belongs_to :child, class_name: 'Person'
  validate :parent_can_not_be_child
  private
    def parent_can_not_be_child
      errors.add(:person, "child can not be parent") if person_id == child_id
    end
end
</code>```

I would prefer to keep working with a has_many :through as opposed to a habtm if possible. And it seemed to the most reasonable way to create the association. The update action in the controller is pretty straight forward:

def update
  @person = current_user.people.find(params[:id])
  if @person.update_attributes(person_params)
    redirect_to @person
  else
    render action: 'edit'
  end
end
```

<p>And in the view I have (HAML, but it seems pretty clear in its intent)</p>

```-if @person.errors.any?
  = @person.errors.full_messages.first
```

The update action has the following behaviours:

Input is all OK: Works as intended ✔

Name validation fails: Shows a validation error in the form template as you would expect ✔

Try to make somebody their own child: Instead of showing the validation error on the form it, I instead get the 500 error page with this error:

ActiveRecord::RecordInvalid in PeopleController#update

Validation failed: Person child can not be parent

I'm sure there is an easy way to handle this in rails but I just seem to be going around in circles at the moment, any help appreciated lots!

答:
Thank you very much to @Pavan for pointing me in the correct direction! The fix is to write this as the validation method:

```<code>def parent_can_not_be_child
  person.errors.add(:base, "child can not be parent") if person_id == child_id
end
</code>```

And then include the validates associated validator on the person object:

```<code>validates_associated :parenthoods
</code>```

The key is that adding the error to person not to the parenthood means the error is displayed in @person.errors later.

Body:
I have the following class:

class Person < ApplicationRecord
  validates :name, presence: true

  has_many :parenthoods
  has_many :children, through: :parenthoods, index_errors: true

  has_many :childhoods, class_name: 'Parenthood', foreign_key: 'child_id'
  has_many :parents, through: :childhoods, source: :person
end

With an explicit join-table model:

class Parenthood < ApplicationRecord
  belongs_to :person
  belongs_to :child, class_name: 'Person'
  validate :parent_can_not_be_child
  private
    def parent_can_not_be_child
      errors.add(:person, "child can not be parent") if person_id == child_id
    end
end

I would prefer to keep working with a has_many :through as opposed to a habtm if possible. And it seemed to the most reasonable way to create the association. The update action in the controller is pretty straight forward:

def update
  @person = current_user.people.find(params[:id])
  if @person.update_attributes(person_params)
    redirect_to @person
  else
    render action: 'edit'
  end
end

And in the view I have (HAML, but it seems pretty clear in its intent)

-if @person.errors.any?
  = @person.errors.full_messages.first

The update action has the following behaviours:

Input is all OK: Works as intended ✔

Name validation fails: Shows a validation error in the form template as you would expect ✔

Try to make somebody their own child: Instead of showing the validation error on the form it, I instead get the 500 error page with this error:

ActiveRecord::RecordInvalid in PeopleController#update

Validation failed: Person child can not be parent

I'm sure there is an easy way to handle this in rails but I just seem to be going around in circles at the moment, any help appreciated lots!

Body:
Thank you very much to @Pavan for pointing me in the correct direction! The fix is to write this as the validation method:

def parent_can_not_be_child
  person.errors.add(:base, "child can not be parent") if person_id == child_id
end

And then include the validates associated validator on the person object:

validates_associated :parenthoods

The key is that adding the error to person not to the parenthood means the error is displayed in @person.errors later.


问:
Presenting a View Controller with a button in a UITableViewCell programmatically (Swift)
I am trying to make it where when a user clicks on a table view cell in my table view it takes them to a new view controller. More specifically, when a user clicks on a persons username it should take them to that users profile. the username being the table view cell and the profile being the new view controller. I thought the way to do this was to use the ".presentViewController(vc, animated: true, completion: nil) however when i do this it says "myCell does not have a member named .presentViewController"

If anyone could help me solve this problem it'd be greatly appreciated

答:
swift3 version

```<code>let storyboard = UIStoryboard(name: "MainViewController", bundle: nil)
let messagesViewController = storyboard.instantiateViewController(withIdentifier: "MessagesViewController") as! MessagesViewController
self.window?.rootViewController?.present(messagesViewController, animated: true, completion: nil)
</code>```

Body:
swift3 version

let storyboard = UIStoryboard(name: "MainViewController", bundle: nil)
let messagesViewController = storyboard.instantiateViewController(withIdentifier: "MessagesViewController") as! MessagesViewController
self.window?.rootViewController?.present(messagesViewController, animated: true, completion: nil)


问:
How to stop the Visibility of the ProgressBar inside LinearLayout
I have an activity which have 5-6 fragments in it and i am trying to show a progress bar whenever a fragment loads its data from REST api.  I am able to show the progress bar but not able to stop visibility of it. whenever i am trying to stop the visibility of it, Progress Bar doesn't come up at all.   Here is my Activity.java

```<code>public class MainActivity extends AppCompatActivity {

    private Toolbar   toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    public LinearLayout linearLayout;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ImageView imageTitle = (ImageView) toolbar.findViewById(R.id.appbar_image);
           setSupportActionBar(toolbar);
           getSupportActionBar().setDisplayShowTitleEnabled(false);
           getSupportActionBar().setDisplayHomeAsUpEnabled(false);
           linearLayout = (LinearLayout)findViewById(R.id.linlaHeaderProgress);
           linearLayout.setVisibility(View.VISIBLE);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

       }

private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new HomeFragment(), "Home News");
        adapter.addFragment(new BusinessFragment(),"Business News");
        adapter.addFragment(new PoliticsFragment(),"Politics News");
        adapter.addFragment(new TechnologyFragment(),"Technology News");
        adapter.addFragment(new SportsFragment(),"Sports News");
        adapter.addFragment(new EntertainmentFragment(),"Entertainment News");
        adapter.addFragment(new HealthFragment(),"Health News");
        adapter.addFragment(new WorldFragment(),"World News");
        adapter.addFragment(new MoreFragment(),"More News");

        viewPager.setAdapter(adapter);

}

private void stopBar() {

    linearLayout.setVisibility(View.GONE);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
     private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager manager) {
    super(manager);
}

@Override
public Fragment getItem(int position) {
    return mFragmentList.get(position);
}

@Override
public int getCount() {
    return mFragmentList.size();
}

public void addFragment(Fragment fragment, String title) {
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);

}

     @Override
    public CharSequence getPageTitle(int position) {
    return mFragmentTitleList.get(position);
   }
 }
}
</code>```

Here is my activity.xml

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/appbar_image"
                android:foregroundGravity="center"
                android:scaleType="fitCenter"
                android:src="@drawable/splash"

                />

        </android.support.v7.widget.Toolbar>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="scrollable"/>
    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:id="@+id/linlaHeaderProgress"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="gone">

        <ProgressBar
            android:id="@+id/pbHeaderProgress"
            style="@style/Widget.AppCompat.ProgressBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:theme="@style/CircularProgress">
        </ProgressBar>

    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>
</code>```

This is my fragment.java

```<code>    public class HomeFragment extends android.support.v4.app.Fragment {

    private RecyclerView recyclerView;
    private ArrayList<HomeNews> data;
    private HomeNewsAdapter adapter;
    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_home, container, false);

        recyclerView = (RecyclerView)rootView.findViewById(R.id.rv_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);

        loadJSON();

        return rootView;

    }

    private void loadJSON() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.vaonlinenews.com/news_api/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RequestInterface request = retrofit.create(RequestInterface.class);
        Call<HomeResponse> call = request.getHomeJSON();

        call.enqueue(new Callback<HomeResponse>() {
            @Override
            public void onResponse(Call<HomeResponse> call, Response<HomeResponse> response) {

                HomeResponse homeResponse = response.body();
                data = new ArrayList<>(Arrays.asList(homeResponse.getArticles()));
                adapter = new HomeNewsAdapter(getContext(),data);
                recyclerView.setAdapter(adapter);

            }

            @Override
            public void onFailure(Call<HomeResponse> call, Throwable t) {
                Log.d("Error",t.getMessage());
                Error_Dialog alert = new Error_Dialog();
                alert.showDialog(getActivity()," Please Check Your Internet Connection");

            }
        });

    }

}
</code>```

Please suggest me where i should place the code to stop the visibility of progress bar after the fragments gets loaded.

答:
main activity method to stop progress bar

```<code>public void stopProgressBar(){
if (progresslayout.getVisibility() == View.VISIBLE)
{
 progresslayout.setVisibility(View.GONE);
}
}
</code>```

call the above method in the fragment after getting the data
ex: in onattach get mainactivity context like below

```<code> @Override
 public void onAttach(Context context) {
    super.onAttach(context);

    mainActivity = (MainActivity) context;
    this.context = context;
}
</code>```

calling stop progressbar method in fragment

```<code>mainActivity.stopProgressBar();
</code>```

Body:
I have an activity which have 5-6 fragments in it and i am trying to show a progress bar whenever a fragment loads its data from REST api.  I am able to show the progress bar but not able to stop visibility of it. whenever i am trying to stop the visibility of it, Progress Bar doesn't come up at all.   Here is my Activity.java

public class MainActivity extends AppCompatActivity {

    private Toolbar   toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    public LinearLayout linearLayout;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ImageView imageTitle = (ImageView) toolbar.findViewById(R.id.appbar_image);
           setSupportActionBar(toolbar);
           getSupportActionBar().setDisplayShowTitleEnabled(false);
           getSupportActionBar().setDisplayHomeAsUpEnabled(false);
           linearLayout = (LinearLayout)findViewById(R.id.linlaHeaderProgress);
           linearLayout.setVisibility(View.VISIBLE);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

       }

private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new HomeFragment(), "Home News");
        adapter.addFragment(new BusinessFragment(),"Business News");
        adapter.addFragment(new PoliticsFragment(),"Politics News");
        adapter.addFragment(new TechnologyFragment(),"Technology News");
        adapter.addFragment(new SportsFragment(),"Sports News");
        adapter.addFragment(new EntertainmentFragment(),"Entertainment News");
        adapter.addFragment(new HealthFragment(),"Health News");
        adapter.addFragment(new WorldFragment(),"World News");
        adapter.addFragment(new MoreFragment(),"More News");

        viewPager.setAdapter(adapter);

}

private void stopBar() {

    linearLayout.setVisibility(View.GONE);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
     private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager manager) {
    super(manager);
}

@Override
public Fragment getItem(int position) {
    return mFragmentList.get(position);
}

@Override
public int getCount() {
    return mFragmentList.size();
}

public void addFragment(Fragment fragment, String title) {
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);

}

     @Override
    public CharSequence getPageTitle(int position) {
    return mFragmentTitleList.get(position);
   }
 }
}

Here is my activity.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/appbar_image"
                android:foregroundGravity="center"
                android:scaleType="fitCenter"
                android:src="@drawable/splash"

                />

        </android.support.v7.widget.Toolbar>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="scrollable"/>
    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:id="@+id/linlaHeaderProgress"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="gone">

        <ProgressBar
            android:id="@+id/pbHeaderProgress"
            style="@style/Widget.AppCompat.ProgressBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:theme="@style/CircularProgress">
        </ProgressBar>

    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

This is my fragment.java

    public class HomeFragment extends android.support.v4.app.Fragment {

    private RecyclerView recyclerView;
    private ArrayList<HomeNews> data;
    private HomeNewsAdapter adapter;
    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_home, container, false);

        recyclerView = (RecyclerView)rootView.findViewById(R.id.rv_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);

        loadJSON();

        return rootView;

    }

    private void loadJSON() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.vaonlinenews.com/news_api/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RequestInterface request = retrofit.create(RequestInterface.class);
        Call<HomeResponse> call = request.getHomeJSON();

        call.enqueue(new Callback<HomeResponse>() {
            @Override
            public void onResponse(Call<HomeResponse> call, Response<HomeResponse> response) {

                HomeResponse homeResponse = response.body();
                data = new ArrayList<>(Arrays.asList(homeResponse.getArticles()));
                adapter = new HomeNewsAdapter(getContext(),data);
                recyclerView.setAdapter(adapter);

            }

            @Override
            public void onFailure(Call<HomeResponse> call, Throwable t) {
                Log.d("Error",t.getMessage());
                Error_Dialog alert = new Error_Dialog();
                alert.showDialog(getActivity()," Please Check Your Internet Connection");

            }
        });

    }

}

Please suggest me where i should place the code to stop the visibility of progress bar after the fragments gets loaded.

Body:
main activity method to stop progress bar

public void stopProgressBar(){
if (progresslayout.getVisibility() == View.VISIBLE)
{
 progresslayout.setVisibility(View.GONE);
}
}

call the above method in the fragment after getting the data
ex: in onattach get mainactivity context like below

 @Override
 public void onAttach(Context context) {
    super.onAttach(context);

    mainActivity = (MainActivity) context;
    this.context = context;
}

calling stop progressbar method in fragment

mainActivity.stopProgressBar();


问:
C program to detect USB drive in Linux
I have a embedded device running Linux Angstrom. I need to detect a USB drive. So when a USB drive is inserted, I need to automatically copy data from the USB to internal memory of the embedded device.

To detect the USB, I am using below code:

```<code>DIR* dir = opendir("/media/sda1/");
if (dir)
{
   printf("USB detected\n");
   //rest of the code
   //to copy data from the USB
}
</code>```

This works normally but sometimes after copying is done, I remove the USB but the name of the mount point (sda1) remains there. So after removing the USB, it again try to copy the data (because sda1 is there in media) and then shows error because physical no USB is connected. What is the best way to detect if USB is connected and if connected then after copying how to eject it properly. Here I cannot use udisks because its not available for the linux angstrom I am using for this embedded device. So only generic linux commands will work.

Any help. Thanks

答:
One naive approach is the following:

execute mount | grep /dev/sda1

parse the output: if there is no output, that means that sda1 is not mounted

You may have to adapt the code to your specific platform.

```<code>#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    /* launch a command and gets its output */
    FILE *f = popen("mount | grep /dev/sda1", "r");
    if (NULL != f)
    {
        /* test if something has been outputed by
           the command */
        if (EOF == fgetc(f))
        {
            puts("/dev/sda1 is NOT mounted");
        }
        else
        {
            puts("/dev/sda1 is mounted");
        }
        /* close the command file */
        pclose(f);
    }
    return 0;
}
</code>```

Title: C program to detect USB drive in Linux

Body:
I have a embedded device running Linux Angstrom. I need to detect a USB drive. So when a USB drive is inserted, I need to automatically copy data from the USB to internal memory of the embedded device.

To detect the USB, I am using below code:

DIR* dir = opendir("/media/sda1/");
if (dir)
{
   printf("USB detected\n");
   //rest of the code
   //to copy data from the USB
}

This works normally but sometimes after copying is done, I remove the USB but the name of the mount point (sda1) remains there. So after removing the USB, it again try to copy the data (because sda1 is there in media) and then shows error because physical no USB is connected. What is the best way to detect if USB is connected and if connected then after copying how to eject it properly. Here I cannot use udisks because its not available for the linux angstrom I am using for this embedded device. So only generic linux commands will work.

Any help. Thanks

Body:
One naive approach is the following:

execute mount | grep /dev/sda1

parse the output: if there is no output, that means that sda1 is not mounted

You may have to adapt the code to your specific platform.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    /* launch a command and gets its output */
    FILE *f = popen("mount | grep /dev/sda1", "r");
    if (NULL != f)
    {
        /* test if something has been outputed by
           the command */
        if (EOF == fgetc(f))
        {
            puts("/dev/sda1 is NOT mounted");
        }
        else
        {
            puts("/dev/sda1 is mounted");
        }
        /* close the command file */
        pclose(f);
    }
    return 0;
}


问:
I need to apply the css for a specific class and id
I need to apply CSS to a specific class and id of an element like this.

```<code><div class="contents" id="contents">
</code>```

I tried

```<code>#contents .contents { ... }
</code>```

but it doesn't seem to work.

How to apply the css for a specific class and id ?

ADDED

With

```<code>#contents.contents {...}
</code>```

It works OK.

答:
```<code>#contents.contents { ... }
</code>```

… should work fine. The problem is likely somewhere in code that you haven't shared with us.

```<code>#contents .contents { ... }
</code>```

… means "An element that is a member of class contents that is a descendent of an element with the id contents"

ContentLicense: CC BY-SA 2.5

Body:
I need to apply CSS to a specific class and id of an element like this.

I tried

#contents .contents { ... }

but it doesn't seem to work.

How to apply the css for a specific class and id ?

ADDED

With

#contents.contents {...}

It works OK.

Body:
#contents.contents { ... }

… should work fine. The problem is likely somewhere in code that you haven't shared with us.

#contents .contents { ... }

… means "An element that is a member of class contents that is a descendent of an element with the id contents"


问:
Can I loop on a method?
I am using a method to retrieve an enumerable and was wandering a silly thing : is it ok to loop on the method call? say I have a method getDocuments in a Document class that returns an IEnumerable, then can I do:

```<code>Document doc=new Document();
foreach(var item in doc.getDocuments())
{//Code here
}
</code>```

Or is it better to assign a variable to that result and loop on the variable?

答: The doc.getDocuments() in your for loop evaluates and returns a result and it is on this result that the var doc is iterated upon. This method is not going to be called each time the loop runs. Hence it will be okay to use this method in the loop.</p>

Title: Can I loop on a method?

Body:
I am using a method to retrieve an enumerable and was wandering a silly thing : is it ok to loop on the method call? say I have a method getDocuments in a Document class that returns an IEnumerable, then can I do:

Document doc=new Document();
foreach(var item in doc.getDocuments())
{//Code here
}

Or is it better to assign a variable to that result and loop on the variable?


问:
Spring Data : How to store enum list in mySQL database
In the following code I have a field shopType which is actually a enum , In my scenario one shop has multiple type for example shop ABC have type grocery as well as pharmacy , so I want to store a list of enum in my database in separate table in which two column present one is shop_id and other is shop_type so that one shop can have multiple types How can i do this ?

here is my code

ShopDetail.java

```<code>@Entity
public class ShopDetail {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String address;

    private Double latitude;

    private Double longitude;

    private float  rating;

    private Time openingTime;

    private Time closingTime;

    @Enumerated(EnumType.STRING)
     private Collection<ShopType> shopType;

    @Column(columnDefinition=" bit(1)default 1")
    private boolean shopEnabled = true;

    //getters and setters
    }
</code>```

ShopType

```<code>public enum ShopType {

    GROCERY,
    PHARAMACY
}
</code>```

答:
This should work:

```<code>@ElementCollection(targetElement = ShopType.class)
@JoinTable(name = "tblShopTypes", joinColumns = @JoinColumn(name = "id"))
@Column(name = "shopType", nullable = false)
@Enumerated(EnumType.STRING)
Collection<ShopType> shopTypes;
</code>```

ref: this answer

Body:
In the following code I have a field shopType which is actually a enum , In my scenario one shop has multiple type for example shop ABC have type grocery as well as pharmacy , so I want to store a list of enum in my database in separate table in which two column present one is shop_id and other is shop_type so that one shop can have multiple types How can i do this ?

here is my code

ShopDetail.java

@Entity
public class ShopDetail {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String address;

    private Double latitude;

    private Double longitude;

    private float  rating;

    private Time openingTime;

    private Time closingTime;

    @Enumerated(EnumType.STRING)
     private Collection<ShopType> shopType;

    @Column(columnDefinition=" bit(1)default 1")
    private boolean shopEnabled = true;

    //getters and setters
    }

ShopType

public enum ShopType {

    GROCERY,
    PHARAMACY
}

Body:
This should work:

@ElementCollection(targetElement = ShopType.class)
@JoinTable(name = "tblShopTypes", joinColumns = @JoinColumn(name = "id"))
@Column(name = "shopType", nullable = false)
@Enumerated(EnumType.STRING)
Collection<ShopType> shopTypes;

ref: this answer


问:
String arrays in float arrays without format change
Is there a way to include strings in an array of floats without the format of the array changing such that all floats are changed to strings but the string element is still kept as a string?

eg.

```<code>import numpy as np

a = np.array([ 'hi' , 1. , 2. , 3. ])
</code>```

Ideally I would like the format to remain the same as how it looks when input as 'a' above.

This gives:

```<code>array(['hi', '1.0', '2.0', '3.0'], dtype='|S3')
</code>```

And then how would one save such an array as a text file?

Many thanks,

J

答:
Use pickle:

```<code>import pickle

a = ['abc',3,4,5,6,7.0]
pickle.dump( a, open( "save.p", "wb" ))
b = pickle.load( open( "save.p", "rb" ) )

print(b)
</code>```

Output:

```<code>['abc', 3, 4, 5, 6, 7.0]
</code>```

Body:
Is there a way to include strings in an array of floats without the format of the array changing such that all floats are changed to strings but the string element is still kept as a string?

eg.

import numpy as np

a = np.array([ 'hi' , 1. , 2. , 3. ])

Ideally I would like the format to remain the same as how it looks when input as 'a' above.

This gives:

array(['hi', '1.0', '2.0', '3.0'], dtype='|S3')

And then how would one save such an array as a text file?

Many thanks,

J

Body:
Use pickle:

import pickle

a = ['abc',3,4,5,6,7.0]
pickle.dump( a, open( "save.p", "wb" ))
b = pickle.load( open( "save.p", "rb" ) )

print(b)

Output:

['abc', 3, 4, 5, 6, 7.0]


问:
How to fetch two Json response Json Object and Array
How to fetch this Two Json Response and save the json response in SQLite. Hope you will guide me how to fetch this Json object inside a Json Array inside an Object

My problem is a cannot fetch the 2nd json response. I noticed that only the 1st response was returned

Login response in Logcat

```<code>D/RegisterActivity: Login Response: {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}{"error":false,"sl_summ":[{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]}
</code>```

only the 1st response was returned in this Logcat

```<code>D/sl_summ: JSON String : {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/sl_summ: -error attribute: false
D/TEST: org.json.JSONException: No value for sl_summ
</code>```

This is the 1st Json response. Was parse and stored in SQLite

```<code>{
  "error": false,
  "user": {
    "br_code": 12,
    "mem_id": 13,
    "username": "novalyn",
    "email": "gsac_tabaco@yahoo.com",
    "created_at": "2016-07-22 09:05:21"
  }
}
</code>```

This is the 2nd Json response. Json object inside a JSON Array. Was not parse and inserted in SQLite

```<code>{
  "error": false,
  "sl_summ":
  [
    {
      "sl_desc": "PA : Savings Account",
      "tr_date": "2015-08-17",
      "actual_balance": "483.67",
      "available_balance": "483.67"
    },
    {
      "sl_desc": "PA : Savings - Cash Bond",
      "tr_date": "2015-08-28",
      "actual_balance": "10129.43",
      "available_balance": "10129.43"
    }
  ]
}
</code>```

Whole JSON response

```<code>{
  "error": false,
  "user": {
    "br_code": 12,
    "mem_id": 13,
    "username": "novalyn",
    "email": "gsac_tabaco@yahoo.com",
    "created_at": "2016-07-22 09:05:21"
  }
}
{
  "error": false,
  "sl_summ":
  [
    {
      "sl_desc": "PA : Savings Account",
      "tr_date": "2015-08-17",
      "actual_balance": "483.67",
      "available_balance": "483.67"
    },
    {
      "sl_desc": "PA : Savings - Cash Bond",
      "tr_date": "2015-08-28",
      "actual_balance": "10129.43",
      "available_balance": "10129.43"
    }
  ]
}
</code>```

This is my Login.java

```<code>try {
    JSONObject jObj = new JSONObject(response.toString());
    boolean error = jObj.getBoolean("error");
    Log.d(TAG, "Checking JSON Object" +jObj);

    Log.d("TEST", "-error attribute             : " + jObj.get("error").toString());
    // Check for error node in json
    if (!error) {
        // user successfully logged in
        // Create login session
        session.setLogin(true);

        // Now store the user in SQLite
        //String uid = jObj.getString("uid");

        JSONObject user = jObj.getJSONObject("user");
            Log.d("USER", "-user object     : " + jObj.getJSONObject("user").toString());
        String br_code = user.getString("br_code");
            Log.d("USER", "-br_code         : " + br_code);
        String mem_id = user.getString("mem_id");
            Log.d("USER", "-mem_id          : " + mem_id);
        String username = user.getString("username");
            Log.d("USER", "-username        : " + username);
        String email = user.getString("email");
            Log.d("USER", "-email           : " + email);
        String created_at = user.getString("created_at");
            Log.d("USER", "-created at      : " + created_at);

        // Inserting row in users table
        db.addUser(br_code, mem_id, username, email, created_at);

        //SL Details
        try {
            // read the json string into a json object
            JSONObject jsonObject = new JSONObject(response.toString());
            Log.d("sl_summ", "JSON String                  : " + jsonObject.toString());
            // access individual json object thru jsonObject.get("FIELD_NAME")
            Log.d("sl_summ", "-error attribute             : " + jsonObject.get("error").toString());
            // access individual json array thru jsonObject.getJSONArray("FIELD_NAME")
            Log.d("sl_summ", "-sl_summ array               : " + jsonObject.getJSONArray("sl_summ").toString());
            JSONArray array = ((JSONArray)jsonObject.getJSONArray("sl_summ"));
            for (int index=0; index<array.length(); index++) {
                JSONObject object = (JSONObject)array.get(index);
                Log.d("SL_SUUM", "-sl_desc attribute           : " + object.get("sl_desc").toString());
                Log.d("SL_SUUM", "-tr_date attribute           : " + object.get("tr_date").toString());
                Log.d("SL_SUUM", "-actual_balance attribute    : " + object.get("actual_balance").toString());
                Log.d("SL_SUUM", "-available_balance attribute : " + object.get("available_balance").toString());
                Log.d("SL_SUUM", "---------------------------------");
            }
        } catch (Exception exception) {
            Log.d("TEST", exception.toString());
        }

        // Launch main activity
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    } else {
        // Error in login. Get the error message
        String errorMsg = jObj.getString("error_msg");
        Toast.makeText(getApplicationContext(),
                errorMsg, Toast.LENGTH_LONG).show();
    }
} catch (JSONException e) {
    // JSON error
    e.printStackTrace();
    Log.d("TEST", e.toString());
    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
</code>```

SQlitehandler.java

```<code>public void addUserSLDTL(String sl_desc, String tr_date, String  actual_balance, String avail_balance){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(SL_DESC, sl_desc); // sl desc
    values.put(TR_DATE, tr_date); // trans date
    values.put(ACTUAL_BALANCE, actual_balance); // actual balance
    values.put(AVAILABLE_BALANCE, avail_balance); // availabe balance

    // Inserting Row
    long id = db.insertOrThrow(TABLE_MEMBERS_SLDTL, null, values);
    db.close(); // Closing database connection

    Log.d(TAG, "Members's SL Details was inserted into sldtl table: " + id);
    Log.d(TAG, "SL Desc: " + sl_desc);
    Log.d(TAG, "Transaction Date: " + tr_date);
    Log.d(TAG, "Actual Balance: " + actual_balance);
    Log.d(TAG, "Available Balance: " + avail_balance);
}

public HashMap<String, String> getUserSLDTL() {
    HashMap<String, String> sl_summ = new HashMap<String, String>();
    String selectQuery = "SELECT * FROM " + TABLE_MEMBERS_SLDTL;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // Move to first row
    cursor.moveToFirst();
    if (cursor.getCount() > 0) {
        sl_summ.put("sl_desc", cursor.getString(0));
        sl_summ.put("tr_date", cursor.getString(1));
        sl_summ.put("actual_balance", cursor.getString(2));
        sl_summ.put("avail_balance", cursor.getString(3));

        Log.d(TAG, "member's SLDTL data: " + sl_summ.toString());
    }
    else{
        Log.d(TAG, "member's SLDTL data is empty");
    }
    cursor.close();
    db.close();

    // return user
    Log.d(TAG, "Fetching member's SL details from Sqlite sldtl table: " + sl_summ.toString());

    return sl_summ;
}
</code>```

Logcat message

```<code>D/RegisterActivity: Login Response: {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}{"error":false,"sl_summ":[{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]}
D/ViewRootImpl@dd06ab4[LoginActivity]: dispatchDetachedFromWindow
D/InputTransport: Input channel destroyed: fd=76
D/RegisterActivity: Checking JSON Object{"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/TEST: -error attribute             : false
D/SessionManager: User login session modified!
D/USER: -user object     : {"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}
D/USER: -br_code         : 12
D/USER: -mem_id          : 13
D/USER: -username        : novalyn
D/USER: -email           : gsac_tabaco@yahoo.com
D/USER: -created at      : 2016-07-22 09:05:21
D/SQLiteHandler: New member was inserted into table members: 13
D/SQLiteHandler: BR CODE: 12
D/SQLiteHandler: Member ID: 13
D/SQLiteHandler: Username: novalyn
D/SQLiteHandler: Email: gsac_tabaco@yahoo.com
D/SQLiteHandler: Created at: 2016-07-22 09:05:21
D/sl_summ: JSON String                  : {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/sl_summ: -error attribute             : false
D/TEST: org.json.JSONException: No value for sl_summ
</code>```

Login.php

```<code><?php
session_start();
require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// json response array
$response = array("error" => FALSE);
$br_response = array("error" => FALSE);
$sl_response["error"] = FALSE;
$sl_response["sl_summ"] = array();

$arclass = "13";
$loanclass = "12";
$accintreceivable = "21";

if (isset($_POST['username']) && isset($_POST['password'])) {

    // receiving the post params
    $username= $_POST['username'];
    $password = $_POST['password'];

    // get the user by username and password
    $user = $db->getUserByUsernameAndPassword($username, $password);

    if ($user != null) {
        // user is found
        $response["error"] = FALSE;
        $response["user"]["br_code"] = $user["MEMBER_ID_BRCODE"];
        $response["user"]["mem_id"] = $user["MEMBER_ID"];
        $response["user"]["username"] = $user["USERNAME"];
        $response["user"]["email"] = $user["EMAIL"];
        $response["user"]["created_at"] = $user["REG_DATE"];
        json_encode($response, true);
        //Displaying json value
        echo json_encode($response, true);

        //$_SESSION= json_encode($response, true);
        // $_SESSION['br_code']= $user["MEMBER_ID_BRCODE"];
        // $_SESSION['username']= $user["USERNAME"];
        // $_SESSION['mem_id']= $user["MEMBER_ID"];

        $br_code= $user["MEMBER_ID_BRCODE"];
        $clientid= $user["MEMBER_ID"];
        //Check if the branch of the user exist in the BRANCH table
        $user = $db->getBrnchInfo($br_code);
        //var_dump($user);
        if ($user != null) {
            $br_response["error"] = FALSE;
            $br_response["user_br"]["ar_class"] = $arclass;
            $br_response["user_br"]["loan_class"] = $loanclass;
            $br_response["user_br"]["accnt_receivable"] = $accintreceivable;
            $br_response["user_br"]["br_code"] = $user["br_id"];
            $br_response["user_br"]["br_desc"] = $user["br_desc"];
            $br_response["user_br"]["br_address"] = $user["br_add"];
            $br_response["user_br"]["br_manager"] = $user["br_manager"];
            $br_response["user_br"]["br_accronym"] = $user["br_accronym"];
            $br_response["user_br"]["br_trans_date"] = $user["br_trans_date"];
            //json_encode($br_response, true);
            //echo json_encode($br_response, true);

            $trans_date = strtotime($user["br_trans_date"]);
            $date  = date('d',$trans_date);
            $year  = date('Y',$trans_date);
            $month = date('m',$trans_date);

            $user_sldtl = $db->getUserSLsummary($arclass, $loanclass, $accintreceivable, $date, $year, $month, $br_code, $clientid);

            If($user_sldtl != null) {
                 for($i = 0; $i < count($user_sldtl); $i++){
                    $item = array();
                        $item["sl_desc"] = $user_sldtl[$i][7];
                        $item["tr_date"] = $user_sldtl[$i][10];
                        $item["actual_balance"] = $user_sldtl[$i][14];
                        $item["available_balance"] = $user_sldtl[$i][14];

                        $response = array("error" => FALSE);
                        $sl_response["sl_summ"][] = $item;
                    }
                    json_encode($sl_response);
                    echo json_encode($sl_response, true);
             }
             else {
                 $sl_response["error"] = TRUE;
                 $sl_response["error_msg"] = "NO SL Details found!";
                 echo json_encode($sl_response);
             }
        }
        else {
            $response["error"] = TRUE;
            $response["error_msg"] = "No branch code found.!";
            json_encode($response);
           // echo json_encode($response);
        }

        //header('Location: accountsummary.php');
    } else {
        // user is not found with the credentials
        $response["error"] = TRUE;
        $response["error_msg"] = "Login credentials are wrong. Please try again!";
        json_encode($response);
        echo json_encode($response);
        // echo "<br />" .$username. "<br />";
        // echo $password;
    }
} else {
    // required post params is missing
    $response["error"] = TRUE;
    $response["error_msg"] = "Required parameters username or password is missing!";
    json_encode($response);
    echo json_encode($response);
}
?>
</code>```

答:
```<code>// your JSON format is wrong . you should arrange proper json data format
//Like this:-
{
  "obj1": {
    "error": false,
    "user": {
      "br_code": 12,
      "mem_id": 13,
      "username": "novalyn",
      "email": "gsac_tabaco@yahoo.com",
      "created_at": "2016-07-22 09:05:21"
    }
  },
  "obj2": {
    "error": false,
    "sl_summ": [
      {
        "sl_desc": "PA : Savings Account",
        "tr_date": "2015-08-17",
        "actual_balance": "483.67",
        "available_balance": "483.67"
      },
      {
        "sl_desc": "PA : Savings - Cash Bond",
        "tr_date": "2015-08-28",
        "actual_balance": "10129.43",
        "available_balance": "10129.43"
      }
    ]
  }
}
</code>```

Body:
How to fetch this Two Json Response and save the json response in SQLite. Hope you will guide me how to fetch this Json object inside a Json Array inside an Object

My problem is a cannot fetch the 2nd json response. I noticed that only the 1st response was returned

Login response in Logcat

D/RegisterActivity: Login Response: {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}{"error":false,"sl_summ":[{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]}

only the 1st response was returned in this Logcat

D/sl_summ: JSON String : {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/sl_summ: -error attribute: false
D/TEST: org.json.JSONException: No value for sl_summ

This is the 1st Json response. Was parse and stored in SQLite

{
  "error": false,
  "user": {
    "br_code": 12,
    "mem_id": 13,
    "username": "novalyn",
    "email": "gsac_tabaco@yahoo.com",
    "created_at": "2016-07-22 09:05:21"
  }
}

This is the 2nd Json response. Json object inside a JSON Array. Was not parse and inserted in SQLite

{
  "error": false,
  "sl_summ":
  [
    {
      "sl_desc": "PA : Savings Account",
      "tr_date": "2015-08-17",
      "actual_balance": "483.67",
      "available_balance": "483.67"
    },
    {
      "sl_desc": "PA : Savings - Cash Bond",
      "tr_date": "2015-08-28",
      "actual_balance": "10129.43",
      "available_balance": "10129.43"
    }
  ]
}

Whole JSON response

{
  "error": false,
  "user": {
    "br_code": 12,
    "mem_id": 13,
    "username": "novalyn",
    "email": "gsac_tabaco@yahoo.com",
    "created_at": "2016-07-22 09:05:21"
  }
}
{
  "error": false,
  "sl_summ":
  [
    {
      "sl_desc": "PA : Savings Account",
      "tr_date": "2015-08-17",
      "actual_balance": "483.67",
      "available_balance": "483.67"
    },
    {
      "sl_desc": "PA : Savings - Cash Bond",
      "tr_date": "2015-08-28",
      "actual_balance": "10129.43",
      "available_balance": "10129.43"
    }
  ]
}

This is my Login.java

try {
    JSONObject jObj = new JSONObject(response.toString());
    boolean error = jObj.getBoolean("error");
    Log.d(TAG, "Checking JSON Object" +jObj);

    Log.d("TEST", "-error attribute             : " + jObj.get("error").toString());
    // Check for error node in json
    if (!error) {
        // user successfully logged in
        // Create login session
        session.setLogin(true);

        // Now store the user in SQLite
        //String uid = jObj.getString("uid");

        JSONObject user = jObj.getJSONObject("user");
            Log.d("USER", "-user object     : " + jObj.getJSONObject("user").toString());
        String br_code = user.getString("br_code");
            Log.d("USER", "-br_code         : " + br_code);
        String mem_id = user.getString("mem_id");
            Log.d("USER", "-mem_id          : " + mem_id);
        String username = user.getString("username");
            Log.d("USER", "-username        : " + username);
        String email = user.getString("email");
            Log.d("USER", "-email           : " + email);
        String created_at = user.getString("created_at");
            Log.d("USER", "-created at      : " + created_at);

        // Inserting row in users table
        db.addUser(br_code, mem_id, username, email, created_at);

        //SL Details
        try {
            // read the json string into a json object
            JSONObject jsonObject = new JSONObject(response.toString());
            Log.d("sl_summ", "JSON String                  : " + jsonObject.toString());
            // access individual json object thru jsonObject.get("FIELD_NAME")
            Log.d("sl_summ", "-error attribute             : " + jsonObject.get("error").toString());
            // access individual json array thru jsonObject.getJSONArray("FIELD_NAME")
            Log.d("sl_summ", "-sl_summ array               : " + jsonObject.getJSONArray("sl_summ").toString());
            JSONArray array = ((JSONArray)jsonObject.getJSONArray("sl_summ"));
            for (int index=0; index<array.length(); index++) {
                JSONObject object = (JSONObject)array.get(index);
                Log.d("SL_SUUM", "-sl_desc attribute           : " + object.get("sl_desc").toString());
                Log.d("SL_SUUM", "-tr_date attribute           : " + object.get("tr_date").toString());
                Log.d("SL_SUUM", "-actual_balance attribute    : " + object.get("actual_balance").toString());
                Log.d("SL_SUUM", "-available_balance attribute : " + object.get("available_balance").toString());
                Log.d("SL_SUUM", "---------------------------------");
            }
        } catch (Exception exception) {
            Log.d("TEST", exception.toString());
        }

        // Launch main activity
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    } else {
        // Error in login. Get the error message
        String errorMsg = jObj.getString("error_msg");
        Toast.makeText(getApplicationContext(),
                errorMsg, Toast.LENGTH_LONG).show();
    }
} catch (JSONException e) {
    // JSON error
    e.printStackTrace();
    Log.d("TEST", e.toString());
    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}

SQlitehandler.java

public void addUserSLDTL(String sl_desc, String tr_date, String  actual_balance, String avail_balance){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(SL_DESC, sl_desc); // sl desc
    values.put(TR_DATE, tr_date); // trans date
    values.put(ACTUAL_BALANCE, actual_balance); // actual balance
    values.put(AVAILABLE_BALANCE, avail_balance); // availabe balance

    // Inserting Row
    long id = db.insertOrThrow(TABLE_MEMBERS_SLDTL, null, values);
    db.close(); // Closing database connection

    Log.d(TAG, "Members's SL Details was inserted into sldtl table: " + id);
    Log.d(TAG, "SL Desc: " + sl_desc);
    Log.d(TAG, "Transaction Date: " + tr_date);
    Log.d(TAG, "Actual Balance: " + actual_balance);
    Log.d(TAG, "Available Balance: " + avail_balance);
}

public HashMap<String, String> getUserSLDTL() {
    HashMap<String, String> sl_summ = new HashMap<String, String>();
    String selectQuery = "SELECT * FROM " + TABLE_MEMBERS_SLDTL;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // Move to first row
    cursor.moveToFirst();
    if (cursor.getCount() > 0) {
        sl_summ.put("sl_desc", cursor.getString(0));
        sl_summ.put("tr_date", cursor.getString(1));
        sl_summ.put("actual_balance", cursor.getString(2));
        sl_summ.put("avail_balance", cursor.getString(3));

        Log.d(TAG, "member's SLDTL data: " + sl_summ.toString());
    }
    else{
        Log.d(TAG, "member's SLDTL data is empty");
    }
    cursor.close();
    db.close();

    // return user
    Log.d(TAG, "Fetching member's SL details from Sqlite sldtl table: " + sl_summ.toString());

    return sl_summ;
}

Logcat message

D/RegisterActivity: Login Response: {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}{"error":false,"sl_summ":[{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]}
D/ViewRootImpl@dd06ab4[LoginActivity]: dispatchDetachedFromWindow
D/InputTransport: Input channel destroyed: fd=76
D/RegisterActivity: Checking JSON Object{"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/TEST: -error attribute             : false
D/SessionManager: User login session modified!
D/USER: -user object     : {"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}
D/USER: -br_code         : 12
D/USER: -mem_id          : 13
D/USER: -username        : novalyn
D/USER: -email           : gsac_tabaco@yahoo.com
D/USER: -created at      : 2016-07-22 09:05:21
D/SQLiteHandler: New member was inserted into table members: 13
D/SQLiteHandler: BR CODE: 12
D/SQLiteHandler: Member ID: 13
D/SQLiteHandler: Username: novalyn
D/SQLiteHandler: Email: gsac_tabaco@yahoo.com
D/SQLiteHandler: Created at: 2016-07-22 09:05:21
D/sl_summ: JSON String                  : {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/sl_summ: -error attribute             : false
D/TEST: org.json.JSONException: No value for sl_summ

Login.php

<?php
session_start();
require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// json response array
$response = array("error" => FALSE);
$br_response = array("error" => FALSE);
$sl_response["error"] = FALSE;
$sl_response["sl_summ"] = array();

$arclass = "13";
$loanclass = "12";
$accintreceivable = "21";

if (isset($_POST['username']) && isset($_POST['password'])) {

    // receiving the post params
    $username= $_POST['username'];
    $password = $_POST['password'];

    // get the user by username and password
    $user = $db->getUserByUsernameAndPassword($username, $password);

    if ($user != null) {
        // user is found
        $response["error"] = FALSE;
        $response["user"]["br_code"] = $user["MEMBER_ID_BRCODE"];
        $response["user"]["mem_id"] = $user["MEMBER_ID"];
        $response["user"]["username"] = $user["USERNAME"];
        $response["user"]["email"] = $user["EMAIL"];
        $response["user"]["created_at"] = $user["REG_DATE"];
        json_encode($response, true);
        //Displaying json value
        echo json_encode($response, true);

        //$_SESSION= json_encode($response, true);
        // $_SESSION['br_code']= $user["MEMBER_ID_BRCODE"];
        // $_SESSION['username']= $user["USERNAME"];
        // $_SESSION['mem_id']= $user["MEMBER_ID"];

        $br_code= $user["MEMBER_ID_BRCODE"];
        $clientid= $user["MEMBER_ID"];
        //Check if the branch of the user exist in the BRANCH table
        $user = $db->getBrnchInfo($br_code);
        //var_dump($user);
        if ($user != null) {
            $br_response["error"] = FALSE;
            $br_response["user_br"]["ar_class"] = $arclass;
            $br_response["user_br"]["loan_class"] = $loanclass;
            $br_response["user_br"]["accnt_receivable"] = $accintreceivable;
            $br_response["user_br"]["br_code"] = $user["br_id"];
            $br_response["user_br"]["br_desc"] = $user["br_desc"];
            $br_response["user_br"]["br_address"] = $user["br_add"];
            $br_response["user_br"]["br_manager"] = $user["br_manager"];
            $br_response["user_br"]["br_accronym"] = $user["br_accronym"];
            $br_response["user_br"]["br_trans_date"] = $user["br_trans_date"];
            //json_encode($br_response, true);
            //echo json_encode($br_response, true);

            $trans_date = strtotime($user["br_trans_date"]);
            $date  = date('d',$trans_date);
            $year  = date('Y',$trans_date);
            $month = date('m',$trans_date);

            $user_sldtl = $db->getUserSLsummary($arclass, $loanclass, $accintreceivable, $date, $year, $month, $br_code, $clientid);

            If($user_sldtl != null) {
                 for($i = 0; $i < count($user_sldtl); $i++){
                    $item = array();
                        $item["sl_desc"] = $user_sldtl[$i][7];
                        $item["tr_date"] = $user_sldtl[$i][10];
                        $item["actual_balance"] = $user_sldtl[$i][14];
                        $item["available_balance"] = $user_sldtl[$i][14];

                        $response = array("error" => FALSE);
                        $sl_response["sl_summ"][] = $item;
                    }
                    json_encode($sl_response);
                    echo json_encode($sl_response, true);
             }
             else {
                 $sl_response["error"] = TRUE;
                 $sl_response["error_msg"] = "NO SL Details found!";
                 echo json_encode($sl_response);
             }
        }
        else {
            $response["error"] = TRUE;
            $response["error_msg"] = "No branch code found.!";
            json_encode($response);
           // echo json_encode($response);
        }

        //header('Location: accountsummary.php');
    } else {
        // user is not found with the credentials
        $response["error"] = TRUE;
        $response["error_msg"] = "Login credentials are wrong. Please try again!";
        json_encode($response);
        echo json_encode($response);
        // echo "
" .$username. "
";
        // echo $password;
    }
} else {
    // required post params is missing
    $response["error"] = TRUE;
    $response["error_msg"] = "Required parameters username or password is missing!";
    json_encode($response);
    echo json_encode($response);
}
?>


问:
How to unselect multiple UITableview cell by tapping the selected button again

Hi, I wanted to select multiple UITableViewCells and unselect any by tapping again.

Following are my codes of didSelectRowAtIndexPath: and cellForRowAtIndexPath:

```<code>-(UITableViewCell *)tableView:(UITableView *)tableView
   cellForRowAtIndexPath:(NSIndexPath *)indexPath
   {
NSString *cellIdentifier = @"serviceTypeSelectionCell";
ServiceTypeSelectionTableViewCell *serviceTypeCell = (ServiceTypeSelectionTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (serviceTypeCell == nil)
{
    serviceTypeCell = [[ServiceTypeSelectionTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
//serviceDetailsCell.noOfQuantityTextField.tag = indexPath.row;
serviceTypeCell.serviceTypeNameLabel.text = [NSString stringWithFormat:@"%@",arrayOfServiceTypes[indexPath.row][@"sub_cat_name"]];

if([[arrayOfSelectedBoolValues objectAtIndex:indexPath.row] boolValue])
{
    serviceTypeCell.serviceTypeImageView.image = [UIImage imageNamed:@"cancellation_reason_correct_icon"];
}
else {
    serviceTypeCell.serviceTypeImageView.image = [UIImage imageNamed:@"cancellation_reason_unselect_icon"];
}
return serviceTypeCell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
for (int i = 0; i < [arrayOfServiceTypes count]; i++)//Make all Rows To UnSelected
{
   [arrayOfSelectedBoolValues replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:NO]];
}
[arrayOfSelectedBoolValues addObjectsFromArray:sele:indexPath.row];
if(arrayOfSelectedBoolValues!=nil)
{
    [arrayOfSelectedBoolValues replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
}

    [arrayOfSelectedBoolValues replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
{
[self.tableView reloadData];
[self showOrHideAddButton];
}
</code>```

I have an existing code of single select and unselect of the above uitableview. And I can get multiple selection only by disabling all the above code and keep this part in didSelectRowAtIndexPath:.

```<code>-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 [arrayOfSelectedBoolValues replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
    [self.tableView reloadData];
    [self showOrHideAddButton];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.doneButton.hidden = YES;
    arrayOfSelectedBoolValues = [[NSMutableArray alloc]init];

    for (int i = 0; i < [arrayOfServiceTypes count]; i++)
    {
        // [arrayOfexpOrCollBoolValues addObject:[NSNumber numberWithBool:NO]];
        [arrayOfSelectedBoolValues addObject:[NSNumber numberWithBool:NO]];
    }
    [self sendServiceToGetServiceTypes];
}
</code>```

so please anyone post a structured code according to my code to select multiple tableviewcells and unselect any cells by tapping again before send selected values to the server.

Thanks in Advance.

答:
Try modifying your didSelectRowAtIndexPath like

```<code>-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{
    if (_selectedIndexes == nil) {
        self.selectedIndexes = [NSMutableArray array];
    }
    if ([_selectedIndexes containsObject:indexPath]) {
        [_selectedIndexes removeObject:indexPath];

    } else {
        [_selectedIndexes addObject:indexPath];

    }
     [self.tableView reloadData];
       [self showOrHideAddButton];

    }
</code>```

And in the cellForRowAtIndexPath try modifying the code to change the serviceTypeImageView image like

```<code>if([_selectedIndexes containsObject:indexPath])
    {
        serviceTypeCell.serviceTypeImageView.image = [UIImage imageNamed:@"cancellation_reason_correct_icon"];
    }
    else {
        serviceTypeCell.serviceTypeImageView.image = [UIImage imageNamed:@"cancellation_reason_unselect_icon"];
    }
</code>```

Here selectedIndexes is a mutable array that keeps track of the selected indexPaths

```<code>@property(nonatomic, strong) NSMutableArray *selectedIndexes;
</code>```

Body:
Hi, I wanted to select multiple UITableViewCells and unselect any by tapping again.

Following are my codes of didSelectRowAtIndexPath: and cellForRowAtIndexPath:

-(UITableViewCell *)tableView:(UITableView *)tableView
   cellForRowAtIndexPath:(NSIndexPath *)indexPath
   {
NSString *cellIdentifier = @"serviceTypeSelectionCell";
ServiceTypeSelectionTableViewCell *serviceTypeCell = (ServiceTypeSelectionTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (serviceTypeCell == nil)
{
    serviceTypeCell = [[ServiceTypeSelectionTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
//serviceDetailsCell.noOfQuantityTextField.tag = indexPath.row;
serviceTypeCell.serviceTypeNameLabel.text = [NSString stringWithFormat:@"%@",arrayOfServiceTypes[indexPath.row][@"sub_cat_name"]];

if([[arrayOfSelectedBoolValues objectAtIndex:indexPath.row] boolValue])
{
    serviceTypeCell.serviceTypeImageView.image = [UIImage imageNamed:@"cancellation_reason_correct_icon"];
}
else {
    serviceTypeCell.serviceTypeImageView.image = [UIImage imageNamed:@"cancellation_reason_unselect_icon"];
}
return serviceTypeCell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
for (int i = 0; i < [arrayOfServiceTypes count]; i++)//Make all Rows To UnSelected
{
   [arrayOfSelectedBoolValues replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:NO]];
}
[arrayOfSelectedBoolValues addObjectsFromArray:sele:indexPath.row];
if(arrayOfSelectedBoolValues!=nil)
{
    [arrayOfSelectedBoolValues replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
}

    [arrayOfSelectedBoolValues replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
{
[self.tableView reloadData];
[self showOrHideAddButton];
}

I have an existing code of single select and unselect of the above uitableview. And I can get multiple selection only by disabling all the above code and keep this part in didSelectRowAtIndexPath:.

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 [arrayOfSelectedBoolValues replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
    [self.tableView reloadData];
    [self showOrHideAddButton];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.doneButton.hidden = YES;
    arrayOfSelectedBoolValues = [[NSMutableArray alloc]init];

    for (int i = 0; i < [arrayOfServiceTypes count]; i++)
    {
        // [arrayOfexpOrCollBoolValues addObject:[NSNumber numberWithBool:NO]];
        [arrayOfSelectedBoolValues addObject:[NSNumber numberWithBool:NO]];
    }
    [self sendServiceToGetServiceTypes];
}

so please anyone post a structured code according to my code to select multiple tableviewcells and unselect any cells by tapping again before send selected values to the server.

Thanks in Advance.

Body:
Try modifying your didSelectRowAtIndexPath like

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{
    if (_selectedIndexes == nil) {
        self.selectedIndexes = [NSMutableArray array];
    }
    if ([_selectedIndexes containsObject:indexPath]) {
        [_selectedIndexes removeObject:indexPath];

    } else {
        [_selectedIndexes addObject:indexPath];

    }
     [self.tableView reloadData];
       [self showOrHideAddButton];

    }

And in the cellForRowAtIndexPath try modifying the code to change the serviceTypeImageView image like

if([_selectedIndexes containsObject:indexPath])
    {
        serviceTypeCell.serviceTypeImageView.image = [UIImage imageNamed:@"cancellation_reason_correct_icon"];
    }
    else {
        serviceTypeCell.serviceTypeImageView.image = [UIImage imageNamed:@"cancellation_reason_unselect_icon"];
    }

Here selectedIndexes is a mutable array that keeps track of the selected indexPaths

@property(nonatomic, strong) NSMutableArray *selectedIndexes;


问:
How to set a random color for each group of elements looping through an array?
I am trying to set a different colors using jquery on each .elements, their children (.element) should have the same color but the attribution of color should be random for each .elements. How can I do it ?

Here's an example : https://jsfiddle.net/auscpzy6/6/

Html

```<code><div class="elements"> <!-- children share the same color -->
  <div class="element">1</div> <!-- exmaple : red -->
  <div class="element">2</div> <!-- exmaple : red -->
</div>

<div class="elements"> <!-- children share the same color -->
  <div class="element">3</div> <!-- exmaple : blue -->
  <div class="element">4</div> <!-- exmaple : blue -->
  <div class="element">5</div> <!-- exmaple : blue -->
</div>

<div class="elements"> <!-- children share the same color -->
  <div class="element">6</div> <!-- exmaple : yellow -->
</div>

<div class="elements"> <!-- children share the same color -->
  <div class="element">7</div> <!-- exmaple : blue -->
  <div class="element">8</div> <!-- exmaple : blue -->
</div>
</code>```

Javascript : This is what I tried but everything stay on the same color.

```<code>function eachEl(el){
    var items = ["blue", "red", "yellow"];
    var item = items[Math.floor(Math.random()*items.length)];
    $(el).css({
        "color": item,
    });
}

$(".elements").each(function() {
    eachEl('.element');
});
</code>```

Any solution ?

答:
function ChangeColorCtrl($) {
  const colors = ['red', 'yellow', 'blue', 'green'];

  return $('.elements')
    .each((i, group) => {
      const background = colors[Math.floor(Math.random() * colors.length)];

      return $(group)
        .each((j, child) => $(child).css({background}))
      ;
    })
  ;
}

jQuery(document).ready(ChangeColorCtrl);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="elements"> <!-- children share the same color -->
  <div class="element">1</div> <!-- exmaple : red -->
  <div class="element">2</div> <!-- exmaple : red -->
</div>

<div class="elements"> <!-- children share the same color -->
  <div class="element">3</div> <!-- exmaple : blue -->
  <div class="element">4</div> <!-- exmaple : blue -->
  <div class="element">5</div> <!-- exmaple : blue -->
</div>

<div class="elements"> <!-- children share the same color -->
  <div class="element">6</div> <!-- exmaple : yellow -->
</div>

<div class="elements"> <!-- children share the same color -->
  <div class="element">7</div> <!-- exmaple : blue -->
  <div class="element">8</div> <!-- exmaple : blue -->
</div></code>```

Body:
I am trying to set a different colors using jquery on each .elements, their children (.element) should have the same color but the attribution of color should be random for each .elements. How can I do it ?

Here's an example : https://jsfiddle.net/auscpzy6/6/

Html

1

2

3

4

5

6

7

8

Javascript : This is what I tried but everything stay on the same color.

function eachEl(el){
    var items = ["blue", "red", "yellow"];
    var item = items[Math.floor(Math.random()*items.length)];
    $(el).css({
        "color": item,
    });
}

$(".elements").each(function() {
    eachEl('.element');
});

Any solution ?

Body:
function ChangeColorCtrl($) {
  const colors = ['red', 'yellow', 'blue', 'green'];

  return $('.elements')
    .each((i, group) => {
      const background = colors[Math.floor(Math.random() * colors.length)];

      return $(group)
        .each((j, child) => $(child).css({background}))
      ;
    })
  ;
}

jQuery(document).ready(ChangeColorCtrl);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="elements"> <!-- children share the same color -->
  <div class="element">1</div> <!-- exmaple : red -->
  <div class="element">2</div> <!-- exmaple : red -->
</div>

<div class="elements"> <!-- children share the same color -->
  <div class="element">3</div> <!-- exmaple : blue -->
  <div class="element">4</div> <!-- exmaple : blue -->
  <div class="element">5</div> <!-- exmaple : blue -->
</div>

<div class="elements"> <!-- children share the same color -->
  <div class="element">6</div> <!-- exmaple : yellow -->
</div>

<div class="elements"> <!-- children share the same color -->
  <div class="element">7</div> <!-- exmaple : blue -->
  <div class="element">8</div> <!-- exmaple : blue -->
</div>