问:
Color grouped bar chart based on comparison of numbers d3
I am building up a grouped bar chart. In the chart, I want to color one group of bar chart differently because its Missouri number is bigger than the national average number. However, my else if statement doesn't work out for the fill function. Can anyone tell me what should I do to color the chart differently based on the comparison of numbers? Thanks in advance!!

Here is my Code

```<code><svg id="bodychart" width="900" height="500" style="display: block; margin: auto"></svg>

<script>

var svg = d3.select("#bodychart"),
    margin = {top: 20, right: 20, bottom: 30, left: 50},
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom,
    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top +")" ); //Not quite understand (??)

var x0 = d3.scaleBand()
    .rangeRound([0, width])
    .paddingInner(0.1);

var x1 = d3.scaleBand()
    .padding(0.05);

var y = d3.scaleLinear()
    .rangeRound([height, 0]);

var z = d3.scaleOrdinal()
    .range(["#F63014", "#ABABAB"]);

var tooltip = d3.select("body").append("div").attr("class", "toolTip");

d3.csv("number.csv", function(d, i, columns){
  for (var i = 1, n = columns.length; i < n; ++i) d[columns[i]] = + d[columns[i]];
    return d;
}, function(error, data) {
  if (error) throw error;

  var keys = data.columns.slice(1);

  x0.domain(data.map(function(d) {return d.BodyParts; }));
  x1.domain(keys).rangeRound([0, x0.bandwidth()]);
  y.domain([0, d3.max(data, function(d) {return d3.max(keys, function(key) {return d[key]; }); })]);

  g.append("g")
    .selectAll("g")
    .data(data)
    .enter()
    .append("g")
      .attr("transform", function(d) {return "translate(" + x0(d.BodyParts) + ",0)"; })
    .selectAll("rect")
    .data(function(d) {return keys.map(function(key){return {key: key, value: d[key]}; }); })
    .enter()
    .append("rect")
      .attr("x", function(d) {return x1(d.key);})
      .attr("y", function(d) {return y(d.value);})
      .attr("width", x1.bandwidth())
      .attr("height", function(d){return height - y(d.value);})
      .attr("fill", function(d, i) {

        if (d.value['Missouri'] > d.value['National_Average']) {
          return z(d.key);
        } else (d.value['Missouri'] < d.value['National_Average']) {
          return "yellow";
        }
        })
      .on("mousemove", function(d){
        tooltip
          .style("left", d3.event.pageX - 50 + "px")
          .style("top", d3.event.pageY - 70 + "px")
          .style("display", "inline-block")

          .html("<span style='font-weight: bold'>"+ (d.key) +"</span>" + ":" + "<br>" + "$" + d3.format(",.0f")(d.value));

    })
        .on("mouseout", function(d){ tooltip.style("display", "none");});

    g.append("g")
      .attr("class", "axis")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x0));

    g.append("g")
        .attr("class", "axis")
        .call(d3.axisLeft(y).ticks(10, ",.0f"))
      .append("text")
        .attr("x", -32)
        .attr("y", y(y.ticks().pop()) + 0.5)
        .attr("dy", "-3em")
        .attr("fill", "#000")
        .attr("font-weight", "bold")
        .attr("text-anchor", "start")
        .text("Dollars");

});
</code>```

Here is my csv file:

```<code>    BodyParts,Missouri,National_Average
    Arm,115100,169878
    Leg,102697,153221
    Hand,86821,144930
    Thumb,29767,42432
    Index Finger,22325,24474
    Middle Finger,17364,20996
    Ring Finger,17364,14660
    Pinky,10915,11343
    Foot,74418,91779
    Big Toe,19845,23436
    Eye,69457,96700
    Ear,24310,38050
    Testicle,0,27678
</code>```

答:
Since the complete data for each pair lies in the parent selection, you have to get it before doing any comparison.

Thus, when setting the fill for each bar, this...

```<code>var parentData = d3.select(this.parentNode).data()[0];
</code>```

... will store the data for the pair, that is, Missouri and National_Average.

Then, use that object to fill the bars conditionally. This is a way to do that (there are shorter ways, of course, but I believe this verbose snippet is more didactic for you):

```<code>.attr("fill", function(d, i) {
    var parentData = d3.select(this.parentNode).data()[0];
    if (d.key === "Missouri") {
        if (parentData.Missouri > parentData.National_Average) {
            return "green"
        } else {
            return "red"
        }
    } else {
        if (parentData.Missouri < parentData.National_Average) {
            return "green"
        } else {
            return "red"
        }
    }
})
</code>```

Here is a plunker showing it: http://plnkr.co/edit/dfjKFUpuiJvLs6wWkO99?p=preview

Body:
I am building up a grouped bar chart. In the chart, I want to color one group of bar chart differently because its Missouri number is bigger than the national average number. However, my else if statement doesn't work out for the fill function. Can anyone tell me what should I do to color the chart differently based on the comparison of numbers? Thanks in advance!!

Here is my Code

<svg id="bodychart" width="900" height="500" style="display: block; margin: auto"></svg>

Body:
Since the complete data for each pair lies in the parent selection, you have to get it before doing any comparison.

Thus, when setting the fill for each bar, this...

var parentData = d3.select(this.parentNode).data()[0];

... will store the data for the pair, that is, Missouri and National_Average.

Then, use that object to fill the bars conditionally. This is a way to do that (there are shorter ways, of course, but I believe this verbose snippet is more didactic for you):

.attr("fill", function(d, i) {
    var parentData = d3.select(this.parentNode).data()[0];
    if (d.key === "Missouri") {
        if (parentData.Missouri > parentData.National_Average) {
            return "green"
        } else {
            return "red"
        }
    } else {
        if (parentData.Missouri < parentData.National_Average) {
            return "green"
        } else {
            return "red"
        }
    }
})

Here is a plunker showing it: http://plnkr.co/edit/dfjKFUpuiJvLs6wWkO99?p=preview


来源: stackexchange

问:
What's the difference between using a stateless functional component versus calling a method?
I'm trying to understand stateless components and what the difference is between these examples:

```<code>class App {
  render() {
    return (
      <div>
        {this.renderAFunction('hello')}
      </div>
    );
  }
  renderAFunction(text) {
    return (
      <p>{text}</p>
    );
  }
}
</code>```

and this:

```<code>class App {
  render() {
    return(
      <div>
        <RenderAFunction text='hello'/>
      </div>
    );
  }
}

const RenderAFunction = ({text}) => (
    <p>{text}</p>
);
</code>```

Or if there is any difference at all?

答:
Functionally, there is absolutely no difference. Both end up rendering a paragraph element, but there are  other aspects to consider. There are three points to make (in my opinion) when examining both methods:

Reusability: You have to understand to separate components when you need to. If renderAFunction is just meant to generate some JSX based on, for example, an API request, then it's fine being in a method. But if you want to reuse it somewhere else, then separate it into it's own component. A huge part of React is component reusability and getting rid of code duplication. Separating the method into it's own component would be imperative to accomplish this.

Purpose: There are reason to use stateless function components and reasons not to. The whole point of stateless functional components is to not have state and be presentational. If you need to do something that involves the React lifecycle or internal state, keep it as a method, or new class depending on if you want it reusable.

Performance: Using a stateless functional component would be less efficient. This is because it's a component, not just some JSX returned from a method. As of right now, the React team plans on making some optimizations for stateless functional components because they do not contain state and are merely presentational, but this probably won't happen until after React Fiber is done and thus your stateless functional component has no optimizations versus a regular full-fledged class component. That makes it incredibly inefficient versus a method returning some JSX, especially if it's just used once in another component.

A good rule of thumb is to ask yourself, do I need it anywhere else? If not, then keep it in a method. If you don't need it anywhere else, separating the JSX into a separate component would have worse performance and wouldn't follow React's core principles.

If you are going to need it somewhere else, then separate the component so you follow React's concept of reusability.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to understand stateless components and what the difference is between these examples:

class App {
  render() {
    return (

        {this.renderAFunction('hello')}

    );
  }
  renderAFunction(text) {
    return (

{text}

    );
  }
}

and this:

class App {
  render() {
    return(

        <RenderAFunction text='hello'/>

    );
  }
}

const RenderAFunction = ({text}) => (

{text}

);

Or if there is any difference at all?


问:
Converting this to shared pointer and passing it as an argument to another C++ class
I am working on a code with the following framework:

```<code>class IFirstStep // abstract interface
{
public:
    virtual commonMethod1() = 0;
    ...
};

class FirstStepBase : public IFirstStep // Jobs common to all FirstStep's
{
public:
    FirstStepBase() {}
    commonMethod1() override;
    ...
protected:
    CommonMembers;
    void correctSettings()
    {
        somePreparations;
        auto smartPtr = static_cast<std::shared_ptr<IFirstStep>>(this);
        SecondStep secondStep(smartPtr);
        some calculations using secondStep;
        reassignment of some of commonMembers;
    }
};

class FirstStep1 : public FirstStepBase
{
public:
    FirstSiep1(bool fineTune)
    {
        commonMembers = initilizeSettings();
        if (fineTune)
            correctSettings();
    }
private:
    CommonMembers initilizeSettings() {calculate and assign commonMembers;}
};

class FirstStep2 : public FirstStepBase
...
class FirstStepN : public FirstStepBase
...

class SecondStep
{
public:
    SecondStep(std::shared_ptr<IFirstStep> & firstStep) : m_firstStep(firstStep) {}
    some methods which use firstStep and return some results;
    firstStep itself is not changed;
};
</code>```

correctSettings() is perfectly executed correcting all settings for FirstStep1 right, but crashes in MS VS debugger on exit from correctSettings() with the diagnostics:

```<code>File: minkernel\crts\ucrt\src\appcrt\heap\debug_heap.cpp
Line: 888
Expression: _CrtIsValidHeapPointer(block)
</code>```

Looks the problem is caused by casting - code crashes even if exit is carried out just after the casting. Other types of casting, including pointer casts, were not accepted by the MS VS compiler. However, the thing works flawlessly if correctSettings() is changed as follows and an appropriate constructor is added to FirstStepBase

```<code>void correctSettings()
{
    std::shared_ptr<IFirstStep> smartPtr
        = <std::make_shared<FirstStepBase>>(commonMembers);
    SecondStep secondStep(smartPtr);
    some calculations using secondStep;
    reassignment of some of commonMembers;
}
</code>```

I would greatly appreciate an explanation of why the first approach fails and is it possible at all to utilize in the code this pointer rather than to generate an additional FirstStepBase object? Please, assume that there is no possibility to change interface to the SecondStep.
Thank you.

答:
You cannot type-cast a raw object pointer directly to a std::shared_ptr.

What you can do, though, is derive FirstStepBase from std::enable_shared_from_this, and then FirstStepBase can call shared_from_this() when needed, eg:

```<code>class FirstStepBase : public std::enable_shared_from_this<FirstStepBase>, public IFirstStep // Jobs common to all FirstStep's
{
    ...
    void correctSettings()
    {
        ...
        auto smartPtr = shared_from_this(); // <-- here
        SecondStep secondStep(smartPtr);
        ...
    }
};
</code>```

This only works if the FirstStep... object is being managed by a std::shared_ptr to begin with, so make sure you always use std::shared_ptr when creating your FirstStep... objects.

On the other hand, if SecondStep is not meant to outlive its associated FirstStep... object, then there is no reason to pass it a std::shared_ptr<IFirstStep> to begin with, just pass it a raw IFirstStep* pointer instead:

```<code>class SecondStep
{
private:
    IFirstStep *m_firstStep;
public:
    SecondStep(IFirstStep *firstStep) : m_firstStep(firstStep) {}
    ...
};
</code>```

Passing a std::shared_ptr only makes sense if SecondStep outlives all FirstStep... references and needs to keep the object alive.

Body:
I am working on a code with the following framework:

class IFirstStep // abstract interface
{
public:
    virtual commonMethod1() = 0;
    ...
};

class FirstStepBase : public IFirstStep // Jobs common to all FirstStep's
{
public:
    FirstStepBase() {}
    commonMethod1() override;
    ...
protected:
    CommonMembers;
    void correctSettings()
    {
        somePreparations;
        auto smartPtr = static_cast<std::shared_ptr<IFirstStep>>(this);
        SecondStep secondStep(smartPtr);
        some calculations using secondStep;
        reassignment of some of commonMembers;
    }
};

class FirstStep1 : public FirstStepBase
{
public:
    FirstSiep1(bool fineTune)
    {
        commonMembers = initilizeSettings();
        if (fineTune)
            correctSettings();
    }
private:
    CommonMembers initilizeSettings() {calculate and assign commonMembers;}
};

class FirstStep2 : public FirstStepBase
...
class FirstStepN : public FirstStepBase
...

class SecondStep
{
public:
    SecondStep(std::shared_ptr<IFirstStep> & firstStep) : m_firstStep(firstStep) {}
    some methods which use firstStep and return some results;
    firstStep itself is not changed;
};

correctSettings() is perfectly executed correcting all settings for FirstStep1 right, but crashes in MS VS debugger on exit from correctSettings() with the diagnostics:

File: minkernel\crts\ucrt\src\appcrt\heap\debug_heap.cpp
Line: 888
Expression: _CrtIsValidHeapPointer(block)

Looks the problem is caused by casting - code crashes even if exit is carried out just after the casting. Other types of casting, including pointer casts, were not accepted by the MS VS compiler. However, the thing works flawlessly if correctSettings() is changed as follows and an appropriate constructor is added to FirstStepBase

void correctSettings()
{
    std::shared_ptr<IFirstStep> smartPtr
        = <std::make_shared<FirstStepBase>>(commonMembers);
    SecondStep secondStep(smartPtr);
    some calculations using secondStep;
    reassignment of some of commonMembers;
}

I would greatly appreciate an explanation of why the first approach fails and is it possible at all to utilize in the code this pointer rather than to generate an additional FirstStepBase object? Please, assume that there is no possibility to change interface to the SecondStep.
Thank you.

Body:
You cannot type-cast a raw object pointer directly to a std::shared_ptr.

What you can do, though, is derive FirstStepBase from std::enable_shared_from_this, and then FirstStepBase can call shared_from_this() when needed, eg:

class FirstStepBase : public std::enable_shared_from_this<FirstStepBase>, public IFirstStep // Jobs common to all FirstStep's
{
    ...
    void correctSettings()
    {
        ...
        auto smartPtr = shared_from_this(); // <-- here
        SecondStep secondStep(smartPtr);
        ...
    }
};

This only works if the FirstStep... object is being managed by a std::shared_ptr to begin with, so make sure you always use std::shared_ptr when creating your FirstStep... objects.

On the other hand, if SecondStep is not meant to outlive its associated FirstStep... object, then there is no reason to pass it a std::shared_ptr<IFirstStep> to begin with, just pass it a raw IFirstStep* pointer instead:

class SecondStep
{
private:
    IFirstStep *m_firstStep;
public:
    SecondStep(IFirstStep *firstStep) : m_firstStep(firstStep) {}
    ...
};

Passing a std::shared_ptr only makes sense if SecondStep outlives all FirstStep... references and needs to keep the object alive.


问:
Element type is invalid: expected a string (for built-in components) or a class/function React Error
I have a problem with React when I try to change the page through the button (but) the console gives me:

Element type is invalid: expected a string (for built-in components) or >a class/function (for composite components) but got: undefined. You >likely forgot to export your component from the file it's defined in.

But when I put the onClick code in the class code it shows the jsx code. So it works but why do I still get the error? Here is my code:

```<code>import React from 'react';
import {render} from 'react-dom';

//sass
require('../sass/style.scss');

var pages = ['Qrscan'];
var jsx = [<Qrscan />];

class App extends React.Component {
    constructor (props) {
        super(props);
        this.state = {target: <Menu />};
        App.changePage = App.changePage.bind(this);
    }

    static changePage (tar) {
       this.setState({target: tar});
    }

    render () {
        return (
          this.state.target
        )
    }
}

//Rendering
class Menu extends React.Component {
    render() {
        return (
            <div id="root">
                <Header />
                <div className="container">
                    <But target="Qrscan" class="button button-QR" text="Use QR code" type="button" linkTo="" />
                    <But class="button button-URL" text="Use URL" type="button" />
                </div>
            </div>
        )
    }
}

class Qrscan extends React.Component {
    render() {
        return (
            <h1>test</h1>
        )
    }
}

//elements
class Header extends React.Component {
    render () {
        return (
            <div className="header">
                <div className="header-logo">Jukey</div>
            </div>
        )
    }
}

class But extends React.Component {
    getInfo () {
        for (var i = 0; i < pages.length; i++) {
            if(pages[i] == this.props.target) {
                return jsx[i];
            }
        }
    }

    render () {
        return (
            <button onClick={() => App.changePage(this.getInfo())} className={this.props.class}>{this.props.text}</button>
        )
    }
}

render (<App />, document.getElementById('app'));
</code>```

Thank you for taking the time to help me with my problems!

答:
ES6 Class declarations are not hoisted.

In your second line when you defined var jsx = [<Qrscan />];, that element is actually undefined. When I print out the contents of the jsx array, I get:

```<code>Object {$$typeof: Symbol(react.element), type: undefined, key: null, ref: null, props: Object…}
</code>```

So you simply have to shift that jsx array declaration to after your <Qrscan> component declaration.

Refer to the following JSFiddle for the fix and see for yourself that it works after shifting the declaration order (:

var pages = ['Qrscan'];

//Rendering
class Menu extends React.Component {
    render() {
        return (

                    <But target="Qrscan" class="button button-QR" text="Use QR code" type="button" linkTo="" />
                    <But class="button button-URL" text="Use URL" type="button" />

        )
    }
}

class App extends React.Component {
    constructor (props) {
        super(props);
        this.state = {target: <Menu />};
        App.changePage = App.changePage.bind(this);
    }

    static changePage (tar) {
       this.setState({target: tar});
    }

    render () {
        return (
          this.state.target
        )
    }
}

class Qrscan extends React.Component {
    render() {
        return (

test

        )
    }
}

var jsx = [<Qrscan />];

//elements
class Header extends React.Component {
    render () {
        return (

Jukey

        )
    }
}

class But extends React.Component {
    getInfo () {
        for (var i = 0; i < pages.length; i++) {
            if (pages[i] == this.props.target) {
                return jsx[i];
            }
        }
    }

    render () {
        return (
            <button onClick={() => App.changePage(this.getInfo())} className={this.props.class}>{this.props.text}</button>
        )
    }
}

ReactDOM.render (<App />, document.getElementById('app'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app">
</div></code>```

Body:
I have a problem with React when I try to change the page through the button (but) the console gives me:

Element type is invalid: expected a string (for built-in components) or >a class/function (for composite components) but got: undefined. You >likely forgot to export your component from the file it's defined in.

But when I put the onClick code in the class code it shows the jsx code. So it works but why do I still get the error? Here is my code:

import React from 'react';
import {render} from 'react-dom';

//sass
require('../sass/style.scss');

var pages = ['Qrscan'];
var jsx = [<Qrscan />];

class App extends React.Component {
    constructor (props) {
        super(props);
        this.state = {target: <Menu />};
        App.changePage = App.changePage.bind(this);
    }

    static changePage (tar) {
       this.setState({target: tar});
    }

    render () {
        return (
          this.state.target
        )
    }
}

//Rendering
class Menu extends React.Component {
    render() {
        return (

                    <But target="Qrscan" class="button button-QR" text="Use QR code" type="button" linkTo="" />
                    <But class="button button-URL" text="Use URL" type="button" />

        )
    }
}

class Qrscan extends React.Component {
    render() {
        return (

test

        )
    }
}

//elements
class Header extends React.Component {
    render () {
        return (

Jukey

        )
    }
}

class But extends React.Component {
    getInfo () {
        for (var i = 0; i < pages.length; i++) {
            if(pages[i] == this.props.target) {
                return jsx[i];
            }
        }
    }

    render () {
        return (
            <button onClick={() => App.changePage(this.getInfo())} className={this.props.class}>{this.props.text}</button>
        )
    }
}

render (<App />, document.getElementById('app'));

Thank you for taking the time to help me with my problems!

Body:
ES6 Class declarations are not hoisted.

In your second line when you defined var jsx = [<Qrscan />];, that element is actually undefined. When I print out the contents of the jsx array, I get:

Object {$$typeof: Symbol(react.element), type: undefined, key: null, ref: null, props: Object…}

So you simply have to shift that jsx array declaration to after your <Qrscan> component declaration.

Refer to the following JSFiddle for the fix and see for yourself that it works after shifting the declaration order (:

var pages = ['Qrscan'];

//Rendering
class Menu extends React.Component {
    render() {
        return (
            <div id="root">
                <Header />
                <div className="container">
                    <But target="Qrscan" class="button button-QR" text="Use QR code" type="button" linkTo="" />
                    <But class="button button-URL" text="Use URL" type="button" />
                </div>
            </div>
        )
    }
}

class App extends React.Component {
    constructor (props) {
        super(props);
        this.state = {target: <Menu />};
        App.changePage = App.changePage.bind(this);
    }

    static changePage (tar) {
       this.setState({target: tar});
    }

    render () {
        return (
          this.state.target
        )
    }
}

class Qrscan extends React.Component {
    render() {
        return (
            <h1>test</h1>
        )
    }
}

var jsx = [<Qrscan />];

//elements
class Header extends React.Component {
    render () {
        return (
            <div className="header">
                <div className="header-logo">Jukey</div>
            </div>
        )
    }
}

class But extends React.Component {
    getInfo () {
        for (var i = 0; i < pages.length; i++) {
            if (pages[i] == this.props.target) {
                return jsx[i];
            }
        }
    }

    render () {
        return (
            <button onClick={() => App.changePage(this.getInfo())} className={this.props.class}>{this.props.text}</button>
        )
    }
}

ReactDOM.render (<App />, document.getElementById('app'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app">
</div>


问:
Values pf pandas data frame columns as list
I am creating a data frame from dictionary in a list like below :

```<code>[{'points': [-9.3613566605198262, 4.0910018605047171, -9.3473134841172731, 4.0960021770649475], 'uid': 0},
 {'points': [-9.4687215264026712, 4.0132947848279499, -9.3641925245477857, 4.0159059337303784], 'uid': 1},
</code>```

The above is a list called l1

For data frame:

```<code>df = pd.DataFrame.from_records(l1)
</code>```

This creates following df:

```<code>   points                                          uid
0  [-9.3613566605198262, 4.09100186050......]      0
1  [-9.4687215264026712, 4.01329478482......]      1
</code>```

I want to know how to remove the list format/ square brackets from the points column, and it should contain simple comma separated values.

Also, How to limit the decimal place only to 2 digits?

I tried the following, but it doesn't works.

```<code>np.round(df, 2)
</code>```

and

```<code>df.round({'points':2})
</code>```

expected df

```<code>   points                      uid
0  -9.36, 4.09, -9.34, 4.09    0
1  -9.46, 4.01, -9.36, 4.01    1
</code>```

答:
Use apply to round the numbers in the list and then concat as a string.</p>

```<code>df['points'] = df.apply(lambda x: ', '.join(str(round(e,2)) for e in x.points),axis=1)

df
Out[1042]:
                     points  uid
0   -9.36, 4.09, -9.35, 4.1    0
1  -9.47, 4.01, -9.36, 4.02    1
</code>```

Body:
I am creating a data frame from dictionary in a list like below :

[{'points': [-9.3613566605198262, 4.0910018605047171, -9.3473134841172731, 4.0960021770649475], 'uid': 0},
 {'points': [-9.4687215264026712, 4.0132947848279499, -9.3641925245477857, 4.0159059337303784], 'uid': 1},

The above is a list called l1

For data frame:

df = pd.DataFrame.from_records(l1)

This creates following df:

   points                                          uid
0  [-9.3613566605198262, 4.09100186050......]      0
1  [-9.4687215264026712, 4.01329478482......]      1

I want to know how to remove the list format/ square brackets from the points column, and it should contain simple comma separated values.

Also, How to limit the decimal place only to 2 digits?

I tried the following, but it doesn't works.

np.round(df, 2)

and

df.round({'points':2})

expected df

   points                      uid
0  -9.36, 4.09, -9.34, 4.09    0
1  -9.46, 4.01, -9.36, 4.01    1

Body:
Use apply to round the numbers in the list and then concat as a string.

df['points'] = df.apply(lambda x: ', '.join(str(round(e,2)) for e in x.points),axis=1)

df
Out[1042]:
                     points  uid
0   -9.36, 4.09, -9.35, 4.1    0
1  -9.47, 4.01, -9.36, 4.02    1


问:
Angular 2 able to post request but not able to read the remote resource
I tried to post a request to my Laravel backend but failed to get the response as the error "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/path. (Reason: missing token ‘access-control-allow-origin’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel)" showed.

I have added Access-Control-Allow-Origin and Access-Control-Allow-Headers in both my client and server. Why does the error still showing?

答:
Remove the client-side code you added to send Access-Control-Allow-Origin in the request.

(Reason: missing token ‘access-control-allow-origin’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel)" showed.

I have added Access-Control-Allow-Origin and Access-Control-Allow-Headers in both my client and server. Why does the error still showing?

The error is showing because you added an Access-Control-Allow-Origin header to the client-side request. But Access-Control-Allow-Origin is a server response header. So if you send it from the client side in a request you’ll see the kind of error you’re seeing now.

“missing token ‘access-control-allow-origin’ in CORS header ‘Access-Control-Allow-Headers’“ is the browser telling you that your client code is  sending an Access-Control-Allow-Origin request header, but the Access-Control-Allow-Headers response header the server has returned doesn’t list "Access-Control-Allow-Origin" as one of the header names it allows in requests.

So because of that, the browser isn’t letting your frontend JavaScript code read the response.


问:
How to read huge CSV file with 29 million rows of data using .net
I have a huge .csv file, to be specific a .TAB file with 29 million rows and the file size is around 600 MB. I would need to read this into an IEnumerable collection.

I have tried CsvHelper, GenericParser, and few other solutions but always ending up with an Out of Memory exception

Please suggest a way to do this

I have tried

```<code>var deliveryPoints = new List<Point>();

using (TextReader csvreader1 = File.OpenText(@"C:\testfile\Prod\PCDP1705.TAB")) //StreamReader csvreader1 = new StreamReader(@"C:\testfile\Prod\PCDP1705.TAB"))
using (var csvR1 = new CsvReader(csvreader1, csvconfig))
{
     csvR1.Configuration.RegisterClassMap<DeliveryMap>();
     deliveryPoints = csvR1.GetRecords<Point>().ToList();
}

using (GenericParser parser = new GenericParser())
{
     parser.SetDataSource(@"C:\testfile\Prod\PCDP1705.TAB");

     parser.ColumnDelimiter = '\t';
     parser.FirstRowHasHeader = false;
     //parser.SkipStartingDataRows = 10;
     //parser.MaxBufferSize = 4096;
     //parser.MaxRows = 500;
     parser.TextQualifier = '\"';

     while (parser.Read())
     {
         var address = new Point();
         address.PostCodeID = int.Parse(parser[0]);
         address.DPS = parser[1];
         address.OrganisationFlag = parser[2];
         deliveryPoints.Add(address);
     }
}
</code>```

and

```<code>var deliveryPoints = new List<Point>();
csvreader = new StreamReader(@"C:\testfile\Prod\PCDP1705.TAB");
csv = new CsvReader(csvreader, csvconfig);

while (csv.Read())
{
     var address = new Point();
     address.PostCodeID = int.Parse(csv.GetField(0));
     address.DPS = csv.GetField(1);
     deliveryPoints.Add(address);
}
</code>```

答:
It worked by running in x64 mode, and by adding
<gcAllowVeryLargeObjects enabled="true" /> in app.config.

Body:
I have a huge .csv file, to be specific a .TAB file with 29 million rows and the file size is around 600 MB. I would need to read this into an IEnumerable collection.

I have tried CsvHelper, GenericParser, and few other solutions but always ending up with an Out of Memory exception

Please suggest a way to do this

I have tried

var deliveryPoints = new List<Point>();

using (TextReader csvreader1 = File.OpenText(@"C:\testfile\Prod\PCDP1705.TAB")) //StreamReader csvreader1 = new StreamReader(@"C:\testfile\Prod\PCDP1705.TAB"))
using (var csvR1 = new CsvReader(csvreader1, csvconfig))
{
     csvR1.Configuration.RegisterClassMap<DeliveryMap>();
     deliveryPoints = csvR1.GetRecords<Point>().ToList();
}

using (GenericParser parser = new GenericParser())
{
     parser.SetDataSource(@"C:\testfile\Prod\PCDP1705.TAB");

     parser.ColumnDelimiter = '\t';
     parser.FirstRowHasHeader = false;
     //parser.SkipStartingDataRows = 10;
     //parser.MaxBufferSize = 4096;
     //parser.MaxRows = 500;
     parser.TextQualifier = '\"';

     while (parser.Read())
     {
         var address = new Point();
         address.PostCodeID = int.Parse(parser[0]);
         address.DPS = parser[1];
         address.OrganisationFlag = parser[2];
         deliveryPoints.Add(address);
     }
}

and

var deliveryPoints = new List<Point>();
csvreader = new StreamReader(@"C:\testfile\Prod\PCDP1705.TAB");
csv = new CsvReader(csvreader, csvconfig);

while (csv.Read())
{
     var address = new Point();
     address.PostCodeID = int.Parse(csv.GetField(0));
     address.DPS = csv.GetField(1);
     deliveryPoints.Add(address);
}


问:
What are the project types supported by Windows store?
Are only universal windows platform (UWP) applications supported by Windows store or normal desktop applications such as win32 are also supported?

Also what is the difference between win32 project and a general empty project? is it the same but just with a console in the output?

Thanks in advance.

答:
Are only universal windows platform (UWP) applications supported by
  Windows store or normal desktop applications such as win32 are also
  supported?

Currently the project types accepted by Windows Store include Windows universal apps for Windows 10 and 8.1 and Windows Phone Silverlight project:

For desktop application, only Win32 desktop apps using .NET 4.6.1 can be published to the Store via Desktop Bridge.

After you generate your converted package, you need to fill out this form and you'll acquire the permission to publish your package once your request gets verified.

Also what is the difference between win32 project and a general empty
  project? is it the same but just with a console in the output?

You might refer to the response from @Elegentin Xie in this thread, which indicate the difference between them.


问:
Get fields from a third model based on the foreign key of a second model
I have three models, one of which has an ID from each of the others to join them. The issue I am trying to solve is how I can get the values From table one into table three  using table two to join them in the serializer, or if that is even the approach I should be taking to begin with.

model

```<code>class ModelOne(models.Model):
    color = models.CharField()
    size = models.CharField()

class ModelTwo(models.Model):
    One_id = models.ForeignKey(ModelOne)
    Three_id = models.CharField()

class ModelThree(models.Model):
</code>```

example serializer

```<code>class ModelThree Serializer
    model = ModelThree
    fields = ('color', 'size')

def get_color(self, obj):
    ???

def get_size(self, obj):
    ???
</code>```

my db structure

```<code>        ModelOne
-------------------------------------
id  color   size

    ModelTwo
-------------------------------------
id  ModelOneID  ModelThreeID

    ModelThree
-------------------------------------
id
</code>```

答:
I don't get it yet but you have: list id of Model 1 right?

~> You want to have model 3 (query by model2)

```<code># The flow: models2.objects.filter(model1_id__in = md1_ids)
# And you want to get model3 ? ~> need ids to query
# ~> Query 1:
md3_ids = models2.objects.filter(model1_id__in = md1_ids).values_list("model3_id", flat="true")
md3 = Models3.objects.filter(pk__in md3_ids)
</code>```

Is this it? I don't know what you want...

Body:
I have three models, one of which has an ID from each of the others to join them. The issue I am trying to solve is how I can get the values From table one into table three  using table two to join them in the serializer, or if that is even the approach I should be taking to begin with.

model

class ModelOne(models.Model):
    color = models.CharField()
    size = models.CharField()

class ModelTwo(models.Model):
    One_id = models.ForeignKey(ModelOne)
    Three_id = models.CharField()

class ModelThree(models.Model):

example serializer

class ModelThree Serializer
    model = ModelThree
    fields = ('color', 'size')

def get_color(self, obj):
    ???

def get_size(self, obj):
    ???

my db structure

        ModelOne
-------------------------------------
id  color   size

    ModelTwo
-------------------------------------
id  ModelOneID  ModelThreeID

    ModelThree
-------------------------------------
id

Body:
I don't get it yet but you have: list id of Model 1 right?

~> You want to have model 3 (query by model2)

# The flow: models2.objects.filter(model1_id__in = md1_ids)
# And you want to get model3 ? ~> need ids to query
# ~> Query 1:
md3_ids = models2.objects.filter(model1_id__in = md1_ids).values_list("model3_id", flat="true")
md3 = Models3.objects.filter(pk__in md3_ids)

Is this it? I don't know what you want...


问:
MBProgressHUD to show label text in more than one line
Hi i have a MBProgressHUD on my iPad screen. Works perfectly fine. But i want to change the label to show in three lines.Like this

```<code>    self.hud =  [[MBProgressHUD alloc] initWithView:self.navigationController.view];
self.hud.frame = CGRectMake(0, 0, 120, 143);

[self.navigationController.view addSubview:self.hud];
self.hud.delegate = self;
self.hud.mode = MBProgressHUDModeAnnularDeterminate;
NSString *strloadingText = [NSString stringWithFormat:@"Loading Data.\r Please Wait.\r 1-2 Minutes"];
NSLog(@"the loading text will be %@",strloadingText);
self.hud.labelText = strloadingText;
[self.hud show:YES];
</code>```

So i want the label in 3 lines

Loading Data.

Please Wait

1-2 Minutes

OR
can i assign an image to the HUD?

All this should be in the labeltext. But i am ending up with only one line. How can i do that?
If you need more info, please ask.Thanks.

答:
I had a question like this, too !

You can set hud.label.numberOfLines = 0;

And it works!

Body:
Hi i have a MBProgressHUD on my iPad screen. Works perfectly fine. But i want to change the label to show in three lines.Like this

    self.hud =  [[MBProgressHUD alloc] initWithView:self.navigationController.view];
self.hud.frame = CGRectMake(0, 0, 120, 143);

[self.navigationController.view addSubview:self.hud];
self.hud.delegate = self;
self.hud.mode = MBProgressHUDModeAnnularDeterminate;
NSString *strloadingText = [NSString stringWithFormat:@"Loading Data.\r Please Wait.\r 1-2 Minutes"];
NSLog(@"the loading text will be %@",strloadingText);
self.hud.labelText = strloadingText;
[self.hud show:YES];

So i want the label in 3 lines

Loading Data.

Please Wait

1-2 Minutes

OR
can i assign an image to the HUD?

All this should be in the labeltext. But i am ending up with only one line. How can i do that?
If you need more info, please ask.Thanks.


问:
Session data lost in Chrome only
I have a problem similar if not identical to the problem in this thread:
Randomly Losing Session Variables Only In Google Chrome & URL Rewriting

But all solutions in that thread don't work for me. I'm getting a strange behavior from only Google Chrome in my PHP/MySQL App. If I try it with Firefox, it works, but Chrome doesn't.

I navigate to some place in my shopping cart and at several places in the code I'll store session data. Don't worry about me starting the session or anything related to that, I've got 11 years in webapp dev, all is done fine.

In all browsers, I can var_dump($_SESSION) and get my data back, but in Chrome it doesn't keep the data. Also note that the session does get passed on, I can look in the network monitor and I see the cookie being sent and many other things related to session work but that one $_SESSION['last_viewed_element'] is not kept. I also can't seem to set anything else, all gets lost.

EDIT:

Problem resolved by switching from SESSIONS TO COOKIES...

答: You are probably loosing sessions only on your development environment, and it may be most probably because of 'same origin policy' of Chrome. If so, then this is your solution Disable same origin policy in Chrome</p>

Title: Session data lost in Chrome only


问:
How can I convert an int number from decimal to binary?
How can I convert an int number from decimal to binary. For example:

```<code>int x=10; // radix 10
</code>```

How can I make another integer has the binary representation of x, such as:

```<code>int y=1010; // radix 2
</code>```

by using c only?

答:
Your question is a bit unclear but I'll do my best to try to make sense of it.

How can I make another integer has the binary representation of x such as: int y=1010 radix 2?

From this it looks like you wish to write a binary literal in your source code. Java doesn't support binary integer literals. It only supports decimal, hexadecimal and octal.

You can write your number as a string instead and use Integer.parseInt with the desired radix:

```<code>int y = Integer.parseInt("1010", 2);
</code>```

But you should note that the final result is identical to writing int y = 10;. The integer 10 that was written as a decimal literal in the source code is identical in every way to one which was parsed from the binary string "1010". There is no difference in their internal representation if they are both stored as int.

If you want to convert an existing integer to its binary representation as a string then you can use Integer.toBinaryString as others have already pointed out.

Body:
How can I convert an int number from decimal to binary. For example:

int x=10; // radix 10

How can I make another integer has the binary representation of x, such as:

int y=1010; // radix 2

by using c only?

Body:
Your question is a bit unclear but I'll do my best to try to make sense of it.

How can I make another integer has the binary representation of x such as: int y=1010 radix 2?

From this it looks like you wish to write a binary literal in your source code. Java doesn't support binary integer literals. It only supports decimal, hexadecimal and octal.

You can write your number as a string instead and use Integer.parseInt with the desired radix:

int y = Integer.parseInt("1010", 2);

But you should note that the final result is identical to writing int y = 10;. The integer 10 that was written as a decimal literal in the source code is identical in every way to one which was parsed from the binary string "1010". There is no difference in their internal representation if they are both stored as int.

If you want to convert an existing integer to its binary representation as a string then you can use Integer.toBinaryString as others have already pointed out.

ContentLicense: CC BY-SA 2.5


问:
insert <button> to the end of layer styled text-overflow:ellipsis
I'm trying to add [read more] button to multiple line ellipsis layer.

```<code><p class="description">this is long text.this is long text. <button type="button">expand</button></p>

.description {
  width: 300px;
  text-overflow: ellipsis;
  display: -webkit-box;
  overflow: hidden;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.description button {
  margin: 0; padding: 0 0 0 10px;
  background-color: transparent; border-width: 0; outline-width: 0;
  font-size: 14px; color: #3f8f7b;
}
</code>```

https://jsfiddle.net/redhork7/symuzrmt/

the result should be like,

```<code>this is long text.this is long text.this is long text.this is long text.
this is long text.this is long text.this is long text.this is long text.
this is long text.this is long text.this is long text...   [more button]
</code>```

is it possible?

答:
Try This:

.wrapper {
  position: relative;
  display: inline-block;
  width: 360px;
}

.description {
  width: 300px;
  text-overflow: ellipsis;
  display: -webkit-box;
  overflow: hidden;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.btn {
  margin: 0; padding: 0 0 0 10px;
  background-color: transparent; border-width: 0; outline-width: 0;
  font-size: 14px; color: #3f8f7b;
  position: absolute;
  bottom: 15px;
  right: 0;
  cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div  class="wrapper">
 <p class="description">this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text. </p>
        <button type="button" class="btn">expand</button>
</div> </code>```

Body:
I'm trying to add [read more] button to multiple line ellipsis layer.

this is long text.this is long text. <button type="button">expand</button>

.description {
  width: 300px;
  text-overflow: ellipsis;
  display: -webkit-box;
  overflow: hidden;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.description button {
  margin: 0; padding: 0 0 0 10px;
  background-color: transparent; border-width: 0; outline-width: 0;
  font-size: 14px; color: #3f8f7b;
}

https://jsfiddle.net/redhork7/symuzrmt/

the result should be like,

this is long text.this is long text.this is long text.this is long text.
this is long text.this is long text.this is long text.this is long text.
this is long text.this is long text.this is long text...   [more button]

is it possible?

Body:
Try This:

.wrapper {
  position: relative;
  display: inline-block;
  width: 360px;
}

.description {
  width: 300px;
  text-overflow: ellipsis;
  display: -webkit-box;
  overflow: hidden;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.btn {
  margin: 0; padding: 0 0 0 10px;
  background-color: transparent; border-width: 0; outline-width: 0;
  font-size: 14px; color: #3f8f7b;
  position: absolute;
  bottom: 15px;
  right: 0;
  cursor: pointer;
}

<div  class="wrapper">
 <p class="description">this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text.this is long text. </p>
        <button type="button" class="btn">expand</button>
</div>


问:
C# Is it possible to replace my dictionary class with the contents of a text file?
For example, in a file of my project I have Dictionaries.cs containing:

```<code> public DictionaryInit() {

        public Dictionary<int, DictionaryCheckup> H = new Dictionary<int, DictionaryCheckup>()
        {
            {180000, new DictionaryCheckup {theGrouping="H"}},
            {180001, new DictionaryCheckup {theGrouping="H"}},
            {180303, new DictionaryCheckup {theGrouping="H"}},
        };

     public Dictionary<int, DictionaryCheckup> C = new Dictionary<int, DictionaryCheckup>()
        {
            {180700, new DictionaryCheckup {theGrouping="C"}},
            {180201, new DictionaryCheckup {theGrouping="C"}},
            {180503, new DictionaryCheckup {theGrouping="C"}},
        };

      Etc.
     }
</code>```

(DictionaryCheckup is a class that get;set; the string theGrouping)

The idea is that I wanted to allow my end user to hot swap a criteria, which is the dictionary class in question. Should he need to add a Dictionary U, he will simply need to copy the structure in the text file, replace the Key or Value where necessary, and then select it from the program. This loads it and replaces my dictionary class at runtime. Is this possible?

After some research, I found that Json and serialization is a method of doing this, but I'm not so  familiar with it, or if there's any difference from reading a text file. Here is a thread I found: How do I read and write a C# string Dictionary to a file?.

In these examples, i'm not sure how they differentiate a key from a value. Furthermore, I don't think I will be able to access my DictionaryCheckup class through this, which is the criteria the Key is valued to.

So, my question is whether I can, for simplicity, write my dictionary class, perhaps as-is, to a text file of some sort, and then load it up at runtime? Or would I have to create a var dictionary, and then add keys and values to it based on the external file? I'll probably look into the Json method anyway of seralization, I'm just worried about implementing a web function when my program has nothing to do with it.

答:
You could use serialisation to convert your dictionary to a json string, then write it down in a text file. Then you can read up that same file and deserialise the json string to get your dictionary back. Here's an example :</p>

```<code>public static string SerializeToJSON<T>(T obj) {
    return new JavaScriptSerializer().Serialize(obj);
}

public static T DeserializeJSON<T>(string json) {
    return new JavaScriptSerializer().Deserialize<T>(json);
}

// Fake path for the example
string path = "~/myFile.json";

// Instanciates a fake dictionary for the example.
Dictionary<string,string> myDict = new Dictionary<string,string>() { new KeyValuePair("A","1") };

// Using serialisation, we save the content of our dictionary into a text file.
string json = SerializeToJSON<Dictionary<string,string>>(myDict);
File.WriteAllText(path, json);

// Then with deserialisation, we get back our old dictionary.
Dictionary myOtherDict = Dictionary<string,string>DeserializeJSON<Dictionary<string,string>>(File.ReadAllText(path));
</code>```

Body:
For example, in a file of my project I have Dictionaries.cs containing:

 public DictionaryInit() {

        public Dictionary<int, DictionaryCheckup> H = new Dictionary<int, DictionaryCheckup>()
        {
            {180000, new DictionaryCheckup {theGrouping="H"}},
            {180001, new DictionaryCheckup {theGrouping="H"}},
            {180303, new DictionaryCheckup {theGrouping="H"}},
        };

     public Dictionary<int, DictionaryCheckup> C = new Dictionary<int, DictionaryCheckup>()
        {
            {180700, new DictionaryCheckup {theGrouping="C"}},
            {180201, new DictionaryCheckup {theGrouping="C"}},
            {180503, new DictionaryCheckup {theGrouping="C"}},
        };

      Etc.
     }

(DictionaryCheckup is a class that get;set; the string theGrouping)

The idea is that I wanted to allow my end user to hot swap a criteria, which is the dictionary class in question. Should he need to add a Dictionary U, he will simply need to copy the structure in the text file, replace the Key or Value where necessary, and then select it from the program. This loads it and replaces my dictionary class at runtime. Is this possible?

After some research, I found that Json and serialization is a method of doing this, but I'm not so  familiar with it, or if there's any difference from reading a text file. Here is a thread I found: How do I read and write a C# string Dictionary to a file?.

In these examples, i'm not sure how they differentiate a key from a value. Furthermore, I don't think I will be able to access my DictionaryCheckup class through this, which is the criteria the Key is valued to.

So, my question is whether I can, for simplicity, write my dictionary class, perhaps as-is, to a text file of some sort, and then load it up at runtime? Or would I have to create a var dictionary, and then add keys and values to it based on the external file? I'll probably look into the Json method anyway of seralization, I'm just worried about implementing a web function when my program has nothing to do with it.

Body:
You could use serialisation to convert your dictionary to a json string, then write it down in a text file. Then you can read up that same file and deserialise the json string to get your dictionary back. Here's an example :

public static string SerializeToJSON<T>(T obj) {
    return new JavaScriptSerializer().Serialize(obj);
}

public static T DeserializeJSON<T>(string json) {
    return new JavaScriptSerializer().Deserialize<T>(json);
}

// Fake path for the example
string path = "~/myFile.json";

// Instanciates a fake dictionary for the example.
Dictionary<string,string> myDict = new Dictionary<string,string>() { new KeyValuePair("A","1") };

// Using serialisation, we save the content of our dictionary into a text file.
string json = SerializeToJSON<Dictionary<string,string>>(myDict);
File.WriteAllText(path, json);

// Then with deserialisation, we get back our old dictionary.
Dictionary myOtherDict = Dictionary<string,string>DeserializeJSON<Dictionary<string,string>>(File.ReadAllText(path));


问:
what does `twine upload dist/*` command do?
I apologize in advance since this seems like a basic question...

I am trying to learn using mujoco(link here), and inside its python binding Makefile it has:

```<code>upload:
   rm -rf dist
   python setup.py sdist
   twine upload dist/*
</code>```

What does twin upload dist/* command do?
In addition, this asks me for a username and password like this:

```<code>Uploading distributions to https://pypi.python.org/pypi
Enter your username: guest
Enter your password:
Uploading mujoco-py-0.5.7.tar.gz
HTTPError: 401 Client Error: You must be identified to edit package information for url: https://pypi.python.org/pypi
Makefile:2: recipe for target 'upload' failed
</code>```

Is this asking for my computer username and password?

答:
Twine is a commonly used system for uploading project builds to PyPI (the Python Package Index).

It will take care of securely transferring your project's build artifacts, in either wheel, sdist, etc. formats to PyPI or some other user defined index server.

When you specify twine upload <files>, twine will attempt to upload said files to PyPI, but in order to do so, it will require you to authenticate yourself. This is because PyPI wants to protect a project from having their advertised packages "hijacked" by a ne'er-do-well. In order for this step to proceed, you would have to give credentials that are marked as authoritative for the project that your uploaded project artifacts belong to.

It looks like the mujoco project's Makefile includes a target to ease in uploading updates of the project to PyPI by utilizing the Twine application. This target would only be meant to be used by the package maintainer(s).

Oh, and in case you were wondering, the python setup.py sdist command is what makes a source code artifact that can be uploaded to PyPI. It will place this artifact in the ./build/ directory as project-name_version.tar.gz.

Body:
I apologize in advance since this seems like a basic question...

I am trying to learn using mujoco(link here), and inside its python binding Makefile it has:

upload:
   rm -rf dist
   python setup.py sdist
   twine upload dist/*

What does twin upload dist/* command do?
In addition, this asks me for a username and password like this:

Uploading distributions to https://pypi.python.org/pypi
Enter your username: guest
Enter your password:
Uploading mujoco-py-0.5.7.tar.gz
HTTPError: 401 Client Error: You must be identified to edit package information for url: https://pypi.python.org/pypi
Makefile:2: recipe for target 'upload' failed

Is this asking for my computer username and password?


问:
What does module.exports = { Mongoose , models: { ... } } mean?
I am learning Node/Mongo, and now I can understand the code like this,

```<code>module.exports = mongoose.model('User', UserSchema);
</code>```

I have trouble understanding the following,

```<code>module.exports = { Mongoose, // var Mongoose = require('mongoose');
    models: {
        user: require('./schemas/user.js'),
        room: require('./schemas/room.js')
    }
};
</code>```

I can see the author wants to export Mongoose and the models. But is the exported object a JSON object? Is the Mongoose in it a key or a value? Is JSON allowed a key without value or a value without a key?
Or I am getting all wrong?

答:
Looks like the author of that is using ES6 semantics.

In ES6, you can shorthand the following:

```<code>const Mongoose = require('mongoose');
const myObj = { Mongoose: Mongoose };
</code>```

to:

```<code>const Mongoose = require('mongoose');
const myObj = { Mongoose };
</code>```

Basically, it will interpret that as the same statement as above, providing the key is the same name as the named variable.

As an aside, exporting the mongoose object is unnecessary in the example you have or the one I have; the require cache will return the same instance of it every time in any event.

Body:
I am learning Node/Mongo, and now I can understand the code like this,

module.exports = mongoose.model('User', UserSchema);

I have trouble understanding the following,

module.exports = { Mongoose, // var Mongoose = require('mongoose');
    models: {
        user: require('./schemas/user.js'),
        room: require('./schemas/room.js')
    }
};

I can see the author wants to export Mongoose and the models. But is the exported object a JSON object? Is the Mongoose in it a key or a value? Is JSON allowed a key without value or a value without a key?
Or I am getting all wrong?

Body:
Looks like the author of that is using ES6 semantics.

In ES6, you can shorthand the following:

const Mongoose = require('mongoose');
const myObj = { Mongoose: Mongoose };

to:

const Mongoose = require('mongoose');
const myObj = { Mongoose };

Basically, it will interpret that as the same statement as above, providing the key is the same name as the named variable.

As an aside, exporting the mongoose object is unnecessary in the example you have or the one I have; the require cache will return the same instance of it every time in any event.


问:
Webkit transitionEnd event grouping
I have a HTML element to which I have attached a webkitTransitionEnd event.

```<code>function transEnd(event) {
    alert( "Finished transition!" );

}

var node = document.getElementById('node');
node.addEventListener( 'webkitTransitionEnd', transEnd, false );
</code>```

Then I proceed to change its CSS left and top properties like:

```<code>node.style.left = '400px';
node.style.top = '400px';
</code>```

This causes the DIV to move smoothly to the new position. But, when it finishes, 2 alert boxes show up, while I was expecting just one at the end of the animation. When I changed just the CSS left property, I get one alert box - so this means that the two changes to the style are being registered as two separate events. I want to specify them as one event, how do I do that?

I can't use a CSS class to apply both the styles at the same time because the left and top CSS properties are variables which I will only know at run time.

答:
Check the propertyName event:

```<code>function transEnd(event) {
    if (event.propertyName === "left") {
        alert( "Finished transition!" );
    }
}

var node = document.getElementById('node');
node.addEventListener( 'webkitTransitionEnd', transEnd, false );
</code>```

That way, it will only fire when the "left" property is finished. This would probably work best if both properties are set to the same duration and delay. Also, this will work if you change only "left", or both, but not if you change only "top".

Alternatively, you could use some timer trickery:

```<code>var transEnd = function anon(event) {
    if (!anon.delay) {
        anon.delay = true;

        clearTimeout(anon.timer);
        anon.timer = setTimeout(function () {
            anon.delay = false;
        }, 100);

        alert( "Finished transition!" );
    }
};

var node = document.getElementById('node');
node.addEventListener( 'webkitTransitionEnd', transEnd, false );
</code>```

This should ensure that your code will run at most 1 time every 100ms. You can change the setTimeout delay to suit your needs.

ContentLicense: CC BY-SA 4.0

Title: Webkit transitionEnd event grouping

Body:
I have a HTML element to which I have attached a webkitTransitionEnd event.

function transEnd(event) {
    alert( "Finished transition!" );

}

var node = document.getElementById('node');
node.addEventListener( 'webkitTransitionEnd', transEnd, false );

Then I proceed to change its CSS left and top properties like:

node.style.left = '400px';
node.style.top = '400px';

This causes the DIV to move smoothly to the new position. But, when it finishes, 2 alert boxes show up, while I was expecting just one at the end of the animation. When I changed just the CSS left property, I get one alert box - so this means that the two changes to the style are being registered as two separate events. I want to specify them as one event, how do I do that?

I can't use a CSS class to apply both the styles at the same time because the left and top CSS properties are variables which I will only know at run time.

Body:
Check the propertyName event:

function transEnd(event) {
    if (event.propertyName === "left") {
        alert( "Finished transition!" );
    }
}

var node = document.getElementById('node');
node.addEventListener( 'webkitTransitionEnd', transEnd, false );

That way, it will only fire when the "left" property is finished. This would probably work best if both properties are set to the same duration and delay. Also, this will work if you change only "left", or both, but not if you change only "top".

Alternatively, you could use some timer trickery:

var transEnd = function anon(event) {
    if (!anon.delay) {
        anon.delay = true;

        clearTimeout(anon.timer);
        anon.timer = setTimeout(function () {
            anon.delay = false;
        }, 100);

        alert( "Finished transition!" );
    }
};

var node = document.getElementById('node');
node.addEventListener( 'webkitTransitionEnd', transEnd, false );

This should ensure that your code will run at most 1 time every 100ms. You can change the setTimeout delay to suit your needs.


答:
First, just a clarification on terminology: JSON is a string and not an object hence it's abbreviation of JavaScript Object Notation. What you have is colloquially referred to as a POJO or Plain Old Javascript Object. They are different.

Second, lets break down the exports statement:

```<code>{ Mongoose, //...
</code>```

This is ES6 (ES2015) syntax for object initialization using shorthand property names. Basically, if a variable name (var foo = 'hi') matches an object property name, then the initialization can simply be { foo } which is the same as { foo: foo }.

Regarding what is exported, it will be a POJO equivalent to:

```<code>{
    Mongoose: require('mongoose'),
    models: {
        user: require('./schemas/user.js'),
        room: require('./schemas/room.js')
    }
};
</code>```

BONUS: Since Node maintains a cache of required modules, Mongoose uses this as a cacheing mechanism for all declared models and schemas. If in one file you import Mongoose and create a model, another module would be able to import Mongoose and have access to that model via Mongoose's cache.

```<code>// a.js
const mongoose = require('mongoose');
const FooModel = new mongoose.model('Foo', {});

// b.js
const aMod = require('./a.js'); // Import here only to declare model.
const mongoose = require('mongoose');
const FooModel = mongoose.model('Foo'); // Same model a.js
</code>```

Title: What does module.exports = { Mongoose , models: { ... } } mean?

Body:
First, just a clarification on terminology: JSON is a string and not an object hence it's abbreviation of JavaScript Object Notation. What you have is colloquially referred to as a POJO or Plain Old Javascript Object. They are different.

Second, lets break down the exports statement:

{ Mongoose, //...

This is ES6 (ES2015) syntax for object initialization using shorthand property names. Basically, if a variable name (var foo = 'hi') matches an object property name, then the initialization can simply be { foo } which is the same as { foo: foo }.

Regarding what is exported, it will be a POJO equivalent to:

{
    Mongoose: require('mongoose'),
    models: {
        user: require('./schemas/user.js'),
        room: require('./schemas/room.js')
    }
};

BONUS: Since Node maintains a cache of required modules, Mongoose uses this as a cacheing mechanism for all declared models and schemas. If in one file you import Mongoose and create a model, another module would be able to import Mongoose and have access to that model via Mongoose's cache.

// a.js
const mongoose = require('mongoose');
const FooModel = new mongoose.model('Foo', {});

// b.js
const aMod = require('./a.js'); // Import here only to declare model.
const mongoose = require('mongoose');
const FooModel = mongoose.model('Foo'); // Same model a.js


问:
how can I run a jar from /usr/local/bin like a Terminal command?
I have made a calculator CLI calculator app in Java that I would like to use. Since I am actually going to use it quite often, I do not like the idea of typing the long path all the time.
I have read an article on StackoverFlow that you can place a .sh command into the /usr/bin folder, but after the El Capitan update, all System folders are locked even for the root user. So, again, I did some more research, and I found that /usr/local/bin folder is specifically made for "home-made" commands for the terminal. I have made a calculator.sh file with the following code:

```<code>    #!/bin/sh
    -jar /Users/mac/Desktop/Данила/my_apps/calculator.jar "$*"
</code>```

The article said that I should place it in the /usr/bin folder, but because it is locked, I placed it in the /usr/local/bin, thinking that it is practically the same thing, and that it should work. Of course after I placed it in there and tried to run "calculator" command in the terminal, it did not work at all. I figured that it might need a "chmod" command to make it work. So I used chmod +x /path, but afterwards it still would not work. Right now I am stumped, so any help would be welcome.

答:
To this I recommend you create an alias.

```<code>alias test="java -jar /full/path/to/jar.jar"
</code>```

And "test" is a command now, if you like get this command allways add it into .bash_profile.

Body:
I have made a calculator CLI calculator app in Java that I would like to use. Since I am actually going to use it quite often, I do not like the idea of typing the long path all the time.
I have read an article on StackoverFlow that you can place a .sh command into the /usr/bin folder, but after the El Capitan update, all System folders are locked even for the root user. So, again, I did some more research, and I found that /usr/local/bin folder is specifically made for "home-made" commands for the terminal. I have made a calculator.sh file with the following code:

    #!/bin/sh
    -jar /Users/mac/Desktop/Данила/my_apps/calculator.jar "$*"

The article said that I should place it in the /usr/bin folder, but because it is locked, I placed it in the /usr/local/bin, thinking that it is practically the same thing, and that it should work. Of course after I placed it in there and tried to run "calculator" command in the terminal, it did not work at all. I figured that it might need a "chmod" command to make it work. So I used chmod +x /path, but afterwards it still would not work. Right now I am stumped, so any help would be welcome.

Body:
To this I recommend you create an alias.

alias test="java -jar /full/path/to/jar.jar"

And "test" is a command now, if you like get this command allways add it into .bash_profile.


问:
Calculation of stack size in FreeRtos or TI rtos
Recently I was working with Rtos and created some tasks to perform my required actions. Although it seems like every time when I create new task with xTaskCreate or TI GUI configuration, I simply try to keep my stack size as much so that the stack must not get overflowed.
Is there any way to calculate the maximum stack size used by my task with respect to these events?
1. Stack used by global and local variable
2. Stack used by the maximum number of recursion of the function
3. Including the interrupt context switching   </p>

答:
The compiler, compiler optimisation level, CPU architecture, local variable allocations and function call nesting depth all have a large impact on the stack size.  The RTOS has minimal impact.  For example, FreeRTOS will add approximately 60 bytes to the stack on a Cortex-M - which is used to store the task's context when the task is not running.  Whichever method you use to calculate stack usage in your non-RTOS project can be used in your RTOS project too - then add approximately 60 bytes.

You can calculate these things, and that can be important in safety critical applications, but in other cases a more pragmatic approach is to try it and see - use the features of the RTOS to measure how much stack is actually being used and use the stack overflow detection - then adjust until you find something optimal.
http://www.freertos.org/Stacks-and-stack-overflow-checking.html
http://www.freertos.org/uxTaskGetStackHighWaterMark.html


问:
Associative arrays in shell scripts
We require a script that simulates associative arrays or map-like data structure for shell scripting. Can anyone let's know how it is done?</p>

答:
Another non-bash 4 way.

```<code>#!/bin/bash

# A pretend Python dictionary with bash 3
ARRAY=( "cow:moo"
        "dinosaur:roar"
        "bird:chirp"
        "bash:rock" )

for animal in "${ARRAY[@]}" ; do
    KEY=${animal%%:*}
    VALUE=${animal#*:}
    printf "%s likes to %s.\n" "$KEY" "$VALUE"
done

echo -e "${ARRAY[1]%%:*} is an extinct animal which likes to ${ARRAY[1]#*:}\n"
</code>```

You could throw an if statement for searching in there as well. if [[ $var =~ /blah/ ]].
or whatever.

OwnerDisplayName: Irfan Zulfiqar

Title: Associative arrays in shell scripts

LastEditorDisplayName: Irfan Zulfiqar

Body:
Another non-bash 4 way.

#!/bin/bash

# A pretend Python dictionary with bash 3
ARRAY=( "cow:moo"
        "dinosaur:roar"
        "bird:chirp"
        "bash:rock" )

for animal in "${ARRAY[@]}" ; do
    KEY=${animal%%:*}
    VALUE=${animal#*:}
    printf "%s likes to %s.\n" "$KEY" "$VALUE"
done

echo -e "${ARRAY[1]%%:*} is an extinct animal which likes to ${ARRAY[1]#*:}\n"

You could throw an if statement for searching in there as well. if [[ $var =~ /blah/ ]].
or whatever.


答:
First, is /usr/local/bin on your path? echo $PATH to find out.

Second, are you sure you pasted the above script properly?

It seems to be missing java on the command line.

I would expect it to look something like:

```<code>#!/bin/sh
java -jar /Users/mac/Desktop/Данила/my_apps/calculator.jar "$*"
</code>```

Also, since you named it calculator.sh, you have to run it using that name.

The .sh extension isn't needed, so you could just call it calculator.

Title: how can I run a jar from /usr/local/bin like a Terminal command?

Body:
First, is /usr/local/bin on your path? echo $PATH to find out.

Second, are you sure you pasted the above script properly?

It seems to be missing java on the command line.

I would expect it to look something like:

#!/bin/sh
java -jar /Users/mac/Desktop/Данила/my_apps/calculator.jar "$*"

Also, since you named it calculator.sh, you have to run it using that name.

The .sh extension isn't needed, so you could just call it calculator.


问:
Jupyter on Azure can not be reached
I can not access Jupyter notebook on Data science VM in Azure clould.

What I did:

create a Data Science VM for Linux. Resource group, NSG, etc are newly created.

follow the instruction of the command dsvm-more-info. That is

set c.NotebookApp.password (u'sha1:89this89is89a89fake89')

restart jupyter

access https://12.34.56.78:9999/ (The IP address is of course a fake.)

But I can not establish any connection to the server.

SSH works without any problem.

NSG looks OK: TCP/9999 is allowed from all (This is the default setting.)

I tried to https://localhost:9999/ on the VM, but no connection is established.

http://12.34.56.78:9999/ is not working. (Just in case.)

c.NotebookApp.allow_origin = '*' changes nothing.

My subscription is a test version. Is this relevant?

Following Jupyter Documentation, I created mykey.key and mycert.pem and
added absolute paths to the files in jupyter_notebook_config.py. But
this does not help.

答:
The Jupyter notebook is accessed through JupyterHub. You sign in using
  your local Linux user name and password.

So, you should connect Jupyter notebook from port 8000, not 9999.

You can access the Jupyter notebook server from any host. Just type https://<VM DNS name or IP Address>:8000/

You also could use netstat -ant to check port listening on your VM. Port 9999 is not listening. So, you could not get it from port 9999.

More information about Jupyter on Azure Data science VM please refer to this link. You could check Jupyter notebook.

Title: Jupyter on Azure can not be reached


问:
I want to pass values between fragment
My situation is like this I have an activity home activity inside it there are three buttons to switch and a container. In each button click I have to replace the container with fragment say A,B,C. In these fragment have a common container which will be replaced by fragments X,Y.

so my problem is that when I want to display data inside say X fragment I want to know which is the parent fragment A or B or C. So how to make this problem solved

Thanks

答: if you are a simple record data, you can remember a variable only when switch(replase) fragment</p>

Title: I want to pass values between fragment


问:
PSQLException: current transaction is aborted, commands ignored until end of transaction block
I am seeing the following (truncated) stacktrace in the server.log file of JBoss 7.1.1 Final:

```<code>Caused by: org.postgresql.util.PSQLException:
ERROR: current transaction is aborted, commands ignored until end of
transaction block

at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:512)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:374)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:302)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.6.0_23]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [rt.jar:1.6.0_23]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [rt.jar:1.6.0_23]
at java.lang.reflect.Method.invoke(Method.java:597) [rt.jar:1.6.0_23]
at org.postgresql.ds.jdbc23.AbstractJdbc23PooledConnection$StatementHandler.invoke(AbstractJdbc23PooledConnection.java:455)
at $Proxy49.executeUpdate(Unknown Source)   at org.jboss.jca.adapters.jdbc.WrappedStatement.executeUpdate(WrappedStatement.java:371)
at org.infinispan.loaders.jdbc.TableManipulation.executeUpdateSql(TableManipulation.java:154) [infinispan-cachestore-jdbc-5.1.2.FINAL.jar:5.1.2.FINAL]
... 154 more
</code>```

Inspecting the Postgres log file reveals the following statements:

```<code>STATEMENT:  SELECT count(*) FROM ISPN_MIXED_BINARY_TABLE_configCache
ERROR:  current transaction is aborted, commands ignored until end of transaction block
STATEMENT:  CREATE TABLE ISPN_MIXED_BINARY_TABLE_configCache(ID_COLUMN VARCHAR(255) NOT NULL, DATA_COLUMN BYTEA, TIMESTAMP_COLUMN BIGINT, PRIMARY KEY (ID_COLUMN))
ERROR:  relation "ispn_mixed_binary_table_configcache" does not exist at character 22
</code>```

I am using the Infinispan shipped with JBoss 7.1.1 Final, which is 5.1.2.Final.

So this is what I think is happening:

Infinispan attempts to run the SELECT count(*)... statement in order to see if there are any records in the ISPN_MIXED_BINARY_TABLE_configCache;

Postgres, for some reason, does not like this statement.

Infinispan ignores this and plows ahead with the CREATE TABLE statement.

Postgres barfs because it still thinks it's the same transaction, which Infinispan has failed to roll back, and this transaction is shafted from the first SELECT count(*)... statement.

What does this error mean and any idea how to work around it?

答: The reason for this error is that there are other database before the wrong operation led to the current database operation can not be carried out（i use google translation to translate my chinese to english）</p>

Body:
I am seeing the following (truncated) stacktrace in the server.log file of JBoss 7.1.1 Final:

Caused by: org.postgresql.util.PSQLException:
ERROR: current transaction is aborted, commands ignored until end of
transaction block

at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:512)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:374)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:302)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.6.0_23]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [rt.jar:1.6.0_23]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [rt.jar:1.6.0_23]
at java.lang.reflect.Method.invoke(Method.java:597) [rt.jar:1.6.0_23]
at org.postgresql.ds.jdbc23.AbstractJdbc23PooledConnection$StatementHandler.invoke(AbstractJdbc23PooledConnection.java:455)
at $Proxy49.executeUpdate(Unknown Source)   at org.jboss.jca.adapters.jdbc.WrappedStatement.executeUpdate(WrappedStatement.java:371)
at org.infinispan.loaders.jdbc.TableManipulation.executeUpdateSql(TableManipulation.java:154) [infinispan-cachestore-jdbc-5.1.2.FINAL.jar:5.1.2.FINAL]
... 154 more

Inspecting the Postgres log file reveals the following statements:

STATEMENT:  SELECT count(*) FROM ISPN_MIXED_BINARY_TABLE_configCache
ERROR:  current transaction is aborted, commands ignored until end of transaction block
STATEMENT:  CREATE TABLE ISPN_MIXED_BINARY_TABLE_configCache(ID_COLUMN VARCHAR(255) NOT NULL, DATA_COLUMN BYTEA, TIMESTAMP_COLUMN BIGINT, PRIMARY KEY (ID_COLUMN))
ERROR:  relation "ispn_mixed_binary_table_configcache" does not exist at character 22

I am using the Infinispan shipped with JBoss 7.1.1 Final, which is 5.1.2.Final.

So this is what I think is happening:

Infinispan attempts to run the SELECT count(*)... statement in order to see if there are any records in the ISPN_MIXED_BINARY_TABLE_configCache;

Postgres, for some reason, does not like this statement.

Infinispan ignores this and plows ahead with the CREATE TABLE statement.

Postgres barfs because it still thinks it's the same transaction, which Infinispan has failed to roll back, and this transaction is shafted from the first SELECT count(*)... statement.

What does this error mean and any idea how to work around it?


问:
Extract text between characters, strings or brackets

I have following types of data :

```<code>pd.DataFrame({"Hashtags": [ "[]", "[u'AAPHealthCare4All']", "[u'CBI',","u'Delhi',", "u'Emergency']"]})
</code>```

Expected Output

```<code>pd.DataFrame({"Hashtags": [ " ", "AAPHealthCare4All", "CBI","Delhi", "Emergency"]})
</code>```

None of the brackets, parentheses or commas and quotes are missing/typo.
[] should be substituted with blanks. Basically I want to remove all the "[" , "]" , " [u' " etc.
I have used the following code, but to no avail :

```<code>for index,row in df.iterrows():
    if "RT @" in row["Tweet"]:
        df['Hashtags'] =df['Hashtags'].str.replace(r'[^[]]*\[|\][^]*|\[u\'*\'\]|\[\'*\'\]', '')
df.to_csv('string_HT.csv', index=False)
</code>```

答:
You can use extract function:</p>

```<code>df.Hashtags.str.extract("'(.*)'").fillna('')
Out[1052]:
0
1    AAPHealthCare4All
2                  CBI
3                Delhi
4            Emergency
Name: Hashtags, dtype: object
</code>```

Body:
I have following types of data :

pd.DataFrame({"Hashtags": [ "[]", "[u'AAPHealthCare4All']", "[u'CBI',","u'Delhi',", "u'Emergency']"]})

Expected Output

pd.DataFrame({"Hashtags": [ " ", "AAPHealthCare4All", "CBI","Delhi", "Emergency"]})

None of the brackets, parentheses or commas and quotes are missing/typo.
[] should be substituted with blanks. Basically I want to remove all the "[" , "]" , " [u' " etc.
I have used the following code, but to no avail :

for index,row in df.iterrows():
    if "RT @" in row["Tweet"]:
        df['Hashtags'] =df['Hashtags'].str.replace(r'[^[]]*\[|\][^]*|\[u\'*\'\]|\[\'*\'\]', '')
df.to_csv('string_HT.csv', index=False)

Body:
You can use extract function:

df.Hashtags.str.extract("'(.*)'").fillna('')
Out[1052]:
0
1    AAPHealthCare4All
2                  CBI
3                Delhi
4            Emergency
Name: Hashtags, dtype: object


问:
Is there a utility that does the opposite of ilmerge?
I would like to strip code from an assembly using a command-line or GUI. There are times when assemblies contain types that are in other assemblies and this requires you to add extern alias to your code (which isn't that big of a deal). The alternative is recompilation from source (if available) into separate assemblies or stripping code the assembly in some way, and adding back references in the "main" assembly.

I guess I'm looking for ilunmerge. Does anyone know of such a utility?

答: Reflector is another tool that will let you disassemble your binaries.</p>


问:
How do I get logs from all pods of a Kubernetes replication controller?
Running kubectl logs shows me the stderr/stdout of one Kubernetes container.

How can I get the aggregated stderr/stdout of a set of pods, preferably those created by a certain replication controller?

答:
You can use labels

```<code>kubectl logs -l app=elasticsearch
</code>```

And you'd probably want to specify --all-containers --ignore-errors in order to:

Include logs from pods with multiple containers

Continue to next pod on fatal error (e.g. logs could not be retrieved)

Body:
You can use labels

kubectl logs -l app=elasticsearch

And you'd probably want to specify --all-containers --ignore-errors in order to:

Include logs from pods with multiple containers

Continue to next pod on fatal error (e.g. logs could not be retrieved)


问:
Converting C++ project to a DLL to use in C# application
I've been searching around for days for a custom .NET control that can select multiple files and multiple folders all at once.

The only one I have found to be exactly what i'm looking for is the one below, but it's written in C++.

https://www.codeproject.com/Articles/28015/SelectDialog-A-Multiple-File-and-Folder-Select-Dia

Can anyone please tell me how I can get it to work in my C# application? Either as a DLL reference or just including the project in my current solution.

I tried to compile it as an unmanaged DLL and then do a DLLImport from my C# project but couldn't get it working.

Thanks in advance.

答:
It's a bit tricky if the class doesn't have a C# wrapper already created for it.  Are you absolutely sure you need this C++ control - in my experience I'd avoid using something that goes outside the .Net library unless you absolutely must.  It's a pain :0

Have a look at this - it's quite a good instruction list:
How to Marshal a C++ class


问:
Windows bat: files without extension (dot in name issue)
At first: it's not a repeated question (I hope). I've searched a lot and found How to find files with no file extension in directory tree with a batch file? and Find and rename files with no extension?, among others, but I have a "small" additional problem.

I'm trying to rename multiple (thousands) of jpg files on Windows 10. The name format is "Name (ABC).jpg" or "Multiple Names (ABC).jpg". I need "Some Name.jpg".

What have you tried? So many things, none of them a real solution, until this:

```<code>for /f "tokens=1-3 delims=)(" %%a in ('dir /b *.jpg') do @rename "%%a(%%b)%%c" "%%a"
for /R %%x in (*.) do ren "%%x" *.png
</code>```

It works fine for most of the files, except when there's a dot in the name. If the name is something like "A Name.Supercool (ABC).jpg", it will be only "A Name.Supercool", with no extension.

I know the problem is on (*.), just don't know how to solve...

答:
Your problem is that renaming your files to "%%a" produces "A Name.Supercool" - and that this has "no extension".

Ah - but it does. The filename is "A Name" and the extension is ".Supercool"

Were you to rename your file to `"%%a%%c" then the name would become "A Name.Supercool.jpg".

Now why, after attempting to rename your file to extensionless, you are then renaming them to *.png I've no idea, and you don't explain, unfortunately. Why wouldn't you simply tack on the .png to the %%a - if that truly was what you wanted to do?

(BTW - the for /f ... dir... approach builds a memory-list of the files, then renames them, so they won't be re-processed as may occur with for %%x in (*.jpg)...)

Given the terminal-space-in-name problem,

```<code>for /f "tokens=1-3 delims=)(" %%a in ('dir /b *.jpg') do rename "%%a(%%b)%%c" "%%a%%c"
SETLOCAL enabledelayedexpansion
for /f "delims=" %%a in ('dir /b "* .jpg"') do (
 SET "name=%%a"
 REN "%%a" "!name:~0,-5!.jpg"
)
endlocal
</code>```

Body:
At first: it's not a repeated question (I hope). I've searched a lot and found How to find files with no file extension in directory tree with a batch file? and Find and rename files with no extension?, among others, but I have a "small" additional problem.

I'm trying to rename multiple (thousands) of jpg files on Windows 10. The name format is "Name (ABC).jpg" or "Multiple Names (ABC).jpg". I need "Some Name.jpg".

What have you tried? So many things, none of them a real solution, until this:

for /f "tokens=1-3 delims=)(" %%a in ('dir /b *.jpg') do @rename "%%a(%%b)%%c" "%%a"
for /R %%x in (*.) do ren "%%x" *.png

It works fine for most of the files, except when there's a dot in the name. If the name is something like "A Name.Supercool (ABC).jpg", it will be only "A Name.Supercool", with no extension.

I know the problem is on (*.), just don't know how to solve...

Body:
Your problem is that renaming your files to "%%a" produces "A Name.Supercool" - and that this has "no extension".

Ah - but it does. The filename is "A Name" and the extension is ".Supercool"

Were you to rename your file to `"%%a%%c" then the name would become "A Name.Supercool.jpg".

Now why, after attempting to rename your file to extensionless, you are then renaming them to *.png I've no idea, and you don't explain, unfortunately. Why wouldn't you simply tack on the .png to the %%a - if that truly was what you wanted to do?

(BTW - the for /f ... dir... approach builds a memory-list of the files, then renames them, so they won't be re-processed as may occur with for %%x in (*.jpg)...)

Given the terminal-space-in-name problem,

for /f "tokens=1-3 delims=)(" %%a in ('dir /b *.jpg') do rename "%%a(%%b)%%c" "%%a%%c"
SETLOCAL enabledelayedexpansion
for /f "delims=" %%a in ('dir /b "* .jpg"') do (
 SET "name=%%a"
 REN "%%a" "!name:~0,-5!.jpg"
)
endlocal


问:
How to sort data of txt file in Python
I have devices.txt file that looks like this:

```<code>tw004:Galaxy S5:Samsung:Mobilni telefon:5
tw002:Galaxy S6:Samsung:Mobilni telefon:1
tw001:Huawei P8:Huawei:Mobilni telefon:4
tw003:Huawei P9:Huawei:Mobilni telefon:3
</code>```

Now, I have code like this, and I have to chose how to sort devices in table (for example sort them by code from tw001 to tw004 or sort them by producer's name from A to Z)

```<code>def formatheader():
        print(
    "Code |    Name    |  Producer  |       Description       |  Quantity   |\n"
    "-----+------------+------------+-------------------------+-------------|")

def sortbycode():
    devices = open('devices.txt', 'r')
    formatheader()
    for i in devices:
        devices = i.strip("\n").split(":")
        print("{0:5}|{1:13}|{2:15}|{3:18}|{4:5}".format(
            devices[0],
            devices[1],
            devices[2],
            devices[3],
            devices[4]))
    print()
</code>```

How to do that?

答:
try this.</p>

```<code>def formatheader():
        print(
    "Code |    Name     |   Producer    |     Description  |  Quantity   |\n"
    "-----+-------------+---------------+------------------+-------------|")

def sortbycode():
    device_file = open('devices.txt', 'r')
    formatheader()
    devices = []
    for line in device_file:
        devices.append([i  for i in line.strip("\n").split(":")])
    devices.sort(key=lambda x:x[0])
    for device in devices:
      print("{0:5}|{1:13}|{2:15}|{3:18}|{4:5}".format(*device))
sortbycode()
</code>```

Title: How to sort data of txt file in Python

Body:
I have devices.txt file that looks like this:

tw004:Galaxy S5:Samsung:Mobilni telefon:5
tw002:Galaxy S6:Samsung:Mobilni telefon:1
tw001:Huawei P8:Huawei:Mobilni telefon:4
tw003:Huawei P9:Huawei:Mobilni telefon:3

Now, I have code like this, and I have to chose how to sort devices in table (for example sort them by code from tw001 to tw004 or sort them by producer's name from A to Z)

def formatheader():
        print(
    "Code |    Name    |  Producer  |       Description       |  Quantity   |\n"
    "-----+------------+------------+-------------------------+-------------|")

def sortbycode():
    devices = open('devices.txt', 'r')
    formatheader()
    for i in devices:
        devices = i.strip("\n").split(":")
        print("{0:5}|{1:13}|{2:15}|{3:18}|{4:5}".format(
            devices[0],
            devices[1],
            devices[2],
            devices[3],
            devices[4]))
    print()

How to do that?

Body:
try this.

def formatheader():
        print(
    "Code |    Name     |   Producer    |     Description  |  Quantity   |\n"
    "-----+-------------+---------------+------------------+-------------|")

def sortbycode():
    device_file = open('devices.txt', 'r')
    formatheader()
    devices = []
    for line in device_file:
        devices.append([i  for i in line.strip("\n").split(":")])
    devices.sort(key=lambda x:x[0])
    for device in devices:
      print("{0:5}|{1:13}|{2:15}|{3:18}|{4:5}".format(*device))
sortbycode()


问:
Foreach error when insert to mysql
I got some error when inserting my data. for data 1-20 , the data inserted well. But after that foreach not inserted all data. Here is the data :

```<code><?php
include "../conn.php";
$source="https://source1.com/json";
$file=file_get_contents($source,true);
$char_parse=json_decode($file,true);

foreach($char_parse['data'] as $a_item){
$item_sold=$char_parse2['item_sold'];
$success=$char_parse2['success'];
$reject=$char_parse2['reject'];
$sqli="INSERT INTO `product` VALUES (NULL, '".$item_sold."', '".$success."', '".$reject."')";
mysqli_query($conn,$sqli);
$i++;
}
$?>
</code>```

Please help me solve this issues

答:
I don't know enough about your data structure.  But based on your code, let's assume...

```<code>$char_parse['data'] = array(
    array('item_sold'=>'item1', 'success'=>1, 'reject'=>2),
    array('item_sold'=>'item2', 'success'=>1, 'reject'=>2)
);
</code>```

Then,

```<code>foreach($char_parse['data'] as $a_item){
    $item_sold = $a_item['item_sold'];
    $success = $a_item['success'];
    $reject = $a_item['reject'];
    $sqli = "INSERT INTO `product` VALUES (NULL, '".$item_sold."', '".$success."', '".$reject."')";
    mysqli_query($conn,$sqli);
}
</code>```

If I'm wrong about the data structure, the proposed code won't work.

Title: Foreach error when insert to mysql

Body:
I got some error when inserting my data. for data 1-20 , the data inserted well. But after that foreach not inserted all data. Here is the data :

<?php
include "../conn.php";
$source="https://source1.com/json";
$file=file_get_contents($source,true);
$char_parse=json_decode($file,true);

foreach($char_parse['data'] as $a_item){
$item_sold=$char_parse2['item_sold'];
$success=$char_parse2['success'];
$reject=$char_parse2['reject'];
$sqli="INSERT INTO `product` VALUES (NULL, '".$item_sold."', '".$success."', '".$reject."')";
mysqli_query($conn,$sqli);
$i++;
}
$?>

Please help me solve this issues

Body:
I don't know enough about your data structure.  But based on your code, let's assume...

$char_parse['data'] = array(
    array('item_sold'=>'item1', 'success'=>1, 'reject'=>2),
    array('item_sold'=>'item2', 'success'=>1, 'reject'=>2)
);

Then,

foreach($char_parse['data'] as $a_item){
    $item_sold = $a_item['item_sold'];
    $success = $a_item['success'];
    $reject = $a_item['reject'];
    $sqli = "INSERT INTO `product` VALUES (NULL, '".$item_sold."', '".$success."', '".$reject."')";
    mysqli_query($conn,$sqli);
}

If I'm wrong about the data structure, the proposed code won't work.