问:
How to add ordinals to an address string using Excel VBA
I am trying to cleaning up some addresses. I already have some code to change "Sw","Ne" and capitalizing them.

However, I would like to add one more step to tack on ordinals to rural addresses in the same code if possible.

all the addresses I need to updated start with 5 numbers then space then 3 numbers.  "NNNNN NNN"

I have some code to add ordinals, I just need a way to only add it to those 3 numbers after the 5. Example "56579 123"  to  "56579 123rd" and leave the rest of the address alone.

Here is my current code.

```<code>Public Function TidyUp(sin As String) As String
    Dim i As Long
    arr = Split(sin, " ")
    For i = LBound(arr) To UBound(arr)

        If UCase(arr(i)) = "NE" Then arr(i) = "NE"
        If UCase(arr(i)) = "NW" Then arr(i) = "NW"
        If UCase(arr(i)) = "SE" Then arr(i) = "SE"
        If UCase(arr(i)) = "SW" Then arr(i) = "SW"

    Next i
    TidyUp = Join(arr, " ")
End Function
</code>```

Here is the ordinal function but this only works if i have a single number in a cell.

```<code>Function AddOrdinal(Address As String) As String

Select Case CLng(VBA.Right(Address, 1))
    Case 1
    AddOrdinal = Address & "st"
    Case 2
    AddOrdinal = Address & "nd"
    Case 3
    AddOrdinal = Address & "rd"
    Case Else
    AddOrdinal = Address & "th"
End Select
Select Case VBA.CLng(VBA.Right(Address, 2))
    Case 11, 12, 13
    AddOrdinal = Address & "th"
End Select
End Function
</code>```

This is basically what I am looking to achieve.

```<code>Address List        Expected Output
12345 673 Ave       12345 673rd Ave
213 N Apple St      213 N Apple St
69818 221st Rd      69818 221st Rd
569 Sw Maple Dr     569 SW Maple Dr
10005 654 Dr        10005 654th Dr
369 Ne Banana St    369 NE Banana St
54489 412th St      54489 412th St
986 W Timber St     986 W Timber St
79532 771 Dr        79532 771st Dr
126 E Washington Ave126 E Washington Ave
56898 422 Dr        56898 422nd Dr
</code>```

答:
You can join the two:

```<code>Public Function TidyUp(sin As String) As String
    Dim i As Long
    arr = Split(sin, " ")
    For i = LBound(arr) To UBound(arr)

        If UCase(arr(i)) = "NE" Then arr(i) = "NE"
        If UCase(arr(i)) = "NW" Then arr(i) = "NW"
        If UCase(arr(i)) = "SE" Then arr(i) = "SE"
        If UCase(arr(i)) = "SW" Then arr(i) = "SW"
        If IsNumeric(arr(i)) And i > 0 Then
            Dim temp As String
            Select Case CLng(Right(arr(i), 1))
                Case 1
                temp = arr(i) & "st"
                Case 2
                temp = arr(i) & "nd"
                Case 3
                temp = arr(i) & "rd"
                Case Else
                temp = arr(i) & "th"
            End Select
            Select Case CLng(Right(arr(i), 2))
                Case 11, 12, 13
                temp = arr(i) & "th"
            End Select
            arr(i) = temp
        End If

    Next i
    TidyUp = Join(arr, " ")
End Function
</code>```

Body:
I am trying to cleaning up some addresses. I already have some code to change "Sw","Ne" and capitalizing them.

However, I would like to add one more step to tack on ordinals to rural addresses in the same code if possible.

all the addresses I need to updated start with 5 numbers then space then 3 numbers.  "NNNNN NNN"

I have some code to add ordinals, I just need a way to only add it to those 3 numbers after the 5. Example "56579 123"  to  "56579 123rd" and leave the rest of the address alone.

Here is my current code.

Public Function TidyUp(sin As String) As String
    Dim i As Long
    arr = Split(sin, " ")
    For i = LBound(arr) To UBound(arr)

        If UCase(arr(i)) = "NE" Then arr(i) = "NE"
        If UCase(arr(i)) = "NW" Then arr(i) = "NW"
        If UCase(arr(i)) = "SE" Then arr(i) = "SE"
        If UCase(arr(i)) = "SW" Then arr(i) = "SW"

    Next i
    TidyUp = Join(arr, " ")
End Function

Here is the ordinal function but this only works if i have a single number in a cell.

Function AddOrdinal(Address As String) As String

Select Case CLng(VBA.Right(Address, 1))
    Case 1
    AddOrdinal = Address & "st"
    Case 2
    AddOrdinal = Address & "nd"
    Case 3
    AddOrdinal = Address & "rd"
    Case Else
    AddOrdinal = Address & "th"
End Select
Select Case VBA.CLng(VBA.Right(Address, 2))
    Case 11, 12, 13
    AddOrdinal = Address & "th"
End Select
End Function

This is basically what I am looking to achieve.

Address List        Expected Output
12345 673 Ave       12345 673rd Ave
213 N Apple St      213 N Apple St
69818 221st Rd      69818 221st Rd
569 Sw Maple Dr     569 SW Maple Dr
10005 654 Dr        10005 654th Dr
369 Ne Banana St    369 NE Banana St
54489 412th St      54489 412th St
986 W Timber St     986 W Timber St
79532 771 Dr        79532 771st Dr
126 E Washington Ave126 E Washington Ave
56898 422 Dr        56898 422nd Dr

Body:
You can join the two:

Public Function TidyUp(sin As String) As String
    Dim i As Long
    arr = Split(sin, " ")
    For i = LBound(arr) To UBound(arr)

        If UCase(arr(i)) = "NE" Then arr(i) = "NE"
        If UCase(arr(i)) = "NW" Then arr(i) = "NW"
        If UCase(arr(i)) = "SE" Then arr(i) = "SE"
        If UCase(arr(i)) = "SW" Then arr(i) = "SW"
        If IsNumeric(arr(i)) And i > 0 Then
            Dim temp As String
            Select Case CLng(Right(arr(i), 1))
                Case 1
                temp = arr(i) & "st"
                Case 2
                temp = arr(i) & "nd"
                Case 3
                temp = arr(i) & "rd"
                Case Else
                temp = arr(i) & "th"
            End Select
            Select Case CLng(Right(arr(i), 2))
                Case 11, 12, 13
                temp = arr(i) & "th"
            End Select
            arr(i) = temp
        End If

    Next i
    TidyUp = Join(arr, " ")
End Function


来源: stackexchange

问:
C++ std::unique is not showing what I am expecting from it
I was trying to find if the vector contains duplicates (please don't provide an algorithm to check duplicates.) I came up with this weird behavior. std::unique on vector 1,2,3,1 should make it 1,2,3,1 returning an iterator to 1 but on erasing the iterator returned till the vector.end() I got the same size vector as that of I original vector. Here is the snippet of code depicting the said behavior (available at ideone)

```<code>    vector<int> nums2 = {1,2,3,4};
    vector<int> nums = {1,2,3,1};
    cout << "nums1" << endl;
    vector<int> a(nums.begin(), nums.end());
    auto ip = unique(nums.begin(), nums.begin()+nums.size());
    nums.resize( std::distance(nums.begin(),ip) );
    cout << a.size() <<  " " << nums.size() << endl;

    cout << "Nums2" << endl;
    vector<int> a2(nums2.begin(), nums2.end());
    auto ip2 = unique(nums2.begin(), nums2.begin()+nums2.size());
    nums.resize( std::distance(nums2.begin(),ip2) );
    cout << a2.size() <<  " " << nums2.size();
</code>```

The actual output is

```<code>nums1
4 4
Nums2
4 4
</code>```

but it  should have been

```<code>nums1
4 3
Nums2
4 4
</code>```

答: If you'd like to remove duplicate elements, while keeping their first occurrences in order, unique is not what you want. Instead, use an unordered_set to keep track of the elements you've seen so far. (You can do this with remove_if, but I wouldn't advise it unless you're familiar with lambda capture semantics; just do it in a for-loop, and read up on how to properly erase elements from a vector in a for-loop.)

ContentLicense: CC BY-SA 4.0

Body:
I was trying to find if the vector contains duplicates (please don't provide an algorithm to check duplicates.) I came up with this weird behavior. std::unique on vector 1,2,3,1 should make it 1,2,3,1 returning an iterator to 1 but on erasing the iterator returned till the vector.end() I got the same size vector as that of I original vector. Here is the snippet of code depicting the said behavior (available at ideone)

    vector<int> nums2 = {1,2,3,4};
    vector<int> nums = {1,2,3,1};
    cout << "nums1" << endl;
    vector<int> a(nums.begin(), nums.end());
    auto ip = unique(nums.begin(), nums.begin()+nums.size());
    nums.resize( std::distance(nums.begin(),ip) );
    cout << a.size() <<  " " << nums.size() << endl;

    cout << "Nums2" << endl;
    vector<int> a2(nums2.begin(), nums2.end());
    auto ip2 = unique(nums2.begin(), nums2.begin()+nums2.size());
    nums.resize( std::distance(nums2.begin(),ip2) );
    cout << a2.size() <<  " " << nums2.size();

The actual output is

nums1
4 4
Nums2
4 4

but it  should have been

nums1
4 3
Nums2
4 4


问:
How to apply border-radius css property on ion-menu in ionic 4?
I'm creating Ionic 4 Angular app , in the app i'm using ion-menu to show menu items. how to apply border-top-right-radius and border-bottom-right-radius css properties on ion-menu ? Below image shows what exactly i want. Here is ion-menu documentation link.

答:
yo think this achieves what you want:

global.scss

```<code>ion-menu{
    --ion-toolbar-background: grey;
    ion-list{
         border: 2px solid grey !important;
    padding: 10px !important;
    border-top-right-radius: 25px !important;
    border-bottom-right-radius: 25px !important;
    background: grey !important;

    }
    ion-item{
        --background: grey !important;
        --color: #fff;
    }
}
</code>```

Body:
yo think this achieves what you want:

global.scss

ion-menu{
    --ion-toolbar-background: grey;
    ion-list{
         border: 2px solid grey !important;
    padding: 10px !important;
    border-top-right-radius: 25px !important;
    border-bottom-right-radius: 25px !important;
    background: grey !important;

    }
    ion-item{
        --background: grey !important;
        --color: #fff;
    }
}


问:
Move data from Vue function to an external JSON file
I am looking to have the data for a Vue project, stored in an external JSON file rather than within the Vue function itself.

I have tried using the code below to get data from an external file but can't get it to work. Perhaps because of the conflict with "items"

```<code>const app = new Vue({
    data: {
        taxRate: '',
        to: '',
        from: '',
        items: ''
    },
    created: function () {
        fetch('https://example.netlify.com/invoicedetails.json')
        .then(resp => resp.json())
        .then(items => {
            this.items = items
        })
    }
    });
</code>```

Here is the code needed for partial extraction of the data:

```<code>new Vue({
    data: {
    taxRate: .13,
    to: [
        'University of Somewhere',
        '118 Bureaucracy Lane',
        'Cityville, CA 90210',
    ],
    from: [
        'Business Time Inc.',
        '60 Paycheck Drive',
        'Townsland, ON A1B 2CD',
        'Canada',
    ],
    items: [
        [1, `Amazing product you can't live without`, 549],
        [3, `Unnecessary extra item`, 49],
    ]
    },
    template: `
    <div class="min-h-screen bg-gray-700 p-8 text-gray-900">
        <div class="max-w-4xl mx-auto">
        <div ref="quote" class="bg-white px-12 py-20">
            <h1 class="uppercase font-bold text-gray-600 text-3xl border-b pb-8">Quote</h1>
            <div class="mt-8 flex -mx-6">
            <div class="w-1/2 px-6">
                <div class="text-gray-700 font-bold text-sm mb-2">To:</div>
                <div v-for="line in to">{{ line }}</div>
            </div>
            <div class="w-1/2 px-6">
                <div class="text-gray-700 font-bold text-sm mb-2">From:</div>
                <div v-for="line in from">{{ line }}</div>
            </div>
            </div>
            <table class="w-full mt-8">
            <thead>
                <tr>
                <th class="px-4 py-4 border-b text-right">Quantity</th>
                <th class="px-4 py-4 border-b text-left">Description</th>
                <th class="px-4 py-4 border-b text-right">Price</th>
                <th class="px-4 py-4 border-b text-right">Total</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="[quantity, description, price] in items">
                <td class="px-4 py-4 border-b text-right">{{ quantity }}</td>
                <td class="px-4 py-4 border-b text-left">{{ description }}</td>
                <td class="px-4 py-4 border-b text-right">{{ price | price }}</td>
                <td class="px-4 py-4 border-b text-right">{{ price * quantity | price }}</td>
                </tr>
                <tr>
                <td class="border-b"></td>
                <td class="border-b"></td>
                <td class="border-b px-4 py-4 text-right font-bold">Subtotal</td>
                <td class="border-b px-4 py-4 text-right font-bold">{{ totalWithoutTaxes | price }}</td>
                </tr>
                <tr>
                <td class="border-b"></td>
                <td class="border-b"></td>
                <td class="border-b px-4 py-4 text-right font-bold">Taxes</td>
                <td class="border-b px-4 py-4 text-right font-bold">{{ taxes | price }}</td>
                </tr>
                <tr>
                <td class="border-b"></td>
                <td class="border-b"></td>
                <td class="border-b px-4 py-4 text-right font-bold">Total</td>
                <td class="border-b px-4 py-4 text-right font-bold">{{ total | price }}</td>
                </tr>
            </tbody>
            </table>
            <div class="mt-8 text-center text-gray-700">
            All prices in USD.
            </div>
        </div>
        </div>
    </div>
    `,
    el: '#app',
    computed: {
    totalWithoutTaxes() {
        return this.items.reduce((total, [quantity, _, price]) => {
        return total + (quantity * price)
        }, 0)
    },
    taxes() {
        return this.totalWithoutTaxes * (1 + this.taxRate) - this.totalWithoutTaxes
    },
    total() {
        return this.totalWithoutTaxes + this.taxes
    },
    },
    filters: {
    price: function (value) {
        return `$${value.toFixed(2)}`
    }
    }
})
</code>```

Here is the CodePen

答:
You can move the data to vuex store. You can read more here (https://vuex.vuejs.org/guide/)

If you need to test your app with rest api data, you can use https://github.com/indexzero/http-server.

Body:
I am looking to have the data for a Vue project, stored in an external JSON file rather than within the Vue function itself.

I have tried using the code below to get data from an external file but can't get it to work. Perhaps because of the conflict with "items"

const app = new Vue({
    data: {
        taxRate: '',
        to: '',
        from: '',
        items: ''
    },
    created: function () {
        fetch('https://example.netlify.com/invoicedetails.json')
        .then(resp => resp.json())
        .then(items => {
            this.items = items
        })
    }
    });

Here is the code needed for partial extraction of the data:

new Vue({
    data: {
    taxRate: .13,
    to: [
        'University of Somewhere',
        '118 Bureaucracy Lane',
        'Cityville, CA 90210',
    ],
    from: [
        'Business Time Inc.',
        '60 Paycheck Drive',
        'Townsland, ON A1B 2CD',
        'Canada',
    ],
    items: [
        [1, `Amazing product you can't live without`, 549],
        [3, `Unnecessary extra item`, 49],
    ]
    },
    template: `

Quote

To:

{{ line }}

From:

{{ line }}

                Quantity
                Description
                Price
                Total

                {{ quantity }}
                {{ description }}
                {{ price | price }}
                {{ price * quantity | price }}

                Subtotal
                {{ totalWithoutTaxes | price }}

                Taxes
                {{ taxes | price }}

                Total
                {{ total | price }}

            All prices in USD.

    `,
    el: '#app',
    computed: {
    totalWithoutTaxes() {
        return this.items.reduce((total, [quantity, _, price]) => {
        return total + (quantity * price)
        }, 0)
    },
    taxes() {
        return this.totalWithoutTaxes * (1 + this.taxRate) - this.totalWithoutTaxes
    },
    total() {
        return this.totalWithoutTaxes + this.taxes
    },
    },
    filters: {
    price: function (value) {
        return `$${value.toFixed(2)}`
    }
    }
})

Here is the CodePen


问:
c++ vectors and pointers
As i understand if i dont store pointers, everything in c++ gets copied, which can lead to bad performance (ignore the simplicity of my example). So i thought i store my objects as pointers instead of string object inside my vector, thats better for performance right? (assumining i have very long strings and lots of them).

The problem when i try to iterate over my vector of string pointers is i cant extract the actual value from them

```<code>string test = "my-name";
vector<string*> names(20);
names.push_back(&test);

vector<string*>::iterator iterator = names.begin();
while (iterator != names.end())
{
    std::cout << (*iterator) << ":" << std::endl;
    // std::cout << *(*iterator); // fails

    iterator++;
}
</code>```

See the commented line, i have no problem in receiving the string pointer. But when i try to get the string pointers value i get an error (i couldnt find what excatly the error is but the program just fails).

I also tried storing (iterator) in a new string variable and but it didnt help?

答:
No, no, a thousand times no.

Don't prematurely optimize. If the program is fast, there's no need to worry about performance. In this instance, the pointers clearly reduce performance by consuming memory and time, since each object is only the target of a single pointer!

Not to mention that manual pointer programming tends to introduce errors, especially for novices. Sacrificing correctness and stability for performance is a huge step backwards.

The advantage of C++ is that it simplifies the optimization process by providing encapsulated data structures and algorithms. So when you decide to optimize, you can usually do so by swapping in standard parts.

If you want to learn about optimizing data structures, read up on smart pointers.

This is probably the program you want:

```<code>vector<string> names(20, "my-name");

for ( vector<string>::iterator iterator = names.begin();
      iterator != names.end();
      ++ iterator )
{
    std::cout << *iterator << '\n';
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: c++ vectors and pointers

Body:
As i understand if i dont store pointers, everything in c++ gets copied, which can lead to bad performance (ignore the simplicity of my example). So i thought i store my objects as pointers instead of string object inside my vector, thats better for performance right? (assumining i have very long strings and lots of them).

The problem when i try to iterate over my vector of string pointers is i cant extract the actual value from them

string test = "my-name";
vector<string*> names(20);
names.push_back(&test);

vector<string*>::iterator iterator = names.begin();
while (iterator != names.end())
{
    std::cout << (*iterator) << ":" << std::endl;
    // std::cout << *(*iterator); // fails

    iterator++;
}

See the commented line, i have no problem in receiving the string pointer. But when i try to get the string pointers value i get an error (i couldnt find what excatly the error is but the program just fails).

I also tried storing (iterator) in a new string variable and but it didnt help?

Body:
No, no, a thousand times no.

Don't prematurely optimize. If the program is fast, there's no need to worry about performance. In this instance, the pointers clearly reduce performance by consuming memory and time, since each object is only the target of a single pointer!

Not to mention that manual pointer programming tends to introduce errors, especially for novices. Sacrificing correctness and stability for performance is a huge step backwards.

The advantage of C++ is that it simplifies the optimization process by providing encapsulated data structures and algorithms. So when you decide to optimize, you can usually do so by swapping in standard parts.

If you want to learn about optimizing data structures, read up on smart pointers.

This is probably the program you want:

vector<string> names(20, "my-name");

for ( vector<string>::iterator iterator = names.begin();
      iterator != names.end();
      ++ iterator )
{
    std::cout << *iterator << '\n';
}


问:
React Native TypeError: TypeError: undefined is not an object (evaluating 'this.props.data.map')
I decide to reuse a component that I thought would work for my new application that is pulling in a third-party API.

The reusable component in question is iterating this.props.data.map() which is evaluating as being undefined in my components/Swipe.js file:

```<code>import React, { Component } from "react";
import {
  View,
  Animated,
  PanResponder,
  Dimensions,
  LayoutAnimation,
  UIManager
} from "react-native";

const SCREEN_WIDTH = Dimensions.get("window").width;
const SWIPE_THRESHOLD = 0.25 * SCREEN_WIDTH;
const SWIPE_OUT_DURATION = 250;

class Swipe extends Component {
  static defaultProps = {
    onSwipeRight: () => {},
    onSwipeLeft: () => {}
  };

  constructor(props) {
    super(props);

    const position = new Animated.ValueXY();
    const panResponder = PanResponder.create({
      onStartShouldSetPanResponder: (event, gestureState) => true,
      onPanResponderMove: (event, gestureState) => {
        position.setValue({ x: gestureState.dx, y: gestureState.dy });
      },
      onPanResponderRelease: (event, gestureState) => {
        if (gestureState.dx > SWIPE_THRESHOLD) {
          this.forceSwipe("right");
        } else if (gestureState.dx < -SWIPE_THRESHOLD) {
          this.forceSwipe("left");
        } else {
          this.resetPosition();
        }
      }
    });

    this.state = { panResponder, position, index: 0 };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.data !== this.props.data) {
      this.setState({ index: 0 });
    }
  }

  componentWillUpdate() {
    UIManager.setLayoutAnimationEnabledExperimental &&
      UIManager.setLayoutAnimationEnabledExperimental(true);
    LayoutAnimation.spring();
  }

  forceSwipe(direction) {
    const x = direction === "right" ? SCREEN_WIDTH : -SCREEN_WIDTH;
    Animated.timing(this.state.position, {
      toValue: { x, y: 0 },
      duration: SWIPE_OUT_DURATION
    }).start(() => this.onSwipeComplete(direction));
  }

  onSwipeComplete(direction) {
    const { onSwipeLeft, onSwipeRight, data } = this.props;
    const item = data[this.state.index];
    direction === "right" ? onSwipeRight(item) : onSwipeLeft(item);
    this.state.position.setValue({ x: 0, y: 0 });
    this.setState({ index: this.state.index + 1 });
  }

  resetPosition() {
    Animated.spring(this.state.position, {
      toValue: { x: 0, y: 0 }
    }).start();
  }

  getCardStyle() {
    const { position } = this.state;
    const rotate = position.x.interpolate({
      inputRange: [-SCREEN_WIDTH * 1.5, 0, SCREEN_WIDTH * 1.5],
      outputRange: ["-120deg", "0deg", "120deg"]
    });
    return {
      ...position.getLayout(),
      transform: [{ rotate }]
    };
  }

  renderCards() {
    console.log(this.props);
    if (this.state.index >= this.props.data.length) {
      return this.props.renderNoMoreCards();
    }
    return this.props.data
      .map((item, i) => {
        if (i < this.state.index) {
          return null;
        }
        if (i === this.state.index) {
          return (
            <Animated.View
              key={item[this.props.id]}
              style={[this.getCardStyle(), styles.cardStyle]}
              {...this.state.panResponder.panHandlers}
            >
              {this.props.renderCard(item)}
            </Animated.View>
          );
        }
        return (
          <Animated.View
            key={item[this.props.id]}
            style={[styles.cardStyle, { top: 10 * (i - this.state.index) }]}
          >
            {this.props.renderCard(item)}
          </Animated.View>
        );
      })
      .reverse();
  }

  render() {
    return <View>{this.renderCards()}</View>;
  }
}

const styles = {
  cardStyle: {
    position: "absolute",
    width: SCREEN_WIDTH
  }
};

export default Swipe;
</code>```

I am unclear why this is happening since I do get back a payload: data in my action creator:

```<code>export const fetchJobs = (region, callback) => async dispatch => {
  try {
    const url =
      JOB_ROOT_URL +
      JOB_QUERY_PARAMS.key +
      "&method=" +
      JOB_QUERY_PARAMS.method +
      "&category=" +
      JOB_QUERY_PARAMS.keyword +
      "&format=" +
      JOB_QUERY_PARAMS.format;
    let { data } = await axios.get(url);
    dispatch({ type: FETCH_JOBS, payload: data });
    callback();
  } catch (e) {
    console.log(e);
  }
};
</code>```

So why is data evaluating as undefined in my reusable component?

It's being called here in DeckScreen.js:

```<code>import React, { Component } from "react";
import { View, Text } from "react-native";
import { connect } from "react-redux";
import { MapView } from "expo";
import { Card, Button } from "react-native-elements";
import Swipe from "../components/Swipe";

class DeckScreen extends Component {
  renderCard(job) {
    return (
      <Card title={job.title}>
        <View style={styles.detailWrapper}>
          <Text>{job.company}</Text>
          <Text>{job.post_date}</Text>
        </View>
        <Text>
          {job.description.replace(/<span>/g, "").replace(/<\/span>/g, "")}
        </Text>
      </Card>
    );
  }

  render() {
    return (
      <View>
        <Swipe data={this.props.jobs} renderCard={this.renderCard} />
      </View>
    );
  }
}

const styles = {
  detailWrapper: {
    flexDirection: "row",
    justifyContent: "space-around",
    marginBottom: 10
  }
};

function mapStateToProps({ jobs }) {
  return { jobs: jobs.listing };
}

export default connect(mapStateToProps)(DeckScreen);
</code>```

The button I am pressing that gives me this error is in the MapScreen screen:

```<code>import React, { Component } from "react";
import { View, Text, ActivityIndicator } from "react-native";
import { Button } from "react-native-elements";
import { MapView } from "expo";
import { connect } from "react-redux";

import * as actions from "../actions";

class MapScreen extends Component {
  state = {
    region: {
      longitude: 30.2672,
      latitude: 97.7431,
      longitudeDelta: 0.04,
      latitudeDelta: 0.09
    }
  };

  onButtonPress = () => {
    this.props.fetchJobs(this.state.region, () => {
      this.props.navigation.navigate("deck");
    });
  };

  getLocationHandler = () => {
    navigator.geolocation.getCurrentPosition(pos => {
      const currentCoords = {
        longitude: pos.coords.longitude,
        latitude: pos.coords.latitude
      };

      this.goToLocation(currentCoords);
    });
  };

  goToLocation = coords => {
    this.map.animateToRegion({
      ...this.state.region,
      longitude: coords.longitude,
      latitude: coords.latitude
    });
    this.setState(prevState => {
      return {
        region: {
          ...prevState.region,
          longitude: coords.longitude,
          latitude: coords.latitude
        }
      };
    });
  };

  render() {
    return (
      <View style={{ flex: 1 }}>
        <MapView
          initialRegion={this.state.region}
          style={{ flex: 1 }}
          ref={ref => (this.map = ref)}
        />
        <View style={styles.buttonContainer}>
          <Button
            title="Search This Area"
            icon={{ name: "search" }}
            onPress={this.onButtonPress}
          />
        </View>
        <View>
          <Button
            title="My Location"
            icon={{ name: "map" }}
            onPress={this.getLocationHandler}
          />
        </View>
      </View>
    );
  }
}

const styles = {
  buttonContainer: {
    position: "absolute",
    bottom: 50,
    left: 0,
    right: 0
  }
};

export default connect(
  null,
  actions
)(MapScreen);
</code>```

This should be an array of objects as verified here:

And in my reducer I have:

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

const INITIAL_STATE = {
  listing: []
};

export default function(state = INITIAL_STATE, action) {
  switch (action.type) {
    case FETCH_JOBS:
      return action.payload;
    default:
      return state;
  }
}
</code>```

I added some verbose error handling and this is what I got back:

[02:25:28] fetchJobs Action Error: Given action "fetch_jobs", reducer
  "jobs" returned undefined. To ignore an action, you must explicitly
  return the previous state. If you want this reducer to hold no value,
  you can return null instead of undefined.

So it seems like the problem is in the jobs_reducer:

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

const INITIAL_STATE = {
  listing: []
};

export default function(state = INITIAL_STATE, action) {
  switch (action.type) {
    case FETCH_JOBS:
      return action.payload;
    default:
      return state;
  }
}
</code>```

I don't know if I am just too exhausted at this point, but I have tried listings: [], I have tried listing: [], I am out of ideas of how to get this reducer to not return undefined because even when I do this:

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

// const INITIAL_STATE = {
//   listing: []
// };

export default function(state = null, action) {
  switch (action.type) {
    case FETCH_JOBS:
      return action.payload;
    default:
      return state;
  }
}
</code>```

I get the same error message.

My idea with creating an INITIAL_STATE and setting it to listing: [] is to ensure I could map over this array and never worry about the case where I have not yet fetched the list of jobs.

So I am perplexed as to exactly where I am getting this undefined since I did set the initial state to null and I was still getting that error.

So in the process of debugging I then tried this:

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

// const INITIAL_STATE = {
//   listing: []
// };

export default function(state = null, action) {
  console.log("action is", action);
  switch (action.type) {
    case FETCH_JOBS:
      return action.payload;
    default:
      return state;
  }
}
</code>```

And got that the payload is undefined:

```<code>Please check your inputs.
[09:39:38] action is Object {
[09:39:38]   "payload": undefined,
[09:39:38]   "type": "fetch_jobs",
[09:39:38] }
</code>```

I have hit a wall here. I did a whole refactor to my jobs action creator and logged out the payload property:

```<code>export const fetchJobs = (region, distance = 10) => async dispatch => {
  try {
    const url = buildJobsUrl();
    let job_list = await axios.get(url);
    job_list = locationify(
      region,
      console.log(job_list.data.listings.listing),
      job_list.data.listings.listing,
      distance,
      (obj, coords) => {
        obj.company.location = { ...obj.company.location, coords };
        return obj;
      }
    );
    dispatch({ type: FETCH_JOBS, payload: job_list });
  } catch (e) {
    console.log("fetchJobs Action Error:", e.message);
  }
};
</code>```

The console.log(job_list.data.listings.listing) logged out the data to my terminal successfully and yet my payload property is still undefined, how is that possible?

I got the action creator and reducer working by refactoring the action creator to just this:

```<code>export const fetchJobs = (region, callback) => async dispatch => {
  try {
    const url =
      JOB_ROOT_URL +
      JOB_QUERY_PARAMS.key +
      "&method=" +
      JOB_QUERY_PARAMS.method +
      "&category=" +
      JOB_QUERY_PARAMS.keyword +
      "&format=" +
      JOB_QUERY_PARAMS.format;
    let { data } = await axios.get(url);
    dispatch({ type: FETCH_JOBS, payload: data });
    callback();
  } catch (e) {
    console.log(e);
  }
};
</code>```0

So the problem is no longer there in theory, right. Then, when I bring in the Swipe.js component, the problem returns, in particular the problem seems to be with this code here:

```<code>export const fetchJobs = (region, callback) => async dispatch => {
  try {
    const url =
      JOB_ROOT_URL +
      JOB_QUERY_PARAMS.key +
      "&method=" +
      JOB_QUERY_PARAMS.method +
      "&category=" +
      JOB_QUERY_PARAMS.keyword +
      "&format=" +
      JOB_QUERY_PARAMS.format;
    let { data } = await axios.get(url);
    dispatch({ type: FETCH_JOBS, payload: data });
    callback();
  } catch (e) {
    console.log(e);
  }
};
</code>```1

This is where I start to hit a roadblock again.

答:
Looks like what helped was refactoring my jobs_reducer file from:

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

const INITIAL_STATE = {
  listing: []
};

export default function(state = INITIAL_STATE, action) {
  switch (action.type) {
    case FETCH_JOBS:
      return action.payload;
    default:
      return state;
  }
}
</code>```

to this:

```<code>export default function(state = INITIAL_STATE, action) {
  switch (action.type) {
    case FETCH_JOBS:
      const { listings } = action.payload;
      return { ...state, listing: listings.listing };
    default:
      return state;
  }
}
</code>```

Body:
I decide to reuse a component that I thought would work for my new application that is pulling in a third-party API.

The reusable component in question is iterating this.props.data.map() which is evaluating as being undefined in my components/Swipe.js file:

import React, { Component } from "react";
import {
  View,
  Animated,
  PanResponder,
  Dimensions,
  LayoutAnimation,
  UIManager
} from "react-native";

const SCREEN_WIDTH = Dimensions.get("window").width;
const SWIPE_THRESHOLD = 0.25 * SCREEN_WIDTH;
const SWIPE_OUT_DURATION = 250;

class Swipe extends Component {
  static defaultProps = {
    onSwipeRight: () => {},
    onSwipeLeft: () => {}
  };

  constructor(props) {
    super(props);

    const position = new Animated.ValueXY();
    const panResponder = PanResponder.create({
      onStartShouldSetPanResponder: (event, gestureState) => true,
      onPanResponderMove: (event, gestureState) => {
        position.setValue({ x: gestureState.dx, y: gestureState.dy });
      },
      onPanResponderRelease: (event, gestureState) => {
        if (gestureState.dx > SWIPE_THRESHOLD) {
          this.forceSwipe("right");
        } else if (gestureState.dx < -SWIPE_THRESHOLD) {
          this.forceSwipe("left");
        } else {
          this.resetPosition();
        }
      }
    });

    this.state = { panResponder, position, index: 0 };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.data !== this.props.data) {
      this.setState({ index: 0 });
    }
  }

  componentWillUpdate() {
    UIManager.setLayoutAnimationEnabledExperimental &&
      UIManager.setLayoutAnimationEnabledExperimental(true);
    LayoutAnimation.spring();
  }

  forceSwipe(direction) {
    const x = direction === "right" ? SCREEN_WIDTH : -SCREEN_WIDTH;
    Animated.timing(this.state.position, {
      toValue: { x, y: 0 },
      duration: SWIPE_OUT_DURATION
    }).start(() => this.onSwipeComplete(direction));
  }

  onSwipeComplete(direction) {
    const { onSwipeLeft, onSwipeRight, data } = this.props;
    const item = data[this.state.index];
    direction === "right" ? onSwipeRight(item) : onSwipeLeft(item);
    this.state.position.setValue({ x: 0, y: 0 });
    this.setState({ index: this.state.index + 1 });
  }

  resetPosition() {
    Animated.spring(this.state.position, {
      toValue: { x: 0, y: 0 }
    }).start();
  }

  getCardStyle() {
    const { position } = this.state;
    const rotate = position.x.interpolate({
      inputRange: [-SCREEN_WIDTH * 1.5, 0, SCREEN_WIDTH * 1.5],
      outputRange: ["-120deg", "0deg", "120deg"]
    });
    return {
      ...position.getLayout(),
      transform: [{ rotate }]
    };
  }

  renderCards() {
    console.log(this.props);
    if (this.state.index >= this.props.data.length) {
      return this.props.renderNoMoreCards();
    }
    return this.props.data
      .map((item, i) => {
        if (i < this.state.index) {
          return null;
        }
        if (i === this.state.index) {
          return (
            <Animated.View
              key={item[this.props.id]}
              style={[this.getCardStyle(), styles.cardStyle]}
              {...this.state.panResponder.panHandlers}
            >
              {this.props.renderCard(item)}
            </Animated.View>
          );
        }
        return (
          <Animated.View
            key={item[this.props.id]}
            style={[styles.cardStyle, { top: 10 * (i - this.state.index) }]}
          >
            {this.props.renderCard(item)}
          </Animated.View>
        );
      })
      .reverse();
  }

  render() {
    return <View>{this.renderCards()}</View>;
  }
}

const styles = {
  cardStyle: {
    position: "absolute",
    width: SCREEN_WIDTH
  }
};

export default Swipe;

I am unclear why this is happening since I do get back a payload: data in my action creator:

export const fetchJobs = (region, callback) => async dispatch => {
  try {
    const url =
      JOB_ROOT_URL +
      JOB_QUERY_PARAMS.key +
      "&method=" +
      JOB_QUERY_PARAMS.method +
      "&category=" +
      JOB_QUERY_PARAMS.keyword +
      "&format=" +
      JOB_QUERY_PARAMS.format;
    let { data } = await axios.get(url);
    dispatch({ type: FETCH_JOBS, payload: data });
    callback();
  } catch (e) {
    console.log(e);
  }
};

So why is data evaluating as undefined in my reusable component?

It's being called here in DeckScreen.js:

import React, { Component } from "react";
import { View, Text } from "react-native";
import { connect } from "react-redux";
import { MapView } from "expo";
import { Card, Button } from "react-native-elements";
import Swipe from "../components/Swipe";

class DeckScreen extends Component {
  renderCard(job) {
    return (
      <Card title={job.title}>
        <View style={styles.detailWrapper}>
          <Text>{job.company}</Text>
          <Text>{job.post_date}</Text>
        </View>
        <Text>
          {job.description.replace(//g, "").replace(/<\/span>/g, "")}
        </Text>
      </Card>
    );
  }

  render() {
    return (
      <View>
        <Swipe data={this.props.jobs} renderCard={this.renderCard} />
      </View>
    );
  }
}

const styles = {
  detailWrapper: {
    flexDirection: "row",
    justifyContent: "space-around",
    marginBottom: 10
  }
};

function mapStateToProps({ jobs }) {
  return { jobs: jobs.listing };
}

export default connect(mapStateToProps)(DeckScreen);

The button I am pressing that gives me this error is in the MapScreen screen:

import React, { Component } from "react";
import { View, Text, ActivityIndicator } from "react-native";
import { Button } from "react-native-elements";
import { MapView } from "expo";
import { connect } from "react-redux";

import * as actions from "../actions";

class MapScreen extends Component {
  state = {
    region: {
      longitude: 30.2672,
      latitude: 97.7431,
      longitudeDelta: 0.04,
      latitudeDelta: 0.09
    }
  };

  onButtonPress = () => {
    this.props.fetchJobs(this.state.region, () => {
      this.props.navigation.navigate("deck");
    });
  };

  getLocationHandler = () => {
    navigator.geolocation.getCurrentPosition(pos => {
      const currentCoords = {
        longitude: pos.coords.longitude,
        latitude: pos.coords.latitude
      };

      this.goToLocation(currentCoords);
    });
  };

  goToLocation = coords => {
    this.map.animateToRegion({
      ...this.state.region,
      longitude: coords.longitude,
      latitude: coords.latitude
    });
    this.setState(prevState => {
      return {
        region: {
          ...prevState.region,
          longitude: coords.longitude,
          latitude: coords.latitude
        }
      };
    });
  };

  render() {
    return (
      <View style={{ flex: 1 }}>
        <MapView
          initialRegion={this.state.region}
          style={{ flex: 1 }}
          ref={ref => (this.map = ref)}
        />
        <View style={styles.buttonContainer}>
          <Button
            title="Search This Area"
            icon={{ name: "search" }}
            onPress={this.onButtonPress}
          />
        </View>
        <View>
          <Button
            title="My Location"
            icon={{ name: "map" }}
            onPress={this.getLocationHandler}
          />
        </View>
      </View>
    );
  }
}

const styles = {
  buttonContainer: {
    position: "absolute",
    bottom: 50,
    left: 0,
    right: 0
  }
};

export default connect(
  null,
  actions
)(MapScreen);

This should be an array of objects as verified here:

And in my reducer I have:

import { FETCH_JOBS } from "../actions/types";

const INITIAL_STATE = {
  listing: []
};

export default function(state = INITIAL_STATE, action) {
  switch (action.type) {
    case FETCH_JOBS:
      return action.payload;
    default:
      return state;
  }
}

I added some verbose error handling and this is what I got back:

[02:25:28] fetchJobs Action Error: Given action "fetch_jobs", reducer
  "jobs" returned undefined. To ignore an action, you must explicitly
  return the previous state. If you want this reducer to hold no value,
  you can return null instead of undefined.

So it seems like the problem is in the jobs_reducer:

import { FETCH_JOBS } from "../actions/types";

const INITIAL_STATE = {
  listing: []
};

export default function(state = INITIAL_STATE, action) {
  switch (action.type) {
    case FETCH_JOBS:
      return action.payload;
    default:
      return state;
  }
}

I don't know if I am just too exhausted at this point, but I have tried listings: [], I have tried listing: [], I am out of ideas of how to get this reducer to not return undefined because even when I do this:

import { FETCH_JOBS } from "../actions/types";

// const INITIAL_STATE = {
//   listing: []
// };

export default function(state = null, action) {
  switch (action.type) {
    case FETCH_JOBS:
      return action.payload;
    default:
      return state;
  }
}

I get the same error message.

My idea with creating an INITIAL_STATE and setting it to listing: [] is to ensure I could map over this array and never worry about the case where I have not yet fetched the list of jobs.

So I am perplexed as to exactly where I am getting this undefined since I did set the initial state to null and I was still getting that error.

So in the process of debugging I then tried this:

import { FETCH_JOBS } from "../actions/types";

// const INITIAL_STATE = {
//   listing: []
// };

export default function(state = null, action) {
  console.log("action is", action);
  switch (action.type) {
    case FETCH_JOBS:
      return action.payload;
    default:
      return state;
  }
}

And got that the payload is undefined:

Please check your inputs.
[09:39:38] action is Object {
[09:39:38]   "payload": undefined,
[09:39:38]   "type": "fetch_jobs",
[09:39:38] }

I have hit a wall here. I did a whole refactor to my jobs action creator and logged out the payload property:

export const fetchJobs = (region, distance = 10) => async dispatch => {
  try {
    const url = buildJobsUrl();
    let job_list = await axios.get(url);
    job_list = locationify(
      region,
      console.log(job_list.data.listings.listing),
      job_list.data.listings.listing,
      distance,
      (obj, coords) => {
        obj.company.location = { ...obj.company.location, coords };
        return obj;
      }
    );
    dispatch({ type: FETCH_JOBS, payload: job_list });
  } catch (e) {
    console.log("fetchJobs Action Error:", e.message);
  }
};

The console.log(job_list.data.listings.listing) logged out the data to my terminal successfully and yet my payload property is still undefined, how is that possible?

I got the action creator and reducer working by refactoring the action creator to just this:

import axios from "axios";
import { Location } from "expo";
import qs from "qs";

import { FETCH_JOBS } from "./types";
// import locationify from "../tools/locationify";

const JOB_ROOT_URL = "https://authenticjobs.com/api/?";

const JOB_QUERY_PARAMS = {
  api_key: "<api_key>",
  method: "aj.jobs.search",
  perpage: "10",
  format: "json",
  keywords: "javascript"
};

const buildJobsUrl = zip => {
  const query = qs.stringify({ ...JOB_QUERY_PARAMS });
  return `${JOB_ROOT_URL}${query}`;
};

export const fetchJobs = (region, callback) => async dispatch => {
  try {
    let zip = await Location.reverseGeocodeAsync(region);
    const url = buildJobsUrl(zip);
    console.log(url);
    let { data } = await axios.get(url);
    dispatch({ type: FETCH_JOBS, payload: data });
    callback();
  } catch (e) {
    console.error(e);
  }
};

So the problem is no longer there in theory, right. Then, when I bring in the Swipe.js component, the problem returns, in particular the problem seems to be with this code here:

renderCards() {
    if (this.state.index >= this.props.data.length) {
      return this.props.renderNoMoreCards();
    }

    return this.props.data
      .map((item, i) => {
        if (i < this.state.index) {
          return null;
        }

        if (i === this.state.index) {
          return (
            <Animated.View
              key={item[this.props.id]}
              style={[this.getCardStyle(), styles.cardStyle]}
              {...this.state.panResponder.panHandlers}
            >
              {this.props.renderCard(item)}
            </Animated.View>
          );
        }
        return (
          <Animated.View
            key={item[this.props.id]}
            style={[styles.cardStyle, { top: 10 * (i - this.state.index) }]}
          >
            {this.props.renderCard(item)}
          </Animated.View>
        );
      })
      .reverse();
  }

This is where I start to hit a roadblock again.

Body:
Looks like what helped was refactoring my jobs_reducer file from:

import { FETCH_JOBS } from "../actions/types";

const INITIAL_STATE = {
  listing: []
};

export default function(state = INITIAL_STATE, action) {
  switch (action.type) {
    case FETCH_JOBS:
      return action.payload;
    default:
      return state;
  }
}

to this:

export default function(state = INITIAL_STATE, action) {
  switch (action.type) {
    case FETCH_JOBS:
      const { listings } = action.payload;
      return { ...state, listing: listings.listing };
    default:
      return state;
  }
}


问:
How to detect double-taps on cells in a UICollectionView
I want to respond to double-taps on cells in a UICollectionView, and have a double-tap action cancel cell selection.

This is what I've tried:

```<code>UITapGestureRecognizer *tapRecogniser = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
tapRecogniser.numberOfTapsRequired = 2;

 for (UITapGestureRecognizer *recogniser in [self.collectionView gestureRecognizers]) {
    [recogniser requireGestureRecognizerToFail:tapRecogniser];
}

[self.collectionView addGestureRecognizer:tapRecogniser];
</code>```

That is, I am trying to get the default gesture recognisers to fail if my double-tap gesture recogniser succeeds.

This doesn't appear to work, as my collection view delegate's collectionView:didSelectItemAtIndexPath: is still getting called after a double-tap

Note on Apple's UICollectionViewController Docs

Apple's documentation is misleading on this point, claiming that the default gesture recogniser is an instance of a UITapGestureRecognizer subclass, so it can be easily picked out with [recogniser isKindOfClass:[UITapGestureRecognizer class]]. Unfortunately this is an error.

答:
For readers looking for a swift answer, this is a mix of @RegularExpression and @Edwin Iskandar answer.

In your controller holding the collectionView add the following lines:

  private var doubleTapGesture: UITapGestureRecognizer!
  func setUpDoubleTap() {
    doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(didDoubleTapCollectionView))
    doubleTapGesture.numberOfTapsRequired = 2
    collectionView.addGestureRecognizer(doubleTapGesture)

    // This line delay the single touch message to the collection view.
    // Simple touch will be sent only when the double tap recogniser is sure
    // this is a simple tap.
    // You can remove it if you don't mind having both a simple tap and double
    // tap event.
    doubleTapGesture.delaysTouchesBegan = true
  }

  @objc func didDoubleTapCollectionView() {
    let pointInCollectionView = doubleTapGesture.location(in: collectionView)
    if let selectedIndexPath = collectionView.indexPathForItem(at: pointInCollectionView) {
      let selectedCell = collectionView.cellForItem(at: selectedIndexPath)

      // Print double tapped cell's path
      print(selectedCell)
    }
  }
```

Body:
I want to respond to double-taps on cells in a UICollectionView, and have a double-tap action cancel cell selection.

This is what I've tried:

UITapGestureRecognizer *tapRecogniser = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
tapRecogniser.numberOfTapsRequired = 2;

 for (UITapGestureRecognizer *recogniser in [self.collectionView gestureRecognizers]) {
    [recogniser requireGestureRecognizerToFail:tapRecogniser];
}

[self.collectionView addGestureRecognizer:tapRecogniser];

That is, I am trying to get the default gesture recognisers to fail if my double-tap gesture recogniser succeeds.

This doesn't appear to work, as my collection view delegate's collectionView:didSelectItemAtIndexPath: is still getting called after a double-tap

Note on Apple's UICollectionViewController Docs

Apple's documentation is misleading on this point, claiming that the default gesture recogniser is an instance of a UITapGestureRecognizer subclass, so it can be easily picked out with [recogniser isKindOfClass:[UITapGestureRecognizer class]]. Unfortunately this is an error.


问:
How to get COUNT of LEFT JOIN data
I'm trying to get the ChannelGroups where the ChannelGroup has a count of 0 on its relation ChannelGroupUsers.

public function userEmptyChannelGroups()
    {
        return $this->getEntityManager()
            ->createQuery(
                'SELECT cg
                 FROM App:ChannelGroup cg
                 LEFT JOIN cg.channelGroupUsers cgu
                 WHERE COUNT(cgu) = 0'
            )
            ->getArrayResult();
    }
```

But I keep getting SQLSTATE[HY000]: General error: 1111 Invalid use of group function (500 Internal Server Error) upon trying the above.

What am I doing wrong?

答:
If you want to find rows that don't have a connection to another table you can do something like this. In where there can be any column from table2.

```<code>select
    *
from table1
left join table2
    on table1.id = table2.id
where table2.someColumn is null
</code>```

Title: How to get COUNT of LEFT JOIN data

Body:
I'm trying to get the ChannelGroups where the ChannelGroup has a count of 0 on its relation ChannelGroupUsers.

public function userEmptyChannelGroups()
    {
        return $this->getEntityManager()
            ->createQuery(
                'SELECT cg
                 FROM App:ChannelGroup cg
                 LEFT JOIN cg.channelGroupUsers cgu
                 WHERE COUNT(cgu) = 0'
            )
            ->getArrayResult();
    }

But I keep getting SQLSTATE[HY000]: General error: 1111 Invalid use of group function (500 Internal Server Error) upon trying the above.

What am I doing wrong?

Body:
If you want to find rows that don't have a connection to another table you can do something like this. In where there can be any column from table2.

select
    *
from table1
left join table2
    on table1.id = table2.id
where table2.someColumn is null


问:
How to check if array[] has a null value in java?
I am reading a csv file. One of the requirements is to check if a certain column has a value or not. In this case I want to check the value in array[18]. However, I am getting

```<code>Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 18
</code>```

Is there any other way to check the array index if it has a value or empty?

My code:

```<code>while ((sCurrentLine = br.readLine())!= null) {

    String[] record = sCurrentLine.split(",");

    if(record.length > 0){ // checking if the current line is not empty on the file
       if(record[18] != null){ // as per console, I am getting the error in this line
          String readDateRecord = record[18];
          // other processing here
       }
    }
}
</code>```

答:
If its an arrayList then check if it contains null</p>

```<code>array.contains(null));
</code>```

Body:
I am reading a csv file. One of the requirements is to check if a certain column has a value or not. In this case I want to check the value in array[18]. However, I am getting

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 18

Is there any other way to check the array index if it has a value or empty?

My code:

while ((sCurrentLine = br.readLine())!= null) {

    String[] record = sCurrentLine.split(",");

    if(record.length > 0){ // checking if the current line is not empty on the file
       if(record[18] != null){ // as per console, I am getting the error in this line
          String readDateRecord = record[18];
          // other processing here
       }
    }
}

Body:
If its an arrayList then check if it contains null

array.contains(null));


问:
aws_key_pair.auth: Error import KeyPair: InvalidKey.Format: Key is not in valid OpenSSH public key format
terraform to create an EC2 instance and use a public key to login to EC2 instance is not working.
aws_key_pair.auth: Error import KeyPair: InvalidKey.Format: Key is not in valid OpenSSH public key format

this is part of the main.tf to create a keypair

```<code>    main.tf

    resource "aws_key_pair" "auth" {
      key_name   = "${var.key_name}"
      public_key = "${file(var.public_key_path)}"
    }
</code>```

declaring the variable

```<code>    variable.tf

    variable "public_key_path" {
      description = <<DESCRIPTION
    Path to the SSH public key to be used for authentication.
    Ensure this keypair is added to your local SSH agent so provisioners can
    connect.
    Example: ~/.ssh/terraform.pub
    DESCRIPTION
      default = "~/.ssh/terraform.pub"
    }
</code>```

placeholder for the keys

```<code>~/.ssh/terraform.pub
resource "aws_key_pair" "deployer" {
  key_name   = "newssh"
  public_key = "ssh-rsa
}
</code>```

答:
You need to add your SSH key to your ssh-agent

Ensure ssh-agent is enabled and running in the background

```<code>$ eval "$(ssh-agent -s)"
</code>```

Add your SSH key to the ssh-agent. If you used an existing SSH key rather than generating a new SSH key, you’ll need to replace id_rsa in the command with the name of your existing private key file.

```<code>$ ssh-add ~/.ssh/id_rsa
</code>```

so in your case

```<code>$ ssh-add ~/.ssh/terraform
</code>```

Then run terraform apply

Body:
terraform to create an EC2 instance and use a public key to login to EC2 instance is not working.
aws_key_pair.auth: Error import KeyPair: InvalidKey.Format: Key is not in valid OpenSSH public key format

this is part of the main.tf to create a keypair

    main.tf

    resource "aws_key_pair" "auth" {
      key_name   = "${var.key_name}"
      public_key = "${file(var.public_key_path)}"
    }

declaring the variable

    variable.tf

    variable "public_key_path" {
      description = <<DESCRIPTION
    Path to the SSH public key to be used for authentication.
    Ensure this keypair is added to your local SSH agent so provisioners can
    connect.
    Example: ~/.ssh/terraform.pub
    DESCRIPTION
      default = "~/.ssh/terraform.pub"
    }

placeholder for the keys

~/.ssh/terraform.pub
resource "aws_key_pair" "deployer" {
  key_name   = "newssh"
  public_key = "ssh-rsa
}

Body:
You need to add your SSH key to your ssh-agent

Ensure ssh-agent is enabled and running in the background

$ eval "$(ssh-agent -s)"

Add your SSH key to the ssh-agent. If you used an existing SSH key rather than generating a new SSH key, you’ll need to replace id_rsa in the command with the name of your existing private key file.

$ ssh-add ~/.ssh/id_rsa

so in your case

$ ssh-add ~/.ssh/terraform

Then run terraform apply


问:
CSOM 2013 error: Unable to cast object of type 'System.Collections.Generic.Dictionary
I'm using this code to loop columns of a SharePoint 2013 List.

```<code>    currentContext.Load(currentList.Fields);
    currentContext.ExecuteQuery();

    foreach (Field f in currentList.Fields) {

    }
</code>```

No problem with normal columns. But, when I arrive to a lookup column I have this error:

"Unable to cast object of type
  'System.Collections.Generic.Dictionary`2[System.String,System.Object]'
  to type 'Microsoft.SharePoint.Client.Field'."

I found for example this discussion

答:
This issue came when we were working with TaxonomyFieldValue fields. For us changing references was not an option. This helped:

```<code>TaxonomyItem dummy = new TaxonomyItem(web.Context, null);
</code>```

It will force program to load adequate libraries forcing correct type in runtime.

Body:
I'm using this code to loop columns of a SharePoint 2013 List.

    currentContext.Load(currentList.Fields);
    currentContext.ExecuteQuery();

    foreach (Field f in currentList.Fields) {

    }

No problem with normal columns. But, when I arrive to a lookup column I have this error:

"Unable to cast object of type
  'System.Collections.Generic.Dictionary`2[System.String,System.Object]'
  to type 'Microsoft.SharePoint.Client.Field'."

I found for example this discussion

Body:
This issue came when we were working with TaxonomyFieldValue fields. For us changing references was not an option. This helped:

TaxonomyItem dummy = new TaxonomyItem(web.Context, null);

It will force program to load adequate libraries forcing correct type in runtime.


问:
How to populate a List of strings from a DataTable?
I'm trying to populate a List with a column of a DataTable in order to later convert it to a AutoCompleteStringCollection later. Is there a neater way to do it than the "good old" For Each?

Is there a way to use myDataTable.Rows.CopyTo for this task?

Cheers! = )

答: No, I don't believe so.  You can do some fancy LINQ expressions, but they all get boiled down to looping through the rows...</p>


问:
VBA problems with finding max values and copying names to a different worksheet
I experience a lot of trouble while designing my first code in Excel VBA. The problem is as following: in column B (worksheet 1), I inserted the names of some students. in column C, I inserted the marks of the corresponding students (see table 1).

In worksheet 2 table 2, I want cells A1:A3 to display the names of the 3 best students. After watching a lot of YouTube tutorials, I still did not manage to figure out how to do it. Is there anyone who could help me designing this code in VBA?

Table 1 worksheet 1:

```<code>Student Mark
Alex    9,5
Sophie  7
Nick    8
Paul    4
Helena  9
jan 6
</code>```

table 2 worksheet 2:

```<code>Best students
?
?
?
</code>```

答:
you don't need any coding for that. Just create a Pivot Table from your data (one column for student, the other one for mark), and use the "Top 10..." Filter to filter the top 3 marks. See the screenshot (unfortunately, I have only German version of Excel, but hope that the screenshot can help point you in the right direction).

Pivot Table Screenshot (German)

Body:
I experience a lot of trouble while designing my first code in Excel VBA. The problem is as following: in column B (worksheet 1), I inserted the names of some students. in column C, I inserted the marks of the corresponding students (see table 1).

In worksheet 2 table 2, I want cells A1:A3 to display the names of the 3 best students. After watching a lot of YouTube tutorials, I still did not manage to figure out how to do it. Is there anyone who could help me designing this code in VBA?

Table 1 worksheet 1:

Student Mark
Alex    9,5
Sophie  7
Nick    8
Paul    4
Helena  9
jan 6

table 2 worksheet 2:

Best students
?
?
?


答:
You can't use an aggregate function, like COUNT in a WHERE clause. You can, however, use an aggregate function in a HAVING clause. See this question for more on the difference between WHERE and HAVING.

However, if you're just trying to get the rows in cg that don't have any  joined rows from cgu, you can select where cgu.id is null.

For example:

SELECT cg
FROM App:ChannelGroup cg
LEFT JOIN cg.channelGroupUsers cgu
WHERE cgu.id IS NULL
```

Title: How to get COUNT of LEFT JOIN data


问:
How can I check if any of my boolean variable is false in VB.NET
Can I ask if is this is the only way to check if a variable is false in VB.net?

here is my code

```<code>if a = true and b = true and c = true then
     msgbox("ok")
else if a= true and b = true and c = false then
     msgbox("c has errors")
else if a= true and b = false and c = true then
     msgbox("b has errors")
else if a= false and b = true and c = true then
     msgbox("a has errors")
end if
</code>```

答:
I will solve it checking each one of the Boolean then storing the error if any.</p>

```<code>Dim Report as String = ""

If a = false Then
    Report = Report & vbCrlf & "a has errors"
End If

If b = false Then
    Report = Report & vbCrlf & "b has errors"
End If

If c = false Then
    Report = Report & vbCrlf & "c has errors"
End If

If Report = "" Then
    Msgbox("OK")
Else
    Msgbox(Report)
End If
</code>```

Body:
Can I ask if is this is the only way to check if a variable is false in VB.net?

here is my code

if a = true and b = true and c = true then
     msgbox("ok")
else if a= true and b = true and c = false then
     msgbox("c has errors")
else if a= true and b = false and c = true then
     msgbox("b has errors")
else if a= false and b = true and c = true then
     msgbox("a has errors")
end if

Body:
I will solve it checking each one of the Boolean then storing the error if any.

Dim Report as String = ""

If a = false Then
    Report = Report & vbCrlf & "a has errors"
End If

If b = false Then
    Report = Report & vbCrlf & "b has errors"
End If

If c = false Then
    Report = Report & vbCrlf & "c has errors"
End If

If Report = "" Then
    Msgbox("OK")
Else
    Msgbox(Report)
End If


问:
Working code needs to be refactored to increase speed
I have some working code but it takes a long time to return the results to a textbox. The output could take up to 20 seconds to output, and I don't have much data to sift through.

I get the correct output but it is not working good.

```<code>    Global variable:string newLine = Environment.NewLine;

    public List<string> AppointmentTypesForReport(int month)
    {
        List<string> appointments = new List<string>();

        string CS = ConfigurationManager.ConnectionStrings["U04i5a"].ConnectionString;
        using (MySqlConnection con = new MySqlConnection(CS))
        {
            try
            {
                con.Open();
                MySqlCommand cmd = con.CreateCommand();
                cmd.CommandText = "SELECT type FROM appointment WHERE MONTH(start) = @month";
                cmd.Parameters.AddWithValue("@month", month);
                cmd.ExecuteNonQuery();

                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        appointments.Add(reader["type"].ToString());
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        return appointments;
    }

    private void TypesByMonthRadioButton_CheckedChanged(object sender, EventArgs e)
    {
        ReportsTextBox.Clear();
        //resultTextBox.Text = string.Empty;

        var typesOutput = "";

        for (int m = 1; m <= 6; m++)
        {
            List<string> list = AppointmentTypesForReport(m);

            var j = from t in list
                    group t by t into g
                    let totalNumber = g.Count()
                    orderby totalNumber descending
                    select new { Returned = g.Key, Tally = totalNumber };

            typesOutput += newLine + DateTimeFormatInfo.CurrentInfo.GetMonthName(m) + newLine;

            //convert to lambda
            foreach (var t in j)
            {
                typesOutput += "Type of appointment scheduled: " + t.Returned + "   " + "-Appointments of this type: " + t.Tally + newLine;
            }
        }
        ReportsTextBox.Text = typesOutput;
    }
</code>```

When the code runs, the following is the output in the text box.

January
Type of appointment scheduled: xyz   -Appointments of this type: 2

February

March

April

May
Type of appointment scheduled: General Doctor   -Appointments of this type: 1

June
Type of appointment scheduled: General Doctor   -Appointments of this type: 1

答:
At least you should use StringBuilder to build result string:

```<code> var typesOutput = new StringBuilder();
 ...
 //typesOutput += newLine + DateTimeFormatInfo.CurrentInfo.GetMonthName(m) + newLine;
 typesOutput.AppendLine();
 typesOutput.AppendLine(DateTimeFormatInfo.CurrentInfo.GetMonthName(m));
 ...
 //typesOutput += "Type of appointment scheduled: " + t.Returned + "   " + "-Appointments of this type: " + t.Tally + newLine;
 typesOutput.AppendFormat("Type of appointment scheduled: {0} - Appointments of this type:  {1}\n", t.Returned, t.Tally);
 ...
 ReportsTextBox.Text = typesOutput.ToString();
</code>```

Body:
I have some working code but it takes a long time to return the results to a textbox. The output could take up to 20 seconds to output, and I don't have much data to sift through.

I get the correct output but it is not working good.

    Global variable:string newLine = Environment.NewLine;

    public List<string> AppointmentTypesForReport(int month)
    {
        List<string> appointments = new List<string>();

        string CS = ConfigurationManager.ConnectionStrings["U04i5a"].ConnectionString;
        using (MySqlConnection con = new MySqlConnection(CS))
        {
            try
            {
                con.Open();
                MySqlCommand cmd = con.CreateCommand();
                cmd.CommandText = "SELECT type FROM appointment WHERE MONTH(start) = @month";
                cmd.Parameters.AddWithValue("@month", month);
                cmd.ExecuteNonQuery();

                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        appointments.Add(reader["type"].ToString());
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        return appointments;
    }

    private void TypesByMonthRadioButton_CheckedChanged(object sender, EventArgs e)
    {
        ReportsTextBox.Clear();
        //resultTextBox.Text = string.Empty;

        var typesOutput = "";

        for (int m = 1; m <= 6; m++)
        {
            List<string> list = AppointmentTypesForReport(m);

            var j = from t in list
                    group t by t into g
                    let totalNumber = g.Count()
                    orderby totalNumber descending
                    select new { Returned = g.Key, Tally = totalNumber };

            typesOutput += newLine + DateTimeFormatInfo.CurrentInfo.GetMonthName(m) + newLine;

            //convert to lambda
            foreach (var t in j)
            {
                typesOutput += "Type of appointment scheduled: " + t.Returned + "   " + "-Appointments of this type: " + t.Tally + newLine;
            }
        }
        ReportsTextBox.Text = typesOutput;
    }

When the code runs, the following is the output in the text box.

January
Type of appointment scheduled: xyz   -Appointments of this type: 2

February

March

April

May
Type of appointment scheduled: General Doctor   -Appointments of this type: 1

June
Type of appointment scheduled: General Doctor   -Appointments of this type: 1

Body:
At least you should use StringBuilder to build result string:

 var typesOutput = new StringBuilder();
 ...
 //typesOutput += newLine + DateTimeFormatInfo.CurrentInfo.GetMonthName(m) + newLine;
 typesOutput.AppendLine();
 typesOutput.AppendLine(DateTimeFormatInfo.CurrentInfo.GetMonthName(m));
 ...
 //typesOutput += "Type of appointment scheduled: " + t.Returned + "   " + "-Appointments of this type: " + t.Tally + newLine;
 typesOutput.AppendFormat("Type of appointment scheduled: {0} - Appointments of this type:  {1}\n", t.Returned, t.Tally);
 ...
 ReportsTextBox.Text = typesOutput.ToString();


问:
How to install and import pandas from python script for specific operating system?
Is there a way for python to detect the OS and then install pandas from the file, and then import it? Basically, I need all my pandas code to function when he invokes the .py file. Please help! </p>

```<code>import pandas as pd

excel_file = r"C:\Users\XXXXXX\Downloads\Record.csv"

df = pd.read_csv(excel_file)
</code>```

答:
Sure,

Just add these lines before the line you "import pandas as pd":

```<code>import subprocess
test = subprocess.Popen("python -m pip install pandas", stdout=subprocess.PIPE)
test.communicate()
</code>```

This lines will open cmd and install pandas library then your code could import pandas.

Body:
Is there a way for python to detect the OS and then install pandas from the file, and then import it? Basically, I need all my pandas code to function when he invokes the .py file. Please help!

import pandas as pd

excel_file = r"C:\Users\XXXXXX\Downloads\Record.csv"

df = pd.read_csv(excel_file)

Body:
Sure,

Just add these lines before the line you "import pandas as pd":

import subprocess
test = subprocess.Popen("python -m pip install pandas", stdout=subprocess.PIPE)
test.communicate()

This lines will open cmd and install pandas library then your code could import pandas.


问:
How to print $1, $2 and then all remaining parameters together in AWK
I'm making a script that generates aliases/abbreviations from a base file. The base file structure is something like this:

```<code>sctl   sudo         systemctl
pac    sudo         pacman
</code>```

This works fine with the following code that reads the base file, removes comments and awks the abbreviation line on the abbreviation file:

```<code>    sed "s/\s*#.*$//;/^\s*$/d" $command_file |
    awk -v c=$cmd -v o="$comp" '{ print c" "$1""o"\""$2" "$3"\"" }' >> $file
</code>```

And the end result would be something like this:

```<code>abbr sctl "sudo systemctl"
abbr pac "sudo pacman"
</code>```

But this code doesn't work when the line has many parts after the 3rd parameter:

```<code>svu    playerctl    -p spotify volume +0.05
</code>```

How can i go about printing in that format? $1 $2 ($3..$N)

答:
You never need sed when you're using awk. Given this input file:

```<code>$ cat file
sctl   sudo         systemctl   # here is a comment
        # and here is another
pac    sudo         pacman

svu    playerctl    -p spotify volume +0.05
</code>```

here's what your sed+awk outputs:

```<code>$ sed "s/\s*#.*$//;/^\s*$/d" file |  awk -v c="abbr" -v o=" " '{ print c" "$1""o"\""$2" "$3"\"" }'
abbr sctl "sudo systemctl"
abbr pac "sudo pacman"
abbr svu "playerctl -p"
</code>```

which you can get just from awk alone:

```<code>$ awk -v c="abbr" -v o=" " '{sub(/\s*#.*/,"")} NF{print c" "$1""o"\""$2" "$3"\""}' file
abbr sctl "sudo systemctl"
abbr pac "sudo pacman"
abbr svu "playerctl -p"
</code>```

and which you can then adjust to do what you want:

```<code>$ awk -v c="abbr" -v o=" " '{sub(/\s*#.*/,"")} NF{x=$1; sub(/^\S+\s+/,""); $1=$1; print c, x o "\"" $0 "\""}' file
abbr sctl "sudo systemctl"
abbr pac "sudo pacman"
abbr svu "playerctl -p spotify volume +0.05"
</code>```

or (I can't tell from your question what you want inside/outside of the double quotes):

```<code>$ awk -v c="abbr" -v o=" " '{sub(/\s*#.*/,"")} NF{x=$1" "$2; sub(/^(\S+\s+){2}/,""); $1=$1; print c, x o "\"" $0 "\""}' file
abbr sctl sudo "systemctl"
abbr pac sudo "pacman"
abbr svu playerctl "-p spotify volume +0.05"
</code>```

The above uses GNU awk for \s and \S - with other awks use [[:space:]] and [^[:space:]] instead.

Since we're using GNU awk, though, we can do the job more concisely and efficiently with the 3rd arg to match():

```<code>$ awk -v c="abbr" -v o=" " '{sub(/\s*#.*/,""); $1=$1} match($0,/(\S+) (.*)/,a){print c, a[1] o "\"" a[2] "\""}' file
abbr sctl "sudo systemctl"
abbr pac "sudo pacman"
abbr svu "playerctl -p spotify volume +0.05"

$ awk -v c="abbr" -v o=" " '{sub(/\s*#.*/,""); $1=$1} match($0,/(\S+ \S+) (.*)/,a){print c, a[1] o "\"" a[2] "\""}' file
abbr sctl sudo "systemctl"
abbr pac sudo "pacman"
abbr svu playerctl "-p spotify volume +0.05"
</code>```

Body:
I'm making a script that generates aliases/abbreviations from a base file. The base file structure is something like this:

sctl   sudo         systemctl
pac    sudo         pacman

This works fine with the following code that reads the base file, removes comments and awks the abbreviation line on the abbreviation file:

    sed "s/\s*#.*$//;/^\s*$/d" $command_file |
    awk -v c=$cmd -v o="$comp" '{ print c" "$1""o"\""$2" "$3"\"" }' >> $file

And the end result would be something like this:

abbr sctl "sudo systemctl"
abbr pac "sudo pacman"

But this code doesn't work when the line has many parts after the 3rd parameter:

svu    playerctl    -p spotify volume +0.05

How can i go about printing in that format? $1 $2 ($3..$N)

Body:
You never need sed when you're using awk. Given this input file:

$ cat file
sctl   sudo         systemctl   # here is a comment
        # and here is another
pac    sudo         pacman

svu    playerctl    -p spotify volume +0.05

here's what your sed+awk outputs:

$ sed "s/\s*#.*$//;/^\s*$/d" file |  awk -v c="abbr" -v o=" " '{ print c" "$1""o"\""$2" "$3"\"" }'
abbr sctl "sudo systemctl"
abbr pac "sudo pacman"
abbr svu "playerctl -p"

which you can get just from awk alone:

$ awk -v c="abbr" -v o=" " '{sub(/\s*#.*/,"")} NF{print c" "$1""o"\""$2" "$3"\""}' file
abbr sctl "sudo systemctl"
abbr pac "sudo pacman"
abbr svu "playerctl -p"

and which you can then adjust to do what you want:

$ awk -v c="abbr" -v o=" " '{sub(/\s*#.*/,"")} NF{x=$1; sub(/^\S+\s+/,""); $1=$1; print c, x o "\"" $0 "\""}' file
abbr sctl "sudo systemctl"
abbr pac "sudo pacman"
abbr svu "playerctl -p spotify volume +0.05"

or (I can't tell from your question what you want inside/outside of the double quotes):

$ awk -v c="abbr" -v o=" " '{sub(/\s*#.*/,"")} NF{x=$1" "$2; sub(/^(\S+\s+){2}/,""); $1=$1; print c, x o "\"" $0 "\""}' file
abbr sctl sudo "systemctl"
abbr pac sudo "pacman"
abbr svu playerctl "-p spotify volume +0.05"

The above uses GNU awk for \s and \S - with other awks use [[:space:]] and [^[:space:]] instead.

Since we're using GNU awk, though, we can do the job more concisely and efficiently with the 3rd arg to match():

$ awk -v c="abbr" -v o=" " '{sub(/\s*#.*/,""); $1=$1} match($0,/(\S+) (.*)/,a){print c, a[1] o "\"" a[2] "\""}' file
abbr sctl "sudo systemctl"
abbr pac "sudo pacman"
abbr svu "playerctl -p spotify volume +0.05"

$ awk -v c="abbr" -v o=" " '{sub(/\s*#.*/,""); $1=$1} match($0,/(\S+ \S+) (.*)/,a){print c, a[1] o "\"" a[2] "\""}' file
abbr sctl sudo "systemctl"
abbr pac sudo "pacman"
abbr svu playerctl "-p spotify volume +0.05"


问:
When using a UINavigationController the viewWillAppear or viewDidAppear methods of my controller are not called
Here is the pitch.

I have a UIViewController subclass which does something in its viewWillAppear and viewDidAppear methods.

I want to nest this view controller in a UINavigationViewController.

Depending on the view hierarchy complexity the two methods viewWillAppear and viewDidAppear of my controller may not be called.

What should I do then to make sure these two methods are always called regardless of my view hierarchy?

Example of a "complex" view hierarchy:

```<code>UIViewController subclass containing a UITabBarController
     |_ Each tab containing a UINavigationViewController
         |_ Each UINavigationController controller containing a custom UIViewController
</code>```

When you present the TabBarController as a modal view the viewWillAppear and viewDidAppear methods of the TabBarController are called but not those of the custom UIViewControllers nested under the UINavigationViewControllers.

答:
The above solution not works for me. My case is the custom view controller nested under a complex UINavigationController not gets called viewWillAppear and viewDidAppear. Use below in custom view controller: </p>

```<code>beginAppearanceTransition(true, animated: animated)  // Tells a child controller its appearance is about to change. Do not invoke viewWillAppear(_:), viewWillDisappear(_:), viewDidAppear(_:), or viewDidDisappear(_:) directly.
endAppearanceTransition() // Tells a child controller its appearance has changed.
</code>```

Body:
Here is the pitch.

I have a UIViewController subclass which does something in its viewWillAppear and viewDidAppear methods.

I want to nest this view controller in a UINavigationViewController.

Depending on the view hierarchy complexity the two methods viewWillAppear and viewDidAppear of my controller may not be called.

What should I do then to make sure these two methods are always called regardless of my view hierarchy?

Example of a "complex" view hierarchy:

UIViewController subclass containing a UITabBarController
     |_ Each tab containing a UINavigationViewController
         |_ Each UINavigationController controller containing a custom UIViewController

When you present the TabBarController as a modal view the viewWillAppear and viewDidAppear methods of the TabBarController are called but not those of the custom UIViewControllers nested under the UINavigationViewControllers.

Body:
The above solution not works for me. My case is the custom view controller nested under a complex UINavigationController not gets called viewWillAppear and viewDidAppear. Use below in custom view controller:

beginAppearanceTransition(true, animated: animated)  // Tells a child controller its appearance is about to change. Do not invoke viewWillAppear(_:), viewWillDisappear(_:), viewDidAppear(_:), or viewDidDisappear(_:) directly.
endAppearanceTransition() // Tells a child controller its appearance has changed.


问:
Wrong annotation generated by XJC for extended base64Binary element
I have a web service to export image files. The entities of the web service are defined in a XSD schema and using xjc we generate the java classes used in the service response.

In the XSD the image is defined as a complexType that extends the base64Binary simple type.

<xsd:complexType name="image">
        <xsd:simpleContent>
            <xsd:extension base="xsd:base64Binary">
                <xsd:attribute name="nil" type="xsd:boolean" use="optional"/>
                <xsd:attribute name="overwrite" type="xsd:boolean"
                               use="optional"/>
                <xsd:attribute name="origin" type="xsd:string" use="optional"/>
            </xsd:extension>
        </xsd:simpleContent>
    </xsd:complexType>

```

<p>With xjc we generate the java classes and I get the following:</p>

<pre class="lang-java prettyprint-override"><code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "image", propOrder = {
    "value"
})
public class Image {

    @XmlValue
    protected byte[] value;
    @XmlAttribute(name = "nil")
    protected Boolean nil;
    @XmlAttribute(name = "overwrite")
    protected Boolean overwrite;
    @XmlAttribute(name = "origin")
    protected String origin;
</code>```

The value property has the annotation @XMlValue instead of @XmlSchemaType(name="base64Binary").

When testing the web service using SoapUI, instead of getting the base64 string with the image, I get the toString() result of the byte array image.

[B@11a0f47b

But if I manually change the @XmlValue annotation by the @XmlSchemaType(name="base64Binary"), the result is correct.

<ns1:value>LzlqLzRBQVFTa1pKUmdBQkFnQUFBUU....</ns1:value>
```

答:
Try to remove

<xsd:simpleContent>
```

in the type definition.

if doesn't work, replace with <xsd:complexContent>

Body:
I have a web service to export image files. The entities of the web service are defined in a XSD schema and using xjc we generate the java classes used in the service response.

In the XSD the image is defined as a complexType that extends the base64Binary simple type.

<xsd:complexType name="image">
        <xsd:simpleContent>
            <xsd:extension base="xsd:base64Binary">
                <xsd:attribute name="nil" type="xsd:boolean" use="optional"/>
                <xsd:attribute name="overwrite" type="xsd:boolean"
                               use="optional"/>
                <xsd:attribute name="origin" type="xsd:string" use="optional"/>
            </xsd:extension>
        </xsd:simpleContent>
    </xsd:complexType>

With xjc we generate the java classes and I get the following:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "image", propOrder = {
    "value"
})
public class Image {

    @XmlValue
    protected byte[] value;
    @XmlAttribute(name = "nil")
    protected Boolean nil;
    @XmlAttribute(name = "overwrite")
    protected Boolean overwrite;
    @XmlAttribute(name = "origin")
    protected String origin;

The value property has the annotation @XMlValue instead of @XmlSchemaType(name="base64Binary").

When testing the web service using SoapUI, instead of getting the base64 string with the image, I get the toString() result of the byte array image.

[B@11a0f47b

But if I manually change the @XmlValue annotation by the @XmlSchemaType(name="base64Binary"), the result is correct.

<ns1:value>LzlqLzRBQVFTa1pKUmdBQkFnQUFBUU....</ns1:value>

Body:
Try to remove

<xsd:simpleContent>

in the type definition.

if doesn't work, replace with <xsd:complexContent>


问:
How to crate random data for the struct in julia?
I have created a structure, txn:

```<code>struct txn
    txn_id::Int64
    bank::String
    branch::String
    teller::String
    customer::String
    account::String
    timestamp::DateTime
    dr_cr::String
    amount::Float64
end
</code>```

Please guide me in creating random data for the struct!

Update 1:

With reference to Professor Bogumił Kamiński's advice, adding domains of fields as follows:

```<code>a) txn_id is a unique integer(auto incrementing)
b) bank is a 20 character Legal Entity Identifier
c) branch is a 8 or 11 character Business Identifier Codes(SWIFT-BIC)
d) teller is a 9 digit Social Security Number
e) customer is a 9 digit Social Security Number or a 20 character Legal Entity Identifier
f) account is an 34 character International Bank Account Number(IBAN)
g) timestamp is a iso8601 date-time.
h) dr_cr is in (dr, cr)
i) amount > 0.0000
</code>```

答:
This question is not specified precisely enough, as "random" is an ambiguous term, therefore what you ask for does not have a single solution.

In general if you say "random" you should specify the domain and the distribution over this domain. Given this here is a solution that automatically detects field types of the struct and populates them with uniform pseudorandom samples from prespecified domains.

```<code>using Dates

domains = Dict(Int => 1:10,
               String => string.('a':'z'),
               DateTime => DateTime("2019-01-01"):Day(1):DateTime("2019-05-30"))

struct Txn
    txn_id::Int64
    bank::String
    branch::String
    teller::String
    customer::String
    account::String
    timestamp::DateTime
    dr_cr::String
    amount::Int64
end

Txn_rand() = Txn(map(t -> rand(domains[t]), fieldtypes(Txn))...)
</code>```

And now you can write:

```<code>julia> Txn_rand()
Txn(3, "q", "f", "j", "m", "z", 2019-03-10T00:00:00, "c", 1)

julia> Txn_rand()
Txn(8, "e", "o", "m", "l", "z", 2019-04-05T00:00:00, "p", 5)

julia> Txn_rand()
Txn(3, "k", "u", "c", "z", "y", 2019-03-13T00:00:00, "x", 1)
</code>```

EDIT

Given the comment here is how I would approach the generation of the Txn structure (you can probably be more specific e.g. by giving a closed list of bank and branch values etc. as you probably have it - then use the approach proposed above):

```<code>using Dates, Random

global TXN_ID_COUNTER = 1

function Txn_rand()
    global TXN_ID_COUNTER += 1
    Txn(TXN_ID_COUNTER,
        randstring('A':'Z', 20),
        randstring('A':'Z', rand(Bool) ? 8 : 11),
        rand(Bool) ? randstring('1':'9', 9) : randstring('A':'Z', 20),
        randstring('1':'9', 9),
        randstring('A':'Z', 2) * randstring('1':'9', 32),
        rand(DateTime("2019-01-01"):Second(1):DateTime("2019-05-30")),
        rand(["dr", "cr"]),
        rand(1:100000) / 10000
       )
end
</code>```

I also omit validation of the generated fields (which in general you could do as some of them have validation rules).

Body:
I have created a structure, txn:

struct txn
    txn_id::Int64
    bank::String
    branch::String
    teller::String
    customer::String
    account::String
    timestamp::DateTime
    dr_cr::String
    amount::Float64
end

Please guide me in creating random data for the struct!

Update 1:

With reference to Professor Bogumił Kamiński's advice, adding domains of fields as follows:

a) txn_id is a unique integer(auto incrementing)
b) bank is a 20 character Legal Entity Identifier
c) branch is a 8 or 11 character Business Identifier Codes(SWIFT-BIC)
d) teller is a 9 digit Social Security Number
e) customer is a 9 digit Social Security Number or a 20 character Legal Entity Identifier
f) account is an 34 character International Bank Account Number(IBAN)
g) timestamp is a iso8601 date-time.
h) dr_cr is in (dr, cr)
i) amount > 0.0000

Body:
This question is not specified precisely enough, as "random" is an ambiguous term, therefore what you ask for does not have a single solution.

In general if you say "random" you should specify the domain and the distribution over this domain. Given this here is a solution that automatically detects field types of the struct and populates them with uniform pseudorandom samples from prespecified domains.

using Dates

domains = Dict(Int => 1:10,
               String => string.('a':'z'),
               DateTime => DateTime("2019-01-01"):Day(1):DateTime("2019-05-30"))

struct Txn
    txn_id::Int64
    bank::String
    branch::String
    teller::String
    customer::String
    account::String
    timestamp::DateTime
    dr_cr::String
    amount::Int64
end

Txn_rand() = Txn(map(t -> rand(domains[t]), fieldtypes(Txn))...)

And now you can write:

julia> Txn_rand()
Txn(3, "q", "f", "j", "m", "z", 2019-03-10T00:00:00, "c", 1)

julia> Txn_rand()
Txn(8, "e", "o", "m", "l", "z", 2019-04-05T00:00:00, "p", 5)

julia> Txn_rand()
Txn(3, "k", "u", "c", "z", "y", 2019-03-13T00:00:00, "x", 1)

EDIT

Given the comment here is how I would approach the generation of the Txn structure (you can probably be more specific e.g. by giving a closed list of bank and branch values etc. as you probably have it - then use the approach proposed above):

using Dates, Random

global TXN_ID_COUNTER = 1

function Txn_rand()
    global TXN_ID_COUNTER += 1
    Txn(TXN_ID_COUNTER,
        randstring('A':'Z', 20),
        randstring('A':'Z', rand(Bool) ? 8 : 11),
        rand(Bool) ? randstring('1':'9', 9) : randstring('A':'Z', 20),
        randstring('1':'9', 9),
        randstring('A':'Z', 2) * randstring('1':'9', 32),
        rand(DateTime("2019-01-01"):Second(1):DateTime("2019-05-30")),
        rand(["dr", "cr"]),
        rand(1:100000) / 10000
       )
end

I also omit validation of the generated fields (which in general you could do as some of them have validation rules).


问:
Tensorflow tf.data.Dataset API, dataset unzip function?
In tensorflow 1.12 there is the Dataset.zip function: documented here.

However, I was wondering if there is a dataset unzip function which will return back the original two datasets.

```<code># NOTE: The following examples use `{ ... }` to represent the
# contents of a dataset.
a = { 1, 2, 3 }
b = { 4, 5, 6 }
c = { (7, 8), (9, 10), (11, 12) }
d = { 13, 14 }

# The nested structure of the `datasets` argument determines the
# structure of elements in the resulting dataset.
Dataset.zip((a, b)) == { (1, 4), (2, 5), (3, 6) }
Dataset.zip((b, a)) == { (4, 1), (5, 2), (6, 3) }

# The `datasets` argument may contain an arbitrary number of
# datasets.
Dataset.zip((a, b, c)) == { (1, 4, (7, 8)),
                            (2, 5, (9, 10)),
                            (3, 6, (11, 12)) }

# The number of elements in the resulting dataset is the same as
# the size of the smallest dataset in `datasets`.
Dataset.zip((a, d)) == { (1, 13), (2, 14) }
</code>```

I would like to have the following

```<code>dataset = Dataset.zip((a, d)) == { (1, 13), (2, 14) }
a, d = dataset.unzip()
</code>```

答:
Building on Ouwen Huang's answer, this function seems to work for arbitrary datasets:</p>

```<code>def split_datasets(dataset):
    tensors = {}
    names = list(dataset.element_spec.keys())
    for name in names:
        tensors[name] = dataset.map(lambda x: x[name])

    return tensors
</code>```

Body:
In tensorflow 1.12 there is the Dataset.zip function: documented here.

However, I was wondering if there is a dataset unzip function which will return back the original two datasets.

# NOTE: The following examples use `{ ... }` to represent the
# contents of a dataset.
a = { 1, 2, 3 }
b = { 4, 5, 6 }
c = { (7, 8), (9, 10), (11, 12) }
d = { 13, 14 }

# The nested structure of the `datasets` argument determines the
# structure of elements in the resulting dataset.
Dataset.zip((a, b)) == { (1, 4), (2, 5), (3, 6) }
Dataset.zip((b, a)) == { (4, 1), (5, 2), (6, 3) }

# The `datasets` argument may contain an arbitrary number of
# datasets.
Dataset.zip((a, b, c)) == { (1, 4, (7, 8)),
                            (2, 5, (9, 10)),
                            (3, 6, (11, 12)) }

# The number of elements in the resulting dataset is the same as
# the size of the smallest dataset in `datasets`.
Dataset.zip((a, d)) == { (1, 13), (2, 14) }

I would like to have the following

dataset = Dataset.zip((a, d)) == { (1, 13), (2, 14) }
a, d = dataset.unzip()

Body:
Building on Ouwen Huang's answer, this function seems to work for arbitrary datasets:

def split_datasets(dataset):
    tensors = {}
    names = list(dataset.element_spec.keys())
    for name in names:
        tensors[name] = dataset.map(lambda x: x[name])

    return tensors


问:
Gmail stripping link color from emails?
Everything renders fine apart from link colors.. These are my links.

```<code><a href="http://www.facebook.com.." style="color:#000000;text-decoration:none;font-weight:bold">Facebook</a>

<a href="http://www.twitter.com/..." style="color:#000000;">Twitter</a>
</code>```

However, in gmail. These links are converted to this.

```<code><a href="http://www.facebook.com.." style="text-decoration:none;font-weight:bold">Facebook</a>

<a href="http://www.twitter.com/..." style="">Twitter</a>
</code>```

OK, so maybe gmail does this for all emails? I look around. Lots of blue links. I then open up a youtube message.

```<code><a target="_blank" style="color:#e12e31;font-family:arial,verdana,sans-serif;text-transform:uppercase;text-decoration:none" href="...">Play all »</a>
</code>```

Curious.. very curious. YouTube isn't having this problem that I am having. Can anyone else modify link colors in gmail when sending html emails? How are you doing it?

答:
Unfortunately it appears all the Answers here are for older Gmail, prior to the 2016/2017 update. None of the Answers provided prior to 2016 here work.

In modern Gmail Web and Gmail for Android, you need to trick Gmail into thinking you're trying to style a link-button, by setting a background color:

```<code>a.btn {
  color: #fff;
  background: #ffa100;
  text-decoration: none;
  text-transform: uppercase;
  padding: 5px 12px 6px 12px;
  border-radius: 5px;
  box-shadow: 0 3px 6px rgba(0,0,0,.18);
}
</code>```

For the curious, it becomes this style, injected as the last style tag in the head of the overall Gmail Web page:

```<code>.msg-6177286137221397679 a.m_-6177286137221397679btn{
    color:#fff;
    background:#ffa100;
    text-decoration:none;
    text-transform:uppercase;
    padding:5px 12px 6px 12px;
    border-radius:5px
}
</code>```

It's all on one minified line with the rest of the styles in actual Gmail; I've gently pretty-printed it here for comparison. You can see my box-shadow was thrown out, yet that didn't kill the entire style rule. You can also see a couple other important things that everyone says you can't do in Gmail, that turn out to no longer be true:

Padding is working

Tag-level style is working - that is, it's a.btn, whereas most Gmail advice tells you to never use tag styles, and only apply class-level styles

While a link-button like above is what Gmail is probably hoping for, you can trick it with, for example:

```<code>body {
    background: #ededed;
}
table.main a {
    color: #1c95cd;
    background: #ededed;
}
</code>```

And that's enough, your link color style survives because Gmail naively considers this a link button.

Title: Gmail stripping link color from emails?

Body:
Everything renders fine apart from link colors.. These are my links.

Facebook

Twitter

However, in gmail. These links are converted to this.

Facebook

Twitter

OK, so maybe gmail does this for all emails? I look around. Lots of blue links. I then open up a youtube message.

Play all »

Curious.. very curious. YouTube isn't having this problem that I am having. Can anyone else modify link colors in gmail when sending html emails? How are you doing it?

Body:
Unfortunately it appears all the Answers here are for older Gmail, prior to the 2016/2017 update. None of the Answers provided prior to 2016 here work.

In modern Gmail Web and Gmail for Android, you need to trick Gmail into thinking you're trying to style a link-button, by setting a background color:

a.btn {
  color: #fff;
  background: #ffa100;
  text-decoration: none;
  text-transform: uppercase;
  padding: 5px 12px 6px 12px;
  border-radius: 5px;
  box-shadow: 0 3px 6px rgba(0,0,0,.18);
}

For the curious, it becomes this style, injected as the last style tag in the head of the overall Gmail Web page:

.msg-6177286137221397679 a.m_-6177286137221397679btn{
    color:#fff;
    background:#ffa100;
    text-decoration:none;
    text-transform:uppercase;
    padding:5px 12px 6px 12px;
    border-radius:5px
}

It's all on one minified line with the rest of the styles in actual Gmail; I've gently pretty-printed it here for comparison. You can see my box-shadow was thrown out, yet that didn't kill the entire style rule. You can also see a couple other important things that everyone says you can't do in Gmail, that turn out to no longer be true:

Padding is working

Tag-level style is working - that is, it's a.btn, whereas most Gmail advice tells you to never use tag styles, and only apply class-level styles

While a link-button like above is what Gmail is probably hoping for, you can trick it with, for example:

body {
    background: #ededed;
}
table.main a {
    color: #1c95cd;
    background: #ededed;
}

And that's enough, your link color style survives because Gmail naively considers this a link button.


问:
How to use a function as a property of an object inside another function in javascript
I'm trying to create a function that will take object as a parameter and inside the object I want to have an object method just same way jQuery ajax works. My problem now is that I can't get that object method to work.

function myAjax({
  type,
  url,
  success
}) {
  var suc = "";
  typeof type === "undefined" ? type = "GET" : type = type;

  var req = new XMLHttpRequest();
  req.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      suc = this.responseText;
      //alert(this.responseText);
    }
  };
  req.open(type, url, false);
  req.setRequestHeader("Content-type", "application/x-www-form-urlencoded ");
  req.send("fname=chijioke&lname=francis");

  function success(suc) {}
  }

  myAjax({
    type: "post",
    url: "page.html",
    success: function(e) {
      alert(e);
    }
  });
```

<p>I want to do something similar to this jQuery ajax call</p>

<pre class="lang-js prettyprint-override"><code>$.ajax({
  type: "post",
  url: "index",
  data: {
    id: id
  },
  success: function(feedback) {
    alert(feedback);
  }
});
</code>```

I need to get the responseText through the success function but it is not working. I want this to work like that of jQuery ajax success, this is really for learning purpose.

答:
The "success" method is already declared when you execute myAjax, so do not need to declare it again in myAjax.

Try this:

```<code>function myAjax(type, url, success) {
    var suc = "";
    typeof type === "undefined" ? type = "GET" : type = type;

    var req = new XMLHttpRequest();
    req.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            suc = this.responseText;
            success(suc); //Call to outside method
        }
    };
    req.open(type, url, false);
    req.setRequestHeader("Content-type", "application/x-www-form-
    urlencoded ");
    req.send("fname=chijioke&lname=francis");
}
</code>```

Body:
I'm trying to create a function that will take object as a parameter and inside the object I want to have an object method just same way jQuery ajax works. My problem now is that I can't get that object method to work.

function myAjax({
  type,
  url,
  success
}) {
  var suc = "";
  typeof type === "undefined" ? type = "GET" : type = type;

  var req = new XMLHttpRequest();
  req.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      suc = this.responseText;
      //alert(this.responseText);
    }
  };
  req.open(type, url, false);
  req.setRequestHeader("Content-type", "application/x-www-form-urlencoded ");
  req.send("fname=chijioke&lname=francis");

  function success(suc) {}
  }

  myAjax({
    type: "post",
    url: "page.html",
    success: function(e) {
      alert(e);
    }
  });

I want to do something similar to this jQuery ajax call

$.ajax({
  type: "post",
  url: "index",
  data: {
    id: id
  },
  success: function(feedback) {
    alert(feedback);
  }
});

I need to get the responseText through the success function but it is not working. I want this to work like that of jQuery ajax success, this is really for learning purpose.

Body:
The "success" method is already declared when you execute myAjax, so do not need to declare it again in myAjax.

Try this:

function myAjax(type, url, success) {
    var suc = "";
    typeof type === "undefined" ? type = "GET" : type = type;

    var req = new XMLHttpRequest();
    req.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            suc = this.responseText;
            success(suc); //Call to outside method
        }
    };
    req.open(type, url, false);
    req.setRequestHeader("Content-type", "application/x-www-form-
    urlencoded ");
    req.send("fname=chijioke&lname=francis");
}