问:
WebRTC: onicecandidate function not been called, hence remote video is not showing
I am trying to create web RTC peer connection on react native. I am using the react-native-webrtc module. When using two emulators and passing the same room id the video connection is not been created. While debugging I found the onIceCandidate funciton is not been called. I am using socket.io to create the room. Please help me with this.

Git: https://github.com/developerajendra/react-native-webrtc-demo

```<code>import React, {useState, useEffect} from 'react';
import {View, SafeAreaView, Button, StyleSheet, Text} from 'react-native';
import {RTCPeerConnection, RTCView, mediaDevices} from 'react-native-webrtc';
import io from "socket.io-client";

export default function WEBRtc({roomNumber}) {
  const [localStream, setLocalStream] = useState();
  const [remoteStream, setRemoteStream] = useState();

  let isCaller, localST, peerConnection;
  const socket = io("http://192.168.0.102:3000", {transports: ['websocket']});

  const constraints = {
    audio: true,
    video:false
  };

/**
 * Getting ready for local stream
 */
  const startLocalStream = () => {
      socket.emit('joinTheRoom', roomNumber);
  };

  socket.on('roomCreated', room=>{
    console.log('room created');

    mediaDevices.getUserMedia(constraints)
      .then(stream=>{
        setLocalStream(stream);
        localST = stream;
        isCaller = true;
      })
  });

  socket.on('roomJoined', room=>{
    console.log('room joined');
    mediaDevices.getUserMedia(constraints)
      .then(stream=>{
        setLocalStream(stream);
        socket.emit('ready', roomNumber)
      });
  });

  const configuration = {iceServers: [
    {'urls':'stun:stun.services.mozilla.com'},
    {'urls':'stun:stun.l.google.com:19302'}
  ]};

  // const localPC = new RTCPeerConnection(configuration);
  // const remotePC = new RTCPeerConnection(configuration);

  // const peerConnection = new RTCPeerConnection(configuration);

    socket.on('ready', room=>{
      if(isCaller){
        console.log('ready');
        peerConnection = new RTCPeerConnection(configuration);
        peerConnection.onicecandidate = onIceCandidate;
        peerConnection.onaddstream = onAddStream;
        peerConnection.createOffer()
        .then(offer=>{
          return peerConnection.setLocalDescription(offer)
          .then(()=>{
            console.log('emit offer');
              socket.emit('offer',{
                type:'offer',
                sdp:offer,
                room: roomNumber
              });
            })
          })
      }
    });

    socket.on("offer",e=>{

      if(!isCaller){
        peerConnection = new RTCPeerConnection(configuration);
        console.log('offer');
        peerConnection.onicecandidate = onIceCandidate;
        peerConnection.onaddstream = onAddStream;

        console.log('about to create answer', e);

        //accept offer from here(ready)
        peerConnection.setRemoteDescription(e)
        .then(()=>{
          return peerConnection.createAnswer()
          .then(answer=>{
            return peerConnection.setLocalDescription(answer)
            .then(()=>{
              console.log('emit answer');
                socket.emit('answer',{
                  type:'answer',
                  sdp: answer,
                  room: roomNumber
              });
            })
          })
        });
      }

    });

    function onAddStream(e){
      console.log('remote stream', e);
      if (e.stream && remoteStream !== e.stream) {
        console.log('remote stream', e.stream);

        setRemoteStream(e.stream);
      }
  };

    function onIceCandidate(event){
      console.log('ice candidate');

      if(event.candidate){
          console.log('sending ice candidate', event.candidate);

          socket.emit('candidate',{
              type: 'candidate',
              label: event.candidate.sdpMLineIndex,
              id: event.candidate.sdpMid,
              candidate: event.candidate.candidate,
              room: roomNumber
          });
      }
  }

    socket.on('candidate', e=>{
      console.log('candidate', isCaller);
      peerConnection.addIceCandidate(e);
      peerConnection.addStream(localStream);
    });

    socket.on('answer', e=>{
      console.log('answer');
      peerConnection.setRemoteDescription(e);
    });

  return (
    <SafeAreaView style={styles.container}>
    <View style={styles.streamContainer}>
      <View style={styles.streamWrapper}>
          <View style={styles.localStream}>
            {localStream && <RTCView style={styles.rtc} streamURL={localStream.toURL()} />}
            {!localStream && <Button title="Tap to start" onPress={startLocalStream} />}
          </View>
          <View style={styles.rtcview}>
            {remoteStream && <RTCView style={styles.rtc} streamURL={remoteStream.toURL()} />}
          </View>
        </View>
        {/* {!!remoteStream ? <Button style={styles.toggleButtons} title="Click to stop call" onPress={closeStreams} disabled={!remoteStream} /> : localStream && <Button title="Click to start call" onPress={startCall}  />} */}
    </View>
</SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#313131',
    justifyContent: 'space-between',
    alignItems: 'center',
    height: '100%',
    width:'100%'
  },
  streamContainer:{
    backgroundColor: 'grey',
    // justifyContent: 'space-around',
    alignItems: 'center',
    height: '50%',
    width: '100%',
    flexDirection:'column'
  },
  streamWrapper:{
    backgroundColor: 'grey',
    justifyContent: 'space-around',
    alignItems: 'center',
    height: '100%',
    width: '100%',
    flexDirection:'row'
  },
  roomTitle:{
    fontSize:20,
    paddingTop:20
  },
  rtcview: {
    width: '45%',
    height: '60%',
    borderColor:'#ccc',
    borderWidth:3,

  },
  rtc: {
    width: '100%',
    height: '100%',
  },
  localStream:{
    width: '45%',
    height: '60%',
    borderColor:'#ccc',
    borderWidth:3,
    display:'flex',
    alignItems:'center',
    flexDirection:'row',
    justifyContent:'space-around',

  }
});
</code>```

答: It may be a good idea to use simple-peer as it simplifies the webrtc script. It's an npm packages so you can directly implement it in react. Here an example project for multi-user calling PROJECT DEMO</p>

Body:
I am trying to create web RTC peer connection on react native. I am using the react-native-webrtc module. When using two emulators and passing the same room id the video connection is not been created. While debugging I found the onIceCandidate funciton is not been called. I am using socket.io to create the room. Please help me with this.

Git: https://github.com/developerajendra/react-native-webrtc-demo

import React, {useState, useEffect} from 'react';
import {View, SafeAreaView, Button, StyleSheet, Text} from 'react-native';
import {RTCPeerConnection, RTCView, mediaDevices} from 'react-native-webrtc';
import io from "socket.io-client";

export default function WEBRtc({roomNumber}) {
  const [localStream, setLocalStream] = useState();
  const [remoteStream, setRemoteStream] = useState();

  let isCaller, localST, peerConnection;
  const socket = io("http://192.168.0.102:3000", {transports: ['websocket']});

  const constraints = {
    audio: true,
    video:false
  };

/**
 * Getting ready for local stream
 */
  const startLocalStream = () => {
      socket.emit('joinTheRoom', roomNumber);
  };

  socket.on('roomCreated', room=>{
    console.log('room created');

    mediaDevices.getUserMedia(constraints)
      .then(stream=>{
        setLocalStream(stream);
        localST = stream;
        isCaller = true;
      })
  });

  socket.on('roomJoined', room=>{
    console.log('room joined');
    mediaDevices.getUserMedia(constraints)
      .then(stream=>{
        setLocalStream(stream);
        socket.emit('ready', roomNumber)
      });
  });

  const configuration = {iceServers: [
    {'urls':'stun:stun.services.mozilla.com'},
    {'urls':'stun:stun.l.google.com:19302'}
  ]};

  // const localPC = new RTCPeerConnection(configuration);
  // const remotePC = new RTCPeerConnection(configuration);

  // const peerConnection = new RTCPeerConnection(configuration);

    socket.on('ready', room=>{
      if(isCaller){
        console.log('ready');
        peerConnection = new RTCPeerConnection(configuration);
        peerConnection.onicecandidate = onIceCandidate;
        peerConnection.onaddstream = onAddStream;
        peerConnection.createOffer()
        .then(offer=>{
          return peerConnection.setLocalDescription(offer)
          .then(()=>{
            console.log('emit offer');
              socket.emit('offer',{
                type:'offer',
                sdp:offer,
                room: roomNumber
              });
            })
          })
      }
    });

    socket.on("offer",e=>{

      if(!isCaller){
        peerConnection = new RTCPeerConnection(configuration);
        console.log('offer');
        peerConnection.onicecandidate = onIceCandidate;
        peerConnection.onaddstream = onAddStream;

        console.log('about to create answer', e);

        //accept offer from here(ready)
        peerConnection.setRemoteDescription(e)
        .then(()=>{
          return peerConnection.createAnswer()
          .then(answer=>{
            return peerConnection.setLocalDescription(answer)
            .then(()=>{
              console.log('emit answer');
                socket.emit('answer',{
                  type:'answer',
                  sdp: answer,
                  room: roomNumber
              });
            })
          })
        });
      }

    });

    function onAddStream(e){
      console.log('remote stream', e);
      if (e.stream && remoteStream !== e.stream) {
        console.log('remote stream', e.stream);

        setRemoteStream(e.stream);
      }
  };

    function onIceCandidate(event){
      console.log('ice candidate');

      if(event.candidate){
          console.log('sending ice candidate', event.candidate);

          socket.emit('candidate',{
              type: 'candidate',
              label: event.candidate.sdpMLineIndex,
              id: event.candidate.sdpMid,
              candidate: event.candidate.candidate,
              room: roomNumber
          });
      }
  }

    socket.on('candidate', e=>{
      console.log('candidate', isCaller);
      peerConnection.addIceCandidate(e);
      peerConnection.addStream(localStream);
    });

    socket.on('answer', e=>{
      console.log('answer');
      peerConnection.setRemoteDescription(e);
    });

  return (
    <SafeAreaView style={styles.container}>
    <View style={styles.streamContainer}>
      <View style={styles.streamWrapper}>
          <View style={styles.localStream}>
            {localStream && <RTCView style={styles.rtc} streamURL={localStream.toURL()} />}
            {!localStream && <Button title="Tap to start" onPress={startLocalStream} />}
          </View>
          <View style={styles.rtcview}>
            {remoteStream && <RTCView style={styles.rtc} streamURL={remoteStream.toURL()} />}
          </View>
        </View>
        {/* {!!remoteStream ? <Button style={styles.toggleButtons} title="Click to stop call" onPress={closeStreams} disabled={!remoteStream} /> : localStream && <Button title="Click to start call" onPress={startCall}  />} */}
    </View>
</SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#313131',
    justifyContent: 'space-between',
    alignItems: 'center',
    height: '100%',
    width:'100%'
  },
  streamContainer:{
    backgroundColor: 'grey',
    // justifyContent: 'space-around',
    alignItems: 'center',
    height: '50%',
    width: '100%',
    flexDirection:'column'
  },
  streamWrapper:{
    backgroundColor: 'grey',
    justifyContent: 'space-around',
    alignItems: 'center',
    height: '100%',
    width: '100%',
    flexDirection:'row'
  },
  roomTitle:{
    fontSize:20,
    paddingTop:20
  },
  rtcview: {
    width: '45%',
    height: '60%',
    borderColor:'#ccc',
    borderWidth:3,

  },
  rtc: {
    width: '100%',
    height: '100%',
  },
  localStream:{
    width: '45%',
    height: '60%',
    borderColor:'#ccc',
    borderWidth:3,
    display:'flex',
    alignItems:'center',
    flexDirection:'row',
    justifyContent:'space-around',

  }
});


来源: stackexchange

问:
Why Anaconda installer doesn't recommend adding its directory to PATH on Windows?
FAQ says it's because it "can interfere with other software", but I couldn't find more details on that. The proposed workaround (opening Anaconda from Windows Start menu) is just too inconvenient.

答:
The base environment includes a lot more than just the Conda binaries, specifically it has a Python installation and libraries. Leaving it on the PATH when activating other environments can lead to packages from the base env being loaded, i.e., violating the isolation that virtual environments are intended to have. Hence, in version 4.4, Conda introduced a mechanism (conda activate) to provide cleaner isolation and officially recommended against adding to PATH directly (see Release Notes).  conda activate is a shell function that gets added to a shell via some lines being added to the initialization files (e.g., .bashrc).

Since Conda version 4.6, there has been a conda init command so that users can manage this initialization for multiple shells and not just have it added at installation time (see Release Notes). Windows users, for instance, can specifically use the conda init powershell in order to use Conda in a PowerShell prompt.

ContentLicense: CC BY-SA 4.0


问:
zsh sed expanding a variable with special characters and keeping them
I'm trying to store a string in a variable, then expand that variable in a sed command.

Several of the values I'm going to put in the variable before calling the command will have parentheses (with and without slashes before the left parentheses, but never before the right), new lines and other special characters. Also, the string will have double quotes around it in the file that's being searched, and I'd like to use those to limit only to the string I'm querying.

The command needs to be able to match with those special characters in the file. Using zsh / Mac OS, although if the command was compatible with bash 4.2 that'd be a nice bonus. echoing to xargs is fine too. Also, if awk would be better for this, I have no requirement to use sed.

Something like...

```<code>sed 's/"\"$(echo -E - ${val})\""/"${key}.localized"/g' "${files}"
</code>```

Given that $val is the variable I described above, $key has no spaces (but underscores) & $files is an array of file paths (preferably compatible with spaces, but not required).

Example Input values for $val...

```<code>... "something \(customStringConvertible) here" ...

... "something (notVar) here" ...

... "something %@ here" ...

... "something @ 100% here" ...

... "something for $100.00" ...
</code>```

Example Output:

```<code>... "some_key".localized ...
</code>```

I was using the sed command to replace the examples above. The text I'm overwriting it with is pretty straight forward.

The key problem I'm having is getting the command to match with the special characters instead of expanding them and then trying to match.

Thanks in advance for any assistance.

答:
awk is better since it provides functions that work with literal strings:

```<code>$ val='something \(customStringConvertible) here' awk 'index($0,ENVIRON["val"])' file
... "something \(customStringConvertible) here" ...

$ val='something for $100.00' awk 'index($0,ENVIRON["val"])' file
... "something for $100.00" ...
</code>```

The above was run on this input file:

```<code>$ cat file
... "something \(customStringConvertible) here" ...
... "something (notVar) here" ...
... "something %@ here" ...
... "something @ 100% here" ...
... "something for $100.00" ...
</code>```

With sed you'd have to follow the instructions at Is it possible to escape regex metacharacters reliably with sed to try to fake sed out.

It's not clear what your real goal is so edit your question to provide concise, testable sample input and expected output if you need more help. Having said that, it looks like you're doing a substitution so maybe this is what you want:

```<code>$ old='"something for $100.00"' new='here & there' awk '
    s=index($0,ENVIRON["old"]) { print substr($0,1,s-1) ENVIRON["new"] substr($0,s+length(ENVIRON["old"])) }
' file
... here & there ...
</code>```

or if you prefer:

```<code>$ old='"something for $100.00"' new='here & there' awk '
    BEGIN { old=ENVIRON["old"]; new=ENVIRON["new"]; lgth=length(old) }
    s=index($0,old) { print substr($0,1,s-1) new substr($0,s+lgth) }
' file
</code>```

or:

```<code>awk '
    BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; lgth=length(old) }
    s=index($0,old) { print substr($0,1,s-1) new substr($0,s+lgth) }
' '"something for $100.00"' 'here & there' file
... here & there ...
</code>```

See How do I use shell variables in an awk script? for info on how I'm using ENVIRON[] vs ARGV[] above.

Body:
I'm trying to store a string in a variable, then expand that variable in a sed command.

Several of the values I'm going to put in the variable before calling the command will have parentheses (with and without slashes before the left parentheses, but never before the right), new lines and other special characters. Also, the string will have double quotes around it in the file that's being searched, and I'd like to use those to limit only to the string I'm querying.

The command needs to be able to match with those special characters in the file. Using zsh / Mac OS, although if the command was compatible with bash 4.2 that'd be a nice bonus. echoing to xargs is fine too. Also, if awk would be better for this, I have no requirement to use sed.

Something like...

sed 's/"\"$(echo -E - ${val})\""/"${key}.localized"/g' "${files}"

Given that $val is the variable I described above, $key has no spaces (but underscores) & $files is an array of file paths (preferably compatible with spaces, but not required).

Example Input values for $val...

... "something \(customStringConvertible) here" ...

... "something (notVar) here" ...

... "something %@ here" ...

... "something @ 100% here" ...

... "something for $100.00" ...

Example Output:

... "some_key".localized ...

I was using the sed command to replace the examples above. The text I'm overwriting it with is pretty straight forward.

The key problem I'm having is getting the command to match with the special characters instead of expanding them and then trying to match.

Thanks in advance for any assistance.

Body:
awk is better since it provides functions that work with literal strings:

$ val='something \(customStringConvertible) here' awk 'index($0,ENVIRON["val"])' file
... "something \(customStringConvertible) here" ...

$ val='something for $100.00' awk 'index($0,ENVIRON["val"])' file
... "something for $100.00" ...

The above was run on this input file:

$ cat file
... "something \(customStringConvertible) here" ...
... "something (notVar) here" ...
... "something %@ here" ...
... "something @ 100% here" ...
... "something for $100.00" ...

With sed you'd have to follow the instructions at Is it possible to escape regex metacharacters reliably with sed to try to fake sed out.

It's not clear what your real goal is so edit your question to provide concise, testable sample input and expected output if you need more help. Having said that, it looks like you're doing a substitution so maybe this is what you want:

$ old='"something for $100.00"' new='here & there' awk '
    s=index($0,ENVIRON["old"]) { print substr($0,1,s-1) ENVIRON["new"] substr($0,s+length(ENVIRON["old"])) }
' file
... here & there ...

or if you prefer:

$ old='"something for $100.00"' new='here & there' awk '
    BEGIN { old=ENVIRON["old"]; new=ENVIRON["new"]; lgth=length(old) }
    s=index($0,old) { print substr($0,1,s-1) new substr($0,s+lgth) }
' file

or:

awk '
    BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; lgth=length(old) }
    s=index($0,old) { print substr($0,1,s-1) new substr($0,s+lgth) }
' '"something for $100.00"' 'here & there' file
... here & there ...

See How do I use shell variables in an awk script? for info on how I'm using ENVIRON[] vs ARGV[] above.


问:
Julia: counting total number of elements in an array-of-arrays
Is there a single function in Julia that will give you the total number of elements in an array-of-arrays (or 'jagged array')?

Here's what I mean:

```<code>my_array_of_arrays = [ [1, 5], [6], [10, 10, 11] ]
</code>```

I'm looking for a function such that
desired_function(my_array_of_arrays) will return 6

And if not, what's the quickest way to do this in Julia?

Thanks in advance!

答:
sum(length, x) suggested by @MattB is a more elegant answer and it deserves being here so others can find it.

Testing:

```<code>julia> my_array_of_arrays = [ [1, 5], [6], [10, 10, 11] ]
3-element Array{Array{Int64,1},1}:
 [1, 5]
 [6]
 [10, 10, 11]

julia> sum(length, my_array_of_arrays)
6
</code>```

Note that the performance of both methods mapreduce(length, +, x) and sum(length, x) is identical since both do not materialize the data.

Body:
Is there a single function in Julia that will give you the total number of elements in an array-of-arrays (or 'jagged array')?

Here's what I mean:

my_array_of_arrays = [ [1, 5], [6], [10, 10, 11] ]

I'm looking for a function such that
desired_function(my_array_of_arrays) will return 6

And if not, what's the quickest way to do this in Julia?

Thanks in advance!

Body:
sum(length, x) suggested by @MattB is a more elegant answer and it deserves being here so others can find it.

Testing:

julia> my_array_of_arrays = [ [1, 5], [6], [10, 10, 11] ]
3-element Array{Array{Int64,1},1}:
 [1, 5]
 [6]
 [10, 10, 11]

julia> sum(length, my_array_of_arrays)
6

Note that the performance of both methods mapreduce(length, +, x) and sum(length, x) is identical since both do not materialize the data.


问:
How do I fix "Expression expected. ts(1109)" in VSCode?
I encountered VSCode error "Expression expected. ts(1009)" while opening one of the reactjs file. do and if were highlighted red.
But I can run the code in my local development environment and also no problem compiling. I guess this is due to VSCode Editor bug.

Other editor like Atom or Sublime Text are fine. I used ternary operation in React to solve it but things get really complicated if there are too many else if.

```<code><div className='form'>
    // Form stuffs
</div>
{
    do{
      if (hasBreakfast) {
        <span>Breakfast Included</span>
      } else if {
        <span>Breakfast Not Included</span>
        }
    }
}
</code>```

Is there any methods to solve the warning in VSCode?

答:
```<code>return (
  <Fragment>
  // JSX to render goes here...
  </Fragment>
);
</code>```

I received the same error on the last line.
I added the fragment element to force the return () to receive one parent element. You can also accomplish this by wrapping your return code is a 'div' element. The issue there however, is you will have random empty 'div' s.

The docs explain it better than I can. https://reactjs.org/docs/fragments.html

Body:
I encountered VSCode error "Expression expected. ts(1009)" while opening one of the reactjs file. do and if were highlighted red.
But I can run the code in my local development environment and also no problem compiling. I guess this is due to VSCode Editor bug.

Other editor like Atom or Sublime Text are fine. I used ternary operation in React to solve it but things get really complicated if there are too many else if.

    // Form stuffs

{
    do{
      if (hasBreakfast) {
        Breakfast Included
      } else if {
        Breakfast Not Included
        }
    }
}

Is there any methods to solve the warning in VSCode?

Body:
return (
  <Fragment>
  // JSX to render goes here...
  </Fragment>
);

I received the same error on the last line.
I added the fragment element to force the return () to receive one parent element. You can also accomplish this by wrapping your return code is a 'div' element. The issue there however, is you will have random empty 'div' s.

The docs explain it better than I can. https://reactjs.org/docs/fragments.html


问:
Obj C: Grouping strings into NSMutableDictionary
I have an NSArray that contains a bunch of strings.  Each string lists a parent and child type, such as:

```<code>Tool: Saw
Fruit: Apple
Fruit: Orange
Tree: Maple
Fruit: Banana
Tree: Oak
Tool: Hammer
Tree: Cedar
</code>```

My final structure that I need to put them into is (sorted parents and children):

```<code>Fruit:
  - Apple
  - Banana
  - Orange
Tool:
  - Hammer
  - Saw
Tree:
  - Cedar
  - Maple
  - Oak
</code>```

I would like to know how to group these under their parent type, sorting by that parent type and sorting the children. I assume the best thing to use would be an NSMutableDictionary to make them into keys and objects.

Here is what I tested so far but does not turn out how I want:

```<code>// Add to tree
if ([tree objectForKey:pathParent]) {
    NSMutableArray *temp = (NSMutableArray *)[tree objectForKey:pathParent];
    [temp addObject:name];
    [tree removeObjectForKey:pathParent];
    [tree setObject:temp forKey:pathParent];

} else {
    [tree setObject:[NSMutableArray arrayWithObject:name] forKey:pathParent];
}//end
</code>```

How would I do this?

答:
[NVM, I see you got it working already! Cool.]

Something roughly like this should work, you'll need to season and debug to taste of course. But this is the general idea...

```<code>- (NSDictionary*)categoriesAndSortedItemsFromItems:(NSArray*)source {

    //Given NSArray *source with the lines you described...

    NSMutableDictionary *categoriesAndItems = [NSMutableDictionary dictionaryWithCapacity:3];

    // Plug the items into the correct arrays by category
    for (NSString *line in source) {

        NSArray *components = [line componentsSeparatedByString:@": "];
        NSString *category = [components objectAtIndex:0]; //e.g. "tree"
        NSString *item = [components objectAtIndex:1]; //e.g. "oak"

        NSMutableArray *itemsForCategory = [self arrayInDict:categoriesAndItems forKey:category];

        [itemsForCategory addObject:item];
    }

    // Now run through and sort each array if you want...
    NSMutableDictionary *categoriesAndSortedItems = [NSMutableDictionary dictionaryWithCapacity:3];

    [categoriesAndItems enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {

        NSArray *sorted = [(NSArray*)obj sortedArrayUsingSelector:@selector(compare:)];
        [categoriesAndSortedItems setObject:sorted forKey:key];
    }];

    return categoriesAndSortedItems;

}

 - (NSMutableArray*)arrayInDict:(NSMutableDictionary*)dict forKey:(NSString*)key {

        NSMutableArray *array = [dict objectForKey:key];

        if (!array)  {

            array = [[NSMutableArray alloc] initWithCapacity:10];

            [dict setObject:array forKey:key];

            [array release];
        }

        return array;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an NSArray that contains a bunch of strings.  Each string lists a parent and child type, such as:

Tool: Saw
Fruit: Apple
Fruit: Orange
Tree: Maple
Fruit: Banana
Tree: Oak
Tool: Hammer
Tree: Cedar

My final structure that I need to put them into is (sorted parents and children):

Fruit:
  - Apple
  - Banana
  - Orange
Tool:
  - Hammer
  - Saw
Tree:
  - Cedar
  - Maple
  - Oak

I would like to know how to group these under their parent type, sorting by that parent type and sorting the children. I assume the best thing to use would be an NSMutableDictionary to make them into keys and objects.

Here is what I tested so far but does not turn out how I want:

// Add to tree
if ([tree objectForKey:pathParent]) {
    NSMutableArray *temp = (NSMutableArray *)[tree objectForKey:pathParent];
    [temp addObject:name];
    [tree removeObjectForKey:pathParent];
    [tree setObject:temp forKey:pathParent];

} else {
    [tree setObject:[NSMutableArray arrayWithObject:name] forKey:pathParent];
}//end

How would I do this?

Body:
[NVM, I see you got it working already! Cool.]

Something roughly like this should work, you'll need to season and debug to taste of course. But this is the general idea...

- (NSDictionary*)categoriesAndSortedItemsFromItems:(NSArray*)source {

    //Given NSArray *source with the lines you described...

    NSMutableDictionary *categoriesAndItems = [NSMutableDictionary dictionaryWithCapacity:3];

    // Plug the items into the correct arrays by category
    for (NSString *line in source) {

        NSArray *components = [line componentsSeparatedByString:@": "];
        NSString *category = [components objectAtIndex:0]; //e.g. "tree"
        NSString *item = [components objectAtIndex:1]; //e.g. "oak"

        NSMutableArray *itemsForCategory = [self arrayInDict:categoriesAndItems forKey:category];

        [itemsForCategory addObject:item];
    }

    // Now run through and sort each array if you want...
    NSMutableDictionary *categoriesAndSortedItems = [NSMutableDictionary dictionaryWithCapacity:3];

    [categoriesAndItems enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {

        NSArray *sorted = [(NSArray*)obj sortedArrayUsingSelector:@selector(compare:)];
        [categoriesAndSortedItems setObject:sorted forKey:key];
    }];

    return categoriesAndSortedItems;

}

 - (NSMutableArray*)arrayInDict:(NSMutableDictionary*)dict forKey:(NSString*)key {

        NSMutableArray *array = [dict objectForKey:key];

        if (!array)  {

            array = [[NSMutableArray alloc] initWithCapacity:10];

            [dict setObject:array forKey:key];

            [array release];
        }

        return array;
    }


问:
How do I change the body background with CSS depending on the screen size, and if a file exists with PHP?
I hope I can explain what I want to do OK.
My site is built in PHP with pages created from a mySQL database. In this case, I want to change the body background of the project page depending on whether there is an image in the folder that matches the ID of the page (project_id). The following code works fine in accomplishing this:

```<code> <body style="background: url(<?php

 $background = dirname(__FILE__) . "/ $myMedia images/bg/ $row[project_id].jpg";
 $background = str_replace(" ", "", $background);

 if (file_exists($background)) {
     echo "images/bg/$row[project_id].jpg";
 } else {
     echo "images/bg.jpg";
 }

?>) repeat-x;" />
</code>```

However, what I want to do is ONLY change the background of the page if the screen size is larger than 767px, otherwise I want to display a different background for the mobile phone view (bg-mob-380.jpg). I've tried the following code but it doesn't work, and I'm not sure what I'm doing wrong.

```<code> <body style="
@media only screen and (max-width: 767px) {
    background: #FFFFFF url(images/bg-mob-380.jpg) repeat-x;
}
@media only screen and (min-width: 768px) {
 background: url(<?php

 $background = dirname(__FILE__) . "/ $myMedia images/bg/ $row[project_id].jpg";
 $background = str_replace(" ", "", $background);

 if (file_exists($background)) {
     echo "images/bg/$row[project_id].jpg";
 } else {
     echo "images/bg.jpg";
 }

?>) repeat-x;
}
" />
</code>```

Any help would be appreciated. Thanks in advance :)

答:
You can organize this in a way that is a little easier to read:

```<code><?php
$background = dirname(__FILE__) . "/ $myMedia images/bg/ $row[project_id].jpg";
$background = str_replace(" ", "", $background);

if (file_exists($background)) {
    $image = "images/bg/$row[project_id].jpg";
} else {
   $image = "images/bg.jpg";
}
?>

@media only screen and (max-width: 767px) {
background: #FFFFFF url('images/bg-mob-380.jpg') no-repeat fixed center;
}
@media only screen and (min-width: 768px) {
background: url('<?php echo $image ?>') no-repeat fixed center;
}
</code>```

Repeating images are what headaches are made from.

Body:
I hope I can explain what I want to do OK.
My site is built in PHP with pages created from a mySQL database. In this case, I want to change the body background of the project page depending on whether there is an image in the folder that matches the ID of the page (project_id). The following code works fine in accomplishing this:

 <body style="background: url(<?php

 $background = dirname(__FILE__) . "/ $myMedia images/bg/ $row[project_id].jpg";
 $background = str_replace(" ", "", $background);

 if (file_exists($background)) {
     echo "images/bg/$row[project_id].jpg";
 } else {
     echo "images/bg.jpg";
 }

?>) repeat-x;" />

However, what I want to do is ONLY change the background of the page if the screen size is larger than 767px, otherwise I want to display a different background for the mobile phone view (bg-mob-380.jpg). I've tried the following code but it doesn't work, and I'm not sure what I'm doing wrong.

 <body style="
@media only screen and (max-width: 767px) {
    background: #FFFFFF url(images/bg-mob-380.jpg) repeat-x;
}
@media only screen and (min-width: 768px) {
 background: url(<?php

 $background = dirname(__FILE__) . "/ $myMedia images/bg/ $row[project_id].jpg";
 $background = str_replace(" ", "", $background);

 if (file_exists($background)) {
     echo "images/bg/$row[project_id].jpg";
 } else {
     echo "images/bg.jpg";
 }

?>) repeat-x;
}
" />

Any help would be appreciated. Thanks in advance :)

Body:
You can organize this in a way that is a little easier to read:

<?php
$background = dirname(__FILE__) . "/ $myMedia images/bg/ $row[project_id].jpg";
$background = str_replace(" ", "", $background);

if (file_exists($background)) {
    $image = "images/bg/$row[project_id].jpg";
} else {
   $image = "images/bg.jpg";
}
?>

@media only screen and (max-width: 767px) {
background: #FFFFFF url('images/bg-mob-380.jpg') no-repeat fixed center;
}
@media only screen and (min-width: 768px) {
background: url('<?php echo $image ?>') no-repeat fixed center;
}

Repeating images are what headaches are made from.


问:
Convert string with many dates to datetime
If my string consisted of just one date I'd use this:

```<code>datetime.datetime.strptime(string, '%b %d %Y').strftime('%Y-%m-%d')
</code>```

But since there are many along the string, I don't know how to proceed. How could I read the string and make the changes only where needed?

So here is my string:

```<code>s = 'Mar 27 2000*56.75*58.39*Mar 26 2000*53.10*56.13*Mar 25 2000*51.50*52.00'
</code>```

and what I expect right after:

```<code>s = '2000-03-27*56.75*58.39*2000-03-26*53.10*56.13*2000-03-25*51.50*52.00'
</code>```

答:
If all string dates are in the same format, you could use a regex for obtaining the dates in the string and then replace it, I'm thinking of something like this:</p>

```<code>import re
import datetime

def operate_on_replacement(matchObj):
    match = matchObj.group(0)
    return datetime.datetime.strptime(match, '%b %d %Y').strftime('%Y-%m-%d')

start_string = 'Mar 27 2000*56.75*58.39*Mar 26 2000*53.10*56.13*Mar 25 2000*51.50*52.00'
replaced_string = re.sub(r'\w{3}\s{1}\d{2}\s{1}\d{4}', operate_on_replacement, start_string)
</code>```

Body:
If my string consisted of just one date I'd use this:

datetime.datetime.strptime(string, '%b %d %Y').strftime('%Y-%m-%d')

But since there are many along the string, I don't know how to proceed. How could I read the string and make the changes only where needed?

So here is my string:

s = 'Mar 27 2000*56.75*58.39*Mar 26 2000*53.10*56.13*Mar 25 2000*51.50*52.00'

and what I expect right after:

s = '2000-03-27*56.75*58.39*2000-03-26*53.10*56.13*2000-03-25*51.50*52.00'

Body:
If all string dates are in the same format, you could use a regex for obtaining the dates in the string and then replace it, I'm thinking of something like this:

import re
import datetime

def operate_on_replacement(matchObj):
    match = matchObj.group(0)
    return datetime.datetime.strptime(match, '%b %d %Y').strftime('%Y-%m-%d')

start_string = 'Mar 27 2000*56.75*58.39*Mar 26 2000*53.10*56.13*Mar 25 2000*51.50*52.00'
replaced_string = re.sub(r'\w{3}\s{1}\d{2}\s{1}\d{4}', operate_on_replacement, start_string)


问:
How do I split text file without delimiter into a list of dictionaries in python3?
I have a text file that has data in the following shape:

```<code>{"id": 1, {"device_data": 123}, "created_at": "2020-04-03"}{"id": 2, {"device_data": 123}, "created_at": '2020-04-03'}{"id": 2, {"device_data": 123}, "created_at": "2020-04-03"}{"id": 2, {"device_data": 123}, "created_at": '2020-04-03'}
</code>```

There aren't any \n delimiters or , delimiters that I can use here. I'd like to parse this into a list of dictionaries in order to load the data into a dataframe.

I've tried parsing this using .split() and list comprehension doing something like this:

```<code>lst = [x + '}' for x in data.split('}') if x != '']

</code>```

But this obviously breaks for records that have nested objects.

I also tried doing this with regex but I'm struggling to figure out the appropriate way.  This is what I have so far:

```<code>re.split('(\{(.*)\})', data)
</code>```

Per the suggestions below, I also attempted making use of the json library.

```<code>with open('path/to/file', 'r') as f:
    res = json.load(f)
</code>```

However, this resulted in an error with the following message: JSONDecodeError: Extra data. I believe this is due to the fact that there are multiple valid jsons in this file.

I wanted to use the json.load() command with a for loop, but then I ran into trouble figuring out how to properly split the file contents.

Does anyone have a suggestion for how to approach this kind of problem?

答:
Your record separator is:

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

so given

```<code>txt="{'id': 1, {'device_data': 123}, 'created_at': '2020-04-03'}{'id': 2, {'device_data': 123}, 'created_at': '2020-04-03'}{'id': 2, {'device_data': 123}, 'created_at': '2020-04-03'}{'id': 2, {'device_data': 123}, 'created_at': '2020-04-03'}"
</code>```

split into records with:

```<code>records=txt.split('}{')
</code>```

The results look like:

```<code>records[0]="{'id': 1, {'device_data': 123}, 'created_at': '2020-04-03'"
records[1]="'id': 2, {'device_data': 123}, 'created_at': '2020-04-03'"
</code>```

and parse the records into dictionary's with

```<code>mydictlist = []
for record in records:
    # clean up excess brackets and tokens
    record = record.replace('{','').replace('}','').replace("'",'')
    mydict = dict((k.strip(), v.strip()) for k,v in
          (item.split(':') for item in record.split(',')))
    mydictlist.append(mydict)
</code>```

Example result looks like:

```<code>mydictlist[2] = {'id': '2', 'device_data': '123', 'created_at': '2020-04-03'}
</code>```

Body:
I have a text file that has data in the following shape:

{"id": 1, {"device_data": 123}, "created_at": "2020-04-03"}{"id": 2, {"device_data": 123}, "created_at": '2020-04-03'}{"id": 2, {"device_data": 123}, "created_at": "2020-04-03"}{"id": 2, {"device_data": 123}, "created_at": '2020-04-03'}

There aren't any \n delimiters or , delimiters that I can use here. I'd like to parse this into a list of dictionaries in order to load the data into a dataframe.

I've tried parsing this using .split() and list comprehension doing something like this:

lst = [x + '}' for x in data.split('}') if x != '']

But this obviously breaks for records that have nested objects.

I also tried doing this with regex but I'm struggling to figure out the appropriate way.  This is what I have so far:

re.split('(\{(.*)\})', data)

Per the suggestions below, I also attempted making use of the json library.

with open('path/to/file', 'r') as f:
    res = json.load(f)

However, this resulted in an error with the following message: JSONDecodeError: Extra data. I believe this is due to the fact that there are multiple valid jsons in this file.

I wanted to use the json.load() command with a for loop, but then I ran into trouble figuring out how to properly split the file contents.

Does anyone have a suggestion for how to approach this kind of problem?

Body:
Your record separator is:

}{

so given

txt="{'id': 1, {'device_data': 123}, 'created_at': '2020-04-03'}{'id': 2, {'device_data': 123}, 'created_at': '2020-04-03'}{'id': 2, {'device_data': 123}, 'created_at': '2020-04-03'}{'id': 2, {'device_data': 123}, 'created_at': '2020-04-03'}"

split into records with:

records=txt.split('}{')

The results look like:

records[0]="{'id': 1, {'device_data': 123}, 'created_at': '2020-04-03'"
records[1]="'id': 2, {'device_data': 123}, 'created_at': '2020-04-03'"

and parse the records into dictionary's with

mydictlist = []
for record in records:
    # clean up excess brackets and tokens
    record = record.replace('{','').replace('}','').replace("'",'')
    mydict = dict((k.strip(), v.strip()) for k,v in
          (item.split(':') for item in record.split(',')))
    mydictlist.append(mydict)

Example result looks like:

mydictlist[2] = {'id': '2', 'device_data': '123', 'created_at': '2020-04-03'}


问:
How to use 2 models in 1 View
I have a Booking model and I create a list of all it's elements in the BookingController. There I managed to export the list as .json, however when I want to import a file I can't manage to use my custom validation to see if it's only .json. The problem is that in my Index for Booking I have a IEnumerable model for Booking and I use a BookingsUpload model to upload the file. So how can I access this BookingsUpload model inside the Index or how could i change it ? (could I combine what i do in BookingsUpload with my Booking model ?

Booking Model:

```<code>public class Booking
{
    [Required]
    [Display(Name = "Ladestand")]
    [Range(0, 100)]
    public double chargeState { get; set; }

    [Required]
    [Display(Name = "Benötigte Fahrstrecke")]
    [Range(1, 1000)]
    public double distance { get; set; }

    [Required]
    [Display(Name = "Beginn")]
    public DateTime startTime { get; set; }

    [Required]
    [Display(Name = "Ende")]
    public DateTime endTime { get; set; }

    [Required]
    [Display(Name = "Anschlusstyp")]
    [EnumDataType(typeof(ConnectorType))]
    [JsonConverter(typeof(StringEnumConverter))]
    public ConnectorType connectorType { get; set; }
}

public class BookingList
        {
            public List<Booking> BookingListObj { get; set; }
        }
</code>```

BookingsUpload Model:

```<code>public class BookingsUpload
{
    [Required(ErrorMessage = "Please select a file.")]
    [DataType(DataType.Upload)]
    [MaxFileSize(1024 * 1024)]
    [AllowedExtensions(new string[] { ".json" })]
    public IFormFile File { get; set; }
}
</code>```

** NEW UPDATE **:
Now Controller doesn't work as intended. Cannot add elements to List (or maybe they are added just can't display it in the View not sure):
Controller:

```<code>public class BookingController : Controller
{
    private IMemoryCache _cache;
    private string bookingsKey = "bookingsList";
    public BookingController(IMemoryCache memoryCache)
    {
        _cache = memoryCache;
    }

    public IActionResult Index()
    {
        List<Booking> bookigsList;
        _cache.TryGetValue<List<Booking>>(bookingsKey, out bookigsList);
        return View(bookigsList);
    }

    /* MVVC fucking failed :(
    public IActionResult Index()
    {
        BookingList bookingsList;
        //_cache.TryGetValue(bookingsKey, out bookingList);

        bookingsList = new BookingList();
        bookingsList.BookingListObj = new List<Booking>();

        bookingsList.BookingListObj.Add(new Booking() { chargeState = 30, distance = 150, startTime = new DateTime(2020, 8, 13, 13, 45, 0), endTime = new DateTime(2020, 8, 13, 17, 0, 0) });
        _cache.Set<List<Booking>>(bookingsKey, bookingsList.BookingListObj);

        BookingViewModel bookingViewModel = new BookingViewModel()
        {
            Bookings = bookingsList.BookingListObj
        };

        return View(bookingViewModel);
    }*/

    [HttpGet]
    public IActionResult Create()
    {
        Booking booking = new Booking();
        return View("Create", booking);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create(Booking booking)
    {
        List<Booking> bookingsList;

        //BookingList bookingsList;
        /*_cache.TryGetValue(bookingsKey, out bookingsList);
        BookingViewModel bookingViewModel = new BookingViewModel()
        {
            BookingList = bookingsList
        };*/

        if (!ModelState.IsValid)
        {
            return View("Create", booking);
        }
        if (!_cache.TryGetValue(bookingsKey, out bookingsList))
        {
            bookingsList = new List<Booking>();
        }

        bookingsList.Add(booking);
        _cache.Set<List<Booking>>(bookingsKey, bookingsList);

        /*BookingViewModel bookingViewModel = new BookingViewModel()
        {
            BookingList = bookingsList
        };*/

        return RedirectToAction("Index", "Booking");
    }
</code>```

BookingViewModel:

```<code>public class BookingViewModel
{
    public Booking Booking { get; set; }
    public BookingList BookingList { get; set; }
    public IEnumerable<Booking> Bookings { get; set; }
    public BookingsUpload BookingsUpload { get; set; }

    public BookingViewModel()
    {
        Booking = new Booking();
        Bookings = new List<Booking>();
        BookingsUpload = new BookingsUpload();
    }
}
</code>```

Booking Index:

```<code>    @model WebApplication.ViewModels.BookingViewModel

@{
    ViewData["Title"] = "Index";
}

<br />
<div class="container row p-0 m-0">
    <div class="container col 6">
        <h1 class="text-info">Übersicht aller Buchungen</h1>
    </div>
    <div class="container col-3">
        <div class="m-1">
            <a asp-controller="Booking" asp-action="Create" class="btn btn-info form-control text-white">Erstelle Buchung</a>
        </div>
        <div class="d-flex flex-row">
            <div class="w-100 m-1">
                <a asp-controller="Booking" asp-action="Export" class="btn btn-info form-control text-white">Export</a>
            </div>
            <div class="w-100 m-1">
                <form asp-controller="Booking" asp-action="Import" method="post" enctype="multipart/form-data">
                    <div class="form-group">
                        <label class="custom-file-upload">
                            <input type="file" name="file" onchange="this.form.submit()" />
                            Import/validation_bc_fuck_MVC
                        </label>
                        <span asp-validation-for="BookingsUpload.File" class="text-danger"></span>
                    </div>
                </form>
                <a asp-controller="Booking" asp-action="Import" class="btn btn-info form-control text-white">Import + validation</a>
            </div>
        </div>
    </div>

    <div class="col-12">
        @if (Model.Booking != null)
        {
            <table class="table table-striped table-borderless table-hover">
                <thead class="thead-dark">

                    <tr>
                        <th>
                            @Html.DisplayNameFor(model => Model.Booking.chargeState) %
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => Model.Booking.distance) (km)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => Model.Booking.connectorType)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => Model.Booking.startTime)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => Model.Booking.endTime)
                        </th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var item in Model.Bookings)
                    {
                        <tr>
                            <td>
                                @Html.DisplayFor(modelItem => item.chargeState)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.distance)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.connectorType)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.startTime)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.endTime)
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
        }
        else
        {
            <p>Es sind keine Buchungen vorhanden</p>
        }
    </div>
</div>

<style>
    input[type="file"] {
        display: none;
    }

    .custom-file-upload {
        color: #fff !important;
        background-color: #17a2b8;
        border-color: #17a2b8;
        /*text display: inline-block;*/
        cursor: pointer;
        font-weight: 400;
        text-align: center;
        vertical-align: middle;
        user-select: none;
        border: 1px solid transparent;
        padding: 6px 12px;
        font-size: 1rem;
        line-height: 1.5;
        border-radius: .25rem;
        transition: color .15s;
        width: 100%;
        height: calc(1.5em + .75rem + 2px);
    }

    .custom-file-upload:hover {
        background-color: #138496;
        border-color: #117a8b;
    }
</style>
</code>```

So the Import label is the problem because I cant access the File from BookingsUpload to make the span asp-validation-for="File" but with the Import button I managed to go to a different View with only this code below and there the validation works because there I can use the BookingsUpload model:

```<code>    @model WebApplication.Models.BookingsUpload;

@{
    ViewData["Title"] = "Import";
}

<h1>Import</h1>

<form asp-controller="Booking" asp-action="Import" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label class="custom-file-upload">
            <input asp-for="File" type="file" name="file" onchange="this.form.submit()" />
            Import
        </label>
        <span asp-validation-for="File" class="text-danger"></span>
    </div>
</form>
</code>```

答:
So I finally realized I had a HUGE logical issue. I don't have to use 2 models in the same View. What I did was use a partial to copy the Import button. Like this in the index:

```<code><form asp-controller="Booking" asp-action="Import" method="post" enctype="multipart/form-data">
                <div class="form-group">
                    @{
                        await Html.RenderPartialAsync("_Import", new WebApplication.Models.BookingsUpload());
                    }
                </div>
            </form>
</code>```

And this is the partial for the Import button:

```<code>    @model WebApplication.Models.BookingsUpload;

<form asp-controller="Booking" asp-action="Import" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label class="custom-file-upload">
            <input asp-for="File" type="file" name="file" onchange="this.form.submit()" />
            Import
        </label>
        <span asp-validation-for="File" class="text-danger"></span>
    </div>
</form>

<style>
    input[type="file"] {
        display: none;
    }

    .custom-file-upload {
        color: #fff !important;
        background-color: #17a2b8;
        border-color: #17a2b8;
        text display: inline-block;
        cursor: pointer;
        font-weight: 400;
        text-align: center;
        vertical-align: middle;
        user-select: none;
        border: 1px solid transparent;
        padding: 6px 12px;
        font-size: 1rem;
        line-height: 1.5;
        border-radius: .25rem;
        transition: color .15s;
        width: 100%;
        height: calc(1.5em + .75rem + 2px);
    }

    .custom-file-upload:hover {
        background-color: #138496;
        border-color: #117a8b;
    }
</style>
</code>```

Title: How to use 2 models in 1 View

Body:
I have a Booking model and I create a list of all it's elements in the BookingController. There I managed to export the list as .json, however when I want to import a file I can't manage to use my custom validation to see if it's only .json. The problem is that in my Index for Booking I have a IEnumerable model for Booking and I use a BookingsUpload model to upload the file. So how can I access this BookingsUpload model inside the Index or how could i change it ? (could I combine what i do in BookingsUpload with my Booking model ?

Booking Model:

public class Booking
{
    [Required]
    [Display(Name = "Ladestand")]
    [Range(0, 100)]
    public double chargeState { get; set; }

    [Required]
    [Display(Name = "Benötigte Fahrstrecke")]
    [Range(1, 1000)]
    public double distance { get; set; }

    [Required]
    [Display(Name = "Beginn")]
    public DateTime startTime { get; set; }

    [Required]
    [Display(Name = "Ende")]
    public DateTime endTime { get; set; }

    [Required]
    [Display(Name = "Anschlusstyp")]
    [EnumDataType(typeof(ConnectorType))]
    [JsonConverter(typeof(StringEnumConverter))]
    public ConnectorType connectorType { get; set; }
}

public class BookingList
        {
            public List<Booking> BookingListObj { get; set; }
        }

BookingsUpload Model:

public class BookingsUpload
{
    [Required(ErrorMessage = "Please select a file.")]
    [DataType(DataType.Upload)]
    [MaxFileSize(1024 * 1024)]
    [AllowedExtensions(new string[] { ".json" })]
    public IFormFile File { get; set; }
}

** NEW UPDATE **:
Now Controller doesn't work as intended. Cannot add elements to List (or maybe they are added just can't display it in the View not sure):
Controller:

public class BookingController : Controller
{
    private IMemoryCache _cache;
    private string bookingsKey = "bookingsList";
    public BookingController(IMemoryCache memoryCache)
    {
        _cache = memoryCache;
    }

    public IActionResult Index()
    {
        List<Booking> bookigsList;
        _cache.TryGetValue<List<Booking>>(bookingsKey, out bookigsList);
        return View(bookigsList);
    }

    /* MVVC fucking failed :(
    public IActionResult Index()
    {
        BookingList bookingsList;
        //_cache.TryGetValue(bookingsKey, out bookingList);

        bookingsList = new BookingList();
        bookingsList.BookingListObj = new List<Booking>();

        bookingsList.BookingListObj.Add(new Booking() { chargeState = 30, distance = 150, startTime = new DateTime(2020, 8, 13, 13, 45, 0), endTime = new DateTime(2020, 8, 13, 17, 0, 0) });
        _cache.Set<List<Booking>>(bookingsKey, bookingsList.BookingListObj);

        BookingViewModel bookingViewModel = new BookingViewModel()
        {
            Bookings = bookingsList.BookingListObj
        };

        return View(bookingViewModel);
    }*/

    [HttpGet]
    public IActionResult Create()
    {
        Booking booking = new Booking();
        return View("Create", booking);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create(Booking booking)
    {
        List<Booking> bookingsList;

        //BookingList bookingsList;
        /*_cache.TryGetValue(bookingsKey, out bookingsList);
        BookingViewModel bookingViewModel = new BookingViewModel()
        {
            BookingList = bookingsList
        };*/

        if (!ModelState.IsValid)
        {
            return View("Create", booking);
        }
        if (!_cache.TryGetValue(bookingsKey, out bookingsList))
        {
            bookingsList = new List<Booking>();
        }

        bookingsList.Add(booking);
        _cache.Set<List<Booking>>(bookingsKey, bookingsList);

        /*BookingViewModel bookingViewModel = new BookingViewModel()
        {
            BookingList = bookingsList
        };*/

        return RedirectToAction("Index", "Booking");
    }

BookingViewModel:

public class BookingViewModel
{
    public Booking Booking { get; set; }
    public BookingList BookingList { get; set; }
    public IEnumerable<Booking> Bookings { get; set; }
    public BookingsUpload BookingsUpload { get; set; }

    public BookingViewModel()
    {
        Booking = new Booking();
        Bookings = new List<Booking>();
        BookingsUpload = new BookingsUpload();
    }
}

Booking Index:

    @model WebApplication.ViewModels.BookingViewModel

@{
    ViewData["Title"] = "Index";
}

Übersicht aller Buchungen

            Erstelle Buchung

                Export

                <form asp-controller="Booking" asp-action="Import" method="post" enctype="multipart/form-data">

                            <input type="file" name="file" onchange="this.form.submit()" />
                            Import/validation_bc_fuck_MVC

                </form>
                Import + validation

        @if (Model.Booking != null)
        {

                            @Html.DisplayNameFor(model => Model.Booking.chargeState) %

                            @Html.DisplayNameFor(model => Model.Booking.distance) (km)

                            @Html.DisplayNameFor(model => Model.Booking.connectorType)

                            @Html.DisplayNameFor(model => Model.Booking.startTime)

                            @Html.DisplayNameFor(model => Model.Booking.endTime)

                    @foreach (var item in Model.Bookings)
                    {

                                @Html.DisplayFor(modelItem => item.chargeState)

                                @Html.DisplayFor(modelItem => item.distance)

                                @Html.DisplayFor(modelItem => item.connectorType)

                                @Html.DisplayFor(modelItem => item.startTime)

                                @Html.DisplayFor(modelItem => item.endTime)

                    }

        }
        else
        {

Es sind keine Buchungen vorhanden

        }

So the Import label is the problem because I cant access the File from BookingsUpload to make the span asp-validation-for="File" but with the Import button I managed to go to a different View with only this code below and there the validation works because there I can use the BookingsUpload model:

    @model WebApplication.Models.BookingsUpload;

@{
    ViewData["Title"] = "Import";
}

Import

<form asp-controller="Booking" asp-action="Import" method="post" enctype="multipart/form-data">

            <input asp-for="File" type="file" name="file" onchange="this.form.submit()" />
            Import

</form>

Body:
So I finally realized I had a HUGE logical issue. I don't have to use 2 models in the same View. What I did was use a partial to copy the Import button. Like this in the index:

<form asp-controller="Booking" asp-action="Import" method="post" enctype="multipart/form-data">
                <div class="form-group">
                    @{
                        await Html.RenderPartialAsync("_Import", new WebApplication.Models.BookingsUpload());
                    }
                </div>
            </form>

And this is the partial for the Import button:

    @model WebApplication.Models.BookingsUpload;

<form asp-controller="Booking" asp-action="Import" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label class="custom-file-upload">
            <input asp-for="File" type="file" name="file" onchange="this.form.submit()" />
            Import
        </label>
        <span asp-validation-for="File" class="text-danger"></span>
    </div>
</form>

<style>
    input[type="file"] {
        display: none;
    }

    .custom-file-upload {
        color: #fff !important;
        background-color: #17a2b8;
        border-color: #17a2b8;
        text display: inline-block;
        cursor: pointer;
        font-weight: 400;
        text-align: center;
        vertical-align: middle;
        user-select: none;
        border: 1px solid transparent;
        padding: 6px 12px;
        font-size: 1rem;
        line-height: 1.5;
        border-radius: .25rem;
        transition: color .15s;
        width: 100%;
        height: calc(1.5em + .75rem + 2px);
    }

    .custom-file-upload:hover {
        background-color: #138496;
        border-color: #117a8b;
    }
</style>


答:
You can use mutate to add a column

df1 %>% group_by(DATE, SITE) %>% mutate(SiteTotal = sum(RowTotal))

Title: How do I replace all data rows grouped by specific conditions when the data has more rows than the replacement?

Body:
dput( DATE     SITE CODE   D1   D2  D3  D4  D5  D6  D7  D8  D9  H   RowTotal
    1  2019-07-03   JUP AAGA    0   0   0   0   0   0   0   1   0   15  16
    2   2019-07-03  JUP EFAS    0   0   0   0   0   0   0   0   0   1   1
    3   2019-07-03  JUP MANG    0   0   0   0   0   0   0   0   0   1   1
    4   2019-07-03  JUP MCAV    0   0   0   0   0   0   0   0   0   128 128
    5   2019-07-03  JUP MDEC    0   0   0   0   0   0   0   0   0   1   1
    6   2019-07-03  JUP MMEA    0   0   0   0   0   0   0   0   0   1   1
    7   2019-07-03  JUP OANN    0   0   0   0   0   0   0   0   0   2   2
    8   2019-07-03  JUP PAST    0   0   0   0   0   0   0   0   0   17  17
    9   2019-07-03  JUP SBOU    0   0   0   0   0   0   0   0   0   2   2
    10  2019-07-03  JUP SINT    0   0   0   0   0   0   0   0   0   9   9
    11  2019-07-03  JUP SRAD    0   0   0   0   0   0   0   0   0   1   1
    12  2019-07-03  JUP SSID    0   0   0   0   0   0   0   0   0   5   5
    13  2019-07-19  SLR ISIN    0   0   0   0   0   0   0   0   0   1   1
    14  2019-07-19  SLR MCAV    0   0   0   0   0   0   0   0   1   1   2
    16  2019-07-19  SLR PCLI    0   0   0   0   0   0   0   0   2   5   7
    17  2019-07-19  SLR SBOU    0   0   0   0   0   0   0   0   0   1   1
    18  2019-07-19  SLR SSID    0   0   0   0   0   0   0   1   0   8   9
    19  2019-07-26  PMP AAGA    0   0   0   0   0   0   0   0   0   7   7
    20  2019-07-26  PMP ACER    0   0   0   0   0   0   0   0   0   57  57
    21  2019-07-26  PMP CNAT    0   0   0   0   0   0   0   0   0   1   1
    22  2019-07-26  PMP DSTO    0   0   0   0   0   0   0   0   1   1   2
    23  2019-07-26  PMP MAUR    0   0   0   0   0   0   0   0   0   14  14
    24  2019-07-26  PMP MCAV    0   0   0   0   0   0   0   0   14  285 299)

This is my dataset. I am trying to add a new column with SiteTotal by adding the RowTotals that meet the same Date and Site conditions. I have tried multiple things in dplyr: group_by, summarize, etc. I keep running into the issue of the replacement being a less number of rows than the dataset. For example with group_by(Date, Site, RowTotal) for this data set we would replacement of 3 but there are 24 rows. Is there a way for each row to be filled that meet the conditions. My end goals is to find the "code" prevalence for each site at the specific date.

The expected column that I want would be SiteTotal shown below:

(184, 184, 184, 184, 184, 184, 184, 184, 184, 184, 184, 184, 429, 429, 429, 429, 429, 429, 81, 81, 81, 81, 81)

The end goal would to take my RowTotal column and divid it by my SiteTotal column to find "code prevalence" at the specific date and site.


问:
How to update npm nested (vulnerable) dependency?
Github has flagged a dependency in my app lock file as vulnerable.

To fix it I should updated that package to a newer version.

How do I do that if I don't have any control on the vulnerable package, because is nested in the dependencies tree?

Apologies if this is a very basic question but I don't seem to find anything useful regarding this.

答: As explained here: https://stackoverflow.com/a/17423915, you can use npm shrinkwrap to explicitly tell npm to get the nested dependency version that you want.


问:
PDO MySQL LIMIT query unexpected result
I'm trying to show a list of files and create a basic pagination system.
I'm stuck on this one because the output of the MySQL query with PDO is different than within MySQL itself.

Here's the code part:

```<code>$sql = "SELECT * FROM libri ORDER BY bookname;";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if ($row > 0) {
  // output data of each row

    $countStart = ($page-1)*$page;
    //Listing da database
    $sql = "SELECT * FROM libri ORDER BY bookname LIMIT 0,3";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $book = $row["bookname"];
    $path = $host."/libreria/lib-folder/".$row["bookname"];
    $truepath = basename($path);
    $coverName = $truepath."-cover.png";
    $fileArr = explode('.', $book);
    $fileExt = strtolower(end($fileArr));

    echo "<a href='$truepath'>".$row["bookname"]."</a><br>";
</code>```

What it's bugging me is that the query with LIMIT is behaving differently than what I see on mysql: on mysql CLI with the same query i get

```<code>+----+---------------------+
| id | bookname            |
+----+---------------------+
| 12 | book.pdf            |
|  1 | book2.pdf           |
| 13 | book3.pdf           |
+----+---------------------+
</code>```

But on the webpage I only get printed

```<code>book2
book3
</code>```

P.S. : i'm still unsure also of the reason why the lines get printed only with this seemingly wrong while statement, but not with the correct comparison ==:

```<code>while($row = $stmt->fetch(PDO::FETCH_ASSOC))
</code>```

答:
You are fetching once before you enter the loop, resulting in the first row being basically bypassed before it gets a chance to be printed. Just remove this unwanted fetch and your code should behave as you expect it to.

```<code>$sql = "SELECT * FROM libri ORDER BY bookname LIMIT 0,3";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC); # --> here

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    ...
}
</code>```

Title: PDO MySQL LIMIT query unexpected result

Body:
I'm trying to show a list of files and create a basic pagination system.
I'm stuck on this one because the output of the MySQL query with PDO is different than within MySQL itself.

Here's the code part:

$sql = "SELECT * FROM libri ORDER BY bookname;";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if ($row > 0) {
  // output data of each row

    $countStart = ($page-1)*$page;
    //Listing da database
    $sql = "SELECT * FROM libri ORDER BY bookname LIMIT 0,3";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $book = $row["bookname"];
    $path = $host."/libreria/lib-folder/".$row["bookname"];
    $truepath = basename($path);
    $coverName = $truepath."-cover.png";
    $fileArr = explode('.', $book);
    $fileExt = strtolower(end($fileArr));

    echo "".$row["bookname"]."
";

What it's bugging me is that the query with LIMIT is behaving differently than what I see on mysql: on mysql CLI with the same query i get

+----+---------------------+
| id | bookname            |
+----+---------------------+
| 12 | book.pdf            |
|  1 | book2.pdf           |
| 13 | book3.pdf           |
+----+---------------------+

But on the webpage I only get printed

book2
book3

P.S. : i'm still unsure also of the reason why the lines get printed only with this seemingly wrong while statement, but not with the correct comparison ==:

while($row = $stmt->fetch(PDO::FETCH_ASSOC))

Body:
You are fetching once before you enter the loop, resulting in the first row being basically bypassed before it gets a chance to be printed. Just remove this unwanted fetch and your code should behave as you expect it to.

$sql = "SELECT * FROM libri ORDER BY bookname LIMIT 0,3";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC); # --> here

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    ...
}


问:
Cannot display image in laravel
I've tried displaying an image with laravel using a Query-- The images are stored in the storage directory and a symlink with "public" has already been established.

I have tried using:
src="{{storage_path('app/public/'.$post->post_image)}}"

src="{{ asset('storage/'.$post->post_image) }}"

src="{{$post->post_image}}"

Testing, I discovered I could use a static path in order to succesfully display the imaage like so:

src="{{ asset('storage/images/image_name.jpeg')}}"

However, this is not what I'm looking for.

The query {{$post->post_image}} returns the following:

127.0.0.1:8000/images/image_name.jpeg

EDIT: If I go edit the database and add "storage/" before the url of the image, then I can use src="{{asset($post->post_image)}}" to display it.

As mentioned before, I already tried src="{{asset('storage/' . $post->post_image)}} without altering the database.

答:
I believe Storage::url could help here.

In your Post model, you can define a url helper like so:

```<code>public function url()
{
    return Storage::url($this->post_image);
}
</code>```

Don't forget to import the Storage facade.

```<code>use Illuminate\Support\Facades\Storage;
</code>```

And then retrieve image like so:

```<code>{{ $post->url() }}
</code>```

Also ensure you have a symbolic link created:

```<code>php artisan storage:link
</code>```

UPDATED

In .env add the below:

```<code>FILESYSTEM_DRIVER=public
</code>```

It changes the default FILESYSTEM_DRIVER to public in config/filesystems.php which means it now uses the below config in the same file

```<code>'public' => [
     'driver' => 'local',
     'root' => storage_path('app/public'),
     'url' => env('APP_URL').'/storage',
     'visibility' => 'public',
],
</code>```

Then run the command php artisan config:cache

https://laravel.com/docs/7.x/filesystem#file-urls

Title: Cannot display image in laravel

Body:
I believe Storage::url could help here.

In your Post model, you can define a url helper like so:

public function url()
{
    return Storage::url($this->post_image);
}

Don't forget to import the Storage facade.

use Illuminate\Support\Facades\Storage;

And then retrieve image like so:

{{ $post->url() }}

Also ensure you have a symbolic link created:

php artisan storage:link

UPDATED

In .env add the below:

FILESYSTEM_DRIVER=public

It changes the default FILESYSTEM_DRIVER to public in config/filesystems.php which means it now uses the below config in the same file

'public' => [
     'driver' => 'local',
     'root' => storage_path('app/public'),
     'url' => env('APP_URL').'/storage',
     'visibility' => 'public',
],

Then run the command php artisan config:cache

https://laravel.com/docs/7.x/filesystem#file-urls


问:
Creating Binary Matrix in R with uneven dataframe
I have a dataset with microRNAs in 8 different groups. I need to transform this data frame into a binary matrix using R. The number of microRNAs is different in the groups and I would like to make the groups in the row and have the microRNAs on the columns. Here is part of the data:

```<code>Group1    Group2    Group3   Group4
miR-133a  miR-133b  miR-456  miR777
miR-777   miR138    miR-564  miR-878
miR-878             miR-777  miR978
                    miR-878
                    miR-978
</code>```

Output expected:

```<code>Groups  miR-133a  miR-133b  miR-456  miR-777.....
Group1  1             0      0        1
Group2  0             1      0        0
.
.
.
</code>```

I tried to use this code:

```<code>im <- which(arr.ind=T,Dat!='');
u <- unique(Dat[im[order(im[,'row'],im[,'col']),]]);
res <- matrix(0L,nrow(Dat),length(u),dimnames=list(NULL,u));
res[cbind(im[,'row'],match(Dat[im],u))] <- 1L;
res
</code>```

But it is giving me a lot of rows. Can anyone help me with that?

答:
Assuming the blanks in your data frame is "" :

```<code>df = structure(list(Group1 = c("miR-133a", "miR-777", "miR-878", "",
""), Group2 = c("miR-133b", "miR138", "", "", ""), Group3 = c("miR-456",
"miR-564", "miR-777", "miR-878", "miR-978"), Group4 = c("miR777",
"miR-878", "miR978", "", "")), row.names = c(NA, -5L), class = "data.frame")
</code>```

Then, make a master set of all items:

```<code>alla = setdiff(sort(unique(unlist(df))),"")
res = t(sapply(colnames(df),function(i)as.numeric(alla %in% df[,i])))
colnames(res) = alla

       miR-133a miR-133b miR-456 miR-564 miR-777 miR-878 miR-978 miR138 miR777
Group1        1        0       0       0       1       1       0      0      0
Group2        0        1       0       0       0       0       0      1      0
Group3        0        0       1       1       1       1       1      0      0
Group4        0        0       0       0       0       1       0      0      1
       miR978
Group1      0
Group2      0
Group3      0
Group4      1
</code>```

Body:
I have a dataset with microRNAs in 8 different groups. I need to transform this data frame into a binary matrix using R. The number of microRNAs is different in the groups and I would like to make the groups in the row and have the microRNAs on the columns. Here is part of the data:

Group1    Group2    Group3   Group4
miR-133a  miR-133b  miR-456  miR777
miR-777   miR138    miR-564  miR-878
miR-878             miR-777  miR978
                    miR-878
                    miR-978

Output expected:

Groups  miR-133a  miR-133b  miR-456  miR-777.....
Group1  1             0      0        1
Group2  0             1      0        0
.
.
.

I tried to use this code:

im <- which(arr.ind=T,Dat!='');
u <- unique(Dat[im[order(im[,'row'],im[,'col']),]]);
res <- matrix(0L,nrow(Dat),length(u),dimnames=list(NULL,u));
res[cbind(im[,'row'],match(Dat[im],u))] <- 1L;
res

But it is giving me a lot of rows. Can anyone help me with that?

Body:
Assuming the blanks in your data frame is "" :

df = structure(list(Group1 = c("miR-133a", "miR-777", "miR-878", "",
""), Group2 = c("miR-133b", "miR138", "", "", ""), Group3 = c("miR-456",
"miR-564", "miR-777", "miR-878", "miR-978"), Group4 = c("miR777",
"miR-878", "miR978", "", "")), row.names = c(NA, -5L), class = "data.frame")

Then, make a master set of all items:

alla = setdiff(sort(unique(unlist(df))),"")
res = t(sapply(colnames(df),function(i)as.numeric(alla %in% df[,i])))
colnames(res) = alla

       miR-133a miR-133b miR-456 miR-564 miR-777 miR-878 miR-978 miR138 miR777
Group1        1        0       0       0       1       1       0      0      0
Group2        0        1       0       0       0       0       0      1      0
Group3        0        0       1       1       1       1       1      0      0
Group4        0        0       0       0       0       1       0      0      1
       miR978
Group1      0
Group2      0
Group3      0
Group4      1


问:
How do I link to another html with a different style? Is it possible to do?
I am working on a home page that links to several of my projects. I am trying to link to another html that has a different style than the home page. The images and text I have for the second html works fine, but it takes on the style of the home page, and not its own design which is different. My question is is it possible to link to another html that has a different style? If so, how do I input this? When I try putting the style for the second html in the home page's folder, it won't let me since there's already another style.css I used for the main home page. I tried changing the name of the second style file and it still does not work. </p>

答:
If I understand you correctly, you have two HTML pages and you want a different CSS style for each page.

You can have several CSS files but you cannot have two with the same name.

Create two different CSS files. For example home.css and secondpage.css

Create two different HTML files. For example home.html and secondpage.html

Go to the  of home.html and add <link href="home.css" type="text/css" rel="stylesheet" />

Go to the  of secondpage.html and add <link href="secondpage.css" type="text/css" rel="stylesheet" />

Make sure the html files and css files are in the same folder.
If you have trouble finding the , see the code below:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="home.css" type="text/css" rel="stylesheet" />
</head>
<body>
    <p>Hello World</p>
</body>
</html>
</code>```

Body:
If I understand you correctly, you have two HTML pages and you want a different CSS style for each page.

You can have several CSS files but you cannot have two with the same name.

Create two different CSS files. For example home.css and secondpage.css

Create two different HTML files. For example home.html and secondpage.html

Go to the <head> of home.html and add <link href="home.css" type="text/css" rel="stylesheet" />

Go to the <head> of secondpage.html and add <link href="secondpage.css" type="text/css" rel="stylesheet" />

Make sure the html files and css files are in the same folder.
If you have trouble finding the <head>, see the code below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="home.css" type="text/css" rel="stylesheet" />
</head>
<body>
    <p>Hello World</p>
</body>
</html>


问:
iPhone Proximity Sensor
Can the iPhone SDK take advantage of the iPhone's proximity sensors? If so, why hasn't anyone taken advantage of them? I could picture a few decent uses.

For example, in a racing game, you could put your finger on the proximity sensor to go instead of taking up screen real-estate with your thumb. Of course though, if this was your only option, then iPod touch users wouldn't be able to use the application.

Does the proximity sensor tell how close you are, or just that something is in front of it?

答:
If you aren't aiming for the AppStore, you can read my articles here on getting access to those:

Proximity Sensor: http://iphonedevwiki.net/index.php/AppleProxShim

Ambient Light Sensor: http://iphonedevwiki.net/index.php/AppleISL29003

OwnerDisplayName: Greg

ContentLicense: CC BY-SA 2.5

Title: iPhone Proximity Sensor


问:
Problem with loading a json file for geo_data in python
I am currently trying to use folium library in python to create webmaps. I have a file world.json which contains geo_data. I have provided a link to the file at the end of this post. I tried the following code:

data = [json.loads(line) for line in open('world.json', 'r')]
```

<p>and received the following error:</p>

```Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
  File "C:\Users\name\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Users\name\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\name\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
```

How can I load this file?

What I want to achieve is essentially obtain the population data and create a Choropleth and overlay it on my webmap.

Edit: Forgot the link:

https://1drv.ms/u/s!Army95vqcKXpaooVAZU_g-VCAVw?e=vwTknq

Edit: Previous link to skydrive stopped working due to "high traffic". Below is link to dropbox, hopefully this works:

https://www.dropbox.com/s/gmm8db0g03rc7cv/world.json?dl=0

答:
The open command will return a file handle, not string lines. I would do:

```<code>with open('world.json', 'r') as fh:
    data = json.load(fh)
</code>```

data will then be your contents converted to python (list or dictionary, etc)

Body:
I am currently trying to use folium library in python to create webmaps. I have a file world.json which contains geo_data. I have provided a link to the file at the end of this post. I tried the following code:

data = [json.loads(line) for line in open('world.json', 'r')]

and received the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
  File "C:\Users\name\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Users\name\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\name\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

How can I load this file?

What I want to achieve is essentially obtain the population data and create a Choropleth and overlay it on my webmap.

Edit: Forgot the link:

https://1drv.ms/u/s!Army95vqcKXpaooVAZU_g-VCAVw?e=vwTknq

Edit: Previous link to skydrive stopped working due to "high traffic". Below is link to dropbox, hopefully this works:

https://www.dropbox.com/s/gmm8db0g03rc7cv/world.json?dl=0

Body:
The open command will return a file handle, not string lines. I would do:

with open('world.json', 'r') as fh:
    data = json.load(fh)

data will then be your contents converted to python (list or dictionary, etc)


问:
Has Google FCM stopped accepting HTTP requests?
I was previously able to send curl messages to
http://fcm.googleapis.com/fcm/send

However now I get
403:Forbidden Error

However, the same curl script works if I change http to https.

This restriction seems to have been put in place yesterday.
My source of messages is an arduino which can only handle HTTP and not HTTPS.

Does anybody know if I can still send HTTP requests to FCM via another route?

答: Set http (http://fcm.googleapis.com/fcm/send) by https (https://fcm.googleapis.com/fcm/send) on API URL.</p>


问:
PyCharm, what is python_stubs?
I have had numerous problems with PyCharm not recognising functions in libraries properly, so I've decided to look into the source code of some example functions that PyCharm recognises incorrectly. For example, PyCharm does not recognise pickle.load() correctly; it thinks that pickle.load() does not take any arguments, when in fact it does take one argument. I've asked that question here. So I've written the following short testing code.

```<code>import pickle

r = range(10)
f = open("../temp/pickling_example.pkl", "wb")
pickle.dump(r, f)
f.close()
f = open("../temp/pickling_example.pkl", "rb")
pickle.load(f)
print(r)
</code>```

I pressed Ctrl+B on pickle.load(f), the penultimate line. I was hoping that this would bring me to the source file containing the definition of pickle.load(), but instead it brought me to a file in the location C:\Users\ray\.PyCharm30\system\python_stubs\-1442825926\_pickle.py. This file contains the following abstract (see screenshot below).

Here you can see the source of the problem of PyCharm incorrectly recognising the signature of pickle.load(); the signature of pickle.load() according to this file has no arguments.

Could someone explain why I was brought here, and what this file is, and what the python_stubs folder (more precisely, C:\Users\ray\.PyCharm30\system\python_stubs\) is?

My guess is the following. I was brought to this file in this location because PyCharm can't find the actual source code where pickle.load() was defined, on my computer. In these situations, PyCharm just generates a dummy file with just the declarations (or just the signatures) of the functions used, in this case it's pickle.load(). This file is where I was brought to when I pressed Ctrl+B on pickle.load(). The purpose of this file is purely so that PyCharm's inspections works properly and can provide autocompletion, and PyCharm puts all of these files inf the python_stubs directory. The actual definition of the pickle.load() function is in a pyc or pyd file somewhere in my C:\Python34\ directory, and I don't have the actual py file containing the definition of pickle.load() because, when I installed Python, I didn't install the source codes.

Questions:

(1) Is my guess roughly correct? Could you provide and more correct and precise

(2) What can I do to prevent PyCharm from wrongly recognising or not recognising library functions? Shall I make sure I always install the source codes of Python and all 3rd party packages, in order to ensure that PyCharm can do its inspections properly?

(3) If I was right in that, PyCharm generates these files, how does PyCharm guess the functions' signatures?

答: PEP484 defined these stub files. As per the PEP, they are supposed to be for type-hints and can be used by type-checker.</p>

Title: PyCharm, what is python_stubs?

Body:
I have had numerous problems with PyCharm not recognising functions in libraries properly, so I've decided to look into the source code of some example functions that PyCharm recognises incorrectly. For example, PyCharm does not recognise pickle.load() correctly; it thinks that pickle.load() does not take any arguments, when in fact it does take one argument. I've asked that question here. So I've written the following short testing code.

import pickle

r = range(10)
f = open("../temp/pickling_example.pkl", "wb")
pickle.dump(r, f)
f.close()
f = open("../temp/pickling_example.pkl", "rb")
pickle.load(f)
print(r)

I pressed Ctrl+B on pickle.load(f), the penultimate line. I was hoping that this would bring me to the source file containing the definition of pickle.load(), but instead it brought me to a file in the location C:\Users\ray\.PyCharm30\system\python_stubs\-1442825926\_pickle.py. This file contains the following abstract (see screenshot below).

Here you can see the source of the problem of PyCharm incorrectly recognising the signature of pickle.load(); the signature of pickle.load() according to this file has no arguments.

Could someone explain why I was brought here, and what this file is, and what the python_stubs folder (more precisely, C:\Users\ray\.PyCharm30\system\python_stubs\) is?

My guess is the following. I was brought to this file in this location because PyCharm can't find the actual source code where pickle.load() was defined, on my computer. In these situations, PyCharm just generates a dummy file with just the declarations (or just the signatures) of the functions used, in this case it's pickle.load(). This file is where I was brought to when I pressed Ctrl+B on pickle.load(). The purpose of this file is purely so that PyCharm's inspections works properly and can provide autocompletion, and PyCharm puts all of these files inf the python_stubs directory. The actual definition of the pickle.load() function is in a pyc or pyd file somewhere in my C:\Python34\ directory, and I don't have the actual py file containing the definition of pickle.load() because, when I installed Python, I didn't install the source codes.

Questions:

(1) Is my guess roughly correct? Could you provide and more correct and precise

(2) What can I do to prevent PyCharm from wrongly recognising or not recognising library functions? Shall I make sure I always install the source codes of Python and all 3rd party packages, in order to ensure that PyCharm can do its inspections properly?

(3) If I was right in that, PyCharm generates these files, how does PyCharm guess the functions' signatures?


问:
Filtering Dataframe based on many conditions
here is my problem:

I have a dataFrame that look like this :

```<code>Date  Name  Score  Country
2012  Paul    45    Mexico
2012  Mike    38    Sweden
2012  Teddy   62    USA
2012  Hilary  80    USA
2013  Ashley  42    France
2013  Temari  58    UK
2013  Harry   78    UK
2013  Silvia  55    Italy
</code>```

I want to select the two best scores, with a filter by date and also from a different country.

For example here : In 2012 Hilary has the best score (USA) so she will be selected.
Teddy has the second best score in 2012 but he won't be selected as he comes from the same country (USA)
So Paul will be selected instead as he comes from a different country (Mexico).

This is what I did :

```<code>df = pd.DataFrame(
    {'Date':["2012","2012","2012","2012","2013","2013","2013","2013"],
     'Name': ["Paul", "Mike", "Teddy", "Hilary", "Ashley", "Temaru","Harry","Silvia"],
     'Score': [45, 38, 62, 80, 42, 58,78,55],
     "Country":["Mexico","Sweden","USA","USA","France","UK",'UK','Italy']})
</code>```

And then I made the filter by Date and by Score :

```<code>df1 = df.set_index('Name').groupby('Date')['Score'].apply(lambda grp: grp.nlargest(2))
</code>```

But I don't really know and to do the filter that takes into account that they have to come from a different country.

Does anyone have an idea on that ? Thank you so much

EDIT : The answer I am looking for should be something like that :

```<code>Date  Name  Score  Country
2012  Hilary  80    USA
2012  Paul    45    Mexico
2013  Harry   78    UK
2013  Silvia  55    Italy
</code>```

Filter two people by date, best score and from a different country

答:
sort_values + tail

```<code>s=df.sort_values('Score').drop_duplicates(['Date','Country'],keep='last').groupby('Date').tail(2)
s
   Date    Name  Score Country
0  2012    Paul     45  Mexico
7  2013  Silvia     55   Italy
6  2013   Harry     78      UK
3  2012  Hilary     80     USA
</code>```

Body:
here is my problem:

I have a dataFrame that look like this :

Date  Name  Score  Country
2012  Paul    45    Mexico
2012  Mike    38    Sweden
2012  Teddy   62    USA
2012  Hilary  80    USA
2013  Ashley  42    France
2013  Temari  58    UK
2013  Harry   78    UK
2013  Silvia  55    Italy

I want to select the two best scores, with a filter by date and also from a different country.

For example here : In 2012 Hilary has the best score (USA) so she will be selected.
Teddy has the second best score in 2012 but he won't be selected as he comes from the same country (USA)
So Paul will be selected instead as he comes from a different country (Mexico).

This is what I did :

df = pd.DataFrame(
    {'Date':["2012","2012","2012","2012","2013","2013","2013","2013"],
     'Name': ["Paul", "Mike", "Teddy", "Hilary", "Ashley", "Temaru","Harry","Silvia"],
     'Score': [45, 38, 62, 80, 42, 58,78,55],
     "Country":["Mexico","Sweden","USA","USA","France","UK",'UK','Italy']})

And then I made the filter by Date and by Score :

df1 = df.set_index('Name').groupby('Date')['Score'].apply(lambda grp: grp.nlargest(2))

But I don't really know and to do the filter that takes into account that they have to come from a different country.

Does anyone have an idea on that ? Thank you so much

EDIT : The answer I am looking for should be something like that :

Date  Name  Score  Country
2012  Hilary  80    USA
2012  Paul    45    Mexico
2013  Harry   78    UK
2013  Silvia  55    Italy

Filter two people by date, best score and from a different country

Body:
sort_values + tail

s=df.sort_values('Score').drop_duplicates(['Date','Country'],keep='last').groupby('Date').tail(2)
s
   Date    Name  Score Country
0  2012    Paul     45  Mexico
7  2013  Silvia     55   Italy
6  2013   Harry     78      UK
3  2012  Hilary     80     USA


问:
How to retrieve all id of firebase database content using Angular?
I am trying to retrieve all firebase database content with their IDs. Currently I have two functions, getAll() and get(input) which returns one specific product with the given ID. My current implementation gives me all the objects from firebase database without the IDs. What do I need to change to be able to get all objects with their IDs?</p>

```<code>product.service.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { Product } from './admin/product-form/product-interface';

@Injectable({
  providedIn: 'root'
})
export class ProductService {

  constructor(private db: AngularFireDatabase) { }

  create(product){
    return this.db.list('/products').push(product);

  }

  getAll() {
    return this.db.list('/products').valueChanges();

  }

  get(productId){
    return this.db.object('/products/' + productId).valueChanges();
  }
}

product-form.component.ts

import { Product } from './product-interface';
import { ProductService } from './../../product.service';
import { CategoryService } from './../../category.service';
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { take } from 'rxjs/operators';

@Component({
  selector: 'app-product-form',
  templateUrl: './product-form.component.html',
  styleUrls: ['./product-form.component.css']
})

export class ProductFormComponent implements OnInit {
  categories$;
  product = {};
  // product:Product;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private categoryService: CategoryService,
    private productService: ProductService)
    {

    }

   save(product){
     this.productService.create(product);
     this.router.navigate(['/admin/products']);
   }

  ngOnInit(): void {
    this.categories$ = this.categoryService.getCategories();
    let id = this.route.snapshot.paramMap.get('id');
    this.productService.getAll().subscribe((a) =>
    this.product = a);

  }

}

admin-products.component.ts

import { ProductService } from './../../product.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-admin-products',
  templateUrl: './admin-products.component.html',
  styleUrls: ['./admin-products.component.css']
})
export class AdminProductsComponent implements OnInit {
  products$;
  constructor(private productService: ProductService) {
    this.products$ = this.productService.getAll()
   }

  ngOnInit(): void {
    this.products$.subscribe(p => {
      console.log(p, 'products');
    })
  }

}

admin-products.component.html

<p>
<a routerLink = "/admin/products/new" class="btn btn-primary">New Product</a>
</p>

<table class="table">
    <thead>
        <tr>
            <th>Title</th>
            <th>Price</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let p of products$ | async">
            <td>{{ p.title }}</td>
            <td>{{ p.price}}</td>
            <td>
                <a [routerLink]="['/admin/products/', p.$key]">Edit</a>
            </td>
        </tr>
    </tbody>
</table>

</code>```

答: Btw, if you subscribe to observables in components (not in angular services), you will have to unsubscribe them ngOnDestroy() lifecycle hook to avoid memory and performance issues in your browser.</p>

Body:
I am trying to retrieve all firebase database content with their IDs. Currently I have two functions, getAll() and get(input) which returns one specific product with the given ID. My current implementation gives me all the objects from firebase database without the IDs. What do I need to change to be able to get all objects with their IDs?

product.service.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { Product } from './admin/product-form/product-interface';

@Injectable({
  providedIn: 'root'
})
export class ProductService {

  constructor(private db: AngularFireDatabase) { }

  create(product){
    return this.db.list('/products').push(product);

  }

  getAll() {
    return this.db.list('/products').valueChanges();

  }

  get(productId){
    return this.db.object('/products/' + productId).valueChanges();
  }
}

product-form.component.ts

import { Product } from './product-interface';
import { ProductService } from './../../product.service';
import { CategoryService } from './../../category.service';
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { take } from 'rxjs/operators';

@Component({
  selector: 'app-product-form',
  templateUrl: './product-form.component.html',
  styleUrls: ['./product-form.component.css']
})

export class ProductFormComponent implements OnInit {
  categories$;
  product = {};
  // product:Product;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private categoryService: CategoryService,
    private productService: ProductService)
    {

    }

   save(product){
     this.productService.create(product);
     this.router.navigate(['/admin/products']);
   }

  ngOnInit(): void {
    this.categories$ = this.categoryService.getCategories();
    let id = this.route.snapshot.paramMap.get('id');
    this.productService.getAll().subscribe((a) =>
    this.product = a);

  }

}

admin-products.component.ts

import { ProductService } from './../../product.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-admin-products',
  templateUrl: './admin-products.component.html',
  styleUrls: ['./admin-products.component.css']
})
export class AdminProductsComponent implements OnInit {
  products$;
  constructor(private productService: ProductService) {
    this.products$ = this.productService.getAll()
   }

  ngOnInit(): void {
    this.products$.subscribe(p => {
      console.log(p, 'products');
    })
  }

}

admin-products.component.html

New Product

            Title
            Price

            {{ p.title }}
            {{ p.price}}

                Edit


问:
Homework-C Programming- Recursive Program
Hey guys! I was assigned this program which was pretty simple and didn't take long to code, yet I can't get it to run. Nothing prints and I think it's because it goes into an endless loop. Just looking for a fix on this.

Assignment:

Write and test a recursive function
  that returns the value of the
  following recursive definition:

```<code>f(x) = 0        if x <= 0
f(x- 1) + 2       otherwise
</code>```

My program:

```<code>#include <stdio.h>
int main(void)
{
    int n, x;

    int factorial(int n) {

        if (x <= 0) {
            printf("x equals: ");
            return 1;
        } else {
            return n * factorial(n - 1); //error here
        }
        f(x) = f(x - 1) + 2;
    }
    return 0;
}
</code>```

答:
You've declared factorial inside main.

You're not calling factorial in main.

Body:
Hey guys! I was assigned this program which was pretty simple and didn't take long to code, yet I can't get it to run. Nothing prints and I think it's because it goes into an endless loop. Just looking for a fix on this.

Assignment:

Write and test a recursive function
  that returns the value of the
  following recursive definition:

f(x) = 0        if x <= 0
f(x- 1) + 2       otherwise

My program:

#include <stdio.h>
int main(void)
{
    int n, x;

    int factorial(int n) {

        if (x <= 0) {
            printf("x equals: ");
            return 1;
        } else {
            return n * factorial(n - 1); //error here
        }
        f(x) = f(x - 1) + 2;
    }
    return 0;
}