问:
Python. Best way to filter array by date
I have a list of Rest objects. It's django model

```<code>class Rest(models.Model):
   product = models.ForeignKey('Product', models.DO_NOTHING)
   date = models.DateTimeField()
   rest = models.FloatField()
</code>```

I want to select objects from it for today's date. I do it like this. Maybe there is some more convenient and compact way?

```<code>    for rest in rests_list:
      if rest.date.day == datetime.now().day:
         result.append(rest)
</code>```

答:
You can use the django filter for filtering and get only today's date data from your model. No need to fetch all data first and then apply loop for get today's date data. You have to write your query like ...

```<code>import datetime
Rest.objects.filter(date__date = datetime.date.today())
</code>```

But be sure that timezone should be same for database server and web server

Body:
I have a list of Rest objects. It's django model

class Rest(models.Model):
   product = models.ForeignKey('Product', models.DO_NOTHING)
   date = models.DateTimeField()
   rest = models.FloatField()

I want to select objects from it for today's date. I do it like this. Maybe there is some more convenient and compact way?

    for rest in rests_list:
      if rest.date.day == datetime.now().day:
         result.append(rest)

Body:
You can use the django filter for filtering and get only today's date data from your model. No need to fetch all data first and then apply loop for get today's date data. You have to write your query like ...

import datetime
Rest.objects.filter(date__date = datetime.date.today())

But be sure that timezone should be same for database server and web server


来源: stackexchange

问:
Python - If/Elif statement (loops)
Can someone tell me why I'm getting 4 as the outcome? Should 3 be printing instead because the code is satisfied in the If section.</p>

```<code>a = 15

if a&5  == 0:
    print('3')
elif a% 5 == 0:
    print('4')

else:
    print('5')
</code>```

答: If you want to check LSB then you should do "and" with 1 and check the result if it's 1 then LSB is 0 else LSB is 1</p>

ContentLicense: CC BY-SA 4.0

Title: Python - If/Elif statement (loops)

Body:
Can someone tell me why I'm getting 4 as the outcome? Should 3 be printing instead because the code is satisfied in the If section.

a = 15

if a&5  == 0:
    print('3')
elif a% 5 == 0:
    print('4')

else:
    print('5')


问:
How to use single component as page and MatDialog in angular
How to use the single component as page and open as component MatDialog
If call from MatDialog need two way data binding
If its open as page no need to bind data

Call from component
    ```var modal = this._dialog.open(SingleComponent, {
      data: { create: true }
    });'''</p>

<p>SingleComponent</p>

``````@Component({
  selector: 'single',
  templateUrl: './single.html',
  styleUrls: ['./single.scss'],
  providers: [{
     provide: MatDialogRef,
     useValue: {close: (dialogResult: any) => { }}
  },{ provide: MAT_DIALOG_DATA, useValue: {} }]
</code>```

})
    constructor(
        public dialogRef: MatDialogRef,
        @Optional() @Inject(MAT_DIALOG_DATA) public data: any) ```

This open in both as page and modal box, but cant bind data between component and single component, and cant close from code
    this.dialogRef.close(); not working

答:
If you are gettingg static injection error in console for the code you have written, you can add below lines to fix that error

In app.module.ts:

```<code>providers: [
   { provide: MatDialogRef, useValue: {} },
   { provide: MAT_DIALOG_DATA, useValue: [] }
  ]
</code>```

Body:
How to use the single component as page and open as component MatDialog
If call from MatDialog need two way data binding
If its open as page no need to bind data

Call from component
    ```var modal = this._dialog.open(SingleComponent, {
      data: { create: true }
    });'''</p>

<p>SingleComponent</p>

<pre><code>```@Component({
  selector: 'single',
  templateUrl: './single.html',
  styleUrls: ['./single.scss'],
  providers: [{
     provide: MatDialogRef,
     useValue: {close: (dialogResult: any) => { }}
  },{ provide: MAT_DIALOG_DATA, useValue: {} }]

})
    constructor(
        public dialogRef: MatDialogRef,
        @Optional() @Inject(MAT_DIALOG_DATA) public data: any) ```

This open in both as page and modal box, but cant bind data between component and single component, and cant close from code
    this.dialogRef.close(); not working

Body:
If you are gettingg static injection error in console for the code you have written, you can add below lines to fix that error

In app.module.ts:

providers: [
   { provide: MatDialogRef, useValue: {} },
   { provide: MAT_DIALOG_DATA, useValue: [] }
  ]


问:
How do I "undo" a --single-branch clone?
I cloned a repo using the

git clone -b <branch name> --single-branch <github url> <target directory>

This cloned ONLY this branch, but now I want to switch to the master and other branches.  Is there any way besides clearing it out and starting over to clone the rest of the repo that I can undo the --single-branch preference?

答:
I initially applied Dominik Pawlak's answer and it worked. But I wasn't able to pull any further changes, after I committed more code into my new branch.

There is another way of resetting single-branch entirely, which hasn't been mentioned here:

```<code>git remote remove origin
git remote add origin git@gitlab.com:{yourProject}/{yourRepo}.git
git branch --set-upstream-to=origin/{yourBranch}  {yourBranch}
git pull
</code>```

This resets everything to the original.

ContentLicense: CC BY-SA 3.0

Body:
I initially applied Dominik Pawlak's answer and it worked. But I wasn't able to pull any further changes, after I committed more code into my new branch.

There is another way of resetting single-branch entirely, which hasn't been mentioned here:

git remote remove origin
git remote add origin git@gitlab.com:{yourProject}/{yourRepo}.git
git branch --set-upstream-to=origin/{yourBranch}  {yourBranch}
git pull

This resets everything to the original.


问:
Select two different Items if they meet different condition
I have a select problem with mssql which is;

```<code>Invoice 1
ItemUniqueNo    ItemName    InvoceNo
1               A           123
3               C           123

Table A (All Invoices)
ItemUniqueNo   ItemName   InvoceNo
1               A           123
2               B           235
3               C           123

Table B (Item List)
ItemUniqueNo    ItemName    ItemGroup
1               A           XXX
2               B           YYY
3               C           ZZZ
</code>```

I want to select every items (from Table A) If an invoice has both type of product which is; ItemUniqueNo=3 and ItemGroup = XXX, in same invoice. Here is my code:

```<code>SELECT
*
FROM
TABLE_A
WHERE
(ItemUniqueNo IN (SELECT ItemUniqueNo FROM TABLE_B WHERE ItemGroup='XXX') OR ItemUniqueNo = 3)
</code>```

with this code, I've listed all items which has either ItemGroup = XXX and ItemUniqueNo=3 BUT
I want to meet both condition in same invoice, like:

```<code>Invoice 1
ItemUniqueNo    ItemName    InvoceNo
1               A           123  --->  This meets 'XXX' ItemGroup condition
3               C           123  --->  This meets '3' ItemUniqueNo condition
</code>```

This invoice meet both 2 condition, so i want to list this two item with InvoceNo.
AND all other items which meet this condition.

答:
You can try this using inner join as shown below.

```<code>Create table TableA (ItemUniqueNo int, ItemName Char(1),  InvoceNo int)
insert into TableA Values
(1, 'A', 123),
(2, 'B', 235),
(3, 'C', 123)

Create table TableB (ItemUniqueNo int, ItemName Char(1),  ItemGroup Varchar(10))
insert into TableB Values
(1, 'A', 'XXX'),
(2, 'B', 'YYY'),
(3, 'C', 'ZZZ')

SELECT TableA.*
    ,TableB.ItemGroup
FROM TableA
INNER JOIN TableB ON TableA.ItemUniqueNo = TableB.ItemUniqueNo
WHERE ItemGroup = 'XXX'
    OR TableA.ItemUniqueNo = 3
ORDER BY TableA.ItemUniqueNo
</code>```

Here is the live db<>fiddle demo.
Another option you can try this

```<code>SELECT TableA.*
FROM TableA
INNER JOIN (
    SELECT TableA.*
    FROM TableA
    WHERE EXISTS (
            SELECT 1
            FROM TableB
            WHERE TableA.ItemName = TableB.ItemName
                AND TableA.ItemName = 'A'
            )
        AND EXISTS (
            SELECT 1
            FROM TableB
            WHERE TableA.ItemName = TableB.ItemName
                AND TableB.ItemGroup = 'XXX'
            )
    ) TEMP ON TableA.InvoceNo = TEMP.InvoceNo
</code>```

Body:
I have a select problem with mssql which is;

Invoice 1
ItemUniqueNo    ItemName    InvoceNo
1               A           123
3               C           123

Table A (All Invoices)
ItemUniqueNo   ItemName   InvoceNo
1               A           123
2               B           235
3               C           123

Table B (Item List)
ItemUniqueNo    ItemName    ItemGroup
1               A           XXX
2               B           YYY
3               C           ZZZ

I want to select every items (from Table A) If an invoice has both type of product which is; ItemUniqueNo=3 and ItemGroup = XXX, in same invoice. Here is my code:

SELECT
*
FROM
TABLE_A
WHERE
(ItemUniqueNo IN (SELECT ItemUniqueNo FROM TABLE_B WHERE ItemGroup='XXX') OR ItemUniqueNo = 3)

with this code, I've listed all items which has either ItemGroup = XXX and ItemUniqueNo=3 BUT
I want to meet both condition in same invoice, like:

Invoice 1
ItemUniqueNo    ItemName    InvoceNo
1               A           123  --->  This meets 'XXX' ItemGroup condition
3               C           123  --->  This meets '3' ItemUniqueNo condition

This invoice meet both 2 condition, so i want to list this two item with InvoceNo.
AND all other items which meet this condition.

Body:
You can try this using inner join as shown below.

Create table TableA (ItemUniqueNo int, ItemName Char(1),  InvoceNo int)
insert into TableA Values
(1, 'A', 123),
(2, 'B', 235),
(3, 'C', 123)

Create table TableB (ItemUniqueNo int, ItemName Char(1),  ItemGroup Varchar(10))
insert into TableB Values
(1, 'A', 'XXX'),
(2, 'B', 'YYY'),
(3, 'C', 'ZZZ')

SELECT TableA.*
    ,TableB.ItemGroup
FROM TableA
INNER JOIN TableB ON TableA.ItemUniqueNo = TableB.ItemUniqueNo
WHERE ItemGroup = 'XXX'
    OR TableA.ItemUniqueNo = 3
ORDER BY TableA.ItemUniqueNo

Here is the live db<>fiddle demo.
Another option you can try this

SELECT TableA.*
FROM TableA
INNER JOIN (
    SELECT TableA.*
    FROM TableA
    WHERE EXISTS (
            SELECT 1
            FROM TableB
            WHERE TableA.ItemName = TableB.ItemName
                AND TableA.ItemName = 'A'
            )
        AND EXISTS (
            SELECT 1
            FROM TableB
            WHERE TableA.ItemName = TableB.ItemName
                AND TableB.ItemGroup = 'XXX'
            )
    ) TEMP ON TableA.InvoceNo = TEMP.InvoceNo


问:
Converting React to React Native
I have a React App that I need to convert to React Native. I do not have a lot of experience on web development, so i might be missing something essential here. The problem I have is that when I open the app in the emulator I only see a white page that says "Home" on top. This what i have translated of the code so far.

index.js

```<code>import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);
</code>```

App.js

```<code>import React from 'react';
import Routes from './src/core/Routes';
import configureStore from './src/services/store';
import {Provider} from 'react-redux';
import {View} from 'react-native';
import {createMuiTheme, MuiThemeProvider} from '@material-ui/core';
import {
    font_family_default,
    font_family_secondary,
    font_size_md,
    font_size_sm,
    font_weight_bold,
    font_weight_normal,
    font_weight_semi_bold,
} from './src/assets/style/variables';
import {rem} from './src/assets/style/functions';
import colors from './src/assets/style/colors';

const theme = createMuiTheme({
    typography: {
        fontFamily: font_family_default,
        fontSize: 16,
        fontWeightLight: font_weight_normal,
        fontWeightRegular: font_weight_semi_bold,
        fontWeightMedium: font_weight_bold,
    },
    overrides: {
        MuiMenuItem: {
            root: {
                fontSize: font_size_sm,
                fontFamily: font_family_secondary,
                fontWeight: font_weight_semi_bold,
                minHeight: rem(40),
            },
        },
        MuiMenu: {
            paper: {
                boxShadow: '0px 12px 56px -8px rgba(0,0,0,0.2)',
                borderRadius: `${rem(3)}`,
            },
        },
        MuiExpansionPanelSummary: {
            root: {
                padding: `0px ${rem(16)}`,
            },
            content: {
                margin: `${rem(8)} 0px `,
            },
        },
        MuiInputBase: {
            root: {
                fontSize: font_size_md,
            },
        },
        MuiPickersToolbar: {
            toolbar: {
                backgroundColor: colors.grey.primary,
            },
        },
        MuiPickersDay: {
            daySelected: {
                backgroundColor: colors.yellow.dark2,
                '&:hover': {
                    backgroundColor: colors.yellow.dark2,
                },
            },
        },

        MuiPickersClockNumber: {
            clockNumberSelected: {backgroundColor: colors.yellow.dark2},
        },

        MuiPickersClock: {
            pin: {backgroundColor: colors.yellow.dark2},
        },
        MuiPickersClockPointer: {
            pointer: {backgroundColor: colors.yellow.dark2},
            thumb: {border: `14px solid ${colors.yellow.dark2}`},
        },
    },
});

const store = configureStore();

const App: () => React$Node = () => {
    return (
        <Provider store={store}>
            <MuiThemeProvider theme={theme}>
                <View style={{flex: 1}}>
                    <Routes/>
                </View>
            </MuiThemeProvider>
        </Provider>
    );
};

export default App;
</code>```

Routes.js

```<code>import React from 'react';
import {Router, Scene} from 'react-native-router-flux';
import Login from '../pages/login';

const Routes = () => (
    <Router>
        <Scene key="root">
            <Scene key="home" component={Login} title="Home" initial={true}/>
        </Scene>
    </Router>
);

export default Routes;
</code>```

/src/page/login/index.js

```<code>import React, {useState} from 'react';
import styled from 'styled-components/native';
import Input from '../../shared/components/Input';
import Button from '../../shared/components/Button';
import {connect} from 'react-redux';
import {APP_ROUTES} from '../../core/global-constants';
import {Link, Redirect} from 'react-router-native';

import Logo from '../../assets/img/log.svg';
import colors from '../../assets/style/colors';
import {rem} from '../../assets/style/functions';
import {device, font_size_md, font_size_xxl, font_weight_normal} from '../../assets/style/variables';
import {login} from '../../services/actions/authenticationActions';
import useForm from '../../shared/hooks/useForm';
import validate from './loginFormValidations';

const theme = {
    backgroundColor: colors.white.light1,
};

function Login(props) {
    const {values, handleChange, handleSubmit, errors} = useForm(login, validate);
    const [redirect, setRedirect] = useState(false);
    const [errorLogin, setErrorLogin] = useState(false);

    function login() {
        if (Object.keys(errors).length === 0) {
            props.login(values).then(
                res => {
                    setRedirect(true);
                },
                err => {
                    errors.login = props.errorMessage
                        ? `${props.errorMessage},  please try again`
                        : `No active account found with the given credentials,  please try again`;
                    setErrorLogin(true);
                },
            );
        }
    }

    if (redirect) {
        return <Redirect to={APP_ROUTES.timeTracker}/>;
    }
    return (
        <Style.Section>
            <Style.Img src={Logo} alt="toki timer logo"/>
            <Style.Hero>
                <Style.Title>Welcome back!</Style.Title>
                <Style.Subtitle>Log in to continue</Style.Subtitle>
            </Style.Hero>
            <Style.Form onSubmit={handleSubmit}>
                <Style.FormGroup>
                    <Input
                        id="username"
                        name="username"
                        placeholder="Username"
                        backgroundColor={theme}
                        onChange={handleChange}
                        value={values.username || ''}
                        hasError={errors.username}
                    />
                    {errors.username && <Style.ErrorMessage>{errors.username}</Style.ErrorMessage>}
                </Style.FormGroup>

                <Style.FormGroup>
                    <Input
                        id="password"
                        name="password"
                        type="password"
                        placeholder="Password"
                        backgroundColor={theme}
                        onChange={handleChange}
                        value={values.password || ''}
                        hasError={errors.password}
                    />
                    {errors.password && <Style.ErrorMessage>{errors.password}</Style.ErrorMessage>}
                    {errorLogin && <Style.ErrorMessage>{errors.login}</Style.ErrorMessage>}
                </Style.FormGroup>
                <Button name="Login" type="submit"/>
            </Style.Form>
            <Style.Hero>
                <Style.BottomLinks>
                    <Style.Link to={APP_ROUTES.forgotPassword}>Forgot your password?</Style.Link>
                </Style.BottomLinks>
            </Style.Hero>
        </Style.Section>
    );
}

const mapStateToProps = state => {
    return {
        loading: state.authorization.loading,
        isAuthenticated: state.authorization.isAuthenticated,
        loginSuccess: state.authorization.loginSuccess,
        loginError: state.authorization.loginError,
        errorMessage: state.authorization.errorMessage,
        isAdmin: state.authorization.userInSession.isAdmin,
    };
};
const mapDispatchToProps = {login};

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

const Style = {};

Style.Section = styled.SectionList`
  background-color: ${colors.grey.primary};
  min-height: 100%;
  margin: 0px auto;
  display: flex;
  flex-direction: column;
`;
Style.Form = styled.View`
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 0 35%;
  margin-bottom: ${rem(40)};

  @media ${device.mobileS} {
    padding: 0 5%;
  }

  @media ${device.mobileL} {
    padding: 0 15%;
  }

  @media ${device.laptop} {
    padding: 0 35%;
  }
`;

Style.Hero = styled.View`
  display: flex;
  flex-direction: column;
  margin-bottom: ${rem(70)};
  align-items: center;
`;
Style.Title = styled.Text`
  color: ${colors.white.primary};
  font-size: ${font_size_xxl};
  font-weight: ${font_weight_normal};
  margin: 0;
`;
Style.Subtitle = styled(Style.Title)`
  font-size: ${font_size_md};
`;
Style.Img = styled.Image`
  margin-bottom: ${rem(60)};
  margin-top: ${rem(60)};
`;
Style.BottomLinks = styled.Text`
  color: ${colors.white.primary};
  margin-top: ${rem(10)};
`;

Style.Link = styled(Link)`
  color: ${colors.yellow.primary};

  &:hover {
    text-decoration: underline;
  }
`;
Style.FormGroup = styled.View`
  margin-bottom: ${rem(45)};
`;
Style.ErrorMessage = styled.Text`
  font-size: ${font_size_md};
  color: ${colors.red.primary};
`;
</code>```

What I don't seem to understand after reading documentation is how routing works, for example, using react, my Routes.js looks like this:

```<code>import React from 'react'
import { Switch, Route } from 'react-router-dom'

import { APP_ROUTES } from './global-constants'
import Login from '../pages/login'
import Dashboard from '../pages/dashboard'
import TimeTracker from '../pages/time-tracker'
import SignUp from '../pages/signUp'
import PrivateRoute from '../shared/components/PrivateRoute'
import UserList from '../pages/user-list'
import DepartmentsList from '../pages/departments-list'
import Reports from '../pages/reports'
import UserProfile from '../pages/user-profile'
import ForgotPassword from '../pages/forgot-password'
import NotFound from '../shared/components/NotFound'

const Routes = () => (
  <main>
    <Switch>
      <Route exact path={[APP_ROUTES.home, APP_ROUTES.login]} component={Login} />
      <Route exact path={APP_ROUTES.signUp} component={SignUp} />
      <Route exact path={APP_ROUTES.forgotPassword} component={ForgotPassword} />
      <PrivateRoute
        exact
        path={[APP_ROUTES.dashboard, APP_ROUTES.dashboardDeparment]}
        component={Dashboard}
      />
      <PrivateRoute exact path={APP_ROUTES.timeTracker} component={TimeTracker} />
      <PrivateRoute exact path={APP_ROUTES.usersList} component={UserList} />
      <PrivateRoute exact path={APP_ROUTES.departments} component={DepartmentsList} />
      <PrivateRoute exact path={APP_ROUTES.reports} component={Reports} />
      <PrivateRoute exact path={APP_ROUTES.userDetails} component={UserProfile} />
      <PrivateRoute component={NotFound} />
    </Switch>
  </main>
)

export default Routes
</code>```

I made the changes to the routes file since I've read that react-router-dom does not work in native. My main purpose is to re-use as much code as possible, but if I can't, what do I need to change for the page to actually show in the emulator?

答:
You have to write the code separately because there are lot of
  difference between reactjs and react native. For example in reactjs we
  are using div tag and in react native its view tag and the codes are
  entirely different.

Title: Converting React to React Native

Body:
I have a React App that I need to convert to React Native. I do not have a lot of experience on web development, so i might be missing something essential here. The problem I have is that when I open the app in the emulator I only see a white page that says "Home" on top. This what i have translated of the code so far.

index.js

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);

App.js

import React from 'react';
import Routes from './src/core/Routes';
import configureStore from './src/services/store';
import {Provider} from 'react-redux';
import {View} from 'react-native';
import {createMuiTheme, MuiThemeProvider} from '@material-ui/core';
import {
    font_family_default,
    font_family_secondary,
    font_size_md,
    font_size_sm,
    font_weight_bold,
    font_weight_normal,
    font_weight_semi_bold,
} from './src/assets/style/variables';
import {rem} from './src/assets/style/functions';
import colors from './src/assets/style/colors';

const theme = createMuiTheme({
    typography: {
        fontFamily: font_family_default,
        fontSize: 16,
        fontWeightLight: font_weight_normal,
        fontWeightRegular: font_weight_semi_bold,
        fontWeightMedium: font_weight_bold,
    },
    overrides: {
        MuiMenuItem: {
            root: {
                fontSize: font_size_sm,
                fontFamily: font_family_secondary,
                fontWeight: font_weight_semi_bold,
                minHeight: rem(40),
            },
        },
        MuiMenu: {
            paper: {
                boxShadow: '0px 12px 56px -8px rgba(0,0,0,0.2)',
                borderRadius: `${rem(3)}`,
            },
        },
        MuiExpansionPanelSummary: {
            root: {
                padding: `0px ${rem(16)}`,
            },
            content: {
                margin: `${rem(8)} 0px `,
            },
        },
        MuiInputBase: {
            root: {
                fontSize: font_size_md,
            },
        },
        MuiPickersToolbar: {
            toolbar: {
                backgroundColor: colors.grey.primary,
            },
        },
        MuiPickersDay: {
            daySelected: {
                backgroundColor: colors.yellow.dark2,
                '&:hover': {
                    backgroundColor: colors.yellow.dark2,
                },
            },
        },

        MuiPickersClockNumber: {
            clockNumberSelected: {backgroundColor: colors.yellow.dark2},
        },

        MuiPickersClock: {
            pin: {backgroundColor: colors.yellow.dark2},
        },
        MuiPickersClockPointer: {
            pointer: {backgroundColor: colors.yellow.dark2},
            thumb: {border: `14px solid ${colors.yellow.dark2}`},
        },
    },
});

const store = configureStore();

const App: () => React$Node = () => {
    return (
        <Provider store={store}>
            <MuiThemeProvider theme={theme}>
                <View style={{flex: 1}}>
                    <Routes/>
                </View>
            </MuiThemeProvider>
        </Provider>
    );
};

export default App;

Routes.js

import React from 'react';
import {Router, Scene} from 'react-native-router-flux';
import Login from '../pages/login';

const Routes = () => (
    <Router>
        <Scene key="root">
            <Scene key="home" component={Login} title="Home" initial={true}/>
        </Scene>
    </Router>
);

export default Routes;

/src/page/login/index.js

import React, {useState} from 'react';
import styled from 'styled-components/native';
import Input from '../../shared/components/Input';
import Button from '../../shared/components/Button';
import {connect} from 'react-redux';
import {APP_ROUTES} from '../../core/global-constants';
import {Link, Redirect} from 'react-router-native';

import Logo from '../../assets/img/log.svg';
import colors from '../../assets/style/colors';
import {rem} from '../../assets/style/functions';
import {device, font_size_md, font_size_xxl, font_weight_normal} from '../../assets/style/variables';
import {login} from '../../services/actions/authenticationActions';
import useForm from '../../shared/hooks/useForm';
import validate from './loginFormValidations';

const theme = {
    backgroundColor: colors.white.light1,
};

function Login(props) {
    const {values, handleChange, handleSubmit, errors} = useForm(login, validate);
    const [redirect, setRedirect] = useState(false);
    const [errorLogin, setErrorLogin] = useState(false);

    function login() {
        if (Object.keys(errors).length === 0) {
            props.login(values).then(
                res => {
                    setRedirect(true);
                },
                err => {
                    errors.login = props.errorMessage
                        ? `${props.errorMessage},  please try again`
                        : `No active account found with the given credentials,  please try again`;
                    setErrorLogin(true);
                },
            );
        }
    }

    if (redirect) {
        return <Redirect to={APP_ROUTES.timeTracker}/>;
    }
    return (

            </Style.Hero>
            }
                </Style.FormGroup>

                }
                    {errorLogin && }
                </Style.FormGroup>
                <Button name="Login" type="submit"/>
            </Style.Form>

                </Style.BottomLinks>
            </Style.Hero>
        </Style.Section>
    );
}

const mapStateToProps = state => {
    return {
        loading: state.authorization.loading,
        isAuthenticated: state.authorization.isAuthenticated,
        loginSuccess: state.authorization.loginSuccess,
        loginError: state.authorization.loginError,
        errorMessage: state.authorization.errorMessage,
        isAdmin: state.authorization.userInSession.isAdmin,
    };
};
const mapDispatchToProps = {login};

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

const Style = {};

Style.Section = styled.SectionList`
  background-color: ${colors.grey.primary};
  min-height: 100%;
  margin: 0px auto;
  display: flex;
  flex-direction: column;
`;
Style.Form = styled.View`
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 0 35%;
  margin-bottom: ${rem(40)};

  @media ${device.mobileS} {
    padding: 0 5%;
  }

  @media ${device.mobileL} {
    padding: 0 15%;
  }

  @media ${device.laptop} {
    padding: 0 35%;
  }
`;

Style.Hero = styled.View`
  display: flex;
  flex-direction: column;
  margin-bottom: ${rem(70)};
  align-items: center;
`;
Style.Title = styled.Text`
  color: ${colors.white.primary};
  font-size: ${font_size_xxl};
  font-weight: ${font_weight_normal};
  margin: 0;
`;
Style.Subtitle = styled(Style.Title)`
  font-size: ${font_size_md};
`;
Style.Img = styled.Image`
  margin-bottom: ${rem(60)};
  margin-top: ${rem(60)};
`;
Style.BottomLinks = styled.Text`
  color: ${colors.white.primary};
  margin-top: ${rem(10)};
`;

Style.Link = styled(Link)`
  color: ${colors.yellow.primary};

  &:hover {
    text-decoration: underline;
  }
`;
Style.FormGroup = styled.View`
  margin-bottom: ${rem(45)};
`;
Style.ErrorMessage = styled.Text`
  font-size: ${font_size_md};
  color: ${colors.red.primary};
`;

What I don't seem to understand after reading documentation is how routing works, for example, using react, my Routes.js looks like this:

import React from 'react'
import { Switch, Route } from 'react-router-dom'

import { APP_ROUTES } from './global-constants'
import Login from '../pages/login'
import Dashboard from '../pages/dashboard'
import TimeTracker from '../pages/time-tracker'
import SignUp from '../pages/signUp'
import PrivateRoute from '../shared/components/PrivateRoute'
import UserList from '../pages/user-list'
import DepartmentsList from '../pages/departments-list'
import Reports from '../pages/reports'
import UserProfile from '../pages/user-profile'
import ForgotPassword from '../pages/forgot-password'
import NotFound from '../shared/components/NotFound'

const Routes = () => (

    <Switch>
      <Route exact path={[APP_ROUTES.home, APP_ROUTES.login]} component={Login} />
      <Route exact path={APP_ROUTES.signUp} component={SignUp} />
      <Route exact path={APP_ROUTES.forgotPassword} component={ForgotPassword} />
      <PrivateRoute
        exact
        path={[APP_ROUTES.dashboard, APP_ROUTES.dashboardDeparment]}
        component={Dashboard}
      />
      <PrivateRoute exact path={APP_ROUTES.timeTracker} component={TimeTracker} />
      <PrivateRoute exact path={APP_ROUTES.usersList} component={UserList} />
      <PrivateRoute exact path={APP_ROUTES.departments} component={DepartmentsList} />
      <PrivateRoute exact path={APP_ROUTES.reports} component={Reports} />
      <PrivateRoute exact path={APP_ROUTES.userDetails} component={UserProfile} />
      <PrivateRoute component={NotFound} />
    </Switch>

)

export default Routes

I made the changes to the routes file since I've read that react-router-dom does not work in native. My main purpose is to re-use as much code as possible, but if I can't, what do I need to change for the page to actually show in the emulator?


问:
Extract specific data from a dataframe
I have a data frame that looks like this:

```<code>| Start| End | Distance|
|------|-----|---------|
| A    | B   |       10|
| A    | C   |       11|
| A    | D   |       12|
| B    | C   |       13|
| B    | D   |       14|
| C    | D   |       15|
</code>```

I need to extract the distance values based on a list that is shown below:

```<code>start_end_list = [A, B, B, C, C]
</code>```

Therefore, the distance value that is extracted will be converted into another data frame that is the combination of Start and End data like shown below:

```<code>| Start| End | Distance|
|------|-----|---------|
| A    | B   |       10|
| A    | B   |       10|
| A    | C   |       11|
| A    | C   |       11|
| B    | C   |       13|
| B    | C   |       13|
</code>```

How to do that using Panda Python?

答:
Use boolean indexing and filter by DataFrame.isin only selected columns in list and test of both Trues per rows by DataFrame.all:

```<code>df1 = df[df[['Start','End']].isin(start_end_list).all(axis=1)]
</code>```

Another idea is test both columns separately by Series.isin and chain masks by & for bitwise AND:

```<code>df1 = df[df['Start'].isin(start_end_list) & df['End'].isin(start_end_list)]
</code>```

```<code>print (df1)
  Start End  Distance
0     A   B        10
1     A   C        11
3     B   C        13
</code>```

Detail1:

```<code>print (df[['Start','End']].isin(start_end_list))
   Start    End
0   True   True
1   True   True
2   True  False
3   True   True
4   True  False
5   True  False

print (df[['Start','End']].isin(start_end_list).all(axis=1))
0     True
1     True
2    False
3     True
4    False
5    False
dtype: bool
</code>```

Detail2:

```<code>print (df['Start'].isin(start_end_list))
0    True
1    True
2    True
3    True
4    True
5    True
Name: Start, dtype: bool

print (df['End'].isin(start_end_list))
0     True
1     True
2    False
3     True
4    False
5    False
Name: End, dtype: bool

print (df['Start'].isin(start_end_list) & df['End'].isin(start_end_list))
0     True
1     True
2    False
3     True
4    False
5    False
dtype: bool
</code>```

EDIT: For repeat rows add concat with DataFrame.sort_index by only stable algo mergesort and last create default index by DataFrame.reset_index with drop=True

```<code>df2 = pd.concat([df1, df1]).sort_index(kind='mergesort').reset_index(drop=True)
print (df2)
  Start End  Distance
0     A   B        10
1     A   B        10
2     A   C        11
3     A   C        11
4     B   C        13
5     B   C        13
</code>```

Title: Extract specific data from a dataframe

Body:
I have a data frame that looks like this:

| Start| End | Distance|
|------|-----|---------|
| A    | B   |       10|
| A    | C   |       11|
| A    | D   |       12|
| B    | C   |       13|
| B    | D   |       14|
| C    | D   |       15|

I need to extract the distance values based on a list that is shown below:

start_end_list = [A, B, B, C, C]

Therefore, the distance value that is extracted will be converted into another data frame that is the combination of Start and End data like shown below:

| Start| End | Distance|
|------|-----|---------|
| A    | B   |       10|
| A    | B   |       10|
| A    | C   |       11|
| A    | C   |       11|
| B    | C   |       13|
| B    | C   |       13|

How to do that using Panda Python?

Body:
Use boolean indexing and filter by DataFrame.isin only selected columns in list and test of both Trues per rows by DataFrame.all:

df1 = df[df[['Start','End']].isin(start_end_list).all(axis=1)]

Another idea is test both columns separately by Series.isin and chain masks by & for bitwise AND:

df1 = df[df['Start'].isin(start_end_list) & df['End'].isin(start_end_list)]

print (df1)
  Start End  Distance
0     A   B        10
1     A   C        11
3     B   C        13

Detail1:

print (df[['Start','End']].isin(start_end_list))
   Start    End
0   True   True
1   True   True
2   True  False
3   True   True
4   True  False
5   True  False

print (df[['Start','End']].isin(start_end_list).all(axis=1))
0     True
1     True
2    False
3     True
4    False
5    False
dtype: bool

Detail2:

print (df['Start'].isin(start_end_list))
0    True
1    True
2    True
3    True
4    True
5    True
Name: Start, dtype: bool

print (df['End'].isin(start_end_list))
0     True
1     True
2    False
3     True
4    False
5    False
Name: End, dtype: bool

print (df['Start'].isin(start_end_list) & df['End'].isin(start_end_list))
0     True
1     True
2    False
3     True
4    False
5    False
dtype: bool

EDIT: For repeat rows add concat with DataFrame.sort_index by only stable algo mergesort and last create default index by DataFrame.reset_index with drop=True

df2 = pd.concat([df1, df1]).sort_index(kind='mergesort').reset_index(drop=True)
print (df2)
  Start End  Distance
0     A   B        10
1     A   B        10
2     A   C        11
3     A   C        11
4     B   C        13
5     B   C        13


问:
Convert multidimensional array to single array with serialize key and value
Here is my multidimensional array. I want to extract specific fields from them and create a one dimensional array.

```<code>   [0] => Array (
        [in_user_id] => 157,
        [st_meta_key] => city
        [st_meta_value] => jaipur
        )
    [1] => Array (
        [in_user_id] => 157
        [st_meta_key] => latitude
        )
    [2] => Array (
        [in_user_id] => 157
        [st_meta_key] => longitude
        )
    [3] => Array (
        [in_user_id] => 203
        [st_meta_key] => city
        [st_meta_value] => Jaipur
        )
    [4] => Array (
        [in_user_id] => 203
        [st_meta_key] => latitude
        [st_meta_value] => 26.8517972
        )
    [5] => Array (
        [in_user_id] => 203
        [st_meta_key] => longitude
        [st_meta_value] => 75.7862232
        )
    [6] => Array (
        [in_user_id] => 214
        [st_meta_key] => city
        [st_meta_value] => Jaipur
        )
    [7] => Array (
        [in_user_id] => 214
        [st_meta_key] => latitude
        [st_meta_value] => 26.8517972
        )
    [8] => Array (
        [in_user_id] => 214
        [st_meta_key] => longitude
        [st_meta_value] => 75.7862232
        )
</code>```

I WANT TO OUTPUT LIKE THIS

```<code>    Array(
        [id] => 157,
        [city] => jaipur,
        [latitude] => '',
        [longitude] => '',
        [id] => 203,
        [city] => jaipur,
        [latitude] => '26.8517972',
        [longitude] => '75.7862232',
        [id] => 214,
        [city] => jaipur,
        [latitude] => '26.8517972',
        [longitude] => '75.7862232',
     )
</code>```

Please help me to solve in any way and format it as I am a beginner.

Thanks in advance for this help :)

答:
```<code>foreach ($run as $childArray)
{

    if($childArray['st_meta_key'] == 'city'){
        $fin[$i] = array(
                'id' => $childArray['in_user_id'],
                'city' => $childArray['st_meta_value'],

                );
    }
    if($childArray['st_meta_key'] == 'latitude'){
        $fin[$i] = array(
                 'id' => $childArray['in_user_id'],
                'latitude' => $childArray['st_meta_value'],

                );
    }
    if($childArray['st_meta_key'] == 'longitude'){
        $fin[$i] = array(
                'id' => $childArray['in_user_id'],
                'longitude' => $childArray['st_meta_value'],

                );
    }
    if($childArray['st_meta_key'] == 'address'){
        $fin[$i] = array(
                'id' => $childArray['in_user_id'],
                'address' => $childArray['st_meta_value'],

                );
    }
    $i++;
}
$arryc = 0;
foreach($fin as $key => $val){

   if(is_array($val)){

       foreach($val as $k => $v){

        if($k == 'id' && $k == $k)   {

               //$singleDimArray['id'] = $val['id'];
               if(!empty($val['city'])){
                $singleDimArray[$arryc]['id'] = $val['id'];
                  $singleDimArray[$arryc]['city'] = $val['city'];
               }
               if(!empty($val['address'])){
                $singleDimArray[$arryc]['id'] = $val['id'];
                   $singleDimArray[$arryc]['address'] = $val['address'];
               }
               if(!empty($val['latitude'])){
                $singleDimArray[$arryc]['id'] = $val['id'];
                   $singleDimArray[$arryc]['latitude'] = $val['latitude'];
               }
               if(!empty($val['longitude'])){
                $singleDimArray[$arryc]['id'] = $val['id'];
                   $singleDimArray[$arryc]['longitude'] = $val['longitude'];
               }

            }

            $arryc++;
        }
   }

}

$arraysMerged = [];
$newarray=[];
   foreach($singleDimArray as $x){

    $arraysMerged = array_merge($arraysMerged, $x);
    $newarray[$x['id']][]=$arraysMerged;
     }
    $FinL= array();
    foreach($newarray as $val){
       // print_r($newarray);
         $FinL[]= end($val);
    }
</code>```

echo json_encode($FinL);
         }

```<code>}
</code>```

Body:
Here is my multidimensional array. I want to extract specific fields from them and create a one dimensional array.

   [0] => Array (
        [in_user_id] => 157,
        [st_meta_key] => city
        [st_meta_value] => jaipur
        )
    [1] => Array (
        [in_user_id] => 157
        [st_meta_key] => latitude
        )
    [2] => Array (
        [in_user_id] => 157
        [st_meta_key] => longitude
        )
    [3] => Array (
        [in_user_id] => 203
        [st_meta_key] => city
        [st_meta_value] => Jaipur
        )
    [4] => Array (
        [in_user_id] => 203
        [st_meta_key] => latitude
        [st_meta_value] => 26.8517972
        )
    [5] => Array (
        [in_user_id] => 203
        [st_meta_key] => longitude
        [st_meta_value] => 75.7862232
        )
    [6] => Array (
        [in_user_id] => 214
        [st_meta_key] => city
        [st_meta_value] => Jaipur
        )
    [7] => Array (
        [in_user_id] => 214
        [st_meta_key] => latitude
        [st_meta_value] => 26.8517972
        )
    [8] => Array (
        [in_user_id] => 214
        [st_meta_key] => longitude
        [st_meta_value] => 75.7862232
        )

I WANT TO OUTPUT LIKE THIS

    Array(
        [id] => 157,
        [city] => jaipur,
        [latitude] => '',
        [longitude] => '',
        [id] => 203,
        [city] => jaipur,
        [latitude] => '26.8517972',
        [longitude] => '75.7862232',
        [id] => 214,
        [city] => jaipur,
        [latitude] => '26.8517972',
        [longitude] => '75.7862232',
     )

Please help me to solve in any way and format it as I am a beginner.

Thanks in advance for this help :)

Body:
foreach ($run as $childArray)
{

    if($childArray['st_meta_key'] == 'city'){
        $fin[$i] = array(
                'id' => $childArray['in_user_id'],
                'city' => $childArray['st_meta_value'],

                );
    }
    if($childArray['st_meta_key'] == 'latitude'){
        $fin[$i] = array(
                 'id' => $childArray['in_user_id'],
                'latitude' => $childArray['st_meta_value'],

                );
    }
    if($childArray['st_meta_key'] == 'longitude'){
        $fin[$i] = array(
                'id' => $childArray['in_user_id'],
                'longitude' => $childArray['st_meta_value'],

                );
    }
    if($childArray['st_meta_key'] == 'address'){
        $fin[$i] = array(
                'id' => $childArray['in_user_id'],
                'address' => $childArray['st_meta_value'],

                );
    }
    $i++;
}
$arryc = 0;
foreach($fin as $key => $val){

   if(is_array($val)){

       foreach($val as $k => $v){

        if($k == 'id' && $k == $k)   {

               //$singleDimArray['id'] = $val['id'];
               if(!empty($val['city'])){
                $singleDimArray[$arryc]['id'] = $val['id'];
                  $singleDimArray[$arryc]['city'] = $val['city'];
               }
               if(!empty($val['address'])){
                $singleDimArray[$arryc]['id'] = $val['id'];
                   $singleDimArray[$arryc]['address'] = $val['address'];
               }
               if(!empty($val['latitude'])){
                $singleDimArray[$arryc]['id'] = $val['id'];
                   $singleDimArray[$arryc]['latitude'] = $val['latitude'];
               }
               if(!empty($val['longitude'])){
                $singleDimArray[$arryc]['id'] = $val['id'];
                   $singleDimArray[$arryc]['longitude'] = $val['longitude'];
               }

            }

            $arryc++;
        }
   }

}

$arraysMerged = [];
$newarray=[];
   foreach($singleDimArray as $x){

    $arraysMerged = array_merge($arraysMerged, $x);
    $newarray[$x['id']][]=$arraysMerged;
     }
    $FinL= array();
    foreach($newarray as $val){
       // print_r($newarray);
         $FinL[]= end($val);
    }

echo json_encode($FinL);
         }

}


问:
How to deselect mat-option in mat-select programmatically if it stay in "active" state and non-clickable
I have mat-table, inside I have mat-select with mat-option. when I click on it - I invoke mat-dialog confirmation modal. when I click cancel (dialog.close()) and try again click on last-time-clicked mat-option - it stays in "active" state and I can't click it at all.

If I click Yes in mat-dialog - so mat-option become normal and I can click it again. I think its some trouble with mat-dialog because the mat-overlay not trigger some cleanup for buttons Idk, but  ==> how I can remove the mat-active state from mat-option programmatically?

答:
I solve it by set deselect() method on it on click action

```<code>// inside mat-select
...
<mat-option *ngFor="let option of actionsOptions"
  #opt // <== get local scope of mat-option
  (click)="opt.deselect()"  /* <== user deselect() method to ensure deselecting
                             * within mat-dialog blocking actions.
                             */
  [value]="option.id">
  {{ option.title }}
</mat-option>
...
</code>```

Hope it helps somebody, I've not found info about this case and spent too much time for this simple bug in mat-table with mat-option

Body:
I solve it by set deselect() method on it on click action

// inside mat-select
...
<mat-option *ngFor="let option of actionsOptions"
  #opt // <== get local scope of mat-option
  (click)="opt.deselect()"  /* <== user deselect() method to ensure deselecting
                             * within mat-dialog blocking actions.
                             */
  [value]="option.id">
  {{ option.title }}
</mat-option>
...

Hope it helps somebody, I've not found info about this case and spent too much time for this simple bug in mat-table with mat-option


问:
Failed to import defined modules in __init__.py
My directory looks like this :

```<code>- HttpExample:
    - __init__.py
    - DBConnection.py
    - getLatlong.py
</code>```

I want to import DBConnection and import getLatlong in __init__.py. There is no error in my __init__.py until I run it, I received :

System.Private.CoreLib: Exception while executing function: Functions.HttpExample. System.Private.CoreLib: Result: Failure
  Exception: ModuleNotFoundError: No module named 'getLatlong'

I'm trying to use function in getLatlong to use the information input by user from __init__.py to getLatlong. Below is the code:

__init__.py :

```<code>from getLatlong import result
from DBConnection import blobService, container_name, account_key, file_path

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    section = req.params.get('section')
    bound = req.params.get('bound')
    km_location = req.params.get('km_location')
    location = req.params.get('location')
    if not section:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            section = req_body.get('section')

    if section and bound and km_location:

        result(section, km_location, bound, location).getResult() #HERE

        return func.HttpResponse(f"Hello {section}, {bound}!")

    #elif section is None or bound is None or km_location is None:
    #    return func.HttpResponse("All values are mandatory!")
</code>```

I am also receiving compile error at getLatlong to import DBConnection to this class. The following values will pass to getLatlong.py. The code :

```<code>from DBConnection import blobService, container_name, account_key, file_path #Another import error here says : Unable to import DBConnection

class result:
    def __init__(self, section, bound, km_location, location):
        self.section = section
        self.bound = bound
        self.km_location = km_location
        self.location = location

    def getResult(self):

        print(self.section)
        print(self.bound)
        print(self.km_location)
        print(self.location)
</code>```

I've tried every way to import these files before I lost my mind..

答:
You could try from __app__.HttpExample import getLatlong.

There is a document about how to import module in the Shared Code folder. Check this doc:Folder structure.

It says Shared code should be kept in a separate folder in __app__. And in my test this could work for me.

Body:
My directory looks like this :

- HttpExample:
    - __init__.py
    - DBConnection.py
    - getLatlong.py

I want to import DBConnection and import getLatlong in __init__.py. There is no error in my __init__.py until I run it, I received :

System.Private.CoreLib: Exception while executing function: Functions.HttpExample. System.Private.CoreLib: Result: Failure
  Exception: ModuleNotFoundError: No module named 'getLatlong'

I'm trying to use function in getLatlong to use the information input by user from __init__.py to getLatlong. Below is the code:

__init__.py :

from getLatlong import result
from DBConnection import blobService, container_name, account_key, file_path

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    section = req.params.get('section')
    bound = req.params.get('bound')
    km_location = req.params.get('km_location')
    location = req.params.get('location')
    if not section:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            section = req_body.get('section')

    if section and bound and km_location:

        result(section, km_location, bound, location).getResult() #HERE

        return func.HttpResponse(f"Hello {section}, {bound}!")

    #elif section is None or bound is None or km_location is None:
    #    return func.HttpResponse("All values are mandatory!")

I am also receiving compile error at getLatlong to import DBConnection to this class. The following values will pass to getLatlong.py. The code :

from DBConnection import blobService, container_name, account_key, file_path #Another import error here says : Unable to import DBConnection

class result:
    def __init__(self, section, bound, km_location, location):
        self.section = section
        self.bound = bound
        self.km_location = km_location
        self.location = location

    def getResult(self):

        print(self.section)
        print(self.bound)
        print(self.km_location)
        print(self.location)

I've tried every way to import these files before I lost my mind..


问:
issues with angular to call api input via parameters
I am trying to fetch data from the API server using angular 9 bypassing id in the input from to get the phone value from JSON in the API. in this mount that not working with me :(, I don't know what the problem even I use the same format in JSON API.
like this one

this.phone = this.results.address.phone
  Please, I need someone to guide me for the right answer.

thank you :)

I live a simple of my work down!

This is my app.component.ts

```<code>import { Component } from '@angular/core';
import { HttpClient } from  '@angular/common/http';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  constructor(private _http: HttpClient){}
url='https://jsonplaceholder.typicode.com/users/1';
id='';
phone='';
results : any;
getsearcha(){
  this._http.get('https://jsonplaceholder.typicode.com/users/'+this.id)
  .subscribe(

    data => {
      this.results = data['results'];
      this.phone = this.results.address.phone
     console.log(this._http.get(this.url));
    })
}
}
</code>```

as well the is my app.component.html

```<code><h1> test app</h1>
<input type="text" [(ngModel)]=id>

<button (click)="getsearcha()">Click</button>
<hr>
phone{{phone}}
</code>```

https://stackblitz.com/edit/angular-dryp3b

答:
First of all once you hit the API , your entire response is coming in 'data' itself so no need to do the following:

```<code>  this.results = data['results'];
</code>```

Instead do:

```<code>  this.results = data;
  this.phone = this.results[(id-1)].phone // did (id-1) because indexing is
  from 0 and for id=2 you'll have appropriate result on index (2-1 i.e 1 and so on).
</code>```

Except that everything is good with your code.

Cheers !

Body:
I am trying to fetch data from the API server using angular 9 bypassing id in the input from to get the phone value from JSON in the API. in this mount that not working with me :(, I don't know what the problem even I use the same format in JSON API.
like this one

this.phone = this.results.address.phone
  Please, I need someone to guide me for the right answer.

thank you :)

I live a simple of my work down!

This is my app.component.ts

import { Component } from '@angular/core';
import { HttpClient } from  '@angular/common/http';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  constructor(private _http: HttpClient){}
url='https://jsonplaceholder.typicode.com/users/1';
id='';
phone='';
results : any;
getsearcha(){
  this._http.get('https://jsonplaceholder.typicode.com/users/'+this.id)
  .subscribe(

    data => {
      this.results = data['results'];
      this.phone = this.results.address.phone
     console.log(this._http.get(this.url));
    })
}
}

as well the is my app.component.html

 test app

<input type="text" [(ngModel)]=id>

<button (click)="getsearcha()">Click</button>

phone{{phone}}

https://stackblitz.com/edit/angular-dryp3b

Body:
First of all once you hit the API , your entire response is coming in 'data' itself so no need to do the following:

  this.results = data['results'];

Instead do:

  this.results = data;
  this.phone = this.results[(id-1)].phone // did (id-1) because indexing is
  from 0 and for id=2 you'll have appropriate result on index (2-1 i.e 1 and so on).

Except that everything is good with your code.

Cheers !


问:
Axios post call through React Native gives Network error for cloud url works for ios and not for android
I am trying make a post call through axios in react native. axios.post('https....)
But I get Network error in the console when I run this in Android but the same works in ios</p>

答:
Change your AndroidManifest.xml in order to accept usesCleartextTraffic="true" as below,

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:usesCleartextTraffic="true"
        ...>
        ...
    </application>
</manifest>
</code>```

Because usesCleartextTraffic indicates whether the app intends to use cleartext network traffic, such as cleartext HTTP. The default value for apps that target API level 27 or lower is "true". Apps that target API level 28 or higher default to "false".

If you want to allow http for some domains but not other domains you must provide networkSecurityConfig file as below.

Goto android/app/src/main/res/xml & create network_security_config.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
</network-security-config>
</code>```

Change your AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:networkSecurityConfig="@xml/network_security_config"
        ...>
        ...
    </application>
</manifest>
</code>```

Hope this helps you. Feel free for doubts.

Body:
Change your AndroidManifest.xml in order to accept usesCleartextTraffic="true" as below,

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:usesCleartextTraffic="true"
        ...>
        ...
    </application>
</manifest>

Because usesCleartextTraffic indicates whether the app intends to use cleartext network traffic, such as cleartext HTTP. The default value for apps that target API level 27 or lower is "true". Apps that target API level 28 or higher default to "false".

If you want to allow http for some domains but not other domains you must provide networkSecurityConfig file as below.

Goto android/app/src/main/res/xml & create network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
</network-security-config>

Change your AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:networkSecurityConfig="@xml/network_security_config"
        ...>
        ...
    </application>
</manifest>

Hope this helps you. Feel free for doubts.


问:
How can I get sign bit of an integer in python?
I want to be able to access the sign bit of a number in python. I can do something like n >> 31 in C since int is represented as 32 bits.

I can't make use of the conditional operator and > <.

答:
Conceptually, the bit representation of a negative integer is padded with an infinite number of 1 bits to the left (just like a non-negative number is regarded as padded with an infinite number of 0 bits). The operation n >> 31 does work (given that n is in the range of signed 32-bit numbers) in the sense that it places the sign bit (or if you prefer, one of the left-padding bits) in the lowest bit position. You just need to get rid of the rest of the left-padding bits, which you can do with a bitwise and operation like this:

```<code>n >> 31 & 1
</code>```

Or you can make use of the fact that all one bits is how −1 is represented, and simply negate the result:

```<code>-(n >> 31)
</code>```

Alternatively, you can cut off all but the lowest 32 1 bits before you do the shift, like this:

```<code>(n & 0xffffffff) >> 31
</code>```

This is all under the assumption that you are working with numbers that fit into a signed 32-bit int. If n might need a 64 bit representation, shift by 63 places instead of 31, and if it's just 16 bits numbers, shifting by 15 places is enoough. (If you use the (n & 0xffffffff) >> 31 variant, adjust the number of fs accordingly).

On machine code level, and-ing/negating and shifting is potentially much more efficient than using comparison. The former is just a couple of machine instructions, while the latter would usually boil down to a branch. Branching doesn't just take more machine instructions, it also has a bad influence on the pipelining and out-of-order execution of modern CPUs. But Python execution takes place in a higher-level layer than machine code execution, and therefore it's difficult to say anything about the performance impact in Python: it may depend on the context – as it would in machine code – and may therefore also be difficult to test generally. (Caveat: I don't know much about how low-level execution happens in CPython, or in Python in general. For someone who does, this might not be so difficult to say.)

If you don't know how big n is (in Python, an integer is not required to fit into any specific number of bits), you can use bit_length() to find out. This will work for integers of any size:

```<code>-(n >> n.bit_length())
</code>```

The bit_length() operation might boil down to a single machine instruction, or it might actually need a loop to find the result, depending on the implementation and the underlying machine architecture. In the latter case, this should be noticeably more costly than using a constant

Final remark: in C, n >> 31 is actually not guaranteed to work like you assume, because the C language leaves it undefined whether >> does logical right shift (like you assume) or arithmetic shift right (like Python does). In some languages, these are different operators, which makes it clear what you get. In Java for instance, logical shift right is >>>, and arithmetic shift right is >>.

Body:
Conceptually, the bit representation of a negative integer is padded with an infinite number of 1 bits to the left (just like a non-negative number is regarded as padded with an infinite number of 0 bits). The operation n >> 31 does work (given that n is in the range of signed 32-bit numbers) in the sense that it places the sign bit (or if you prefer, one of the left-padding bits) in the lowest bit position. You just need to get rid of the rest of the left-padding bits, which you can do with a bitwise and operation like this:

n >> 31 & 1

Or you can make use of the fact that all one bits is how −1 is represented, and simply negate the result:

-(n >> 31)

Alternatively, you can cut off all but the lowest 32 1 bits before you do the shift, like this:

(n & 0xffffffff) >> 31

This is all under the assumption that you are working with numbers that fit into a signed 32-bit int. If n might need a 64 bit representation, shift by 63 places instead of 31, and if it's just 16 bits numbers, shifting by 15 places is enoough. (If you use the (n & 0xffffffff) >> 31 variant, adjust the number of fs accordingly).

On machine code level, and-ing/negating and shifting is potentially much more efficient than using comparison. The former is just a couple of machine instructions, while the latter would usually boil down to a branch. Branching doesn't just take more machine instructions, it also has a bad influence on the pipelining and out-of-order execution of modern CPUs. But Python execution takes place in a higher-level layer than machine code execution, and therefore it's difficult to say anything about the performance impact in Python: it may depend on the context – as it would in machine code – and may therefore also be difficult to test generally. (Caveat: I don't know much about how low-level execution happens in CPython, or in Python in general. For someone who does, this might not be so difficult to say.)

If you don't know how big n is (in Python, an integer is not required to fit into any specific number of bits), you can use bit_length() to find out. This will work for integers of any size:

-(n >> n.bit_length())

The bit_length() operation might boil down to a single machine instruction, or it might actually need a loop to find the result, depending on the implementation and the underlying machine architecture. In the latter case, this should be noticeably more costly than using a constant

Final remark: in C, n >> 31 is actually not guaranteed to work like you assume, because the C language leaves it undefined whether >> does logical right shift (like you assume) or arithmetic shift right (like Python does). In some languages, these are different operators, which makes it clear what you get. In Java for instance, logical shift right is >>>, and arithmetic shift right is >>.


问:
presenting a menu multple times with Tkinter
I'm trying to build a simple 'Connect 4' game.  In the game, I'd like a menu with radiobuttons to present itself to the user at every turn, so that he/she could pick the next move.

I've tried putting the menu into a "while" loop, but it simply doesn't do any action.  I don't know how to fix it, because I don't understand exactly how tkinter works.  I've seen some other questions touching on this subject, but I still can't figure out how to fix it.

Below is the code, along with the two classes I used along with it.  The menu I'm trying to present in a loop is in 'present_columns_choice', which is being used in a loop in 'handle_two_humans'

Would be grateful for any help.  Thanks!

```<code>from game import *
from tkinter import *

HUMAN = 0
COMPUTER = 1
GRID_SIZE = 50
NUM_ROWS = 6
NUM_COLUMNS = 7
COLOR_A = "red"
COLOR_B = "blue"

class GameGUI:

def __init__(self, root):
    self.__root = root
    self.__player_A = None
    self.__player_B = None

def assign_player(self, player, identity):
    if player == "player A":
        self.__player_A = identity
    elif player == "player B":
        self.__player_B = identity
    print("Player A is:  " + str(self.__player_A))
    print("Player B is:  " + str(self.__player_B))

def present_player_choice(self):
    self.ask_choose_player("player A")
    self.ask_choose_player("player B")
    Button(self.__root, text="OK", command=quit).pack(anchor=W)

def ask_choose_player(self, player):
    Label(self.__root, text="Who would you like to play " + player + "?").pack(anchor=W)
    var = IntVar()
    Radiobutton(self.__root, text="human", variable=var,
                command=lambda:self.assign_player(player, HUMAN), value=1).pack(anchor=W)
    Radiobutton(self.__root, text="computer", variable=var,
                command=lambda:self.assign_player(player, COMPUTER), value=2).pack(anchor=W)

def get_playerA(self):
    return self.__player_A

def get_playerB(self):
    return self.__player_B

def handle_two_humans(self):

    game = Game()
    canvas_width = GRID_SIZE*NUM_COLUMNS
    canvas_height = GRID_SIZE*NUM_ROWS
    canvas = Canvas(self.__root, width=canvas_width, height=canvas_height)
    canvas.pack()
    for row_ind in range(NUM_ROWS):
        for column_ind in range(NUM_COLUMNS):
            canvas.create_rectangle(column_ind*GRID_SIZE, row_ind*GRID_SIZE,
                                    (column_ind+1)*GRID_SIZE, (row_ind+1)*GRID_SIZE)
    while not IS_GAME_WON:
        self.present_columns_choice(game, canvas)

def add_disc(self, game, column, canvas):

    current_player = game.get_current_player()
    if current_player == PLAYER_A:
        self.fill_square(game, canvas, COLOR_A, column)
    elif current_player == PLAYER_B:
        self.fill_square(game, canvas, COLOR_B, column)
    game.make_move(column)

def present_columns_choice(self, game, canvas):
    columns = game.get_board().get_available_columns()
    var = IntVar()
    Label(self.__root, text="The following columns are still available.  "
                            "Where would you like to place your disc?").pack(anchor=W)
    for ind, column in enumerate(columns):
        shown_column = column+1
        Radiobutton(self.__root, text=shown_column, padx=20, variable=var, value=ind,
                    command=lambda column=column: self.add_disc(game, column, canvas)).pack(anchor=W)
    Button(self.__root, text="OK", command=quit).pack(anchor=W)

def fill_square(self, game, canvas, color, column):
    """  Fills square of column chosen by player.  """
    row = game.get_board().get_available_row(column)
    canvas.create_rectangle(column*GRID_SIZE, row*GRID_SIZE, (column+1)*GRID_SIZE,
                            (row+1)*GRID_SIZE, fill = color)

if __name__ == '__main__':

root = Tk()
gui = GameGUI(root)
gui.handle_two_humans()
mainloop()

Here's the Game class, which was used here:

from board import *

PLAYER_A = 1
PLAYER_B = 2
INITIAL_ROW = 0
INITIAL_COLUMN = 0
FINAL_ROW = 5
FINAL_COLUMN = 6
ILLEGAL_LOCATION_MSG = "Illegal location."
ILLEGAL_MOVE_MSG = "Illegal move."
IS_GAME_WON = False
WINNER = None

class Game:

def __init__(self):
    self.__current_player = PLAYER_A
    self.__board = Board()
    self.__is_game_won = False
    self.__winner = None

def make_move(self, column):
    """  Makes move and updates board and current player, if column is a valid choice and game is ongoing.  """
    possible_winner = self.__current_player
    if self.__board.is_col_illegal(column) or self.__is_game_won:
        raise Exception(ILLEGAL_MOVE_MSG)
    self.do_move(column)
    if self.__board.is_win(column):
        self.__is_game_won = True
        self.__winner = possible_winner

def do_move(self, column):
    """  Actual implementation of the move.  """
    if self.__current_player == PLAYER_A:
        self.__board.update_board(column, PLAYER_A)
        self.__current_player = PLAYER_B
    elif self.__current_player == PLAYER_B:
        self.__board.update_board(column, PLAYER_B)
        self.__current_player = PLAYER_A

def get_winner(self):
   """  Returns winner, or None if there is none.  """
   return self.__winner

def get_player_at(self, row, col):
    """  Returns the player whose disc is at the given position in the game.  """
    if row < INITIAL_ROW or row > FINAL_ROW or col < INITIAL_COLUMN or col > FINAL_COLUMN:
        raise Exception(ILLEGAL_LOCATION_MSG)
    return self.__board.get_board()[row][col]

def get_current_player(self):
    """  Returns current_player.  """
    return self.__current_player

def get_board(self):
    """  Returns board."""
    return self.__board

And here's Board, which is used in Game:

NUM_ROWS = 6
NUM_COLUMNS = 7
INITIAL_VALUE = None
WIN_COUNT = 4
FIRST_ROW = 5
LAST_ROW = 0

class Board:

def __init__(self):
    self.__playboard = []
    self.__available_rows_list = NUM_COLUMNS*[NUM_ROWS-1]
    initial_row = NUM_COLUMNS * [INITIAL_VALUE]
    for i in range(NUM_ROWS):
        self.__playboard.append(initial_row.copy())

def get_available_columns(self):
    """  Returns all columns that still have empty space in them.  """
    available_columns = []
    for col in range(len(self.__available_rows_list)):
        if self.__available_rows_list[col] >= 0:
            available_columns.append(col)
    return available_columns

def get_playboard(self):
    """  Returns board.  """
    return self.__playboard

def update_board(self, col, val):
    """  Updates current status of board.  """
    row = self.__available_rows_list[col]
    self.__playboard[row][col] = val
    self.__update_row(col)

def __update_row(self, col):
    """  Updates available_row_list.  """
    self.__available_rows_list[col] = self.__available_rows_list[col] - 1

def __is_col_available(self, col):
    """  Checks if given col has empty spaces left on the playboard.  """
    if self.__available_rows_list[col] < 0:
        return False
    return True

def __is_col_exist(self, col):
    """  Checks if given column is within the capacity of the playboard.  """
    if col < 0 or col >= NUM_COLUMNS:
        return False
    return True

def is_col_illegal(self, col):
    """  Checks if given column is an illegal option.  """
    if not self.__is_col_available(col) or not self.__is_col_exist(col):
        return True
    return False

def print_playboard(self):
    for row in self.__playboard:
        print(row)

def is_win(self, col):
    """  Checks if current state of board resulted in a win.  """
    row = self.__available_rows_list[col]+1
    if self.__check_vertical_win(row, col) or self.__check_horizontal_win(row, col) or \
            self.__check_decreasing_diagonal_win(row, col) or self.__check_increasing_diagonal_win(row, col):
                return True
    return False

def __check_increasing_diagonal_win(self, original_row, original_col):
    """  Checks if player has won in the increasing diagonal direction.  """
    count = 1
    player = self.__playboard[original_row][original_col]
    col = original_col + 1
    row = original_row - 1
    while self.__is_col_exist(col) and row >= LAST_ROW and self.__playboard[row][col] == player:
        count = count + 1
        if count == WIN_COUNT:
            return True
        col = col + 1
        row = row - 1
    # Then: undergo same process, this time in the opposite direction.
    col = original_col - 1
    row = original_row + 1
    while self.__is_col_exist(col) and row <= FIRST_ROW and self.__playboard[row][col] == player:
        count = count + 1
        if count == WIN_COUNT:
            return True
        col = col - 1
        row = row + 1

def __check_decreasing_diagonal_win(self, original_row, original_col):
    """  Checks if player has won in the decreasing diagonal direction.  """
    count = 1
    player = self.__playboard[original_row][original_col]
    col = original_col + 1
    row = original_row + 1
    while self.__is_col_exist(col) and row <= FIRST_ROW and self.__playboard[row][col] == player:
        count = count + 1
        if count == WIN_COUNT:
            return True
        col = col + 1
        row = row + 1
    # Then: undergo same process, this time in the opposite direction.
    col = original_col - 1
    row = original_row - 1
    while self.__is_col_exist(col) and row >= LAST_ROW and self.__playboard[row][col] == player:
        count = count + 1
        if count == WIN_COUNT:
            return True
        col = col - 1
        row = row - 1

def __check_vertical_win(self, original_row, col):
    """  Checks if player has won in the horizontal direction.  """
    count = 1
    player = self.__playboard[original_row][col]
    row = original_row + 1
    while row <= FIRST_ROW and self.__playboard[row][col] == player:
        count = count + 1
        if count == WIN_COUNT:
            return True
        row = row + 1

def __check_horizontal_win(self, row, original_col):
    """  Checks if player has won in the horizontal direction.  """
    count = 1
    player = self.__playboard[row][original_col]
    col = original_col + 1
    while self.__is_col_exist(col) and self.__playboard[row][col] == player:
        count = count + 1
        if count == WIN_COUNT:
            return True
        col = col + 1
    # Then: undergo same process, this time in the opposite direction (the left).
    col = original_col - 1
    while self.__is_col_exist(col) and self.__playboard[row][col] == player:
        count = count + 1
        if count == WIN_COUNT:
            return True
        col = col - 1

def get_available_row(self, column):
    """  Returns the row which will be filled if you choose this column.  """
    return self.__available_rows_list[column]
</code>```

答:
The while loop inside handle_two_humans() will block the tkinter mainloop.

Since you do the move if a radiobutton is selected in the menu, why don't you just do the move when you click on the board?

Create a function check_move() in GameGUI class:

```<code>def check_move(self, game, column, canvas):
    if not game.get_winner():
        self.add_disc(game, column, canvas)
</code>```

And modify handle_two_humands() as below:

```<code>def handle_two_humans(self):
    game = Game()
    canvas_width = GRID_SIZE*NUM_COLUMNS
    canvas_height = GRID_SIZE*NUM_ROWS
    canvas = Canvas(self.__root, width=canvas_width, height=canvas_height)
    canvas.pack()
    for row_ind in range(NUM_ROWS):
        for column_ind in range(NUM_COLUMNS):
            canvas.create_rectangle(column_ind*GRID_SIZE, row_ind*GRID_SIZE,
                                    (column_ind+1)*GRID_SIZE, (row_ind+1)*GRID_SIZE)
    # bind mouse click event to perform move
    # e.x//GRID_SIZE will get the clicked column
    canvas.bind('<Button-1>', lambda e: self.check_move(game, e.x//GRID_SIZE, canvas))
</code>```

Body:
I'm trying to build a simple 'Connect 4' game.  In the game, I'd like a menu with radiobuttons to present itself to the user at every turn, so that he/she could pick the next move.

I've tried putting the menu into a "while" loop, but it simply doesn't do any action.  I don't know how to fix it, because I don't understand exactly how tkinter works.  I've seen some other questions touching on this subject, but I still can't figure out how to fix it.

Below is the code, along with the two classes I used along with it.  The menu I'm trying to present in a loop is in 'present_columns_choice', which is being used in a loop in 'handle_two_humans'

Would be grateful for any help.  Thanks!

from game import *
from tkinter import *

HUMAN = 0
COMPUTER = 1
GRID_SIZE = 50
NUM_ROWS = 6
NUM_COLUMNS = 7
COLOR_A = "red"
COLOR_B = "blue"

class GameGUI:

def __init__(self, root):
    self.__root = root
    self.__player_A = None
    self.__player_B = None

def assign_player(self, player, identity):
    if player == "player A":
        self.__player_A = identity
    elif player == "player B":
        self.__player_B = identity
    print("Player A is:  " + str(self.__player_A))
    print("Player B is:  " + str(self.__player_B))

def present_player_choice(self):
    self.ask_choose_player("player A")
    self.ask_choose_player("player B")
    Button(self.__root, text="OK", command=quit).pack(anchor=W)

def ask_choose_player(self, player):
    Label(self.__root, text="Who would you like to play " + player + "?").pack(anchor=W)
    var = IntVar()
    Radiobutton(self.__root, text="human", variable=var,
                command=lambda:self.assign_player(player, HUMAN), value=1).pack(anchor=W)
    Radiobutton(self.__root, text="computer", variable=var,
                command=lambda:self.assign_player(player, COMPUTER), value=2).pack(anchor=W)

def get_playerA(self):
    return self.__player_A

def get_playerB(self):
    return self.__player_B

def handle_two_humans(self):

    game = Game()
    canvas_width = GRID_SIZE*NUM_COLUMNS
    canvas_height = GRID_SIZE*NUM_ROWS
    canvas = Canvas(self.__root, width=canvas_width, height=canvas_height)
    canvas.pack()
    for row_ind in range(NUM_ROWS):
        for column_ind in range(NUM_COLUMNS):
            canvas.create_rectangle(column_ind*GRID_SIZE, row_ind*GRID_SIZE,
                                    (column_ind+1)*GRID_SIZE, (row_ind+1)*GRID_SIZE)
    while not IS_GAME_WON:
        self.present_columns_choice(game, canvas)

def add_disc(self, game, column, canvas):

    current_player = game.get_current_player()
    if current_player == PLAYER_A:
        self.fill_square(game, canvas, COLOR_A, column)
    elif current_player == PLAYER_B:
        self.fill_square(game, canvas, COLOR_B, column)
    game.make_move(column)

def present_columns_choice(self, game, canvas):
    columns = game.get_board().get_available_columns()
    var = IntVar()
    Label(self.__root, text="The following columns are still available.  "
                            "Where would you like to place your disc?").pack(anchor=W)
    for ind, column in enumerate(columns):
        shown_column = column+1
        Radiobutton(self.__root, text=shown_column, padx=20, variable=var, value=ind,
                    command=lambda column=column: self.add_disc(game, column, canvas)).pack(anchor=W)
    Button(self.__root, text="OK", command=quit).pack(anchor=W)

def fill_square(self, game, canvas, color, column):
    """  Fills square of column chosen by player.  """
    row = game.get_board().get_available_row(column)
    canvas.create_rectangle(column*GRID_SIZE, row*GRID_SIZE, (column+1)*GRID_SIZE,
                            (row+1)*GRID_SIZE, fill = color)

if __name__ == '__main__':

root = Tk()
gui = GameGUI(root)
gui.handle_two_humans()
mainloop()

Here's the Game class, which was used here:

from board import *

PLAYER_A = 1
PLAYER_B = 2
INITIAL_ROW = 0
INITIAL_COLUMN = 0
FINAL_ROW = 5
FINAL_COLUMN = 6
ILLEGAL_LOCATION_MSG = "Illegal location."
ILLEGAL_MOVE_MSG = "Illegal move."
IS_GAME_WON = False
WINNER = None

class Game:

def __init__(self):
    self.__current_player = PLAYER_A
    self.__board = Board()
    self.__is_game_won = False
    self.__winner = None

def make_move(self, column):
    """  Makes move and updates board and current player, if column is a valid choice and game is ongoing.  """
    possible_winner = self.__current_player
    if self.__board.is_col_illegal(column) or self.__is_game_won:
        raise Exception(ILLEGAL_MOVE_MSG)
    self.do_move(column)
    if self.__board.is_win(column):
        self.__is_game_won = True
        self.__winner = possible_winner

def do_move(self, column):
    """  Actual implementation of the move.  """
    if self.__current_player == PLAYER_A:
        self.__board.update_board(column, PLAYER_A)
        self.__current_player = PLAYER_B
    elif self.__current_player == PLAYER_B:
        self.__board.update_board(column, PLAYER_B)
        self.__current_player = PLAYER_A

def get_winner(self):
   """  Returns winner, or None if there is none.  """
   return self.__winner

def get_player_at(self, row, col):
    """  Returns the player whose disc is at the given position in the game.  """
    if row < INITIAL_ROW or row > FINAL_ROW or col < INITIAL_COLUMN or col > FINAL_COLUMN:
        raise Exception(ILLEGAL_LOCATION_MSG)
    return self.__board.get_board()[row][col]

def get_current_player(self):
    """  Returns current_player.  """
    return self.__current_player

def get_board(self):
    """  Returns board."""
    return self.__board

And here's Board, which is used in Game:

NUM_ROWS = 6
NUM_COLUMNS = 7
INITIAL_VALUE = None
WIN_COUNT = 4
FIRST_ROW = 5
LAST_ROW = 0

class Board:

def __init__(self):
    self.__playboard = []
    self.__available_rows_list = NUM_COLUMNS*[NUM_ROWS-1]
    initial_row = NUM_COLUMNS * [INITIAL_VALUE]
    for i in range(NUM_ROWS):
        self.__playboard.append(initial_row.copy())

def get_available_columns(self):
    """  Returns all columns that still have empty space in them.  """
    available_columns = []
    for col in range(len(self.__available_rows_list)):
        if self.__available_rows_list[col] >= 0:
            available_columns.append(col)
    return available_columns

def get_playboard(self):
    """  Returns board.  """
    return self.__playboard

def update_board(self, col, val):
    """  Updates current status of board.  """
    row = self.__available_rows_list[col]
    self.__playboard[row][col] = val
    self.__update_row(col)

def __update_row(self, col):
    """  Updates available_row_list.  """
    self.__available_rows_list[col] = self.__available_rows_list[col] - 1

def __is_col_available(self, col):
    """  Checks if given col has empty spaces left on the playboard.  """
    if self.__available_rows_list[col] < 0:
        return False
    return True

def __is_col_exist(self, col):
    """  Checks if given column is within the capacity of the playboard.  """
    if col < 0 or col >= NUM_COLUMNS:
        return False
    return True

def is_col_illegal(self, col):
    """  Checks if given column is an illegal option.  """
    if not self.__is_col_available(col) or not self.__is_col_exist(col):
        return True
    return False

def print_playboard(self):
    for row in self.__playboard:
        print(row)

def is_win(self, col):
    """  Checks if current state of board resulted in a win.  """
    row = self.__available_rows_list[col]+1
    if self.__check_vertical_win(row, col) or self.__check_horizontal_win(row, col) or \
            self.__check_decreasing_diagonal_win(row, col) or self.__check_increasing_diagonal_win(row, col):
                return True
    return False

def __check_increasing_diagonal_win(self, original_row, original_col):
    """  Checks if player has won in the increasing diagonal direction.  """
    count = 1
    player = self.__playboard[original_row][original_col]
    col = original_col + 1
    row = original_row - 1
    while self.__is_col_exist(col) and row >= LAST_ROW and self.__playboard[row][col] == player:
        count = count + 1
        if count == WIN_COUNT:
            return True
        col = col + 1
        row = row - 1
    # Then: undergo same process, this time in the opposite direction.
    col = original_col - 1
    row = original_row + 1
    while self.__is_col_exist(col) and row <= FIRST_ROW and self.__playboard[row][col] == player:
        count = count + 1
        if count == WIN_COUNT:
            return True
        col = col - 1
        row = row + 1

def __check_decreasing_diagonal_win(self, original_row, original_col):
    """  Checks if player has won in the decreasing diagonal direction.  """
    count = 1
    player = self.__playboard[original_row][original_col]
    col = original_col + 1
    row = original_row + 1
    while self.__is_col_exist(col) and row <= FIRST_ROW and self.__playboard[row][col] == player:
        count = count + 1
        if count == WIN_COUNT:
            return True
        col = col + 1
        row = row + 1
    # Then: undergo same process, this time in the opposite direction.
    col = original_col - 1
    row = original_row - 1
    while self.__is_col_exist(col) and row >= LAST_ROW and self.__playboard[row][col] == player:
        count = count + 1
        if count == WIN_COUNT:
            return True
        col = col - 1
        row = row - 1

def __check_vertical_win(self, original_row, col):
    """  Checks if player has won in the horizontal direction.  """
    count = 1
    player = self.__playboard[original_row][col]
    row = original_row + 1
    while row <= FIRST_ROW and self.__playboard[row][col] == player:
        count = count + 1
        if count == WIN_COUNT:
            return True
        row = row + 1

def __check_horizontal_win(self, row, original_col):
    """  Checks if player has won in the horizontal direction.  """
    count = 1
    player = self.__playboard[row][original_col]
    col = original_col + 1
    while self.__is_col_exist(col) and self.__playboard[row][col] == player:
        count = count + 1
        if count == WIN_COUNT:
            return True
        col = col + 1
    # Then: undergo same process, this time in the opposite direction (the left).
    col = original_col - 1
    while self.__is_col_exist(col) and self.__playboard[row][col] == player:
        count = count + 1
        if count == WIN_COUNT:
            return True
        col = col - 1

def get_available_row(self, column):
    """  Returns the row which will be filled if you choose this column.  """
    return self.__available_rows_list[column]

Body:
The while loop inside handle_two_humans() will block the tkinter mainloop.

Since you do the move if a radiobutton is selected in the menu, why don't you just do the move when you click on the board?

Create a function check_move() in GameGUI class:

def check_move(self, game, column, canvas):
    if not game.get_winner():
        self.add_disc(game, column, canvas)

And modify handle_two_humands() as below:

def handle_two_humans(self):
    game = Game()
    canvas_width = GRID_SIZE*NUM_COLUMNS
    canvas_height = GRID_SIZE*NUM_ROWS
    canvas = Canvas(self.__root, width=canvas_width, height=canvas_height)
    canvas.pack()
    for row_ind in range(NUM_ROWS):
        for column_ind in range(NUM_COLUMNS):
            canvas.create_rectangle(column_ind*GRID_SIZE, row_ind*GRID_SIZE,
                                    (column_ind+1)*GRID_SIZE, (row_ind+1)*GRID_SIZE)
    # bind mouse click event to perform move
    # e.x//GRID_SIZE will get the clicked column
    canvas.bind('<Button-1>', lambda e: self.check_move(game, e.x//GRID_SIZE, canvas))


问:
How to interpret linux kernel trap error line?
I have a socket application written in C++ which runs on Linux. It crashed this morning and when I check the /var/log/messages I see the following line at the time of the crash:

```<code>kernel: traps: LogProcessor[9364] general protection ip:4f2555 sp:7fbd529b1670 error:0 in MyPrg[400000+21a000]
</code>```

I want to dig into the code and find the reason but I don't know how to interpret the values in the error line.

Does it mean the error is caused by LogProcessor? What are the values "ip", "sp", "error:0", MyPrg[400000+21a000] ?

答:
The most meaningful information is Instruction Pointer (IP). You can examine your binary with GNU tools and check what happened. For example with addr2line

addr2line -e <your binary> 0x4f2555
```

If your application was build with debug symbols (-g) and if fault happened in your code (not library), output should show you the problem.

SP is Stack Pointer at the time of the crash. MyPrg[400000+21a000] tells you Virtual Address of binary.

error:0 means dividing by zero (if your application works on x86 architecture):
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/arch/x86/include/asm/traps.h#n148

Body:
I have a socket application written in C++ which runs on Linux. It crashed this morning and when I check the /var/log/messages I see the following line at the time of the crash:

kernel: traps: LogProcessor[9364] general protection ip:4f2555 sp:7fbd529b1670 error:0 in MyPrg[400000+21a000]

I want to dig into the code and find the reason but I don't know how to interpret the values in the error line.

Does it mean the error is caused by LogProcessor? What are the values "ip", "sp", "error:0", MyPrg[400000+21a000] ?

Body:
The most meaningful information is Instruction Pointer (IP). You can examine your binary with GNU tools and check what happened. For example with addr2line

addr2line -e <your binary> 0x4f2555

If your application was build with debug symbols (-g) and if fault happened in your code (not library), output should show you the problem.

SP is Stack Pointer at the time of the crash. MyPrg[400000+21a000] tells you Virtual Address of binary.

error:0 means dividing by zero (if your application works on x86 architecture):
https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/arch/x86/include/asm/traps.h#n148


问:
Can't get realtime data after deleting the document
I'm going to add like feature to the app in React + Redux + Firebase. When clicking "Like" (createLike) works in realtime but deleteLike doesn't work in realtime. With reloading, it shows "Like" after clicking "Unlike". The issue is deleteDestory is not working asynchronously in Redux + Firestore.

The code:
I define currentUser from Firestore user and id is fetched from params. The user likes the content of each article.

```<code>  onLike = value => {
    const { id, currentUser } = this.props;
    if (value) {
      this.props.createLike(currentUser.uid, id);
    } else {
      this.props.deleteLike(currentUser.uid, id);
    }
  };

  renderLike = () => {
    const { like } = this.props;

      if (like.is_like) {
        return (
          <button
            className="like"
            onClick={() => this.onLike(true)}
          >
            <span>Like</span>
          </button>
        );
      } else {
        return (
          <button
            className="unlike"
            onClick={() => this.onLike(false)}
          >
            <span>Unlike</span>
          </button>
        );
      }
  };
</code>```

The Redux code:

```<code>// Fetch like
export function fetchLike(id) {
  return dispatch => {
    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        likesRef
          .where("uid", "==", user.uid)
          .where("cid", "==", id)
          .onSnapshot(function(querySnapshot) {
            if (querySnapshot) {
              querySnapshot.forEach(function(doc) {
                dispatch({ type: FETCH_LIKE, payload: doc.data() });
              });
            }
          });
      }
    });
  };
}

// Delete like
export function deleteLike(uid, cid) {
  return dispatch => {
    likesRef
      .where("uid", "==", uid)
      .where("cid", "==", cid)
      .get()
      .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
          doc.ref.delete();
        });
        dispatch({ type: DELETE_LIKE });
      });
  };
}
</code>```

Reducer:

```<code>import { FETCH_LIKE } from "../actions";

const initialState = {
  is_like: true
};

export default (state = initialState, action) => {
  switch (action.type) {
    case FETCH_LIKE:
      return action.payload;

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

Addition

I add createLike here.

```<code>// Create Like
export function createLike(uid, cid) {
  return dispatch => {
    likesRef
      .add({
        uid: uid,
        cid: cid,
        created_at: firebase.firestore.FieldValue.serverTimestamp()
      })
      .then(function() {
        dispatch({ type: CREATE_LIKE });
      });
  };
}
</code>```

答:
I have it done.</p>

```<code>import { FETCH_LIKE, DELETE_LIKE } from "../actions";
const initialState = {
  is_like: true
};
export default (state = initialState, action) => {
  switch (action.type) {
    case FETCH_LIKE:
      return action.payload;
    case DELETE_LIKE:
      return { is_like: true };
    default:
      return state;
  }
};
</code>```

Body:
I'm going to add like feature to the app in React + Redux + Firebase. When clicking "Like" (createLike) works in realtime but deleteLike doesn't work in realtime. With reloading, it shows "Like" after clicking "Unlike". The issue is deleteDestory is not working asynchronously in Redux + Firestore.

The code:
I define currentUser from Firestore user and id is fetched from params. The user likes the content of each article.

  onLike = value => {
    const { id, currentUser } = this.props;
    if (value) {
      this.props.createLike(currentUser.uid, id);
    } else {
      this.props.deleteLike(currentUser.uid, id);
    }
  };

  renderLike = () => {
    const { like } = this.props;

      if (like.is_like) {
        return (
          <button
            className="like"
            onClick={() => this.onLike(true)}
          >
            Like
          </button>
        );
      } else {
        return (
          <button
            className="unlike"
            onClick={() => this.onLike(false)}
          >
            Unlike
          </button>
        );
      }
  };

The Redux code:

// Fetch like
export function fetchLike(id) {
  return dispatch => {
    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        likesRef
          .where("uid", "==", user.uid)
          .where("cid", "==", id)
          .onSnapshot(function(querySnapshot) {
            if (querySnapshot) {
              querySnapshot.forEach(function(doc) {
                dispatch({ type: FETCH_LIKE, payload: doc.data() });
              });
            }
          });
      }
    });
  };
}

// Delete like
export function deleteLike(uid, cid) {
  return dispatch => {
    likesRef
      .where("uid", "==", uid)
      .where("cid", "==", cid)
      .get()
      .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
          doc.ref.delete();
        });
        dispatch({ type: DELETE_LIKE });
      });
  };
}

Reducer:

import { FETCH_LIKE } from "../actions";

const initialState = {
  is_like: true
};

export default (state = initialState, action) => {
  switch (action.type) {
    case FETCH_LIKE:
      return action.payload;

    default:
      return state;
  }
};

Addition

I add createLike here.

// Create Like
export function createLike(uid, cid) {
  return dispatch => {
    likesRef
      .add({
        uid: uid,
        cid: cid,
        created_at: firebase.firestore.FieldValue.serverTimestamp()
      })
      .then(function() {
        dispatch({ type: CREATE_LIKE });
      });
  };
}

Body:
I have it done.

import { FETCH_LIKE, DELETE_LIKE } from "../actions";
const initialState = {
  is_like: true
};
export default (state = initialState, action) => {
  switch (action.type) {
    case FETCH_LIKE:
      return action.payload;
    case DELETE_LIKE:
      return { is_like: true };
    default:
      return state;
  }
};


问:
Android Studio Update 3.3.1 debugging breakpoints executing very slowly?
I have updated my Android Studio to version 3.3.1, but now breakpoints are executing very slowly? First breakpoint take around 5 minutes to execute.

Can anyone please tell me what can I do to make it work like it was in the previous version?

答:
just remove all breakup points in your android studio.then automatically android debug will be fast.

remove all breakpoint step:
go to debugger then select red button it will pop up all debugger break point and then remove.


问:
Programmatic scheduling - what is the best approach?
I need to start multiple independent periodic tasks based on some configuration data - the total number is not known upfront. For example, I would like to check the content of different directories with different intervals and different parameters, where the list and parameters are read from the configuration.

It seems to me that the quarkus-scheduler can schedule just the fixed, upfront-known methods. What is the best approach to do the scheduling dynamically/programmatically? Is vertx.setPeriodic the right approach or should I somehow access Quartz?

答:
Yes, you can inject a managed Vertx instance and make use of Vertx.setPeriodic() or Vertx.setTimer() (one-shot timer). But keep in mind that the handler is executed on an event loop thread and so the code should not block. If you really need to execute some blocking code then look at Vertx.executeBlocking().

The plan is to add an injectable managed ScheduledExecutorService for similar use cases.

There is also https://github.com/quarkusio/quarkus/issues/7246 - this would allow you to leverage the Quartz API (when using the quarkus-quartz extension).