问:
Return highest number and associated name from object in Javascript
This is my react app - https://imgur.com/a/QSuK8rY

I'm trying to return the highest and lowest latitude and the name of the city. I have it working to return the latitude but the name is coming up undefined... It is weird because in my jest testing, my function is working fine. I'm using React, Javascript and my API to load and store data... What I'm doing in this function is putting all the latitudes into an array then doing Math.max then looping through this.cities to see which latitude in the object matches the highest latitude that we put into mostNorthLat, then getting the name of the city that matches the lat.

This is my javascript file with my pure functions:

```<code>//Loads cities in API and injects it into this.cities

    async loadCities() {
            const data = await postData(url + "all");
            //Create a dictionary of cities and keep track of the last key
            const cities = {};
            data.forEach(x => {
                cities[x.key] = x;
                this.lastKey = (x.key > this.lastKey) ? x.key : this.lastKey;
            });

            this.cities = cities;
        }

//This is my add function I use for adding new cities to my API, which then React uses to create my cards for each object in my cities object in the API

    async addOrUpdate(city) {
            let theUrl;

            if (city.key) {
                theUrl = url + 'update'
            } else {
                theUrl = url + 'add'
                this.lastKey++;
                city.key = this.lastKey;
                city.population = Number(city.population)
            }
            await postData(theUrl, city);
            this.cities[city.key] = city;
    }

//My functions that are running the most North and most South

    getMostNorthern() {
            let latitudeArray = []
            let theName;
            for (let key in this.cities) {
                latitudeArray.push(this.cities[key].latitude)
            }
            let mostNorthLat = Math.max.apply(null, latitudeArray);
            for (let key in this.cities) {
                if (mostNorthLat === this.cities[key].latitude) {
                    theName = this.cities[key].name
                }
            }
            if (this.length() > 0) {
                return `${theName} at ${mostNorthLat}°`
            }
        }

    getMostSouthern() {
            let latitudeArray = []
            let theName;
            for (let key in this.cities) {
                latitudeArray.push(this.cities[key].latitude)
            }
            let mostSouthLat = Math.min.apply(null, latitudeArray);
            for (let key in this.cities) {
                if (mostSouthLat === this.cities[key].latitude) {
                    theName = this.cities[key].name
                }
            }
            if (this.length() > 0) {
                return `${theName} at ${mostSouthLat}°`
            }
        }
</code>```

Here is what a city object looks like:

```<code>    {
        "key": 1,
        "latitude": "1",
        "longitude": "1",
        "name": "City",
        "population": 49500
    },
</code>```

Each city object is held in a main object called 'cities'

```<code>    constructor() {
            this.cities = {};
            this.lastKey = 0;
        }
</code>```

So this is an what 3 cities inside the object looks like:

```<code>    {
            '1': City {
              name: "Gangster's Paradise",
              latitude: -15,
              longitude: 5,
              population: 10,
              key: 1
            },
            '2': City {
              name: 'Pho City',
              latitude: 5,
              longitude: 52,
              population: 1050,
              key: 2
            },
            '3': City {
              name: 'Frisbee Land',
              latitude: 0,
              longitude: 12,
              population: 1000000,
              key: 3
            }
    }
</code>```

My React portion:

```<code>    function CitiesApp() {
       const classes = useStyles();
       const [message, setMessage] = useState('')

       const [count, setCount] = useState(0)

       const [total, setTotal] = useState()
       const [northest, setNorthest] = useState()
       const [southest, setSouthest] = useState()

       useEffect(() => {
          //Load cities from the API - re-render when count is updated
          async function fetchData() {
             try {
                await cityCtrl.loadCities()
                updateSummary()
             } catch (e) {
                userMsg('Turn on the server')
             }
          }
          fetchData();
       }, [count]);

       async function onSave(city) {
          await cityCtrl.addOrUpdate(city)
          setCount(count + 1)
          updateSummary()
       }

       async function deleteCard(thekey) {
          await cityCtrl.deleteCard(thekey)
          setCount(count + 1)
          updateSummary()
       }

       async function moveIn(thekey, num) {
          await cityCtrl.movedIn(thekey, num)
          setCount(count + 1)
          updateSummary()
       }

       async function moveOut(thekey, num) {
          await cityCtrl.movedOut(thekey, num)
          setCount(count + 1)
          updateSummary()
       }

       function updateSummary() {
          setTotal(cityCtrl.getTotalPopulation())
          setNorthest(cityCtrl.getMostNorthern())
          setSouthest(cityCtrl.getMostSouthern())
       }
    }
</code>```

答:
Looks like you've found an answer.

Here's an alternative approach to finding the largest and smallest values by sorting arrays of values.

This approach uses a functional approach with regular objects, rather than an object-oriented approach with classes. Note that this would require a refactoring of your code since you're currently using City object instances.

const cities = {
  '1': {
    name: 'Gangster\'s Paradise',
    latitude: -15,
    longitude: 5,
    population: 10,
    key: 1
  },
  '2': {
    name: 'Pho City',
    latitude: 5,
    longitude: 52,
    population: 1050,
    key: 2
  },
  '3': {
    name: 'Frisbee Land',
    latitude: 0,
    longitude: 12,
    population: 1000000,
    key: 3
  }
}

// statically defined keys that the city objects contain
const cityKeys = [
  'name',
  'latitude',
  'longitude',
  'population',
  'key'
]

// convert an array of values back into a city object
const cityArrayToObject = (city) => city.
  reduce(
      (accumulator, current, currentIndex) =>{
        accumulator[cityKeys[currentIndex]] = current
        return accumulator
      }, {}
  )

// sort the arrays by latitude smallest to largest
// and then returns the first and last elements, converted
// back to an object using the function above.
// The array of values of cities looks like this before being sorted:
/*
[
  [ "Gangster's Paradise", -15, 5, 10, 1 ],
  [ 'Frisbee Land', 0, 12, 1000000, 3 ],
  [ 'Pho City', 5, 52, 1050, 2 ]
]
*/
const sortedCities = Object
  // make an array out of the keys of the city
  .keys(cities)
  // map that array to a new array of values for each key
  .map((value, index) => Object.values(cities[value]))
  // then sort that array by the latitude, which is in index 1
  .sort((a, b) => a[1] - b[1])

// take out the last item (pop), which is the largest
const largest = cityArrayToObject(sortedCities.pop())

// take out the first item (shift) which is the lowest
const smallest = cityArrayToObject(sortedCities.shift())

console.log('Largest:', largest, 'Smallest:', smallest)
```

<p>Which outputs:</p>

```Largest: {
  name: 'Pho City',
  latitude: 5,
  longitude: 52,
  population: 1050,
  key: 2
}
Smallest: {
  name: "Gangster's Paradise",
  latitude: -15,
  longitude: 5,
  population: 10,
  key: 1
}
```

Note that this doesn't account for the case where two cities may have the same latitude.

Body:
This is my react app - https://imgur.com/a/QSuK8rY

I'm trying to return the highest and lowest latitude and the name of the city. I have it working to return the latitude but the name is coming up undefined... It is weird because in my jest testing, my function is working fine. I'm using React, Javascript and my API to load and store data... What I'm doing in this function is putting all the latitudes into an array then doing Math.max then looping through this.cities to see which latitude in the object matches the highest latitude that we put into mostNorthLat, then getting the name of the city that matches the lat.

This is my javascript file with my pure functions:

//Loads cities in API and injects it into this.cities

    async loadCities() {
            const data = await postData(url + "all");
            //Create a dictionary of cities and keep track of the last key
            const cities = {};
            data.forEach(x => {
                cities[x.key] = x;
                this.lastKey = (x.key > this.lastKey) ? x.key : this.lastKey;
            });

            this.cities = cities;
        }

//This is my add function I use for adding new cities to my API, which then React uses to create my cards for each object in my cities object in the API

    async addOrUpdate(city) {
            let theUrl;

            if (city.key) {
                theUrl = url + 'update'
            } else {
                theUrl = url + 'add'
                this.lastKey++;
                city.key = this.lastKey;
                city.population = Number(city.population)
            }
            await postData(theUrl, city);
            this.cities[city.key] = city;
    }

//My functions that are running the most North and most South

    getMostNorthern() {
            let latitudeArray = []
            let theName;
            for (let key in this.cities) {
                latitudeArray.push(this.cities[key].latitude)
            }
            let mostNorthLat = Math.max.apply(null, latitudeArray);
            for (let key in this.cities) {
                if (mostNorthLat === this.cities[key].latitude) {
                    theName = this.cities[key].name
                }
            }
            if (this.length() > 0) {
                return `${theName} at ${mostNorthLat}°`
            }
        }

    getMostSouthern() {
            let latitudeArray = []
            let theName;
            for (let key in this.cities) {
                latitudeArray.push(this.cities[key].latitude)
            }
            let mostSouthLat = Math.min.apply(null, latitudeArray);
            for (let key in this.cities) {
                if (mostSouthLat === this.cities[key].latitude) {
                    theName = this.cities[key].name
                }
            }
            if (this.length() > 0) {
                return `${theName} at ${mostSouthLat}°`
            }
        }

Here is what a city object looks like:

    {
        "key": 1,
        "latitude": "1",
        "longitude": "1",
        "name": "City",
        "population": 49500
    },

Each city object is held in a main object called 'cities'

    constructor() {
            this.cities = {};
            this.lastKey = 0;
        }

So this is an what 3 cities inside the object looks like:

    {
            '1': City {
              name: "Gangster's Paradise",
              latitude: -15,
              longitude: 5,
              population: 10,
              key: 1
            },
            '2': City {
              name: 'Pho City',
              latitude: 5,
              longitude: 52,
              population: 1050,
              key: 2
            },
            '3': City {
              name: 'Frisbee Land',
              latitude: 0,
              longitude: 12,
              population: 1000000,
              key: 3
            }
    }

My React portion:

    function CitiesApp() {
       const classes = useStyles();
       const [message, setMessage] = useState('')

       const [count, setCount] = useState(0)

       const [total, setTotal] = useState()
       const [northest, setNorthest] = useState()
       const [southest, setSouthest] = useState()

       useEffect(() => {
          //Load cities from the API - re-render when count is updated
          async function fetchData() {
             try {
                await cityCtrl.loadCities()
                updateSummary()
             } catch (e) {
                userMsg('Turn on the server')
             }
          }
          fetchData();
       }, [count]);

       async function onSave(city) {
          await cityCtrl.addOrUpdate(city)
          setCount(count + 1)
          updateSummary()
       }

       async function deleteCard(thekey) {
          await cityCtrl.deleteCard(thekey)
          setCount(count + 1)
          updateSummary()
       }

       async function moveIn(thekey, num) {
          await cityCtrl.movedIn(thekey, num)
          setCount(count + 1)
          updateSummary()
       }

       async function moveOut(thekey, num) {
          await cityCtrl.movedOut(thekey, num)
          setCount(count + 1)
          updateSummary()
       }

       function updateSummary() {
          setTotal(cityCtrl.getTotalPopulation())
          setNorthest(cityCtrl.getMostNorthern())
          setSouthest(cityCtrl.getMostSouthern())
       }
    }

Body:
Looks like you've found an answer.

Here's an alternative approach to finding the largest and smallest values by sorting arrays of values.

This approach uses a functional approach with regular objects, rather than an object-oriented approach with classes. Note that this would require a refactoring of your code since you're currently using City object instances.

const cities = {
  '1': {
    name: 'Gangster\'s Paradise',
    latitude: -15,
    longitude: 5,
    population: 10,
    key: 1
  },
  '2': {
    name: 'Pho City',
    latitude: 5,
    longitude: 52,
    population: 1050,
    key: 2
  },
  '3': {
    name: 'Frisbee Land',
    latitude: 0,
    longitude: 12,
    population: 1000000,
    key: 3
  }
}

// statically defined keys that the city objects contain
const cityKeys = [
  'name',
  'latitude',
  'longitude',
  'population',
  'key'
]

// convert an array of values back into a city object
const cityArrayToObject = (city) => city.
  reduce(
      (accumulator, current, currentIndex) =>{
        accumulator[cityKeys[currentIndex]] = current
        return accumulator
      }, {}
  )

// sort the arrays by latitude smallest to largest
// and then returns the first and last elements, converted
// back to an object using the function above.
// The array of values of cities looks like this before being sorted:
/*
[
  [ "Gangster's Paradise", -15, 5, 10, 1 ],
  [ 'Frisbee Land', 0, 12, 1000000, 3 ],
  [ 'Pho City', 5, 52, 1050, 2 ]
]
*/
const sortedCities = Object
  // make an array out of the keys of the city
  .keys(cities)
  // map that array to a new array of values for each key
  .map((value, index) => Object.values(cities[value]))
  // then sort that array by the latitude, which is in index 1
  .sort((a, b) => a[1] - b[1])

// take out the last item (pop), which is the largest
const largest = cityArrayToObject(sortedCities.pop())

// take out the first item (shift) which is the lowest
const smallest = cityArrayToObject(sortedCities.shift())

console.log('Largest:', largest, 'Smallest:', smallest)

Which outputs:

Largest: {
  name: 'Pho City',
  latitude: 5,
  longitude: 52,
  population: 1050,
  key: 2
}
Smallest: {
  name: "Gangster's Paradise",
  latitude: -15,
  longitude: 5,
  population: 10,
  key: 1
}

Note that this doesn't account for the case where two cities may have the same latitude.


来源: stackexchange

问:
Spring Log in system
I'm bulding webApp in Spring, which need log in system and authorization system.

For login I will have route that provides JSON Wep Token. Code of checking user:

```<code>    @RequestMapping(value="test", method = RequestMethod.GET)
@ResponseBody
public void test (@RequestBody user checkUser) {

    System.out.println(checkCredentials(checkUser));

}

public final Boolean checkCredentials (user checkUser) {

    try {

        user existingUser = uRepo.getOne(checkUser.getuEmail());
        Boolean match = BCrypt.checkpw(checkUser.getuPassword(),existingUser.getuPassword());
        return match;
    } catch (Exception e) {
        System.out.println("User does not exist!");
        System.out.println(e.toString());
        return false;
    }
}
</code>```

For now its raw, but it checks if there is uses with that email, than will check password.

First question: Is it valid way of checking users credentials? Or should I use spring security?

Secound question: How should I move function to other class? Because when i just moved it and used, I had problems with exceptions (null pointer) and function didn't work.

Third question: is there any good way to make "middleware" like in Node.js? I think it will need to be some kind of HttpRequest Filter but I'm not quite sure. I want to check if user have bearer token to go with other functions.

答:
It's not best way to do that. Use Spring Security and sit back. Everything you want is bundled in Spring Security. Filters, method level security, roles, authorities...

You can find Spring Security + JWT example projects on Github:

Here is minimal example

More advanced one

ContentLicense: CC BY-SA 4.0

Title: Spring Log in system

Body:
I'm bulding webApp in Spring, which need log in system and authorization system.

For login I will have route that provides JSON Wep Token. Code of checking user:

    @RequestMapping(value="test", method = RequestMethod.GET)
@ResponseBody
public void test (@RequestBody user checkUser) {

    System.out.println(checkCredentials(checkUser));

}

public final Boolean checkCredentials (user checkUser) {

    try {

        user existingUser = uRepo.getOne(checkUser.getuEmail());
        Boolean match = BCrypt.checkpw(checkUser.getuPassword(),existingUser.getuPassword());
        return match;
    } catch (Exception e) {
        System.out.println("User does not exist!");
        System.out.println(e.toString());
        return false;
    }
}

For now its raw, but it checks if there is uses with that email, than will check password.

First question: Is it valid way of checking users credentials? Or should I use spring security?

Secound question: How should I move function to other class? Because when i just moved it and used, I had problems with exceptions (null pointer) and function didn't work.

Third question: is there any good way to make "middleware" like in Node.js? I think it will need to be some kind of HttpRequest Filter but I'm not quite sure. I want to check if user have bearer token to go with other functions.


问:
How do you compute minimum from pandas data frame columns, without creating temporary column?
Suppose, I have a pandas data frame df with columns A, B and C. I would like to compute the row-wise minimum from arithmetic operator on the columns, specifically df['D']=min(df['A']+dF['B']*3, df['C']*np.sqrt(12)). I have seen related questions, and it would seem like I would need to first create two columns for the arguments in the min function, and them perform min of axis =1. I was wondering if there was another way, without creating the temporary columns.

答:
Without creating new columns, you can use apply:

```<code>df['D'] = df.apply(lambda x: min(x['A'] + x['B']*3, x['C']*np.sqrt(12), axis=1)
</code>```

But it's best just do:

```<code>df['D'] = np.mininum(df['A']+dF['B']*3, df['C']*np.sqrt(12))
</code>```

which creates two intermediate columns/series but is much faster thanks to vectorization.

Body:
Without creating new columns, you can use apply:

df['D'] = df.apply(lambda x: min(x['A'] + x['B']*3, x['C']*np.sqrt(12), axis=1)

But it's best just do:

df['D'] = np.mininum(df['A']+dF['B']*3, df['C']*np.sqrt(12))

which creates two intermediate columns/series but is much faster thanks to vectorization.


问:
Destructuring to get the last element of an array in es6
In coffeescript this is straightforward:

```<code>coffee> a = ['a', 'b', 'program']
[ 'a', 'b', 'program' ]
coffee> [_..., b] = a
[ 'a', 'b', 'program' ]
coffee> b
'program'
</code>```

Does es6 allow for something similar?

```<code>> const [, b] = [1, 2, 3]
'use strict'
> b  // it got the second element, not the last one!
2
> const [...butLast, last] = [1, 2, 3]
SyntaxError: repl: Unexpected token (1:17)
> 1 | const [...butLast, last] = [1, 2, 3]
    |                  ^
    at Parser.pp.raise (C:\Users\user\AppData\Roaming\npm\node_modules\babel\node_modules\babel-core\node_modules\babylon\lib\parser\location.js:24:13)
</code>```

Of course I can do it the es5 way -

```<code>const a = b[b.length - 1]
</code>```

But maybe this is a bit prone to off by one errors. Can the splat only be the last thing in the destructuring?

ContentLicense: CC BY-SA 3.0

Body:
In coffeescript this is straightforward:

coffee> a = ['a', 'b', 'program']
[ 'a', 'b', 'program' ]
coffee> [_..., b] = a
[ 'a', 'b', 'program' ]
coffee> b
'program'

Does es6 allow for something similar?

> const [, b] = [1, 2, 3]
'use strict'
> b  // it got the second element, not the last one!
2
> const [...butLast, last] = [1, 2, 3]
SyntaxError: repl: Unexpected token (1:17)
> 1 | const [...butLast, last] = [1, 2, 3]
    |                  ^
    at Parser.pp.raise (C:\Users\user\AppData\Roaming\npm\node_modules\babel\node_modules\babel-core\node_modules\babylon\lib\parser\location.js:24:13)

Of course I can do it the es5 way -

const a = b[b.length - 1]

But maybe this is a bit prone to off by one errors. Can the splat only be the last thing in the destructuring?

Body:
let a = [1,2,3]
let [b] = [...a].reverse()


问:
App crashing when using Firebase Auth, reason: 'Default app has already been configured.'
I'm building my first iOS application, and I am using Firebase to handle authentication, database, etc. I added a sign up screen and used the following code to create a new user:

```<code>FIRAuth.auth()?.createUserWithEmail(emailAddress.text!, password: password.text!, completion: { (user, error) in

        })
</code>```

When the user taps on the sign up button, there is a segue that should take them back to the original login view controller. However, when I got to run the app, it hangs on the launch screen. Here is the debugger output:

```<code>2016-06-19 14:35:05.402 unitaskr[4386:82981] Configuring the default app.
2016-06-19 14:35:05.413 unitaskr[4386:] <FIRAnalytics/INFO> Firebase Analytics     v.3200000 started
2016-06-19 14:35:05.414 unitaskr[4386:] <FIRAnalytics/INFO> To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see ...)
2016-06-19 14:35:05.419: <FIRInstanceID/WARNING> FIRInstanceID AppDelegate proxy enabled, will swizzle app delegate remote notification handlers. To disable add "FirebaseAppDelegateProxyEnabled" to your Info.plist and set it to NO
2016-06-19 14:35:05.418 unitaskr[4386:] <FIRAnalytics/INFO> Successfully created Firebase Analytics App Delegate Proxy automatically. To disable the proxy, set the flag FirebaseAppDelegateProxyEnabled to NO in the Info.plist
2016-06-19 14:35:05.430 unitaskr[4386:82981] *** Terminating app due to uncaught exception 'com.firebase.core', reason: 'Default app has already been configured.'
*** First throw call stack:
(
0   CoreFoundation                      0x00000001100a8d85   __exceptionPreprocess + 165
1   libobjc.A.dylib                     0x00000001108e7deb objc_exception_throw + 48
2   CoreFoundation                      0x00000001100a8cbd +[NSException raise:format:] + 205
3   unitaskr                            0x000000010b58844d +[FIRApp    configureDefaultAppWithOptions:sendingNotifications:] + 102
4   unitaskr                            0x000000010b588238 +[FIRApp configure] + 302
5   unitaskr                            0x000000010b541f1a _TFC8unitaskr11AppDelegate11applicationfTCSo13UIApplication29didFinishLaunchingWithOptionsGSqGVs10DictionaryCSo8NSObjectPs9AnyObject____Sb + 266
6   unitaskr                            0x000000010b542204 _TToFC8unitaskr11AppDelegate11applicationfTCSo13UIApplication29didFinishLaunchingWithOptionsGSqGVs10DictionaryCSo8NSObjectPs9AnyObject____Sb + 180
7   UIKit                               0x000000010e5bf9ac -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 272
8   UIKit                               0x000000010e5c0c0d -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 3415
9   UIKit                               0x000000010e5c7568 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1769
10  UIKit                               0x000000010e5c4714 -[UIApplication workspaceDidEndTransaction:] + 188
11  FrontBoardServices                  0x00000001127b78c8 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24
12  FrontBoardServices                  0x00000001127b7741 -[FBSSerialQueue _performNext] + 178
13  FrontBoardServices                  0x00000001127b7aca -[FBSSerialQueue _performNextFromRunLoopSource] + 45
14  CoreFoundation                      0x000000010ffce301 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
15  CoreFoundation                      0x000000010ffc422c __CFRunLoopDoSources0 + 556
16  CoreFoundation                      0x000000010ffc36e3 __CFRunLoopRun + 867
17  CoreFoundation                      0x000000010ffc30f8 CFRunLoopRunSpecific + 488
18  UIKit                               0x000000010e5c3f21 -[UIApplication _run] + 402
19  UIKit                               0x000000010e5c8f09 UIApplicationMain + 171
20  unitaskr                            0x000000010b542a42 main + 114
21  libdyld.dylib                       0x00000001113b692d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
</code>```

I can provide additional information as needed, any help/advice would be greatly appreciated as I am just starting out and looking to learn as much as possible. Have a great day!

答:
If you're using Scene delegate from and you have different iOS versions like 9, 10 up to 13, you must call in AppDelegate.swift in this way:

```<code> if #available(iOS 13.0, *) {

 } else {
     FirebaseApp.configure()
 }
</code>```

And in SceneDelegate.swift this way:

```<code> if #available(iOS 13.0, *) {
   FirebaseApp.configure()
 }
</code>```

These settings will exclude error like:
*

*** Terminating app due to uncaught exception 'com.firebase.core', reason: 'Default app has already been configured.'

Body:
I'm building my first iOS application, and I am using Firebase to handle authentication, database, etc. I added a sign up screen and used the following code to create a new user:

FIRAuth.auth()?.createUserWithEmail(emailAddress.text!, password: password.text!, completion: { (user, error) in

        })

When the user taps on the sign up button, there is a segue that should take them back to the original login view controller. However, when I got to run the app, it hangs on the launch screen. Here is the debugger output:

2016-06-19 14:35:05.402 unitaskr[4386:82981] Configuring the default app.
2016-06-19 14:35:05.413 unitaskr[4386:] <FIRAnalytics/INFO> Firebase Analytics     v.3200000 started
2016-06-19 14:35:05.414 unitaskr[4386:] <FIRAnalytics/INFO> To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see ...)
2016-06-19 14:35:05.419: <FIRInstanceID/WARNING> FIRInstanceID AppDelegate proxy enabled, will swizzle app delegate remote notification handlers. To disable add "FirebaseAppDelegateProxyEnabled" to your Info.plist and set it to NO
2016-06-19 14:35:05.418 unitaskr[4386:] <FIRAnalytics/INFO> Successfully created Firebase Analytics App Delegate Proxy automatically. To disable the proxy, set the flag FirebaseAppDelegateProxyEnabled to NO in the Info.plist
2016-06-19 14:35:05.430 unitaskr[4386:82981] *** Terminating app due to uncaught exception 'com.firebase.core', reason: 'Default app has already been configured.'
*** First throw call stack:
(
0   CoreFoundation                      0x00000001100a8d85   __exceptionPreprocess + 165
1   libobjc.A.dylib                     0x00000001108e7deb objc_exception_throw + 48
2   CoreFoundation                      0x00000001100a8cbd +[NSException raise:format:] + 205
3   unitaskr                            0x000000010b58844d +[FIRApp    configureDefaultAppWithOptions:sendingNotifications:] + 102
4   unitaskr                            0x000000010b588238 +[FIRApp configure] + 302
5   unitaskr                            0x000000010b541f1a _TFC8unitaskr11AppDelegate11applicationfTCSo13UIApplication29didFinishLaunchingWithOptionsGSqGVs10DictionaryCSo8NSObjectPs9AnyObject____Sb + 266
6   unitaskr                            0x000000010b542204 _TToFC8unitaskr11AppDelegate11applicationfTCSo13UIApplication29didFinishLaunchingWithOptionsGSqGVs10DictionaryCSo8NSObjectPs9AnyObject____Sb + 180
7   UIKit                               0x000000010e5bf9ac -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 272
8   UIKit                               0x000000010e5c0c0d -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 3415
9   UIKit                               0x000000010e5c7568 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1769
10  UIKit                               0x000000010e5c4714 -[UIApplication workspaceDidEndTransaction:] + 188
11  FrontBoardServices                  0x00000001127b78c8 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24
12  FrontBoardServices                  0x00000001127b7741 -[FBSSerialQueue _performNext] + 178
13  FrontBoardServices                  0x00000001127b7aca -[FBSSerialQueue _performNextFromRunLoopSource] + 45
14  CoreFoundation                      0x000000010ffce301 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
15  CoreFoundation                      0x000000010ffc422c __CFRunLoopDoSources0 + 556
16  CoreFoundation                      0x000000010ffc36e3 __CFRunLoopRun + 867
17  CoreFoundation                      0x000000010ffc30f8 CFRunLoopRunSpecific + 488
18  UIKit                               0x000000010e5c3f21 -[UIApplication _run] + 402
19  UIKit                               0x000000010e5c8f09 UIApplicationMain + 171
20  unitaskr                            0x000000010b542a42 main + 114
21  libdyld.dylib                       0x00000001113b692d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

I can provide additional information as needed, any help/advice would be greatly appreciated as I am just starting out and looking to learn as much as possible. Have a great day!

Body:
If you're using Scene delegate from and you have different iOS versions like 9, 10 up to 13, you must call in AppDelegate.swift in this way:

 if #available(iOS 13.0, *) {

 } else {
     FirebaseApp.configure()
 }

And in SceneDelegate.swift this way:

 if #available(iOS 13.0, *) {
   FirebaseApp.configure()
 }

These settings will exclude error like:
*

*** Terminating app due to uncaught exception 'com.firebase.core', reason: 'Default app has already been configured.'


问:
how to set radio button text(caption) to center
**VB.NET 2010 , ASPNET *******

Hi,

Is there a way to set the radio button text to center,
I want to show it on the top of radiobutton hole..thanks

答: Set the Text of the RadioButton to String.Empty. Add a Label to the top of it.


问:
viv.self does not define "profile"
what does this error message mean?

Line 35:5'viv.self' does not define 'profile'

capsule.bxb:

```<code> permissions {
    library-permission (contact:contacts)
    library-permission (self:profile)
    device-location-access
  }
</code>```

Does it mean there has to be a Profile concept?

答:
Please use an updated version 4.0.1.

Please also add code to capsule-info.bxb as step 3 in https://bixbydevelopers.com/dev/docs/dev-guide/developers/library.self

Title: viv.self does not define "profile"

Body:
what does this error message mean?

Line 35:5'viv.self' does not define 'profile'

capsule.bxb:

 permissions {
    library-permission (contact:contacts)
    library-permission (self:profile)
    device-location-access
  }

Does it mean there has to be a Profile concept?


问:
SQL SELECT with bad data
If a column has bad data such as:

```<code> 45612345698
 (456)123-7452
 125-145-9856
</code>```

Without fixing the data. Is it possible to have a sql query of 1251459856 which then would return the 3rd item in the column?

答:
Hmmm . . . you could use replace():

```<code>where replace(replace(replace(col, '-', ''), '(', ''), ')', '') = '1251459856'
</code>```

Title: SQL SELECT with bad data

Body:
If a column has bad data such as:

 45612345698
 (456)123-7452
 125-145-9856

Without fixing the data. Is it possible to have a sql query of 1251459856 which then would return the 3rd item in the column?

Body:
Hmmm . . . you could use replace():

where replace(replace(replace(col, '-', ''), '(', ''), ')', '') = '1251459856'


问:
Can i change the button's content in MFMessageComposeViewController?
I want to use MFMessageComposeViewController to send a message. Can I change the button's content? For example, from "Send" to "OK"?

答:
You are not allowed to customize the MFMessageComposeViewController by apple.

Check in the Apple Documentation for MFMessageComposeViewController


问:
Understanding nested Monad constraints
Say I have the following type:

```<code>data Row = Row
  {
    id                          :: !AddressID
  }
</code>```

with the following internal transformation function:

```<code>makeAddress :: MonadIO m => MonadError Error m => Connection -> Row -> m Address
makeAddress _ Row{..} = return $ Address "Potato"
</code>```

I then have the following function to read from a database using Postgres.Simple:

```<code>findMany
  :: MonadIO m
  => MonadReader Context m
  => MonadError Error m
  => [AddressID]
  -> m [Address]

findMany ids = do
  db <- view Context.db
  xs <- liftIO $ PG.query db sql_query_addr $ PG.Only (PG.In (map unAddressId ids))
  if (length xs) == (length ids)
    then do
      let addresses = concat (map (makeAddress db) xs)
      return addresses
    else
      throwError $ AddressNotFound Nothing

-----------------------------------------------------------------------------------------------------------------------

sql_query_addr :: PG.Query
sql_query_addr = [qms|
  SELECT *
  FROM addresses a
  WHERE a.id in ?
|]
</code>```

This fails to compile with:

```<code>    • Could not deduce (MonadIO [])
        arising from a use of ‘makeAddress’
      from the context: (MonadIO m, MonadReader Context m,
                         MonadError Error m)
        bound by the type signature for:
                   findMany :: forall (m :: * -> *).
                               (MonadIO m, MonadReader Context m, MonadError Error m) =>
                               [AddressID] -> m [Address]
        at app/Impl/ReadModelApi/FindMany.hs:(22,1)-(27,18)
    • In the first argument of ‘map’, namely ‘(makeAddress db)’
      In the first argument of ‘concat’, namely
        ‘(map (makeAddress db) xs)’
      In the expression: concat (map (makeAddress db) xs)
   |
34 |       let quotations = concat (map (makeAddress db) xs)
   |                                     ^^^^^^^^^^^^^^^^^
</code>```

I realize that my makeAddress function is needlessly complex, this is a minimal case, boiled down from a much larger, more sideffecty transformation function.

But I don't understand why this fails to compile, I would have thought that:

Given this type: makeAddress :: MonadIO m => MonadError Error m => Connection -> Row -> m Address, the type of makeAddress db is MonadIO m => MonadError Error m -> Row -> m Address. Given xs has type [Row], map (makeAddress db) xs should give [Addresses].

And given that both the inner and outer m (in makeAddress and in findMany) is an instance of the MonadIO typeclass, these should be compatible monads?

Clearly this is incorrect, but I have no idea where my reasoning breaks down, or how to therefore fix my implementation.

答:
concat (map f list) requires f to return a list. This is so map f list can produce a list-of-lists to concat.

Hence, in your code you are using makeAddress choosing m = [] so that map (makeAddress ...) xs :: [[Address]] and concat (....) :: [Address]. Now, makeAddress requires that the monad m is in class MonadIO, but m = [] is not, hence the error.

Try using something like

```<code>...
then mapM (makeAddress db) xs
else ...
</code>```

Title: Understanding nested Monad constraints

Body:
Say I have the following type:

data Row = Row
  {
    id                          :: !AddressID
  }

with the following internal transformation function:

makeAddress :: MonadIO m => MonadError Error m => Connection -> Row -> m Address
makeAddress _ Row{..} = return $ Address "Potato"

I then have the following function to read from a database using Postgres.Simple:

findMany
  :: MonadIO m
  => MonadReader Context m
  => MonadError Error m
  => [AddressID]
  -> m [Address]

findMany ids = do
  db <- view Context.db
  xs <- liftIO $ PG.query db sql_query_addr $ PG.Only (PG.In (map unAddressId ids))
  if (length xs) == (length ids)
    then do
      let addresses = concat (map (makeAddress db) xs)
      return addresses
    else
      throwError $ AddressNotFound Nothing

-----------------------------------------------------------------------------------------------------------------------

sql_query_addr :: PG.Query
sql_query_addr = [qms|
  SELECT *
  FROM addresses a
  WHERE a.id in ?
|]

This fails to compile with:

    • Could not deduce (MonadIO [])
        arising from a use of ‘makeAddress’
      from the context: (MonadIO m, MonadReader Context m,
                         MonadError Error m)
        bound by the type signature for:
                   findMany :: forall (m :: * -> *).
                               (MonadIO m, MonadReader Context m, MonadError Error m) =>
                               [AddressID] -> m [Address]
        at app/Impl/ReadModelApi/FindMany.hs:(22,1)-(27,18)
    • In the first argument of ‘map’, namely ‘(makeAddress db)’
      In the first argument of ‘concat’, namely
        ‘(map (makeAddress db) xs)’
      In the expression: concat (map (makeAddress db) xs)
   |
34 |       let quotations = concat (map (makeAddress db) xs)
   |                                     ^^^^^^^^^^^^^^^^^

I realize that my makeAddress function is needlessly complex, this is a minimal case, boiled down from a much larger, more sideffecty transformation function.

But I don't understand why this fails to compile, I would have thought that:

Given this type: makeAddress :: MonadIO m => MonadError Error m => Connection -> Row -> m Address, the type of makeAddress db is MonadIO m => MonadError Error m -> Row -> m Address. Given xs has type [Row], map (makeAddress db) xs should give [Addresses].

And given that both the inner and outer m (in makeAddress and in findMany) is an instance of the MonadIO typeclass, these should be compatible monads?

Clearly this is incorrect, but I have no idea where my reasoning breaks down, or how to therefore fix my implementation.

Body:
concat (map f list) requires f to return a list. This is so map f list can produce a list-of-lists to concat.

Hence, in your code you are using makeAddress choosing m = [] so that map (makeAddress ...) xs :: [[Address]] and concat (....) :: [Address]. Now, makeAddress requires that the monad m is in class MonadIO, but m = [] is not, hence the error.

Try using something like

...
then mapM (makeAddress db) xs
else ...


问:
How to obtain the max. value of n-period for every row based on values of another columns in a dataframe?
Let's say I have a df:

```<code>idx   c1
A     1
B     7
C     8
D     6
E     5
F     6
G     9
H     8
I     0
J    10
</code>```

What's the fastest way to obtain the highest value for n-periods for every row based on c1, then create a new column for it? Eg. if it's 3-period, then it will be like this:

```<code>idx   c1   new_col
A     1     0
B     7     0
C     8     0
D     6     8      (prev. 3-period, 1,7,8, 8 is the highest)
E     5     8      (prev. 3-period, 7,8,6  8 is the highest)
F     6     8      (prev. 3-period, 8,6,5  8 is the highest)
G     9     6      (prev. 3-period, 6,5,6  6 is the highest)
H     8     9      (prev. 3-period, 5,6,9  9 is the highest)
I     0     9      (prev. 3-period, 6,9,8  9 is the highest)
J    10     9      (prev. 3-period, 9,8,0  9 is the highest)
</code>```

My current code is now:

```<code>list=[]
for row in range(len(df)):
    if row < 3:
       list.append(0)
    else:
       list.append(max(c1[row-3:row]))
df['new_col'] = list
</code>```

This method is very slow because I have many rows and this has to loop through the whole thing. Is there a faster way to do it? Thanks.

Body:
Let's say I have a df:

idx   c1
A     1
B     7
C     8
D     6
E     5
F     6
G     9
H     8
I     0
J    10

What's the fastest way to obtain the highest value for n-periods for every row based on c1, then create a new column for it? Eg. if it's 3-period, then it will be like this:

idx   c1   new_col
A     1     0
B     7     0
C     8     0
D     6     8      (prev. 3-period, 1,7,8, 8 is the highest)
E     5     8      (prev. 3-period, 7,8,6  8 is the highest)
F     6     8      (prev. 3-period, 8,6,5  8 is the highest)
G     9     6      (prev. 3-period, 6,5,6  6 is the highest)
H     8     9      (prev. 3-period, 5,6,9  9 is the highest)
I     0     9      (prev. 3-period, 6,9,8  9 is the highest)
J    10     9      (prev. 3-period, 9,8,0  9 is the highest)

My current code is now:

list=[]
for row in range(len(df)):
    if row < 3:
       list.append(0)
    else:
       list.append(max(c1[row-3:row]))
df['new_col'] = list

This method is very slow because I have many rows and this has to loop through the whole thing. Is there a faster way to do it? Thanks.

Body:
This is just rolling and shift:

df['new_col'] = df['c1'].rolling(3).max().shift().fillna(0)

Output:

  idx  c1  new_col
0   A   1      0.0
1   B   7      0.0
2   C   8      0.0
3   D   6      8.0
4   E   5      8.0
5   F   6      8.0
6   G   9      6.0
7   H   8      9.0
8   I   0      9.0
9   J  10      9.0


问:
Why does the "Try a higher/lower number." only appear after the second run?
When I run the code with the commented out portion, the program works as intended. After the first guess, it tells the user to try a higher or lower number. Without the commented out portion, the prompts only appear after the second guess.

I just started learning Java and the book I am following does not offer further explanation.

```<code>import static java.lang.System.out;
import java.util.Scanner;
import java.util.Random;

public class GuessAgain {

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

        int numGuesses = 0;
        int randomNumber = new Random().nextInt(100) + 1;

        int minbound = 1;
        int maxbound = 100;

        out.println("          **********          ");
        out.println(" Welcome to the Guessing Game ");
        out.println("          **********          ");
        out.println();

        out.print(" Enter an number from " + minbound + " to " + maxbound + ": ");
        int inputNumber = keyboard.nextInt();
        numGuesses++;

        /*
        if (inputNumber > randomNumber) {
            out.println("Try a lower number!");
        }
        if (inputNumber < randomNumber) {
            out.println("Try a higher number!");

         */

            while (inputNumber != randomNumber) {
                out.println();
                out.print(" Enter an number from " + minbound + " to " + maxbound + ": ");
                inputNumber = keyboard.nextInt();
                numGuesses++;

                if (inputNumber > randomNumber) {
                    out.println("Try a lower number!");
                }
                if (inputNumber < randomNumber) {
                    out.println("Try a higher number!");
                }
            }

            out.println("You win after " + numGuesses + " guesses.");

            keyboard.close();

        }
    }

</code>```

答:
This is because after the first guess you are entering the while loop, which starts with asking for a new guess before giving a hint.

First ask is outside of while loop, second is inside, afterwards comes the hint.

Body:
When I run the code with the commented out portion, the program works as intended. After the first guess, it tells the user to try a higher or lower number. Without the commented out portion, the prompts only appear after the second guess.

I just started learning Java and the book I am following does not offer further explanation.

import static java.lang.System.out;
import java.util.Scanner;
import java.util.Random;

public class GuessAgain {

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

        int numGuesses = 0;
        int randomNumber = new Random().nextInt(100) + 1;

        int minbound = 1;
        int maxbound = 100;

        out.println("          **********          ");
        out.println(" Welcome to the Guessing Game ");
        out.println("          **********          ");
        out.println();

        out.print(" Enter an number from " + minbound + " to " + maxbound + ": ");
        int inputNumber = keyboard.nextInt();
        numGuesses++;

        /*
        if (inputNumber > randomNumber) {
            out.println("Try a lower number!");
        }
        if (inputNumber < randomNumber) {
            out.println("Try a higher number!");

         */

            while (inputNumber != randomNumber) {
                out.println();
                out.print(" Enter an number from " + minbound + " to " + maxbound + ": ");
                inputNumber = keyboard.nextInt();
                numGuesses++;

                if (inputNumber > randomNumber) {
                    out.println("Try a lower number!");
                }
                if (inputNumber < randomNumber) {
                    out.println("Try a higher number!");
                }
            }

            out.println("You win after " + numGuesses + " guesses.");

            keyboard.close();

        }
    }


问:
TradingView. How to count how many time an indicator matches a certain criteria?
I have created an indicator. It's more like a statistic, it calculates the maximum difference in the last ex.100 candlesticks.

I added a line at 10. I need to know: in how many cases the value is bellow and above the line.

How can this be achieved without a loop that runs the script multiple times?

答:
Use cum():

```<code>//@version=4
study("")
r = rsi(close, 14)
rAbove = r > 50
rBelow = r <= 50
barsAbove = cum(rAbove ? 1 : 0)
barsBelow = cum(rBelow ? 1 : 0)
plot(barsAbove, "barsAbove")
plot(barsBelow, "barsBelow")
bgcolor(rAbove ? color.green : rBelow ? color.red : na)
plotchar(r, "r", "", location.top, size = size.tiny)
</code>```

Body:
Use cum():

//@version=4
study("")
r = rsi(close, 14)
rAbove = r > 50
rBelow = r <= 50
barsAbove = cum(rAbove ? 1 : 0)
barsBelow = cum(rBelow ? 1 : 0)
plot(barsAbove, "barsAbove")
plot(barsBelow, "barsBelow")
bgcolor(rAbove ? color.green : rBelow ? color.red : na)
plotchar(r, "r", "", location.top, size = size.tiny)


问:
How to reference a resource file from a Model in ASP.Net Core (3.1)?
So, I read all about the new localization system in ASP.Net Core (3.1) and successfully made use of the IStringLocalizer<MyController> and the IViewLocalizer<MyView>. I also could use the localization for the [DisplayName("Property description") in Models.

Below what I seem unable to do:
In good old .Net Framework I could do this:

```<code> public class Month
{
    public int MonthNumber { get; set; }

    public string  Name
    {
        get
        {
            switch(MonthNumber)
            {
                case 1:
                    return Properties.Resources.Jan;
                case 2:
                    return Properties.Resources.Feb;
                default:
                    return "?";
            }
        }
    }
</code>```

But how can I do this in a Model in ASP.Net Core 3.1?

答:
I solved it thus:

Just add the resource files following the structure you have chosen. All docs and tutorials suggest you take a folder named "Resources" as your base folder, so that is what you see here.
The link that is  most probable to survive over time that explains how to use resources in an ASP.Net Core project:
Microsoft docs on Localization for ASP.Net Core

Make sure that you mark all three "Month" resx files as Public:

Visual Studio will at first complain with the message:

Custom tool PublicResXFileCodeGenerator failed to produce an output for input file 'Month.en.resx' but did not log a specific error.

Simply get rid of this error by restarting Visual Studio!

Now you can use the resources as follows:

```<code>  public string Name
    {
        get
        {
            return MonthNumber switch
            {
                1 => Resources.Models.Month.Jan,
                2 => Resources.Models.Month.Feb,
                _ => "?"
            };
        }
    }
</code>```

Body:
So, I read all about the new localization system in ASP.Net Core (3.1) and successfully made use of the IStringLocalizer<MyController> and the IViewLocalizer<MyView>. I also could use the localization for the [DisplayName("Property description") in Models.

Below what I seem unable to do:
In good old .Net Framework I could do this:

 public class Month
{
    public int MonthNumber { get; set; }

    public string  Name
    {
        get
        {
            switch(MonthNumber)
            {
                case 1:
                    return Properties.Resources.Jan;
                case 2:
                    return Properties.Resources.Feb;
                default:
                    return "?";
            }
        }
    }

But how can I do this in a Model in ASP.Net Core 3.1?

Body:
I solved it thus:

Just add the resource files following the structure you have chosen. All docs and tutorials suggest you take a folder named "Resources" as your base folder, so that is what you see here.
The link that is  most probable to survive over time that explains how to use resources in an ASP.Net Core project:
Microsoft docs on Localization for ASP.Net Core

Make sure that you mark all three "Month" resx files as Public:

Visual Studio will at first complain with the message:

Custom tool PublicResXFileCodeGenerator failed to produce an output for input file 'Month.en.resx' but did not log a specific error.

Simply get rid of this error by restarting Visual Studio!

Now you can use the resources as follows:

  public string Name
    {
        get
        {
            return MonthNumber switch
            {
                1 => Resources.Models.Month.Jan,
                2 => Resources.Models.Month.Feb,
                _ => "?"
            };
        }
    }


问:
Azure IoT Edge Batching behaviour
I am noticing the following behavior using IoT Edge batching: I know that my individual message size is less than 200 bytes. I can batch these comfortably 1000 at a time and send them to IoT Hub when I am not using IoT Edge. When using IoT Edge, the maximum batch that is being sent to IoT Hub is 100 messages. I can set the environment variable "MaxUpstreamBatchSize" on EdgeHub to a value below 100 and the batch size would change accordingly, but anything above 100 is ignored and the batch size defaults to 100. When I don't enter a value for the "MaxUpstreamBatchSize" I get batch size of 10. So is 100 the maximum batch size that we can get from IoT Edge?
Thanks</p>

答:
Did a quick search on iotedge source code and noticed AsyncEndpointExecutor.cs stating: "This block emits a batch when the batch size is reached or the batch timer times out."

Therefore I believe you are being hit by that time-out and therefore your batches are smaller than defined on environment variable "MaxUpstreamBatchSize".

You can debug your code and double check if that's what is happening. Then open a new issue under iot edge repo for a feature request if you want to have an environment variable to disable the timer or make it larger.

Title: Azure IoT Edge Batching behaviour


问:
Error while importing DASK: module 'dask.array' has no attribute 'blockwise'
I am trying to use DASK for fast computing as logistic regression aborted after 17 hours on my system.
My data set is about 1 million rows.

I first ran these commands:

```<code>import dask.array as da
import dask.dataframe as dd
from dask.distributed import Client
client = Client()
from dask.distributed import Client
client = Client()
</code>```

The above commands ran but through a warning:

C:\ProgramData\Anaconda3\lib\site-packages\distributed\bokeh\core.py:57: UserWarning:
Port 8787 is already in use.
Perhaps you already have a cluster running?
Hosting the diagnostics dashboard on a random port instead.
  warnings.warn('\n' + msg)

Then I ran these commands:

```<code>import dask_ml.joblib
from sklearn.externals import joblib
</code>```

Error: AttributeError: module 'dask.array' has no attribute 'blockwise'

Can anyone help me with how to resolve this?

答:
You should not be setting up two local clusters, which is what calling Client() twice will do for you - that is why you see the warning and a port being unavailable.

Error: AttributeError: module 'dask.array' has no attribute 'blockwise'

I can assure you that the module is indeed part of dask, so this suggests that maybe you do not have your environment set up correctly. Without further details on how you installed things and what versions you have installed, it is hard to say more. have you run client.get_versions()?

Body:
I am trying to use DASK for fast computing as logistic regression aborted after 17 hours on my system.
My data set is about 1 million rows.

I first ran these commands:

import dask.array as da
import dask.dataframe as dd
from dask.distributed import Client
client = Client()
from dask.distributed import Client
client = Client()

The above commands ran but through a warning:

C:\ProgramData\Anaconda3\lib\site-packages\distributed\bokeh\core.py:57: UserWarning:
Port 8787 is already in use.
Perhaps you already have a cluster running?
Hosting the diagnostics dashboard on a random port instead.
  warnings.warn('\n' + msg)

Then I ran these commands:

import dask_ml.joblib
from sklearn.externals import joblib

Error: AttributeError: module 'dask.array' has no attribute 'blockwise'

Can anyone help me with how to resolve this?


问:
unable to copy python script dependencies in DockerFile
I'm working on a project in Windows 10 where I have to create a docker image to run a python app using a DockerFile . I have to import pip , python  and the libraries time and request for my app to run . However I get an error when building the Docker image when the script dependencies time and request have to be imported .
My error :

```<code>Could not find a version that satisfies the requirement time (from versions: )
No matching distribution found for time
You are using pip version 8.1.1, however version 20.1.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
</code>```

My DockerFile :

```<code> FROM ubuntu:16.04
 MAINTAINER name <vskentos1@gmail.com>
 RUN apt-get update
 RUN apt-get install -y python3 python3-pip
 RUN pip3 install time requests
 RUN mkdir /script  //create new directory
 COPY ex2.py /script  //add python script in new directory
 ENTRYPOINT ["python" , "/script/ex2.py"]
</code>```

What I have tried :
CMD :

```<code>pip install --pip upgrade
</code>```

And I get that pip has been installed to the latest version :

```<code> C:\Windows\system32>pip install --upgrade pip
 Requirement already up-to-date: pip in c:\users\vasilis\anaconda3\envs\environment\lib\site-
 packages (20.1.1)
</code>```

However my image gets the same error when the time library is imported .
I would appreciate your help with guiding me through this task .
Thank you in advance.

答: It seems that the module was already installed in the python version . Deleting it's installation made my program run</p>

Body:
I'm working on a project in Windows 10 where I have to create a docker image to run a python app using a DockerFile . I have to import pip , python  and the libraries time and request for my app to run . However I get an error when building the Docker image when the script dependencies time and request have to be imported .
My error :

Could not find a version that satisfies the requirement time (from versions: )
No matching distribution found for time
You are using pip version 8.1.1, however version 20.1.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

My DockerFile :

 FROM ubuntu:16.04
 MAINTAINER name <vskentos1@gmail.com>
 RUN apt-get update
 RUN apt-get install -y python3 python3-pip
 RUN pip3 install time requests
 RUN mkdir /script  //create new directory
 COPY ex2.py /script  //add python script in new directory
 ENTRYPOINT ["python" , "/script/ex2.py"]

What I have tried :
CMD :

pip install --pip upgrade

And I get that pip has been installed to the latest version :

 C:\Windows\system32>pip install --upgrade pip
 Requirement already up-to-date: pip in c:\users\vasilis\anaconda3\envs\environment\lib\site-
 packages (20.1.1)

However my image gets the same error when the time library is imported .
I would appreciate your help with guiding me through this task .
Thank you in advance.


问:
how to convert pc serial number to string
First of all I'd like to know if I can use these two instructions

```<code>gwmi win32_bios | select serialnumber

gwmi win32_Computersystemproduct | select identifyingnumber
</code>```

indifferently.

The second question is why if I write

```<code>$sn = gwmi win32_bios | select serialnumber | out-string
</code>```

$sn.gettype() returns me system.object

and

$sn.length returns me 561 even though my serial number is made of 22 chars. Thanks.

答:
Or you can just do this:</p>

```<code>$sn = (gwmi win32_bios).serialnumber
</code>```

Body:
First of all I'd like to know if I can use these two instructions

gwmi win32_bios | select serialnumber

gwmi win32_Computersystemproduct | select identifyingnumber

indifferently.

The second question is why if I write

$sn = gwmi win32_bios | select serialnumber | out-string

$sn.gettype() returns me system.object

and

$sn.length returns me 561 even though my serial number is made of 22 chars. Thanks.

Body:
Or you can just do this:

$sn = (gwmi win32_bios).serialnumber


问:
How to take a photo in Android, using full image size(not thumbnail) and compress the image to bytes?
I dont know if im doing something wrong maybe im not using the image at all or im compressing the image in the wrong way because when im tring to send it to a server it responds me saying that the size is over 10 MB when my phone takes pictures jpg around 7-9 MB (In the Edit.java I have a comment that I before was using the thumbnail but needed to change it cause the thumbnail has a bad quality when im trying to see it in a Desktop)

Here is my code:

AndroidManifest.xml

```<code>    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <uses-feature android:name="android.hardware.camera"></uses-feature>

<provider
            android:authorities="cam.com.example.fileprovider"
            android:name="android.support.v4.content.FileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_path"/>
        </provider>
</code>```

file_path.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">

    <external-path
        name="external"
        path="/"/>
    <external-files-path
        name="external_files"
        path="/"/>
    <cache-path
        name="cache"
        path="/"/>
    <external-cache-path
        name="external_cache"
        path="/"/>
    <files-path
        name="files"
        path="/"/>

</paths>
</code>```

Edit.java

```<code>btn_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    REQUEST_IMAGE_CAPTURE = 1;
                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    if (cameraIntent.resolveActivity(getPackageManager()) != null) {

                        File imageFile = null;
                        try{
                            imageFile=getImageFile();
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                        if(imageFile!=null){
                            Uri imageUri = FileProvider.getUriForFile(Edit.this,"cam.com.example.fileprovider",imageFile);
                            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                            startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);

                        }

                    }
                } catch (Exception e) {
                        Toasty.warning(getApplicationContext(), IC, Toast.LENGTH_SHORT, true).show();

                }
            }

        });

public File getImageFile() throws IOException{
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageName = "jpg_"+timeStamp+"_";
        File storageDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

        File imageFile = File.createTempFile(imageName,".jpg",storageDir);
        currentImagePath = imageFile.getAbsolutePath();
        return imageFile;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            if (imagenString == null) {

                File imgFile = new File(currentImagePath);
                String path = imgFile.getAbsolutePath();
                Bitmap mybitmap = BitmapFactory.decodeFile(path);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                mybitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                byte[] byteArray = byteArrayOutputStream.toByteArray();
                imagenString = Base64.encodeToString(byteArray, Base64.DEFAULT);

/* **Before I was doing this, but the thumbnail has such a bad quality so needed to change it**

                Bundle extras = data.getExtras();
                Bitmap imageBitmap = (Bitmap) extras.get("data");
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                byte[] byteArray = byteArrayOutputStream.toByteArray();
                imagenString = Base64.encodeToString(byteArray, Base64.DEFAULT);*/
            }
        }
    }
</code>```

答:
It is because you're converting your image to Base64-encoding string which makes the size of the data bigger.

In the following code you're using a value of 100 for the compression, 100 is least compression and high quality.

```<code>mybitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
</code>```

You can try to compress more your image, but it reduces the quality a bit:

```<code>mybitmap.compress(Bitmap.CompressFormat.PNG, 70, byteArrayOutputStream);
</code>```

Body:
I dont know if im doing something wrong maybe im not using the image at all or im compressing the image in the wrong way because when im tring to send it to a server it responds me saying that the size is over 10 MB when my phone takes pictures jpg around 7-9 MB (In the Edit.java I have a comment that I before was using the thumbnail but needed to change it cause the thumbnail has a bad quality when im trying to see it in a Desktop)

Here is my code:

AndroidManifest.xml

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <uses-feature android:name="android.hardware.camera"></uses-feature>

<provider
            android:authorities="cam.com.example.fileprovider"
            android:name="android.support.v4.content.FileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_path"/>
        </provider>

file_path.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">

    <external-path
        name="external"
        path="/"/>
    <external-files-path
        name="external_files"
        path="/"/>
    <cache-path
        name="cache"
        path="/"/>
    <external-cache-path
        name="external_cache"
        path="/"/>
    <files-path
        name="files"
        path="/"/>

</paths>

Edit.java

btn_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    REQUEST_IMAGE_CAPTURE = 1;
                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    if (cameraIntent.resolveActivity(getPackageManager()) != null) {

                        File imageFile = null;
                        try{
                            imageFile=getImageFile();
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                        if(imageFile!=null){
                            Uri imageUri = FileProvider.getUriForFile(Edit.this,"cam.com.example.fileprovider",imageFile);
                            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                            startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);

                        }

                    }
                } catch (Exception e) {
                        Toasty.warning(getApplicationContext(), IC, Toast.LENGTH_SHORT, true).show();

                }
            }

        });

public File getImageFile() throws IOException{
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageName = "jpg_"+timeStamp+"_";
        File storageDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

        File imageFile = File.createTempFile(imageName,".jpg",storageDir);
        currentImagePath = imageFile.getAbsolutePath();
        return imageFile;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            if (imagenString == null) {

                File imgFile = new File(currentImagePath);
                String path = imgFile.getAbsolutePath();
                Bitmap mybitmap = BitmapFactory.decodeFile(path);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                mybitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                byte[] byteArray = byteArrayOutputStream.toByteArray();
                imagenString = Base64.encodeToString(byteArray, Base64.DEFAULT);

/* **Before I was doing this, but the thumbnail has such a bad quality so needed to change it**

                Bundle extras = data.getExtras();
                Bitmap imageBitmap = (Bitmap) extras.get("data");
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                byte[] byteArray = byteArrayOutputStream.toByteArray();
                imagenString = Base64.encodeToString(byteArray, Base64.DEFAULT);*/
            }
        }
    }

Body:
It is because you're converting your image to Base64-encoding string which makes the size of the data bigger.

In the following code you're using a value of 100 for the compression, 100 is least compression and high quality.

mybitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);

You can try to compress more your image, but it reduces the quality a bit:

mybitmap.compress(Bitmap.CompressFormat.PNG, 70, byteArrayOutputStream);


问:
Delete part of string between { and | in JavaScript
Currently I am getting strings that look like this:

I like {{Pizza|Pasta}} for breakfast.

I want to manipulate strings in JS so that they only contain the part after the '|' so that the sentence would be

I like Pasta for breakfast.

So far this piece of code has brought me a fair end.

```<code>str.replace(/\{\{.*?\|.*?\}\}/g, "");
</code>```

But if I have a string like:

I eat {{bread}} and {{cereal|yoghurt}} for breakfast.

The results is:

I eat yoghurt for breakfast.

But I want:

I eat bread and yoghurt for breakfast.

So far I have tried this with regex. But it doesn't seem to replace anything.

```<code>str.replace(/\{\{.*((?!]).).*?\|(.*?)\}\}/g, "");
</code>```

答:
This is the perfect use case for a regular expression. You could use one to find all occurances of {{...|...}} and replace them with the part between | and }}

let string = "I like {{Pizza|Pasta}} for breakfast and {{Pasta|Pizza}} for lunch."

console.log(string.replace(/\{\{.*?\|(.*?)\}\}/g, "$1"));```
</div>
</div>
</p>

<p>And there they are, multiple placeholders :D</p>

<blockquote>
  <p>thanks for the help but I unfortunately have another problem. If I have the string "I eat {{bread}} and {{yoghurt|cereal}} for breakfast" it will results in "I eat cereal for breakfast, but I don't want the bread part to disappear.</p>
</blockquote>

<p>It does that, because here you have changed the pattern for the placeholder. From exactly <code>{{...|...}}</code> <em>(what the regex above covers)</em> to a <code>|</code>-sperated list of entries inside of the <code>{{...}}</code>.</p>

<p>There are basically two ways to go about this. </p>

<p>Change the regex to reflect that that list:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let string = "I eat {{bread}} and {{yoghurt|cereal}} for breakfast"

console.log(string.replace(/{{(?:.*?\|)*?([^|]*?)}}/g, "$1"));</code>```

Or the we go a bit simpler with the regex and let a function deal with its content:

let string = "I eat {{bread}} and {{yoghurt|cereal}} for breakfast"

console.log(string.replace(
  // the placeholder is simply `{{....}}`
  /{{(.*?)}}/g,
  // the function takes the content between `{{` and `}}`
  // splits it by `|` and returns the last item
  (match, content) => content.split("|").pop()
));```

Body:
Currently I am getting strings that look like this:

I like {{Pizza|Pasta}} for breakfast.

I want to manipulate strings in JS so that they only contain the part after the '|' so that the sentence would be

I like Pasta for breakfast.

So far this piece of code has brought me a fair end.

str.replace(/\{\{.*?\|.*?\}\}/g, "");

But if I have a string like:

I eat {{bread}} and {{cereal|yoghurt}} for breakfast.

The results is:

I eat yoghurt for breakfast.

But I want:

I eat bread and yoghurt for breakfast.

So far I have tried this with regex. But it doesn't seem to replace anything.

str.replace(/\{\{.*((?!]).).*?\|(.*?)\}\}/g, "");

Body:
This is the perfect use case for a regular expression. You could use one to find all occurances of {{...|...}} and replace them with the part between | and }}

let string = "I like {{Pizza|Pasta}} for breakfast and {{Pasta|Pizza}} for lunch."

console.log(string.replace(/\{\{.*?\|(.*?)\}\}/g, "$1"));

And there they are, multiple placeholders :D

thanks for the help but I unfortunately have another problem. If I have the string "I eat {{bread}} and {{yoghurt|cereal}} for breakfast" it will results in "I eat cereal for breakfast, but I don't want the bread part to disappear.

It does that, because here you have changed the pattern for the placeholder. From exactly {{...|...}} (what the regex above covers) to a |-sperated list of entries inside of the {{...}}.

There are basically two ways to go about this.

Change the regex to reflect that that list:

let string = "I eat {{bread}} and {{yoghurt|cereal}} for breakfast"

console.log(string.replace(/{{(?:.*?\|)*?([^|]*?)}}/g, "$1"));

Or the we go a bit simpler with the regex and let a function deal with its content:

let string = "I eat {{bread}} and {{yoghurt|cereal}} for breakfast"

console.log(string.replace(
  // the placeholder is simply `{{....}}`
  /{{(.*?)}}/g,
  // the function takes the content between `{{` and `}}`
  // splits it by `|` and returns the last item
  (match, content) => content.split("|").pop()
));


问:
Convert a list of string into a comma separated string without duplications
I have a list of strings in Java. I would like to to insert it into a string with commas, something like:

```<code>Input: [option1,option2,option3,option1,option4]
Output: option1,option2,option3,option4
</code>```

I saw this topic and I really liked this one:

```<code>        StringBuilder result = new StringBuilder();
        String delimiter= "";
        for (String i : list) {
            result.append(delimiter).append(i);
            delimiter = ",";
        }
        return result.toString();
</code>```

But what would be the best way to add support for unique only items? How can I return a string without any duplicates? I could remove duplication from list first but it feels like there is a better solution here.

答:
Extra requirements from comments:

Limited to Java 7

Support unique flag

Handle case-sensitive

Optional: Alphabetical sort may be allowed

Sorted

If sorting the values is ok, handling case-sensitive is easiest done using a TreeSet with a case-insensitive Comparator, like the String.CASE_INSENSITIVE_ORDER, or by using a Collator for full language support.

static String toString(List<String> list, boolean unique) {
    Collection<String> dataToProcess = list;
    if (unique) {
        dataToProcess = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        dataToProcess.addAll(list);
    }

    StringBuilder result = new StringBuilder();
    String delimiter= "";
    for (String s : dataToProcess) {
        result.append(delimiter).append(s);
        delimiter = ",";
    }
    return result.toString();
}
```
<p><em>Test</em></p>
<pre class="lang-java prettyprint-override"><code>List<String> list = Arrays.asList("option1", "option3", "OPTION1", "OPTION2", "option4", "option2");
System.out.println(toString(list, false));
System.out.println(toString(list, true));
</code>```

Output

option1,option3,OPTION1,OPTION2,option4,option2
option1,OPTION2,option3,option4
```
<p>Notice how the "unique" result is sorted, but the non-unique result is not.</p>
<p><em><strong>Using Collator</strong></em></p>
<p>For better language support, use a <code>Collator</code>:</p>
<pre class="lang-java prettyprint-override"><code>    if (unique) {
        Collator collator = Collator.getInstance(/*Locale.GERMANY*/);
        collator.setStrength(Collator.SECONDARY);
        dataToProcess = new TreeSet<>(collator);
        dataToProcess.addAll(list);
    }
</code>```

Unsorted

To do it without sorting the values, we'll keep using the TreeSet but build a new list.

    if (unique) {
        Collator collator = Collator.getInstance(/*Locale.GERMANY*/);
        collator.setStrength(Collator.SECONDARY);
        Set<String> set = new TreeSet<>(collator);
        dataToProcess = new ArrayList<>();
        for (String s : list)
            if (set.add(s))
                dataToProcess.add(s);
    }
```
<p><em>Output</em></p>
<pre class="lang-none prettyprint-override"><code>option1,option3,OPTION1,OPTION2,option4,option2
option1,option3,OPTION2,option4
</code>```

Body:
I have a list of strings in Java. I would like to to insert it into a string with commas, something like:

Input: [option1,option2,option3,option1,option4]
Output: option1,option2,option3,option4

I saw this topic and I really liked this one:

        StringBuilder result = new StringBuilder();
        String delimiter= "";
        for (String i : list) {
            result.append(delimiter).append(i);
            delimiter = ",";
        }
        return result.toString();

But what would be the best way to add support for unique only items? How can I return a string without any duplicates? I could remove duplication from list first but it feels like there is a better solution here.

Body:
Extra requirements from comments:

Limited to Java 7

Support unique flag

Handle case-sensitive

Optional: Alphabetical sort may be allowed

Sorted

If sorting the values is ok, handling case-sensitive is easiest done using a TreeSet with a case-insensitive Comparator, like the String.CASE_INSENSITIVE_ORDER, or by using a Collator for full language support.

static String toString(List<String> list, boolean unique) {
    Collection<String> dataToProcess = list;
    if (unique) {
        dataToProcess = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        dataToProcess.addAll(list);
    }

    StringBuilder result = new StringBuilder();
    String delimiter= "";
    for (String s : dataToProcess) {
        result.append(delimiter).append(s);
        delimiter = ",";
    }
    return result.toString();
}

Test

List<String> list = Arrays.asList("option1", "option3", "OPTION1", "OPTION2", "option4", "option2");
System.out.println(toString(list, false));
System.out.println(toString(list, true));

Output

option1,option3,OPTION1,OPTION2,option4,option2
option1,OPTION2,option3,option4

Notice how the "unique" result is sorted, but the non-unique result is not.

Using Collator

For better language support, use a Collator:

    if (unique) {
        Collator collator = Collator.getInstance(/*Locale.GERMANY*/);
        collator.setStrength(Collator.SECONDARY);
        dataToProcess = new TreeSet<>(collator);
        dataToProcess.addAll(list);
    }

Unsorted

To do it without sorting the values, we'll keep using the TreeSet but build a new list.

    if (unique) {
        Collator collator = Collator.getInstance(/*Locale.GERMANY*/);
        collator.setStrength(Collator.SECONDARY);
        Set<String> set = new TreeSet<>(collator);
        dataToProcess = new ArrayList<>();
        for (String s : list)
            if (set.add(s))
                dataToProcess.add(s);
    }

Output

option1,option3,OPTION1,OPTION2,option4,option2
option1,option3,OPTION2,option4


问:
How do I connect my consent screen to my google data studio connector?
I'm building a connector for google data studio.
When adding a connecctor you're asked to first authorize it via google and are shown a consent screen. I've setup my consent screen in the oath2 console  (https://console.developers.google.com).
Though I'm not sure how to let google data studio use my consent screen I've created in the console.

Currently it shows like this:

Similar to what'd I'd like

Anyone had experience with this? Maybe its something set in the manifest file?

答:
To configure the OAuth consent screen for your Data Studio Community Connector:

Attach your connector Apps Script project to a Standard GCP Project.

Configure the OAuth consent screen for your GCP project.


问:
import input_data MNIST tensorflow not working
TensorFlow MNIST example not running with fully_connected_feed.py

I checked this out and realized that input_data was not built-in.  So I downloaded the whole folder from here. How can I start the tutorial:

```<code>import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-6-a5af65173c89> in <module>()
----> 1 import input_data
      2 mnist = tf.input_data.read_data_sets("MNIST_data/", one_hot=True)

ImportError: No module named input_data
</code>```

I'm using iPython (Jupyter) so do I need to change my working directory to this folder I downloaded? or can I add this to my tensorflow directory? If so, where do I add the files? I installed tensorflow with pip (on my OSX) and the current location is ~/anaconda/lib/python2.7/site-packages/tensorflow/__init__.py

Are these files meant to be accessed directly through tensorflow like sklearn datasets? or am I just supposed to cd into the directory and work from there? The example is not clear.

EDIT:

This post is very out-dated

答:
If you're using Tensorflow 2.0 or higher, you need to install tensorflow_datasets first:

```<code>pip install tensorflow_datasets
</code>```

or if you're using an Anaconda distribution:

```<code>conda install tensorflow_datasets
</code>```

from the command line.

If you're using a Jupyter Notebook you will need to install and enable ipywidgets. According to the docs (https://ipywidgets.readthedocs.io/en/stable/user_install.html) using pip:

```<code>pip install ipywidgets
jupyter nbextension enable --py widgetsnbextension
</code>```

If you're using an Anaconda distribution, install ipywidgets from the command line like such:

```<code>conda install -c conda-forge ipywidgets
</code>```

With the Anaconda distribution there is no need to enable the extension, conda handles this for you.

Then import into your code:

```<code>import tensorflow_datasets as tfds
mnist = tfds.load(name='mnist')
</code>```

You should be able to use it without error if you follow these instructions.

Body:
TensorFlow MNIST example not running with fully_connected_feed.py

I checked this out and realized that input_data was not built-in.  So I downloaded the whole folder from here. How can I start the tutorial:

import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-6-a5af65173c89> in <module>()
----> 1 import input_data
      2 mnist = tf.input_data.read_data_sets("MNIST_data/", one_hot=True)

ImportError: No module named input_data

I'm using iPython (Jupyter) so do I need to change my working directory to this folder I downloaded? or can I add this to my tensorflow directory? If so, where do I add the files? I installed tensorflow with pip (on my OSX) and the current location is ~/anaconda/lib/python2.7/site-packages/tensorflow/__init__.py

Are these files meant to be accessed directly through tensorflow like sklearn datasets? or am I just supposed to cd into the directory and work from there? The example is not clear.

EDIT:

This post is very out-dated

Body:
If you're using Tensorflow 2.0 or higher, you need to install tensorflow_datasets first:

pip install tensorflow_datasets

or if you're using an Anaconda distribution:

conda install tensorflow_datasets

from the command line.

If you're using a Jupyter Notebook you will need to install and enable ipywidgets. According to the docs (https://ipywidgets.readthedocs.io/en/stable/user_install.html) using pip:

pip install ipywidgets
jupyter nbextension enable --py widgetsnbextension

If you're using an Anaconda distribution, install ipywidgets from the command line like such:

conda install -c conda-forge ipywidgets

With the Anaconda distribution there is no need to enable the extension, conda handles this for you.

Then import into your code:

import tensorflow_datasets as tfds
mnist = tfds.load(name='mnist')

You should be able to use it without error if you follow these instructions.


问:
Android Studio Javadoc won't generate because "Selected scope contain no Java classes"
I am trying to generate the JavaDoc for the Activity class source code in Android Studio 3.6.3.  The file is open in the editor, and I use "Tools | Generate JavaDoc".

When I click OK, it fails with the message "Error running 'Javadoc': Selected scope contain no Java classes".  I also tried the "Custom Scope" option with "Current File" choice, but same results.

Can someone help why can I not generate the JavaDoc for this file?

答:
Thanks for the idea.  It was someone else's code, so I looked at another project of mine where the build.gradle file for the module has:

```<code>    dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.annotation:annotation:1.1.0'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
</code>```

Then I followed the declaration chain in my code for an Activity up to the Activity superclass -- and it goes to the same source file.  I guess my SDK has one source file regardless of the library used.  Anyway, same problem, it won't print the JavaDoc.  I don't understand why it won't print that source file, since it exists.

Body:
Thanks for the idea.  It was someone else's code, so I looked at another project of mine where the build.gradle file for the module has:

    dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.annotation:annotation:1.1.0'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

Then I followed the declaration chain in my code for an Activity up to the Activity superclass -- and it goes to the same source file.  I guess my SDK has one source file regardless of the library used.  Anyway, same problem, it won't print the JavaDoc.  I don't understand why it won't print that source file, since it exists.