问:
So I'm trying to understand Exists condition in sql. I know it returns True if there exists one or more tuples
How does with work. My nested query returns only 3 tuples. But when combined with outer query, it(outer query) returns 736 tuples. And this is the same amount of tuples if I write a query say select p.height from ... where True.

I read the books which says it only returns true which makes sense in my case. Also read few online article where exists returns True but the outer query only selects from the results of nested query.

mysql-workbench

```<code>select p.height
from world_cup.player as p
where Exists(select q.height from world_cup.player as q where q.height = 165)
order by p.height;
</code>```

Actual result should have been those three tuples 165, 165, 165(according to the book and online resources)

答:
Yeah, I got to test myself and what you said is correct. However from the link you're referring to here https://www.w3schools.com/sql/sql_exists.asp , you're missing one condition whereby you need to have a p.height=q.heightbefore q.height=165 for it to return the values correctly. Hence, your query suppose to be like this:

```<code>SELECT p.height
FROM world_cup.player AS p
WHERE EXISTS (
              SELECT q.height FROM world_cup.player AS q
               WHERE p.height=q.height -- you're missing this condition
                 AND q.height = 165
              )
ORDER BY p.height;
</code>```

Here's a reference:
https://dev.mysql.com/doc/refman/8.0/en/exists-and-not-exists-subqueries.html

"For the preceding example, if t2 contains any rows, even rows with nothing but NULL values, the EXISTS condition is TRUE."

Body:
How does with work. My nested query returns only 3 tuples. But when combined with outer query, it(outer query) returns 736 tuples. And this is the same amount of tuples if I write a query say select p.height from ... where True.

I read the books which says it only returns true which makes sense in my case. Also read few online article where exists returns True but the outer query only selects from the results of nested query.

mysql-workbench

select p.height
from world_cup.player as p
where Exists(select q.height from world_cup.player as q where q.height = 165)
order by p.height;

Actual result should have been those three tuples 165, 165, 165(according to the book and online resources)

Body:
Yeah, I got to test myself and what you said is correct. However from the link you're referring to here https://www.w3schools.com/sql/sql_exists.asp , you're missing one condition whereby you need to have a p.height=q.heightbefore q.height=165 for it to return the values correctly. Hence, your query suppose to be like this:

SELECT p.height
FROM world_cup.player AS p
WHERE EXISTS (
              SELECT q.height FROM world_cup.player AS q
               WHERE p.height=q.height -- you're missing this condition
                 AND q.height = 165
              )
ORDER BY p.height;

Here's a reference:
https://dev.mysql.com/doc/refman/8.0/en/exists-and-not-exists-subqueries.html

"For the preceding example, if t2 contains any rows, even rows with nothing but NULL values, the EXISTS condition is TRUE."


来源: stackexchange

问:
Style mapped views in a row react native
I map over this.props.league to create these checkboxes

I want each checkbox selection item to be position in a row from left to right.

How do I do that when I have an indefinite amount of items?

This is my render:

```<code>        <View style={{marginTop: 22}}>
              <Modal
                animationType="slide"
                transparent={false}
                visible={this.state.modalVisible}
                onRequestClose={() => {
                Alert.alert('Modal has been closed.');
                }}
              >

                <View
                    style={{
                        marginTop: 100
                    }}
                >

                    <TouchableHighlight
                        onPress={() => {
                            this.setModalVisible(!this.state.modalVisible);
                        }}
                    >
                        <Text>Hide Modal</Text>
                    </TouchableHighlight>
                        <Text>Leagues</Text>

                        {this.props.league === null ?'' : this.props.league.map(
                            (v, i) => {
                                return(
                                        <View
                                            key={i}
                                            style={{
                                            }}
                                        >
                                            <Check
                                                checked={this.state.checked[i]}
                                                index={i}
                                                acronym={v.acronym}
                                                changeCheck={this.changeCheck}

                                            />
                                            <Text>{v.acronym}</Text>
                                        </View>
                                )
                            }
                        )}
                </View>
              </Modal>

              <TouchableHighlight
                onPress={() => {
                  this.setModalVisible(true);
                }}>
                <Text>Show Modal</Text>
              </TouchableHighlight>

            </View>
</code>```

I tried a few different options, but none of them were able to position the two side by side.

答:
You need to give parent view of check box style in order to show all items in a row

```<code>flexDirection: 'row'
</code>```

And if you have an array so you can use flatlist to show as a list also it has option to show number of columns like if you want to show 2 checkbox per row, you can do as

```<code><FlatList
           numColumns={2}
           ....
        />
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I map over this.props.league to create these checkboxes

I want each checkbox selection item to be position in a row from left to right.

How do I do that when I have an indefinite amount of items?

This is my render:

        <View style={{marginTop: 22}}>
              <Modal
                animationType="slide"
                transparent={false}
                visible={this.state.modalVisible}
                onRequestClose={() => {
                Alert.alert('Modal has been closed.');
                }}
              >

                <View
                    style={{
                        marginTop: 100
                    }}
                >

                    <TouchableHighlight
                        onPress={() => {
                            this.setModalVisible(!this.state.modalVisible);
                        }}
                    >
                        <Text>Hide Modal</Text>
                    </TouchableHighlight>
                        <Text>Leagues</Text>

                        {this.props.league === null ?'' : this.props.league.map(
                            (v, i) => {
                                return(
                                        <View
                                            key={i}
                                            style={{
                                            }}
                                        >
                                            <Check
                                                checked={this.state.checked[i]}
                                                index={i}
                                                acronym={v.acronym}
                                                changeCheck={this.changeCheck}

                                            />
                                            <Text>{v.acronym}</Text>
                                        </View>
                                )
                            }
                        )}
                </View>
              </Modal>

              <TouchableHighlight
                onPress={() => {
                  this.setModalVisible(true);
                }}>
                <Text>Show Modal</Text>
              </TouchableHighlight>

            </View>

I tried a few different options, but none of them were able to position the two side by side.

Body:
You need to give parent view of check box style in order to show all items in a row

flexDirection: 'row'

And if you have an array so you can use flatlist to show as a list also it has option to show number of columns like if you want to show 2 checkbox per row, you can do as

<FlatList
           numColumns={2}
           ....
        />


问:
Redux-thunk dispatch function doesn't work on Laravel
I'm using React-Laravel for my project.
The problem is when I tried to use redux-thunk for the asynchronous dispatch function.
My dispatch function won't get executed.
Please do help me figure out this problem.

I have already tried to use promise or redux-devtools-extension library
https://codeburst.io/reactjs-app-with-laravel-restful-api-endpoint-part-2-aef12fe6db02

app.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import logger from 'redux-logger';

import Layout from './jsx/Layout/Layout';
import marketplaceReducer from './store/reducers/marketplace';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const appReducer = combineReducers({
    marketplace: marketplaceReducer
});

const rootReducer = (state, action) => {
    return appReducer(state, action);
}

const store = createStore(rootReducer, composeEnhancers(
    applyMiddleware(logger, thunk)
));

const render = (
    <Provider store={store}>
        <BrowserRouter>
            <Layout />
        </BrowserRouter>
    </Provider>
);

ReactDOM.render(render, document.getElementById('root'));
</code>```

marketplace.js (action)

```<code>import * as actionTypes from './actionTypes';
import axios from '../../axios';

export const loadMarketplace = () => {
    console.log("Load Marketplace");
    return {
        type: actionTypes.LOAD_MARKETPLACE
    };
}

export const successMarketplace = (data) => {
    console.log("Success Marketplace");
    return {
        type: actionTypes.SUCCESS_MARKETPLACE,
        data: data
    }
}

export const failedMarketplace = () => {
    console.log("Failed Marketplace");
    return {
        type: actionTypes.FAILED_MARKETPLACE
    }
}

export const showMarketplace = () => {
    console.log("Show Marketplace Action")
    return dispatch => {
        //This is the problem
        //Inside this function, I can't see any console.log, even loadMarketplace() didn't get called.
        console.log("Show Marketplace in dispatch");
        dispatch(loadMarketplace());
        axios.get('/marketplaces')
            .then(response => {
                dispatch(successMarketplace(response));
            })
            .catch(error => {
                dispatch(failedMarketplace());
            });
    };
}
</code>```

marketplace.js (reducer)

```<code>import * as actionTypes from '../actions/actionTypes';

const initial_state = {
    data: [],
    loading: false
}

const loadMarketplace = (state, action) => {
    console.log("Load Marketplace Reducer")
    return {
        ...state,
        loading: true
    };
}
const successMarketplace = (state, action) => {
    console.log("Success Marketplace Reducer", action.data)
    return {
        ...state,
        loading: false,
        data: action.data
    };
}

const failedMarketplace = (state, action) => {
    return {
        ...state,
        loading: false
    };
}

const reducer = (state = initial_state, action) => {
    //This is called when the first init, never got it through showMarketplace() function.
    console.log("Marketplace Reducer", action);
    switch (action.type) {
        case actionTypes.LOAD_MARKETPLACE: return loadMarketplace(state, action);
        case actionTypes.SUCCESS_MARKETPLACE: return successMarketplace(state, action);
        case actionTypes.FAILED_MARKETPLACE: return failedMarketplace(state, action);
        default: return state;
    }
}

export default reducer;
</code>```

Marketplace.js (jsx view)

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';

import * as actions from '../../../store/actions';

class Marketplace extends Component {
    componentDidMount() {
        console.log('[ComponentDidMount] Marketplace')
        this.props.showMarketplace();
    }

    render() {
        return (
            <React.Fragment>
                Marketplace
            </React.Fragment>
        );
    }
}

const mapDispatchToProps = dispatch => {
    return {
        showMarketplace: () => dispatch(actions.showMarketplace)
    };
}

export default connect(null, mapDispatchToProps)(Marketplace);
</code>```

This is the result of my console.log (when loading the first time for Marketplace.js)

Please do help, I've been struggling for 2 hours or more, only because of this problem. (This is my first time using React-Laravel).
Thank you.

答:
I already found the problem. It is not redux-thunk problem.
It is actually a normal Redux problem we found anywhere.

Marketplace.js (jsx view)

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';

import * as actions from '../../../store/actions';

class Marketplace extends Component {
    componentDidMount() {
        console.log('[ComponentDidMount] Marketplace')
        this.props.showMarketplace();
    }

    render() {
        return (
            <React.Fragment>
                Marketplace
            </React.Fragment>
        );
    }
}

const mapDispatchToProps = dispatch => {
    return {
        showMarketplace: () => dispatch(actions.showMarketplace) //THIS IS THE PROBLEM, IT IS NOT EXECUTING PROPERLY. THIS ONE SHOULD BE
        showMarketplace: () => dispatch(actions.showMarketplace()) //SHOULD BE LIKE THIS.
    };
}

export default connect(null, mapDispatchToProps)(Marketplace);
</code>```

Body:
I'm using React-Laravel for my project.
The problem is when I tried to use redux-thunk for the asynchronous dispatch function.
My dispatch function won't get executed.
Please do help me figure out this problem.

I have already tried to use promise or redux-devtools-extension library
https://codeburst.io/reactjs-app-with-laravel-restful-api-endpoint-part-2-aef12fe6db02

app.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import logger from 'redux-logger';

import Layout from './jsx/Layout/Layout';
import marketplaceReducer from './store/reducers/marketplace';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const appReducer = combineReducers({
    marketplace: marketplaceReducer
});

const rootReducer = (state, action) => {
    return appReducer(state, action);
}

const store = createStore(rootReducer, composeEnhancers(
    applyMiddleware(logger, thunk)
));

const render = (
    <Provider store={store}>
        <BrowserRouter>
            <Layout />
        </BrowserRouter>
    </Provider>
);

ReactDOM.render(render, document.getElementById('root'));

marketplace.js (action)

import * as actionTypes from './actionTypes';
import axios from '../../axios';

export const loadMarketplace = () => {
    console.log("Load Marketplace");
    return {
        type: actionTypes.LOAD_MARKETPLACE
    };
}

export const successMarketplace = (data) => {
    console.log("Success Marketplace");
    return {
        type: actionTypes.SUCCESS_MARKETPLACE,
        data: data
    }
}

export const failedMarketplace = () => {
    console.log("Failed Marketplace");
    return {
        type: actionTypes.FAILED_MARKETPLACE
    }
}

export const showMarketplace = () => {
    console.log("Show Marketplace Action")
    return dispatch => {
        //This is the problem
        //Inside this function, I can't see any console.log, even loadMarketplace() didn't get called.
        console.log("Show Marketplace in dispatch");
        dispatch(loadMarketplace());
        axios.get('/marketplaces')
            .then(response => {
                dispatch(successMarketplace(response));
            })
            .catch(error => {
                dispatch(failedMarketplace());
            });
    };
}

marketplace.js (reducer)

import * as actionTypes from '../actions/actionTypes';

const initial_state = {
    data: [],
    loading: false
}

const loadMarketplace = (state, action) => {
    console.log("Load Marketplace Reducer")
    return {
        ...state,
        loading: true
    };
}
const successMarketplace = (state, action) => {
    console.log("Success Marketplace Reducer", action.data)
    return {
        ...state,
        loading: false,
        data: action.data
    };
}

const failedMarketplace = (state, action) => {
    return {
        ...state,
        loading: false
    };
}

const reducer = (state = initial_state, action) => {
    //This is called when the first init, never got it through showMarketplace() function.
    console.log("Marketplace Reducer", action);
    switch (action.type) {
        case actionTypes.LOAD_MARKETPLACE: return loadMarketplace(state, action);
        case actionTypes.SUCCESS_MARKETPLACE: return successMarketplace(state, action);
        case actionTypes.FAILED_MARKETPLACE: return failedMarketplace(state, action);
        default: return state;
    }
}

export default reducer;

Marketplace.js (jsx view)

import React, { Component } from 'react';
import { connect } from 'react-redux';

import * as actions from '../../../store/actions';

class Marketplace extends Component {
    componentDidMount() {
        console.log('[ComponentDidMount] Marketplace')
        this.props.showMarketplace();
    }

    render() {
        return (
            <React.Fragment>
                Marketplace
            </React.Fragment>
        );
    }
}

const mapDispatchToProps = dispatch => {
    return {
        showMarketplace: () => dispatch(actions.showMarketplace)
    };
}

export default connect(null, mapDispatchToProps)(Marketplace);

This is the result of my console.log (when loading the first time for Marketplace.js)

Please do help, I've been struggling for 2 hours or more, only because of this problem. (This is my first time using React-Laravel).
Thank you.

Body:
I already found the problem. It is not redux-thunk problem.
It is actually a normal Redux problem we found anywhere.

Marketplace.js (jsx view)

import React, { Component } from 'react';
import { connect } from 'react-redux';

import * as actions from '../../../store/actions';

class Marketplace extends Component {
    componentDidMount() {
        console.log('[ComponentDidMount] Marketplace')
        this.props.showMarketplace();
    }

    render() {
        return (
            <React.Fragment>
                Marketplace
            </React.Fragment>
        );
    }
}

const mapDispatchToProps = dispatch => {
    return {
        showMarketplace: () => dispatch(actions.showMarketplace) //THIS IS THE PROBLEM, IT IS NOT EXECUTING PROPERLY. THIS ONE SHOULD BE
        showMarketplace: () => dispatch(actions.showMarketplace()) //SHOULD BE LIKE THIS.
    };
}

export default connect(null, mapDispatchToProps)(Marketplace);


问:
Why Q.head = Q.tail + 1 represents the queue is full in CLRS
I was reading Elementary Data Structures from CLRS and while reading Queue ADT I came across this:

When  Q.head = Q.tail + 1  , the queue is full, and if we attempt to enqueue an
  element, then the queue overflows.

Is it always true? because if Q.tail equals Q.length then we set Q.tail = 1 according to the text. Therefore if we completely fill the Queue then Q.tail  and Q.head will be pointing to the same position (index 1) and the above condition shall not hold. What am I missing here? Please point out where am I misinterpreting the text. Thanks in advance.

Here Attribute Q.head  indexes, or points to, queue's head. The attribute Q.tail indexes the next location at which a newly arriving element will be inserted into the queue.

答:
It's been been six years but none of these answers point out the fact that in circular buffers, there is no clean way to differentiate the case where the buffer full vs empty cases. In both cases head = tail.

Most workarounds hinder readability and introduce complexities, so when implementing circular buffers, we make a few assumptions that solve this problem and maintain simplicity.

We deliberately use only N-1 elements in the N element buffer.

When head = tail it means the buffer empty.

tail + 1 = head means the buffer full.

Here is a good read on implementing circular buffers.

ContentLicense: CC BY-SA 3.0


问:
How can i disable a checkbox field in woocommerce?
I have added a checkbox field in woocommerce and I want to only view its result on the accounts screen. I have added the checkbox using an example like:

```<code>            'register-checkboxes' => array(
            'type'     => 'checkboxes',
            'label'    => __( 'Regions of Construction', 'woo' ),
            'options'  => array(
                'qld1' => __( 'QLD Zone Q1', 'woo' ),
                'qld2' => __( 'QLD Zone Q2', 'woo' ),
                'qld3' => __( 'QLD Zone Q3', 'woo' ),
            ),
            'hide_in_registration' => true,
            'required' => true,
        ),
</code>```

But when I add:

```<code>$field_args['custom_attributes'] = array( 'disabled' => 'disabled' );
</code>```

On the Account screen this works for disabling Text inputs and selects but not checkbox options.

I am using: https://rudrastyh.com/woocommerce/woocommerce_form_field.html as a guide but it seems you can't pass an array of Custom Attributes to each option of the checkboxes? What am I missing?

答:
Try this jQuery

```<code>jQuery(function($){
   $('#Chekbox_Id_Here').attr('checked', false);
});
</code>```

I hope it's helps you

Thanks.

Body:
I have added a checkbox field in woocommerce and I want to only view its result on the accounts screen. I have added the checkbox using an example like:

            'register-checkboxes' => array(
            'type'     => 'checkboxes',
            'label'    => __( 'Regions of Construction', 'woo' ),
            'options'  => array(
                'qld1' => __( 'QLD Zone Q1', 'woo' ),
                'qld2' => __( 'QLD Zone Q2', 'woo' ),
                'qld3' => __( 'QLD Zone Q3', 'woo' ),
            ),
            'hide_in_registration' => true,
            'required' => true,
        ),

But when I add:

$field_args['custom_attributes'] = array( 'disabled' => 'disabled' );

On the Account screen this works for disabling Text inputs and selects but not checkbox options.

I am using: https://rudrastyh.com/woocommerce/woocommerce_form_field.html as a guide but it seems you can't pass an array of Custom Attributes to each option of the checkboxes? What am I missing?

Body:
Try this jQuery

jQuery(function($){
   $('#Chekbox_Id_Here').attr('checked', false);
});

I hope it's helps you

Thanks.


问:
How can I add space between these logos in list
I want to use social media icons and I'm trying to add space between them. I have then in ul and set each li to a different class. I know there's an easier way to go about this using fontawesome link and icons but I just wanted to see if this way works, I'm a beginner I just started coding 2 weeks ago.

I've tried the light-height and nothing happens:

```

<pre class="lang-css prettyprint-override"><code>.contact1 {
    position: absolute;
    display: flex;
    margin: 0;
    padding: 0;
    top: 50%;
    left: 50%;
    transform: translate(-50%.-50%)
}

 .contact1, .contact2, .contact3, .contact4, .contact5 {
    list-style: none;
    border: none;
    position: relative;
    line-height: 50px;
 }
</code>```

答:
I would recommend simply setting margin-left on every .contact that is not the first.

This can be achieved much easier by giving each element the same class of .contact, and then using the pseudo-selector :not in conjunction with the pseudo-selector :first-of-type. This can be seen in the following:

.contact-container {
  position: absolute;
  display: flex;
  margin: 0;
  padding: 0;
  top: 50%;
  left: 50%;
  transform: translate(-50%.-50%)
}

.contact-container,
.contact {
  list-style: none;
  border: none;
  position: relative;
  line-height: 50px;
}

.contact:not(:first-of-type) {
  margin-left: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="contact-container">
  <li class="contact"><img src="https://placehold.it/100" alt="facebook" class="facebook"> </li>
  <li class="contact"><img src="https://placehold.it/100" alt="twitter" class="twitter"> </li>
  <li class="contact"><img src="https://placehold.it/100" alt="instagram" class="instagram"> </li>
  <li class="contact"><img src="https://placehold.it/100" alt="twitch" class="twitch"> </li>
</ul></code>```

Body:
I want to use social media icons and I'm trying to add space between them. I have then in ul and set each li to a different class. I know there's an easier way to go about this using fontawesome link and icons but I just wanted to see if this way works, I'm a beginner I just started coding 2 weeks ago.

I've tried the light-height and nothing happens:

.contact1 {
    position: absolute;
    display: flex;
    margin: 0;
    padding: 0;
    top: 50%;
    left: 50%;
    transform: translate(-50%.-50%)
}

 .contact1, .contact2, .contact3, .contact4, .contact5 {
    list-style: none;
    border: none;
    position: relative;
    line-height: 50px;
 }

Body:
I would recommend simply setting margin-left on every .contact that is not the first.

This can be achieved much easier by giving each element the same class of .contact, and then using the pseudo-selector :not in conjunction with the pseudo-selector :first-of-type. This can be seen in the following:

.contact-container {
  position: absolute;
  display: flex;
  margin: 0;
  padding: 0;
  top: 50%;
  left: 50%;
  transform: translate(-50%.-50%)
}

.contact-container,
.contact {
  list-style: none;
  border: none;
  position: relative;
  line-height: 50px;
}

.contact:not(:first-of-type) {
  margin-left: 20px;
}

<ul class="contact-container">
  <li class="contact"><img src="https://placehold.it/100" alt="facebook" class="facebook"> </li>
  <li class="contact"><img src="https://placehold.it/100" alt="twitter" class="twitter"> </li>
  <li class="contact"><img src="https://placehold.it/100" alt="instagram" class="instagram"> </li>
  <li class="contact"><img src="https://placehold.it/100" alt="twitch" class="twitch"> </li>
</ul>


问:
Failed to parse MongoDB URI: 'mongodb://'. Invalid host string in URI
While trying to run MongoDB 4.0 with laravel I am getting the following error

PHP Fatal error:  Uncaught MongoDB\Driver\Exception\InvalidArgumentException:
  Failed to parse MongoDB URI: 'mongodb://'. Invalid host string in URI. in /var/www/html/valueableapp/valueable_rest_app/api_src/vendor/mongodb/mongodb/src/Client.php:87`

I used the command mongo to run the mongo shell and it's working fine.
also sudo service mongod status and its also showing the status running.
I am not able to start my project even anyone please. here is the complete stack trace of the issues I am getting
php artisan serve --port=8080

Laravel development server started: http://127.0.0.1:8080
      [Wed May 22 10:00:54 2019] PHP Fatal error:  Uncaught MongoDB\Driver\Exception\InvalidArgumentException: Failed to parse MongoDB URI: 'mongodb://'. Invalid host string in URI. in /var/www/html/valueable-app/valueable_rest_app/api_src/vendor/mongodb/mongodb/src/Client.php:87
      Stack trace:
      #0 /var/www/html/valueable-app/valueable_rest_app/api_src/vendor/mongodb/mongodb/src/Client.php(87): MongoDB\Driver\Manager->__construct('mongodb://', Array, Array)
      #1 /var/www/html/valueable-app/valueable_rest_app/api_src/vendor/jenssegers/mongodb/src/Jenssegers/Mongodb/Connection.php(141): MongoDB\Client->__construct('mongodb://', Array, Array)
      #2 /var/www/html/valueable-app/valueable_rest_app/api_src/vendor/jenssegers/mongodb/src/Jenssegers/Mongodb/Connection.php(41): Jenssegers\Mongodb\Connection->createConnection('mongodb://', Array, Array)
      #3 /var/www/html/valueable-app/valueable_rest_app/api_src/vendor/jenssegers/mongodb/src/Jenssegers/Mongodb/MongodbServiceProvider.php(30): Jenssegers\Mongodb\Connection->__construct(Array)
      #4 [internal function]: Jenssegers\Mongo in /var/www/html/valueable-app/valueable_rest_app/api_src/vendor/mongodb/mongodb/src/Client.php on line 87

Config/database.php

```<code><?php

return [
    'fetch' => PDO::FETCH_CLASS,
    'default'=>'mongodb',
    'connections' => array(

        'mongodb' => array(
            'driver'   => 'mongodb',
            'host'     => env('DB_HOST'),
            'port'     => env('DB_PORT'),
            'username' => env('DB_USERNAME'),
            'password' => env('DB_PASSWORD'),
            'database' => env('DB_DATABASE'),
            'options' => [
                'database' => env('DB_DATABASE')
            ]
        ),

    ),
    'migrations' => 'migrations',
    'redis' => [

        'cluster' => false,

        'default' => [
            'host' => env('REDIS_HOST', 'localhost'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => 0,
        ],

    ],

];
</code>```

.env

```<code>APP_ENV=local
APP_DEBUG=true
APP_KEY=base64:q0DOPnhqUzhmMrqryyyN6SDOi6NHKh/BbmJGHw35e3E=

DB_CONNECTION=mongodb
DB_HOST=localhost
DB_PORT=27017
DB_DATABASE=abc
DB_USERNAME=
DB_PASSWORD=

CACHE_DRIVER=array
SESSION_DRIVER=file
QUEUE_DRIVER=sync

CRITERIA_MAX_SCORE=5
CRITERIA_MIN_SCORE=1
MAX_SCORE_APP=1000
</code>```

Thanks in advance. I have look for the solution on this site

Laravel 5.2 Mongo MonogDB Failed to parse MongoDB URI  but this question is not having answer.

答:
In my case, I just resolved it but changing the name of the file from .env to .env.local.
Thanks.

Body:
While trying to run MongoDB 4.0 with laravel I am getting the following error

PHP Fatal error:  Uncaught MongoDB\Driver\Exception\InvalidArgumentException:
  Failed to parse MongoDB URI: 'mongodb://'. Invalid host string in URI. in /var/www/html/valueableapp/valueable_rest_app/api_src/vendor/mongodb/mongodb/src/Client.php:87`

I used the command mongo to run the mongo shell and it's working fine.
also sudo service mongod status and its also showing the status running.
I am not able to start my project even anyone please. here is the complete stack trace of the issues I am getting
php artisan serve --port=8080

Laravel development server started: http://127.0.0.1:8080
      [Wed May 22 10:00:54 2019] PHP Fatal error:  Uncaught MongoDB\Driver\Exception\InvalidArgumentException: Failed to parse MongoDB URI: 'mongodb://'. Invalid host string in URI. in /var/www/html/valueable-app/valueable_rest_app/api_src/vendor/mongodb/mongodb/src/Client.php:87
      Stack trace:
      #0 /var/www/html/valueable-app/valueable_rest_app/api_src/vendor/mongodb/mongodb/src/Client.php(87): MongoDB\Driver\Manager->__construct('mongodb://', Array, Array)
      #1 /var/www/html/valueable-app/valueable_rest_app/api_src/vendor/jenssegers/mongodb/src/Jenssegers/Mongodb/Connection.php(141): MongoDB\Client->__construct('mongodb://', Array, Array)
      #2 /var/www/html/valueable-app/valueable_rest_app/api_src/vendor/jenssegers/mongodb/src/Jenssegers/Mongodb/Connection.php(41): Jenssegers\Mongodb\Connection->createConnection('mongodb://', Array, Array)
      #3 /var/www/html/valueable-app/valueable_rest_app/api_src/vendor/jenssegers/mongodb/src/Jenssegers/Mongodb/MongodbServiceProvider.php(30): Jenssegers\Mongodb\Connection->__construct(Array)
      #4 [internal function]: Jenssegers\Mongo in /var/www/html/valueable-app/valueable_rest_app/api_src/vendor/mongodb/mongodb/src/Client.php on line 87

Config/database.php

<?php

return [
    'fetch' => PDO::FETCH_CLASS,
    'default'=>'mongodb',
    'connections' => array(

        'mongodb' => array(
            'driver'   => 'mongodb',
            'host'     => env('DB_HOST'),
            'port'     => env('DB_PORT'),
            'username' => env('DB_USERNAME'),
            'password' => env('DB_PASSWORD'),
            'database' => env('DB_DATABASE'),
            'options' => [
                'database' => env('DB_DATABASE')
            ]
        ),

    ),
    'migrations' => 'migrations',
    'redis' => [

        'cluster' => false,

        'default' => [
            'host' => env('REDIS_HOST', 'localhost'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => 0,
        ],

    ],

];

.env

APP_ENV=local
APP_DEBUG=true
APP_KEY=base64:q0DOPnhqUzhmMrqryyyN6SDOi6NHKh/BbmJGHw35e3E=

DB_CONNECTION=mongodb
DB_HOST=localhost
DB_PORT=27017
DB_DATABASE=abc
DB_USERNAME=
DB_PASSWORD=

CACHE_DRIVER=array
SESSION_DRIVER=file
QUEUE_DRIVER=sync

CRITERIA_MAX_SCORE=5
CRITERIA_MIN_SCORE=1
MAX_SCORE_APP=1000

Thanks in advance. I have look for the solution on this site

Laravel 5.2 Mongo MonogDB Failed to parse MongoDB URI  but this question is not having answer.


问:
binary file of the helloworld.go generated by Grumpy does not get generated
I wrote a HelloWorld.py and using grumpy I compiled the HelloWorld.py to a Go source code. but after running go build, the binary file does not get generated, the go build command was executed successfully without any error but there was no binary file found in the folder.

here is the code inside HelloWorld.py:

```<code>def hello():
        print("hello, world")
</code>```

here is the generated code in hello.go:

```<code>package __main__

import πg "grumpy/build/src/grumpy"

var Code *πg.Code

func init() {
    Code = πg.NewCode("<module>", "hello.py", nil, 0, func(πF *πg.Frame, _ []*πg.Object) (*πg.Object, *πg.BaseException) {
        var πR *πg.Object; _ = πR
        var πE *πg.BaseException; _ = πE
        ßhello := πg.InternStr("hello")
        var πTemp001 *πg.Object
        _ = πTemp001
        var πTemp002 []πg.Param
        _ = πTemp002
        for ; πF.State() >= 0; πF.PopCheckpoint() {
            switch πF.State() {
            case 0:
            default: panic("unexpected function state")
            }
            // line 1: def hello(): print "hello, world"
            πF.SetLineno(1)
            πTemp002 = make([]πg.Param, 0)
            πTemp001 = πg.NewFunction(πg.NewCode("hello", "hello.py", πTemp002, 0, func(πF *πg.Frame, πArgs []*πg.Object) (*πg.Object, *πg.BaseException) {
                var πTemp001 []*πg.Object
                _ = πTemp001
                var πR *πg.Object; _ = πR
                var πE *πg.BaseException; _ = πE
                for ; πF.State() >= 0; πF.PopCheckpoint() {
                    switch πF.State() {
                    case 0:
                    default: panic("unexpected function state")
                    }
                    // line 1: def hello(): print "hello, world"
                    πF.SetLineno(1)
                    πTemp001 = make([]*πg.Object, 1)
                    πTemp001[0] = πg.NewStr("hello, world").ToObject()
                    if πE = πg.Print(πF, πTemp001, true); πE != nil {
                        continue
                    }
                }
                if πE != nil {
                    πR = nil
                } else if πR == nil {
                    πR = πg.None
                }
                return πR, πE
            }), πF.Globals()).ToObject()
            if πE = πF.Globals().SetItem(πF, ßhello.ToObject(), πTemp001); πE != nil {
                continue
            }
        }
        return nil, πE
    })
    πg.RegisterModule("__main__", Code)
}
</code>```

when i try to add the main function to the end of the hello.go and call init() like this :

```<code>func main() {
    init()
}
</code>```

i get this error when i run go build

```<code>can't load package: package .:  main.go:1:2: expected 'package', found 'EOF'
</code>```

答:
I know it is an old post but following code in python file may work:

```<code>def hello():
        print("hello, world")
if __name__ == "__main__":
    hello()
</code>```

Now go will create its own main function and is likely to work. (disclaimer: I have not yet tried this myself).

Body:
I wrote a HelloWorld.py and using grumpy I compiled the HelloWorld.py to a Go source code. but after running go build, the binary file does not get generated, the go build command was executed successfully without any error but there was no binary file found in the folder.

here is the code inside HelloWorld.py:

def hello():
        print("hello, world")

here is the generated code in hello.go:

package __main__

import πg "grumpy/build/src/grumpy"

var Code *πg.Code

func init() {
    Code = πg.NewCode("<module>", "hello.py", nil, 0, func(πF *πg.Frame, _ []*πg.Object) (*πg.Object, *πg.BaseException) {
        var πR *πg.Object; _ = πR
        var πE *πg.BaseException; _ = πE
        ßhello := πg.InternStr("hello")
        var πTemp001 *πg.Object
        _ = πTemp001
        var πTemp002 []πg.Param
        _ = πTemp002
        for ; πF.State() >= 0; πF.PopCheckpoint() {
            switch πF.State() {
            case 0:
            default: panic("unexpected function state")
            }
            // line 1: def hello(): print "hello, world"
            πF.SetLineno(1)
            πTemp002 = make([]πg.Param, 0)
            πTemp001 = πg.NewFunction(πg.NewCode("hello", "hello.py", πTemp002, 0, func(πF *πg.Frame, πArgs []*πg.Object) (*πg.Object, *πg.BaseException) {
                var πTemp001 []*πg.Object
                _ = πTemp001
                var πR *πg.Object; _ = πR
                var πE *πg.BaseException; _ = πE
                for ; πF.State() >= 0; πF.PopCheckpoint() {
                    switch πF.State() {
                    case 0:
                    default: panic("unexpected function state")
                    }
                    // line 1: def hello(): print "hello, world"
                    πF.SetLineno(1)
                    πTemp001 = make([]*πg.Object, 1)
                    πTemp001[0] = πg.NewStr("hello, world").ToObject()
                    if πE = πg.Print(πF, πTemp001, true); πE != nil {
                        continue
                    }
                }
                if πE != nil {
                    πR = nil
                } else if πR == nil {
                    πR = πg.None
                }
                return πR, πE
            }), πF.Globals()).ToObject()
            if πE = πF.Globals().SetItem(πF, ßhello.ToObject(), πTemp001); πE != nil {
                continue
            }
        }
        return nil, πE
    })
    πg.RegisterModule("__main__", Code)
}

when i try to add the main function to the end of the hello.go and call init() like this :

func main() {
    init()
}

i get this error when i run go build

can't load package: package .:  main.go:1:2: expected 'package', found 'EOF'

Body:
I know it is an old post but following code in python file may work:

def hello():
        print("hello, world")
if __name__ == "__main__":
    hello()

Now go will create its own main function and is likely to work. (disclaimer: I have not yet tried this myself).


问:
What difference between throttleLatest and throttleLast in rxjava?
In Observable, there are two methods called throttleLast and throttleLatest.

throttleLast javadoc

throttleLatest javadoc

Marble diagrams are similar, but the two internal codes are different.

public final Observable<T> throttleLast(long intervalDuration, TimeUnit unit) {
    return sample(intervalDuration, unit);
}

public final Observable<T> sample(long period, TimeUnit unit, Scheduler scheduler, boolean emitLast) {
    ObjectHelper.requireNonNull(unit, "unit is null");
    ObjectHelper.requireNonNull(scheduler, "scheduler is null");
    return RxJavaPlugins.onAssembly(new ObservableSampleTimed<T>(this, period, unit, scheduler, emitLast));
}
```

<pre class="lang-java prettyprint-override"><code>public final Observable<T> throttleLatest(long timeout, TimeUnit unit, Scheduler scheduler, boolean emitLast) {
    ObjectHelper.requireNonNull(unit, "unit is null");
    ObjectHelper.requireNonNull(scheduler, "scheduler is null");
    return RxJavaPlugins.onAssembly(new ObservableThrottleLatest<T>(this, timeout, unit, scheduler, emitLast));
}
</code>```

What difference between them?

答:
See comments of @Slaw and @akarnokd.

Not positive, but throttleLast might operate on fixed time intervals and throttleLatest resets the timeout whenever an item arrives. In other words, the difference between fixed rate and fixed delay.

And

It's in the javadoc: throttleLatest "If no items were emitted from the upstream during this timeout phase, the next upstream item is emitted immediately and the timeout window starts from then.". ThrottleLast emits at a fixed rate and if there is no item, nothing is emitted.

I did not understand well, so I tried to compare myself.

sample code

Body:
In Observable, there are two methods called throttleLast and throttleLatest.

throttleLast javadoc

throttleLatest javadoc

Marble diagrams are similar, but the two internal codes are different.

public final Observable<T> throttleLast(long intervalDuration, TimeUnit unit) {
    return sample(intervalDuration, unit);
}

public final Observable<T> sample(long period, TimeUnit unit, Scheduler scheduler, boolean emitLast) {
    ObjectHelper.requireNonNull(unit, "unit is null");
    ObjectHelper.requireNonNull(scheduler, "scheduler is null");
    return RxJavaPlugins.onAssembly(new ObservableSampleTimed<T>(this, period, unit, scheduler, emitLast));
}

public final Observable<T> throttleLatest(long timeout, TimeUnit unit, Scheduler scheduler, boolean emitLast) {
    ObjectHelper.requireNonNull(unit, "unit is null");
    ObjectHelper.requireNonNull(scheduler, "scheduler is null");
    return RxJavaPlugins.onAssembly(new ObservableThrottleLatest<T>(this, timeout, unit, scheduler, emitLast));
}

What difference between them?


问:
ValueError at /accounts/profile/ The 'image' attribute has no file associated with it
This error occurs when a user is either not a superuser or doesn't have a profile image (submitted via userprofile in admin).

ValueError at /accounts/profile/
The 'image' attribute has no file associated with it.
Request Method: GET
Request URL:    http://127.0.0.1:8000/accounts/profile/

Error during template rendering

```<code>In template /Users/joseph/Documents/django/tutorial/accounts/templates/base.html, error at line 17
The 'image' attribute has no file associated with it.
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

9     <meta charset="utf-8">
10    <html lang="en" dir="ltr">
11
12  <!-- Navigation bar -->
13
14    <br>
15    <nav class="navbar navbar-expand-lg navbar-green bg-light">
16    <a class="navbar-brand" href="/accounts/home">MySite</a>
17    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
18      <span class="navbar-toggler-icon"></span>
19    </button>
20        {% if user.is_authenticated %}
21    <div class="collapse navbar-collapse" id="navbarNav">
22      <ul class="nav navbar-nav ml-auto">
23        <li class="nav-item">
24          <a class="nav-link"   href="/accounts/explore/">Explore</a>
25        </li>
26        </ul>
27      <ul class="nav navbar-nav ml-auto">
</code>```

models.py:

```<code>class UserProfile(models.Model):
   user = models.OneToOneField(User, models.CASCADE)
   description = models.CharField(max_length=100, blank=True, default='')
   city = models.CharField(max_length=100, blank=True, default='')
   website = models.URLField(blank=True, default='')
   contactNumber = models.IntegerField(blank=True, default=0)
   image = models.ImageField(upload_to='profile_image', blank=True)

def __str__(self):
    return self.user.username
</code>```

Why does this happen? It can't actually be base.html(extended)? If there is anything else that needs adding to help solve the problem, please let me know .Thanks

答:
You could add a 'null=True' to ImageField().
Also, check if the image has been successfully uploaded in the admin. If it has, try reuploading the image and retry.</p>

Body:
This error occurs when a user is either not a superuser or doesn't have a profile image (submitted via userprofile in admin).

ValueError at /accounts/profile/
The 'image' attribute has no file associated with it.
Request Method: GET
Request URL:    http://127.0.0.1:8000/accounts/profile/

Error during template rendering

In template /Users/joseph/Documents/django/tutorial/accounts/templates/base.html, error at line 17
The 'image' attribute has no file associated with it.
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

9     <meta charset="utf-8">
10
11
12
13
14

15
16    MySite
17    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
18
19    </button>
20        {% if user.is_authenticated %}
21

22

23

24          Explore
25

26

27

models.py:

class UserProfile(models.Model):
   user = models.OneToOneField(User, models.CASCADE)
   description = models.CharField(max_length=100, blank=True, default='')
   city = models.CharField(max_length=100, blank=True, default='')
   website = models.URLField(blank=True, default='')
   contactNumber = models.IntegerField(blank=True, default=0)
   image = models.ImageField(upload_to='profile_image', blank=True)

def __str__(self):
    return self.user.username

Why does this happen? It can't actually be base.html(extended)? If there is anything else that needs adding to help solve the problem, please let me know .Thanks


问:
Selecting default item from Combobox C#
I have few items on my ComboBox items collection, and i'd like to select one item from this list and set it as default item - when app starts - this item is already on comboBox.

I'm trying something like that:

```<code>SelectPrint11.SelectedIndex=2;
</code>```

but error is:

```<code>System.ArgumentOutOfRangeException: InvalidArgument=Value of '2' is not valid for 'SelectedIndex'
</code>```

Edit:

In mylist are 3 items, Printer1, Printer2, Printer3. All are added in ComboBox Properties -> Items -> Collection

答: Remember that collections in C# are zero-based (in other words, the first item in a collection is at position zero). If you have two items in your list, and you want to select the last item, use SelectedIndex = 1.

Title: Selecting default item from Combobox C#

Body:
I have few items on my ComboBox items collection, and i'd like to select one item from this list and set it as default item - when app starts - this item is already on comboBox.

I'm trying something like that:

SelectPrint11.SelectedIndex=2;

but error is:

System.ArgumentOutOfRangeException: InvalidArgument=Value of '2' is not valid for 'SelectedIndex'

Edit:

In mylist are 3 items, Printer1, Printer2, Printer3. All are added in ComboBox Properties -> Items -> Collection


问:
How to convert this SQL Query on Code Igniter Model php code Igniter
```<code>SELECT mahasiswa.nama,
(select dosen.nama_dosen from mahasiswa,dosen
where mahasiswa.id_mahasiswa ='MH000004' and mahasiswa.pembimbing_1 = dosen.id_dosen)
as pembimbing_pertama,
(select dosen.nama_dosen from mahasiswa,dosen
where mahasiswa.id_mahasiswa ='MH000004' and mahasiswa.pembimbing_2 = dosen.id_dosen)
as pembimbing_kedua
FROM mahasiswa where mahasiswa.id_mahasiswa ='MH000004'
</code>```

答:
Try this,</p>

```<code>$mahasiswa = 'MH000004';
$this->db->select("SELECT mahasiswa.nama,
(select dosen.nama_dosen from mahasiswa,dosen
where mahasiswa.id_mahasiswa ='".$mahasiswa."' and mahasiswa.pembimbing_1 = dosen.id_dosen)
as pembimbing_pertama,
(select dosen.nama_dosen from mahasiswa,dosen
where mahasiswa.id_mahasiswa ='".$mahasiswa."' and mahasiswa.pembimbing_2 = dosen.id_dosen)
as pembimbing_kedua");
$this->db->from('mahasiswa');
$this->db->where('mahasiswa.id_mahasiswa', $mahasiswa);
$query = $this->db->get();
if ($query->num_rows() > 0) {
    return $query->result();//or row();
} else {
    return array();
}
</code>```

Body:
Try this,

$mahasiswa = 'MH000004';
$this->db->select("SELECT mahasiswa.nama,
(select dosen.nama_dosen from mahasiswa,dosen
where mahasiswa.id_mahasiswa ='".$mahasiswa."' and mahasiswa.pembimbing_1 = dosen.id_dosen)
as pembimbing_pertama,
(select dosen.nama_dosen from mahasiswa,dosen
where mahasiswa.id_mahasiswa ='".$mahasiswa."' and mahasiswa.pembimbing_2 = dosen.id_dosen)
as pembimbing_kedua");
$this->db->from('mahasiswa');
$this->db->where('mahasiswa.id_mahasiswa', $mahasiswa);
$query = $this->db->get();
if ($query->num_rows() > 0) {
    return $query->result();//or row();
} else {
    return array();
}


答:
If you just want to add space, you can do it using flex box justify-content:space-around

 and I edited your transform: translate(-50%, -50%); in .contact1
see this snippet below

.contact1 {
    position: absolute;
    display: flex;
    justify-content:space-around;
    margin: 0;
    padding: 0;
    top: 50%;
    left: 50%;
    transform: translate(-50% , -50%);
}

 .contact1, .contact2, .contact3, .contact4, .contact5 {
    list-style: none;
    border: none;
    position: relative;
    line-height: 50px;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container2">
        <ul class="contact1">
            <li class="contact2"><img src="facebook.png" alt="facebook" class="facebook"> </li>
            <li class="contact3"><img src="twitter.png" alt="twitter" class="twitter"> </li>
            <li class="contact4"><img src="instagram.png" alt="instagram" class="instagram"> </li>
            <li class="contact5"><img src="twitch.png" alt="twitch" class="twitch"> </li>
        </ul>
    </div></code>```

Title: How can I add space between these logos in list

Body:
If you just want to add space, you can do it using flex box justify-content:space-around

 and I edited your transform: translate(-50%, -50%); in .contact1
see this snippet below

.contact1 {
    position: absolute;
    display: flex;
    justify-content:space-around;
    margin: 0;
    padding: 0;
    top: 50%;
    left: 50%;
    transform: translate(-50% , -50%);
}

 .contact1, .contact2, .contact3, .contact4, .contact5 {
    list-style: none;
    border: none;
    position: relative;
    line-height: 50px;
 }

<div class="container2">
        <ul class="contact1">
            <li class="contact2"><img src="facebook.png" alt="facebook" class="facebook"> </li>
            <li class="contact3"><img src="twitter.png" alt="twitter" class="twitter"> </li>
            <li class="contact4"><img src="instagram.png" alt="instagram" class="instagram"> </li>
            <li class="contact5"><img src="twitch.png" alt="twitch" class="twitch"> </li>
        </ul>
    </div>


问:
How to reduce points in a list around a specific point?
I have no idea how to explain this concept, as if I did I probably would have found the answer on Google already.

What I'm trying to do is take a list of y points and reduce all values above and below a specific chosen point. Could be in the middle of the graph, could be at the beginning, etc.

This is easier with a picture. Here's a visualization of what I want to do.

You can see the point I chose to "reduce" the points around it.

I wrote this overly complicated function to do exactly that:

```<code>import numpy as np
x = [0.0, 4.8, 9.0, 11.3, 13.6, 17.1, 23.1, 29.5, 35.1, 39.8, 42.2]
y = [1.35, 1.36, 1.39, 1.43, 1.46, 1.48, 1.49, 1.53, 1.59, 1.68, 1.8]

squash_around = 1.43
squash_min = min([i-squash_around for i in y])
squash_max = max([i-squash_around for i in y])
y = [np.interp(i-squash_around, [squash_min, 0, squash_max], [.9, 1.0, 1.1])*i for i in y]
</code>```

However, it fails to work correctly with some data, for example I set squash_around to .2, so it should modify all points except the top left, but it doesn't:

If anyone can point me to the probable duplicate question for this, that'd be great.

答:
It seems like what you're trying to "reduce" is the difference in y-value between the point of interest (i.e. the circled one), and each other point's y-value.

If we let (x, y) be the point that you want to "reduce" around, then we can "reduce" another point (x1, y1) relative to (x, y) by a factor of a with the following transformation

```<code>(x1, y1) => (x1, y + (y1 - y) * a)
</code>```

If 0 < a < 1 then (x, y) stays exactly where it is, points below y move up towards it, and points above y move down towards it. Putting this into numpy code

```<code>import numpy as np
x = np.array([0.0, 4.8, 9.0, 11.3, 13.6, 17.1, 23.1, 29.5, 35.1, 39.8, 42.2])
y = np.array([1.35, 1.36, 1.39, 1.43, 1.46, 1.48, 1.49, 1.53, 1.59, 1.68, 1.8])

i = 5   # the index of the point to "reduce" around
a = 0.5 # reduction factor

reduced = y[i] + (y - y[i]) * a

# plt.plot(x, y)
# plt.plot(x, reduced)
</code>```

Is that the kind of reduction that you are looking for?

Body:
I have no idea how to explain this concept, as if I did I probably would have found the answer on Google already.

What I'm trying to do is take a list of y points and reduce all values above and below a specific chosen point. Could be in the middle of the graph, could be at the beginning, etc.

This is easier with a picture. Here's a visualization of what I want to do.

You can see the point I chose to "reduce" the points around it.

I wrote this overly complicated function to do exactly that:

import numpy as np
x = [0.0, 4.8, 9.0, 11.3, 13.6, 17.1, 23.1, 29.5, 35.1, 39.8, 42.2]
y = [1.35, 1.36, 1.39, 1.43, 1.46, 1.48, 1.49, 1.53, 1.59, 1.68, 1.8]

squash_around = 1.43
squash_min = min([i-squash_around for i in y])
squash_max = max([i-squash_around for i in y])
y = [np.interp(i-squash_around, [squash_min, 0, squash_max], [.9, 1.0, 1.1])*i for i in y]

However, it fails to work correctly with some data, for example I set squash_around to .2, so it should modify all points except the top left, but it doesn't:

If anyone can point me to the probable duplicate question for this, that'd be great.

Body:
It seems like what you're trying to "reduce" is the difference in y-value between the point of interest (i.e. the circled one), and each other point's y-value.

If we let (x, y) be the point that you want to "reduce" around, then we can "reduce" another point (x1, y1) relative to (x, y) by a factor of a with the following transformation

(x1, y1) => (x1, y + (y1 - y) * a)

If 0 < a < 1 then (x, y) stays exactly where it is, points below y move up towards it, and points above y move down towards it. Putting this into numpy code

import numpy as np
x = np.array([0.0, 4.8, 9.0, 11.3, 13.6, 17.1, 23.1, 29.5, 35.1, 39.8, 42.2])
y = np.array([1.35, 1.36, 1.39, 1.43, 1.46, 1.48, 1.49, 1.53, 1.59, 1.68, 1.8])

i = 5   # the index of the point to "reduce" around
a = 0.5 # reduction factor

reduced = y[i] + (y - y[i]) * a

# plt.plot(x, y)
# plt.plot(x, reduced)

Is that the kind of reduction that you are looking for?


问:
Regex segmentation fault
I have a regex that fires segmentation fault error.
After some tests I noticed that [\s\S]*\s+ part of regex is making problems if string is larger than 15 KB, so sometimes it works but sometimes it crashes.

Here is the C++ code compiled with g++ (gcc v. 6.3.0)

```<code>#include <regex>
#include <fstream>
#include <string>
#include <iostream>

int main (int argc, char *argv[]) {

    std::regex regex(
            R"([\s\S]*\s+)",
            std::regex_constants::icase
    );

    std::ifstream ifs("/home/input.txt");
    const std::string input(
            (std::istreambuf_iterator<char>(ifs)),
            (std::istreambuf_iterator<char>())
            );

    std::cout << "input size: " << input.size() << std::endl;

    bool reg_match = std::regex_match(input, regex);

    std::cout << "matched: " << reg_match << std::endl;

}
</code>```

What is going on, why is it happening with such pattern and why is it affected by input size?

UPDATE:

Error produced by running binary when compiled with -fsanitize=address:

g++ -std=c++11 /home/app/src/test.cpp -o /home/app/bin/test -fsanitize=address

```<code>ASAN:DEADLYSIGNAL
=================================================================
==37041==ERROR: AddressSanitizer: stack-overflow on address 0x7ffbff8edff8 (pc 0x55afae25781b bp 0x7ffbff8ee010 sp 0x7ffbff8edff0 T0)
    #0 0x55afae25781a in bool __gnu_cxx::operator==<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >(__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > const&, __gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > const&) (/home/app/bin/test+0x1981a)
    #1 0x55afae2587bd in std::__detail::_Executor<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::__cxx11::sub_match<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, std::__cxx11::regex_traits<char>, true>::_M_dfs(std::__detail::_Executor<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::__cxx11::sub_match<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, std::__cxx11::regex_traits<char>, true>::_Match_mode, long) (/home/app/bin/test+0x1a7bd)
    #2 0x55afae25e2d2 in std::__detail::_Executor<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::__cxx11::sub_match<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, std::__cxx11::regex_traits<char>, true>::_M_rep_once_more(std::__detail::_Executor<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::__cxx11::sub_match<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, std::__cxx11::regex_traits<char>, true>::_Match_mode, long) (/home/app/bin/test+0x202d2)
.
.
.
 #251 0x55afae25e2d2 in std::__detail::_Executor<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::__cxx11::sub_match<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, std::__cxx11::regex_traits<char>, true>::_M_rep_once_more(std::__detail::_Executor<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::__cxx11::sub_match<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, std::__cxx11::regex_traits<char>, true>::_Match_mode, long) (/home/app/bin/test+0x202d2)

SUMMARY: AddressSanitizer: stack-overflow (/home/app/bin/test) in std::__detail::_Executor<__gnu_cxx::__normal_iterator<char const*, std:__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::__cxx11::sub_match<__gnu_cxx::__normal_iterator<char const*,std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, std::__cxx11::regex_traits<char>, true>::_M_dfs(std::__detail::_Executo<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::__cxx11::submatch<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, std::__cxx11::regex_trats<char>, true>::_Match_mode, long)
    ==37017==ABORTING
</code>```

答:
I don't have a full answer but for some reason there is a stack overflow happening while matching your regular expression. This is usually caused either by too much data on the stack or by too many levels of recursion. Looking at your program I don't see any large objects on the stack (the string object on the stack is small since it's data is on the heap). However, the state machines used for regex parsing are known for making many recursive function calls (this goes together with your long Address Sanitizer output). You have a couple of options (I would try them in this order):

Ensure you are compiling with an appropriate level of optimization. At higher levels of optimization compilers often push less frames on the stack (see "tail call optimization").

Try passing std::regex_constants::optimize to encourage the regex code to take more time for optimizing while constructing the state machine for regex processing.

Rethink your regex. Maybe you can simplify it in a way that results in a simpler state machine working with less levels of recursion? The [\s\S]* part looks a little unconventional.

Modify your program to process input data in smaller chunks, e.g. line by line.

Increase your stack size. On POSIX systems you can do so by calling ulimit -s <stack size in kB> before you run your program.

Consider compiling your program with automatically growing stacks (-fsplit-stacks). Note that this comes at the cost of some performance.

Title: Regex segmentation fault

Body:
I have a regex that fires segmentation fault error.
After some tests I noticed that [\s\S]*\s+ part of regex is making problems if string is larger than 15 KB, so sometimes it works but sometimes it crashes.

Here is the C++ code compiled with g++ (gcc v. 6.3.0)

#include <regex>
#include <fstream>
#include <string>
#include <iostream>

int main (int argc, char *argv[]) {

    std::regex regex(
            R"([\s\S]*\s+)",
            std::regex_constants::icase
    );

    std::ifstream ifs("/home/input.txt");
    const std::string input(
            (std::istreambuf_iterator<char>(ifs)),
            (std::istreambuf_iterator<char>())
            );

    std::cout << "input size: " << input.size() << std::endl;

    bool reg_match = std::regex_match(input, regex);

    std::cout << "matched: " << reg_match << std::endl;

}

What is going on, why is it happening with such pattern and why is it affected by input size?

UPDATE:

Error produced by running binary when compiled with -fsanitize=address:

g++ -std=c++11 /home/app/src/test.cpp -o /home/app/bin/test -fsanitize=address

ASAN:DEADLYSIGNAL
=================================================================
==37041==ERROR: AddressSanitizer: stack-overflow on address 0x7ffbff8edff8 (pc 0x55afae25781b bp 0x7ffbff8ee010 sp 0x7ffbff8edff0 T0)
    #0 0x55afae25781a in bool __gnu_cxx::operator==<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >(__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > const&, __gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > const&) (/home/app/bin/test+0x1981a)
    #1 0x55afae2587bd in std::__detail::_Executor<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::__cxx11::sub_match<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, std::__cxx11::regex_traits<char>, true>::_M_dfs(std::__detail::_Executor<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::__cxx11::sub_match<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, std::__cxx11::regex_traits<char>, true>::_Match_mode, long) (/home/app/bin/test+0x1a7bd)
    #2 0x55afae25e2d2 in std::__detail::_Executor<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::__cxx11::sub_match<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, std::__cxx11::regex_traits<char>, true>::_M_rep_once_more(std::__detail::_Executor<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::__cxx11::sub_match<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, std::__cxx11::regex_traits<char>, true>::_Match_mode, long) (/home/app/bin/test+0x202d2)
.
.
.
 #251 0x55afae25e2d2 in std::__detail::_Executor<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::__cxx11::sub_match<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, std::__cxx11::regex_traits<char>, true>::_M_rep_once_more(std::__detail::_Executor<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::__cxx11::sub_match<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, std::__cxx11::regex_traits<char>, true>::_Match_mode, long) (/home/app/bin/test+0x202d2)

SUMMARY: AddressSanitizer: stack-overflow (/home/app/bin/test) in std::__detail::_Executor<__gnu_cxx::__normal_iterator<char const*, std:__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::__cxx11::sub_match<__gnu_cxx::__normal_iterator<char const*,std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, std::__cxx11::regex_traits<char>, true>::_M_dfs(std::__detail::_Executo<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::__cxx11::submatch<__gnu_cxx::__normal_iterator<char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, std::__cxx11::regex_trats<char>, true>::_Match_mode, long)
    ==37017==ABORTING


问:
Promises, rejections, and errors - Trying to found a solution for highly cadenced async operations
First, I apologize for a rudimentary question but I have spent days reading on Async functions and have yet to find a solution or gain understanding. I promise if I get help I'll pay it forward later here.

I have a set of operations, or tasks, that I am supposed to execute one at a time. Task one is to run, then task two, then task three.

The problem is this:

For all tasks execute a random number, x, of write operations to a folder. Each task is to be done until completion and then move to the next task.

Task 1:
Log to the console when you start to write the file Task1_1. When the file is done writing, log 'Finished writing Task1_1'. Move to Task1_1+1 until reach Task1_X.

Task 2:
Write all tasks at the same "time". Finish writing all files before you move to the next task.

Task 3:
30% of the Files are to be written to a bad path. If it is written to a bad path, write "Failed to write File Task3_X" otherwise follow the same pattern as task 1.

I have tried to use Async and await, I have tried traditional callbacks. I am most comfortable with promises but I am clearly missing a key conceptual understanding of what is happening (if this bothers you... I am sorry.. people have been kind harsh about my level on here.. just trying to learn).

```<code>function writeFileAsync(directory, file){
    return new Promise( (resolve,reject) => {
        console.log(`Writing File ${file}`)
        fs.writeFile(path.join(directory,file), 'this is a file', (err) => {
            if(err){
                reject(err)
            } else{
                resolve()
            }
        })
    })
}

function taskOne(x, location){
    return new Promise(resolve => {
        console.log('** Starting task taskOne **')
        let i = 1;
        while(i <= x){
            let name = `taskOne_${i}`;
            writeFileAsync(location,name)
            .then(logCompletion(name))
            .then(i++)
        }
        console.log('** Finished with taskOne **')
    })
}

function taskTwo(x, location){
    return new Promise(resolve => {
        console.log('** Starting task taskTwo **')
        let i = 1;
        while(i <= x){
            let name = `taskTwo_${i}`;
                writeFileAsync(location, name)
                .then((success) => logCompletion(name))
                .then(i++)
        }
        console.log(`** Finished with taskTwo **`)
    })
}

function taskThree(x, location){
    return new Promise( resolve => {
        console.log('** Starting task taskThree **')
        const badPath = path.join(__dirname,`/notHome`);
        const randomlyDelayedIndex = Math.floor(Math.random()*Math.floor(x+1)+1);
        const isItGoodOrBad = () => {
            let chance =  Math.floor(Math.random()*Math.floor(10)+1)
            return chance < 7 ? true : false
        }
        let i = 1;
        while(i <= x){
            let name = `taskThree_${i}`;
            let directionIsGood = isItGoodOrBad();
            if(directionIsGood){
                debugger
                writeFileAsync(location, name)
                .then(logCompletion(name))
                .then(i++)
            } else{
                writeFileAsync(badPath, name)
                .then((success)=> logCompletion(name))
                .catch((err) => console.log(`Failed to write ${name}`))
                .then(i++)
            }
        }
        console.log(`** Finished with taskThree **`)
    })
}

function main(){
    const folderName = String(Date.now());
    const x = Number(folderName.slice(-1));
    const location = path.join(__dirname,folderName);
    fs.mkdir(location, ()=> {});
    return taskOne(7, location)
    .then(taskTwo(7,location))
    .then(taskThree(7,location))
}

main();
</code>```

I expect (might change cadence depending on randomness):

```<code>Starting Task1
Writing Task1_1
Finished Task1_1
Writing Task1_2
Finished Task1_2
etc....
Finished with Task1

Starting Task2
Writing Task2_1
Writing Task2_2
Writing Task2_2
etc...
Finished Task2_1
Finished Task2_2
Finished Task2_3
etc...
Finished with Task2

Starting Task3
Writing Task3_1
Failed to Write Task3_1
Writing Task3_2
Finished Writing Task3_2
Writing Task3_3
Finished Writing Task3_3
Finished Task3
</code>```

What I am getting is something like this:

```<code>** Starting task taskOne **
Writing File taskOne_1
Finished Writing file taskOne_1
Writing File taskOne_2
Finished Writing file taskOne_2
Writing File taskOne_3
Finished Writing file taskOne_3
Writing File taskOne_4
Finished Writing file taskOne_4
Writing File taskOne_5
Finished Writing file taskOne_5
Writing File taskOne_6
Finished Writing file taskOne_6
Writing File taskOne_7
Finished Writing file taskOne_7
** Finished with taskOne **
** Starting task taskTwo **
Writing File taskTwo_1
Writing File taskTwo_2
Writing File taskTwo_3
Writing File taskTwo_4
Writing File taskTwo_5
Writing File taskTwo_6
Writing File taskTwo_7
** Finished with taskTwo **
** Starting task taskThree **
Writing File taskThree_1
Finished Writing file taskThree_1
Writing File taskThree_2
Writing File taskThree_3
Writing File taskThree_4
Finished Writing file taskThree_4
Writing File taskThree_5
Finished Writing file taskThree_5
Writing File taskThree_6
Writing File taskThree_7
Finished Writing file taskThree_7
** Finished with taskThree **
Failed to write taskThree_2
Failed to write taskThree_3
Failed to write taskThree_6
Finished Writing file taskTwo_1
Finished Writing file taskTwo_2
Finished Writing file taskTwo_3
Finished Writing file taskTwo_6
Finished Writing file taskTwo_7
Finished Writing file taskTwo_4
</code>```

答:
You are mixing synchrouous and async code. You can rewrite, for example, your taskOne as the following:

```<code>const writeFileAsync = () => {
   return Promise.resolve();
};

const logCompletion = (n) => {
   console.log(n);
   return Promise.resolve();
};

async function taskOne(x, location){
        console.log('** Starting task taskOne **')
        let i = 1;
        while(i <= x){
            let name = `taskOne_${i}`;
            await writeFileAsync(location,name)
            .then(logCompletion(name))
            .then(i++)
        }
        console.log('** Finished! with taskOne **')
}

async function taskTwo(x, location){
        console.log('** Starting task taskTwo **')
        let i = 1;
        while(i <= x){
            let name = `taskTwo_${i}`;
            await writeFileAsync(location,name)
            .then(logCompletion(name))
            .then(i++)
        }
        console.log('** Finished with taskTwo **')
}

taskOne(12).then(() => taskTwo(12));

</code>```

You can check out an example here: https://codepen.io/anon/pen/KLBwby

You should be able to figure out the rest, I think.

Body:
First, I apologize for a rudimentary question but I have spent days reading on Async functions and have yet to find a solution or gain understanding. I promise if I get help I'll pay it forward later here.

I have a set of operations, or tasks, that I am supposed to execute one at a time. Task one is to run, then task two, then task three.

The problem is this:

For all tasks execute a random number, x, of write operations to a folder. Each task is to be done until completion and then move to the next task.

Task 1:
Log to the console when you start to write the file Task1_1. When the file is done writing, log 'Finished writing Task1_1'. Move to Task1_1+1 until reach Task1_X.

Task 2:
Write all tasks at the same "time". Finish writing all files before you move to the next task.

Task 3:
30% of the Files are to be written to a bad path. If it is written to a bad path, write "Failed to write File Task3_X" otherwise follow the same pattern as task 1.

I have tried to use Async and await, I have tried traditional callbacks. I am most comfortable with promises but I am clearly missing a key conceptual understanding of what is happening (if this bothers you... I am sorry.. people have been kind harsh about my level on here.. just trying to learn).

function writeFileAsync(directory, file){
    return new Promise( (resolve,reject) => {
        console.log(`Writing File ${file}`)
        fs.writeFile(path.join(directory,file), 'this is a file', (err) => {
            if(err){
                reject(err)
            } else{
                resolve()
            }
        })
    })
}

function taskOne(x, location){
    return new Promise(resolve => {
        console.log('** Starting task taskOne **')
        let i = 1;
        while(i <= x){
            let name = `taskOne_${i}`;
            writeFileAsync(location,name)
            .then(logCompletion(name))
            .then(i++)
        }
        console.log('** Finished with taskOne **')
    })
}

function taskTwo(x, location){
    return new Promise(resolve => {
        console.log('** Starting task taskTwo **')
        let i = 1;
        while(i <= x){
            let name = `taskTwo_${i}`;
                writeFileAsync(location, name)
                .then((success) => logCompletion(name))
                .then(i++)
        }
        console.log(`** Finished with taskTwo **`)
    })
}

function taskThree(x, location){
    return new Promise( resolve => {
        console.log('** Starting task taskThree **')
        const badPath = path.join(__dirname,`/notHome`);
        const randomlyDelayedIndex = Math.floor(Math.random()*Math.floor(x+1)+1);
        const isItGoodOrBad = () => {
            let chance =  Math.floor(Math.random()*Math.floor(10)+1)
            return chance < 7 ? true : false
        }
        let i = 1;
        while(i <= x){
            let name = `taskThree_${i}`;
            let directionIsGood = isItGoodOrBad();
            if(directionIsGood){
                debugger
                writeFileAsync(location, name)
                .then(logCompletion(name))
                .then(i++)
            } else{
                writeFileAsync(badPath, name)
                .then((success)=> logCompletion(name))
                .catch((err) => console.log(`Failed to write ${name}`))
                .then(i++)
            }
        }
        console.log(`** Finished with taskThree **`)
    })
}

function main(){
    const folderName = String(Date.now());
    const x = Number(folderName.slice(-1));
    const location = path.join(__dirname,folderName);
    fs.mkdir(location, ()=> {});
    return taskOne(7, location)
    .then(taskTwo(7,location))
    .then(taskThree(7,location))
}

main();

I expect (might change cadence depending on randomness):

Starting Task1
Writing Task1_1
Finished Task1_1
Writing Task1_2
Finished Task1_2
etc....
Finished with Task1

Starting Task2
Writing Task2_1
Writing Task2_2
Writing Task2_2
etc...
Finished Task2_1
Finished Task2_2
Finished Task2_3
etc...
Finished with Task2

Starting Task3
Writing Task3_1
Failed to Write Task3_1
Writing Task3_2
Finished Writing Task3_2
Writing Task3_3
Finished Writing Task3_3
Finished Task3

What I am getting is something like this:

** Starting task taskOne **
Writing File taskOne_1
Finished Writing file taskOne_1
Writing File taskOne_2
Finished Writing file taskOne_2
Writing File taskOne_3
Finished Writing file taskOne_3
Writing File taskOne_4
Finished Writing file taskOne_4
Writing File taskOne_5
Finished Writing file taskOne_5
Writing File taskOne_6
Finished Writing file taskOne_6
Writing File taskOne_7
Finished Writing file taskOne_7
** Finished with taskOne **
** Starting task taskTwo **
Writing File taskTwo_1
Writing File taskTwo_2
Writing File taskTwo_3
Writing File taskTwo_4
Writing File taskTwo_5
Writing File taskTwo_6
Writing File taskTwo_7
** Finished with taskTwo **
** Starting task taskThree **
Writing File taskThree_1
Finished Writing file taskThree_1
Writing File taskThree_2
Writing File taskThree_3
Writing File taskThree_4
Finished Writing file taskThree_4
Writing File taskThree_5
Finished Writing file taskThree_5
Writing File taskThree_6
Writing File taskThree_7
Finished Writing file taskThree_7
** Finished with taskThree **
Failed to write taskThree_2
Failed to write taskThree_3
Failed to write taskThree_6
Finished Writing file taskTwo_1
Finished Writing file taskTwo_2
Finished Writing file taskTwo_3
Finished Writing file taskTwo_6
Finished Writing file taskTwo_7
Finished Writing file taskTwo_4

Body:
You are mixing synchrouous and async code. You can rewrite, for example, your taskOne as the following:

const writeFileAsync = () => {
   return Promise.resolve();
};

const logCompletion = (n) => {
   console.log(n);
   return Promise.resolve();
};

async function taskOne(x, location){
        console.log('** Starting task taskOne **')
        let i = 1;
        while(i <= x){
            let name = `taskOne_${i}`;
            await writeFileAsync(location,name)
            .then(logCompletion(name))
            .then(i++)
        }
        console.log('** Finished! with taskOne **')
}

async function taskTwo(x, location){
        console.log('** Starting task taskTwo **')
        let i = 1;
        while(i <= x){
            let name = `taskTwo_${i}`;
            await writeFileAsync(location,name)
            .then(logCompletion(name))
            .then(i++)
        }
        console.log('** Finished with taskTwo **')
}

taskOne(12).then(() => taskTwo(12));

You can check out an example here: https://codepen.io/anon/pen/KLBwby

You should be able to figure out the rest, I think.


问:
What are the benefits of using a sigmoid function?
I am dipping my toe into neural networks and starting with some basic perceptrons. In one video, this guy is explaining how to make a machine that can 'learn' how to distinguish two arrays. He explains the training process, but just shoves all of his inputs and weights into the sigmoid function. I did some research on the sigmoid function and was wondering why it is used in machine learning and why programmers use it to test their inputs.</p>

答:
Sigmoid is a non-linear activation function widely used in Logistic Regression and Artificial Neural Networks. If, we look at its Python implementation,

```<code>import math

def sigmoid( x ):
    return 1 / ( 1 + math.exp( -x ))
</code>```

If the inputs are negative then the outputs will be smaller than 0.5. If the inputs are positive then the outputs are greater than 0.5.

Uses in Machine Learning:

In machine learning, if we tend to learn a relationship between some features and a binary feature then we use a sigmoid function at the output layer ( which produces the outputs ). As the output ranges between 0 and 1, we can set a decision boundary and determine whether the label was 0 or 1.

Also, they were used in hidden layers of Artificial Neural Networks. Sigmoid produces an activation based on its inputs ( from the previous layer ) which is then multiplied by the weights of the succeeding layer to produce further activations. If a greater positive value is intercepted by Sigmoid, it gives a fully saturated firing of 1. In the case of small negative value, a firing of 0 is produced. Hence, it produces an activation value based on a threshold.

Also, since the output is between 0 and 1, it's output could be interpreted as a probability for a particular class.

Some Particular problems with Sigmoid ( And its replacement with ReLU ):

Sigmoid suffers from the problem of Vanishing Gradient. The gradients
  of the NN's output with respect to the parameters become so small,
  that the NN takes smaller steps towards the minima of the loss
  function and eventually stop learning.

Also, extremely greater or smaller values are mapped to extremities i.e 0 or 1 which causes no change in the model's output w.r.t the parameters like the weights and biases.

This problem was tackled by the use of ReLU which does not squash the inputs ( like the sigmoid ) and hence the Vanishing Gradient problem was solved.

Body:
Sigmoid is a non-linear activation function widely used in Logistic Regression and Artificial Neural Networks. If, we look at its Python implementation,

import math

def sigmoid( x ):
    return 1 / ( 1 + math.exp( -x ))

If the inputs are negative then the outputs will be smaller than 0.5. If the inputs are positive then the outputs are greater than 0.5.

Uses in Machine Learning:

In machine learning, if we tend to learn a relationship between some features and a binary feature then we use a sigmoid function at the output layer ( which produces the outputs ). As the output ranges between 0 and 1, we can set a decision boundary and determine whether the label was 0 or 1.

Also, they were used in hidden layers of Artificial Neural Networks. Sigmoid produces an activation based on its inputs ( from the previous layer ) which is then multiplied by the weights of the succeeding layer to produce further activations. If a greater positive value is intercepted by Sigmoid, it gives a fully saturated firing of 1. In the case of small negative value, a firing of 0 is produced. Hence, it produces an activation value based on a threshold.

Also, since the output is between 0 and 1, it's output could be interpreted as a probability for a particular class.

Some Particular problems with Sigmoid ( And its replacement with ReLU ):

Sigmoid suffers from the problem of Vanishing Gradient. The gradients
  of the NN's output with respect to the parameters become so small,
  that the NN takes smaller steps towards the minima of the loss
  function and eventually stop learning.

Also, extremely greater or smaller values are mapped to extremities i.e 0 or 1 which causes no change in the model's output w.r.t the parameters like the weights and biases.

This problem was tackled by the use of ReLU which does not squash the inputs ( like the sigmoid ) and hence the Vanishing Gradient problem was solved.


问:
Transparent JButton Turns Light Blue when Clicked
I am trying to make transparent JButtons (with visible text) but when the button has clicked the background becomes light blue. (Don't mind the indentation in the code. It's all properly indented)

I've made the button successfully transparent but I fear that the problem might be because I add all the JButtons to a JLabel(A background image).

```<code>    JButton play = new JButton("Play");
    JButton quit = new JButton("Quit");
    JButton instructions = new JButton("Instructions");

    Color invs = new Color(0,0,0,0);

    play.setBackground(invs);
    quit.setBackground(invs);
    instructions.setBackground(invs);

    play.setBorderPainted(false);
    //play.setMargin(new Insets(0,0,0,0));
    play.setRolloverEnabled(false);
    play.setFocusable(false);
    play.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

    instructions.setBorderPainted(false);
    //instructions.setMargin(new Insets(0,0,0,0));
    instructions.setRolloverEnabled(false);
    instructions.setFocusable(false);

   instructions.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

    quit.setBorderPainted(false);
    //quit.setMargin(new Insets(0,0,0,0));
    quit.setRolloverEnabled(false);
    quit.setFocusable(false);
    quit.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

    instructions.setForeground(Color.WHITE);
    play.setForeground(Color.WHITE);
    quit.setForeground(Color.WHITE);
</code>```

答:
```<code>Color invs = new Color(0,0,0,0);
</code>```

Don't use a transparent Color to attempt to set the background of any Swing component. Swing does not paint components correctly when using transparent colors.

In general you use:

```<code>setOpaque( false );
</code>```

when you want full transparency on any Swing component.

However with a JButton you also need:

```<code>setContentAreaFilled( false );
</code>```

to prevent the button background from being painted when it is clicked.

If you ever want partial transparency, then check out Backgrounds With Transparency for a solution.

Body:
I am trying to make transparent JButtons (with visible text) but when the button has clicked the background becomes light blue. (Don't mind the indentation in the code. It's all properly indented)

I've made the button successfully transparent but I fear that the problem might be because I add all the JButtons to a JLabel(A background image).

    JButton play = new JButton("Play");
    JButton quit = new JButton("Quit");
    JButton instructions = new JButton("Instructions");

    Color invs = new Color(0,0,0,0);

    play.setBackground(invs);
    quit.setBackground(invs);
    instructions.setBackground(invs);

    play.setBorderPainted(false);
    //play.setMargin(new Insets(0,0,0,0));
    play.setRolloverEnabled(false);
    play.setFocusable(false);
    play.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

    instructions.setBorderPainted(false);
    //instructions.setMargin(new Insets(0,0,0,0));
    instructions.setRolloverEnabled(false);
    instructions.setFocusable(false);

   instructions.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

    quit.setBorderPainted(false);
    //quit.setMargin(new Insets(0,0,0,0));
    quit.setRolloverEnabled(false);
    quit.setFocusable(false);
    quit.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

    instructions.setForeground(Color.WHITE);
    play.setForeground(Color.WHITE);
    quit.setForeground(Color.WHITE);

Body:
Color invs = new Color(0,0,0,0);

Don't use a transparent Color to attempt to set the background of any Swing component. Swing does not paint components correctly when using transparent colors.

In general you use:

setOpaque( false );

when you want full transparency on any Swing component.

However with a JButton you also need:

setContentAreaFilled( false );

to prevent the button background from being painted when it is clicked.

If you ever want partial transparency, then check out Backgrounds With Transparency for a solution.


问:
'linear-gradient(rgb(255, 255, 255), rgb(230, 230, 230))' Http Requests every day
I get a ton of these requests below, 400 today which throw 404 errors. Where and why are these being called to my site?  The user agent looks legit.

```<code>System.Web.HttpException: A public action method 'linear-gradient(rgb(255, 255, 255), rgb(230, 230, 230))' was not found on controller 'Tournaments.Controllers.EventController'.
</code>```

Url

```<code>https://basketball.exposureevents.com/128833/third-annual-its-lit-basketball-tournament/linear-gradient(rgb(255, 255, 255), rgb(230, 230, 230))
</code>```

答:
Just aborted the requests.</p>

```<code><rule name="LinearGradientRequest" enabled="true" stopProcessing="true">
          <match url="^.*linear-gradient.*$" />
          <action type="AbortRequest" />
        </rule>
</code>```

Body:
I get a ton of these requests below, 400 today which throw 404 errors. Where and why are these being called to my site?  The user agent looks legit.

System.Web.HttpException: A public action method 'linear-gradient(rgb(255, 255, 255), rgb(230, 230, 230))' was not found on controller 'Tournaments.Controllers.EventController'.

Url

https://basketball.exposureevents.com/128833/third-annual-its-lit-basketball-tournament/linear-gradient(rgb(255, 255, 255), rgb(230, 230, 230))

Body:
Just aborted the requests.

<rule name="LinearGradientRequest" enabled="true" stopProcessing="true">
          <match url="^.*linear-gradient.*$" />
          <action type="AbortRequest" />
        </rule>


问:
Android studio keep importing old version of libraries
Android studio keeps importing old version of libraries even though my gradle are updated.

I'm trying to import the new notification builder

I'm trying to import the new notification builder but then my project won't give me the updated version of the library

I have these in my gradle :

```<code> implementation 'com.android.support:support-compat:28.0.0'
 implementation 'com.android.support:appcompat-v7:28.0.0'
</code>```

what else am I missing?
why is it keeps importing 25.3.0 library if I have 28.0.0 in my gradle

答:
Go to File->Settings->Editor->General->Auto Import.

1) Remove the check mark from "Add unambiguos imports on the fly".

then in your java class Call the Required Library Class and press Alt+Enter. You can choose which library class to be imported.

Body:
Android studio keeps importing old version of libraries even though my gradle are updated.

I'm trying to import the new notification builder

I'm trying to import the new notification builder but then my project won't give me the updated version of the library

I have these in my gradle :

 implementation 'com.android.support:support-compat:28.0.0'
 implementation 'com.android.support:appcompat-v7:28.0.0'

what else am I missing?
why is it keeps importing 25.3.0 library if I have 28.0.0 in my gradle


问:
Converting array iteration to lambda function using Java8
I am trying to convert to Lambda function

So far I am able to convert the above code to lambda function like as shown below

```<code>Stream.of(acceptedDetails, rejectedDetails)
.filter(list -> !isNull(list) && list.length > 0)
.forEach(new Consumer<Object>() {
    public void accept(Object acceptedOrRejected) {
        String id;
        if(acceptedOrRejected instanceof EmployeeValidationAccepted) {
            id = ((EmployeeValidationAccepted) acceptedOrRejected).getId();
        } else {
            id = ((EmployeeValidationRejected) acceptedOrRejected).getAd().getId();
        }

        if(acceptedOrRejected instanceof EmployeeValidationAccepted) {
            dates1.add(new Integer(id.split("something")[1]));
            Integer empId = Integer.valueOf(id.split("something")[2]);
            empIds1.add(empId);
        } else {
            dates2.add(new Integer(id.split("something")[1]));
            Integer empId = Integer.valueOf(id.split("something")[2]);
            empIds2.add(empId);
        }
    }
});
</code>```

But still my goal was to avoid repeating the same logic and also to convert to Lambda function, still in my converted lambda function I feel its not clean and efficient.

This is just for my learning aspect I am doing this stuff by taking one existing code snippet.

Can anyone please tell me how can I improvise the converted Lambda function

答:
A similar approach as @roookeee already posted with but maybe slightly more concise would be to store the mappings using mapping functions declared as :

```<code>Function<String, Integer> extractEmployeeId = empId -> Integer.valueOf(empId.split("-")[2]);
Function<String, BigInteger> extractDate = empId -> new BigInteger(empId.split("-")[1]);
</code>```

then proceed with mapping as:

```<code>Map<Integer, BigInteger> acceptedDetailMapping = Arrays.stream(acceptedDetails)
        .collect(Collectors.toMap(a -> extractEmployeeId.apply(a.getId()),
                a -> extractDate.apply(a.getId())));

Map<Integer, BigInteger> rejectedDetailMapping = Arrays.stream(rejectedDetails)
        .collect(Collectors.toMap(a -> extractEmployeeId.apply(a.getAd().getId()),
                a -> extractDate.apply(a.getAd().getId())));
</code>```

Hereafter you can also access the date of acceptance or rejection corresponding to the employeeId of the employee as well.

Body:
I am trying to convert to Lambda function

So far I am able to convert the above code to lambda function like as shown below

Stream.of(acceptedDetails, rejectedDetails)
.filter(list -> !isNull(list) && list.length > 0)
.forEach(new Consumer<Object>() {
    public void accept(Object acceptedOrRejected) {
        String id;
        if(acceptedOrRejected instanceof EmployeeValidationAccepted) {
            id = ((EmployeeValidationAccepted) acceptedOrRejected).getId();
        } else {
            id = ((EmployeeValidationRejected) acceptedOrRejected).getAd().getId();
        }

        if(acceptedOrRejected instanceof EmployeeValidationAccepted) {
            dates1.add(new Integer(id.split("something")[1]));
            Integer empId = Integer.valueOf(id.split("something")[2]);
            empIds1.add(empId);
        } else {
            dates2.add(new Integer(id.split("something")[1]));
            Integer empId = Integer.valueOf(id.split("something")[2]);
            empIds2.add(empId);
        }
    }
});

But still my goal was to avoid repeating the same logic and also to convert to Lambda function, still in my converted lambda function I feel its not clean and efficient.

This is just for my learning aspect I am doing this stuff by taking one existing code snippet.

Can anyone please tell me how can I improvise the converted Lambda function

Body:
A similar approach as @roookeee already posted with but maybe slightly more concise would be to store the mappings using mapping functions declared as :

Function<String, Integer> extractEmployeeId = empId -> Integer.valueOf(empId.split("-")[2]);
Function<String, BigInteger> extractDate = empId -> new BigInteger(empId.split("-")[1]);

then proceed with mapping as:

Map<Integer, BigInteger> acceptedDetailMapping = Arrays.stream(acceptedDetails)
        .collect(Collectors.toMap(a -> extractEmployeeId.apply(a.getId()),
                a -> extractDate.apply(a.getId())));

Map<Integer, BigInteger> rejectedDetailMapping = Arrays.stream(rejectedDetails)
        .collect(Collectors.toMap(a -> extractEmployeeId.apply(a.getAd().getId()),
                a -> extractDate.apply(a.getAd().getId())));

Hereafter you can also access the date of acceptance or rejection corresponding to the employeeId of the employee as well.