问:
Getting the Angular error on hot reload of webpack server to browser console for jhipster only, not at the other compilation
I have a debug dev set up configured according to jHipster instruction https://www.jhipster.tech/development/ with proxy webpack server and broswersink. The server side works fine, the static files are pulled well from it and can be requested on localhost:9000 and localhost:9060, but not the angular app itself when the localhost:9000/ nor the localhost:9000/api is called on the browser tab under the browsersynk. I shows me the error in the browser console like this:

```<code>Error: Invalid configuration of route 'teacher/class/:id'. One of the following must be provided: component, redirectTo, children or loadChildren
    at validateNode (router.js?6580:607)
    at validateConfig (router.js?6580:577)
    at validateNode (router.js?6580:623)
    at validateConfig (router.js?6580:577)
    at Router.resetConfig (router.js?6580:4111)
    at new Router (router.js?6580:3779)
    at setupRouter (router.js?6580:5591)
    at _callFactory (core.js?09c9:18520)
    at _createProviderInstance (core.js?09c9:18466)
    at initNgModule (core.js?09c9:18396)
</code>```

And it doesn't point to almost the same routes configured in the same file. I had no idea what is wrong with this specific route.

In one place I have a couple of routes configured like:

```<code>import { Route, Routes } from '@angular/router';

import { CreateKindergartenclassComponent } from 'app/businesslogic';
import { DetailKindergartenclassComponent } from 'app/businesslogic';
import { ListKindergartenclassComponent } from 'app/businesslogic';
import { SelectKindergartenclassComponent } from 'app/businesslogic';
import { UserRouteAccessService } from 'app/core';
import { KindergartenClassResolve } from 'app/entities/kindergarten-class';
import { CommentResolve } from 'app/entities/comment';

export const createKindergartenclassRoute: Route = {
  path: 'teacher/class/create',
  component: CreateKindergartenclassComponent,
  data: {
    authorities: ['ROLE_TEACHER_PAID'],
    pageTitle: 'businesslogic.create.kindergartenclass.title'
  },
  canActivate: [UserRouteAccessService]
};

export const detailKindergartenclassRouteChild: Route = {
  path: 'child/class/:id',
  component: DetailKindergartenclassComponent,
  data: {
    authorities: ['ROLE_CHILD_PAID'],
    pageTitle: 'businesslogic.kindergartenclass.title'
  },
  resolve: {
    kindergartenClass: KindergartenClassResolve
  },
  canActivate: [UserRouteAccessService]
};

export const detailKindergartenclassRouteTeacher: Route = {
  path: 'teacher/class/:id',
  component: DetailKindergartenclassComponent,
  data: {
    authorities: ['ROLE_TEACHER_PAID'],
    pageTitle: 'businesslogic.kindergartenclass.title'
  },
  resolve: {
    kindergartenClass: KindergartenClassResolve
  },
  canActivate: [UserRouteAccessService]
};

export const listKindergartenclassRoute: Route = {
  path: 'teacher/classes',
  component: ListKindergartenclassComponent,
  data: {
    authorities: ['ROLE_TEACHER_PAID'],
    pageTitle: 'businesslogic.list.kindergartenclass.title'
  },
  resolve: {
    kindergartenClass: KindergartenClassResolve
  },
  canActivate: [UserRouteAccessService]
};

export const listKindergartenclassRouteChild: Route = {
  path: 'child/classes',
  component: ListKindergartenclassComponent,
  data: {
    authorities: ['ROLE_CHILD_PAID'],
    pageTitle: 'businesslogic.list.kindergartenclass.title'
  },
  resolve: {
    kindergartenClass: KindergartenClassResolve
  },
  canActivate: [UserRouteAccessService]
};

export const selectKindergartenclassRoute: Route = {
  path: 'child/select',
  component: SelectKindergartenclassComponent,
  data: {
    authorities: ['ROLE_CHILD_PAID'],
    pageTitle: 'businesslogic.list.kindergartenclass.title'
  },
  resolve: {
    kindergartenClass: KindergartenClassResolve
  },
  canActivate: [UserRouteAccessService]
};

export const listKindergartenclassCommentPopupRoute: Route = {
  path: 'teacher/classes/:id/delete',
  component: ListKindergartenclassComponent,
  resolve: {
    comment: CommentResolve
  },
  data: {
    authorities: ['ROLE_USER', 'ROLE_TEACHER_PAID'],
    pageTitle: 'mentalApp.comment.home.title'
  },
  canActivate: [UserRouteAccessService]
};

export const listKindergartenclassCommentPopupRouteChild: Route = {
  path: 'child/classes/:id/delete',
  component: ListKindergartenclassComponent,
  resolve: {
    comment: CommentResolve
  },
  data: {
    authorities: ['ROLE_USER', 'ROLE_CHILD_PAID'],
    pageTitle: 'mentalApp.comment.home.title'
  },
  canActivate: [UserRouteAccessService]
};
</code>```

答:
It is still unclear for me why, but everything started working in browsersync after I have splatted the large *.route.ts code into several ones:

```<code>import { Route, Routes } from '@angular/router';

import {
  CreateKindergartenclassComponent,
  DetailKindergartenclassComponent,
  ListKindergartenclassComponent,
  SelectKindergartenclassComponent
} from 'app/businesslogic';
import { UserRouteAccessService } from 'app/core';
import { KindergartenClassResolve } from 'app/entities/kindergarten-class';
import { CommentResolve } from 'app/entities/comment';

export const createKindergartenclassRoute: Route = {
  path: 'teacher/class/create',
  component: CreateKindergartenclassComponent,
  data: {
    authorities: ['ROLE_TEACHER_PAID'],
    pageTitle: 'businesslogic.create.kindergartenclass.title'
  },
  canActivate: [UserRouteAccessService]
};
</code>```

and

```<code>import { Route, Routes } from '@angular/router';

import {
  CreateKindergartenclassComponent,
  DetailKindergartenclassComponent,
  ListKindergartenclassComponent,
  SelectKindergartenclassComponent
} from 'app/businesslogic';
import { UserRouteAccessService } from 'app/core';
import { KindergartenClassResolve } from 'app/entities/kindergarten-class';
import { CommentResolve } from 'app/entities/comment';

export const listKindergartenclassCommentPopupRoute: Route = {
  path: 'teacher/classes/:id/delete',
  component: ListKindergartenclassComponent,
  resolve: {
    comment: CommentResolve
  },
  data: {
    authorities: ['ROLE_USER', 'ROLE_TEACHER_PAID'],
    pageTitle: 'mentalApp.comment.home.title'
  },
  canActivate: [UserRouteAccessService]
};

export const listKindergartenclassCommentPopupRouteChild: Route = {
  path: 'child/classes/:id/delete',
  component: ListKindergartenclassComponent,
  resolve: {
    comment: CommentResolve
  },
  data: {
    authorities: ['ROLE_USER', 'ROLE_CHILD_PAID'],
    pageTitle: 'mentalApp.comment.home.title'
  },
  canActivate: [UserRouteAccessService]
};
</code>```

and

```<code>import { Route, Routes } from '@angular/router';

import {
  CreateKindergartenclassComponent,
  DetailKindergartenclassComponent,
  ListKindergartenclassComponent,
  SelectKindergartenclassComponent
} from 'app/businesslogic';
import { UserRouteAccessService } from 'app/core';
import { KindergartenClassResolve } from 'app/entities/kindergarten-class';
import { CommentResolve } from 'app/entities/comment';

export const detailKindergartenclassRoute: Route = {
  path: 'teacher/class/:id',
  component: DetailKindergartenclassComponent,
  data: {
    authorities: ['ROLE_TEACHER_PAID'],
    pageTitle: 'businesslogic.kindergartenclass.title'
  },
  resolve: {
    kindergartenClass: KindergartenClassResolve
  },
  canActivate: [UserRouteAccessService]
};

export const detailKindergartenclassRouteChild: Route = {
  path: 'child/class/:id',
  component: DetailKindergartenclassComponent,
  data: {
    authorities: ['ROLE_CHILD_PAID'],
    pageTitle: 'businesslogic.kindergartenclass.title'
  },
  resolve: {
    kindergartenClass: KindergartenClassResolve
  },
  canActivate: [UserRouteAccessService]
};
</code>```

and

```<code>import { Route, Routes } from '@angular/router';

import {
  CreateKindergartenclassComponent,
  DetailKindergartenclassComponent,
  ListKindergartenclassComponent,
  SelectKindergartenclassComponent
} from 'app/businesslogic';
import { UserRouteAccessService } from 'app/core';
import { KindergartenClassResolve } from 'app/entities/kindergarten-class';
import { CommentResolve } from 'app/entities/comment';

export const listKindergartenclassRoute: Route = {
  path: 'teacher/classes',
  component: ListKindergartenclassComponent,
  data: {
    authorities: ['ROLE_TEACHER_PAID'],
    pageTitle: 'businesslogic.list.kindergartenclass.title'
  },
  resolve: {
    kindergartenClass: KindergartenClassResolve
  },
  canActivate: [UserRouteAccessService]
};

export const listKindergartenclassRouteChild: Route = {
  path: 'child/classes',
  component: ListKindergartenclassComponent,
  data: {
    authorities: ['ROLE_CHILD_PAID'],
    pageTitle: 'businesslogic.list.kindergartenclass.title'
  },
  resolve: {
    kindergartenClass: KindergartenClassResolve
  },
  canActivate: [UserRouteAccessService]
};
</code>```

and

```<code>import { Route, Routes } from '@angular/router';

import {
  CreateKindergartenclassComponent,
  DetailKindergartenclassComponent,
  ListKindergartenclassComponent,
  SelectKindergartenclassComponent
} from 'app/businesslogic';
import { UserRouteAccessService } from 'app/core';
import { KindergartenClassResolve } from 'app/entities/kindergarten-class';
import { CommentResolve } from 'app/entities/comment';

export const selectKindergartenclassRoute: Route = {
  path: 'child/select',
  component: SelectKindergartenclassComponent,
  data: {
    authorities: ['ROLE_CHILD_PAID'],
    pageTitle: 'businesslogic.list.kindergartenclass.title'
  },
  resolve: {
    kindergartenClass: KindergartenClassResolve
  },
  canActivate: [UserRouteAccessService]
};
</code>```

still Angular magic for me and I still don't know what particular splitting has made the trick.

Body:
I have a debug dev set up configured according to jHipster instruction https://www.jhipster.tech/development/ with proxy webpack server and broswersink. The server side works fine, the static files are pulled well from it and can be requested on localhost:9000 and localhost:9060, but not the angular app itself when the localhost:9000/ nor the localhost:9000/api is called on the browser tab under the browsersynk. I shows me the error in the browser console like this:

Error: Invalid configuration of route 'teacher/class/:id'. One of the following must be provided: component, redirectTo, children or loadChildren
    at validateNode (router.js?6580:607)
    at validateConfig (router.js?6580:577)
    at validateNode (router.js?6580:623)
    at validateConfig (router.js?6580:577)
    at Router.resetConfig (router.js?6580:4111)
    at new Router (router.js?6580:3779)
    at setupRouter (router.js?6580:5591)
    at _callFactory (core.js?09c9:18520)
    at _createProviderInstance (core.js?09c9:18466)
    at initNgModule (core.js?09c9:18396)

And it doesn't point to almost the same routes configured in the same file. I had no idea what is wrong with this specific route.

In one place I have a couple of routes configured like:

import { Route, Routes } from '@angular/router';

import { CreateKindergartenclassComponent } from 'app/businesslogic';
import { DetailKindergartenclassComponent } from 'app/businesslogic';
import { ListKindergartenclassComponent } from 'app/businesslogic';
import { SelectKindergartenclassComponent } from 'app/businesslogic';
import { UserRouteAccessService } from 'app/core';
import { KindergartenClassResolve } from 'app/entities/kindergarten-class';
import { CommentResolve } from 'app/entities/comment';

export const createKindergartenclassRoute: Route = {
  path: 'teacher/class/create',
  component: CreateKindergartenclassComponent,
  data: {
    authorities: ['ROLE_TEACHER_PAID'],
    pageTitle: 'businesslogic.create.kindergartenclass.title'
  },
  canActivate: [UserRouteAccessService]
};

export const detailKindergartenclassRouteChild: Route = {
  path: 'child/class/:id',
  component: DetailKindergartenclassComponent,
  data: {
    authorities: ['ROLE_CHILD_PAID'],
    pageTitle: 'businesslogic.kindergartenclass.title'
  },
  resolve: {
    kindergartenClass: KindergartenClassResolve
  },
  canActivate: [UserRouteAccessService]
};

export const detailKindergartenclassRouteTeacher: Route = {
  path: 'teacher/class/:id',
  component: DetailKindergartenclassComponent,
  data: {
    authorities: ['ROLE_TEACHER_PAID'],
    pageTitle: 'businesslogic.kindergartenclass.title'
  },
  resolve: {
    kindergartenClass: KindergartenClassResolve
  },
  canActivate: [UserRouteAccessService]
};

export const listKindergartenclassRoute: Route = {
  path: 'teacher/classes',
  component: ListKindergartenclassComponent,
  data: {
    authorities: ['ROLE_TEACHER_PAID'],
    pageTitle: 'businesslogic.list.kindergartenclass.title'
  },
  resolve: {
    kindergartenClass: KindergartenClassResolve
  },
  canActivate: [UserRouteAccessService]
};

export const listKindergartenclassRouteChild: Route = {
  path: 'child/classes',
  component: ListKindergartenclassComponent,
  data: {
    authorities: ['ROLE_CHILD_PAID'],
    pageTitle: 'businesslogic.list.kindergartenclass.title'
  },
  resolve: {
    kindergartenClass: KindergartenClassResolve
  },
  canActivate: [UserRouteAccessService]
};

export const selectKindergartenclassRoute: Route = {
  path: 'child/select',
  component: SelectKindergartenclassComponent,
  data: {
    authorities: ['ROLE_CHILD_PAID'],
    pageTitle: 'businesslogic.list.kindergartenclass.title'
  },
  resolve: {
    kindergartenClass: KindergartenClassResolve
  },
  canActivate: [UserRouteAccessService]
};

export const listKindergartenclassCommentPopupRoute: Route = {
  path: 'teacher/classes/:id/delete',
  component: ListKindergartenclassComponent,
  resolve: {
    comment: CommentResolve
  },
  data: {
    authorities: ['ROLE_USER', 'ROLE_TEACHER_PAID'],
    pageTitle: 'mentalApp.comment.home.title'
  },
  canActivate: [UserRouteAccessService]
};

export const listKindergartenclassCommentPopupRouteChild: Route = {
  path: 'child/classes/:id/delete',
  component: ListKindergartenclassComponent,
  resolve: {
    comment: CommentResolve
  },
  data: {
    authorities: ['ROLE_USER', 'ROLE_CHILD_PAID'],
    pageTitle: 'mentalApp.comment.home.title'
  },
  canActivate: [UserRouteAccessService]
};

Body:
It is still unclear for me why, but everything started working in browsersync after I have splatted the large *.route.ts code into several ones:

import { Route, Routes } from '@angular/router';

import {
  CreateKindergartenclassComponent,
  DetailKindergartenclassComponent,
  ListKindergartenclassComponent,
  SelectKindergartenclassComponent
} from 'app/businesslogic';
import { UserRouteAccessService } from 'app/core';
import { KindergartenClassResolve } from 'app/entities/kindergarten-class';
import { CommentResolve } from 'app/entities/comment';

export const createKindergartenclassRoute: Route = {
  path: 'teacher/class/create',
  component: CreateKindergartenclassComponent,
  data: {
    authorities: ['ROLE_TEACHER_PAID'],
    pageTitle: 'businesslogic.create.kindergartenclass.title'
  },
  canActivate: [UserRouteAccessService]
};

and

import { Route, Routes } from '@angular/router';

import {
  CreateKindergartenclassComponent,
  DetailKindergartenclassComponent,
  ListKindergartenclassComponent,
  SelectKindergartenclassComponent
} from 'app/businesslogic';
import { UserRouteAccessService } from 'app/core';
import { KindergartenClassResolve } from 'app/entities/kindergarten-class';
import { CommentResolve } from 'app/entities/comment';

export const listKindergartenclassCommentPopupRoute: Route = {
  path: 'teacher/classes/:id/delete',
  component: ListKindergartenclassComponent,
  resolve: {
    comment: CommentResolve
  },
  data: {
    authorities: ['ROLE_USER', 'ROLE_TEACHER_PAID'],
    pageTitle: 'mentalApp.comment.home.title'
  },
  canActivate: [UserRouteAccessService]
};

export const listKindergartenclassCommentPopupRouteChild: Route = {
  path: 'child/classes/:id/delete',
  component: ListKindergartenclassComponent,
  resolve: {
    comment: CommentResolve
  },
  data: {
    authorities: ['ROLE_USER', 'ROLE_CHILD_PAID'],
    pageTitle: 'mentalApp.comment.home.title'
  },
  canActivate: [UserRouteAccessService]
};

and

import { Route, Routes } from '@angular/router';

import {
  CreateKindergartenclassComponent,
  DetailKindergartenclassComponent,
  ListKindergartenclassComponent,
  SelectKindergartenclassComponent
} from 'app/businesslogic';
import { UserRouteAccessService } from 'app/core';
import { KindergartenClassResolve } from 'app/entities/kindergarten-class';
import { CommentResolve } from 'app/entities/comment';

export const detailKindergartenclassRoute: Route = {
  path: 'teacher/class/:id',
  component: DetailKindergartenclassComponent,
  data: {
    authorities: ['ROLE_TEACHER_PAID'],
    pageTitle: 'businesslogic.kindergartenclass.title'
  },
  resolve: {
    kindergartenClass: KindergartenClassResolve
  },
  canActivate: [UserRouteAccessService]
};

export const detailKindergartenclassRouteChild: Route = {
  path: 'child/class/:id',
  component: DetailKindergartenclassComponent,
  data: {
    authorities: ['ROLE_CHILD_PAID'],
    pageTitle: 'businesslogic.kindergartenclass.title'
  },
  resolve: {
    kindergartenClass: KindergartenClassResolve
  },
  canActivate: [UserRouteAccessService]
};

and

import { Route, Routes } from '@angular/router';

import {
  CreateKindergartenclassComponent,
  DetailKindergartenclassComponent,
  ListKindergartenclassComponent,
  SelectKindergartenclassComponent
} from 'app/businesslogic';
import { UserRouteAccessService } from 'app/core';
import { KindergartenClassResolve } from 'app/entities/kindergarten-class';
import { CommentResolve } from 'app/entities/comment';

export const listKindergartenclassRoute: Route = {
  path: 'teacher/classes',
  component: ListKindergartenclassComponent,
  data: {
    authorities: ['ROLE_TEACHER_PAID'],
    pageTitle: 'businesslogic.list.kindergartenclass.title'
  },
  resolve: {
    kindergartenClass: KindergartenClassResolve
  },
  canActivate: [UserRouteAccessService]
};

export const listKindergartenclassRouteChild: Route = {
  path: 'child/classes',
  component: ListKindergartenclassComponent,
  data: {
    authorities: ['ROLE_CHILD_PAID'],
    pageTitle: 'businesslogic.list.kindergartenclass.title'
  },
  resolve: {
    kindergartenClass: KindergartenClassResolve
  },
  canActivate: [UserRouteAccessService]
};

and

import { Route, Routes } from '@angular/router';

import {
  CreateKindergartenclassComponent,
  DetailKindergartenclassComponent,
  ListKindergartenclassComponent,
  SelectKindergartenclassComponent
} from 'app/businesslogic';
import { UserRouteAccessService } from 'app/core';
import { KindergartenClassResolve } from 'app/entities/kindergarten-class';
import { CommentResolve } from 'app/entities/comment';

export const selectKindergartenclassRoute: Route = {
  path: 'child/select',
  component: SelectKindergartenclassComponent,
  data: {
    authorities: ['ROLE_CHILD_PAID'],
    pageTitle: 'businesslogic.list.kindergartenclass.title'
  },
  resolve: {
    kindergartenClass: KindergartenClassResolve
  },
  canActivate: [UserRouteAccessService]
};

still Angular magic for me and I still don't know what particular splitting has made the trick.


来源: stackexchange

问:
JAVA: How do I determine if the input is a palindrome?
Please use the method below.

I am trying to get rid of all white spaces, punctuations and make everything lowercase. Then I want to see whether the string is a palindrome (same when read from the front and back.

I can't figure it out.

```<code>public static void main(String[] args) {

        String word=null;
        String reverse="";
        Scanner console = new Scanner(System.in);

        System.out.print("Please enter a word or a phrase:");
        word = console.nextLine();

        word=word.replaceAll("\\s+",""); //removes white space
        word=word.replaceAll("[^a-zA-Z ]", ""); //removes all punctuation
        word=word.toLowerCase();

        for(int i=word.length()-1; i>=0; i--) {
        reverse +=word.charAt(i);

        }

        for(int i=0; i<word.length(); i++) {
            System.out.print(word);
        if(word.charAt(i) != reverse.charAt(i)) {
            System.out.println("Not a Palindrome");
        }else {
                System.out.println("Palindrome");```

```

答:
First, you can combine all of your regular expressions into one (first make the input lowercase, then eliminate everything not a lowercase letter). Second, you can eliminate building a temporary String to check if it's a palindrome; because you can iterate the characters in the word and check the front with the back. Like,

```<code>System.out.print("Please enter a word or a phrase:");
String word = console.nextLine().toLowerCase().replaceAll("[^a-z]", "");
boolean palindrome = true;
for (int i = 0; i < word.length() / 2; i++) {
    if (word.charAt(i) != word.charAt(word.length() - i - 1)) {
        palindrome = false;
        break;
    }
}
if (!palindrome) {
    System.out.println("Not a Palindrome");
} else {
    System.out.println("Palindrome");
}
</code>```

If you decide you want to reverse word anyway for a less efficient implementation. Use StringBuilder, because it can be done in one line (and I think it looks more readable).

```<code>System.out.print("Please enter a word or a phrase:");
String word = console.nextLine().toLowerCase().replaceAll("[^a-z]", "");
if (!new StringBuilder(word).reverse().toString().equals(word)) {
    System.out.println("Not a Palindrome");
} else {
    System.out.println("Palindrome");
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Please use the method below.

I am trying to get rid of all white spaces, punctuations and make everything lowercase. Then I want to see whether the string is a palindrome (same when read from the front and back.

I can't figure it out.

public static void main(String[] args) {

        String word=null;
        String reverse="";
        Scanner console = new Scanner(System.in);

        System.out.print("Please enter a word or a phrase:");
        word = console.nextLine();

        word=word.replaceAll("\\s+",""); //removes white space
        word=word.replaceAll("[^a-zA-Z ]", ""); //removes all punctuation
        word=word.toLowerCase();

        for(int i=word.length()-1; i>=0; i--) {
        reverse +=word.charAt(i);

        }

        for(int i=0; i<word.length(); i++) {
            System.out.print(word);
        if(word.charAt(i) != reverse.charAt(i)) {
            System.out.println("Not a Palindrome");
        }else {
                System.out.println("Palindrome");```

Body:
First, you can combine all of your regular expressions into one (first make the input lowercase, then eliminate everything not a lowercase letter). Second, you can eliminate building a temporary String to check if it's a palindrome; because you can iterate the characters in the word and check the front with the back. Like,

System.out.print("Please enter a word or a phrase:");
String word = console.nextLine().toLowerCase().replaceAll("[^a-z]", "");
boolean palindrome = true;
for (int i = 0; i < word.length() / 2; i++) {
    if (word.charAt(i) != word.charAt(word.length() - i - 1)) {
        palindrome = false;
        break;
    }
}
if (!palindrome) {
    System.out.println("Not a Palindrome");
} else {
    System.out.println("Palindrome");
}

If you decide you want to reverse word anyway for a less efficient implementation. Use StringBuilder, because it can be done in one line (and I think it looks more readable).

System.out.print("Please enter a word or a phrase:");
String word = console.nextLine().toLowerCase().replaceAll("[^a-z]", "");
if (!new StringBuilder(word).reverse().toString().equals(word)) {
    System.out.println("Not a Palindrome");
} else {
    System.out.println("Palindrome");
}


问:
react native navigation payload error for login
I am facing a issue with my login screen. Every thing works quite well But my problem is after successfully making a login i am getting a payload error. I am using a function component not a class component. And all my screens are outside the Route.js.

Error is

My Route.js code are as follows:

```<code> import  React, {  useState } from 'react';
import 'react-native-gesture-handler';
import {AsyncStorage} from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
/// All components of screens
import HomeScreen from './src/Component/HomeScreen';
import DefaultScreen from './src/Component/DefaultScreen';
import Privacy from './src/Component/Privacy';
import Signup from './src/Component/Signup';
import ForgetPassword from './src/Component/ForgetPassword';
import Dashboard from './src/Component/Dashboard';
import SplashScreen from './src/Component/SplashScreen';
const AuthContext = React.createContext();

export default function Routes(){
const Stack = createStackNavigator();
const [state, dispatch] = React.useReducer(
  (prevState, action) => {
    switch (action.type) {
      case 'RESTORE_TOKEN':
        return {
          ...prevState,
          userToken: action.token,
          isLoading: false,
        };
      case 'SIGN_IN':
        return {
          ...prevState,
          isSignout: false,
          userToken: action.token,
        };
      case 'SIGN_OUT':
        return {
          ...prevState,
          isSignout: true,
          userToken: undefined,
        };
    }
  },
  {
    isLoading: true,
    isSignout: false,
    userToken: null,
  }
);

React.useEffect(() => {
  // Fetch the token from storage then navigate to our appropriate place
  const bootstrapAsync = async () => {
    let userToken;

    try {
      userToken = await AsyncStorage.getItem('@kiklee-user-id');
    } catch (e) {
      // Restoring token failed
    }

    // After restoring token, we may need to validate it in production apps

    // This will switch to the App screen or Auth screen and this loading
    // screen will be unmounted and thrown away.
    dispatch({ type: 'RESTORE_TOKEN', token: userToken });
  };

  bootstrapAsync();
}, []);

const authContext = React.useMemo(
  () => ({
    signIn: async data => {
      // In a production app, we need to send some data (usually username, password) to server and get a token
      // We will also need to handle errors if sign in failed
      // After getting token, we need to persist the token using `AsyncStorage`
      // In the example, we'll use a dummy token

      dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
    },
    signOut: () => dispatch({ type: 'SIGN_OUT' }),
    signUp: async data => {
      // In a production app, we need to send user data to server and get a token
      // We will also need to handle errors if sign up failed
      // After getting token, we need to persist the token using `AsyncStorage`
      // In the example, we'll use a dummy token

      dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
    },
  }),
  []
);

if (state.isLoading) {
  // We haven't finished checking for the token yet
  return <SplashScreen />;
}
  //alert(authContext);

    return(
      <AuthContext.Provider value={authContext}>
      <NavigationContainer>
      <Stack.Navigator>
     {state.userToken == null ? (
  <>
    <Stack.Screen name="Home" component={HomeScreen} options={{ headerShown:false, animationTypeForReplace: state.isSignout ? 'pop' : 'push', }} />
    <Stack.Screen name="Privacy" component={Privacy} options={{ headerShown:false }} />
    <Stack.Screen name="ForgetPassword" component={ForgetPassword} options={{  headerShown:false }} />
    <Stack.Screen name="SignUp" component={Signup} options={{  headerShown:false }} />
    <Stack.Screen name="SplashScreen" component={SplashScreen} options={{ headerShown:false }} />
    </>
) : (
  <>
    <Stack.Screen name='Dashboard' component={Dashboard} />
    <Stack.Screen name="SplashScreen" component={SplashScreen} options={{ headerShown:false }} />

  </>
)}

      </Stack.Navigator>
    </NavigationContainer>
    </AuthContext.Provider>
            );

}
</code>```

My login screen is HomeScreen.js 'HomeScreen' and After log in i am redirecting user to Dashboard.js  'Dashboard'

答: I think the code await AsyncStorage.getItem('@kiklee-user-id') returns null, so state.userToken value is always null, and your <Stack.Navigator> component has not any Dashboard route

Body:
I am facing a issue with my login screen. Every thing works quite well But my problem is after successfully making a login i am getting a payload error. I am using a function component not a class component. And all my screens are outside the Route.js.

Error is

My Route.js code are as follows:

 import  React, {  useState } from 'react';
import 'react-native-gesture-handler';
import {AsyncStorage} from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
/// All components of screens
import HomeScreen from './src/Component/HomeScreen';
import DefaultScreen from './src/Component/DefaultScreen';
import Privacy from './src/Component/Privacy';
import Signup from './src/Component/Signup';
import ForgetPassword from './src/Component/ForgetPassword';
import Dashboard from './src/Component/Dashboard';
import SplashScreen from './src/Component/SplashScreen';
const AuthContext = React.createContext();

export default function Routes(){
const Stack = createStackNavigator();
const [state, dispatch] = React.useReducer(
  (prevState, action) => {
    switch (action.type) {
      case 'RESTORE_TOKEN':
        return {
          ...prevState,
          userToken: action.token,
          isLoading: false,
        };
      case 'SIGN_IN':
        return {
          ...prevState,
          isSignout: false,
          userToken: action.token,
        };
      case 'SIGN_OUT':
        return {
          ...prevState,
          isSignout: true,
          userToken: undefined,
        };
    }
  },
  {
    isLoading: true,
    isSignout: false,
    userToken: null,
  }
);

React.useEffect(() => {
  // Fetch the token from storage then navigate to our appropriate place
  const bootstrapAsync = async () => {
    let userToken;

    try {
      userToken = await AsyncStorage.getItem('@kiklee-user-id');
    } catch (e) {
      // Restoring token failed
    }

    // After restoring token, we may need to validate it in production apps

    // This will switch to the App screen or Auth screen and this loading
    // screen will be unmounted and thrown away.
    dispatch({ type: 'RESTORE_TOKEN', token: userToken });
  };

  bootstrapAsync();
}, []);

const authContext = React.useMemo(
  () => ({
    signIn: async data => {
      // In a production app, we need to send some data (usually username, password) to server and get a token
      // We will also need to handle errors if sign in failed
      // After getting token, we need to persist the token using `AsyncStorage`
      // In the example, we'll use a dummy token

      dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
    },
    signOut: () => dispatch({ type: 'SIGN_OUT' }),
    signUp: async data => {
      // In a production app, we need to send user data to server and get a token
      // We will also need to handle errors if sign up failed
      // After getting token, we need to persist the token using `AsyncStorage`
      // In the example, we'll use a dummy token

      dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
    },
  }),
  []
);

if (state.isLoading) {
  // We haven't finished checking for the token yet
  return <SplashScreen />;
}
  //alert(authContext);

    return(
      <AuthContext.Provider value={authContext}>
      <NavigationContainer>
      <Stack.Navigator>
     {state.userToken == null ? (
  <>
    <Stack.Screen name="Home" component={HomeScreen} options={{ headerShown:false, animationTypeForReplace: state.isSignout ? 'pop' : 'push', }} />
    <Stack.Screen name="Privacy" component={Privacy} options={{ headerShown:false }} />
    <Stack.Screen name="ForgetPassword" component={ForgetPassword} options={{  headerShown:false }} />
    <Stack.Screen name="SignUp" component={Signup} options={{  headerShown:false }} />
    <Stack.Screen name="SplashScreen" component={SplashScreen} options={{ headerShown:false }} />
    </>
) : (
  <>
    <Stack.Screen name='Dashboard' component={Dashboard} />
    <Stack.Screen name="SplashScreen" component={SplashScreen} options={{ headerShown:false }} />

  </>
)}

      </Stack.Navigator>
    </NavigationContainer>
    </AuthContext.Provider>
            );

}

My login screen is HomeScreen.js 'HomeScreen' and After log in i am redirecting user to Dashboard.js  'Dashboard'


问:
How to exit the script if the directories already exist?
Bellow there is a PHP code to make multiple directories inside the current directory.

I need to terminate the script in case the directories already exist.

But instead, I get multiple "file exists" warning messages.

Code

```<code><?php

//Creates multiple directories inside the current directory.

$curdir = getcwd();
$slash = "/0";

for ($dir = 1; $dir <= 12; $dir++){

      $concat = $slash . $dir;

      if (!file_exists($concat)) {

        mkdir($curdir . "$concat" , 0777);

      } else {

        exit("Files already exist.");

      }

}

?>
</code>```

Output

```<code>Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14
</code>```

答:
You have to edit your if statement. You are checking a different directory than what you were creating:</p>

```<code><?php

$curdir = getcwd();
$slash = "/0";

for ($dir = 1; $dir <= 12; $dir++){

      $concat = $slash . $dir;

      if (!file_exists($curdir . $concat)) {

        mkdir($curdir . $concat , 0777);

      } else {

        exit("Files already exist.");

      }

}
</code>```

Body:
Bellow there is a PHP code to make multiple directories inside the current directory.

I need to terminate the script in case the directories already exist.

But instead, I get multiple "file exists" warning messages.

Code

<?php

//Creates multiple directories inside the current directory.

$curdir = getcwd();
$slash = "/0";

for ($dir = 1; $dir <= 12; $dir++){

      $concat = $slash . $dir;

      if (!file_exists($concat)) {

        mkdir($curdir . "$concat" , 0777);

      } else {

        exit("Files already exist.");

      }

}

?>

Output

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Warning: mkdir(): File exists in /opt/lampp/htdocs/SQL/mkdir.php on line 14

Body:
You have to edit your if statement. You are checking a different directory than what you were creating:

<?php

$curdir = getcwd();
$slash = "/0";

for ($dir = 1; $dir <= 12; $dir++){

      $concat = $slash . $dir;

      if (!file_exists($curdir . $concat)) {

        mkdir($curdir . $concat , 0777);

      } else {

        exit("Files already exist.");

      }

}


问:
Evaluating a string against a pattern with RegExp in Flutter
I'm trying to evaluate a string against a set list of parameters with RegExp in Flutter. For example, the string must contain at least:

One capital letter

One lowercase letter

One number from 0-9

One special character, such as $ or !

This is basically for a password entry field of an application. I have set things up, firstly using validateStructure as follows:

```<code>abstract class PasswordValidator {
  bool validateStructure(String value);
}
</code>```

Then, I have used the RegExp function as follows:

```<code>class PasswordValidatorSpecial implements PasswordValidator {
  bool validateStructure(String value) {
    String pattern =
        r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~£]).{8,}$';
    RegExp regEx = new RegExp(pattern);
    return regEx.hasMatch(value);
  }
}
</code>```

This does work well, in a sense that when I pass a string/password through it, it does tell me if at least one of the criteria is not met. However, what I would like to do is for the output to be more specific, telling me which of those criteria isn't met.

For example, if the password were to have everything but a number (from 0-9) I would want to be able to get the output to specifically say that a number is missing, but everything else is present.

How would I adapt my code to be able to do that? I thought perhaps by using conditional 'if' statement, although I don't know how that would work. Thanks!

答:
That's right, you can use RegExr to check your RegExp, separate each part and use them separately to have a custom error. Also instead of return a bool value, you can return a String value, such as the following function: </p>

```<code>String validateStructure(String value) {
    String patternUpperCaseCharacters = r'^(?=.*?[A-Z])';
    String patternLowerCaseCharacters = r'^(?=.*?[a-z])';
    String patternNumbers = r'^(?=.*?[0-9])';
    String patternSpecialCharacters = r'^(?=.*?[!@#\$&*~£])';

    RegExp regEx = new RegExp(patternUpperCaseCharacters);
    if (regEx.hasMatch(value)) {
      regEx = new RegExp(patternLowerCaseCharacters);
      if (regEx.hasMatch(value)) {
        return "More errors";
      } else {
        return "You need at least one lowercase letter";
      }
    } else {
      return "You need at least one capital letter";
    }
  }
</code>```

Body:
I'm trying to evaluate a string against a set list of parameters with RegExp in Flutter. For example, the string must contain at least:

One capital letter

One lowercase letter

One number from 0-9

One special character, such as $ or !

This is basically for a password entry field of an application. I have set things up, firstly using validateStructure as follows:

abstract class PasswordValidator {
  bool validateStructure(String value);
}

Then, I have used the RegExp function as follows:

class PasswordValidatorSpecial implements PasswordValidator {
  bool validateStructure(String value) {
    String pattern =
        r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~£]).{8,}$';
    RegExp regEx = new RegExp(pattern);
    return regEx.hasMatch(value);
  }
}

This does work well, in a sense that when I pass a string/password through it, it does tell me if at least one of the criteria is not met. However, what I would like to do is for the output to be more specific, telling me which of those criteria isn't met.

For example, if the password were to have everything but a number (from 0-9) I would want to be able to get the output to specifically say that a number is missing, but everything else is present.

How would I adapt my code to be able to do that? I thought perhaps by using conditional 'if' statement, although I don't know how that would work. Thanks!

Body:
That's right, you can use RegExr to check your RegExp, separate each part and use them separately to have a custom error. Also instead of return a bool value, you can return a String value, such as the following function:

String validateStructure(String value) {
    String patternUpperCaseCharacters = r'^(?=.*?[A-Z])';
    String patternLowerCaseCharacters = r'^(?=.*?[a-z])';
    String patternNumbers = r'^(?=.*?[0-9])';
    String patternSpecialCharacters = r'^(?=.*?[!@#\$&*~£])';

    RegExp regEx = new RegExp(patternUpperCaseCharacters);
    if (regEx.hasMatch(value)) {
      regEx = new RegExp(patternLowerCaseCharacters);
      if (regEx.hasMatch(value)) {
        return "More errors";
      } else {
        return "You need at least one lowercase letter";
      }
    } else {
      return "You need at least one capital letter";
    }
  }


问:
Why are my dicts alternating between mutable and immutable?
Consider this code

```<code>from pprint import pprint
test_dict = {}
new = {}
new['slot'] = {}
for k in range(5):
    test_dict[k] = {}
    test_dict[k].update(new)
    if k == 3:
        test_dict[k]['slot']['this should only be in 3'] = []
pprint(test_dict)
print('Round 2, without SLOT')
test_dict = {}
new = {}
for k in range(5):
    test_dict[k] = {}
    test_dict[k].update(new)
    if k == 3:
        test_dict[k]['this should only be in 3'] = []
pprint(test_dict)

</code>```

With this output

```<code>> python -i .\test2.py
{0: {'slot': {'this should only be in 3': []}},
 1: {'slot': {'this should only be in 3': []}},
 2: {'slot': {'this should only be in 3': []}},
 3: {'slot': {'this should only be in 3': []}},
 4: {'slot': {'this should only be in 3': []}}}
Round 2, without SLOT
{0: {}, 1: {}, 2: {}, 3: {'this should only be in 3': []}, 4: {}}
</code>```

Help me understand why in the first case, the 'should only be...' list is appearing in every case and not the second. Dicts are immutable but I don't understand why I'm getting different results.

Thanks,

答:
You are storing the same instance of the dict stored in new['slot'] in each key of test_dict:

from pprint import pprint
test_dict = {}
new = {}
new['slot'] = {}
new['slot']['id'] = id(new['slot'])
for k in range(5):
    test_dict[k] = {}
    test_dict[k].update(new)
    if k == 3:
        test_dict[k]['slot']['this should only be in 3'] = []
pprint(test_dict)
```

<p><strong>Output</strong></p>

<pre class="lang-none prettyprint-override"><code>{0: {'slot': {'id': 4433735760, 'this should only be in 3': []}},
 1: {'slot': {'id': 4433735760, 'this should only be in 3': []}},
 2: {'slot': {'id': 4433735760, 'this should only be in 3': []}},
 3: {'slot': {'id': 4433735760, 'this should only be in 3': []}},
 4: {'slot': {'id': 4433735760, 'this should only be in 3': []}}}
</code>```

A possible fix would be to create a new dict each time you need one:

from pprint import pprint
test_dict = {}
for k in range(5):
    test_dict[k] = {}
    new = {'slot': dict()}
    new['slot']['id'] = id(new['slot'])
    test_dict[k].update(new)
    if k == 3:
        test_dict[k]['slot']['this should only be in 3'] = []
pprint(test_dict)
```

<p><strong>Output</strong></p>

<pre class="lang-none prettyprint-override"><code>{0: {'slot': {'id': 4399711968}},
 1: {'slot': {'id': 4399712528}},
 2: {'slot': {'id': 4399713088}},
 3: {'slot': {'id': 4399713648, 'this should only be in 3': []}},
 4: {'slot': {'id': 4399730768}}}
</code>```

Body:
Consider this code

from pprint import pprint
test_dict = {}
new = {}
new['slot'] = {}
for k in range(5):
    test_dict[k] = {}
    test_dict[k].update(new)
    if k == 3:
        test_dict[k]['slot']['this should only be in 3'] = []
pprint(test_dict)
print('Round 2, without SLOT')
test_dict = {}
new = {}
for k in range(5):
    test_dict[k] = {}
    test_dict[k].update(new)
    if k == 3:
        test_dict[k]['this should only be in 3'] = []
pprint(test_dict)

With this output

> python -i .\test2.py
{0: {'slot': {'this should only be in 3': []}},
 1: {'slot': {'this should only be in 3': []}},
 2: {'slot': {'this should only be in 3': []}},
 3: {'slot': {'this should only be in 3': []}},
 4: {'slot': {'this should only be in 3': []}}}
Round 2, without SLOT
{0: {}, 1: {}, 2: {}, 3: {'this should only be in 3': []}, 4: {}}

Help me understand why in the first case, the 'should only be...' list is appearing in every case and not the second. Dicts are immutable but I don't understand why I'm getting different results.

Thanks,

Body:
You are storing the same instance of the dict stored in new['slot'] in each key of test_dict:

from pprint import pprint
test_dict = {}
new = {}
new['slot'] = {}
new['slot']['id'] = id(new['slot'])
for k in range(5):
    test_dict[k] = {}
    test_dict[k].update(new)
    if k == 3:
        test_dict[k]['slot']['this should only be in 3'] = []
pprint(test_dict)

Output

{0: {'slot': {'id': 4433735760, 'this should only be in 3': []}},
 1: {'slot': {'id': 4433735760, 'this should only be in 3': []}},
 2: {'slot': {'id': 4433735760, 'this should only be in 3': []}},
 3: {'slot': {'id': 4433735760, 'this should only be in 3': []}},
 4: {'slot': {'id': 4433735760, 'this should only be in 3': []}}}

A possible fix would be to create a new dict each time you need one:

from pprint import pprint
test_dict = {}
for k in range(5):
    test_dict[k] = {}
    new = {'slot': dict()}
    new['slot']['id'] = id(new['slot'])
    test_dict[k].update(new)
    if k == 3:
        test_dict[k]['slot']['this should only be in 3'] = []
pprint(test_dict)

Output

{0: {'slot': {'id': 4399711968}},
 1: {'slot': {'id': 4399712528}},
 2: {'slot': {'id': 4399713088}},
 3: {'slot': {'id': 4399713648, 'this should only be in 3': []}},
 4: {'slot': {'id': 4399730768}}}


问:
Adding new 'step' value column for timeseries data with multiple records per time in Python / Pandas
I am trying to assign a new df column, 'step', where the value of each row in df['step'] increments for each unique value in a different column ('time'). The time column is ordered in ascending order, the order of the tag_id's are not important. Each unique time stamp may have a different number of unique tag_id values, but all time values are regularly spaced, 00:00:00:05 apart.

The dataset looks something like this, with timestamps, and at each time there are multiple unique tag_id's with an x and y position.

```<code>    tag_id      x_pos      y_pos             time
0        1  77.134000  70.651000         19:03:51
1        2  66.376432  34.829683         19:03:51
2        3  49.250835  37.848381         19:03:51
3        1  50.108018   7.670564  19:03:51.050000
4        2  54.919299  47.613906  19:03:51.050000
5        3  57.584265  38.440233  19:03:51.050000
6        1  47.862124  29.133489  19:03:51.100000
7        2  71.092900  71.650500  19:03:51.100000
8        3  65.704667  25.856978  19:03:51.100000
9        1  62.680708  13.710716  19:03:51.150000
10       2  65.673670  47.574349  19:03:51.150000
11       3  77.134000  70.651000  19:03:51.150000
12       1  66.410406  34.792751  19:03:51.200000
13       2  49.306861  37.714626  19:03:51.200000
14       3  50.142578   7.575307  19:03:51.200000
15       1  54.940298  47.528109  19:03:51.250000
</code>```

I created the following function using masks for each unique value in df['time'], which works, but is extremely slow (original data set around 500,000 records with 41,000 unique times).

```<code># after adding step column by:
# df['step'] = 0

def timeToSteps(df):
    count = 0
    for t in df['time'].unique():
        mask = df['time'].values == t
        df.loc[mask, ['step']] = count
        count += 1
</code>```

Giving:

```<code>    tag_id      x_pos      y_pos             time  step
0        1  77.134000  70.651000         19:03:51     0
1        2  66.376432  34.829683         19:03:51     0
2        3  49.250835  37.848381         19:03:51     0
3        1  50.108018   7.670564  19:03:51.050000     1
4        2  54.919299  47.613906  19:03:51.050000     1
5        3  57.584265  38.440233  19:03:51.050000     1
6        1  47.862124  29.133489  19:03:51.100000     2
7        2  71.092900  71.650500  19:03:51.100000     2
8        3  65.704667  25.856978  19:03:51.100000     2
9        1  62.680708  13.710716  19:03:51.150000     3
10       2  65.673670  47.574349  19:03:51.150000     3
11       3  77.134000  70.651000  19:03:51.150000     3
12       1  66.410406  34.792751  19:03:51.200000     4
13       2  49.306861  37.714626  19:03:51.200000     4
14       3  50.142578   7.575307  19:03:51.200000     4
15       1  54.940298  47.528109  19:03:51.250000     5
</code>```

Is there a more efficient way to achieve this result? Thank you!

Body:
I am trying to assign a new df column, 'step', where the value of each row in df['step'] increments for each unique value in a different column ('time'). The time column is ordered in ascending order, the order of the tag_id's are not important. Each unique time stamp may have a different number of unique tag_id values, but all time values are regularly spaced, 00:00:00:05 apart.

The dataset looks something like this, with timestamps, and at each time there are multiple unique tag_id's with an x and y position.

    tag_id      x_pos      y_pos             time
0        1  77.134000  70.651000         19:03:51
1        2  66.376432  34.829683         19:03:51
2        3  49.250835  37.848381         19:03:51
3        1  50.108018   7.670564  19:03:51.050000
4        2  54.919299  47.613906  19:03:51.050000
5        3  57.584265  38.440233  19:03:51.050000
6        1  47.862124  29.133489  19:03:51.100000
7        2  71.092900  71.650500  19:03:51.100000
8        3  65.704667  25.856978  19:03:51.100000
9        1  62.680708  13.710716  19:03:51.150000
10       2  65.673670  47.574349  19:03:51.150000
11       3  77.134000  70.651000  19:03:51.150000
12       1  66.410406  34.792751  19:03:51.200000
13       2  49.306861  37.714626  19:03:51.200000
14       3  50.142578   7.575307  19:03:51.200000
15       1  54.940298  47.528109  19:03:51.250000

I created the following function using masks for each unique value in df['time'], which works, but is extremely slow (original data set around 500,000 records with 41,000 unique times).

# after adding step column by:
# df['step'] = 0

def timeToSteps(df):
    count = 0
    for t in df['time'].unique():
        mask = df['time'].values == t
        df.loc[mask, ['step']] = count
        count += 1

Giving:

    tag_id      x_pos      y_pos             time  step
0        1  77.134000  70.651000         19:03:51     0
1        2  66.376432  34.829683         19:03:51     0
2        3  49.250835  37.848381         19:03:51     0
3        1  50.108018   7.670564  19:03:51.050000     1
4        2  54.919299  47.613906  19:03:51.050000     1
5        3  57.584265  38.440233  19:03:51.050000     1
6        1  47.862124  29.133489  19:03:51.100000     2
7        2  71.092900  71.650500  19:03:51.100000     2
8        3  65.704667  25.856978  19:03:51.100000     2
9        1  62.680708  13.710716  19:03:51.150000     3
10       2  65.673670  47.574349  19:03:51.150000     3
11       3  77.134000  70.651000  19:03:51.150000     3
12       1  66.410406  34.792751  19:03:51.200000     4
13       2  49.306861  37.714626  19:03:51.200000     4
14       3  50.142578   7.575307  19:03:51.200000     4
15       1  54.940298  47.528109  19:03:51.250000     5

Is there a more efficient way to achieve this result? Thank you!

Body:
Try this

import numpy as np
import pandas as pd

df = pd.read_csv('data.txt', delim_whitespace=True, parse_dates=['time'])
df['step'] = df['time']-df['time'].shift(1)     #shift index and find difference
zero = np.timedelta64(0, 's')
df['step'][0] = np.timedelta64(0, 's')          #change first var from naT to zero
df['step'] = df['step'].apply(lambda x: x>zero).cumsum()
print(df)

produces

    tag_id      x_pos      y_pos                    time  step
0        1  77.134000  70.651000 2020-02-16 19:03:51.000     0
1        2  66.376432  34.829683 2020-02-16 19:03:51.000     0
2        3  49.250835  37.848381 2020-02-16 19:03:51.000     0
3        1  50.108018   7.670564 2020-02-16 19:03:51.050     1
4        2  54.919299  47.613906 2020-02-16 19:03:51.050     1
5        3  57.584265  38.440233 2020-02-16 19:03:51.050     1
6        1  47.862124  29.133489 2020-02-16 19:03:51.100     2
7        2  71.092900  71.650500 2020-02-16 19:03:51.100     2
8        3  65.704667  25.856978 2020-02-16 19:03:51.100     2
9        1  62.680708  13.710716 2020-02-16 19:03:51.150     3
10       2  65.673670  47.574349 2020-02-16 19:03:51.150     3
11       3  77.134000  70.651000 2020-02-16 19:03:51.150     3
12       1  66.410406  34.792751 2020-02-16 19:03:51.200     4
13       2  49.306861  37.714626 2020-02-16 19:03:51.200     4
14       3  50.142578   7.575307 2020-02-16 19:03:51.200     4
15       1  54.940298  47.528109 2020-02-16 19:03:51.250     5


问:
data rollback when one of the stored prod found faile in .net c#
Does anyone know how can I all data rollback in .net c# if one of the stored proc failed during the process?

Example:

```<code> protected void btnSave_Click(object sender, EventArgs e)
   {
      int ixTest= SaveTest("123");
      CreateTest(ixTest);

   }

   protected int SaveTest(int ixTestID)
   {
      SubSonic.StoredProcedure sp = Db.SPs.TestInsert(
         null,
         ixTestID);
      sp.Execute();
      int ixTest= (int)sp.OutputValues[0];
      return ixTest;
   }

   private long CreateTest(int ixTest)
   {
      long ixTestCustomer = CreateTestCustomer();

      TestCustomer testCustomer= new TestCustomer();
      try
      {
          testCustomer.TestCustomerId = ixTest;
          testCustomer.InteractionId = ixTestCustomer ;
          testCustomer.Save();
      }
      catch
      {
          Response.Redirect("pgCallSaveFailure.aspx");
      }

      m_saleDetail = new TestSaleDetail();
      try
      {
          m_saleDetail.SaleId = sale.SaleId;
          m_saleDetail.Save();
      }
      catch
      {
          Response.Redirect("pgCallSaveFailure.aspx");
      }

      return ixTestCustomer ;
   }
</code>```

I have the following code will call to btnSave_Click, then it will call to another 2 function Savetest() and CreateTest() to save data into the database. How can I rollback all data transaction in the following code if issue only happened in CreateTest() and which Savetest() have run successfully. How can I rollback all data for both Savetest() and CreateTest()?

答:
Code performs exact is given below. Hope you can get the idea. </p>

```<code>public void SaveData()
{
SqlConnection connDB = new SqlConnection();
SqlCommand cmdExecuting = new SqlCommand();

try {
    connDB = new SqlConnection(connection_string);
    cmdExecuting.Connection = connDB;
    connDB.Open();
    cmdExecuting.Transaction = connDB.BeginTransaction();

    int result = 0;

    result = Method1(cmdExecuting);

    if (result != 0) {
        cmdExecuting.Transaction.Rollback();
        return;
    }

    result = Method2(cmdExecuting);

    if (result != 0) {
        cmdExecuting.Transaction.Rollback();
        return;
    }

    cmdExecuting.Transaction.Commit();

} catch (Exception ex) {
    cmdExecuting.Transaction.Rollback();
} finally {
    cmdExecuting.Dispose();
    cmdExecuting = null;
    connDB.Close();
    connDB = null;
}

}

public int Method1(SqlCommand cmdExecuting)
{

cmdExecuting.Parameters.Clear();
cmdExecuting.CommandText = "stored proc 01";
cmdExecuting.CommandType = CommandType.StoredProcedure;

cmdExecuting.Parameters.Add("@para1", SqlDbType.Int);
cmdExecuting.Parameters("@para1").Value = value;

return cmdExecuting.ExecuteScalar();

}

public int Method2(SqlCommand cmdExecuting)
{

cmdExecuting.Parameters.Clear();
cmdExecuting.CommandText = "stored proc 02";
cmdExecuting.CommandType = CommandType.StoredProcedure;

cmdExecuting.Parameters.Add("@para1", SqlDbType.Int);
cmdExecuting.Parameters("@para1").Value = value;

return cmdExecuting.ExecuteScalar();

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Does anyone know how can I all data rollback in .net c# if one of the stored proc failed during the process?

Example:

 protected void btnSave_Click(object sender, EventArgs e)
   {
      int ixTest= SaveTest("123");
      CreateTest(ixTest);

   }

   protected int SaveTest(int ixTestID)
   {
      SubSonic.StoredProcedure sp = Db.SPs.TestInsert(
         null,
         ixTestID);
      sp.Execute();
      int ixTest= (int)sp.OutputValues[0];
      return ixTest;
   }

   private long CreateTest(int ixTest)
   {
      long ixTestCustomer = CreateTestCustomer();

      TestCustomer testCustomer= new TestCustomer();
      try
      {
          testCustomer.TestCustomerId = ixTest;
          testCustomer.InteractionId = ixTestCustomer ;
          testCustomer.Save();
      }
      catch
      {
          Response.Redirect("pgCallSaveFailure.aspx");
      }

      m_saleDetail = new TestSaleDetail();
      try
      {
          m_saleDetail.SaleId = sale.SaleId;
          m_saleDetail.Save();
      }
      catch
      {
          Response.Redirect("pgCallSaveFailure.aspx");
      }

      return ixTestCustomer ;
   }

I have the following code will call to btnSave_Click, then it will call to another 2 function Savetest() and CreateTest() to save data into the database. How can I rollback all data transaction in the following code if issue only happened in CreateTest() and which Savetest() have run successfully. How can I rollback all data for both Savetest() and CreateTest()?

Body:
Code performs exact is given below. Hope you can get the idea.

public void SaveData()
{
SqlConnection connDB = new SqlConnection();
SqlCommand cmdExecuting = new SqlCommand();

try {
    connDB = new SqlConnection(connection_string);
    cmdExecuting.Connection = connDB;
    connDB.Open();
    cmdExecuting.Transaction = connDB.BeginTransaction();

    int result = 0;

    result = Method1(cmdExecuting);

    if (result != 0) {
        cmdExecuting.Transaction.Rollback();
        return;
    }

    result = Method2(cmdExecuting);

    if (result != 0) {
        cmdExecuting.Transaction.Rollback();
        return;
    }

    cmdExecuting.Transaction.Commit();

} catch (Exception ex) {
    cmdExecuting.Transaction.Rollback();
} finally {
    cmdExecuting.Dispose();
    cmdExecuting = null;
    connDB.Close();
    connDB = null;
}

}

public int Method1(SqlCommand cmdExecuting)
{

cmdExecuting.Parameters.Clear();
cmdExecuting.CommandText = "stored proc 01";
cmdExecuting.CommandType = CommandType.StoredProcedure;

cmdExecuting.Parameters.Add("@para1", SqlDbType.Int);
cmdExecuting.Parameters("@para1").Value = value;

return cmdExecuting.ExecuteScalar();

}

public int Method2(SqlCommand cmdExecuting)
{

cmdExecuting.Parameters.Clear();
cmdExecuting.CommandText = "stored proc 02";
cmdExecuting.CommandType = CommandType.StoredProcedure;

cmdExecuting.Parameters.Add("@para1", SqlDbType.Int);
cmdExecuting.Parameters("@para1").Value = value;

return cmdExecuting.ExecuteScalar();

}


问:
Why is Google Colab raising an error for reading in a csv and jupyter notebook isn't?
I'm receiving this error when attempting to read in csv data using python and pandas. I don't experience this error in Jupyter notebooks but I'm trying to use google colab and experience the error there. Any ideas why google colab is raising the error but jupyter isn't?

```<code>df = pd.read_csv('./final_data_for_modeling.csv')

---------------------------------------------------------------------------
ParserError                               Traceback (most recent call last)
<ipython-input-7-3a755ce18082> in <module>()
      2
      3 # Load the dataset into a pandas dataframe.
----> 4 df = pd.read_csv('./final_data_for_modeling.csv')

ParserError: Error tokenizing data. C error: Expected 1 fields in line 3, saw 2
</code>```

For contrast here is a screenshot of the success in jupyter

If you'd like to take a look at the csv here is a dropbox link to the data:

https://www.dropbox.com/s/i3od76b52t19vzr/final_data_for_modeling.csv?dl=0

答:
This works out of the box for me. Here's a complete notebook:
https://colab.research.google.com/drive/1CATW8DtNh9wZTKpp5bV2DqfU6ChkFgty

Full code & output:

Body:
I'm receiving this error when attempting to read in csv data using python and pandas. I don't experience this error in Jupyter notebooks but I'm trying to use google colab and experience the error there. Any ideas why google colab is raising the error but jupyter isn't?

df = pd.read_csv('./final_data_for_modeling.csv')

---------------------------------------------------------------------------
ParserError                               Traceback (most recent call last)
<ipython-input-7-3a755ce18082> in <module>()
      2
      3 # Load the dataset into a pandas dataframe.
----> 4 df = pd.read_csv('./final_data_for_modeling.csv')

ParserError: Error tokenizing data. C error: Expected 1 fields in line 3, saw 2

For contrast here is a screenshot of the success in jupyter

If you'd like to take a look at the csv here is a dropbox link to the data:

https://www.dropbox.com/s/i3od76b52t19vzr/final_data_for_modeling.csv?dl=0


问:
Android Adapter only fetching the last entered data
I tried looking around but cant seem to find an answer that could resolve it.
Here is the process of what I'm doing:

1: Users enter data in a alert dialog

2: Data get sent into sql.

3: Adapter runs, takes data and put into a cardview.

4: Cardview is displayed(Stacks according to number of inputs made).

What that is not working to plan, the data that is being outputted overrides all previous inputs,and updates all cardviews with the latest information.

EG: Input 1: Test 1, Input 2: Test 2. Output will be 2 cardviews of Test 2.

Contact Activity

```<code>import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.sp.R;

public class Contacts extends AppCompatActivity {

    private Button newContact;
    private AlertDialog.Builder builder;
    private AlertDialog dialog;
    private RecyclerView recyclerView;

    private ContactDatabaseHelper helper;
    private ContactAdapter mAdapter;

    private EditText new_contact_name;
    private EditText new_contact_number;
    private EditText new_contact_relation;
    private Button button_create_contact;
    private Button button_cancel_create;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contacts);

        helper = new ContactDatabaseHelper(this);

        recyclerView = findViewById(R.id.contact_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ContactAdapter(this,getAllItems());
        recyclerView.setAdapter(mAdapter);

        newContact = findViewById(R.id.contact_button);
        // New Contact Button
        newContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                builder = new AlertDialog.Builder(Contacts.this);
                builder.setTitle("Create New Contact");
                builder.setCancelable(false);
                View view = LayoutInflater.from(Contacts.this).inflate(R.layout.new_contact_dialog,null,false);
                CreateDialog(view);
                builder.setView(view);
                dialog = builder.create();
                dialog.show();
            }
        });

    }

    private void CreateDialog(View view) {

        // ContactDialog ID's
        new_contact_name = view.findViewById(R.id.new_contact_name);
        new_contact_number = view.findViewById(R.id.new_contact_number);
        new_contact_relation = view.findViewById(R.id.new_contact_relation);
        button_create_contact = view.findViewById(R.id.button_create_contact);
        button_cancel_create = view.findViewById(R.id.button_cancel_create);

        button_create_contact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                        // Get String of Name, Number, Relationship
                        String contactNameStr = new_contact_name.getText().toString();
                        String contactNumberStr = new_contact_number.getText().toString();
                        String contactRelationStr = new_contact_relation.getText().toString();

                        // Insert into ContactTable
                        helper.insertContactDatabase(contactNameStr,contactNumberStr,contactRelationStr);
                        mAdapter.swapCursor(getAllItems());

                        // Outputs a Toast
                        Toast.makeText(Contacts.this, "Contact Created", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
            }
        });

        button_cancel_create.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

    }

    private Cursor getAllItems(){
        return helper.getContactDatabase();
    }

}
</code>```

Contact Adapter

```<code>import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.sp.R;

public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.MyHolder>{

    private Context mContext;
    private Cursor c;
    private ContactDatabaseHelper helper;

    public ContactAdapter(Context context,Cursor cursor) {

        mContext = context;
        c = cursor;
        helper = new ContactDatabaseHelper(mContext);
    }

    public static class MyHolder extends RecyclerView.ViewHolder{

        private TextView contact_name;
        private TextView contact_number;
        private TextView contact_relation;

        public MyHolder(View itemView) {
            super(itemView);

            contact_name = itemView.findViewById(R.id.contact_list_name_item);
            contact_number = itemView.findViewById(R.id.contact_list_number_item);
            contact_relation = itemView.findViewById(R.id.contact_list_relation_item);
        }
    }

    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(mContext).inflate(R.layout.contact_list,parent,false);

        return new MyHolder(view);
    }

    @Override
    public void onBindViewHolder(MyHolder holder, final int position) {

        c.moveToFirst();

        holder.contact_name.setText(helper.getContactName(c));
        holder.contact_number.setText(helper.getContactNumber(c));
        holder.contact_relation.setText(helper.getContactRelation(c));

    }

    @Override
    public int getItemCount() {

        return c.getCount();
    }

    public void swapCursor(Cursor newCursor){
        if (c != null){
            c.close();
        }

        c = newCursor;

        if (newCursor != null){
            notifyDataSetChanged();
        }
    }

}
</code>```

Contact Database

```<code>import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class ContactDatabaseHelper extends SQLiteOpenHelper {

    public static String DATABASE_NAME = "contactlist.db";
    private static final int SCHEMA_VERSION = 1;

    public ContactDatabaseHelper(Context context) { super(context, DATABASE_NAME, null, SCHEMA_VERSION); }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE contact_table( name TEXT, number TEXT , relation TEXT);");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    // Adds data into Contact database
    public void insertContactDatabase (String contact_name, String contact_number, String contact_relation) {
        ContentValues cv = new ContentValues();

        cv.put("name", contact_name);
        cv.put("number", contact_number);
        cv.put("relation", contact_relation);

        getWritableDatabase().insert("contact_table", "name", cv);
    }

    // Read Contact database
    public Cursor getContactDatabase() {
        return  (getReadableDatabase().rawQuery(
                "SELECT name, number, relation  FROM contact_table ORDER BY  + name", null));
    }

    // Delete Contact database
    public Integer deleteContactDatabase () {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete("contact_table",null,null);

    }

    public String getContactName (Cursor c){ return (c.getString(0)); }

    public String getContactNumber (Cursor c){ return (c.getString(1)); }

    public String getContactRelation (Cursor c){ return (c.getString(2)); }
}
</code>```

contacts

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/contact_background"
    tools:context=".Contact.Contacts">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/contact_recycler_view"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_above="@id/contact_button"
                    android:layout_marginTop="10dp"
                    android:scrollbars="vertical">

                </androidx.recyclerview.widget.RecyclerView>

                <Button
                    android:id="@+id/contact_button"
                    android:layout_width="150dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="10sp"
                    android:layout_marginBottom="10sp"
                    android:background="#43464B"
                    android:text="New Contact"
                    android:textAlignment="center"
                    android:textColor="#FFFFFF"
                    android:textSize="18sp" />
            </LinearLayout>
        </ScrollView>

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

contact_list (Cardview)

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/list_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="#FFEAB8"
    app:cardCornerRadius="15dp"
    app:cardElevation="5dp"
    app:cardUseCompatPadding="true">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardBackgroundColor="#00ACEE"
        app:cardCornerRadius="5dp"
        app:cardElevation="15dp"
        app:cardUseCompatPadding="true">

        <LinearLayout
            android:id="@+id/contact_layout_name"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="10dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:text="Name"
                android:textAlignment="center"
                android:textColor="#E6E6E6"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text=":"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/contact_list_name_item"
                android:layout_width="190dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text="Name"
                android:textColor="#FFFF00"
                android:textSize="20sp" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/contact_layout_number"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="35dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="5dp"
                android:text="Number"
                android:textAlignment="center"
                android:textColor="#E6E6E6"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:text=":"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/contact_list_number_item"
                android:layout_width="190dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:text="Number"
                android:textColor="#FFFF00"
                android:textSize="20sp" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/contact_layout_relation"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="60dp"
            android:layout_marginBottom="15dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="10dp"
                android:text="Relationship"
                android:textAlignment="center"
                android:textColor="#E6E6E6"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:text=":"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/contact_list_relation_item"
                android:layout_width="190dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:text="Relationship"
                android:textColor="#FFFF00"
                android:textSize="20sp" />

        </LinearLayout>

    </androidx.cardview.widget.CardView>

</androidx.cardview.widget.CardView>
</code>```

答:
Try copy all items to arrayList (only for test), then get item by position in onBindViewHolder

I am thinking your problem - c.moveToFirst(); in  onBindViewHolder

Body:
I tried looking around but cant seem to find an answer that could resolve it.
Here is the process of what I'm doing:

1: Users enter data in a alert dialog

2: Data get sent into sql.

3: Adapter runs, takes data and put into a cardview.

4: Cardview is displayed(Stacks according to number of inputs made).

What that is not working to plan, the data that is being outputted overrides all previous inputs,and updates all cardviews with the latest information.

EG: Input 1: Test 1, Input 2: Test 2. Output will be 2 cardviews of Test 2.

Contact Activity

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.sp.R;

public class Contacts extends AppCompatActivity {

    private Button newContact;
    private AlertDialog.Builder builder;
    private AlertDialog dialog;
    private RecyclerView recyclerView;

    private ContactDatabaseHelper helper;
    private ContactAdapter mAdapter;

    private EditText new_contact_name;
    private EditText new_contact_number;
    private EditText new_contact_relation;
    private Button button_create_contact;
    private Button button_cancel_create;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contacts);

        helper = new ContactDatabaseHelper(this);

        recyclerView = findViewById(R.id.contact_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ContactAdapter(this,getAllItems());
        recyclerView.setAdapter(mAdapter);

        newContact = findViewById(R.id.contact_button);
        // New Contact Button
        newContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                builder = new AlertDialog.Builder(Contacts.this);
                builder.setTitle("Create New Contact");
                builder.setCancelable(false);
                View view = LayoutInflater.from(Contacts.this).inflate(R.layout.new_contact_dialog,null,false);
                CreateDialog(view);
                builder.setView(view);
                dialog = builder.create();
                dialog.show();
            }
        });

    }

    private void CreateDialog(View view) {

        // ContactDialog ID's
        new_contact_name = view.findViewById(R.id.new_contact_name);
        new_contact_number = view.findViewById(R.id.new_contact_number);
        new_contact_relation = view.findViewById(R.id.new_contact_relation);
        button_create_contact = view.findViewById(R.id.button_create_contact);
        button_cancel_create = view.findViewById(R.id.button_cancel_create);

        button_create_contact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                        // Get String of Name, Number, Relationship
                        String contactNameStr = new_contact_name.getText().toString();
                        String contactNumberStr = new_contact_number.getText().toString();
                        String contactRelationStr = new_contact_relation.getText().toString();

                        // Insert into ContactTable
                        helper.insertContactDatabase(contactNameStr,contactNumberStr,contactRelationStr);
                        mAdapter.swapCursor(getAllItems());

                        // Outputs a Toast
                        Toast.makeText(Contacts.this, "Contact Created", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
            }
        });

        button_cancel_create.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

    }

    private Cursor getAllItems(){
        return helper.getContactDatabase();
    }

}

Contact Adapter

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.sp.R;

public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.MyHolder>{

    private Context mContext;
    private Cursor c;
    private ContactDatabaseHelper helper;

    public ContactAdapter(Context context,Cursor cursor) {

        mContext = context;
        c = cursor;
        helper = new ContactDatabaseHelper(mContext);
    }

    public static class MyHolder extends RecyclerView.ViewHolder{

        private TextView contact_name;
        private TextView contact_number;
        private TextView contact_relation;

        public MyHolder(View itemView) {
            super(itemView);

            contact_name = itemView.findViewById(R.id.contact_list_name_item);
            contact_number = itemView.findViewById(R.id.contact_list_number_item);
            contact_relation = itemView.findViewById(R.id.contact_list_relation_item);
        }
    }

    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(mContext).inflate(R.layout.contact_list,parent,false);

        return new MyHolder(view);
    }

    @Override
    public void onBindViewHolder(MyHolder holder, final int position) {

        c.moveToFirst();

        holder.contact_name.setText(helper.getContactName(c));
        holder.contact_number.setText(helper.getContactNumber(c));
        holder.contact_relation.setText(helper.getContactRelation(c));

    }

    @Override
    public int getItemCount() {

        return c.getCount();
    }

    public void swapCursor(Cursor newCursor){
        if (c != null){
            c.close();
        }

        c = newCursor;

        if (newCursor != null){
            notifyDataSetChanged();
        }
    }

}

Contact Database

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class ContactDatabaseHelper extends SQLiteOpenHelper {

    public static String DATABASE_NAME = "contactlist.db";
    private static final int SCHEMA_VERSION = 1;

    public ContactDatabaseHelper(Context context) { super(context, DATABASE_NAME, null, SCHEMA_VERSION); }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE contact_table( name TEXT, number TEXT , relation TEXT);");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    // Adds data into Contact database
    public void insertContactDatabase (String contact_name, String contact_number, String contact_relation) {
        ContentValues cv = new ContentValues();

        cv.put("name", contact_name);
        cv.put("number", contact_number);
        cv.put("relation", contact_relation);

        getWritableDatabase().insert("contact_table", "name", cv);
    }

    // Read Contact database
    public Cursor getContactDatabase() {
        return  (getReadableDatabase().rawQuery(
                "SELECT name, number, relation  FROM contact_table ORDER BY  + name", null));
    }

    // Delete Contact database
    public Integer deleteContactDatabase () {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete("contact_table",null,null);

    }

    public String getContactName (Cursor c){ return (c.getString(0)); }

    public String getContactNumber (Cursor c){ return (c.getString(1)); }

    public String getContactRelation (Cursor c){ return (c.getString(2)); }
}

contacts

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/contact_background"
    tools:context=".Contact.Contacts">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/contact_recycler_view"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_above="@id/contact_button"
                    android:layout_marginTop="10dp"
                    android:scrollbars="vertical">

                </androidx.recyclerview.widget.RecyclerView>

                <Button
                    android:id="@+id/contact_button"
                    android:layout_width="150dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="10sp"
                    android:layout_marginBottom="10sp"
                    android:background="#43464B"
                    android:text="New Contact"
                    android:textAlignment="center"
                    android:textColor="#FFFFFF"
                    android:textSize="18sp" />
            </LinearLayout>
        </ScrollView>

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

contact_list (Cardview)

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/list_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="#FFEAB8"
    app:cardCornerRadius="15dp"
    app:cardElevation="5dp"
    app:cardUseCompatPadding="true">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardBackgroundColor="#00ACEE"
        app:cardCornerRadius="5dp"
        app:cardElevation="15dp"
        app:cardUseCompatPadding="true">

        <LinearLayout
            android:id="@+id/contact_layout_name"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="10dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:text="Name"
                android:textAlignment="center"
                android:textColor="#E6E6E6"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text=":"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/contact_list_name_item"
                android:layout_width="190dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text="Name"
                android:textColor="#FFFF00"
                android:textSize="20sp" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/contact_layout_number"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="35dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="5dp"
                android:text="Number"
                android:textAlignment="center"
                android:textColor="#E6E6E6"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:text=":"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/contact_list_number_item"
                android:layout_width="190dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:text="Number"
                android:textColor="#FFFF00"
                android:textSize="20sp" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/contact_layout_relation"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="60dp"
            android:layout_marginBottom="15dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="10dp"
                android:text="Relationship"
                android:textAlignment="center"
                android:textColor="#E6E6E6"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:text=":"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/contact_list_relation_item"
                android:layout_width="190dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:text="Relationship"
                android:textColor="#FFFF00"
                android:textSize="20sp" />

        </LinearLayout>

    </androidx.cardview.widget.CardView>

</androidx.cardview.widget.CardView>


问:
Non-greedy capture groups in Postgres
I'm trying to implement a regex expression to parse out different groups of a string. The string I am provided signals a customer who wants to change their primary language on our platform from X to Y, so it will look like

language_change__from_english_to_spanish

language_change__from_spanish_to_somali

language_change__from_simplified_chinese_to_english

I have a regex to parse out the languages (the original language, and then the new language):

SUBSTRING(language_field FROM '^language_change__([a-zA-Z_]+)_to_[a-zA-Z_]+$')

The works great for the original language, but it does not work as well for the new language, because sometimes people have entered in language_change__from_english_to_spanish_. So what is actually parsed is spanish_ instead of spanish.

I know that I could easily just wrap my SUBSTRING(...) with a REPLACE to replace the final _, but I'm trying to find a way to do it using regex to sharpen my regex skills. I basically want to ignore the final _. However, I cannot remove _ from my capture group, because some languages coded in our system have _: simplified_chinese, for instance.

Basically, I want my capture group to include the first _ followed by text (like simplified_chinese), but do not include the _ if it is at the end of the string (english_).

So when language_change__from_spanish_to_english_ is entered, I should still capture english, and not english_ as the language.

I tried various ways:

Using negative lookahead: SUBSTRING(language_field FROM '^language_change__[a-zA-Z_]+_to_([a-zA-Z_]+)(?!_)$')

Using non-greedy capture groups: SUBSTRING(language_field FROM '^language_change__[a-zA-Z_]+_to_([a-zA-Z_]+?)$')

Using a combination of negative lookahead and non-greedy capture groups: SUBSTRING(language_field FROM '^language_change__[a-zA-Z_]+_to_([a-zA-Z_]+?)(?!_)$')

I feel like I've been on StackOverflow long enough to not say "nothing works", but all three things I tried above still yield english_ and not english when people incorrectly have entered language_change__from_spanish_to_english_ on our end.

Can someone give me some pointers what I'm missing?

答:
You may use

```<code>SUBSTRING(language_field FROM '^language_change__[a-zA-Z_]+_to_([a-zA-Z_]+?)_*$')
</code>```

The ([a-zA-Z_]+?)_*$ part means:

([a-zA-Z_]+?) - Group 1: match 1 or more ASCII letters or _ as few times as possible

_* - match 0 or more _ chars

$ - at the end of string.

The ([a-zA-Z_]+?) pattern will match 1 char, then _*$ pattern part will be tried. If _*$ fails to match, the engine will backtrack and the ([a-zA-Z_]+?) pattern will grab another char and the tests will repeat. Hence, if _s exist at the end of the string, they will not be included in the capturing group, they will be matched with _* part, and will thus be discarded from the result.

See this regex debugger step by step to see the regex in action.

Title: Non-greedy capture groups in Postgres

Body:
You may use

SUBSTRING(language_field FROM '^language_change__[a-zA-Z_]+_to_([a-zA-Z_]+?)_*$')

The ([a-zA-Z_]+?)_*$ part means:

([a-zA-Z_]+?) - Group 1: match 1 or more ASCII letters or _ as few times as possible

_* - match 0 or more _ chars

$ - at the end of string.

The ([a-zA-Z_]+?) pattern will match 1 char, then _*$ pattern part will be tried. If _*$ fails to match, the engine will backtrack and the ([a-zA-Z_]+?) pattern will grab another char and the tests will repeat. Hence, if _s exist at the end of the string, they will not be included in the capturing group, they will be matched with _* part, and will thus be discarded from the result.

See this regex debugger step by step to see the regex in action.


问:
Error converting tensorflow .pb model to .mlmodel
I am trying to convert a tensorflow graph (.pb file) into a .mlmodel

import tfcoreml
coreml_model = tfcoreml.convert(tf_model_path='optimized_model.pb', mlmodel_path='FaceImages.mlmodel', output_feature_names=['final_result'], input_name_shape_dict={'ResizeBilinear': {'images': None, 'size': {None, None}}}, minimum_ios_deployment_target='13')

```

<p>but I am getting following error:</p>

<blockquote>
  <p><em>/usr/local/lib/python3.6/dist-packages/coremltools/converters/nnssa/frontend/tensorflow/graphdef_to_ssa.py
  in load_tf_graph(graph_file)</em></p>

``` 21     with tf.io.gfile.GFile(graph_file, "rb") as f:
 22         graph_def = tf.compat.v1.GraphDef()
```

  <p><strong><em><code>---> 23         graph_def.ParseFromString(f.read())</code></em></strong></p>

``` 24
 25     # Then, we import the graph_def into a new Graph and returns it
```

DecodeError: Error parsing message

Could anybody help with this pls?

Here is the colab project where I have attached the tensorflow model and the associated code for conversion

https://colab.research.google.com/drive/1S7nf7pnX15UuswFZaTih5pHhfDFwG5Xa

答:
Have you checked that the version of Tensorflow your are using is compatible with those libraries? This is just a guess, but you could try running

!pip install tensorflow --upgrade

at the top of the notebook to see if it resolves the issue.

Body:
I am trying to convert a tensorflow graph (.pb file) into a .mlmodel

import tfcoreml
coreml_model = tfcoreml.convert(tf_model_path='optimized_model.pb', mlmodel_path='FaceImages.mlmodel', output_feature_names=['final_result'], input_name_shape_dict={'ResizeBilinear': {'images': None, 'size': {None, None}}}, minimum_ios_deployment_target='13')

but I am getting following error:

/usr/local/lib/python3.6/dist-packages/coremltools/converters/nnssa/frontend/tensorflow/graphdef_to_ssa.py
  in load_tf_graph(graph_file)

 21     with tf.io.gfile.GFile(graph_file, "rb") as f:
 22         graph_def = tf.compat.v1.GraphDef()

---> 23         graph_def.ParseFromString(f.read())

 24
 25     # Then, we import the graph_def into a new Graph and returns it

DecodeError: Error parsing message

Could anybody help with this pls?

Here is the colab project where I have attached the tensorflow model and the associated code for conversion

https://colab.research.google.com/drive/1S7nf7pnX15UuswFZaTih5pHhfDFwG5Xa


问:
How to find second occurrence of a column based on a condition?
Well, to find the first occurrence of STO1, I set aside a value 1 for STOf. Similarly, I want to find the second occurrence in STO1, to set aside a value 1 for STOs. I tried using some counter, but did not get it right.</p>

```<code>     ov26<-ov25 %>%
           group_by(ID) %>%
           mutate(STOf = { STO1 == 1 } %>% { . * !duplicated(.) } )
           %>% ungroup
</code>```

答:
I'm not sure this is what you're looking for, but just in case --- could you group_by both ID and STO1, something like:

```<code>ov25 %>%
  group_by(ID, STO1) %>%
  mutate(STOf = if_else(STO1 == 1 & row_number() == 1, 1, 0),
         STOs = if_else(STO1 == 1 & row_number() == 2, 1, 0))
</code>```

this would put a 1 in STOf for first row in the group, where STO1 is 1. Similar approach for STOs.

Body:
Well, to find the first occurrence of STO1, I set aside a value 1 for STOf. Similarly, I want to find the second occurrence in STO1, to set aside a value 1 for STOs. I tried using some counter, but did not get it right.

     ov26<-ov25 %>%
           group_by(ID) %>%
           mutate(STOf = { STO1 == 1 } %>% { . * !duplicated(.) } )
           %>% ungroup

Body:
I'm not sure this is what you're looking for, but just in case --- could you group_by both ID and STO1, something like:

ov25 %>%
  group_by(ID, STO1) %>%
  mutate(STOf = if_else(STO1 == 1 & row_number() == 1, 1, 0),
         STOs = if_else(STO1 == 1 & row_number() == 2, 1, 0))

this would put a 1 in STOf for first row in the group, where STO1 is 1. Similar approach for STOs.