问:
Pagination help in SQL
The below inner SELECT returns huge amount of rows (1000000+) and the outer SELECTs(alpha BETWEEN #startRec# AND #endRec#) is used for PAGINATION
to display data with 25 in each page.

Issue is:-This PAGINATION done below is very slow and slows the entire display of data.So could all please help me on doing this below
pagination in a BETTER WAY? COde about pagination would be best.

**I am very sorry to put in this way but i am very new to Pagination concepts and so need your help.

```<code>/*********ORIGINAL QUERY ****/
SELECT
*
FROM
(
SELECT
beta.*, rownum as alpha
FROM
(
SELECT
p.lastname, p.firstname, porg.DEPARTMENT,
porg.org_relationship,
porg.enterprise_name,
(
SELECT
count(*)
FROM
test_person p, test_contact c1, test_org_person porg
WHERE
p.p_id = c1.ref_id(+)
AND p.p_id = porg.o_p_id
$where_clause$

) AS results
FROM
test_person p, test_contact c1, test_org_person porg
WHERE
p.p_id = c1.ref_id(+)
AND p.p_id = porg.o_p_id
$where_clause$

ORDER BY
upper(p.lastname), upper(p.firstname)
) beta
)
WHERE
alpha BETWEEN #startRec# AND #endRec#
</code>```

My tried implementation below

(1)The inner most query..is the 1st QUERY fetching the data.
(2)Then,we do a total COUNT on the above data.

Now,main issue is running the query goes on forever....and finally i have to forcibly cancel it.
I feel there is something missing in the below query for which it hangs off.

Also,I came to know doing the COUNT outside is the best approach for performance.So,could you please correct the query below so that I am able return the COUNT
*** DATA using Pagination,rownum etc.Mainly with the aliases below,rownum and getting data.

```<code>select * from
( select x.* ,rownum rnum

from ( SELECT
count(*) as results /****2nd QUERY is OUTSIDE to get total count**/
</code>```

Question is here,how do i access the data selected inside the 1st query below

```<code>from ( /****1st query to SELECT data***/

SELECT
p.lastname, p.firstname, porg.DEPARTMENT,
porg.org_relationship,
porg.enterprise_name

FROM
t_person p, t_contact c1, t_o_person porg
WHERE rownum <10
and
p.person_id = c1.ref_id(+)
AND p.person_id = porg.o_person_id

ORDER BY
upper(p.lastname), upper(p.firstname)

) y ------------------>alias defined Y from data of the 1st query

)x ------------------>alias defined X
where rownum <= 20 )
where rnum >= 1
</code>```

答:
These are specifically intended for ASP, but can be adapted without much trouble:
http://databases.aspfaq.com/database/how-do-i-page-through-a-recordset.html
Personally, I implemented the "#Temp table" stored procedure method when I recently needed a paging solution.</p>

OwnerDisplayName: Neer

LastEditorDisplayName: Tom H.

ContentLicense: CC BY-SA 2.5

Title: Pagination help in SQL

Body:
The below inner SELECT returns huge amount of rows (1000000+) and the outer SELECTs(alpha BETWEEN #startRec# AND #endRec#) is used for PAGINATION
to display data with 25 in each page.

Issue is:-This PAGINATION done below is very slow and slows the entire display of data.So could all please help me on doing this below
pagination in a BETTER WAY? COde about pagination would be best.

**I am very sorry to put in this way but i am very new to Pagination concepts and so need your help.

/*********ORIGINAL QUERY ****/
SELECT
*
FROM
(
SELECT
beta.*, rownum as alpha
FROM
(
SELECT
p.lastname, p.firstname, porg.DEPARTMENT,
porg.org_relationship,
porg.enterprise_name,
(
SELECT
count(*)
FROM
test_person p, test_contact c1, test_org_person porg
WHERE
p.p_id = c1.ref_id(+)
AND p.p_id = porg.o_p_id
$where_clause$

) AS results
FROM
test_person p, test_contact c1, test_org_person porg
WHERE
p.p_id = c1.ref_id(+)
AND p.p_id = porg.o_p_id
$where_clause$

ORDER BY
upper(p.lastname), upper(p.firstname)
) beta
)
WHERE
alpha BETWEEN #startRec# AND #endRec#

My tried implementation below

(1)The inner most query..is the 1st QUERY fetching the data.
(2)Then,we do a total COUNT on the above data.

Now,main issue is running the query goes on forever....and finally i have to forcibly cancel it.
I feel there is something missing in the below query for which it hangs off.

Also,I came to know doing the COUNT outside is the best approach for performance.So,could you please correct the query below so that I am able return the COUNT
*** DATA using Pagination,rownum etc.Mainly with the aliases below,rownum and getting data.

select * from
( select x.* ,rownum rnum

from ( SELECT
count(*) as results /****2nd QUERY is OUTSIDE to get total count**/

Question is here,how do i access the data selected inside the 1st query below

from ( /****1st query to SELECT data***/

SELECT
p.lastname, p.firstname, porg.DEPARTMENT,
porg.org_relationship,
porg.enterprise_name

FROM
t_person p, t_contact c1, t_o_person porg
WHERE rownum <10
and
p.person_id = c1.ref_id(+)
AND p.person_id = porg.o_person_id

ORDER BY
upper(p.lastname), upper(p.firstname)

) y ------------------>alias defined Y from data of the 1st query

)x ------------------>alias defined X
where rownum <= 20 )
where rnum >= 1


来源: stackexchange

问:
selectBooleanCheckbox in icefaces
```<code><ice:column style="width: 30px;">
                    <f:facet name="header">
                        <ice:selectBooleanCheckbox
                            value="#{createToolsOrderInwardsBean.test}"
                            partialSubmit="true"
                            valueChangeListener="#{createToolsOrderInwardsBean.selectInwardQuantityChk}"
                            id="slc-tlmanage-selectallee"></ice:selectBooleanCheckbox>
                    </f:facet>
                    <ice:selectBooleanCheckbox value="#{currentRow.chkInwardQuantity}"
                        immediate="true" partialSubmit="true" style="margin-left: 10px;"
                        id="slc-tlmanage-enableinput"></ice:selectBooleanCheckbox>
                </ice:column>
</code>```

I have this code whtin ocefaces datatable.When i select first one than all other checkbox whin that column of datatable will be selected.

below i described a valuchage method

```<code> public void selectInwardQuantityChk(ValueChangeEvent evt){
        if(evt != null){
            Boolean value =(Boolean)evt.getNewValue();
            if(test)
                for(int i=0;i<this.toolsOrderVO.getToolsOrderItemVOList().size();i++){
                    this.toolsOrderVO.getToolsOrderItemVOList().get(i).setChkInwardQuantity(value);
                    System.out.println("int the for loop for changing value ============>"+this.toolsOrderVO.getToolsOrderItemVOList().get(i).getChkInwardQuantity());
                }

        }
    }
</code>```

method called and even checkbox value can't change.

答:
There were considerable typos in your question, So my understanding of your problem could be patchy. If I understand your problem correctly, then it can be solved easily.

Add this line to your event handler.(At the start of the method)

```<code>if (!evt.getPhaseId().equals(PhaseId.INVOKE_APPLICATION)) {
            evt.setPhaseId(PhaseId.INVOKE_APPLICATION);
            evt.queue();
            return;
        }
</code>```

ContentLicense: CC BY-SA 3.0

Title: selectBooleanCheckbox in icefaces

Body:
<ice:column style="width: 30px;">
                    <f:facet name="header">
                        <ice:selectBooleanCheckbox
                            value="#{createToolsOrderInwardsBean.test}"
                            partialSubmit="true"
                            valueChangeListener="#{createToolsOrderInwardsBean.selectInwardQuantityChk}"
                            id="slc-tlmanage-selectallee"></ice:selectBooleanCheckbox>
                    </f:facet>
                    <ice:selectBooleanCheckbox value="#{currentRow.chkInwardQuantity}"
                        immediate="true" partialSubmit="true" style="margin-left: 10px;"
                        id="slc-tlmanage-enableinput"></ice:selectBooleanCheckbox>
                </ice:column>

I have this code whtin ocefaces datatable.When i select first one than all other checkbox whin that column of datatable will be selected.

below i described a valuchage method

 public void selectInwardQuantityChk(ValueChangeEvent evt){
        if(evt != null){
            Boolean value =(Boolean)evt.getNewValue();
            if(test)
                for(int i=0;i<this.toolsOrderVO.getToolsOrderItemVOList().size();i++){
                    this.toolsOrderVO.getToolsOrderItemVOList().get(i).setChkInwardQuantity(value);
                    System.out.println("int the for loop for changing value ============>"+this.toolsOrderVO.getToolsOrderItemVOList().get(i).getChkInwardQuantity());
                }

        }
    }

method called and even checkbox value can't change.

Body:
There were considerable typos in your question, So my understanding of your problem could be patchy. If I understand your problem correctly, then it can be solved easily.

Add this line to your event handler.(At the start of the method)

if (!evt.getPhaseId().equals(PhaseId.INVOKE_APPLICATION)) {
            evt.setPhaseId(PhaseId.INVOKE_APPLICATION);
            evt.queue();
            return;
        }


问:
How to take user input using getter and setter
I  have created a getter and setter class as book and from that i am accessing setbookName,setbookPrice,setAuthorName similar get methods too but i am not able to take inputs from user please check my code     </p>

```<code>Scanner sc=new Scanner(System.in);
try
{
    System.out.println("Enter book name:");
    String bookName=sc.nextLine();
    System.out.println("Enter book price:");
    String bookPrice=sc.nextLine();
    System.out.println("Enter author name:");
    String authorName=sc.nextLine();
}
catch(Exception e)
{
    System.out.println("I/O Exception");
}
book b=new book();
b.setBookName(bookName);          //here i am facing error
b.setBookPrice(bookPrice);
b.setAuthorName(authorName);
    System.out.println("Book Details");
    System.out.println("Book Name"+b.getBookName());
    System.out.println("Book Name"+b.getBookPrice());
    System.out.println("Book Name"+b.getAuthorName());
}
</code>```

<p>// book class</p>

```<code>    class book
   {

     private String bookName;
    private String authorName;
    private String bookPrice;

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public String getAuthorName() {
        return authorName;
    }

    public void setAuthorName(String authorName) {
        this.authorName = authorName;
    }

    public String getBookPrice() {
        return bookPrice;
    }

    public void setBookPrice(String bookPrice) {
        this.bookPrice = bookPrice;
    }
</code>```

答:
Following is your main code - please see my comment that I've added to it...

For future reference, it would be helpful if you included the error messages you are getting. I'm assuming that the code is representative of what you are doing:

Scanner sc=new Scanner(System.in);
try
{
    System.out.println("Enter book name:");
    String bookName=sc.nextLine();
    System.out.println("Enter book price:");
    String bookPrice=sc.nextLine();
    System.out.println("Enter author name:");
    String authorName=sc.nextLine();
}
/********************
 * The variables bookName, bookPrice, authorName cease to exist after the above
 * curly brace.
 * If you want to access them beyond this point, you must declare them before
 * the try { statement.
 * Alternatively, move the declaration of your Book prior to the try statement
 * and set the properties of the book in the above try block
 * e.g. use b.setBookName(sc.nextLine())
 * instead of reading it into the String bookName variable.
 *************************************************/
catch(Exception e)
{
    System.out.println("I/O Exception");
}
book b=new book();
b.setBookName(bookName);          //here i am facing error
b.setBookPrice(bookPrice);
b.setAuthorName(authorName);
    System.out.println("Book Details");
    System.out.println("Book Name"+b.getBookName());
    System.out.println("Book Name"+b.getBookPrice());
    System.out.println("Book Name"+b.getAuthorName());
}
```

<p>Following is one possible example of how to rewrite it:</p>

<pre class="lang-java prettyprint-override"><code>Scanner sc=new Scanner(System.in);
book b=new book();
try
{
    System.out.println("Enter book name:");
    b.setBookName(sc.nextLine());
    System.out.println("Enter book price:");
    b.setBookPrice(sc.nextLine());
    System.out.println("Enter author name:");
    b.setAuthorName(sc.nextLine());
}
catch(Exception e)
{
    System.out.println("I/O Exception");
}

    System.out.println("Book Details");
    System.out.println("Book Name"+b.getBookName());
    System.out.println("Book Name"+b.getBookPrice());
    System.out.println("Book Name"+b.getAuthorName());
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I  have created a getter and setter class as book and from that i am accessing setbookName,setbookPrice,setAuthorName similar get methods too but i am not able to take inputs from user please check my code

Scanner sc=new Scanner(System.in);
try
{
    System.out.println("Enter book name:");
    String bookName=sc.nextLine();
    System.out.println("Enter book price:");
    String bookPrice=sc.nextLine();
    System.out.println("Enter author name:");
    String authorName=sc.nextLine();
}
catch(Exception e)
{
    System.out.println("I/O Exception");
}
book b=new book();
b.setBookName(bookName);          //here i am facing error
b.setBookPrice(bookPrice);
b.setAuthorName(authorName);
    System.out.println("Book Details");
    System.out.println("Book Name"+b.getBookName());
    System.out.println("Book Name"+b.getBookPrice());
    System.out.println("Book Name"+b.getAuthorName());
}

// book class

    class book
   {

     private String bookName;
    private String authorName;
    private String bookPrice;

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public String getAuthorName() {
        return authorName;
    }

    public void setAuthorName(String authorName) {
        this.authorName = authorName;
    }

    public String getBookPrice() {
        return bookPrice;
    }

    public void setBookPrice(String bookPrice) {
        this.bookPrice = bookPrice;
    }

Body:
Following is your main code - please see my comment that I've added to it...

For future reference, it would be helpful if you included the error messages you are getting. I'm assuming that the code is representative of what you are doing:

Scanner sc=new Scanner(System.in);
try
{
    System.out.println("Enter book name:");
    String bookName=sc.nextLine();
    System.out.println("Enter book price:");
    String bookPrice=sc.nextLine();
    System.out.println("Enter author name:");
    String authorName=sc.nextLine();
}
/********************
 * The variables bookName, bookPrice, authorName cease to exist after the above
 * curly brace.
 * If you want to access them beyond this point, you must declare them before
 * the try { statement.
 * Alternatively, move the declaration of your Book prior to the try statement
 * and set the properties of the book in the above try block
 * e.g. use b.setBookName(sc.nextLine())
 * instead of reading it into the String bookName variable.
 *************************************************/
catch(Exception e)
{
    System.out.println("I/O Exception");
}
book b=new book();
b.setBookName(bookName);          //here i am facing error
b.setBookPrice(bookPrice);
b.setAuthorName(authorName);
    System.out.println("Book Details");
    System.out.println("Book Name"+b.getBookName());
    System.out.println("Book Name"+b.getBookPrice());
    System.out.println("Book Name"+b.getAuthorName());
}

Following is one possible example of how to rewrite it:

Scanner sc=new Scanner(System.in);
book b=new book();
try
{
    System.out.println("Enter book name:");
    b.setBookName(sc.nextLine());
    System.out.println("Enter book price:");
    b.setBookPrice(sc.nextLine());
    System.out.println("Enter author name:");
    b.setAuthorName(sc.nextLine());
}
catch(Exception e)
{
    System.out.println("I/O Exception");
}

    System.out.println("Book Details");
    System.out.println("Book Name"+b.getBookName());
    System.out.println("Book Name"+b.getBookPrice());
    System.out.println("Book Name"+b.getAuthorName());
}


问:
How to check if dark mode is enabled on iOS/Android using Flutter?
How can I check if dark mode is enabled in Android Q with Flutter?
 I know how to set the dark mode, but I didn't find a way to check the background theme.

Here is the code to set the dark theme.

```<code>darkTheme: ThemeData.dark(),
</code>```

答:
If you define a dark theme in your MaterialApp, your app will automatically go dark when Android Q dark theme is enabled. You have to specify your dark theme like this:

MaterialApp(
  theme: ThemeData(
    brightness: Brightness.light,
    primaryColor: Colors.red,
  ),
  darkTheme: ThemeData(
    brightness: Brightness.dark,
  ),
);
```

According to this medium article,

Now when you toggle Dark Theme in your system drawer, your Flutter app will automatically switch from your regular theme to your darkTheme!

However, if you want to manually check whether you're on dark mode, you can easily write a method using the Platform Channel API. More details here. As for the native code, check here.

Body:
How can I check if dark mode is enabled in Android Q with Flutter?
 I know how to set the dark mode, but I didn't find a way to check the background theme.

Here is the code to set the dark theme.

darkTheme: ThemeData.dark(),

Body:
If you define a dark theme in your MaterialApp, your app will automatically go dark when Android Q dark theme is enabled. You have to specify your dark theme like this:

MaterialApp(
  theme: ThemeData(
    brightness: Brightness.light,
    primaryColor: Colors.red,
  ),
  darkTheme: ThemeData(
    brightness: Brightness.dark,
  ),
);

According to this medium article,

Now when you toggle Dark Theme in your system drawer, your Flutter app will automatically switch from your regular theme to your darkTheme!

However, if you want to manually check whether you're on dark mode, you can easily write a method using the Platform Channel API. More details here. As for the native code, check here.


问:
How to get all documents(including data) in String array from a collection in Firestore?
I want to get all itemName of all documents in a String array,
further I want to perform searching on that array, how could I achieve my task? Please help me. Thanx.

https://i.stack.imgur.com/ge5x2.png

答:
I want to get all itemName of all documents in a string array

To get all item names within all documents, you need to create a reference and use a get() call, like in the following lines of code:

```<code>FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference offersDataRef = rootRef.collection("MartWayDB").document("Offers")
    .collection("OffersData");
offersDataRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            String[] array = new String[task.getResult().size()];
            int count = 0;
            for (QueryDocumentSnapshot document : task.getResult()) {
                String itemName = document.getString("itemName");
                array[count] = itemName;
                Log.d(TAG, itemName);
                count++;
            }

            //Do what you need to do with your array
        }
    }
});
</code>```

Body:
I want to get all itemName of all documents in a string array

To get all item names within all documents, you need to create a reference and use a get() call, like in the following lines of code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference offersDataRef = rootRef.collection("MartWayDB").document("Offers")
    .collection("OffersData");
offersDataRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            String[] array = new String[task.getResult().size()];
            int count = 0;
            for (QueryDocumentSnapshot document : task.getResult()) {
                String itemName = document.getString("itemName");
                array[count] = itemName;
                Log.d(TAG, itemName);
                count++;
            }

            //Do what you need to do with your array
        }
    }
});


问:
How do I remove values that are under a specified length of characters from a dictionary?
In this code, I am trying to remove values (synonyms) within a list that are 7 or fewer characters from the dictionary. For some reason, my code is only partially removing the values that are 7 or fewer characters. Also, please do not remove any of the functions or use imports and sets to solve and keep the current code as intact as possible.

My current output:

```<code>{'show': ['exhibit', 'note', 'point to', 'indicate', 'reveal', 'demonstrate'], 'slow': ['unhurried', 'leisurely', 'behind', 'slack'],
'dangerous': ['perilous', 'hazardous', 'uncertain']}

</code>```

Desired output:

```<code>{'show' : ['demonstrate', 'indicate', 'point to'],
'slow' : ['leisurely', 'unhurried'],
'dangerous' : ['hazardous', 'perilous', 'uncertain']}
</code>```

```<code>word_dict = {'show': ['display', 'exhibit', 'convey', 'communicate', 'manifest', 'disclose'],
             'slow': ['unhurried', 'gradual', 'leisurely', 'late', 'behind', 'tedious', 'slack'],
             'dangerous': ['perilous', 'hazardous', 'uncertain']}

def main():
    edited_synonyms = remove_word(word_dict)
    print(edited_synonyms)

def remove_word(word_dict):
    for key, value in word_dict.items():
        for item in value:
            if len(item) <= 7:
                value.remove(item)
    return word_dict

main()
</code>```

答:
Create a new list to filter the values with length > 7 and later assign it to the respective key.

Simply, You can modify your code like this:

```<code>word_dict = {'show': ['exhibit', 'note', 'point to', 'indicate', 'reveal', 'demonstrate'], 'slow': ['unhurried', 'leisurely', 'behind', 'slack'],
            'dangerous': ['perilous', 'hazardous', 'uncertain']}

def main():
    edited_synonyms = remove_word(word_dict)
    print(edited_synonyms)

def remove_word(word_dict):
    for key, value in word_dict.items():
        new_val = []
        for item in value:
            if len(item) > 7:
                new_val.append(item)
        word_dict[key] = new_val
    return word_dict

main()
</code>```

Body:
In this code, I am trying to remove values (synonyms) within a list that are 7 or fewer characters from the dictionary. For some reason, my code is only partially removing the values that are 7 or fewer characters. Also, please do not remove any of the functions or use imports and sets to solve and keep the current code as intact as possible.

My current output:

{'show': ['exhibit', 'note', 'point to', 'indicate', 'reveal', 'demonstrate'], 'slow': ['unhurried', 'leisurely', 'behind', 'slack'],
'dangerous': ['perilous', 'hazardous', 'uncertain']}

Desired output:

{'show' : ['demonstrate', 'indicate', 'point to'],
'slow' : ['leisurely', 'unhurried'],
'dangerous' : ['hazardous', 'perilous', 'uncertain']}

word_dict = {'show': ['display', 'exhibit', 'convey', 'communicate', 'manifest', 'disclose'],
             'slow': ['unhurried', 'gradual', 'leisurely', 'late', 'behind', 'tedious', 'slack'],
             'dangerous': ['perilous', 'hazardous', 'uncertain']}

def main():
    edited_synonyms = remove_word(word_dict)
    print(edited_synonyms)

def remove_word(word_dict):
    for key, value in word_dict.items():
        for item in value:
            if len(item) <= 7:
                value.remove(item)
    return word_dict

main()

Body:
Create a new list to filter the values with length > 7 and later assign it to the respective key.

Simply, You can modify your code like this:

word_dict = {'show': ['exhibit', 'note', 'point to', 'indicate', 'reveal', 'demonstrate'], 'slow': ['unhurried', 'leisurely', 'behind', 'slack'],
            'dangerous': ['perilous', 'hazardous', 'uncertain']}

def main():
    edited_synonyms = remove_word(word_dict)
    print(edited_synonyms)

def remove_word(word_dict):
    for key, value in word_dict.items():
        new_val = []
        for item in value:
            if len(item) > 7:
                new_val.append(item)
        word_dict[key] = new_val
    return word_dict

main()


问:
Swift unwind modal
I'm working on an app where I have an error page displayed incase there is a network problem. The app has several storyboards, and this can happen anywhere.

```<code> func displayErrorPage(errorCode: ErrorCode) -> Void {
    if !isDisplayingError {
        DispatchQueue.main.async {
            self.isDisplayingError = true
            let storyboard = UIStoryboard(name: "alert", bundle: nil)
            let controller = storyboard.instantiateViewController(withIdentifier: "AlertScreen") as! AlertVC
            controller.errorCode = errorCode
            UIApplication.shared.topViewController?.present(controller, animated: true, completion: nil)
        }
    }
}
</code>```

I would like to use unwind to dismiss it, to clear out any views and get back to the home page. I have used this in the alert view to close, but sometimes doesn't work.

```<code> @IBAction func closeBtn(_ sender: Any) {
    flowError = true
    NetworkManager.shared().isDisplayingError = false
    performSegue(withIdentifier: "unwindToSH", sender: self)
 }
</code>```

Anyone with some pointers?

答:
Create  the unwind segue IBAction  in the view controller you want to unwind to.
Perhaps in your case it is HomeViewController. Add this code inside your HomeViewController

```<code>@IBAction func unwindToHomeVC(segue: UIStoryboardSegue) {}
</code>```

Wire up the unwind segue - Control drag from AlertVC’s ViewController icon to exit icon in the storyboard choose the unwind segue action (unwindToHomeVC) that was created in step 1 from the list of IBActions.

Specify a segue Identifier - specify its identifier in the Attributes Inspector of the Utilities Pane. Ex: “unwindToHomeVC”

Trigger unwind segue programmatically - trigger that in the appropriate place. In your case close button action

```<code>self.performSegue(withIdentifier: "unwindToMenu", sender: self)
</code>```

It will work even if you work with multiple storyboard as well, if your setup is right. I hope that this one would help you.
Thanks

Title: Swift unwind modal

Body:
I'm working on an app where I have an error page displayed incase there is a network problem. The app has several storyboards, and this can happen anywhere.

 func displayErrorPage(errorCode: ErrorCode) -> Void {
    if !isDisplayingError {
        DispatchQueue.main.async {
            self.isDisplayingError = true
            let storyboard = UIStoryboard(name: "alert", bundle: nil)
            let controller = storyboard.instantiateViewController(withIdentifier: "AlertScreen") as! AlertVC
            controller.errorCode = errorCode
            UIApplication.shared.topViewController?.present(controller, animated: true, completion: nil)
        }
    }
}

I would like to use unwind to dismiss it, to clear out any views and get back to the home page. I have used this in the alert view to close, but sometimes doesn't work.

 @IBAction func closeBtn(_ sender: Any) {
    flowError = true
    NetworkManager.shared().isDisplayingError = false
    performSegue(withIdentifier: "unwindToSH", sender: self)
 }

Anyone with some pointers?

Body:
Create  the unwind segue IBAction  in the view controller you want to unwind to.
Perhaps in your case it is HomeViewController. Add this code inside your HomeViewController

@IBAction func unwindToHomeVC(segue: UIStoryboardSegue) {}

Wire up the unwind segue - Control drag from AlertVC’s ViewController icon to exit icon in the storyboard choose the unwind segue action (unwindToHomeVC) that was created in step 1 from the list of IBActions.

Specify a segue Identifier - specify its identifier in the Attributes Inspector of the Utilities Pane. Ex: “unwindToHomeVC”

Trigger unwind segue programmatically - trigger that in the appropriate place. In your case close button action

self.performSegue(withIdentifier: "unwindToMenu", sender: self)

It will work even if you work with multiple storyboard as well, if your setup is right. I hope that this one would help you.
Thanks


问:
Does pull request in Azure devops merge the code and then runs the build definition
I have feature branch feature/feature1 and dev branch. I created a branch policy for dev branch where I have selected a build definition.

When I initiate a pull request from feature/feature1 to dev does it merge the 2 branches and then does the build? Or does it just build feature/feature1?

```<code> * [new branch]      dev                -> origin/dev
 * [new branch]      feature/feature2   -> origin/feature/feature2
 * [new branch]      feature/test       -> origin/feature/test
 * [new branch]      master             -> origin/master
 * [new branch]      release/release-1  -> origin/release/release-1
 * [new branch]      release/release-2  -> origin/release/release-2
 * [new ref]         refs/pull/37/merge -> pull/37/merge
##[command]git checkout --progress --force refs/remotes/pull/37/merge
Note: checking out 'refs/remotes/pull/37/merge'.
</code>```

答:
A pull request will always perform a merge into a temporary space in order to validate that the code in your source branch and the code in the target branch do not conflict.  If there are merge conflicts, you will be unable to complete the pull request.

If you have a pull request validation build configured, then this temporary result of the merge will also be built.  The contents of your branch are not built, only the result of the merge.

However this temporary merge result is discarded after checks run.

When you complete the pull request, your source branch will actually be merged into the target.

Body:
I have feature branch feature/feature1 and dev branch. I created a branch policy for dev branch where I have selected a build definition.

When I initiate a pull request from feature/feature1 to dev does it merge the 2 branches and then does the build? Or does it just build feature/feature1?

 * [new branch]      dev                -> origin/dev
 * [new branch]      feature/feature2   -> origin/feature/feature2
 * [new branch]      feature/test       -> origin/feature/test
 * [new branch]      master             -> origin/master
 * [new branch]      release/release-1  -> origin/release/release-1
 * [new branch]      release/release-2  -> origin/release/release-2
 * [new ref]         refs/pull/37/merge -> pull/37/merge
##[command]git checkout --progress --force refs/remotes/pull/37/merge
Note: checking out 'refs/remotes/pull/37/merge'.


问:
Why my isLocationEnabled need SuppressLint(MissingPermission) in EasyPermissions?
why it still need permission checker when i have used EasyPermissions?</p>

```<code>@SuppressLint("MissingPermission")
    @AfterPermissionGranted(100)
    private fun methodRequiresTwoPermission() {
        val perms =  Manifest.permission.ACCESS_FINE_LOCATION
        if (EasyPermissions.hasPermissions(this, perms)) {
            Toast.makeText(applicationContext, "Granted", Toast.LENGTH_SHORT).show()
            mMap.isMyLocationEnabled = true // Call requires permission. @SuppressLint("MissingPermission")
            mMap.getUiSettings().setMyLocationButtonEnabled(true)
        } else {
            Toast.makeText(applicationContext, "Denied", Toast.LENGTH_SHORT).show()
            EasyPermissions.requestPermissions(
                this, "Please allow the permission",
                100, perms
            )
        }
    }
</code>```

答:
The library you are using is not explicitly included in the Android SDK. It is a helper library developed by other developers by adding extra code.

Lint thinks that you are not requesting permissions at run-time because it doesn't see any code such as Activity#requestPermissions(), hence the warning.

But you can safely ignore or suppress the warning because it has been called from somewhere inside the library.

Body:
why it still need permission checker when i have used EasyPermissions?

@SuppressLint("MissingPermission")
    @AfterPermissionGranted(100)
    private fun methodRequiresTwoPermission() {
        val perms =  Manifest.permission.ACCESS_FINE_LOCATION
        if (EasyPermissions.hasPermissions(this, perms)) {
            Toast.makeText(applicationContext, "Granted", Toast.LENGTH_SHORT).show()
            mMap.isMyLocationEnabled = true // Call requires permission. @SuppressLint("MissingPermission")
            mMap.getUiSettings().setMyLocationButtonEnabled(true)
        } else {
            Toast.makeText(applicationContext, "Denied", Toast.LENGTH_SHORT).show()
            EasyPermissions.requestPermissions(
                this, "Please allow the permission",
                100, perms
            )
        }
    }


问:
Redux Action is not been dispatched
I am working on a react - redux application. Now I faced an issue to dispatch the action. The following code cannot dispatch the generateReport action.

```<code>import React, { Component } from "react";
import { Button, Icon } from "semantic-ui-react";
import { connect } from "react-redux";
import { submit, getFormValues, isValid } from "redux-form";
import { generateReport } from "../actions/generateActions";
import { Link } from "react-router-dom";

const docsButtonStyle = {
  position: "fixed",
  marginBottom: "0.5em",
  marginLeft: "0.1em",
  bottom: 0,
  left: 0,
  animation: "back-to-docs 1.5s ease-in-out infinite",
  zIndex: 6
};

class ButtonGroup extends Component {
  generate = () => {
    this.props.generateReport(this.props.values);
  };

  render() {
    return (
      <div style={docsButtonStyle}>
        <Button.Group vertical>
          <Button animated="fade" color="teal" onClick={this.generate}>
            <Button.Content hidden>Generate</Button.Content>
            <Button.Content visible>
              <Icon name="chart bar" size="large" />
            </Button.Content>
          </Button>
        </Button.Group>
      </div>
    );
  }
}

const mapStateToProps = state => ({
  values: getFormValues("privateForm")(state),
  valid: isValid("privateForm")(state)
});

const mapDispatchToProps = dispatch => ({
  generateReport,
  remoteSubmit: () => {
    dispatch(submit("privateForm"));
  }
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ButtonGroup);
</code>```

generateActions.js

```<code>export const generateReport = values => async dispatch => {
  console.log("test");
  try {
    dispatch(generateReportBegin());
    const response = await axios.post(`${ROOT_URL}/submit`, values);
    dispatch(generateReportSuccess());
  } catch (error) {

  }
};
</code>```

If I change connect function into

```<code>export default connect(
  mapStateToProps,
  {generateReport}
)(ButtonGroup);
</code>```

It works. Can anyone tell me why it does not work in the first situation? Thanks.

答:
This happens due to different behavior of connect function depending of passed arguments to mapDispatchToProps

If you pass function it will be called with dispatch as first argument and resulting object will be merged to props. In this case it is assumed that in supplied function you prepare dispatch calls for every action.

In code

```<code>const mapDispatchToProps = dispatch => ({
    generateReport,
    remoteSubmit: () => {
        dispatch(submit("privateForm"));
    }
});
</code>```

mapDispatchToProps will be called with dispatch as argument and produces object with 2 functions. remoteSubmit should work correctly as it is bound to dispatch. But generateReport is just some external function which is passed as is. So on any call to this.props.generateReport just function will be returned taking dispatch as argument. Redux belives that you already prepared everything needed for dispatching in mapDispatchToProps so it does nothing.

If you pass object as mapDispatchToProps (what is you do in second example), connect will call bindActionCreators for you and wrap generateReport inside dispatch call. So it works.

To make both actions work you should wrap all action creators in dispatch calls.

Possible ways to do so

```<code>const mapDispatchToProps = dispatch => ({
    generateReport: bindActionCreators(generateReport, dispatch),
    remoteSubmit: () => {
        dispatch(submit("privateForm"));
    }
});
</code>```

Another way

```<code>const mapDispatchToProps = dispatch => ({
    generateReport: (value) => dispatch(generateReport(value)),
    remoteSubmit: () => {
        dispatch(submit("privateForm"));
    }
});
</code>```

Or call mapDispatchToProps with one object containing all action creators. In this case connect will call bindActionCreators for you.

```<code>const mapDispatchToProps = {
    generateReport,
    remoteSubmit: () => submit("privateForm")
    }
</code>```

Title: Redux Action is not been dispatched

Body:
I am working on a react - redux application. Now I faced an issue to dispatch the action. The following code cannot dispatch the generateReport action.

import React, { Component } from "react";
import { Button, Icon } from "semantic-ui-react";
import { connect } from "react-redux";
import { submit, getFormValues, isValid } from "redux-form";
import { generateReport } from "../actions/generateActions";
import { Link } from "react-router-dom";

const docsButtonStyle = {
  position: "fixed",
  marginBottom: "0.5em",
  marginLeft: "0.1em",
  bottom: 0,
  left: 0,
  animation: "back-to-docs 1.5s ease-in-out infinite",
  zIndex: 6
};

class ButtonGroup extends Component {
  generate = () => {
    this.props.generateReport(this.props.values);
  };

  render() {
    return (

        <Button.Group vertical>
          <Button animated="fade" color="teal" onClick={this.generate}>
            <Button.Content hidden>Generate</Button.Content>
            <Button.Content visible>
              <Icon name="chart bar" size="large" />
            </Button.Content>
          </Button>
        </Button.Group>

    );
  }
}

const mapStateToProps = state => ({
  values: getFormValues("privateForm")(state),
  valid: isValid("privateForm")(state)
});

const mapDispatchToProps = dispatch => ({
  generateReport,
  remoteSubmit: () => {
    dispatch(submit("privateForm"));
  }
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ButtonGroup);

generateActions.js

export const generateReport = values => async dispatch => {
  console.log("test");
  try {
    dispatch(generateReportBegin());
    const response = await axios.post(`${ROOT_URL}/submit`, values);
    dispatch(generateReportSuccess());
  } catch (error) {

  }
};

If I change connect function into

export default connect(
  mapStateToProps,
  {generateReport}
)(ButtonGroup);

It works. Can anyone tell me why it does not work in the first situation? Thanks.

Body:
This happens due to different behavior of connect function depending of passed arguments to mapDispatchToProps

If you pass function it will be called with dispatch as first argument and resulting object will be merged to props. In this case it is assumed that in supplied function you prepare dispatch calls for every action.

In code

const mapDispatchToProps = dispatch => ({
    generateReport,
    remoteSubmit: () => {
        dispatch(submit("privateForm"));
    }
});

mapDispatchToProps will be called with dispatch as argument and produces object with 2 functions. remoteSubmit should work correctly as it is bound to dispatch. But generateReport is just some external function which is passed as is. So on any call to this.props.generateReport just function will be returned taking dispatch as argument. Redux belives that you already prepared everything needed for dispatching in mapDispatchToProps so it does nothing.

If you pass object as mapDispatchToProps (what is you do in second example), connect will call bindActionCreators for you and wrap generateReport inside dispatch call. So it works.

To make both actions work you should wrap all action creators in dispatch calls.

Possible ways to do so

const mapDispatchToProps = dispatch => ({
    generateReport: bindActionCreators(generateReport, dispatch),
    remoteSubmit: () => {
        dispatch(submit("privateForm"));
    }
});

Another way

const mapDispatchToProps = dispatch => ({
    generateReport: (value) => dispatch(generateReport(value)),
    remoteSubmit: () => {
        dispatch(submit("privateForm"));
    }
});

Or call mapDispatchToProps with one object containing all action creators. In this case connect will call bindActionCreators for you.

const mapDispatchToProps = {
    generateReport,
    remoteSubmit: () => submit("privateForm")
    }


问:
Does MySQL foreign_key_checks affect the entire database?
When I execute this command in MySQL:

```<code>SET FOREIGN_KEY_CHECKS=0;
</code>```

Does it affect the whole engine or it is only my current transaction?

答:
I had the same error when I tried to migrate Drupal database to a new local apache server(I am using XAMPP on Windows machine). Actually I don't know the meaning of this error, but after trying steps below, I imported the database without errors. Hope this could help:

Changing php.ini at C:\xampp\php\php.ini

```<code>max_execution_time = 600
max_input_time = 600
memory_limit = 1024M
post_max_size = 1024M
</code>```

Changing my.ini at C:\xampp\mysql\bin\my.ini

```<code>max_allowed_packet = 1024M
</code>```

Body:
When I execute this command in MySQL:

SET FOREIGN_KEY_CHECKS=0;

Does it affect the whole engine or it is only my current transaction?

Body:
I had the same error when I tried to migrate Drupal database to a new local apache server(I am using XAMPP on Windows machine). Actually I don't know the meaning of this error, but after trying steps below, I imported the database without errors. Hope this could help:

Changing php.ini at C:\xampp\php\php.ini

max_execution_time = 600
max_input_time = 600
memory_limit = 1024M
post_max_size = 1024M

Changing my.ini at C:\xampp\mysql\bin\my.ini

max_allowed_packet = 1024M


问:
Ensuring template argument type matches that of its variadic constructor
I would like to have a class like this:

```<code>template<typename T>
struct Foo {
    T* data_;

    template<typename... Ts, std::enable_if<std::is_same<T,Ts>...>...>
    explicit Foo(Ts...ts) : data_{ ts... } {}
};
</code>```

However; something with the syntax is wrong, and I'm not sure if you can set parameters into a pointer directly like this upon initialization.

What I would like for this to do is simply this:

```<code>Foo<int> f1{ 1, 3, 5, 7 }; // Or
// Foo<int> f1( 1, 3, 5 7 );
// f1.data_[0] = 1
// f1.data_[1] = 3
// f1.data_[2] = 5
// f1.data_[3] = 7
// f1.data_[4] = ... not our memory either garbage or undefined...

Foo<float> f2{ 3.5f, 7.2f, 9.8f }; // Or
// Foo<float> f2( 3.5f, 7.2f, 9.8f );
// f2.data_[0] = 3.5
// f2.data_[1] = 7.2
// f2.data_[2] = 9.8
// f2.data_[3] = ... not our memory
</code>```

I would also like to have the constructor check to make sure that each and every parameter that is passed into the constructor is of type <T>; simply put for each Ts it must be a T.

I might be overthinking this but for the life of me I can not get this or something similar to compile. I don't know if it's within enable_if, is_same or through the class's initializer list and trying to store the contents into a pointer. I don't know if I should use an array of T instead but the array's size won't be known until the arguments are passed into the constructor. I'm also trying to do this without using a basic container such as std::vector; it's more for self education than practical source code. I just want to see how this could be done with raw pointers.

Edit

I've changed my class to something like this:

```<code>template<typename T>
struct Foo {
    T* data_;

    template<typename... Ts, std::enable_if_t<std::is_same<T, Ts...>::value>* = nullptr>
    explicit Foo( const Ts&&... ts ) : data_{ std::move(ts)... } {}
 };
</code>```

And when trying to use it:

```<code> int a = 1, b = 3, c = 5, d = 7;
 Foo<int> f1( a, b, c, d );
 Foo<int> f2{ a, b, c, d };
</code>```

I'm a little closer with this iteration; but they both give different compiler errors.

The first being: C2661: "No overloaded function takes 4 arguments"

And the second:  C2440: "initializing, cannot convert from initializer list to Container, no constructor could take the source type, or constructor overload resolution was ambiguous."

答:
Why not simply use a std::initialize_list:?

```<code>#include <iostream>
#include <type_traits>
#include <vector>

template <class T>
struct Foo
{
  std::vector<T> data_;

  explicit Foo(std::initializer_list<T> data) : data_(data)
  {
    std::cout << "1";
  };

  template <typename... Ts,
            typename ENABLE=std::enable_if_t<(std::is_same_v<T,Ts> && ...)> >
  explicit Foo(Ts... ts) : Foo(std::initializer_list<T>{ts...})
  {
    std::cout << "2";
  }
};

int main()
{
  Foo<int> f1{1, 3, 5, 7}; // prints 1
  Foo<int> f2(1, 3, 5, 7); // prints 1 then 2

  return 0;
}
</code>```

If some Ts are different from T you will get a compile-time error.

With

```<code>gcc -std=c++17  prog.cpp
</code>```

you get:

```<code>  Foo<int> f1{1, 3, 5., 7};
</code>```

error: narrowing conversion of ‘5.0e+0’ from ‘double’ to ‘int’ inside
  { } [-Wnarrowing]    Foo f1{1, 3, 5., 7};
                            ^

and

```<code>Foo<int> f2(1, 3, 5., 7);
</code>```

you get

error: no matching function for call to ‘Foo::Foo(int, int,
  double, int)’    Foo f2(1, 3, 5., 7);
                            ^ note: candidate: ‘template Foo::Foo(Ts ...)’    explicit Foo(Ts... ts) :
  Foo(std::initializer_list{ts...})

...

Update: if you really want to use something like raw pointer, here is a complete working example:

```<code>#include <iostream>
#include <memory>
#include <type_traits>
#include <vector>

template <class T>
struct Foo
{
  size_t n_;
  std::unique_ptr<T[]> data_;

  explicit Foo(std::initializer_list<T> data) : n_(data.size()), data_(new T[n_])
  {
    std::copy(data.begin(), data.end(), data_.get());
    std::cout << "1";
  };

  template <typename... Ts, typename ENABLE = std::enable_if_t<(std::is_same_v<T, Ts> && ...)> >
  explicit Foo(Ts... ts) : Foo(std::initializer_list<T>{ts...})
  {
    std::cout << "2";
  }

  friend std::ostream& operator<<(std::ostream& out, const Foo<T>& toPrint)
  {
    for (size_t i = 0; i < toPrint.n_; i++)
      std::cout << "\n" << toPrint.data_[i];
    return out;
  }
};

int main()
{
  Foo<int> f1{1, 3, 5, 7};  // prints 1
  Foo<int> f2(1, 3, 5, 7);  // prints 1,2

  std::cout << f1;
  std::cout << f2;

  return 0;
}
</code>```

I let you replace unique_ptr by a raw pointer with all the extra work: delete[] etc...

Body:
I would like to have a class like this:

template<typename T>
struct Foo {
    T* data_;

    template<typename... Ts, std::enable_if<std::is_same<T,Ts>...>...>
    explicit Foo(Ts...ts) : data_{ ts... } {}
};

However; something with the syntax is wrong, and I'm not sure if you can set parameters into a pointer directly like this upon initialization.

What I would like for this to do is simply this:

Foo<int> f1{ 1, 3, 5, 7 }; // Or
// Foo<int> f1( 1, 3, 5 7 );
// f1.data_[0] = 1
// f1.data_[1] = 3
// f1.data_[2] = 5
// f1.data_[3] = 7
// f1.data_[4] = ... not our memory either garbage or undefined...

Foo<float> f2{ 3.5f, 7.2f, 9.8f }; // Or
// Foo<float> f2( 3.5f, 7.2f, 9.8f );
// f2.data_[0] = 3.5
// f2.data_[1] = 7.2
// f2.data_[2] = 9.8
// f2.data_[3] = ... not our memory

I would also like to have the constructor check to make sure that each and every parameter that is passed into the constructor is of type <T>; simply put for each Ts it must be a T.

I might be overthinking this but for the life of me I can not get this or something similar to compile. I don't know if it's within enable_if, is_same or through the class's initializer list and trying to store the contents into a pointer. I don't know if I should use an array of T instead but the array's size won't be known until the arguments are passed into the constructor. I'm also trying to do this without using a basic container such as std::vector; it's more for self education than practical source code. I just want to see how this could be done with raw pointers.

Edit

I've changed my class to something like this:

template<typename T>
struct Foo {
    T* data_;

    template<typename... Ts, std::enable_if_t<std::is_same<T, Ts...>::value>* = nullptr>
    explicit Foo( const Ts&&... ts ) : data_{ std::move(ts)... } {}
 };

And when trying to use it:

 int a = 1, b = 3, c = 5, d = 7;
 Foo<int> f1( a, b, c, d );
 Foo<int> f2{ a, b, c, d };

I'm a little closer with this iteration; but they both give different compiler errors.

The first being: C2661: "No overloaded function takes 4 arguments"

And the second:  C2440: "initializing, cannot convert from initializer list to Container, no constructor could take the source type, or constructor overload resolution was ambiguous."

Body:
Why not simply use a std::initialize_list:?

#include <iostream>
#include <type_traits>
#include <vector>

template <class T>
struct Foo
{
  std::vector<T> data_;

  explicit Foo(std::initializer_list<T> data) : data_(data)
  {
    std::cout << "1";
  };

  template <typename... Ts,
            typename ENABLE=std::enable_if_t<(std::is_same_v<T,Ts> && ...)> >
  explicit Foo(Ts... ts) : Foo(std::initializer_list<T>{ts...})
  {
    std::cout << "2";
  }
};

int main()
{
  Foo<int> f1{1, 3, 5, 7}; // prints 1
  Foo<int> f2(1, 3, 5, 7); // prints 1 then 2

  return 0;
}

If some Ts are different from T you will get a compile-time error.

With

gcc -std=c++17  prog.cpp

you get:

  Foo<int> f1{1, 3, 5., 7};

error: narrowing conversion of ‘5.0e+0’ from ‘double’ to ‘int’ inside
  { } [-Wnarrowing]    Foo f1{1, 3, 5., 7};
                            ^

and

Foo<int> f2(1, 3, 5., 7);

you get

error: no matching function for call to ‘Foo::Foo(int, int,
  double, int)’    Foo f2(1, 3, 5., 7);
                            ^ note: candidate: ‘template Foo::Foo(Ts ...)’    explicit Foo(Ts... ts) :
  Foo(std::initializer_list{ts...})

...

Update: if you really want to use something like raw pointer, here is a complete working example:

#include <iostream>
#include <memory>
#include <type_traits>
#include <vector>

template <class T>
struct Foo
{
  size_t n_;
  std::unique_ptr<T[]> data_;

  explicit Foo(std::initializer_list<T> data) : n_(data.size()), data_(new T[n_])
  {
    std::copy(data.begin(), data.end(), data_.get());
    std::cout << "1";
  };

  template <typename... Ts, typename ENABLE = std::enable_if_t<(std::is_same_v<T, Ts> && ...)> >
  explicit Foo(Ts... ts) : Foo(std::initializer_list<T>{ts...})
  {
    std::cout << "2";
  }

  friend std::ostream& operator<<(std::ostream& out, const Foo<T>& toPrint)
  {
    for (size_t i = 0; i < toPrint.n_; i++)
      std::cout << "\n" << toPrint.data_[i];
    return out;
  }
};

int main()
{
  Foo<int> f1{1, 3, 5, 7};  // prints 1
  Foo<int> f2(1, 3, 5, 7);  // prints 1,2

  std::cout << f1;
  std::cout << f2;

  return 0;
}

I let you replace unique_ptr by a raw pointer with all the extra work: delete[] etc...


问:
Why do we need Database HA Software like SQL Always On, Oracle Dataguard etc
I am learning the very basics of High Availability, SAN etc. and hence this question may sound stupid to experts, but would greatly help me if you answer it. Let’s say I am using an Enterprise SAN setup. I understand that any database e.g. SQL stores the data in a File which is stored on the SAN. Now if let’s say I enable array-based replication to another array may be in another Data center, then my database file will continuously be replicated in the second data center. Whenever the first data center is lost, I can use the replicated file in second data center to bring up the data and database. Then what exactly is the role played by various HA solutions like SQL Always On, Oracle Dataguard etc.? Thanks a ton in advance to people who rely.</p>

答:
When you build IT solutions, some requirements to consider are how resilient your
 IT solution needs to be based on the business process criticality.
there are two aspects of the solution that you need to consider.

High availability (HA): Which determines how resilient you application needs to be and it is usually expressed in 9s (nines) for example 99.99% availability is called four nines availability which is the equivalent of about one hour of unplanned downtime. HA in Oracle this is accomplished usually by using oracle real application cluster (RAC), which gives you availability even in the event when a node in the cluster goes down.
in SQL Server this would be SQL Server availability group.

Disaster recovery(DR): determines methods and technologies to provide business continuity in case of disaster in other words when your application High Availability (HA) features are no longer responding to requests.
in Oracle this would be a dataguard replicating your database from one cluster in one datacenter to a second cluster at the remote location.
SQL server also provides similiar features such as log shipping, alwas-on, and availability groups.
disaster recovery capabilities can be measured by two metrics:  Recovery time objective (RTO) which determines how long it would take for the backup site to be fully funtional in case of loss of the primary data center.  and the Recovery Time objective (RPO) which determines business data loss tolerance.


问:
Unable to find instrumentation target package firebase error
I'm writing an instrumentation test for my app in a separated empty project using UIAutomator and AndroidJUnit4 as runner. It runs well on my device. For testing it on Firebase, it needs the application APK which I provided, and the test APK which I took from C:\Users\user\MyApplication\app\build\outputs\apk\androidTest\debug and when I run the test it fails with this error:"Unable to find instrumentation target package:" am I missing something?

I created another manifest into the androidTest package and the target package is red with "cannot resolve symbol" and nothing changed.

I also changed the targetPackage to the name of the package of the application I'm trying to test, in case that was the problem, and nothing changed.

My androidTest manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.myapplication.test"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk android:minSdkVersion="18" android:targetSdkVersion="28"/>

    <instrumentation
        android:targetPackage="com.example.myapplication"
        android:name="androidx.test.runner.AndroidJUnitRunner"
        />

    <application
        tools:replace="label" android:label="SampleTest"/>

</manifest>
</code>```

答:
After a lot of research, I found out that gradle changes the target package automatically to the application package name which I'm writing test on.
So I had to move my tests to my application project and generate test apk from it, so it will have the same target package while setting the same signature for both.</p>

Body:
I'm writing an instrumentation test for my app in a separated empty project using UIAutomator and AndroidJUnit4 as runner. It runs well on my device. For testing it on Firebase, it needs the application APK which I provided, and the test APK which I took from C:\Users\user\MyApplication\app\build\outputs\apk\androidTest\debug and when I run the test it fails with this error:"Unable to find instrumentation target package:" am I missing something?

I created another manifest into the androidTest package and the target package is red with "cannot resolve symbol" and nothing changed.

I also changed the targetPackage to the name of the package of the application I'm trying to test, in case that was the problem, and nothing changed.

My androidTest manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.myapplication.test"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk android:minSdkVersion="18" android:targetSdkVersion="28"/>

    <instrumentation
        android:targetPackage="com.example.myapplication"
        android:name="androidx.test.runner.AndroidJUnitRunner"
        />

    <application
        tools:replace="label" android:label="SampleTest"/>

</manifest>


问:
How to write an action method in a controller to reference a partial view?
I have written an action method in the ReservationController class. To get this code to work I should move the GetCoreTab file to the Reservation folder. I do not want to do that since I give the path of the GetCoreTab file in the ReservationController class. I want to give the path, such that the code for the GetCoreTab method would work from the Reservation controller class.

Structure:

Code:

```<code>        public PartialViewResult GetCoreTab()
    {
        return PartialView("Tabs/GetCoreTab");
    }
</code>```

HTML:

```<code><a href="<%= Url.Action("GetCoreTab", "Reservation") %>" class="a">
                <b>
                    <div id="home" class="menu">
                    </div>
                </b>
            </a>
</code>```

Any ideas?

Thanks

答:
You could specify the path to the partial:</p>

```<code>public PartialViewResult GetCoreTab()
{
    return PartialView("~/Views/Shared/Tabs/GetCoreTab.ascx");
}
</code>```

Body:
I have written an action method in the ReservationController class. To get this code to work I should move the GetCoreTab file to the Reservation folder. I do not want to do that since I give the path of the GetCoreTab file in the ReservationController class. I want to give the path, such that the code for the GetCoreTab method would work from the Reservation controller class.

Structure:

Code:

        public PartialViewResult GetCoreTab()
    {
        return PartialView("Tabs/GetCoreTab");
    }

HTML:

<a href="<%= Url.Action("GetCoreTab", "Reservation") %>" class="a">

Any ideas?

Thanks

Body:
You could specify the path to the partial:

public PartialViewResult GetCoreTab()
{
    return PartialView("~/Views/Shared/Tabs/GetCoreTab.ascx");
}


问:
How to make an in purchase app subscription
I need to make an in purchase app subscription, such that a user can use the app for 1 month after than he/she should pay every month</p>

答: Check out this package. Also this Medium article if you need help.</p>


问:
Stream.of(int[]) returns Stream<int[]> whereas Stream.of(String[]) returns Stream<String> why?
Stream.of(int[]) returns Stream<int[]>, whereas Stream.of(String[])
returns Stream<String>.

Why are the two methods are behaving differently? Both should have either returned
Stream<int> and Stream<String> or Stream<int[]> and Stream<String[]>.

```<code>static int intArr[] = { 1, 2, 3, 4, 5 };
static String stringArr[] = { "3", "6", "8","14", "15" };

Stream<int[]> stream = Stream.of(intArr);
Stream<String> stream1 = Stream.of(stringArr);
</code>```

答:
There's no such thing Stream<int>, just like there's no List<int>. Generic type parameters cannot be substituted with primitive types.

For a stream of (primitive) int elements there's IntStream. IntStream.of(int... values) and Arrays.stream(int[] array) will both give you an IntStream, whose elements are int, where you pass an int[] to them.

Body:
Stream.of(int[]) returns Stream<int[]>, whereas Stream.of(String[])
returns Stream<String>.

Why are the two methods are behaving differently? Both should have either returned
Stream<int> and Stream<String> or Stream<int[]> and Stream<String[]>.

static int intArr[] = { 1, 2, 3, 4, 5 };
static String stringArr[] = { "3", "6", "8","14", "15" };

Stream<int[]> stream = Stream.of(intArr);
Stream<String> stream1 = Stream.of(stringArr);


问:
How to trace this? AttributeError: 'NoneType' object has no attribute 'is_relation' during makemigrations
I'm getting a confusing error for the second time since yesterday. Last time I just flattened my whole migrations, but I've never actually found what caused the problem.

So this comes up when I try to makemigrations for my python project. Where should I look for errors? I have feeling it's not actually about the migrations, but rather about errors in views.py or models.py even though I absolutely don't understand why this influences db migration.

Anyway, none of theses errors points to code that I have written. It's all in Django. So how to find the error that causes that?

```<code>(testenv1) C:\Users\user\eclipse_workspace\test1\test1>python manage.py makemigrations --trace
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python27\testenv1\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "C:\Python27\testenv1\lib\site-packages\django\core\management\__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python27\testenv1\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Python27\testenv1\lib\site-packages\django\core\management\base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "C:\Python27\testenv1\lib\site-packages\django\core\management\commands\makemigrations.py", line 150, in handle
    loader.project_state(),
  File "C:\Python27\testenv1\lib\site-packages\django\db\migrations\loader.py", line 323, in project_state
    return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps))
  File "C:\Python27\testenv1\lib\site-packages\django\db\migrations\graph.py", line 409, in make_state
    project_state = self.nodes[node].mutate_state(project_state, preserve=False)
  File "C:\Python27\testenv1\lib\site-packages\django\db\migrations\migration.py", line 92, in mutate_state
    operation.state_forwards(self.app_label, new_state)
  File "C:\Python27\testenv1\lib\site-packages\django\db\migrations\operations\fields.py", line 148, in state_forwards
    delay = not old_field.is_relation
AttributeError: 'NoneType' object has no attribute 'is_relation'

(testenv1) C:\Users\user\eclipse_workspace\test1\test1>
</code>```

Here is my models.py. It's currently WIP:

```<code># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models
#from wheel.metadata import unique
from datetime import datetime
from django.urls import reverse
# Create your models here.
from django.shortcuts import redirect

class Task(models.Model):
    name = models.CharField(max_length=255,blank=True)
    code = models.SlugField(max_length=255, unique=True)
    sender = models.ForeignKey("Sender", default=0)
    client = models.ForeignKey("Client", null=True,blank=True)
    datetime = models.DateTimeField(default=datetime.now)
    duration = models.IntegerField(default=0,blank=True)
    photo = models.ImageField(null=True, blank=True)
    route = models.TextField(blank=True)
    km = models.FloatField(default=0, blank=True)
    notes = models.TextField(blank=True)
    milage_receipt = models.ForeignKey("MilageReceipt", null=True, blank=True, on_delete=models.SET_NULL)

    def date(self):
        return self.datetime.date()
    def status(self):
        try:
            if self.receipt and self.milage_receipt:
                return "done"
            elif not self.receipt:
                return "new"
            elif not self.milage_receipt:
                return "ok"
        except Receipt.DoesNotExist:
            return "new"
        except MilageReceipt.DoesNotExist:
            return "processing"
        return str(self.receipt)

    def save(self, *args, **kwargs):
        if self.duration == None:
            self.duration = 0
        if self.km == None:
            self.km = 0
        super(Task, self).save(*args, **kwargs) # Call the "real" save() method.

    def get_absolute_url(self):
        return reverse('task_update', args=[str(self.id)])

    def __unicode__(self):
            return self.code

class Client(models.Model):
    name = models.CharField(max_length=255)
    name2 = models.CharField(max_length=255, blank=True)
    slug = models.SlugField(unique=True, max_length=255)
    email = models.EmailField()
    handle = models.CharField(max_length=255, blank=True)
    contact_name = models.CharField(max_length=255, blank=True)
    street = models.CharField(max_length=255)
    zip = models.IntegerField()
    city = models.CharField(max_length=255)
    street2 = models.CharField(max_length=255,blank=True)
    zip2 = models.CharField(max_length=255,blank=True)
    city2 = models.CharField(max_length=255,blank=True)
    default_vat = models.IntegerField(default=7)
    km_price = models.FloatField(default=0)
    active = models.BooleanField(default=False)
    def __unicode__(self):
            return self.slug

class Sender(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255)
    email = models.EmailField()
    street = models.CharField(max_length=255)
    zip = models.IntegerField()
    city = models.CharField(max_length=255)
    phone = models.CharField(max_length=255)
    website = models.URLField()
    tax_id = models.CharField(max_length=255)
    vat_id = models.CharField(max_length=255)
    bank = models.ForeignKey("BankAccount")

    def __unicode__(self):
        return self.slug

class BankAccount(models.Model):
    name = models.CharField(max_length=255)
    iban = models.CharField(max_length=255)
    bic = models.CharField(max_length=255)
    holder = models.CharField(max_length=255)

class ReceiptNumber(models.Model):
    id = models.AutoField(primary_key=True, unique=True)
    number = models.IntegerField(blank=True)

    def __unicode__(self):
        return str(self.id)

class MyQuerySet(models.query.QuerySet):
    def delete(self):
        print self
        raise

class SingleDeleteManager(models.Manager):
    def get_query_set(self):
        return MyQuerySet(self.model, using=self._db)

class Receipt(models.Model):
    number = models.OneToOneField("ReceiptNumber", blank=True, related_name="receipt", null=True)
    vat = models.IntegerField(blank=True)
    amount = models.DecimalField(max_digits=10, decimal_places=2, blank=True)
    body = models.TextField(blank=True)
    date = models.DateField(default=datetime.now, blank=True)
    task = models.OneToOneField("Task", related_name="receipt")
    objects = SingleDeleteManager()
    def total(self):
        a = float(self.amount) * (self.vat / 100.0) + float(self.amount)
        return "%.2f" % round(a,2)
    def vat_amount(self):
        a = float(self.amount) * (self.vat / 100.0)
        return "%.2f" % round(a,2)

    def save(self,*args, **kwargs):
        if self.date == None:
            self.date = datetime.now()
        if self.amount == None:
            self.amount = 0
        if self.vat == None:
            self.vat = self.task.client.default_vat
        super(Receipt, self).save(*args, **kwargs)
        #if not hasattr(self, "number") or self.number == None:
        #    new_number = ReceiptNumber.objects.create()
        #    new_number.number = ReceiptNumber.objects.filter(Q(receipt__task__sender_id=self.sender.id) | Q(milage_receipt__task__sender_id=self.sender.id)).latest('id').number+1
        #    new_number.save()
        #    self.number = new_number
        #    super(Receipt, self).save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        if hasattr(self,"number") and self.number.id:
            self.number.delete()
        return super(self.__class__, self).delete(*args, **kwargs)
    def get_absolute_url(self):
        return reverse('receipt_create_for_task', args=[str(self.task.id)])
    def __unicode__(self):
        try:
            return str(self.number) + ": " + self.task.code
        except Task.DoesNotExist:
            return "should be gone"

class ReceiptTemplate(models.Model):
    name = models.CharField(max_length=255)
    vat = models.IntegerField()
    amount = models.FloatField()
    body = models.TextField()

class MilageReceipt(models.Model):
    number = models.OneToOneField("ReceiptNumber", null=True)
    sender = models.ForeignKey("Sender")
    client = models.ForeignKey("Client")
</code>```

It's Version 1.11!

答:
I am not 100% sure how to solve this problem, but I will write what worked for me:

Find function state_forwards ( I am using ubuntu) at following path:

```<code>"/home/aseem/venv/bt_pip/lib/python3.6/site-packages/django/db/migrations/operations/fields.py"
</code>```

bt_pip is my pip virtual env name stored in folder venv.In above state_forwards func add following line:

```<code>print (app_label + " " + self.model_name_lower + " " + self.name + str(self.field))
</code>```

This will show which app is causing the problem.

Now install  django-reset-migrations. Then in terminal run :

```<code>python manage.py reset_migrations app_name
</code>```

It showed me some error, but after that when I tried python manage.py makemigrations it just worked.

Body:
I'm getting a confusing error for the second time since yesterday. Last time I just flattened my whole migrations, but I've never actually found what caused the problem.

So this comes up when I try to makemigrations for my python project. Where should I look for errors? I have feeling it's not actually about the migrations, but rather about errors in views.py or models.py even though I absolutely don't understand why this influences db migration.

Anyway, none of theses errors points to code that I have written. It's all in Django. So how to find the error that causes that?

(testenv1) C:\Users\user\eclipse_workspace\test1\test1>python manage.py makemigrations --trace
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python27\testenv1\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "C:\Python27\testenv1\lib\site-packages\django\core\management\__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python27\testenv1\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Python27\testenv1\lib\site-packages\django\core\management\base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "C:\Python27\testenv1\lib\site-packages\django\core\management\commands\makemigrations.py", line 150, in handle
    loader.project_state(),
  File "C:\Python27\testenv1\lib\site-packages\django\db\migrations\loader.py", line 323, in project_state
    return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps))
  File "C:\Python27\testenv1\lib\site-packages\django\db\migrations\graph.py", line 409, in make_state
    project_state = self.nodes[node].mutate_state(project_state, preserve=False)
  File "C:\Python27\testenv1\lib\site-packages\django\db\migrations\migration.py", line 92, in mutate_state
    operation.state_forwards(self.app_label, new_state)
  File "C:\Python27\testenv1\lib\site-packages\django\db\migrations\operations\fields.py", line 148, in state_forwards
    delay = not old_field.is_relation
AttributeError: 'NoneType' object has no attribute 'is_relation'

(testenv1) C:\Users\user\eclipse_workspace\test1\test1>

Here is my models.py. It's currently WIP:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models
#from wheel.metadata import unique
from datetime import datetime
from django.urls import reverse
# Create your models here.
from django.shortcuts import redirect

class Task(models.Model):
    name = models.CharField(max_length=255,blank=True)
    code = models.SlugField(max_length=255, unique=True)
    sender = models.ForeignKey("Sender", default=0)
    client = models.ForeignKey("Client", null=True,blank=True)
    datetime = models.DateTimeField(default=datetime.now)
    duration = models.IntegerField(default=0,blank=True)
    photo = models.ImageField(null=True, blank=True)
    route = models.TextField(blank=True)
    km = models.FloatField(default=0, blank=True)
    notes = models.TextField(blank=True)
    milage_receipt = models.ForeignKey("MilageReceipt", null=True, blank=True, on_delete=models.SET_NULL)

    def date(self):
        return self.datetime.date()
    def status(self):
        try:
            if self.receipt and self.milage_receipt:
                return "done"
            elif not self.receipt:
                return "new"
            elif not self.milage_receipt:
                return "ok"
        except Receipt.DoesNotExist:
            return "new"
        except MilageReceipt.DoesNotExist:
            return "processing"
        return str(self.receipt)

    def save(self, *args, **kwargs):
        if self.duration == None:
            self.duration = 0
        if self.km == None:
            self.km = 0
        super(Task, self).save(*args, **kwargs) # Call the "real" save() method.

    def get_absolute_url(self):
        return reverse('task_update', args=[str(self.id)])

    def __unicode__(self):
            return self.code

class Client(models.Model):
    name = models.CharField(max_length=255)
    name2 = models.CharField(max_length=255, blank=True)
    slug = models.SlugField(unique=True, max_length=255)
    email = models.EmailField()
    handle = models.CharField(max_length=255, blank=True)
    contact_name = models.CharField(max_length=255, blank=True)
    street = models.CharField(max_length=255)
    zip = models.IntegerField()
    city = models.CharField(max_length=255)
    street2 = models.CharField(max_length=255,blank=True)
    zip2 = models.CharField(max_length=255,blank=True)
    city2 = models.CharField(max_length=255,blank=True)
    default_vat = models.IntegerField(default=7)
    km_price = models.FloatField(default=0)
    active = models.BooleanField(default=False)
    def __unicode__(self):
            return self.slug

class Sender(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255)
    email = models.EmailField()
    street = models.CharField(max_length=255)
    zip = models.IntegerField()
    city = models.CharField(max_length=255)
    phone = models.CharField(max_length=255)
    website = models.URLField()
    tax_id = models.CharField(max_length=255)
    vat_id = models.CharField(max_length=255)
    bank = models.ForeignKey("BankAccount")

    def __unicode__(self):
        return self.slug

class BankAccount(models.Model):
    name = models.CharField(max_length=255)
    iban = models.CharField(max_length=255)
    bic = models.CharField(max_length=255)
    holder = models.CharField(max_length=255)

class ReceiptNumber(models.Model):
    id = models.AutoField(primary_key=True, unique=True)
    number = models.IntegerField(blank=True)

    def __unicode__(self):
        return str(self.id)

class MyQuerySet(models.query.QuerySet):
    def delete(self):
        print self
        raise

class SingleDeleteManager(models.Manager):
    def get_query_set(self):
        return MyQuerySet(self.model, using=self._db)

class Receipt(models.Model):
    number = models.OneToOneField("ReceiptNumber", blank=True, related_name="receipt", null=True)
    vat = models.IntegerField(blank=True)
    amount = models.DecimalField(max_digits=10, decimal_places=2, blank=True)
    body = models.TextField(blank=True)
    date = models.DateField(default=datetime.now, blank=True)
    task = models.OneToOneField("Task", related_name="receipt")
    objects = SingleDeleteManager()
    def total(self):
        a = float(self.amount) * (self.vat / 100.0) + float(self.amount)
        return "%.2f" % round(a,2)
    def vat_amount(self):
        a = float(self.amount) * (self.vat / 100.0)
        return "%.2f" % round(a,2)

    def save(self,*args, **kwargs):
        if self.date == None:
            self.date = datetime.now()
        if self.amount == None:
            self.amount = 0
        if self.vat == None:
            self.vat = self.task.client.default_vat
        super(Receipt, self).save(*args, **kwargs)
        #if not hasattr(self, "number") or self.number == None:
        #    new_number = ReceiptNumber.objects.create()
        #    new_number.number = ReceiptNumber.objects.filter(Q(receipt__task__sender_id=self.sender.id) | Q(milage_receipt__task__sender_id=self.sender.id)).latest('id').number+1
        #    new_number.save()
        #    self.number = new_number
        #    super(Receipt, self).save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        if hasattr(self,"number") and self.number.id:
            self.number.delete()
        return super(self.__class__, self).delete(*args, **kwargs)
    def get_absolute_url(self):
        return reverse('receipt_create_for_task', args=[str(self.task.id)])
    def __unicode__(self):
        try:
            return str(self.number) + ": " + self.task.code
        except Task.DoesNotExist:
            return "should be gone"

class ReceiptTemplate(models.Model):
    name = models.CharField(max_length=255)
    vat = models.IntegerField()
    amount = models.FloatField()
    body = models.TextField()

class MilageReceipt(models.Model):
    number = models.OneToOneField("ReceiptNumber", null=True)
    sender = models.ForeignKey("Sender")
    client = models.ForeignKey("Client")

It's Version 1.11!

Body:
I am not 100% sure how to solve this problem, but I will write what worked for me:

Find function state_forwards ( I am using ubuntu) at following path:

"/home/aseem/venv/bt_pip/lib/python3.6/site-packages/django/db/migrations/operations/fields.py"

bt_pip is my pip virtual env name stored in folder venv.In above state_forwards func add following line:

print (app_label + " " + self.model_name_lower + " " + self.name + str(self.field))

This will show which app is causing the problem.

Now install  django-reset-migrations. Then in terminal run :

python manage.py reset_migrations app_name

It showed me some error, but after that when I tried python manage.py makemigrations it just worked.


问:
How can I solve TypeError
Uncaught TypeError: Cannot read property 'addEventListener' of null
    at SpinBox.addEvent (spinbox3.js:28)
    at new SpinBox (spinbox3.js:9)
    at spinbox3.js:68

I'm personally studying development.
I tried to make a class and refer to the method.
But the problem continues to arise and cannot be solved.
I don't know the problem when the error is repeated as an undefined function or can't read property.

```<code>
class SpinBox{
  constructor(element, value, min, max) {
    this.init(element, value, min, max)
    this.addEvent()
  }

  init(element, val, min, max) {
    this.upButton = element.querySelector('.plus-button');
    this.dwButton = element.querySelector('.minus-button');
    this.textInput = element.querySelector('.text-box');

    this.setDefaultValue(val);
    this.setMinValue(min);
    this.setMaxValue(max);
  }

  addEvent() {
    this.mousedownUpButton = this.mousedownUpButton.bind(this);
    this.mousedownDwButton = this.mousedownDwButton.bind(this);
    this.mosueupButton = this.mosueupButton.bind(this);
    this.focuseoutTextBox = this.focuseoutTextBox.bind(this);

    this.upButton.addEventListener('mousedown', this.mousedownUpButton);
    this.dwButton.addEventListener('mousedown', this.mousedownDwButton);
    this.upButton.addEventListener('mouseup', this.mosueupButton);
    this.dwButton.addEventListener('mouseup', this.mosueupButton);
    this.textInput.addEventListener('blur', this.focuseoutTextBox);

  }

  mousedownUpButton(){}

  mousedownDwButton(){}

  mosueupButton(){}

  focuseoutTextBox(){}

...
}

let spinbox01 = new SpinBox(document.getElementById('spinbox-01'), 200, 100, 300);

</code>```

答:
Change "element" to "document" for all of the below:

```<code>this.upButton = element.querySelector('.plus-button');
    this.dwButton = element.querySelector('.minus-button');
    this.textInput = element.querySelector('.text-box');
</code>```

You are trying to search the document or window for the element.

Title: How can I solve TypeError

Body:
Uncaught TypeError: Cannot read property 'addEventListener' of null
    at SpinBox.addEvent (spinbox3.js:28)
    at new SpinBox (spinbox3.js:9)
    at spinbox3.js:68

I'm personally studying development.
I tried to make a class and refer to the method.
But the problem continues to arise and cannot be solved.
I don't know the problem when the error is repeated as an undefined function or can't read property.

class SpinBox{
  constructor(element, value, min, max) {
    this.init(element, value, min, max)
    this.addEvent()
  }

  init(element, val, min, max) {
    this.upButton = element.querySelector('.plus-button');
    this.dwButton = element.querySelector('.minus-button');
    this.textInput = element.querySelector('.text-box');

    this.setDefaultValue(val);
    this.setMinValue(min);
    this.setMaxValue(max);
  }

  addEvent() {
    this.mousedownUpButton = this.mousedownUpButton.bind(this);
    this.mousedownDwButton = this.mousedownDwButton.bind(this);
    this.mosueupButton = this.mosueupButton.bind(this);
    this.focuseoutTextBox = this.focuseoutTextBox.bind(this);

    this.upButton.addEventListener('mousedown', this.mousedownUpButton);
    this.dwButton.addEventListener('mousedown', this.mousedownDwButton);
    this.upButton.addEventListener('mouseup', this.mosueupButton);
    this.dwButton.addEventListener('mouseup', this.mosueupButton);
    this.textInput.addEventListener('blur', this.focuseoutTextBox);

  }

  mousedownUpButton(){}

  mousedownDwButton(){}

  mosueupButton(){}

  focuseoutTextBox(){}

...
}

let spinbox01 = new SpinBox(document.getElementById('spinbox-01'), 200, 100, 300);

Body:
Change "element" to "document" for all of the below:

this.upButton = element.querySelector('.plus-button');
    this.dwButton = element.querySelector('.minus-button');
    this.textInput = element.querySelector('.text-box');

You are trying to search the document or window for the element.


问:
Python: Urllib2 and OpenCV
I have a program that saves an image in a local directory and then reads the image from that directory.

But I dont want to save the image. I want to read it directly from the url.

Here's my code:

```<code>import cv2.cv as cv
import urllib2

url = "http://cache2.allpostersimages.com/p/LRG/18/1847/M5G8D00Z/posters/curious-cat.jpg"
filename = "my_test_image" + url[-4:]
print filename
opener = urllib2.build_opener()

page = opener.open(url)
img= page.read()

abc = open(filename, "wb")
abc.write(img)
abc.close()

img = cv.LoadImage(filename)

cv.ShowImage("Optical Flow", img)
cv.WaitKey(30)
</code>```

If i change it to:

```<code>img = cv.LoadImage(img)
</code>```

This will give me this error:

argument 1 must be string without null bytes, not str

What can I do?

答:
```<code>import numpy as np
import urllib
import cv2

def url_to_image(url):
    response = urllib.urlopen(url)
    image = np.asarray(bytearray(response.read()), dtype="uint8")
    cv2_img = cv2.imdecode(image, cv2.IMREAD_COLOR)
    return cv2_img
</code>```

Title: Python: Urllib2 and OpenCV

Body:
I have a program that saves an image in a local directory and then reads the image from that directory.

But I dont want to save the image. I want to read it directly from the url.

Here's my code:

import cv2.cv as cv
import urllib2

url = "http://cache2.allpostersimages.com/p/LRG/18/1847/M5G8D00Z/posters/curious-cat.jpg"
filename = "my_test_image" + url[-4:]
print filename
opener = urllib2.build_opener()

page = opener.open(url)
img= page.read()

abc = open(filename, "wb")
abc.write(img)
abc.close()

img = cv.LoadImage(filename)

cv.ShowImage("Optical Flow", img)
cv.WaitKey(30)

If i change it to:

img = cv.LoadImage(img)

This will give me this error:

argument 1 must be string without null bytes, not str

What can I do?


问:
How to place code from library to my project without import 'library_name'
I want to use function cv2.getGaborKernel in my project. However, thus the project will be evaluated on a server, where only library available is numpy, I must provide code for this method with my own .py files. Is there any way to put library's fuction code into my project's files not to call 'import opencv' later?

import numpy as np
```

答:
Either you put the code into the main script directly, or you use a second script and use

```<code>import secondscriptname
</code>```

There is nothing else you can do to get your own Code into the script. Atleast if you can not use any other Libraries.

You can look up the script of cv2, and try to copy the function there to put it in youre Code.

Body:
Either you put the code into the main script directly, or you use a second script and use

import secondscriptname

There is nothing else you can do to get your own Code into the script. Atleast if you can not use any other Libraries.

You can look up the script of cv2, and try to copy the function there to put it in youre Code.


问:
Unable to open/download files in HDFS using Hadoop Web UI
I have configured a standalone single node Hadoop environment in an external RHEL server. I am trying to view the files in HDFS using Hadoop Web UI:

http://<host ip>:50070/explorer.html#/user. I am able to browse through the directories and even delete files in HDFS. But i am unable to download or Open(Preview) and view any files in HDFS using web UI. I can see all the files and open them from command line in the server.

I am getting an error as displayed in below screenshot when i am trying to open a file:

Similar error is thrown while uploading files too. I am not using HUE due to some restrictions imposed on the server for the time period.

I am new to Hadoop. Can some one please help me out here?

答:
The main reason for failure of some operations via webui is permissions issue as the default user for it is drwho ex: Permission denied: user=dr.who, access=WRITE, inode="/":suyash:supergroup:drwxr-xr-x.

Workaround is to to use the console to do these operations if HUE is unavailable. Also could you try changing the browser/ clearing cache?


问:
Filtering an array with multiple filter arrays
I'm trying to filter an array of items based on multiple filter arrays. Each of the items has a selection of filters, and I need to show only the ones that match all of the selected filters.

```<code>const selectedFilters = {
    color: ["Red", "Blue"],
    type: ["Shirt"],
    size: ["M"]
};

const items = [
    {
        name: "Item 1",
        filters: {
            color: ["Red", "Blue", "Black"],
            type: ["Shirt"],
            size: ["M"]
        }
    },
    {
        name: "Item 2",
        filters: {
            color: ["Red"],
            type: ["Pants"],
            size: ["M"]
        }
    }
];
</code>```

This is how I've been trying to solve it. Filter through all of the items - for each filter category that is not empty, go through all the filter words and check that the item matches all of them.

```<code>const filterItems = (items, selectedFilters) => {
    const filterKeys = Object.keys(selectedFilters);

    return items.filter(item => {
        return filterKeys.every(key => {

            // Ignore empty filters
            if (!selectedFilters[key].length) {
                return true;
            }

            return selectedFilters[key].every(filterWord => {
                item.filters[key].includes(filterWord);
            });
        });
    });
};

filterItems(items, selectedFilters);
</code>```

Returns an empty array, should return an array with the "Item 1" object.

答:
```<code>getFilteredResult = (data)=>{
    let res = true;
    for(d in data) {
            if(d == 'filters') {
                let obj = data[d];
                for(key in obj) {
                    for(filterkey in selectedFilters) {
                        if(filterkey == key) {
                            selectedFilters[filterkey].forEach(data=>{
                                 if(!obj[key].includes(data)){
                                    res=false;
                                }
                            })
                        }
                    }
                }
            }
        }
    return res;
}
items.filter((data,index,arr)=> getFilteredResult(data))
</code>```

Body:
I'm trying to filter an array of items based on multiple filter arrays. Each of the items has a selection of filters, and I need to show only the ones that match all of the selected filters.

const selectedFilters = {
    color: ["Red", "Blue"],
    type: ["Shirt"],
    size: ["M"]
};

const items = [
    {
        name: "Item 1",
        filters: {
            color: ["Red", "Blue", "Black"],
            type: ["Shirt"],
            size: ["M"]
        }
    },
    {
        name: "Item 2",
        filters: {
            color: ["Red"],
            type: ["Pants"],
            size: ["M"]
        }
    }
];

This is how I've been trying to solve it. Filter through all of the items - for each filter category that is not empty, go through all the filter words and check that the item matches all of them.

const filterItems = (items, selectedFilters) => {
    const filterKeys = Object.keys(selectedFilters);

    return items.filter(item => {
        return filterKeys.every(key => {

            // Ignore empty filters
            if (!selectedFilters[key].length) {
                return true;
            }

            return selectedFilters[key].every(filterWord => {
                item.filters[key].includes(filterWord);
            });
        });
    });
};

filterItems(items, selectedFilters);

Returns an empty array, should return an array with the "Item 1" object.


问:
Whatsapp Business API production setup not working
I am trying to configure or setup the production environment of whatsapp business api as mentioned in the link https://developers.facebook.com/docs/whatsapp/installation/prod-single-instance
I have done everything mentioned in this my dockers are also running on port:9090 as can be seen in the image
still I can't access it. Whenever I try to call https://localhost:9090 the error with "This site can’t be reached" occurs. Whatsapp business api does not have good documentation or tutorials till now. So this site is the only last way for me.

答:
I think your setup is already complete. You just need to start with the registration process and start sending messages. The containers are up and running but calling https://localhost:9090 won't send you any response as this is not any specified API endpoint expected to be used.

Since you're using prod single instance, the documentation can be found here which seems pretty straight forward. https://developers.facebook.com/docs/whatsapp/installation/prod-single-instance

You seem to have completed till the 7 steps. The next step can be to perform a health check to make sure it is healthy. The API endpoint for that would be https://localhost:9090/v1/health https://developers.facebook.com/docs/whatsapp/api/health


问:
PUG - Pass variable to include js file
I have a function that passes a variable 'message' to my pug file. Which works fine within the pug file but I need it to work inside a JS file that I am including in the pug file.

I am including a js file in my pug file like so:

```<code>include test.js
</code>```

My JS file contains some code with #{message} variable which is passed into my pug file through a function.

```<code>document.getElementById("demo").innerHTML = "#{message}";
</code>```

Because I am including this JS file through include, it basically shows it as plain text without  tags. Which is exactly what I want. However, I need to insert some custom variables into the JS as its being displayed as a plain text file.

答:
```<code>script
  | var nextPageToken = '#{nextPageToken}'
  include dynamicLoad.js
</code>```

Supposing you have the token as string in your template variables, it will pass it to JS.

Please note than include in script will dump the JS code, it's not optimized, to load it in a parallel request and benefit the cache browser, use:

```<code>script
  | var nextPageToken = '#{nextPageToken}'
script(src="dynamicLoad.js ")
</code>```

Title: PUG - Pass variable to include js file

Body:
I have a function that passes a variable 'message' to my pug file. Which works fine within the pug file but I need it to work inside a JS file that I am including in the pug file.

I am including a js file in my pug file like so:

include test.js

My JS file contains some code with #{message} variable which is passed into my pug file through a function.

document.getElementById("demo").innerHTML = "#{message}";

Because I am including this JS file through include, it basically shows it as plain text without  tags. Which is exactly what I want. However, I need to insert some custom variables into the JS as its being displayed as a plain text file.

Body:
script
  | var nextPageToken = '#{nextPageToken}'
  include dynamicLoad.js

Supposing you have the token as string in your template variables, it will pass it to JS.

Please note than include in script will dump the JS code, it's not optimized, to load it in a parallel request and benefit the cache browser, use:

script
  | var nextPageToken = '#{nextPageToken}'
script(src="dynamicLoad.js ")