问:
React-native StackNavigation pass props
I'm building an app in react-native and I'm trying to put navigation into it. I have a button and I want to move to another page by clicking on it.
But I got that error : undefined is not an object (evaluating '_this.props.navigation')

App.js :

```<code>import React, { Component } from 'react';
import { View } from 'react-native';
import YTSearch from 'youtube-api-search';
import AppHeader from './components/AppHeader';
import SearchBar from './components/SearchBar';
import VideoList from './components/VideoList';
import TrackPlayerScreen from './Screens/TrackPlayerScreen';
import VideoListItems from './components/VideoListItems';

import {StackNavigator}  from 'react-navigation';

const AppNavigator = StackNavigator({
  VideoListItems: { screen: VideoListItems, navigationOptions: { header: null } },
  TrackPlayerScreen: { screen: TrackPlayerScreen,navigationOptions: { header: null } }
});

const API_KEY = 'APIKEY;

export default class App extends Component {
  state = {
    loading: false,
    videos: []
  }

  componentWillMount(){
    this.searchYT('');
  }

  onPressSearch = term => {
    this.searchYT(term);
  }

  searchYT = term => {
    this.setState({ loading: true });
    YTSearch({key: API_KEY, term }, videos => {
      console.log(videos);
      this.setState({
        loading: false,
        videos
      });
    });
  }

  render() {
    const { loading, videos } = this.state;
    return (
      <View style={{ flex: 1, backgroundColor: '#ddd' }}>

        <AppHeader headerText="Project Master Sound Control" />
        <SearchBar
        loading={loading}
        onPressSearch={this.onPressSearch} />
        <VideoList videos={videos} />
      </View>
    );
  }
}
</code>```

File where button will navigate to another page by clicking on it VideoListItems :

```<code>import React from 'react';
import { View, Text, Image } from 'react-native';
import { Card } from 'react-native-elements';
import TrackPlayerScreen from '../Screens/TrackPlayerScreen';
import { Button } from 'react-native-elements';
import { WebBrowser } from 'expo';
import {StackNavigator}  from 'react-navigation';

const VideoListItems = ({ video }) => {
    const {
        cardStyle,
        imageStyle,
        contentStyle,
        titleStyle,
        channelTitleStyle,
        descriptionStyle
     } = styles;
    const {
        title,
        channelTitle,
        description,
        thumbnails: { medium: { url } }
    } = video.snippet;

    const videoId = video.id.videoId;

    return(
        <View>
             <Card title={null} containerStyle={cardStyle}>
                <Image
                    style={imageStyle}
                    source= {{ uri: url}}
                />
                <View style={contentStyle}>
                    <Text style={titleStyle}>
                        {title}
                    </Text>
                    <Text style={channelTitleStyle}>
                        {channelTitle}
                    </Text>
                    <Text style={descriptionStyle}>
                        {description}
                    </Text>
                    <Button
                      raised
                      title="Save And Play"
                      icon={{ name: 'play-arrow' }}
                      containerViewStyle={{ marginTop: 10 }}
                      backgroundColor="#E62117"
                      onPress={() => {
                        this.props.navigation.navigate('InformationScreen')
                      }}
                    />

                </View>
             </Card>
        </View>
    );
};
export default VideoListItems;
</code>```

I'm having trouble of how to pass the navigation props to my VideoListItems, anyone any ideas ? Or am I missing something somewhere else ?

答:
It seems to me that you have declared the stack navigator but aren't actually rendering it. You could try simply replacing the VideoList component in your render function with the

<AppNavigator/>

and then adding the VideoList as a screen when declaring the stack navigator.

The first screen that you declare in the stack navigator will be used as default, so if you declare the VideoList first, you will have access to the navigation props from within that component allowing you to navigate to the VideoListItems.

I hope this helps

Title: React-native StackNavigation pass props

Body:
I'm building an app in react-native and I'm trying to put navigation into it. I have a button and I want to move to another page by clicking on it.
But I got that error : undefined is not an object (evaluating '_this.props.navigation')

App.js :

import React, { Component } from 'react';
import { View } from 'react-native';
import YTSearch from 'youtube-api-search';
import AppHeader from './components/AppHeader';
import SearchBar from './components/SearchBar';
import VideoList from './components/VideoList';
import TrackPlayerScreen from './Screens/TrackPlayerScreen';
import VideoListItems from './components/VideoListItems';

import {StackNavigator}  from 'react-navigation';

const AppNavigator = StackNavigator({
  VideoListItems: { screen: VideoListItems, navigationOptions: { header: null } },
  TrackPlayerScreen: { screen: TrackPlayerScreen,navigationOptions: { header: null } }
});

const API_KEY = 'APIKEY;

export default class App extends Component {
  state = {
    loading: false,
    videos: []
  }

  componentWillMount(){
    this.searchYT('');
  }

  onPressSearch = term => {
    this.searchYT(term);
  }

  searchYT = term => {
    this.setState({ loading: true });
    YTSearch({key: API_KEY, term }, videos => {
      console.log(videos);
      this.setState({
        loading: false,
        videos
      });
    });
  }

  render() {
    const { loading, videos } = this.state;
    return (
      <View style={{ flex: 1, backgroundColor: '#ddd' }}>

        <AppHeader headerText="Project Master Sound Control" />
        <SearchBar
        loading={loading}
        onPressSearch={this.onPressSearch} />
        <VideoList videos={videos} />
      </View>
    );
  }
}

File where button will navigate to another page by clicking on it VideoListItems :

import React from 'react';
import { View, Text, Image } from 'react-native';
import { Card } from 'react-native-elements';
import TrackPlayerScreen from '../Screens/TrackPlayerScreen';
import { Button } from 'react-native-elements';
import { WebBrowser } from 'expo';
import {StackNavigator}  from 'react-navigation';

const VideoListItems = ({ video }) => {
    const {
        cardStyle,
        imageStyle,
        contentStyle,
        titleStyle,
        channelTitleStyle,
        descriptionStyle
     } = styles;
    const {
        title,
        channelTitle,
        description,
        thumbnails: { medium: { url } }
    } = video.snippet;

    const videoId = video.id.videoId;

    return(
        <View>
             <Card title={null} containerStyle={cardStyle}>
                <Image
                    style={imageStyle}
                    source= {{ uri: url}}
                />
                <View style={contentStyle}>
                    <Text style={titleStyle}>
                        {title}
                    </Text>
                    <Text style={channelTitleStyle}>
                        {channelTitle}
                    </Text>
                    <Text style={descriptionStyle}>
                        {description}
                    </Text>
                    <Button
                      raised
                      title="Save And Play"
                      icon={{ name: 'play-arrow' }}
                      containerViewStyle={{ marginTop: 10 }}
                      backgroundColor="#E62117"
                      onPress={() => {
                        this.props.navigation.navigate('InformationScreen')
                      }}
                    />

                </View>
             </Card>
        </View>
    );
};
export default VideoListItems;

I'm having trouble of how to pass the navigation props to my VideoListItems, anyone any ideas ? Or am I missing something somewhere else ?


来源: stackexchange

问:
Removing the corner of a box outline in SVG (or any part of any element in SVG)
I'm trying to advance beyond the basics of SVG and create an image which involves masking or clipping. However I seem to have fallen at the first hurdle.

I understand that I can use <mask> to leave parts of the image visible and remove everything else.

What I cannot see - either with <clip-path> or with <mask> - is how to remove parts of the image and leave everything else visible.

Here is the beginning of an image below:

<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     viewBox="0 0 420 420">

<defs>

</defs>

<rect x="0" y="0" width="420" height="420" />
<rect x="21" y="99" width="300" height="300" rx="15" ry="15" />

<g transform="rotate(-45 50 50)">
<rect x="-100" y="240" width="355" height="90" />
</g>

</svg>```
</div>
</div>
</p>
<p>What is the correct approach to removing the top-right corner of the box, beneath the 45-degree slanted rectangle, so that the dark red rectangle shows through from below?</p>
<p><strong>N.B.</strong> I do mean <em>remove</em> and not just hide. I know I can <code>fill</code> the rectangle and it will hide the box-corner beneath.</p>
<hr />
<h1>Update 1</h1>
<p>I have come up with "a solution" using <code><clip-path></code> which looks great:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     viewBox="0 0 420 420">

<defs>

<clipPath id="clip-corner">
<path d="M0,76 L274,76 L224,126 L306,209 L355,160 L355,420 L0,420 L0,76" />
</clipPath>

<style type="text/css"><![CDATA[

rect:nth-of-type(1) {
fill: rgb(191, 0, 0);
}

rect:nth-of-type(2) {
clip-path: url(#clip-corner);
}

rect, g rect:nth-of-type(1) {
stroke: rgb(255,255,255);
stroke-width: 10;
fill: rgba(0, 0, 0, 0);
}

]]></style>
</defs>

<rect x="0" y="0" width="420" height="420" />
<rect x="21" y="99" width="300" height="300" rx="15" ry="15" />
<g transform="rotate(-45 50 50)">
<rect x="-100" y="240" width="355" height="90" />
</g>

</svg></code>```

But... the problem is, this is how I did it. By drawing the following clip-path:

<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     viewBox="0 0 420 420">

<defs>

</defs>

<rect x="0" y="0" width="420" height="420" />
<path d="M0,76 L274,76 L224,126 L306,209 L355,160 L355,420 L0,420 L0,76" />
<rect x="21" y="99" width="300" height="300" rx="15" ry="15" />

</svg>```

That's not how you're supposed to do it, is it?

答:
In a mask, everything that should be visible should be white: make the background white. Everything that should be invisble should be black: make the slanted rectangle plus a wide enough stroke black.

Reuse the basic shapes with <use>, so that you only need to edit them in one place. Define them within <defs> and make sure no style is applied to them. Instead, apply the style to the <use> elements.

mask use:first-child {
    fill: rgb(255, 255, 255);
}

mask use:last-child {
    stroke: rgb(0, 0, 0);
    fill: rgb(0, 0, 0);
    stroke-width: 30;
}

.filled {
    fill: rgb(191, 0, 0);
}

.stroked {
    stroke: rgb(255,255,255);
    stroke-width: 10;
}

.masked {
     mask: url(#mask);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     viewBox="0 0 420 420">

  <defs>

    <rect id="back" x="0" y="0" width="420" height="420" />
    <rect id="slanted" transform="rotate(-45 50 50)"
          x="-100" y="240" width="355" height="90" />

    <mask id="mask">
      <use xlink:href="#back" />
      <use xlink:href="#slanted" />
    </mask>

  </defs>

  <use class="filled" xlink:href="#back" />

  <rect class="filled stroked masked"
        x="21" y="99" width="300" height="300" rx="15" ry="15" />

  <use class="filled stroked" xlink:href="#slanted" />

</svg></code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to advance beyond the basics of SVG and create an image which involves masking or clipping. However I seem to have fallen at the first hurdle.

I understand that I can use <mask> to leave parts of the image visible and remove everything else.

What I cannot see - either with <clip-path> or with <mask> - is how to remove parts of the image and leave everything else visible.

Here is the beginning of an image below:

<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     viewBox="0 0 420 420">

<defs>

</defs>

<rect x="0" y="0" width="420" height="420" />
<rect x="21" y="99" width="300" height="300" rx="15" ry="15" />

<g transform="rotate(-45 50 50)">
<rect x="-100" y="240" width="355" height="90" />
</g>

</svg>

What is the correct approach to removing the top-right corner of the box, beneath the 45-degree slanted rectangle, so that the dark red rectangle shows through from below?

N.B. I do mean remove and not just hide. I know I can fill the rectangle and it will hide the box-corner beneath.

Update 1

I have come up with "a solution" using <clip-path> which looks great:

<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     viewBox="0 0 420 420">

<defs>

<clipPath id="clip-corner">
<path d="M0,76 L274,76 L224,126 L306,209 L355,160 L355,420 L0,420 L0,76" />
</clipPath>

</defs>

<rect x="0" y="0" width="420" height="420" />
<rect x="21" y="99" width="300" height="300" rx="15" ry="15" />
<g transform="rotate(-45 50 50)">
<rect x="-100" y="240" width="355" height="90" />
</g>

</svg>

But... the problem is, this is how I did it. By drawing the following clip-path:

<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     viewBox="0 0 420 420">

<defs>

</defs>

<rect x="0" y="0" width="420" height="420" />
<path d="M0,76 L274,76 L224,126 L306,209 L355,160 L355,420 L0,420 L0,76" />
<rect x="21" y="99" width="300" height="300" rx="15" ry="15" />

</svg>

That's not how you're supposed to do it, is it?

Body:
In a mask, everything that should be visible should be white: make the background white. Everything that should be invisble should be black: make the slanted rectangle plus a wide enough stroke black.

Reuse the basic shapes with <use>, so that you only need to edit them in one place. Define them within <defs> and make sure no style is applied to them. Instead, apply the style to the <use> elements.

mask use:first-child {
    fill: rgb(255, 255, 255);
}

mask use:last-child {
    stroke: rgb(0, 0, 0);
    fill: rgb(0, 0, 0);
    stroke-width: 30;
}

.filled {
    fill: rgb(191, 0, 0);
}

.stroked {
    stroke: rgb(255,255,255);
    stroke-width: 10;
}

.masked {
     mask: url(#mask);
}

<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     viewBox="0 0 420 420">

  <defs>

    <rect id="back" x="0" y="0" width="420" height="420" />
    <rect id="slanted" transform="rotate(-45 50 50)"
          x="-100" y="240" width="355" height="90" />

    <mask id="mask">
      <use xlink:href="#back" />
      <use xlink:href="#slanted" />
    </mask>

  </defs>

  <use class="filled" xlink:href="#back" />

  <rect class="filled stroked masked"
        x="21" y="99" width="300" height="300" rx="15" ry="15" />

  <use class="filled stroked" xlink:href="#slanted" />

</svg>


问:
Regex to extract 3 digit number in an excel function
I need to extract a 3-digit number from text strings in an excel sheet.
I've written my custom function to return a substring based on a pattern, that's fine, it works. It's the pattern that's beating me.
So, examples could include:

Lorem ipsum dolor cc123 sit amet

Lorem ipsum dolor sit amet cc 123

Lorem ipsum c 123, dolor sit amet

I'm no expert in regex, but usually I'd use (?<=\D)\d{3}\b That works with all the tests I've tried but VBA doesn't seem to support (?<=x). Using just \D\d{3}\b and trimming the leading char works, but offends my senses.

I'm using the standard VBscript Regular Expressions 5.5 library.

The practical background to this is that I have a large worksheet that has a comments field on each line. Policy has been that users include their cost centre somewhere in this field. It can appear anywhere in the field, it's always a three-digit number, it is always followed by a word boundary and it is always preceded by a non-number char.

答:
you can go for a backreference solution:

```<code>\D(\d{3})\b
</code>```

if you are interested only in the 3 digits, you could use the regex described here-over and reuse the first capturing group \1 (might be $1 in VB)

Body:
you can go for a backreference solution:

\D(\d{3})\b

if you are interested only in the 3 digits, you could use the regex described here-over and reuse the first capturing group \1 (might be $1 in VB)


问:
Kotlin – String formatting
Kotlin has an excellent feature called string templates.

```<code>val i = 10
val s = "i = $i" // evaluates to "i = 10"
</code>```

But is it possible to have any formatting in the templates? For example, I would like to format Double in string templates in kotlin, at least to set a number of digits after a decimal separator:

```<code>val pi = 3.14159265358979323
val s = "pi = $pi??" // How to make it "pi = 3.14"?
</code>```

答:
Kotlin's String class has a format function now, which internally uses Java's String.format method:

```<code>/**
 * Uses this string as a format string and returns a string obtained by substituting the specified arguments,
 * using the default locale.
 */
@kotlin.internal.InlineOnly
public inline fun String.Companion.format(format: String, vararg args: Any?): String = java.lang.String.format(format, *args)
</code>```

Usage

```<code>val pi = 3.14159265358979323
val formatted = String.format("%.2f", pi) ;
println(formatted)
>>3.14
</code>```

ContentLicense: CC BY-SA 4.0

Title: Kotlin – String formatting

Body:
Kotlin has an excellent feature called string templates.

val i = 10
val s = "i = $i" // evaluates to "i = 10"

But is it possible to have any formatting in the templates? For example, I would like to format Double in string templates in kotlin, at least to set a number of digits after a decimal separator:

val pi = 3.14159265358979323
val s = "pi = $pi??" // How to make it "pi = 3.14"?

Body:
Kotlin's String class has a format function now, which internally uses Java's String.format method:

/**
 * Uses this string as a format string and returns a string obtained by substituting the specified arguments,
 * using the default locale.
 */
@kotlin.internal.InlineOnly
public inline fun String.Companion.format(format: String, vararg args: Any?): String = java.lang.String.format(format, *args)

Usage

val pi = 3.14159265358979323
val formatted = String.format("%.2f", pi) ;
println(formatted)
>>3.14


问:
Possibility of store object type for std::any
In c++17 we have the std::any which stores variable type of object in memory. Good part is I can create a vector of std::any to simulate a container for arbitrary type of object.

Whenever to query back the object from the container one will use  std::any_cast with the exact same type when calling std::make_any to create the any object. Here is the snippet of how I achieve this

```<code>#include <any>
#include <iostream>
#include <unordered_map>
#include <vector>
#include <set>

int main()
{
    /* create some objects */
    std::set<int> mySet = { 1, 2, 3 };
    std::vector<int> myVec = { 3, 4, 5 };
    std::unordered_map<int, std::vector<int>> myHash = { std::make_pair(1, myVec) };
    /* create any store */
    std::vector<std::any> anyStore;
    anyStore.push_back(std::make_any<decltype(mySet)>(mySet));
    anyStore.push_back(std::make_any<decltype(myVec)>(myVec));
    anyStore.push_back(std::make_any<decltype(myHash)>(myHash));
    /* get object back */
    auto newSet = std::any_cast<decltype(mySet)>(anyStore[0]);
    auto newVec = std::any_cast<decltype(myVec)>(anyStore[1]);
    auto newHash = std::any_cast<decltype(myHash)>(anyStore[2]);

    /* Question is can we store the decltype(mySet) in memory so that
     * it can be read back while query from the vector to do any_cast?
     */

    return 0;
}
</code>```

The question is as follows:
Is it possible to store the decltype(mySet) as run time variable so that we can use it in any_cast to auto resolve the type we want to get? I know probably you cannot store the type in memory since it is compile time variable, but is there workaround like using std::type_index or std::type_info to achieve goal?

Edit:

Per @KerrekSB 's request. Here is an example usage of this dynamic sized container of std::any to create a class with dynamic properties.

```<code>#include <any>
#include <iostream>
#include <unordered_map>
#include <vector>
#include <set>
#include <string>

class FooWithDynamic
{
public:
    FooWithDynamic() = default;

    template <class T>
    void RegisterProperty(const std::string &key, const T &obj)
    {
        m_store.emplace(key, std::make_any<T>(obj));
    }

    template <class T>
    T GetProperty(const std::string &key)
    {
        if (m_store.find(key) == m_store.end())
            throw;
        return std::any_cast<T>(m_store[key]);
    }
private:
    std::unordered_map<std::string, std::any> m_store;
};

int main()
{
    /* create some objects */
    FooWithDynamic foo;
    foo.RegisterProperty("mySet", std::set<int>{ 1, 2, 3 });
    foo.RegisterProperty("myVec", std::vector<int>{ 1, 2, 3 });
    foo.RegisterProperty("myHash", std::unordered_map<int, int>{ std::make_pair(1, 2) });
    /* query back object */
    auto mySet = foo.GetProperty<std::set<int>>("mySet");
    auto myVec = foo.GetProperty<std::vector<int>>("myVec");
    auto myHash = foo.GetProperty<std::unordered_map<int, int>>("myHash");
    return 0;
}
</code>```

Thanks everyone to let me know this is not possible because it is in contrast of C++'s static typed philosophy.

答:
Is it possible to store the decltype(mySet) as run time variable

No. C++ is a statically typed language. Types cannot be determined at runtime. The type of every expression, like the return value of a function that would return the value stored in the any, must be known at compile time.

That's precisely why you have to supply the type explicitly when you any_cast.

Body:
In c++17 we have the std::any which stores variable type of object in memory. Good part is I can create a vector of std::any to simulate a container for arbitrary type of object.

Whenever to query back the object from the container one will use  std::any_cast with the exact same type when calling std::make_any to create the any object. Here is the snippet of how I achieve this

#include <any>
#include <iostream>
#include <unordered_map>
#include <vector>
#include <set>

int main()
{
    /* create some objects */
    std::set<int> mySet = { 1, 2, 3 };
    std::vector<int> myVec = { 3, 4, 5 };
    std::unordered_map<int, std::vector<int>> myHash = { std::make_pair(1, myVec) };
    /* create any store */
    std::vector<std::any> anyStore;
    anyStore.push_back(std::make_any<decltype(mySet)>(mySet));
    anyStore.push_back(std::make_any<decltype(myVec)>(myVec));
    anyStore.push_back(std::make_any<decltype(myHash)>(myHash));
    /* get object back */
    auto newSet = std::any_cast<decltype(mySet)>(anyStore[0]);
    auto newVec = std::any_cast<decltype(myVec)>(anyStore[1]);
    auto newHash = std::any_cast<decltype(myHash)>(anyStore[2]);

    /* Question is can we store the decltype(mySet) in memory so that
     * it can be read back while query from the vector to do any_cast?
     */

    return 0;
}

The question is as follows:
Is it possible to store the decltype(mySet) as run time variable so that we can use it in any_cast to auto resolve the type we want to get? I know probably you cannot store the type in memory since it is compile time variable, but is there workaround like using std::type_index or std::type_info to achieve goal?

Edit:

Per @KerrekSB 's request. Here is an example usage of this dynamic sized container of std::any to create a class with dynamic properties.

#include <any>
#include <iostream>
#include <unordered_map>
#include <vector>
#include <set>
#include <string>

class FooWithDynamic
{
public:
    FooWithDynamic() = default;

    template <class T>
    void RegisterProperty(const std::string &key, const T &obj)
    {
        m_store.emplace(key, std::make_any<T>(obj));
    }

    template <class T>
    T GetProperty(const std::string &key)
    {
        if (m_store.find(key) == m_store.end())
            throw;
        return std::any_cast<T>(m_store[key]);
    }
private:
    std::unordered_map<std::string, std::any> m_store;
};

int main()
{
    /* create some objects */
    FooWithDynamic foo;
    foo.RegisterProperty("mySet", std::set<int>{ 1, 2, 3 });
    foo.RegisterProperty("myVec", std::vector<int>{ 1, 2, 3 });
    foo.RegisterProperty("myHash", std::unordered_map<int, int>{ std::make_pair(1, 2) });
    /* query back object */
    auto mySet = foo.GetProperty<std::set<int>>("mySet");
    auto myVec = foo.GetProperty<std::vector<int>>("myVec");
    auto myHash = foo.GetProperty<std::unordered_map<int, int>>("myHash");
    return 0;
}

Thanks everyone to let me know this is not possible because it is in contrast of C++'s static typed philosophy.


问:
JavaScript: Compressing object assignment for different cases
I'm trying to set the porperties of an object based on a specific case. I think the following code can be compressed and I'm looking for the best way to go about it. </p>

<p>NOTE: I have considered using a switch statement but it results in pretty much the same number of lines. </p>

```<code>let oNoificationData = {};
if (data.type === 'newUser') {
    oNotificationData = {
        title: `${data.user} is online!`,
        icon: `https://www.gravatar.com/avatar/${sHash}?d=mm`,
        body: 'A new user has come online',
    };
} else if (data.type === 'logoff') {
    oNotificationData = {
        title: `${data.user} has logged out!`,
        icon: `https://www.gravatar.com/avatar/${sHash}?d=mm`,
        body: 'A user has logged out'
    };
} else if (data.type === "newMsg") {
    oNotificationData = {
        title: `new message from ${data.user}`,
        icon: `https://www.gravatar.com/avatar/${sHash}?d=mm`,
        body: 'You have a new message!'
    };
} else if (data.type === "closeRoom") {
    oNotificationData = {
        title: `${data.user} has left the chat`,
        icon: `https://www.gravatar.com/avatar/${sHash}?d=mm`,
        body: 'Chat user has left'
    };
}
</code>```

答:
So use an object

```<code>var notifications = {
  newUser : {
    title: `${data.user} is online!`,
    icon:`https://www.gravatar.com/avatar/${sHash}?d=mm`,
    body: 'A new user has come online',
  },
  logoff : {
    title: `${data.user} has logged out!`,
    icon:`https://www.gravatar.com/avatar/${sHash}?d=mm`,
    body: 'A user has logged out'
  }
}
</code>```

and it is just

```<code>var obj = notifications[data.type];
</code>```

Body:
I'm trying to set the porperties of an object based on a specific case. I think the following code can be compressed and I'm looking for the best way to go about it.

NOTE: I have considered using a switch statement but it results in pretty much the same number of lines.

let oNoificationData = {};
if (data.type === 'newUser') {
    oNotificationData = {
        title: `${data.user} is online!`,
        icon: `https://www.gravatar.com/avatar/${sHash}?d=mm`,
        body: 'A new user has come online',
    };
} else if (data.type === 'logoff') {
    oNotificationData = {
        title: `${data.user} has logged out!`,
        icon: `https://www.gravatar.com/avatar/${sHash}?d=mm`,
        body: 'A user has logged out'
    };
} else if (data.type === "newMsg") {
    oNotificationData = {
        title: `new message from ${data.user}`,
        icon: `https://www.gravatar.com/avatar/${sHash}?d=mm`,
        body: 'You have a new message!'
    };
} else if (data.type === "closeRoom") {
    oNotificationData = {
        title: `${data.user} has left the chat`,
        icon: `https://www.gravatar.com/avatar/${sHash}?d=mm`,
        body: 'Chat user has left'
    };
}

Body:
So use an object

var notifications = {
  newUser : {
    title: `${data.user} is online!`,
    icon:`https://www.gravatar.com/avatar/${sHash}?d=mm`,
    body: 'A new user has come online',
  },
  logoff : {
    title: `${data.user} has logged out!`,
    icon:`https://www.gravatar.com/avatar/${sHash}?d=mm`,
    body: 'A user has logged out'
  }
}

and it is just

var obj = notifications[data.type];


问:
Operate on column with dplyr given only partial column name
I have a function that processes a number of different data frames, using `dplyr, like this:

```<code>some_function <- function(some_data){

    processed_data = some_data %>%
        group_by(session_id) %>%
        arrange(some_date) %>%
        mutate(n = row_number()) %>%
        filter(n == 1) %>%
        select(-n)
}
</code>```

The data frames passed to the function each share a few key column names but the others differ. In this function, I'm generally just dealing with shared column names, so it is simple to refer to them.

The exception is wanting to arrange() by some variable that differs systematically across data frames. e.g. it might be a column that is named a_date in one data frame but b_date in another.

So I want to operate on the column name that ends with _date. There are ways to operate with string representations of entire column names, but it is trickier to use some sort of matching. The select() function in dplyr has the ability to select columns using functions like ends_with() and so on. But how can this be achieved within other dplyr verbs, such as arrange()?

答:
You can use the scoped verb arrange_at; for your case, use arrange_at with vars + select helper functions,  %>% arrange_at(vars(ends_with('_date'))).

Example:

```<code>df <- data.frame(a_date = c(3,1,4,4), b_date = c(1,3,4,2))
</code>```

Arrange on column a_date:

```<code>arrange_at(df, vars(starts_with('a')))
#  a_date b_date
#1      1      3
#2      3      1
#3      4      4
#4      4      2
</code>```

Arrange on column b_date:

```<code>arrange_at(df, vars(starts_with('b')))
#  a_date b_date
#1      3      1
#2      4      2
#3      1      3
#4      4      4
</code>```

Arrange on column a_date then b_date:

```<code>arrange_at(df, vars(ends_with('date')))
#  a_date b_date
#1      1      3
#2      3      1
#3      4      2
#4      4      4
</code>```

Body:
I have a function that processes a number of different data frames, using `dplyr, like this:

some_function <- function(some_data){

    processed_data = some_data %>%
        group_by(session_id) %>%
        arrange(some_date) %>%
        mutate(n = row_number()) %>%
        filter(n == 1) %>%
        select(-n)
}

The data frames passed to the function each share a few key column names but the others differ. In this function, I'm generally just dealing with shared column names, so it is simple to refer to them.

The exception is wanting to arrange() by some variable that differs systematically across data frames. e.g. it might be a column that is named a_date in one data frame but b_date in another.

So I want to operate on the column name that ends with _date. There are ways to operate with string representations of entire column names, but it is trickier to use some sort of matching. The select() function in dplyr has the ability to select columns using functions like ends_with() and so on. But how can this be achieved within other dplyr verbs, such as arrange()?

Body:
You can use the scoped verb arrange_at; for your case, use arrange_at with vars + select helper functions,  %>% arrange_at(vars(ends_with('_date'))).

Example:

df <- data.frame(a_date = c(3,1,4,4), b_date = c(1,3,4,2))

Arrange on column a_date:

arrange_at(df, vars(starts_with('a')))
#  a_date b_date
#1      1      3
#2      3      1
#3      4      4
#4      4      2

Arrange on column b_date:

arrange_at(df, vars(starts_with('b')))
#  a_date b_date
#1      3      1
#2      4      2
#3      1      3
#4      4      4

Arrange on column a_date then b_date:

arrange_at(df, vars(ends_with('date')))
#  a_date b_date
#1      1      3
#2      3      1
#3      4      2
#4      4      4


问:
PHP users local time
Hey Stackfriends =P
I know about the time() and the date() functuions,
but what I want to achieve is that the user from china gets another time shown than the user from France.
I cannot use JavaScript, because I am also using the local time for some calculations.</p>

答:
The only thing that should stop you from using javascript is if a) you're just serving an API and have no control over page content; or b) client has javascript blocked anyway.  Via javascript is the most reliable method, short of simply prompting the user to enter their timezone.

Cookies or ajax will work.  For the easier cookie way, put this javascript in your head section on any page to add a cookie...

```<code><script>

d = new Date;
gmtoffset = d.getTimezoneOffset() / 60;
document.cookie = 'gmtoffset=' + gmtoffset;

</script>
</code>```

Then in your PHP scripts, read $_COOKIE['gmtoffset'] to get their timezone relative to GMT.

IMHO, client's time w/ timezone should've been an industry-wide standard request header.

Edit: removed 'expires' date from cookie example as it may cause problems after Jan 1, 2012.

ContentLicense: CC BY-SA 2.5

Title: PHP users local time

Body:
The only thing that should stop you from using javascript is if a) you're just serving an API and have no control over page content; or b) client has javascript blocked anyway.  Via javascript is the most reliable method, short of simply prompting the user to enter their timezone.

Cookies or ajax will work.  For the easier cookie way, put this javascript in your head section on any page to add a cookie...

<script>

d = new Date;
gmtoffset = d.getTimezoneOffset() / 60;
document.cookie = 'gmtoffset=' + gmtoffset;

</script>

Then in your PHP scripts, read $_COOKIE['gmtoffset'] to get their timezone relative to GMT.

IMHO, client's time w/ timezone should've been an industry-wide standard request header.

Edit: removed 'expires' date from cookie example as it may cause problems after Jan 1, 2012.


问:
JAVAFX FXML: dynamic ImageView in dynamically created tabs not displaying
I am making a java app that will display ski resort weather data. Upon user login it creates a scene that has a Tab Pane with dynamically created tabs, one for each of the users favorited resorts. All of the data is being stored in a mysql database.

I am able to successfully create all the the tabs for each user, now I am trying to load an image associated with each resort into each tab being loaded, using an ImageView object. I have no Idea why but I can not get any images to show up in any of the tabs. Ideally I want to take the name of the image file, that I have stored in my database, create a the file path string and load the image. I have also tried hardcoding the file path, and setting the image in scene builder but neither work.

My favorites controller that has the tabPane and dynamically creates tabs

```<code>@FXML
private TabPane tabPane;
private Tab myTab;

/**
 * Initializes the controller class.
 * @param url
 * @param rb
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    try {
        DBConnect dbConnection = new DBConnect();
        // GET USER ID, THEN ARRAY OF THE ID'S FAVORITE RESORTS
        int id = LoggedInUser.id;
        //string array of the names of the users favorited resorts
        String[] resorts = dbConnection.getFavorites(id);

        // DYNAMICALLY CREATE TABS BASED ON THE NUMBER OF FAVORITES FOR THE ACTIVE USER.
        for(int i = 0; i < resorts.length; i++) {
            FXMLLoader loader = new FXMLLoader();
            ResortTab newTabController = new ResortTab(resorts[i]);
            loader.setLocation(getClass().getResource("ResortTab.fxml"));
            loader.setController(newTabController);

            Parent parent = loader.load();
            myTab = new Tab(resorts[i]);
            myTab.setContent(parent);
            tabPane.getTabs().add(myTab);
        }

    } catch (SQLException | ClassNotFoundException | IOException ex) {
        Logger.getLogger(FavoritesController.class.getName()).log(Level.SEVERE, null, ex);
    }

}
</code>```

ResortTab, controller for dynamically created tabs

```<code>public class ResortTab implements Initializable{
String name;
DBConnect dbConnection;
private Image image;
private String resort;

@FXML
private Label label;
@FXML
private ImageView logo;

// CONSTRUCTOR
public ResortTab(String name) throws SQLException, ClassNotFoundException {
    resort = name;
    this.name = name;
    // GET LOGO FILE PATH FROM DATABASE AND LOAD IT TO THE SCENE
    dbConnection = new DBConnect();
    //returns file path thats stored in the database example: images/Logos/resortname.jpg
    String path = dbConnection.getLogoPath(name);

    System.out.println("'src/jesnwdskiweather/" + path + "'");
    System.out.println("Working Directory = " + System.getProperty("user.dir"));

    // Create full path
    String full_path = "file:'/src/jesnwdskiweather/" + path + "'";

    // String used to test by hardcoding
    String testPath = "file:'src/jesnwdskiweather/images/Logos/RevelstokeMountain.png'";

    System.out.println(full_path); //prints correct file path
    image = new Image(full_path);
    if(image == null){
        System.out.println("Image is null"); //does not print
    }

}

@Override
public void initialize(URL location, ResourceBundle resources) {
    logo.setImage(image);
    logo.setCache(true);
    label.setText(name);
}
</code>```

ResortTab.fxml

```<code><?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.image.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0"     xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
  <children>
     <Label fx:id="label" layoutX="342.0" layoutY="112.0" text="Label" />
     <ImageView fx:id="logo" fitHeight="150.0" fitWidth="200.0" pickOnBounds="true" preserveRatio="true" />
  </children>
</AnchorPane>
</code>```

答:
I tried to copy your code and make some changes to find ther error and i find that your error is here String full_path = "file:'/src/jesnwdskiweather/" + path + "'"; and you don't need adding /src/ to your path see the description

False path :

True path :

Try change the full path to  String full_path = "jesnwdskiweather/" + path";

Source code with some changes :

```<code>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package stackoverflow;

import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

/**
 * FXML Controller class
 *
 * @author Electron
 */
public class ResortTab implements Initializable {

    String name;
    private Image image;
    private String resort;
    @FXML
    private Label label;
    @FXML
    private ImageView logo;

// CONSTRUCTOR
    public ResortTab(String name) throws SQLException, ClassNotFoundException {
        resort = name;
        this.name = name;
        // GET LOGO FILE PATH FROM DATABASE AND LOAD IT TO THE SCENE
      //  dbConnection = new DBConnect();
        //returns file path thats stored in the database example: images/Logos/resortname.jpg
        String path = "1487868084_39_Email_Marketing.png";

        System.out.println("'src/jesnwdskiweather/" + path + "'");
        System.out.println("Working Directory = " + System.getProperty("user.dir"));

        // Create full path
        String full_path = "jesnwdskiweather/" + path +"";

        // String used to test by hardcoding
        String testPath = "file:'src/jesnwdskiweather/images/Logos/RevelstokeMountain.png'";

        System.out.println(full_path); //prints correct file path
        image = new Image(full_path);
        if (image == null) {
            System.out.println("Image is null"); //does not print
        }

    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        logo.setImage(image);
        logo.setCache(true);
        label.setText(name);
    }
}
</code>```

Note : Your code add an image into each content of tab note into tab ,if you need to add an image into each tab use setGraphic(node);.

Body:
I am making a java app that will display ski resort weather data. Upon user login it creates a scene that has a Tab Pane with dynamically created tabs, one for each of the users favorited resorts. All of the data is being stored in a mysql database.

I am able to successfully create all the the tabs for each user, now I am trying to load an image associated with each resort into each tab being loaded, using an ImageView object. I have no Idea why but I can not get any images to show up in any of the tabs. Ideally I want to take the name of the image file, that I have stored in my database, create a the file path string and load the image. I have also tried hardcoding the file path, and setting the image in scene builder but neither work.

My favorites controller that has the tabPane and dynamically creates tabs

@FXML
private TabPane tabPane;
private Tab myTab;

/**
 * Initializes the controller class.
 * @param url
 * @param rb
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    try {
        DBConnect dbConnection = new DBConnect();
        // GET USER ID, THEN ARRAY OF THE ID'S FAVORITE RESORTS
        int id = LoggedInUser.id;
        //string array of the names of the users favorited resorts
        String[] resorts = dbConnection.getFavorites(id);

        // DYNAMICALLY CREATE TABS BASED ON THE NUMBER OF FAVORITES FOR THE ACTIVE USER.
        for(int i = 0; i < resorts.length; i++) {
            FXMLLoader loader = new FXMLLoader();
            ResortTab newTabController = new ResortTab(resorts[i]);
            loader.setLocation(getClass().getResource("ResortTab.fxml"));
            loader.setController(newTabController);

            Parent parent = loader.load();
            myTab = new Tab(resorts[i]);
            myTab.setContent(parent);
            tabPane.getTabs().add(myTab);
        }

    } catch (SQLException | ClassNotFoundException | IOException ex) {
        Logger.getLogger(FavoritesController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

ResortTab, controller for dynamically created tabs

public class ResortTab implements Initializable{
String name;
DBConnect dbConnection;
private Image image;
private String resort;

@FXML
private Label label;
@FXML
private ImageView logo;

// CONSTRUCTOR
public ResortTab(String name) throws SQLException, ClassNotFoundException {
    resort = name;
    this.name = name;
    // GET LOGO FILE PATH FROM DATABASE AND LOAD IT TO THE SCENE
    dbConnection = new DBConnect();
    //returns file path thats stored in the database example: images/Logos/resortname.jpg
    String path = dbConnection.getLogoPath(name);

    System.out.println("'src/jesnwdskiweather/" + path + "'");
    System.out.println("Working Directory = " + System.getProperty("user.dir"));

    // Create full path
    String full_path = "file:'/src/jesnwdskiweather/" + path + "'";

    // String used to test by hardcoding
    String testPath = "file:'src/jesnwdskiweather/images/Logos/RevelstokeMountain.png'";

    System.out.println(full_path); //prints correct file path
    image = new Image(full_path);
    if(image == null){
        System.out.println("Image is null"); //does not print
    }

}

@Override
public void initialize(URL location, ResourceBundle resources) {
    logo.setImage(image);
    logo.setCache(true);
    label.setText(name);
}

ResortTab.fxml

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.image.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0"     xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
  <children>

     <ImageView fx:id="logo" fitHeight="150.0" fitWidth="200.0" pickOnBounds="true" preserveRatio="true" />
  </children>
</AnchorPane>

Body:
I tried to copy your code and make some changes to find ther error and i find that your error is here String full_path = "file:'/src/jesnwdskiweather/" + path + "'"; and you don't need adding /src/ to your path see the description

False path :

True path :

Try change the full path to  String full_path = "jesnwdskiweather/" + path";

Source code with some changes :

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package stackoverflow;

import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

/**
 * FXML Controller class
 *
 * @author Electron
 */
public class ResortTab implements Initializable {

    String name;
    private Image image;
    private String resort;
    @FXML
    private Label label;
    @FXML
    private ImageView logo;

// CONSTRUCTOR
    public ResortTab(String name) throws SQLException, ClassNotFoundException {
        resort = name;
        this.name = name;
        // GET LOGO FILE PATH FROM DATABASE AND LOAD IT TO THE SCENE
      //  dbConnection = new DBConnect();
        //returns file path thats stored in the database example: images/Logos/resortname.jpg
        String path = "1487868084_39_Email_Marketing.png";

        System.out.println("'src/jesnwdskiweather/" + path + "'");
        System.out.println("Working Directory = " + System.getProperty("user.dir"));

        // Create full path
        String full_path = "jesnwdskiweather/" + path +"";

        // String used to test by hardcoding
        String testPath = "file:'src/jesnwdskiweather/images/Logos/RevelstokeMountain.png'";

        System.out.println(full_path); //prints correct file path
        image = new Image(full_path);
        if (image == null) {
            System.out.println("Image is null"); //does not print
        }

    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        logo.setImage(image);
        logo.setCache(true);
        label.setText(name);
    }
}

Note : Your code add an image into each content of tab note into tab ,if you need to add an image into each tab use setGraphic(node);.


问:
PHP taking extra time when making another connection to MySQL for logging purposes
I have various PHP scripts which run all day via cron jobs and as more users use my application, the cron jobs are taking longer. These jobs started taking twice as long when I moved from file logging to database logging because (I believe) the logging function takes time to make a new connection to the database - about one second each.

My structure is as follows. The scripts run by cron jobs look like this:

```<code><?php
require("db-helper-class.php");
require("action-class.php");

$con = new DB();
$action = new ActionClass($con);

$action->method_1();
</code>```

The "Action Classes" look like this:

```<code><?php
include "logging-functions.php";

class ActionClass {

    private $db;

    public function __construct(DB $pdo) {
        //connect to database
        $this->db = $pdo;
    }

    public function method_1() {
        //do stuff like a database action
        $sql = "...";
        $this->db->$query($sql)

        //log result
        logSomething($vars);

        //do another database action
        $sql = "...";
        $this->db->$query($sql)

        //log result
        logSomething($vars);

    }
...
</code>```

And the "logging-functions.php" looks like this:

```<code><?php
require_once("db-helper-class.php");

function logSomething($input) {
    $logDBcon = new DB();
    $sql = "...";
    $logDBcon->query($sql);
    ...
}
</code>```

So as you can see, when logging, multiple new connections are happening. I have 2 main questions:

Am I right in saying that my extra logging connections are a slow point because of the new connection.

Would I be right in saying that I will lose the lastInsertId() if I included the logging in the original connection?

And to sneak in a third question, is this design even best practice?

答:
yes and NO. Making a connection itself, sure, takes time but that's so insignificant so you shouldn't even bother. What makes your application slow would be if you've got really slow queries.

The question is not clear. If you run get insert id command against a connection it will return you last inserted id for that connection. Read: those 2 connections are isolated from each other.

I'd say no since you endangered to open/close (btw, you should be mindful about closing connections) a ton of connections whenever you call that logging method. I'd open up a connection once and shut that down as soon as the program is finished.

To sneak a side-note: to contemplate about best practices you should create a new question on SO since those kind of questions are usually bloated. So this question is, indeed, sneaky.

Body:
I have various PHP scripts which run all day via cron jobs and as more users use my application, the cron jobs are taking longer. These jobs started taking twice as long when I moved from file logging to database logging because (I believe) the logging function takes time to make a new connection to the database - about one second each.

My structure is as follows. The scripts run by cron jobs look like this:

<?php
require("db-helper-class.php");
require("action-class.php");

$con = new DB();
$action = new ActionClass($con);

$action->method_1();

The "Action Classes" look like this:

<?php
include "logging-functions.php";

class ActionClass {

    private $db;

    public function __construct(DB $pdo) {
        //connect to database
        $this->db = $pdo;
    }

    public function method_1() {
        //do stuff like a database action
        $sql = "...";
        $this->db->$query($sql)

        //log result
        logSomething($vars);

        //do another database action
        $sql = "...";
        $this->db->$query($sql)

        //log result
        logSomething($vars);

    }
...

And the "logging-functions.php" looks like this:

<?php
require_once("db-helper-class.php");

function logSomething($input) {
    $logDBcon = new DB();
    $sql = "...";
    $logDBcon->query($sql);
    ...
}

So as you can see, when logging, multiple new connections are happening. I have 2 main questions:

Am I right in saying that my extra logging connections are a slow point because of the new connection.

Would I be right in saying that I will lose the lastInsertId() if I included the logging in the original connection?

And to sneak in a third question, is this design even best practice?


问:
Backup a mysql [xampp] database in java
So I am still learning programming, I am creating a simple application that can backup a database but the problem is when I click the button for backup, nothing happens, it does not even display the "can't create backup". I am using xampp, in case that is relevant. I have zero idea as to why is it is not working, and I am really curios what is the reason behind it, any help will be greatly appreciated.</p>

```<code>...
String path = null;
String filename;

//choose where to backup

 private void jButtonLocationActionPerformed(java.awt.event.ActionEvent evt)   {
    JFileChooser fc = new JFileChooser();
    fc.showOpenDialog(this);
    String date = new SimpleDateFormat("MM-dd-yyy").format(new Date());

    try {
        File f = fc.getSelectedFile();
        path = f.getAbsolutePath();
        path = path.replace('\\', '/');
        path = path+"_"+date+".sql";
        jTextField1.setText(path);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

//backup
private void jButtonBackUpActionPerformed(java.awt.event.ActionEvent evt) {
    Process p = null;

    try{
        Runtime runtime = Runtime.getRuntime();

        p=runtime.exec("C:/xampp/mysq/bin/mysqldump -u root --add-drop-database -B capstone -r "+path);

        int processComplete = p.waitFor();
        if (processComplete==0) {
            jLabel1.setText("Backup Created Success!");
        } else {
            jLabel1.setText("Can't create backup.");
        }
    } catch (Exception e) {

    }

}
</code>```

答:
I found the underlying problem, thanks to stan. It was a typo problem, instead of "mysql", I have put "mysq" thank you guys!</p>

```<code>  java.io.IOException: Cannot run program "C:/xampp/mysq/bin/mysqldump.exe": CreateProcess error=2, The system cannot find the file specified
</code>```

Title: Backup a mysql [xampp] database in java

Body:
So I am still learning programming, I am creating a simple application that can backup a database but the problem is when I click the button for backup, nothing happens, it does not even display the "can't create backup". I am using xampp, in case that is relevant. I have zero idea as to why is it is not working, and I am really curios what is the reason behind it, any help will be greatly appreciated.

...
String path = null;
String filename;

//choose where to backup

 private void jButtonLocationActionPerformed(java.awt.event.ActionEvent evt)   {
    JFileChooser fc = new JFileChooser();
    fc.showOpenDialog(this);
    String date = new SimpleDateFormat("MM-dd-yyy").format(new Date());

    try {
        File f = fc.getSelectedFile();
        path = f.getAbsolutePath();
        path = path.replace('\\', '/');
        path = path+"_"+date+".sql";
        jTextField1.setText(path);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

//backup
private void jButtonBackUpActionPerformed(java.awt.event.ActionEvent evt) {
    Process p = null;

    try{
        Runtime runtime = Runtime.getRuntime();

        p=runtime.exec("C:/xampp/mysq/bin/mysqldump -u root --add-drop-database -B capstone -r "+path);

        int processComplete = p.waitFor();
        if (processComplete==0) {
            jLabel1.setText("Backup Created Success!");
        } else {
            jLabel1.setText("Can't create backup.");
        }
    } catch (Exception e) {

    }

}

Body:
I found the underlying problem, thanks to stan. It was a typo problem, instead of "mysql", I have put "mysq" thank you guys!

  java.io.IOException: Cannot run program "C:/xampp/mysq/bin/mysqldump.exe": CreateProcess error=2, The system cannot find the file specified


问:
Getting error while trying to serialize int
I am trying to serialize my integer but i get the following error:

InvalidCastException: Cannot cast from source type to destination type.

SaveLoad.Load() (at Assets/SaveLoad.cs:24) refers to another
script that just loads it on awake loadgame.Awake() (at
Assets/loadgame.cs:8) refers to

```<code>StatContainer.totalcoins = (int)bf.Deserialize(file);
</code>```

I am new to data serialization can someone explain where my mistake is ?

```<code>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public static class SaveLoad {
//public static List<StatContainer> savedGames = new List<StatContainer>();

//it's static so we can call it from anywhere
public static void Save() {
    //SaveLoad.savedGames.Add(StatContainer.current);
    BinaryFormatter bf = new BinaryFormatter();
    //Application.persistentDataPath is a string, so if you wanted you can put that into debug.log if you want to know where save games are located
    FileStream file = File.Create (Application.persistentDataPath + "/savedGames.gd"); //you can call it anything you want
    bf.Serialize(file, StatContainer.current);
    file.Close();
}

public static void Load() {
    if(File.Exists(Application.persistentDataPath + "/savedGames.gd")) {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Open(Application.persistentDataPath + "/savedGames.gd", FileMode.Open);
        StatContainer.totalcoins = (int)bf.Deserialize(file);
        file.Close();
        Debug.Log ("Loaded");
    }
}
}
</code>```

答: Call Debug.Log(bf.Deserialize(file)); to see what kind of object it's returning, because it's obviously not an int.

Body:
I am trying to serialize my integer but i get the following error:

InvalidCastException: Cannot cast from source type to destination type.

SaveLoad.Load() (at Assets/SaveLoad.cs:24) refers to another
script that just loads it on awake loadgame.Awake() (at
Assets/loadgame.cs:8) refers to

StatContainer.totalcoins = (int)bf.Deserialize(file);

I am new to data serialization can someone explain where my mistake is ?

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public static class SaveLoad {
//public static List<StatContainer> savedGames = new List<StatContainer>();

//it's static so we can call it from anywhere
public static void Save() {
    //SaveLoad.savedGames.Add(StatContainer.current);
    BinaryFormatter bf = new BinaryFormatter();
    //Application.persistentDataPath is a string, so if you wanted you can put that into debug.log if you want to know where save games are located
    FileStream file = File.Create (Application.persistentDataPath + "/savedGames.gd"); //you can call it anything you want
    bf.Serialize(file, StatContainer.current);
    file.Close();
}

public static void Load() {
    if(File.Exists(Application.persistentDataPath + "/savedGames.gd")) {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Open(Application.persistentDataPath + "/savedGames.gd", FileMode.Open);
        StatContainer.totalcoins = (int)bf.Deserialize(file);
        file.Close();
        Debug.Log ("Loaded");
    }
}
}


Title: How to visualize images in tensorboard using tf.summary.image() in [batch, channels, width, height] (NCHW) order?

Body:
First, I want to reshape the 2-D to 4-D tensor using tf.reshape().

I thought tf.reshape() will transform

[batch, array] -> [batch, width, height, channels] (NHWC) order

but in practice it transformed

[batch, array] -> [batch, channels, width, height] (NCHW) order

Example:

a = np.array([[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]])
print(a.shape)

# [batch_size, channels, height, width]
b = sess.run(tf.reshape(a, shape=[2, 3, 4, 4]))

# [batch_size, height, width, channels]
c = sess.run(tf.reshape(a, shape=[2, 4, 4, 3]))

print(b)
print('*******')
print(c)

The result was:

(2, 48)
[[[[ 1  2  3  4]
   [ 5  6  7  8]
   [ 9 10 11 12]
   [13 14 15 16]]

  [[ 1  2  3  4]
   [ 5  6  7  8]
   [ 9 10 11 12]
   [13 14 15 16]]

  [[ 1  2  3  4]
   [ 5  6  7  8]
   [ 9 10 11 12]
   [13 14 15 16]]]

 [[[ 1  2  3  4]
   [ 5  6  7  8]
   [ 9 10 11 12]
   [13 14 15 16]]

  [[ 1  2  3  4]
   [ 5  6  7  8]
   [ 9 10 11 12]
   [13 14 15 16]]

  [[ 1  2  3  4]
   [ 5  6  7  8]
   [ 9 10 11 12]
   [13 14 15 16]]]]
*******
[[[[ 1  2  3]
   [ 4  5  6]
   [ 7  8  9]
   [10 11 12]]

  [[13 14 15]
   [16  1  2]
   [ 3  4  5]
   [ 6  7  8]]

  [[ 9 10 11]
   [12 13 14]
   [15 16  1]
   [ 2  3  4]]

  [[ 5  6  7]
   [ 8  9 10]
   [11 12 13]
   [14 15 16]]]

 [[[ 1  2  3]
   [ 4  5  6]
   [ 7  8  9]
   [10 11 12]]

  [[13 14 15]
   [16  1  2]
   [ 3  4  5]
   [ 6  7  8]]

  [[ 9 10 11]
   [12 13 14]
   [15 16  1]
   [ 2  3  4]]

  [[ 5  6  7]
   [ 8  9 10]
   [11 12 13]
   [14 15 16]]]]

So, I changed data_format='channels_first' for conv and pooling layers to using the reshaped tensor in NCHW order. In fact, the training was good. --verbose: it gave better result, as mention by @mrry in here, and I think it could be understandable because NCHW is the default order of cuDNN.

However, I can not add image to summary using tf.summary.image(), which is documented here, because the required tensor shape should be in [batch_size, height, width, channels] order.

Moreover, if I train and visualize the input images in [batch, width, height, channels] order, it represented incorrect images.

And I worth to mention that, the training result was not as good as using [batch, channels, width, height] order.

There are several questions:

1. Why tf.reshape() transform [batch , array] -> (NCHW) order instead of (NHWC) order ? I tested with both tf CPU and GPU, same result. I also used np.reshape(), also same result. (This's why I think I could misunderstand something here)

2. How can I visualize images in tensorboard using tf.summary.image() in (NCHW) order? (question #2 solved using advice from @Maosi Chen. Thanks)

I've trained the model on GPU (version 1.4), the images are from CIFAR-10 dataset.

Thanks

Body:
You can reorder the dimensions by tf.transpose (https://www.tensorflow.org/api_docs/python/tf/transpose).

Note that perm elements are the dimension indices of the source tensor (a)

import tensorflow as tf
import numpy as np

sess = tf.InteractiveSession()

a = np.array([[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]])
print(a.shape)

# [batch_size, channels, height, width]
b = sess.run(tf.reshape(a, shape=[2, 3, 4, 4]))

# [batch_size, height, width, channels]
c = sess.run(tf.transpose(b, perm=[0, 2, 3, 1]))

print(b)
print('*******')
print(c)

Results:

(2, 48) [[[[ 1  2  3  4]    [ 5  6  7  8]    [ 9 10 11 12]    [13 14 15 16]]

  [[ 1  2  3  4]    [ 5  6  7  8]    [ 9 10 11 12]    [13 14 15 16]]

  [[ 1  2  3  4]    [ 5  6  7  8]    [ 9 10 11 12]    [13 14 15 16]]]

 [[[ 1  2  3  4]    [ 5  6  7  8]    [ 9 10 11 12]    [13 14 15 16]]

  [[ 1  2  3  4]    [ 5  6  7  8]    [ 9 10 11 12]    [13 14 15 16]]

  [[ 1  2  3  4]    [ 5  6  7  8]    [ 9 10 11 12]    [13 14 15 16]]]]
******* [[[[ 1  1  1]    [ 2  2  2]    [ 3  3  3]    [ 4  4  4]]

  [[ 5  5  5]    [ 6  6  6]    [ 7  7  7]    [ 8  8  8]]

  [[ 9  9  9]    [10 10 10]    [11 11 11]    [12 12 12]]

  [[13 13 13]    [14 14 14]    [15 15 15]    [16 16 16]]]

 [[[ 1  1  1]    [ 2  2  2]    [ 3  3  3]    [ 4  4  4]]

  [[ 5  5  5]    [ 6  6  6]    [ 7  7  7]    [ 8  8  8]]

  [[ 9  9  9]    [10 10 10]    [11 11 11]    [12 12 12]]

  [[13 13 13]    [14 14 14]    [15 15 15]    [16 16 16]]]]


问:
How to plot keys and values from dictionary in histogram
I need to plot a histogram with the following dictionary

```<code>x = {5:289, 8:341, 1:1565, 4:655, 2:1337, 9:226, 7:399, 3:967, 6:405}
</code>```

I need first keys be ordered from 1 to 9. Then the values will be plotted in the histogram, showing a maximum probability of 1.0. I have tried the following (plus other stuff).

```<code>import matplotlib.pyplot as plt
import numpy as np

plt.hist(x.keys(), x.values(), color='g', label = "Real distribution")
plt.show()
</code>```

Or

```<code>plt.hist (x, bins = np.arange(9), color = 'g', label = "Real distribution")
plt.show()
</code>```

Or

```<code>fsn_count_ = sorted(fsn_count)

plt.hist (fsn_count_, bins = np.arange(9), color = 'b', label = "Real distribution")
plt.plot ([0] + bf, color = 'g', label = "Benford Model")
plt.xlabel ('Significant number')
plt.ylabel ('Percentage')
plt.xlim (1,9)
plt.ylim (0,1)
plt.legend (bbox_to_anchor = (1, 1), loc="upper right", borderaxespad=0.)
plt.savefig (country_ + '.png')
plt.show ()
plt.clf ()

distribution_sum = sum(bf)
print('The sum of percentage distribution is:', distribution_sum)
</code>```

答:
Sort your data before plotting:

```<code>import matplotlib.pyplot as plt
import numpy as np
x = {5:289, 8:341, 1:1565, 4:655, 2:1337, 9:226, 7:399, 3:967, 6:405}
new_x = sorted(x.items(), key=lambda x:x[0])
plt.hist([i[-1] for i in new_x], normed=True, bins=len(new_x), color='g', label = "Real distribution")
plt.show()
</code>```

Body:
I need to plot a histogram with the following dictionary

x = {5:289, 8:341, 1:1565, 4:655, 2:1337, 9:226, 7:399, 3:967, 6:405}

I need first keys be ordered from 1 to 9. Then the values will be plotted in the histogram, showing a maximum probability of 1.0. I have tried the following (plus other stuff).

import matplotlib.pyplot as plt
import numpy as np

plt.hist(x.keys(), x.values(), color='g', label = "Real distribution")
plt.show()

Or

plt.hist (x, bins = np.arange(9), color = 'g', label = "Real distribution")
plt.show()

Or

fsn_count_ = sorted(fsn_count)

plt.hist (fsn_count_, bins = np.arange(9), color = 'b', label = "Real distribution")
plt.plot ([0] + bf, color = 'g', label = "Benford Model")
plt.xlabel ('Significant number')
plt.ylabel ('Percentage')
plt.xlim (1,9)
plt.ylim (0,1)
plt.legend (bbox_to_anchor = (1, 1), loc="upper right", borderaxespad=0.)
plt.savefig (country_ + '.png')
plt.show ()
plt.clf ()

distribution_sum = sum(bf)
print('The sum of percentage distribution is:', distribution_sum)

Body:
Sort your data before plotting:

import matplotlib.pyplot as plt
import numpy as np
x = {5:289, 8:341, 1:1565, 4:655, 2:1337, 9:226, 7:399, 3:967, 6:405}
new_x = sorted(x.items(), key=lambda x:x[0])
plt.hist([i[-1] for i in new_x], normed=True, bins=len(new_x), color='g', label = "Real distribution")
plt.show()


问:
JavaFX - Issue when including another fxml to a border pane center of a main fxml
I'm trying to include an additional fxml in a main fxml, border pane center. When I do this, the fxml gets included and shows in the center, but the fxml does not occupy the full width and height of the main fxml window.

In the SceneBuilder, if I add the TableView in the center of the borderpane, it acts as it should. Only when I include the fxml via code it does not.

Please help, what am I missing? Any help will be appreciated!

This is what I need:

This is what I get:

Main FXML:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.effect.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>

<TabPane fx:id="TabPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="800.0" prefWidth="1300.0" tabClosingPolicy="UNAVAILABLE" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
  <tabs>
      <Tab fx:id="lecturersTab" closable="false" text="Lecturers">
         <content>
            <BorderPane prefHeight="200.0" prefWidth="200.0">

                  <TableView prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
                    <columns>
                      <TableColumn prefWidth="75.0" text="C1" />
                      <TableColumn prefWidth="75.0" text="C2" />
                    </columns>
                  </TableView>

            </BorderPane>
         </content>
      </Tab>
      <Tab fx:id="membersTab" closable="false" text="Members">
        <content>
            <BorderPane prefHeight="200.0" prefWidth="200.0">

       <fx:include fx:id="memberPage" source="GUImembers.fxml"/>

            </BorderPane>
        </content>
      </Tab>
  </tabs>
</TabPane>```
</div>
</div>
</p>

<p>FXML I want to add:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>

<BorderPane fx:id="memberPage" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="700.0" prefWidth="1300.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="GUImembersController">
   <center>
      <TableView BorderPane.alignment="CENTER">
        <columns>
          <TableColumn prefWidth="75.0" text="C1" />
          <TableColumn prefWidth="75.0" text="C2" />
        </columns>
      </TableView>
   </center>
</BorderPane></code>```

Main:

```<code>import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class MainClass extends Application
{
public FXMLLoader loader;

public static void main(String[] args)
{
    launch(args);
}

public void start(Stage stage) throws Exception
{
    loader = new FXMLLoader();
    loader.setLocation(getClass().getResource("FXML/GUImain.fxml"));
    loader.setController(new GUImainController());

    Parent root = loader.load();
    Scene scene = new Scene(root);

    stage.setTitle("VIA - Event Management System");
    stage.setScene(scene);
    stage.show();
}
}
</code>```

答: Finally, after long hours of fighting with java fx, I got the sollution, which was quite simple. Thanks to this question : JavaFX Borderpane without left and right children</p>

Body:
I'm trying to include an additional fxml in a main fxml, border pane center. When I do this, the fxml gets included and shows in the center, but the fxml does not occupy the full width and height of the main fxml window.

In the SceneBuilder, if I add the TableView in the center of the borderpane, it acts as it should. Only when I include the fxml via code it does not.

Please help, what am I missing? Any help will be appreciated!

This is what I need:

This is what I get:

Main FXML:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.effect.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>

<TabPane fx:id="TabPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="800.0" prefWidth="1300.0" tabClosingPolicy="UNAVAILABLE" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
  <tabs>
      <Tab fx:id="lecturersTab" closable="false" text="Lecturers">
         <content>
            <BorderPane prefHeight="200.0" prefWidth="200.0">

                  <TableView prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
                    <columns>
                      <TableColumn prefWidth="75.0" text="C1" />
                      <TableColumn prefWidth="75.0" text="C2" />
                    </columns>
                  </TableView>

            </BorderPane>
         </content>
      </Tab>
      <Tab fx:id="membersTab" closable="false" text="Members">
        <content>
            <BorderPane prefHeight="200.0" prefWidth="200.0">

       <fx:include fx:id="memberPage" source="GUImembers.fxml"/>

            </BorderPane>
        </content>
      </Tab>
  </tabs>
</TabPane>

FXML I want to add:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>

<BorderPane fx:id="memberPage" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="700.0" prefWidth="1300.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="GUImembersController">

      <TableView BorderPane.alignment="CENTER">
        <columns>
          <TableColumn prefWidth="75.0" text="C1" />
          <TableColumn prefWidth="75.0" text="C2" />
        </columns>
      </TableView>

</BorderPane>

Main:

import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class MainClass extends Application
{
public FXMLLoader loader;

public static void main(String[] args)
{
    launch(args);
}

public void start(Stage stage) throws Exception
{
    loader = new FXMLLoader();
    loader.setLocation(getClass().getResource("FXML/GUImain.fxml"));
    loader.setController(new GUImainController());

    Parent root = loader.load();
    Scene scene = new Scene(root);

    stage.setTitle("VIA - Event Management System");
    stage.setScene(scene);
    stage.show();
}
}


问:
What is the Typescript equivalent to C# LINQ GroupBy ?
I am using Angular with Typescript. I have array of objects with multiple properties. I have grouped them in server side code and set duplicate property. When user updates the list I have to loop though the list and find duplicates in the client side. Is there any C# LINQ GroupBy equivalent in Typescript?

Here is my C# LINQ code:

```<code>listMP.Where(item => item.Type == "Other").GroupBy(i => new { i.Type, i.Name, i.Address1, i.City }).Where(g => g.Count() > 1)
.SelectMany(g=>g.Select(gg =>gg.Id));
</code>```

答:
What is the Typescript equivalent to C# LINQ GroupBy ?

You can use Array.prototype.reduce : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Alternatively you can use lodash groupBy: https://lodash.com/docs/4.17.4#groupBy

Body:
I am using Angular with Typescript. I have array of objects with multiple properties. I have grouped them in server side code and set duplicate property. When user updates the list I have to loop though the list and find duplicates in the client side. Is there any C# LINQ GroupBy equivalent in Typescript?

Here is my C# LINQ code:

listMP.Where(item => item.Type == "Other").GroupBy(i => new { i.Type, i.Name, i.Address1, i.City }).Where(g => g.Count() > 1)
.SelectMany(g=>g.Select(gg =>gg.Id));


答:
No. C++ is not a dynamically typed language. Even when a variable is declared auto, its type is fixed at compile time---it just makes it so that you don't have to write out the type of the right-hand side yourself. It is impossible to declare a variable whose type depends on runtime information---unless all the possible types have a common base class.

Most of the time, std::any is not useful for precisely this reason: when you have a collection of objects and you erase their types in this way, those objects usually become useless. If you don't know what they are, then you can't do anything with them.

Are you sure you don't want to use std::variant instead? Or std::tuple? Or templates?

Title: Possibility of store object type for std::any

Body:
In c++17 we have the std::any which stores variable type of object in memory. Good part is I can create a vector of std::any to simulate a container for arbitrary type of object.

Whenever to query back the object from the container one will use  std::any_cast with the exact same type when calling std::make_any to create the any object. Here is the snippet of how I achieve this

#include <any>
#include <iostream>
#include <unordered_map>
#include <vector>
#include <set>

int main()
{
    /* create some objects */
    std::set<int> mySet = { 1, 2, 3 };
    std::vector<int> myVec = { 3, 4, 5 };
    std::unordered_map<int, std::vector<int>> myHash = { std::make_pair(1, myVec) };
    /* create any store */
    std::vector<std::any> anyStore;
    anyStore.push_back(std::make_any<decltype(mySet)>(mySet));
    anyStore.push_back(std::make_any<decltype(myVec)>(myVec));
    anyStore.push_back(std::make_any<decltype(myHash)>(myHash));
    /* get object back */
    auto newSet = std::any_cast<decltype(mySet)>(anyStore[0]);
    auto newVec = std::any_cast<decltype(myVec)>(anyStore[1]);
    auto newHash = std::any_cast<decltype(myHash)>(anyStore[2]);

    /* Question is can we store the decltype(mySet) in memory so that
     * it can be read back while query from the vector to do any_cast?
     */

    return 0;
}

The question is as follows:
Is it possible to store the decltype(mySet) as run time variable so that we can use it in any_cast to auto resolve the type we want to get? I know probably you cannot store the type in memory since it is compile time variable, but is there workaround like using std::type_index or std::type_info to achieve goal?

Edit:

Per @KerrekSB 's request. Here is an example usage of this dynamic sized container of std::any to create a class with dynamic properties.

#include <any>
#include <iostream>
#include <unordered_map>
#include <vector>
#include <set>
#include <string>

class FooWithDynamic
{
public:
    FooWithDynamic() = default;

    template <class T>
    void RegisterProperty(const std::string &key, const T &obj)
    {
        m_store.emplace(key, std::make_any<T>(obj));
    }

    template <class T>
    T GetProperty(const std::string &key)
    {
        if (m_store.find(key) == m_store.end())
            throw;
        return std::any_cast<T>(m_store[key]);
    }
private:
    std::unordered_map<std::string, std::any> m_store;
};

int main()
{
    /* create some objects */
    FooWithDynamic foo;
    foo.RegisterProperty("mySet", std::set<int>{ 1, 2, 3 });
    foo.RegisterProperty("myVec", std::vector<int>{ 1, 2, 3 });
    foo.RegisterProperty("myHash", std::unordered_map<int, int>{ std::make_pair(1, 2) });
    /* query back object */
    auto mySet = foo.GetProperty<std::set<int>>("mySet");
    auto myVec = foo.GetProperty<std::vector<int>>("myVec");
    auto myHash = foo.GetProperty<std::unordered_map<int, int>>("myHash");
    return 0;
}

Thanks everyone to let me know this is not possible because it is in contrast of C++'s static typed philosophy.


问:
Compatibility between structs with differently const-qualified pointers
Is it allowed to use a pointer to some type as a pointer to a different type if they have otherwise-identical pointer members that differ only in the constness of the pointed-to values?

Concretely, given the following two structures:

```<code>struct type {
  char *a;
   int *b;
};

struct const_type {
  const char *a;
  const  int *b;
};
</code>```

Is it allowed to treat a pointer to type as a pointer to const_type and vice-versa1, for example passing a type pointer to a function expecting a const_type pointer as shown:

```<code>int add(const const_type* t2) {
  return *t2->a + *t2->b;
}

int is_it_legal() {
  int some_int = 42;
  char blah[] = "six times and counting...";
  type t1 = {blah, &some_int};
  return add((const_type*)&t1);
}
</code>```

My overall motivation here is to have a foo and const_foo struct which differ only in the constness of the objects pointed to by their contained embedded pointers. For any function that doesn't modify the pointed-to data, I would like to write a single function (that takes the const_foo variant) and have it work for both types of objects.

1Evidently in the latter case (using a const_type as a type it is not be safe if it results in an attempt to modify a pointed to value in case they were defined const, but you may assume this doesn't occur).

答:
IMO, I do not think that const matter in the way you want to use it.
Also, I think you meant this:

```<code>typedef struct type1 {
  char *a;
   int *b;
}type1;

typedef struct type2 {
  const char *a;
  const  int *b;
}type2;

int add(const type2* t2) {
  return t2->a[0] + *t2->b;
}

int is_it_legal() {

  int one = 1;

  type1 t1 = {"third time the charm?", &one};
  return add((type2*)&t1);
}
</code>```

Body:
Is it allowed to use a pointer to some type as a pointer to a different type if they have otherwise-identical pointer members that differ only in the constness of the pointed-to values?

Concretely, given the following two structures:

struct type {
  char *a;
   int *b;
};

struct const_type {
  const char *a;
  const  int *b;
};

Is it allowed to treat a pointer to type as a pointer to const_type and vice-versa1, for example passing a type pointer to a function expecting a const_type pointer as shown:

int add(const const_type* t2) {
  return *t2->a + *t2->b;
}

int is_it_legal() {
  int some_int = 42;
  char blah[] = "six times and counting...";
  type t1 = {blah, &some_int};
  return add((const_type*)&t1);
}

My overall motivation here is to have a foo and const_foo struct which differ only in the constness of the objects pointed to by their contained embedded pointers. For any function that doesn't modify the pointed-to data, I would like to write a single function (that takes the const_foo variant) and have it work for both types of objects.

1Evidently in the latter case (using a const_type as a type it is not be safe if it results in an attempt to modify a pointed to value in case they were defined const, but you may assume this doesn't occur).

Body:
IMO, I do not think that const matter in the way you want to use it.
Also, I think you meant this:

typedef struct type1 {
  char *a;
   int *b;
}type1;

typedef struct type2 {
  const char *a;
  const  int *b;
}type2;

int add(const type2* t2) {
  return t2->a[0] + *t2->b;
}

int is_it_legal() {

  int one = 1;

  type1 t1 = {"third time the charm?", &one};
  return add((type2*)&t1);
}


答:
No, the behavior is not defined by the C standard.  (Although it is “allowed” in various senses, including that a C implementation may support this as an extension.)

First, C 2011 6.7.3 10 says “For two qualified types to be compatible, both shall have the identically qualified version of a compatible type…” So const char and char are not compatible.

Then 6.7.6.1 says “For two pointer types to be compatible, both shall be identically qualified and both shall be pointers to compatible types.” So const char * and char * are not compatible.

Next, 6.2.7 1 says “Moreover, two structure, union, or enumerated types declared in separate translation units are compatible if their tags and members satisfy the following requirements: … If both are completed anywhere within their respective translation units, then the following additional requirements apply: there shall be a one-to-one correspondence between their members such that each pair of corresponding members are declared with compatible types;…” Also, it requires “If one is declared with a tag, the other shall be declared with the same tag.” So the structures are not compatible.

Finally, 6.5 7 tells us “An object shall have its stored value accessed only by an lvalue expression that has one of the following types: a type compatible with the effective type of the object, a qualified version of a type compatible with the effective type of the object,…” The first of these does not apply since the structures are not compatible. The second says you can refer to a structure using a const version, which unfortunately does not apply since the const here qualifies the members, not the structure.

Title: Compatibility between structs with differently const-qualified pointers


问:
How to use for loop to read in files and apply functions to each file to give a list of data frames
I have 3 data frames:

```<code>dataF <- data.frame(year = c(1986, 1987, 1988, 1988, 1999),  Female_ID = c("A1","B1","C1","E1","D1"), Terr = c("TAT", "CAT", "PLU", "GER", "ATT"))

dataM <- data.frame(year = c(1986, 1986, 1986, 1987, 1987, 1988, 1988, 1988, 1988, 1999, 1999),
Male_ID = c("F1", "G1", "H1", "I1", "J1", "K1", "L1", "M1", "N1", "O1", "P1"), Terr = c("GAT","URS","OPI","INN","WOF","DUG","WAT","YUU","WRF","HUT","RIT")
</code>```

genome: gives you the relatedness for every possible combination of male and females above. It looks something like this:

```<code>    Male_ID   Female_ID  Pair1  Pair2  relatedness
         F1          A1  F1 A1  A1 F1         0.02
    etc...
</code>```

And I have 4 shape files: lala_d1986_t.shp,  lala_d1987t.shp, lala_d1988_t.shp, lala_d1989_t.shp.

Each of these above shape files gives a map of territories for their given year. For example, the first shape file gives a map for the year 1986.

For each year from 1986 to 1989 I read in its shape file, apply some functions to it to give me a list of neighboring territories for each territory; subset the dataF and dataM for the given year; use the dataF, dataM, and the list of neighboring territories for each territory of that given year to create a data frame that has each female paired up with each of the males that are in the territories surrounding her territory; then I find the relatedness between all those pairs using the genome data frame, then I take the mean relatedness of a female and all her male partners to create a data frame with just the female ID, year, and mean relatedness.

I already have all the functions to do what I want to do above, but I'm having trouble in creating a code that allows me to do all this at once without having to do this manually year by year. Specifically, I'm having trouble reading in the correct shape file for each year.

I've tried:

```<code>   files <- c(lala_d1986_t.shp,  lala_d1987t.shp, lala_d1988_t.shp, lala_d1989_t.shp)
   listofdfs <- list()
   for(j in c(1986:1989) {
     for(i in length(files)){
       getinfo.shape(paste(files[[i]]))
       FSJShape <- readOGR(paste(files[[i]]))
       FSJShape <- subset(FSJShape, TERRYR!='<NA>')
       listofpositions_year <- gTouches(FSJShape, byid = TRUE, returnDense = FALSE)
       listofneighterr_year <- lapply(listofpositions_year, function(x) FSJShape$TERRYR[x])
       names(listofneighterr_year) <- FSJShape$TERRYR
       listofneighterr_year[] <- lapply(listofneighterr_year, as.character)
       dataF_year <- subset(dataF, year == j)
       dataM_year <- subset(dataM, year == j)
       ...
       final_df
       listofdfs[[j]] <- final_df
     }
   }
</code>```

When I run this, it gives me back an error saying it can't find a certain column name. I've done the codes within the for loops already for each year so I know that these all work. What I believe is the problem is the way I'm using the paste function in the first two lines within the for loops. It's reading all the shape files at once and it uses the last shape file it reads in (the one for 1989) for the rest of the codes.

I am not sure how to solve this. I've already tried googling and I can't find anything that does what I want to do.

答:
Looks like you might have a typo in the i loop initialisation?

```<code>for (i in length(files)) {
          ^
</code>```

That will only iterate over the last element in the files vector. If you want to iterate over all of them you could change that to:

```<code>for (i in 1:length(files)) {
</code>```

Or more efficiently:

```<code>for (i in seq_along(files)) {
</code>```

Hope that fixes it!

Body:
I have 3 data frames:

dataF <- data.frame(year = c(1986, 1987, 1988, 1988, 1999),  Female_ID = c("A1","B1","C1","E1","D1"), Terr = c("TAT", "CAT", "PLU", "GER", "ATT"))

dataM <- data.frame(year = c(1986, 1986, 1986, 1987, 1987, 1988, 1988, 1988, 1988, 1999, 1999),
Male_ID = c("F1", "G1", "H1", "I1", "J1", "K1", "L1", "M1", "N1", "O1", "P1"), Terr = c("GAT","URS","OPI","INN","WOF","DUG","WAT","YUU","WRF","HUT","RIT")

genome: gives you the relatedness for every possible combination of male and females above. It looks something like this:

    Male_ID   Female_ID  Pair1  Pair2  relatedness
         F1          A1  F1 A1  A1 F1         0.02
    etc...

And I have 4 shape files: lala_d1986_t.shp,  lala_d1987t.shp, lala_d1988_t.shp, lala_d1989_t.shp.

Each of these above shape files gives a map of territories for their given year. For example, the first shape file gives a map for the year 1986.

For each year from 1986 to 1989 I read in its shape file, apply some functions to it to give me a list of neighboring territories for each territory; subset the dataF and dataM for the given year; use the dataF, dataM, and the list of neighboring territories for each territory of that given year to create a data frame that has each female paired up with each of the males that are in the territories surrounding her territory; then I find the relatedness between all those pairs using the genome data frame, then I take the mean relatedness of a female and all her male partners to create a data frame with just the female ID, year, and mean relatedness.

I already have all the functions to do what I want to do above, but I'm having trouble in creating a code that allows me to do all this at once without having to do this manually year by year. Specifically, I'm having trouble reading in the correct shape file for each year.

I've tried:

   files <- c(lala_d1986_t.shp,  lala_d1987t.shp, lala_d1988_t.shp, lala_d1989_t.shp)
   listofdfs <- list()
   for(j in c(1986:1989) {
     for(i in length(files)){
       getinfo.shape(paste(files[[i]]))
       FSJShape <- readOGR(paste(files[[i]]))
       FSJShape <- subset(FSJShape, TERRYR!='<NA>')
       listofpositions_year <- gTouches(FSJShape, byid = TRUE, returnDense = FALSE)
       listofneighterr_year <- lapply(listofpositions_year, function(x) FSJShape$TERRYR[x])
       names(listofneighterr_year) <- FSJShape$TERRYR
       listofneighterr_year[] <- lapply(listofneighterr_year, as.character)
       dataF_year <- subset(dataF, year == j)
       dataM_year <- subset(dataM, year == j)
       ...
       final_df
       listofdfs[[j]] <- final_df
     }
   }

When I run this, it gives me back an error saying it can't find a certain column name. I've done the codes within the for loops already for each year so I know that these all work. What I believe is the problem is the way I'm using the paste function in the first two lines within the for loops. It's reading all the shape files at once and it uses the last shape file it reads in (the one for 1989) for the rest of the codes.

I am not sure how to solve this. I've already tried googling and I can't find anything that does what I want to do.

Body:
Looks like you might have a typo in the i loop initialisation?

for (i in length(files)) {
          ^

That will only iterate over the last element in the files vector. If you want to iterate over all of them you could change that to:

for (i in 1:length(files)) {

Or more efficiently:

for (i in seq_along(files)) {

Hope that fixes it!


答:
It's not even guaranteed to work if the two structs have exactly the same member list. The code is a strict aliasing violation, accessing type1 via an lvalue of type type2.

As always for strict aliasing discussions: the text of the rule is underspecificed, however it's widely accepted that x->y, which is defined as (*x).y, counts as an access of *x for the purposes of strict aliasing. The rationale for this can be seen in this code:

```<code>void f(struct A *a, struct B *b)
{
     a->x = 5;
     b->y = 6;
}
</code>```

The compiler should be free to assume that a->x and b->y cannot alias each other , even if they both happen to have type  int, and regardless of their offsets within the struct.

However, if you declare a union containing the two struct types, and that declaration is visible at the point of the attempted aliasing,  then this bypasses the strict aliasing rule, even if the objects being aliased are not currently in a union!

See this thread for good coverage of the topic, with commentary about compiler compliance.

Back to your question though: since your structs don't even have the same member list, the text from 6.5.2.3/6 about common initial sequences in unions:

Two structures share a common initial sequence if corresponding members
  have compatible types (and, for bit-fields, the same widths) for a sequence of one or more initial members.

does not apply; the two types are just unrelated struct types. (The definition of "compatible type" is in 6.2.7 - changing qualifiers makes the types incompatible). And putting them in a union doesn't gain anything.

Finally though, as discussed on the linked thread; what the standard says and what compilers actually do are not the same thing in this area.

Body:
It's not even guaranteed to work if the two structs have exactly the same member list. The code is a strict aliasing violation, accessing type1 via an lvalue of type type2.

As always for strict aliasing discussions: the text of the rule is underspecificed, however it's widely accepted that x->y, which is defined as (*x).y, counts as an access of *x for the purposes of strict aliasing. The rationale for this can be seen in this code:

void f(struct A *a, struct B *b)
{
     a->x = 5;
     b->y = 6;
}

The compiler should be free to assume that a->x and b->y cannot alias each other , even if they both happen to have type  int, and regardless of their offsets within the struct.

However, if you declare a union containing the two struct types, and that declaration is visible at the point of the attempted aliasing,  then this bypasses the strict aliasing rule, even if the objects being aliased are not currently in a union!

See this thread for good coverage of the topic, with commentary about compiler compliance.

Back to your question though: since your structs don't even have the same member list, the text from 6.5.2.3/6 about common initial sequences in unions:

Two structures share a common initial sequence if corresponding members
  have compatible types (and, for bit-fields, the same widths) for a sequence of one or more initial members.

does not apply; the two types are just unrelated struct types. (The definition of "compatible type" is in 6.2.7 - changing qualifiers makes the types incompatible). And putting them in a union doesn't gain anything.

Finally though, as discussed on the linked thread; what the standard says and what compilers actually do are not the same thing in this area.


问:
How to print list of lists without extra brackets and quotes?
I'm working on assignment for my Python 3 programming class. It's a database to look up movies and the year they came out. However, I'm having a hard time printing the output without extra brackets and quotes:

```<code># Build a dictionary containing the specified movie collection
list_2005 = [["Munich", "Steven Spielberg"]]
list_2006 = [["The Departed", "Martin Scorsese"], ["The Prestige", "Christopher Nolan"]]
list_2007 = [["Into the Wild", "Sean Penn"]]

movies = {
'2005': list_2005,
'2006': list_2006,
'2007': list_2007
      }

# Prompt the user for a year
# Displaying the title(s) and directors(s) from that year
user_year = str(input("Enter a year between 2005 and 2007:\n"))

if user_year in movies:

    for name in movies[user_year]:
        print("%s" % ', '.join(name))
    print()

elif user_year not in movies:
    print("N/A")

# Display menu
user_choice = ''

while user_choice != 'q':
    print("MENU\nSort by:\ny - Year\nd - Director\nt - Movie title\nq - Quit")
    print()
    user_choice = str(input("Choose an option:\n"))

    if user_choice == 'y':
       for key, value in sorted(movies.items()):
           print("%s:" % key)
           print("    %s" % ''.join(str(movies[key])))

# Carry out the desired option: Display movies by year,
# display movies by director, display movies by movie title, or quit
</code>```

I would like this output to be:

2005:
    Munich, Steven Spielberg

2006:
    The Prestige, Christopher Nolan
    The Departed, Martin Scorsese
```

<p>etc.</p>

<p>The output I am getting:</p>

<pre class="lang-none prettyprint-override"><code>2005:
    ['Munich', 'Steven Spielberg']

2006:
    [['The Prestige', 'Christopher Nolan'], ['The Departed', 'Martin Scorsese']]
</code>```

etc.

答:
Replace </p>

```<code>print(" %s" % ''.join(str(movies[key])))
</code>```

<p>with </p>

```<code>print("\t" + '\n\t'.join("{}, {}".format(m[0], m[1]) for m in movies[key]))
</code>```

Body:
I'm working on assignment for my Python 3 programming class. It's a database to look up movies and the year they came out. However, I'm having a hard time printing the output without extra brackets and quotes:

# Build a dictionary containing the specified movie collection
list_2005 = [["Munich", "Steven Spielberg"]]
list_2006 = [["The Departed", "Martin Scorsese"], ["The Prestige", "Christopher Nolan"]]
list_2007 = [["Into the Wild", "Sean Penn"]]

movies = {
'2005': list_2005,
'2006': list_2006,
'2007': list_2007
      }

# Prompt the user for a year
# Displaying the title(s) and directors(s) from that year
user_year = str(input("Enter a year between 2005 and 2007:\n"))

if user_year in movies:

    for name in movies[user_year]:
        print("%s" % ', '.join(name))
    print()

elif user_year not in movies:
    print("N/A")

# Display menu
user_choice = ''

while user_choice != 'q':
    print("MENU\nSort by:\ny - Year\nd - Director\nt - Movie title\nq - Quit")
    print()
    user_choice = str(input("Choose an option:\n"))

    if user_choice == 'y':
       for key, value in sorted(movies.items()):
           print("%s:" % key)
           print("    %s" % ''.join(str(movies[key])))

# Carry out the desired option: Display movies by year,
# display movies by director, display movies by movie title, or quit

I would like this output to be:

2005:
    Munich, Steven Spielberg

2006:
    The Prestige, Christopher Nolan
    The Departed, Martin Scorsese

etc.

The output I am getting:

2005:
    ['Munich', 'Steven Spielberg']

2006:
    [['The Prestige', 'Christopher Nolan'], ['The Departed', 'Martin Scorsese']]

etc.

Body:
Replace

print(" %s" % ''.join(str(movies[key])))

with

print("\t" + '\n\t'.join("{}, {}".format(m[0], m[1]) for m in movies[key]))