问:
Oracle SQL Merge query to fix the data integrity issue
```<code>create table abc
(
job_id integer
,etl_job_run_day date
,cust_sid integer
,cust_id number(38,0)
,cust_first_name varchar2(100)
,cust_last_name varchar2(100)
,effective_dt_from date
,effective_dt_to date
,version integer
,latest_fl varchar2(1)
,actual_cust_id integer
);

insert into abc values (123,01.01.2020,100,6842,'Tony','Greig',10.01.2020 00:00:00,31.12.2199 23:59:59,1,'Y','');
insert into abc values (123,01.01.2020,123,6842,'Tony','Greig',10.01.2020 00:00:00,31.12.2199 23:59:59,1,'Y',9011);
</code>```

JOB_ID  ETL_JOB_RUN_DAY    CUST_SID CUST_ID CUST_FIRST_NAME CUST_LAST_NAME   EFFECTIVE_DATE_FROM   EFFECTIVE_DATE_TO    VERSION LATEST_FL ACTUAL_CUST_ID
123 01.01.20 00:00:00  100      6842    Tony        Greig        10.01.00 00:00:00     31.12.99 23:59:59    1   Y
123 15.01.20 00:00:00  148      6842    Tony        Greig        10.01.00 00:00:00     31.12.99 23:59:59    1   Y     9011
```

<p>so this is wrong due to some wrong historical data update so the expected values should be like this </p>

<pre class="lang-none prettyprint-override"><code>JOB_ID  ETL_JOB_RUN_DAY    CUST_SID CUST_ID CUST_FIRST_NAME CUST_LAST_NAME   EFFECTIVE_DATE_FROM   EFFECTIVE_DATE_TO    VERSION LATEST_FL ACTUAL_CUST_ID
123 01.01.20 00:00:00  100      6842    Tony        Greig        01.01.00 00:00:00     15.01.20 00:00:00    1   N
123 15.01.20 00:00:00  148      6842    Tony        Greig        15.01.20 00:00:00     31.12.99 23:59:59    2   Y     9011
</code>```

答:
First thing is that we need some primary key to clearly define the order of rows. We need to compare previous and next rows and for that an order is elementary. If we can use job_id, etl_job_run_day, cust_sid for that then you can find problematic rows using this query:

```<code>select *
  from (
    select job_id, etl_job_run_day, cust_sid, effective_dt_from edf, effective_dt_to edt, version, latest_fl,
           lag(latest_fl)  over (partition by job_id order by etl_job_run_day, cust_sid) prev_fl,
           lead(latest_fl) over (partition by job_id order by etl_job_run_day, cust_sid) next_fl,
           lag(effective_dt_to)  over (partition by job_id order by etl_job_run_day, cust_sid) prev_edt,
           lead(effective_dt_to) over (partition by job_id order by etl_job_run_day, cust_sid) next_edt,
           lead(etl_job_run_day) over (partition by job_id order by etl_job_run_day, cust_sid) next_run
      from abc
      where latest_fl = 'Y' )
  where edt in (prev_edt, next_edt)
</code>```

Please test it, if OK, you can use above query as source table in merge:

```<code>merge into abc a
using (
    select *
      from (
        select job_id, etl_job_run_day, cust_sid, effective_dt_from edf, effective_dt_to edt, version, latest_fl,
               lag(latest_fl)  over (partition by job_id order by etl_job_run_day, cust_sid) prev_fl,
               lead(latest_fl) over (partition by job_id order by etl_job_run_day, cust_sid) next_fl,
               lag(effective_dt_to)  over (partition by job_id order by etl_job_run_day, cust_sid) prev_edt,
               lead(effective_dt_to) over (partition by job_id order by etl_job_run_day, cust_sid) next_edt,
               lead(etl_job_run_day) over (partition by job_id order by etl_job_run_day, cust_sid) next_run
          from abc
          where latest_fl = 'Y' )
      where edt in (prev_edt, next_edt)) s
on (a.job_id = s.job_id and a.etl_job_run_day = s.etl_job_run_day and a.cust_sid = s.cust_sid)
when matched then update set
    a.latest_fl = case when next_fl = 'Y' then 'N' else a.latest_fl end,
    a.effective_dt_to   = case when next_fl = 'Y' and  next_edt = a.effective_dt_to
                                then next_run
                                else a.effective_dt_to end,
    a.effective_dt_from = case when prev_fl = 'Y' and  prev_edt = a.effective_dt_to
                                then etl_job_run_day
                                else a.effective_dt_to end,
    version = case when prev_fl = 'Y' then version + 1 else version end
</code>```

dbfiddle

This gave me requested values for your (corrected) sample data. Again, please test it. Make a copy if possible. If you have more than two positions in a row and there is always same version there, you will need additional merge, but in this case all following versions should be increased? You can do it using count() over (order by...) in next similiar merge.

Body:
create table abc
(
job_id integer
,etl_job_run_day date
,cust_sid integer
,cust_id number(38,0)
,cust_first_name varchar2(100)
,cust_last_name varchar2(100)
,effective_dt_from date
,effective_dt_to date
,version integer
,latest_fl varchar2(1)
,actual_cust_id integer
);

insert into abc values (123,01.01.2020,100,6842,'Tony','Greig',10.01.2020 00:00:00,31.12.2199 23:59:59,1,'Y','');
insert into abc values (123,01.01.2020,123,6842,'Tony','Greig',10.01.2020 00:00:00,31.12.2199 23:59:59,1,'Y',9011);

JOB_ID  ETL_JOB_RUN_DAY    CUST_SID CUST_ID CUST_FIRST_NAME CUST_LAST_NAME   EFFECTIVE_DATE_FROM   EFFECTIVE_DATE_TO    VERSION LATEST_FL ACTUAL_CUST_ID
123 01.01.20 00:00:00  100      6842    Tony        Greig        10.01.00 00:00:00     31.12.99 23:59:59    1   Y
123 15.01.20 00:00:00  148      6842    Tony        Greig        10.01.00 00:00:00     31.12.99 23:59:59    1   Y     9011

so this is wrong due to some wrong historical data update so the expected values should be like this

JOB_ID  ETL_JOB_RUN_DAY    CUST_SID CUST_ID CUST_FIRST_NAME CUST_LAST_NAME   EFFECTIVE_DATE_FROM   EFFECTIVE_DATE_TO    VERSION LATEST_FL ACTUAL_CUST_ID
123 01.01.20 00:00:00  100      6842    Tony        Greig        01.01.00 00:00:00     15.01.20 00:00:00    1   N
123 15.01.20 00:00:00  148      6842    Tony        Greig        15.01.20 00:00:00     31.12.99 23:59:59    2   Y     9011

Body:
First thing is that we need some primary key to clearly define the order of rows. We need to compare previous and next rows and for that an order is elementary. If we can use job_id, etl_job_run_day, cust_sid for that then you can find problematic rows using this query:

select *
  from (
    select job_id, etl_job_run_day, cust_sid, effective_dt_from edf, effective_dt_to edt, version, latest_fl,
           lag(latest_fl)  over (partition by job_id order by etl_job_run_day, cust_sid) prev_fl,
           lead(latest_fl) over (partition by job_id order by etl_job_run_day, cust_sid) next_fl,
           lag(effective_dt_to)  over (partition by job_id order by etl_job_run_day, cust_sid) prev_edt,
           lead(effective_dt_to) over (partition by job_id order by etl_job_run_day, cust_sid) next_edt,
           lead(etl_job_run_day) over (partition by job_id order by etl_job_run_day, cust_sid) next_run
      from abc
      where latest_fl = 'Y' )
  where edt in (prev_edt, next_edt)

Please test it, if OK, you can use above query as source table in merge:

merge into abc a
using (
    select *
      from (
        select job_id, etl_job_run_day, cust_sid, effective_dt_from edf, effective_dt_to edt, version, latest_fl,
               lag(latest_fl)  over (partition by job_id order by etl_job_run_day, cust_sid) prev_fl,
               lead(latest_fl) over (partition by job_id order by etl_job_run_day, cust_sid) next_fl,
               lag(effective_dt_to)  over (partition by job_id order by etl_job_run_day, cust_sid) prev_edt,
               lead(effective_dt_to) over (partition by job_id order by etl_job_run_day, cust_sid) next_edt,
               lead(etl_job_run_day) over (partition by job_id order by etl_job_run_day, cust_sid) next_run
          from abc
          where latest_fl = 'Y' )
      where edt in (prev_edt, next_edt)) s
on (a.job_id = s.job_id and a.etl_job_run_day = s.etl_job_run_day and a.cust_sid = s.cust_sid)
when matched then update set
    a.latest_fl = case when next_fl = 'Y' then 'N' else a.latest_fl end,
    a.effective_dt_to   = case when next_fl = 'Y' and  next_edt = a.effective_dt_to
                                then next_run
                                else a.effective_dt_to end,
    a.effective_dt_from = case when prev_fl = 'Y' and  prev_edt = a.effective_dt_to
                                then etl_job_run_day
                                else a.effective_dt_to end,
    version = case when prev_fl = 'Y' then version + 1 else version end

dbfiddle

This gave me requested values for your (corrected) sample data. Again, please test it. Make a copy if possible. If you have more than two positions in a row and there is always same version there, you will need additional merge, but in this case all following versions should be increased? You can do it using count() over (order by...) in next similiar merge.


来源: stackexchange

问:
ReactJs - Not able to display all data at once. The loop to get the data runs automatically by re-rendering one by one and stops at the last data set
Image of my ReactJS web page and the console view to see the data structure

My code below:

```<code>    import React, {
  Component,
  useState,
  useEffect
} from 'react';
import './App.css';
import {
  Card,
  CardImg,
  CardText,
  CardBody,
  CardTitle,
  CardSubtitle,
  Button
} from 'reactstrap';
import Image from 'react-image-resizer';
import * as firebase from 'firebase';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {

    };
  }

   async getOrderbookData() {
      try{
       var clientArray = ['Client1', 'Client2', 'Client3', 'Client4',
                        'Client5', 'Client6', 'Client7'];
    for (var i=0; i<clientArray.length; i++) {
    const db = firebase.firestore();
    await db.collection('Orderbook').get().then((querySnapshot) => {
      var orderbooks = []
      var orderbook = []
         querySnapshot.forEach(doc => {
            orderbooks.push(doc.data())
              console.log('THISS'+ orderbooks)
      });
       orderbook = orderbooks[i].body
       console.log('i value:' + i);

      this.setState({
          orderbook: orderbook
      })
    });
   }
    }catch (err) {
       return "Error:" + err
   }
  }

  async componentDidMount() {

    this.getMarginData()

    this.getOrderbookData()

   }

  render() {
    return (
      <div className = "App" >

          <Image src={ require('./investsaathilogo.png')}
          height = {100} width = {100}/>

        <h2> Orderbook Data </h2>

              <h5 className="container">
          {
            console.log('ORDERBOOKNOW' + this.state.orderbook),

        this.state.orderbook && this.state.orderbook.map((order, key) =>
          <div key={order + key}>

          <li>BuySell: {order.BuySell}</li>

        </div>

         )
         }
             </h5>

            </div>
        );
      }
     }

    export default App;
</code>```

Now I am able to display the data for all clients and all their orders one by one. But React automatically re-renders the data one after the other. Does anyone know how to display all the clients data at once instead of it going through the loop automatically and stopping and displaying the last item of data in the loop?

答:
You can't JSON.stringify something and map. Rather do something like this,

import React, {
  Component,
  useState,
  useEffect
} from 'react';
import './App.css';
import {
  Card,
  CardImg,
  CardText,
  CardBody,
  CardTitle,
  CardSubtitle,
  Button
} from 'reactstrap';
import Image from 'react-image-resizer';
import * as firebase from 'firebase';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {}
  }

  getMarginData() {

    const db = firebase.firestore();
    return db.collection('Margin').get().then((querySnapshot) => {
      const margins = []
      querySnapshot.forEach(doc => {
        margins.push(doc.data())

        console.log(margins);
      });

      this.setState({
        margins: margins
      })

    });

  }

  getOrderbookData() {

    const db = firebase.firestore();
    return db.collection('Orderbook').get().then((querySnapshot) => {
      const orderbooks = []
      querySnapshot.forEach(doc => {
        orderbooks.push(doc.data())

        console.log(orderbooks);
      });

      this.setState({
        orderbooks: orderbooks[0]
      })

    });
  }

  componentDidMount() {

    this.getMarginData()
    this.getOrderbookData()

  }

  render() {
    return (

          <Image src={ require('./investsaathilogo.png')} height = {100} width = {100}/>

 Margin Data

                {this.state.margins && this.state.margins.map((margin, index) =>

                )}

 Orderbook Data

              <card>

 {JSON.stringify(this.state.orderbooks)}

              </card>

    );
  }
}

export default App;```

ContentLicense: CC BY-SA 4.0

Body:
Image of my ReactJS web page and the console view to see the data structure

My code below:

    import React, {
  Component,
  useState,
  useEffect
} from 'react';
import './App.css';
import {
  Card,
  CardImg,
  CardText,
  CardBody,
  CardTitle,
  CardSubtitle,
  Button
} from 'reactstrap';
import Image from 'react-image-resizer';
import * as firebase from 'firebase';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {

    };
  }

   async getOrderbookData() {
      try{
       var clientArray = ['Client1', 'Client2', 'Client3', 'Client4',
                        'Client5', 'Client6', 'Client7'];
    for (var i=0; i<clientArray.length; i++) {
    const db = firebase.firestore();
    await db.collection('Orderbook').get().then((querySnapshot) => {
      var orderbooks = []
      var orderbook = []
         querySnapshot.forEach(doc => {
            orderbooks.push(doc.data())
              console.log('THISS'+ orderbooks)
      });
       orderbook = orderbooks[i].body
       console.log('i value:' + i);

      this.setState({
          orderbook: orderbook
      })
    });
   }
    }catch (err) {
       return "Error:" + err
   }
  }

  async componentDidMount() {

    this.getMarginData()

    this.getOrderbookData()

   }

  render() {
    return (

          <Image src={ require('./investsaathilogo.png')}
          height = {100} width = {100}/>

 Orderbook Data

          {
            console.log('ORDERBOOKNOW' + this.state.orderbook),

        this.state.orderbook && this.state.orderbook.map((order, key) =>

BuySell: {order.BuySell}

         )
         }

        );
      }
     }

    export default App;

Now I am able to display the data for all clients and all their orders one by one. But React automatically re-renders the data one after the other. Does anyone know how to display all the clients data at once instead of it going through the loop automatically and stopping and displaying the last item of data in the loop?

Body:
You can't JSON.stringify something and map. Rather do something like this,

import React, {
  Component,
  useState,
  useEffect
} from 'react';
import './App.css';
import {
  Card,
  CardImg,
  CardText,
  CardBody,
  CardTitle,
  CardSubtitle,
  Button
} from 'reactstrap';
import Image from 'react-image-resizer';
import * as firebase from 'firebase';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {}
  }

  getMarginData() {

    const db = firebase.firestore();
    return db.collection('Margin').get().then((querySnapshot) => {
      const margins = []
      querySnapshot.forEach(doc => {
        margins.push(doc.data())

        console.log(margins);
      });

      this.setState({
        margins: margins
      })

    });

  }

  getOrderbookData() {

    const db = firebase.firestore();
    return db.collection('Orderbook').get().then((querySnapshot) => {
      const orderbooks = []
      querySnapshot.forEach(doc => {
        orderbooks.push(doc.data())

        console.log(orderbooks);
      });

      this.setState({
        orderbooks: orderbooks[0]
      })

    });
  }

  componentDidMount() {

    this.getMarginData()
    this.getOrderbookData()

  }

  render() {
    return (
      <div className = "App" >

          <Image src={ require('./investsaathilogo.png')} height = {100} width = {100}/>

          <p>
              <h2> Margin Data </h2>
              <h5>
                {this.state.margins && this.state.margins.map((margin, index) =>
                  <div key = {margin.Client1.ALB} > < /div>
                )}
              </h5>
          </p>

          <p>
              <h2> Orderbook Data </h2>
              <card>
                  <h5> {JSON.stringify(this.state.orderbooks)} </h5>
              </card>
          </p>

      </div>
    );
  }
}

export default App;


问:
Android Studio: Resolving Duplicate Classes
When I try to run my android application on an Android device, the gradle console reports the following error:

```<code>Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/loopj/android/http/AsyncHttpClient$1.class
</code>```

When I search for the "AsyncHttpClient" class, I see that it's indeed being found in two separate locations:

```<code>/Users/Afflatus/.gradle/caches/modules-2/files-2.1/com.loopj.android/android-async-http/1.4.9/5d171c3cd5343e5997f974561abed21442273fd1/android-async-http-1.4.9-sources.jar!/com/loopj/android/http/AsyncHttpClient.java

/Users/Afflatus/.ideaLibSources/android-async-http-1.4.9-sources.jar!/com/loopj/android/http/AsyncHttpClient.java
</code>```

The first path seems to suggest it's a "cache" file... so I've tried invalidating & restarting my cache, but both files are still there after the gradle gets rebuilt and I try to run the application. I've read in alternate posts that it can be resolved by deleting one of the files... So I went to the cache location and deleted all the files found in the "1.4.9" folder... unfortunantly after reopening Android Studio, a new cache file gets created and I get the same error.

Other posts (here, here,here, and here) suggest if I add "./gradlew clean" to the root directory it would rebuild the gradle again just for the run (as far as I understand). So I tried doing that as well:

Which made my app's folder look like this:

But unfortunantly, that didn't help things I still get the same error. What am I doing wrong? What should I be doing?

答: Delete files with duplicate jar extensions in the libs folder. However, if there are no duplicate files and there is still a "Duplicate classes" error, look for the name in the rest of the "Duplicate classes ...." clause in the error section. For example, "duplicated classes 'dagger' bla bla". Delete the file named 'dagger' from the libs folder. (Be careful not to delete it with shift.)

ContentLicense: CC BY-SA 3.0

Body:
When I try to run my android application on an Android device, the gradle console reports the following error:

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/loopj/android/http/AsyncHttpClient$1.class

When I search for the "AsyncHttpClient" class, I see that it's indeed being found in two separate locations:

/Users/Afflatus/.gradle/caches/modules-2/files-2.1/com.loopj.android/android-async-http/1.4.9/5d171c3cd5343e5997f974561abed21442273fd1/android-async-http-1.4.9-sources.jar!/com/loopj/android/http/AsyncHttpClient.java

/Users/Afflatus/.ideaLibSources/android-async-http-1.4.9-sources.jar!/com/loopj/android/http/AsyncHttpClient.java

The first path seems to suggest it's a "cache" file... so I've tried invalidating & restarting my cache, but both files are still there after the gradle gets rebuilt and I try to run the application. I've read in alternate posts that it can be resolved by deleting one of the files... So I went to the cache location and deleted all the files found in the "1.4.9" folder... unfortunantly after reopening Android Studio, a new cache file gets created and I get the same error.

Other posts (here, here,here, and here) suggest if I add "./gradlew clean" to the root directory it would rebuild the gradle again just for the run (as far as I understand). So I tried doing that as well:

Which made my app's folder look like this:

But unfortunantly, that didn't help things I still get the same error. What am I doing wrong? What should I be doing?


问:
Read Excel cell value and not the formula computing it -openpyxl
I am using openpyxl to read cell value (excel addin-webservice update this column.
)

I have used data_only = True but it is not showing the current cell value instead it is the value stored the last time Excel read the sheet.

```<code>wbFile = openpyxl.load_workbook(filename = xxxx,data_only=True)
wsFile = wbFile[c_sSheet]
</code>```

How can i read the cell actual value ?

答:
I solved this problem by the following way:

```<code>import xlwings
from openpyxl import load_workbook

data = load_workbook('PATH_TO_YOUR_XLSX_FILE')
data['sheet_name']['A1'].value = 1
data.save('PATH_TO_YOUR_XLSX_FILE')

excel_app = xlwings.App(visible=False)
excel_book = excel_app.books.open('PATH_TO_YOUR_XLSX_FILE')
excel_book.save()
excel_book.close()
excel_app.quit()

data = load_workbook('PATH_TO_YOUR_XLSX_FILE', data_only=True)
</code>```

I hope, this can help You...

Body:
I am using openpyxl to read cell value (excel addin-webservice update this column.
)

I have used data_only = True but it is not showing the current cell value instead it is the value stored the last time Excel read the sheet.

wbFile = openpyxl.load_workbook(filename = xxxx,data_only=True)
wsFile = wbFile[c_sSheet]

How can i read the cell actual value ?

Body:
I solved this problem by the following way:

import xlwings
from openpyxl import load_workbook

data = load_workbook('PATH_TO_YOUR_XLSX_FILE')
data['sheet_name']['A1'].value = 1
data.save('PATH_TO_YOUR_XLSX_FILE')

excel_app = xlwings.App(visible=False)
excel_book = excel_app.books.open('PATH_TO_YOUR_XLSX_FILE')
excel_book.save()
excel_book.close()
excel_app.quit()

data = load_workbook('PATH_TO_YOUR_XLSX_FILE', data_only=True)

I hope, this can help You...


问:
Is there a curl/wget option that prevents saving files in case of http errors?
I want to download a lot of urls in a script but I do not want to save the ones that lead to HTTP errors.

As far as I can tell from the man pages, neither curl or wget provide such functionality.
Does anyone know about another downloader who does?

答:
As alternative you can create a temporal rotational file:

```<code>wget http://example.net/myfile.json -O myfile.json.tmp -t 3 -q && mv list.json.tmp list.json
</code>```

The previous command will always download the file "myfile.json.tmp" however only when the wget exit status is equal to 0 the file is rotated as "myfile.json".

This solution will prevent to overwrite the final file when a network failure occurs.

The advantage of this method is that in case that something is wrong you can inspect the temporal file and see what error message is returned.

The "-t" parameter attempt to download the file several times in case of error.

The "-q" is the quiet mode and it's important to use with cron because cron will report any output of wget.

The "-O" is the output file path and name.

Remember that for Cron schedules it's very important to provide always the full path for all the files and in this case for the "wget" program it self as well.

OwnerDisplayName: kiwi

Body:
As alternative you can create a temporal rotational file:

wget http://example.net/myfile.json -O myfile.json.tmp -t 3 -q && mv list.json.tmp list.json

The previous command will always download the file "myfile.json.tmp" however only when the wget exit status is equal to 0 the file is rotated as "myfile.json".

This solution will prevent to overwrite the final file when a network failure occurs.

The advantage of this method is that in case that something is wrong you can inspect the temporal file and see what error message is returned.

The "-t" parameter attempt to download the file several times in case of error.

The "-q" is the quiet mode and it's important to use with cron because cron will report any output of wget.

The "-O" is the output file path and name.

Remember that for Cron schedules it's very important to provide always the full path for all the files and in this case for the "wget" program it self as well.


问:
play MIDI files in python?
I'm looking for a method to play midi files in python.
It seems python does not support MIDI in its standard library.
After I searched, I found some python midi librarys such as pythonmidi.
However, most of them can only create and read MIDI file without playing function.
I would like to find a python midi library including playing method.
Any recommendations? Thanks!</p>

答: Use pygame to play your midi file. Examples are here or here</p>

Title: play MIDI files in python?


问:
How to compare two lists and if they have an equal value take the two indexes of the lists
How would you go about comparing two lists and saying that if these two lists have an equal value take index of the two different spots and spit out two other list values from two different lists at that index. Both lists have equally as many values both of the lists that should be compared have ids in them and the other two that are supposed to write out value have categoryNames in them.  My code looks like this...

```<code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;

namespace PrestaConverter
{
    public class ExcellCreation
    {
        #region privata variabler

        /// <summary>
        /// WhatExcelFile Håller reda på Vilken excelfil som ska sparas,
        /// Name Namnet på sparfilen,
        /// count är en räknare som ger id till Kategorierna
        /// </summary>
        Hashtable myHashtable = new Hashtable();
        private int WhatExcellFile;
        private string name = "CategoriesCatalog";
        private List<string> ColumnNames = new List<string>() {"ID",
            "Active(0/1)",
            "Name*",
            "Parent Category",
            "Root Category(0/1)",
            "Description",
            "Meta title",
            "Meta keywords",
            "Meta description",
            "URL rewritten",
            "Image URL"
        };
        private Categories categories1 = new Categories();
        private Categories categories2 = new Categories();
        private Categories categories3 = new Categories();
        private int count;
        ExcelConverter converter = new ExcelConverter();

        #endregion

        #region Skapa excel

        /// <summary>
        /// Funktion som skapar de nya Excelfilerna
        /// </summary>
        /// <param name="excelValue">Kategorinamnen sänds över till denna funktion för upplägg i ny fil</param>
        /// <param name="rowAmmount">Används till att få tag på hur många rader som ska existera i excel filen</param>
        /// <returns></returns>
        public string CreateExcel(List<Categories> categories)
        {
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

            if (xlApp == null)
            {
                return "Excel är inte korrekt installerat";
            }

            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;

            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            categories1 = categories[0];
            categories2 = categories[1];
            categories3 = categories[2];

            for(int i = 0; i < categories1.CategoryId.Count; i++)
            {
                if(categories1.NewCategoryId.Contains(categories1.CategoryId[i]) == false && categories1.CategoryId[i].Substring(3,4) == "0000")
                {
                    categories1.NewCategoryId.Add(categories1.CategoryId[i]);
                    categories1.NewCategoryName.Add(categories1.CategoryName[i]);
                }
            }
            Console.WriteLine(categories1.NewCategoryId.Count);
            for(int i = 0; i < ColumnNames.Count; i++)
            {
                xlWorkSheet.Cells[1, i + 1].Value2 = ColumnNames[i];
            }
            for(int i = 0; i < categories1.NewCategoryId.Count; i++)
            {
                xlWorkSheet.Cells[2 + i , 3].Value2 = categories1.NewCategoryName[i];
                xlWorkSheet.Cells[2 + i, 4].Value2 = "Home";
            }
            for(int i = 0; i < categories2.CategoryId.Count; i++)
            {
                if(categories2.NewCategoryId.Contains(categories2.CategoryId[i]) == false && categories2.CategoryId[i].Substring(5, 2) == "00")
                {
                    categories2.NewCategoryId.Add(categories2.CategoryId[i]);
                    categories2.NewCategoryName.Add(categories2.CategoryName[i]);
                }
            }

            Console.WriteLine(categories2.NewCategoryName.Count);
            for(int i = 0; i < categories1.NewCategoryId.Count; i++)
            {
                for(int j = 0; j < categories2.NewCategoryId.Count; j++)
                {
                    if(categories1.NewCategoryId[i].Substring(0,3) == categories2.NewCategoryId[j].Substring(0, 3))
                    {
                        categories2.parentCategoryId.Add(categories1.NewCategoryId[i]);
                        categories2.parentCategoryName.Add(categories1.NewCategoryName[i]);
                    }
                }
            }
            for(int i = 0; i < categories2.parentCategoryId.Count; i++)
            {
                xlWorkSheet.Cells[categories1.NewCategoryId.Count + i, 4].Value2 = categories2.parentCategoryName[i];
            }
            for(int i = 0; i < categories2.NewCategoryName.Count; i++)
            {
                xlWorkSheet.Cells[categories1.NewCategoryId.Count + i, 3].Value2 = categories2.NewCategoryName[i];
            }

            //Here saving the file in xlsx
            xlWorkBook.SaveAs(@"C:\Users\Jens Svensson\Documents\" + name + ".xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, misValue,
                misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

            xlWorkBook.Close(true);
            xlApp.Quit();

            return "Funkar";
        }

        #endregion

        private string createId(string Id, int start, int end)
        {
            return Id.Substring(start, end);
        }
    }
}
</code>```

TestCode

```<code>    public List<string> NewCategoryId = new List<string>();
    public List<string> NewCategoryName = new List<string>();

    public List<string> parentCategoryId = new List<string>();
    public List<string> parentCategoryName = new List<string>();

    parentCategoryId = <"3930000", "3930000",4230000, 5200000 >
    parentCategoryName = <"Computers", "Computers", Toys, Furniture>

    NewCategoryId = <"3931200", "4231400","5201300" "3931700">
    NewCategoryName = <"Chairs","HP","ToyCars", "Lenovo">

    for(int i = 0; i < NewCategoryId.Count; i++){

       for(int j = 0; parentCategoryId.Count; j++){
           if(parentCategoryId[j] == NewCategoryId[i]){
               Console.Write(NewCategoryId[i] + "     ")
               Console.Write(NewCategoryName[i] + "     ")
               Console.Write(parentCategoryId[j] + "   " )
               Console.Write(parentCategoryName[j] + "\n")
           }
       }

    }

Wanted result
3931700 Lenovo  3930000 Computers
3931200 HP      3930000 Computers
4231400 Chairs  4230000 Furniture
5201300 ToyCars 5201300 Toys
</code>```

This is an ish result that i whant but im just getting them scrambled so how to do this?

答:
You can retrieve matching elements with .Intersect(), then use .IndexOf() to get the indexes. Finally, access the index values of the other lists.

```<code>var list1 = new List<int> { 1, 2, 3, 4, 5 };
var list2 = new List<int> { 4, 5, 6, 7, 8 };

var intersectingValues = list1.Intersect(list2); // 4, 5
var interesectingValueIndexes = intersectingValues.Select(x =>
                                   new { I1 = list1.IndexOf(x), I2 = list2.IndexOf(x) });

var otherList1 = new List<string> { "a", "b", "c", "d", "e" };
var otherList2 = new List<string> { "f", "g", "h", "i", "j" };

var otherListIndexValues = interesectingValueIndexes.Select(x =>
                                   new { V1 = otherList1[x.I1], V2 = otherList2[x.I2] });
</code>```

Body:
How would you go about comparing two lists and saying that if these two lists have an equal value take index of the two different spots and spit out two other list values from two different lists at that index. Both lists have equally as many values both of the lists that should be compared have ids in them and the other two that are supposed to write out value have categoryNames in them.  My code looks like this...

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;

namespace PrestaConverter
{
    public class ExcellCreation
    {
        #region privata variabler

        ///
        /// WhatExcelFile Håller reda på Vilken excelfil som ska sparas,
        /// Name Namnet på sparfilen,
        /// count är en räknare som ger id till Kategorierna
        ///
        Hashtable myHashtable = new Hashtable();
        private int WhatExcellFile;
        private string name = "CategoriesCatalog";
        private List<string> ColumnNames = new List<string>() {"ID",
            "Active(0/1)",
            "Name*",
            "Parent Category",
            "Root Category(0/1)",
            "Description",
            "Meta title",
            "Meta keywords",
            "Meta description",
            "URL rewritten",
            "Image URL"
        };
        private Categories categories1 = new Categories();
        private Categories categories2 = new Categories();
        private Categories categories3 = new Categories();
        private int count;
        ExcelConverter converter = new ExcelConverter();

        #endregion

        #region Skapa excel

        ///
        /// Funktion som skapar de nya Excelfilerna
        ///
        /// <param name="excelValue">Kategorinamnen sänds över till denna funktion för upplägg i ny fil</param>
        /// <param name="rowAmmount">Används till att få tag på hur många rader som ska existera i excel filen</param>
        /// <returns></returns>
        public string CreateExcel(List<Categories> categories)
        {
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

            if (xlApp == null)
            {
                return "Excel är inte korrekt installerat";
            }

            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;

            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            categories1 = categories[0];
            categories2 = categories[1];
            categories3 = categories[2];

            for(int i = 0; i < categories1.CategoryId.Count; i++)
            {
                if(categories1.NewCategoryId.Contains(categories1.CategoryId[i]) == false && categories1.CategoryId[i].Substring(3,4) == "0000")
                {
                    categories1.NewCategoryId.Add(categories1.CategoryId[i]);
                    categories1.NewCategoryName.Add(categories1.CategoryName[i]);
                }
            }
            Console.WriteLine(categories1.NewCategoryId.Count);
            for(int i = 0; i < ColumnNames.Count; i++)
            {
                xlWorkSheet.Cells[1, i + 1].Value2 = ColumnNames[i];
            }
            for(int i = 0; i < categories1.NewCategoryId.Count; i++)
            {
                xlWorkSheet.Cells[2 + i , 3].Value2 = categories1.NewCategoryName[i];
                xlWorkSheet.Cells[2 + i, 4].Value2 = "Home";
            }
            for(int i = 0; i < categories2.CategoryId.Count; i++)
            {
                if(categories2.NewCategoryId.Contains(categories2.CategoryId[i]) == false && categories2.CategoryId[i].Substring(5, 2) == "00")
                {
                    categories2.NewCategoryId.Add(categories2.CategoryId[i]);
                    categories2.NewCategoryName.Add(categories2.CategoryName[i]);
                }
            }

            Console.WriteLine(categories2.NewCategoryName.Count);
            for(int i = 0; i < categories1.NewCategoryId.Count; i++)
            {
                for(int j = 0; j < categories2.NewCategoryId.Count; j++)
                {
                    if(categories1.NewCategoryId[i].Substring(0,3) == categories2.NewCategoryId[j].Substring(0, 3))
                    {
                        categories2.parentCategoryId.Add(categories1.NewCategoryId[i]);
                        categories2.parentCategoryName.Add(categories1.NewCategoryName[i]);
                    }
                }
            }
            for(int i = 0; i < categories2.parentCategoryId.Count; i++)
            {
                xlWorkSheet.Cells[categories1.NewCategoryId.Count + i, 4].Value2 = categories2.parentCategoryName[i];
            }
            for(int i = 0; i < categories2.NewCategoryName.Count; i++)
            {
                xlWorkSheet.Cells[categories1.NewCategoryId.Count + i, 3].Value2 = categories2.NewCategoryName[i];
            }

            //Here saving the file in xlsx
            xlWorkBook.SaveAs(@"C:\Users\Jens Svensson\Documents\" + name + ".xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, misValue,
                misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

            xlWorkBook.Close(true);
            xlApp.Quit();

            return "Funkar";
        }

        #endregion

        private string createId(string Id, int start, int end)
        {
            return Id.Substring(start, end);
        }
    }
}

TestCode

    public List<string> NewCategoryId = new List<string>();
    public List<string> NewCategoryName = new List<string>();

    public List<string> parentCategoryId = new List<string>();
    public List<string> parentCategoryName = new List<string>();

    parentCategoryId = <"3930000", "3930000",4230000, 5200000 >
    parentCategoryName = <"Computers", "Computers", Toys, Furniture>

    NewCategoryId = <"3931200", "4231400","5201300" "3931700">
    NewCategoryName = <"Chairs","HP","ToyCars", "Lenovo">

    for(int i = 0; i < NewCategoryId.Count; i++){

       for(int j = 0; parentCategoryId.Count; j++){
           if(parentCategoryId[j] == NewCategoryId[i]){
               Console.Write(NewCategoryId[i] + "     ")
               Console.Write(NewCategoryName[i] + "     ")
               Console.Write(parentCategoryId[j] + "   " )
               Console.Write(parentCategoryName[j] + "\n")
           }
       }

    }

Wanted result
3931700 Lenovo  3930000 Computers
3931200 HP      3930000 Computers
4231400 Chairs  4230000 Furniture
5201300 ToyCars 5201300 Toys

This is an ish result that i whant but im just getting them scrambled so how to do this?

Body:
You can retrieve matching elements with .Intersect(), then use .IndexOf() to get the indexes. Finally, access the index values of the other lists.

var list1 = new List<int> { 1, 2, 3, 4, 5 };
var list2 = new List<int> { 4, 5, 6, 7, 8 };

var intersectingValues = list1.Intersect(list2); // 4, 5
var interesectingValueIndexes = intersectingValues.Select(x =>
                                   new { I1 = list1.IndexOf(x), I2 = list2.IndexOf(x) });

var otherList1 = new List<string> { "a", "b", "c", "d", "e" };
var otherList2 = new List<string> { "f", "g", "h", "i", "j" };

var otherListIndexValues = interesectingValueIndexes.Select(x =>
                                   new { V1 = otherList1[x.I1], V2 = otherList2[x.I2] });


问:
Hide component from any active component?
There is a component <app-tabs-components>.

It gets data from service. There is variable show: boolean in this service to show/hide component on the page.

```<code>@Injectable({ providedIn: "root" })
export class TabService {
    show = false;
    showHide(status: boolean) {
        this.show = status;
    }

     get() {
          return this.show;
     }
}
</code>```

Problem is that I need to call tabService.showHide(false) in every component where I want to hide component <app-tabs-components>.

Component <app-tabs-components> always should be closed if it lost focus, not active area.

In my case I am breaking DRY principle.

For example, when user activates any component I must do:

```<code>ngOnInit() {
  tabService.showHide(false)
}
</code>```

So this part of code is repeated ine each component where I wan to hide tabsComponent

答:
Create a Base Class and in constructor of this class call the your service.

```<code>export class BaseComp  {

  public IsHide: boolean;
  constructor() {
    this.IsHide = tabService.showHide(false);
  }

}
</code>```

Inherit this BaseComp in different Components.

```<code>export class YourComponent extends BaseComp implements OnInit  {

constructor() {
  super(); // calls the base constructor
  console.log(this.IsHide); // this IsHide is of Base class
}

ngOnInit() {

}

}
</code>```

Hope this helps !!

Body:
There is a component <app-tabs-components>.

It gets data from service. There is variable show: boolean in this service to show/hide component on the page.

@Injectable({ providedIn: "root" })
export class TabService {
    show = false;
    showHide(status: boolean) {
        this.show = status;
    }

     get() {
          return this.show;
     }
}

Problem is that I need to call tabService.showHide(false) in every component where I want to hide component <app-tabs-components>.

Component <app-tabs-components> always should be closed if it lost focus, not active area.

In my case I am breaking DRY principle.

For example, when user activates any component I must do:

ngOnInit() {
  tabService.showHide(false)
}

So this part of code is repeated ine each component where I wan to hide tabsComponent

Body:
Create a Base Class and in constructor of this class call the your service.

export class BaseComp  {

  public IsHide: boolean;
  constructor() {
    this.IsHide = tabService.showHide(false);
  }

}

Inherit this BaseComp in different Components.

export class YourComponent extends BaseComp implements OnInit  {

constructor() {
  super(); // calls the base constructor
  console.log(this.IsHide); // this IsHide is of Base class
}

ngOnInit() {

}

}

Hope this helps !!


问:
how to implement ModelChoiceField in Django
I am trying to create an input selection from database model fields and I have tried using ModelChoiceField but I keep getting an error I don't know how to solve. I need help.

Here are the models

```<code>class WeeklySavingsDeposit(models.Model):

    WEEKLY_SAVE_DEPOSIT_STATUS_PENDING = 'Pending'
    WEEKLY_SAVE_DEPOSIT_STATUS_APPROVED = 'Approved'
    WEEKLY_SAVE_DEPOSIT_STATUS_DENIED = 'Denied'

    WEEKLY_SAVE_DEPOSIT_STATUS_CHOICES = ((WEEKLY_SAVE_DEPOSIT_STATUS_PENDING, 'Pending'), (WEEKLY_SAVE_DEPOSIT_STATUS_APPROVED, 'Approved'), (WEEKLY_SAVE_DEPOSIT_STATUS_DENIED, 'Denied'))

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date = models.DateTimeField(default=timezone.now)
    savings_title = models.CharField(max_length=100, null = True, blank=True)
    amount = models.FloatField()
    dep_proof = models.ImageField(upload_to='deposit_proofs')
    status = models.CharField(max_length = 40, choices = WEEKLY_SAVE_DEPOSIT_STATUS_CHOICES, default='Pending')
    dep_tag = models.IntegerField(default=0)

    def __str__(self):
        return f'{self.user.username} WeeklySaveDeposit'
</code>```

```<code>class WeeklySaving(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    created = models.DateTimeField(default=timezone.now)
    title = models.CharField(max_length = 100, default = 'Weekly Savings Title')
    duration = models.CharField(max_length=40, choices=WEEKLY_SAVE_DURATION_CHOICES, default ='2 Months')
    completion_date = models.DateTimeField(null=True)
    amount = models.FloatField()
    target_amount = models.FloatField(null=True)
    status = models.CharField(max_length= 40,choices = WEEKLY_SAVE_STATUS_CHOICES, default='Pending')
    week_save_day = models.CharField(max_length =100, choices=WEEKLY_SAVE_DAY_CHOICES, default='Friday')
    amount_saved = models.FloatField()
</code>```

My Forms.

```<code>class StartWeeklySaveForm(forms.ModelForm):

   title = forms.CharField(label = 'Savings Title', required=True)
   amount =  forms.FloatField(label='Amount to Save Weekly? (in Naira):', min_value=WeeklySaving.MIN_WEEKLY_SAVE, max_value=WeeklySaving.MAX_WEEKLY_SAVE, required=True, widget=forms.TextInput(attrs={'placeholder': 'Input the amount you want to save weekly. Minimum 500'}))

   class Meta:
       model = WeeklySaving
       fields = ["title", "amount", "duration", "week_save_day"]

class DepositWeeklySaveForm(forms.ModelForm):
       amount = forms.FloatField(label='Enter Amount in (Naira)', min_value=WeeklySaving.MIN_WEEKLY_SAVE, max_value=WeeklySaving.MAX_WEEKLY_SAVE, required=True, help_text='How much to deposit? Minimum 500',)
   dep_proof = forms.ImageField(label='Upload a Proof of Payment', help_text='teller or transaction receipt as image')

   class Meta:
       model = WeeklySavingsDeposit
       fields =["savings_title", "amount", "dep_proof"]
</code>```

In my Views.py i have this

```<code>@login_required
def weekly_save(request):
    startwksave_form = StartWeeklySaveForm(request.POST or None, request.FILES)
    depwksave_form = DepositWeeklySaveForm(request.POST or None, request.FILES)
    user=request.user
    depwksave_form.fields['savings_title'] = WeeklySaveDepositModelChoiceField(WeeklySaving.objects.filter(user=user), empty_label="(Select savings)",required=True)
    depwksave_form.fields['amount'] = WeeklySaveDepositAmountModelChoiceField(WeeklySaving.objects.filter(user=user), empty_label="(Select savings amount)",required=True)
</code>```

I have a fields.py as follows

```<code>
from savings.models import WeeklySaving, WeeklySavingsDeposit
from django.forms import ModelChoiceField

class WeeklySaveDepositModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        result = obj.title
        return str(result)

class WeeklySaveDepositAmountModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        result = obj.amount
        return float(result)
</code>```

in my template the form appears like this..
Form Template View

I am able to select the savings title and the amount from the WeeklySaving object which is what I want but when I submit the form it shows the error "Username Saving" must be a float. which means it is actually saving the input as 'Username Saving' instead of the selected saving title and amount.

How can I solve this problem please I need help. I am still new using django.

thanks for your help.

答:
In general, it always gets hard with multiple forms in the same view. So if you split them into 2 views it would be much easier. Maybe it is possible to create one object from the other one?
It is even worse (i think) that both forms do have the field "amount". Maybe it is possible to rename one of them.

Another big problem is this:
DepositWeeklySaveForm().amount = forms.FloatField and this depwksave_form.fields['amount'] = WeeklySaveDepositAmountModelChoiceField This cannot work. WeeklySaveDepositAmountModelChoiceField should reference a ForeginKey, not a FloatField.
so add to your models:

```<code>class WeeklySavingsDeposit(models.Model):
    weekly_savings = models.ForeignKey(WeeklySaving, on_delete=models.CASCADE)
    ...
</code>```

I would recommend changing everything to a class based view e.g. CreateView and use get_form_kwargs to pass the user. Something like

```<code>    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs
</code>```

Then you can set the field in the forms.py like this:

```<code>class DepositWeeklySaveForm(forms.ModelForm):
    weekly_savings = forms.ModelMultipleChoiceField(queryset=None)
    required=True, help_text='How much to deposit? Minimum 500',)
   dep_proof = forms.ImageField(label='Upload a Proof of Payment', help_text='teller or transaction receipt as image')

   class Meta:
       model = WeeklySavingsDeposit
       fields =["savings_title", "amount", "dep_proof", "weekly_savings"]

    def __init__(self, user, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['weekly_savings'].queryset = WeeklySaving.objects.filter(user=user)
</code>```

Body:
I am trying to create an input selection from database model fields and I have tried using ModelChoiceField but I keep getting an error I don't know how to solve. I need help.

Here are the models

class WeeklySavingsDeposit(models.Model):

    WEEKLY_SAVE_DEPOSIT_STATUS_PENDING = 'Pending'
    WEEKLY_SAVE_DEPOSIT_STATUS_APPROVED = 'Approved'
    WEEKLY_SAVE_DEPOSIT_STATUS_DENIED = 'Denied'

    WEEKLY_SAVE_DEPOSIT_STATUS_CHOICES = ((WEEKLY_SAVE_DEPOSIT_STATUS_PENDING, 'Pending'), (WEEKLY_SAVE_DEPOSIT_STATUS_APPROVED, 'Approved'), (WEEKLY_SAVE_DEPOSIT_STATUS_DENIED, 'Denied'))

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    date = models.DateTimeField(default=timezone.now)
    savings_title = models.CharField(max_length=100, null = True, blank=True)
    amount = models.FloatField()
    dep_proof = models.ImageField(upload_to='deposit_proofs')
    status = models.CharField(max_length = 40, choices = WEEKLY_SAVE_DEPOSIT_STATUS_CHOICES, default='Pending')
    dep_tag = models.IntegerField(default=0)

    def __str__(self):
        return f'{self.user.username} WeeklySaveDeposit'

class WeeklySaving(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    created = models.DateTimeField(default=timezone.now)
    title = models.CharField(max_length = 100, default = 'Weekly Savings Title')
    duration = models.CharField(max_length=40, choices=WEEKLY_SAVE_DURATION_CHOICES, default ='2 Months')
    completion_date = models.DateTimeField(null=True)
    amount = models.FloatField()
    target_amount = models.FloatField(null=True)
    status = models.CharField(max_length= 40,choices = WEEKLY_SAVE_STATUS_CHOICES, default='Pending')
    week_save_day = models.CharField(max_length =100, choices=WEEKLY_SAVE_DAY_CHOICES, default='Friday')
    amount_saved = models.FloatField()

My Forms.

class StartWeeklySaveForm(forms.ModelForm):

   title = forms.CharField(label = 'Savings Title', required=True)
   amount =  forms.FloatField(label='Amount to Save Weekly? (in Naira):', min_value=WeeklySaving.MIN_WEEKLY_SAVE, max_value=WeeklySaving.MAX_WEEKLY_SAVE, required=True, widget=forms.TextInput(attrs={'placeholder': 'Input the amount you want to save weekly. Minimum 500'}))

   class Meta:
       model = WeeklySaving
       fields = ["title", "amount", "duration", "week_save_day"]

class DepositWeeklySaveForm(forms.ModelForm):
       amount = forms.FloatField(label='Enter Amount in (Naira)', min_value=WeeklySaving.MIN_WEEKLY_SAVE, max_value=WeeklySaving.MAX_WEEKLY_SAVE, required=True, help_text='How much to deposit? Minimum 500',)
   dep_proof = forms.ImageField(label='Upload a Proof of Payment', help_text='teller or transaction receipt as image')

   class Meta:
       model = WeeklySavingsDeposit
       fields =["savings_title", "amount", "dep_proof"]

In my Views.py i have this

@login_required
def weekly_save(request):
    startwksave_form = StartWeeklySaveForm(request.POST or None, request.FILES)
    depwksave_form = DepositWeeklySaveForm(request.POST or None, request.FILES)
    user=request.user
    depwksave_form.fields['savings_title'] = WeeklySaveDepositModelChoiceField(WeeklySaving.objects.filter(user=user), empty_label="(Select savings)",required=True)
    depwksave_form.fields['amount'] = WeeklySaveDepositAmountModelChoiceField(WeeklySaving.objects.filter(user=user), empty_label="(Select savings amount)",required=True)

I have a fields.py as follows

from savings.models import WeeklySaving, WeeklySavingsDeposit
from django.forms import ModelChoiceField

class WeeklySaveDepositModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        result = obj.title
        return str(result)

class WeeklySaveDepositAmountModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        result = obj.amount
        return float(result)

in my template the form appears like this..
Form Template View

I am able to select the savings title and the amount from the WeeklySaving object which is what I want but when I submit the form it shows the error "Username Saving" must be a float. which means it is actually saving the input as 'Username Saving' instead of the selected saving title and amount.

How can I solve this problem please I need help. I am still new using django.

thanks for your help.

Body:
In general, it always gets hard with multiple forms in the same view. So if you split them into 2 views it would be much easier. Maybe it is possible to create one object from the other one?
It is even worse (i think) that both forms do have the field "amount". Maybe it is possible to rename one of them.

Another big problem is this:
DepositWeeklySaveForm().amount = forms.FloatField and this depwksave_form.fields['amount'] = WeeklySaveDepositAmountModelChoiceField This cannot work. WeeklySaveDepositAmountModelChoiceField should reference a ForeginKey, not a FloatField.
so add to your models:

class WeeklySavingsDeposit(models.Model):
    weekly_savings = models.ForeignKey(WeeklySaving, on_delete=models.CASCADE)
    ...

I would recommend changing everything to a class based view e.g. CreateView and use get_form_kwargs to pass the user. Something like

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs

Then you can set the field in the forms.py like this:

class DepositWeeklySaveForm(forms.ModelForm):
    weekly_savings = forms.ModelMultipleChoiceField(queryset=None)
    required=True, help_text='How much to deposit? Minimum 500',)
   dep_proof = forms.ImageField(label='Upload a Proof of Payment', help_text='teller or transaction receipt as image')

   class Meta:
       model = WeeklySavingsDeposit
       fields =["savings_title", "amount", "dep_proof", "weekly_savings"]

    def __init__(self, user, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['weekly_savings'].queryset = WeeklySaving.objects.filter(user=user)


问:
How to send data via POST or GET in Mod_Python?
With JS, i send a AJAX post request.

```<code> $.ajax(
        {method:"POST",
        url:"https://my/website/send_data.py",
        data:JSON.stringify(data),
        contentType: 'application/json;charset=UTF-8'
</code>```

On my Apache2 mod_Python server, I wish for my python file to access data. How can i do this?

```<code>def index(req):
    # data = ??
</code>```

PS: here is how to reproduce the problem. Create testjson.html:

```<code><script type="text/javascript">
xhr = new XMLHttpRequest();
xhr.open("POST", "testjson.py");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function(res) { console.log(xhr.responseText); };
xhr.send(JSON.stringify({'foo': '0', 'bar': '1'}));
</script>
</code>```

and create testjson.py containing:

```<code>from mod_python import apache

def index(req):
    req.content_type = "application/json"
    req.write("hello")
    data = req.read()
    return apache.OK
</code>```

Create a .htaccess containing:

```<code>AddHandler mod_python .py
PythonHandler mod_python.publisher
</code>```

Here is the result:

testjson.html:10 POST http://localhost/test_py/testjson.py 501 (Not Implemented)

答:
From Mod_python docs:

Client data, such as POST requests, can be read by using the request.read() function.

Body:
With JS, i send a AJAX post request.

 $.ajax(
        {method:"POST",
        url:"https://my/website/send_data.py",
        data:JSON.stringify(data),
        contentType: 'application/json;charset=UTF-8'

On my Apache2 mod_Python server, I wish for my python file to access data. How can i do this?

def index(req):
    # data = ??

PS: here is how to reproduce the problem. Create testjson.html:

and create testjson.py containing:

from mod_python import apache

def index(req):
    req.content_type = "application/json"
    req.write("hello")
    data = req.read()
    return apache.OK

Create a .htaccess containing:

AddHandler mod_python .py
PythonHandler mod_python.publisher

Here is the result:

testjson.html:10 POST http://localhost/test_py/testjson.py 501 (Not Implemented)


问:
How to get branch name on GitHub action?
During a GitHub action, I'd like to know the name of the branch:

for a push action: name of the current branch

for a pull_request action: name of the target branch

I need a string like develop, master or feature/xxx (and not refs/pull/…).

The ${{ github.ref }} var gives me refs/heads/develop. How can I get only the develop?

答:
Update: GitHub added the context variable ${{ github.ref_name }}, returning "The branch or tag name that triggered the workflow run."

Original Answer:

You can create a step output of the last part of GITHUB_REF like the following.

```<code>on: push
jobs:
  example:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2

      - name: Set output
        id: vars
        run: echo ::set-output name=short_ref::${GITHUB_REF#refs/*/}

      - name: Check output
        run: echo ${{ steps.vars.outputs.short_ref }}
</code>```

Body:
Update: GitHub added the context variable ${{ github.ref_name }}, returning "The branch or tag name that triggered the workflow run."

Original Answer:

You can create a step output of the last part of GITHUB_REF like the following.

on: push
jobs:
  example:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2

      - name: Set output
        id: vars
        run: echo ::set-output name=short_ref::${GITHUB_REF#refs/*/}

      - name: Check output
        run: echo ${{ steps.vars.outputs.short_ref }}


问:
C++ Float Division and Precision
I know that 511 divided by 512 actually equals 0.998046875. I also know that the precision of floats is 7 digits. My question is, when I do this math in C++ (GCC) the result I get is 0.998047, which is a rounded value. I'd prefer to just get the truncated value of 0.998046, how can I do that?</p>

```<code>  float a = 511.0f;
  float b = 512.0f;
  float c = a / b;
</code>```

答:
Your question is not unique, it has been answered numerous times before. This is not a simple topic and just because answers are posted doesn't necessarily mean they'll be of good quality. If you browse a little you'll find the really good stuff. And it will take you less time.

I bet someone will -1 me for commenting and not answering.

_____ Edit _____

What is fundamental to understanding floating point is to realize that everything is displayed in binary digits. Because most people have trouble grasping this they try to see it from the point of view of decimal digits.

On the subject of 511/512 you can start by looking at the value 1.0. In floating point this could be expressed as i.000000... * 2^0 or implicit bit set (to 1) multiplied by 2^0 ie equals 1. Since 511/512 is less than 1 you need to start with the next lower power -1 giving i.000000... * 2^-1 i e 0.5. Notice that the only thing that has changed is the exponent. If we want to express 511 in binary we get 9 ones - 111111111 or in floating point with implicit bit i.11111111 - which we can divide by 512 and put together with the exponent of -1 giving i.1111111100... * 2^-1.

How does this translate to 0.998046875?

Well to begin with the implicit bit represents 0.5 (or 2^-1), the first explicit bit 0.25 (2^-2), the next explicit bit 0.125 (2^-3), 0.0625, 0.03125 and so on until you've represented the ninth bit (eighth explicit). Sum them up and you get 0.998046875. From the i.11111111 we find that this number represents 9 binary digits of precision and, coincidentally, 9 decimal precision.

If you multiply 511/512 by 512 you will get i1111111100... * 2^8. Here there are the same nine binary digits of precision but only three decimal digits (for 511).

Consider i.11111111111111111111111 (i + 23 ones) * 2^-1. We will get a fraction (2^(24-1)^/(2^24))with 24 binary and 24 decimal digits of precision. Given an appropriate printf formatting all 24 decimal digits will be displayed. Multiply it by 2^24 and you still have 24 binary digits of precision but only 8 decimal (for 16777215).

Now consider i.1111100... * 2^2 which comes out to 7.875. i11 is the integer part and 111 the fraction part (111/1000 or 7/8ths). 6 binary digits of precision and 4 decimal.

Thinking decimal when doing floating-point is utterly detrimental to understanding it. Free yourself!

Title: C++ Float Division and Precision

Body:
I know that 511 divided by 512 actually equals 0.998046875. I also know that the precision of floats is 7 digits. My question is, when I do this math in C++ (GCC) the result I get is 0.998047, which is a rounded value. I'd prefer to just get the truncated value of 0.998046, how can I do that?

  float a = 511.0f;
  float b = 512.0f;
  float c = a / b;


问:
Date problem with sql - displaying only one row
i've go a table with employee_id, school_end(date), school_name
and some employeers have a several school names with dates.

i want to see in query only the latest school and date for one employee_id

Thanks in advance

答:
I want to see in query only the latest school and date for one employee_id

One cross-database solution to this top-1-per-group question is to filter with a correlated subquery:

```<code>select t.*
from mytable t
where t.school_end = (
    select max(t1.school_end) from mytable t1 where t1.employee_id = t.employee_id
)
</code>```

For performance, you want an index on (employee_id, school_end).

Depending on your database, more efficient options might be available (for example, Postgres has the distinct on syntax).

Body:
I want to see in query only the latest school and date for one employee_id

One cross-database solution to this top-1-per-group question is to filter with a correlated subquery:

select t.*
from mytable t
where t.school_end = (
    select max(t1.school_end) from mytable t1 where t1.employee_id = t.employee_id
)

For performance, you want an index on (employee_id, school_end).

Depending on your database, more efficient options might be available (for example, Postgres has the distinct on syntax).


问:
Extract bits from the CAN message data(8 bytes)
I wants to extract the bits from the CAN message (8 bytes).

so, how to i extract bits from 8 bytes.

答:
Here is a chunk of code to get the bits from one byte:</p>

```<code>on message myMessage
{
 byte bitArray[8];
 int iByteToRead = 0;

 f_ByteToBitArray(this.byte(iByteToRead),bitArray);
 write ("f_ByteToBitArray %X :Bits %X %X %X %X %X %X %X %X", iByteToRead , bitArray[0],bitArray[1],bitArray[2],bitArray[3],bitArray[4],bitArray[5],bitArray[6],bitArray[7]);
}

void f_ByteToBitArray(byte in, byte out[])
{
  //                          7 6 5 4 3 2 1 0
  // f_ByteToBitArray 1 :Bits 0 0 0 0 0 0 0 1
 // f_ByteToBitArray 2 :Bits 0 0 0 0 0 0 1 0

 byte a;
 a = in;
 out[0] = a & 0x01;
 a = a >> 1;
 out[1] = a & 0x01;
 a = a >> 1;
 out[2] = a & 0x01;
 a = a >> 1;
 out[3] = a & 0x01;
 a = a >> 1;
 out[4] = a & 0x01;
 a = a >> 1;
 out[5] = a & 0x01;
 a = a >> 1;
 out[6] = a & 0x01;
 a = a >> 1;
 out[7] = a & 0x01;
}
</code>```

Body:
Here is a chunk of code to get the bits from one byte:

on message myMessage
{
 byte bitArray[8];
 int iByteToRead = 0;

 f_ByteToBitArray(this.byte(iByteToRead),bitArray);
 write ("f_ByteToBitArray %X :Bits %X %X %X %X %X %X %X %X", iByteToRead , bitArray[0],bitArray[1],bitArray[2],bitArray[3],bitArray[4],bitArray[5],bitArray[6],bitArray[7]);
}

void f_ByteToBitArray(byte in, byte out[])
{
  //                          7 6 5 4 3 2 1 0
  // f_ByteToBitArray 1 :Bits 0 0 0 0 0 0 0 1
 // f_ByteToBitArray 2 :Bits 0 0 0 0 0 0 1 0

 byte a;
 a = in;
 out[0] = a & 0x01;
 a = a >> 1;
 out[1] = a & 0x01;
 a = a >> 1;
 out[2] = a & 0x01;
 a = a >> 1;
 out[3] = a & 0x01;
 a = a >> 1;
 out[4] = a & 0x01;
 a = a >> 1;
 out[5] = a & 0x01;
 a = a >> 1;
 out[6] = a & 0x01;
 a = a >> 1;
 out[7] = a & 0x01;
}


问:
Error: listen EADDRINUSE node JS
I have 2 Sails application, one depend on another.
First I'm running at port 1337 the second at 1338.
All was working fine until yesterday. Have Mac, now I can run only that at 1337 and then 1338 at the second terminal tab giving me the:
Error: listen EADDRINUSE :::1338
If I'm running killall -9 node
It killing the 1337 then when I'm trying rerun 1337 again I'm getting Error: listen EADDRINUSE :::1337 also,
If I will run on tab of 1337 the killall -9 node
Im getting: No matching processes belonging to you were found
And cannot run any application.
Will help only restarting terminal

Is there any system setting that I can adjust?
I'm pretty new Mac user.

答:
If you're using VS Code in Windows, You would need to first KILL the previous instances of your Node-App

Open BASH terminal in VS Code and run below command

cmd "/C TASKKILL /IM node.exe /F"

Title: Error: listen EADDRINUSE node JS


问:
Possible to display multiple html results from different divs in one or multiple Ajax calls?
Wondering if it's possible to get multiple divs refreshed with the data pulled from one or more Ajax calls, called by the same button.

I'm getting the correct results, just having a difficult time showing more than one div being refreshed with the html result.

I've tried the following ways;

```<code>$(document).on('click', '#customButton', function(event) {

var rangeDate_from = document.getElementsByName("rangeDate_from")[0].value;
var rangeDate_to = document.getElementsByName("rangeDate_to")[0].value;

  $.ajax({
       url: "load1.php",
       data: {'action' : 'search_prods', 'rangeDate_from' : rangeDate_from, 'rangeDate_to' : rangeDate_to},
       type: 'post',
       success: function(result) {
          form_updated = true;
          $('#dd_stocktake_details').html(result);
         },
           error: function() {}
         });

});

$(document).on('click', '#customButton', function(event) {

var rangeDate_from = document.getElementsByName("rangeDate_from")[0].value;
var rangeDate_to = document.getElementsByName("rangeDate_to")[0].value;

  $.ajax({
       url: "load2.php",
       data: {'action' : 'search_prods', 'rangeDate_from' : rangeDate_from, 'rangeDate_to' : rangeDate_to},
       type: 'post',
       success: function(result2) {
          form_updated = true;
          $('#dd_stocktake_details_2').html(result2);
         },
           error: function() {}
         });

});
</code>```

And

```<code>$(document).on('click', '#customButton', function(event) {

var rangeDate_from = document.getElementsByName("rangeDate_from")[0].value;
var rangeDate_to = document.getElementsByName("rangeDate_to")[0].value;

  $.ajax({
       url: "load1.php",
       data: {'action' : 'search_prods', 'rangeDate_from' : rangeDate_from, 'rangeDate_to' : rangeDate_to},
       type: 'post',
       success: function(result) {
          form_updated = true;
          $('#dd_stocktake_details').html(result);
         },
           error: function() {}
         });

         $.ajax({
              url: "load2.php",
              data: {'action' : 'search_prods', 'rangeDate_from' : rangeDate_from, 'rangeDate_to' : rangeDate_to},
              type: 'post',
              success: function(result2) {
                 form_updated = true;
                 $('#dd_stocktake_details_2').html(result2);
                 alert(result2);
                },
                  error: function() {}
                });

});
</code>```

Both these ways get me the results I want correctly, but both of these options only seem to display the first div each time.

If any more code needs to be seen, just ask!

Any ideas?

答:
You can use Jquery When
ref: https://api.jquery.com/jQuery.when/</p>

```<code>        $(document).on('click', '#customButton', function (event) {

            var result1;
            var result2;
            var rangeDate_from = document.getElementsByName("rangeDate_from")[0].value;
            var rangeDate_to = document.getElementsByName("rangeDate_to")[0].value;
            $.when(
                $.ajax({
                    url: "load1.php",
                    data: { 'action': 'search_prods', 'rangeDate_from': rangeDate_from, 'rangeDate_to': rangeDate_to },
                    type: 'post',
                    success: function (result) {
                        form_updated = true;
                        result1 = result;
                    },
                    error: function () { }
                });

            $.ajax({
                url: "load2.php",
                data: { 'action': 'search_prods', 'rangeDate_from': rangeDate_from, 'rangeDate_to': rangeDate_to },
                type: 'post',
                success: function (result) {
                    form_updated = true;
                    result2 = result2
                },
                error: function () { }
            });

            ).then(function () {
                $('#dd_stocktake_details').html(result1);
                $('#dd_stocktake_details_2').html(result2);
            });

        });
</code>```

Body:
Wondering if it's possible to get multiple divs refreshed with the data pulled from one or more Ajax calls, called by the same button.

I'm getting the correct results, just having a difficult time showing more than one div being refreshed with the html result.

I've tried the following ways;

$(document).on('click', '#customButton', function(event) {

var rangeDate_from = document.getElementsByName("rangeDate_from")[0].value;
var rangeDate_to = document.getElementsByName("rangeDate_to")[0].value;

  $.ajax({
       url: "load1.php",
       data: {'action' : 'search_prods', 'rangeDate_from' : rangeDate_from, 'rangeDate_to' : rangeDate_to},
       type: 'post',
       success: function(result) {
          form_updated = true;
          $('#dd_stocktake_details').html(result);
         },
           error: function() {}
         });

});

$(document).on('click', '#customButton', function(event) {

var rangeDate_from = document.getElementsByName("rangeDate_from")[0].value;
var rangeDate_to = document.getElementsByName("rangeDate_to")[0].value;

  $.ajax({
       url: "load2.php",
       data: {'action' : 'search_prods', 'rangeDate_from' : rangeDate_from, 'rangeDate_to' : rangeDate_to},
       type: 'post',
       success: function(result2) {
          form_updated = true;
          $('#dd_stocktake_details_2').html(result2);
         },
           error: function() {}
         });

});

And

$(document).on('click', '#customButton', function(event) {

var rangeDate_from = document.getElementsByName("rangeDate_from")[0].value;
var rangeDate_to = document.getElementsByName("rangeDate_to")[0].value;

  $.ajax({
       url: "load1.php",
       data: {'action' : 'search_prods', 'rangeDate_from' : rangeDate_from, 'rangeDate_to' : rangeDate_to},
       type: 'post',
       success: function(result) {
          form_updated = true;
          $('#dd_stocktake_details').html(result);
         },
           error: function() {}
         });

         $.ajax({
              url: "load2.php",
              data: {'action' : 'search_prods', 'rangeDate_from' : rangeDate_from, 'rangeDate_to' : rangeDate_to},
              type: 'post',
              success: function(result2) {
                 form_updated = true;
                 $('#dd_stocktake_details_2').html(result2);
                 alert(result2);
                },
                  error: function() {}
                });

});

Both these ways get me the results I want correctly, but both of these options only seem to display the first div each time.

If any more code needs to be seen, just ask!

Any ideas?

Body:
You can use Jquery When
ref: https://api.jquery.com/jQuery.when/

        $(document).on('click', '#customButton', function (event) {

            var result1;
            var result2;
            var rangeDate_from = document.getElementsByName("rangeDate_from")[0].value;
            var rangeDate_to = document.getElementsByName("rangeDate_to")[0].value;
            $.when(
                $.ajax({
                    url: "load1.php",
                    data: { 'action': 'search_prods', 'rangeDate_from': rangeDate_from, 'rangeDate_to': rangeDate_to },
                    type: 'post',
                    success: function (result) {
                        form_updated = true;
                        result1 = result;
                    },
                    error: function () { }
                });

            $.ajax({
                url: "load2.php",
                data: { 'action': 'search_prods', 'rangeDate_from': rangeDate_from, 'rangeDate_to': rangeDate_to },
                type: 'post',
                success: function (result) {
                    form_updated = true;
                    result2 = result2
                },
                error: function () { }
            });

            ).then(function () {
                $('#dd_stocktake_details').html(result1);
                $('#dd_stocktake_details_2').html(result2);
            });

        });


问:
Random value from Flags enum
Say I have a function that accepts an enum decorated with the Flags attribute. If the value of the enum is a combination of more than one of the enum elements how can I extract one of those elements at random? I have the following but it seems there must be a better way.</p>

```<code>[Flags]
enum Colours
{
    Blue = 1,
    Red = 2,
    Green = 4
}

public static void Main()
{
    var options = Colours.Blue | Colours.Red | Colours.Green;
    var opts = options.ToString().Split(',');
    var rand = new Random();
    var selected = opts[rand.Next(opts.Length)].Trim();
    var myEnum = Enum.Parse(typeof(Colours), selected);
    Console.WriteLine(myEnum);
    Console.ReadLine();
}
</code>```

答:
In my case - I have enums with missing members e.g 0x01, 0x02, 0x08, and large ulong enum with 0x200000000 maximal value.

This code works for all of my cases:

```<code>/// <summary>
///     Gets <see cref="System.Random"/> instance.
/// </summary>
public static Random Random { get; } = new Random(Guid.NewGuid().GetHashCode());

/// <summary>
///     Gets random combination of Flags Enum.
/// </summary>
/// <typeparam name="T">Enum type.</typeparam>
/// <returns>Random Flags Enum combination.</returns>
public static T GetRandomFlagsEnumValue<T>()
    where T : Enum
{
    var allValues = (T[])Enum.GetValues(typeof(T));

    ulong numberValue = allValues.OrderBy(x => Random.Next())
        .Take(GetRandomInteger(1, allValues.Length - 1))
        .Select(e => Convert.ToUInt64(e, CultureInfo.InvariantCulture))
        .Aggregate((a, c) => a + c);

    return (T)Enum.ToObject(typeof(T), numberValue);
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Random value from Flags enum

Body:
Say I have a function that accepts an enum decorated with the Flags attribute. If the value of the enum is a combination of more than one of the enum elements how can I extract one of those elements at random? I have the following but it seems there must be a better way.

[Flags]
enum Colours
{
    Blue = 1,
    Red = 2,
    Green = 4
}

public static void Main()
{
    var options = Colours.Blue | Colours.Red | Colours.Green;
    var opts = options.ToString().Split(',');
    var rand = new Random();
    var selected = opts[rand.Next(opts.Length)].Trim();
    var myEnum = Enum.Parse(typeof(Colours), selected);
    Console.WriteLine(myEnum);
    Console.ReadLine();
}

Body:
In my case - I have enums with missing members e.g 0x01, 0x02, 0x08, and large ulong enum with 0x200000000 maximal value.

This code works for all of my cases:

/// <summary>
///     Gets <see cref="System.Random"/> instance.
/// </summary>
public static Random Random { get; } = new Random(Guid.NewGuid().GetHashCode());

/// <summary>
///     Gets random combination of Flags Enum.
/// </summary>
/// <typeparam name="T">Enum type.</typeparam>
/// <returns>Random Flags Enum combination.</returns>
public static T GetRandomFlagsEnumValue<T>()
    where T : Enum
{
    var allValues = (T[])Enum.GetValues(typeof(T));

    ulong numberValue = allValues.OrderBy(x => Random.Next())
        .Take(GetRandomInteger(1, allValues.Length - 1))
        .Select(e => Convert.ToUInt64(e, CultureInfo.InvariantCulture))
        .Aggregate((a, c) => a + c);

    return (T)Enum.ToObject(typeof(T), numberValue);
}


问:
How to change font color SecureField in SwiftUI?
I have custom Textfield.

```<code>CustomTextField(placeholder: Text("Login").foregroundColor(.white),
                                        text: $login)
                                        .background(Color(red: 0/255, green: 174/255, blue: 180/255))
                                        .opacity(0.5)
                                        .cornerRadius (29)
                                        .frame (height: 50)
                                        .font(.system(size: 40))
                                        .foregroundColor(Color.white)
</code>```

but i need create this for Securefield. How i can do this?
used form for custom Textfield

```<code>struct CustomTextField: View {
var placeholder: Text
@Binding var text: String
var editingChanged: (Bool)->() = { _ in }
var commit: ()->() = { }

var body: some View {
    ZStack(alignment: .leading) {
        if text.isEmpty { placeholder }
        TextField("", text: $text, onEditingChanged: editingChanged, onCommit: commit)
    }
}
</code>```

答:
you mean this?</p>

```<code>struct ContentView : View {

    @State var login : String = "aha"

    @State var password : String = "aha"

    var body : some View {

        CustomTextField(placeholder: Text("Login").foregroundColor(.white),
                        text: $login, password: $password)
            .background(Color(red: 0/255, green: 174/255, blue: 180/255))
            .opacity(0.5)
            .cornerRadius (29)
            .frame (height: 50)
            .font(.system(size: 40))
            .foregroundColor(Color.white)
    }
}

struct CustomTextField: View {
    var placeholder: Text
    @Binding var text: String
    var editingChanged: (Bool)->() = { _ in }
    var commit: ()->() = { }
    @Binding var password : String

    var body: some View {
        ZStack(alignment: .leading) {
            if text.isEmpty { placeholder }
           // TextField("", text: $text, onEditingChanged: editingChanged, onCommit: commit)
            SecureField(text, text: $password) {

            }
        }
    }
}
</code>```

Body:
I have custom Textfield.

CustomTextField(placeholder: Text("Login").foregroundColor(.white),
                                        text: $login)
                                        .background(Color(red: 0/255, green: 174/255, blue: 180/255))
                                        .opacity(0.5)
                                        .cornerRadius (29)
                                        .frame (height: 50)
                                        .font(.system(size: 40))
                                        .foregroundColor(Color.white)

but i need create this for Securefield. How i can do this?
used form for custom Textfield

struct CustomTextField: View {
var placeholder: Text
@Binding var text: String
var editingChanged: (Bool)->() = { _ in }
var commit: ()->() = { }

var body: some View {
    ZStack(alignment: .leading) {
        if text.isEmpty { placeholder }
        TextField("", text: $text, onEditingChanged: editingChanged, onCommit: commit)
    }
}

Body:
you mean this?

struct ContentView : View {

    @State var login : String = "aha"

    @State var password : String = "aha"

    var body : some View {

        CustomTextField(placeholder: Text("Login").foregroundColor(.white),
                        text: $login, password: $password)
            .background(Color(red: 0/255, green: 174/255, blue: 180/255))
            .opacity(0.5)
            .cornerRadius (29)
            .frame (height: 50)
            .font(.system(size: 40))
            .foregroundColor(Color.white)
    }
}

struct CustomTextField: View {
    var placeholder: Text
    @Binding var text: String
    var editingChanged: (Bool)->() = { _ in }
    var commit: ()->() = { }
    @Binding var password : String

    var body: some View {
        ZStack(alignment: .leading) {
            if text.isEmpty { placeholder }
           // TextField("", text: $text, onEditingChanged: editingChanged, onCommit: commit)
            SecureField(text, text: $password) {

            }
        }
    }
}


问:
Refactoring PL/SQL: many cursors with same rowtype (in theory)
I am writing some PL/SQL and found myself falling into a repeptitive pattern:

```<code>cursor c_curs1 is
   select a, b, c
   from (...) big_subquery_1
   where big_subquery_1.a_ind = 'Y'

cursor c_curs2 is
   select a, b, c
   from (...) big_subquery_2
   where big_subquery_2.b_ind = 'R'

cursor c_curs3 is
   select a, b, c
   from (...) big_subquery_3
   where big_subquery_3.c_ind = 'M'

...
type t_curs1_tab is table of c_curs1;
type t_curs2_tab is table of c_curs2;
type t_curs3_tab is table of c_curs3;
...
v_curs1_results t_curs1_tab := t_curs1_tab();
v_curs2_results t_curs2_tab := t_curs2_tab();
v_curs3_results t_curs3_tab := t_curs3_tab();
</code>```

Then when processing the results, I have code like this:

```<code>    open c_curs1;
    fetch c_curs1 bulk collect into v_curs1_results;
    close c_curs1;

    if v_curs1_results.first is not null and v_curs1_results.last is not null then
       for i in v_curs1_results.first .. v_curs1_results.last loop
           /*Do something with field a in the results
             Do something with field b in the results
             Do something with field c in the results*/
           ....
       end loop;
    end if;
</code>```

The code in the processing loop is the same for all cursors, as all 3 cursors return a,b,c - the only difference being which cursor is referenced. I wanted to refactor this into some sort of generic result-set processor, but I'm stuck here:

```<code>procedure sp_process_collection(in_collection t_curs1_tab) is ...
</code>```

I can only call this with v_curs1_results, I can't call it with v_curs2_results or I get a PLS-00306 wrong number of types or arguments... compiler error. Is there any way to do this generically so I only have to write one collection processing procedure? I have this pattern of cursor (returning the same three columns, always the same types) appears in several other parts of the same package, and the processing loop, while semantically the same is sometimes written with slightly different code. I'd very much like to centralize the processing in one procedure, I just can'd figure out how to do it in PL/SQL. I know PL/SQL doesn't have generics (Which I think would have made a Java/C# solution fairly trivial), but I'm wondering if there's another way to approach this problem that I just haven't thought of.

(using Oracle 10g)

答:
Seems like you HAVE to have 3 cursors because the "big_subquery" in each are different I assume.  So, you really just need to centralize a procedure to handle processing a, b, and c results.  Nothing too fancy here, just define a local procedure to do this:

```<code>CREATE or replace procedure my_proc IS

  cursor c_curs1 is
   select a, b, c
   from (...) big_subquery_1
   where big_subquery_1.a_ind = 'Y';

  cursor c_curs2 is
   select a, b, c
   from (...) big_subquery_2
   where big_subquery_2.b_ind = 'R';

  cursor c_curs3 is
   select a, b, c
   from (...) big_subquery_3
   where big_subquery_3.c_ind = 'M';

  -- local procedure to handle processing of a,b,c "types"
  procedure process_type(i_type in varchar2) is
  begin
    -- do something great here
  end process_type;

BEGIN
  for rec in c_curs1
  loop
    process_type(rec.a);
    -- do something else
    process_type(rec.b);
    -- do something more
    process_type(rec.c);
    -- do something even more
  end loop;

  for rec in c_curs2
  loop
    -- do processing for this cursor
    -- use process_type like above
  end loop;

  for rec in c_curs3
  loop
    -- do processing for this cursor
    -- use process_type like above
  end loop;

END;
</code>```

Of course, if you need to process all 3 types together for each row, or if the types are different (varchar2, date, and number), just modify the process_type procedure to pass in all 3 (a,b,and c).  Something like:

```<code>procedure process_type(i_type_a in varchar2, i_type_b in date, i_type_c in number) is
  begin
    -- do something great here
  end process_type;
</code>```

And you can make this a function if you need a return value.

Body:
I am writing some PL/SQL and found myself falling into a repeptitive pattern:

cursor c_curs1 is
   select a, b, c
   from (...) big_subquery_1
   where big_subquery_1.a_ind = 'Y'

cursor c_curs2 is
   select a, b, c
   from (...) big_subquery_2
   where big_subquery_2.b_ind = 'R'

cursor c_curs3 is
   select a, b, c
   from (...) big_subquery_3
   where big_subquery_3.c_ind = 'M'

...
type t_curs1_tab is table of c_curs1;
type t_curs2_tab is table of c_curs2;
type t_curs3_tab is table of c_curs3;
...
v_curs1_results t_curs1_tab := t_curs1_tab();
v_curs2_results t_curs2_tab := t_curs2_tab();
v_curs3_results t_curs3_tab := t_curs3_tab();

Then when processing the results, I have code like this:

    open c_curs1;
    fetch c_curs1 bulk collect into v_curs1_results;
    close c_curs1;

    if v_curs1_results.first is not null and v_curs1_results.last is not null then
       for i in v_curs1_results.first .. v_curs1_results.last loop
           /*Do something with field a in the results
             Do something with field b in the results
             Do something with field c in the results*/
           ....
       end loop;
    end if;

The code in the processing loop is the same for all cursors, as all 3 cursors return a,b,c - the only difference being which cursor is referenced. I wanted to refactor this into some sort of generic result-set processor, but I'm stuck here:

procedure sp_process_collection(in_collection t_curs1_tab) is ...

I can only call this with v_curs1_results, I can't call it with v_curs2_results or I get a PLS-00306 wrong number of types or arguments... compiler error. Is there any way to do this generically so I only have to write one collection processing procedure? I have this pattern of cursor (returning the same three columns, always the same types) appears in several other parts of the same package, and the processing loop, while semantically the same is sometimes written with slightly different code. I'd very much like to centralize the processing in one procedure, I just can'd figure out how to do it in PL/SQL. I know PL/SQL doesn't have generics (Which I think would have made a Java/C# solution fairly trivial), but I'm wondering if there's another way to approach this problem that I just haven't thought of.

(using Oracle 10g)

Body:
Seems like you HAVE to have 3 cursors because the "big_subquery" in each are different I assume.  So, you really just need to centralize a procedure to handle processing a, b, and c results.  Nothing too fancy here, just define a local procedure to do this:

CREATE or replace procedure my_proc IS

  cursor c_curs1 is
   select a, b, c
   from (...) big_subquery_1
   where big_subquery_1.a_ind = 'Y';

  cursor c_curs2 is
   select a, b, c
   from (...) big_subquery_2
   where big_subquery_2.b_ind = 'R';

  cursor c_curs3 is
   select a, b, c
   from (...) big_subquery_3
   where big_subquery_3.c_ind = 'M';

  -- local procedure to handle processing of a,b,c "types"
  procedure process_type(i_type in varchar2) is
  begin
    -- do something great here
  end process_type;

BEGIN
  for rec in c_curs1
  loop
    process_type(rec.a);
    -- do something else
    process_type(rec.b);
    -- do something more
    process_type(rec.c);
    -- do something even more
  end loop;

  for rec in c_curs2
  loop
    -- do processing for this cursor
    -- use process_type like above
  end loop;

  for rec in c_curs3
  loop
    -- do processing for this cursor
    -- use process_type like above
  end loop;

END;

Of course, if you need to process all 3 types together for each row, or if the types are different (varchar2, date, and number), just modify the process_type procedure to pass in all 3 (a,b,and c).  Something like:

procedure process_type(i_type_a in varchar2, i_type_b in date, i_type_c in number) is
  begin
    -- do something great here
  end process_type;

And you can make this a function if you need a return value.


问:
Creating multiple consumers for a Single kafka topic
I have a spring boot application. I wish to implement a functionaly that consumes from a Kafka topic and for every consumed message it calls another method that does some processing on the message and then stores it in a database. The source kafka topic has 12 partitions. I want to create 6 or 12 kafka consumers under the same consumer group. All of the consumers will consume messages from Kafka and call the function. I am not able to get to a good design for this. Can someone help me ? </p>

答:
The source kafka topic has 12 partitions. I want to create 6 or 12 kafka consumers under the same consumer group

You can either set spring.kafka.listener.concurrency or you can simply run multiple Java processes on the same machine or multiple machines with the same configs.

There's nothing else you need to do as the rest is handled by the Consumer API


问:
How can i add a value/entry to a field within a collection in firebase
Firebase DB

My code trying to addtodo
error on console once i click add to do

Just wondering does anyone know how i would go about getting my addtodo to store in my todolist field in the house subcollection
 `

```<code>todo_title:string;
  todo_description: string;
  todo_last_date: Date;
  todo_owner: string;

  constructor(private navCtrl: NavController, private toastCtrl:ToastController) {
  this.todo_owner = firebase.auth().currentUser.uid;
  }
  ngOnInit() {

    firebase.firestore().collection("house").doc("this.house.id").collection("toDoList").add({
      title: this.todo_title,
      description: this.todo_description,
      last_date: this.todo_last_date,
      owner: this.todo_owner,
      created: firebase.firestore.FieldValue.serverTimestamp
      ()
    }).then((docRef) => {
      this.toastCtrl.create({
        message: "toDo has been added!",
        duration: 2000
      }).then((toast) => {
        toast.present();
        this.navCtrl.navigateBack
      })
       }).catch((err) => {
         this.toastCtrl.create({
           message: "ToDo has been Added",
           duration: 3000
         }).then((toast) => {
           toast.present();
         })
         })
       }

  }`
</code>```

答:
The error tells you that the value you pass to title (the property of the object you pass to the add() method) is undefined. So, in other words, this.todo_title seems to be undefined.

In addition, I think that you should do:

```<code>firebase.firestore().collection("house").doc(this.house.id).collection("toDoList").add(...)
</code>```

Note doc(this.house.id) instead of doc("this.house.id"): with the latter you pass a string with a value of "this.house.id".

Body:
Firebase DB

My code trying to addtodo
error on console once i click add to do

Just wondering does anyone know how i would go about getting my addtodo to store in my todolist field in the house subcollection
 `

todo_title:string;
  todo_description: string;
  todo_last_date: Date;
  todo_owner: string;

  constructor(private navCtrl: NavController, private toastCtrl:ToastController) {
  this.todo_owner = firebase.auth().currentUser.uid;
  }
  ngOnInit() {

    firebase.firestore().collection("house").doc("this.house.id").collection("toDoList").add({
      title: this.todo_title,
      description: this.todo_description,
      last_date: this.todo_last_date,
      owner: this.todo_owner,
      created: firebase.firestore.FieldValue.serverTimestamp
      ()
    }).then((docRef) => {
      this.toastCtrl.create({
        message: "toDo has been added!",
        duration: 2000
      }).then((toast) => {
        toast.present();
        this.navCtrl.navigateBack
      })
       }).catch((err) => {
         this.toastCtrl.create({
           message: "ToDo has been Added",
           duration: 3000
         }).then((toast) => {
           toast.present();
         })
         })
       }

  }`

Body:
The error tells you that the value you pass to title (the property of the object you pass to the add() method) is undefined. So, in other words, this.todo_title seems to be undefined.

In addition, I think that you should do:

firebase.firestore().collection("house").doc(this.house.id).collection("toDoList").add(...)

Note doc(this.house.id) instead of doc("this.house.id"): with the latter you pass a string with a value of "this.house.id".


问:
Passing data from PHP/HTML to .vue Component
What I'm trying to do is seemingly simple, but I can't seem to figure it out. Basically, I have 2 files:

A PHP file with the following:

```<code>...
<user-panel v-if="user.id  && loaded" v-bind:user="user" v-bind:name="theUserName"></user-panel>
...
</code>```

A .Vue component file with the following (that gets compiled into another file):

```<code><template>
    <span id="userPanel" class="d-flex align-items-center">
        <a href="#" role="button" class="user-dropdown-toggle">
            <div class="logged-in d-flex align-items-center">
                <span class="d-flex align-items-center justify-contnet-center"></span>
                {{name}}
            </div>
        </a>
    </span>
</template>

<script>
    export default {
        name: "UserPanel",
        props: ['user'],
        created () {
            console.log(this.$refs.myTestField.value)
        }
    }
</script>
</code>```

All I'd like to do is pass data from the PHP to Vue into {{name}}. I've tried v-bind, a data-attribute, a hidden input, etc. Any help would be greatly appreciated.

答:
My intention is to transfer data from my .php file to the .js file where the VUE code resides. Here I show you my code. In the proposed example I would like to import a simple string, subsequently I would like to import a JSON. Thank you so much.
File PHP

```<code><div id='app'> <App v-bind:import='Value Import'> C'è QUALCHE PROBLEMA </App> </div>"
</code>```

File .js

```<code>var App = Vue.component("App", {
    template: `
      <div class="container">
        <div>
          <h2>{{ titolo }}</h2>
          <h3>{{ import }}</h3>

        </div>
      </div>
    `,
    props: ['import'],

    data() {
      return {
        color: "color: red",
        titolo: "Inizio Container",
      };
    }
  });

  new Vue({
    el: "#app",
  });
</code>```

Quanto sopra purtroppo non funziona.

Body:
What I'm trying to do is seemingly simple, but I can't seem to figure it out. Basically, I have 2 files:

A PHP file with the following:

...
<user-panel v-if="user.id  && loaded" v-bind:user="user" v-bind:name="theUserName"></user-panel>
...

A .Vue component file with the following (that gets compiled into another file):

<template>

                {{name}}

</template>

All I'd like to do is pass data from the PHP to Vue into {{name}}. I've tried v-bind, a data-attribute, a hidden input, etc. Any help would be greatly appreciated.

Body:
My intention is to transfer data from my .php file to the .js file where the VUE code resides. Here I show you my code. In the proposed example I would like to import a simple string, subsequently I would like to import a JSON. Thank you so much.
File PHP

<div id='app'> <App v-bind:import='Value Import'> C'è QUALCHE PROBLEMA </App> </div>"

File .js

var App = Vue.component("App", {
    template: `
      <div class="container">
        <div>
          <h2>{{ titolo }}</h2>
          <h3>{{ import }}</h3>

        </div>
      </div>
    `,
    props: ['import'],

    data() {
      return {
        color: "color: red",
        titolo: "Inizio Container",
      };
    }
  });

  new Vue({
    el: "#app",
  });

Quanto sopra purtroppo non funziona.