问:
I need to count both vowels and consonants but i am stumped on the consonants
I can't figure out how to have both vowels and consonants. The vowels part of the code works fine. I have no idea how to add the consonants.

```<code>import java.util.Scanner;

public class Main
{
   public static void main(String args[])
   {
      Scanner in = new Scanner(System.in);

      System.out.println("Enter some text: ");
      String str = in.nextLine();
      System.out.println(str);

System.out.print("your input has " + count_Vowels(str) + "vowels");
    }
 public static int count_Vowels(String str)
    {
        int vcount = 0;
        for (int i = 0; i < str.length(); i++)
        {
            char ch = str.charAt(i);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
            {
              vcount++;
            }
        }
        return vcount;
    }
public static int count_Consanants(String str)
    {
      int ccount = 0;
      for (int i = 0; i < str.length(); i++)
    {
      char ch = str.charAt(i);
      if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
      {
        vcount++;
      }
      else
      {
        consonants++;
      }
    }
  }
}
</code>```

I cannot seem to figure out the consonant part of the code

答:
Here is one way to do it.

First it converts the string to lower case to facilitate the search

Then it sets a string to the vowels.  You may want to add y if you're counting that

The main part loops thru the array, ensuring the character is a letter, and then tallying the counts. It is important to only check letters since spaces and punctuation marks could throw off the results.

```<code>Scanner in = new Scanner(System.in);

System.out.println("Enter some text: ");
String str = in.nextLine().toLowerCase();
String vowels = "aeiou";
System.out.println(str);

int vcount = 0;
int ccount = 0;

for (char c : str.toCharArray()) {
    if (Character.isLetter(c)) {
        if (vowels.indexOf(c) >= 0) {
            vcount++;
        } else {
            // must be a consonant
            ccount++;
        }
    }
}
System.out.printf("There were %d vowels and %d consonants%n",
        vcount, ccount);

</code>```

Body:
I can't figure out how to have both vowels and consonants. The vowels part of the code works fine. I have no idea how to add the consonants.

import java.util.Scanner;

public class Main
{
   public static void main(String args[])
   {
      Scanner in = new Scanner(System.in);

      System.out.println("Enter some text: ");
      String str = in.nextLine();
      System.out.println(str);

System.out.print("your input has " + count_Vowels(str) + "vowels");
    }
 public static int count_Vowels(String str)
    {
        int vcount = 0;
        for (int i = 0; i < str.length(); i++)
        {
            char ch = str.charAt(i);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
            {
              vcount++;
            }
        }
        return vcount;
    }
public static int count_Consanants(String str)
    {
      int ccount = 0;
      for (int i = 0; i < str.length(); i++)
    {
      char ch = str.charAt(i);
      if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
      {
        vcount++;
      }
      else
      {
        consonants++;
      }
    }
  }
}

I cannot seem to figure out the consonant part of the code

Body:
Here is one way to do it.

First it converts the string to lower case to facilitate the search

Then it sets a string to the vowels.  You may want to add y if you're counting that

The main part loops thru the array, ensuring the character is a letter, and then tallying the counts. It is important to only check letters since spaces and punctuation marks could throw off the results.

Scanner in = new Scanner(System.in);

System.out.println("Enter some text: ");
String str = in.nextLine().toLowerCase();
String vowels = "aeiou";
System.out.println(str);

int vcount = 0;
int ccount = 0;

for (char c : str.toCharArray()) {
    if (Character.isLetter(c)) {
        if (vowels.indexOf(c) >= 0) {
            vcount++;
        } else {
            // must be a consonant
            ccount++;
        }
    }
}
System.out.printf("There were %d vowels and %d consonants%n",
        vcount, ccount);


来源: stackexchange

问:
Apache not Starting : (98)Address already in use
Yesterday my WordPress sites went offline showing the error ERR_CONNECTION_REFUSED.  Today i discovered Apache is turned off in my VPS. Starting Apache, my Control panel returns:

```<code>Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details.
</code>```

```<code> httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Mon 2019-12-23 17:05:28 UTC; 7min ago
     Docs: man:httpd(8)
           man:apachectl(8)
  Process: 7728 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=1/FAILURE)
  Process: 7727 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE)
 Main PID: 7727 (code=exited, status=1/FAILURE)

Dec 23 17:05:27 site.com systemd[1]: Starting The Apache HTTP Server...
Dec 23 17:05:28 site.com httpd[7727]: (98)Address already in use: AH00072: make_sock: could not bind to address 0.0.0.0:443 (hidden ip)
Dec 23 17:05:28 site.com httpd[7727]: no listening sockets available, shutting down
Dec 23 17:05:28 site.com httpd[7727]: AH00015: Unable to open logs
Dec 23 17:05:28 site.com systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE
Dec 23 17:05:28 site.com kill[7728]: kill: cannot find process ""
Dec 23 17:05:28 site.com systemd[1]: httpd.service: control process exited, code=exited status=1
Dec 23 17:05:28 site.com systemd[1]: Failed to start The Apache HTTP Server.
Dec 23 17:05:28 site.com systemd[1]: Unit httpd.service entered failed state.
Dec 23 17:05:28 site.com systemd[1]: httpd.service failed.
</code>```

I tried to discover what services are running on port, to kill them, but ports 80 and 443 are not being used.

By specifically querying these ports, they return:

```<code>80/tcp closed http
443/tcp closed https
</code>```

Even with doors closed, error occurs when trying to start apache service. I searched Stack Overflow answers, tried all of  answer methods on these question, but nothing solved the problem.

I'm using updated Webmin on CentOS 7.7.1908

答:
I had exactly the same issue and I opened this file:

/etc/httpd/conf.d/ssl.conf

and saw these 2 lines:

```<code>Listen 443 https
Listen MY_IP:443
</code>```

I just commented the first line, like this:

```<code># Listen 443 https
Listen MY_IP:443
</code>```

and everything went to normal. I was able to start the httpd service.

systemctl start httpd.service

ContentLicense: CC BY-SA 4.0

Body:
Yesterday my WordPress sites went offline showing the error ERR_CONNECTION_REFUSED.  Today i discovered Apache is turned off in my VPS. Starting Apache, my Control panel returns:

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details.

 httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Mon 2019-12-23 17:05:28 UTC; 7min ago
     Docs: man:httpd(8)
           man:apachectl(8)
  Process: 7728 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=1/FAILURE)
  Process: 7727 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE)
 Main PID: 7727 (code=exited, status=1/FAILURE)

Dec 23 17:05:27 site.com systemd[1]: Starting The Apache HTTP Server...
Dec 23 17:05:28 site.com httpd[7727]: (98)Address already in use: AH00072: make_sock: could not bind to address 0.0.0.0:443 (hidden ip)
Dec 23 17:05:28 site.com httpd[7727]: no listening sockets available, shutting down
Dec 23 17:05:28 site.com httpd[7727]: AH00015: Unable to open logs
Dec 23 17:05:28 site.com systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE
Dec 23 17:05:28 site.com kill[7728]: kill: cannot find process ""
Dec 23 17:05:28 site.com systemd[1]: httpd.service: control process exited, code=exited status=1
Dec 23 17:05:28 site.com systemd[1]: Failed to start The Apache HTTP Server.
Dec 23 17:05:28 site.com systemd[1]: Unit httpd.service entered failed state.
Dec 23 17:05:28 site.com systemd[1]: httpd.service failed.

I tried to discover what services are running on port, to kill them, but ports 80 and 443 are not being used.

By specifically querying these ports, they return:

80/tcp closed http
443/tcp closed https

Even with doors closed, error occurs when trying to start apache service. I searched Stack Overflow answers, tried all of  answer methods on these question, but nothing solved the problem.

I'm using updated Webmin on CentOS 7.7.1908

Body:
I had exactly the same issue and I opened this file:

/etc/httpd/conf.d/ssl.conf

and saw these 2 lines:

Listen 443 https
Listen MY_IP:443

I just commented the first line, like this:

# Listen 443 https
Listen MY_IP:443

and everything went to normal. I was able to start the httpd service.

systemctl start httpd.service


问:
Issue with passing the data from one vc to another using protocol
I am trying to pass the data from UserProfileVc to ChallengeVC. I declared the protocol

```<code>protocol DidTapToChallengeDelegate {
    func didTapChallenge(challenge: Challenge)
}
</code>```

```<code>class UserProfileVC: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    var delegate: DidTapToChallengeDelegate?
}
</code>```

Inside the UserProfileVc, I want to pass the data when didSelect function happens.

```<code>override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        delegate?.didTapChallenge(challenge: challenges[indexPath.row])
        let challengeVC = ChallengeVC(collectionViewLayout: UICollectionViewFlowLayout())
        navigationController?.pushViewController(challengeVC, animated: true)
        }
</code>```

Here is the code from ChallengeVC

```<code>class ChallengeVC: UICollectionViewController, UICollectionViewDelegateFlowLayout, DidTapToChallengeDelegate  {
    func didTapChallenge(challenge: Challenge) {
        print("Hello, world!")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.backgroundColor = .white

        var vc = UserProfileVC()
        vc.delegate = self
    }
</code>```

But however, the print statement from above does not execute when I switch to ChallengeVC. Where is the problem?

答:
You don't Need delegates for forward communication </p>

```<code>class ChallengeVC: UICollectionViewController, UICollectionViewDelegateFlowLayout, DidTapToChallengeDelegate  {
   var challenge: Challenge!
}

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
       // delegate?.didTapChallenge(challenge: challenges[indexPath.row])
        let challengeVC = ChallengeVC(collectionViewLayout: UICollectionViewFlowLayout())
        challengeVC.challenge = challenges[indexPath.row]
        navigationController?.pushViewController(challengeVC, animated: true)
        }
</code>```

Body:
I am trying to pass the data from UserProfileVc to ChallengeVC. I declared the protocol

protocol DidTapToChallengeDelegate {
    func didTapChallenge(challenge: Challenge)
}

class UserProfileVC: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    var delegate: DidTapToChallengeDelegate?
}

Inside the UserProfileVc, I want to pass the data when didSelect function happens.

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        delegate?.didTapChallenge(challenge: challenges[indexPath.row])
        let challengeVC = ChallengeVC(collectionViewLayout: UICollectionViewFlowLayout())
        navigationController?.pushViewController(challengeVC, animated: true)
        }

Here is the code from ChallengeVC

class ChallengeVC: UICollectionViewController, UICollectionViewDelegateFlowLayout, DidTapToChallengeDelegate  {
    func didTapChallenge(challenge: Challenge) {
        print("Hello, world!")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.backgroundColor = .white

        var vc = UserProfileVC()
        vc.delegate = self
    }

But however, the print statement from above does not execute when I switch to ChallengeVC. Where is the problem?

Body:
You don't Need delegates for forward communication

class ChallengeVC: UICollectionViewController, UICollectionViewDelegateFlowLayout, DidTapToChallengeDelegate  {
   var challenge: Challenge!
}

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
       // delegate?.didTapChallenge(challenge: challenges[indexPath.row])
        let challengeVC = ChallengeVC(collectionViewLayout: UICollectionViewFlowLayout())
        challengeVC.challenge = challenges[indexPath.row]
        navigationController?.pushViewController(challengeVC, animated: true)
        }


问:
Firebase Angular9
I cant display particular element from db.

//component.html

{{scholarship.title}}

{{scholarship.description}}

//component.ts
import { Component, OnInit } from '@angular/core';
import {AngularFireDatabase} from 'angularfire2/database';

@Component({
    selector: 'app-scholarship',
    templateUrl: './scholarship.component.html',
    styleUrls: ['./scholarship.component.css']
})
export class ScholarshipComponent implements OnInit {
    scholarships: any[];
    constructor(db: AngularFireDatabase){
    db.list('scholarships')
        .valueChanges()
        .subscribe(scholarships => {
        this.scholarships = scholarships;
        console.log(this.scholarships); });
    }
    ngOnInit(): void {
    }
}
```

<p>that's work</p>

<p>but when I put, for example     </p>

<pre class="lang-html prettyprint-override"><code><div *ngFor="let scholarship of scholarships" >
    <h3>{{scholarship.3}}</h3>
</div>
</code>```

that doesn't work. I've tried also with "first_post", but also doesn't work

here is db

答:
I think you might need:

```<code><h3>{{scholarship[3].title}}</h3>
</code>```

Or

```<code><h3>{{scholarship["3"].title}}</h3>
</code>```

Title: Firebase Angular9

Body:
I cant display particular element from db.

//component.html

{{scholarship.title}}

{{scholarship.description}}

//component.ts
import { Component, OnInit } from '@angular/core';
import {AngularFireDatabase} from 'angularfire2/database';

@Component({
    selector: 'app-scholarship',
    templateUrl: './scholarship.component.html',
    styleUrls: ['./scholarship.component.css']
})
export class ScholarshipComponent implements OnInit {
    scholarships: any[];
    constructor(db: AngularFireDatabase){
    db.list('scholarships')
        .valueChanges()
        .subscribe(scholarships => {
        this.scholarships = scholarships;
        console.log(this.scholarships); });
    }
    ngOnInit(): void {
    }
}

that's work

but when I put, for example

{{scholarship.3}}

that doesn't work. I've tried also with "first_post", but also doesn't work

here is db

Body:
I think you might need:

<h3>{{scholarship[3].title}}</h3>

Or

<h3>{{scholarship["3"].title}}</h3>


问:
Redux State doesnt change in comonent
The reducers and actions are being called and working properly but my react components arent being changed after state is being changed.

This is my actions called cart.js:

```<code>import { ADD_TO_CART, REMOVE_FROM_CART } from './types';

export const addToCart = item => dispatch => {
    dispatch({
        type: ADD_TO_CART,
        payload: {
            item
        }
    });
}

export const removeFromCart = uid => dispatch => {
    dispatch({
        type: REMOVE_FROM_CART,
        payload: {
            uid
        }
    });
}
</code>```

This is my reducers file called cart.js:

```<code>import { ADD_TO_CART, REMOVE_FROM_CART } from '../actions/types';

const initialState = [];

//Cannot mutate array in reducer

export default function(state = initialState, action){
    const { type, payload } = action;

    switch(type){
        case ADD_TO_CART:
            for(var i = 0; i < state.length; i++){
                if(state[i].item.uid === payload.item.uid){
                    state[i].item.qty ++;
                    return [...state];
                }
            }
            return [...state, payload];
        case REMOVE_FROM_CART:
            for(var j = 0; j < state.length; j++){
                    if(state[j].item.uid === payload.uid){
                        state[j].item.qty = 1;
                    }
            }
            return state.filter(cartItem => cartItem.item.uid !== payload.uid);

        default:
            return state;
    }
}
</code>```

My component files:
Cart.js:

```<code>import React, { Fragment } from 'react';

import { connect } from 'react-redux';
import { removeFromCart } from '../actions/cart';

import CartItem from './CartItem';

const Cart = ({ cart }) => {

    return (
        <div>
           <h1>Cart</h1>
           {cart.map(cartItem => (
               <div style={{backgroundColor: 'blue'}}>
                   <CartItem cartItem={cartItem.item} key={cartItem.item.uid} />
               </div>
           ))}
        </div>
    )
}

const mapStateToProps = state => ({
    cart: state.cart
})

export default connect(
    mapStateToProps,
    { removeFromCart }
)(Cart);
</code>```

CartItem.js:

```<code>import React from 'react'

import { removeFromCart } from '../actions/cart';
import { connect } from 'react-redux';

const CartItem = ({ cartItem, removeFromCart }) => {

    const handleRemoveClick = () => {
        console.log('clicked', cartItem.uid);
        removeFromCart(cartItem.uid);
    }

    return (
        <div onClick={handleRemoveClick}>
            {cartItem.name}
            {cartItem.qty}
        </div>
    )
}

export default connect(
    null,
    { removeFromCart }
)(CartItem);
</code>```

Im trying to learn redux using react and any help is appreciated. Are for loops allowed in reducers? Im not sure why it isnt updating, the redux devtools shows everything is working. Specifically the part that isnt working is the item quantity is not being updated in component. When i remove an item it works.

答:
Don't mutate the redux state in reducers. Copy the state and mutate it.</p>

```<code>const newState = [...state];
//mutate newState;
return newState;
</code>```

Title: Redux State doesnt change in comonent

Body:
The reducers and actions are being called and working properly but my react components arent being changed after state is being changed.

This is my actions called cart.js:

import { ADD_TO_CART, REMOVE_FROM_CART } from './types';

export const addToCart = item => dispatch => {
    dispatch({
        type: ADD_TO_CART,
        payload: {
            item
        }
    });
}

export const removeFromCart = uid => dispatch => {
    dispatch({
        type: REMOVE_FROM_CART,
        payload: {
            uid
        }
    });
}

This is my reducers file called cart.js:

import { ADD_TO_CART, REMOVE_FROM_CART } from '../actions/types';

const initialState = [];

//Cannot mutate array in reducer

export default function(state = initialState, action){
    const { type, payload } = action;

    switch(type){
        case ADD_TO_CART:
            for(var i = 0; i < state.length; i++){
                if(state[i].item.uid === payload.item.uid){
                    state[i].item.qty ++;
                    return [...state];
                }
            }
            return [...state, payload];
        case REMOVE_FROM_CART:
            for(var j = 0; j < state.length; j++){
                    if(state[j].item.uid === payload.uid){
                        state[j].item.qty = 1;
                    }
            }
            return state.filter(cartItem => cartItem.item.uid !== payload.uid);

        default:
            return state;
    }
}

My component files:
Cart.js:

import React, { Fragment } from 'react';

import { connect } from 'react-redux';
import { removeFromCart } from '../actions/cart';

import CartItem from './CartItem';

const Cart = ({ cart }) => {

    return (

Cart

           {cart.map(cartItem => (

                   <CartItem cartItem={cartItem.item} key={cartItem.item.uid} />

           ))}

    )
}

const mapStateToProps = state => ({
    cart: state.cart
})

export default connect(
    mapStateToProps,
    { removeFromCart }
)(Cart);

CartItem.js:

import React from 'react'

import { removeFromCart } from '../actions/cart';
import { connect } from 'react-redux';

const CartItem = ({ cartItem, removeFromCart }) => {

    const handleRemoveClick = () => {
        console.log('clicked', cartItem.uid);
        removeFromCart(cartItem.uid);
    }

    return (

            {cartItem.name}
            {cartItem.qty}

    )
}

export default connect(
    null,
    { removeFromCart }
)(CartItem);

Im trying to learn redux using react and any help is appreciated. Are for loops allowed in reducers? Im not sure why it isnt updating, the redux devtools shows everything is working. Specifically the part that isnt working is the item quantity is not being updated in component. When i remove an item it works.

Body:
Don't mutate the redux state in reducers. Copy the state and mutate it.

const newState = [...state];
//mutate newState;
return newState;


问:
Error when picking out unique numbers in an array
This is a problem in my textbook for my Java class where the user enters 10 integers. The program is supposed to read all integers and only display the unique numbers (not duplicated) as the output. I am having trouble understanding why my output is not picking up the last unique value in the array (5). Can anyone give some insight to this issue? Any help would be appreciated. (Since we are in the early stages of the class and understanding the language, our assignment is to complete this using a nested loop.)

-The output is:
 Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
 The number of distinct numbers is 5
 The distinct numbers are: 1 2 3 6 4

-When it should be:
 Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
 The number of distinct numbers is 6
 The distinct numbers are: 1 2 3 6 4 5

```<code>
public class ch7e5{

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.print("Enter 10 numbers: ");

        int[] numberArray = new int[10];
        //create array for all numbers

        int[] distinctArray = new int[10];
        //create array for distinct numbers

        int distinct = 0;

        for (int i = 0; i < 10; i++)

            numberArray[i] = input.nextInt();

        distinctArray[0] = numberArray[0];
        //first value will be distinct

        for (int i = 1; i < numberArray.length; i++) {
        //loop to go through remaining values in numberArray

            boolean exists = false;
            //create boolean

            for (int j = 0; j < numberArray.length; j++) {
            //loop to check if value exists already in distinctArray

                if (numberArray[i] == distinctArray[j]) {

                    exists = true;

                    break;
                    //break out of inner loop

                }
            }

            if (exists == false) {
            //if value is unique then add it to the distinct array

                distinct++;
                distinctArray[distinct] = distinctArray[i];

            }
        }
        //}

        System.out.println("The number of distinct numbers is " + distinct);

        System.out.print("The distinct numbers are: ");

        for (int k = 0; k < distinct; k++)

            System.out.print(distinctArray[k] + " ");

    }

}```

```

答:
The error was here

```<code>distinct++;
distinctArray[distinct] = distinctArray[i];
</code>```

1, you should increment distinct after adding a number to distinctArray, and 2, you should have done distinctArray[distinct] = numberArray[i]. Right now, you're just putting what is possibly a 0 into distinctArray[distinct].

A shorter way to do it would be this

```<code>int[] distinctArray = Arrays.stream(numberArray).distinct().toArray();
System.out.println("The number of distinct numbers is " + distinctArray.length);
System.out.print("The distinct numbers are: ");
for (int d : distinctArray) System.out.print(d + " ");
</code>```

Output:

```<code>Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
The number of distinct numbers is 6
The distinct numbers are: 1 2 3 6 4 5
</code>```

Body:
This is a problem in my textbook for my Java class where the user enters 10 integers. The program is supposed to read all integers and only display the unique numbers (not duplicated) as the output. I am having trouble understanding why my output is not picking up the last unique value in the array (5). Can anyone give some insight to this issue? Any help would be appreciated. (Since we are in the early stages of the class and understanding the language, our assignment is to complete this using a nested loop.)

-The output is:
 Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
 The number of distinct numbers is 5
 The distinct numbers are: 1 2 3 6 4

-When it should be:
 Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
 The number of distinct numbers is 6
 The distinct numbers are: 1 2 3 6 4 5

public class ch7e5{

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.print("Enter 10 numbers: ");

        int[] numberArray = new int[10];
        //create array for all numbers

        int[] distinctArray = new int[10];
        //create array for distinct numbers

        int distinct = 0;

        for (int i = 0; i < 10; i++)

            numberArray[i] = input.nextInt();

        distinctArray[0] = numberArray[0];
        //first value will be distinct

        for (int i = 1; i < numberArray.length; i++) {
        //loop to go through remaining values in numberArray

            boolean exists = false;
            //create boolean

            for (int j = 0; j < numberArray.length; j++) {
            //loop to check if value exists already in distinctArray

                if (numberArray[i] == distinctArray[j]) {

                    exists = true;

                    break;
                    //break out of inner loop

                }
            }

            if (exists == false) {
            //if value is unique then add it to the distinct array

                distinct++;
                distinctArray[distinct] = distinctArray[i];

            }
        }
        //}

        System.out.println("The number of distinct numbers is " + distinct);

        System.out.print("The distinct numbers are: ");

        for (int k = 0; k < distinct; k++)

            System.out.print(distinctArray[k] + " ");

    }

}```

Body:
The error was here

distinct++;
distinctArray[distinct] = distinctArray[i];

1, you should increment distinct after adding a number to distinctArray, and 2, you should have done distinctArray[distinct] = numberArray[i]. Right now, you're just putting what is possibly a 0 into distinctArray[distinct].

A shorter way to do it would be this

int[] distinctArray = Arrays.stream(numberArray).distinct().toArray();
System.out.println("The number of distinct numbers is " + distinctArray.length);
System.out.print("The distinct numbers are: ");
for (int d : distinctArray) System.out.print(d + " ");

Output:

Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
The number of distinct numbers is 6
The distinct numbers are: 1 2 3 6 4 5


问:
In Memory Database
I'm using SqlServer to drive a WPF application, I'm currently using NHibernate and pre-read all the data so it's cached for performance reasons. That works for a single client app, but I was wondering if there's an in memory database that I could use so I can share the information across multiple apps on the same machine. Ideally this would sit below my NHibernate stack, so my code wouldn't have to change. Effectively I'm looking to move my DB from it's traditional format on the server to be an in memory DB on the client.

Note I only need select functionality.

答:
Velocity is an out of process object caching server designed by Microsoft to do pretty much what you want although it's only in CTP form at the moment.

I believe there are also wrappers for memcached, which can also be used to cache objects.

OwnerDisplayName: MrTelly

ContentLicense: CC BY-SA 2.5

Title: In Memory Database

LastEditorDisplayName: MrTelly


问:
How can I pass POST parameters in a URL?
Basically, I think that I can't, but I would be very happy to be proven wrong.

I am generating an HTML menu dynamically in PHP, adding one item for each current user, so that I get something like >, but I have a preference for POST over GET.

Is there a way to pass the information as a POST parameter, rather than GET from a clickable HREF link?

I am not allowed to use JavaScript.

It looks like href="https://stackoverflow.com/questions/6210900/how-to-pass-post-parameters-in-a-url#comment7231173_6210900">Rob is on to something with "You could use a button instead of an anchor and just style the button to look like a link. That way you could have your values in hidden fields inside the same form to be sent via POST"

答:
Parameters in the URL are GET parameters, a request body, if present, is POST data. So your basic premise is by definition not achievable.

You should choose whether to use POST or GET based on the action. Any destructive action, i.e. something that permanently changes the state of the server (deleting, adding, editing) should always be invoked by POST requests. Any pure "information retrieval" should be accessible via an unchanging URL (i.e. GET requests).

To make a POST request, you need to create a <form>. You could use Javascript to create a POST request instead, but I wouldn't recommend using Javascript for something so basic. If you want your submit button to look like a link, I'd suggest you create a normal form with a normal submit button, then use CSS to restyle the button and/or use Javascript to replace the  button with a link that submits the form using Javascript (depending on what reproduces the desired behavior better). That'd be a good example of progressive enhancement.

Body:
Basically, I think that I can't, but I would be very happy to be proven wrong.

I am generating an HTML menu dynamically in PHP, adding one item for each current user, so that I get something like <a href="process_user.php?user=<user>>, but I have a preference for POST over GET.

Is there a way to pass the information as a POST parameter, rather than GET from a clickable HREF link?

I am not allowed to use JavaScript.

It looks like Rob is on to something with "You could use a button instead of an anchor and just style the button to look like a link. That way you could have your values in hidden fields inside the same form to be sent via POST"

ContentLicense: CC BY-SA 3.0


问:
How to parse JSON object to CSV file using json2csv nodejs module
I'm currently learning how to parse a JSON object to a CSV file using the json2csv node module. Have never worked with JSON before, so this is all new to me.

My JSON object is formatted like this:

```<code>{
 "car":
      {
          "name":["Audi"],
          "price":["40000"],
          "color":["blue"]
      }
}
</code>```

And the output CSV file is formatted like this:

```<code>"car","name","price","color"
{"name":["Audi"],"price":["40000"],"color":["blue"]},,,
</code>```

How would I be able to get the CSV output to look like this instead?

```<code>name, price, color
"Audi",40000,"blue"
</code>```

I understand I can call fields directly for just regular JSON data, but I don't understand how it would work under a JSON object.

答:
I don't know about you guys, but i like small packages that just work as expected without a lot of extra configuration, try using jsonexport, works really well with objects, arrays, .. and its fast!

Install

```<code>npm i --save jsonexport
</code>```

Usage

```<code>const jsonexport = require('jsonexport');
const fs = require('fs');

jsonexport({
 "car":[
  {
   "name":"Audi",
   "price":"40000",
   "color":"blue"
  }
 ]
}, function(err, csv) {
  if (err) return console.error(err);
  fs.writeFile('cars.csv', csv, function(err) {
    if (err) return console.error(err);
    console.log('cars.csv saved');
  });
});
</code>```

https://github.com/kauegimenes/jsonexport

Body:
I'm currently learning how to parse a JSON object to a CSV file using the json2csv node module. Have never worked with JSON before, so this is all new to me.

My JSON object is formatted like this:

{
 "car":
      {
          "name":["Audi"],
          "price":["40000"],
          "color":["blue"]
      }
}

And the output CSV file is formatted like this:

"car","name","price","color"
{"name":["Audi"],"price":["40000"],"color":["blue"]},,,

How would I be able to get the CSV output to look like this instead?

name, price, color
"Audi",40000,"blue"

I understand I can call fields directly for just regular JSON data, but I don't understand how it would work under a JSON object.

Body:
I don't know about you guys, but i like small packages that just work as expected without a lot of extra configuration, try using jsonexport, works really well with objects, arrays, .. and its fast!

Install

npm i --save jsonexport

Usage

const jsonexport = require('jsonexport');
const fs = require('fs');

jsonexport({
 "car":[
  {
   "name":"Audi",
   "price":"40000",
   "color":"blue"
  }
 ]
}, function(err, csv) {
  if (err) return console.error(err);
  fs.writeFile('cars.csv', csv, function(err) {
    if (err) return console.error(err);
    console.log('cars.csv saved');
  });
});

https://github.com/kauegimenes/jsonexport


问:
No matching distribution found while using pip
I've been trying to install Pybossa and I've been trying to follow these steps from the documentation, and this link too (which they're the same).

when it comes to using this command pip install -r requirements.txt it keeps running some installations and then and error occurred :

ERROR: Could not find a version that satisfies the requirement jeepney==0.4 (from pybossa==3.1.2->-r requirements.t
xt (line 3)) (from versions: none)

ERROR: No matching distribution found for jeepney==0.4 (from pybossa==3.1.2->-r requirements.txt (line 3))

this is what's inside requirements.txt :

I don't know why this is happening as i'm following the documentation .. so i'd glade if anyone helped me.

I'm using :

Ubuntu server 18.04

python 2.7

virtualenv

PostgreSQL

答:
You are better off going for latest python 3. python 2 had its eol early this year. For new approaches it would be a dead end.

I am on 16.04, but hope you can do the turn likewise

make use of native venv option, don't use virtualenv any more

during the setup you likely will get compilation errors. Those are due to the fact not having a fully equipped build machine. It's very likely that you need to apt-get install more or less dev packages to your system. It depends how deep you had done gcc compilation in the past. For me it was:

sudo apt-get install python3-dev

sudo apt-get install libsasl2-dev libldap2-dev libssl-devm

whenever you encounter compilation errors like this:

```<code>Modules/constants.h:7:18: fatal error: lber.h: No such file or directory
compilation terminated.
</code>```

you need to find the appropriate dev lib and add it to the system with apt-get like mentioned above by easiest looking the error up in your favorite internet search engine

Steps for the setup of pybossa

python3 -m venv ./pb_env

. ./pb_env/bin/activate

pip install --upgrade pip

mkdir pb #shorthand for pybossa

cd pb

git clone --recursive https://github.com/Scifabric/pybossa

cd pybossa/

pip install -r requirements.txt

feel free to ask again if you still get stuck.

Body:
You are better off going for latest python 3. python 2 had its eol early this year. For new approaches it would be a dead end.

I am on 16.04, but hope you can do the turn likewise

make use of native venv option, don't use virtualenv any more

during the setup you likely will get compilation errors. Those are due to the fact not having a fully equipped build machine. It's very likely that you need to apt-get install more or less dev packages to your system. It depends how deep you had done gcc compilation in the past. For me it was:

sudo apt-get install python3-dev

sudo apt-get install libsasl2-dev libldap2-dev libssl-devm

whenever you encounter compilation errors like this:

Modules/constants.h:7:18: fatal error: lber.h: No such file or directory
compilation terminated.

you need to find the appropriate dev lib and add it to the system with apt-get like mentioned above by easiest looking the error up in your favorite internet search engine

Steps for the setup of pybossa

python3 -m venv ./pb_env

. ./pb_env/bin/activate

pip install --upgrade pip

mkdir pb #shorthand for pybossa

cd pb

git clone --recursive https://github.com/Scifabric/pybossa

cd pybossa/

pip install -r requirements.txt

feel free to ask again if you still get stuck.


问:
How to intersect two lists in Prolog
I do this

a([1,3,5,2,4]).

b([6,1,2]).

issn(L):-intersection(a,b,L).

why do I get false?

Thanks

Title: How to intersect two lists in Prolog

Body:
I found it!

a([1,3,5,2,4]).

b([6,1,2]).

issn(L):-
    a(D),
    b(G),
    intersection(D,G,L).


答: All versions of jeepney starting with 0.1 (released in 2017) requires Python >= 3.5.</p>

Title: No matching distribution found while using pip

Body:
I've been trying to install Pybossa and I've been trying to follow these steps from the documentation, and this link too (which they're the same).

when it comes to using this command pip install -r requirements.txt it keeps running some installations and then and error occurred :

ERROR: Could not find a version that satisfies the requirement jeepney==0.4 (from pybossa==3.1.2->-r requirements.t
xt (line 3)) (from versions: none)

ERROR: No matching distribution found for jeepney==0.4 (from pybossa==3.1.2->-r requirements.txt (line 3))

this is what's inside requirements.txt :

I don't know why this is happening as i'm following the documentation .. so i'd glade if anyone helped me.

I'm using :

Ubuntu server 18.04

python 2.7

virtualenv

PostgreSQL


问:
Drawing Bowling Pins (pyramid) with Recursion in Ada
I know this is pushing the good will of the community by presenting my least elaborate work expecting someone to come and save me but I simply have no choice with nothing to lose. I've gone through packets, files, types, flags and boxes the last few weeks but I haven't covered much of recursion. Especially not drawing with recursion. My exam is in roughly one week and I hope this is ample time to repeat and learn simple recursion tricks like that of drawing bowling pins or other patterns:

```<code>I I I I I
 I I I I
  I I I
   I I
    I
n = 5
</code>```

The problem I have with recursion is that I don't quite get it. How are you supposed to approach a problem like drawing pins like this using recursion?

The closest I've come is

```<code>I I I
I I
I
n = 3
</code>```

and that's using

THIS CODE NOW WORKS

```<code>with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure pyramidchaser is

   subtype X_Type is Integer range 0..30;
   X: X_Type;
   Indent : Integer := 0;

   procedure Numbergrabber (X : out Integer) is
   begin

      Put("Enter a number: ");
      Get(X);
      Skip_Line;
   end Numbergrabber;

   procedure PrintSpaces(I : in Integer) is
   begin
      if I in X_Type then
      Put(" ");
      else
     return;
      end if;

      PrintSpaces(I - 1);
   end Printspaces;

   procedure PrintPins(i, n: in Integer) is
   begin
      if i >= n then
     return;
      end if;

    Put('I');
    Put(' ');

    PrintPins(i + 1, n);
    end Printpins;

   function Pins (X, Indent: in Integer) return Integer is

      Printed : Integer;

   begin

      Printed:= 0;
      if X > 0 then
     PrintSpaces(Indent);
     PrintPins(0, X);
     New_Line;

     Printed := X + Pins(X - 1, Indent + 1);
      end if;
      return Printed;

   end Pins;

   Bowlingpins : Integer;

begin

   Numbergrabber(X);
   Bowlingpins:= Pins(X, Indent);

end pyramidchaser;

</code>```

but with that I throw in a sum I dont really need just to kick off the recursive part which I dont really know why I do except it seems to be needed to be there. I experimented with code from a completely different assignment, thats why it looks the way it does. I know mod 2 will grant me too many new lines but at least it was an approach to finding heights to the pyramid. I understand the real approach is something similar to N+1 as with each step of the growing pyramid a new line is needed, but I dont know how to implement it.

I don't expect anyone to present a complete code but I hope somebody can clue me in on how to think on the way towards finding a solution.

I can still pass the exam without knowing recursion as its typically 2 assignments where one is and one isnt recursion and you need to pass one or the other, but given that I have some time I thought Id give it a chance.

As always, immensely thankful for anyone fighting the good fight!

Seeing this post gathered some attention Id like to expand the pyramid to one a little more complex:

THE PYRAMID PROBLEM 2

hope someone looks at it. I didnt expect so many good answers, I thought why not throw all I have out there.

```<code>Level 1
|=|

Level 2
|===|
||=||
|===|

Level 3

|=====|
||===||
|||=|||
||===||
|=====|

it needs to be figured out recursively. so some way it has to build both upwards and downwards from the center.
</code>```

To clarify Im studying for an exam and surely so are many others whom would be thankful for code to sink their teeth in. Maybe theres an easy way to apply what Tama built in terms of bowling pin lines in pyramid walls?

答:
You’re going to print as many lines as there are pins. Each line has an indentation consisting of a number of spaces and a number of pins, each printed as "I " (OK,there's an extra space at the end of the line, but no one's going to see that).

Start off with no leading spaces and the number of pins you were asked to print.

The next line needs one more leading space and one fewer pin (unless, of course, that would mean printing no pins, in which case we're done).

Body:
I know this is pushing the good will of the community by presenting my least elaborate work expecting someone to come and save me but I simply have no choice with nothing to lose. I've gone through packets, files, types, flags and boxes the last few weeks but I haven't covered much of recursion. Especially not drawing with recursion. My exam is in roughly one week and I hope this is ample time to repeat and learn simple recursion tricks like that of drawing bowling pins or other patterns:

I I I I I
 I I I I
  I I I
   I I
    I
n = 5

The problem I have with recursion is that I don't quite get it. How are you supposed to approach a problem like drawing pins like this using recursion?

The closest I've come is

I I I
I I
I
n = 3

and that's using

THIS CODE NOW WORKS

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure pyramidchaser is

   subtype X_Type is Integer range 0..30;
   X: X_Type;
   Indent : Integer := 0;

   procedure Numbergrabber (X : out Integer) is
   begin

      Put("Enter a number: ");
      Get(X);
      Skip_Line;
   end Numbergrabber;

   procedure PrintSpaces(I : in Integer) is
   begin
      if I in X_Type then
      Put(" ");
      else
     return;
      end if;

      PrintSpaces(I - 1);
   end Printspaces;

   procedure PrintPins(i, n: in Integer) is
   begin
      if i >= n then
     return;
      end if;

    Put('I');
    Put(' ');

    PrintPins(i + 1, n);
    end Printpins;

   function Pins (X, Indent: in Integer) return Integer is

      Printed : Integer;

   begin

      Printed:= 0;
      if X > 0 then
     PrintSpaces(Indent);
     PrintPins(0, X);
     New_Line;

     Printed := X + Pins(X - 1, Indent + 1);
      end if;
      return Printed;

   end Pins;

   Bowlingpins : Integer;

begin

   Numbergrabber(X);
   Bowlingpins:= Pins(X, Indent);

end pyramidchaser;

but with that I throw in a sum I dont really need just to kick off the recursive part which I dont really know why I do except it seems to be needed to be there. I experimented with code from a completely different assignment, thats why it looks the way it does. I know mod 2 will grant me too many new lines but at least it was an approach to finding heights to the pyramid. I understand the real approach is something similar to N+1 as with each step of the growing pyramid a new line is needed, but I dont know how to implement it.

I don't expect anyone to present a complete code but I hope somebody can clue me in on how to think on the way towards finding a solution.

I can still pass the exam without knowing recursion as its typically 2 assignments where one is and one isnt recursion and you need to pass one or the other, but given that I have some time I thought Id give it a chance.

As always, immensely thankful for anyone fighting the good fight!

Seeing this post gathered some attention Id like to expand the pyramid to one a little more complex:

THE PYRAMID PROBLEM 2

hope someone looks at it. I didnt expect so many good answers, I thought why not throw all I have out there.

Level 1
|=|

Level 2
|===|
||=||
|===|

Level 3

|=====|
||===||
|||=|||
||===||
|=====|

it needs to be figured out recursively. so some way it has to build both upwards and downwards from the center.

To clarify Im studying for an exam and surely so are many others whom would be thankful for code to sink their teeth in. Maybe theres an easy way to apply what Tama built in terms of bowling pin lines in pyramid walls?


问:
Assign constant char to character array inside structure in VC++
I want a linked list structure in my VC++ application

My structure is:-

```<code>struct xml_data {
    int id;
    char file_name[50];
    char url_source[50];
    struct xml_Data *next;
}xml_data1;
</code>```

If I declare a variable like

```<code>struct xml_data *var;
const char* abc;
</code>```

I want to assign a value from a const char* variable to the structure members.

I tried using

```<code>var->file_name=abc;
</code>```

but it is giving an error that it cannot convert const char* to char[50]...

this may be a small problem but I am very new in using data structures....

答:
After you've used new to allocate memory for the struct.

```<code>var = new xml_data;
</code>```

Use strcpy to copy one to the other.

```<code>strcpy(var->file_name,abc);
</code>```

include <cstring> and make sure there's enough room in the destination.

Body:
I want a linked list structure in my VC++ application

My structure is:-

struct xml_data {
    int id;
    char file_name[50];
    char url_source[50];
    struct xml_Data *next;
}xml_data1;

If I declare a variable like

struct xml_data *var;
const char* abc;

I want to assign a value from a const char* variable to the structure members.

I tried using

var->file_name=abc;

but it is giving an error that it cannot convert const char* to char[50]...

this may be a small problem but I am very new in using data structures....

Body:
After you've used new to allocate memory for the struct.

var = new xml_data;

Use strcpy to copy one to the other.

strcpy(var->file_name,abc);

include <cstring> and make sure there's enough room in the destination.


问:
async/await in react with redux
Hi guys I am quite new to programming and trying to understand one thing with redux and await/async functions. Basically I have this function:

```<code> //nh functions
    const onSubmit = async data => {
        try{
            await dispatch(Login(data))
            if (auth.logged != false){
                addToast(content, { appearance: 'success', autoDismiss: true, })
                history.push('/')
            } else if (auth.logged == false){
                addToast(content2, { appearance: 'error', autoDismiss: true, })
            }
        }finally{
            console.log('Tada')
        }
    }

</code>```

which should first authenticate an account and then push a notification. However, the await is not working at all, and it proceeds immediately to the if statement. Any tips?

答:
Wht dave said is true. If you want to do something like that, you should dispatch your data and get the result in a props. Then you can use a useEffect to listen to this prop and do your things. Somethink like:

```<code>useEffect(() => {
  // Do your things after your dispatch here
}, [yourProp]);
</code>```

Title: async/await in react with redux

Body:
Hi guys I am quite new to programming and trying to understand one thing with redux and await/async functions. Basically I have this function:

 //nh functions
    const onSubmit = async data => {
        try{
            await dispatch(Login(data))
            if (auth.logged != false){
                addToast(content, { appearance: 'success', autoDismiss: true, })
                history.push('/')
            } else if (auth.logged == false){
                addToast(content2, { appearance: 'error', autoDismiss: true, })
            }
        }finally{
            console.log('Tada')
        }
    }

which should first authenticate an account and then push a notification. However, the await is not working at all, and it proceeds immediately to the if statement. Any tips?

Body:
Wht dave said is true. If you want to do something like that, you should dispatch your data and get the result in a props. Then you can use a useEffect to listen to this prop and do your things. Somethink like:

useEffect(() => {
  // Do your things after your dispatch here
}, [yourProp]);


问:
Positioning a widget with place inside the parent widget positioned by grid
```<code>root = tkinter.Tk()

base_label = tkinter.Label(root)
base_label.grid(row=0, column=0)
label2 = tkinter.Label(base_label, text='RESULT')
label2.place(height=100, width=100)

print(root['height'])
root.mainloop()
</code>```

Question 1: How is the height and width of label2(positioned by place) affected by it being in a widget positioned by grid? label2 does not properly display the text 'RESULT', but this is not the case if the base_label is positioned by place.

Question 2: Why does root['height'] return 0?

答:
Question 1: How is the height and width of label2(positioned by place) affected by it being in a widget positioned by grid?

It's not affected by the use of grid at all, other than the fact that if the inner label is wider than its parent, part of it won't be visible. When you use place, it doesn't matter at all how the parent is managed. With place you are in complete control over the position and size of a widget unless you use relative placement and/or relative sizing. However, child widgets will be clipped by their parent.

In other words, the label added with place will be the size you requested. You've requested it be 100 characters wide and 100 characters tall so that is what it is. The visible part of the label will be constrained by the parent label.

Why does root['height'] return 0?

It is because that is the default value of the height attribute. Getting the attribute doesn't get the actual height, only the value of the attribute. However, even if you tried to get the actual height it would only be 1 because tkinter hasn't had a chance to render the window. Until a window is rendered its size is indeterminate.

Body:
root = tkinter.Tk()

base_label = tkinter.Label(root)
base_label.grid(row=0, column=0)
label2 = tkinter.Label(base_label, text='RESULT')
label2.place(height=100, width=100)

print(root['height'])
root.mainloop()

Question 1: How is the height and width of label2(positioned by place) affected by it being in a widget positioned by grid? label2 does not properly display the text 'RESULT', but this is not the case if the base_label is positioned by place.

Question 2: Why does root['height'] return 0?


问:
Stackdriver Custom Alerting
I am trying to get alert via stack driver using logs from my server. My log entry will have an attribute health_status whose value can be [true/false], I wanted to create an alerting policy which triggers an alert if the last log entry's health_status is false. I succeeded that part(By creating a metric with the label - health_status, defining an alerting policy, if health_status = false), but the complexity is, the log entry will be updated every 15 minutes, I don't want to get notified if an alert is already triggered in the past 15 minutes. (i.e) if in the first 15 minutes, health_status = true, in the next 15 minutes, health_status = false, I need an alert. But, if in the first 15 minutes, health_status = false, in the next 15 minutes, health_status = false, I don't need an alert. Is it possible to implement such an alerting policy in stack driver?
Thanks in advance!</p>

答:
I believe you can leverage the alerting policy to add multiple conditions.

You can set your first condition to trigger if the value = true for the first 15 minutes

For your second condition, you can add an opposite value that contradicts the first statement.

You can then configure the policy trigger, forcing the alert to be triggered only if both policies are met. Meaning that if in the first 15 minutes value is true and the second 15 minutes value is false, then all conditions are met and this will trigger the alert.

Title: Stackdriver Custom Alerting


问:
OMNeT++ inet::b to Int
I'm trying to make an application that gets the size of an Ethernet chunk and stores it in a vector of ints. To get the chunk length I'm using the function provided by inet: chunk->getChunkLength(). Is there a way to convert the type inet::b to int?

答:
To obtain the size of a chunk in bits use this code:

```<code>int bitSize = b(chunk->getChunkLength()).get();
</code>```

If you want to obtain the size in bytes use this way:

```<code>int byteSize = B(chunk->getChunkLength()).get();
</code>```

Title: OMNeT++ inet::b to Int

Body:
To obtain the size of a chunk in bits use this code:

int bitSize = b(chunk->getChunkLength()).get();

If you want to obtain the size in bytes use this way:

int byteSize = B(chunk->getChunkLength()).get();


问:
NaCL sealed box on different platforms
There is tweetnacl-sealedbox-js for node.js

For example we can encrypt some data

```<code>const key = crypto.pseudoRandomBytes(32);
const publicKey = 'ed9f2af89336b2ff5960634fafb401ca36644cad61cb6a1daafdda0c74ef4636';
const encryptedKey = seal(key, Buffer.from(publicKey, 'hex'));
</code>```

But is there similar library for C# ? I'm trying to use libsodium-net but am not completely sure that this is correct

For example

```<code>byte[] randKey = new byte[32];
Random.NextBytes(randKey);
string publicKey = "ed9f2af89336b2ff5960634fafb401ca36644cad61cb6a1daafdda0c74ef4636";
byte[] encryptedKey = SealedPublicKeyBox.Create(randKey, HexToByte(publicKey));
public static byte [] HexToByte(string hexStr)
        {
            byte[] bArray = new byte[hexStr.Length / 2];
            for (int i = 0; i < (hexStr.Length / 2); i++)
            {
                byte firstNibble = Byte.Parse(hexStr.Substring((2 * i), 1),
                                   System.Globalization.NumberStyles.HexNumber); // [x,y)
                byte secondNibble = Byte.Parse(hexStr.Substring((2 * i) + 1, 1),
                                    System.Globalization.NumberStyles.HexNumber);
                int finalByte = (secondNibble) | (firstNibble << 4);
                bArray[i] = (byte)finalByte;
            }
            return bArray;
        }
</code>```

Does anybody know can the owner of private key decrypt both messages? or c# code is not the same action?

答:
SO I make some tests:
run var keyPair = tweetnacl.box.keyPair() at node.js and convert to base64 strings public key and secret key.

```<code>var pubKey = Buffer.from('Uv4bICdcUlIO+Z9YsLLg9EGaLPy/M7oTBVZJn2B7XhU=', 'base64');
var secKey = Buffer.from('fEAUUQ+axuD3NkOr+a59ZtsVurZPTa4Ee8ULoNr3WS0=', 'base64');
</code>```

try to encrypt message via c# and libsodium-net like that:

```<code>string mes = "i want to believe";
string pKey = "Uv4bICdcUlIO+Z9YsLLg9EGaLPy/M7oTBVZJn2B7XhU=";

byte [] enc = Sodium.SealedPublicKeyBox.Create(mes, Convert.FromBase64String(pKey));

return Convert.ToBase64String(enc);
</code>```

and try to decrypt message via node.js

```<code>var msg = Buffer.from('uW+5ecQhzKKx++uRYcbCu2nUVNIqToWTSjVB7UmdDCeJn9Buf3UWFu5kRfIGIxMJYdVeTFijdvJhlHR0VBd5HnE=', 'base64');
var result = sealedbox.open(msg, pubKey, secKey);
console.log(Buffer.from(result).toString());
</code>```

and got my message in log.

so I found out that these libraries are mutually compatible.

Title: NaCL sealed box on different platforms

Body:
There is tweetnacl-sealedbox-js for node.js

For example we can encrypt some data

const key = crypto.pseudoRandomBytes(32);
const publicKey = 'ed9f2af89336b2ff5960634fafb401ca36644cad61cb6a1daafdda0c74ef4636';
const encryptedKey = seal(key, Buffer.from(publicKey, 'hex'));

But is there similar library for C# ? I'm trying to use libsodium-net but am not completely sure that this is correct

For example

byte[] randKey = new byte[32];
Random.NextBytes(randKey);
string publicKey = "ed9f2af89336b2ff5960634fafb401ca36644cad61cb6a1daafdda0c74ef4636";
byte[] encryptedKey = SealedPublicKeyBox.Create(randKey, HexToByte(publicKey));
public static byte [] HexToByte(string hexStr)
        {
            byte[] bArray = new byte[hexStr.Length / 2];
            for (int i = 0; i < (hexStr.Length / 2); i++)
            {
                byte firstNibble = Byte.Parse(hexStr.Substring((2 * i), 1),
                                   System.Globalization.NumberStyles.HexNumber); // [x,y)
                byte secondNibble = Byte.Parse(hexStr.Substring((2 * i) + 1, 1),
                                    System.Globalization.NumberStyles.HexNumber);
                int finalByte = (secondNibble) | (firstNibble << 4);
                bArray[i] = (byte)finalByte;
            }
            return bArray;
        }

Does anybody know can the owner of private key decrypt both messages? or c# code is not the same action?

Body:
SO I make some tests:
run var keyPair = tweetnacl.box.keyPair() at node.js and convert to base64 strings public key and secret key.

var pubKey = Buffer.from('Uv4bICdcUlIO+Z9YsLLg9EGaLPy/M7oTBVZJn2B7XhU=', 'base64');
var secKey = Buffer.from('fEAUUQ+axuD3NkOr+a59ZtsVurZPTa4Ee8ULoNr3WS0=', 'base64');

try to encrypt message via c# and libsodium-net like that:

string mes = "i want to believe";
string pKey = "Uv4bICdcUlIO+Z9YsLLg9EGaLPy/M7oTBVZJn2B7XhU=";

byte [] enc = Sodium.SealedPublicKeyBox.Create(mes, Convert.FromBase64String(pKey));

return Convert.ToBase64String(enc);

and try to decrypt message via node.js

var msg = Buffer.from('uW+5ecQhzKKx++uRYcbCu2nUVNIqToWTSjVB7UmdDCeJn9Buf3UWFu5kRfIGIxMJYdVeTFijdvJhlHR0VBd5HnE=', 'base64');
var result = sealedbox.open(msg, pubKey, secKey);
console.log(Buffer.from(result).toString());

and got my message in log.

so I found out that these libraries are mutually compatible.


问:
Spark dataframe to arrow
I have been using Apache Arrow with Spark for a while in Python and have been easily able to convert between dataframes and Arrow objects by using Pandas as an intermediary.

Recently, however, I’ve moved from Python to Scala for interacting with Spark and using Arrow isn’t as intuitive in Scala (Java) as it is in Python. My basic need is to convert a Spark dataframe (or RDD since they’re easily convertible) to an Arrow object as quickly as possible. My initial thought was to convert to Parquet first and go from Parquet to Arrow since I remembered that pyarrow could read from Parquet. However, and please correct me if I’m wrong, after looking at the Arrow Java docs for a while I couldn’t find a Parquet to Arrow function. Does this function not exist in the Java version? Is there another way to get a Spark dataframe to an Arrow object? Perhaps converting the dataframe's columns to arrays then converting to arrow objects?

Any help would be much appreciated. Thank you

EDIT: Found the following link that converts a parquet schema to an Arrow schema. But it doesn't seem to return an Arrow object from a parquet file like I need:
https://github.com/apache/parquet-mr/blob/70f28810a5547219e18ffc3465f519c454fee6e5/parquet-arrow/src/main/java/org/apache/parquet/arrow/schema/SchemaConverter.java

答: Now there's an answer, Arrow can be used to convert Spark DataFrames to Pandas DataFrames or when calling Pandas UDFs. Please see the SQL PySpark Pandas with Arrow documentation page.</p>

Title: Spark dataframe to arrow


问:
Can't establish a connection to the server at ws://localhost:8000/socket/server/startDaemon.php. var socket = new WebSocket(host);
I am using javascript to connect websocket:

```<code><script>
    var socket;
    var host = "ws://localhost:8000/socket/server/startDaemon.php";
    var socket = new WebSocket(host);
</script>
</code>```

I got the error:

Can't establish a connection to the server at

```<code>var host = "ws://localhost:8000/socket/server/startDaemon.php";
var socket = new WebSocket(host);
</code>```

How can I solve this issue?

NOTE : I enabled websocket in mozilla to support web socket application.
       and when i run in chrome i got error:

```<code>   can't establish a connection to the server at ws://localhost:8000/socket/server/startDaemon.php. var socket = new WebSocket(host);
</code>```

答:
Are you trying to run the client in Firefox?  According to the documentation:

As of Feb/10 the only browsers that
  support websockets are Google Chrome
  and Webkit Nightlies. Get it from here
  http://www.google.com/chrome

Try running it in Chrome and see if that works for you.

Body:
I am using javascript to connect websocket:

I got the error:

Can't establish a connection to the server at

var host = "ws://localhost:8000/socket/server/startDaemon.php";
var socket = new WebSocket(host);

How can I solve this issue?

NOTE : I enabled websocket in mozilla to support web socket application.
       and when i run in chrome i got error:

   can't establish a connection to the server at ws://localhost:8000/socket/server/startDaemon.php. var socket = new WebSocket(host);


问:
add limit for list in for loop django template
I want to print only 10 elements from list in Django template

here is my code

```<code><ul>
    <h3>Positive Tweets :</h3>
    {% for tweet in positiveTweet %}
      <li>{{ tweet.0 }}</li>
    {% endfor %}
</ul>
</code>```

How can I print first 10 elements if positiveTweet list having length of 100 something.

答:
Check for the loop counter like this:</p>

```<code>          {% for tweet in positiveTweet %}

               {% if forloop.counter < 11 %}

                <!-- Do your something here -->

               {% endif %}

          {% endfor %}
</code>```

Body:
I want to print only 10 elements from list in Django template

here is my code

Positive Tweets :

    {% for tweet in positiveTweet %}

{{ tweet.0 }}

    {% endfor %}

How can I print first 10 elements if positiveTweet list having length of 100 something.

Body:
Check for the loop counter like this:

          {% for tweet in positiveTweet %}

               {% if forloop.counter < 11 %}

                <!-- Do your something here -->

               {% endif %}

          {% endfor %}


问:
Can't access property from object in Javascript
EDIT: Re-structured question, cleaer, and cleaner:

I have a data object from Sequelize that is sent by node-express:

```<code>{
    "page": 0,
    "limit": 10,
    "total": 4,
    "data": [
        {
            "id": 1,
            "title": "movies",
            "isActive": true,
            "createdAt": "2020-05-30T19:26:04.000Z",
            "updatedAt": "2020-05-30T19:26:04.000Z",
            "questions": [
                {
                    "questionsCount": 4
                }
            ]
        }
    ]
}
</code>```

The BIG question is, how do I get the value of questionsCount?
The PROBLEM is, I just can't extract it, these two methods give me undefined result:

category.questions[0].questionsCount

category.questions[0]['questionsCount']

I WAS ABLE to get it using toJSON() (From Sequelize lib I think), like so:

```<code>category.questions[0].toJSON().questionsCount
</code>```

But I'd like to know the answer to the question, or at least a clear explanation of why do I have to use toJSON() just to get the questionsCount?

More context:

I have this GET in my controller:

```<code>exports.getCategories = (req, res) => {
  const page = myUtil.parser.tryParseInt(req.query.page, 0)
  const limit = myUtil.parser.tryParseInt(req.query.limit, 10)

  db.Category.findAndCountAll({
    where: {},
    include: [
      {
        model: db.Question,
        as: "questions",
        attributes: [[db.Sequelize.fn('COUNT', 'id'), 'questionsCount']]
      }
    ],
    offset: limit * page,
    limit: limit,
    order: [["id", "ASC"]],
  })
    .then(data => {

      data.rows.forEach(function(category) {
        console.log("------ May 31 ----> " + JSON.stringify(category.questions[0]) + " -->" + category.questions[0].hasOwnProperty('questionsCount'))
        console.log(JSON.stringify(category))
        console.log(category.questions[0].toJSON().questionsCount)
      })

      res.json(myUtil.response.paging(data, page, limit))
    })
    .catch(err => {
      console.log("Error get categories: " + err.message)
      res.status(500).send({
        message: "An error has occured while retrieving data."
      })
    })
}
</code>```

I loop through the data.rows to get each category object.

The console.log outputs are:

```<code>------ May 31 ----> {"questionsCount":4} -->false

{"id":1,"title":"movies","isActive":true,"createdAt":"2020-05-30T19:26:04.000Z","updatedAt":"2020-05-30T19:26:04.000Z","questions":[{"questionsCount":4}]}

4
</code>```

答:
try this </p>

```<code>category.data[0].questions[0].questionCount
</code>```

<p>the reason why you have to use toJSON is because it's sometimes it is used to customise the stringification behavior. like doing some calculation before assinging the value to the object that will be returned , so it is most likley been used here to calculate the "numb of questions and then return an object with the property questionscount and the number calculated
so the object you retreived more or less looks like this </p>

```<code>var cathegory = {
  data: 'data',
  questions:[{
    // some calulation here to get the questionsCount
      result=4,
    toJSON () {
      return  {"questionsCount":this.result}
    }
  }
 ]
};

console.log(cathegory.questions[0].toJSON().questionsCount) //4
console.log(JSON.stringify(cathegory))  // {"data":"data","questions":[{"questionsCount":4}]}
console.log("------ May 31 ----> " + JSON.stringify(cathegory.questions[0]) + " -->" + cathegory.questions[0].hasOwnProperty('questionsCount')) //false
</code>```

Body:
EDIT: Re-structured question, cleaer, and cleaner:

I have a data object from Sequelize that is sent by node-express:

{
    "page": 0,
    "limit": 10,
    "total": 4,
    "data": [
        {
            "id": 1,
            "title": "movies",
            "isActive": true,
            "createdAt": "2020-05-30T19:26:04.000Z",
            "updatedAt": "2020-05-30T19:26:04.000Z",
            "questions": [
                {
                    "questionsCount": 4
                }
            ]
        }
    ]
}

The BIG question is, how do I get the value of questionsCount?
The PROBLEM is, I just can't extract it, these two methods give me undefined result:

category.questions[0].questionsCount

category.questions[0]['questionsCount']

I WAS ABLE to get it using toJSON() (From Sequelize lib I think), like so:

category.questions[0].toJSON().questionsCount

But I'd like to know the answer to the question, or at least a clear explanation of why do I have to use toJSON() just to get the questionsCount?

More context:

I have this GET in my controller:

exports.getCategories = (req, res) => {
  const page = myUtil.parser.tryParseInt(req.query.page, 0)
  const limit = myUtil.parser.tryParseInt(req.query.limit, 10)

  db.Category.findAndCountAll({
    where: {},
    include: [
      {
        model: db.Question,
        as: "questions",
        attributes: [[db.Sequelize.fn('COUNT', 'id'), 'questionsCount']]
      }
    ],
    offset: limit * page,
    limit: limit,
    order: [["id", "ASC"]],
  })
    .then(data => {

      data.rows.forEach(function(category) {
        console.log("------ May 31 ----> " + JSON.stringify(category.questions[0]) + " -->" + category.questions[0].hasOwnProperty('questionsCount'))
        console.log(JSON.stringify(category))
        console.log(category.questions[0].toJSON().questionsCount)
      })

      res.json(myUtil.response.paging(data, page, limit))
    })
    .catch(err => {
      console.log("Error get categories: " + err.message)
      res.status(500).send({
        message: "An error has occured while retrieving data."
      })
    })
}

I loop through the data.rows to get each category object.

The console.log outputs are:

------ May 31 ----> {"questionsCount":4} -->false

{"id":1,"title":"movies","isActive":true,"createdAt":"2020-05-30T19:26:04.000Z","updatedAt":"2020-05-30T19:26:04.000Z","questions":[{"questionsCount":4}]}

4

Body:
try this

category.data[0].questions[0].questionCount

the reason why you have to use toJSON is because it's sometimes it is used to customise the stringification behavior. like doing some calculation before assinging the value to the object that will be returned , so it is most likley been used here to calculate the "numb of questions and then return an object with the property questionscount and the number calculated
so the object you retreived more or less looks like this

var cathegory = {
  data: 'data',
  questions:[{
    // some calulation here to get the questionsCount
      result=4,
    toJSON () {
      return  {"questionsCount":this.result}
    }
  }
 ]
};

console.log(cathegory.questions[0].toJSON().questionsCount) //4
console.log(JSON.stringify(cathegory))  // {"data":"data","questions":[{"questionsCount":4}]}
console.log("------ May 31 ----> " + JSON.stringify(cathegory.questions[0]) + " -->" + cathegory.questions[0].hasOwnProperty('questionsCount')) //false


问:
AWS CloudFormation template generation issue
I have AWS Lambda service running which I had developed and deployed using the AWS SAM CLI. There are some other services as like ElasticCache, RDS, etc running in my AWS Account.

Now my requirement is to generate the CloudFormation YAML template file out of existing running service which I can use to provision later and keep as a backup. For this, I used CloudFormer template however problem is that CloudFormer does not consider or generate YAML template for AWS Lambda services which I had noticed. And also I believe CloudFormer has become obsolete as well.

Please assist me here to let me know if there any latest service from AWS that can fulfil my requirement here.

Thank you

答:
Unfortunately, there is no such functionality, apart from CloudFormer which is not maintained anymore by AWS nor reliable (in beta for years).

To use the importing resources feature into CFN, you have to manually write its template. This means you prepare your templates for RDS or EC, which match exactly your existing resources. If you have written the yaml or json template for the imported resources, you then can attempt to import them. In other words, the feature does not generate yaml code for you.

Maybe there are some non-AWS third party tools for that, but I'm not aware of any worth recommending unfortunately.


问:
Getting the orginal value of variable after entering a for loop
I'm making a simple script that iterates through the files in the current directories,
the $1 is for a size parameter and the others $1,$2 ..... are for the manipulated files and set for the file names.
the problem is after using the for loop the variable are losing their value and start with integers like 1,2,3, and the script doesn't work unless I use files named as 1,2,3,....
How can I keep the original values?
ex:
 ./script 50 my_first_file .....

```<code>#!/bin/bash
size=$1
allfiles=$#
shift
#here the value of the $1 is "my_first_file"
  for ((i = 1 ; i < allfiles ; i++))
  do
  #here the value of the $1 = 1
  done
</code>```

答:
Instead of using a for loop with integers, you can loop on arguments directly like this:

```<code>#!/bin/bash

size="$1"
allfiles=$#
shift

counter=1
for i in "$@"
do
    echo "$counter= $i"
    (( counter = counter + 1 ))
done

echo "size= $size"
</code>```

This will show you each argument in sequence.
If you need to show or use the position of each argument, you can use a counter.

If I call this: script.bash 25 a b c
The output is:

```<code>1= a
2= b
3= c
size= 25
</code>```

Body:
I'm making a simple script that iterates through the files in the current directories,
the $1 is for a size parameter and the others $1,$2 ..... are for the manipulated files and set for the file names.
the problem is after using the for loop the variable are losing their value and start with integers like 1,2,3, and the script doesn't work unless I use files named as 1,2,3,....
How can I keep the original values?
ex:
 ./script 50 my_first_file .....

#!/bin/bash
size=$1
allfiles=$#
shift
#here the value of the $1 is "my_first_file"
  for ((i = 1 ; i < allfiles ; i++))
  do
  #here the value of the $1 = 1
  done

Body:
Instead of using a for loop with integers, you can loop on arguments directly like this:

#!/bin/bash

size="$1"
allfiles=$#
shift

counter=1
for i in "$@"
do
    echo "$counter= $i"
    (( counter = counter + 1 ))
done

echo "size= $size"

This will show you each argument in sequence.
If you need to show or use the position of each argument, you can use a counter.

If I call this: script.bash 25 a b c
The output is:

1= a
2= b
3= c
size= 25


问:
How do I solve a function for a given x?
I have been browsing through quite some help pages, but I did not find the solution for my - probably - simple problem.
I defined a function

```<code>funB <- function(x) (0.8042851 +
    ((3.9417843-0.8042851)/(1+((x/0.4039609)^(-3.285016)))))
</code>```

and would like to solve it for a given x (say, x = 0.2).
How do I do that? I have looked at uniroot() and polyroot(), but they did not seem to fit my function.

答:
If you wanted to find the value of x such that funB(x) was equal to 0.2, you would do something like this:

```<code>funB <- function(x) (0.8042851 +
    ((3.9417843-0.8042851)/(1+((x/0.4039609)^(-3.285016)))))
target <- 0.2
uniroot(function(x) funB(x)-target, interval=c(-5,10))
</code>```

but there's a problem.  It's up to you to pick an interval value that brackets a root (i.e. funB(x)<0.2 for the lower value and >0.2 for the upper value, or vice versa. funB is NaN for x<0, 0.8042851 for x==0, and increasing for x>0 (try curve(funB, from=-5, to=100, n=1001) for example).  So the solution you want (if I've guessed right about the meaning of your question) doesn't seem to exist.

note: in general a negative value raised to a negative power is NaN in R (even in cases where the answer "should" be defined, e.g. (-8)^(1/3) is the cube root of -8, which is -2 ...).  If you're sure you know what you're doing you could replace (x/a)^b with sign(x)*(abs(x)/a)^b) ... (if you make this change, the function appears well-behaved for x>-0.4 and funB(x)-0.2 does have a root between -0.3 and -0.2 ... but I have no idea if this makes sense for your application or not)

Body:
I have been browsing through quite some help pages, but I did not find the solution for my - probably - simple problem.
I defined a function

funB <- function(x) (0.8042851 +
    ((3.9417843-0.8042851)/(1+((x/0.4039609)^(-3.285016)))))

and would like to solve it for a given x (say, x = 0.2).
How do I do that? I have looked at uniroot() and polyroot(), but they did not seem to fit my function.

Body:
If you wanted to find the value of x such that funB(x) was equal to 0.2, you would do something like this:

funB <- function(x) (0.8042851 +
    ((3.9417843-0.8042851)/(1+((x/0.4039609)^(-3.285016)))))
target <- 0.2
uniroot(function(x) funB(x)-target, interval=c(-5,10))

but there's a problem.  It's up to you to pick an interval value that brackets a root (i.e. funB(x)<0.2 for the lower value and >0.2 for the upper value, or vice versa. funB is NaN for x<0, 0.8042851 for x==0, and increasing for x>0 (try curve(funB, from=-5, to=100, n=1001) for example).  So the solution you want (if I've guessed right about the meaning of your question) doesn't seem to exist.

note: in general a negative value raised to a negative power is NaN in R (even in cases where the answer "should" be defined, e.g. (-8)^(1/3) is the cube root of -8, which is -2 ...).  If you're sure you know what you're doing you could replace (x/a)^b with sign(x)*(abs(x)/a)^b) ... (if you make this change, the function appears well-behaved for x>-0.4 and funB(x)-0.2 does have a root between -0.3 and -0.2 ... but I have no idea if this makes sense for your application or not)


问:
How to create a number of Labels and Entry widgets, and get data from them in Tkinter with loop
I need to create a couple of Labels and Entry fields using Tkinker, they all will be the same, only difference is a text in the label which i could have in a list.
This is what the problem looks like while done in a simple way, i want to do it smarter, using some kind of loop, so i could expand it. </p>

```<code>from tkinter import *

root = Tk()

question1 = Label(root, text="Please give data number one")
question1.grid(row=1, column=0)
field1 = Entry(root)
field1.grid(row=1, column=1)

question2 = Label(root, text="Please give data number two")
question2.grid(row=2, column=0)
field2 = Entry(root)
field2.grid(row=2, column=1)

question3 = Label(root, text="Please give data number three")
question3.grid(row=3, column=0)
field3 = Entry(root)
field3.grid(row=3, column=1)

question4 = Label(root, text="Please give data number four")
question4.grid(row=4, column=0)
field4 = Entry(root)
field4.grid(row=4, column=1)

data1 = field1.get()
data2 = field2.get()
data3 = field3.get()
data4 = field4.get()

root.mainloop()

</code>```

<p>I thought abour something like this but i don't know how to get values from Enter widgets. </p>

```<code>from tkinter import *

root = Tk()

questions = ["Please give data number one",
"Please give data number two"
"Please give data number three"
"Please give data number four"
]

for question in enumerate(questions):
    ask = Label(root, text=question[1])
    ask.grid(row=(question[0] + 1), column=0)
    field = Entry(root)
    field.grid(row=(question[0] + 1), column=1)

root.mainloop()

</code>```

答:
You need to do two things:
Firstly keep a reference to the widget, and then use the get() method to get the string.

For an example:

```<code>self.entry = Entry(...)
</code>```

...some code

```<code>print("the text is", self.entry.get())
</code>```

Sample Get Entries:

```<code>class InputPage(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self,parent)

        label =  Label(self, text="Please give data number four")
        label.grid(row=0, column=0, sticky ='n', columnspan =2)

        # i brought your variable in the class for example sake

        namesInput = ["First:", "second:", "Third:", "Fourth:", "Fifth:"]

        self.entryWidgets = [] # we want to call this in another function so we assign it as self.variableName

        labelWidgets = []

        #LOOP TO CREATE WIDGETS
        for i in range(0, len(namesInput)):
            labelWidgets.append(Label(self, text = namesInput[i]))
            self.entryWidgets.append(Entry(self))
            labelWidgets[-1].grid(row= i+1, column =0, sticky='e')
            self.entryWidgets[-1].grid(row= i+1, column = 1, sticky='w')

        submit = Button(self, text = "Submit", command = self.getEntries)
        submit.grid(row = 6, column =0, columnspan =2)

    def getEntries(self):
        results = []

        for x in self.entryWidgets: # i.e for each widget in entryWidget list
            results.append(x.get())
        print(results)
</code>```

Body:
I need to create a couple of Labels and Entry fields using Tkinker, they all will be the same, only difference is a text in the label which i could have in a list.
This is what the problem looks like while done in a simple way, i want to do it smarter, using some kind of loop, so i could expand it.

from tkinter import *

root = Tk()

question1 = Label(root, text="Please give data number one")
question1.grid(row=1, column=0)
field1 = Entry(root)
field1.grid(row=1, column=1)

question2 = Label(root, text="Please give data number two")
question2.grid(row=2, column=0)
field2 = Entry(root)
field2.grid(row=2, column=1)

question3 = Label(root, text="Please give data number three")
question3.grid(row=3, column=0)
field3 = Entry(root)
field3.grid(row=3, column=1)

question4 = Label(root, text="Please give data number four")
question4.grid(row=4, column=0)
field4 = Entry(root)
field4.grid(row=4, column=1)

data1 = field1.get()
data2 = field2.get()
data3 = field3.get()
data4 = field4.get()

root.mainloop()

I thought abour something like this but i don't know how to get values from Enter widgets.

from tkinter import *

root = Tk()

questions = ["Please give data number one",
"Please give data number two"
"Please give data number three"
"Please give data number four"
]

for question in enumerate(questions):
    ask = Label(root, text=question[1])
    ask.grid(row=(question[0] + 1), column=0)
    field = Entry(root)
    field.grid(row=(question[0] + 1), column=1)

root.mainloop()

Body:
You need to do two things:
Firstly keep a reference to the widget, and then use the get() method to get the string.

For an example:

self.entry = Entry(...)

...some code

print("the text is", self.entry.get())

Sample Get Entries:

class InputPage(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self,parent)

        label =  Label(self, text="Please give data number four")
        label.grid(row=0, column=0, sticky ='n', columnspan =2)

        # i brought your variable in the class for example sake

        namesInput = ["First:", "second:", "Third:", "Fourth:", "Fifth:"]

        self.entryWidgets = [] # we want to call this in another function so we assign it as self.variableName

        labelWidgets = []

        #LOOP TO CREATE WIDGETS
        for i in range(0, len(namesInput)):
            labelWidgets.append(Label(self, text = namesInput[i]))
            self.entryWidgets.append(Entry(self))
            labelWidgets[-1].grid(row= i+1, column =0, sticky='e')
            self.entryWidgets[-1].grid(row= i+1, column = 1, sticky='w')

        submit = Button(self, text = "Submit", command = self.getEntries)
        submit.grid(row = 6, column =0, columnspan =2)

    def getEntries(self):
        results = []

        for x in self.entryWidgets: # i.e for each widget in entryWidget list
            results.append(x.get())
        print(results)


问:
Celery, calling delay with countdown
I'm trying to understand how celery works

In my django application in tasks.py file I have created one task:

```<code>@celery.shared_task(default_retry_delay=2 * 60, max_retries=2)
def my_task(param1, param2):
    # There are some operations
</code>```

I call this task by using this code:

```<code>my_task.delay(param1, param2)
</code>```

Inside of this my_task there is one condition where this task should be started again but after one minute delay

I have found that there are some kind of ETA and countdown for tasks, but their examples are only with apply_async

Is it possible to use some kind countdown for delay?

答:
Just to add to iklinac's answer. This is how you would call the task using apply_async()

```<code>my_task.apply_async(args=(param1, param2), countdown=60)
</code>```

or

```<code>my_task.apply_async(kwargs={'param1':param1, 'param2':param2}, countdown=60)
</code>```

The second option will really come in handy if you are using a tool like Flower for monitoring. You can look at Celery tasks best practices page for other tips.

Title: Celery, calling delay with countdown

Body:
I'm trying to understand how celery works

In my django application in tasks.py file I have created one task:

@celery.shared_task(default_retry_delay=2 * 60, max_retries=2)
def my_task(param1, param2):
    # There are some operations

I call this task by using this code:

my_task.delay(param1, param2)

Inside of this my_task there is one condition where this task should be started again but after one minute delay

I have found that there are some kind of ETA and countdown for tasks, but their examples are only with apply_async

Is it possible to use some kind countdown for delay?

Body:
Just to add to iklinac's answer. This is how you would call the task using apply_async()

my_task.apply_async(args=(param1, param2), countdown=60)

or

my_task.apply_async(kwargs={'param1':param1, 'param2':param2}, countdown=60)

The second option will really come in handy if you are using a tool like Flower for monitoring. You can look at Celery tasks best practices page for other tips.


答:
The "normal" pattern is to write asynchronous pseudo-actions: async function dispatching classical synchronous actions :

```<code>// reducer

// define 3 synchronous actions : loginActionBegin, loginActionSuccess,
// loginActionFailure which update your state at your convenience, for example setting a boolean flag to inform components that request is
// flying, or add user infos in store when loginActionSuccess is dispatched...

// async pseudo action
export const loginActionAsync = (loginInfos: any): any => {
  return (dispatch: Dispatch, getState: any): any => {
    dispatch(loginActionBegin());
    return loginService.login(loginInfos)
      .then(result: any): any => {
        // request succeeded, add toast, user feedback...
        dispatch(loginActionSuccess(result));
      })
      .catch((error: any) => {
        // request failed, add toast, user feedback...
        dispatch(loginActionFailure(error));
      });
  };
}
</code>```

Then in a component:

```<code>// grab infos from store
const user = useSelector(state => state.user)

// on login form submit
dispatch(loginActionAsync({username:..., password:...}));
</code>```

You will need async middleware to do so like https://github.com/reduxjs/redux-thunk

See :

https://redux.js.org/advanced/async-actions

https://www.digitalocean.com/community/tutorials/redux-redux-thunk

https://redux-toolkit.js.org/usage/usage-with-typescript#createasyncthunk

Title: async/await in react with redux

Body:
Hi guys I am quite new to programming and trying to understand one thing with redux and await/async functions. Basically I have this function:

 //nh functions
    const onSubmit = async data => {
        try{
            await dispatch(Login(data))
            if (auth.logged != false){
                addToast(content, { appearance: 'success', autoDismiss: true, })
                history.push('/')
            } else if (auth.logged == false){
                addToast(content2, { appearance: 'error', autoDismiss: true, })
            }
        }finally{
            console.log('Tada')
        }
    }

which should first authenticate an account and then push a notification. However, the await is not working at all, and it proceeds immediately to the if statement. Any tips?

Body:
The "normal" pattern is to write asynchronous pseudo-actions: async function dispatching classical synchronous actions :

// reducer

// define 3 synchronous actions : loginActionBegin, loginActionSuccess,
// loginActionFailure which update your state at your convenience, for example setting a boolean flag to inform components that request is
// flying, or add user infos in store when loginActionSuccess is dispatched...

// async pseudo action
export const loginActionAsync = (loginInfos: any): any => {
  return (dispatch: Dispatch, getState: any): any => {
    dispatch(loginActionBegin());
    return loginService.login(loginInfos)
      .then(result: any): any => {
        // request succeeded, add toast, user feedback...
        dispatch(loginActionSuccess(result));
      })
      .catch((error: any) => {
        // request failed, add toast, user feedback...
        dispatch(loginActionFailure(error));
      });
  };
}

Then in a component:

// grab infos from store
const user = useSelector(state => state.user)

// on login form submit
dispatch(loginActionAsync({username:..., password:...}));

You will need async middleware to do so like https://github.com/reduxjs/redux-thunk

See :

https://redux.js.org/advanced/async-actions

https://www.digitalocean.com/community/tutorials/redux-redux-thunk

https://redux-toolkit.js.org/usage/usage-with-typescript#createasyncthunk


答:
Just to be sure that there is a root where you are expecting it, plot the graph of funB.

```<code>curve(funB)
</code>```

Define an auxiliary function, f, taking an extra argument and solve this new function for a = <target_value>.

```<code>f <- function(x, a) funB(x) - a

uniroot(f, interval = c(0, 1e3), a = 2)

#$root
#[1] 0.3485097
#
#$f.root
#[1] -0.0001305644
#
#$iter
#[1] 12
#
#$init.it
#[1] NA
#
#$estim.prec
#[1] 6.103516e-05
</code>```

Title: How do I solve a function for a given x?

Body:
Just to be sure that there is a root where you are expecting it, plot the graph of funB.

curve(funB)

Define an auxiliary function, f, taking an extra argument and solve this new function for a = <target_value>.

f <- function(x, a) funB(x) - a

uniroot(f, interval = c(0, 1e3), a = 2)

#$root
#[1] 0.3485097
#
#$f.root
#[1] -0.0001305644
#
#$iter
#[1] 12
#
#$init.it
#[1] NA
#
#$estim.prec
#[1] 6.103516e-05


答:
since you want a column in same dataframe but the output is correspondent to only certain rows , I will be replacing every other column with nan values,

```<code>data = pd.read_csv('file.csv')
data.columns=['low', 'pivot_low_1', 'PH']
count = 0
l = list()
new=list()
for index, row in data.iterrows():
    if row['pivot_low_1']==1:
        l.append(count)
    if (row['PH']==1) and (row['pivot_low_1']==1):
        new.append(data.iloc[l[len(l)-2]].low)
    elif (row['PH']==1):
        new.append(data.iloc[l[len(l)-1]].low)
    elif (row['PH']==0):
        new.append(np.nan)
    count+=1
data['new'] = new
data
</code>```

The output is as shown in this image, https://imgur.com/a/IqowZHZ , hope this helps

Title: Pandas time series - need to extract row value based on multiple conditionals based on other columns

Body:
I have a time series dataframe with the below columns. I am trying to figure out:

If df['PH'] ==1, then I need find the previous date where df['pivot_low_1'] == 1 and extract the value of df['low'] for that date. So, for 2010-01-12 where df['PH'] ==1, I would need to identify the previous non-zero df['pivot_low_1'] == 1 on 2010-01-07 and get df['low'] == 1127.00000.

                  low  pivot_low_1  PH
date
2010-01-04 1114.00000            1   0
2010-01-05 1125.00000            0   0
2010-01-06 1127.25000            0   0
2010-01-07 1127.00000            1   0
2010-01-08 1131.00000            0   0
2010-01-11 1137.75000            0   0
2010-01-12 1127.75000            1   1
2010-01-13 1129.25000            0   0
2010-01-14 1138.25000            0   0
2010-01-15 1127.50000            1   0
2010-01-18 1129.50000            0   0
2010-01-19 1126.25000            0   0
2010-01-20 1125.25000            0   0
2010-01-21 1108.50000            0   0
2010-01-22 1086.25000            1   0
2010-01-25 1089.75000            0   0
2010-01-26 1081.00000            0   0
2010-01-27 1078.50000            0   0
2010-01-28 1074.25000            0   0
2010-01-29 1066.50000            1   1
2010-02-01 1068.00000            0   0

Body:
since you want a column in same dataframe but the output is correspondent to only certain rows , I will be replacing every other column with nan values,

data = pd.read_csv('file.csv')
data.columns=['low', 'pivot_low_1', 'PH']
count = 0
l = list()
new=list()
for index, row in data.iterrows():
    if row['pivot_low_1']==1:
        l.append(count)
    if (row['PH']==1) and (row['pivot_low_1']==1):
        new.append(data.iloc[l[len(l)-2]].low)
    elif (row['PH']==1):
        new.append(data.iloc[l[len(l)-1]].low)
    elif (row['PH']==0):
        new.append(np.nan)
    count+=1
data['new'] = new
data

The output is as shown in this image, https://imgur.com/a/IqowZHZ , hope this helps


问:
How to properly declare a self-referencing template type?
How do I declare a templated type that refers to itself?

```<code>template <class T = Animal> class Animal
{
public:
    T getChild ();
}
</code>```

With this, I get a compiler error concerning a missing type specifier. I tried to forward-declare Animal, without success.

I am trying to impose a type constraint. A Lion can only have a Lion as a child, a Bear has a Bear, and so on.

EDIT

I'll post part of the actual class. It is a template for classes that can appear in a linked list:

```<code>template <class T = Linked<T> > class Linked
{
private:
    T* m_prev;
    T* m_next;
}
</code>```

I want to enforce that the class can only point to object of the same class (or a subclass).

答:
The OP has been answered but I want to chime in because the immediate cause of the problem is not recursion, as others claim. The simplest reason this wouldn't work is that class templates are not types. They are templates. Similarly, function templates are not functions either. So all of this is nonsensical:

```<code>template<typename T> int function_template(int);
typedef int function_type(int);
void eats_a_function(function_type&); // needs a reference to function

std::vector< std::vector > vec0; // std::vector is not a type
std::vector< std::list > vec1; // std::list is not a type
eats_a_function(function_template); // function_template is not a function
</code>```

Notice that in the vec1 case, std::list is not related to std::vector. The template is fully defined (assuming header inclusion) at the point of instantiation. It still won't work.

Instead, the following works:

```<code>std::vector< std::vector<int> > vec2; // std::vector<int> is a type
std::vector< std::list<double> > vec3; // std::list<double> is a type
eats_a_function(function_template<long>); // function_template<long> is a function
</code>```

Notice that in the vec2 case, it's fine to pass an instantiation of the template itself.

For the record, a toy solution to the toy problem on writing a template that refers to itself, using the proverbial layer of indirection:

```<code>// expects a template that expects a type
template<template<class> class T> struct indirection {};

// forward decl. for defaulting the parameter
template<typename T> struct recursive;

// template that expects a type
template<typename T = indirection<recursive> > struct recursive {};
</code>```

Not terribly powerful given the few things that are possible with a template (the T parameter inside indirection). It's of course possible to write a rebind-style metafunction that returns an instantiation of T.

Body:
How do I declare a templated type that refers to itself?

template <class T = Animal> class Animal
{
public:
    T getChild ();
}

With this, I get a compiler error concerning a missing type specifier. I tried to forward-declare Animal, without success.

I am trying to impose a type constraint. A Lion can only have a Lion as a child, a Bear has a Bear, and so on.

EDIT

I'll post part of the actual class. It is a template for classes that can appear in a linked list:

template <class T = Linked<T> > class Linked
{
private:
    T* m_prev;
    T* m_next;
}

I want to enforce that the class can only point to object of the same class (or a subclass).

Body:
The OP has been answered but I want to chime in because the immediate cause of the problem is not recursion, as others claim. The simplest reason this wouldn't work is that class templates are not types. They are templates. Similarly, function templates are not functions either. So all of this is nonsensical:

template<typename T> int function_template(int);
typedef int function_type(int);
void eats_a_function(function_type&); // needs a reference to function

std::vector< std::vector > vec0; // std::vector is not a type
std::vector< std::list > vec1; // std::list is not a type
eats_a_function(function_template); // function_template is not a function

Notice that in the vec1 case, std::list is not related to std::vector. The template is fully defined (assuming header inclusion) at the point of instantiation. It still won't work.

Instead, the following works:

std::vector< std::vector<int> > vec2; // std::vector<int> is a type
std::vector< std::list<double> > vec3; // std::list<double> is a type
eats_a_function(function_template<long>); // function_template<long> is a function

Notice that in the vec2 case, it's fine to pass an instantiation of the template itself.

For the record, a toy solution to the toy problem on writing a template that refers to itself, using the proverbial layer of indirection:

// expects a template that expects a type
template<template<class> class T> struct indirection {};

// forward decl. for defaulting the parameter
template<typename T> struct recursive;

// template that expects a type
template<typename T = indirection<recursive> > struct recursive {};

Not terribly powerful given the few things that are possible with a template (the T parameter inside indirection). It's of course possible to write a rebind-style metafunction that returns an instantiation of T.