问:
axios.post doesn't seem to work?
Maybe I am just not using axios correctly but I currently have a react front-end and node.js back end.

I am trying to POST to my api endpoint "/api/:id/addItem" but nothing is logging when making the request.

Here is my code:

ListForm component ->

```<code>import React from 'react';
import * as helpers from '../helpers';

class ListForm extends React.Component {
  state = {
    value: ''
  }

  handSubmit = e => {
    e.preventDefault();
    helpers.addItem(this.props.currentUser.googleId, this.state.value);

    this.setState({value: ''});
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input type="text"
          value={this.state.value}
          onChange={e => this.setState({value: e.target.value})}
        />
        <button>Add item</button>
      </form>
    );
  }
}

export default ListForm;
</code>```

Routes ->

```<code>const mongoose = require('mongoose');
const User = require('../models/userSchema');

module.exports = (app) => {
  app.post('/api/:id/addItem', (req, res) => {
    console.log('HEY!');
  });
};
</code>```

helpers.js ->

```<code>import axios from 'axios';

export const fetchUser = async () => {
  const resp = await axios.get('/api/current_user');

  return resp.data;
}

export const addItem = async (id, newItem) => {
  const resp = await axios.post("/api/" + id + "/addItem", newItem);

  return resp.data;
}
</code>```

Package.json to show forwarding requests->

```<code>{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "proxy": {
    "/auth/google": {
      "target": "http://localhost:5000"
    },
    "/api/*": {
      "target": "http://localhost:5000"
    }
  },
  "dependencies": {
    "axios": "^0.17.1",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-scripts": "1.0.17"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}
</code>```

答:
Issue here is with newItem , its not json it's just simple value

```<code>axios.post("/api/" + id + "/addItem", newItem);
</code>```

It should be like :

```<code>axios.post("/api/" + id + "/addItem", {value : newItem});
</code>```

Or pass json from addItem :

```<code>helpers.addItem(this.props.currentUser.googleId, this_should_be_json );
</code>```

Title: axios.post doesn't seem to work?

Body:
Maybe I am just not using axios correctly but I currently have a react front-end and node.js back end.

I am trying to POST to my api endpoint "/api/:id/addItem" but nothing is logging when making the request.

Here is my code:

ListForm component ->

import React from 'react';
import * as helpers from '../helpers';

class ListForm extends React.Component {
  state = {
    value: ''
  }

  handSubmit = e => {
    e.preventDefault();
    helpers.addItem(this.props.currentUser.googleId, this.state.value);

    this.setState({value: ''});
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input type="text"
          value={this.state.value}
          onChange={e => this.setState({value: e.target.value})}
        />
        <button>Add item</button>
      </form>
    );
  }
}

export default ListForm;

Routes ->

const mongoose = require('mongoose');
const User = require('../models/userSchema');

module.exports = (app) => {
  app.post('/api/:id/addItem', (req, res) => {
    console.log('HEY!');
  });
};

helpers.js ->

import axios from 'axios';

export const fetchUser = async () => {
  const resp = await axios.get('/api/current_user');

  return resp.data;
}

export const addItem = async (id, newItem) => {
  const resp = await axios.post("/api/" + id + "/addItem", newItem);

  return resp.data;
}

Package.json to show forwarding requests->

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "proxy": {
    "/auth/google": {
      "target": "http://localhost:5000"
    },
    "/api/*": {
      "target": "http://localhost:5000"
    }
  },
  "dependencies": {
    "axios": "^0.17.1",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-scripts": "1.0.17"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

Body:
Issue here is with newItem , its not json it's just simple value

axios.post("/api/" + id + "/addItem", newItem);

It should be like :

axios.post("/api/" + id + "/addItem", {value : newItem});

Or pass json from addItem :

helpers.addItem(this.props.currentUser.googleId, this_should_be_json );


来源: stackexchange

问:
put content in block
I have some element and want to put all them in block when screen size is less than 900px

```<code><a href="#home">Home</a>
<a href="#news">News</a>
<div class="dropdown">
  <img style="width:30px;height:auto;" src="/escapologinphpto.jpeg">
  <button class="dropbtn" onclick="myFunction()">Dropdown
          <!-- <i class="fa fa-caret-down"></i> -->
        </button>
  <div class="dropdown-content" id="myDropdown">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
  </div>
</div>
</code>```

here is link of work till now
https://jsfiddle.net/153qkyoh/

答:
You can achieve this by using the CSS media query. However, you need know the various breakpoints for certain devices and screen types.
We have 992px as a screen breakpoint which is the closest to 900px.

```<code>@media screen and ( max-width: 992px) {
    a {
        display: block;
    }
}
</code>```

Or should incase the link elements display property is being inherited, you can add the - !important keyword to ignore all inherited styles connected to it.

```<code>@media screen and ( max-width: 992px) {
    a {
        display: block !important;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: put content in block

Body:
I have some element and want to put all them in block when screen size is less than 900px

Home
News

  <button class="dropbtn" onclick="myFunction()">Dropdown

        </button>

    Link 1
    Link 2
    Link 3

here is link of work till now
https://jsfiddle.net/153qkyoh/

Body:
You can achieve this by using the CSS media query. However, you need know the various breakpoints for certain devices and screen types.
We have 992px as a screen breakpoint which is the closest to 900px.

@media screen and ( max-width: 992px) {
    a {
        display: block;
    }
}

Or should incase the link elements display property is being inherited, you can add the - !important keyword to ignore all inherited styles connected to it.

@media screen and ( max-width: 992px) {
    a {
        display: block !important;
    }
}


问:
What does this symbol mean in C++? "~"
If we use ~ before a function like this: ~func();, what does this mean?

Thanks.

答:
If it is ~Foo, where Foo is a class, it is a destructor.

If it is used in other cases, it is the bitwise negation operator. It flips all the bits set to 1 to 0, and vice versa.

ContentLicense: CC BY-SA 2.5

Title: What does this symbol mean in C++? "~"


问:
Retrieve a file from browser using API gateway, AWS LAMBDA and S3
The setup is using S3 as a storage, API gateway for the rest endpoint and Lambda (Python) for get/fetch of file in S3.

I'm using Boto3 for the Lambda function (Python) to check if the file exists in S3, and I was able to download it but being stored in Lambda machine ("/tmp"). The API Gateway can trigger the lambda function already. Is there a way that once the lambda function is triggered then the download will happen in the browser?

Thanks!

答:
Here is how we did it:

Check and Redirect:

API Gateway --> Lambda (return 302)

Deliver Content:

CloudFront --> S3

Check for S3 existence with Lambda returning a 302 to cloudfront. You can also return Signed URL from Lambda with a valid time to access the URL from CloudFront.

Hope it helps.


问:
designing layout of magento 2 theme

I am new to Magento.

I am creating Magenta 2 site, I have managed to install Magento, and for it to use the luma theme.

I want to be able to edit the theme (through Inheritance), I understand it uses XML files to design the layout, how do I change these, should they be in the new theme folder, and change them there?

If so, where do I get the origonal Luma xml files, or does magento create these? - There are no themes within the app/ folder, is it here where I create the new theme (that inherits from Luma)?

Many thanks for any help, I am completely new to Magento.

答:
You have to create a custom theme and make theme.xml and set a parent to LUMA.
Now app/design/frontend/customthemename

So anything that you want to customized used in customthemename folder

Thanks

Title: designing layout of magento 2 theme


问:
How to build index map with multiple value from list in python with elegant way?
I want to build a dict in python from a list, the key of the dict is the first column and the value of the map is the second column. Is there any elegant way to implement this?

For example,

A= [[1,2], [1,3], [2,3]]

The result is

M={1:[2,3],2:[3]}

My own way is

for row in A:
    if row[0] not in M: M[row[0]] = []
    M[row[0]].append(row[1])

Is there any better solution? Functional Programming methods are preferred.

答:
One way to do this is with a defaultdict

```<code>from collections import defaultdict

A= [[1,2], [1,3], [2,3]]
d = defaultdict(list)
for k, v in A:
    d[k].append(v)
</code>```

Body:
One way to do this is with a defaultdict

from collections import defaultdict

A= [[1,2], [1,3], [2,3]]
d = defaultdict(list)
for k, v in A:
    d[k].append(v)


问:
Keyboard interrupt tensorflow run and save at that point
Is there a way to break a tensorflow session by keyboard interrupt and have the option to save the model at that point? I currently leave the session running overnight but need to stop it so I can free memory for pc use during the day. As the training progresses each epoch gets slower so there are times when I may have to wait hours for the next scheduled save in the program. I'd like the functionality of being able to break into the run at any time and save from that point. I can't even find if that's possible. Would appreciate a pointer.</p>

答:
One option is to subclass the tf.Session object and create an __exit__ function that saves out the current state as the keyboard interrupt passes through.  This would only work when the new object is called as part of a with block.

Here is the subclass:

```<code>import tensorflow as tf

class SessionWithExitSave(tf.Session):
    def __init__(self, *args, saver=None, exit_save_path=None, **kwargs):
        self.saver = saver
        self.exit_save_path = exit_save_path
        super().__init__(*args, **kwargs)

    def __exit__(self, exc_type, exc_value, exc_tb):
        if exc_type is KeyboardInterrupt:
            if self.saver:
                self.saver.save(self, self.exit_save_path)
                print('Output saved to: "{}./*"'.format(self.exit_save_path))
        super().__exit__(exc_type, exc_value, exc_tb)
</code>```

Example usage from the TensorFlow mnist walkthrough.

```<code>import tensorflow as tf
import datetime as dt
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('U:/mnist/', one_hot=True)
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x, W) + b
# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(cross_entropy)

saver = tf.train.Saver()

with SessionWithExitSave(
        saver=saver,
        exit_save_path='./tf-saves/_lastest.ckpt') as sess:
    sess.run(tf.global_variables_initializer())
    total_epochs = 50
    for epoch in range(1, total_epochs+1):
        for _ in range(1000):
            batch_xs, batch_ys = mnist.train.next_batch(100)
            sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
        # Test trained model
        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

        print(f'Epoch {epoch} of {total_epochs} :: accuracy = ', end='')
        print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
        save_time = dt.datetime.now().strftime('%Y%m%d-%H.%M.%S')
        saver.save(sess, f'./tf-saves/mnist-{save_time}.ckpt')
</code>```

I let this run for 10 epochs before sending an interrupt signal from the keyboard.  Here is the output:

```<code>Epoch 1 of 50 :: accuracy = 0.9169
Epoch 2 of 50 :: accuracy = 0.919
Epoch 3 of 50 :: accuracy = 0.9205
Epoch 4 of 50 :: accuracy = 0.9221
Epoch 5 of 50 :: accuracy = 0.92
Epoch 6 of 50 :: accuracy = 0.9229
Epoch 7 of 50 :: accuracy = 0.9234
Epoch 8 of 50 :: accuracy = 0.9234
Epoch 9 of 50 :: accuracy = 0.9252
Epoch 10 of 50 :: accuracy = 0.9248
Output saved to: "./tf-saves/_lastest.ckpt./*"
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
...
--> 768   elif item[0].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
    769     return item[1]._is_present_in_parent
    770   else:
KeyboardInterrupt:
</code>```

And indeed, I do have all of the saved files include the save from the keyboard interrupt that was sent to the system.

```<code>import os

os.listdir('./tf-saves/')
# returns:
['checkpoint',
 'mnist-20171207-23.05.18.ckpt.data-00000-of-00001',
 'mnist-20171207-23.05.18.ckpt.index',
 'mnist-20171207-23.05.18.ckpt.meta',
 'mnist-20171207-23.05.22.ckpt.data-00000-of-00001',
 'mnist-20171207-23.05.22.ckpt.index',
 'mnist-20171207-23.05.22.ckpt.meta',
 'mnist-20171207-23.05.26.ckpt.data-00000-of-00001',
 'mnist-20171207-23.05.26.ckpt.index',
 'mnist-20171207-23.05.26.ckpt.meta',
 'mnist-20171207-23.05.31.ckpt.data-00000-of-00001',
 'mnist-20171207-23.05.31.ckpt.index',
 '_lastest.ckpt.data-00000-of-00001',
 '_lastest.ckpt.index',
 '_lastest.ckpt.meta']
</code>```

Body:
One option is to subclass the tf.Session object and create an __exit__ function that saves out the current state as the keyboard interrupt passes through.  This would only work when the new object is called as part of a with block.

Here is the subclass:

import tensorflow as tf

class SessionWithExitSave(tf.Session):
    def __init__(self, *args, saver=None, exit_save_path=None, **kwargs):
        self.saver = saver
        self.exit_save_path = exit_save_path
        super().__init__(*args, **kwargs)

    def __exit__(self, exc_type, exc_value, exc_tb):
        if exc_type is KeyboardInterrupt:
            if self.saver:
                self.saver.save(self, self.exit_save_path)
                print('Output saved to: "{}./*"'.format(self.exit_save_path))
        super().__exit__(exc_type, exc_value, exc_tb)

Example usage from the TensorFlow mnist walkthrough.

import tensorflow as tf
import datetime as dt
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('U:/mnist/', one_hot=True)
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x, W) + b
# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(cross_entropy)

saver = tf.train.Saver()

with SessionWithExitSave(
        saver=saver,
        exit_save_path='./tf-saves/_lastest.ckpt') as sess:
    sess.run(tf.global_variables_initializer())
    total_epochs = 50
    for epoch in range(1, total_epochs+1):
        for _ in range(1000):
            batch_xs, batch_ys = mnist.train.next_batch(100)
            sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
        # Test trained model
        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

        print(f'Epoch {epoch} of {total_epochs} :: accuracy = ', end='')
        print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
        save_time = dt.datetime.now().strftime('%Y%m%d-%H.%M.%S')
        saver.save(sess, f'./tf-saves/mnist-{save_time}.ckpt')

I let this run for 10 epochs before sending an interrupt signal from the keyboard.  Here is the output:

Epoch 1 of 50 :: accuracy = 0.9169
Epoch 2 of 50 :: accuracy = 0.919
Epoch 3 of 50 :: accuracy = 0.9205
Epoch 4 of 50 :: accuracy = 0.9221
Epoch 5 of 50 :: accuracy = 0.92
Epoch 6 of 50 :: accuracy = 0.9229
Epoch 7 of 50 :: accuracy = 0.9234
Epoch 8 of 50 :: accuracy = 0.9234
Epoch 9 of 50 :: accuracy = 0.9252
Epoch 10 of 50 :: accuracy = 0.9248
Output saved to: "./tf-saves/_lastest.ckpt./*"
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
...
--> 768   elif item[0].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE:
    769     return item[1]._is_present_in_parent
    770   else:
KeyboardInterrupt:

And indeed, I do have all of the saved files include the save from the keyboard interrupt that was sent to the system.

import os

os.listdir('./tf-saves/')
# returns:
['checkpoint',
 'mnist-20171207-23.05.18.ckpt.data-00000-of-00001',
 'mnist-20171207-23.05.18.ckpt.index',
 'mnist-20171207-23.05.18.ckpt.meta',
 'mnist-20171207-23.05.22.ckpt.data-00000-of-00001',
 'mnist-20171207-23.05.22.ckpt.index',
 'mnist-20171207-23.05.22.ckpt.meta',
 'mnist-20171207-23.05.26.ckpt.data-00000-of-00001',
 'mnist-20171207-23.05.26.ckpt.index',
 'mnist-20171207-23.05.26.ckpt.meta',
 'mnist-20171207-23.05.31.ckpt.data-00000-of-00001',
 'mnist-20171207-23.05.31.ckpt.index',
 '_lastest.ckpt.data-00000-of-00001',
 '_lastest.ckpt.index',
 '_lastest.ckpt.meta']


问:
Overwriting data in memory
I've written a password manager in Ocaml. In order to make it as secure as possible, I'd like to store a string (an encryption key) in memory in such a way that it can be overwritten. Since Ocaml is pass by value , and there's a garbage collector, this has proven difficult. I encrypt all buffers and variables I can, but I still need a "session key" stored to do this. To prevent this from being detected by automated key searching programs or put into swap, it's assembled from a bunch of random data in a buffer using a random increment. So really, all I need is a single variable that can be overwritten for the assembled key for a few seconds before it's passed into the Nocrypto library... Would a reference work for this?

According to this cornell "Refs and Arrays" page, refs are mutable and work similarly to pointers in C. That being said, I also found a stack overflow answer discussing Ocaml refs, in which the answer mentions "they act like pointers to new allocated memory". Does this mean every time, it just allocates a new thing in memory instead of actually mutating the stuff in memory? If so, you couldn't really "overwrite" a ref.

Other possible solutions I've come across are Bigarrays, and "custom blocks". I'm not entirely sure if "custom blocks" are actually allocated outside of the scope of garbage collection or not. They seem like they're used to access external C code. Are they copied around by the garbage collector? Could they be "overwritten?" There's also this idea of "opaque bytes" and opaque objects in memory. I'm having a pretty hard time wrapping my head around how this all fits together. A useful but confusing (to me) discussion of custom blocks in memory on stack overflow is here: Are custom blocks ever copied in memory? Answer says they can be moved around. Even so, could they be overwritten?

The last possible solution is to store it using a Cstruct like the Nocrypto library seems to do. They discuss it in this github issue: Secret material erasure The asker states:

"Granted, most key material is Cstruct.t, which is a Bigarray.Array1.t, which is allocated outside of the GC heap"

Is this even correct? If so, I can't seem to find a source file that actually does this. I'm pretty new to Ocaml and functional programming in general. If you're curious, my program is located on github here: ocaml-pass

答:
I would use a value of type bytes, essentially a mutable array of bytes:

```<code># let buffer = Bytes.make 16 'x';;
val buffer : bytes = "xxxxxxxxxxxxxxxx"
# Bytes.set buffer 0 'T';;
- : unit = ()
# buffer;;
- : bytes = "Txxxxxxxxxxxxxxx"
# Bytes.fill buffer 0 16 ' ';;
- : unit = ()
# buffer;;
- : bytes = "                "
</code>```

You can overwrite with Bytes.fill after you're done.

Title: Overwriting data in memory

Body:
I would use a value of type bytes, essentially a mutable array of bytes:

# let buffer = Bytes.make 16 'x';;
val buffer : bytes = "xxxxxxxxxxxxxxxx"
# Bytes.set buffer 0 'T';;
- : unit = ()
# buffer;;
- : bytes = "Txxxxxxxxxxxxxxx"
# Bytes.fill buffer 0 16 ' ';;
- : unit = ()
# buffer;;
- : bytes = "                "

You can overwrite with Bytes.fill after you're done.


问:
Nativescript Angular - Only white after splashscreen with Webpack for ios
after working on an app for quite a while all that's left now is improving startup timings - and the given solution for that is Webpack.
Using npm run start-android-bundle produces an app that works as intended (with some minor problems with firebase).

But using npm run start-ios-bundle produces an app that starts with the splash screen and then only shows white. Unlike other problems here on StackOverflow it doesn't just need a few seconds on the white screen but the starting component never shows up, without throwing an error.

Has anyone encountered the same problem or has an idea how to fix this problem?

答:
Many thanks to Nick Iliev for looking into the matter. The problem was in the Firebase-plugin and has been addressed here: https://github.com/EddyVerbruggen/nativescript-plugin-firebase/issues/564.

Updating nativescript-plugin-firebase should fix the problem


答:
You can use setdefault:

```<code>A= [[1,2], [1,3], [2,3]]
M = {}
for k,v in A:
    M.setdefault(k, []).append(v)

M
# {1: [2, 3], 2: [3]}
</code>```

If it must be functional (Disclaimer: wasteful, not recommended):

```<code>import operator, itertools
grps = itertools.groupby(sorted(A, key=operator.itemgetter(0)), operator.itemgetter(0))
M = {k: list(map(operator.itemgetter(1), v)) for k, v in grps}
M
# {1: [2, 3], 2: [3]}
</code>```

Title: How to build index map with multiple value from list in python with elegant way?

Body:
I want to build a dict in python from a list, the key of the dict is the first column and the value of the map is the second column. Is there any elegant way to implement this?

For example,

A= [[1,2], [1,3], [2,3]]

The result is

M={1:[2,3],2:[3]}

My own way is

for row in A:
    if row[0] not in M: M[row[0]] = []
    M[row[0]].append(row[1])

Is there any better solution? Functional Programming methods are preferred.

Body:
You can use setdefault:

A= [[1,2], [1,3], [2,3]]
M = {}
for k,v in A:
    M.setdefault(k, []).append(v)

M
# {1: [2, 3], 2: [3]}

If it must be functional (Disclaimer: wasteful, not recommended):

import operator, itertools
grps = itertools.groupby(sorted(A, key=operator.itemgetter(0)), operator.itemgetter(0))
M = {k: list(map(operator.itemgetter(1), v)) for k, v in grps}
M
# {1: [2, 3], 2: [3]}


问:
Compiling and serving React components individually
We are using Laravel Mix to compile react components and serve them individually to the respective pages where they are needed - It's not a SPA.

I'm new to React, so excuse my ignorance. I'm trying to get my head around the current setup and find out if it's the proper way of having multiple components in the same page.

So the boilerplate below has been copied and pasted in every component, only changing the selector, e.g.:

```<code>'use strict'
import React from 'react'
import ReactDOM from 'react-dom'
import {Provider} from 'react-redux'
import {createStore, applyMiddleware, compose} from 'redux'
import ReduxPromise from 'redux-promise'
import App from './containers/App'
import reducers from './reducers'

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
const enhancer = composeEnhancers(
    applyMiddleware(ReduxPromise),
)
const newstore = createStore(reducers, enhancer)

ReactDOM.render(
    <Provider store={newstore}>
        <App />
    </Provider>, document.querySelector('.component-foo')
)
</code>```

Some components also differ slightly in how the store is created, e.g. redux devtools is not always present.

So, coming from Vue.js, that doesn't make much sense to me - in Vue.js you'd use a single file to import everything related to the framework and then load each component you need with a single line of code. But this React setup seems to be doing quite the opposite: loading a separate instance of React and Redux for every component in the page, as if I had multiple root/app components in Vue.js.

Is it right to assume React is being bundled and booted multiple times and would that be the proper way to do things?

答:
You're almost certainly doing this wrong. Yes, its very likely you are bundling and booting React multiple times, but no that is not the proper way to do things. It seems you are trying to use the Vue paradigm to do this but with code copied from a React SPA which is why you are building this monstrosity.

May I suggest checking basic react+laravel tutorials before you proceed? simple google search showed this: https://code.tutsplus.com/tutorials/build-a-react-app-with-laravel-backend-part-2-react--cms-29443 and I'm sure there are many others.

Since you are new to react, avoid redux for now and just get familiar with putting up react with multiple components. only then add the redux state management IF YOU NEED IT.

Body:
We are using Laravel Mix to compile react components and serve them individually to the respective pages where they are needed - It's not a SPA.

I'm new to React, so excuse my ignorance. I'm trying to get my head around the current setup and find out if it's the proper way of having multiple components in the same page.

So the boilerplate below has been copied and pasted in every component, only changing the selector, e.g.:

'use strict'
import React from 'react'
import ReactDOM from 'react-dom'
import {Provider} from 'react-redux'
import {createStore, applyMiddleware, compose} from 'redux'
import ReduxPromise from 'redux-promise'
import App from './containers/App'
import reducers from './reducers'

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
const enhancer = composeEnhancers(
    applyMiddleware(ReduxPromise),
)
const newstore = createStore(reducers, enhancer)

ReactDOM.render(
    <Provider store={newstore}>
        <App />
    </Provider>, document.querySelector('.component-foo')
)

Some components also differ slightly in how the store is created, e.g. redux devtools is not always present.

So, coming from Vue.js, that doesn't make much sense to me - in Vue.js you'd use a single file to import everything related to the framework and then load each component you need with a single line of code. But this React setup seems to be doing quite the opposite: loading a separate instance of React and Redux for every component in the page, as if I had multiple root/app components in Vue.js.

Is it right to assume React is being bundled and booted multiple times and would that be the proper way to do things?


问:
Save repeated calculations in Python Pandas

In Pandas, I can use .apply to apply functions to two columns. For example,
</p>

```<code>df = pd.DataFrame({'A':['a', 'a', 'a', 'b'], 'B':[3, 3, 2, 5], 'C':[2, 2, 2, 8]})
formula = lambda x: (x.B + x.C)**2
df.apply(formula, axis=1)
</code>```

<p>
But, notice that results on the first two rows are the same since all the inputs are the same. In large dataset with complicated operations. These repeated calculations is likely to slow down my program. Is there a way that I can program it so that I can save time with these repeated calculations?
</p>

答:
You can use a technique called  memoization. For functions which accept hashable arguments, you can use the built-in functools.lru_cache.

```<code>from functools import lru_cache

@lru_cache(maxsize=None)
def cached_function(B, C):
    return (B + C)**2

def formula(x):
    return cached_function(x.B, x.C)
</code>```

Notice that I had to pass the values through to the cached function for lru_cache to work correctly because Series objects aren't hashable.

Body:
In Pandas, I can use .apply to apply functions to two columns. For example,

df = pd.DataFrame({'A':['a', 'a', 'a', 'b'], 'B':[3, 3, 2, 5], 'C':[2, 2, 2, 8]})
formula = lambda x: (x.B + x.C)**2
df.apply(formula, axis=1)

But, notice that results on the first two rows are the same since all the inputs are the same. In large dataset with complicated operations. These repeated calculations is likely to slow down my program. Is there a way that I can program it so that I can save time with these repeated calculations?

Body:
You can use a technique called  memoization. For functions which accept hashable arguments, you can use the built-in functools.lru_cache.

from functools import lru_cache

@lru_cache(maxsize=None)
def cached_function(B, C):
    return (B + C)**2

def formula(x):
    return cached_function(x.B, x.C)

Notice that I had to pass the values through to the cached function for lru_cache to work correctly because Series objects aren't hashable.


问:
Google API is showing an old address for a business

I was trying to create a direct link to a Google business review.  I went to the Google Place ID and found the company, but it's showing both the old (at the top) and current address (in the box with the ID code)
I have a screenshot that shows the Google Place ID page with the old address and new address
</p>

<p>
How can I update the information at the top so that both addresses are the same, current listing?
</p>

答:
It seems this issue is happening in Google Maps as well. I would like to suggest in Google Maps, look for the Menu Icon (located at the top left part of the page) and click "Send feedback". In there, you can either choose "Suggest an edit" or "Other feedback". Just provide clear details on how to reproduce your concern.

On the other hand, if you are the owner of this business, you can manage or edit locations in your Google My Business API. Just be informed that it may take some time for your edits to take effect.

Hope this helps you!

Body:
I was trying to create a direct link to a Google business review.  I went to the Google Place ID and found the company, but it's showing both the old (at the top) and current address (in the box with the ID code)
I have a screenshot that shows the Google Place ID page with the old address and new address

How can I update the information at the top so that both addresses are the same, current listing?


问:
object gets hit but the score is not updating
I wrote a simple game (will show just the trouble part) Everything is working great except the health score. I  put a print statement to check if one object gets hit by another. So, the if statement is True because I see the print statement, but my health score is not updating. Am I missing something here? Thank you for your help!

```<code>sqrls = pygame.image.load("crazySquirrel1.gif")
sqrlsrect = sqrls.get_rect()
sqrls_startx = 200
sqrls_starty = 530
sqrlsrect.center = (sqrls_startx, sqrls_starty)

girl = pygame.image.load('girl1.gif')
girlrect = girl.get_rect()
x = 850
y = 278
girlrect.center = (x, y)
screen.blit(girl,(x, y))

## adding health score
health = 3
font = pygame.font.SysFont("Comic Sans MS", 20)
text = font.render("Health: " + str(health),1, RED)
## main game loop **********************************
x_change = 0
endGame = False

while not endGame:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                x_change = -2
            elif event.key == pygame.K_RIGHT:
                x_change = 2
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    x_change = 0
    x += x_change

    sqrlsrect = sqrlsrect.move(sqrls_speed) # moving squirrel 1
    if sqrlsrect.left < 0 or sqrlsrect.right > w:
        sqrls_speed[0] = -sqrls_speed[0]
    if sqrlsrect.top < 0 or sqrlsrect.bottom > h:
        sqrls_speed[1] = -sqrls_speed[1]

    if sqrlsrect.center == girlrect.center:
       print ('Ouch s!')
       health -= 1

    screen.blit(bg, (0, 0))
    screen.blit(sqrls, sqrlsrect)
    screen.blit(girl, (x, y))
    screen.blit(text, (w*0.88, h*0.03))

    pygame.display.update()
    clock.tick(60)

pygame.quit()
quit()
</code>```

答:
Although you are modifying health, you aren't modifying the actual text which is being displayed. Instead, try using the following:

```<code>if sqrlsrect.center == girlrect.center:
       print ('Ouch s!')
       health -= 1
       text = font.render("Health: " + str(health),1, RED)
</code>```

Body:
I wrote a simple game (will show just the trouble part) Everything is working great except the health score. I  put a print statement to check if one object gets hit by another. So, the if statement is True because I see the print statement, but my health score is not updating. Am I missing something here? Thank you for your help!

sqrls = pygame.image.load("crazySquirrel1.gif")
sqrlsrect = sqrls.get_rect()
sqrls_startx = 200
sqrls_starty = 530
sqrlsrect.center = (sqrls_startx, sqrls_starty)

girl = pygame.image.load('girl1.gif')
girlrect = girl.get_rect()
x = 850
y = 278
girlrect.center = (x, y)
screen.blit(girl,(x, y))

## adding health score
health = 3
font = pygame.font.SysFont("Comic Sans MS", 20)
text = font.render("Health: " + str(health),1, RED)
## main game loop **********************************
x_change = 0
endGame = False

while not endGame:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                x_change = -2
            elif event.key == pygame.K_RIGHT:
                x_change = 2
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    x_change = 0
    x += x_change

    sqrlsrect = sqrlsrect.move(sqrls_speed) # moving squirrel 1
    if sqrlsrect.left < 0 or sqrlsrect.right > w:
        sqrls_speed[0] = -sqrls_speed[0]
    if sqrlsrect.top < 0 or sqrlsrect.bottom > h:
        sqrls_speed[1] = -sqrls_speed[1]

    if sqrlsrect.center == girlrect.center:
       print ('Ouch s!')
       health -= 1

    screen.blit(bg, (0, 0))
    screen.blit(sqrls, sqrlsrect)
    screen.blit(girl, (x, y))
    screen.blit(text, (w*0.88, h*0.03))

    pygame.display.update()
    clock.tick(60)

pygame.quit()
quit()

Body:
Although you are modifying health, you aren't modifying the actual text which is being displayed. Instead, try using the following:

if sqrlsrect.center == girlrect.center:
       print ('Ouch s!')
       health -= 1
       text = font.render("Health: " + str(health),1, RED)


问:
Getting Trying to get property of non-object error

Trying to display values from database for a specific id using json and php

When I do var dump all correct values are displayed

```<code>function getItemByID($id) {

    //Connect to database and server
    include ("connect.php") ;

    if (!$connect) {
    die("Connection failed: " . mysqli_connect_error());
    }

    $sql = "SELECT * FROM items WHERE id ='".$id."'";
    $res1 = mysqli_query($connect, $sql);

    $rows = mysqli_fetch_assoc($res1);

    $itemtxt = '[{"id" : '.$rows['id'].',' ;
    $itemtxt = $itemtxt.'"item" : '.$rows['item'].',' ;
    $itemtxt = $itemtxt.'"image" : '.$rows['image'].',' ;
    $itemtxt = $itemtxt.'"descr" : '.$rows['descr'].'}] ,' ;

    $itemtxt = substr($itemtxt, 0, -2) ;

    var_dump($itemtxt);

    return $itemtxt;

}
</code>```

This is where the error gets displayed from on line 10,11,12,13

```<code><?php
    $id = $_GET['id'];

    include("library.php");

    $itemtxt = getItemByID($id);
    $itemjson = json_decode($itemtxt);

    echo $itemjson -> id;
    echo $itemjson -> item;
    echo $itemjson -> image;
    echo $itemjson -> descr;

?>
</code>```

Trying to get this data to display on this page but getting "Trying to get property of non object" error.

答:
I would just fetch the object from the start:

```<code>function getItemByID($id,$connect)
{
    if(!$connect)
        return false;
    elseif(!is_numeric($id))
        return false;

    $query = mysqli_query($connect, "SELECT * FROM items WHERE id ='{$id}'");
    return mysqli_fetch_object($query);
}
</code>```

To use:

```<code># Add connection
include("connect.php");
# You should have this bit right on the connect.php so you don't have to
# keep writing it on each page you use the connection
if (!$connect) {
    die("Connection failed: " . mysqli_connect_error());
}
# Make a check to make sure value is set and is numeric
$id = (isset($_GET['id']) && is_numeric($_GET['id']))? $_GET['id'] : false;
# I would include this at the top if it doesn't require $id, it would be cleaner
include("library.php");
# Feed in the connection and ID
$itemtxt = getItemByID($id,$connect);
# Check that it's filled and not empty
if(!empty($itemtxt)) {
    echo $itemtxt->id;
    echo $itemtxt->item;
    echo $itemtxt->image;
    echo $itemtxt->descr;
}
</code>```

Body:
Trying to display values from database for a specific id using json and php

When I do var dump all correct values are displayed

function getItemByID($id) {

    //Connect to database and server
    include ("connect.php") ;

    if (!$connect) {
    die("Connection failed: " . mysqli_connect_error());
    }

    $sql = "SELECT * FROM items WHERE id ='".$id."'";
    $res1 = mysqli_query($connect, $sql);

    $rows = mysqli_fetch_assoc($res1);

    $itemtxt = '[{"id" : '.$rows['id'].',' ;
    $itemtxt = $itemtxt.'"item" : '.$rows['item'].',' ;
    $itemtxt = $itemtxt.'"image" : '.$rows['image'].',' ;
    $itemtxt = $itemtxt.'"descr" : '.$rows['descr'].'}] ,' ;

    $itemtxt = substr($itemtxt, 0, -2) ;

    var_dump($itemtxt);

    return $itemtxt;

}

This is where the error gets displayed from on line 10,11,12,13

<?php
    $id = $_GET['id'];

    include("library.php");

    $itemtxt = getItemByID($id);
    $itemjson = json_decode($itemtxt);

    echo $itemjson -> id;
    echo $itemjson -> item;
    echo $itemjson -> image;
    echo $itemjson -> descr;

?>

Trying to get this data to display on this page but getting "Trying to get property of non object" error.

Body:
I would just fetch the object from the start:

function getItemByID($id,$connect)
{
    if(!$connect)
        return false;
    elseif(!is_numeric($id))
        return false;

    $query = mysqli_query($connect, "SELECT * FROM items WHERE id ='{$id}'");
    return mysqli_fetch_object($query);
}

To use:

# Add connection
include("connect.php");
# You should have this bit right on the connect.php so you don't have to
# keep writing it on each page you use the connection
if (!$connect) {
    die("Connection failed: " . mysqli_connect_error());
}
# Make a check to make sure value is set and is numeric
$id = (isset($_GET['id']) && is_numeric($_GET['id']))? $_GET['id'] : false;
# I would include this at the top if it doesn't require $id, it would be cleaner
include("library.php");
# Feed in the connection and ID
$itemtxt = getItemByID($id,$connect);
# Check that it's filled and not empty
if(!empty($itemtxt)) {
    echo $itemtxt->id;
    echo $itemtxt->item;
    echo $itemtxt->image;
    echo $itemtxt->descr;
}


问:
Functional Equivalent to Python Statement Logic
I'm trying to find the functional equivalent of logic statements in Python (e.g. and/or/not). I thought I had found them in the operator module, but the behavior is remarkable different.

For example, the and statement does the behavior I want, whereas operator.and_ seems to requir an explicit type comparison, or else it throws a TypeError exception.

```<code>>>> from operator import *
>>> class A: pass
...
>>> and_(A(), True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'instance' and 'bool'
>>> A() and True
True
</code>```

Is there something like the operator module, but containing functions that match the behavior of Python's statement logic exactly?

答:
The functions operator.and_ and operator.or_ are the equivalent of the bit-wise "and" function and "or" function, respectively.  There are no functions representing the and and or operators in operator, but you can use the built-ins any() and all() instead.  They will take a single sequence as argument, but you can simply pass a tuple of two entries to use them as binary operators.

Note that it is impossible to match the logic of and and or exactly with any function you call.  For example

```<code>False and sys.stdout.write("Hello")
</code>```

will never print anything, while

```<code>f(False, sys.stdout.write("Hello"))
</code>```

will always print the output, regardless how f() is defined.  This is also the reason they are omitted from operator.

Body:
I'm trying to find the functional equivalent of logic statements in Python (e.g. and/or/not). I thought I had found them in the operator module, but the behavior is remarkable different.

For example, the and statement does the behavior I want, whereas operator.and_ seems to requir an explicit type comparison, or else it throws a TypeError exception.

>>> from operator import *
>>> class A: pass
...
>>> and_(A(), True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'instance' and 'bool'
>>> A() and True
True

Is there something like the operator module, but containing functions that match the behavior of Python's statement logic exactly?

Body:
The functions operator.and_ and operator.or_ are the equivalent of the bit-wise "and" function and "or" function, respectively.  There are no functions representing the and and or operators in operator, but you can use the built-ins any() and all() instead.  They will take a single sequence as argument, but you can simply pass a tuple of two entries to use them as binary operators.

Note that it is impossible to match the logic of and and or exactly with any function you call.  For example

False and sys.stdout.write("Hello")

will never print anything, while

f(False, sys.stdout.write("Hello"))

will always print the output, regardless how f() is defined.  This is also the reason they are omitted from operator.


问:
Get CRC checksum of an NSData in Objective-C
How can I count CRC (32 or 64) of an NSData object in Objective-C?

Thanks in advance!

答:
From iOS11 use this:</p>

```<code>unsigned long result = crc32_z(0, data.bytes, data.length);
</code>```

Body:
From iOS11 use this:

unsigned long result = crc32_z(0, data.bytes, data.length);


问:
How to trigger method in controller when element is clicked in view for Rails?
The drop down list elements that I want to click on are

```<code><select class="store-select">
  <option value="" selected="selected">Please select</option>
  <option value="1">Administrator</option>
  <option value="2">User</option>
  <option value="3">Editor</option>
</select>
</code>```

And I want it to trigger an action in the controller based on the option that was clicked.  So one of the things I'm hoping to learn is how to access that value in the controller.  I also want to redirect the page after an option is clicked.  I'm able to redirect the page when other links are clicked in my view, but when I click on an element in the drop down list, it doesn't redirect.  It doesn't even go to the view for that method.  When an element in the drop down list is clicked it just stays on the current page.

```<code>def practice  # the redirect doesn't work in this method but works in others
    # redirect_to "https://tosbourn.com"
    render "ibotta/show"
end
</code>```

My application.js file looks as the following

```<code>$('.store-select').on('change', function() {
  $.ajax({
    url : '/users',
    type : 'GET',
    data : { user_id: this.value },
    dataType:'script'
  });
})
</code>```

My routes.rb file contains the following

```<code>get 'users' => 'smiths#practice'
</code>```

Let me know if there is anything I'm missing that you want to know about this problem.  Thank you.

答:
As you want to redirect on drop down change you can follow this

Suppose your drop down is

```<code><select name="select1" id="select1">
        <option value="0">Page1</option>
        <option value="1">Page2</option>
        <option value="2">Page3</option>
        <option value="3">Page4</option>
    </select>
</code>```

and your java script change event is

```<code>$select1.on( 'change', function() {
  switch(this.value){
    case '0':
      window.location = [page1url];
        break;
      case '1':
      window.location = [page2url];
        break;
      case '2':
      window.location = [page3url];
        break;
      case '3':
      window.location = [page4url];
        break;
  }
});
</code>```

you will redirect to urls you want on change

Body:
The drop down list elements that I want to click on are

<select class="store-select">
  <option value="" selected="selected">Please select</option>
  <option value="1">Administrator</option>
  <option value="2">User</option>
  <option value="3">Editor</option>
</select>

And I want it to trigger an action in the controller based on the option that was clicked.  So one of the things I'm hoping to learn is how to access that value in the controller.  I also want to redirect the page after an option is clicked.  I'm able to redirect the page when other links are clicked in my view, but when I click on an element in the drop down list, it doesn't redirect.  It doesn't even go to the view for that method.  When an element in the drop down list is clicked it just stays on the current page.

def practice  # the redirect doesn't work in this method but works in others
    # redirect_to "https://tosbourn.com"
    render "ibotta/show"
end

My application.js file looks as the following

$('.store-select').on('change', function() {
  $.ajax({
    url : '/users',
    type : 'GET',
    data : { user_id: this.value },
    dataType:'script'
  });
})

My routes.rb file contains the following

get 'users' => 'smiths#practice'

Let me know if there is anything I'm missing that you want to know about this problem.  Thank you.

Body:
As you want to redirect on drop down change you can follow this

Suppose your drop down is

<select name="select1" id="select1">
        <option value="0">Page1</option>
        <option value="1">Page2</option>
        <option value="2">Page3</option>
        <option value="3">Page4</option>
    </select>

and your java script change event is

$select1.on( 'change', function() {
  switch(this.value){
    case '0':
      window.location = [page1url];
        break;
      case '1':
      window.location = [page2url];
        break;
      case '2':
      window.location = [page3url];
        break;
      case '3':
      window.location = [page4url];
        break;
  }
});

you will redirect to urls you want on change


问:
Relay Modern nested pagination
I have a root query of songs, this is in a pagination container.
I then have a nested property on songs called comments that I also want to be paginated because I don't want to load 10k comments for each song all at once.

songsContainer.js:

```<code>fragment songsContainer on Query {
    songs(
      first: $count
      after: $cursor
      genre: $genre
      filter: $filter
    ) @connection(key: "songsContainer_songs") {
      edges {
        node {
          audioId
          name
          coverImageUrl
          artist
          likes
          dislikes
          ...commentsContainer
        }
      }
    }
  }

const connectionConfig = {
  direction: 'forward',
  query: graphql`
    query songsContainerForwardQuery(
      $count: Int!
      $cursor: String
      $genre: String
      $filter: FilterInput
    ) {
      ...songsContainer
    }
  `,
  getVariables: (_, { count, cursor }) => ({
    count,
    cursor,
  }),
};

paginationContainer(fragments, connectionConfig);
</code>```

commentsContainer.js

```<code>  fragment commentsContainer on Audio {
    comments(
      first: $count
      after: $cursor
      getReplies: $getReplies
    ) @connection(key: "commentsContainer_comments") {
      edges {
        node {
          commentId
          body
          date
          likes
          dislikes
          repliesCount
          originalComment {
            id
          }
          user {
            userName
          }
        }
      }
    }
  }
</code>```

How do I write the connectionConfig for the comments? I tried this:

```<code>const connectionConfig = {
  direction: 'forward',
  query: graphql`
    query commentsContainerForwardQuery(
      $count: Int!
      $cursor: String
    ) {
      ...commentsContainer
    }
  `,
  getVariables: (_, { count, cursor }) => ({
    count,
    cursor,
  }),
};
</code>```

But because the comments are nested on songs then it throws an error saying that the query doesn't exist on the Root.

答:
SongsContainer.js

```<code>createPaginationContainer(
  SongsContainer,
  {
    viewer: graphql`
      fragment SongsContainer_viewer on Query {
        id
        songs(first: $count, after: $cursor)
          @connection(key: "SongsContainer_songs", filters: []) {
          edges {
            cursor
            node {
              id
              ...SongItem_song
            }
          }
        }
      }
    `
  },
  {
    direction: 'forward',
    getConnectionFromProps(props) {
      return props.viewer && props.viewer.songs;
    },
    getFragmentVariables(prevVars, totalCount) {
      return {
        ...prevVars,
        count: totalCount
      };
    },
    getVariables(props, { count, cursor }, fragmentVariables) {
      return {
        count,
        cursor
      };
    },
    query: graphql`
      query SongsContainerQuery($count: Int!, $cursor: String) {
        viewer {
          ...SongsContainer_viewer
        }
      }
    `
  }
);
</code>```

SongItem.js

```<code>createRefetchContainer(
  SongItem,
  {
    song: graphql`
      fragment SongItem_song on Audio
        @argumentDefinitions(
          count: { type: "Int", defaultValue: 20 }
          cursor: { type: "String", defaultValue: null }
        ) {
        id
        ...CommentsContainer_song
        # ...more pagination container other_song
      }
    `
  },
  graphql`
    query SongItemQuery($id: ID!, $count: Int!, $cursor: String) {
      song(id: $id) {
        ...SongItem_song @arguments(count: $count, cursor: $cursor)
      }
    }
  `
);
</code>```

CommentsContainer.js

```<code>createPaginationContainer(
  CommentsContainer,
  {
    song: graphql`
      fragment CommentsContainer_song on Audio {
        id
        comments(first: $count, after: $cursor)
          @connection(key: "CommentsContainer_comments", filters: []) {
          edges {
            id
          }
        }
      }
    `
  },
  {
    direction: 'forward',
    getConnectionFromProps(props) {
      return props.song && props.song.comments;
    },
    getFragmentVariables(prevVars, totalCount) {
      return {
        ...prevVars,
        count: totalCount
      };
    },
    getVariables(props, { count, cursor }, fragmentVariables) {
      return {
        count,
        cursor,
        id: props.song.id
      };
    },
    query: graphql`
      query CommentsContainerQuery($id: ID!, $count: Int!, $cursor: String) {
        song(id: $id) {
          ...CommentsContainer_song
        }
      }
    `
  }
);
</code>```

Title: Relay Modern nested pagination

Body:
I have a root query of songs, this is in a pagination container.
I then have a nested property on songs called comments that I also want to be paginated because I don't want to load 10k comments for each song all at once.

songsContainer.js:

fragment songsContainer on Query {
    songs(
      first: $count
      after: $cursor
      genre: $genre
      filter: $filter
    ) @connection(key: "songsContainer_songs") {
      edges {
        node {
          audioId
          name
          coverImageUrl
          artist
          likes
          dislikes
          ...commentsContainer
        }
      }
    }
  }

const connectionConfig = {
  direction: 'forward',
  query: graphql`
    query songsContainerForwardQuery(
      $count: Int!
      $cursor: String
      $genre: String
      $filter: FilterInput
    ) {
      ...songsContainer
    }
  `,
  getVariables: (_, { count, cursor }) => ({
    count,
    cursor,
  }),
};

paginationContainer(fragments, connectionConfig);

commentsContainer.js

  fragment commentsContainer on Audio {
    comments(
      first: $count
      after: $cursor
      getReplies: $getReplies
    ) @connection(key: "commentsContainer_comments") {
      edges {
        node {
          commentId
          body
          date
          likes
          dislikes
          repliesCount
          originalComment {
            id
          }
          user {
            userName
          }
        }
      }
    }
  }

How do I write the connectionConfig for the comments? I tried this:

const connectionConfig = {
  direction: 'forward',
  query: graphql`
    query commentsContainerForwardQuery(
      $count: Int!
      $cursor: String
    ) {
      ...commentsContainer
    }
  `,
  getVariables: (_, { count, cursor }) => ({
    count,
    cursor,
  }),
};

But because the comments are nested on songs then it throws an error saying that the query doesn't exist on the Root.

Body:
SongsContainer.js

createPaginationContainer(
  SongsContainer,
  {
    viewer: graphql`
      fragment SongsContainer_viewer on Query {
        id
        songs(first: $count, after: $cursor)
          @connection(key: "SongsContainer_songs", filters: []) {
          edges {
            cursor
            node {
              id
              ...SongItem_song
            }
          }
        }
      }
    `
  },
  {
    direction: 'forward',
    getConnectionFromProps(props) {
      return props.viewer && props.viewer.songs;
    },
    getFragmentVariables(prevVars, totalCount) {
      return {
        ...prevVars,
        count: totalCount
      };
    },
    getVariables(props, { count, cursor }, fragmentVariables) {
      return {
        count,
        cursor
      };
    },
    query: graphql`
      query SongsContainerQuery($count: Int!, $cursor: String) {
        viewer {
          ...SongsContainer_viewer
        }
      }
    `
  }
);

SongItem.js

createRefetchContainer(
  SongItem,
  {
    song: graphql`
      fragment SongItem_song on Audio
        @argumentDefinitions(
          count: { type: "Int", defaultValue: 20 }
          cursor: { type: "String", defaultValue: null }
        ) {
        id
        ...CommentsContainer_song
        # ...more pagination container other_song
      }
    `
  },
  graphql`
    query SongItemQuery($id: ID!, $count: Int!, $cursor: String) {
      song(id: $id) {
        ...SongItem_song @arguments(count: $count, cursor: $cursor)
      }
    }
  `
);

CommentsContainer.js

createPaginationContainer(
  CommentsContainer,
  {
    song: graphql`
      fragment CommentsContainer_song on Audio {
        id
        comments(first: $count, after: $cursor)
          @connection(key: "CommentsContainer_comments", filters: []) {
          edges {
            id
          }
        }
      }
    `
  },
  {
    direction: 'forward',
    getConnectionFromProps(props) {
      return props.song && props.song.comments;
    },
    getFragmentVariables(prevVars, totalCount) {
      return {
        ...prevVars,
        count: totalCount
      };
    },
    getVariables(props, { count, cursor }, fragmentVariables) {
      return {
        count,
        cursor,
        id: props.song.id
      };
    },
    query: graphql`
      query CommentsContainerQuery($id: ID!, $count: Int!, $cursor: String) {
        song(id: $id) {
          ...CommentsContainer_song
        }
      }
    `
  }
);


问:
Import data from the excel file
In the below mentioned code, data is imported from an Excel file containing Sent_date column in MM/DD/YYYY format. Each data row is iterated upon and sent_date and date values stored in the ex_date variable.

```<code>      protected void btnUpload_Click(object sender, EventArgs e)
    {

        MySqlTransaction transaction;

        string ex_id = "";
        var count = 0;

        string file_name = Path.GetFileName(FileUpload1.FileName);
        string Excel_path = Server.MapPath("~/Excel/" + file_name);
        FileUpload1.SaveAs(Excel_path);

        using (OleDbConnection my_con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended Properties=Excel 8.0;Persist Security Info=False"))
        {
            my_con.Open();

            // get the excel file data and assign it in OleDbcoomad object(o_cmd)
            using (OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", my_con))
            {

                // read the excel file data and assing it o_dr object
                using (OleDbDataReader dr = command.ExecuteReader())
                {

                    /////////////////////////////////////////////
                   // while (dr.Read() && count++ < 10)
                   while(dr.Read())
                    {
                        //get first row data and assign it ex_id variable
                        ex_id = dr[0].ToString();
                        string ex_uid = dr[1].ToString();
                        //get second row data and assign it ex_name variable
                        string ex_date = dr[2].ToString();
                        //get thirdt row data and assign it ex_name variable

                        string ex_dir = dr[3].ToString();

                        //get first row data and assign it ex_location variable
                        string ex_email = dr[4].ToString();
                        string ex_email1 = dr[5].ToString();
                        string ex_email2 = dr[6].ToString();
                        //string ex_company = dr[7].ToString();
                        string ex_company = dr[7].ToString();
                        string ex_contact = dr[8].ToString();
                        string ex_proposal = dr[9].ToString();
                        string ex_reason = dr[10].ToString();
                        //string ex_type = dr[11].ToString();

                        int chk = 0;
                        int type = 0;
                        int dup = 0;
                        int dir = 0;

                        if (ddlwebsites.SelectedIndex != 0)
                        {
                            dir = Convert.ToInt32(ddlwebsites.SelectedValue);
                            if (dir == 8)
                            {
                                type = 1;
                            }

                        }

                        foreach (ListItem lstAssign in ddlevents.Items)
                        {
                            if (lstAssign.Selected == true)
                            {
                                chk = 1;
                            }
                        }

                        if (type == 1 && chk == 0)
                        {
                            evyerror.Text = "Please Select the Event!!";
                            return;

                        }

                        else
                        {
                            string querycomp = "", compID = "";
                            querycomp = "Select * from barter_company where website like '%' '" + ex_dir + "' '%'";
                            string connStr = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
                            connect = new MySqlConnection(connStr);
                            connect.Open();
                            transaction = connect.BeginTransaction();
                            try
                            {
                                ClassDtBaseConnect clsDtResult = new ClassDtBaseConnect();
                                DataTable dt = clsDtResult.GetDataTable(querycomp);
                                if (dt.Rows.Count > 0)
                                {
                                    compID = dt.Rows[0]["comp_id"].ToString();
                                    ViewState["comp_id"] = compID;
                                    if (type == 1)
                                    {
                                        dup = checkforDuplicates(Convert.ToInt32(compID));
                                        if (dup == 1)
                                        {
                                            //Confirm_MP.Show();
                                            // ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "confirmation();", true);
                                        }

                                    }
                                    //return;
                                }
                                else
                                {

                                    string queryStr = "insert into barter_company (comp_name,website) values(?comp,?website)";
                                    MySqlCommand cmd = new MySqlCommand(queryStr, connect, transaction);
                                    cmd.Parameters.AddWithValue("?comp", ex_company);
                                    cmd.Parameters.AddWithValue("?website", ex_dir);
                                    cmd.ExecuteNonQuery();
                                    cmd.CommandText = "Select LAST_INSERT_ID()";
                                    compID = cmd.ExecuteScalar().ToString();
                                    transaction.Commit();
                                    connect.Close();

                                }
                            }
                            catch
                            {
                                transaction.Rollback();
                            }

                            if (dup == 0)
                            {
                                // create a connection string with your sql database
                                string connStr1 = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
                                connect = new MySqlConnection(connStr1);
                                connect.Open();

                                DateTime date = new DateTime();//added by chetan
                                ex_date = ex_date.Split(' ')[0];//added by chetan
                                date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);//added by chetan
                                string SentDateString = date.ToString("yyyy/MM/dd");//added by chetan
                                DateTime SentDate = Convert.ToDateTime(SentDateString).Date;//added by chetan
                                                                                //DateTime SentDate = DateTime.Parse(ex_date);//added by chetan

                                // }
                                //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);//added by chetan
                                //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);
                                // string SentDateString = date.ToString("yyyy/MM/dd");
                                transaction = connect.BeginTransaction();
                                try
                                {

                                    ex_uid = Session["session_barterUser_id"].ToString();

                                    MySqlCommand cmd = new MySqlCommand("insert into barter_proposals(user_id, sent_date, website_a, email_id, email_id2, email_id3, company, contact_name, proposal_status, reason,type) values(?uid,?sentdate,?dir,?email,?email2,?email3,?comp,?cont_name,?pro_status,?reason,?type)", connect);

                                    cmd.Parameters.AddWithValue("?uid", ex_uid);
                                    cmd.Parameters.AddWithValue("?comp", compID);

                                    cmd.Parameters.AddWithValue("?sentdate", SentDate);
                                    // command.Parameters.AddWithValue("?event", eventname);
                                    cmd.Parameters.AddWithValue("?dir", dir);
                                    // command.Parameters.AddWithValue("?bar_type", ddlbartertype.SelectedValue);
                                    // command.Parameters.AddWithValue("?website_b", txtwebsite.Text);
                                    //cmd.Parameters.AddWithValue("?comp", ex_company);
                                    cmd.Parameters.AddWithValue("?cont_name", ex_contact);
                                    cmd.Parameters.AddWithValue("?email", ex_email);
                                    cmd.Parameters.AddWithValue("?email2", ex_email1);
                                    cmd.Parameters.AddWithValue("?email3", ex_email2);
                                    cmd.Parameters.AddWithValue("?pro_status", ex_proposal);
                                    cmd.Parameters.AddWithValue("?reason", ex_reason);
                                    cmd.Parameters.AddWithValue("?type", type);
                                    // command.Parameters.AddWithValue("?type", type);

                                    cmd.ExecuteNonQuery();
                                    if (type == 1)
                                    {

                                        cmd.CommandText = "Select LAST_INSERT_ID()";
                                        Int64 CurrentProId = Convert.ToInt64(cmd.ExecuteScalar());
                                        int eventAssignID;
                                        string QueryInqEventAssign = "insert into barter_propeventassign(prop_id,event_id) values(?pro_id,?event_id)";

                                        foreach (ListItem lstAssign in ddlevents.Items)
                                        {
                                            if (lstAssign.Selected == true)
                                            {
                                                cmd = new MySqlCommand(QueryInqEventAssign, connect, transaction);
                                                cmd.Parameters.AddWithValue("?pro_id", CurrentProId);
                                                eventAssignID = Convert.ToInt32(lstAssign.Value);
                                                cmd.Parameters.AddWithValue("?event_id", eventAssignID);
                                                cmd.ExecuteNonQuery();

                                            }
                                        }

                                    }//end of if
                                    transaction.Commit();
                                    connect.Close();
                                    Response.Write("<script type=\"text/javascript\">alert('Proposal Added Successfully!!!');</script>");
                                }//end of try
                                catch (Exception ex)
                                {
                                    transaction.Rollback();
                                    Response.Write("<script>alert('There is an Error Ocurred:" + Server.HtmlEncode(ex.Message) + "')</script>");
                                }
                                finally
                                {
                                    connect.Close();

                                }

                            }//ifdupzero
                        }//else
                    }//while

            //dr.Close();//commented by chetan
        }//using
    }//using

  }//using

        if (System.IO.File.Exists(Excel_path))
        {
            System.IO.File.Delete(Excel_path);
        }

    }
</code>```

Now the issue is that suppose when an excel file contains 3 rows as given below:

```<code>sent_date
11/21/2017----1strow
11/22/2017----2ndrow
11/23/2017----3rdrow
</code>```

The Reader does read the 3 rows but but does not stop after that. It again goes to while loop and reads the date (actual value:"") and gives the error "string is not recognised as datetime".

A strange thing observed is that while importing 16 rows it does not give this error - the reader stops and data gets inserted. No idea why it takes 16 rows to stop the reader

What should be added to the code to stop the reader after reading the initial 3 rows - that is after reading 3rd row, how will it go to dr.close()?

答:
While reading excel file, you need to consider concept of empty/used rows. If you delete rows from excel after 3 rows and import it again, the issue won't arise.

As per your explanation, excel is having total 16 used rows but data is populated only in 3 rows.

To come out while loop after 3 data rows, you will need to enter more exhaustive where condition like "SELECT * FROM [Sheet1$] WHERE [F1] <> ''"

Title: Import data from the excel file

Body:
In the below mentioned code, data is imported from an Excel file containing Sent_date column in MM/DD/YYYY format. Each data row is iterated upon and sent_date and date values stored in the ex_date variable.

      protected void btnUpload_Click(object sender, EventArgs e)
    {

        MySqlTransaction transaction;

        string ex_id = "";
        var count = 0;

        string file_name = Path.GetFileName(FileUpload1.FileName);
        string Excel_path = Server.MapPath("~/Excel/" + file_name);
        FileUpload1.SaveAs(Excel_path);

        using (OleDbConnection my_con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended Properties=Excel 8.0;Persist Security Info=False"))
        {
            my_con.Open();

            // get the excel file data and assign it in OleDbcoomad object(o_cmd)
            using (OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", my_con))
            {

                // read the excel file data and assing it o_dr object
                using (OleDbDataReader dr = command.ExecuteReader())
                {

                    /////////////////////////////////////////////
                   // while (dr.Read() && count++ < 10)
                   while(dr.Read())
                    {
                        //get first row data and assign it ex_id variable
                        ex_id = dr[0].ToString();
                        string ex_uid = dr[1].ToString();
                        //get second row data and assign it ex_name variable
                        string ex_date = dr[2].ToString();
                        //get thirdt row data and assign it ex_name variable

                        string ex_dir = dr[3].ToString();

                        //get first row data and assign it ex_location variable
                        string ex_email = dr[4].ToString();
                        string ex_email1 = dr[5].ToString();
                        string ex_email2 = dr[6].ToString();
                        //string ex_company = dr[7].ToString();
                        string ex_company = dr[7].ToString();
                        string ex_contact = dr[8].ToString();
                        string ex_proposal = dr[9].ToString();
                        string ex_reason = dr[10].ToString();
                        //string ex_type = dr[11].ToString();

                        int chk = 0;
                        int type = 0;
                        int dup = 0;
                        int dir = 0;

                        if (ddlwebsites.SelectedIndex != 0)
                        {
                            dir = Convert.ToInt32(ddlwebsites.SelectedValue);
                            if (dir == 8)
                            {
                                type = 1;
                            }

                        }

                        foreach (ListItem lstAssign in ddlevents.Items)
                        {
                            if (lstAssign.Selected == true)
                            {
                                chk = 1;
                            }
                        }

                        if (type == 1 && chk == 0)
                        {
                            evyerror.Text = "Please Select the Event!!";
                            return;

                        }

                        else
                        {
                            string querycomp = "", compID = "";
                            querycomp = "Select * from barter_company where website like '%' '" + ex_dir + "' '%'";
                            string connStr = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
                            connect = new MySqlConnection(connStr);
                            connect.Open();
                            transaction = connect.BeginTransaction();
                            try
                            {
                                ClassDtBaseConnect clsDtResult = new ClassDtBaseConnect();
                                DataTable dt = clsDtResult.GetDataTable(querycomp);
                                if (dt.Rows.Count > 0)
                                {
                                    compID = dt.Rows[0]["comp_id"].ToString();
                                    ViewState["comp_id"] = compID;
                                    if (type == 1)
                                    {
                                        dup = checkforDuplicates(Convert.ToInt32(compID));
                                        if (dup == 1)
                                        {
                                            //Confirm_MP.Show();
                                            // ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "confirmation();", true);
                                        }

                                    }
                                    //return;
                                }
                                else
                                {

                                    string queryStr = "insert into barter_company (comp_name,website) values(?comp,?website)";
                                    MySqlCommand cmd = new MySqlCommand(queryStr, connect, transaction);
                                    cmd.Parameters.AddWithValue("?comp", ex_company);
                                    cmd.Parameters.AddWithValue("?website", ex_dir);
                                    cmd.ExecuteNonQuery();
                                    cmd.CommandText = "Select LAST_INSERT_ID()";
                                    compID = cmd.ExecuteScalar().ToString();
                                    transaction.Commit();
                                    connect.Close();

                                }
                            }
                            catch
                            {
                                transaction.Rollback();
                            }

                            if (dup == 0)
                            {
                                // create a connection string with your sql database
                                string connStr1 = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
                                connect = new MySqlConnection(connStr1);
                                connect.Open();

                                DateTime date = new DateTime();//added by chetan
                                ex_date = ex_date.Split(' ')[0];//added by chetan
                                date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);//added by chetan
                                string SentDateString = date.ToString("yyyy/MM/dd");//added by chetan
                                DateTime SentDate = Convert.ToDateTime(SentDateString).Date;//added by chetan
                                                                                //DateTime SentDate = DateTime.Parse(ex_date);//added by chetan

                                // }
                                //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);//added by chetan
                                //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);
                                // string SentDateString = date.ToString("yyyy/MM/dd");
                                transaction = connect.BeginTransaction();
                                try
                                {

                                    ex_uid = Session["session_barterUser_id"].ToString();

                                    MySqlCommand cmd = new MySqlCommand("insert into barter_proposals(user_id, sent_date, website_a, email_id, email_id2, email_id3, company, contact_name, proposal_status, reason,type) values(?uid,?sentdate,?dir,?email,?email2,?email3,?comp,?cont_name,?pro_status,?reason,?type)", connect);

                                    cmd.Parameters.AddWithValue("?uid", ex_uid);
                                    cmd.Parameters.AddWithValue("?comp", compID);

                                    cmd.Parameters.AddWithValue("?sentdate", SentDate);
                                    // command.Parameters.AddWithValue("?event", eventname);
                                    cmd.Parameters.AddWithValue("?dir", dir);
                                    // command.Parameters.AddWithValue("?bar_type", ddlbartertype.SelectedValue);
                                    // command.Parameters.AddWithValue("?website_b", txtwebsite.Text);
                                    //cmd.Parameters.AddWithValue("?comp", ex_company);
                                    cmd.Parameters.AddWithValue("?cont_name", ex_contact);
                                    cmd.Parameters.AddWithValue("?email", ex_email);
                                    cmd.Parameters.AddWithValue("?email2", ex_email1);
                                    cmd.Parameters.AddWithValue("?email3", ex_email2);
                                    cmd.Parameters.AddWithValue("?pro_status", ex_proposal);
                                    cmd.Parameters.AddWithValue("?reason", ex_reason);
                                    cmd.Parameters.AddWithValue("?type", type);
                                    // command.Parameters.AddWithValue("?type", type);

                                    cmd.ExecuteNonQuery();
                                    if (type == 1)
                                    {

                                        cmd.CommandText = "Select LAST_INSERT_ID()";
                                        Int64 CurrentProId = Convert.ToInt64(cmd.ExecuteScalar());
                                        int eventAssignID;
                                        string QueryInqEventAssign = "insert into barter_propeventassign(prop_id,event_id) values(?pro_id,?event_id)";

                                        foreach (ListItem lstAssign in ddlevents.Items)
                                        {
                                            if (lstAssign.Selected == true)
                                            {
                                                cmd = new MySqlCommand(QueryInqEventAssign, connect, transaction);
                                                cmd.Parameters.AddWithValue("?pro_id", CurrentProId);
                                                eventAssignID = Convert.ToInt32(lstAssign.Value);
                                                cmd.Parameters.AddWithValue("?event_id", eventAssignID);
                                                cmd.ExecuteNonQuery();

                                            }
                                        }

                                    }//end of if
                                    transaction.Commit();
                                    connect.Close();
                                    Response.Write("");
                                }//end of try
                                catch (Exception ex)
                                {
                                    transaction.Rollback();
                                    Response.Write("");
                                }
                                finally
                                {
                                    connect.Close();

                                }

                            }//ifdupzero
                        }//else
                    }//while

            //dr.Close();//commented by chetan
        }//using
    }//using

  }//using

        if (System.IO.File.Exists(Excel_path))
        {
            System.IO.File.Delete(Excel_path);
        }

    }

Now the issue is that suppose when an excel file contains 3 rows as given below:

sent_date
11/21/2017----1strow
11/22/2017----2ndrow
11/23/2017----3rdrow

The Reader does read the 3 rows but but does not stop after that. It again goes to while loop and reads the date (actual value:"") and gives the error "string is not recognised as datetime".

A strange thing observed is that while importing 16 rows it does not give this error - the reader stops and data gets inserted. No idea why it takes 16 rows to stop the reader

What should be added to the code to stop the reader after reading the initial 3 rows - that is after reading 3rd row, how will it go to dr.close()?


问:
How to read a custom Json Object from a String
I am using Gson Library to read Json. I have a Json Object that is not always the same, so I can't define a class with particular properties.

I want to read it as a String and later split and manipulate it as a Map<K,V>.

Below is my object.

I want the row filed to be converted to a String while reading.

```<code>{
   "data":{
      "sampleTime":"2017-12-08T02:24:26.334Z",
      "target":{
         "gateway":"TRADPRT_OTPLTP_GDCE",
         "probe":"HKLGISWAS02B-7102",
         "managedEntity":"HKLGISWAS02B-7102",
         "type":"Core_Linux",
         "sampler":"Disk",
         "dataview":"Disk",
         "filter":{
            "osType":"Linux",
            "pluginName":"DISK"
         }
      },
      "name":"freeSpace",
      "row":{
         "/":"5806 MB",
         "/sys":"0 MB",
         "/dev/pts":"0 MB",
         "/dev/shm":"64475 MB",
         "/boot":"28 MB",
         "/home":"6775 MB",
         "/opt":"5971 MB",
         "/tmp":"4287 MB",
         "/u/operator":"277 MB",
         "/usr/controlm":"3665 MB",
         ...
         "/apps/S2B/WBDS":"11249 MB"
      }
   },
   "operation":"update"
}
</code>```

答:
Complex JSON can be represented as Map<String, Object>, where the Object can also be a Map<String, Object>, and so on. (If I understand your question correctly)

Then you can call

```<code>Map<String, Object> o = gson.fromJson(jsonString, new TypeToken<Map<String, Object>>() {}.getType());
</code>```

to convert a JSON string to a Map

Body:
I am using Gson Library to read Json. I have a Json Object that is not always the same, so I can't define a class with particular properties.

I want to read it as a String and later split and manipulate it as a Map<K,V>.

Below is my object.

I want the row filed to be converted to a String while reading.

{
   "data":{
      "sampleTime":"2017-12-08T02:24:26.334Z",
      "target":{
         "gateway":"TRADPRT_OTPLTP_GDCE",
         "probe":"HKLGISWAS02B-7102",
         "managedEntity":"HKLGISWAS02B-7102",
         "type":"Core_Linux",
         "sampler":"Disk",
         "dataview":"Disk",
         "filter":{
            "osType":"Linux",
            "pluginName":"DISK"
         }
      },
      "name":"freeSpace",
      "row":{
         "/":"5806 MB",
         "/sys":"0 MB",
         "/dev/pts":"0 MB",
         "/dev/shm":"64475 MB",
         "/boot":"28 MB",
         "/home":"6775 MB",
         "/opt":"5971 MB",
         "/tmp":"4287 MB",
         "/u/operator":"277 MB",
         "/usr/controlm":"3665 MB",
         ...
         "/apps/S2B/WBDS":"11249 MB"
      }
   },
   "operation":"update"
}

Body:
Complex JSON can be represented as Map<String, Object>, where the Object can also be a Map<String, Object>, and so on. (If I understand your question correctly)

Then you can call

Map<String, Object> o = gson.fromJson(jsonString, new TypeToken<Map<String, Object>>() {}.getType());

to convert a JSON string to a Map


问:
good looking alert in iphone app
I am working on making my first iPhone app nicer :)
When an error occurs, I display it in a "basic" UIAlertView (blue background, a Cancel button).
I saw in several apps very good looking alerts when network errors occur (nice grey modal alert that only shows for a couple of seconds).
How can this be done ? Is that a particular configuration of UIAlertView ?

Thanks a lot for your help,
Luc

答:
This isn't an alertview per se, but it is often used in conjunction with networking operations, as you mention.

https://github.com/matej/MBProgressHUD

Title: good looking alert in iphone app


问:
ImageView image load logic from gallery
I am having 2 ImageView. I want to load image from gallery into ImageView. My requirement is, if I select the image 1st time, then image should be loaded into ImageView 1, and when I select image 2nd time, image should be loaded into ImageView 2.  </p>

```<code> -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo :(NSDictionary *)info
        {
          int  count=0;

            iscamera=YES;
            _imageuser.image=[info objectForKey:UIImagePickerControllerOriginalImage];
            _imageuser1.image=[info objectForKey:UIImagePickerControllerOriginalImage];
            _imageuser2.image=[info objectForKey:UIImagePickerControllerOriginalImage];

            if (ipc.sourceType == UIImagePickerControllerSourceTypeSavedPhotosAlbum) {
                if (count==0) {
                    pngData = UIImagePNGRepresentation(_imageuser.image);
                    pngData = UIImagePNGRepresentation(_imageuser1.image);
                }

        else if (count== 1)
        {
            pngData = UIImagePNGRepresentation(_imageuser.image);
            pngData = UIImagePNGRepresentation(_imageuser2.image);
        }
                count ++;
            }

            else{
                pngData = UIImagePNGRepresentation([self rotateUIImage:_imageuser.image clockwise:YES]);

            }
            [picker dismissViewControllerAnimated:YES completion:nil];

        }
</code>```

答:
You can check the NSdata of the image in image1.
If it exists supply the 2nd selected  image to second imageView otherwise supply it to first imageView.</p>

Title: ImageView image load logic from gallery

Body:
I am having 2 ImageView. I want to load image from gallery into ImageView. My requirement is, if I select the image 1st time, then image should be loaded into ImageView 1, and when I select image 2nd time, image should be loaded into ImageView 2.

 -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo :(NSDictionary *)info
        {
          int  count=0;

            iscamera=YES;
            _imageuser.image=[info objectForKey:UIImagePickerControllerOriginalImage];
            _imageuser1.image=[info objectForKey:UIImagePickerControllerOriginalImage];
            _imageuser2.image=[info objectForKey:UIImagePickerControllerOriginalImage];

            if (ipc.sourceType == UIImagePickerControllerSourceTypeSavedPhotosAlbum) {
                if (count==0) {
                    pngData = UIImagePNGRepresentation(_imageuser.image);
                    pngData = UIImagePNGRepresentation(_imageuser1.image);
                }

        else if (count== 1)
        {
            pngData = UIImagePNGRepresentation(_imageuser.image);
            pngData = UIImagePNGRepresentation(_imageuser2.image);
        }
                count ++;
            }

            else{
                pngData = UIImagePNGRepresentation([self rotateUIImage:_imageuser.image clockwise:YES]);

            }
            [picker dismissViewControllerAnimated:YES completion:nil];

        }


问:
How to remove the blank line above raw_input in Python?
I have in a while statement:

```<code>print 'Word', len(guessMe), 'letters long.'
print '------------- '
while verify != [] and guessesLeft > 0:
  print 'You have', guessesLeft, 'guesses left.'
  userGuess = raw_input('Please guess a letter: ')
  userGuess = userGuess.lower()
  userGuessSingleton = list(userGuess)
  userGuessList = userGuessList + userGuessSingleton

  p = lettersList.index(userGuess)
  del(lettersList[p])
  letters = "".join(lettersList)
  print 'Available letters: ', letters
</code>```

It outputs this:

```<code>Word is 10 letters long.
---------------
You have 13.0 guesses left.

Please guess a letter: a
</code>```

Why is it that the other print statements don't create this issue? Does it have something to do with raw_input()? How do I remove that blank line after 'You have 13.0 guesses left'

Note: Nsh's recommendation doesn't work because it creates another problem: an indent of one space on the line after "Please guess a letter: a"

```<code>Please guess a letter: a
 Letters are 'abc'
</code>```

答:
you can change this line:
</p>

```<code>print("Available Letters: " + getAvailableLetters(lettersGuessed))
</code>```

<p>to </p>

```<code>print("Available Letters: " + getAvailableLetters(lettersGuessed), end="")
</code>```

Body:
I have in a while statement:

print 'Word', len(guessMe), 'letters long.'
print '------------- '
while verify != [] and guessesLeft > 0:
  print 'You have', guessesLeft, 'guesses left.'
  userGuess = raw_input('Please guess a letter: ')
  userGuess = userGuess.lower()
  userGuessSingleton = list(userGuess)
  userGuessList = userGuessList + userGuessSingleton

  p = lettersList.index(userGuess)
  del(lettersList[p])
  letters = "".join(lettersList)
  print 'Available letters: ', letters

It outputs this:

Word is 10 letters long.
---------------
You have 13.0 guesses left.

Please guess a letter: a

Why is it that the other print statements don't create this issue? Does it have something to do with raw_input()? How do I remove that blank line after 'You have 13.0 guesses left'

Note: Nsh's recommendation doesn't work because it creates another problem: an indent of one space on the line after "Please guess a letter: a"

Please guess a letter: a
 Letters are 'abc'

Body:
you can change this line:

print("Available Letters: " + getAvailableLetters(lettersGuessed))

to

print("Available Letters: " + getAvailableLetters(lettersGuessed), end="")


问:
How do I turn an array into a record / tuple / row type?
I need to execute a dynamic insert into a table with a variable number of columns.

Right now I'm quoting both the column names, with quote_ident, and the actual values, with quote_nullable, and then joining them with array_to_string:

```<code>for ... loop
    ...
    cols := array_append(cols, quote_ident(column_name));
    vals := array_append(vals, quote_nullable(column_value));
end loop;

execute format('insert into %s (%s) values (%s)',
    target_table,
    array_to_string(cols, ', ')
    array_to_string(vals, ', ')
);
</code>```

It's a pattern found all over the place, including on the official documentation. But it feels a bit unclean. I'd rather pass the array of values a parameter in the using clause:

```<code>execute format('insert into %s (%s) ... $1 ...',
    target_table,
    array_to_string(cols, ', ')
)
using vals;
</code>```

Notice the using vals, which is what I'd like to achieve. But I cannot seem to be able to fill in the dots in the insert statement. Maybe some kind of select ... from ...?

More generally, how do I turn an array into a record / tuple / row type?

答:
I'm using code very like this in production:

```<code>EXECUTE ( SELECT 'insert into sometable '
    '('||string_agg(quote_ident(p.key),',') ||
            ') values ('|| string_agg(quote_nullable(p.value),',') || ');'
            FROM each(payload) as p
            );
</code>```

but here payload is a hstore, not a pair of arrays.

Body:
I need to execute a dynamic insert into a table with a variable number of columns.

Right now I'm quoting both the column names, with quote_ident, and the actual values, with quote_nullable, and then joining them with array_to_string:

for ... loop
    ...
    cols := array_append(cols, quote_ident(column_name));
    vals := array_append(vals, quote_nullable(column_value));
end loop;

execute format('insert into %s (%s) values (%s)',
    target_table,
    array_to_string(cols, ', ')
    array_to_string(vals, ', ')
);

It's a pattern found all over the place, including on the official documentation. But it feels a bit unclean. I'd rather pass the array of values a parameter in the using clause:

execute format('insert into %s (%s) ... $1 ...',
    target_table,
    array_to_string(cols, ', ')
)
using vals;

Notice the using vals, which is what I'd like to achieve. But I cannot seem to be able to fill in the dots in the insert statement. Maybe some kind of select ... from ...?

More generally, how do I turn an array into a record / tuple / row type?

Body:
I'm using code very like this in production:

EXECUTE ( SELECT 'insert into sometable '
    '('||string_agg(quote_ident(p.key),',') ||
            ') values ('|| string_agg(quote_nullable(p.value),',') || ');'
            FROM each(payload) as p
            );

but here payload is a hstore, not a pair of arrays.


问:
Using Firebase, React and Server Side Rendering
I'm building a project with react and firebase, with an node express server.  What's the best way to handle routes that need to retrieve the auth status of the user?  If I understand correctly firebase doesn't store its auth data in a cookie, so I'm not sure I'll be able to know the logged in user or even if a user is logged in at all, when on the server.</p>

答:
My experience with React Redux is that everything is stored in state. When you login , it stores it in state and being passed from Actions to Reducers to the components.

Actions:

```<code>export function login(email,password){
    return dispatch => auth.signInWithEmailAndPassword(email, password);
}

export function logout(){
    return dispatch => auth.signOut();
}

export function createAccount(email, password){
    return dispatch => auth.createUserWithEmailAndPassword(email, password);
}
</code>```

Body:
My experience with React Redux is that everything is stored in state. When you login , it stores it in state and being passed from Actions to Reducers to the components.

Actions:

export function login(email,password){
    return dispatch => auth.signInWithEmailAndPassword(email, password);
}

export function logout(){
    return dispatch => auth.signOut();
}

export function createAccount(email, password){
    return dispatch => auth.createUserWithEmailAndPassword(email, password);
}


问:
Provisioning profile Xcode
I'm new on iOs development and I'm facing this issue:

I found some posts about but nothing work out.

答:
Change the bundle Id as explained, its already taken by someone on Developer/Enterprise Account under apple.

If this is not a solution ask the previous vendor/authority who was
holding this app to give you the P12, and provisioning profile for
this Bundle Id to regenerate and use to build new IPA.

If this app now is taken over by your side or company and not yet uploaded to store make a new bundle ID

If this is also not possible change the bundle Id for the tell the previous holding authority to delete the app ID. / Transfer the itunesConnect App to your developer account and resubmit the new IPA with updated profiles. This will allow you to overwrite the existing apps on users side rather having duplicates.

Title: Provisioning profile Xcode


答:
You could use np.unique to create a copy of the dataframe consisting of only the unique rows, then do the calculation on those, and construct the full results.

For example:

```<code>import numpy as np

# convert to records for use with numpy
rec = df.to_records(index=False)
arr, ind = np.unique(rec, return_inverse=True)

# find dataframe of unique rows
df_small = pd.DataFrame(arr)

# Apply the formula & construct the full result
df_small.apply(formula, axis=1).iloc[ind].reset_index()
</code>```

Even faster than using apply here would be to use broadcasting: for example, simply compute

```<code>(df.B + df.C) ** 2
</code>```

If this is still too slow, you can use this method on the de-duplicated dataframe, as above.

Title: Save repeated calculations in Python Pandas

Body:
In Pandas, I can use .apply to apply functions to two columns. For example,

df = pd.DataFrame({'A':['a', 'a', 'a', 'b'], 'B':[3, 3, 2, 5], 'C':[2, 2, 2, 8]})
formula = lambda x: (x.B + x.C)**2
df.apply(formula, axis=1)

But, notice that results on the first two rows are the same since all the inputs are the same. In large dataset with complicated operations. These repeated calculations is likely to slow down my program. Is there a way that I can program it so that I can save time with these repeated calculations?

Body:
You could use np.unique to create a copy of the dataframe consisting of only the unique rows, then do the calculation on those, and construct the full results.

For example:

import numpy as np

# convert to records for use with numpy
rec = df.to_records(index=False)
arr, ind = np.unique(rec, return_inverse=True)

# find dataframe of unique rows
df_small = pd.DataFrame(arr)

# Apply the formula & construct the full result
df_small.apply(formula, axis=1).iloc[ind].reset_index()

Even faster than using apply here would be to use broadcasting: for example, simply compute

(df.B + df.C) ** 2

If this is still too slow, you can use this method on the de-duplicated dataframe, as above.